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