Skip to main content

ironwork_compile/
layout.rs

1//! WORKING-STORAGE as IBM lays it out: sizes by USAGE and PICTURE, REDEFINES sharing storage,
2//! OCCURS repeating it, SYNCHRONIZED slack bytes before an item and after each occurrence, and
3//! level-66 RENAMES over what is laid out. See [`numeric::assumptions::WORKING_STORAGE_LAYOUT`]
4//! for where each 01 level starts.
5
6use crate::picture::{self, Category, Sym};
7use numeric::Qualify;
8use syntax::ast::{DataEntry, Environment, FileDecl, Literal, Organization, Ref, SignClause, Usage};
9use syntax::{Error, Pos};
10use zarch::hfp::Precision;
11
12pub use rt::storage::Kind;
13
14#[derive(Clone, Debug)]
15pub struct Item {
16    pub name: Option<String>,
17    pub level: u8,
18    pub parent: Option<usize>,
19    pub children: Vec<usize>,
20    pub offset: u32,
21    /// One occurrence.
22    pub size: u32,
23    pub occurs: u32,
24    /// The fewest occurrences: OCCURS DEPENDING ON's minimum, else `occurs`.
25    pub occurs_min: u32,
26    /// Declared with OCCURS, so references to it take a subscript.
27    pub table: bool,
28    /// OCCURS ... DEPENDING ON: the item holding the current number of occurrences.
29    pub depending_on: Option<syntax::ast::Ref>,
30    /// The OCCURS DEPENDING ON tables within this group, other than one within another of them: the
31    /// occurrences past each one's current count leave its length out.
32    pub odo: Vec<usize>,
33    /// The OCCURS DEPENDING ON tables ahead of this item in its record: the occurrences past each
34    /// one's current count move it back (a variably located item, Language Reference SC27-8713-03,
35    /// p. 206).
36    pub moved_by: Vec<usize>,
37    /// Whether an item after this one in its record moves with an OCCURS DEPENDING ON table in it.
38    pub followed: bool,
39    /// A table's INDEXED BY names, and its ASCENDING/DESCENDING keys.
40    pub index_names: Vec<String>,
41    pub keys: Vec<(bool, syntax::ast::Ref)>,
42    /// A LOCAL-STORAGE item: its offset is from the activation's local storage.
43    pub local: bool,
44    pub kind: Kind,
45    pub value: Option<Literal>,
46    /// Stride and count of each OCCURS on the item and its ancestors, outermost first.
47    pub dims: Vec<(u32, u32)>,
48    pub redefines: Option<String>,
49    /// The file whose record area holds the item, for a FILE SECTION record.
50    pub file: Option<u16>,
51    /// The LINKAGE record the item belongs to, by its position among LINKAGE 01 and 77 items; its
52    /// offset is from that record's start, wherever the caller's argument puts it.
53    pub linkage: Option<u16>,
54    /// The class-name of a typed object reference.
55    pub object_class: Option<String>,
56    /// PICTURE scaling positions P right of the digits: the item's value is its digits times ten
57    /// to this power.
58    pub scaling: u32,
59    /// Of category alphabetic: a PICTURE of the symbol A alone.
60    pub alphabetic: bool,
61    pub pos: Pos,
62}
63
64#[derive(Clone, Debug)]
65pub struct Condition {
66    pub name: String,
67    pub item: usize,
68    pub values: Vec<(Literal, Option<Literal>)>,
69    /// The WHEN SET TO FALSE value.
70    pub false_value: Option<Literal>,
71}
72
73#[derive(Clone, Copy, Debug, PartialEq, Eq)]
74pub enum Resolved {
75    Item(usize),
76    Condition(usize),
77}
78
79/// Where a record addressed as a LINKAGE record is. Every other record is in the program's own
80/// storage (Language Reference SC27-8713-03, pp. 63-66).
81#[derive(Clone, Debug, PartialEq, Eq)]
82pub enum Binding {
83    /// A LINKAGE record: an argument, SET ADDRESS OF or the runtime gives it its address.
84    Argument,
85    /// An EXTERNAL data record, or a record redefining one: the run unit's record of this name
86    /// and size.
87    External { name: String, size: u32 },
88    /// A record of file k, an EXTERNAL file: the run unit's record area of that file-name.
89    ExternalFile(u16),
90    /// A GLOBAL record of a program containing this one, by its PROGRAM-ID and the record's name.
91    Global { program: String, record: String, section: Section },
92}
93
94/// Where a GLOBAL record is in the program that declares it.
95#[derive(Clone, Debug, PartialEq, Eq)]
96pub enum Section {
97    WorkingStorage,
98    LocalStorage,
99    Linkage,
100    /// The record area of the file of this name.
101    File(String),
102}
103
104pub struct Layout {
105    pub items: Vec<Item>,
106    pub conditions: Vec<Condition>,
107    /// The positions of each edited PICTURE.
108    pub edits: Vec<Vec<Sym>>,
109    /// The currency sign value each edited PICTURE's currency symbol stands for, empty without one.
110    pub currencies: Vec<String>,
111    /// Offset and size of each file's record area, in declaration order.
112    pub file_areas: Vec<(u32, u32)>,
113    /// The least and greatest length of each file's level-01 records, an OCCURS DEPENDING ON table
114    /// counted at its fewest and at its most occurrences (Language Reference SC27-8713-03, p. 188);
115    /// None for a file with none.
116    pub record_lengths: Vec<Option<(u32, u32)>>,
117    /// The item of each LINKAGE record, in order: the LINKAGE SECTION's, then the records whose
118    /// storage is elsewhere, as `bindings` says.
119    pub linkage_roots: Vec<usize>,
120    pub bindings: Vec<Binding>,
121    /// How many programs out the program declaring each LINKAGE record is: 0 for its own.
122    pub depths: Vec<u8>,
123    /// For each file whose record area is not in the program's storage, the LINKAGE record
124    /// bound to that area.
125    pub bound_areas: Vec<Option<u16>>,
126    /// Bytes of LOCAL-STORAGE each activation gets.
127    pub local_size: u32,
128    pub size: u32,
129    /// Each FD and SD name, in declaration order: the highest qualifier of its records.
130    pub file_names: Vec<String>,
131    /// The LINAGE-COUNTER item of each file whose FD has LINAGE, which its file-name qualifies.
132    pub linage_counters: Vec<Option<usize>>,
133    /// The QUALIFY option [`Layout::resolve`] follows.
134    pub qualify: Qualify,
135    /// PARMCHECK's buffer: its offset, at the end of the WORKING-STORAGE the program declares, and
136    /// its length (assumption [`numeric::assumptions::PARMCHECK_BUFFER`]).
137    pub parmcheck: Option<(u32, u32)>,
138    pub numcheck: crate::numcheck::NumcheckFacts,
139}
140
141const LEVEL_ALIGNMENT: u32 = 8;
142/// The interpreter's ceiling on WORKING-STORAGE, well under Enterprise COBOL's own.
143pub const MAX_STORAGE: u32 = 128 << 20;
144
145/// Lays out WORKING-STORAGE, then each file's record area, which all its 01 records share and
146/// which is at least `record_max` bytes. Files whose `shared` entry names the same file share one
147/// area, as large as the largest of them (see [`record_area_owners`]). `notation` is what
148/// SPECIAL-NAMES changes in the PICTUREs; `qualify` how RENAMES and later references resolve.
149/// Under PARMCHECK, `parmcheck` is how many of `entries` the program declares itself, the special
150/// registers the compiler adds following them, and the bytes of the buffer that goes between
151/// (Programming Guide SC27-8714-03, p. 397).
152#[allow(clippy::too_many_arguments)]
153pub fn build(
154    entries: &[DataEntry],
155    files: &[(&[DataEntry], Option<u32>)],
156    shared: &[usize],
157    linkage: &[DataEntry],
158    local: &[DataEntry],
159    notation: picture::Notation,
160    qualify: Qualify,
161    parmcheck: Option<(usize, u32)>,
162) -> Result<Layout, Error> {
163    let mut items: Vec<Item> = Vec::new();
164    let mut usages: Vec<Option<Usage>> = Vec::new();
165    let mut signs: Vec<Option<SignClause>> = Vec::new();
166    let mut synchronized: Vec<bool> = Vec::new();
167    let mut conditions = Vec::new();
168    let mut open: Vec<usize> = Vec::new();
169    let mut renames: Vec<(usize, &DataEntry)> = Vec::new();
170    const LINKAGE: u16 = u16::MAX;
171    const LOCAL: u16 = u16::MAX - 1;
172    let tagged: Vec<(Option<u16>, &DataEntry)> = entries
173        .iter()
174        .map(|e| (None, e))
175        .chain(files.iter().enumerate().flat_map(|(k, (records, _))| records.iter().map(move |e| (Some(k as u16), e))))
176        .chain(linkage.iter().map(|e| (Some(LINKAGE), e)))
177        .chain(local.iter().map(|e| (Some(LOCAL), e)))
178        .collect();
179    let mut group = None;
180    let mut linkage_roots = Vec::new();
181    let mut after_renames = false;
182    let bound = bound_records(&tagged);
183    let mut bound_roots = Vec::new();
184    for (&(region, e), &bound) in tagged.iter().zip(&bound) {
185        if region != group {
186            open.clear();
187            group = region;
188            after_renames = false;
189        }
190        let file = region.filter(|&r| r != LINKAGE && r != LOCAL);
191        let in_linkage = region == Some(LINKAGE);
192        if e.occurs.is_some() && matches!(e.level, 1 | 66 | 77 | 88) {
193            return Err(Error::at(e.pos, format!("OCCURS at level {:02}: Enterprise COBOL takes OCCURS only at levels 02 to 49", e.level)));
194        }
195        if e.level == 88 {
196            if after_renames {
197                return Err(Error::at(e.pos, "a level-88 entry after a level-66 entry: a RENAMES item cannot be a conditional variable"));
198            }
199            let item = *open.last().ok_or_else(|| Error::at(e.pos, "a level-88 entry with no item before it"))?;
200            let name = e.name.clone().ok_or_else(|| Error::at(e.pos, "a level-88 entry needs a name"))?;
201            conditions.push(Condition { name, item, values: e.condition_values.clone(), false_value: e.false_value.clone() });
202            continue;
203        }
204        if e.renames.is_some() != (e.level == 66) {
205            return Err(Error::at(e.pos, "RENAMES goes with level 66, and level 66 with RENAMES"));
206        }
207        if e.level == 66 {
208            let record = open.first().copied().filter(|&r| items[r].level == 1).ok_or_else(|| Error::at(e.pos, "a level-66 entry must follow the entries of a level-01 record"))?;
209            if e.name.is_none() || e.picture.is_some() || e.usage.is_some() || e.value.is_some() || e.redefines.is_some() || e.sync || e.sign.is_some() {
210                return Err(Error::at(e.pos, "a level-66 entry has a name and a RENAMES clause, and nothing else"));
211            }
212            renames.push((items.len(), e));
213            items.push(Item {
214                name: e.name.clone(),
215                level: 66,
216                parent: Some(record),
217                children: Vec::new(),
218                offset: 0,
219                size: 0,
220                occurs: 1,
221                occurs_min: 1,
222                table: false,
223                depending_on: None,
224                odo: Vec::new(),
225                moved_by: Vec::new(),
226                followed: false,
227                index_names: Vec::new(),
228                keys: Vec::new(),
229                local: items[record].local,
230                kind: Kind::Group,
231                value: None,
232                dims: Vec::new(),
233                redefines: None,
234                file,
235                linkage: items[record].linkage,
236                object_class: None,
237                scaling: 0,
238                alphabetic: false,
239                pos: e.pos,
240            });
241            usages.push(None);
242            signs.push(None);
243            synchronized.push(false);
244            after_renames = true;
245            continue;
246        }
247        if !(e.level == 1 || e.level == 77 || (2..=49).contains(&e.level)) {
248            return Err(Error::at(e.pos, format!("level {} is not a data level", e.level)));
249        }
250        if after_renames && e.level != 1 && e.level != 77 {
251            return Err(Error::at(e.pos, format!("level {:02} after a level-66 entry: a record's RENAMES entries follow its last entry", e.level)));
252        }
253        after_renames = false;
254        while open.last().is_some_and(|&i| items[i].level >= e.level || items[i].level == 77) {
255            open.pop();
256        }
257        let parent = if e.level == 1 || e.level == 77 { None } else { open.last().copied() };
258        if e.level != 1 && e.level != 77 && parent.is_none() {
259            return Err(Error::at(e.pos, format!("level {} with no group to belong to", e.level)));
260        }
261        let index = items.len();
262        items.push(Item {
263            name: e.name.clone(),
264            level: e.level,
265            parent,
266            children: Vec::new(),
267            offset: 0,
268            size: 0,
269            occurs: e.occurs.unwrap_or(1),
270            occurs_min: e.occurs_min.or(e.occurs).unwrap_or(1),
271            table: e.occurs.is_some(),
272            depending_on: e.depending_on.clone(),
273            odo: Vec::new(),
274            moved_by: Vec::new(),
275            followed: false,
276            index_names: e.indexed_by.clone(),
277            keys: e.keys.clone(),
278            local: region == Some(LOCAL),
279            kind: Kind::Group,
280            value: e.value.clone().filter(|_| file.is_none() && !in_linkage),
281            dims: Vec::new(),
282            redefines: e.redefines.clone(),
283            file,
284            linkage: if in_linkage {
285                Some(match (parent, &e.redefines) {
286                    (None, Some(target)) => linkage_roots.iter().position(|&r: &usize| items[r].name.as_ref() == Some(target)).ok_or_else(|| {
287                        Error::at(e.pos, format!("REDEFINES {target}: no earlier 01-level item of that name"))
288                    })? as u16,
289                    (None, None) => {
290                        linkage_roots.push(index);
291                        linkage_roots.len() as u16 - 1
292                    }
293                    (Some(p), _) => items[p].linkage.unwrap_or_default(),
294                })
295            } else if bound {
296                if parent.is_none() {
297                    bound_roots.push(index);
298                }
299                Some(0)
300            } else {
301                None
302            },
303            object_class: e.object_class.clone(),
304            scaling: 0,
305            alphabetic: false,
306            pos: e.pos,
307        });
308        if e.occurs == Some(0) {
309            return Err(Error::at(e.pos, "OCCURS 0 is not a table"));
310        }
311        let inherited = parent.and_then(|p| usages[p]);
312        usages.push(e.usage.or(inherited));
313        signs.push(e.sign.or(parent.and_then(|p| signs[p])));
314        synchronized.push(e.sync || parent.is_some_and(|p| synchronized[p]));
315        if let Some(p) = parent {
316            items[p].children.push(index);
317        }
318        open.push(index);
319    }
320    let (mut edits, mut currencies) = (Vec::new(), Vec::new());
321    let mut aligns = vec![1u32; items.len()];
322    for (index, (_, e)) in tagged.iter().filter(|(_, e)| e.level != 88).enumerate() {
323        if e.level == 66 {
324            continue;
325        }
326        let pic = e.picture.as_deref().map(|p| picture::analyse_with(p, notation).map_err(|m| Error::at(e.pos, m))).transpose()?;
327        items[index].kind = kind(e, &items[index], usages[index], signs[index], pic.as_ref(), &mut edits)?;
328        if currencies.len() < edits.len() {
329            currencies.push(pic.as_ref().and_then(|p| p.currency.clone()).unwrap_or_default());
330        }
331        items[index].scaling = pic.as_ref().map_or(0, |p| p.scaling);
332        items[index].alphabetic = matches!(items[index].kind, Kind::Alnum { .. }) && e.picture.as_deref().is_some_and(crate::corresponding::is_alphabetic);
333        items[index].size = elementary_size(&items[index], pic.as_ref().map(|p| p.size));
334        if synchronized[index] && items[index].kind != Kind::Group {
335            aligns[index] = alignment(items[index].kind);
336        }
337    }
338    for (_, e) in &tagged {
339        for name in &e.indexed_by {
340            items.push(Item {
341                name: Some(name.clone()),
342                level: 77,
343                parent: None,
344                children: Vec::new(),
345                offset: 0,
346                size: 4,
347                occurs: 1,
348                occurs_min: 1,
349                table: false,
350                depending_on: None,
351                odo: Vec::new(),
352                moved_by: Vec::new(),
353                followed: false,
354                index_names: Vec::new(),
355                keys: Vec::new(),
356                local: false,
357                kind: Kind::Index,
358                value: None,
359                dims: Vec::new(),
360                redefines: None,
361                file: None,
362                linkage: None,
363                object_class: None,
364                scaling: 0,
365                alphabetic: false,
366                pos: e.pos,
367            });
368        }
369    }
370    aligns.resize(items.len(), 1);
371    let arguments = linkage_roots.len();
372    for i in 0..items.len() {
373        let mut r = i;
374        while let Some(p) = items[r].parent {
375            r = p;
376        }
377        if let Some(b) = bound_roots.iter().position(|&x| x == r) {
378            items[i].linkage = Some((arguments + b) as u16);
379        }
380    }
381    linkage_roots.extend(&bound_roots);
382    let roots: Vec<usize> = (0..items.len()).filter(|&i| items[i].parent.is_none()).collect();
383    for &r in &roots {
384        measure(&mut items, &aligns, r, 0)?;
385    }
386    let mut local_cursor = 0u32;
387    let local_roots: Vec<usize> = roots.iter().copied().filter(|&r| items[r].local).collect();
388    for r in local_roots {
389        let start = local_cursor.div_ceil(LEVEL_ALIGNMENT) * LEVEL_ALIGNMENT;
390        local_cursor = start + items[r].size;
391        if local_cursor > MAX_STORAGE {
392            return Err(Error::at(items[r].pos, format!("LOCAL-STORAGE exceeds the interpreter's {MAX_STORAGE} bytes")));
393        }
394        place(&mut items, r, start, Vec::new());
395    }
396    let owner = |k: usize| shared.get(k).copied().filter(|&g| g < files.len()).unwrap_or(k);
397    let mut own: Vec<u32> = files.iter().map(|f| f.1.unwrap_or(0)).collect();
398    for &r in &roots {
399        if let Some(k) = items[r].file {
400            own[k as usize] = own[k as usize].max(items[r].size);
401        }
402    }
403    let mut area_size = vec![0u32; files.len()];
404    for (k, &size) in own.iter().enumerate() {
405        area_size[owner(k)] = area_size[owner(k)].max(size);
406    }
407    let mut cursor = 0u32;
408    let mut root_offsets: Vec<(String, u32)> = Vec::new();
409    let mut area_starts: Vec<Option<u32>> = vec![None; files.len()];
410    let mut pending = parmcheck.map(|(declared, bytes)| (entries[..declared.min(entries.len())].iter().filter(|e| e.level != 88).count(), bytes));
411    let mut buffer = None;
412    for &r in &roots {
413        if items[r].local {
414            continue;
415        }
416        if items[r].linkage.is_some() {
417            place(&mut items, r, 0, Vec::new());
418            continue;
419        }
420        if let Some((own, bytes)) = pending
421            && r >= own
422        {
423            buffer = Some((cursor, bytes));
424            cursor += bytes;
425            pending = None;
426        }
427        if let Some(k) = items[r].file {
428            let g = owner(k as usize);
429            let start = *area_starts[g].get_or_insert(cursor.div_ceil(LEVEL_ALIGNMENT) * LEVEL_ALIGNMENT);
430            cursor = cursor.max(start + area_size[g]);
431            if cursor > MAX_STORAGE {
432                return Err(Error::at(items[r].pos, format!("storage exceeds the interpreter's {MAX_STORAGE} bytes")));
433            }
434            place(&mut items, r, start, Vec::new());
435            continue;
436        }
437        let offset = match &items[r].redefines {
438            Some(target) => root_offsets.iter().find(|(n, _)| n == target).map(|&(_, o)| o).ok_or_else(|| {
439                Error::at(items[r].pos, format!("REDEFINES {target}: no earlier 01-level item of that name"))
440            })?,
441            None => cursor.div_ceil(LEVEL_ALIGNMENT) * LEVEL_ALIGNMENT,
442        };
443        cursor = cursor.max(offset + items[r].size);
444        if cursor > MAX_STORAGE {
445            return Err(Error::at(items[r].pos, format!("WORKING-STORAGE exceeds the interpreter's {MAX_STORAGE} bytes")));
446        }
447        if let Some(name) = &items[r].name {
448            root_offsets.push((name.clone(), offset));
449        }
450        place(&mut items, r, offset, Vec::new());
451    }
452    if let Some((_, bytes)) = pending {
453        buffer = Some((cursor, bytes));
454        cursor += bytes;
455    }
456    let tables: Vec<usize> = (0..items.len()).filter(|&i| items[i].depending_on.is_some()).collect();
457    for &t in &tables {
458        let (mut child, mut at, mut nested) = (t, items[t].parent, false);
459        let (mut chain, mut followers) = (vec![t], Vec::new());
460        while let Some(a) = at {
461            nested |= child != t && items[child].depending_on.is_some();
462            if !nested {
463                items[a].odo.push(t);
464            }
465            let end = items[child].offset + items[child].size * items[child].occurs;
466            let after = items[a].children.iter().skip_while(|&&c| c != child).skip(1).copied().filter(|&c| items[c].offset >= end);
467            let before = followers.len();
468            followers.extend(after);
469            if followers.len() > before {
470                chain.iter().for_each(|&c| items[c].followed = true);
471            }
472            chain.push(a);
473            (child, at) = (a, items[a].parent);
474        }
475        let holds_another = tables.iter().any(|&u| u != t && ancestors(&items, u).any(|p| p == t));
476        if !followers.is_empty() && (items[t].dims.len() > 1 || holds_another) {
477            return Err(Error::at(items[t].pos, "items after an OCCURS DEPENDING ON table in the same record are not supported yet"));
478        }
479        while let Some(f) = followers.pop() {
480            items[f].moved_by.push(t);
481            followers.extend(items[f].children.iter().copied());
482        }
483    }
484    for (index, e) in renames {
485        rename(&mut items, index, e, qualify)?;
486    }
487    let mut bound_areas = vec![None; files.len()];
488    let mut bindings = vec![Binding::Argument; arguments];
489    for &r in &bound_roots {
490        let binding = match items[r].file {
491            Some(k) => {
492                bound_areas[k as usize].get_or_insert(items[r].linkage.unwrap_or_default());
493                Binding::ExternalFile(k)
494            }
495            None => {
496                let name = items[r].redefines.clone().or_else(|| items[r].name.clone()).unwrap_or_default();
497                let size = bound_roots.iter().find(|&&t| items[t].name.as_deref() == Some(name.as_str())).map_or(items[r].size, |&t| items[t].size);
498                Binding::External { name, size }
499            }
500        };
501        bindings.push(binding);
502    }
503    let mut areas = Vec::new();
504    for (k, &size) in own.iter().enumerate() {
505        if bound_areas[k].is_some() {
506            areas.push((0, area_size[owner(k)]));
507            continue;
508        }
509        let g = owner(k);
510        let start = match area_starts[g] {
511            Some(start) => start,
512            None => {
513                let start = cursor.div_ceil(LEVEL_ALIGNMENT) * LEVEL_ALIGNMENT;
514                area_starts[g] = Some(start);
515                cursor = cursor.max(start + area_size[g]);
516                start
517            }
518        };
519        areas.push((start, size));
520    }
521    let mut record_lengths: Vec<Option<(u32, u32)>> = vec![None; files.len()];
522    for &r in &roots {
523        let Some(k) = items[r].file else { continue };
524        let fewer: u32 = items[r]
525            .odo
526            .iter()
527            .map(|&t| {
528                let t = &items[t];
529                let outer: u32 = t.dims[..t.dims.len().saturating_sub(1)].iter().map(|&(_, n)| n).product();
530                t.occurs.saturating_sub(t.occurs_min) * t.size * outer
531            })
532            .sum();
533        let (least, most) = (items[r].size.saturating_sub(fewer), items[r].size);
534        let lengths = &mut record_lengths[k as usize];
535        *lengths = Some(lengths.map_or((least, most), |(l, m)| (l.min(least), m.max(most))));
536    }
537    Ok(Layout {
538        items,
539        conditions,
540        edits,
541        currencies,
542        file_areas: areas,
543        record_lengths,
544        linkage_roots,
545        depths: vec![0; bindings.len()],
546        bindings,
547        bound_areas,
548        local_size: local_cursor,
549        size: cursor,
550        file_names: Vec::new(),
551        linage_counters: Vec::new(),
552        qualify,
553        parmcheck: buffer,
554        numcheck: Default::default(),
555    })
556}
557
558
559/// The names of item `start` and each group above it, nearest first: the hierarchy of names that
560/// qualifies an item `start` holds or a condition-name of `start`. FILLER and unnamed items give
561/// none.
562fn names_from(items: &[Item], start: Option<usize>) -> impl Iterator<Item = &str> {
563    std::iter::successors(start, |&p| items[p].parent).filter_map(|p| items[p].name.as_deref())
564}
565
566/// Which entries belong to records whose storage the run unit holds: an EXTERNAL record of
567/// WORKING-STORAGE or of an EXTERNAL file, or a WORKING-STORAGE record redefining an EXTERNAL one
568/// (Language Reference SC27-8713-03, p. 197).
569fn bound_records(tagged: &[(Option<u16>, &DataEntry)]) -> Vec<bool> {
570    let mut externals: Vec<&str> = Vec::new();
571    let mut current = false;
572    let mut out = Vec::with_capacity(tagged.len());
573    for &(region, e) in tagged {
574        if matches!(e.level, 1 | 77) {
575            current = match region {
576                None => e.external || e.redefines.as_deref().is_some_and(|t| externals.contains(&t)),
577                Some(r) => r < u16::MAX - 1 && e.external,
578            };
579            if current && region.is_none() && e.external {
580                externals.extend(e.name.as_deref());
581            }
582        }
583        out.push(current);
584    }
585    out
586}
587
588/// Gives level-66 entry `index` the storage and attributes of what it renames (Language Reference
589/// SC27-8713-03, pp. 228-229): one item as that item is, or from the start of the first item
590/// through the end of the last as an alphanumeric group.
591fn rename(items: &mut [Item], index: usize, e: &DataEntry, qualify: Qualify) -> Result<(), Error> {
592    let Some((first, last)) = &e.renames else { return Ok(()) };
593    let record = items[index].parent.unwrap_or(index);
594    let find = |r: &Ref| -> Result<usize, Error> {
595        let err = |m: String| Err(Error::at(r.pos, format!("RENAMES {}: {m}", r.name)));
596        if !r.subscripts.is_empty() || r.refmod.is_some() {
597            return err("a renamed item is named without subscripts or reference modification".into());
598        }
599        let in_record = |mut at: usize| {
600            let mut wanted = r.qualifiers.iter().peekable();
601            while let Some(p) = items[at].parent {
602                if wanted.peek().is_some_and(|q| items[p].name.as_deref() == Some(q.as_str())) {
603                    wanted.next();
604                }
605                at = p;
606            }
607            at == record && wanted.next().is_none()
608        };
609        let mut found: Vec<usize> = (0..items.len()).filter(|&i| i != record && items[i].level != 66 && items[i].name.as_deref() == Some(r.name.as_str()) && in_record(i)).collect();
610        if found.len() > 1 && qualify == Qualify::Extend {
611            let complete: Vec<usize> = found.iter().copied().filter(|&i| names_from(items, items[i].parent).eq(r.qualifiers.iter().map(String::as_str))).collect();
612            if complete.len() == 1 {
613                found = complete;
614            }
615        }
616        let &[t] = found.as_slice() else {
617            let record_name = items[record].name.clone().unwrap_or_default();
618            return err(if found.is_empty() { format!("no item of that name below {record_name}, other than a level-66 entry") } else { "ambiguous; qualify it with OF or IN".into() });
619        };
620        if !items[t].dims.is_empty() {
621            return err("a renamed item must not have OCCURS, nor belong to a group that has it".into());
622        }
623        Ok(t)
624    };
625    if first.name == items[record].name.clone().unwrap_or_default() && first.qualifiers.is_empty() {
626        return Err(Error::at(first.pos, format!("RENAMES {}: a level-66 entry cannot rename a level-01 record", first.name)));
627    }
628    let a = find(first)?;
629    let Some(last) = last else {
630        let (offset, size, kind, scaling, odo, moved_by, followed) =
631            (items[a].offset, items[a].size, items[a].kind, items[a].scaling, items[a].odo.clone(), items[a].moved_by.clone(), items[a].followed);
632        let it = &mut items[index];
633        (it.offset, it.size, it.kind, it.scaling, it.odo, it.moved_by, it.followed) = (offset, size, kind, scaling, odo, moved_by, followed);
634        return Ok(());
635    };
636    let b = find(last)?;
637    let end = |i: usize| items[i].offset + items[i].size;
638    let mut up = items[b].parent;
639    while let Some(p) = up {
640        if p == a {
641            return Err(Error::at(last.pos, format!("RENAMES {} THRU {}: the last item cannot be within the first", first.name, last.name)));
642        }
643        up = items[p].parent;
644    }
645    if a == b || items[b].offset < items[a].offset || end(b) < end(a) {
646        return Err(Error::at(last.pos, format!("RENAMES {} THRU {}: the last item must start and end no earlier than the first", first.name, last.name)));
647    }
648    let root = |mut i: usize| {
649        while let Some(p) = items[i].parent {
650            i = p;
651        }
652        i
653    };
654    if let Some(t) = (0..items.len()).find(|&i| items[i].depending_on.is_some() && root(i) == record && items[i].offset >= items[a].offset && items[i].offset < end(b)) {
655        return Err(Error::at(items[t].pos, format!("RENAMES {} THRU {}: no OCCURS DEPENDING ON between them", first.name, last.name)));
656    }
657    let (offset, size, moved_by) = (items[a].offset, end(b) - items[a].offset, items[a].moved_by.clone());
658    let it = &mut items[index];
659    (it.offset, it.size, it.kind, it.moved_by) = (offset, size, Kind::Group, moved_by);
660    Ok(())
661}
662
663/// The groups item `i` belongs to, nearest first.
664fn ancestors(items: &[Item], i: usize) -> impl Iterator<Item = usize> + '_ {
665    std::iter::successors(items[i].parent, |&p| items[p].parent)
666}
667
668/// The boundary a SYNCHRONIZED item of this kind is aligned on (Language Reference SC27-8713-03,
669/// pp. 232-233); 1 for the kinds SYNCHRONIZED leaves where they are.
670fn alignment(kind: Kind) -> u32 {
671    match kind {
672        Kind::Binary { digits: 0..=4, .. } => 2,
673        Kind::Binary { .. } | Kind::Float(Precision::Short) | Kind::Pointer | Kind::Index | Kind::ObjectReference | Kind::ProgramPointer => 4,
674        Kind::Float(_) => 8,
675        _ => 1,
676    }
677}
678
679/// An elementary item's kind. `sign` is its own SIGN clause or the nearest group's above it, which
680/// applies to a signed zoned item alone (Language Reference SC27-8713-03, p. 231).
681fn kind(e: &DataEntry, item: &Item, usage: Option<Usage>, sign: Option<SignClause>, pic: Option<&picture::Picture>, edits: &mut Vec<Vec<Sym>>) -> Result<Kind, Error> {
682    let err = |m: String| Error::at(e.pos, m);
683    let usage = usage.unwrap_or_default();
684    let handle = matches!(usage, Usage::ObjectReference | Usage::ProgramPointer);
685    let elementary = e.picture.is_some() || (handle || matches!(usage, Usage::Float1 | Usage::Float2 | Usage::Pointer | Usage::Index)) && item.children.is_empty();
686    if !elementary {
687        return if item.children.is_empty() { Err(err("an elementary item needs a PICTURE".into())) } else { Ok(Kind::Group) };
688    }
689    if !item.children.is_empty() {
690        return Err(err("a group item cannot have a PICTURE".into()));
691    }
692    if handle {
693        if e.picture.is_some() || e.value.as_ref().is_some_and(|v| *v != Literal::Figurative(syntax::ast::Figurative::Null)) {
694            return Err(err("an object reference, function-pointer or procedure-pointer takes no PICTURE and only VALUE NULL".into()));
695        }
696        return Ok(if usage == Usage::ObjectReference { Kind::ObjectReference } else { Kind::ProgramPointer });
697    }
698    if let Usage::Pointer | Usage::Index = usage {
699        if e.picture.is_some() {
700            return Err(err("POINTER and INDEX items take no PICTURE".into()));
701        }
702        return Ok(if usage == Usage::Pointer { Kind::Pointer } else { Kind::Index });
703    }
704    if let Usage::Float1 | Usage::Float2 = usage {
705        if e.picture.is_some() {
706            return Err(err("COMP-1 and COMP-2 items take no PICTURE".into()));
707        }
708        return Ok(Kind::Float(if usage == Usage::Float1 { Precision::Short } else { Precision::Long }));
709    }
710    let Some(pic) = pic else { return Err(err("an elementary item needs a PICTURE".into())) };
711    let blank_numeric;
712    let pic = match pic.category {
713        Category::Numeric if e.blank_when_zero && usage == Usage::Display => {
714            blank_numeric = picture::blank_when_zero(pic).map_err(err)?;
715            &blank_numeric
716        }
717        Category::NumericEdited => pic,
718        Category::Numeric if e.blank_when_zero && usage == Usage::National => return Err(err("BLANK WHEN ZERO on a USAGE NATIONAL item is not supported yet".into())),
719        _ if e.blank_when_zero => return Err(err("BLANK WHEN ZERO needs a numeric or numeric-edited item of USAGE DISPLAY or NATIONAL".into())),
720        _ => pic,
721    };
722    let k = match (pic.category, usage) {
723        (Category::NumericEdited, Usage::Display) => {
724            edits.push(pic.edit.clone().unwrap_or_default());
725            Kind::NumericEdited { edit: edits.len() as u32 - 1, digits: pic.digits, scale: pic.scale, blank_when_zero: e.blank_when_zero }
726        }
727        (Category::AlphanumericEdited, Usage::Display) => {
728            edits.push(pic.edit.clone().unwrap_or_default());
729            Kind::AlnumEdited { edit: edits.len() as u32 - 1 }
730        }
731        (Category::Numeric, Usage::Display) => Kind::Zoned { digits: pic.digits, scale: pic.scale, signed: pic.signed, sign: sign.filter(|_| pic.signed) },
732        (Category::Numeric, Usage::Packed) => Kind::Packed { digits: pic.digits, scale: pic.scale, signed: pic.signed },
733        (Category::Numeric, Usage::Binary | Usage::NativeBinary) if pic.digits <= 18 => {
734            Kind::Binary { digits: pic.digits, scale: pic.scale, signed: pic.signed, native: usage == Usage::NativeBinary }
735        }
736        (Category::Numeric, Usage::Binary | Usage::NativeBinary) => return Err(err("a binary item holds at most 18 digits".into())),
737        (Category::Alphanumeric, Usage::Display) => Kind::Alnum { justified: e.justified },
738        (Category::Dbcs | Category::National, Usage::Dbcs) => {
739            if pic.edit.is_some() && e.justified {
740                return Err(err("JUSTIFIED cannot be given for a DBCS item whose PICTURE has B".into()));
741            }
742            let edit = pic.edit.clone().map(|syms| {
743                edits.push(syms);
744                edits.len() as u32 - 1
745            });
746            Kind::Dbcs { justified: e.justified, edit }
747        }
748        (Category::Dbcs, _) => return Err(err("a PICTURE with G needs USAGE DISPLAY-1 (Language Reference SC27-8713-03, p. 214)".into())),
749        (Category::National, Usage::Display | Usage::National) if pic.edit.is_some() => return Err(err("a national-edited PICTURE is not supported yet".into())),
750        (Category::National, Usage::Display | Usage::National) => Kind::National,
751        (category, usage) => return Err(err(format!("a {category:?} PICTURE with USAGE {usage:?} is not supported yet"))),
752    };
753    if e.sign.is_some() && matches!(k, Kind::Zoned { signed: false, .. }) {
754        return Err(err("a SIGN clause needs an S in the PICTURE".into()));
755    }
756    Ok(k)
757}
758
759fn elementary_size(item: &Item, e_size: Option<u32>) -> u32 {
760    match item.kind {
761        Kind::Group => 0,
762        Kind::Alnum { .. } | Kind::NumericEdited { .. } | Kind::AlnumEdited { .. } => e_size.unwrap_or(0),
763        Kind::National | Kind::Dbcs { .. } => 2 * e_size.unwrap_or(0),
764        Kind::Zoned { digits, sign, .. } => digits + sign.is_some_and(|s| s.separate) as u32,
765        Kind::Packed { digits, .. } => digits / 2 + 1,
766        Kind::Binary { digits, .. } => match digits {
767            0..=4 => 2,
768            5..=9 => 4,
769            _ => 8,
770        },
771        Kind::Float(p) => p.bytes() as u32,
772        Kind::Pointer | Kind::Index | Kind::ObjectReference | Kind::ProgramPointer => 4,
773    }
774}
775
776/// Sizes the item and its descendants; children's offsets are relative to their parent here.
777/// `base` is where the item starts in its record, the 01 level on a doubleword, which is what a
778/// SYNCHRONIZED item's boundary is reckoned from (Language Reference SC27-8713-03, pp. 233-235).
779fn measure(items: &mut [Item], aligns: &[u32], index: usize, base: u32) -> Result<(), Error> {
780    if items[index].kind != Kind::Group {
781        return Ok(());
782    }
783    let children = items[index].children.clone();
784    let (mut cursor, mut extent) = (0u32, 0u32);
785    let mut placed: Vec<(Option<String>, u32)> = Vec::new();
786    let mut previous: Option<usize> = None;
787    for c in children {
788        let redefined = match items[c].redefines.clone() {
789            Some(target) => Some(placed.iter().rev().find(|(n, _)| n.as_deref() == Some(target.as_str())).map(|&(_, o)| o).ok_or_else(|| {
790                Error::at(items[c].pos, format!("REDEFINES {target}: no earlier item of that name at this level"))
791            })?),
792            None => None,
793        };
794        let start = redefined.unwrap_or(cursor);
795        let m = first_alignment(items, aligns, c);
796        let slack = (m - (base + start) % m) % m;
797        if slack > 0 && redefined.is_some() {
798            return Err(Error::at(items[c].pos, format!("a SYNCHRONIZED item at the start of a REDEFINES would need {slack} slack bytes: the redefined item must be on a {m}-byte boundary")));
799        }
800        if slack > 0 {
801            give_slack(items, previous, cursor, slack);
802        }
803        let offset = start + slack;
804        measure(items, aligns, c, base + offset)?;
805        if items[c].table {
806            let m = widest_alignment(items, aligns, c);
807            items[c].size = items[c].size.div_ceil(m) * m;
808        }
809        let too_large = || Error::at(items[c].pos, format!("an item larger than the interpreter's {MAX_STORAGE} bytes"));
810        let span = items[c].size.checked_mul(items[c].occurs).filter(|&s| s <= MAX_STORAGE).ok_or_else(too_large)?;
811        if redefined.is_none() {
812            cursor = offset.checked_add(span).filter(|&s| s <= MAX_STORAGE).ok_or_else(too_large)?;
813        }
814        extent = extent.max(offset + span);
815        items[c].offset = offset;
816        placed.push((items[c].name.clone(), offset));
817        previous = Some(c);
818    }
819    items[index].size = cursor.max(extent);
820    Ok(())
821}
822
823/// The boundary the first elementary item within `index` is aligned on.
824fn first_alignment(items: &[Item], aligns: &[u32], index: usize) -> u32 {
825    match items[index].children.first() {
826        Some(&c) if items[index].kind == Kind::Group => first_alignment(items, aligns, c),
827        _ => aligns[index],
828    }
829}
830
831/// The widest boundary of any elementary item within `index`, to which each occurrence of a table
832/// is padded so that every occurrence aligns as the first does.
833fn widest_alignment(items: &[Item], aligns: &[u32], index: usize) -> u32 {
834    items[index].children.iter().map(|&c| widest_alignment(items, aligns, c)).fold(aligns[index], u32::max)
835}
836
837/// Slack bytes before a SYNCHRONIZED item belong at the level of the elementary item before it
838/// (Language Reference SC27-8713-03, p. 234): so they lengthen the group sibling that ends where
839/// they start, and that group's last group, down to the elementary item's own group. A table or
840/// a redefinition keeps its length and leaves them to the group it is in.
841fn give_slack(items: &mut [Item], previous: Option<usize>, cursor: u32, slack: u32) {
842    let Some(mut g) = previous else { return };
843    let mut end = cursor;
844    while items[g].kind == Kind::Group && !items[g].table && items[g].redefines.is_none() && items[g].offset + items[g].size == end {
845        end = items[g].size;
846        items[g].size += slack;
847        match items[g].children.last() {
848            Some(&c) => g = c,
849            None => return,
850        }
851    }
852}
853
854fn place(items: &mut [Item], index: usize, offset: u32, mut dims: Vec<(u32, u32)>) {
855    items[index].offset = offset;
856    if items[index].table {
857        dims.push((items[index].size, items[index].occurs));
858    }
859    items[index].dims = dims.clone();
860    for c in items[index].children.clone() {
861        let relative = items[c].offset;
862        place(items, c, offset + relative, dims.clone());
863    }
864}
865
866impl Item {
867    /// The index a SEARCH of this table steps: VARYING's index-name when it is one of the table's
868    /// own, else the table's first index-name, else VARYING's item (Language Reference
869    /// SC27-8713-03, p. 437).
870    pub fn search_index(&self, varying: Option<&Ref>, pos: Pos) -> Option<Ref> {
871        match (varying.filter(|v| self.index_names.contains(&v.name)), self.index_names.first()) {
872            (Some(own), _) => Some(own.clone()),
873            (None, Some(name)) => Some(Ref { name: name.clone(), qualifiers: Vec::new(), subscripts: Vec::new(), refmod: None, pos }),
874            (None, None) => varying.cloned(),
875        }
876    }
877}
878
879impl Layout {
880    /// An elementary item's category as INITIALIZE's phrases name it, a floating-point item's as
881    /// NUMERIC (assumption [`numeric::assumptions::INITIALIZE_FLOAT_NUMERIC`]); None for a group
882    /// and for a pointer, index or object reference.
883    pub fn category(&self, i: usize) -> Option<syntax::ast::DataCategory> {
884        use syntax::ast::DataCategory;
885        let item = &self.items[i];
886        Some(match item.kind {
887            Kind::Alnum { .. } if item.alphabetic => DataCategory::Alphabetic,
888            Kind::Alnum { .. } => DataCategory::Alphanumeric,
889            Kind::AlnumEdited { .. } => DataCategory::AlphanumericEdited,
890            Kind::National => DataCategory::National,
891            Kind::Dbcs { .. } => DataCategory::Dbcs,
892            Kind::NumericEdited { .. } => DataCategory::NumericEdited,
893            Kind::Zoned { .. } | Kind::Packed { .. } | Kind::Binary { .. } | Kind::Float(_) => DataCategory::Numeric,
894            Kind::Group | Kind::Pointer | Kind::Index | Kind::ObjectReference | Kind::ProgramPointer => return None,
895        })
896    }
897
898    /// The category of the elementary item reference modification makes of `item` of `kind`, or of
899    /// a special register of `kind` when there is no item: national when `kind` is, alphabetic for
900    /// an alphabetic item, and alphanumeric otherwise (Language Reference SC27-8713-03, p. 76;
901    /// assumption [`numeric::assumptions::INITIALIZE_REFERENCE_MODIFIED`]).
902    pub fn refmod_category(&self, item: Option<usize>, kind: Kind) -> syntax::ast::DataCategory {
903        use syntax::ast::DataCategory;
904        match item.and_then(|i| self.category(i)) {
905            Some(DataCategory::Alphabetic) => DataCategory::Alphabetic,
906            _ if kind == Kind::National => DataCategory::National,
907            _ => DataCategory::Alphanumeric,
908        }
909    }
910
911    /// LENGTH OF a table element written without subscripts gives one occurrence's length (Language
912    /// Reference SC27-8713-03, p. 23): the reference with each subscript 1.
913    pub fn length_of_ref<'r>(&self, r: &'r Ref) -> std::borrow::Cow<'r, Ref> {
914        use syntax::ast::{Expr, Operand};
915        match self.resolve(&r.name, &r.qualifiers, r.pos) {
916            Ok(Resolved::Item(i)) if r.subscripts.is_empty() && !self.items[i].dims.is_empty() => {
917                let one = Expr::Operand(Operand::Literal(Literal::Number("1".into())));
918                std::borrow::Cow::Owned(Ref { subscripts: vec![one; self.items[i].dims.len()], ..r.clone() })
919            }
920            _ => std::borrow::Cow::Borrowed(r),
921        }
922    }
923
924    /// The elementary items INITIALIZE of item `i` may move to, each occurrence with its offset from
925    /// `i`'s start (Language Reference SC27-8713-03, p. 352, rules 1a and 1b): none under a
926    /// REDEFINES, no FILLER unless `filler`, and no index, object reference or program pointer.
927    pub fn initialize_receivers(&self, i: usize, filler: bool) -> Vec<(usize, u32)> {
928        let mut out = Vec::new();
929        self.receivers_under(i, 0, filler, &mut out);
930        out
931    }
932
933    fn receivers_under(&self, i: usize, offset: u32, filler: bool, out: &mut Vec<(usize, u32)>) {
934        let item = &self.items[i];
935        match item.kind {
936            Kind::Index | Kind::ObjectReference | Kind::ProgramPointer => {}
937            Kind::Group => {
938                for &c in &item.children {
939                    let child = &self.items[c];
940                    if child.redefines.is_some() || child.name.is_none() && child.kind != Kind::Group && !filler {
941                        continue;
942                    }
943                    for k in 0..child.occurs {
944                        self.receivers_under(c, offset + (child.offset - item.offset) + k * child.size, filler, out);
945                    }
946                }
947            }
948            _ => out.push((i, offset)),
949        }
950    }
951
952    /// Names the files, so that a file-name qualifies its records and its LINAGE-COUNTER.
953    pub fn name_files(&mut self, files: &[FileDecl], linage_counters: Vec<Option<usize>>) {
954        self.file_names = files.iter().map(|f| f.name.clone()).collect();
955        self.linage_counters = linage_counters;
956    }
957
958    /// How many programs out the program declaring a name is: 0 for this program's own.
959    fn depth(&self, r: Resolved) -> u8 {
960        let mut i = match r {
961            Resolved::Item(i) => i,
962            Resolved::Condition(c) => self.conditions[c].item,
963        };
964        while let Some(p) = self.items[i].parent {
965            i = p;
966        }
967        self.items[i].linkage.and_then(|l| self.depths.get(l as usize)).copied().unwrap_or_default()
968    }
969
970    /// Whether LINKAGE record `ordinal` is one an argument or SET ADDRESS OF addresses.
971    pub fn is_argument(&self, ordinal: usize) -> bool {
972        self.bindings.get(ordinal).is_none_or(|b| *b == Binding::Argument)
973    }
974
975    /// The file whose name qualifies item `i`: the file of its record, or the one it is the
976    /// LINAGE-COUNTER of.
977    fn file_qualifying(&self, mut i: usize) -> Option<&str> {
978        while let Some(p) = self.items[i].parent {
979            i = p;
980        }
981        let k = self.items[i].file.map(usize::from).or_else(|| self.linage_counters.iter().position(|&c| c == Some(i)))?;
982        self.file_names.get(k).map(String::as_str)
983    }
984
985    /// Whether `qualifiers` are the complete set of a candidate: every name of its hierarchy, the
986    /// file-name of its FD or SD allowed last but not needed (assumption
987    /// [`numeric::assumptions::COMPLETE_SET_OF_QUALIFIERS`]).
988    fn complete(&self, candidate: Resolved, qualifiers: &[String]) -> bool {
989        let (start, own) = match candidate {
990            Resolved::Item(i) => (self.items[i].parent, i),
991            Resolved::Condition(c) => (Some(self.conditions[c].item), self.conditions[c].item),
992        };
993        let given = || qualifiers.iter().map(String::as_str);
994        given().eq(names_from(&self.items, start)) || given().eq(names_from(&self.items, start).chain(self.file_qualifying(own)))
995    }
996
997    /// A data item, condition-name or LINAGE-COUNTER named with its qualifiers, the last of which
998    /// may be the file-name of an FD or SD (Language Reference SC27-8713-03, pp. 69-70). Under
999    /// QUALIFY(EXTEND) a reference the standard's rules find ambiguous names the one candidate it
1000    /// gives a complete set of qualifiers, if only one (Programming Guide SC27-8714-03, p. 400;
1001    /// Language Reference SC27-8713-03, pp. 67-68).
1002    pub fn resolve(&self, name: &str, qualifiers: &[String], pos: Pos) -> Result<Resolved, Error> {
1003        let within = |mut at: Option<usize>, own: usize| {
1004            let mut wanted = qualifiers.iter();
1005            let mut next = wanted.next();
1006            while let (Some(q), Some(i)) = (next, at) {
1007                if self.items[i].name.as_deref() == Some(q.as_str()) {
1008                    next = wanted.next();
1009                }
1010                at = self.items[i].parent;
1011            }
1012            match next {
1013                None => true,
1014                Some(file) => wanted.next().is_none() && self.file_qualifying(own) == Some(file.as_str()),
1015            }
1016        };
1017        let mut found: Vec<Resolved> = self
1018            .items
1019            .iter()
1020            .enumerate()
1021            .filter(|(i, it)| it.name.as_deref() == Some(name) && within(it.parent, *i))
1022            .map(|(i, _)| Resolved::Item(i))
1023            .collect();
1024        found.extend(
1025            self.conditions.iter().enumerate().filter(|(_, c)| c.name == name && within(Some(c.item), c.item)).map(|(i, _)| Resolved::Condition(i)),
1026        );
1027        if found.len() > 1 {
1028            let nearest = found.iter().map(|&r| self.depth(r)).min().unwrap_or_default();
1029            found.retain(|&r| self.depth(r) == nearest);
1030        }
1031        if found.len() > 1 && self.qualify == Qualify::Extend {
1032            let complete: Vec<Resolved> = found.iter().copied().filter(|&r| self.complete(r, qualifiers)).collect();
1033            if let [one] = complete.as_slice() {
1034                return Ok(*one);
1035            }
1036        }
1037        match found.as_slice() {
1038            [one] => Ok(*one),
1039            [] => Err(Error::at(pos, format!("{name} is not defined"))),
1040            _ => Err(Error::at(pos, format!("{name} is ambiguous; qualify it with OF or IN"))),
1041        }
1042    }
1043}
1044
1045/// The file whose record area each file uses: its own, or the first file of its SAME RECORD AREA
1046/// clause. SAME AREA shares the record area of the VSAM (indexed and relative) files it names and
1047/// is documentation for the rest: SAME_AREA_VSAM in numeric::assumptions.
1048pub fn record_area_owners(files: &[FileDecl], environment: &Environment) -> Result<Vec<usize>, Error> {
1049    let mut owner: Vec<usize> = (0..files.len()).collect();
1050    let root = |owner: &[usize], mut k: usize| {
1051        while owner[k] != k {
1052            k = owner[k];
1053        }
1054        k
1055    };
1056    let clauses = environment.same_record_areas.iter().map(|c| ("SAME RECORD AREA", c)).chain(environment.same_areas.iter().map(|c| ("SAME AREA", c)));
1057    for (clause, names) in clauses {
1058        let mut members = Vec::new();
1059        for name in names {
1060            let k = files.iter().position(|f| f.name == *name).ok_or_else(|| Error::at(Pos::default(), format!("{clause} names {name}, which is not a file")))?;
1061            if clause == "SAME RECORD AREA" || matches!(files[k].organization, Organization::Indexed | Organization::Relative) {
1062                members.push(k);
1063            }
1064        }
1065        for pair in members.windows(2) {
1066            let (a, b) = (root(&owner, pair[0]), root(&owner, pair[1]));
1067            owner[a.max(b)] = a.min(b);
1068        }
1069    }
1070    Ok((0..files.len()).map(|k| root(&owner, k)).collect())
1071}