ironwork-rt 0.8.0

ironwork for COBOL: the runtime a compiled program links, under the runtime exception
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! The ops (lir.md §8.1, §9): each a call of the semantics library the walker's statement makes,
//! with the `Loc`s and values it would pass, and the `Host` the library's statements call back.

use super::value::int_binop;
use super::{Code, Facts, R, Vm, not_yet};
use crate::abend::Abend;
use crate::accept;
use crate::display;
use crate::fixed::places_of;
use crate::host::{Host, Values};
use super::markup::Receiving;
use crate::lir::{DisplayItem, InitPlan, InitValue, Inspected, MovePlan, NumericFrom, Op, Operand, PlaceId, SearchAllPlan, SenderCheck, Step, StorePlan, TempId};
use crate::set;
use crate::storage::{Kind, Loc, Val};
use crate::store;
use crate::text::{self, UnstringField};
use crate::unit::Loader;
use crate::vocab::{AcceptFrom, BinOp, Figurative, Pos};
use numeric::precision::Fixed;
use std::cmp::Ordering;
use std::rc::Rc;

/// Whether a store by MOVE rules passes the sender's storage with its value. Only PERFORM VARYING's
/// FROM lowers without it, into a fixed-point receiver, where its plan shows what the storage would
/// change: a group's bytes copied, a numeric-edited item de-edited, a packed item copied under
/// NUMPROC(PFD).
fn sender_kept(sender: Kind, dest: Kind, plan: &MovePlan) -> bool {
    if !matches!(dest, Kind::Zoned { .. } | Kind::Packed { .. } | Kind::Binary { .. }) {
        return true;
    }
    match (sender, plan) {
        (Kind::Group, MovePlan::Numeric { .. }) => false,
        (Kind::NumericEdited { .. }, MovePlan::Numeric { from: NumericFrom::Zoned, .. }) => false,
        (Kind::Packed { .. }, MovePlan::Numeric { from: NumericFrom::Value, .. }) => sender != dest,
        _ => true,
    }
}

/// The kind of the elementary item an INITIALIZE field's MOVE plan was made for.
fn field_kind(plan: &MovePlan) -> Option<Kind> {
    Some(match *plan {
        MovePlan::Alnum { justified, .. } => Kind::Alnum { justified },
        MovePlan::AlnumEdited { edit, .. } => Kind::AlnumEdited { edit },
        MovePlan::National(_) => Kind::National,
        MovePlan::Dbcs { justified, edit } => Kind::Dbcs { justified, edit },
        MovePlan::Float { precision, .. } => Kind::Float(precision),
        MovePlan::Address => Kind::Pointer,
        MovePlan::Index => Kind::Index,
        MovePlan::Numeric { store, .. } => match store {
            StorePlan::Zoned { digits, scale, signed, sign } => Kind::Zoned { digits, scale, signed, sign },
            StorePlan::Packed { digits, scale, signed } => Kind::Packed { digits, scale, signed },
            StorePlan::Binary { digits, scale, signed, native, .. } => Kind::Binary { digits, scale, signed, native },
            StorePlan::NumericEdited { edit, digits, scale, blank_when_zero } => Kind::NumericEdited { edit, digits, scale, blank_when_zero },
            StorePlan::Float(p) => Kind::Float(p),
            StorePlan::Index => Kind::Index,
            StorePlan::Refused(_) => return None,
        },
        MovePlan::Refused(_) => return None,
    })
}

