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