1#![forbid(unsafe_code)]
23
24use gnucobol_rs::copybook::expand;
25use gnucobol_rs::layout::{lay_out, Item, Odo};
26
27pub use bank_reconcile::{bank_reconcile_report, BankReconcileInputs, BankReconcileReport};
28pub use banking::{
29 reconcile_banking, BankingResult, BankingSummary, ControlSpec, Variant, VariantSpec,
30};
31pub use currency::{currency_validate, CurrencyFieldProfile, CurrencyManifest, CurrencyProfile};
32pub use date_profile::{date_validate, DateFieldProfile, DateFormat, DateManifest, DateProfile};
33pub use db2host::{db2host_evaluate, Db2HostResult, IndicatorManifest, IndicatorPair, NullState};
34pub use diff::{diff_artifacts, DiffInput, DiffReport, DiffTarget, OracleStatus};
35pub use extract::{
36 extract_manifest, ExtractManifest, ExtractMethod, ExtractProfile, FileOrganization,
37 RecordLengthSource,
38};
39pub use file::{ingest, ExitCode, Ingest, IngestPolicy, PartialRecord, TrailingNewline};
40pub use fixture::{replay_fixture, Fixture, FixtureOutcome, FixtureResult, FixtureVerdict};
41pub use gnucobol_rs::copybook::CopyResolver;
43use gnucobol_rs::pic::COB_TYPE_ALPHANUMERIC;
44use gnucobol_rs::{
45 build_field, eval_88, translate_byte, CodePage, CondLit, CondValue, Condition, Decimal,
46 FieldAttr, Usage, COB_FLAG_NO_SIGN_NIBBLE, COB_TYPE_NUMERIC_BINARY, COB_TYPE_NUMERIC_DISPLAY,
47 COB_TYPE_NUMERIC_PACKED,
48};
49pub use pilot::{pilot_packet, PilotArtifact, PilotInputs, PilotPacket};
50pub use posting::{posting_manifest, PostingManifest, PostingProfile};
51pub use privacy::{
52 redact_record, DefaultAction, FieldRule, RedactionAction, RedactionPolicy, RedactionResult,
53};
54pub use recon2::{reconcile_transform, ReconTransformResult, Transform, TransformOp};
55pub use redefines::{redefines_manifest, RedefinesDiscriminator, RedefinesManifest};
56pub use sentinel::{sentinel_scan, SentinelManifest, SentinelMatch, SentinelProfile, SentinelRule};
57pub use tooling::{tooling_export, ToolingExport};
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
63#[cfg_attr(feature = "serde", derive(serde::Serialize))]
64pub enum Encoding {
65 #[default]
67 Ascii,
68 Cp500,
71}
72
73fn logical_bytes<'a>(
78 category: &str,
79 encoding: Encoding,
80 raw: &'a [u8],
81) -> std::borrow::Cow<'a, [u8]> {
82 match (encoding, category) {
83 (Encoding::Cp500, "alphanumeric") => std::borrow::Cow::Owned(
84 raw.iter()
85 .map(|&b| translate_byte(CodePage::Cp500, b).unwrap_or(b))
86 .collect(),
87 ),
88 _ => std::borrow::Cow::Borrowed(raw),
89 }
90}
91use std::collections::HashMap;
92
93pub mod bank_reconcile;
94pub mod banking;
95pub mod batch_chain;
96pub mod batch_control;
97pub mod currency;
98pub mod date_profile;
99pub mod db2host;
100pub mod diff;
101pub mod extract;
102pub mod file;
103pub mod fixture;
104pub mod operator;
105pub mod pilot;
106pub mod posting;
107pub mod privacy;
108pub mod recon;
109pub mod recon2;
110pub mod redefines;
111pub mod sentinel;
112pub mod sha256;
113pub mod tooling;
114pub mod variant;
115pub use operator::{control_totals, explain_field, DirtyMode, STALE_COPYBOOK_RISK};
116
117#[derive(Debug, Clone, PartialEq, Eq)]
119#[cfg_attr(feature = "serde", derive(serde::Serialize))]
120#[non_exhaustive]
121pub struct DecodedField {
122 pub name: String,
123 pub level: u16,
124 pub offset: usize,
125 pub size: usize,
126 pub category: &'static str,
128 pub value: String,
131 pub raw_hex: String,
133 pub edited_numeric: Option<String>,
138}
139
140#[derive(Debug, Clone, PartialEq, Eq)]
142pub enum ShimError {
143 Copy(String),
144 BadItem(String),
146 Layout(String),
148}
149
150impl std::fmt::Display for ShimError {
151 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
152 match self {
153 ShimError::Copy(e) => write!(f, "COPY expansion failed: {e}"),
154 ShimError::BadItem(l) => write!(f, "could not parse copybook item: {l}"),
155 ShimError::Layout(e) => write!(f, "record layout failed: {e}"),
156 }
157 }
158}
159impl std::error::Error for ShimError {}
160
161pub struct NoCopy;
163impl CopyResolver for NoCopy {
164 fn resolve(&self, _name: &str) -> Option<String> {
165 None
166 }
167}
168
169fn hex(b: &[u8]) -> String {
170 let mut s = String::with_capacity(b.len() * 2);
171 for x in b {
172 s.push_str(&format!("{x:02x}"));
173 }
174 s
175}
176
177fn parse_item(decl: &str) -> Option<(Item, Usage, bool, bool)> {
180 let decl = decl.trim_end().trim_end_matches('.');
182 let toks: Vec<String> = decl
183 .split_whitespace()
184 .map(|s| s.to_ascii_uppercase())
185 .collect();
186 if toks.len() < 2 {
187 return None;
188 }
189 let level: u16 = toks[0].parse().ok()?;
190 if level == 88 {
191 return None; }
193 let name = toks[1].clone();
194 let (mut pic, mut usage, mut occurs, mut redefines, mut sep, mut lead, mut odo) =
195 (None, Usage::Display, None, None, false, false, None);
196 let mut i = 2;
197 while i < toks.len() {
198 match toks[i].as_str() {
199 "PIC" | "PICTURE" => {
200 if i + 1 < toks.len() {
201 pic = Some(toks[i + 1].clone());
202 i += 2;
203 continue;
204 }
205 }
206 "COMP-3" | "PACKED-DECIMAL" | "COMPUTATIONAL-3" => usage = Usage::Comp3,
207 "COMP" | "BINARY" | "COMPUTATIONAL" => usage = Usage::Comp,
208 "COMP-5" => usage = Usage::Comp5,
209 "COMP-X" => usage = Usage::CompX,
210 "COMP-6" | "COMPUTATIONAL-6" => usage = Usage::Comp6,
211 "DISPLAY" => usage = Usage::Display,
212 "OCCURS" => {
213 if i + 3 < toks.len() && toks[i + 2] == "TO" {
215 let min = toks[i + 1].parse().unwrap_or(0);
216 let max = toks[i + 3].parse().unwrap_or(0);
217 let mut dep = String::new();
218 let mut k = i + 4;
219 while k + 2 < toks.len() {
220 if toks[k] == "DEPENDING" && toks[k + 1] == "ON" {
221 dep = toks[k + 2].clone();
222 break;
223 }
224 k += 1;
225 }
226 odo = Some(Odo {
227 min,
228 max,
229 depending_on: dep,
230 });
231 i += 4;
232 continue;
233 } else if i + 1 < toks.len() {
234 occurs = toks[i + 1].parse().ok();
235 i += 2;
236 continue;
237 }
238 }
239 "REDEFINES" => {
240 if i + 1 < toks.len() {
241 redefines = Some(toks[i + 1].clone());
242 i += 2;
243 continue;
244 }
245 }
246 "SEPARATE" => sep = true,
247 "LEADING" => lead = true,
248 _ => {}
249 }
250 i += 1;
251 }
252 let item = Item {
253 level,
254 name,
255 pic: pic.map(|p| (p, usage, sep, lead)),
256 occurs,
257 redefines,
258 odo,
259 };
260 Some((item, usage, sep, lead))
261}
262
263fn parse_88(decl: &str) -> Option<(String, Vec<CondValue>)> {
266 let decl = decl.trim_end().trim_end_matches('.');
267 let mut words = decl.split_whitespace();
268 if words.next()? != "88" {
269 return None;
270 }
271 let name = words.next()?.to_ascii_uppercase();
272 if !words.next()?.eq_ignore_ascii_case("VALUE") {
273 return None;
274 }
275 let rest: String = decl
277 .split_once("VALUE")
278 .or_else(|| decl.split_once("value"))
279 .map(|(_, r)| r.to_string())
280 .unwrap_or_default();
281 let lits = tokenize_values(&rest);
282 let mut values = Vec::new();
283 let mut i = 0;
284 while i < lits.len() {
285 if i + 2 < lits.len() && lits[i + 1].eq_ignore_ascii_case("THRU") {
286 values.push(CondValue::Range(make_lit(&lits[i]), make_lit(&lits[i + 2])));
287 i += 3;
288 } else {
289 values.push(CondValue::Lit(make_lit(&lits[i])));
290 i += 1;
291 }
292 }
293 if values.is_empty() {
294 return None;
295 }
296 Some((name, values))
297}
298
299fn tokenize_values(s: &str) -> Vec<String> {
301 let mut out = Vec::new();
302 let mut chars = s.chars().peekable();
303 while let Some(&c) = chars.peek() {
304 if c.is_whitespace() {
305 chars.next();
306 } else if c == '"' || c == '\'' {
307 let q = c;
308 chars.next();
309 let mut lit = String::from("\"");
310 for ch in chars.by_ref() {
311 if ch == q {
312 break;
313 }
314 lit.push(ch);
315 }
316 lit.push('"');
317 out.push(lit);
318 } else {
319 let mut tok = String::new();
320 while let Some(&ch) = chars.peek() {
321 if ch.is_whitespace() {
322 break;
323 }
324 tok.push(ch);
325 chars.next();
326 }
327 out.push(tok);
328 }
329 }
330 out
331}
332
333fn make_lit(tok: &str) -> CondLit {
335 if let Some(inner) = tok.strip_prefix('"').and_then(|t| t.strip_suffix('"')) {
336 CondLit::Alpha(inner.to_string())
337 } else {
338 CondLit::Num(tok.to_string())
339 }
340}
341
342#[derive(Debug, Clone, PartialEq, Eq)]
344#[cfg_attr(feature = "serde", derive(serde::Serialize))]
345pub struct DecodedCondition {
346 pub name: String,
347 pub parent: String,
348 pub value: Option<bool>,
350}
351
352#[derive(Debug, Clone, PartialEq, Eq)]
354#[cfg_attr(feature = "serde", derive(serde::Serialize))]
355pub struct DecodedRecord {
356 pub fields: Vec<DecodedField>,
357 pub conditions: Vec<DecodedCondition>,
358}
359
360impl DecodedRecord {
361 pub fn unsupported(&self) -> usize {
363 self.fields
364 .iter()
365 .filter(|f| f.category == "unsupported")
366 .count()
367 }
368}
369
370#[derive(Debug, Clone, Default)]
374pub(crate) struct FieldMeta {
375 pub pic: String,
376 pub usage: String,
377 pub source_file: String,
378 pub source_line: usize,
379}
380
381struct Program {
382 laid: Vec<gnucobol_rs::Laid>,
383 attrs: HashMap<String, (FieldAttr, &'static str)>,
384 conditions: Vec<(String, Condition)>,
385 meta: HashMap<String, FieldMeta>,
386 used_copy: bool,
388}
389
390fn usage_label(u: Usage) -> &'static str {
391 match u {
392 Usage::Display => "DISPLAY",
393 Usage::Comp3 => "COMP-3",
394 Usage::Comp => "COMP",
395 Usage::Comp5 => "COMP-5",
396 Usage::CompX => "COMP-X",
397 Usage::Comp6 => "COMP-6",
398 _ => "UNKNOWN-USAGE",
399 }
400}
401
402fn parse_program(copybook: &str, resolver: &impl CopyResolver) -> Result<Program, ShimError> {
403 let expanded = expand(copybook, resolver).map_err(|e| ShimError::Copy(e.to_string()))?;
404 let mut items = Vec::new();
405 let mut attrs: HashMap<String, (FieldAttr, &'static str)> = HashMap::new();
406 let mut conditions: Vec<(String, Condition)> = Vec::new();
407 let mut meta: HashMap<String, FieldMeta> = HashMap::new();
408 let mut last_parent: Option<String> = None;
409
410 for (idx, line) in expanded.lines.iter().enumerate() {
411 if line.trim().is_empty() {
412 continue;
413 }
414 if let Some((cname, values)) = parse_88(line) {
416 if let Some(parent) = &last_parent {
417 conditions.push((
418 parent.clone(),
419 Condition {
420 name: cname,
421 values,
422 },
423 ));
424 }
425 continue;
426 }
427 let Some((item, usage, sep, lead)) = parse_item(line) else {
428 continue; };
430 if let Some((ref pic, _, _, _)) = item.pic {
431 let signed_comp6 =
434 usage == Usage::Comp6 && pic.trim_start().to_ascii_uppercase().starts_with('S');
435 let built = if signed_comp6 {
436 None
437 } else {
438 build_field(pic, usage, sep, lead).ok()
439 };
440 if let Some(pf) = built {
441 let cat = match pf.attr.field_type {
442 COB_TYPE_NUMERIC_DISPLAY
443 | COB_TYPE_NUMERIC_PACKED
444 | COB_TYPE_NUMERIC_BINARY => "numeric",
445 COB_TYPE_ALPHANUMERIC => "alphanumeric",
446 _ => "unsupported",
447 };
448 attrs.insert(item.name.clone(), (pf.attr, cat));
449 let prov = expanded.provenance.get(idx);
450 meta.insert(
451 item.name.clone(),
452 FieldMeta {
453 pic: pic.clone(),
454 usage: usage_label(usage).to_string(),
455 source_file: prov.map(|p| p.file.clone()).unwrap_or_default(),
456 source_line: prov.map(|p| p.line).unwrap_or(0),
457 },
458 );
459 } else if usage == Usage::Display && gnucobol_rs::edited_size(pic).is_ok() {
460 attrs.insert(
464 item.name.clone(),
465 (
466 FieldAttr {
467 field_type: 0,
468 digits: 0,
469 scale: 0,
470 flags: 0,
471 },
472 "edited",
473 ),
474 );
475 let prov = expanded.provenance.get(idx);
476 meta.insert(
477 item.name.clone(),
478 FieldMeta {
479 pic: pic.clone(),
480 usage: "DISPLAY (edited)".to_string(),
481 source_file: prov.map(|p| p.file.clone()).unwrap_or_default(),
482 source_line: prov.map(|p| p.line).unwrap_or(0),
483 },
484 );
485 } else {
486 attrs.insert(
487 item.name.clone(),
488 (
489 FieldAttr {
490 field_type: 0,
491 digits: 0,
492 scale: 0,
493 flags: 0,
494 },
495 "unsupported",
496 ),
497 );
498 }
499 last_parent = Some(item.name.clone());
500 }
501 items.push(item);
502 }
503 let laid = lay_out(&items).map_err(|e| ShimError::Layout(e.to_string()))?;
504 let mut files: Vec<&str> = expanded
505 .provenance
506 .iter()
507 .map(|p| p.file.as_str())
508 .collect();
509 files.sort_unstable();
510 files.dedup();
511 let used_copy = files.len() > 1;
512 Ok(Program {
513 laid,
514 attrs,
515 conditions,
516 meta,
517 used_copy,
518 })
519}
520
521fn decode_fields(prog: &Program, record: &[u8], encoding: Encoding) -> Vec<DecodedField> {
522 let mut out = Vec::new();
523 for l in &prog.laid {
524 let slice = record.get(l.offset..l.offset + l.size);
525 let (category, value, raw, edited_numeric) = match (prog.attrs.get(&l.name), slice) {
526 (None, _) => ("group", String::from("(group)"), String::new(), None),
527 (Some((_, "unsupported")), Some(bytes)) => (
528 "unsupported",
529 String::from("(unsupported PIC/usage)"),
530 hex(bytes),
531 None,
532 ),
533 (Some((attr, "numeric")), Some(bytes))
536 if encoding == Encoding::Cp500 && attr.field_type == COB_TYPE_NUMERIC_DISPLAY =>
537 {
538 let d = Decimal::from_ebcdic_zoned(bytes, attr);
539 ("numeric", format_decimal(&d), hex(bytes), None)
540 }
541 (Some((attr, "numeric")), Some(bytes)) => {
542 let d = match attr.field_type {
544 COB_TYPE_NUMERIC_PACKED => Decimal::from_packed(bytes, attr),
545 COB_TYPE_NUMERIC_BINARY => Decimal::from_binary(bytes, attr),
546 _ => Decimal::from_display(bytes, attr),
547 };
548 ("numeric", format_decimal(&d), hex(bytes), None)
549 }
550 (Some((_, "edited")), Some(bytes)) if encoding == Encoding::Cp500 => (
554 "unsupported",
555 String::from("(edited picture under EBCDIC: deferred)"),
556 hex(bytes),
557 None,
558 ),
559 (Some((_, "edited")), Some(bytes)) => {
560 let pic = prog.meta.get(&l.name).map(|m| m.pic.as_str()).unwrap_or("");
561 match gnucobol_rs::decode_edited(pic, bytes) {
562 Ok(d) => {
563 let num = d.numeric_value.as_ref().map(format_decimal);
564 ("edited", d.raw_text.trim_end().to_string(), hex(bytes), num)
565 }
566 Err(_) => (
567 "unsupported",
568 String::from("(edited decode failed)"),
569 hex(bytes),
570 None,
571 ),
572 }
573 }
574 (Some((_, "alphanumeric")), Some(bytes)) => (
575 "alphanumeric",
576 String::from_utf8_lossy(&logical_bytes("alphanumeric", encoding, bytes))
577 .trim_end()
578 .to_string(),
579 hex(bytes),
580 None,
581 ),
582 (Some(_), None) => (
583 "unsupported",
584 String::from("(record too short for field)"),
585 String::new(),
586 None,
587 ),
588 (Some((_, other)), Some(bytes)) => (*other, String::new(), hex(bytes), None),
589 };
590 out.push(DecodedField {
591 name: l.name.clone(),
592 level: l.level,
593 offset: l.offset,
594 size: l.size,
595 category,
596 value,
597 raw_hex: raw,
598 edited_numeric,
599 });
600 }
601 out
602}
603
604fn eval_conditions(prog: &Program, record: &[u8], encoding: Encoding) -> Vec<DecodedCondition> {
605 let mut out = Vec::new();
606 for (parent, cond) in &prog.conditions {
607 let value = prog.laid.iter().find(|l| &l.name == parent).and_then(|l| {
608 let (attr, cat) = prog.attrs.get(parent)?;
609 let bytes = record.get(l.offset..l.offset + l.size)?;
610 let logical = logical_bytes(cat, encoding, bytes);
613 eval_88(attr, &logical, cond).ok()
614 });
615 out.push(DecodedCondition {
616 name: cond.name.clone(),
617 parent: parent.clone(),
618 value,
619 });
620 }
621 out
622}
623
624pub fn decode_with_resolver(
627 copybook: &str,
628 record: &[u8],
629 resolver: &impl CopyResolver,
630) -> Result<Vec<DecodedField>, ShimError> {
631 let prog = parse_program(copybook, resolver)?;
632 Ok(decode_fields(&prog, record, Encoding::Ascii))
633}
634
635pub fn decode_record(
638 copybook: &str,
639 record: &[u8],
640 resolver: &impl CopyResolver,
641) -> Result<DecodedRecord, ShimError> {
642 decode_record_encoded(copybook, record, resolver, Encoding::Ascii)
643}
644
645pub fn decode_record_encoded(
649 copybook: &str,
650 record: &[u8],
651 resolver: &impl CopyResolver,
652 encoding: Encoding,
653) -> Result<DecodedRecord, ShimError> {
654 let prog = parse_program(copybook, resolver)?;
655 Ok(DecodedRecord {
656 fields: decode_fields(&prog, record, encoding),
657 conditions: eval_conditions(&prog, record, encoding),
658 })
659}
660
661pub fn decode_all(
665 copybook: &str,
666 data: &[u8],
667 record_len: usize,
668 resolver: &impl CopyResolver,
669) -> Result<Vec<DecodedRecord>, ShimError> {
670 if record_len == 0 {
671 return Err(ShimError::Layout("record_len must be > 0".into()));
672 }
673 data.chunks(record_len)
674 .map(|chunk| decode_record(copybook, chunk, resolver))
675 .collect()
676}
677
678pub fn decode(copybook: &str, record: &[u8]) -> Result<Vec<DecodedField>, ShimError> {
680 decode_with_resolver(copybook, record, &NoCopy)
681}
682
683fn format_decimal(d: &Decimal) -> String {
685 let mut digits: String = d.digits.iter().map(|x| (b'0' + x) as char).collect();
686 let scale = d.scale.max(0) as usize;
687 while digits.len() <= scale {
688 digits.insert(0, '0');
689 }
690 let split = digits.len() - scale;
691 let mut s = String::new();
692 if d.negative {
693 s.push('-');
694 }
695 let int_part = digits[..split].trim_start_matches('0');
697 s.push_str(if int_part.is_empty() { "0" } else { int_part });
698 if scale > 0 {
699 s.push('.');
700 s.push_str(&digits[split..]);
701 }
702 s
703}
704
705#[cfg(test)]
706mod tests {
707 use super::*;
708
709 #[test]
710 fn decodes_a_record() {
711 let cb = "01 CUST.\n05 CUST-ID PIC 9(3).\n05 CUST-NAME PIC X(4).\n05 CUST-BAL PIC S9(3)V99 COMP-3.";
713 let mut rec = Vec::new();
715 rec.extend_from_slice(b"042");
716 rec.extend_from_slice(b"ANNA");
717 rec.extend_from_slice(&[0x01, 0x23, 0x4d]);
718 let fields = decode(cb, &rec).unwrap();
719 let by = |n: &str| fields.iter().find(|f| f.name == n).unwrap();
720 assert_eq!(by("CUST-ID").value, "42");
721 assert_eq!(by("CUST-NAME").value, "ANNA");
722 assert_eq!(by("CUST-BAL").value, "-12.34");
723 assert_eq!(by("CUST-BAL").raw_hex, "01234d");
724 assert_eq!(by("CUST").category, "group");
725 }
726}