kobold-data-shim 0.2.0

A verifiable COBOL record-decoding shim for data-migration pipelines: ingest a copybook + a raw record dump and decode it byte-exactly via the oracle-proven gnucobol-rs courts (PIC, layout, COPY, decimal MOVE).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
//! # kobold-data-shim
//!
//! A **verifiable** COBOL record-decoding shim for data-migration pipelines. Given a copybook and a
//! raw record dump, it answers *"what did this COBOL record actually mean?"* — byte-exactly —
//! by composing the oracle-proven [`gnucobol_rs`] courts:
//!
//! - `COPY` expansion ([`gnucobol_rs::copybook`], `GNURUST.5`/`6`),
//! - `PIC`→field model ([`gnucobol_rs::pic`], `GNURUST.3`),
//! - record layout / offsets ([`gnucobol_rs::layout`], `GNURUST.4`),
//! - packed/zoned/display decode ([`gnucobol_rs::Decimal`], `GNURUST.2`).
//!
//! Every numeric value this shim emits is decoded by a court that is proven byte-identical to
//! GnuCOBOL 3.2's `libcob` under a differential sweep. Fields outside the sealed subset **fail
//! closed** — they are reported as `unsupported`, never silently guessed (the reconciliation signal
//! that migrations need).
//!
//! ## License
//!
//! This crate's source is **Apache-2.0**. It links `gnucobol-rs`, which is **LGPL-3.0-or-later** —
//! see `NOTICE` for the obligations that places on distributed binaries (relink-ability + notice).

#![forbid(unsafe_code)]

use gnucobol_rs::copybook::expand;
use gnucobol_rs::layout::{lay_out, Item, Odo};

/// Re-exported so callers can implement a custom copybook search path for [`decode_with_resolver`].
pub use gnucobol_rs::copybook::CopyResolver;
use gnucobol_rs::pic::COB_TYPE_ALPHANUMERIC;
use gnucobol_rs::{
    build_field, eval_88, CondLit, CondValue, Condition, Decimal, FieldAttr, Usage,
    COB_TYPE_NUMERIC_DISPLAY, COB_TYPE_NUMERIC_PACKED,
};
use std::collections::HashMap;

pub mod recon;
pub mod sha256;

/// A decoded elementary field.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DecodedField {
    pub name: String,
    pub level: u16,
    pub offset: usize,
    pub size: usize,
    /// `"numeric"`, `"alphanumeric"`, `"group"`, or `"unsupported"`.
    pub category: &'static str,
    /// The decoded value: a canonical decimal string for numerics, text for alphanumerics, or an
    /// explanatory marker for unsupported/short fields.
    pub value: String,
    /// The raw field bytes as lowercase hex (the audit trail).
    pub raw_hex: String,
}

/// What went wrong decoding a record against a copybook.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ShimError {
    Copy(String),
    /// A copybook line could not be parsed into a data item.
    BadItem(String),
    /// The record/copybook produced no `01` record to lay out.
    Layout(String),
}

impl std::fmt::Display for ShimError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ShimError::Copy(e) => write!(f, "COPY expansion failed: {e}"),
            ShimError::BadItem(l) => write!(f, "could not parse copybook item: {l}"),
            ShimError::Layout(e) => write!(f, "record layout failed: {e}"),
        }
    }
}
impl std::error::Error for ShimError {}

/// A resolver that finds nothing (for copybooks with no nested `COPY`).
pub struct NoCopy;
impl CopyResolver for NoCopy {
    fn resolve(&self, _name: &str) -> Option<String> {
        None
    }
}

fn hex(b: &[u8]) -> String {
    let mut s = String::with_capacity(b.len() * 2);
    for x in b {
        s.push_str(&format!("{x:02x}"));
    }
    s
}

