Skip to main content

kobold_data_shim/
lib.rs

1//! # kobold-data-shim
2//!
3//! A **verifiable** COBOL record-decoding shim for data-migration pipelines. Given a copybook and a
4//! raw record dump, it answers *"what did this COBOL record actually mean?"* — byte-exactly —
5//! by composing the oracle-proven [`gnucobol_rs`] courts:
6//!
7//! - `COPY` expansion ([`gnucobol_rs::copybook`], `GNURUST.5`/`6`),
8//! - `PIC`→field model ([`gnucobol_rs::pic`], `GNURUST.3`),
9//! - record layout / offsets ([`gnucobol_rs::layout`], `GNURUST.4`),
10//! - packed/zoned/display decode ([`gnucobol_rs::Decimal`], `GNURUST.2`).
11//!
12//! Every numeric value this shim emits is decoded by a court that is proven byte-identical to
13//! GnuCOBOL 3.2's `libcob` under a differential sweep. Fields outside the sealed subset **fail
14//! closed** — they are reported as `unsupported`, never silently guessed (the reconciliation signal
15//! that migrations need).
16//!
17//! ## License
18//!
19//! This crate's source is **Apache-2.0**. It links `gnucobol-rs`, which is **LGPL-3.0-or-later** —
20//! see `NOTICE` for the obligations that places on distributed binaries (relink-ability + notice).
21
22#![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};
41/// Re-exported so callers can implement a custom copybook search path for [`decode_with_resolver`].
42pub 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/// The record's declared character encoding (`KOBOLD.DATA.3`). **Never auto-detected** — the caller
60/// states it. `Cp500` decodes *alphanumeric DISPLAY* fields through the sealed `GNURUST.15` table;
61/// **binary and packed fields are raw storage domains and are never text-converted.**
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
63#[cfg_attr(feature = "serde", derive(serde::Serialize))]
64pub enum Encoding {
65    /// Native ASCII (the default): DISPLAY bytes are already the logical characters.
66    #[default]
67    Ascii,
68    /// EBCDIC cp500 (`ebcdic500_ascii8bit`): alphanumeric DISPLAY fields are decoded via the sealed
69    /// `GNURUST.15` table. Numeric DISPLAY (EBCDIC zoned) is **deferred** and fails closed.
70    Cp500,
71}
72
73/// The logical (decoded) bytes of a field under `encoding`: for an **alphanumeric** field under
74/// [`Encoding::Cp500`], each raw EBCDIC byte is translated to its ASCII byte via the sealed
75/// `GNURUST.15` cp500 table; otherwise the raw bytes are returned unchanged (binary/packed/ASCII
76/// pass through untouched).
77fn 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/// A decoded elementary field.
118#[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    /// `"numeric"`, `"alphanumeric"`, `"edited"`, `"group"`, or `"unsupported"`.
127    pub category: &'static str,
128    /// The decoded value: a canonical decimal string for numerics, text for alphanumerics, or an
129    /// explanatory marker for unsupported/short fields.
130    pub value: String,
131    /// The raw field bytes as lowercase hex (the audit trail).
132    pub raw_hex: String,
133    /// For an **edited** DISPLAY field (`GNURUST.16`): the oracle-proven numeric interpretation of the
134    /// presentation string (`value`). `None` for non-edited fields. JSON keeps `value` as the edited
135    /// presentation string; this is the *interpreted* numeric, recorded as audit evidence — never a
136    /// silent replacement.
137    pub edited_numeric: Option<String>,
138}
139
140/// What went wrong decoding a record against a copybook.
141#[derive(Debug, Clone, PartialEq, Eq)]
142pub enum ShimError {
143    Copy(String),
144    /// A copybook line could not be parsed into a data item.
145    BadItem(String),
146    /// The record/copybook produced no `01` record to lay out.
147    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
161/// A resolver that finds nothing (for copybooks with no nested `COPY`).
162pub 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
177/// Parse one COBOL data-item line into a layout [`Item`], plus the elementary field's
178/// `(usage, sign_separate, sign_leading)` for decoding.
179fn parse_item(decl: &str) -> Option<(Item, Usage, bool, bool)> {
180    // Strip the clause-terminating period(s) so a PIC token isn't captured as e.g. "9(3).".
181    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; // a LEVEL-88 condition, handled separately (not a storage item)
192    }
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                // "OCCURS min TO max TIMES DEPENDING ON item" (ODO) or "OCCURS n TIMES" (fixed).
214                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
263/// Parse a `88 NAME VALUE …` condition line into `(name, values)`. Handles `"lit"` / numeric
264/// literals, multiple values, and `THRU` ranges. Returns `None` for non-88 lines.
265fn 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    // Tokenize the remaining text into literals and the THRU keyword (quotes preserved).
276    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
299/// Split a VALUE clause body into literal/keyword tokens (a quoted string is one token).
300fn 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
333/// A token like `"A"` becomes an alphanumeric literal; everything else is numeric.
334fn 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/// A decoded LEVEL-88 condition: its truth (or an error marker) for the current record.
343#[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    /// `Some(true/false)` if evaluated, `None` if the parent/values were unsupported.
349    pub value: Option<bool>,
350}
351
352/// A fully decoded record: its fields and condition-name truths.
353#[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    /// Count of fields outside the sealed subset (the reconciliation signal).
362    pub fn unsupported(&self) -> usize {
363        self.fields
364            .iter()
365            .filter(|f| f.category == "unsupported")
366            .count()
367    }
368}
369
370/// A parsed program: the laid-out items, per-field attrs/category, and LEVEL-88 conditions keyed by
371/// parent field. Shared by the field decoder and the condition evaluator.
372/// Per-field provenance + declaration metadata for the operator `explain` evidence (`KOBOLD.OPERATOR.1`).
373#[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    /// True if expansion spliced more than one source file (a `COPY` was used).
387    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        // A LEVEL-88 condition attaches to the most recent elementary field.
415        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; // tolerate non-item lines (DIVISION headers etc.)
429        };
430        if let Some((ref pic, _, _, _)) = item.pic {
431            // Signed COMP-6 is NOT admitted (KOBOLD.DATA.6 / GNURUST.18): GnuCOBOL silently converts
432            // `S9(n) COMP-6` to COMP-3, so we fail closed rather than treat it as unsigned COMP-6.
433            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                // An edited DISPLAY picture (GNURUST.16): decoded by the `edited` court, not `pic`.
461                // (An edited PIC with a binary/packed USAGE is the wrong domain → falls through to
462                // "unsupported" below, since it only reaches here when usage == Display.)
463                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            // Numeric DISPLAY (zoned) under EBCDIC decodes through GNURUST.17 (KOBOLD.DATA.5): cp500
534            // translate + the cob_get_sign_ebcdic overpunch sign. Binary/packed stay RAW (next arm).
535            (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                // Binary/packed are RAW storage domains — never text-converted (passthrough).
543                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            // Edited DISPLAY field (GNURUST.16): JSON keeps the presentation string; the oracle-proven
551            // numeric goes to `edited_numeric` (audit), never silently replacing the text. Edited under
552            // cp500 is deferred (the decode table is ASCII) → fail closed.
553            (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            // 88 literals in the copybook are ASCII, so under cp500 the parent's alphanumeric bytes
611            // are decoded to ASCII *before* the predicate runs (raw EBCDIC would never match).
612            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
624/// Decode `record` against a `copybook` (data-division item lines, possibly with `COPY`), using
625/// `resolver` to find copybooks. Returns one [`DecodedField`] per named item (groups included).
626pub 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
635/// Decode a record into its fields **and** its LEVEL-88 condition-name truths (`eval_88`), as native
636/// ASCII. For EBCDIC, use [`decode_record_encoded`].
637pub 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
645/// Decode a record under an explicit [`Encoding`] (`KOBOLD.DATA.3`). Under [`Encoding::Cp500`],
646/// alphanumeric DISPLAY fields (and the parent bytes feeding `eval_88`) are decoded through the
647/// sealed `GNURUST.15` cp500 table; binary/packed fields pass through as raw storage.
648pub 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
661/// Decode a buffer of fixed-length records into one [`DecodedRecord`] per record (fields +
662/// conditions). A higher-level iterator over `data.chunks(record_len)`; a trailing partial record is
663/// decoded as-is (its short fields are reported `unsupported`, never guessed).
664pub 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
678/// Decode a record against a copybook with no nested `COPY`.
679pub fn decode(copybook: &str, record: &[u8]) -> Result<Vec<DecodedField>, ShimError> {
680    decode_with_resolver(copybook, record, &NoCopy)
681}
682
683/// Render a [`Decimal`] as a canonical signed decimal string (e.g. `-12.34`).
684fn 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    // strip leading zeros in the integer part (keep one)
696    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        // 01 CUST. 05 CUST-ID PIC 9(3). 05 CUST-NAME PIC X(4). 05 CUST-BAL PIC S9(3)V99 COMP-3.
712        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        // record: "042" + "ANNA" + COMP-3(-12.34 as S9(3)V99 = 01234d)
714        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}