Skip to main content

ironwork_exec/
machine.rs

1//! The interpreter: one activation of one program, over the run unit's memory in EBCDIC. A
2//! reference can reach anywhere in that memory, as a program compiled without SSRANGE can on
3//! z/OS, but never outside it.
4
5pub use rt::abend::{Abend, Ending};
6use crate::abend::{AbendCode, Signal};
7use crate::layout::{Kind, Layout, Resolved};
8use rt::storage::{Loc, Val};
9pub(crate) use rt::storage::literal_fixed;
10use crate::unit::{ADDRESS_BASE, Event, LoadError, OS_COMMAND_ROUTINES, RETURN_CODE, RunUnit};
11use crate::Compiled;
12use numeric::precision::{self, Fixed, Places};
13use numeric::{Options, Trunc};
14use rt::fixed::{align, places_of};
15use rt::arith;
16use rt::callee::{self, Bindings, By, Callee};
17use rt::display::utf16_text;
18use rt::host::Host;
19use rt::lir::{ByteClass, CallArg, ConvertTable, Converting, SignTest, StringSource, TrimSide};
20use rt::loc;
21use rt::store;
22use rt::text::UnstringField;
23use std::cmp::Ordering;
24use std::collections::HashMap;
25use syntax::Pos;
26use syntax::ast::*;
27use zarch::ebcdic::{self, CodePage, Collation};
28use zarch::hfp::{Hfp, Precision};
29
30mod cics;
31pub(crate) mod cics_bind;
32mod declaratives;
33mod facts;
34mod file_io;
35mod function;
36mod intrinsic;
37use intrinsic::Within;
38mod json;
39mod le_services;
40mod oo;
41mod parmcheck;
42mod perform;
43mod report;
44mod scope;
45mod sort;
46pub(crate) mod sql;
47mod xml;
48
49type R<T> = Result<T, Abend>;
50
51enum Flow {
52    Next,
53    End(Ending),
54    GoTo(usize),
55    ExitParagraph,
56    ExitSection,
57    ExitPerform,
58    ExitPerformCycle,
59    NextSentence,
60    /// Returning, at this paragraph and statement, after a PERFORM whose range control left.
61    Resume(usize, usize),
62    /// Returning to the active PERFORM with this frame number.
63    Return(u64),
64}
65
66pub struct Machine<'p, 'u, 'w> {
67    compiled: &'p Compiled,
68    program: &'p Program,
69    layout: &'p Layout,
70    options: Options,
71    ssrange: bool,
72    page: &'static CodePage,
73    collating: &'p crate::collating::Sequence,
74    when_compiled: rt::lir::CompileTime,
75    resolved: HashMap<(String, Vec<String>), Resolved>,
76    /// This program's place in the run unit, and where its storage starts.
77    me: usize,
78    base: usize,
79    /// Where each LINKAGE record is, once an argument or SET ADDRESS OF has given it an address.
80    linkage: Vec<Option<usize>>,
81    /// Where this activation's LOCAL-STORAGE starts.
82    local_base: usize,
83    /// The first program of the run unit, where EXIT PROGRAM does nothing.
84    main: bool,
85    /// The logical level's HANDLE CONDITION, IGNORE CONDITION and HANDLE ABEND, which the
86    /// activation running holds (C234).
87    cics_handlers: cics::Handlers,
88    /// This activation's number in the CICS task, which owns the HANDLE labels it sets.
89    serial: u64,
90    /// The run unit's first program, which the run unit holds no handle to, for a CALL, LINK or
91    /// XCTL of it from this activation (C148, C127).
92    first: Option<&'p Compiled>,
93    report_writer: &'p crate::report::Writer,
94    /// Each file's printer control character, when it is a print file.
95    carriage: &'p [Option<crate::printer::Carriage>],
96    /// The method this activation runs, if it is one: its class and SELF.
97    oo: oo::Frame,
98    /// The SORT or MERGE whose input or output procedure is running.
99    sort: Option<sort::Active>,
100    /// The priority-number of the segment the running paragraph is in.
101    segment: u8,
102    declaratives: &'p crate::declaratives::Table,
103    uses: declaratives::State,
104    returns: perform::Returns,
105    /// XML-TEXT and the other XML registers of the event being processed.
106    xml: xml::Registers,
107    /// The programs containing this one, innermost first, as they are running.
108    containers: Vec<scope::Frame<'p>>,
109    /// The user-defined functions the program may invoke.
110    functions: &'p [compile::function::Udf],
111    unit: &'u mut RunUnit<'w>,
112}
113
114enum Step {
115    Again,
116    Leave,
117    Out(Flow),
118}
119
120impl<'p, 'u, 'w> Machine<'p, 'u, 'w> {
121    /// An activation of loaded program `me`. Its storage is initialized on its first activation,
122    /// after a CANCEL, and on every activation of an INITIAL program.
123    pub fn activation(compiled: &'p Compiled, me: usize, unit: &'u mut RunUnit<'w>, main: bool) -> R<Self> {
124        Self::activation_within(compiled, me, unit, main, Vec::new())
125    }
126
127    /// An activation of a contained program, called with the programs containing it running.
128    fn activation_within(compiled: &'p Compiled, me: usize, unit: &'u mut RunUnit<'w>, main: bool, containers: Vec<scope::Frame<'p>>) -> R<Self> {
129        let (base, fresh) = unit.activate(me, compiled.program.initial);
130        let mut m = Self::over(compiled, me, base, unit, main);
131        m.containers = containers;
132        m.bind_shared()?;
133        m.initial_values(fresh)
134    }
135
136    /// An activation with no EXTERNAL or GLOBAL record bound, which VALUE clauses never reach:
137    /// the storage lowering keeps as a program's initial image.
138    pub fn unbound(compiled: &'p Compiled, me: usize, unit: &'u mut RunUnit<'w>) -> R<Self> {
139        let (base, fresh) = unit.activate(me, compiled.program.initial);
140        Self::over(compiled, me, base, unit, true).initial_values(fresh)
141    }
142
143    fn initial_values(mut self, fresh: bool) -> R<Self> {
144        let (local, size) = (self.layout.local_size as usize, self.layout.size as usize);
145        if local > 0 {
146            self.local_base = self.unit.push_temporary(&vec![0; local]);
147            self.initialize_values(true)?;
148            self.unit.mark_input(self.local_base, local, false);
149        }
150        if fresh {
151            self.unit.mem[self.base..self.base + size].fill(0);
152            self.initialize_values(false)?;
153            self.unit.mark_input(self.base, size, false);
154            self.unit.initialized(self.me);
155        }
156        Ok(self)
157    }
158
159    /// Program `me` over its storage at `base`, with nothing bound or initialized.
160    fn over(compiled: &'p Compiled, me: usize, base: usize, unit: &'u mut RunUnit<'w>, main: bool) -> Self {
161        let serial = unit.cics.as_mut().map_or(0, crate::cics::Task::next_activation);
162        let first = unit.programs[me].compiled.is_none().then_some(compiled);
163        Self {
164            compiled,
165            program: &compiled.program,
166            layout: &compiled.layout,
167            options: compiled.options,
168            ssrange: compiled.ssrange,
169            page: compiled.options.code_page(),
170            collating: &compiled.collating,
171            when_compiled: compiled.when_compiled,
172            resolved: HashMap::new(),
173            me,
174            base,
175            linkage: vec![None; compiled.layout.linkage_roots.len()],
176            local_base: 0,
177            main,
178            cics_handlers: cics::Handlers::default(),
179            serial,
180            first,
181            report_writer: &compiled.report_writer,
182            carriage: &compiled.carriage,
183            oo: oo::Frame::default(),
184            sort: None,
185            segment: 0,
186            declaratives: &compiled.declaratives,
187            uses: declaratives::State::default(),
188            returns: perform::Returns::new(compiled.program.paragraphs.len()),
189            xml: xml::Registers::default(),
190            containers: Vec::new(),
191            functions: &compiled.functions,
192            unit,
193        }
194    }
195
196    /// Applies VALUE clauses: to WORKING-STORAGE and file records, or to LOCAL-STORAGE.
197    fn initialize_values(&mut self, local: bool) -> R<()> {
198        let base = if local { self.local_base } else { self.base };
199        for index in 0..self.layout.items.len() {
200            let item = &self.layout.items[index];
201            let Some(value) = item.value.clone().filter(|_| item.linkage.is_none() && item.local == local) else { continue };
202            let occurrences: u32 = item.dims.iter().map(|&(_, n)| n).product::<u32>().max(1);
203            let kind = value_kind(item.kind, &value);
204            for k in 0..occurrences {
205                let offset = base + item.offset as usize + loc::occurrence_offset(&item.dims, k);
206                let loc = Loc { offset, len: item.size as usize, kind, item: index };
207                let val = self.literal_value(&value, item.pos)?;
208                self.assign(loc, val, None, item.pos)?;
209            }
210        }
211        Ok(())
212    }
213
214    pub fn run_procedure(&mut self) -> R<Ending> {
215        self.run_from(None)
216    }
217
218    /// Control reaching a paragraph of segment `priority`: an independent segment entered from
219    /// another is in its initial state, so its altered GO TOs are as written (assumption C52).
220    fn enter_segment(&mut self, priority: u8) {
221        if priority == self.segment {
222            return;
223        }
224        self.segment = priority;
225        if priority >= 50 {
226            let program = self.program;
227            for (i, target) in self.unit.programs[self.me].altered.iter_mut().enumerate() {
228                if program.paragraphs[i].priority == priority {
229                    *target = None;
230                }
231            }
232        }
233    }
234
235    /// A paragraph's statements: NEXT SENTENCE resumes after the next separator period.
236    fn run_sentences(&mut self, stmts: &'p [Stmt]) -> R<Flow> {
237        let mut i = 0;
238        while i < stmts.len() {
239            match self.exec(&stmts[i])? {
240                Flow::Next => i += 1,
241                Flow::NextSentence => i = stmts[i..].iter().position(|s| *s == Stmt::SentenceEnd).map_or(stmts.len(), |j| i + j + 1),
242                other => return Ok(other),
243            }
244        }
245        Ok(Flow::Next)
246    }
247
248    fn run_block(&mut self, stmts: &'p [Stmt]) -> R<Flow> {
249        for s in stmts {
250            match self.exec(s)? {
251                Flow::Next => {}
252                other => return Ok(other),
253            }
254        }
255        Ok(Flow::Next)
256    }
257
258    fn procedure(&self, p: &ProcName, pos: Pos) -> R<(usize, usize)> {
259        crate::procedure(self.program, p).map_err(|m| Abend::ironwork(m, pos))
260    }
261
262    /// One statement. An EXCEPTION/ERROR procedure it ran may have sent control elsewhere.
263    fn exec(&mut self, s: &'p Stmt) -> R<Flow> {
264        if !self.declaratives.triggers.is_empty()
265            && let Some(pos) = declaratives::statement_pos(s)
266        {
267            self.uses.line = pos;
268        }
269        if self.unit.statement_limit.is_some()
270            && let Some(pos) = declaratives::statement_pos(s)
271        {
272            self.unit.start_statement(pos)?;
273        }
274        if (self.unit.statements.is_some() || self.unit.taint.is_some())
275            && let Some(pos) = declaratives::statement_pos(s)
276        {
277            self.unit.statement_starts();
278            if self.unit.traces(pos.line) {
279                let file = self.event_file(pos);
280                self.unit.notify(Event::Statement { file: &file, line: pos.line });
281            }
282        }
283        match self.statement(s) {
284            Err(Abend { code: AbendCode::Signal(Signal::DeclarativeExit), .. }) => Ok(self.declarative_exit()),
285            Err(Abend { code: AbendCode::Signal(Signal::StopRun), .. }) => Ok(Flow::End(Ending::StopRun)),
286            flow => flow,
287        }
288    }
289
290    fn statement(&mut self, s: &'p Stmt) -> R<Flow> {
291        match s {
292            Stmt::Move { from, to, pos } => {
293                for r in to {
294                    let dest = self.locate_written(|m| m.locate_receiving(r))?;
295                    let (val, src) = self.move_source(from, dest, *pos)?;
296                    self.assign(dest, val, src, *pos)?;
297                }
298            }
299            Stmt::Compute { targets, expr, size_error, pos } => {
300                let computations: Vec<(Target, Expr)> = targets.iter().map(|t| (t.clone(), expr.clone())).collect();
301                return self.arithmetic(&computations, None, size_error.as_ref(), false, *pos);
302            }
303            Stmt::Arith(a) => return self.arithmetic(&a.computations, a.remainder.as_ref(), a.size_error.as_ref(), true, a.pos),
304            Stmt::Corresponding(c) => return Err(Abend::ironwork("CORRESPONDING reached the interpreter unexpanded", c.pos)),
305            Stmt::If { cond, then, otherwise, pos } => {
306                let branch = if self.condition(cond, *pos)? { then } else { otherwise };
307                return self.run_block(branch);
308            }
309            Stmt::Evaluate { subjects, whens, other, pos } => {
310                for w in whens {
311                    for alternative in &w.alternatives {
312                        if self.alternative_matches(subjects, alternative, *pos)? {
313                            return self.run_block(&w.body);
314                        }
315                    }
316                }
317                return self.run_block(other);
318            }
319            Stmt::PerformProc { from, thru, repeat, pos } => {
320                let (start, first_end) = self.procedure(from, *pos)?;
321                let end = match thru {
322                    Some(t) => self.procedure(t, *pos)?.1,
323                    None => first_end,
324                };
325                let statement = if matches!(repeat, Loop::Once) { self.after(s) } else { None };
326                return self.repeat(repeat, *pos, &mut |m: &mut Self| {
327                    m.uses.line = *pos;
328                    m.perform_range(start, end, None, statement)
329                });
330            }
331            Stmt::PerformInline { body, repeat, pos } => return self.repeat(repeat, *pos, &mut |m: &mut Self| m.run_block(body)),
332            Stmt::Display { items, no_advancing, pos } => self.display(items, *no_advancing, *pos)?,
333            Stmt::Open { files, pos } => {
334                for (mode, name) in files {
335                    self.open_file(*mode, name, *pos)?;
336                }
337            }
338            Stmt::Close { files, pos } => {
339                for (name, closing) in files {
340                    self.close_file_with(name, *closing, *pos)?;
341                }
342            }
343            Stmt::Read(r) => return self.read_stmt(r),
344            Stmt::Write { record, from, advancing, invalid, end_of_page, pos } => return self.write_stmt(record, from.as_ref(), advancing.as_ref(), invalid, end_of_page, *pos),
345            Stmt::Rewrite { record, from, invalid, pos } => return self.rewrite_stmt(record, from.as_ref(), invalid, *pos),
346            Stmt::Delete { file, invalid, pos } => return self.delete_stmt(file, invalid, *pos),
347            Stmt::Start { file, key, invalid, pos } => return self.start_stmt(file, key.as_ref(), invalid, *pos),
348            Stmt::Initialize { targets, with, pos } => {
349                let with = with.as_deref().unwrap_or(&NO_PHRASES);
350                for r in targets {
351                    let loc = self.locate_written(|m| m.locate(r))?;
352                    if loc.item != usize::MAX {
353                        self.initialize(loc.item, loc.offset, with, *pos)?;
354                        continue;
355                    }
356                    match with.initial_value(Some(DataCategory::Numeric), false) {
357                        Some(InitialValue::Replacing(by)) => {
358                            let (val, src) = self.operand_with_loc(by, *pos)?;
359                            self.assign(loc, val, src, *pos)?;
360                        }
361                        Some(_) => self.unit.write(loc.offset, &vec![0; loc.len]),
362                        None => {}
363                    }
364                }
365            }
366            Stmt::GoTo { target: Some(target), pos } => return Ok(Flow::GoTo(self.procedure(target, *pos)?.0)),
367            Stmt::GoTo { target: None, .. } | Stmt::Entry { .. } => {}
368            Stmt::GoToDepending { targets, on, pos } => {
369                let n = self.integer(&Expr::Operand(Operand::Ref(on.clone())), *pos)?;
370                if let Some(target) = usize::try_from(n).ok().and_then(|n| targets.get(n.wrapping_sub(1))) {
371                    return Ok(Flow::GoTo(self.procedure(target, *pos)?.0));
372                }
373            }
374            Stmt::Alter { pairs, pos } => {
375                for (paragraph, target) in pairs {
376                    let (at, to) = (self.procedure(paragraph, *pos)?.0, self.procedure(target, *pos)?.0);
377                    let paragraphs = self.program.paragraphs.len();
378                    let altered = &mut self.unit.programs[self.me].altered;
379                    altered.resize(paragraphs, None);
380                    altered[at] = Some(to);
381                }
382                if let Some(flow) = self.debug_alter(pairs, *pos)? {
383                    return Ok(flow);
384                }
385            }
386            Stmt::Goback { .. } => return Ok(Flow::End(Ending::Goback)),
387            Stmt::ExitProgram { .. } if self.main => {}
388            Stmt::ExitProgram { .. } => return Ok(Flow::End(Ending::Goback)),
389            Stmt::Call(c) => return self.call(c),
390            Stmt::Cancel { targets, pos } => {
391                for t in targets {
392                    let name = self.program_name(t, *pos)?;
393                    callee::cancel(self.unit, &name, *pos)?;
394                }
395            }
396            Stmt::Set { set, pos } => self.set(set, *pos)?,
397            Stmt::Accept { target, from, pos } => self.accept(target, *from, *pos)?,
398            Stmt::String(st) => return self.string_stmt(st),
399            Stmt::Unstring(u) => return self.unstring(u),
400            Stmt::Inspect(i) => self.inspect(i)?,
401            Stmt::Search(se) => return self.search(se),
402            Stmt::Sorting(s) => return self.sorting(s),
403            Stmt::NextSentence => return Ok(Flow::NextSentence),
404            Stmt::Exec(block) if block.declarative() => {}
405            Stmt::Exec(block) if block.kind == ExecKind::Cics => return self.cics(block),
406            Stmt::Exec(block) if block.kind == ExecKind::Sql => return self.sql(block),
407            Stmt::Report(r) => return self.report_statement(r),
408            Stmt::Exec(block) => {
409                let kind = match block.kind {
410                    ExecKind::Sql => "SQL",
411                    ExecKind::Cics => "CICS",
412                    ExecKind::Dli => "DLI",
413                    ExecKind::Other => "",
414                };
415                return Err(Abend {
416                    code: AbendCode::Exec,
417                    message: format!("EXEC {kind} {} was reached: ironwork for COBOL checks EXEC statements but does not run them yet", block.command),
418                    pos: block.pos,
419                    file: None,
420                });
421            }
422            Stmt::Invoke(i) => return self.invoke(i),
423            Stmt::JsonGenerate(g) => return self.json_generate(g),
424            Stmt::XmlParse(x) => return self.xml_parse(x),
425            Stmt::XmlGenerate(x) => return self.xml_generate(x),
426            Stmt::JsonParse(j) => return self.json_parse(j),
427            Stmt::ExitMethod { .. } => return Ok(Flow::End(Ending::Goback)),
428            Stmt::SentenceEnd => {}
429            Stmt::StopRun { .. } => return Ok(Flow::End(Ending::StopRun)),
430            Stmt::Exit { kind: ExitKind::Paragraph, .. } => return Ok(Flow::ExitParagraph),
431            Stmt::Exit { kind: ExitKind::Section, .. } => return Ok(Flow::ExitSection),
432            Stmt::Exit { kind: ExitKind::Perform, .. } => return Ok(Flow::ExitPerform),
433            Stmt::Exit { kind: ExitKind::PerformCycle, .. } => return Ok(Flow::ExitPerformCycle),
434            Stmt::Continue | Stmt::Exit { kind: ExitKind::Plain, .. } => {}
435        }
436        Ok(Flow::Next)
437    }
438
439    fn alternative_matches(&mut self, subjects: &[Subject], objects: &[Object], pos: Pos) -> R<bool> {
440        for (subject, object) in subjects.iter().zip(objects) {
441            let hit = match (subject, object) {
442                (_, Object::Any) => true,
443                (Subject::Bool(b), Object::Bool(o)) => b == o,
444                (Subject::Bool(b), Object::Cond(c)) => self.condition(c, pos)? == *b,
445                (Subject::Cond(c), Object::Bool(o)) => self.condition(c, pos)? == *o,
446                (Subject::Cond(c), Object::Cond(d)) => self.condition(c, pos)? == self.condition(d, pos)?,
447                (Subject::Expr(e), Object::Value { not, from, thru }) => {
448                    let inside = match thru {
449                        None => self.compare(e, from, pos)? == Ordering::Equal,
450                        Some(t) => self.compare(e, from, pos)? != Ordering::Less && self.compare(e, t, pos)? != Ordering::Greater,
451                    };
452                    inside != *not
453                }
454                _ => return Err(Abend::ironwork("a WHEN object of a different kind from its subject", pos)),
455            };
456            if !hit {
457                return Ok(false);
458            }
459        }
460        Ok(true)
461    }
462
463    /// Runs a PERFORM's body as its phrase says. EXIT PERFORM leaves the loop; EXIT PERFORM CYCLE
464    /// ends one iteration.
465    fn repeat(&mut self, repeat: &'p Loop, pos: Pos, body: &mut dyn FnMut(&mut Self) -> R<Flow>) -> R<Flow> {
466        self.unit.enter(pos)?;
467        let flow = self.repeat_nested(repeat, pos, body);
468        self.unit.depth -= 1;
469        flow
470    }
471
472    fn repeat_nested(&mut self, repeat: &'p Loop, pos: Pos, body: &mut dyn FnMut(&mut Self) -> R<Flow>) -> R<Flow> {
473        let mut run = |m: &mut Self| -> R<Step> {
474            Ok(match body(m)? {
475                Flow::Next | Flow::ExitPerformCycle => Step::Again,
476                Flow::ExitPerform => Step::Leave,
477                other => Step::Out(other),
478            })
479        };
480        match repeat {
481            Loop::Once => match run(self)? {
482                Step::Out(f) => return Ok(f),
483                Step::Again | Step::Leave => {}
484            },
485            Loop::Times(count) => {
486                for _ in 0..self.integer(count, pos)?.max(0) {
487                    match run(self)? {
488                        Step::Again => {}
489                        Step::Leave => break,
490                        Step::Out(f) => return Ok(f),
491                    }
492                }
493            }
494            Loop::Until { cond, test_after } => loop {
495                if !test_after && self.condition(cond, pos)? {
496                    break;
497                }
498                match run(self)? {
499                    Step::Again => {}
500                    Step::Leave => break,
501                    Step::Out(f) => return Ok(f),
502                }
503                if *test_after && self.condition(cond, pos)? {
504                    break;
505                }
506            },
507            Loop::Varying { varying, after, test_after } => {
508                let levels: Vec<&'p Varying> = std::iter::once(&**varying).chain(after).collect();
509                let count = if *test_after { 1 } else { levels.len() };
510                for v in &levels[..count] {
511                    self.vary_from(v, pos)?;
512                }
513                if let Step::Out(f) = self.vary(&levels, *test_after, pos, &mut run)? {
514                    return Ok(f);
515                }
516            }
517        }
518        Ok(Flow::Next)
519    }
520
521    /// The loop of `levels[0]`, each pass running the loops of the levels inside it, in the order of
522    /// the Language Reference's figures for TEST BEFORE and TEST AFTER (SC27-8713-03, pp. 425-428):
523    /// an outer variable is augmented before the one inside it is set to its FROM value again.
524    fn vary(&mut self, levels: &[&'p Varying], test_after: bool, pos: Pos, run: &mut dyn FnMut(&mut Self) -> R<Step>) -> R<Step> {
525        let Some((level, inner)) = levels.split_first() else { return run(self) };
526        loop {
527            if !test_after && self.condition(&level.until, pos)? {
528                return Ok(Step::Again);
529            }
530            if test_after && let Some(next) = inner.first() {
531                self.vary_from(next, pos)?;
532            }
533            match self.vary(inner, test_after, pos, run)? {
534                Step::Again => {}
535                other => return Ok(other),
536            }
537            if test_after && self.condition(&level.until, pos)? {
538                return Ok(Step::Again);
539            }
540            self.vary_by(level, pos)?;
541            if !test_after && let Some(next) = inner.first() {
542                self.vary_from(next, pos)?;
543            }
544        }
545    }
546
547    fn vary_from(&mut self, v: &Varying, pos: Pos) -> R<()> {
548        let var = self.locate_written(|m| m.locate(&v.var))?;
549        let start = self.expr_value(&v.from, pos)?;
550        self.assign(var, start, None, pos)
551    }
552
553    fn vary_by(&mut self, v: &Varying, pos: Pos) -> R<()> {
554        let var = self.locate(&v.var)?;
555        let step = Expr::Bin(Box::new(Expr::Operand(Operand::Ref(v.var.clone()))), BinOp::Add, Box::new(v.by.clone()));
556        let dmax = var.kind.digits_scale().map_or(0, |(_, s)| s).max(self.dmax(&step)?);
557        let next = self.eval_fixed(&step, dmax, pos)?;
558        store::store_fixed(&self.facts(), self.unit, var, &next, false, pos)
559    }
560
561    fn resolve(&mut self, r: &Ref) -> R<Resolved> {
562        let key = (r.name.clone(), r.qualifiers.clone());
563        if let Some(&hit) = self.resolved.get(&key) {
564            return Ok(hit);
565        }
566        let found = self.layout.resolve(&r.name, &r.qualifiers, r.pos).map_err(|e| Abend::ironwork(e.message, r.pos))?;
567        self.resolved.insert(key, found);
568        Ok(found)
569    }
570
571    fn locate(&mut self, r: &Ref) -> R<Loc> {
572        self.locate_as(r, false)
573    }
574
575    /// A receiver the statement only writes, located as `locate` would: under taint its old bytes
576    /// are not read (`Taint::writing`).
577    fn locate_written(&mut self, locate: impl FnOnce(&mut Self) -> R<Loc>) -> R<Loc> {
578        let was = self.unit.writing(true);
579        let loc = locate(self);
580        self.unit.writing(was);
581        loc
582    }
583
584    /// The receiving item of MOVE, ACCEPT, STRING, UNSTRING, READ and RETURN INTO, and WRITE,
585    /// REWRITE and RELEASE FROM: a group holding the object of its own OCCURS DEPENDING ON is its
586    /// maximum length (Language Reference SC27-8713-03, pp. 205-206).
587    fn locate_receiving(&mut self, r: &Ref) -> R<Loc> {
588        self.locate_as(r, true)
589    }
590
591    fn locate_as(&mut self, r: &Ref, receiving: bool) -> R<Loc> {
592        if let Some(loc) = self.oo_register(r)?.or(self.xml_register(r)?) {
593            self.unit.taint_read(loc);
594            return Ok(loc);
595        }
596        if r.name == "RETURN-CODE" && r.qualifiers.is_empty() && !self.layout.items.iter().any(|i| i.name.as_deref() == Some("RETURN-CODE")) {
597            let loc = Loc { offset: RETURN_CODE, len: 2, kind: Kind::Binary { digits: 4, scale: 0, signed: true, native: false }, item: usize::MAX };
598            self.unit.taint_read(loc);
599            return Ok(loc);
600        }
601        let Resolved::Item(index) = self.resolve(r)? else {
602            return Err(Abend::ironwork(format!("{} is a condition-name, not a data item", r.name), r.pos));
603        };
604        self.locate_item(index, r, receiving)
605    }
606
607    /// Item `index` with `r`'s subscripts and reference modification, `r` naming it in messages:
608    /// how a condition-name reaches its conditional variable, which may be FILLER or share its
609    /// name with other items.
610    fn locate_item(&mut self, index: usize, r: &Ref, receiving: bool) -> R<Loc> {
611        let layout = self.layout;
612        let item = &layout.items[index];
613        if r.subscripts.len() != item.dims.len() {
614            return Err(Abend::ironwork(format!("{} takes {} subscripts, not {}", r.name, item.dims.len(), r.subscripts.len()), r.pos));
615        }
616        let base = match item.linkage {
617            Some(l) => loc::linkage_base(self.linkage[l as usize], &r.name, r.pos)?,
618            None if item.local => self.local_base,
619            None => self.base,
620        };
621        let mut offset = (base + item.offset as usize) as i64;
622        for &t in &item.moved_by {
623            offset -= self.unused(t, r.pos)?;
624        }
625        for (&(stride, count), sub) in item.dims.iter().zip(&r.subscripts) {
626            let s = self.integer(sub, r.pos)?;
627            offset += loc::subscript(s, stride, self.ssrange.then_some(count), &r.name, r.pos)?;
628        }
629        let (mut len, mut kind) = (item.size as i64, item.kind);
630        if !item.odo.is_empty() && !(receiving && r.refmod.is_none() && !item.followed && self.objects_within(&item.odo, index)?) {
631            for &t in &item.odo {
632                len -= self.unused(t, r.pos)?;
633            }
634        }
635        if let Some(rm) = &r.refmod {
636            let start = self.integer(&rm.start, r.pos)?;
637            let length = match &rm.length {
638                Some(l) => Some(self.integer(l, r.pos)?),
639                None => None,
640            };
641            // A national item's character positions are two bytes, and a part of it is national.
642            let unit = if kind == Kind::National { 2 } else { 1 };
643            let (from, length) = loc::refmod(len / unit, start, length, self.ssrange, &r.name, r.pos)?;
644            offset += from * unit;
645            len = length * unit;
646            if kind != Kind::National {
647                kind = Kind::Alnum { justified: false };
648            }
649        }
650        let (offset, len) = loc::within(offset, len, self.unit.mem.len(), &r.name, r.pos)?;
651        let loc = Loc { offset, len, kind, item: index };
652        self.unit.taint_read(loc);
653        Ok(loc)
654    }
655
656    /// Whether the objects of these tables' OCCURS DEPENDING ON all lie within item `group`.
657    fn objects_within(&mut self, tables: &[usize], group: usize) -> R<bool> {
658        for &t in tables {
659            if !self.object_within(t, group)? {
660                return Ok(false);
661            }
662        }
663        Ok(true)
664    }
665
666    /// The bytes of OCCURS DEPENDING ON table `t` past its current count of occurrences.
667    fn unused(&mut self, t: usize, pos: Pos) -> R<i64> {
668        let table = &self.layout.items[t];
669        let (max, element) = (table.occurs, table.size);
670        let current = self.occurrences(t, pos)?;
671        Ok(loc::unused(max, current, element))
672    }
673
674    /// The bytes the OCCURS DEPENDING ON tables ahead of item `member` in its record, and not ahead
675    /// of the group `holder` it is in, move it back from where the group's layout puts it.
676    fn moved_within(&mut self, member: usize, holder: usize, pos: Pos) -> R<usize> {
677        let layout = self.layout;
678        let mut moved = 0;
679        for &t in layout.items[member].moved_by.iter().filter(|t| !layout.items[holder].moved_by.contains(t)) {
680            moved += self.unused(t, pos)? as usize;
681        }
682        Ok(moved)
683    }
684
685    /// Whether the object of table `t`'s OCCURS DEPENDING ON lies within item `group`.
686    fn object_within(&mut self, t: usize, group: usize) -> R<bool> {
687        let layout = self.layout;
688        let Some(object) = &layout.items[t].depending_on else { return Ok(false) };
689        let Resolved::Item(mut at) = self.resolve(object)? else { return Ok(false) };
690        loop {
691            if at == group {
692                return Ok(true);
693            }
694            match layout.items[at].parent {
695                Some(p) => at = p,
696                None => return Ok(false),
697            }
698        }
699    }
700
701    /// The current count of an OCCURS DEPENDING ON table, kept within its declared maximum so that
702    /// a bad count never reaches past the table's storage.
703    fn occurrences(&mut self, table: usize, pos: Pos) -> R<u32> {
704        let layout = self.layout;
705        let item = &layout.items[table];
706        let Some(object) = &item.depending_on else { return Ok(item.occurs) };
707        let count = self.integer(&Expr::Operand(Operand::Ref(object.clone())), pos)?;
708        loc::occurrences(count, item.occurs, self.ssrange, &object.name, pos)
709    }
710
711    fn integer(&mut self, e: &Expr, pos: Pos) -> R<i64> {
712        let dmax = self.dmax(e)?;
713        let v = self.eval_fixed(e, dmax, pos)?;
714        let whole = align(&v, 0, false).and_then(|m| m.to_u128()).and_then(|m| i64::try_from(m).ok());
715        let whole = whole.ok_or_else(|| Abend::ironwork("an integer operand beyond 64 bits", pos))?;
716        Ok(if v.negative { -whole } else { whole })
717    }
718
719    fn literal_value(&self, lit: &Literal, pos: Pos) -> R<Val> {
720        Ok(match lit {
721            Literal::Alnum(s) => Val::Bytes(self.page.encode(s).map_err(|e| Abend::ironwork(e.to_string(), pos))?),
722            Literal::Hex(b) => Val::Bytes(b.clone()),
723            Literal::National(s) => Val::National(s.encode_utf16().flat_map(u16::to_be_bytes).collect()),
724            Literal::Number(t) => Val::Num(literal_fixed(t).ok_or_else(|| Abend::ironwork(format!("the literal {t} has more than 31 digits"), pos))?),
725            Literal::Figurative(f) => Val::Fig(*f),
726            Literal::All(inner) => match self.literal_value(inner, pos)? {
727                Val::Bytes(b) => Val::All(b),
728                Val::Fig(f) => Val::Fig(f),
729                _ => return Err(Abend::ironwork("ALL takes an alphanumeric literal", pos)),
730            },
731        })
732    }
733
734    /// What a DECIMAL-POINT IS COMMA program shows for a decimal point.
735    fn decimal_point(&self) -> char {
736        if self.program.environment.decimal_point_comma { ',' } else { '.' }
737    }
738
739    fn default_currency(&self) -> String {
740        numval_currency(&self.program.environment.currency)
741    }
742
743    fn operand_with_loc(&mut self, op: &Operand, pos: Pos) -> R<(Val, Option<Loc>)> {
744        if let Operand::Ref(r) = op {
745            let loc = self.locate(r)?;
746            self.numcheck(loc, false, r.pos)?;
747            return Ok((store::read(&self.facts(), &self.unit.mem, loc, r.pos)?, Some(loc)));
748        }
749        Ok((self.operand(op, pos)?, None))
750    }
751
752    /// NUMCHECK's test of a sending item, under the option (`rt::store::numcheck`).
753    fn numcheck(&mut self, loc: Loc, as_integer: bool, pos: Pos) -> R<()> {
754        if self.options.numcheck.is_none() {
755            return Ok(());
756        }
757        let facts = self.facts();
758        rt::store::numcheck(&facts, self.unit, loc, as_integer, &self.program.id, pos)
759    }
760
761    /// A MOVE's sender, tested as `rt::store::move_check` says.
762    fn move_source(&mut self, from: &Operand, dest: Loc, pos: Pos) -> R<(Val, Option<Loc>)> {
763        let Operand::Ref(r) = from else { return self.operand_with_loc(from, pos) };
764        let loc = self.locate(r)?;
765        let check = store::move_check(&self.options, loc.kind, dest.kind);
766        store::numcheck_sender(&self.facts(), self.unit, loc, check, &self.program.id, r.pos)?;
767        Ok((store::move_sender(&self.facts(), &self.unit.mem, loc, dest, r.pos)?, Some(loc)))
768    }
769
770    fn operand(&mut self, op: &Operand, pos: Pos) -> R<Val> {
771        match op {
772            Operand::Ref(r) => {
773                let loc = self.locate(r)?;
774                self.numcheck(loc, false, r.pos)?;
775                store::read(&self.facts(), &self.unit.mem, loc, r.pos)
776            }
777            Operand::Literal(lit) => self.literal_value(lit, pos),
778            Operand::LengthOf(r) => {
779                let layout = self.layout;
780                let loc = self.locate(&layout.length_of_ref(r))?;
781                Ok(Val::Num(Fixed::new(loc.len as i128, Places::new(9, 0))))
782            }
783            Operand::Function(f) => self.function(f, Within::Own),
784            Operand::AddressOf(r) => Ok(Val::Address(self.address_of(r)?)),
785        }
786    }
787
788    fn set_integer(&mut self, r: &Ref, value: i64, pos: Pos) -> R<()> {
789        let dest = self.locate(r)?;
790        store::set_integer(&self.facts(), self.unit, dest, value, pos)
791    }
792
793    fn overflow_branch(&mut self, overflow: bool, on: &'p Option<Vec<Stmt>>, not_on: &'p Option<Vec<Stmt>>) -> R<Flow> {
794        match (overflow, on, not_on) {
795            (true, Some(body), _) | (false, _, Some(body)) => self.run_block(body),
796            _ => Ok(Flow::Next),
797        }
798    }
799
800    fn string_stmt(&mut self, st: &'p StringStmt) -> R<Flow> {
801        let sources: Vec<_> = st.sources.iter().map(|(op, d)| StringSource { chars: facts::chars(op), delimiter: match d {
802            Delimiter::Size => None,
803            Delimiter::By(d) => Some(facts::chars(d)),
804        } }).collect();
805        let overflow = rt::text::string(self, &st.into, st.pointer.as_ref(), &sources, st.pos)?;
806        self.overflow_branch(overflow, &st.on_overflow, &st.not_on_overflow)
807    }
808
809    fn unstring(&mut self, u: &'p Unstring) -> R<Flow> {
810        let delimiters: Vec<_> = u.delimiters.iter().map(|(all, d)| (*all, facts::chars(d))).collect();
811        let into: Vec<_> = u.into.iter().map(|i| UnstringField { target: &i.target, delimiter: i.delimiter_in.as_ref(), count: i.count_in.as_ref() }).collect();
812        let overflow = rt::text::unstring(self, &u.source, u.pointer.as_ref(), &delimiters, &into, u.tallying.as_ref(), u.pos)?;
813        self.overflow_branch(overflow, &u.on_overflow, &u.not_on_overflow)
814    }
815
816    fn inspect(&mut self, i: &Inspect) -> R<()> {
817        let tallying: Vec<_> = i.tallying.iter().map(facts::inspect_phrase).collect();
818        let Operand::Ref(target) = &i.target else {
819            return rt::text::tally(self, &&i.target, &tallying, i.pos);
820        };
821        let replacing: Vec<_> = i.replacing.iter().map(facts::inspect_phrase).collect();
822        let converting = i.converting.as_ref().map(|(from, to, bounds)| Converting { table: ConvertTable::Operands { from: facts::chars(from), to: facts::chars(to) }, bounds: facts::bounds(bounds) });
823        rt::text::inspect(self, target, &tallying, &replacing, converting.as_ref(), i.pos)
824    }
825
826    fn search(&mut self, se: &'p Search) -> R<Flow> {
827        let pos = se.pos;
828        let Resolved::Item(t) = self.resolve(&se.table)? else {
829            return Err(Abend::ironwork(format!("SEARCH {}: not a table", se.table.name), pos));
830        };
831        let layout = self.layout;
832        let table = &layout.items[t];
833        let count = self.occurrences(t, pos)? as i64;
834        let index = match (&se.varying, table.index_names.first()) {
835            (_, Some(name)) => Ref { name: name.clone(), qualifiers: Vec::new(), subscripts: Vec::new(), refmod: None, pos },
836            (Some(v), None) => v.clone(),
837            (None, None) => return Err(Abend::ironwork(format!("SEARCH {}: the table has no INDEXED BY", se.table.name), pos)),
838        };
839        let index_expr = Expr::Operand(Operand::Ref(index.clone()));
840        if !se.all {
841            loop {
842                let i = self.integer(&index_expr, pos)?;
843                if i < 1 || i > count {
844                    return match &se.at_end {
845                        Some(body) => self.run_block(body),
846                        None => Ok(Flow::Next),
847                    };
848                }
849                for (cond, body) in &se.whens {
850                    if self.condition(cond, pos)? {
851                        return self.run_block(body);
852                    }
853                }
854                self.set_integer(&index, i + 1, pos)?;
855                if let Some(v) = &se.varying
856                    && v.name != index.name
857                {
858                    let current = self.integer(&Expr::Operand(Operand::Ref(v.clone())), pos)?;
859                    self.set_integer(v, current + 1, pos)?;
860                }
861            }
862        }
863        let (cond, body) = &se.whens[0];
864        let mut terms = Vec::new();
865        flatten_and(cond, &mut terms);
866        let (mut low, mut high) = (1i64, count);
867        while low <= high {
868            let mid = (low + high) / 2;
869            self.set_integer(&index, mid, pos)?;
870            let mut order = Ordering::Equal;
871            for (ascending, key) in &table.keys {
872                let Some((subject, value)) = key_term(&terms, &key.name) else { continue };
873                let o = self.compare(subject, value, pos)?;
874                order = if *ascending { o } else { o.reverse() };
875                if order != Ordering::Equal {
876                    break;
877                }
878            }
879            match order {
880                Ordering::Less => low = mid + 1,
881                Ordering::Greater => high = mid - 1,
882                Ordering::Equal => {
883                    return if self.condition(cond, pos)? {
884                        self.run_block(body)
885                    } else {
886                        match &se.at_end {
887                            Some(b) => self.run_block(b),
888                            None => Ok(Flow::Next),
889                        }
890                    };
891                }
892            }
893        }
894        match &se.at_end {
895            Some(b) => self.run_block(b),
896            None => Ok(Flow::Next),
897        }
898    }
899
900    /// ADDRESS OF: the item's address, or NULL for a LINKAGE record with none yet.
901    fn address_of(&mut self, r: &Ref) -> R<u32> {
902        if let Ok(Resolved::Item(i)) = self.resolve(r)
903            && let Some(l) = self.layout.items[i].linkage
904            && self.linkage[l as usize].is_none()
905        {
906            return Ok(0);
907        }
908        let loc = self.locate(r)?;
909        Ok(ADDRESS_BASE + loc.offset as u32)
910    }
911
912    fn program_name(&mut self, op: &Operand, pos: Pos) -> R<String> {
913        Ok(match self.operand(op, pos)? {
914            Val::Bytes(b) => self.page.decode(&b).trim().to_ascii_uppercase(),
915            _ => return Err(Abend::ironwork("a program name must be alphanumeric", pos)),
916        })
917    }
918
919    /// Tells the observer, for the input trace, the operand of an operation an input could steer.
920    pub(crate) fn sink(&mut self, kind: &'static str, pos: Pos, operand: &str) {
921        let file = self.event_file(pos);
922        let input = self.unit.input_at_sink();
923        self.unit.notify(Event::Sink { kind, file: &file, line: pos.line, operand, input });
924    }
925
926    /// The file an event names for `pos`: a library program's own source by its path, a COPY
927    /// member by the program's file table, and the first program's own source as empty.
928    fn event_file(&self, pos: Pos) -> String {
929        match (pos.file, &self.unit.programs[self.me].source) {
930            (0, Some(path)) => path.to_str().unwrap_or_default().to_owned(),
931            (i, _) => self.program.sources.get(i as usize).cloned().unwrap_or_default(),
932        }
933    }
934
935    fn arguments_text(&mut self, c: &Call) -> R<String> {
936        callee::arguments_text(self, &call_args(&c.using), c.pos)
937    }
938
939    fn call(&mut self, c: &'p Call) -> R<Flow> {
940        let pos = c.pos;
941        let (name, dynamic) = match self.entry_pointer(&c.target)? {
942            Some(entry) => (entry.name, entry.dynamic),
943            None => {
944                if let Some(flow) = self.call_through_pointer(c)? {
945                    return Ok(flow);
946                }
947                let name = self.program_name(&c.target, pos)?;
948                let variable = !matches!(c.target, Operand::Literal(_));
949                if variable && self.unit.observed() {
950                    self.sink("dynamic-program-load", pos, &name);
951                }
952                (name, self.options.dynam || variable)
953            }
954        };
955        // ironwork runs no operating-system command: the CALL loads a program of that name or fails.
956        if self.unit.observed()
957            && OS_COMMAND_ROUTINES.contains(&name.as_str())
958            && let Ok(text) = self.arguments_text(c)
959        {
960            self.sink("os-command", pos, &text);
961        }
962        let (index, entry) = match self.unit.load_entry(&name, dynamic) {
963            Ok(i) => i,
964            Err(LoadError::NotFound) if crate::le::provides(&name) => return self.le_call(c, &name),
965            Err(LoadError::NotFound) => {
966                if let Some(flow) = self.virtual_print(c, &name)? {
967                    return Ok(flow);
968                }
969                return match &c.on_exception {
970                    Some(body) => self.run_block(body),
971                    None => Err(Abend { code: AbendCode::ModuleNotFound, message: crate::le::missing(&name), pos, file: None }),
972                };
973            }
974            Err(LoadError::Compile(message)) => return Err(Abend::ironwork(format!("CALL {name}: {message}"), pos)),
975        };
976        let held = self.unit.programs[index].compiled.clone();
977        let Some(compiled) = held.as_deref().or(self.first) else {
978            return Err(Abend::ironwork(format!("CALL {name}: the run unit's first program cannot be CALLed from a function or a method"), pos));
979        };
980        self.unit.programs[index].dynamic |= dynamic;
981        let program = &compiled.program;
982        if self.unit.programs[index].active && !program.recursive {
983            let unit = program.containers.last().map_or(&program.id, |c| &c.id);
984            return Err(callee::recursive_call(&program.id, unit, pos));
985        }
986        self.unit.enter(pos)?;
987        let result = self.call_nested(c, index, entry, compiled, dynamic);
988        self.unit.depth -= 1;
989        if let Some(flow) = result? {
990            return Ok(flow);
991        }
992        match &c.not_on_exception {
993            Some(body) => self.run_block(body),
994            None => Ok(Flow::Next),
995        }
996    }
997
998    /// A CALL no library answers that the virtual printer serves: SYSTEM or C$SYSTEM with an lp or
999    /// lpr command, in a run given DD PRINTER. It returns lp's status, 0 printed or 1 not, through
1000    /// RETURNING or else RETURN-CODE.
1001    fn virtual_print(&mut self, c: &'p Call, name: &str) -> R<Option<Flow>> {
1002        use rt::virtual_printer::{self, Job};
1003        if !virtual_printer::ROUTINES.contains(&name) {
1004            return Ok(None);
1005        }
1006        let Some(printer) = self.unit.dds.get(virtual_printer::DD) else { return Ok(None) };
1007        let Some(job) = self.arguments_text(c).ok().as_deref().and_then(Job::parse) else { return Ok(None) };
1008        let dds = self.unit.dds.clone();
1009        let status: i16 = match virtual_printer::print(&dds, &printer, &job, &mut |event| self.unit.notify(event)) {
1010            Ok(()) => 0,
1011            Err(why) => {
1012                let _ = writeln!(self.unit.err, "ironwork: {}: CALL {name}: the virtual printer printed nothing: {why}", c.pos);
1013                1
1014            }
1015        };
1016        match &c.returning {
1017            Some(target) => {
1018                let dest = self.locate(target)?;
1019                self.assign(dest, Val::Num(Fixed::new(i128::from(status), Places::new(9, 0))), None, c.pos)?;
1020            }
1021            None => self.unit.write(RETURN_CODE, &status.to_be_bytes()),
1022        }
1023        Ok(Some(match &c.not_on_exception {
1024            Some(body) => self.run_block(body)?,
1025            None => Flow::Next,
1026        }))
1027    }
1028
1029    /// The entry a CALL's function-pointer or procedure-pointer holds, when SET TO ENTRY set it.
1030    fn entry_pointer(&mut self, target: &Operand) -> R<Option<rt::set::Entry>> {
1031        let Operand::Ref(r) = target else { return Ok(None) };
1032        let Ok(Resolved::Item(item)) = self.resolve(r) else { return Ok(None) };
1033        if self.layout.items[item].kind != Kind::ProgramPointer {
1034            return Ok(None);
1035        }
1036        let loc = self.locate(r)?;
1037        let Ok(value) = <[u8; 4]>::try_from(store::bytes(&self.unit.mem, loc)).map(u32::from_be_bytes) else { return Ok(None) };
1038        Ok(rt::set::entry_of(&self.unit.entries, value).cloned())
1039    }
1040
1041    /// SET TO ENTRY's entry: its name and whether a CALL through it is dynamic, loaded when the
1042    /// SET runs (C140).
1043    fn entry_named(&mut self, entry: &Operand, pos: Pos) -> R<(String, bool)> {
1044        let name = self.program_name(entry, pos)?;
1045        let variable = !matches!(entry, Operand::Literal(_));
1046        if variable && self.unit.observed() {
1047            self.sink("dynamic-program-load", pos, &name);
1048        }
1049        let dynamic = self.options.dynam || variable;
1050        match self.unit.load_entry(&name, dynamic) {
1051            Ok(_) => Ok((name, dynamic)),
1052            Err(LoadError::NotFound) if crate::le::provides(&name) => Ok((name, dynamic)),
1053            Err(LoadError::NotFound) => Err(Abend { code: AbendCode::ModuleNotFound, message: crate::le::missing(&name), pos, file: None }),
1054            Err(LoadError::Compile(message)) => Err(Abend::ironwork(format!("SET TO ENTRY {name}: {message}"), pos)),
1055        }
1056    }
1057
1058    /// The CALL's callee run, through RETURNING; `Some` when the run unit or the logical level ends
1059    /// (C233). NOT ON EXCEPTION is the caller's, after the CALL's nesting is released, as INVOKE's
1060    /// and an LE service's are.
1061    fn call_nested(&mut self, c: &'p Call, index: usize, entry: Option<usize>, compiled: &Compiled, dynamic: bool) -> R<Option<Flow>> {
1062        let pos = c.pos;
1063        let mark = self.unit.mem.len();
1064        let addresses = callee::addresses(self, &call_args(&c.using), pos)?;
1065        self.parmcheck_set();
1066        // A dynamic CALL suspends the caller's handlers, as CBLPSHPOP(ON) does (C234).
1067        let suspends = dynamic && compiled.program.containers.is_empty();
1068        let containers = self.containers_of(&compiled.program);
1069        let by = By::Call { initial: compiled.program.initial };
1070        let (ending, returned) = callee::run(self, &Callee { index, by, mark: Some(mark), pos }, |m| {
1071            let mut callee = Machine::activation_within(compiled, index, &mut *m.unit, false, containers)?;
1072            let entry = entry.and_then(|k| compiled.entries.get(k));
1073            callee.bind_linkage(&[], entry.map_or(&compiled.program.using, |e| &e.using), &addresses, true);
1074            (callee.cics_handlers, callee.first) = (m.cics_handlers.lend(suspends), m.first);
1075            let ending = callee.run_called(entry.map(|e| (e.paragraph, e.statement)));
1076            m.cics_handlers.take_back(&mut callee.cics_handlers, suspends && ending.is_ok());
1077            let returned = match (&compiled.program.returning, &ending) {
1078                (Some(item), Ok(_)) => Some(callee.returned(item, pos)?),
1079                _ => None,
1080            };
1081            Ok::<_, Abend>((ending, returned))
1082        })?;
1083        if ending? == Ending::StopRun {
1084            return Ok(Some(Flow::End(Ending::StopRun)));
1085        }
1086        if crate::cics::level_ended(self.unit) {
1087            return Ok(Some(Flow::End(Ending::Goback)));
1088        }
1089        self.parmcheck_test(c, &addresses, |unit| unit.programs[index].name.clone())?;
1090        if let (Some(target), Some(val)) = (&c.returning, returned) {
1091            let dest = self.locate_written(|m| m.locate(target))?;
1092            self.assign(dest, val, None, pos)?;
1093        }
1094        Ok(None)
1095    }
1096
1097    /// Gives each PROCEDURE DIVISION USING item the address of the argument in its position.
1098    pub(crate) fn bind(&mut self, addresses: &[Option<usize>]) {
1099        let program = self.program;
1100        self.bind_linkage(&[], &program.using, addresses, false);
1101    }
1102
1103    /// Binds this activation's LINKAGE records as `rt::callee::Bindings` does: the object's data
1104    /// `records`, each item of a PROCEDURE DIVISION or ENTRY USING list the argument in its position,
1105    /// and with `returning` the RETURNING item.
1106    fn bind_linkage(&mut self, records: &[(usize, usize)], using: &[Param], addresses: &[Option<usize>], returning: bool) {
1107        let layout = self.layout;
1108        let ordinal = |name: &str| layout.linkage_roots.iter().position(|&i| layout.items[i].name.as_deref() == Some(name));
1109        let using = using.iter().map(|param| ordinal(&param.name)).collect();
1110        let returning = self.program.returning.as_deref().filter(|_| returning).and_then(ordinal).map(|o| (o, layout.items[layout.linkage_roots[o]].size as usize));
1111        Bindings { records, using, addresses, returning }.bind(self.unit, &mut self.linkage);
1112    }
1113
1114    fn returned(&mut self, name: &str, pos: Pos) -> R<Val> {
1115        let r = Ref { name: name.to_owned(), qualifiers: Vec::new(), subscripts: Vec::new(), refmod: None, pos };
1116        let loc = self.locate(&r)?;
1117        store::read(&self.facts(), &self.unit.mem, loc, pos)
1118    }
1119
1120    fn set(&mut self, set: &SetStmt, pos: Pos) -> R<()> {
1121        match set {
1122            SetStmt::ConditionTrue(targets) | SetStmt::ConditionFalse(targets) => {
1123                let truth = matches!(set, SetStmt::ConditionTrue(_));
1124                for r in targets {
1125                    let Resolved::Condition(index) = self.resolve(r)? else {
1126                        return Err(Abend::ironwork(format!("SET {} TO {}: not a condition-name", r.name, if truth { "TRUE" } else { "FALSE" }), pos));
1127                    };
1128                    let condition = &self.layout.conditions[index];
1129                    let value = if truth { condition.values.first().map(|(v, _)| v) } else { condition.false_value.as_ref() };
1130                    let Some(value) = value else { continue };
1131                    let dest = self.locate_written(|m| m.locate_item(condition.item, r, false))?;
1132                    let val = self.literal_value(value, pos)?;
1133                    self.assign(dest, val, None, pos)?;
1134                }
1135            }
1136            SetStmt::To { targets, value } => {
1137                for r in targets {
1138                    let dest = self.locate_written(|m| m.locate(r))?;
1139                    let (val, src) = self.operand_with_loc(value, pos)?;
1140                    let (val, src) = rt::set::to(dest, val, src, pos)?;
1141                    self.assign(dest, val, src, pos)?;
1142                }
1143            }
1144            SetStmt::Entry { targets, entry } => {
1145                let (name, dynamic) = self.entry_named(entry, pos)?;
1146                let value = rt::set::entry(&mut self.unit.entries, &name, dynamic, pos)?;
1147                for r in targets {
1148                    let dest = self.locate_written(|m| m.locate(r))?;
1149                    self.assign(dest, Val::Address(value), None, pos)?;
1150                }
1151            }
1152            SetStmt::AddressOf { targets, value } => {
1153                let val = self.operand(value, pos)?;
1154                let offset = rt::set::address(val, self.unit.mem.len(), pos)?;
1155                for r in targets {
1156                    let Resolved::Item(i) = self.resolve(r)? else {
1157                        return Err(Abend::ironwork(format!("SET ADDRESS OF {}: not a data item", r.name), pos));
1158                    };
1159                    let Some(ordinal) = self.layout.items[i].linkage.filter(|_| self.layout.items[i].parent.is_none()) else {
1160                        return Err(Abend::ironwork(format!("SET ADDRESS OF {}: only a LINKAGE record can be given an address", r.name), pos));
1161                    };
1162                    self.linkage[ordinal as usize] = offset;
1163                }
1164            }
1165            SetStmt::UpDown { targets, down, by } => {
1166                let by = self.integer(by, pos)?;
1167                let targets: Vec<&Ref> = targets.iter().collect();
1168                rt::set::up_down(self, by, *down, &targets, pos)?;
1169            }
1170        }
1171        Ok(())
1172    }
1173
1174    fn accept(&mut self, target: &Ref, from: AcceptFrom, pos: Pos) -> R<()> {
1175        let dest = self.locate_written(|m| m.locate_receiving(target))?;
1176        rt::accept::accept(&self.facts(), self.unit, dest, from, &target.name, pos)
1177    }
1178
1179    fn function(&mut self, f: &FunctionCall, within: Within) -> R<Val> {
1180        if let Some(udf) = self.user_function(&f.name) {
1181            let value = self.invoke_function(udf, f)?;
1182            return self.function_refmod(f, value);
1183        }
1184        if let Some(value) = self.storage_function(f)? {
1185            return self.function_refmod(f, value);
1186        }
1187        let args = self.function_arguments(f, within)?;
1188        let side = match f.modifier.as_deref() {
1189            Some("LEADING") => Some(TrimSide::Leading),
1190            Some("TRAILING") => Some(TrimSide::Trailing),
1191            _ => None,
1192        };
1193        let value = rt::intrinsic::function::evaluate(&mut intrinsic::Call { machine: self, f }, &f.name, side, args, f.pos)?;
1194        self.function_refmod(f, value)
1195    }
1196
1197    fn function_refmod(&mut self, f: &FunctionCall, value: Val) -> R<Val> {
1198        let pos = f.pos;
1199        let Some(rm) = &f.refmod else { return Ok(value) };
1200        rt::intrinsic::function::refmod(value, pos, || {
1201            let start = self.integer(&rm.start, pos)?;
1202            let length = match &rm.length {
1203                Some(l) => Some(self.integer(l, pos)?),
1204                None => None,
1205            };
1206            Ok((start, length))
1207        })
1208    }
1209
1210    fn expr_value(&mut self, e: &Expr, pos: Pos) -> R<Val> {
1211        match e {
1212            Expr::Operand(op) => self.operand(op, pos),
1213            _ if self.uses_float(e)? => Ok(Val::Float(self.eval_float(e, self.options.arith.float_intermediate(), pos)?)),
1214            _ => {
1215                let dmax = self.dmax(e)?;
1216                Ok(Val::Num(self.eval_fixed(e, dmax, pos)?))
1217            }
1218        }
1219    }
1220
1221    fn operand_kind(&mut self, op: &Operand) -> R<Option<Kind>> {
1222        Ok(match op {
1223            Operand::Ref(r) => Some(self.locate(r)?.kind),
1224            Operand::Function(f) => self.user_function(&f.name).map(|u| u.result.kind),
1225            _ => None,
1226        })
1227    }
1228
1229    /// Fixed at lowering as `ArithStep.mode` (lower/plans.rs); the walker decides it on each execution.
1230    fn uses_float(&mut self, e: &Expr) -> R<bool> {
1231        Ok(match e {
1232            Expr::Operand(Operand::Function(f)) => self.is_floating_point(f)?,
1233            Expr::Operand(op) => matches!(self.operand_kind(op)?, Some(Kind::Float(_))),
1234            Expr::Neg(inner) => self.uses_float(inner)?,
1235            Expr::Bin(a, _, b) => self.uses_float(a)? || self.uses_float(b)?,
1236        })
1237    }
1238
1239    /// The most decimal places among an expression's operands, divisors and exponents aside. Fixed at
1240    /// lowering as `ArithPlan.dmax` (lower/plans.rs); the walker works it out on each execution.
1241    fn dmax(&mut self, e: &Expr) -> R<u32> {
1242        Ok(match e {
1243            Expr::Operand(Operand::Literal(Literal::Number(t))) => literal_fixed(t).map_or(0, |f| f.places.dec),
1244            Expr::Operand(op) => self.operand_kind(op)?.and_then(Kind::digits_scale).map_or(0, |(_, s)| s),
1245            Expr::Neg(inner) => self.dmax(inner)?,
1246            Expr::Bin(a, BinOp::Div | BinOp::Pow, _) => self.dmax(a)?,
1247            Expr::Bin(a, _, b) => self.dmax(a)?.max(self.dmax(b)?),
1248        })
1249    }
1250
1251    fn eval_fixed(&mut self, e: &Expr, dmax: u32, pos: Pos) -> R<Fixed> {
1252        let arith = self.options.arith;
1253        match e {
1254            Expr::Operand(Operand::Function(f)) => {
1255                let val = self.function(f, Within::Fixed(dmax))?;
1256                arith::fixed_operand(val, dmax, pos)
1257            }
1258            Expr::Operand(op) => {
1259                let val = self.operand(op, pos)?;
1260                arith::fixed_operand(val, dmax, pos)
1261            }
1262            Expr::Neg(inner) => Ok(arith::fixed_neg(self.eval_fixed(inner, dmax, pos)?)),
1263            Expr::Bin(a, op, b) => {
1264                let x = self.eval_fixed(a, dmax, pos)?;
1265                if *op == BinOp::Pow {
1266                    let n = self.integer(b, pos)?;
1267                    return arith::pow(x, n, dmax, arith, pos);
1268                }
1269                let y = self.eval_fixed(b, dmax, pos)?;
1270                if arith::divides_by_zero(*op, &y) {
1271                    let binary = self.binary_division(a, b)?;
1272                    return Err(arith::zero_divide(binary, pos));
1273                }
1274                arith::fixed_binop(x, *op, y, dmax, arith, pos)
1275            }
1276        }
1277    }
1278
1279    /// Whether the compiler divides `a` by `b` with the fixed-point divide instruction: every
1280    /// operand of both an integer binary item or an integer literal, and one of them an item
1281    /// (assumption C55). Otherwise a fixed-point division is decimal.
1282    fn binary_division(&mut self, a: &Expr, b: &Expr) -> R<bool> {
1283        let mut items = 0;
1284        Ok(self.binary_operands(a, &mut items)? && self.binary_operands(b, &mut items)? && items > 0)
1285    }
1286
1287    fn binary_operands(&mut self, e: &Expr, items: &mut usize) -> R<bool> {
1288        Ok(match e {
1289            Expr::Operand(Operand::Literal(Literal::Number(t))) => !t.contains('.'),
1290            Expr::Operand(Operand::Literal(Literal::Figurative(Figurative::Zero))) => true,
1291            Expr::Operand(Operand::LengthOf(_)) => {
1292                *items += 1;
1293                true
1294            }
1295            Expr::Operand(op @ Operand::Ref(_)) => {
1296                let binary = matches!(self.operand_kind(op)?, Some(Kind::Binary { scale: 0, .. } | Kind::Index));
1297                *items += usize::from(binary);
1298                binary
1299            }
1300            Expr::Operand(_) => false,
1301            Expr::Neg(inner) => self.binary_operands(inner, items)?,
1302            Expr::Bin(x, _, y) => self.binary_operands(x, items)? && self.binary_operands(y, items)?,
1303        })
1304    }
1305
1306    fn eval_float(&mut self, e: &Expr, p: Precision, pos: Pos) -> R<Hfp> {
1307        match e {
1308            Expr::Operand(Operand::Function(f)) => {
1309                let val = self.function(f, Within::Float(p))?;
1310                arith::float_operand(val, p, pos)
1311            }
1312            Expr::Operand(op) => {
1313                let val = self.operand(op, pos)?;
1314                arith::float_operand(val, p, pos)
1315            }
1316            Expr::Neg(inner) => Ok(arith::float_neg(self.eval_float(inner, p, pos)?)),
1317            Expr::Bin(a, op, b) => {
1318                let (x, y) = (self.eval_float(a, p, pos)?, self.eval_float(b, p, pos)?);
1319                arith::float_binop(x, *op, y, p, pos)
1320            }
1321        }
1322    }
1323
1324    /// COMPUTE, ADD, SUBTRACT, MULTIPLY, DIVIDE: what the receivers share is computed before any is
1325    /// stored, then each receiver in turn gets it, or with `per_receiver` combines it with its own
1326    /// current value (Language Reference SC27-8713-03, p. 298, multiple results). A size error
1327    /// leaves the target unchanged when the statement handles it.
1328    fn arithmetic(&mut self, computations: &[(Target, Expr)], remainder: Option<&(Target, Expr, Expr)>, handler: Option<&'p SizeError>, per_receiver: bool, pos: Pos) -> R<Flow> {
1329        let mut size_error = false;
1330        let mut dmax = 0;
1331        // A COMP-1 or COMP-2 receiver makes the statement's arithmetic floating point (Programming
1332        // Guide SC27-8714-03, p. 800).
1333        let mut float_receiver = false;
1334        for (t, e) in computations {
1335            let loc = self.locate(&t.r)?;
1336            float_receiver |= matches!(loc.kind, Kind::Float(_));
1337            dmax = dmax.max(precision::receiver_dec(loc.kind.digits_scale().map_or(0, |(_, s)| s), t.rounded)).max(self.dmax(e)?);
1338        }
1339        if let Some((t, dividend, _)) = remainder {
1340            let loc = self.locate(&t.r)?;
1341            dmax = dmax.max(loc.kind.digits_scale().map_or(0, |(_, s)| s)).max(self.dmax(dividend)?);
1342        }
1343        let mut quotient_target: Option<Loc> = None;
1344        let mut results = Vec::with_capacity(computations.len());
1345        for (t, e) in computations {
1346            let own = |x: &Expr| per_receiver && matches!(x, Expr::Operand(Operand::Ref(r)) if *r == t.r);
1347            let float = float_receiver || self.uses_float(e)?;
1348            let (shared, with) = match e {
1349                Expr::Bin(a, op, b) if *op != BinOp::Pow && own(a) => (b.as_ref(), Some((*op, true))),
1350                Expr::Bin(a, op, b) if *op != BinOp::Pow && own(b) => (a.as_ref(), Some((*op, false))),
1351                _ => (e, None),
1352            };
1353            let outcome = if float {
1354                self.eval_float(shared, self.options.arith.float_intermediate(), pos).map(Val::Float)
1355            } else {
1356                self.eval_fixed(shared, dmax, pos).map(Val::Num)
1357            };
1358            results.push((t, shared, with, outcome));
1359        }
1360        let operands = match remainder {
1361            Some((_, dividend, divisor)) => Some((self.eval_fixed(dividend, dmax, pos)?, self.eval_fixed(divisor, dmax, pos)?)),
1362            None => None,
1363        };
1364        for (t, shared, with, outcome) in results {
1365            let loc = self.locate(&t.r)?;
1366            quotient_target.get_or_insert(loc);
1367            let outcome = match (with, outcome) {
1368                (Some((op, receiver_first)), Ok(Val::Num(value))) => {
1369                    let current = self.eval_fixed(&Expr::Operand(Operand::Ref(t.r.clone())), dmax, pos)?;
1370                    let (x, y) = if receiver_first { (current, value) } else { (value, current) };
1371                    if arith::divides_by_zero(op, &y) {
1372                        let receiver = Expr::Operand(Operand::Ref(t.r.clone()));
1373                        let binary = self.binary_division(&receiver, shared)?;
1374                        Err(arith::zero_divide(binary, pos))
1375                    } else {
1376                        arith::fixed_binop(x, op, y, dmax, self.options.arith, pos).map(Val::Num)
1377                    }
1378                }
1379                (Some((op, receiver_first)), Ok(Val::Float(value))) => {
1380                    let p = self.options.arith.float_intermediate();
1381                    let current = self.eval_float(&Expr::Operand(Operand::Ref(t.r.clone())), p, pos)?;
1382                    let (x, y) = if receiver_first { (current, value) } else { (value, current) };
1383                    arith::float_binop(x, op, y, p, pos).map(Val::Float)
1384                }
1385                (_, outcome) => outcome,
1386            };
1387            let Some(value) = arith::size_error(outcome, handler.is_some())? else {
1388                size_error = true;
1389                continue;
1390            };
1391            size_error |= store::store_value(&self.facts(), self.unit, loc, value, t.rounded, handler.is_some(), pos)?;
1392        }
1393        if let (Some((t, _, _)), Some((x, y)), Some(q_loc)) = (remainder, operands, quotient_target)
1394            && let Some(r) = arith::remainder(x, y, places_of(q_loc.kind).dec, dmax, self.options.arith, pos)?
1395        {
1396            let r_loc = self.locate(&t.r)?;
1397            size_error |= store::store_value(&self.facts(), self.unit, r_loc, Val::Num(r), false, handler.is_some(), pos)?;
1398        }
1399        if let Some(h) = handler {
1400            return self.run_block(if size_error { &h.on } else { &h.not_on });
1401        }
1402        Ok(Flow::Next)
1403    }
1404
1405    fn condition(&mut self, c: &Cond, pos: Pos) -> R<bool> {
1406        Ok(match c {
1407            Cond::Rel(a, op, b) => {
1408                let o = self.compare(a, b, pos)?;
1409                match op {
1410                    RelOp::Eq => o == Ordering::Equal,
1411                    RelOp::Ne => o != Ordering::Equal,
1412                    RelOp::Lt => o == Ordering::Less,
1413                    RelOp::Le => o != Ordering::Greater,
1414                    RelOp::Gt => o == Ordering::Greater,
1415                    RelOp::Ge => o != Ordering::Less,
1416                }
1417            }
1418            Cond::Not(inner) => !self.condition(inner, pos)?,
1419            Cond::And(a, b) => self.condition(a, pos)? && self.condition(b, pos)?,
1420            Cond::Or(a, b) => self.condition(a, pos)? || self.condition(b, pos)?,
1421            Cond::Class(e, class) => self.class(e, *class, pos)?,
1422            Cond::NameOrRel { subject, op, negated, name } => match self.resolve(name)? {
1423                Resolved::Condition(_) => self.condition(&Cond::Name(name.clone()), pos)?,
1424                Resolved::Item(_) => self.condition(&Cond::Rel(subject.clone(), *op, Expr::Operand(Operand::Ref(name.clone()))), pos)? != *negated,
1425            },
1426            Cond::Name(r) => {
1427                let Resolved::Condition(index) = self.resolve(r)? else {
1428                    return Err(Abend::ironwork(format!("{} is a data item, not a condition", r.name), r.pos));
1429                };
1430                let condition = &self.layout.conditions[index];
1431                let loc = self.locate_item(condition.item, r, false)?;
1432                self.numcheck(loc, false, r.pos)?;
1433                let mut subject = None;
1434                for (low, high) in &condition.values {
1435                    let hit = match high {
1436                        None => self.compare_value(loc, &mut subject, low, r.pos, pos)? == Ordering::Equal,
1437                        Some(high) => self.compare_value(loc, &mut subject, low, r.pos, pos)? != Ordering::Less && self.compare_value(loc, &mut subject, high, r.pos, pos)? != Ordering::Greater,
1438                    };
1439                    if hit {
1440                        return Ok(true);
1441                    }
1442                }
1443                false
1444            }
1445        })
1446    }
1447
1448    fn class(&mut self, e: &Expr, class: Class, pos: Pos) -> R<bool> {
1449        if let (Class::Numeric | Class::Alphabetic | Class::AlphabeticLower | Class::AlphabeticUpper, Expr::Operand(Operand::Ref(r))) = (class, e) {
1450            let loc = self.locate(r)?;
1451            let test = match (class, loc.kind) {
1452                (Class::Numeric, Kind::Packed { signed, .. }) => ByteClass::Packed { signed },
1453                (Class::Numeric, Kind::Zoned { signed, sign: None, .. }) => ByteClass::Zoned { signed },
1454                (Class::Numeric, _) => ByteClass::Digits,
1455                (Class::AlphabeticLower, _) => ByteClass::AlphabeticLower,
1456                (Class::AlphabeticUpper, _) => ByteClass::AlphabeticUpper,
1457                (_, _) => ByteClass::Alphabetic,
1458            };
1459            return Ok(store::byte_class(&self.facts(), &self.unit.mem, loc, test));
1460        }
1461        let test = match class {
1462            Class::Positive => SignTest::Positive,
1463            Class::Negative => SignTest::Negative,
1464            _ => SignTest::Zero,
1465        };
1466        store::sign_test(self.expr_value(e, pos)?, test, pos)
1467    }
1468
1469    /// Object references are compared here; `rt::store::compare` compares everything else.
1470    fn compare(&mut self, a: &Expr, b: &Expr, pos: Pos) -> R<Ordering> {
1471        for (zoned, other, zoned_first) in [(a, b, true), (b, a, false)] {
1472            if let Some(image) = self.zoned_bytes_against(zoned, other)? {
1473                if let Expr::Operand(Operand::Ref(r)) = zoned
1474                    && self.checks_against(other)?
1475                {
1476                    let loc = self.locate(r)?;
1477                    self.numcheck(loc, false, r.pos)?;
1478                }
1479                let other = match other {
1480                    Expr::Operand(Operand::Ref(r)) if self.zone_sensitive(other)? => {
1481                        let loc = self.locate(r)?;
1482                        self.numcheck(loc, false, r.pos)?;
1483                        (Val::Bytes(Vec::new()), Some(loc))
1484                    }
1485                    _ => self.comparand_against(other, zoned, pos)?,
1486                };
1487                return store::compare_zoned_bytes(&self.facts(), &self.unit.mem, &image, other, zoned_first, pos);
1488            }
1489        }
1490        let (va, la) = self.comparand_against(a, b, pos)?;
1491        let (vb, lb) = self.comparand_against(b, a, pos)?;
1492        if let Some(o) = self.compare_references(a, b, (&va, la), (&vb, lb), pos)? {
1493            return Ok(o);
1494        }
1495        store::compare(&self.facts(), &self.unit.mem, (va, la), (vb, lb), pos)
1496    }
1497
1498    /// Whether `e` is an alphanumeric item, literal or figurative constant other than ZERO.
1499    fn nonnumeric(&mut self, e: &Expr) -> R<bool> {
1500        Ok(match e {
1501            Expr::Operand(Operand::Literal(l)) => {
1502                matches!(l, Literal::Alnum(_) | Literal::Hex(_) | Literal::All(_)) || matches!(l, Literal::Figurative(f) if !matches!(f, Figurative::Zero | Figurative::Null))
1503            }
1504            Expr::Operand(Operand::Ref(o)) => store::nonnumeric(self.locate(o)?.kind),
1505            _ => false,
1506        })
1507    }
1508
1509    /// Whether NUMCHECK tests a zoned item compared with `other`: always, but under ZON(NOALPHNUM)
1510    /// not against an alphanumeric operand (Programming Guide SC27-8714-03, pp. 389-390).
1511    fn checks_against(&mut self, other: &Expr) -> R<bool> {
1512        Ok(!store::noalphnum(&self.options) || !self.nonnumeric(other)?)
1513    }
1514
1515    /// A comparand, NUMCHECK testing an item unless ZON(NOALPHNUM) exempts it against `other`.
1516    fn comparand_against(&mut self, e: &Expr, other: &Expr, pos: Pos) -> R<(Val, Option<Loc>)> {
1517        match e {
1518            Expr::Operand(Operand::Ref(r)) if !self.checks_against(other)? => {
1519                let loc = self.locate(r)?;
1520                Ok((store::read(&self.facts(), &self.unit.mem, loc, r.pos)?, Some(loc)))
1521            }
1522            _ => self.comparand(e, pos),
1523        }
1524    }
1525
1526    /// The bytes of `e`, a zoned integer item, when `other` is nonnumeric: that comparison reads the
1527    /// item's bytes, never its value, so invalid data compares rather than abends.
1528    fn zoned_bytes_against(&mut self, e: &Expr, other: &Expr) -> R<Option<Vec<u8>>> {
1529        let Expr::Operand(Operand::Ref(r)) = e else { return Ok(None) };
1530        let nonnumeric = self.nonnumeric(other)?;
1531        // Where zones are compared, an unsigned zoned integer against zero or one of its own
1532        // length compares its zones too (assumptions C223, C262).
1533        let zones_count = self.options.zones_compared()
1534            && self.zone_sensitive(e)?
1535            && match other {
1536                Expr::Operand(Operand::Literal(l)) => self.zero_literal(l),
1537                Expr::Operand(Operand::Ref(o)) => self.zone_sensitive(other)? && self.locate(o)?.len == self.locate(r)?.len,
1538                _ => false,
1539            };
1540        if !nonnumeric && !zones_count {
1541            return Ok(None);
1542        }
1543        let loc = self.locate(r)?;
1544        Ok(store::compared_zoned_bytes(&self.facts(), &self.unit.mem, loc))
1545    }
1546
1547    /// Whether `e` is an unsigned, unscaled zoned integer item.
1548    fn zone_sensitive(&mut self, e: &Expr) -> R<bool> {
1549        let Expr::Operand(Operand::Ref(r)) = e else { return Ok(false) };
1550        let loc = self.locate(r)?;
1551        Ok(self.zone_sensitive_at(loc))
1552    }
1553
1554    fn zone_sensitive_at(&self, loc: Loc) -> bool {
1555        matches!(loc.kind, Kind::Zoned { scale: 0, signed: false, .. }) && self.layout.items.get(loc.item).is_none_or(|i| i.scaling == 0)
1556    }
1557
1558    fn zero_literal(&self, l: &Literal) -> bool {
1559        match l {
1560            Literal::Figurative(Figurative::Zero) => true,
1561            Literal::Number(t) => literal_fixed(t).is_some_and(|f| store::zero(&Val::Num(f))),
1562            _ => false,
1563        }
1564    }
1565
1566    /// A condition-name's value compared with its conditional variable at `loc` as the relation
1567    /// of the two would compare them: by the variable's bytes where `zoned_bytes_against` would
1568    /// take them, otherwise as numbers, the variable read once into `subject` at `at`.
1569    fn compare_value(&mut self, loc: Loc, subject: &mut Option<(Val, Option<Loc>)>, value: &Literal, at: Pos, pos: Pos) -> R<Ordering> {
1570        let nonnumeric = matches!(value, Literal::Alnum(_) | Literal::Hex(_) | Literal::All(_)) || matches!(value, Literal::Figurative(f) if !matches!(f, Figurative::Zero | Figurative::Null));
1571        let zones_count = self.options.zones_compared() && self.zone_sensitive_at(loc) && self.zero_literal(value);
1572        if (nonnumeric || zones_count)
1573            && let Some(image) = store::compared_zoned_bytes(&self.facts(), &self.unit.mem, loc)
1574        {
1575            let value = self.literal_value(value, pos)?;
1576            return store::compare_zoned_bytes(&self.facts(), &self.unit.mem, &image, (value, None), true, pos);
1577        }
1578        let subject = match subject {
1579            Some(s) => s.clone(),
1580            None => subject.insert((store::read(&self.facts(), &self.unit.mem, loc, at)?, Some(loc))).clone(),
1581        };
1582        self.compare_literal(&subject, value, pos)
1583    }
1584
1585    fn compare_literal(&mut self, subject: &(Val, Option<Loc>), literal: &Literal, pos: Pos) -> R<Ordering> {
1586        let value = self.literal_value(literal, pos)?;
1587        store::compare(&self.facts(), &self.unit.mem, subject.clone(), (value, None), pos)
1588    }
1589
1590    fn comparand(&mut self, e: &Expr, pos: Pos) -> R<(Val, Option<Loc>)> {
1591        match e {
1592            Expr::Operand(op) => self.operand_with_loc(op, pos),
1593            _ => Ok((self.expr_value(e, pos)?, None)),
1594        }
1595    }
1596
1597    fn display(&mut self, items: &[Operand], no_advancing: bool, pos: Pos) -> R<()> {
1598        let mut text = String::new();
1599        for op in items {
1600            let shown = match op {
1601                Operand::Ref(r) => {
1602                    let loc = self.locate(r)?;
1603                    rt::display::place(&self.facts(), &self.unit.mem, loc, r.pos)?
1604                }
1605                Operand::Literal(Literal::Number(t)) => rt::display::number(t, &self.facts()),
1606                other => {
1607                    let val = self.operand(other, pos)?;
1608                    rt::display::value(&self.facts(), val, pos)?
1609                }
1610            };
1611            text.push_str(&shown);
1612        }
1613        if self.unit.observed() {
1614            self.sink("log", pos, &text);
1615        }
1616        rt::display::write(&mut *self.unit.out, &text, no_advancing, pos)
1617    }
1618
1619    /// The implicit MOVEs of INITIALIZE to item `index` at `offset`.
1620    fn initialize(&mut self, index: usize, offset: usize, with: &InitializeWith, pos: Pos) -> R<()> {
1621        let layout = self.layout;
1622        for (i, at) in layout.initialize_receivers(index, with.filler) {
1623            let item = &layout.items[i];
1624            let loc = Loc { offset: offset + at as usize, len: item.size as usize, kind: item.kind, item: i };
1625            match (with.initial_value(layout.category(i), item.value.is_some()), &item.value) {
1626                (Some(InitialValue::Value), Some(value)) => {
1627                    let val = self.literal_value(value, pos)?;
1628                    self.assign(Loc { kind: value_kind(item.kind, value), ..loc }, val, None, pos)?;
1629                }
1630                (Some(InitialValue::Replacing(by)), _) => {
1631                    let (val, src) = self.operand_with_loc(by, pos)?;
1632                    self.assign(loc, val, src, pos)?;
1633                }
1634                (Some(_), _) => self.assign(loc, initial_default(item.kind), None, pos)?,
1635                (None, _) => {}
1636            }
1637        }
1638        Ok(())
1639    }
1640}
1641
1642/// The cs of NUMVAL-C and TEST-NUMVAL-C without argument-2 (assumption C102).
1643pub(crate) fn numval_currency(signs: &[CurrencySign]) -> String {
1644    match signs {
1645        [only] => only.value.clone(),
1646        _ => "$".to_owned(),
1647    }
1648}
1649
1650static NO_PHRASES: InitializeWith = InitializeWith { filler: false, value: Vec::new(), replacing: Vec::new(), default: false };
1651
1652/// The kind a VALUE clause's literal is placed as: editing is ignored, so an alphanumeric VALUE fills
1653/// a numeric-edited or alphanumeric-edited item as alphanumeric data (Language Reference p. 246).
1654pub(crate) fn value_kind(kind: Kind, value: &Literal) -> Kind {
1655    match (kind, value) {
1656        (Kind::NumericEdited { .. } | Kind::AlnumEdited { .. }, Literal::Alnum(_) | Literal::Figurative(_) | Literal::All(_)) => Kind::Alnum { justified: false },
1657        (kind, _) => kind,
1658    }
1659}
1660
1661/// A CALL's USING phrase as `rt::callee` takes it: a data item BY REFERENCE by its place, BY VALUE
1662/// by its value, and anything else as BY CONTENT copies it.
1663fn call_args(using: &[Arg]) -> Vec<CallArg<&Ref, &Operand>> {
1664    using
1665        .iter()
1666        .map(|arg| match (arg.mode, &arg.value) {
1667            (_, None) => CallArg::Omitted,
1668            (ArgMode::Reference, Some(Operand::Ref(r))) => CallArg::Reference(r),
1669            (ArgMode::Value, Some(op)) => CallArg::Value(op),
1670            (_, Some(op)) => CallArg::Content(facts::chars(op)),
1671        })
1672        .collect()
1673}
1674
1675/// INITIALIZE's implied sending item for an elementary receiver of `kind` (Language Reference
1676/// SC27-8713-03, p. 353), NULL for a pointer.
1677fn initial_default(kind: Kind) -> Val {
1678    match kind {
1679        Kind::Pointer => Val::Address(0),
1680        Kind::Alnum { .. } | Kind::AlnumEdited { .. } | Kind::National => Val::Fig(Figurative::Space),
1681        _ => Val::Fig(Figurative::Zero),
1682    }
1683}
1684
1685pub(crate) fn flatten_and<'c>(cond: &'c Cond, out: &mut Vec<&'c Cond>) {
1686    match cond {
1687        Cond::And(a, b) => {
1688            flatten_and(a, out);
1689            flatten_and(b, out);
1690        }
1691        other => out.push(other),
1692    }
1693}
1694
1695/// In a SEARCH ALL condition, the key item and the value it must equal.
1696pub(crate) fn key_term<'c>(terms: &[&'c Cond], key: &str) -> Option<(&'c Expr, &'c Expr)> {
1697    let is_key = |e: &Expr| matches!(e, Expr::Operand(Operand::Ref(r)) if r.name == key);
1698    terms.iter().find_map(|t| match t {
1699        Cond::Rel(a, RelOp::Eq, b) if is_key(a) => Some((a, b)),
1700        Cond::Rel(a, RelOp::Eq, b) if is_key(b) => Some((b, a)),
1701        _ => None,
1702    })
1703}