/// Parse one COBOL data-item line into a layout [`Item`], plus the elementary field's
/// `(usage, sign_separate, sign_leading)` for decoding.
fn parse_item(decl: &str) -> Option<(Item, Usage, bool, bool)> {
    // Strip the clause-terminating period(s) so a PIC token isn't captured as e.g. "9(3).".
    let decl = decl.trim_end().trim_end_matches('.');
    let toks: Vec<String> = decl
        .split_whitespace()
        .map(|s| s.to_ascii_uppercase())
        .collect();
    if toks.len() < 2 {
        return None;
    }
    let level: u16 = toks[0].parse().ok()?;
    if level == 88 {
        return None; // a LEVEL-88 condition, handled separately (not a storage item)
    }
    let name = toks[1].clone();
    let (mut pic, mut usage, mut occurs, mut redefines, mut sep, mut lead, mut odo) =
        (None, Usage::Display, None, None, false, false, None);
    let mut i = 2;
    while i < toks.len() {
        match toks[i].as_str() {
            "PIC" | "PICTURE" => {
                if i + 1 < toks.len() {
                    pic = Some(toks[i + 1].clone());
                    i += 2;
                    continue;
                }
            }
            "COMP-3" | "PACKED-DECIMAL" | "COMPUTATIONAL-3" => usage = Usage::Comp3,
            "DISPLAY" => usage = Usage::Display,
            "OCCURS" => {
                // "OCCURS min TO max TIMES DEPENDING ON item" (ODO) or "OCCURS n TIMES" (fixed).
                if i + 3 < toks.len() && toks[i + 2] == "TO" {
                    let min = toks[i + 1].parse().unwrap_or(0);
                    let max = toks[i + 3].parse().unwrap_or(0);
                    let mut dep = String::new();
                    let mut k = i + 4;
                    while k + 2 < toks.len() {
                        if toks[k] == "DEPENDING" && toks[k + 1] == "ON" {
                            dep = toks[k + 2].clone();
                            break;
                        }
                        k += 1;
                    }
                    odo = Some(Odo {
                        min,
                        max,
                        depending_on: dep,
                    });
                    i += 4;
                    continue;
                } else if i + 1 < toks.len() {
                    occurs = toks[i + 1].parse().ok();
                    i += 2;
                    continue;
                }
            }
            "REDEFINES" => {
                if i + 1 < toks.len() {
                    redefines = Some(toks[i + 1].clone());
                    i += 2;
                    continue;
                }
            }
            "SEPARATE" => sep = true,
            "LEADING" => lead = true,
            _ => {}
        }
        i += 1;
    }
    let item = Item {
        level,
        name,
        pic: pic.map(|p| (p, usage, sep, lead)),
        occurs,
        redefines,
        odo,
    };
    Some((item, usage, sep, lead))
}

/// Parse a `88 NAME VALUE …` condition line into `(name, values)`. Handles `"lit"` / numeric
/// literals, multiple values, and `THRU` ranges. Returns `None` for non-88 lines.
fn parse_88(decl: &str) -> Option<(String, Vec<CondValue>)> {
    let decl = decl.trim_end().trim_end_matches('.');
    let mut words = decl.split_whitespace();
    if words.next()? != "88" {
        return None;
    }
    let name = words.next()?.to_ascii_uppercase();
    if !words.next()?.eq_ignore_ascii_case("VALUE") {
        return None;
    }
    // Tokenize the remaining text into literals and the THRU keyword (quotes preserved).
    let rest: String = decl
        .split_once("VALUE")
        .or_else(|| decl.split_once("value"))
        .map(|(_, r)| r.to_string())
        .unwrap_or_default();
    let lits = tokenize_values(&rest);
    let mut values = Vec::new();
    let mut i = 0;
    while i < lits.len() {
        if i + 2 < lits.len() && lits[i + 1].eq_ignore_ascii_case("THRU") {
            values.push(CondValue::Range(make_lit(&lits[i]), make_lit(&lits[i + 2])));
            i += 3;
        } else {
            values.push(CondValue::Lit(make_lit(&lits[i])));
            i += 1;
        }
    }
    if values.is_empty() {
        return None;
    }
    Some((name, values))
}

/// Split a VALUE clause body into literal/keyword tokens (a quoted string is one token).
fn tokenize_values(s: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut chars = s.chars().peekable();
    while let Some(&c) = chars.peek() {
        if c.is_whitespace() {
            chars.next();
        } else if c == '"' || c == '\'' {
            let q = c;
            chars.next();
            let mut lit = String::from("\"");
            for ch in chars.by_ref() {
                if ch == q {
                    break;
                }
                lit.push(ch);
            }
            lit.push('"');
            out.push(lit);
        } else {
            let mut tok = String::new();
            while let Some(&ch) = chars.peek() {
                if ch.is_whitespace() {
                    break;
                }
                tok.push(ch);
                chars.next();
            }
            out.push(tok);
        }
    }
    out
}