impl<'p, L: Loader<Rc<Code>>> Vm<'p, '_, '_, L> {
    pub(super) fn op(&mut self, op: &Op, at: u32) -> R<Step> {
        let p = self.p;
        let pos = self.pos(at);
        match op {
            Op::Move { from, to, plan, check } => {
                let dest = self.loc_written(*to)?;
                self.move_to(Some(*check), *from, dest, plan, at)?;
            }
            Op::Set { from, to, plan } => {
                let dest = self.loc_written(*to)?;
                self.move_to(None, *from, dest, plan, at)?;
            }
            Op::Initialize { target, plan } => self.initialize(*target, &p.plans.init[*plan as usize], at)?,
            Op::Arith(id) => return self.arith(&p.plans.arith[*id as usize], pos),
            Op::SetAddress { records, address } => {
                let val = self.value(*address)?;
                let offset = set::address(val, self.unit.mem.len(), pos)?;
                for &r in records {
                    self.linkage[r as usize] = offset;
                }
            }
            Op::SetEntry { entry, targets } => self.set_entry(*entry, targets, pos)?,
            Op::SetUpDown { by, down, targets } => {
                let by = self.int(by, pos)?;
                let places: Vec<PlaceId> = targets.iter().map(|(place, _)| *place).collect();
                let result = set::up_down(self, by, *down, &places, pos);
                self.settle(result)?;
            }
            Op::Step { var, by, plan, prepass } => {
                let dest = self.loc(*var)?;
                for &q in prepass {
                    self.loc(q)?;
                }
                let x = self.operand_number(Operand::Load(*var), plan.dmax, pos)?;
                let y = self.eval_number(*by, plan.dmax, pos)?;
                let arith = p.options.options.arith;
                let next = match int_binop(x, BinOp::Add, y, plan.dmax, arith) {
                    Some(next) => next.fixed(),
                    None => crate::arith::fixed_binop(x.fixed(), BinOp::Add, y.fixed(), plan.dmax, arith, pos)?,
                };
                store::store_fixed(&self.facts(), self.unit, dest, &next, false, pos)?;
            }
            Op::SetInt { target, value } => {
                let n = self.int(value, pos)?;
                let dest = self.loc(*target)?;
                store::set_integer(&self.facts(), self.unit, dest, n, pos)?;
            }
            Op::Inspect(id) => self.inspect(*id, pos)?,
            Op::String(id) => {
                let plan = &p.plans.string[*id as usize];
                let result = text::string(self, plan.into, plan.pointer.map(|(q, _)| q), &plan.sources, pos);
                return Ok(Step::Arm(u8::from(self.settle(result)?)));
            }
            Op::Unstring(id) => {
                let plan = &p.plans.unstring[*id as usize];
                let into: Vec<UnstringField<PlaceId>> =
                    plan.into.iter().map(|i| UnstringField { target: i.target, delimiter: i.delimiter.map(|d| d.target), count: i.count.map(|(q, _)| q) }).collect();
                let result = text::unstring(self, plan.source, plan.pointer.map(|(q, _)| q), &plan.delimiters, &into, plan.tallying.map(|(q, _)| q), pos);
                return Ok(Step::Arm(u8::from(self.settle(result)?)));
            }
            Op::SearchAll(id) => return self.search_all(&p.plans.search_all[*id as usize], pos),
            Op::Nest => self.unit.enter(pos)?,
            Op::Unnest(n) => self.unit.depth = self.unit.depth.saturating_sub(usize::from(*n)),
            Op::SetTemp(t, value) => {
                let n = self.int(value, pos)?.max(0);
                self.set_temp(*t, n)?;
            }
            Op::SetCount(t, odo) => {
                let n = self.occurrences(odo, pos)?;
                self.set_temp(*t, i64::from(n))?;
            }
            Op::DecTemp(t) => {
                if let Some(n) = self.returns.frames.last_mut().and_then(|f| f.temps.get_mut(usize::from(*t))) {
                    *n -= 1;
                }
            }
            Op::Display(id) => self.display(*id, pos)?,
            Op::ArgumentNumber(value) => {
                let n = self.int(value, pos)?;
                self.unit.arguments.position(n);
            }
            Op::Accept { target, from, .. } => {
                let dest = self.loc_written(*target)?;
                let name = self.sym(p.places[*target as usize].name);
                let exception = accept::accept(&self.facts(), self.unit, dest, *from, name, pos)?;
                if *from == AcceptFrom::ArgumentValue {
                    return Ok(Step::Arm(u8::from(exception)));
                }
            }
            Op::File(id) => return self.file(&p.services.file_ops[*id as usize], at),
            Op::Call(id) => return self.call(&p.services.calls[*id as usize], pos),
            Op::Cancel(name) => self.cancel(*name, pos)?,
            Op::Sort(id) => return self.sort(&p.services.sorts[*id as usize], pos),
            Op::Release(id) => self.release(&p.services.releases[*id as usize], at)?,
            Op::Return(id) => return self.return_record(&p.services.returns[*id as usize], pos),
            Op::Report(op) => return self.report(*op, pos),
            Op::Invoke(id) => return self.invoke(&p.services.invokes[*id as usize], pos),
            Op::Cics(id) => return self.cics(*id, pos),
            Op::Sql(ordinal) => return self.sql(*ordinal, pos),
            Op::Markup(id) => return self.markup(&p.services.markup[*id as usize], at, pos),
            Op::Alter { para, to } => {
                let paragraphs = p.paragraphs.len();
                let altered = &mut self.unit.programs[self.me].altered;
                altered.resize(paragraphs, None);
                altered[*para as usize] = Some(*to as usize);
            }
            Op::EnterSegment(priority) => self.enter_segment(*priority),
            Op::DebugLine(line) => self.line = *line,
            Op::DebugAlter { range, name, contents } => {
                if self.debugging {
                    return Ok(Step::Next);
                }
                return Ok(self.run_debugging(*range, self.sym(*name), pos.line, self.sym(*contents), pos)?.unwrap_or(Step::Next));
            }
        }
        Ok(Step::Next)
    }

