Skip to main content

ironwork_compile/
oo.rs

1//! Object-oriented COBOL, compiled and checked. A class written in COBOL becomes code the
2//! interpreter runs within the run unit: each method is compiled as a program whose LINKAGE SECTION
3//! ends with the records of the OBJECT or FACTORY WORKING-STORAGE it works on, and each
4//! INVOKE finds its method by name and Java signature, as the JNI does. Running is in `rt::oo`;
5//! a Java class is checked here and never run.
6
7use crate::layout::{Kind, Layout, Resolved};
8use crate::{Check, Compiled};
9use numeric::Options;
10use rt::lir::CompileTime;
11use numeric::assumptions::{INITIAL_UNDER_THREAD, OO_OPTIONS_REQUIRED, OO_OPTIONS_SEVERITY};
12use std::collections::HashSet;
13use std::rc::Rc;
14use syntax::ast::*;
15use syntax::{Error, Pos};
16
17pub use rt::oo::JAVA_LANG_OBJECT;
18
19/// A COBOL class, compiled.
20pub type ClassCode = rt::oo::ClassCode<Rc<Compiled>>;
21/// FACTORY or OBJECT WORKING-STORAGE, laid out as a program's, and where each record starts in it.
22pub type Part = rt::oo::Part<Rc<Compiled>>;
23pub type MethodCode = rt::oo::MethodCode<Rc<Compiled>>;
24
25/// A class definition's source compiles when each of its methods does.
26pub(crate) fn compile_class_definition(program: Program, flags: &[String], at: CompileTime) -> Result<Compiled, Vec<Error>> {
27    let mut shell = program.clone();
28    shell.oo = None;
29    let mut compiled = crate::compile_program(shell, flags, false, at)?;
30    let (_, diagnostics) = class_code(&program, flags, at)?;
31    compiled.diagnostics.extend(diagnostics);
32    compiled.program = program;
33    Ok(compiled)
34}
35
36/// A class definition, INVOKE or an object reference; the JNI reached through JNIENVPTR alone is
37/// not object-oriented syntax.
38fn object_oriented(program: &Program) -> bool {
39    let files = program.files.iter().flat_map(|f| f.records.iter());
40    let mut data = program.working_storage.iter().chain(&program.local_storage).chain(&program.linkage).chain(files);
41    let mut invoke = false;
42    for p in &program.paragraphs {
43        each(&p.statements, &mut |s| invoke |= matches!(s, Stmt::Invoke(_)));
44    }
45    program.oo.as_deref().is_some_and(|o| o.class().is_some()) || invoke || data.any(|e| e.usage == Some(Usage::ObjectReference))
46}
47
48/// IBM's rules for the options a program is compiled with (see [`OO_OPTIONS_REQUIRED`]): object-
49/// oriented syntax needs THREAD, DLL, RENT and DBCS, NORENT conflicts with THREAD and DLL, INITIAL
50/// with THREAD, and under THREAD a program is RECURSIVE, not INITIAL, contains no program, and
51/// SORTs or MERGEs no file. A method answers only for its statements; its class answers for the
52/// options. A missing option and the two conflicts are warnings, the rest errors (see
53/// [`OO_OPTIONS_SEVERITY`] and [`INITIAL_UNDER_THREAD`]).
54pub(crate) fn option_rules(program: &Program, options: &Options, errors: &mut Vec<Error>) {
55    let oo = program.oo.as_deref();
56    let method = oo.and_then(Oo::method).is_some();
57    let who = match oo.and_then(Oo::class) {
58        Some(c) => format!("class {}", c.name),
59        None => format!("program {}", program.id),
60    };
61    if !method {
62        let forcing: Vec<&str> = [(options.thread, "THREAD"), (options.dll, "DLL")].into_iter().filter(|(on, _)| *on).map(|(_, o)| o).collect();
63        if !options.rent && !forcing.is_empty() {
64            errors.push(Error::warning(Pos::default(), format!("NORENT conflicts with {}, which IBM compiles only as RENT (see {OO_OPTIONS_REQUIRED})", forcing.join(" and "))));
65        }
66        if object_oriented(program) {
67            let missing: Vec<&str> = [(options.thread, "THREAD"), (options.dll, "DLL"), (options.rent || !forcing.is_empty(), "RENT"), (options.dbcs, "DBCS")]
68                .into_iter()
69                .filter(|(on, _)| !*on)
70                .map(|(_, o)| o)
71                .collect();
72            if !missing.is_empty() {
73                errors.push(Error::warning(
74                    Pos::default(),
75                    format!(
76                        "{who} uses object-oriented syntax, which IBM compiles only with THREAD, DLL, RENT and DBCS: {} missing from its CBL or PROCESS cards (see {OO_OPTIONS_REQUIRED} and {OO_OPTIONS_SEVERITY})",
77                        missing.join(", ")
78                    ),
79                ));
80            }
81        }
82    }
83    if !options.thread {
84        return;
85    }
86    if !method && options.initial {
87        errors.push(Error::warning(Pos::default(), format!("INITIAL conflicts with THREAD, which IBM compiles only as NOINITIAL (see {INITIAL_UNDER_THREAD})")));
88    }
89    if !method && oo.and_then(Oo::class).is_none() {
90        if !program.recursive {
91            errors.push(Error::at(Pos::default(), format!("{who} is compiled with THREAD, which requires RECURSIVE in its PROGRAM-ID paragraph")));
92        }
93        if program.initial {
94            errors.push(Error::at(Pos::default(), format!("{who} is INITIAL, which THREAD does not allow")));
95        }
96        if let Some(inner) = program.nested.first() {
97            errors.push(Error::at(Pos::default(), format!("{who} contains program {inner}, and THREAD does not allow nested programs")));
98        }
99    }
100    for p in &program.paragraphs {
101        each(&p.statements, &mut |s| {
102            if let Stmt::Sorting(so) = s
103                && let Sorting::Sort(st) = &**so
104                && (st.merge || program.files.iter().any(|f| f.name == st.subject.name))
105            {
106                let verb = if st.merge { "MERGE" } else { "SORT of a file" };
107                errors.push(Error::at(st.pos, format!("{verb} is not allowed in a program compiled with THREAD")));
108            }
109        });
110    }
111}
112
113/// The external name a class definition defines.
114pub fn defined_class(program: &Program) -> Option<String> {
115    let oo = program.oo.as_ref()?;
116    let class = oo.class()?;
117    Some(oo.external(&class.name).map_or_else(|| external_class_name(&class.name), str::to_owned))
118}
119
120fn records(entries: &[DataEntry]) -> usize {
121    entries.iter().filter(|e| e.level == 1 || e.level == 77).count()
122}
123
124/// Every name a method declares, which hides a name of its paragraph's data.
125fn declared_names(program: &Program) -> HashSet<String> {
126    let files = program.files.iter().flat_map(|f| f.records.iter());
127    program
128        .working_storage
129        .iter()
130        .chain(&program.local_storage)
131        .chain(&program.linkage)
132        .chain(files)
133        .flat_map(|e| e.name.iter().chain(&e.indexed_by))
134        .cloned()
135        .collect()
136}
137
138/// A class definition's code, compiled at `at`, and the warnings and informational messages it
139/// compiled with.
140pub fn class_code(program: &Program, flags: &[String], at: CompileTime) -> Result<(ClassCode, Vec<Error>), Vec<Error>> {
141    let Some(oo) = program.oo.as_deref() else { return Err(vec![Error::at(Pos::default(), "not a class definition")]) };
142    let Some(def) = oo.class() else { return Err(vec![Error::at(Pos::default(), "not a class definition")]) };
143    let mut errors = Vec::new();
144    let mut options = Options::default();
145    for option in &program.options {
146        options.apply(option).ok();
147    }
148    for flag in flags {
149        options.apply_flag(flag).ok();
150    }
151    option_rules(program, &options, &mut errors);
152    let external = defined_class(program).unwrap_or_default();
153    let parent = match oo.external(&def.inherits) {
154        Some(e) => e.to_owned(),
155        None => {
156            errors.push(Error::at(def.pos, format!("{}: the class a class INHERITS must be named in its REPOSITORY paragraph", def.inherits)));
157            String::new()
158        }
159    };
160    if def.inherits == def.name || parent == external {
161        errors.push(Error::at(def.pos, format!("class {} cannot inherit from itself", def.name)));
162    }
163    let mut base = program.clone();
164    base.oo = None;
165    let mut code = ClassCode { parent, factory: None, object: None, methods: Vec::new() };
166    for (factory, part) in [(true, &def.factory), (false, &def.object)] {
167        let Some(part) = part else { continue };
168        if let Some(e) = part.working_storage.iter().find(|e| !e.indexed_by.is_empty()) {
169            errors.push(Error::at(e.pos, "INDEXED BY in FACTORY or OBJECT data is not supported yet"));
170            continue;
171        }
172        let mut data = base.clone();
173        data.working_storage = part.working_storage.clone();
174        data.oo = Some(Box::new(Oo { repository: oo.repository.clone(), unit: OoUnit::Program }));
175        match crate::compile_program(data, flags, false, at) {
176            Ok(c) => {
177                let offsets = c.layout.items.iter().filter(|i| i.parent.is_none()).take(records(&part.working_storage)).map(|i| i.offset).collect();
178                let compiled = Part { data: Rc::new(c), records: offsets };
179                if factory { code.factory = Some(compiled) } else { code.object = Some(compiled) }
180            }
181            Err(e) => errors.extend(e),
182        }
183        for m in &part.methods {
184            match method_code(program, m, part, factory, flags, at) {
185                Ok(mc) => {
186                    errors.extend(mc.code.diagnostics.iter().cloned());
187                    code.methods.push(mc);
188                }
189                Err(e) => errors.extend(e),
190            }
191        }
192    }
193    for (k, m) in code.methods.iter().enumerate() {
194        if let Some(twin) = code.methods[..k].iter().find(|o| o.name == m.name && o.params == m.params) {
195            let kind = |f: bool| if f { "factory" } else { "instance" };
196            let pos = m.code.program.oo.as_deref().and_then(Oo::method).map_or(def.pos, |m| m.pos);
197            errors.push(Error::at(pos, format!("{} method \"{}\" has the same parameter types as {} method \"{}\"", kind(m.factory), m.name, kind(twin.factory), twin.name)));
198        }
199    }
200    if crate::refused(&errors, &options) { Err(errors) } else { Ok((code, errors)) }
201}
202
203/// A method compiled with its paragraph's data after its own LINKAGE records; a name the method
204/// declares itself hides the paragraph's.
205fn method_code(class: &Program, method: &Program, part: &ClassPart, factory: bool, flags: &[String], at: CompileTime) -> Result<MethodCode, Vec<Error>> {
206    let mut p = method.clone();
207    p.sources = class.sources.clone();
208    p.options = class.options.clone();
209    let own_records = records(&p.linkage);
210    let hidden = declared_names(&p);
211    let hide = |n: &mut String| {
212        if hidden.contains(n) {
213            n.insert(0, ' ');
214        }
215    };
216    for e in &part.working_storage {
217        let mut e = e.clone();
218        e.value = None;
219        e.name.iter_mut().for_each(hide);
220        e.redefines.iter_mut().for_each(hide);
221        e.depending_on.iter_mut().for_each(|r| hide(&mut r.name));
222        p.linkage.push(e);
223    }
224    let pos = method.oo.as_deref().and_then(Oo::method).map_or(part.pos, |m| m.pos);
225    let name = method.id.clone();
226    let compiled = crate::compile_at(p, flags, at)?;
227    let mut errors = Vec::new();
228    let layout = &compiled.layout;
229    let oo = compiled.program.oo.as_deref();
230    let own = |n: &str| layout.linkage_roots.iter().take(own_records).copied().find(|&i| layout.items[i].name.as_deref() == Some(n));
231    let mut params = Vec::new();
232    for param in &compiled.program.using {
233        if !param.by_value {
234            errors.push(Error::at(pos, format!("method \"{name}\" receives {} BY REFERENCE: a method's parameters are BY VALUE", param.name)));
235        }
236        match own(&param.name).map(|i| item_type(layout, oo, i)) {
237            Some(Ok(t)) => params.push(t),
238            Some(Err(m)) => errors.push(Error::at(pos, format!("method \"{name}\" parameter {}: {m}", param.name))),
239            None => errors.push(Error::at(pos, format!("method \"{name}\" parameter {}: not a record of the method's own LINKAGE SECTION", param.name))),
240        }
241    }
242    let mut shared = Vec::new();
243    for paragraph in &compiled.program.paragraphs {
244        each(&paragraph.statements, &mut |s| {
245            if let Stmt::Set { set: SetStmt::AddressOf { targets, .. }, pos } = s {
246                for r in targets {
247                    if let Ok(Resolved::Item(i)) = layout.resolve(&r.name, &r.qualifiers, r.pos)
248                        && layout.items[i].linkage.is_some_and(|l| l as usize >= own_records)
249                    {
250                        shared.push(Error::at(*pos, format!("SET ADDRESS OF {}: FACTORY and OBJECT data is WORKING-STORAGE, not LINKAGE", r.name)));
251                    }
252                }
253            }
254        });
255    }
256    errors.extend(shared);
257    let returns = match &compiled.program.returning {
258        None => None,
259        Some(r) => match own(r).map(|i| item_type(layout, oo, i)) {
260            Some(Ok(t)) => Some(t),
261            Some(Err(m)) => {
262                errors.push(Error::at(pos, format!("method \"{name}\" RETURNING {r}: {m}")));
263                None
264            }
265            None => {
266                errors.push(Error::at(pos, format!("method \"{name}\" RETURNING {r}: not a record of the method's own LINKAGE SECTION")));
267                None
268            }
269        },
270    };
271    if !errors.is_empty() {
272        return Err(errors.into_iter().map(|e| e.in_files(&class.sources)).collect());
273    }
274    Ok(MethodCode { name, factory, params, returns, code: Rc::new(compiled), own_records })
275}
276
277/// The Java type of a class-name's objects, as a JNI signature spells it.
278pub(crate) fn class_type(external: &str) -> String {
279    match external {
280        "jstring" | "java.lang.String" => "Ljava/lang/String;".into(),
281        "jbooleanArray" => "[Z".into(),
282        "jbyteArray" => "[B".into(),
283        "jshortArray" => "[S".into(),
284        "jintArray" => "[I".into(),
285        "jlongArray" => "[J".into(),
286        "jcharArray" => "[C".into(),
287        "jfloatArray" => "[F".into(),
288        "jdoubleArray" => "[D".into(),
289        "jobjectArray" => "[Ljava/lang/Object;".into(),
290        e => match e.strip_prefix("jobjectArray:") {
291            Some(element) => format!("[L{};", element.replace('.', "/")),
292            None => format!("L{};", e.replace('.', "/")),
293        },
294    }
295}
296
297/// A PIC X item with exactly the two condition-names IBM's boolean needs.
298fn boolean(layout: &Layout, item: usize) -> bool {
299    let byte = |l: &Literal| match l {
300        Literal::Hex(b) if b.len() == 1 => Some(b[0]),
301        Literal::Figurative(Figurative::LowValue) => Some(0x00),
302        Literal::Figurative(Figurative::HighValue) => Some(0xFF),
303        _ => None,
304    };
305    let conditions: Vec<_> = layout.conditions.iter().filter(|c| c.item == item).collect();
306    let is = |low: u8, high: Option<u8>| {
307        conditions.iter().any(|c| matches!(c.values.as_slice(), [(l, h)] if byte(l) == Some(low) && h.as_ref().and_then(byte) == high))
308    };
309    conditions.len() == 2 && is(0x00, None) && is(0x01, Some(0xFF))
310}
311
312/// The Java type an item passes as, as a JNI signature spells it; a universal object reference
313/// passes as java.lang.Object.
314pub fn item_type(layout: &Layout, oo: Option<&Oo>, item: usize) -> Result<String, String> {
315    let it = &layout.items[item];
316    Ok(match it.kind {
317        Kind::Alnum { .. } if it.size == 1 => (if boolean(layout, item) { "Z" } else { "B" }).into(),
318        Kind::Binary { digits, scale: 0, signed: true, .. } => (match digits {
319            1..=4 => "S",
320            5..=9 => "I",
321            _ => "J",
322        })
323        .into(),
324        Kind::Float(zarch::hfp::Precision::Short) => "F".into(),
325        Kind::Float(_) => "D".into(),
326        Kind::National if it.size == 2 => "C".into(),
327        Kind::ObjectReference => match &it.object_class {
328            None => format!("L{};", JAVA_LANG_OBJECT.replace('.', "/")),
329            Some(c) => class_type(oo.and_then(|o| o.external(c)).ok_or_else(|| format!("class {c} is not named in the REPOSITORY paragraph"))?),
330        },
331        _ => return Err("not a type Java shares with COBOL: PIC X for byte or boolean, a signed binary integer, COMP-1, COMP-2, PIC N for char, or an object reference".into()),
332    })
333}
334
335/// The Java type of an INVOKE argument: an item, a one-character reference modification, LENGTH OF,
336/// or one of the literals IBM lists.
337pub fn operand_type(layout: &Layout, oo: Option<&Oo>, op: &Operand) -> Result<String, String> {
338    match op {
339        Operand::Ref(r) => {
340            let Ok(Resolved::Item(i)) = layout.resolve(&r.name, &r.qualifiers, r.pos) else { return Err(format!("{} is not a data item", r.name)) };
341            match &r.refmod {
342                None => item_type(layout, oo, i),
343                Some(_) if layout.items[i].kind == Kind::National => Err("a reference-modified national argument is not supported yet".into()),
344                Some(rm) if matches!(rm.length.as_deref(), Some(Expr::Operand(Operand::Literal(Literal::Number(n)))) if n == "1") => Ok("C".into()),
345                Some(_) => Err("a reference-modified argument must be one character long".into()),
346            }
347        }
348        Operand::LengthOf(_) => Ok("I".into()),
349        Operand::Literal(Literal::Number(t)) if !t.contains('.') && t.trim_start_matches(['+', '-']).len() <= 9 => Ok("I".into()),
350        Operand::Literal(Literal::Figurative(Figurative::Zero)) => Ok("I".into()),
351        Operand::Literal(Literal::Figurative(Figurative::Space | Figurative::Quote | Figurative::HighValue | Figurative::LowValue)) => Ok("B".into()),
352        Operand::Literal(Literal::Alnum(s)) if s.chars().count() == 1 => Ok("B".into()),
353        Operand::Literal(Literal::National(s)) if s.chars().count() == 1 => Ok("C".into()),
354        _ => Err("not an argument Java takes: an item of a type Java shares, LENGTH OF, an integer literal of up to nine digits, or a one-character literal".into()),
355    }
356}
357
358fn is_named(r: &Ref, name: &str) -> bool {
359    r.name == name && r.qualifiers.is_empty() && r.subscripts.is_empty() && r.refmod.is_none()
360}
361
362/// SELF and JNIENVPTR, which are not data items of the program.
363pub(crate) fn special_register(layout: &Layout, r: &Ref) -> bool {
364    (is_named(r, "SELF") || is_named(r, "JNIENVPTR")) && layout.resolve(&r.name, &r.qualifiers, r.pos).is_err()
365}
366
367/// A class-name of the REPOSITORY used where a data item could also be named.
368fn class_name<'o>(layout: &Layout, oo: Option<&'o Oo>, r: &Ref) -> Option<&'o str> {
369    let external = oo?.external(&r.name)?;
370    (r.qualifiers.is_empty() && r.subscripts.is_empty() && r.refmod.is_none() && layout.resolve(&r.name, &r.qualifiers, r.pos).is_err()).then_some(external)
371}
372
373impl Check<'_> {
374    pub(crate) fn invoke(&mut self, i: &Invoke) {
375        let oo = self.program.oo.as_deref();
376        let in_method = oo.and_then(Oo::method).is_some();
377        let err = |m: String| Error::at(i.pos, m);
378        let special = is_named(&i.target, "SELF") || is_named(&i.target, "SUPER");
379        let class = class_name(self.layout, oo, &i.target).is_some();
380        let mut typed = false;
381        if special && self.layout.resolve(&i.target.name, &[], i.pos).is_err() {
382            if !in_method {
383                self.errors.push(err(format!("INVOKE {}: SELF and SUPER can be used only in a method", i.target.name)));
384            }
385        } else if !class {
386            self.reference(&i.target);
387            match self.layout.resolve(&i.target.name, &i.target.qualifiers, i.target.pos) {
388                Ok(Resolved::Item(k)) if self.layout.items[k].kind == Kind::ObjectReference => typed = self.layout.items[k].object_class.is_some(),
389                Ok(_) => self.errors.push(err(format!("INVOKE {}: not an object reference or a class named in the REPOSITORY paragraph", i.target.name))),
390                Err(_) => {}
391            }
392        }
393        match &i.method {
394            InvokeMethod::New => {
395                if !class {
396                    self.errors.push(err(format!("INVOKE {} NEW: NEW takes a class-name from the REPOSITORY paragraph", i.target.name)));
397                }
398                match &i.returning {
399                    None => self.errors.push(err("INVOKE ... NEW needs RETURNING an object reference".into())),
400                    Some(r) if !matches!(self.layout.resolve(&r.name, &r.qualifiers, r.pos), Ok(Resolved::Item(k)) if self.layout.items[k].kind == Kind::ObjectReference) => {
401                        self.errors.push(err(format!("INVOKE ... NEW RETURNING {}: not an object reference", r.name)));
402                    }
403                    Some(_) => {}
404                }
405            }
406            InvokeMethod::Named(name) if name.is_empty() => self.errors.push(err("INVOKE with an empty method name".into())),
407            InvokeMethod::Named(_) => {}
408            InvokeMethod::Identifier(r) => {
409                self.reference(r);
410                if let Ok(Resolved::Item(k)) = self.layout.resolve(&r.name, &r.qualifiers, r.pos)
411                    && !matches!(self.layout.items[k].kind, Kind::Alnum { .. } | Kind::National | Kind::Group)
412                {
413                    self.errors.push(err(format!("INVOKE ... {}: a method name is held in an alphanumeric or national item", r.name)));
414                }
415                if typed {
416                    self.errors.push(err(format!("INVOKE {} {}: a method named by a data item is invoked on a universal object reference", i.target.name, r.name)));
417                }
418            }
419        }
420        for op in &i.using {
421            self.operand(op);
422            if let Err(m) = operand_type(self.layout, oo, op) {
423                self.errors.push(err(format!("INVOKE argument: {m}")));
424            }
425        }
426        if let Some(r) = &i.returning {
427            self.reference(r);
428            if r.refmod.is_some() {
429                self.errors.push(err(format!("INVOKE ... RETURNING {}: not reference-modified", r.name)));
430            }
431            if let (false, Ok(Resolved::Item(k))) = (i.method == InvokeMethod::New, self.layout.resolve(&r.name, &r.qualifiers, r.pos))
432                && let Err(m) = item_type(self.layout, oo, k)
433            {
434                self.errors.push(err(format!("INVOKE ... RETURNING {}: {m}", r.name)));
435            }
436        }
437        self.statements(i.on_exception.as_deref().unwrap_or_default());
438        self.statements(i.not_on_exception.as_deref().unwrap_or_default());
439    }
440}
441
442#[derive(Clone, Copy, PartialEq, Eq)]
443enum Side {
444    Object,
445    ProgramPointer,
446    Null,
447    Other,
448}
449
450/// The rules for object references, SELF, EXIT METHOD and the rest of the object-oriented syntax,
451/// over a program or method that has otherwise checked.
452struct Rules<'a> {
453    layout: &'a Layout,
454    method: bool,
455    uses_oo: bool,
456    errors: &'a mut Vec<Error>,
457}
458
459pub(crate) fn check(layout: &Layout, program: &Program, errors: &mut Vec<Error>) {
460    let oo = program.oo.as_deref();
461    let method = oo.and_then(Oo::method).is_some();
462    let mut rules = Rules { layout, method, uses_oo: oo.is_some_and(|o| !o.repository.is_empty()), errors };
463    for item in &layout.items {
464        if item.kind == Kind::ObjectReference {
465            rules.uses_oo = true;
466        }
467        if let Some(c) = &item.object_class
468            && oo.and_then(|o| o.external(c)).is_none()
469        {
470            rules.errors.push(Error::at(item.pos, format!("OBJECT REFERENCE {c}: the class must be named in the REPOSITORY paragraph")));
471        }
472    }
473    if method && let Some(f) = program.files.first() {
474        rules.errors.push(Error::at(f.pos, "a method's FILE SECTION can define only EXTERNAL files, which ironwork for COBOL does not support yet"));
475    }
476    for p in &program.paragraphs {
477        rules.statements(&p.statements);
478    }
479    // The Report Writer precompiler's code MOVEs each CONTROL and SOURCE item.
480    for report in &program.report_writer.reports {
481        report.controls.iter().for_each(|c| rules.plain(&Operand::Ref(c.clone()), c.pos));
482        for e in report.groups.iter().flat_map(|g| &g.entries) {
483            if let Some(syntax::report::Content::Source(x)) = &e.content {
484                rules.expr(x, e.pos);
485            }
486        }
487    }
488    let exec = program.exec_declarations.iter().map(|b| (b.kind, b.pos)).chain(execs(&program.paragraphs));
489    for (kind, pos) in exec {
490        if method {
491            rules.errors.push(Error::at(pos, "a class definition cannot contain EXEC statements"));
492        } else if kind == ExecKind::Cics && rules.uses_oo {
493            rules.errors.push(Error::at(pos, "a program that uses object-oriented syntax cannot contain EXEC CICS"));
494        }
495    }
496}
497
498fn execs(paragraphs: &[Paragraph]) -> Vec<(ExecKind, Pos)> {
499    let mut out = Vec::new();
500    for p in paragraphs {
501        each(&p.statements, &mut |s| {
502            if let Stmt::Exec(b) = s {
503                out.push((b.kind, b.pos));
504            }
505        });
506    }
507    out
508}
509
510/// Every statement, and every statement nested in it.
511fn each(stmts: &[Stmt], f: &mut dyn FnMut(&Stmt)) {
512    for s in stmts {
513        f(s);
514        for body in bodies(s) {
515            each(body, f);
516        }
517    }
518}
519
520/// [`each`], to change.
521pub fn each_mut(stmts: &mut [Stmt], f: &mut dyn FnMut(&mut Stmt)) {
522    for s in stmts {
523        f(s);
524        for body in bodies_mut(s) {
525            each_mut(body, f);
526        }
527    }
528}
529
530fn opt(o: &Option<Vec<Stmt>>) -> &[Stmt] {
531    o.as_deref().unwrap_or_default()
532}
533
534fn handlers(h: &Handlers) -> [&[Stmt]; 2] {
535    [opt(&h.on), opt(&h.not_on)]
536}
537
538pub fn bodies(s: &Stmt) -> Vec<&[Stmt]> {
539    match s {
540        Stmt::If { then, otherwise, .. } => vec![then, otherwise],
541        Stmt::PerformInline { body, .. } => vec![body],
542        Stmt::Evaluate { whens, other, .. } => whens.iter().map(|w| w.body.as_slice()).chain([other.as_slice()]).collect(),
543        Stmt::Compute { size_error: Some(se), .. } => vec![&se.on, &se.not_on],
544        Stmt::Arith(a) => a.size_error.iter().flat_map(|se| [se.on.as_slice(), se.not_on.as_slice()]).collect(),
545        Stmt::Corresponding(c) => c.size_error.iter().flat_map(|se| [se.on.as_slice(), se.not_on.as_slice()]).collect(),
546        Stmt::Read(r) => handlers(&r.at_end).into_iter().chain(handlers(&r.invalid)).collect(),
547        Stmt::Write { invalid, end_of_page, .. } => handlers(invalid).into_iter().chain(handlers(end_of_page)).collect(),
548        Stmt::Rewrite { invalid, .. } | Stmt::Delete { invalid, .. } | Stmt::Start { invalid, .. } => handlers(invalid).to_vec(),
549        Stmt::Call(c) => vec![opt(&c.on_exception), opt(&c.not_on_exception)],
550        Stmt::Invoke(i) => vec![opt(&i.on_exception), opt(&i.not_on_exception)],
551        Stmt::JsonGenerate(g) => vec![opt(&g.on_exception), opt(&g.not_on_exception)],
552        Stmt::JsonParse(j) => vec![opt(&j.on_exception), opt(&j.not_on_exception)],
553        Stmt::XmlParse(x) => vec![opt(&x.on_exception), opt(&x.not_on_exception)],
554        Stmt::XmlGenerate(x) => vec![opt(&x.on_exception), opt(&x.not_on_exception)],
555        Stmt::String(st) => vec![opt(&st.on_overflow), opt(&st.not_on_overflow)],
556        Stmt::Unstring(u) => vec![opt(&u.on_overflow), opt(&u.not_on_overflow)],
557        Stmt::Search(se) => se.whens.iter().map(|(_, b)| b.as_slice()).chain([opt(&se.at_end)]).collect(),
558        Stmt::Sorting(so) => match &**so {
559            Sorting::Return { at_end, .. } => handlers(at_end).to_vec(),
560            _ => Vec::new(),
561        },
562        _ => Vec::new(),
563    }
564}
565
566/// The statement lists [`bodies`] gives, those that are present, to change.
567pub fn bodies_mut(s: &mut Stmt) -> Vec<&mut Vec<Stmt>> {
568    fn handlers(h: &mut Handlers) -> impl Iterator<Item = &mut Vec<Stmt>> {
569        h.on.iter_mut().chain(h.not_on.iter_mut())
570    }
571    fn pair<'s>(a: &'s mut Option<Vec<Stmt>>, b: &'s mut Option<Vec<Stmt>>) -> Vec<&'s mut Vec<Stmt>> {
572        a.iter_mut().chain(b.iter_mut()).collect()
573    }
574    match s {
575        Stmt::If { then, otherwise, .. } => vec![then, otherwise],
576        Stmt::PerformInline { body, .. } => vec![body],
577        Stmt::Evaluate { whens, other, .. } => whens.iter_mut().map(|w| &mut w.body).chain([other]).collect(),
578        Stmt::Compute { size_error: Some(se), .. } => vec![&mut se.on, &mut se.not_on],
579        Stmt::Arith(a) => a.size_error.iter_mut().flat_map(|se| [&mut se.on, &mut se.not_on]).collect(),
580        Stmt::Corresponding(c) => c.size_error.iter_mut().flat_map(|se| [&mut se.on, &mut se.not_on]).collect(),
581        Stmt::Read(r) => handlers(&mut r.at_end).chain(handlers(&mut r.invalid)).collect(),
582        Stmt::Write { invalid, end_of_page, .. } => handlers(invalid).chain(handlers(end_of_page)).collect(),
583        Stmt::Rewrite { invalid, .. } | Stmt::Delete { invalid, .. } | Stmt::Start { invalid, .. } => handlers(invalid).collect(),
584        Stmt::Call(c) => pair(&mut c.on_exception, &mut c.not_on_exception),
585        Stmt::Invoke(i) => pair(&mut i.on_exception, &mut i.not_on_exception),
586        Stmt::JsonGenerate(g) => pair(&mut g.on_exception, &mut g.not_on_exception),
587        Stmt::JsonParse(j) => pair(&mut j.on_exception, &mut j.not_on_exception),
588        Stmt::XmlParse(x) => pair(&mut x.on_exception, &mut x.not_on_exception),
589        Stmt::XmlGenerate(x) => pair(&mut x.on_exception, &mut x.not_on_exception),
590        Stmt::String(st) => pair(&mut st.on_overflow, &mut st.not_on_overflow),
591        Stmt::Unstring(u) => pair(&mut u.on_overflow, &mut u.not_on_overflow),
592        Stmt::Search(se) => se.whens.iter_mut().map(|(_, b)| b).chain(se.at_end.iter_mut()).collect(),
593        Stmt::Sorting(so) => match &mut **so {
594            Sorting::Return { at_end, .. } => handlers(at_end).collect(),
595            _ => Vec::new(),
596        },
597        _ => Vec::new(),
598    }
599}
600
601impl Rules<'_> {
602    fn statements(&mut self, stmts: &[Stmt]) {
603        for s in stmts {
604            self.statement(s);
605            for body in bodies(s) {
606                self.statements(body);
607            }
608        }
609    }
610
611    fn statement(&mut self, s: &Stmt) {
612        match s {
613            Stmt::Move { from, to, pos } => {
614                self.plain(from, *pos);
615                to.iter().for_each(|r| self.receiver(r, *pos));
616            }
617            Stmt::Display { items, pos, .. } => items.iter().for_each(|o| self.plain(o, *pos)),
618            Stmt::Compute { targets, expr, pos, .. } => {
619                targets.iter().for_each(|t| self.receiver(&t.r, *pos));
620                self.expr(expr, *pos);
621            }
622            Stmt::Arith(a) => {
623                for (t, e) in &a.computations {
624                    self.receiver(&t.r, a.pos);
625                    self.expr(e, a.pos);
626                }
627            }
628            Stmt::Initialize { targets, pos } | Stmt::Set { set: SetStmt::UpDown { targets, .. }, pos } => targets.iter().for_each(|r| self.receiver(r, *pos)),
629            Stmt::Accept { target, pos, .. } => self.receiver(target, *pos),
630            Stmt::String(st) => {
631                st.sources.iter().for_each(|(o, _)| self.plain(o, st.pos));
632                self.receiver(&st.into, st.pos);
633            }
634            Stmt::Unstring(u) => {
635                self.plain(&Operand::Ref(u.source.clone()), u.pos);
636                u.into.iter().for_each(|i| self.receiver(&i.target, u.pos));
637            }
638            Stmt::Inspect(i) => match &i.target {
639                Operand::Ref(r) => self.receiver(r, i.pos),
640                subject => self.plain(subject, i.pos),
641            },
642            Stmt::If { cond, pos, .. } => self.cond(cond, *pos),
643            Stmt::PerformInline { repeat, pos, .. } | Stmt::PerformProc { repeat, pos, .. } => match repeat {
644                Loop::Until { cond, .. } => self.cond(cond, *pos),
645                Loop::Varying { varying, after, .. } => std::iter::once(&**varying).chain(after).for_each(|v| self.cond(&v.until, *pos)),
646                _ => {}
647            },
648            Stmt::Evaluate { subjects, whens, pos, .. } => {
649                for subject in subjects {
650                    match subject {
651                        Subject::Cond(c) => self.cond(c, *pos),
652                        Subject::Expr(e) => self.expr(e, *pos),
653                        Subject::Bool(_) => {}
654                    }
655                }
656                for w in whens {
657                    for object in w.alternatives.iter().flatten() {
658                        match object {
659                            Object::Cond(c) => self.cond(c, *pos),
660                            Object::Value { from, thru, .. } => thru.iter().chain([from]).for_each(|e| self.expr(e, *pos)),
661                            _ => {}
662                        }
663                    }
664                }
665            }
666            Stmt::Search(se) => se.whens.iter().for_each(|(c, _)| self.cond(c, se.pos)),
667            Stmt::Set { set, pos } => self.set(set, *pos),
668            Stmt::ExitMethod { pos } if !self.method => self.errors.push(Error::at(*pos, "EXIT METHOD can be used only in a method")),
669            Stmt::ExitProgram { pos } if self.method => self.errors.push(Error::at(*pos, "EXIT PROGRAM cannot be used in a method: use EXIT METHOD or GOBACK")),
670            Stmt::Invoke(_) => self.uses_oo = true,
671            Stmt::Sorting(so) => match &**so {
672                Sorting::Release { from: Some(op), pos, .. } => self.plain(op, *pos),
673                Sorting::Return { into: Some(r), pos, .. } => self.receiver(r, *pos),
674                _ => {}
675            },
676            _ => {}
677        }
678    }
679
680    fn is_self(&self, r: &Ref) -> bool {
681        is_named(r, "SELF") && self.layout.resolve(&r.name, &[], r.pos).is_err()
682    }
683
684    fn side_of_ref(&mut self, r: &Ref, pos: Pos) -> Side {
685        if self.is_self(r) {
686            if !self.method {
687                self.errors.push(Error::at(pos, "SELF can be used only in a method"));
688            }
689            return Side::Object;
690        }
691        match self.layout.resolve(&r.name, &r.qualifiers, r.pos) {
692            Ok(Resolved::Item(i)) if self.layout.items[i].kind == Kind::ObjectReference => Side::Object,
693            Ok(Resolved::Item(i)) if self.layout.items[i].kind == Kind::ProgramPointer => Side::ProgramPointer,
694            _ => Side::Other,
695        }
696    }
697
698    fn side(&mut self, op: &Operand, pos: Pos) -> Side {
699        match op {
700            Operand::Ref(r) => self.side_of_ref(r, pos),
701            Operand::Literal(Literal::Figurative(Figurative::Null)) => Side::Null,
702            _ => Side::Other,
703        }
704    }
705
706    /// An operand of a statement that takes no object reference or function-pointer.
707    fn plain(&mut self, op: &Operand, pos: Pos) {
708        let what = match self.side(op, pos) {
709            Side::Object => "an object reference",
710            Side::ProgramPointer => "a function-pointer or procedure-pointer",
711            _ => return,
712        };
713        let name = if let Operand::Ref(r) = op { r.name.as_str() } else { "" };
714        self.errors.push(Error::at(pos, format!("{name} is {what}: it can be used only in SET, INVOKE, CALL and a relation condition")));
715    }
716
717    fn receiver(&mut self, r: &Ref, pos: Pos) {
718        if is_named(r, "JNIENVPTR") && self.layout.resolve(&r.name, &[], r.pos).is_err() {
719            self.errors.push(Error::at(pos, "JNIENVPTR cannot receive a value"));
720        } else if self.is_self(r) {
721            self.errors.push(Error::at(pos, "SELF cannot receive a value"));
722        } else {
723            self.plain(&Operand::Ref(r.clone()), pos);
724        }
725    }
726
727    fn expr(&mut self, e: &Expr, pos: Pos) {
728        match e {
729            Expr::Operand(op) => self.plain(op, pos),
730            Expr::Neg(inner) => self.expr(inner, pos),
731            Expr::Bin(a, _, b) => {
732                self.expr(a, pos);
733                self.expr(b, pos);
734            }
735        }
736    }
737
738    fn cond(&mut self, c: &Cond, pos: Pos) {
739        match c {
740            Cond::Rel(a, op, b) => {
741                let side = |r: &mut Self, e: &Expr| match e {
742                    Expr::Operand(o) => r.side(o, pos),
743                    _ => Side::Other,
744                };
745                let (x, y) = (side(self, a), side(self, b));
746                let handle = |s: Side| matches!(s, Side::Object | Side::ProgramPointer);
747                if !handle(x) && !handle(y) {
748                    self.expr(a, pos);
749                    self.expr(b, pos);
750                    return;
751                }
752                if !matches!(op, RelOp::Eq | RelOp::Ne) {
753                    self.errors.push(Error::at(pos, "object references and function-pointers compare only as equal or not equal"));
754                }
755                let fits = |s: Side, other: Side| s == other || s == Side::Null || other == Side::Null;
756                if !fits(x, y) {
757                    self.errors.push(Error::at(pos, "an object reference compares with another object reference, SELF or NULL; a function-pointer with another or NULL"));
758                }
759            }
760            Cond::Class(e, _) => self.expr(e, pos),
761            Cond::Not(inner) => self.cond(inner, pos),
762            Cond::And(a, b) | Cond::Or(a, b) => {
763                self.cond(a, pos);
764                self.cond(b, pos);
765            }
766            Cond::Name(_) | Cond::NameOrRel { .. } => {}
767        }
768    }
769
770    fn set(&mut self, set: &SetStmt, pos: Pos) {
771        let SetStmt::To { targets, value } = set else { return };
772        let value_side = self.side(value, pos);
773        for r in targets {
774            if is_named(r, "JNIENVPTR") && self.layout.resolve(&r.name, &[], r.pos).is_err() {
775                self.errors.push(Error::at(pos, "JNIENVPTR cannot receive a value"));
776                continue;
777            }
778            if self.is_self(r) {
779                self.errors.push(Error::at(pos, "SELF cannot receive a value"));
780                continue;
781            }
782            let message = match (self.side_of_ref(r, pos), value_side) {
783                (Side::Object, Side::Object | Side::Null) | (Side::ProgramPointer, Side::ProgramPointer | Side::Null) => continue,
784                (Side::Object, _) => "an object reference takes another object reference, SELF or NULL",
785                (Side::ProgramPointer, _) => "a function-pointer takes another function-pointer or NULL (SET TO ENTRY is not supported yet)",
786                (_, Side::Object | Side::ProgramPointer) => "an object reference or function-pointer can be set only into its own kind",
787                _ => continue,
788            };
789            self.errors.push(Error::at(pos, format!("SET {} TO: {message}", r.name)));
790        }
791    }
792}