/// A token like `"A"` becomes an alphanumeric literal; everything else is numeric.
fn make_lit(tok: &str) -> CondLit {
    if let Some(inner) = tok.strip_prefix('"').and_then(|t| t.strip_suffix('"')) {
        CondLit::Alpha(inner.to_string())
    } else {
        CondLit::Num(tok.to_string())
    }
}

/// A decoded LEVEL-88 condition: its truth (or an error marker) for the current record.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DecodedCondition {
    pub name: String,
    pub parent: String,
    /// `Some(true/false)` if evaluated, `None` if the parent/values were unsupported.
    pub value: Option<bool>,
}

/// A fully decoded record: its fields and condition-name truths.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DecodedRecord {
    pub fields: Vec<DecodedField>,
    pub conditions: Vec<DecodedCondition>,
}

impl DecodedRecord {
    /// Count of fields outside the sealed subset (the reconciliation signal).
    pub fn unsupported(&self) -> usize {
        self.fields
            .iter()
            .filter(|f| f.category == "unsupported")
            .count()
    }
}

/// A parsed program: the laid-out items, per-field attrs/category, and LEVEL-88 conditions keyed by
/// parent field. Shared by the field decoder and the condition evaluator.
struct Program {
    laid: Vec<gnucobol_rs::Laid>,
    attrs: HashMap<String, (FieldAttr, &'static str)>,
    conditions: Vec<(String, Condition)>,
}

fn parse_program(copybook: &str, resolver: &impl CopyResolver) -> Result<Program, ShimError> {
    let expanded = expand(copybook, resolver).map_err(|e| ShimError::Copy(e.to_string()))?;
    let mut items = Vec::new();
    let mut attrs: HashMap<String, (FieldAttr, &'static str)> = HashMap::new();
    let mut conditions: Vec<(String, Condition)> = Vec::new();
    let mut last_parent: Option<String> = None;

    for line in &expanded.lines {
        if line.trim().is_empty() {
            continue;
        }
        // A LEVEL-88 condition attaches to the most recent elementary field.
        if let Some((cname, values)) = parse_88(line) {
            if let Some(parent) = &last_parent {
                conditions.push((
                    parent.clone(),
                    Condition {
                        name: cname,
                        values,
                    },
                ));
            }
            continue;
        }
        let Some((item, usage, sep, lead)) = parse_item(line) else {
            continue; // tolerate non-item lines (DIVISION headers etc.)
        };
        if let Some((ref pic, _, _, _)) = item.pic {
            if let Ok(pf) = build_field(pic, usage, sep, lead) {
                let cat = match pf.attr.field_type {
                    COB_TYPE_NUMERIC_DISPLAY | COB_TYPE_NUMERIC_PACKED => "numeric",
                    COB_TYPE_ALPHANUMERIC => "alphanumeric",
                    _ => "unsupported",
                };
                attrs.insert(item.name.clone(), (pf.attr, cat));
            } else {
                attrs.insert(
                    item.name.clone(),
                    (
                        FieldAttr {
                            field_type: 0,
                            digits: 0,
                            scale: 0,
                            flags: 0,
                        },
                        "unsupported",
                    ),
                );
            }
            last_parent = Some(item.name.clone());
        }
        items.push(item);
    }
    let laid = lay_out(&items).map_err(|e| ShimError::Layout(e.to_string()))?;
    Ok(Program {
        laid,
        attrs,
        conditions,
    })
}

fn decode_fields(prog: &Program, record: &[u8]) -> Vec<DecodedField> {
    let mut out = Vec::new();
    for l in &prog.laid {
        let slice = record.get(l.offset..l.offset + l.size);
        let (category, value, raw) = match (prog.attrs.get(&l.name), slice) {
            (None, _) => ("group", String::from("(group)"), String::new()),
            (Some((_, "unsupported")), Some(bytes)) => (
                "unsupported",
                String::from("(unsupported PIC/usage)"),
                hex(bytes),
            ),
            (Some((attr, "numeric")), Some(bytes)) => {
                let d = match attr.field_type {
                    COB_TYPE_NUMERIC_PACKED => Decimal::from_packed(bytes, attr),
                    _ => Decimal::from_display(bytes, attr),
                };
                ("numeric", format_decimal(&d), hex(bytes))
            }
            (Some((_, "alphanumeric")), Some(bytes)) => (
                "alphanumeric",
                String::from_utf8_lossy(bytes).trim_end().to_string(),
                hex(bytes),
            ),
            (Some(_), None) => (
                "unsupported",
                String::from("(record too short for field)"),
                String::new(),
            ),
            (Some((_, other)), Some(bytes)) => (*other, String::new(), hex(bytes)),
        };
        out.push(DecodedField {
            name: l.name.clone(),
            level: l.level,
            offset: l.offset,
            size: l.size,
            category,
            value,
            raw_hex: raw,
        });
    }
    out
}

fn eval_conditions(prog: &Program, record: &[u8]) -> Vec<DecodedCondition> {
    let mut out = Vec::new();
    for (parent, cond) in &prog.conditions {
        let value = prog.laid.iter().find(|l| &l.name == parent).and_then(|l| {
            let (attr, _) = prog.attrs.get(parent)?;
            let bytes = record.get(l.offset..l.offset + l.size)?;
            eval_88(attr, bytes, cond).ok()
        });
        out.push(DecodedCondition {
            name: cond.name.clone(),
            parent: parent.clone(),
            value,
        });
    }
    out
}

/// Decode `record` against a `copybook` (data-division item lines, possibly with `COPY`), using
/// `resolver` to find copybooks. Returns one [`DecodedField`] per named item (groups included).
pub fn decode_with_resolver(
    copybook: &str,
    record: &[u8],
    resolver: &impl CopyResolver,
) -> Result<Vec<DecodedField>, ShimError> {
    let prog = parse_program(copybook, resolver)?;
    Ok(decode_fields(&prog, record))
}

/// Decode a record into its fields **and** its LEVEL-88 condition-name truths (`eval_88`).
pub fn decode_record(
    copybook: &str,
    record: &[u8],
    resolver: &impl CopyResolver,
) -> Result<DecodedRecord, ShimError> {
    let prog = parse_program(copybook, resolver)?;
    Ok(DecodedRecord {
        fields: decode_fields(&prog, record),
        conditions: eval_conditions(&prog, record),
    })
}

/// Decode a record against a copybook with no nested `COPY`.
pub fn decode(copybook: &str, record: &[u8]) -> Result<Vec<DecodedField>, ShimError> {
    decode_with_resolver(copybook, record, &NoCopy)
}

/// Render a [`Decimal`] as a canonical signed decimal string (e.g. `-12.34`).
fn format_decimal(d: &Decimal) -> String {
    let mut digits: String = d.digits.iter().map(|x| (b'0' + x) as char).collect();
    let scale = d.scale.max(0) as usize;
    while digits.len() <= scale {
        digits.insert(0, '0');
    }
    let split = digits.len() - scale;
    let mut s = String::new();
    if d.negative {
        s.push('-');
    }
    // strip leading zeros in the integer part (keep one)
    let int_part = digits[..split].trim_start_matches('0');
    s.push_str(if int_part.is_empty() { "0" } else { int_part });
    if scale > 0 {
        s.push('.');
        s.push_str(&digits[split..]);
    }
    s
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn decodes_a_record() {
        // 01 CUST. 05 CUST-ID PIC 9(3). 05 CUST-NAME PIC X(4). 05 CUST-BAL PIC S9(3)V99 COMP-3.
        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.";
        // record: "042" + "ANNA" + COMP-3(-12.34 as S9(3)V99 = 01234d)
        let mut rec = Vec::new();
        rec.extend_from_slice(b"042");
        rec.extend_from_slice(b"ANNA");
        rec.extend_from_slice(&[0x01, 0x23, 0x4d]);
        let fields = decode(cb, &rec).unwrap();
        let by = |n: &str| fields.iter().find(|f| f.name == n).unwrap();
        assert_eq!(by("CUST-ID").value, "42");
        assert_eq!(by("CUST-NAME").value, "ANNA");
        assert_eq!(by("CUST-BAL").value, "-12.34");
        assert_eq!(by("CUST-BAL").raw_hex, "01234d");
        assert_eq!(by("CUST").category, "group");
    }
}