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