    /// MOVE of `from` into `dest`, located already, by `plan`, a data item sender tested as `check`
    /// says (`Machine::move_source`); without `check`, as SET TO moves it. An integer sender that
    /// reads without an abend goes to a binary or zoned receiver as `store::assign` stores its value.
    pub(super) fn move_to(&mut self, check: Option<SenderCheck>, from: Operand, dest: Loc, plan: &MovePlan, at: u32) -> R<()> {
        match (check, from) {
            (Some(check), Operand::Load(p)) => {
                let src = self.loc(p)?;
                let pos = self.pos(self.p.places[p as usize].at);
                self.numcheck(src, check, pos)?;
                if matches!(dest.kind, Kind::Binary { .. } | Kind::Zoned { .. })
                    && !matches!(plan, MovePlan::Refused(_))
                    && super::place::plain(&self.p.places[p as usize])
                    && let Some(n) = store::read_integer(&self.facts(), &self.unit.mem, src)
                {
                    let value = Fixed::new(i128::from(n), places_of(src.kind));
                    return Ok(store::store_fixed(&self.facts(), self.unit, dest, &value, false, self.pos(at))?);
                }
                let val = store::move_sender(&self.facts(), &self.unit.mem, src, dest, pos)?;
                self.moved(val, Some(src), dest, plan, at)
            }
            _ => {
                let (val, src) = self.value_with_loc(from)?;
                self.moved(val, src, dest, plan, at)
            }
        }
    }

    /// The sender's value, read, stored into `dest` by `plan`.
    fn moved(&mut self, val: Val, src: Option<Loc>, dest: Loc, plan: &MovePlan, at: u32) -> R<()> {
        if let MovePlan::Refused(abend) = plan {
            return Err(self.abend(*abend, Some(at)).into());
        }
        let src = src.filter(|s| sender_kept(s.kind, dest.kind, plan));
        Ok(store::assign(&self.facts(), self.unit, dest, val, src, self.pos(at))?)
    }

    fn set_temp(&mut self, t: TempId, n: i64) -> R<()> {
        let Some(frame) = self.returns.frames.last_mut() else { return Err(not_yet("a TIMES counter outside a frame")) };
        let t = usize::from(t);
        if frame.temps.len() <= t {
            frame.temps.resize(t + 1, 0);
        }
        frame.temps[t] = n;
        Ok(())
    }

