1mod 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#[derive(Clone, Debug, PartialEq, Eq)]
49pub enum LowerError {
50 Unsupported(&'static str, Pos),
52 Exceeds(&'static str, Pos),
54 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
94fn 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
105pub 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
162struct 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 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 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 entries: Vec<BlockId>,
192 sentences: HashMap<(usize, usize), BlockId>,
194 entry_blocks: HashMap<(usize, usize), BlockId>,
196 altered: BTreeSet<usize>,
198 segments: bool,
201 debugging: bool,
203 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 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 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 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 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
357fn 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
372fn 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
380fn 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}