@cobol-ts/layout 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,346 @@
1
- # Temporary Holding Version
1
+ # COBOL Layout Compilation
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `@cobol-ts/layout` turns a parsed COBOL copybook into a **reusable description of where bytes belong**. It determines the physical extent of declarations, the positions of fields within their containing groups, alignment gaps, repeated storage, and overlapping `REDEFINES` views. It does **not** decode a record into a COBOL object, select a business interpretation, or read an `OCCURS DEPENDING ON` (ODO) count from a byte buffer.
4
+
5
+ The difficult part is that a COBOL layout is not always a list of fields with fixed offsets. A declaration can start after a variable-length table; several declarations can occupy the same bytes; a nested synchronized field can insert padding into a parent group; and the size of one occurrence can depend on the indices of enclosing occurrences. The compiler therefore preserves **symbolic storage geometry**, rather than pretending all offsets are known at compilation time.
6
+
7
+ The implementation targets an **IBM Enterprise COBOL for z/OS-oriented subset** with configurable storage policies. Its goal is to locate fields from *legal, working copybooks* correctly, not to act as a complete COBOL compiler or an exhaustive source validator.
8
+
9
+ For the broader architectural decision, see [COBOL Layout Compilation](https://docs.google.com/document/d/1dALb84lfj2HpKNBerqIXkXV4qYUxv7m3MXW3CSXRHRA/edit?usp=drivesdk). For test cases, source provenance, and what each test actually proves, see [README.tests.md](README.tests.md).
10
+
11
+ ## The mental model
12
+
13
+ A compiled layout is a tree with one node per storage declaration (plus explicit compiler-generated padding nodes). Every node has three expressions, all measured in **bits**:
14
+
15
+ | Expression | Meaning |
16
+ | --- | --- |
17
+ | `size` | Physical extent occupied by this declaration, including its declared repetitions. |
18
+ | `leftOffset` | Distance from the beginning of the containing group to this declaration's beginning. |
19
+ | `rightOffset` | Distance from the end of this declaration to the end of the containing group. |
20
+
21
+ For a record root, both offsets are zero. For a child of a **repeated group**, offsets refer to **one occurrence body** of that group; the repeated group's `size` describes the full table. The expressions can be numbers, or symbolic sums, maxima, repetitions, alignment gaps, and differences that are evaluated for a particular record.
22
+
23
+ For example:
24
+
25
+ ```cobol
26
+ 01 RECORD.
27
+ 05 HEADER PIC X(3).
28
+ 05 DETAILS.
29
+ 10 CODE PIC X(2).
30
+ 10 FLAG PIC X.
31
+ 05 TAIL PIC X.
32
+ ```
33
+
34
+ Ignoring any separately configured alignment requirements, `HEADER` begins at byte 0, `DETAILS` at byte 3, `CODE` at byte 3, `FLAG` at byte 5, and `TAIL` at byte 6. `DETAILS` has `leftOffset = 24` bits within `RECORD`, while `FLAG` has `leftOffset = 16` bits within **DETAILS**. The latter is **not** an absolute offset: to locate it from the record origin, add the group offsets along its ancestry.
35
+
36
+ This distinction is intentional. The tree describes **relative geometry that can be reused**, not an eagerly expanded record instance.
37
+
38
+ ## How the compiler works
39
+
40
+ The code follows this sequence:
41
+
42
+ ```text
43
+ CopybookAst
44
+ |
45
+ v
46
+ Index declaration context and supported ODO controllers
47
+ |
48
+ v
49
+ transformTree: build mutable storage nodes and padding intents
50
+ |
51
+ v
52
+ foldTreeLeft: place nodes, close overlay runs, resolve padding,
53
+ determine sizes and left offsets
54
+ |
55
+ v
56
+ foldTreeRight: determine suffix offsets independently
57
+ |
58
+ v
59
+ Readonly compiled tree: elementary / group / padding
60
+ |
61
+ +--> evaluateStorageSize(..., resolveCount) for a record
62
+ +--> locateCobolEntry(..., path, resolveCount) for a field
63
+ ```
64
+
65
+ ### 1. Index the context; decide which strategy applies
66
+
67
+ A preliminary walk records each declaration's containing names and inherited `USAGE` and `SYNCHRONIZED` clauses. This is needed because an elementary field's width and alignment can depend on an enclosing group, rather than only on its own `PIC` clause. The original AST retains the information; the compiler does not flatten away the relationship.
68
+
69
+ The same setup resolves supported `DEPENDING ON` names to symbolic controller paths. Resolution searches the nearest enclosing declarative scope first, rejects ambiguous matches, and checks the controller's suitability under the implemented IBM-oriented rules. This is **not** a general DATA DIVISION qualified-name resolver.
70
+
71
+ The compiler then composes small partial-function strategies using `chainOfResponsibility`:
72
+
73
+ - **Declaration:** elementary storage, group storage, or ignored non-storage entry.
74
+ - **Repetition:** no `OCCURS`, fixed `OCCURS`, or dependent `OCCURS`.
75
+ - **Placement:** sequential sibling or a `REDEFINES` alternative in an active overlay run.
76
+
77
+ These are separate decisions. ODO is a repetition strategy, not another algorithm for walking the layout; `REDEFINES` is a placement strategy, not an alternative size calculator.
78
+
79
+ ### 2. `transformTree`: construct storage nodes, not positions
80
+
81
+ `transformTree` works bottom-up, converting source entries to private mutable `PendingElementary`, `PendingGroup`, and `PendingPadding` nodes. Primitive sizing is delegated to `CobolPrimitiveSizer`. Groups retain a tree of children representing **one occurrence body**. A declaration with `OCCURS 100 TIMES` does not produce one hundred child subtrees.
82
+
83
+ At this stage the compiler can know that a synchronized field *may require padding*, without yet knowing how many bits of padding will be needed. It inserts a **padding intent**. This is a real intermediate node, not an invented absolute-position expression or a deferred second layout.
84
+
85
+ `RENAMES` and constants contribute no storage nodes. `FILLER` does contribute physical storage; it simply does not provide an ordinary named path for lookup.
86
+
87
+ ### 3. `foldTreeLeft`: perform physical placement
88
+
89
+ The left fold walks each record root with a frame containing the current group, its symbolic origin, the current parent-relative position, and the currently open overlay run.
90
+
91
+ For an ordinary sequential declaration, the compiler closes the previous run, assigns the current position as `leftOffset`, and starts a new run. For `REDEFINES`, it **does not advance** the position: the new alternative shares the existing run's beginning.
92
+
93
+ When an overlay run closes, it advances the position by **the maximum alternative extent**, not by their sum. Thus storage after an overlay starts after the longest member even if the shorter view happens to be selected at runtime.
94
+
95
+ When the fold reaches a pending padding node, it asks the injected padding policy how many bits are needed at the **actual symbolic left position**. A constant position often gives a numeric answer. A position after ODO may instead give an `align(...)` expression, which is evaluated for each record. Zero-size padding disappears; nonzero or symbolic padding remains an explicit child of the group that physically owns it.
96
+
97
+ On exiting a group, the fold closes its last run, obtains the size of **one** occurrence body, and applies its repetition strategy. The resulting group `size` may remain symbolic. This is where group sizes, including nested variable sizes, become complete.
98
+
99
+ ### 4. `foldTreeRight`: calculate independent suffix geometry
100
+
101
+ After sizes and left positions exist, the right fold visits children before their parents and works from the end of each group's sibling runs. It calculates the distance from a declaration's **end** to its containing group's **end**.
102
+
103
+ This calculation is deliberately independent of `group.size - leftOffset - size`. That subtraction is especially awkward when alternatives in the same `REDEFINES` run have unequal symbolic extents. Instead, each run contributes its maximum extent and each alternative receives its own gap within that run:
104
+
105
+ ```text
106
+ rightOffset(alternative)
107
+ = size of subsequent sibling runs
108
+ + (maximum size of this overlay run - this alternative's size)
109
+ ```
110
+
111
+ The expression form is `difference(max(...), alternativeSize)` when it cannot be reduced to a number. A shorter alternative therefore has a larger right offset, even though all alternatives begin at the same address.
112
+
113
+ The right fold also removes compilation-only occurrence and padding-intent metadata. The returned nodes expose readonly geometry and retain source declarations by reference; compilation used mutation internally, but no parallel immutable trees or expanded occurrence objects are created. **Treat the source AST as immutable while the compiled layout is in use.**
114
+
115
+ ## A worked `REDEFINES` example
116
+
117
+ ```cobol
118
+ 01 RECORD.
119
+ 05 PREFIX PIC X(3).
120
+ 05 SHORT-VIEW PIC X(2).
121
+ 05 LONG-VIEW REDEFINES SHORT-VIEW PIC X(5).
122
+ 05 TRAILER PIC X.
123
+ ```
124
+
125
+ The two views start at byte **3**. They overlap; they are **not** stored one after the other. The overlay occupies five bytes because the longest alternative is five bytes. `TRAILER` therefore starts at byte **8**, and the record occupies **9 bytes**.
126
+
127
+ | Node | Start byte | Size (bytes) | Right offset within RECORD (bytes) |
128
+ | --- | ---: | ---: | ---: |
129
+ | `PREFIX` | 0 | 3 | 6 |
130
+ | `SHORT-VIEW` | 3 | 2 | 4 |
131
+ | `LONG-VIEW` | 3 | 5 | 1 |
132
+ | `TRAILER` | 8 | 1 | 0 |
133
+
134
+ The right offset of `SHORT-VIEW` is four bytes: three unused bytes within the overlay's allocated extent, then one byte for `TRAILER`. The two source views are both represented; **the compiler does not select which is meaningful**.
135
+
136
+ If an overlay's sizes depend on a runtime count, the same rules apply symbolically: the allocated extent is `max(alternative sizes)` and the right-hand gap is a `difference`. This is also why evaluating an overlay's physical allocation may require more information than evaluating one chosen view. Never infer that an inactive `REDEFINES` branch is safe to decode merely because the layout can describe it.
137
+
138
+ ## The corner cases that shape the design
139
+
140
+ ### 1. `OCCURS` is a binder, not a copied subtree
141
+
142
+ Fixed `OCCURS` stores one compiled body. At runtime, the evaluator can calculate the repeated extent. For a constant-width body, this often canonicalises to a single number. But if the body contains symbolic dependent sizes, the evaluator **iterates over each occurrence with its own index binding**. In the general algebra, `N × size(the selected occurrence)` is not a valid replacement for the sum of each occurrence's size.
143
+
144
+ Even an explicit `OCCURS 1 TIMES` matters. It introduces occurrence index 0, which nested symbolic expressions may reference. It must not automatically become indistinguishable from a declaration with **no** `OCCURS` clause.
145
+
146
+ The compiled group children always describe one occurrence, not the whole repetition. Both their left and right offsets are relative to that occurrence body.
147
+
148
+ ### 2. ODO changes both sizes and later field positions
149
+
150
+ ```cobol
151
+ 01 RECORD.
152
+ 05 COUNT PIC 9.
153
+ 05 ITEMS OCCURS 0 TO 4 TIMES DEPENDING ON COUNT.
154
+ 10 CODE PIC X(2).
155
+ 05 AFTER-TABLE PIC X.
156
+ ```
157
+
158
+ Assuming one-byte DISPLAY characters, the table occupies `16 × COUNT` bits. `AFTER-TABLE` starts at `8 + 16 × COUNT` bits, not at a fixed offset. With `COUNT = 0`, it starts immediately after the controller; with `COUNT = 3`, it starts after three two-byte occurrences. A legal zero minimum means the table may occupy no bytes at all.
159
+
160
+ The ODO expression retains the controller path, one-occurrence expression, and declared minimum and maximum. Bounds are checked **when the expression is evaluated**. A callback supplies count values; the layout compiler does not read or decode the controller from a record.
161
+
162
+ The implemented IBM-oriented resolver deliberately requires a **fixed-location, suitable integer controller**, outside the controlled table and not an occurrence of another table. A controller following a variable table, a controller nested in a repeated element, an ambiguous controller name, or a controller inside its own table is rejected in the current supported subset. The expression algebra is broader than the currently accepted source declarations.
163
+
164
+ ### 3. Nested ODO and indexed locations require prefix sums
165
+
166
+ ```cobol
167
+ 01 RECORD.
168
+ 05 OUTER-COUNT PIC 9.
169
+ 05 INNER-COUNT PIC 9.
170
+ 05 OUTER OCCURS 0 TO 3 TIMES DEPENDING ON OUTER-COUNT.
171
+ 10 INNER OCCURS 0 TO 4 TIMES DEPENDING ON INNER-COUNT.
172
+ 15 CODE PIC X(2).
173
+ 10 TRAILER PIC X.
174
+ 05 FINAL PIC X.
175
+ ```
176
+
177
+ For `OUTER-COUNT = 2` and `INNER-COUNT = 3`, one `OUTER` occurrence is seven bytes (three two-byte codes and a one-byte trailer). The full record is **17 bytes (136 bits)**. The path `['RECORD', 'OUTER', 1, 'INNER', 1, 'CODE']` selects the second `CODE` in the second `OUTER`. It starts at byte **11 (bit 88)** and occupies two bytes.
178
+
179
+ The locator reaches that address by summing the sizes of preceding occurrences, not by choosing a convenient stride after the fact. If a repeated body has variable-sized nested components, those prefix sums must be evaluated with the correct enclosing indices. This is a correctness requirement, not merely a performance issue.
180
+
181
+ ### 4. `SYNCHRONIZED` padding belongs to a particular group
182
+
183
+ A group is not automatically padded just because it contains a synchronized field. The owner of a gap depends on **where the gap lies physically**.
184
+
185
+ ```cobol
186
+ 01 RECORD.
187
+ 05 PREFIX PIC X(2).
188
+ 05 DETAILS.
189
+ 10 CODE PIC X.
190
+ 10 AMOUNT PIC S9(9) COMP SYNCHRONIZED.
191
+ ```
192
+
193
+ Under the IBM-oriented policy, the four-byte `AMOUNT` needs a four-byte boundary. `PREFIX` uses bytes 0–1 and `CODE` uses byte 2. The gap at byte **3** is **inside `DETAILS`**, between `CODE` and `AMOUNT`; `AMOUNT` begins at byte 4.
194
+
195
+ Now remove `CODE` and make `PREFIX` three bytes. The same one-byte gap before `AMOUNT` belongs to **RECORD, before `DETAILS`**, because the first child of `DETAILS` must start aligned. The `alignedAtStart` guard prevents both levels from inserting the same padding. This ownership is important: an incorrect padding parent gives wrong child coordinates even when the final record length happens to be correct.
196
+
197
+ Alignment is calculated against the physical left origin. An ordinary group does not receive gratuitous trailing padding. A **repeated** group or elementary entry may need padding after each occurrence, so that the next occurrence obeys the configured alignment rule. Such padding can remain symbolic when the occurrence length is variable.
198
+
199
+ ### 5. Overlay alignment is not free space
200
+
201
+ `REDEFINES` alternatives must start at the same location. A synchronized alternative cannot simply shift to the next boundary without ceasing to redefine the target. The overlay alignment policy decides whether a requested alignment is satisfied inside the existing overlay or must be rejected. The implementation does not silently insert a gap that changes the meaning of `REDEFINES`.
202
+
203
+ The IBM-oriented strategy rejects an ODO declaration directly on either explicit `REDEFINES` participant. Other IBM restrictions, such as the full rule concerning an `OCCURS` clause on the redefined target, are **not yet completely enforced**. Legal-copybook layout correctness is the primary goal; the package must not be treated as a complete legality checker.
204
+
205
+ ### 6. Primitive sizing is not simply the number of `PIC` characters
206
+
207
+ `PICTURE` parsing and category classification precede physical sizing. DISPLAY numeric, edited fields, signs, `COMP`/binary, `COMP-3`/packed decimal, floating formats, NATIONAL, DBCS, and fixed-character UTF-8 have different storage rules. Repeated picture fragments are parsed structurally rather than expanded into a huge string.
208
+
209
+ Some source conventions are **not available from the copybook alone**: for example, currency picture symbols, `NSYMBOL` behaviour, and compiler-specific storage options. They must be supplied through `primitiveSizing` or an injected `primitiveSizer` rather than guessed. `PIC U BYTE-LENGTH n` reserves exactly `n` bytes; `DYNAMIC LENGTH` is recognised but cannot be assigned an invented fixed inline record extent.
210
+
211
+ ### 7. Non-storage declarations, `FILLER`, and names
212
+
213
+ A constant or `RENAMES` declaration does not allocate new storage, so the structural transform returns no compiled storage node for it. `FILLER` **does** occupy bytes and affects every later offset, even though it has no normal named selector. It must never be skipped when calculating geometry.
214
+
215
+ The current locator resolves names **case-insensitively among siblings** and reports missing or ambiguous matches. It is not a general-purpose COBOL name-qualification engine. A name index for a later projection package can be built from the compiled tree, but it must not replace the physical semantics or confuse distinct declarations that share a name.
216
+
217
+ ### 8. Record roots, bounds, and unknown conventions
218
+
219
+ Each top-level record root is compiled independently, with zero parent-relative offsets. Explicit `REDEFINES` between record roots is not currently supported by the ordinary overlay strategy; implicit record-description overlays in an FD are a separate problem.
220
+
221
+ A symbolic size is not permission to read arbitrary bytes. At access time, the caller still needs a trusted record boundary, validated ODO counts, and a valid path. A later byte-backed projection must also check that a selected bit range lies within the leased record and is compatible with the decoder's byte-alignment requirements. File framing and the byte source are deliberately outside this package.
222
+
223
+ ## The symbolic size algebra
224
+
225
+ `@cobol-ts/size` defines the expressions the compiler constructs:
226
+
227
+ | Form | Why it exists |
228
+ | --- | --- |
229
+ | `number` | A known number of bits; the common result for fixed layouts. |
230
+ | `sum` | Ordinary sequential extents and suffixes. |
231
+ | `max` | The extent of an overlapping `REDEFINES` run. |
232
+ | `occurs` | A fixed number of occurrence bodies, with index binding preserved when needed. |
233
+ | `depending-on` | A count read through a symbolic controller path at evaluation time. |
234
+ | `align` | The number of bits required to reach an alignment boundary. |
235
+ | `difference` | A nonnegative gap, notably between an overlay's maximum extent and one alternative. |
236
+
237
+ `canonicaliseStorageSize` folds constants, flattens suitable sums/maxima, and removes redundant terms **without consulting a record**. It does not replace a genuinely variable body with an arbitrary fixed stride, discard an index binder needed by a nested expression, or choose a `REDEFINES` view.
238
+
239
+ `evaluateStorageSize(expression, resolveCount, enclosingIndices?)` then produces a concrete bit count for a particular record/count environment. Symbolic paths use strings for declaration names and, where present, numbers for **relative enclosing-occurrence depths**. The evaluator binds these depths to concrete indices while iterating. They are not the same thing as literal indexes in a user's location path.
240
+
241
+ A few important identities are:
242
+
243
+ ```text
244
+ sequentialExtent = sum(siblingRunExtents)
245
+ overlayRunExtent = max(alternativeExtents)
246
+ alignmentGap = (boundary - position % boundary) % boundary
247
+ rightOverlayGap = max(alternativeExtents) - selectedAlternativeExtent
248
+ ```
249
+
250
+ The expressions retain their structure when some terms depend on a runtime count. Evaluation validates count types and ODO bounds; an impossible negative `difference` fails rather than producing a nonsensical offset.
251
+
252
+ ## Using the API
253
+
254
+ The `copybook` argument to the compiler is a **source label for diagnostics**; the copybook has already been parsed into `CopybookAst` by the caller.
255
+
256
+ ```ts
257
+ import {valueOrThrow} from '@cobol-ts/errors';
258
+ import {
259
+ compileCobolLayout,
260
+ locateCobolEntry
261
+ } from '@cobol-ts/layout';
262
+
263
+ const roots = valueOrThrow(compileCobolLayout(ast, 'customer.cpy'));
264
+
265
+ // For a fixed-only record, this callback should never be invoked.
266
+ const noCounts = () => {
267
+ throw new Error('Unexpected ODO evaluation');
268
+ };
269
+
270
+ const field = valueOrThrow(locateCobolEntry(
271
+ roots,
272
+ ['RECORD', 'DETAILS', 'CODE'],
273
+ noCounts
274
+ ));
275
+
276
+ // field.node -- the selected compiled entry
277
+ // field.offsetBits -- start relative to the selected record root
278
+ // field.sizeBits -- selected physical extent
279
+ ```
280
+
281
+ The locator accepts a path of declaration names and **zero-based numeric indices immediately after each repeated declaration name**. For example:
282
+
283
+ ```ts
284
+ const selected = valueOrThrow(locateCobolEntry(
285
+ roots,
286
+ ['RECORD', 'OUTER', 1, 'INNER', 1, 'CODE'],
287
+ resolveCount
288
+ ));
289
+ ```
290
+
291
+ `resolveCount` is a caller-supplied callback accepting a **concrete controller path** and returning the corresponding numeric value. The locator does not decode COBOL bytes. For fixed-only layouts, expressions usually canonicalise to numbers and no counts need resolving.
292
+
293
+ `CobolLayoutOptions` supports `primitiveSizer`, `primitiveSizing`, `padding`, `overlayAlignment`, and `canonicalise`. These override storage conventions or expression handling, not the responsibilities of the compiler's stages. For example:
294
+
295
+ ```ts
296
+ const rootsWithSourceOptions = valueOrThrow(compileCobolLayout(
297
+ ast,
298
+ 'invoice.cpy',
299
+ {
300
+ primitiveSizing: {
301
+ defaultCurrency: {symbol: '$', value: '$'},
302
+ currencySigns: [{symbol: 'f', value: 'CHF'}],
303
+ nSymbol: 'national'
304
+ }
305
+ }
306
+ ));
307
+ ```
308
+
309
+ Choose these options from the originating program and compiler configuration. It is unsafe to treat the bare copybook as a complete specification of physical storage in all dialects.
310
+
311
+ ### Failures and diagnostics
312
+
313
+ Expected source/layout failures return `ErrorsOr`, with contextual information including copybook, source line, and declaration path where available. The compiler can aggregate independent context, subtree, and root errors. It cannot always continue truthfully after a placement failure within the same record, because later positions depend on earlier positions. Unhandled strategy cases and broken internal invariants throw, as programming/configuration failures rather than recoverable copybook diagnostics.
314
+
315
+ ## Where this stops and projection begins
316
+
317
+ The layout compiler provides **geometry and indexed location**, not a fully integrated byte-backed COBOL reader. In particular, it does not:
318
+
319
+ - obtain ODO controller values from physical record bytes;
320
+ - decode EBCDIC, packed-decimal, binary, or other primitive values;
321
+ - choose the active `REDEFINES` interpretation or safely decode inactive alternatives;
322
+ - choose a right-hand anchor or establish record framing (FB, VB/RDW, etc.);
323
+ - manage physical-record leases or application-facing projections.
324
+
325
+ The implemented consumer is **`@cobol-ts/cursor-loader-cobol`**. It creates a name index of the same compiled nodes and then compiles either constant-geometry paths (fixed OCCURS) or symbolic paths (ODO). The runtime retains variable-body occurrence boundary prefixes in the pooled physical-record state. The independent `locateCobolEntry()` algorithm remains a useful test oracle for coordinates, but it is not the hot-path locator used for already-compiled projections.
326
+
327
+ The adapter currently tests three levels of nested ODO and two independent sibling ODO arrays, using **fixed-position, supported count fields**. The geometry expressions can model enclosing occurrence indices and variable body lengths, but the adapter's physical-byte controller resolver explicitly rejects controllers at variable positions. Consequently, passing nested geometry tests does **not** establish support for a separately stored count inside every preceding outer occurrence. Layout compilation also does not decide FB/VB/RDW framing: the parser needs a trusted frame length before byte-backed access.
328
+
329
+ The adapter's scalar methods still return byte-range diagnostics instead of applying production primitive codecs, which remain separately implemented in `@cobol-ts/cobolcodec`.
330
+
331
+
332
+ ## Source map
333
+
334
+ | Location | Main responsibility |
335
+ | --- | --- |
336
+ | `src/cobol.layout.ts` | Public geometry, context and controller resolution, strategies, structural transform and both folds. |
337
+ | `src/cobol.layout.location.ts` | Locate a concrete named/indexed entry by evaluating geometry. |
338
+ | `src/cobol.picture.ts` | PICTURE parsing and classification. |
339
+ | `src/cobol.primitive.size.ts` | IBM-oriented and injectable elementary storage-size rules. |
340
+ | `src/cobol.padding.ts` | Boundary and occurrence-tail padding policy. |
341
+ | `src/cobol.overlay.alignment.ts` | Alignment decisions for overlapping alternatives. |
342
+ | `@cobol-ts/copybook` | Source AST and storage clauses. |
343
+ | `@cobol-ts/size` | Symbolic expressions, canonicalisation, count binding and evaluation. |
344
+ | `@cobol-ts/trees` | `transformTree`, `foldTreeLeft`, `foldTreeRight`. |
345
+ | `@cobol-ts/partial_functions` | Small composable declaration/repetition/placement strategies. |
346
+ | `@cobol-ts/errors` | Recoverable `ErrorsOr` diagnostics. |
@@ -0,0 +1,155 @@
1
+ # COBOL Layout — Tests and Confidence
2
+
3
+ This document explains **what `@cobol-ts/layout` tests, which claims those tests support, and where our evidence is still incomplete**. It complements [README.md](README.md), which describes the compiler and API.
4
+
5
+ The purpose is to establish confidence that **legal COBOL copybooks produce correct physical storage extents and field locations**. Byte-value decoding and the application projection pipeline are separate concerns. A correct total record length is necessary but **not sufficient**: fields can still be misplaced inside a record whose total length happens to match.
6
+
7
+ Test totals are intentionally omitted. They change as the corpus evolves; the test runner is the source of truth for execution status.
8
+
9
+ ## Evidence hierarchy
10
+
11
+ | Evidence | What it establishes | Limit |
12
+ | --- | --- | --- |
13
+ | Published record length / LRECL | Entire record has the expected physical extent | Does not prove interior offsets |
14
+ | Published sample bytes and literal field slices | Selected field ranges agree with bytes from the originating source | Not a complete IBM compiler storage map |
15
+ | Fixed expected field coordinates derived from published copybooks | Specific offsets and sizes agree with separately reviewed declarations | Humans can misunderstand the same language rule |
16
+ | IBM-rule-derived worked examples | Known effects of `REDEFINES`, `SYNCHRONIZED`, etc., at specified positions | Adapted examples are not original production copybooks |
17
+ | Geometric invariants | Left/right offsets, parent extents and overlays are internally coherent | Two incorrect calculations can agree with each other |
18
+
19
+ **Do not promote a source-derived coordinate to an IBM-compiler-verified offset unless an independent IBM listing or equivalent evidence exists.** Where an oracle is calculated manually, retain the declaration and reasoning alongside the expected literal numbers.
20
+
21
+ ## Test inventory
22
+
23
+ The following files all live under `src/`. Each tests the production parser, compiler, evaluator or locator; no special geometry implementation is substituted to make an external fixture pass.
24
+
25
+ | File | What it checks | Oracle type |
26
+ | --- | --- | --- |
27
+ | `cobol.layout.spec.ts` | Elementary/group layout and sequential physical placement | Hand-calculated geometry |
28
+ | `cobol.alignment.spec.ts`, `cobol.padding.spec.ts` | Alignment boundaries, padding generation and ownership | Storage-rule-derived coordinates |
29
+ | `cobol.layout.ibm.redefines.spec.ts` | IBM-oriented overlay restrictions and behaviour | IBM-rule-derived cases |
30
+ | `cobol.layout.odo.spec.ts`, `cobol.layout.odo.nested.spec.ts` | Fixed/variable tables, nested ODO, controllers and bounds | Literal sizes and physical positions |
31
+ | `cobol.layout.right.symbolic.spec.ts` | Right offsets and unequal symbolic overlay gaps | Algebraic suffix expectations |
32
+ | `cobol.layout.location.spec.ts` | Selected declarations and indexed occurrence locations | Literal bit offsets and lengths |
33
+ | `cobol.layout.composable.spec.ts`, `symbolic.layout.composition.spec.ts` | Independent declaration/repetition/placement strategies and tree composition | Architectural invariants |
34
+ | `cobol.layout.integration.campaign.spec.ts` | Deliberate combinations of ODO, overlays, alignment and indexed positions | Independent constructed expectations |
35
+ | `cobol.picture.spec.ts` | PICTURE grammar, repetitions, categories and configured currency symbols | Token/category expectations |
36
+ | `cobol.primitive.size.spec.ts` | DISPLAY, binary, packed, edited, national, DBCS, UTF-8 and sign storage | IBM-oriented known widths |
37
+ | `cobol.layout.ibm-options.spec.ts` | Actual copybook-to-layout path with configured currency and `BYTE-LENGTH`; dynamic storage rejection | Literal bit offsets and contract checks |
38
+ | `cobol.layout.published.spec.ts` | Published IBM examples and AWS `REC-OUTFILE` | Declared sizes and hand-derived field coordinates |
39
+ | `cobol.layout.aws.emprec.spec.ts` | AWS employee record, address occurrences, overlays, right offsets and published hex slices | Published LRECL/hex plus literal field coordinates |
40
+ | `cobol.layout.carddemo.spec.ts` | Original AWS CardDemo copybooks versus documented record lengths | Externally documented LRECL |
41
+ | `cobol.layout.carddemo.coordinates.spec.ts` | Named fields, trailing filler and tree consistency in CardDemo sources | Source-derived literal coordinates; additional invariants |
42
+ | `cobol.layout.reference-geometry.spec.ts` | Unequal overlays, IBM alignment boundaries, variable tables before overlays, nested ODO coordinates | Adapted IBM rules and constructed literal positions |
43
+
44
+ The symbolic expression package `@cobol-ts/size` additionally tests canonicalisation, count binding, occurrence-prefix evaluation, `max`, `align` and symbolic `difference`. Those tests guard the algebra used by this package but do not replace physical-coordinate tests.
45
+
46
+ ## Public copybook corpus and provenance
47
+
48
+ ### Published IBM and AWS worked examples
49
+
50
+ `fixtures/` contains published-example copybooks consumed by `cobol.layout.published.spec.ts`, including:
51
+
52
+ - `ibm-redefinition-example.cpy`: overlapping declaration origins, internal fields and storage following an overlay.
53
+ - `ibm-zos-error-messages.cpy`: consecutive message fields with expected repeated spacing.
54
+ - `aws-rec-outfile.cpy`: numeric-edited DISPLAY, binary, packed decimal, fixed `OCCURS` and `REDEFINES`, with literal field coordinates.
55
+
56
+ These examples are **transcriptions/adaptations of published declarations**, not unmodified upstream compiler input. Their origins are recorded in `fixtures/SOURCES.md`. Their coordinates are independently calculated from the declarations rather than obtained from this compiler's output.
57
+
58
+ ### AWS employee record
59
+
60
+ `fixtures/public/aws-emprec01.cpy` and `fixtures/public/aws-emprec01.first-record.hex` support `cobol.layout.aws.emprec.spec.ts`.
61
+
62
+ The AWS source documents a fixed **FB/150** employee record and publishes EBCDIC record bytes. The tests check group and elementary offsets, indexed addresses, `REDEFINES` origins, right offsets and field slices against literal hex bytes, **without decoding values**. The copybook fixture is transcribed from AWS's published listing; the test must not be described as an unmodified upstream `.cpy` download.
63
+
64
+ Source: [AWS — Unlock Mainframe Data Files on AWS](https://github.com/aws-samples/unlock-mainframe-data-files-on-aws#input-copybook).
65
+
66
+ ### AWS CardDemo
67
+
68
+ `fixtures/carddemo/` contains original public `.cpy` files used by `cobol.layout.carddemo.spec.ts` and `cobol.layout.carddemo.coordinates.spec.ts`. The upstream project separately documents their fixed record lengths.
69
+
70
+ The coordinate suite includes literal field offsets derived from declarations in:
71
+
72
+ - `CSUSR01Y.cpy` — user fields and final filler;
73
+ - `CVACT03Y.cpy` — card/customer/account cross-reference and trailing filler;
74
+ - `CVTRA05Y.cpy` — transaction fields, including the signed amount, timestamps and final filler.
75
+
76
+ For the other selected CardDemo sources, the suite checks the published LRECL and structural consistency but **does not claim independently reviewed field-offset oracles**. `fixtures/CARDDemo-offset-oracles.md` documents the separately reviewed coordinates and their provenance.
77
+
78
+ Source: [AWS CardDemo copybooks](https://github.com/aws-samples/aws-mainframe-modernization-carddemo/tree/main/app/cpy) and the [project's sample-data record lengths](https://github.com/aws-samples/aws-mainframe-modernization-carddemo#4-upload-sample-data).
79
+
80
+ Keep the downloaded original sources and `fixtures/carddemo/SOURCE.json` with their recorded upstream revision. The fetch script is intended for initial fixture acquisition or an explicit corpus update—not for ordinary test execution. Review upstream license and attribution requirements when checking fixtures into Git.
81
+
82
+ ### Constructed cross-feature tests
83
+
84
+ `cobol.layout.reference-geometry.spec.ts` and `cobol.layout.integration.campaign.spec.ts` deliberately combine difficult constructs to stress the symbolic architecture:
85
+
86
+ - longer and shorter `REDEFINES` alternatives sharing an origin, including right-hand gaps;
87
+ - `SYNCHRONIZED` binary fields requiring padding before or within nested groups;
88
+ - variable tables followed by further storage or overlays, evaluated at zero, intermediate and maximum counts;
89
+ - indexed nested ODO, with occurrence-prefix locations checked separately from total extent;
90
+ - left and right offsets, aligned ends and complete containing-group coverage.
91
+
92
+ These are **constructed tests**, not externally certified COBOL compiler listings. They matter because public examples with independently published coordinates for such combinations are unusually difficult to find.
93
+
94
+ ## Geometry acceptance rules
95
+
96
+ Where applicable, tests should assert more than the enclosing record size:
97
+
98
+ - The absolute start and physical length of a **named field** match fixed expected coordinates (expressed in bytes in fixture documentation, compared in bits in the API).
99
+ - Every occurrence index lands at its own correct start; nested variable-sized bodies are not assumed to have a constant stride.
100
+ - `REDEFINES` alternatives share their proper origin, while subsequent sequential storage starts after the **maximum** alternative extent.
101
+ - Alignment padding occupies the correct physical range and belongs to the correct containing group.
102
+ - Parent-relative left and right offsets describe a complete child occurrence body, with explicit overlay allowance; they do **not** silently substitute a whole-table extent for a repeated child's body.
103
+ - Record-specific ODO resolver values do not leak into shared compiled geometry.
104
+ - No byte decoding is required to establish these claims. Published hex fixtures, where present, are used to verify **slices at known positions**, not to test type conversion.
105
+
106
+ Internal identities, such as *left offset + selected size + right offset = containing occurrence extent*, are valuable guards but must not be mistaken for independent layout evidence. Unequal overlays require their alternative-specific gaps to be included in that identity.
107
+
108
+ ## Running the tests
109
+
110
+ From the existing `layout/` package:
111
+
112
+ ```sh
113
+ npm test -- --runInBand
114
+ ```
115
+
116
+ Focused runs:
117
+
118
+ ```sh
119
+ npm test -- --runInBand cobol.layout.published.spec.ts
120
+ npm test -- --runInBand cobol.layout.aws.emprec.spec.ts
121
+ npm test -- --runInBand cobol.layout.carddemo.spec.ts
122
+ npm test -- --runInBand cobol.layout.carddemo.coordinates.spec.ts
123
+ npm test -- --runInBand cobol.layout.reference-geometry.spec.ts
124
+ npm test -- --runInBand cobol.layout.integration.campaign.spec.ts
125
+ npm test -- --runInBand cobol.primitive.size.spec.ts
126
+ npm test -- --runInBand cobol.picture.spec.ts
127
+ ```
128
+
129
+ If the CardDemo fixtures are missing, populate them explicitly from `layout/`:
130
+
131
+ ```sh
132
+ node scripts/fetch-carddemo-copybooks.mjs
133
+ ```
134
+
135
+ An `ENOENT` from `fixtures/carddemo/` means the test data is absent; it is **not** a failed layout assertion. Once populated, keep fixtures pinned and run ordinary tests offline. Run the project's normal TypeScript checking in addition to Jest.
136
+
137
+ ## Maintaining trust in the tests
138
+
139
+ - Treat public copybooks as source artifacts. Do not edit them to make the parser accept them; keep necessary transformations separately documented.
140
+ - Keep external oracles as **literal expectations**. Never derive the expected offset or record length from `compileCobolLayout`, `locateCobolEntry` or the same evaluator being tested.
141
+ - Record the upstream URL, revision, record format, relevant compiler options and provenance of each expected value.
142
+ - If a legal upstream declaration fails, preserve the failing integration case while fixing the parser, primitive sizer or layout. Do not bypass it with a test-specific primitive sizer.
143
+ - Test useful **combinations**, not just individual language features: errors can cancel when only the final record length is checked.
144
+ - When a source is adapted from IBM documentation, label it **adapted**. When a field position is hand-derived, label it **source-derived**. Reserve **compiler-verified** for an actual independent compiler-produced oracle.
145
+ - Do not use a passing suite to claim exhaustive IBM compiler conformance or independent certification of every physical offset.
146
+
147
+ ## Remaining confidence gaps
148
+
149
+ Our strongest evidence still lies in fixed-layout public records and hand-checked fields. In particular, externally produced IBM storage maps would materially improve confidence for `SYNCHRONIZED` within repeated bodies, nested ODO, variable storage preceding aligned fields, and overlays whose alternatives have distinct symbolic extents. Tests for those interactions already exist internally; what remains missing is **independent compiler-produced coordinate evidence**.
150
+
151
+ Until client copybooks arrive, continue enriching the public corpus with verifiable record layouts. The objective is high confidence in **physical geometry** before investing in byte decoding—not a larger test count for its own sake.
152
+
153
+ ## Separate runtime acceptance boundary
154
+
155
+ This package's location and extent fixtures are independent **layout-geometry** tests. End-to-end projected access through a borrowed byte-backed record is covered separately in `cursor-loader-cobol`, notably `cobol.odo.projection.spec.ts`, `cobol.multiple.nested.odo.spec.ts` and `cobol.odo.three.level.spec.ts`. Their nested fixtures use count fields at fixed physical locations. They do not prove occurrence-local count decoding, variable-record framing or production scalar codec integration. Keep that distinction explicit when claiming nested ODO support.
@@ -0,0 +1,7 @@
1
+ export * from './src/cobol.alignment';
2
+ export * from './src/cobol.layout.location';
3
+ export * from './src/cobol.overlay.alignment';
4
+ export * from './src/cobol.layout';
5
+ export * from './src/cobol.padding';
6
+ export * from './src/cobol.primitive.size';
7
+ export * from './src/cobol.picture';
package/dist/index.js ADDED
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./src/cobol.alignment"), exports);
18
+ __exportStar(require("./src/cobol.layout.location"), exports);
19
+ __exportStar(require("./src/cobol.overlay.alignment"), exports);
20
+ __exportStar(require("./src/cobol.layout"), exports);
21
+ __exportStar(require("./src/cobol.padding"), exports);
22
+ __exportStar(require("./src/cobol.primitive.size"), exports);
23
+ __exportStar(require("./src/cobol.picture"), exports);
24
+ //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,66 @@
1
1
  {
2
2
  "name": "@cobol-ts/layout",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "description": "Compiles COBOL copybook ASTs into immutable physical storage layouts, including canonical size expressions, field offsets, and dependency resolution.",
4
+ "version": "0.0.1",
5
+ "main": "dist/index",
6
+ "types": "dist/index",
7
+ "browserslist": {
8
+ "development": [
9
+ "last 1 chrome version",
10
+ "last 1 firefox version",
11
+ "last 1 safari version"
12
+ ],
13
+ "production": [
14
+ ">0.2%",
15
+ "not dead",
16
+ "not op_mini all"
17
+ ]
18
+ },
19
+ "dependencies": {
20
+ "@cobol-ts/copybook": "0.0.1",
21
+ "@cobol-ts/errors": "0.0.1",
22
+ "@cobol-ts/partial_functions": "0.0.1",
23
+ "@cobol-ts/size": "0.0.1",
24
+ "@cobol-ts/trees": "0.0.1"
25
+ },
26
+ "devDependencies": {
27
+ "@testing-library/jest-dom": "^6.1.4",
28
+ "@types/jest": "^29.0.0",
29
+ "@types/node": "^14.0.0",
30
+ "jest": "^29.0.0",
31
+ "ts-jest": "^29.0.0",
32
+ "typescript": "^5.2.2"
33
+ },
34
+ "eslintConfig": {
35
+ "extends": [
36
+ "react-app",
37
+ "react-app/jest"
38
+ ],
39
+ "overrides": [
40
+ {
41
+ "files": [
42
+ "**/*.stories.*"
43
+ ],
44
+ "rules": {
45
+ "import/no-anonymous-default-export": "off"
46
+ }
47
+ }
48
+ ]
49
+ },
50
+ "files": [
51
+ "dist/index.js",
52
+ "dist/index.d.ts",
53
+ "dist/src/",
54
+ "build/"
55
+ ],
56
+ "keywords": [
57
+ "indexing"
58
+ ],
59
+ "license": "MIT",
60
+ "repository": "git@github.com:intellimaintain/intellimaintain.git",
61
+ "scripts": {
62
+ "test": "jest --config jest.config.json --env node",
63
+ "test:watch": "npm run test -- --watch",
64
+ "start": "react-scripts start"
65
+ }
6
66
  }