    /// `Machine::enter_segment`: an independent segment entered from another is in its initial
    /// state, its altered GO TOs as written (assumption C52).
    pub(super) fn enter_segment(&mut self, priority: u8) {
        if priority == self.segment {
            return;
        }
        self.segment = priority;
        if priority >= 50 {
            let p = self.p;
            for (i, target) in self.unit.programs[self.me].altered.iter_mut().enumerate() {
                if p.paragraphs[i].priority == priority {
                    *target = None;
                }
            }
        }
    }

    /// `Machine::initialize`: each elementary item the walk reaches sent its field's value by MOVE
    /// rules, a data item REPLACING names located and read again for each. A reference-modified
    /// target's one field is the target as located.
    fn initialize(&mut self, target: PlaceId, plan: &InitPlan, at: u32) -> R<()> {
        let pos = self.pos(at);
        let loc = self.loc_written(target)?;
        let refmod = self.p.places[target as usize].refmod.is_some();
        for field in &plan.fields {
            let (val, src) = match field.value {
                InitValue::Default(Figurative::Null) => (Val::Address(0), None),
                InitValue::Default(f) => (Val::Fig(f), None),
                InitValue::Value(c) => (self.value(Operand::Const(c))?, None),
                InitValue::Replacing(o) => self.value_with_loc(o)?,
            };
            let store = match field.store {
                MovePlan::Refused(abend) => return Err(self.abend(abend, Some(at)).into()),
                MovePlan::Numeric { store, .. } => Some(store),
                _ => None,
            };
            let Some(kind) = field_kind(&field.store) else { return Err(not_yet("an INITIALIZE field with no MOVE plan")) };
            let (offset, len) = if refmod { (loc.offset, loc.len) } else { (loc.offset + field.offset as usize, field.len as usize) };
            let dest = Loc { offset, len, kind, item: usize::MAX };
            let facts = Receiving { scaling: Some(field.scaling), ..self.receiving(store.as_ref()) };
            store::assign(&facts, self.unit, dest, val, src, pos)?;
        }
        Ok(())
    }

    fn inspect(&mut self, id: u32, pos: Pos) -> R<()> {
        let plan = &self.p.plans.inspect[id as usize];
        let phrase = |p: &crate::lir::InspectPhrase| text::InspectPhrase {
            mode: p.mode,
            pattern: p.pattern.clone(),
            by: p.by.clone(),
            counter: p.counter.map(|(q, _)| q),
            bounds: p.bounds.clone(),
        };
        let tallying: Vec<_> = plan.tallying.iter().map(phrase).collect();
        let result = match &plan.target {
            Inspected::Item(target) => {
                let replacing: Vec<_> = plan.replacing.iter().map(phrase).collect();
                text::inspect(self, *target, &tallying, &replacing, plan.converting.as_ref(), pos)
            }
            Inspected::Value(subject) => text::tally(self, subject, &tallying, pos),
        };
        self.settle(result)
    }

    /// `Machine::display`: each item as its kind or value shows, the line told to an observer,
    /// then written. A national item is converted only as `DisplayItem::National`, UPON CONSOLE.
    fn display(&mut self, id: u32, pos: Pos) -> R<()> {
        let p = self.p;
        let plan = &p.plans.display[id as usize];
        let mut shown = String::new();
        for item in &plan.items {
            shown.push_str(&match item {
                DisplayItem::Bytes(place) | DisplayItem::National(place) | DisplayItem::Digits { place, .. } | DisplayItem::Refused { place, .. } => {
                    let loc = self.loc(*place)?;
                    let upon_console = matches!(item, DisplayItem::National(_));
                    display::place(&self.facts(), &self.unit.mem, loc, self.pos(p.places[*place as usize].at), upon_console)?
                }
                DisplayItem::Text(text) => self.sym(*text).to_owned(),
                DisplayItem::Value(o) => {
                    let val = self.value(*o)?;
                    display::value(&self.facts(), val, pos, false)?
                }
            });
        }
        if self.unit.observed() {
            self.sink("log", pos, &shown);
        }
        Ok(display::write(&mut *self.unit.out, &shown, plan.no_advancing, pos)?)
    }

