1use super::{
5 AbendId, AbendText, Access, Advance, Argument, ArithId, ArithPlan, ArithStep, Base, Binding, Block, BlockId, Bound, CallArg, CallId, CallTarget, Ccsid,
6 Chars, CicsId, Class, Comparand, Compare, Cond, CondId, Const, ConstId, Convert, ConvertTable, Count, Debug, DebugId, DisplayId, DisplayItem,
7 Expr, ExprId, FileDesc, FileOpId, FileVerb, Flag, FloatFrom, FromMove, FunctionId, GlobalAt, Image, Indicator, InitValue, InspectId,
8 InspectPhrase, Inspected, IntExpr, InvokeId, Item, JsonLeaf, JsonNode, JsonValue, Marker, MarkupId, MethodName, Mode, MovePlan, Named,
9 NationalFrom, NumberInto, NumericFrom, Odo, Op, Operand, Organization, ParaId, Paragraph, ParseLeaf, ParseNode, ParseValue, Phrase, Place,
10 PlaceId, Plans, Program, Range, RangeId, RangeKind, Receiver, Replacement, ReportOp, ReturnId, SearchAllId, Section, SenderCheck, Services,
11 SetTo, SignTest, SortIo, SortKeys, SortPlan, Spacing, SqlEntry, SqlStatement, SqlTest, SqlcaField, StartKey, StartRel, StepPlan,
12 StorePlan, StringId, SymId, Terminator, TrimSide, UnstringId, UpDown, UserArgument, UserFunctionId, XmlForm, XmlNode, XmlRegister,
13 XmlValue,
14};
15use super::{Markup, ReleaseId, SortId, SqlId};
16use crate::abend::Ending;
17use crate::cics::{Cics, CicsCommand, Datum, Handles};
18use crate::files::Format;
19use crate::report::{Adding, Field, FieldContent, GroupKind, LineNumber, NextGroup, Origin};
20use crate::sql::HostType;
21use crate::storage::Kind;
22use crate::store::LaxRedefinition;
23use crate::vocab::{AcceptFrom, BinOp, Closing, Figurative, InspectMode, OpenMode, Pos, RelOp, SignClause, SignPosition};
24use numeric::Arith;
25use numeric::precision::Fixed;
26use std::cell::Cell;
27use std::collections::BTreeMap;
28use std::convert::Infallible;
29use std::fmt;
30use zarch::ebcdic::CodePage;
31use zarch::hfp::Precision;
32use zarch::wide::U256;
33
34#[derive(Clone, Copy)]
36pub struct Code<'a> {
37 pub id: SymId,
38 pub initial: bool,
39 pub recursive: bool,
40 pub paragraphs: &'a [Paragraph],
41 pub procedure_start: ParaId,
42 pub ranges: &'a [Range],
43 pub blocks: &'a [Block],
44 pub places: &'a [Place],
45 pub exprs: &'a [Expr],
46 pub conds: &'a [Cond],
47 pub consts: &'a [Const],
48 pub plans: &'a Plans,
49 pub services: &'a Services,
50 pub abends: &'a [AbendText],
51 pub symbols: &'a [String],
52}
53
54#[derive(Clone, Copy)]
58pub struct Listing<'a> {
59 pub code: Code<'a>,
60 pub items: &'a [Item],
61 pub debug: Option<&'a Debug>,
62 pub sql: &'a [SqlEntry],
63 pub ccsid: Option<u16>,
64}
65
66impl Program {
67 pub fn code(&self) -> Code<'_> {
68 Code {
69 id: self.id,
70 initial: self.initial,
71 recursive: self.recursive,
72 paragraphs: &self.paragraphs,
73 procedure_start: self.procedure_start,
74 ranges: &self.ranges,
75 blocks: &self.blocks,
76 places: &self.places,
77 exprs: &self.exprs,
78 conds: &self.conds,
79 consts: &self.consts,
80 plans: &self.plans,
81 services: &self.services,
82 abends: &self.abends,
83 symbols: &self.symbols,
84 }
85 }
86}
87
88impl<'a> Listing<'a> {
89 pub fn of(program: &'a Program) -> Self {
90 Listing {
91 code: program.code(),
92 items: &program.items,
93 debug: Some(&program.debug),
94 sql: &program.sql,
95 ccsid: Some(program.options.options.codepage),
96 }
97 }
98}
99
100impl fmt::Display for Listing<'_> {
101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102 Printer::new(self).program(f)
103 }
104}
105
106impl fmt::Display for Program {
107 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108 Listing::of(self).fmt(f)
109 }
110}
111
112const DEPTH: u32 = 256;
115const BUDGET: u32 = 100_000;
116
117struct Printer<'a> {
118 c: Code<'a>,
119 items: &'a [Item],
120 debug: Option<&'a Debug>,
121 sql: &'a [SqlEntry],
122 page: Option<&'static CodePage>,
123 shared: BTreeMap<&'a str, Vec<usize>>,
125 repeated: BTreeMap<&'a str, usize>,
127 depth: Cell<u32>,
128 spent: Cell<u32>,
129}
130
131fn join(parts: impl IntoIterator<Item = String>, separator: &str) -> String {
132 parts.into_iter().collect::<Vec<_>>().join(separator)
133}
134
135fn attrs(open: char, parts: Vec<String>) -> String {
137 if parts.is_empty() {
138 return String::new();
139 }
140 let close = if open == '[' { ']' } else { '}' };
141 format!(" {open}{}{close}", parts.join(", "))
142}
143
144fn yes(on: bool, text: &str) -> Option<String> {
145 on.then(|| text.to_owned())
146}
147
148fn label(id: BlockId) -> String {
149 format!("b{id}")
150}
151
152fn abend_ref(id: AbendId) -> String {
153 format!("a{id}")
154}
155
156impl<'a> Printer<'a> {
157 fn new(l: &Listing<'a>) -> Self {
158 let symbol = |id: SymId| l.code.symbols.get(id as usize).map(String::as_str);
159 let mut shared: BTreeMap<&'a str, Vec<usize>> = BTreeMap::new();
160 for (k, item) in l.items.iter().enumerate() {
161 if let Some(name) = item.name.and_then(symbol) {
162 shared.entry(name).or_default().push(k);
163 }
164 }
165 shared.retain(|_, items| items.len() > 1);
166 let mut repeated: BTreeMap<&'a str, usize> = BTreeMap::new();
167 for p in l.code.paragraphs {
168 if let Some(name) = symbol(p.name) {
169 *repeated.entry(name).or_default() += 1;
170 }
171 }
172 repeated.retain(|_, n| *n > 1);
173 Printer {
174 c: l.code,
175 items: l.items,
176 debug: l.debug,
177 sql: l.sql,
178 page: l.ccsid.and_then(CodePage::by_ccsid),
179 shared,
180 repeated,
181 depth: Cell::new(0),
182 spent: Cell::new(0),
183 }
184 }
185
186 fn nested(&self, render: impl FnOnce() -> String) -> String {
187 let depth = self.depth.get();
188 if depth == 0 {
189 self.spent.set(0);
190 }
191 let spent = self.spent.get();
192 if depth >= DEPTH || spent >= BUDGET {
193 return "...".to_owned();
194 }
195 self.depth.set(depth + 1);
196 self.spent.set(spent + 1);
197 let text = render();
198 self.depth.set(depth);
199 text
200 }
201
202 fn symbol(&self, id: SymId) -> Option<&'a str> {
203 self.c.symbols.get(id as usize).map(String::as_str)
204 }
205
206 fn name(&self, id: SymId) -> String {
208 self.symbol(id).map_or_else(|| format!("symbol{id}?"), word)
209 }
210
211 fn string(&self, id: SymId) -> String {
213 self.symbol(id).map_or_else(|| format!("symbol{id}?"), |s| format!("{s:?}"))
214 }
215
216 fn raw(&self, id: SymId) -> String {
218 self.symbol(id).map_or_else(|| format!("symbol{id}?"), |s| if s.chars().any(char::is_control) { format!("{s:?}") } else { s.to_owned() })
219 }
220
221 fn literal(&self, id: SymId) -> String {
223 self.symbol(id).map_or_else(|| format!("symbol{id}?"), quote)
224 }
225
226 fn bytes(&self, bytes: &[u8]) -> String {
227 let decoded = self.page.and_then(|page| {
228 bytes
229 .iter()
230 .map(|&b| {
231 let ch = page.decode_byte(b);
232 (!ch.is_control() && page.encode_char(ch) == Some(b)).then_some(ch)
233 })
234 .collect::<Option<String>>()
235 });
236 decoded.map_or_else(|| hex("X", bytes), |text| quote(&text))
237 }
238
239 fn position(&self, pos: &Pos) -> String {
240 if pos.file == 0 {
241 return format!("{}:{}", pos.line, pos.col);
242 }
243 let file = self.debug.and_then(|d| d.sources.get(usize::from(pos.file))).map_or_else(|| format!("file{}", pos.file), |&s| self.name(s));
244 format!("{file}:{}:{}", pos.line, pos.col)
245 }
246
247 fn pos(&self, at: DebugId) -> Option<String> {
248 self.debug.and_then(|d| d.positions.get(at as usize)).map(|p| self.position(p))
249 }
250
251 fn at(&self, at: DebugId) -> String {
252 self.pos(at).map_or_else(String::new, |p| format!(" @{p}"))
253 }
254
255 fn para(&self, id: ParaId) -> String {
256 let Some(p) = self.c.paragraphs.get(id as usize) else { return format!("paragraph{id}?") };
257 let name = self.name(p.name);
258 if !self.symbol(p.name).is_some_and(|n| self.repeated.contains_key(n)) {
259 return name;
260 }
261 let section = (0..id).rev().map(|s| (s, &self.c.paragraphs[s as usize])).find(|(_, s)| s.is_section && s.section_end >= id);
262 match section {
263 Some((_, s)) if !self.symbol(s.name).is_some_and(|n| self.repeated.contains_key(n)) => format!("{name} OF {}", self.name(s.name)),
264 _ => format!("{name} (paragraph {id})"),
265 }
266 }
267
268 fn next_para(&self, id: ParaId) -> String {
270 if id as usize == self.c.paragraphs.len() { "end".to_owned() } else { self.para(id) }
271 }
272
273 fn range(&self, id: RangeId) -> String {
274 match self.c.ranges.get(id as usize) {
275 None => format!("r{id}?"),
276 Some(r) if r.first == r.last => format!("r{id} {}", self.para(r.first)),
277 Some(r) => format!("r{id} {} thru {}", self.para(r.first), self.para(r.last)),
278 }
279 }
280
281 fn file(&self, file: u16) -> String {
282 self.c.services.files.get(usize::from(file)).map_or_else(|| format!("file{file}?"), |d| self.name(d.name))
283 }
284
285 fn file_at(&self, file: usize) -> String {
286 u16::try_from(file).map_or_else(|_| format!("file{file}?"), |f| self.file(f))
287 }
288
289 fn linkage(&self, n: u16) -> String {
291 let record = self.items.iter().find(|i| i.linkage == Some(n) && i.parent.is_none()).and_then(|i| i.name);
292 record.map_or_else(|| format!("linkage{n}"), |s| self.name(s))
293 }
294
295 fn place(&self, id: PlaceId) -> String {
298 self.nested(|| match self.c.places.get(id as usize) {
299 None => format!("p{id}?"),
300 Some(p) => self.reference(p, &[]),
301 })
302 }
303
304 fn places(&self, ids: &[PlaceId]) -> String {
305 join(ids.iter().map(|&p| self.place(p)), " ")
306 }
307
308 fn reference(&self, p: &Place, all: &[u32]) -> String {
310 let mut text = self.data_name(p);
311 if !p.subscripts.is_empty() {
312 let subscripts = p.subscripts.iter().enumerate().map(|(k, s)| if all.contains(&(k as u32)) { "ALL".to_owned() } else { self.int(&s.value) });
313 text += &format!("({})", join(subscripts, ", "));
314 }
315 if let Some(r) = &p.refmod {
316 text += &format!("({}:{})", self.int(&r.start), r.length.as_ref().map_or_else(String::new, |l| self.int(l)));
317 }
318 text
319 }
320
321 fn data_name(&self, p: &Place) -> String {
322 let name = self.name(p.name);
323 let Some(same) = self.symbol(p.name).and_then(|n| self.shared.get(n)) else { return name };
324 let held = |i: &Item| match p.base {
325 Base::Program => !i.local && i.linkage.is_none(),
326 Base::Local => i.local,
327 Base::Linkage(n) => i.linkage == Some(n),
328 Base::ReturnCode | Base::Eib | Base::SelfRef | Base::JniEnv | Base::Xml(_) => false,
329 };
330 let Some(&own) = same.iter().find(|&&k| self.items[k].offset == p.offset && held(&self.items[k])) else { return name };
331 let mut others: Vec<usize> = same.iter().copied().filter(|&k| k != own).collect();
332 let mut qualifiers: Vec<&str> = Vec::new();
333 for ancestor in self.ancestors(own) {
334 if others.is_empty() {
335 break;
336 }
337 let Some(q) = self.items[ancestor].name.and_then(|s| self.symbol(s)) else { continue };
338 qualifiers.push(q);
339 others.retain(|&k| self.qualifies(k, &qualifiers));
340 }
341 qualifiers.iter().fold(name, |text, q| format!("{text} OF {}", word(q)))
342 }
343
344 fn ancestors(&self, k: usize) -> Vec<usize> {
346 let mut out = Vec::new();
347 let mut next = self.items.get(k).and_then(|i| i.parent);
348 while let Some(p) = next.map(|p| p as usize).filter(|&p| p < self.items.len() && out.len() < self.items.len()) {
349 out.push(p);
350 next = self.items[p].parent;
351 }
352 out
353 }
354
355 fn qualifies(&self, k: usize, qualifiers: &[&str]) -> bool {
357 let mut wanted = qualifiers.iter().peekable();
358 for a in self.ancestors(k) {
359 if wanted.peek().is_some_and(|&&q| self.items[a].name.and_then(|s| self.symbol(s)) == Some(q)) {
360 wanted.next();
361 }
362 }
363 wanted.peek().is_none()
364 }
365
366 fn konst(&self, id: ConstId) -> String {
367 match self.c.consts.get(id as usize) {
368 None => format!("c{id}?"),
369 Some(c) => self.constant(c),
370 }
371 }
372
373 fn constant(&self, c: &Const) -> String {
374 match c {
375 Const::Bytes(b) => self.bytes(b),
376 Const::National(units) => national(units),
377 Const::Number(n) => decimal(n),
378 Const::Figurative(f) => figurative(*f).to_owned(),
379 Const::All(b) => format!("ALL {}", self.bytes(b)),
380 Const::AllNational(units) => format!("ALL {}", national(units)),
381 Const::Dbcs(b) => hex("GX", b),
382 Const::Refused(a) => format!("refused {}", abend_ref(*a)),
383 }
384 }
385
386 fn operand(&self, o: &Operand) -> String {
387 match *o {
388 Operand::Load(p) => self.place(p),
389 Operand::Const(c) => self.konst(c),
390 Operand::LengthOf(p) => format!("LENGTH OF {}", self.place(p)),
391 Operand::AddressOf(p) => format!("ADDRESS OF {}", self.place(p)),
392 Operand::Function(f) => self.function(f),
393 Operand::UserFunction(u) => self.user_function(u),
394 }
395 }
396
397 fn function(&self, id: FunctionId) -> String {
398 self.nested(|| {
399 let Some(f) = self.c.plans.function.get(id as usize) else { return format!("function{id}?") };
400 let args = f.args.iter().map(|a| match a {
401 Argument::Value(v) => self.comparand(v),
402 Argument::All { element, all } => match self.c.places.get(*element as usize) {
403 None => format!("p{element}?"),
404 Some(p) => self.reference(p, &all.iter().map(|(k, _)| *k).collect::<Vec<_>>()),
405 },
406 });
407 let side = match f.side {
408 None => "",
409 Some(TrimSide::Leading) => " LEADING",
410 Some(TrimSide::Trailing) => " TRAILING",
411 };
412 let mut text = format!("FUNCTION {}({}{side})", f.func.name(), join(args, ", "));
413 if let Some(r) = &f.refmod {
414 text += &format!("({}:{})", self.int(&r.start), r.length.as_ref().map_or_else(String::new, |l| self.int(l)));
415 }
416 let how = [f.integer.as_ref().map(|i| format!("integer {}", self.int(i))), f.arity.map(|a| format!("arity {}", abend_ref(a)))];
417 text + &attrs('{', how.into_iter().flatten().collect())
418 })
419 }
420
421 fn user_function(&self, id: UserFunctionId) -> String {
422 self.nested(|| {
423 let Some(u) = self.c.services.user_functions.get(id as usize) else { return format!("user-function{id}?") };
424 let args = u.args.iter().map(|a| match a {
425 UserArgument::Reference(p) => self.place(*p),
426 UserArgument::Value(v) => format!("value {}", self.comparand(v)),
427 });
428 let mut text = format!("FUNCTION {}({})", self.name(u.name), join(args, ", "));
429 if let Some(r) = &u.refmod {
430 text += &format!("({}:{})", self.int(&r.start), r.length.as_ref().map_or_else(String::new, |l| self.int(l)));
431 }
432 let external = (u.external != u.name).then(|| format!("external {}", self.name(u.external)));
433 text + &attrs('{', external.into_iter().collect())
434 })
435 }
436
437 fn expr(&self, id: ExprId) -> String {
438 self.nested(|| match self.c.exprs.get(id as usize) {
439 None => format!("e{id}?"),
440 Some(Expr::Operand(o)) => self.operand(o),
441 Some(Expr::Neg(e)) => format!("-{}", self.term(*e)),
442 Some(Expr::Bin(a, op, b)) => format!("{} {} {}", self.term(*a), binop(*op), self.term(*b)),
443 Some(Expr::Pow(a, n)) => {
444 let exponent = self.int(n);
445 let compound = matches!(n, IntExpr::Fixed { expr, .. } if matches!(self.c.exprs.get(*expr as usize), Some(Expr::Bin(..) | Expr::Pow(..))));
446 if compound { format!("{} ** ({exponent})", self.term(*a)) } else { format!("{} ** {exponent}", self.term(*a)) }
447 }
448 })
449 }
450
451 fn term(&self, id: ExprId) -> String {
453 match self.c.exprs.get(id as usize) {
454 Some(Expr::Bin(..) | Expr::Pow(..)) => format!("({})", self.expr(id)),
455 _ => self.expr(id),
456 }
457 }
458
459 fn int(&self, e: &IntExpr) -> String {
460 match e {
461 IntExpr::Const(n) => n.to_string(),
462 IntExpr::Item(p) => self.place(*p),
463 IntExpr::Fixed { expr, dmax, prepass } => {
464 let how = self.how(*dmax, &Mode::Fixed, prepass);
465 if how.is_empty() { self.expr(*expr) } else { self.term(*expr) + &attrs('{', how) }
466 }
467 IntExpr::Walk(k) => format!("walk{k}"),
468 }
469 }
470
471 fn how(&self, dmax: u32, mode: &Mode, prepass: &[PlaceId]) -> Vec<String> {
474 let mut how = Vec::new();
475 if dmax != 0 {
476 how.push(format!("dmax {dmax}"));
477 }
478 match mode {
479 Mode::Fixed => {}
480 Mode::Float(p) => how.push(format!("float {}", precision(*p))),
481 }
482 if !prepass.is_empty() {
483 how.push(format!("prepass {}", self.places(prepass)));
484 }
485 how
486 }
487
488 fn comparand(&self, c: &Comparand) -> String {
489 match c {
490 Comparand::Operand(o) => self.operand(o),
491 Comparand::Expr { expr, dmax, mode, prepass } => self.term(*expr) + &attrs('{', self.how(*dmax, mode, prepass)),
492 }
493 }
494
495 fn cond(&self, id: CondId) -> String {
496 self.nested(|| match self.c.conds.get(id as usize) {
497 None => format!("k{id}?"),
498 Some(Cond::Rel { a, op, b, how }) => format!("{} {} {} [{}]", self.comparand(a), relop(*op), self.comparand(b), compare(*how)),
499 Some(Cond::Class { place, test }) => format!("{} is {}", self.place(*place), byte_class(*test)),
500 Some(Cond::Sign { value, test }) => format!("{} is {}", self.comparand(value), sign_test(*test)),
501 Some(Cond::Name { subject, values, how }) => {
502 let values = values.iter().map(|(low, high)| match high {
503 None => self.konst(*low),
504 Some(h) => format!("{} thru {}", self.konst(*low), self.konst(*h)),
505 });
506 format!("{} in ({}) [{}]", self.place(*subject), join(values, ", "), compare(*how))
507 }
508 Some(Cond::Not(c)) => format!("not ({})", self.cond(*c)),
509 Some(Cond::And(a, b)) => format!("{} and {}", self.logical(*a), self.logical(*b)),
510 Some(Cond::Or(a, b)) => format!("{} or {}", self.logical(*a), self.logical(*b)),
511 Some(Cond::Counter(t)) => format!("t{t} > 0"),
512 Some(Cond::InTable { index, count }) => format!("{} within {}", self.place(*index), self.count(count)),
513 Some(Cond::Sql(test)) => format!("sql {}", sql_test(*test)),
514 })
515 }
516
517 fn logical(&self, id: CondId) -> String {
519 match self.c.conds.get(id as usize) {
520 Some(Cond::And(..) | Cond::Or(..)) => format!("({})", self.cond(id)),
521 _ => self.cond(id),
522 }
523 }
524
525 fn count(&self, c: &Count) -> String {
526 match c {
527 Count::Fixed(n) => n.to_string(),
528 Count::Odo(o) => self.odo(o),
529 Count::Temp(t) => format!("t{t}"),
530 }
531 }
532
533 fn odo(&self, o: &Odo) -> String {
534 format!("({} max {} element {}{})", self.int(&o.object), o.max, o.element, if o.check { " check" } else { "" })
535 }
536
537 fn chars(&self, c: &Chars) -> String {
538 match c {
539 Chars::Literal(b) => self.bytes(b),
540 Chars::Place(p) => self.place(*p),
541 Chars::Value(o) => self.operand(o),
542 }
543 }
544
545 fn store(&self, s: &StorePlan) -> String {
546 match *s {
547 StorePlan::Zoned { digits, scale, signed, sign } => format!("zoned {}{}", pic(digits, scale, signed), sign_clause(sign)),
548 StorePlan::Packed { digits, scale, signed } => format!("packed {}", pic(digits, scale, signed)),
549 StorePlan::Binary { digits, scale, signed, native, name: _ } => format!("binary {}{}", pic(digits, scale, signed), if native { " native" } else { "" }),
550 StorePlan::NumericEdited { edit, digits, scale, blank_when_zero } => {
551 format!("numeric-edited edit {edit} {}{}", pic(digits, scale, false), if blank_when_zero { " blank-when-zero" } else { "" })
552 }
553 StorePlan::Float(p) => format!("float {}", precision(p)),
554 StorePlan::Index => "index".to_owned(),
555 StorePlan::Refused(a) => format!("refused {}", abend_ref(a)),
556 }
557 }
558
559 fn step(&self, s: &StepPlan) -> String {
560 format!("{}, dmax {}", self.store(&s.store), s.dmax)
561 }
562
563 fn move_plan(&self, m: &MovePlan) -> String {
564 match *m {
565 MovePlan::Alnum { image: i, justified } => format!("alnum{}{}", image(i), if justified { " justified" } else { "" }),
566 MovePlan::AlnumEdited { image: i, edit, positions } => format!("alnum-edited edit {edit} positions {positions}{}", image(i)),
567 MovePlan::National(from) => format!("national {}", national_from(from)),
568 MovePlan::Dbcs { justified, edit } => {
569 format!("dbcs{}{}", if justified { " justified" } else { "" }, edit.map_or(String::new(), |e| format!(" edit {e}")))
570 }
571 MovePlan::Numeric { from, store } => format!("numeric {} to {}", numeric_from(from), self.store(&store)),
572 MovePlan::Float { from, precision: p } => format!("float {} to {}", float_from(from), precision(p)),
573 MovePlan::Address => "address".to_owned(),
574 MovePlan::Index => "index".to_owned(),
575 MovePlan::Refused(a) => format!("refused {}", abend_ref(a)),
576 }
577 }
578
579 fn moved(&self, plan: &MovePlan, check: SenderCheck) -> String {
581 let check = match check {
582 SenderCheck::None => None,
583 SenderCheck::Item => Some("check item".to_owned()),
584 SenderCheck::Integer => Some("check integer".to_owned()),
585 };
586 attrs('[', std::iter::once(self.move_plan(plan)).chain(check).collect())
587 }
588
589 fn stored(&self, (place, store): &(PlaceId, StorePlan)) -> String {
590 format!("{} [{}]", self.place(*place), self.store(store))
591 }
592
593 fn program(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
594 let start = (!self.c.paragraphs.is_empty()).then(|| format!("start {}", self.para(self.c.procedure_start)));
595 let flags = [start, yes(self.c.initial, "initial"), yes(self.c.recursive, "recursive")];
596 writeln!(f, "program {}{}", self.name(self.c.id), join(flags.into_iter().flatten().map(|s| format!(" {s}")), ""))?;
597 for (k, r) in self.c.ranges.iter().enumerate() {
598 let span = if r.first == r.last { self.para(r.first) } else { format!("{} thru {}", self.para(r.first), self.para(r.last)) };
599 writeln!(f, "range r{k} {} {span}", range_kind(r.kind))?;
600 }
601 self.code(f)?;
602 self.tables(f)
603 }
604
605 fn code(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
606 let mut entries: BTreeMap<BlockId, Vec<ParaId>> = BTreeMap::new();
607 for (k, p) in self.c.paragraphs.iter().enumerate() {
608 entries.entry(p.entry).or_default().push(k as ParaId);
609 }
610 for (b, block) in self.c.blocks.iter().enumerate() {
611 for &p in entries.get(&(b as BlockId)).into_iter().flatten() {
612 writeln!(f, "{}", self.paragraph(p, false))?;
613 }
614 writeln!(f, "{}:", label(b as BlockId))?;
615 let ats = self.debug.and_then(|d| d.ops.get(b));
616 let starts = self.debug.and_then(|d| d.statements.get(b)).map_or(&[][..], Vec::as_slice);
617 let mut statement = None;
618 let starting = |f: &mut fmt::Formatter<'_>, k: usize, statement: &mut Option<String>| -> fmt::Result {
619 for (_, at) in starts.iter().filter(|(i, _)| *i as usize == k) {
620 let pos = self.pos(*at);
621 writeln!(f, " statement {}", pos.as_deref().unwrap_or("?"))?;
622 *statement = pos;
623 }
624 Ok(())
625 };
626 let suffix = |k: usize, statement: &Option<String>| match ats.and_then(|a| a.get(k)).and_then(|&at| self.pos(at)) {
627 Some(pos) if Some(&pos) != statement.as_ref() => format!(" @{pos}"),
628 _ => String::new(),
629 };
630 for (k, op) in block.ops.iter().enumerate() {
631 starting(f, k, &mut statement)?;
632 writeln!(f, " {}{}", self.op(op), suffix(k, &statement))?;
633 }
634 let k = block.ops.len();
635 starting(f, k, &mut statement)?;
636 let at = match block.end {
637 Terminator::Jump(_) | Terminator::Select(_) => String::new(),
638 _ => suffix(k, &statement),
639 };
640 writeln!(f, " {}{at}", self.terminator(&block.end))?;
641 }
642 for (&b, paragraphs) in entries.range(self.c.blocks.len() as BlockId..) {
643 for &p in paragraphs {
644 writeln!(f, "{} entry {}?", self.paragraph(p, true), label(b))?;
645 }
646 }
647 Ok(())
648 }
649
650 fn paragraph(&self, k: ParaId, bare: bool) -> String {
651 let p = &self.c.paragraphs[k as usize];
652 let mut text = format!("paragraph {k} {}", self.name(p.name));
653 if p.is_section {
654 text += &format!(" section thru {}", self.para(p.section_end));
655 }
656 if p.priority != 0 {
657 text += &format!(" priority {}", p.priority);
658 }
659 if let Some(a) = p.abandoned {
660 text += &format!(" abandoned {}", abend_ref(a));
661 }
662 if bare { text } else { text + &self.at(p.at) }
663 }
664
665 fn terminator(&self, t: &Terminator) -> String {
666 match t {
667 Terminator::Jump(b) => format!("Jump {}", label(*b)),
668 Terminator::Branch { cond, then, otherwise } => format!("Branch ({}) {} else {}", self.cond(*cond), label(*then), label(*otherwise)),
669 Terminator::Select(arms) => format!("Select {}", join(arms.iter().map(|&b| label(b)), " ")),
670 Terminator::ParagraphEnd { next } => format!("ParagraphEnd next {}", self.next_para(*next)),
671 Terminator::GoTo(p) => format!("GoTo {}", self.para(*p)),
672 Terminator::Switch { value, targets, otherwise } => {
673 format!("Switch {} {} else {}", self.int(value), join(targets.iter().map(|&p| self.para(p)), " "), label(*otherwise))
674 }
675 Terminator::PerformEnter { range, ret, resume } => {
676 let resume = resume.map_or_else(String::new, |r| format!(" resume {} {}", self.para(r.para), label(r.block)));
677 format!("PerformEnter {} -> {}{resume}", self.range(*range), label(*ret))
678 }
679 Terminator::ExitProgram { next } => format!("ExitProgram next {}", label(*next)),
680 Terminator::End(e) => format!("End {}", ending(*e)),
681 Terminator::Abend(a) => match self.c.abends.get(*a as usize) {
682 Some(text) => format!("Abend {} {} {}", abend_ref(*a), text.code, self.string(text.message)),
683 None => format!("Abend {}?", abend_ref(*a)),
684 },
685 Terminator::AlteredGoTo { para, otherwise } => format!("AlteredGoTo {} else {}", self.para(*para), label(*otherwise)),
686 Terminator::Debug { range, name, next } => format!("Debug {} name {} next {}", self.range(*range), self.literal(*name), label(*next)),
687 }
688 }
689
690 fn op(&self, op: &Op) -> String {
691 match op {
692 Op::Move { from, to, plan, check } => format!("Move {} <- {}{}", self.place(*to), self.operand(from), self.moved(plan, *check)),
693 Op::Set { from, to, plan } => format!("Set {} <- {}{}", self.place(*to), self.operand(from), self.moved(plan, SenderCheck::None)),
694 Op::Initialize { target, plan } => format!("Initialize {} init {plan}", self.place(*target)),
695 Op::Arith(id) => self.arith(*id),
696 Op::SetAddress { records, address } => format!("SetAddress {} <- {}", join(records.iter().map(|&r| self.linkage(r)), " "), self.operand(address)),
697 Op::SetUpDown { by, down, targets } => {
698 let targets = targets.iter().map(|(p, how)| {
699 let how = match how {
700 UpDown::Pointer => "pointer".to_owned(),
701 UpDown::Number(step) => self.step(step),
702 UpDown::Refused(a) => format!("refused {}", abend_ref(*a)),
703 };
704 format!("{} [{how}]", self.place(*p))
705 });
706 format!("SetUpDown {} {} by {}", join(targets, ", "), if *down { "down" } else { "up" }, self.int(by))
707 }
708 Op::SetEntry { entry, targets } => format!("SetEntry {} <- {}", self.places(targets), self.operand(entry)),
709 Op::Step { var, by, plan, prepass } => {
710 let prepass = (!prepass.is_empty()).then(|| format!("prepass {}", self.places(prepass)));
711 format!("Step {} by {} [{}]{}", self.place(*var), self.expr(*by), self.step(plan), attrs('{', prepass.into_iter().collect()))
712 }
713 Op::SetInt { target, value } => format!("SetInt {} <- {}", self.place(*target), self.int(value)),
714 Op::Inspect(id) => self.inspect(*id),
715 Op::String(id) => self.string_op(*id),
716 Op::Unstring(id) => self.unstring(*id),
717 Op::SearchAll(id) => self.search_all(*id),
718 Op::Nest => "Nest".to_owned(),
719 Op::Unnest(n) => format!("Unnest {n}"),
720 Op::SetTemp(t, value) => format!("SetTemp t{t} <- {}", self.int(value)),
721 Op::DecTemp(t) => format!("DecTemp t{t}"),
722 Op::SetCount(t, odo) => format!("SetCount t{t} <- {}", self.odo(odo)),
723 Op::Display(id) => self.display(*id),
724 Op::ArgumentNumber(value) => format!("ArgumentNumber <- {}", self.int(value)),
725 Op::Accept { target, from, plan } => format!("Accept {} <- {}{}", self.place(*target), accept_from(*from), self.moved(plan, SenderCheck::None)),
726 Op::File(id) => self.file_op(*id),
727 Op::Call(id) => self.call(*id),
728 Op::Cancel(name) => format!("Cancel {}", self.operand(name)),
729 Op::Sort(id) => self.sort(*id),
730 Op::Release(id) => self.release(*id),
731 Op::Return(id) => self.return_op(*id),
732 Op::Report(r) => self.report_op(r),
733 Op::Invoke(id) => self.invoke(*id),
734 Op::Cics(id) => self.cics(*id),
735 Op::Sql(ordinal) => self.sql(*ordinal),
736 Op::Alter { para, to } => format!("Alter {} to {}", self.para(*para), self.para(*to)),
737 Op::EnterSegment(priority) => format!("EnterSegment {priority}"),
738 Op::DebugLine(line) => format!("DebugLine {line}"),
739 Op::DebugAlter { range, name, contents } => format!("DebugAlter {} name {} contents {}", self.range(*range), self.literal(*name), self.literal(*contents)),
740 Op::Markup(id) => self.markup(*id),
741 }
742 }
743
744 fn arith(&self, id: ArithId) -> String {
745 let Some(ArithPlan { dmax, arith, prepass, steps, remainder, handled, per_receiver, inner_dmax }) = self.c.plans.arith.get(id as usize) else {
746 return format!("Arith arith{id}?");
747 };
748 let mut steps: Vec<String> = steps.iter().map(|s| self.arith_step(s)).collect();
749 if let Some(r) = remainder {
750 steps.push(format!(
751 "remainder {} <- {} / {} [{}, quotient scale {}]",
752 self.place(r.target),
753 self.term(r.dividend),
754 self.term(r.divisor),
755 self.store(&r.store),
756 r.quotient_scale
757 ));
758 }
759 let mut how = vec![format!("dmax {dmax}")];
760 if inner_dmax != dmax {
761 how.push(format!("inner dmax {inner_dmax}"));
762 }
763 match arith {
764 Arith::Compat => {}
765 Arith::Extend => how.push("arith extend".to_owned()),
766 }
767 if !prepass.is_empty() {
768 how.push(format!("prepass {}", self.places(prepass)));
769 }
770 how.extend(yes(*per_receiver, "per receiver"));
771 how.extend(yes(*handled, "size error"));
772 format!("Arith {}{}", steps.join("; "), attrs('{', how))
773 }
774
775 fn arith_step(&self, s: &ArithStep) -> String {
776 let mut how = vec![self.store(&s.store)];
777 how.extend(yes(s.rounded, "rounded"));
778 match s.mode {
779 Mode::Fixed => {}
780 Mode::Float(p) => how.push(format!("float {}", precision(p))),
781 }
782 if !s.probe.is_empty() {
783 how.push(format!("probe {}", self.places(&s.probe)));
784 }
785 format!("{} <- {}{}", self.place(s.target), self.expr(s.expr), attrs('[', how))
786 }
787
788 fn display(&self, id: DisplayId) -> String {
789 let Some(d) = self.c.plans.display.get(id as usize) else { return format!("Display display{id}?") };
790 let items = d.items.iter().map(|item| match item {
791 DisplayItem::Bytes(p) => self.place(*p),
792 DisplayItem::National(p) => format!("{} [national]", self.place(*p)),
793 DisplayItem::Digits { place, digits, signed } => format!("{} [digits {digits}{}]", self.place(*place), if *signed { " signed" } else { "" }),
794 DisplayItem::Refused { place, abend } => format!("{} [refused {}]", self.place(*place), abend_ref(*abend)),
795 DisplayItem::Text(text) => self.literal(*text),
796 DisplayItem::Value(o) => self.operand(o),
797 });
798 format!("Display {}{}", join(items, ", "), attrs('{', yes(d.no_advancing, "no advancing").into_iter().collect()))
799 }
800
801 fn inspect(&self, id: InspectId) -> String {
802 let Some(i) = self.c.plans.inspect.get(id as usize) else { return format!("Inspect inspect{id}?") };
803 let mut text = format!(
804 "Inspect {}",
805 match &i.target {
806 Inspected::Item(p) => self.place(*p),
807 Inspected::Value(o) => self.operand(o),
808 }
809 );
810 for phrase in &i.tallying {
811 text += &format!(" tallying {}", self.inspect_phrase(phrase));
812 }
813 for phrase in &i.replacing {
814 text += &format!(" replacing {}", self.inspect_phrase(phrase));
815 }
816 if let Some(c) = &i.converting {
817 text += &match &c.table {
818 ConvertTable::Built(pairs) => {
819 let (from, to): (Vec<u8>, Vec<u8>) = pairs.iter().copied().unzip();
820 format!(" converting {} to {} {{built}}", self.bytes(&from), self.bytes(&to))
821 }
822 ConvertTable::Operands { from, to } => format!(" converting {} to {}", self.chars(from), self.chars(to)),
823 };
824 text += &self.bounds(&c.bounds);
825 }
826 text
827 }
828
829 fn inspect_phrase(&self, phrase: &InspectPhrase) -> String {
830 let mut text = String::new();
831 if let Some((p, step)) = &phrase.counter {
832 text += &format!("{} [{}] for ", self.place(*p), self.step(step));
833 }
834 text += match phrase.mode {
835 InspectMode::Characters => "CHARACTERS",
836 InspectMode::All => "ALL",
837 InspectMode::Leading => "LEADING",
838 InspectMode::First => "FIRST",
839 };
840 if let Some(pattern) = &phrase.pattern {
841 text += &format!(" {}", self.chars(pattern));
842 }
843 match &phrase.by {
844 None => {}
845 Some(Replacement::Chars(c)) => text += &format!(" by {}", self.chars(c)),
846 Some(Replacement::Fill(b)) => text += &format!(" by fill {}", hex("X", &[*b])),
847 }
848 text + &self.bounds(&phrase.bounds)
849 }
850
851 fn bounds(&self, bounds: &[Bound]) -> String {
852 join(bounds.iter().map(|b| format!(" {} {}", if b.after { "after" } else { "before" }, self.chars(&b.value))), "")
853 }
854
855 fn string_op(&self, id: StringId) -> String {
856 let Some(s) = self.c.plans.string.get(id as usize) else { return format!("String string{id}?") };
857 let sources = s.sources.iter().map(|source| {
858 let delimiter = source.delimiter.as_ref().map_or_else(|| "size".to_owned(), |d| self.chars(d));
859 format!("{} delimited by {delimiter}", self.chars(&source.chars))
860 });
861 let pointer = s.pointer.as_ref().map_or_else(String::new, |p| format!(" pointer {}", self.stored(p)));
862 format!("String {} <- {}{pointer}", self.place(s.into), join(sources, ", "))
863 }
864
865 fn unstring(&self, id: UnstringId) -> String {
866 let Some(u) = self.c.plans.unstring.get(id as usize) else { return format!("Unstring unstring{id}?") };
867 let mut text = format!("Unstring {}", self.place(u.source));
868 if !u.delimiters.is_empty() {
869 let delimiters = u.delimiters.iter().map(|(all, c)| format!("{}{}", if *all { "ALL " } else { "" }, self.chars(c)));
870 text += &format!(" delimited by {}", join(delimiters, ", "));
871 }
872 let into = u.into.iter().map(|i| {
873 let mut field = format!("{} [{}]", self.place(i.target), self.move_plan(&i.plan));
874 if let Some(d) = &i.delimiter {
875 field += &format!(" delimiter in {} [found {}, none {}]", self.place(d.target), self.move_plan(&d.found), self.move_plan(&d.none));
876 }
877 if let Some(c) = &i.count {
878 field += &format!(" count in {}", self.stored(c));
879 }
880 field
881 });
882 text += &format!(" into {}", join(into, ", "));
883 if let Some(p) = &u.pointer {
884 text += &format!(" pointer {}", self.stored(p));
885 }
886 if let Some((p, step)) = &u.tallying {
887 text += &format!(" tallying {} [{}]", self.place(*p), self.step(step));
888 }
889 text
890 }
891
892 fn search_all(&self, id: SearchAllId) -> String {
893 let Some(s) = self.c.plans.search_all.get(id as usize) else { return format!("SearchAll search-all{id}?") };
894 let keys = s.keys.iter().map(|k| {
895 format!("{} = {} [{}{}]", self.comparand(&k.key), self.comparand(&k.value), compare(k.how), if k.ascending { "" } else { ", descending" })
896 });
897 format!("SearchAll {} [{}] within {} when {}", self.place(s.index), self.store(&s.store), self.count(&s.count), join(keys, " and "))
898 }
899
900 fn file_op(&self, id: FileOpId) -> String {
901 let Some(op) = self.c.services.file_ops.get(id as usize) else { return format!("File file-op{id}?") };
902 let file = self.file(op.file);
903 let (text, at_end) = match &op.verb {
904 FileVerb::Open(mode) => (format!("OPEN {} {file}", open_mode(*mode)), false),
905 FileVerb::Close => (format!("CLOSE {file}"), false),
906 FileVerb::CloseWith(closing) => (format!("CLOSE {file} {}", closing_text(*closing)), false),
907 FileVerb::Read { sequential, previous, into, key } => {
908 let mut text = format!("READ {file}");
909 text += &if *sequential { " sequential".to_owned() } else { format!(" key {key}") };
910 if *previous {
911 text += " previous";
912 }
913 if let Some((p, plan)) = into {
914 text += &format!(" into {}{}", self.place(*p), self.moved(plan, SenderCheck::None));
915 }
916 (text, *sequential)
917 }
918 FileVerb::Write { record, from, advancing } => {
919 let mut text = format!("WRITE {}{}", self.place(*record), self.sender(from.as_ref()));
920 if let Some(a) = advancing {
921 text += &format!(" advancing {}", self.advance(a));
922 }
923 (text, false)
924 }
925 FileVerb::Rewrite { record, from } => (format!("REWRITE {}{}", self.place(*record), self.sender(from.as_ref())), false),
926 FileVerb::Delete => (format!("DELETE {file}"), false),
927 FileVerb::Start { rel, key } => {
928 let rel = match rel {
929 StartRel::Equal => "=",
930 StartRel::Greater => ">",
931 StartRel::NotLess => ">=",
932 };
933 let key = match key {
934 StartKey::Prime => "prime".to_owned(),
935 StartKey::Named { key, span } => format!("{key} +{} len {}", span.offset, span.len),
936 StartKey::Relative(value) => format!("relative {}", self.int(value)),
937 StartKey::RelativeKey => "relative key".to_owned(),
938 };
939 (format!("START {file} key {rel} {key}"), false)
940 }
941 };
942 let (on, not_on) = if at_end { ("at end", "not at end") } else { ("invalid key", "not invalid key") };
943 let mut phrases = phrase_words(op.phrase, on, not_on);
944 phrases.extend(phrase_words(op.end_of_page, "end-of-page", "not end-of-page"));
945 format!("File {text}{}", attrs('{', phrases))
946 }
947
948 fn sender(&self, from: Option<&FromMove>) -> String {
949 from.map_or_else(String::new, |m| format!(" <- {}{}", self.operand(&m.from), self.moved(&m.plan, m.check)))
950 }
951
952 fn advance(&self, a: &Advance) -> String {
953 let side = |before: bool| if before { "before" } else { "after" };
954 match a {
955 Advance::Lines { before, count } => format!("{} {} lines", side(*before), self.int(count)),
956 Advance::Page { before } => format!("{} page", side(*before)),
957 Advance::Mnemonic { before, space } => format!(
958 "{} {}",
959 side(*before),
960 match space {
961 Spacing::Lines(n) => format!("{n} lines"),
962 Spacing::Channel(c) => format!("channel {c}"),
963 Spacing::PageMode => "page mode".to_owned(),
964 }
965 ),
966 }
967 }
968
969 fn call(&self, id: CallId) -> String {
970 let Some(c) = self.c.services.calls.get(id as usize) else { return format!("Call call{id}?") };
971 let target = match &c.target {
972 CallTarget::Named { name, le: None } => self.literal(*name),
973 CallTarget::Named { name, le: Some(service) } => {
974 let service = format!("{service:?}").to_ascii_uppercase();
975 format!("{} or {service}", self.literal(*name))
976 }
977 CallTarget::Dynamic(o) => self.operand(o),
978 CallTarget::Pointer(p) => format!("pointer {}", self.place(*p)),
979 CallTarget::Entry(p) => format!("entry {}", self.place(*p)),
980 };
981 let mut text = format!("Call {target}");
982 if !c.args.is_empty() {
983 let args = c.args.iter().map(|a| match a {
984 CallArg::Reference(p) => self.place(*p),
985 CallArg::Content(chars) => format!("content {}", self.chars(chars)),
986 CallArg::Value(o) => format!("value {}", self.operand(o)),
987 CallArg::Omitted => "omitted".to_owned(),
988 });
989 text += &format!(" using {}", join(args, ", "));
990 }
991 if let Some(r) = c.returning {
992 text += &format!(" returning {}", self.place(r));
993 }
994 text + &attrs('{', [yes(c.on_exception, "on exception"), yes(c.not_on_exception, "not on exception")].into_iter().flatten().collect())
995 }
996
997 fn sort_keys(&self, keys: &SortKeys) -> String {
998 let named = keys.keys.iter().map(|k| {
999 let item = self.items.get(k.item as usize).and_then(|i| i.name).map_or_else(|| format!("+{} len {}", k.offset, k.len), |s| self.name(s));
1000 format!("{} {item}{}", if k.ascending { "ascending" } else { "descending" }, if k.collated { " collated" } else { "" })
1001 });
1002 format!("keys {}{}", join(named, ", "), if keys.collating.is_some() { " {collating sequence}" } else { "" })
1003 }
1004
1005 fn sort(&self, id: SortId) -> String {
1006 match self.c.services.sorts.get(id as usize) {
1007 None => format!("Sort sort{id}?"),
1008 Some(SortPlan::File(s)) => {
1009 let io = |io: &Option<SortIo>, files: &str, procedure: &str| match io {
1010 None => format!("{procedure} none"),
1011 Some(SortIo::Files(list)) => format!("{files} {}", join(list.iter().map(|&k| self.file(k)), " ")),
1012 Some(SortIo::Procedure(r)) => format!("{procedure} procedure {}", self.range(*r)),
1013 };
1014 format!(
1015 "Sort {} {} {} {} {}{}",
1016 if s.merge { "merge" } else { "file" },
1017 self.file(s.sd),
1018 self.sort_keys(&s.keys),
1019 io(&s.input, "using", "input"),
1020 io(&s.output, "giving", "output"),
1021 attrs('{', vec![format!("sort-return {}", self.place(s.sort_return)), format!("sort-control {}", self.place(s.sort_control))])
1022 )
1023 }
1024 Some(SortPlan::Table(t)) => {
1025 format!("Sort table {} first {} within {} stride {} {}", self.name(t.name), self.place(t.first), self.count(&t.count), t.stride, self.sort_keys(&t.keys))
1026 }
1027 }
1028 }
1029
1030 fn release(&self, id: ReleaseId) -> String {
1031 let Some(r) = self.c.services.releases.get(id as usize) else { return format!("Release release{id}?") };
1032 let file = r.file.map_or_else(|| self.name(r.name), |k| self.file(k));
1033 format!("Release {}{}{}", self.place(r.record), self.sender(r.from.as_ref()), attrs('{', vec![format!("file {file}"), format!("sort-return {}", self.place(r.sort_return))]))
1034 }
1035
1036 fn return_op(&self, id: ReturnId) -> String {
1037 let Some(r) = self.c.services.returns.get(id as usize) else { return format!("Return return{id}?") };
1038 let file = r.file.map_or_else(|| self.name(r.name), |k| self.file(k));
1039 let into = r.into.as_ref().map_or_else(String::new, |(p, plan)| format!(" into {}{}", self.place(*p), self.moved(plan, SenderCheck::None)));
1040 format!("Return {file}{into}{}", attrs('{', vec![format!("sort-return {}", self.place(r.sort_return))]))
1041 }
1042
1043 fn report_name(&self, report: u32) -> String {
1044 self.c.services.report.reports.get(report as usize).map_or_else(|| format!("report{report}?"), |r| word(&r.name))
1045 }
1046
1047 fn report_op(&self, op: &ReportOp) -> String {
1048 match *op {
1049 ReportOp::Initiate(r) => format!("Report Initiate {}", self.report_name(r)),
1050 ReportOp::Generate { report, detail } => {
1051 let group = detail.map_or_else(String::new, |d| {
1052 let name = self.c.services.report.reports.get(report as usize).and_then(|r| r.groups.get(d as usize)).and_then(|g| g.name.as_deref());
1053 format!(" detail {}", name.map_or_else(|| format!("group{d}"), word))
1054 });
1055 format!("Report Generate {}{group}", self.report_name(report))
1056 }
1057 ReportOp::Terminate(r) => format!("Report Terminate {}", self.report_name(r)),
1058 ReportOp::Suppress => "Report Suppress".to_owned(),
1059 }
1060 }
1061
1062 fn invoke(&self, id: InvokeId) -> String {
1063 let Some(i) = self.c.services.invokes.get(id as usize) else { return format!("Invoke invoke{id}?") };
1064 let receiver = match &i.receiver {
1065 Receiver::SelfRef => "SELF".to_owned(),
1066 Receiver::Super => "SUPER".to_owned(),
1067 Receiver::Class { name, external } if name == external => format!("class {}", self.name(*name)),
1068 Receiver::Class { name, external } => format!("class {} external {}", self.name(*name), self.string(*external)),
1069 Receiver::Object(p) => self.place(*p),
1070 };
1071 let method = match &i.method {
1072 MethodName::New => "NEW".to_owned(),
1073 MethodName::Named(s) => self.literal(*s),
1074 MethodName::Dynamic(p) => self.place(*p),
1075 };
1076 let mut text = format!("Invoke {receiver} {method}");
1077 if !i.args.is_empty() {
1078 text += &format!(" using {}", join(i.args.iter().map(|(o, sig)| format!("{} as {}", self.operand(o), self.string(*sig))), ", "));
1079 }
1080 if let Some((p, sig)) = &i.returning {
1081 text += &format!(" returning {} as {}", self.place(*p), self.string(*sig));
1082 }
1083 text + &attrs('{', [yes(i.on_exception, "on exception"), yes(i.not_on_exception, "not on exception")].into_iter().flatten().collect())
1084 }
1085
1086 fn cics(&self, id: CicsId) -> String {
1087 let Some(written) = self.c.services.cics.get(id as usize) else { return format!("Cics cics{id}?") };
1088 let Ok(CicsCommand { name: _, command, resp, sinks }) = written.clone().map(&mut Names(self));
1089 let mut words = vec![command.name().to_owned()];
1090 self.cics_options(&command, &mut words);
1091 option(&mut words, "RESP", &resp.resp);
1092 option(&mut words, "RESP2", &resp.resp2);
1093 flag(&mut words, "NOHANDLE", resp.nohandle);
1094 let mut how = Vec::new();
1095 if self.symbol(written.name) != Some(command.name()) {
1096 how.push(format!("written {}", self.string(written.name)));
1097 }
1098 if !sinks.is_empty() {
1099 how.push(format!("sinks {}", join(sinks.iter().map(|(p, s)| format!("{p} {}", s.kind())), " ")));
1100 }
1101 format!("Cics {}{}", words.join(" "), attrs('{', how))
1102 }
1103
1104 fn sql(&self, ordinal: SqlId) -> String {
1105 let Some(e) = (ordinal as usize).checked_sub(1).and_then(|k| self.sql.get(k)) else { return format!("Sql {ordinal}") };
1106 let text = if self.symbol(e.text).is_some_and(|t| !t.is_empty()) { self.string(e.text) } else { self.name(e.verb) };
1107 let hosts = |key: &str, list: &[super::HostPlace]| if list.is_empty() { String::new() } else { format!(" {key} ({})", join(list.iter().map(|h| self.host(h)), ", ")) };
1108 let statement = match &e.statement {
1109 SqlStatement::Query { inputs, into } => format!("query{}{}", hosts("inputs", inputs), hosts("into", into)),
1110 SqlStatement::Change { delete, inputs, current_of } => {
1111 let current = current_of.map_or_else(String::new, |c| format!(" current of {}", self.name(c)));
1112 format!("{}{}{current}", if *delete { "delete" } else { "change" }, hosts("inputs", inputs))
1113 }
1114 SqlStatement::Open { cursor, inputs } => format!("open {}{}", self.name(*cursor), hosts("inputs", inputs)),
1115 SqlStatement::Fetch { cursor, into } => format!("fetch {}{}", self.name(*cursor), hosts("into", into)),
1116 SqlStatement::Close { cursor } => format!("close {}", self.name(*cursor)),
1117 SqlStatement::Commit => "commit".to_owned(),
1118 SqlStatement::Rollback => "rollback".to_owned(),
1119 SqlStatement::Declaration => "declaration".to_owned(),
1120 SqlStatement::Unsupported(what) => format!("unsupported {}", self.string(*what)),
1121 SqlStatement::Connect { what, location } => format!("connect {}{}", self.string(*what), hosts("location", location)),
1122 SqlStatement::Prepare { name, source } => format!("prepare {}{}", self.name(*name), hosts("from", source)),
1123 SqlStatement::ExecuteImmediate { source } => format!("execute immediate{}", hosts("from", source)),
1124 SqlStatement::Execute { name, inputs } => format!("execute {}{}", self.name(*name), hosts("using", inputs)),
1125 SqlStatement::OpenPrepared { cursor, statement, inputs } => format!("open {} for {}{}", self.name(*cursor), self.name(*statement), hosts("using", inputs)),
1126 SqlStatement::Describe { name, descriptor, names } => format!("describe {} into {} {names:?}", self.name(*name), self.place(*descriptor)),
1127 SqlStatement::PrepareInto { name, source, descriptor, names } => format!("prepare {} into {} {names:?}{}", self.name(*name), self.place(*descriptor), hosts("from", source)),
1128 SqlStatement::ExecuteDescriptor { name, descriptor } => format!("execute {} using descriptor {}", self.name(*name), self.place(*descriptor)),
1129 SqlStatement::OpenDescriptor { cursor, statement, descriptor } => format!("open {} for {} using descriptor {}", self.name(*cursor), self.name(*statement), self.place(*descriptor)),
1130 SqlStatement::FetchDescriptor { cursor, descriptor } => format!("fetch {} using descriptor {}", self.name(*cursor), self.place(*descriptor)),
1131 SqlStatement::FetchRowset { cursor, rows, into, enabled } => {
1132 let disabled = if *enabled { "" } else { " (no rowset positioning)" };
1133 format!("fetch rowset {}{disabled}{}{}", self.name(*cursor), self.rows(rows), self.arrays("into", into))
1134 }
1135 SqlStatement::InsertRows { inputs, rows, atomic } => format!("insert rows{}{}{}", if *atomic { " atomic" } else { " not atomic" }, self.rows(rows), self.arrays("inputs", inputs)),
1136 SqlStatement::Call { procedure, args } => format!("call {}{}", self.name(*procedure), hosts("arguments", args)),
1137 };
1138 format!("Sql {ordinal} {text} {statement}{}", attrs('{', yes(e.with_hold, "with hold").into_iter().collect()))
1139 }
1140
1141 fn rows(&self, rows: &super::RowCount) -> String {
1142 match rows {
1143 super::RowCount::Implicit => String::new(),
1144 super::RowCount::Constant(n) => format!(" for {n} rows"),
1145 super::RowCount::Host(h) => format!(" for ({}) rows", self.host(h)),
1146 }
1147 }
1148
1149 fn arrays(&self, key: &str, list: &[super::HostArray]) -> String {
1150 if list.is_empty() {
1151 return String::new();
1152 }
1153 let array = |a: &super::HostArray| match a.array {
1154 Some(d) => format!("{} array {} by {} indicator by {}", self.host(&a.place), d.count, d.stride, d.indicator_stride),
1155 None => self.host(&a.place),
1156 };
1157 format!(" {key} ({})", join(list.iter().map(array), ", "))
1158 }
1159
1160 fn host(&self, h: &super::HostPlace) -> String {
1161 let mut text = self.place(h.var);
1162 if let Some((offset, len)) = h.member {
1163 text += &format!(" member +{offset} len {len}");
1164 }
1165 text += &match &h.ty {
1166 Ok(ty) => format!(" [{}]", host_type(ty)),
1167 Err(a) => format!(" [refused {}]", abend_ref(*a)),
1168 };
1169 if let Some((p, offset)) = h.indicator {
1170 text += &format!(" indicator {} +{offset}", self.place(p));
1171 }
1172 text
1173 }
1174
1175 fn ccsid(&self, c: &Ccsid) -> Option<String> {
1176 match c {
1177 Ccsid::Unnamed => None,
1178 Ccsid::CodePage => Some("encoding codepage".to_owned()),
1179 Ccsid::Operand(o) => Some(format!("encoding {}", self.operand(o))),
1180 }
1181 }
1182
1183 fn markup(&self, id: MarkupId) -> String {
1184 let Some(m) = self.c.services.markup.get(id as usize) else { return format!("Markup markup{id}?") };
1185 let subscripts = |s: &[IntExpr]| (!s.is_empty()).then(|| format!("subscripts ({})", join(s.iter().map(|e| self.int(e)), ", ")));
1186 let (verb, words) = match m {
1187 Markup::JsonGenerate(g) => {
1188 let name = g.name.map_or_else(|| "name omitted".to_owned(), |n| format!("name {}", self.raw(n)));
1189 let mut words = vec![format!("{} <- {}", self.place(g.receiver), self.place(g.from))];
1190 words.extend(subscripts(&g.subscripts));
1191 words.push(name);
1192 words.extend(self.ccsid(&g.encoding));
1193 words.extend(g.count.as_ref().map(|c| format!("count {}", self.stored(c))));
1194 words.push(format!("code {}", self.stored(&g.code)));
1195 ("JSON GENERATE", words)
1196 }
1197 Markup::XmlGenerate(g) => {
1198 let mut words = vec![format!("{} <- {}", self.place(g.receiver), self.place(g.from))];
1199 words.extend(subscripts(&g.subscripts));
1200 words.extend(self.ccsid(&g.encoding));
1201 words.extend(g.namespace.as_ref().map(|o| format!("namespace {}", self.operand(o))));
1202 words.extend(g.prefix.as_ref().map(|o| format!("prefix {}", self.operand(o))));
1203 words.extend(yes(g.declaration, "declaration"));
1204 words.extend(yes(g.suppressing, "suppress"));
1205 words.extend(g.count.as_ref().map(|c| format!("count {}", self.stored(c))));
1206 words.push(format!("code {}", self.stored(&g.code)));
1207 ("XML GENERATE", words)
1208 }
1209 Markup::XmlParse(p) => {
1210 let mut words = vec![self.place(p.document)];
1211 words.extend(p.encoding.as_ref().map(|o| format!("encoding {}", self.operand(o))));
1212 words.extend(yes(p.national, "returning national"));
1213 words.push(format!("procedure {}", self.range(p.procedure)));
1214 words.push(format!("event {}", self.place(p.event)));
1215 words.push(format!("code {}", self.stored(&p.code)));
1216 words.push(format!("information {}", self.stored(&p.information)));
1217 words.push(format!("code-value {}", self.int(&p.code_value)));
1218 ("XML PARSE", words)
1219 }
1220 Markup::JsonParse(p) => {
1221 let mut words = vec![format!("{} <- {}", self.place(p.into), self.place(p.source))];
1222 words.extend(subscripts(&p.subscripts));
1223 words.extend(self.ccsid(&p.encoding));
1224 words.extend(yes(p.ignore_all, "ignoring null for all"));
1225 words.push(format!("code {}", self.stored(&p.code)));
1226 words.push(format!("status {}", self.stored(&p.status)));
1227 ("JSON PARSE", words)
1228 }
1229 };
1230 let (on, not_on) = m.phrases();
1231 let phrases = [yes(on, "on exception"), yes(not_on, "not on exception")].into_iter().flatten().collect();
1232 format!("Markup m{id} {verb} {}{}", words.join(" "), attrs('{', phrases))
1233 }
1234
1235 fn tables(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1236 for (k, p) in self.c.places.iter().enumerate() {
1237 writeln!(f, "{}", self.place_row(k, p))?;
1238 }
1239 for (k, c) in self.c.consts.iter().enumerate() {
1240 writeln!(f, "const c{k} {}", self.constant(c))?;
1241 }
1242 for (k, a) in self.c.abends.iter().enumerate() {
1243 writeln!(f, "abend a{k} {} {}{}", a.code, self.string(a.message), a.at.map_or_else(String::new, |at| self.at(at)))?;
1244 }
1245 let s = self.c.services;
1246 for (k, d) in s.files.iter().enumerate() {
1247 writeln!(f, "file {k} {}", self.file_row(d))?;
1248 }
1249 for (k, e) in s.entries.iter().enumerate() {
1250 let using = join(e.using.iter().map(|&r| self.linkage(r)), " ");
1251 writeln!(f, "entry {k} {} paragraph {} block {} using ({using})", self.name(e.name), self.para(e.paragraph), label(e.block))?;
1252 }
1253 for (k, plan) in self.c.plans.init.iter().enumerate() {
1254 for field in &plan.fields {
1255 let value = match &field.value {
1256 InitValue::Default(v) => figurative(*v).to_owned(),
1257 InitValue::Value(c) => self.konst(*c),
1258 InitValue::Replacing(o) => format!("replacing {}", self.operand(o)),
1259 };
1260 let scaling = if field.scaling == 0 { String::new() } else { format!(" scaling {}", field.scaling) };
1261 writeln!(f, "init {k} +{} len {} <- {value}{}{scaling}", field.offset, field.len, self.moved(&field.store, SenderCheck::None))?;
1262 }
1263 }
1264 for (field, p, ty) in &s.sqlca.fields {
1265 writeln!(f, "sqlca {} {} [{}]", sqlca_field(*field), self.place(*p), host_type(ty))?;
1266 }
1267 let modes = s.declaratives.modes.iter().zip(MODES).filter_map(|(r, mode)| r.map(|r| format!("{mode} {}", self.range(r))));
1268 for mode in modes {
1269 writeln!(f, "declaratives {mode}")?;
1270 }
1271 if let Some((offset, len)) = s.declaratives.debug_item {
1272 writeln!(f, "declaratives debug-item program+{offset} len {len}")?;
1273 }
1274 self.scope(f)?;
1275 if let Some(d) = &s.function {
1276 writeln!(f, "function params ({}) returning {}", self.places(&d.params), self.place(d.returning))?;
1277 }
1278 self.reports(f)?;
1279 for (k, m) in s.markup.iter().enumerate() {
1280 self.markup_nodes(f, k, m)?;
1281 }
1282 if let Some(class) = &s.class {
1283 self.class(f, class)?;
1284 }
1285 Ok(())
1286 }
1287
1288 fn place_row(&self, k: usize, p: &Place) -> String {
1289 let mut text = format!("place p{k} {} {}+{} len {} {}", self.reference(p, &[]), base(p.base), p.offset, p.len, kind(&p.kind));
1290 if p.scaling != 0 {
1291 text += &format!(" scaling {}", p.scaling);
1292 }
1293 for o in &p.moved {
1294 text += &format!(" moved {}", self.odo(o));
1295 }
1296 for s in &p.subscripts {
1297 text += &format!(" stride {}", s.stride);
1298 if let Some(n) = s.check {
1299 text += &format!(" check {n}");
1300 }
1301 }
1302 if let Some(t) = p.table {
1303 text += &format!(" table check {}+{}", t.displacement, t.extent);
1304 }
1305 for o in &p.odo {
1306 text += &format!(" odo {}", self.odo(o));
1307 }
1308 if p.refmod.as_ref().is_some_and(|r| r.check) {
1309 text += " refmod check";
1310 }
1311 match p.numcheck.lax {
1312 None => {}
1313 Some(LaxRedefinition::Signed) => text += " numcheck lax signed",
1314 Some(LaxRedefinition::LeadingSpaces(n)) => text += &format!(" numcheck lax {n} leading spaces"),
1315 }
1316 if p.numcheck.removed {
1317 text += " numcheck removed";
1318 }
1319 text + &self.at(p.at)
1320 }
1321
1322 fn file_row(&self, d: &FileDesc) -> String {
1323 let organization = match d.organization {
1324 Organization::Sequential => "sequential",
1325 Organization::LineSequential => "line-sequential",
1326 Organization::Indexed => "indexed",
1327 Organization::Relative => "relative",
1328 };
1329 let access = match d.access {
1330 Access::Sequential => "sequential",
1331 Access::Random => "random",
1332 Access::Dynamic => "dynamic",
1333 };
1334 let format = match d.format {
1335 Format::Fixed => "fixed",
1336 Format::Variable => "variable",
1337 Format::Text => "text",
1338 };
1339 let mut text = format!("{} assign {} {organization} access {access} format {format} read {} to {}", self.name(d.name), self.name(d.assign), d.read_lengths.0, d.read_lengths.1);
1340 let flags = [yes(d.optional, "optional"), yes(d.fixed, "fixed-length"), yes(d.sort, "sort")];
1341 text += &join(flags.into_iter().flatten().map(|s| format!(" {s}")), "");
1342 if let Some(min) = d.record_min {
1343 text += &format!(" record-min {min}");
1344 }
1345 if let Some(dep) = &d.depending {
1346 text += &format!(" depending {} from {} to {}", self.place(dep.item), dep.lengths.0, dep.lengths.1);
1347 }
1348 if let Some((p, plan)) = &d.status {
1349 text += &format!(" status {}{}", self.place(*p), self.moved(plan, SenderCheck::None));
1350 }
1351 if let Some(keys) = &d.keys {
1352 text += &format!(" key +{} len {}", keys.prime.offset, keys.prime.len);
1353 for (span, duplicates) in &keys.alternates {
1354 text += &format!(" alternate +{} len {}{}", span.offset, span.len, if *duplicates { " duplicates" } else { "" });
1355 }
1356 }
1357 if let Some(r) = &d.relative {
1358 let digits = r.digits.map_or_else(String::new, |n| format!(" digits {n}"));
1359 text += &format!(" relative-key {} [{}] value {}{digits}", self.place(r.place), self.store(&r.store), self.int(&r.value));
1360 }
1361 if let Some(l) = &d.linage {
1362 text += &format!(" linage {}", self.int(&l.lines));
1363 for (key, value) in [("footing", &l.footing), ("top", &l.top), ("bottom", &l.bottom)] {
1364 if let Some(v) = value {
1365 text += &format!(" {key} {}", self.int(v));
1366 }
1367 }
1368 if let Some(c) = &l.counter {
1369 text += &format!(" counter {}", self.stored(c));
1370 }
1371 }
1372 if let Some(c) = d.carriage {
1373 text += &format!(" carriage {}{}", if c.machine { "machine" } else { "asa" }, if c.reserved { " reserved" } else { "" });
1374 }
1375 if let Some(r) = d.error {
1376 text += &format!(" error {}", self.range(r));
1377 }
1378 if let Some(a) = d.assign_item {
1379 text += &format!(" assign-item {} @{}", self.place(a.place), a.select);
1380 }
1381 text
1382 }
1383
1384 fn scope(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1385 let s = &self.c.services.scope;
1386 for &c in &s.containers {
1387 writeln!(f, "scope container {}", self.name(c))?;
1388 }
1389 for (record, binding) in &s.records {
1390 let binding = match binding {
1391 Binding::External { name, size } => format!("external {} size {size}", self.name(*name)),
1392 Binding::ExternalFile(k) => format!("external file {}", self.file(*k)),
1393 Binding::Global { program, section, name } => format!("global {} of {} in {}", self.name(*name), scope_section(*section), self.name(*program)),
1394 };
1395 writeln!(f, "scope record {} {binding}", self.linkage(*record))?;
1396 }
1397 for shared in &s.files {
1398 let from = match (shared.external, shared.declared_in) {
1399 (true, _) => "external".to_owned(),
1400 (false, Some(p)) => format!("global in {}", self.name(p)),
1401 (false, None) => "global".to_owned(),
1402 };
1403 writeln!(f, "scope file {} {from}", self.file(shared.file))?;
1404 }
1405 for (file, record) in &s.areas {
1406 writeln!(f, "scope area {} {}", self.file(*file), self.linkage(*record))?;
1407 }
1408 for g in &s.globals {
1409 let at = match g.at {
1410 GlobalAt::Program(offset) => format!("program+{offset}"),
1411 GlobalAt::Local(offset) => format!("local+{offset}"),
1412 GlobalAt::Linkage(record) => self.linkage(record),
1413 };
1414 writeln!(f, "scope global {} of {} at {at}", self.name(g.name), scope_section(g.section))?;
1415 }
1416 for (file, range) in &s.global_files {
1417 writeln!(f, "scope global-error {} {}", self.file(*file), self.range(*range))?;
1418 }
1419 for (mode, r) in MODES.iter().zip(&s.global_modes) {
1420 if let Some(r) = r {
1421 writeln!(f, "scope global-error {mode} {}", self.range(*r))?;
1422 }
1423 }
1424 Ok(())
1425 }
1426
1427 fn reports(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1428 let w = &self.c.services.report;
1429 if let Some(p) = w.print_switch {
1430 writeln!(f, "report print-switch {}", self.place_at(p))?;
1431 }
1432 for (k, r) in w.reports.iter().enumerate() {
1433 let mut text = format!("report {k} {} file {} width {}", word(&r.name), self.file_at(r.file), r.width);
1434 if let Some(c) = r.code {
1435 text += &format!(" code {}", self.konst(c));
1436 }
1437 if let Some(p) = r.page {
1438 text += &format!(" page limit {} heading {} first-detail {} last-detail {} footing {}", p.limit, p.heading, p.first_detail, p.last_detail, p.footing);
1439 }
1440 text += &format!(" page-counter {} line-counter {} state {}", self.place_at(r.page_counter), self.place_at(r.line_counter), self.place_at(r.state));
1441 let headings = [("report-heading", r.report_heading), ("page-heading", r.page_heading), ("page-footing", r.page_footing), ("report-footing", r.report_footing)];
1442 for (key, group) in headings {
1443 if let Some(g) = group {
1444 text += &format!(" {key} group {g}");
1445 }
1446 }
1447 for (key, list) in [("control-headings", &r.control_headings), ("control-footings", &r.control_footings)] {
1448 if list.iter().any(Option::is_some) {
1449 text += &format!(" {key} ({})", join(list.iter().map(|g| g.map_or_else(|| "-".to_owned(), |g| g.to_string())), " "));
1450 }
1451 }
1452 if let Some(n) = r.first_detail_written {
1453 text += &format!(" first-detail-written {n}");
1454 }
1455 writeln!(f, "{text}")?;
1456 for (c, control) in r.controls.iter().enumerate() {
1457 writeln!(f, "report {k} control {c} {} saved +{} len {}", self.place(control.reference), control.saved, control.len)?;
1458 }
1459 for (g, group) in r.groups.iter().enumerate() {
1460 let name = group.name.as_deref().map_or_else(|| "-".to_owned(), word);
1461 let mut text = format!("report {k} group {g} {name} {} level {}", group_kind(group.kind), group.level);
1462 if let Some(n) = group.next_group {
1463 text += &format!(" next-group {}", next_group(n));
1464 }
1465 if let Some(i) = group.indicate {
1466 text += &format!(" indicate +{i}");
1467 }
1468 if let Some(r) = group.declarative {
1469 text += &format!(" declarative {}", self.range(r));
1470 }
1471 if !group.totals.is_empty() {
1472 text += &format!(" totals ({})", join(group.totals.iter().map(|t| format!("sum{t}")), " "));
1473 }
1474 writeln!(f, "{text}")?;
1475 for (l, line) in group.lines.iter().enumerate() {
1476 writeln!(f, "report {k} group {g} line {l} {}", line_number(line.number))?;
1477 for field in &line.fields {
1478 writeln!(f, "report {k} group {g} line {l} {}", self.report_field(field))?;
1479 }
1480 }
1481 for field in &group.unprinted {
1482 writeln!(f, "report {k} group {g} unprinted {}", self.report_field(field))?;
1483 }
1484 for (key, list) in [("cross", &group.cross), ("roll", &group.rolls)] {
1485 for (sum, origin) in list {
1486 writeln!(f, "report {k} group {g} {key} sum{sum} <- {}", self.origin(origin))?;
1487 }
1488 }
1489 }
1490 for (s, sum) in r.sums.iter().enumerate() {
1491 let reset = sum.reset.map_or_else(String::new, |l| format!(" reset on control {l}"));
1492 writeln!(f, "report {k} sum{s} {}{reset}", self.place_at(sum.total))?;
1493 }
1494 for t in &r.subtotals {
1495 let adding = match &t.adding {
1496 Adding::EveryGenerate => "every generate".to_owned(),
1497 Adding::Upon(groups) => format!("upon groups ({})", join(groups.iter().map(usize::to_string), " ")),
1498 Adding::Correlated(groups) => format!("correlated groups ({})", join(groups.iter().map(usize::to_string), " ")),
1499 };
1500 writeln!(f, "report {k} subtotal sum{} <- {} {adding}", t.sum, self.comparand(&t.operand))?;
1501 }
1502 }
1503 Ok(())
1504 }
1505
1506 fn place_at(&self, place: usize) -> String {
1507 u32::try_from(place).map_or_else(|_| format!("p{place}?"), |p| self.place(p))
1508 }
1509
1510 fn report_field(&self, field: &Field) -> String {
1511 let content = match &field.content {
1512 FieldContent::Source(x) => format!("source {}", self.comparand(x)),
1513 FieldContent::Value(v) => format!("value {}", self.konst(*v)),
1514 FieldContent::Sum(s) => format!("sum{s}"),
1515 FieldContent::Program => "program".to_owned(),
1516 };
1517 let flags = [yes(field.group_indicate, "group indicate"), yes(field.blank_when_zero, "blank-when-zero"), yes(field.rounded, "rounded")];
1518 format!("column {} {} <- {content}{} @{}", field.column, self.place_at(field.item), attrs('{', flags.into_iter().flatten().collect()), self.position(&field.pos))
1519 }
1520
1521 fn origin(&self, origin: &Origin) -> String {
1522 match origin {
1523 Origin::Source(x) => self.comparand(x),
1524 Origin::Value(v) => self.konst(*v),
1525 Origin::Total(s) => format!("sum{s}"),
1526 }
1527 }
1528
1529 fn markup_nodes(&self, f: &mut fmt::Formatter<'_>, k: usize, m: &Markup) -> fmt::Result {
1530 let rows: Vec<String> = match m {
1531 Markup::JsonGenerate(g) => g.nodes.iter().map(|n| self.json_node(n)).collect(),
1532 Markup::XmlGenerate(g) => g.nodes.iter().map(|n| self.xml_node(n)).collect(),
1533 Markup::XmlParse(_) => Vec::new(),
1534 Markup::JsonParse(p) => p.nodes.iter().map(|n| self.parse_node(n)).collect(),
1535 };
1536 for (n, row) in rows.iter().enumerate() {
1537 writeln!(f, "markup m{k} node {n} {row}")?;
1538 }
1539 Ok(())
1540 }
1541
1542 fn node(&self, name: String, offset: u32, moved: &[Odo], len: u32, kind_of: &Kind, occurs: Option<&Count>) -> String {
1544 let mut text = format!("{name} +{offset} len {len} {}", kind(kind_of));
1545 if let Some(c) = occurs {
1546 text += &format!(" occurs {}", self.count(c));
1547 }
1548 for o in moved {
1549 text += &format!(" moved {}", self.odo(o));
1550 }
1551 text
1552 }
1553
1554 fn marker(&self, m: &Marker) -> String {
1555 match m {
1556 Marker::Byte(Some(b)) => format!("byte {}", hex("X", &[*b])),
1557 Marker::Byte(None) => "byte none".to_owned(),
1558 Marker::Condition(c) => format!("condition ({})", self.cond(*c)),
1559 Marker::Refused(a) => format!("refused {}", abend_ref(*a)),
1560 }
1561 }
1562
1563 fn convert(c: &Convert) -> String {
1564 match c {
1565 Convert::Chars { justified } => if *justified { "chars justified" } else { "chars" }.to_owned(),
1566 Convert::National => "national".to_owned(),
1567 Convert::Dbcs => "dbcs".to_owned(),
1568 Convert::Float(p) => format!("float {}", precision(*p)),
1569 Convert::Fixed { integers } => format!("fixed {integers} integers"),
1570 Convert::Scaled { integers, scaling } => format!("fixed {integers} integers scaled {scaling}"),
1571 Convert::Refused(a) => format!("refused {}", abend_ref(*a)),
1572 }
1573 }
1574
1575 fn suppress(list: &[Figurative]) -> String {
1576 if list.is_empty() { String::new() } else { format!(" suppress {}", join(list.iter().map(|f| figurative(*f).to_owned()), " ")) }
1577 }
1578
1579 fn json_node(&self, n: &JsonNode) -> String {
1580 let mut text = self.node(self.raw(n.name), n.offset, &n.moved, n.len, &n.kind, n.occurs.as_ref());
1581 if let Some((place, marker)) = &n.indicator {
1582 let place = place.map_or_else(|a| format!("refused {}", abend_ref(a)), |p| self.place(p));
1583 text += &format!(" indicator {place} {}", self.marker(marker));
1584 }
1585 if let Some(null) = n.null {
1586 text += &format!(" null {}", figurative(null));
1587 }
1588 text + &match &n.value {
1589 JsonValue::Object { members, eligible } => format!(" object ({}){}", members_list(members), if *eligible { " eligible" } else { "" }),
1590 JsonValue::Leaf(JsonLeaf { suppress, boolean, convert }) => {
1591 let boolean = boolean.as_ref().map_or_else(String::new, |m| format!(" boolean {}", self.marker(m)));
1592 format!(" leaf{}{boolean} {}", Self::suppress(suppress), Self::convert(convert))
1593 }
1594 }
1595 }
1596
1597 fn xml_node(&self, n: &XmlNode) -> String {
1598 let text = self.node(self.string(n.name), n.offset, &n.moved, n.len, &n.kind, n.occurs.as_ref());
1599 text + &match &n.value {
1600 XmlValue::Element { members } => format!(" element ({})", members_list(members)),
1601 XmlValue::Members { members } => format!(" members ({})", members_list(members)),
1602 XmlValue::Leaf { form, suppress, convert } => {
1603 let form = match form {
1604 XmlForm::Attribute => "attribute",
1605 XmlForm::Element => "element",
1606 XmlForm::Content => "content",
1607 };
1608 format!(" leaf {form}{} {}", Self::suppress(suppress), Self::convert(convert))
1609 }
1610 }
1611 }
1612
1613 fn set_to(&self, s: &SetTo) -> String {
1614 match s {
1615 SetTo::Nothing => "nothing".to_owned(),
1616 SetTo::Move { place, value, plan } => format!("{} <- {}{}", self.place(*place), self.konst(*value), self.moved(plan, SenderCheck::None)),
1617 SetTo::Refused(a) => format!("refused {}", abend_ref(*a)),
1618 }
1619 }
1620
1621 fn flag(&self, flag: &Flag) -> String {
1622 match flag {
1623 Flag::Set { on, off } => format!("set on {} off {}", self.set_to(on), self.set_to(off)),
1624 Flag::Literals { on, off } => format!(
1625 "literals on {}{} off {}{}",
1626 self.konst(on.0),
1627 self.moved(&on.1, SenderCheck::None),
1628 self.konst(off.0),
1629 self.moved(&off.1, SenderCheck::None)
1630 ),
1631 }
1632 }
1633
1634 fn parse_node(&self, n: &ParseNode) -> String {
1635 let name = match n.name {
1636 Named::Exactly(s) => self.string(s),
1637 Named::Folded(s) => format!("folded {}", self.name(s)),
1638 Named::Omitted => "omitted".to_owned(),
1639 };
1640 let mut text = self.node(name, n.offset, &n.moved, n.len, &n.kind, n.occurs.as_ref());
1641 if n.ignored {
1642 text += " ignoring null";
1643 }
1644 if let Some(Indicator { place, flag }) = &n.indicator {
1645 let place = match place {
1646 None => "-".to_owned(),
1647 Some(Ok(p)) => self.place(*p),
1648 Some(Err(a)) => format!("refused {}", abend_ref(*a)),
1649 };
1650 text += &format!(" indicator {place} {}", self.flag(flag));
1651 }
1652 if let Some((null, plan)) = &n.null {
1653 text += &format!(" null {}{}", figurative(*null), self.moved(plan, SenderCheck::None));
1654 }
1655 text + &match &n.value {
1656 ParseValue::Object { members } => format!(" object ({})", members_list(members)),
1657 ParseValue::Suppressed => " suppressed".to_owned(),
1658 ParseValue::Leaf(ParseLeaf { boolean, text, number }) => {
1659 let mut leaf = " leaf".to_owned();
1660 if let Some(b) = boolean {
1661 leaf += &format!(" boolean {}", self.flag(b));
1662 }
1663 if let Some(plan) = text {
1664 leaf += &format!(" text{}", self.moved(plan, SenderCheck::None));
1665 }
1666 leaf + &match number {
1667 NumberInto::Float(plan) => format!(" number float{}", self.moved(plan, SenderCheck::None)),
1668 NumberInto::Store(store) => format!(" number [{}]", self.store(store)),
1669 NumberInto::Edited(plan) => format!(" number edited{}", self.moved(plan, SenderCheck::None)),
1670 NumberInto::Digits => " number digits".to_owned(),
1671 NumberInto::Incompatible => " number incompatible".to_owned(),
1672 NumberInto::StoreScaled { store, scaling } => format!(" number [{}] scaled {scaling}", self.store(store)),
1673 NumberInto::EditedScaled { plan, scaling } => format!(" number edited{} scaled {scaling}", self.moved(plan, SenderCheck::None)),
1674 }
1675 }
1676 }
1677 }
1678
1679 fn class(&self, f: &mut fmt::Formatter<'_>, class: &Class) -> fmt::Result {
1681 writeln!(f, "class {} inherits {}", self.string(class.external), self.string(class.parent))?;
1682 for (key, part) in [("factory", &class.factory), ("object", &class.object)] {
1683 if let Some(part) = part {
1684 writeln!(f, "class {key} data records ({})", join(part.records.iter().map(|r| format!("+{r}")), " "))?;
1685 write!(f, "{}", Listing::of(&part.data))?;
1686 }
1687 }
1688 for (k, m) in class.methods.iter().enumerate() {
1689 let params = join(m.params.iter().map(|&s| self.string(s)), " ");
1690 let returns = m.returns.map_or_else(String::new, |s| format!(" returns {}", self.string(s)));
1691 let factory = if m.factory { " factory" } else { "" };
1692 writeln!(f, "class method {k} {}{factory} params ({params}){returns} own-records {}", self.name(m.name), m.own_records)?;
1693 write!(f, "{}", Listing::of(&m.code))?;
1694 }
1695 Ok(())
1696 }
1697}
1698
1699struct Names<'p, 'a>(&'p Printer<'a>);
1701
1702impl Handles<PlaceId, Operand, SymId> for Names<'_, '_> {
1703 type Place = String;
1704 type Value = String;
1705 type Text = String;
1706 type Error = Infallible;
1707
1708 fn place(&mut self, place: PlaceId) -> Result<String, Infallible> {
1709 Ok(self.0.place(place))
1710 }
1711
1712 fn value(&mut self, value: Operand) -> Result<String, Infallible> {
1713 Ok(self.0.operand(&value))
1714 }
1715
1716 fn text(&mut self, text: SymId) -> Result<String, Infallible> {
1717 Ok(self.0.name(text))
1718 }
1719}
1720
1721type CicsOpt = Option<Datum<String, String, String>>;
1722
1723fn option(words: &mut Vec<String>, key: &str, value: &CicsOpt) {
1724 match value {
1725 None => {}
1726 Some(Datum::Place(v) | Datum::Value(v) | Datum::Text(v)) => words.push(format!("{key}({v})")),
1727 Some(Datum::Bare) => words.push(key.to_owned()),
1728 }
1729}
1730
1731fn flag(words: &mut Vec<String>, key: &str, on: bool) {
1732 if on {
1733 words.push(key.to_owned());
1734 }
1735}
1736
1737impl Printer<'_> {
1738 fn cics_options(&self, command: &Cics<String, String, String>, w: &mut Vec<String>) {
1740 match command {
1741 Cics::File { verb: _, file, options: o } => {
1742 option(w, "FILE", file);
1743 for (key, value) in [("RIDFLD", &o.ridfld), ("KEYLENGTH", &o.keylength), ("REQID", &o.reqid), ("FROM", &o.from), ("NUMREC", &o.numrec)] {
1744 option(w, key, value);
1745 }
1746 for (key, value) in [("INTO", &o.record.into), ("SET", &o.record.set), ("LENGTH", &o.record.length)] {
1747 option(w, key, value);
1748 }
1749 for (key, on) in [("GENERIC", o.generic), ("RRN", o.rrn), ("GTEQ", o.gteq), ("EQUAL", o.equal), ("UPDATE", o.update)] {
1750 flag(w, key, on);
1751 }
1752 }
1753 Cics::Return { transid, commarea, length, channel, immediate } => {
1754 for (key, value) in [("TRANSID", transid), ("COMMAREA", commarea), ("LENGTH", length), ("CHANNEL", channel)] {
1755 option(w, key, value);
1756 }
1757 flag(w, "IMMEDIATE", *immediate);
1758 }
1759 Cics::Link(t) | Cics::Xctl(t) => {
1760 for (key, value) in [("PROGRAM", &t.program), ("COMMAREA", &t.commarea), ("LENGTH", &t.length)] {
1761 option(w, key, value);
1762 }
1763 }
1764 Cics::Abend { abcode, cancel } => {
1765 option(w, "ABCODE", abcode);
1766 flag(w, "CANCEL", *cancel);
1767 }
1768 Cics::HandleCondition(labels) => {
1769 w.extend(labels.iter().map(|(c, label)| label.map_or_else(|| c.name().to_owned(), |p| format!("{}({})", c.name(), self.para(p)))));
1770 }
1771 Cics::IgnoreCondition(conditions) => w.extend(conditions.iter().map(|c| c.name().to_owned())),
1772 Cics::PushHandle | Cics::PopHandle | Cics::HandleAid | Cics::Freemain | Cics::Enq | Cics::Deq | Cics::Delay | Cics::Unsupported => {}
1773 Cics::HandleAbend { program, label, reset } => {
1774 option(w, "PROGRAM", program);
1775 if let Some(p) = label {
1776 w.push(format!("LABEL({})", self.para(*p)));
1777 }
1778 flag(w, "RESET", *reset);
1779 }
1780 Cics::SendMap { map, mapset, from, maponly, dataonly, cursor, control } => {
1781 for (key, value) in [("MAP", map), ("MAPSET", mapset), ("FROM", from), ("CURSOR", cursor)] {
1782 option(w, key, value);
1783 }
1784 flag(w, "MAPONLY", *maponly);
1785 flag(w, "DATAONLY", *dataonly);
1786 control_flags(w, control);
1787 }
1788 Cics::ReceiveMap { map, mapset, into, set } => {
1789 for (key, value) in [("MAP", map), ("MAPSET", mapset), ("INTO", into), ("SET", set)] {
1790 option(w, key, value);
1791 }
1792 }
1793 Cics::SendControl { cursor, control } => {
1794 option(w, "CURSOR", cursor);
1795 control_flags(w, control);
1796 }
1797 Cics::Receive(r) => {
1798 for (key, value) in [("INTO", &r.into), ("SET", &r.set), ("LENGTH", &r.length)] {
1799 option(w, key, value);
1800 }
1801 }
1802 Cics::Asktime { abstime } => option(w, "ABSTIME", abstime),
1803 Cics::Formattime { abstime, datesep, timesep, outputs } => {
1804 for (key, value) in [("ABSTIME", abstime), ("DATESEP", datesep), ("TIMESEP", timesep)] {
1805 option(w, key, value);
1806 }
1807 for (key, value) in outputs {
1808 option(w, key, &Some(value.clone()));
1809 }
1810 }
1811 Cics::Assign(a) => {
1812 let options = [
1813 ("APPLID", &a.applid),
1814 ("SYSID", &a.sysid),
1815 ("USERID", &a.userid),
1816 ("NETNAME", &a.netname),
1817 ("FACILITY", &a.facility),
1818 ("STARTCODE", &a.startcode),
1819 ("ABCODE", &a.abcode),
1820 ("PROGRAM", &a.program),
1821 ("CWALENG", &a.cwaleng),
1822 ("TWALENG", &a.twaleng),
1823 ];
1824 for (key, value) in options {
1825 option(w, key, value);
1826 }
1827 }
1828 Cics::Getmain { flength, length, initimg, set } => {
1829 for (key, value) in [("FLENGTH", flength), ("LENGTH", length), ("INITIMG", initimg), ("SET", set)] {
1830 option(w, key, value);
1831 }
1832 }
1833 Cics::Syncpoint { rollback } => flag(w, "ROLLBACK", *rollback),
1834 Cics::Address { eib, commarea, cwa, twa } => {
1835 for (key, value) in [("EIB", eib), ("COMMAREA", commarea), ("CWA", cwa), ("TWA", twa)] {
1836 option(w, key, value);
1837 }
1838 }
1839 Cics::SendText { from, length } => {
1840 option(w, "FROM", from);
1841 option(w, "LENGTH", length);
1842 }
1843 Cics::WriteOperator { text, textlength } => {
1844 option(w, "TEXT", text);
1845 option(w, "TEXTLENGTH", textlength);
1846 }
1847 Cics::WriteqTs { queue, from, length, rewrite, item, numitems } => {
1848 for (key, value) in [("QUEUE", queue), ("FROM", from), ("LENGTH", length), ("ITEM", item), ("NUMITEMS", numitems)] {
1849 option(w, key, value);
1850 }
1851 flag(w, "REWRITE", *rewrite);
1852 }
1853 Cics::ReadqTs { queue, next, item, numitems, record } => {
1854 option(w, "QUEUE", queue);
1855 flag(w, "NEXT", *next);
1856 for (key, value) in [("ITEM", item), ("NUMITEMS", numitems), ("INTO", &record.into), ("SET", &record.set), ("LENGTH", &record.length)] {
1857 option(w, key, value);
1858 }
1859 }
1860 Cics::DeleteqTs { queue } | Cics::DeleteqTd { queue } => option(w, "QUEUE", queue),
1861 Cics::WriteqTd { queue, from, length } => {
1862 for (key, value) in [("QUEUE", queue), ("FROM", from), ("LENGTH", length)] {
1863 option(w, key, value);
1864 }
1865 }
1866 Cics::ReadqTd { queue, record } => {
1867 for (key, value) in [("QUEUE", queue), ("INTO", &record.into), ("SET", &record.set), ("LENGTH", &record.length)] {
1868 option(w, key, value);
1869 }
1870 }
1871 Cics::Refused(why) => w.push(format!("{why:?}")),
1872 }
1873 }
1874}
1875
1876fn control_flags(w: &mut Vec<String>, c: &crate::cics::Control) {
1877 for (key, on) in [("ERASE", c.erase), ("FREEKB", c.freekb), ("ALARM", c.alarm), ("FRSET", c.frset)] {
1878 flag(w, key, on);
1879 }
1880}
1881
1882fn word(s: &str) -> String {
1884 if !s.is_empty() && s.chars().all(|c| !c.is_control() && !c.is_whitespace()) { s.to_owned() } else { format!("{s:?}") }
1885}
1886
1887fn quote(s: &str) -> String {
1890 if s.chars().any(char::is_control) { format!("{s:?}") } else { format!("'{}'", s.replace('\'', "''")) }
1891}
1892
1893fn hex(prefix: &str, bytes: &[u8]) -> String {
1894 format!("{prefix}'{}'", join(bytes.iter().map(|b| format!("{b:02X}")), ""))
1895}
1896
1897fn national(units: &[u8]) -> String {
1899 let (pairs, odd) = units.as_chunks::<2>();
1900 let text = odd
1901 .is_empty()
1902 .then(|| char::decode_utf16(pairs.iter().map(|&u| u16::from_be_bytes(u))).collect::<Result<String, _>>().ok())
1903 .flatten()
1904 .filter(|t| !t.chars().any(char::is_control));
1905 text.map_or_else(|| hex("NX", units), |t| format!("N{}", quote(&t)))
1906}
1907
1908fn decimal(n: &Fixed) -> String {
1910 const MOST: u32 = 100;
1911 if n.places.dec > MOST {
1912 return format!("{:?}", n.magnitude);
1913 }
1914 let mut digits = Vec::new();
1915 let mut rest = n.magnitude;
1916 while !rest.is_zero() {
1917 let (q, r) = rest.div_rem(U256::from_u128(10));
1918 digits.push(char::from(b'0' + r.to_u128().and_then(|d| u8::try_from(d).ok()).unwrap_or(0)));
1919 rest = q;
1920 }
1921 let dec = n.places.dec as usize;
1922 while digits.len() <= dec {
1923 digits.push('0');
1924 }
1925 digits.reverse();
1926 let (int, frac): (String, String) = (digits[..digits.len() - dec].iter().collect(), digits[digits.len() - dec..].iter().collect());
1927 let sign = if n.negative { "-" } else { "" };
1928 if frac.is_empty() { format!("{sign}{int}") } else { format!("{sign}{int}.{frac}") }
1929}
1930
1931fn pic(digits: u32, scale: u32, signed: bool) -> String {
1932 let int = digits.saturating_sub(scale);
1933 let mut text = if signed { "S".to_owned() } else { String::new() };
1934 if int > 0 || scale == 0 {
1935 text += &format!("9({int})");
1936 }
1937 if scale > 0 {
1938 text += &format!("V9({scale})");
1939 }
1940 text
1941}
1942
1943fn sign_clause(sign: Option<SignClause>) -> String {
1944 sign.map_or_else(String::new, |s| {
1945 let position = match s.position {
1946 SignPosition::Leading => "leading",
1947 SignPosition::Trailing => "trailing",
1948 };
1949 format!(" sign {position}{}", if s.separate { " separate" } else { "" })
1950 })
1951}
1952
1953fn kind(k: &Kind) -> String {
1954 match *k {
1955 Kind::Group => "group".to_owned(),
1956 Kind::Alnum { justified } => if justified { "alnum justified" } else { "alnum" }.to_owned(),
1957 Kind::National => "national".to_owned(),
1958 Kind::Dbcs { justified, edit } => format!("dbcs{}{}", if justified { " justified" } else { "" }, edit.map_or(String::new(), |e| format!(" edit {e}"))),
1959 Kind::Zoned { digits, scale, signed, sign } => format!("zoned {}{}", pic(digits, scale, signed), sign_clause(sign)),
1960 Kind::Packed { digits, scale, signed } => format!("packed {}", pic(digits, scale, signed)),
1961 Kind::Binary { digits, scale, signed, native } => format!("binary {}{}", pic(digits, scale, signed), if native { " native" } else { "" }),
1962 Kind::Float(p) => format!("float {}", precision(p)),
1963 Kind::NumericEdited { edit, digits, scale, blank_when_zero } => {
1964 format!("numeric-edited edit {edit} {}{}", pic(digits, scale, false), if blank_when_zero { " blank-when-zero" } else { "" })
1965 }
1966 Kind::AlnumEdited { edit } => format!("alnum-edited edit {edit}"),
1967 Kind::Pointer => "pointer".to_owned(),
1968 Kind::Index => "index".to_owned(),
1969 Kind::ObjectReference => "object-reference".to_owned(),
1970 Kind::ProgramPointer => "program-pointer".to_owned(),
1971 }
1972}
1973
1974fn base(b: Base) -> String {
1975 match b {
1976 Base::Program => "program".to_owned(),
1977 Base::Local => "local".to_owned(),
1978 Base::Linkage(n) => format!("linkage{n}"),
1979 Base::ReturnCode => "return-code".to_owned(),
1980 Base::Eib => "eib".to_owned(),
1981 Base::SelfRef => "self".to_owned(),
1982 Base::JniEnv => "jnienv".to_owned(),
1983 Base::Xml(r) => match r {
1984 XmlRegister::Text => "xml-text",
1985 XmlRegister::NText => "xml-ntext",
1986 XmlRegister::Namespace => "xml-namespace",
1987 XmlRegister::NNamespace => "xml-nnamespace",
1988 XmlRegister::Prefix => "xml-namespace-prefix",
1989 XmlRegister::NPrefix => "xml-nnamespace-prefix",
1990 }
1991 .to_owned(),
1992 }
1993}
1994
1995fn precision(p: Precision) -> &'static str {
1996 match p {
1997 Precision::Short => "short",
1998 Precision::Long => "long",
1999 Precision::Extended => "extended",
2000 }
2001}
2002
2003fn figurative(f: Figurative) -> &'static str {
2004 match f {
2005 Figurative::Zero => "ZERO",
2006 Figurative::Space => "SPACE",
2007 Figurative::HighValue => "HIGH-VALUE",
2008 Figurative::LowValue => "LOW-VALUE",
2009 Figurative::Quote => "QUOTE",
2010 Figurative::Null => "NULL",
2011 }
2012}
2013
2014fn binop(op: BinOp) -> &'static str {
2015 match op {
2016 BinOp::Add => "+",
2017 BinOp::Sub => "-",
2018 BinOp::Mul => "*",
2019 BinOp::Div => "/",
2020 BinOp::Pow => "**",
2021 }
2022}
2023
2024fn relop(op: RelOp) -> &'static str {
2025 match op {
2026 RelOp::Eq => "=",
2027 RelOp::Ne => "<>",
2028 RelOp::Lt => "<",
2029 RelOp::Le => "<=",
2030 RelOp::Gt => ">",
2031 RelOp::Ge => ">=",
2032 }
2033}
2034
2035fn compare(c: Compare) -> String {
2036 match c {
2037 Compare::PackedPfd => "packed-pfd".to_owned(),
2038 Compare::Address => "address".to_owned(),
2039 Compare::Float => "float".to_owned(),
2040 Compare::Fixed => "fixed".to_owned(),
2041 Compare::National => "national".to_owned(),
2042 Compare::Dbcs => "dbcs".to_owned(),
2043 Compare::Alphanumeric => "alnum".to_owned(),
2044 Compare::Refused(a) => format!("refused {}", abend_ref(a)),
2045 Compare::References => "references".to_owned(),
2046 Compare::ZonedBytes { zoned_first } => format!("zoned-bytes {}", if zoned_first { "left" } else { "right" }),
2047 }
2048}
2049
2050fn byte_class(c: super::ByteClass) -> String {
2051 use super::ByteClass;
2052 let name = match c {
2053 ByteClass::Packed { signed: true } => "numeric [packed signed]",
2054 ByteClass::Packed { signed: false } => "numeric [packed]",
2055 ByteClass::Zoned { signed: true } => "numeric [zoned signed]",
2056 ByteClass::Zoned { signed: false } => "numeric [zoned]",
2057 ByteClass::Digits => "numeric [digits]",
2058 ByteClass::Alphabetic => "alphabetic",
2059 ByteClass::AlphabeticLower => "alphabetic-lower",
2060 ByteClass::AlphabeticUpper => "alphabetic-upper",
2061 ByteClass::Dbcs => "dbcs",
2062 ByteClass::Kanji => "kanji",
2063 ByteClass::Set { bits } => return format!("class [{}]", (0..=255u8).filter(|&b| bits[usize::from(b / 8)] >> (b % 8) & 1 == 1).map(|b| format!("{b:02X}")).collect::<Vec<_>>().join(" ")),
2064 };
2065 name.to_owned()
2066}
2067
2068fn sign_test(t: SignTest) -> &'static str {
2069 match t {
2070 SignTest::Positive => "positive",
2071 SignTest::Negative => "negative",
2072 SignTest::Zero => "zero",
2073 }
2074}
2075
2076fn sql_test(t: SqlTest) -> &'static str {
2077 match t {
2078 SqlTest::Error => "error",
2079 SqlTest::NotFound => "not found",
2080 SqlTest::Warning => "warning",
2081 }
2082}
2083
2084fn ending(e: Ending) -> &'static str {
2085 match e {
2086 Ending::Goback => "goback",
2087 Ending::StopRun => "stop-run",
2088 Ending::EndOfProgram => "end-of-program",
2089 }
2090}
2091
2092fn range_kind(k: RangeKind) -> &'static str {
2093 match k {
2094 RangeKind::Perform => "perform",
2095 RangeKind::SortProcedure => "sort-procedure",
2096 RangeKind::UseBeforeReporting => "use-before-reporting",
2097 RangeKind::UseProcedure => "use-procedure",
2098 RangeKind::Debugging => "debugging",
2099 RangeKind::Processing => "processing",
2100 }
2101}
2102
2103fn image(i: Image) -> String {
2104 match i {
2105 Image::Bytes => String::new(),
2106 Image::All => " all".to_owned(),
2107 Image::Figurative => " figurative".to_owned(),
2108 Image::Digits { digits } => format!(" digits {digits}"),
2109 Image::Stored => " stored".to_owned(),
2110 }
2111}
2112
2113fn national_from(n: NationalFrom) -> &'static str {
2114 match n {
2115 NationalFrom::Units => "units",
2116 NationalFrom::Decoded => "decoded",
2117 NationalFrom::Figurative => "figurative",
2118 NationalFrom::Dbcs => "dbcs",
2119 }
2120}
2121
2122fn numeric_from(n: NumericFrom) -> String {
2123 match n {
2124 NumericFrom::Value => "value".to_owned(),
2125 NumericFrom::PackedCopy => "packed-copy".to_owned(),
2126 NumericFrom::Float => "float".to_owned(),
2127 NumericFrom::Zero => "zero".to_owned(),
2128 NumericFrom::Fill => "fill".to_owned(),
2129 NumericFrom::Zoned => "zoned".to_owned(),
2130 NumericFrom::DeEdit { edit, digits, scale } => format!("de-edit edit {edit} {}", pic(digits, scale, false)),
2131 }
2132}
2133
2134fn float_from(f: FloatFrom) -> &'static str {
2135 match f {
2136 FloatFrom::Float => "float",
2137 FloatFrom::Fixed => "fixed",
2138 FloatFrom::Zero => "zero",
2139 }
2140}
2141
2142fn accept_from(a: AcceptFrom) -> &'static str {
2143 match a {
2144 AcceptFrom::Sysin => "SYSIN",
2145 AcceptFrom::Date { four_digit_year: false } => "DATE",
2146 AcceptFrom::Date { four_digit_year: true } => "DATE YYYYMMDD",
2147 AcceptFrom::Day { four_digit_year: false } => "DAY",
2148 AcceptFrom::Day { four_digit_year: true } => "DAY YYYYDDD",
2149 AcceptFrom::DayOfWeek => "DAY-OF-WEEK",
2150 AcceptFrom::Time => "TIME",
2151 AcceptFrom::CommandLine => "COMMAND-LINE",
2152 AcceptFrom::ArgumentNumber => "ARGUMENT-NUMBER",
2153 AcceptFrom::ArgumentValue => "ARGUMENT-VALUE",
2154 }
2155}
2156
2157fn open_mode(m: OpenMode) -> &'static str {
2158 match m {
2159 OpenMode::Input => "INPUT",
2160 OpenMode::Output => "OUTPUT",
2161 OpenMode::Extend => "EXTEND",
2162 OpenMode::InputOutput => "I-O",
2163 }
2164}
2165
2166fn closing_text(c: Closing) -> &'static str {
2167 match c {
2168 Closing::Volume => "volume",
2169 Closing::NoRewind => "no rewind",
2170 Closing::Lock => "lock",
2171 }
2172}
2173
2174fn phrase_words(p: Option<Phrase>, on: &str, not_on: &str) -> Vec<String> {
2175 p.map_or_else(Vec::new, |p| [yes(p.on, on), yes(p.not_on, not_on)].into_iter().flatten().collect())
2176}
2177
2178fn host_type(t: &HostType) -> String {
2179 let unsigned = |signed: bool| if signed { "" } else { " unsigned" };
2180 match t {
2181 HostType::SmallInt { signed } => format!("smallint{}", unsigned(*signed)),
2182 HostType::Integer { signed } => format!("integer{}", unsigned(*signed)),
2183 HostType::BigInt { signed } => format!("bigint{}", unsigned(*signed)),
2184 HostType::Decimal { digits, scale, signed } => format!("decimal({digits},{scale}){}", unsigned(*signed)),
2185 HostType::Zoned { digits, scale, signed, sign } => format!("zoned({digits},{scale}){}{}", unsigned(*signed), sign_clause(*sign)),
2186 HostType::Real => "real".to_owned(),
2187 HostType::Double => "double".to_owned(),
2188 HostType::Char(n) => format!("char({n})"),
2189 HostType::VarChar(n) => format!("varchar({n})"),
2190 HostType::Graphic(n) => format!("graphic({n})"),
2191 HostType::VarGraphic(n) => format!("vargraphic({n})"),
2192 HostType::Structure(members) => format!("structure of {}", members.len()),
2193 }
2194}
2195
2196fn sqlca_field(f: SqlcaField) -> String {
2197 match f {
2198 SqlcaField::CaId => "SQLCAID".to_owned(),
2199 SqlcaField::CaBc => "SQLCABC".to_owned(),
2200 SqlcaField::Code => "SQLCODE".to_owned(),
2201 SqlcaField::ErrMl => "SQLERRML".to_owned(),
2202 SqlcaField::ErrMc => "SQLERRMC".to_owned(),
2203 SqlcaField::ErrP => "SQLERRP".to_owned(),
2204 SqlcaField::State => "SQLSTATE".to_owned(),
2205 SqlcaField::ErrD(n) => format!("SQLERRD({n})"),
2206 SqlcaField::Warn(n) => format!("SQLWARN{}", if n == 10 { "A".to_owned() } else { n.to_string() }),
2207 }
2208}
2209
2210fn scope_section(s: Section) -> &'static str {
2211 match s {
2212 Section::WorkingStorage => "working-storage",
2213 Section::LocalStorage => "local-storage",
2214 Section::Linkage => "linkage",
2215 Section::File => "file",
2216 }
2217}
2218
2219fn group_kind(k: GroupKind) -> &'static str {
2220 match k {
2221 GroupKind::ReportHeading => "report-heading",
2222 GroupKind::PageHeading => "page-heading",
2223 GroupKind::ControlHeading => "control-heading",
2224 GroupKind::Detail => "detail",
2225 GroupKind::ControlFooting => "control-footing",
2226 GroupKind::PageFooting => "page-footing",
2227 GroupKind::ReportFooting => "report-footing",
2228 }
2229}
2230
2231fn next_group(n: NextGroup) -> String {
2232 match n {
2233 NextGroup::Line(l) => format!("line {l}"),
2234 NextGroup::Plus(l) => format!("plus {l}"),
2235 NextGroup::NextPage => "next page".to_owned(),
2236 }
2237}
2238
2239fn line_number(n: LineNumber) -> String {
2240 match n {
2241 LineNumber::Line(l) => format!("at {l}"),
2242 LineNumber::Plus(l) => format!("plus {l}"),
2243 LineNumber::NextPage(None) => "next page".to_owned(),
2244 LineNumber::NextPage(Some(l)) => format!("next page at {l}"),
2245 }
2246}
2247
2248fn members_list(members: &[u32]) -> String {
2249 join(members.iter().map(u32::to_string), " ")
2250}
2251
2252const MODES: [&str; 4] = ["input", "output", "i-o", "extend"];
2254
2255#[cfg(test)]
2256mod tests {
2257 use super::*;
2258 use numeric::precision::Places;
2259
2260 #[test]
2261 fn a_number_prints_with_every_decimal_place_it_holds() {
2262 let n = |value: i128, int: u32, dec: u32| decimal(&Fixed::new(value, Places::new(int, dec)));
2263 assert_eq!([n(125, 3, 1), n(-5, 1, 2), n(0, 1, 0), n(1250, 3, 2), n(7, 1, 0)], ["12.5", "-0.05", "0", "12.50", "7"]);
2264 }
2265
2266 #[test]
2267 fn text_prints_on_one_line_whatever_it_holds() {
2268 assert_eq!(quote("IT'S"), "'IT''S'");
2269 assert_eq!(quote("A\nB"), "\"A\\nB\"");
2270 assert_eq!(word("WS-A"), "WS-A");
2271 assert_eq!(word("A B"), "\"A B\"");
2272 assert_eq!(national(&[0, 0x41, 0, 0x42]), "N'AB'");
2273 assert_eq!(national(&[0xD8, 0x00]), "NX'D800'");
2274 assert_eq!(pic(9, 2, true), "S9(7)V9(2)");
2275 assert_eq!(pic(2, 2, false), "V9(2)");
2276 assert_eq!(pic(4, 0, false), "9(4)");
2277 }
2278
2279 #[test]
2280 fn tables_that_refer_to_each_other_in_a_cycle_print_and_stop() {
2281 let (plans, services) = (Plans::default(), Services::default());
2282 let exprs = [Expr::Bin(0, BinOp::Add, 0)];
2283 let conds = [Cond::Rel { a: Comparand::Expr { expr: 0, dmax: 0, mode: Mode::Fixed, prepass: Vec::new() }, op: RelOp::Eq, b: Comparand::Operand(Operand::Const(9)), how: Compare::Fixed }];
2284 let blocks = [Block { ops: vec![Op::Display(4)], end: Terminator::Branch { cond: 0, then: 0, otherwise: 1 } }];
2285 let code = Code {
2286 id: 0,
2287 initial: false,
2288 recursive: false,
2289 paragraphs: &[],
2290 procedure_start: 0,
2291 ranges: &[],
2292 blocks: &blocks,
2293 places: &[],
2294 exprs: &exprs,
2295 conds: &conds,
2296 consts: &[],
2297 plans: &plans,
2298 services: &services,
2299 abends: &[],
2300 symbols: &[],
2301 };
2302 let text = Listing { code, items: &[], debug: None, sql: &[], ccsid: None }.to_string();
2303 let lines: Vec<&str> = text.lines().collect();
2304 assert_eq!(lines[..3], ["program symbol0?", "b0:", " Display display4?"]);
2305 assert!(lines[3].starts_with(" Branch (((((") && lines[3].contains("...") && lines[3].ends_with(" = c9? [fixed]) b0 else b1"), "{text}");
2306 }
2307}