Skip to main content

ironwork_compile/lower/
mod.rs

1//! Lowering (docs/lir.md): a compiled program with every name resolved, every category decided and
2//! every transfer of control made explicit, as the LIR a VM runs and a load module holds.
3//!
4//! Lowered so far: storage, places, expressions and conditions, the arithmetic verbs, MOVE, IF,
5//! EVALUATE, DISPLAY, INITIALIZE, PERFORM, GO TO, GO TO DEPENDING ON, ALTER, EXIT, STOP RUN, GOBACK,
6//! CALL, CANCEL, ENTRY, INVOKE, SET, STRING, UNSTRING, INSPECT, SEARCH, ACCEPT, the file
7//! statements, intrinsic functions, independent segments, class definitions, USE AFTER
8//! EXCEPTION/ERROR, USE FOR DEBUGGING, JSON and XML GENERATE and PARSE, the EXEC blocks, SORT,
9//! MERGE, RELEASE and RETURN, the Report Writer, user-defined functions, and EXTERNAL and GLOBAL
10//! records, files and declaratives.
11//! Anything else is [`LowerError::Unsupported`], naming the construct.
12
13mod call;
14mod check;
15mod cics;
16mod class;
17mod cond;
18mod data;
19mod file;
20mod flow;
21mod function;
22mod markup;
23mod plans;
24mod report;
25mod scope;
26mod search;
27mod set;
28mod sort;
29mod sql;
30mod text;
31mod user_function;
32mod verify;
33
34
35pub use verify::verify;
36
37use crate::Compiled;
38use crate::layout::{Layout, Resolved};
39use rt::abend::AbendCode;
40use rt::lir::{self, AbendId, BlockId, ConstId, DebugId, PlaceId, RangeId, SymId};
41use std::collections::{BTreeSet, HashMap};
42use std::fmt;
43use syntax::Pos;
44use syntax::ast;
45use zarch::ebcdic::CodePage;
46
47/// Why a program does not lower.
48#[derive(Clone, Debug, PartialEq, Eq)]
49pub enum LowerError {
50    /// A construct this slice does not lower yet, and where the program uses it.
51    Unsupported(&'static str, Pos),
52    /// A table larger than the LIR's ids can index.
53    Exceeds(&'static str, Pos),
54    /// The lowered program fails [`verify`], which is a fault in lowering.
55    Invalid(String),
56}
57
58impl LowerError {
59    pub fn pos(&self) -> Pos {
60        match self {
61            Self::Unsupported(_, pos) | Self::Exceeds(_, pos) => *pos,
62            Self::Invalid(_) => Pos::default(),
63        }
64    }
65}
66
67impl fmt::Display for LowerError {
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        match self {
70            Self::Unsupported(what, _) => write!(f, "lowering: {what} is not lowered yet"),
71            Self::Exceeds(what, _) => write!(f, "lowering: {what} exceeds the LIR's limit"),
72            Self::Invalid(why) => write!(f, "lowering: the lowered program is invalid: {why}"),
73        }
74    }
75}
76
77impl From<LowerError> for syntax::Error {
78    fn from(e: LowerError) -> Self {
79        let message = match e {
80            LowerError::Unsupported(..) => syntax::messages::IWR0052,
81            LowerError::Exceeds(..) => syntax::messages::IWL0001,
82            LowerError::Invalid(_) => syntax::messages::IWL0002,
83        };
84        message.at(e.pos(), e.to_string())
85    }
86}
87
88type R<T> = Result<T, LowerError>;
89
90fn unsupported<T>(what: &'static str, pos: Pos) -> R<T> {
91    Err(LowerError::Unsupported(what, pos))
92}
93
94/// The next index of a table, refused past `u32`.
95fn next_id<T>(table: &[T], what: &'static str) -> R<u32> {
96    u32::try_from(table.len()).map_err(|_| LowerError::Exceeds(what, Pos::default()))
97}
98
99fn push<T>(table: &mut Vec<T>, value: T, what: &'static str) -> R<u32> {
100    let id = next_id(table, what)?;
101    table.push(value);
102    Ok(id)
103}
104
105/// Lowers one compiled program, or a class definition with its data and methods. One that passes
106/// Check and uses only the constructs lowered so far lowers.
107pub fn lower(compiled: &Compiled) -> Result<lir::Program, LowerError> {
108    let mut l = Lower::new(compiled);
109    let id = l.sym(&compiled.program.id);
110    let sources = compiled.program.sources.iter().map(|s| l.sym(s)).collect();
111    let storage = l.storage()?;
112    let items = l.items()?;
113    l.services.files = l.files()?;
114    l.services.declaratives = l.declaratives()?;
115    l.services.scope = l.scope()?;
116    l.services.report = l.report_writer()?;
117    (l.sql, l.services.sqlca) = l.sql_table()?;
118    let paragraphs = l.procedure()?;
119    l.unresolved_statuses()?;
120    l.services.entries = l.entry_points()?;
121    l.services.class = l.class_definition()?;
122    l.services.function = l.function_definition()?;
123    let procedure_start = compiled.program.report_writer.procedure_start.min(compiled.program.paragraphs.len());
124    let (blocks, debug) = l.blocks.finish()?;
125    let program = lir::Program {
126        id,
127        options: lir::ProgramOptions {
128            options: compiled.options,
129            ssrange: compiled.ssrange,
130            cards: compiled.program.options.clone(),
131            collating: collating(&compiled.collating),
132            decimal_point_comma: compiled.program.environment.decimal_point_comma,
133            numval_currency: crate::statements::numval_currency(&compiled.program.environment.currency),
134            when_compiled: l.plans.function.iter().any(|f| f.func == lir::Func::WhenCompiled).then_some(compiled.when_compiled),
135        },
136        initial: compiled.program.initial,
137        recursive: compiled.program.recursive,
138        storage,
139        items,
140        paragraphs,
141        procedure_start: procedure_start as u32,
142        ranges: l.ranges,
143        blocks,
144        places: l.places,
145        exprs: l.exprs,
146        conds: l.conds,
147        consts: l.consts,
148        plans: l.plans,
149        services: l.services,
150        sql: l.sql,
151        abends: l.abends,
152        edits: edits(&compiled.layout)?,
153        symbols: l.symbols,
154        debug: lir::Debug { sources, positions: l.positions, ops: debug.ops, statements: debug.statements },
155    };
156    if cfg!(debug_assertions) {
157        verify(&program).map_err(LowerError::Invalid)?;
158    }
159    Ok(program)
160}
161
162/// The tables a program lowers into, each interned where equal entries may be shared.
163struct Lower<'c> {
164    c: &'c Compiled,
165    layout: &'c Layout,
166    program: &'c ast::Program,
167    page: &'static CodePage,
168    symbols: Vec<String>,
169    symbol_ids: HashMap<String, SymId>,
170    positions: Vec<Pos>,
171    position_ids: HashMap<(u16, u32, u32), DebugId>,
172    places: Vec<lir::Place>,
173    /// The layout item each place names, None for RETURN-CODE the program does not declare.
174    place_items: Vec<Option<usize>>,
175    place_ids: HashMap<String, PlaceId>,
176    exprs: Vec<lir::Expr>,
177    conds: Vec<lir::Cond>,
178    consts: Vec<lir::Const>,
179    const_ids: HashMap<String, ConstId>,
180    abends: Vec<lir::AbendText>,
181    abend_ids: HashMap<String, AbendId>,
182    plans: lir::Plans,
183    services: lir::Services,
184    /// Every EXEC SQL block's entry, by ordinal.
185    sql: Vec<lir::SqlEntry>,
186    ranges: Vec<lir::Range>,
187    range_ids: HashMap<(u32, u32, lir::RangeKind), RangeId>,
188    blocks: flow::Blocks,
189    temps: u16,
190    /// Each paragraph's entry block.
191    entries: Vec<BlockId>,
192    /// The block that starts statement k of paragraph p, after a separator period.
193    sentences: HashMap<(usize, usize), BlockId>,
194    /// The block that starts statement k of paragraph p, after an ENTRY statement.
195    entry_blocks: HashMap<(usize, usize), BlockId>,
196    /// The paragraphs an ALTER names.
197    altered: BTreeSet<usize>,
198    /// Whether an ALTER names a paragraph of an independent segment, which makes the segment
199    /// control reaches observable.
200    segments: bool,
201    /// Under the DEBUG option, whether a debugging section serves a paragraph.
202    debugging: bool,
203    /// The arithmetic of the expression being lowered, which its functions' argument expressions
204    /// take part in.
205    within: data::Within,
206}
207
208impl<'c> Lower<'c> {
209    fn new(c: &'c Compiled) -> Self {
210        Self {
211            c,
212            layout: &c.layout,
213            program: &c.program,
214            page: c.options.code_page(),
215            symbols: Vec::new(),
216            symbol_ids: HashMap::new(),
217            positions: Vec::new(),
218            position_ids: HashMap::new(),
219            places: Vec::new(),
220            place_items: Vec::new(),
221            place_ids: HashMap::new(),
222            exprs: Vec::new(),
223            conds: Vec::new(),
224            consts: Vec::new(),
225            const_ids: HashMap::new(),
226            abends: Vec::new(),
227            abend_ids: HashMap::new(),
228            plans: lir::Plans::default(),
229            services: lir::Services::default(),
230            sql: Vec::new(),
231            ranges: Vec::new(),
232            range_ids: HashMap::new(),
233            blocks: flow::Blocks::default(),
234            temps: 0,
235            entries: Vec::new(),
236            sentences: HashMap::new(),
237            entry_blocks: HashMap::new(),
238            altered: BTreeSet::new(),
239            segments: false,
240            debugging: !c.declaratives.triggers.is_empty(),
241            within: data::Within::Own,
242        }
243    }
244
245    fn sym(&mut self, text: &str) -> SymId {
246        if let Some(&id) = self.symbol_ids.get(text) {
247            return id;
248        }
249        let id = self.symbols.len() as SymId;
250        self.symbols.push(text.to_owned());
251        self.symbol_ids.insert(text.to_owned(), id);
252        id
253    }
254
255    fn at(&mut self, pos: Pos) -> DebugId {
256        let key = (pos.file, pos.line, pos.col);
257        if let Some(&id) = self.position_ids.get(&key) {
258            return id;
259        }
260        let id = self.positions.len() as DebugId;
261        self.positions.push(pos);
262        self.position_ids.insert(key, id);
263        id
264    }
265
266    /// An abend's text, with a position of its own only where no op gives one.
267    fn abend(&mut self, code: AbendCode, message: &str, pos: Option<Pos>) -> R<AbendId> {
268        let at = pos.map(|p| self.at(p));
269        let key = format!("{code:?}{at:?}{message}");
270        if let Some(&id) = self.abend_ids.get(&key) {
271            return Ok(id);
272        }
273        let text = lir::AbendText { code, message: self.sym(message), at };
274        let id = push(&mut self.abends, text, "abend messages")?;
275        self.abend_ids.insert(key, id);
276        Ok(id)
277    }
278
279    fn ironwork(&mut self, message: &str) -> R<AbendId> {
280        self.abend(AbendCode::Ironwork, message, None)
281    }
282
283    /// The slab and LOCAL-STORAGE as VALUE initialization leaves them on a first activation, with
284    /// what it reported and any abend.
285    fn storage(&mut self) -> R<lir::Storage> {
286        let layout = self.layout;
287        let initial = crate::values::initial(self.c);
288        let init_reports = initial.reports.iter().map(|l| self.sym(l)).collect();
289        let init_abend = match initial.abend {
290            Some(a) => Some(self.abend(a.code.clone(), &a.message, Some(a.pos))?),
291            None => None,
292        };
293        let root = |name: &str| layout.linkage_roots.iter().position(|&i| layout.items[i].name.as_deref() == Some(name));
294        let mut using = Vec::new();
295        // BY VALUE or BY REFERENCE is the caller's to honour, for the walker as for the VM.
296        for ast::Param { by_value: _, name } in &self.program.using {
297            match root(name).map(u16::try_from) {
298                Some(Ok(ordinal)) => using.push(ordinal),
299                Some(Err(_)) => return Err(LowerError::Exceeds("LINKAGE records", Pos::default())),
300                None => return unsupported("PROCEDURE DIVISION USING an item that is not a LINKAGE record", Pos::default()),
301            }
302        }
303        let returning = match &self.program.returning {
304            None => None,
305            Some(name) => match root(name).map(u16::try_from) {
306                Some(Ok(ordinal)) => Some(ordinal),
307                Some(Err(_)) => return Err(LowerError::Exceeds("LINKAGE records", Pos::default())),
308                None => return unsupported("RETURNING an item that is not a LINKAGE record", Pos::default()),
309            },
310        };
311        Ok(lir::Storage {
312            size: layout.size,
313            image: initial.image,
314            local_image: initial.local_image,
315            init_reports,
316            init_abend,
317            linkage: layout.linkage_roots.iter().map(|&i| layout.items[i].size).collect(),
318            using,
319            returning,
320            file_areas: layout.file_areas.clone(),
321            parmcheck: layout.parmcheck,
322        })
323    }
324
325    /// The layout's items for `dump`, with DEPENDING ON objects and keys as item indices.
326    fn items(&mut self) -> R<Vec<lir::Item>> {
327        let layout = self.layout;
328        let mut items = Vec::with_capacity(layout.items.len());
329        for item in &layout.items {
330            let item_of = |r: &ast::Ref| match layout.resolve(&r.name, &r.qualifiers, r.pos) {
331                Ok(Resolved::Item(i)) => Ok(i as u32),
332                _ => unsupported("an OCCURS DEPENDING ON or KEY that names no data item", r.pos),
333            };
334            let depending_on = item.depending_on.as_ref().map(item_of).transpose()?;
335            let keys = item.keys.iter().map(|(ascending, r)| item_of(r).map(|i| (*ascending, i))).collect::<R<_>>()?;
336            items.push(lir::Item {
337                name: item.name.as_deref().map(|n| self.sym(n)),
338                level: item.level,
339                parent: item.parent.map(|p| p as u32),
340                offset: item.offset,
341                size: item.size,
342                occurs: item.occurs,
343                dims: item.dims.clone(),
344                kind: item.kind,
345                local: item.local,
346                linkage: item.linkage,
347                redefines: item.redefines.as_deref().map(|n| self.sym(n)),
348                depending_on,
349                keys,
350                at: self.at(item.pos),
351            });
352        }
353        Ok(items)
354    }
355}
356
357/// The program's sequence, from what `collating::Sequence` exposes: each byte's position, the
358/// character FUNCTION CHAR gives for each position, and HIGH-VALUE and LOW-VALUE.
359fn collating(sequence: &crate::collating::Sequence) -> lir::Collating {
360    if sequence.is_native() {
361        return lir::Collating::Native;
362    }
363    let characters = (1..=sequence.count() as i64).filter_map(|k| sequence.character(k)).collect();
364    lir::Collating::Sequence(lir::Sequence {
365        positions: Box::new(sequence.positions()),
366        characters,
367        high_value: sequence.high_value,
368        low_value: sequence.low_value,
369    })
370}
371
372/// Each edited PICTURE with the currency sign value it shows.
373fn edits(layout: &Layout) -> R<Vec<lir::Edit>> {
374    if layout.edits.len() != layout.currencies.len() {
375        return Err(LowerError::Invalid(format!("{} edited PICTUREs with {} currency values", layout.edits.len(), layout.currencies.len())));
376    }
377    Ok(layout.edits.iter().zip(&layout.currencies).map(|(syms, currency)| lir::Edit { syms: syms.clone(), currency: currency.clone() }).collect())
378}
379
380/// Whether the place cannot abend when evaluated: a slab, LOCAL-STORAGE or RETURN-CODE base and a
381/// constant offset and length.
382fn is_static(place: &lir::Place) -> bool {
383    matches!(place.base, lir::Base::Program | lir::Base::Local | lir::Base::ReturnCode) && place.moved.is_empty() && place.subscripts.is_empty() && place.odo.is_empty() && place.refmod.is_none()
384}