    /// `Machine::search` of SEARCH ALL: a binary search setting the index to each occurrence
    /// tried; Arm(0) at one whose keys equal their WHEN terms, Arm(1) when there is none.
    fn search_all(&mut self, plan: &SearchAllPlan, pos: Pos) -> R<Step> {
        let count = i64::from(self.count(&plan.count, pos)?);
        let (mut low, mut high) = (1i64, count);
        while low <= high {
            let mid = (low + high) / 2;
            let dest = self.loc(plan.index)?;
            store::set_integer(&self.facts(), self.unit, dest, mid, pos)?;
            let mut order = Ordering::Equal;
            for key in &plan.keys {
                let o = self.compare(&key.key, &key.value, key.how, pos)?;
                order = if key.ascending { o } else { o.reverse() };
                if order != Ordering::Equal {
                    break;
                }
            }
            match order {
                Ordering::Less => low = mid + 1,
                Ordering::Greater => high = mid - 1,
                Ordering::Equal => return Ok(Step::Arm(0)),
            }
        }
        Ok(Step::Arm(1))
    }
}

impl<'p, L: Loader<Rc<Code>>> Host<PlaceId> for Vm<'p, '_, '_, L> {
    type Facts = Facts<'p>;

    fn facts(&self) -> Facts<'p> {
        Vm::facts(self)
    }

    fn mem(&mut self) -> &mut [u8] {
        &mut self.unit.mem
    }

    fn taint(&mut self) -> Option<&mut crate::taint::Taint> {
        self.unit.taint.as_mut()
    }

    fn locate(&mut self, place: PlaceId, _receiving: bool) -> Result<Loc, Abend> {
        let pos = self.pos(self.p.places[place as usize].at);
        let loc = self.loc(place);
        self.lift(loc, pos)
    }

    fn integer(&mut self, place: PlaceId, pos: Pos) -> Result<i64, Abend> {
        let n = self.int_place(place, pos);
        self.lift(n, pos)
    }

    fn assign(&mut self, dest: Loc, val: Val, src: Option<Loc>, pos: Pos) -> Result<(), Abend> {
        store::assign(&Vm::facts(self), self.unit, dest, val, src, pos)
    }

    fn store_fixed(&mut self, dest: Loc, value: &Fixed, pos: Pos) -> Result<(), Abend> {
        store::store_fixed(&Vm::facts(self), self.unit, dest, value, false, pos)
    }
}

impl<L: Loader<Rc<Code>>> Values<PlaceId, Operand> for Vm<'_, '_, '_, L> {
    fn value(&mut self, operand: &Operand, pos: Pos) -> Result<Val, Abend> {
        let val = Vm::value(self, *operand);
        self.lift(val, pos)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lir::Image;

    #[test]
    fn only_varying_from_moves_without_the_sender_s_storage() {
        let zoned = Kind::Zoned { digits: 3, scale: 0, signed: false, sign: None };
        let packed = Kind::Packed { digits: 5, scale: 0, signed: true };
        let store = StorePlan::Packed { digits: 5, scale: 0, signed: true };
        let bytes = MovePlan::Alnum { image: Image::Bytes, justified: false };
        assert!(sender_kept(Kind::Group, packed, &bytes));
        assert!(!sender_kept(Kind::Group, packed, &MovePlan::Numeric { from: NumericFrom::Zoned, store }));
        assert!(sender_kept(packed, packed, &MovePlan::Numeric { from: NumericFrom::PackedCopy, store }));
        assert!(!sender_kept(packed, packed, &MovePlan::Numeric { from: NumericFrom::Value, store }));
        assert!(sender_kept(zoned, packed, &MovePlan::Numeric { from: NumericFrom::Value, store }));
        assert!(sender_kept(Kind::Group, Kind::Alnum { justified: false }, &bytes));
    }
}