Skip to main content

ironwork_numeric/
options.rs

1use crate::assumptions;
2use std::fmt;
3use zarch::ebcdic::{self, CodePage};
4use zarch::hfp::Precision;
5
6/// Enterprise COBOL's compiler options, from Table 45 of IBM's Programming Guide, vendored byte for
7/// byte from cobolwork's provenance/enterprise-options.tsv (tools/sync-option-table.sh).
8const TABLE: &str = include_str!("../data/enterprise-options.tsv");
9
10/// An option in IBM's table: the spellings it answers to, and where it may be given.
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub struct Documented {
13    pub name: &'static str,
14    spellings: &'static str,
15    /// Whether a CBL or PROCESS statement may give it.
16    pub process: bool,
17    /// Whether a CBL or PROCESS statement may give it only before a batch compilation's first program.
18    pub first_program_only: bool,
19    pub installation_default: bool,
20    /// The page of its section in the Enterprise COBOL 6.4 Programming Guide.
21    pub page: u16,
22}
23
24impl Documented {
25    pub fn spellings(&self) -> impl Iterator<Item = &'static str> {
26        self.spellings.split(' ')
27    }
28}
29
30/// Every option in IBM's table.
31pub fn documented() -> impl Iterator<Item = Documented> {
32    TABLE.lines().filter(|l| !l.starts_with('#')).map(|line| {
33        let f: Vec<&'static str> = line.split('\t').collect();
34        let yes = |i: usize| f[i] == "yes";
35        Documented { name: f[0], spellings: f[2], process: yes(3), first_program_only: yes(4), installation_default: yes(5), page: f[6].parse().expect("the table's pages are numbers") }
36    })
37}
38
39/// The option IBM documents under `spelling`, and whether the spelling turns the option off: a
40/// spelling beginning NO that is not the option's own name.
41pub fn spelled(spelling: &str) -> Option<(Documented, bool)> {
42    let o = documented().find(|o| o.spellings().any(|s| s == spelling))?;
43    Some((o, spelling.starts_with("NO") && !o.name.split('/').any(|n| n == spelling)))
44}
45
46/// Whether `option`, as a CBL or PROCESS statement writes it, sets the on-off option `name`, and to
47/// which: `SSR(ZLEN)` gives Some(true) for SSRANGE, `NOSSR` Some(false), and TRUNC(OPT) None.
48pub fn switch(option: &str, name: &str) -> Option<bool> {
49    let option = option.trim().to_ascii_uppercase();
50    let word = option.split('(').next().unwrap_or("").trim();
51    spelled(word).filter(|(o, _)| o.name == name).map(|(_, off)| !off)
52}
53
54#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
55pub enum Arith {
56    #[default]
57    Compat,
58    Extend,
59}
60
61impl Arith {
62    pub const fn max_picture_digits(self) -> u32 {
63        match self {
64            Self::Compat => 18,
65            Self::Extend => 31,
66        }
67    }
68
69    pub const fn intermediate_digits(self) -> u32 {
70        match self {
71            Self::Compat => 30,
72            Self::Extend => 31,
73        }
74    }
75
76    pub const fn float_intermediate(self) -> Precision {
77        match self {
78            Self::Compat => Precision::Long,
79            Self::Extend => Precision::Extended,
80        }
81    }
82}
83
84#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
85pub enum Trunc {
86    #[default]
87    Std,
88    Opt,
89    Bin,
90}
91
92#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
93pub enum Numproc {
94    #[default]
95    Nopfd,
96    Pfd,
97}
98
99/// Whether checked mode reports: a store that TRUNC(OPT) leaves to the generated code, when decimal
100/// and binary truncation disagree, and a SORT whose outcome FASTSRT changes. `-silent` turns the
101/// reports off.
102#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
103pub enum TruncCheck {
104    #[default]
105    Report,
106    Silent,
107}
108
109/// How SORT and MERGE compare a zoned or packed key: as DFSORT compares ZD and PD fields, so no
110/// bytes are invalid, or (`-strict-sort-keys`) as the program reads the item, so an invalid one is a
111/// data exception.
112#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
113pub enum SortKeys {
114    #[default]
115    Dfsort,
116    Strict,
117}
118
119/// Whether FASTSRT gives DFSORT the I/O of a USING or GIVING print file under ADV, whose data set's
120/// records are a byte longer than its FD's: never (`--fastsrt-adv-print=exclude`), or as any other
121/// file's (`--fastsrt-adv-print=include`).
122#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
123pub enum FastsrtAdvPrint {
124    #[default]
125    Exclude,
126    Include,
127}
128
129impl FastsrtAdvPrint {
130    pub const fn flag(self) -> &'static str {
131        match self {
132            Self::Exclude => "--fastsrt-adv-print=exclude",
133            Self::Include => "--fastsrt-adv-print=include",
134        }
135    }
136}
137
138/// INVDATA: zoned and packed items may hold invalid digits, sign codes or zone bits. FORCENUMCMP
139/// compares zoned items as numbers whatever their zones; CLEANSIGN cleans a sign code on input to
140/// a comparison or computation (Programming Guide SC27-8714-03, pp. 376-378). ZONEDATA(NOPFD) and
141/// ZONEDATA(MIG) are INVDATA with FORCENUMCMP off and on.
142#[derive(Clone, Copy, Debug, PartialEq, Eq)]
143pub struct Invdata {
144    pub forcenumcmp: bool,
145    pub cleansign: bool,
146}
147
148impl Default for Invdata {
149    fn default() -> Self {
150        Self { forcenumcmp: false, cleansign: true }
151    }
152}
153
154/// NUMCHECK: implicit numeric class tests of zoned and packed senders, and size tests of binary
155/// senders, each a warning that lets the statement run (MSG) or a terminating message (`abd`)
156/// (Programming Guide SC27-8714-03, pp. 388-392). ZONECHECK(MSG|ABD) is NUMCHECK(ZON,MSG|ABD)
157/// (p. 427).
158#[derive(Clone, Copy, Debug, PartialEq, Eq)]
159pub struct Numcheck {
160    pub zon: Option<ZonCheck>,
161    pub pac: bool,
162    pub bin: Option<BinCheck>,
163    pub abd: bool,
164}
165
166impl Default for Numcheck {
167    fn default() -> Self {
168        Self { zon: Some(ZonCheck::default()), pac: true, bin: Some(BinCheck { truncbin: true }), abd: false }
169    }
170}
171
172/// ZON's suboptions: whether a zoned item compared with an alphanumeric operand is checked
173/// (ALPHNUM, the default), and whether the redefinitions p. 390 lists are tolerated (LAX).
174#[derive(Clone, Copy, Debug, PartialEq, Eq)]
175pub struct ZonCheck {
176    pub alphnum: bool,
177    pub lax: bool,
178}
179
180impl Default for ZonCheck {
181    fn default() -> Self {
182        Self { alphnum: true, lax: false }
183    }
184}
185
186/// BIN's suboption: whether binary senders are checked under TRUNC(BIN) too (TRUNCBIN, the default).
187#[derive(Clone, Copy, Debug, PartialEq, Eq)]
188pub struct BinCheck {
189    pub truncbin: bool,
190}
191
192/// PARMCHECK: a buffer of `bytes` after the last WORKING-STORAGE item, set to X'AA' before each
193/// CALL and checked after it, a change being a warning (MSG) or a terminating message (`abd`)
194/// (Programming Guide SC27-8714-03, p. 397).
195#[derive(Clone, Copy, Debug, PartialEq, Eq)]
196pub struct Parmcheck {
197    pub abd: bool,
198    pub bytes: u16,
199}
200
201/// INITCHECK: a compile-time warning for a WORKING-STORAGE or LOCAL-STORAGE item used before it is
202/// set on some path (`Lax`, the default) or on any path (`Strict`) (Programming Guide
203/// SC27-8714-03, pp. 373-374).
204#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
205pub enum Initcheck {
206    #[default]
207    Lax,
208    Strict,
209}
210
211/// What a program with no STOP RUN, GOBACK or EXIT PROGRAM that ends with EXEC CICS RETURN or XCTL
212/// gets (assumption C124): IBM's warning (`--cics-return-warning=always`), one informational note
213/// in place of it (`once`), or nothing (`never`).
214#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
215pub enum CicsReturnWarning {
216    #[default]
217    Once,
218    Always,
219    Never,
220}
221
222impl CicsReturnWarning {
223    pub const fn flag(self) -> &'static str {
224        match self {
225            Self::Once => "--cics-return-warning=once",
226            Self::Always => "--cics-return-warning=always",
227            Self::Never => "--cics-return-warning=never",
228        }
229    }
230}
231
232/// What the figurative constant QUOTE is: a quotation mark under QUOTE, IBM's default, or an
233/// apostrophe under APOST (Programming Guide SC27-8714-03, p. 347).
234#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
235pub enum Quote {
236    #[default]
237    Quote,
238    Apost,
239}
240
241impl Quote {
242    /// The character in EBCDIC, where every single-byte page carries it at the same place.
243    pub const fn byte(self) -> u8 {
244        match self {
245            Self::Quote => ebcdic::QUOTE,
246            Self::Apost => ebcdic::APOSTROPHE,
247        }
248    }
249
250    /// The character as a UTF-16 unit, for a national item.
251    pub const fn unit(self) -> u16 {
252        match self {
253            Self::Quote => 0x0022,
254            Self::Apost => 0x0027,
255        }
256    }
257}
258
259/// CURRENCY(literal): the character, or a hexadecimal literal's byte, which the program's code page
260/// turns into one (Programming Guide SC27-8714-03, p. 358).
261#[derive(Clone, Copy, Debug, PartialEq, Eq)]
262pub enum Currency {
263    Char(char),
264    Hex(u8),
265}
266
267/// Whether N literals, and PICTURE N items with no USAGE clause, are national, IBM's default, or
268/// DBCS (Programming Guide SC27-8714-03, pp. 387-388).
269#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
270pub enum Nsymbol {
271    #[default]
272    National,
273    Dbcs,
274}
275
276/// How DISPLAY shows a signed binary, packed or overpunched zoned item: as releases before 6 did,
277/// with an overpunched digit (`Compat`), or with a separate leading sign (`Sep`) (Programming
278/// Guide SC27-8714-03, pp. 362-363).
279#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
280pub enum DispSign {
281    #[default]
282    Compat,
283    Sep,
284}
285
286/// Day 1 of the date intrinsic functions' integer dates: 1 January 1601 (`Ansi`), or Language
287/// Environment's Lilian 15 October 1582 (Programming Guide SC27-8714-03, p. 375).
288#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
289pub enum IntDate {
290    #[default]
291    Ansi,
292    Lilian,
293}
294
295/// Whether a reference must be unique by the standard's rules (`Compat`), or resolves to the one
296/// item a complete set of qualifiers names (`Extend`) (Programming Guide SC27-8714-03, p. 400).
297#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
298pub enum Qualify {
299    #[default]
300    Compat,
301    Extend,
302}
303
304/// What a READ of a variable-length record checks its length against: the level-01 records under
305/// `Standard`, RECORD VARYING under `Compat`; outside them its status is 04, else 00 (Programming
306/// Guide SC27-8714-03, pp. 422-424, Table 52). See assumptions C218 and C219.
307#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
308pub enum Vlr {
309    #[default]
310    Standard,
311    Compat,
312}
313
314/// The file status of a VSAM OPEN that succeeds once its file's integrity is verified: 97 under
315/// `Compat`, 00 under `Succ` (Programming Guide SC27-8714-03, p. 424). OPEN verifies a data set a
316/// run left open for output (assumption C220).
317#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
318pub enum VsamOpenFs {
319    #[default]
320    Compat,
321    Succ,
322}
323
324/// Whether a program whose compile gave warnings runs (`Proceed`), or (`-warnings-block`, the
325/// command line's NOCOMPILE(W)) is refused. The return code is 4 either way.
326#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
327pub enum Warnings {
328    #[default]
329    Proceed,
330    Block,
331}
332
333/// Whose result a computation gives where ironwork knowingly differs from GnuCOBOL: Enterprise
334/// COBOL's as the assumptions register reads it (`Ibm`), or that of GnuCOBOL's
335/// `cobc -std=ibm-strict` (`Gnucobol`, `--dialect gnucobol`), so a migration can compare ironwork
336/// with a GnuCOBOL build. docs/dialect.md lists each difference.
337#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
338pub enum Dialect {
339    #[default]
340    Ibm,
341    Gnucobol,
342}
343
344impl Dialect {
345    pub const fn flag(self) -> &'static str {
346        match self {
347            Self::Ibm => "--dialect=ibm",
348            Self::Gnucobol => "--dialect=gnucobol",
349        }
350    }
351
352    /// The value `--dialect` takes for it.
353    pub const fn name(self) -> &'static str {
354        match self {
355            Self::Ibm => "ibm",
356            Self::Gnucobol => "gnucobol",
357        }
358    }
359
360    pub fn named(value: &str) -> Option<Self> {
361        [Self::Ibm, Self::Gnucobol].into_iter().find(|d| d.name() == value)
362    }
363}
364
365/// A chosen assumption `--assume ID=VALUE` switches, by its place in [`SWITCHES`].
366#[derive(Clone, Copy, Debug, PartialEq, Eq)]
367pub enum Switched {
368    RoundedExtraPlace,
369    DisplayOfNondisplayNumeric,
370    DecimalCommaDisplayLiteral,
371    AcceptAtEnd,
372    EntryCalls,
373    ExternalStorage,
374    OptimizedZonesCompared,
375}
376
377const IBM_OR_GNUCOBOL: &[&str] = &["ibm", "gnucobol"];
378
379/// Each switched assumption's register id and the values `--assume` takes for it: `ibm`, the result
380/// the register states, then `gnucobol`, cobc's, which `--dialect gnucobol` gives, then any other
381/// alternative the claim names (docs/dialect.md).
382pub const SWITCHES: [(&str, &[&str]); 7] = [
383    (assumptions::ROUNDED_EXTRA_PLACE, &["ibm", "gnucobol", "off"]),
384    (assumptions::DISPLAY_OF_NONDISPLAY_NUMERIC, IBM_OR_GNUCOBOL),
385    (assumptions::DECIMAL_COMMA_DISPLAY_LITERAL, IBM_OR_GNUCOBOL),
386    (assumptions::ACCEPT_AT_END, IBM_OR_GNUCOBOL),
387    (assumptions::ENTRY_CALLS, IBM_OR_GNUCOBOL),
388    (assumptions::EXTERNAL_STORAGE, IBM_OR_GNUCOBOL),
389    (assumptions::OPTIMIZED_ZONES_COMPARED, IBM_OR_GNUCOBOL),
390];
391
392/// Where a ROUNDED receiver's extra decimal place counts (assumption C101): in every operation of
393/// the statement (`ibm`), in its last alone (`gnucobol`), or in none (`off`).
394#[derive(Clone, Copy, Debug, PartialEq, Eq)]
395pub enum ExtraPlace {
396    Every,
397    Last,
398    Off,
399}
400
401/// The values `--assume` gave, by place in [`SWITCHES`]: 0 where none did and the dialect decides,
402/// else one more than the value's place in the switch's list.
403#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
404pub struct Assumed {
405    pub given: [u8; SWITCHES.len()],
406}
407
408impl Assumed {
409    /// Reads `ID=VALUE` as a switch's place and the value's mark, refusing by name an id the
410    /// register lacks, an assumption with no alternative, and a value the switch does not take.
411    pub fn parse(spec: &str) -> Result<(usize, u8), String> {
412        let Some((id, value)) = spec.split_once('=') else {
413            return Err(format!("--assume {spec}: needs ID=VALUE, such as C101=off"));
414        };
415        let Some(i) = SWITCHES.iter().position(|(s, _)| *s == id) else {
416            let switched = listed(&SWITCHES.map(|(s, _)| s), "and");
417            return Err(match assumptions::ASSUMPTIONS.iter().find(|a| a.id == id) {
418                Some(a) => format!("--assume {spec}: assumption {id} ({}) has no alternative; --assume switches {switched}", a.basis.name()),
419                None => format!("--assume {spec}: the register has no assumption {id}; ironwork assumptions lists them"),
420            });
421        };
422        match SWITCHES[i].1.iter().position(|v| *v == value) {
423            Some(k) => Ok((i, k as u8 + 1)),
424            None => Err(format!("--assume {spec}: {id} takes {}", listed(SWITCHES[i].1, "or"))),
425        }
426    }
427}
428
429/// `a, b and c`, or with `or`.
430fn listed(words: &[&str], last: &str) -> String {
431    match words {
432        [] => String::new(),
433        [one] => (*one).to_owned(),
434        [rest @ .., end] => format!("{} {last} {end}", rest.join(", ")),
435    }
436}
437
438/// The COMPILE option: which messages stop the object code, so that run and cics refuse the
439/// program (Programming Guide SC27-8714-03, p. 355).
440#[derive(Clone, Copy, Debug, PartialEq, Eq)]
441pub enum Compile {
442    /// COMPILE: object code whatever the messages, unless one is U and the compilation ended.
443    Full,
444    /// NOCOMPILE(W), NOCOMPILE(E) or NOCOMPILE(S): none from the first message of that severity up.
445    Until(Stop),
446    /// NOCOMPILE: a syntax check, with no object code at all.
447    SyntaxOnly,
448}
449
450/// A severity NOCOMPILE names.
451#[derive(Clone, Copy, Debug, PartialEq, Eq)]
452pub enum Stop {
453    W,
454    E,
455    S,
456}
457
458impl Default for Compile {
459    fn default() -> Self {
460        Self::Until(Stop::S)
461    }
462}
463
464impl Compile {
465    /// The lowest return code (Programming Guide Table 38, p. 282) of a message that stops the object
466    /// code: 0 stops it whatever the messages.
467    pub const fn stops_at(self) -> u8 {
468        match self {
469            Self::Full => 16,
470            Self::Until(Stop::S) => 12,
471            Self::Until(Stop::E) => 8,
472            Self::Until(Stop::W) => 4,
473            Self::SyntaxOnly => 0,
474        }
475    }
476}
477
478/// Whether the compile refuses what Enterprise COBOL refuses (`Strict`), or accepts, each with a
479/// warning, the other dialects' extensions docs/compliance.md lists (`Extended`,
480/// `--compliance extended`).
481#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
482pub enum Compliance {
483    #[default]
484    Strict,
485    Extended,
486}
487
488impl Compliance {
489    pub const fn flag(self) -> &'static str {
490        match self {
491            Self::Strict => "--compliance=strict",
492            Self::Extended => "--compliance=extended",
493        }
494    }
495
496    /// The value `--compliance` takes for it.
497    pub const fn name(self) -> &'static str {
498        match self {
499            Self::Strict => "strict",
500            Self::Extended => "extended",
501        }
502    }
503
504    pub fn named(value: &str) -> Option<Self> {
505        [Self::Strict, Self::Extended].into_iter().find(|c| c.name() == value)
506    }
507
508    /// The level the last `--compliance=` flag among `flags` gives, strict without one.
509    pub fn of(flags: &[String]) -> Self {
510        flags.iter().rev().find_map(|f| f.strip_prefix("--compliance=").and_then(Self::named)).unwrap_or_default()
511    }
512}
513
514#[derive(Clone, Copy, Debug, PartialEq, Eq)]
515pub struct Options {
516    pub arith: Arith,
517    pub trunc: Trunc,
518    pub numproc: Numproc,
519    pub codepage: u16,
520    pub trunc_check: TruncCheck,
521    /// FASTSRT: DFSORT does the I/O of a SORT's USING and GIVING files where IBM's rules allow.
522    pub fastsrt: bool,
523    pub fastsrt_adv_print: FastsrtAdvPrint,
524    pub sort_keys: SortKeys,
525    /// ADV: a print file's printer control character is a byte added before each record; under
526    /// NOADV it is the record's own first byte.
527    pub adv: bool,
528    /// THREAD, DLL, RENT and DBCS, which object-oriented programs are compiled with.
529    pub thread: bool,
530    pub dll: bool,
531    pub rent: bool,
532    pub dbcs: bool,
533    pub warnings: Warnings,
534    /// COMPILE or NOCOMPILE as a CBL or PROCESS card gave it; None when none did.
535    pub compile: Option<Compile>,
536    /// DYNAM: a CALL of a literal loads the program at run time, as a CALL of an identifier does.
537    pub dynam: bool,
538    /// The Language Environment runtime option DEBUG (`-debug`): USE FOR DEBUGGING procedures run.
539    /// NODEBUG, IBM's default, keeps them from running (assumption C63).
540    pub debug: bool,
541    pub cics_return_warning: CicsReturnWarning,
542    /// INVDATA's suboptions; None for NOINVDATA, IBM's default, which assumes the data is valid.
543    pub invdata: Option<Invdata>,
544    /// ZWB: a signed zoned item compared with a nonnumeric operand loses its sign first.
545    pub zwb: bool,
546    pub quote: Quote,
547    /// CURRENCY(literal): the currency symbol a program with no CURRENCY SIGN clause uses in place
548    /// of $. None under NOCURRENCY, IBM's default.
549    pub currency: Option<Currency>,
550    pub nsymbol: Nsymbol,
551    pub dispsign: DispSign,
552    pub intdate: IntDate,
553    pub qualify: Qualify,
554    /// INITIAL: the program and its nested programs behave as though their PROGRAM-ID paragraphs
555    /// said IS INITIAL (Programming Guide SC27-8714-03, p. 374). A compile with THREAD takes
556    /// NOINITIAL (p. 344).
557    pub initial: bool,
558    pub vlr: Vlr,
559    pub vsamopenfs: VsamOpenFs,
560    pub numcheck: Option<Numcheck>,
561    pub parmcheck: Option<Parmcheck>,
562    pub initcheck: Option<Initcheck>,
563    /// OPTIMIZE's level, 0 to 2.
564    pub optimize: u8,
565    pub compliance: Compliance,
566    pub dialect: Dialect,
567    pub assumed: Assumed,
568}
569
570impl Default for Options {
571    fn default() -> Self {
572        Self {
573            arith: Arith::default(),
574            trunc: Trunc::default(),
575            numproc: Numproc::default(),
576            codepage: 1140,
577            trunc_check: TruncCheck::default(),
578            fastsrt: false,
579            fastsrt_adv_print: FastsrtAdvPrint::default(),
580            sort_keys: SortKeys::default(),
581            adv: true,
582            thread: false,
583            dll: false,
584            rent: true,
585            dbcs: true,
586            warnings: Warnings::default(),
587            compile: None,
588            dynam: false,
589            debug: false,
590            cics_return_warning: CicsReturnWarning::default(),
591            invdata: None,
592            zwb: true,
593            quote: Quote::default(),
594            currency: None,
595            nsymbol: Nsymbol::default(),
596            dispsign: DispSign::default(),
597            intdate: IntDate::default(),
598            qualify: Qualify::default(),
599            initial: false,
600            vlr: Vlr::default(),
601            vsamopenfs: VsamOpenFs::default(),
602            numcheck: None,
603            parmcheck: None,
604            initcheck: None,
605            optimize: 0,
606            compliance: Compliance::default(),
607            dialect: Dialect::default(),
608            assumed: Assumed::default(),
609        }
610    }
611}
612
613/// What an option could not do. Each but UnsupportedCodePage and UnknownFlag is a message IBM's
614/// compiler gives and carries on from (assumptions C120 to C122).
615#[derive(Clone, Debug, PartialEq, Eq)]
616pub enum OptionError {
617    /// A suboption the option does not have: the option is discarded.
618    BadSuboption { option: String, given: String },
619    /// A suboption IBM removed, replaced by `instead`.
620    Removed { option: String, since: &'static str, instead: &'static str },
621    /// An option Enterprise COBOL 6.4 does not have, given a warning or (`warning` false) an
622    /// informational message and no effect.
623    NoEffect { option: &'static str, why: &'static str, warning: bool },
624    UnsupportedCodePage(u16),
625    UnknownFlag(String),
626}
627
628impl fmt::Display for OptionError {
629    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
630        match self {
631            Self::BadSuboption { option, given } => write!(f, "{option} does not take ({given})"),
632            Self::Removed { option, since, instead } => write!(f, "{option} was removed in Enterprise COBOL {since}, so {instead} is in effect"),
633            Self::NoEffect { option, why, .. } => write!(f, "{option} {why}"),
634            Self::UnsupportedCodePage(ccsid) => write!(f, "CODEPAGE({ccsid}) is not an EBCDIC page this compiler carries"),
635            Self::UnknownFlag(flag) => write!(f, "unknown flag {flag}"),
636        }
637    }
638}
639
640/// The options IBM removed from Enterprise COBOL that a 6.4 compile accepts without effect, by
641/// spelling: LIB and SIZE (Migration Guide GC27-8715-03, Table 32, p. 167), FLAGSAA and NOFDUMP
642/// (Table 23, p. 112).
643fn without_effect(name: &str) -> Option<OptionError> {
644    let (option, why, warning) = match name {
645        "LIB" => ("LIB", "is no longer needed: COPY members are always read from the libraries", false),
646        "SIZE" | "SZ" => ("SIZE", "was removed in Enterprise COBOL V5 and has no effect", false),
647        "FLAGSAA" => ("FLAGSAA", "is not an Enterprise COBOL option and has no effect", true),
648        "NOFDUMP" => ("NOFDUMP", "is not an Enterprise COBOL option and has no effect", true),
649        _ => return None,
650    };
651    Some(OptionError::NoEffect { option, why, warning })
652}
653
654/// CURRENCY's literal: one character between quotation marks or apostrophes, or a hexadecimal
655/// literal of one byte (Programming Guide SC27-8714-03, p. 358). A figurative constant, a
656/// null-terminated, DBCS or national literal is none of these, so it is refused here.
657fn currency_literal(text: &str) -> Option<Currency> {
658    fn quoted(t: &str) -> Option<&str> {
659        let q = t.chars().next().filter(|q| matches!(q, '\'' | '"'))?;
660        (t.len() >= 2 && t.ends_with(q)).then(|| &t[1..t.len() - 1])
661    }
662    let text = text.trim();
663    if let Some(hex) = text.strip_prefix(['X', 'x']).and_then(quoted) {
664        return u8::from_str_radix(hex, 16).ok().filter(|_| hex.len() == 2).map(Currency::Hex);
665    }
666    let mut chars = quoted(text)?.chars();
667    match (chars.next(), chars.next()) {
668        (Some(c), None) if can_be_currency(c) => Some(Currency::Char(c)),
669        _ => None,
670    }
671}
672
673/// The text between an option's first opening parenthesis and its last closing one.
674fn inner(option: &str) -> &str {
675    option.split_once('(').map_or("", |(_, rest)| rest.trim_end().strip_suffix(')').unwrap_or(rest)).trim()
676}
677
678/// `text` split at the commas outside parentheses.
679fn top_level(text: &str) -> Vec<&str> {
680    let (mut parts, mut depth, mut start) = (Vec::new(), 0i32, 0);
681    for (i, c) in text.char_indices() {
682        match c {
683            '(' => depth += 1,
684            ')' => depth -= 1,
685            ',' if depth == 0 => {
686                parts.push(text[start..i].trim());
687                start = i + 1;
688            }
689            _ => {}
690        }
691    }
692    parts.push(text[start..].trim());
693    parts.into_iter().filter(|p| !p.is_empty()).collect()
694}
695
696/// NUMCHECK's suboptions with IBM's defaults: none gives every data type and MSG; data types left
697/// out are on when none is given and off when any is; every data type off is NONUMCHECK, None
698/// (Programming Guide SC27-8714-03, p. 389). None inside Some is a suboption IBM does not have.
699fn numcheck(text: &str) -> Option<Option<Numcheck>> {
700    let (mut zon, mut pac, mut bin, mut abd, mut typed) = (None, None, None, false, false);
701    for part in top_level(text) {
702        let (word, args) = match part.split_once('(') {
703            Some((w, _)) => (w.trim(), top_level(inner(part))),
704            None => (part, Vec::new()),
705        };
706        match word {
707            "ZON" => {
708                let mut z = ZonCheck::default();
709                for a in args {
710                    match a {
711                        "ALPHNUM" => z.alphnum = true,
712                        "NOALPHNUM" => z.alphnum = false,
713                        "LAX" | "LAXREDEF" => z.lax = true,
714                        "STRICT" | "STRICTREDEF" => z.lax = false,
715                        _ => return None,
716                    }
717                }
718                zon = Some(Some(z));
719            }
720            "NOZON" if args.is_empty() => zon = Some(None),
721            "PAC" if args.is_empty() => pac = Some(true),
722            "NOPAC" if args.is_empty() => pac = Some(false),
723            "BIN" => {
724                bin = Some(Some(BinCheck {
725                    truncbin: match args[..] {
726                        [] | ["TRUNCBIN"] => true,
727                        ["NOTRUNCBIN"] => false,
728                        _ => return None,
729                    },
730                }))
731            }
732            "NOBIN" if args.is_empty() => bin = Some(None),
733            "MSG" if args.is_empty() => abd = false,
734            "ABD" if args.is_empty() => abd = true,
735            _ => return None,
736        }
737        typed |= matches!(word, "ZON" | "NOZON" | "PAC" | "NOPAC" | "BIN" | "NOBIN");
738    }
739    let all = Numcheck::default();
740    let n = if typed {
741        Numcheck { zon: zon.flatten(), pac: pac.unwrap_or(false), bin: bin.flatten(), abd }
742    } else {
743        Numcheck { abd, ..all }
744    };
745    Some((n.zon.is_some() || n.pac || n.bin.is_some()).then_some(n))
746}
747
748/// PARMCHECK's MSG or ABD and buffer size, 100 bytes and MSG when left out (Programming Guide
749/// SC27-8714-03, p. 397).
750fn parmcheck(sub: &str) -> Option<Parmcheck> {
751    let mut p = Parmcheck { abd: false, bytes: 100 };
752    let parts: Vec<&str> = sub.split(',').map(str::trim).filter(|s| !s.is_empty()).collect();
753    if parts.len() > 2 {
754        return None;
755    }
756    for (i, part) in parts.iter().enumerate() {
757        match *part {
758            "MSG" if i == 0 => p.abd = false,
759            "ABD" if i == 0 => p.abd = true,
760            n => p.bytes = n.parse().ok().filter(|b| (1..=9999).contains(b))?,
761        }
762    }
763    Some(p)
764}
765
766/// Whether the CURRENCY option may name `c`: a single-byte character that is no digit, space, one
767/// of the letters A B C D E G N P R S U V X Z in either case, or one of * + - / , . ; ( ) " =.
768pub fn can_be_currency(c: char) -> bool {
769    u32::from(c) < 256 && !c.is_ascii_digit() && !"ABCDEGNPRSUVXZabcdegnprsuvxz *+-/,.;()\"=".contains(c)
770}
771
772impl std::error::Error for OptionError {}
773
774impl Options {
775    /// Applies one IBM compiler option as a CBL or PROCESS card or PARM writes it, e.g.
776    /// `TRUNC(OPT)`, `AR(E)`, `CP(1047)`. Returns false for an option this layer does not read. An
777    /// error leaves the options as they were, except NUMPROC(MIG), which sets the default NUMPROC.
778    pub fn apply(&mut self, option: &str) -> Result<bool, OptionError> {
779        let given = option.trim();
780        let option = given.to_ascii_uppercase();
781        let (name, sub) = match option.split_once('(') {
782            Some((name, rest)) => (name.trim(), rest.trim_end_matches(')').trim()),
783            None => (option.as_str(), ""),
784        };
785        let bad = || OptionError::BadSuboption { option: name.to_owned(), given: sub.to_owned() };
786        if let Some(e) = without_effect(name) {
787            return Err(e);
788        }
789        let Some((documented, off)) = spelled(name) else { return Ok(false) };
790        match documented.name {
791            "ARITH" => {
792                self.arith = match sub {
793                    "COMPAT" | "C" => Arith::Compat,
794                    "EXTEND" | "E" => Arith::Extend,
795                    _ => return Err(bad()),
796                }
797            }
798            "TRUNC" => {
799                self.trunc = match sub {
800                    "STD" => Trunc::Std,
801                    "OPT" => Trunc::Opt,
802                    "BIN" => Trunc::Bin,
803                    _ => return Err(bad()),
804                }
805            }
806            "NUMPROC" => {
807                self.numproc = match sub {
808                    "NOPFD" => Numproc::Nopfd,
809                    "PFD" => Numproc::Pfd,
810                    "MIG" => {
811                        self.numproc = Numproc::default();
812                        return Err(OptionError::Removed { option: "NUMPROC(MIG)".into(), since: "V5", instead: "NUMPROC(NOPFD)" });
813                    }
814                    _ => return Err(bad()),
815                }
816            }
817            "CODEPAGE" => {
818                let ccsid: u16 = sub.parse().map_err(|_| bad())?;
819                CodePage::by_ccsid(ccsid).ok_or(OptionError::UnsupportedCodePage(ccsid))?;
820                self.codepage = ccsid;
821            }
822            "COMPILE" => {
823                self.compile = Some(match (off, sub) {
824                    (false, "") => Compile::Full,
825                    (true, "") => Compile::SyntaxOnly,
826                    (true, "W") => Compile::Until(Stop::W),
827                    (true, "E") => Compile::Until(Stop::E),
828                    (true, "S") => Compile::Until(Stop::S),
829                    _ => return Err(bad()),
830                })
831            }
832            "INVDATA" if off => self.invdata = None,
833            "INVDATA" => {
834                let mut invdata = Invdata::default();
835                for part in sub.split(',').map(str::trim).filter(|p| !p.is_empty()) {
836                    match part {
837                        "FORCENUMCMP" | "FNC" => invdata.forcenumcmp = true,
838                        "NOFORCENUMCMP" | "NOFNC" => invdata.forcenumcmp = false,
839                        "CLEANSIGN" | "CS" => invdata.cleansign = true,
840                        "NOCLEANSIGN" | "NOCS" => invdata.cleansign = false,
841                        _ => return Err(bad()),
842                    }
843                }
844                self.invdata = Some(invdata);
845            }
846            "ZONEDATA" => {
847                self.invdata = match sub {
848                    "PFD" => None,
849                    "NOPFD" => Some(Invdata::default()),
850                    "MIG" => Some(Invdata { forcenumcmp: true, cleansign: true }),
851                    _ => return Err(bad()),
852                }
853            }
854            "ZWB" => self.zwb = !off,
855            "NUMCHECK" if off => self.numcheck = None,
856            "NUMCHECK" => self.numcheck = numcheck(inner(&option)).ok_or_else(bad)?,
857            "ZONECHECK" if off => self.numcheck = self.numcheck.map(|n| Numcheck { zon: None, ..n }).filter(|n| n.pac || n.bin.is_some()),
858            "ZONECHECK" => {
859                let abd = match sub {
860                    "MSG" => false,
861                    "ABD" => true,
862                    _ => return Err(bad()),
863                };
864                self.numcheck = Some(Numcheck { zon: Some(ZonCheck::default()), pac: false, bin: None, abd });
865            }
866            "PARMCHECK" if off => self.parmcheck = None,
867            "PARMCHECK" => self.parmcheck = Some(parmcheck(sub).ok_or_else(bad)?),
868            "INITCHECK" if off => self.initcheck = None,
869            "INITCHECK" => {
870                self.initcheck = Some(match sub {
871                    "" | "LAX" => Initcheck::Lax,
872                    "STRICT" => Initcheck::Strict,
873                    _ => return Err(bad()),
874                })
875            }
876            "FASTSRT" => self.fastsrt = !off,
877            "ADV" => self.adv = !off,
878            "THREAD" => self.thread = !off,
879            "DLL" => self.dll = !off,
880            "RENT" => self.rent = !off,
881            "DBCS" => self.dbcs = !off,
882            "DYNAM" => self.dynam = !off,
883            "APOST/QUOTE" if sub.is_empty() => self.quote = if name == "APOST" { Quote::Apost } else { Quote::Quote },
884            "CURRENCY" => {
885                self.currency = match (off, sub) {
886                    (true, "") => None,
887                    (false, _) => Some(currency_literal(given.split_once('(').map_or("", |(_, rest)| rest.trim_end().trim_end_matches(')'))).ok_or_else(bad)?),
888                    _ => return Err(bad()),
889                }
890            }
891            "NSYMBOL" => {
892                self.nsymbol = match sub {
893                    "NATIONAL" | "NAT" => Nsymbol::National,
894                    "DBCS" => Nsymbol::Dbcs,
895                    _ => return Err(bad()),
896                }
897            }
898            "DISPSIGN" => {
899                self.dispsign = match sub {
900                    "COMPAT" | "C" => DispSign::Compat,
901                    "SEP" | "S" => DispSign::Sep,
902                    _ => return Err(bad()),
903                }
904            }
905            "INTDATE" => {
906                self.intdate = match sub {
907                    "ANSI" => IntDate::Ansi,
908                    "LILIAN" => IntDate::Lilian,
909                    _ => return Err(bad()),
910                }
911            }
912            "QUALIFY" => {
913                self.qualify = match sub {
914                    "COMPAT" | "C" => Qualify::Compat,
915                    "EXTEND" | "E" => Qualify::Extend,
916                    _ => return Err(bad()),
917                }
918            }
919            "INITIAL" if sub.is_empty() => self.initial = !off,
920            "VLR" => {
921                self.vlr = match sub {
922                    "STANDARD" | "S" => Vlr::Standard,
923                    "COMPAT" | "C" => Vlr::Compat,
924                    _ => return Err(bad()),
925                }
926            }
927            "VSAMOPENFS" => {
928                self.vsamopenfs = match sub {
929                    "COMPAT" | "C" => VsamOpenFs::Compat,
930                    "SUCC" | "S" => VsamOpenFs::Succ,
931                    _ => return Err(bad()),
932                }
933            }
934            // NOOPTIMIZE, OPTIMIZE, OPTIMIZE(STD) and OPTIMIZE(FULL) are tolerated as Table 51
935            // maps them; FULL's STGOPT changes nothing ironwork runs.
936            "OPTIMIZE" => {
937                self.optimize = match (off, sub) {
938                    (true, "") | (false, "0") => 0,
939                    (false, "1") => 1,
940                    (false, "2" | "" | "STD" | "FULL") => 2,
941                    _ => return Err(bad()),
942                }
943            }
944            "APOST/QUOTE" | "INITIAL" => return Err(bad()),
945            _ => return Ok(false),
946        }
947        Ok(true)
948    }
949
950    /// Applies a flag of this compiler's own command line.
951    pub fn apply_flag(&mut self, flag: &str) -> Result<(), OptionError> {
952        match flag {
953            "-silent" => self.trunc_check = TruncCheck::Silent,
954            "-strict-sort-keys" => self.sort_keys = SortKeys::Strict,
955            "--fastsrt-adv-print=exclude" => self.fastsrt_adv_print = FastsrtAdvPrint::Exclude,
956            "--fastsrt-adv-print=include" => self.fastsrt_adv_print = FastsrtAdvPrint::Include,
957            "-warnings-block" => self.warnings = Warnings::Block,
958            "-debug" => self.debug = true,
959            "--cics-return-warning=once" => self.cics_return_warning = CicsReturnWarning::Once,
960            "--cics-return-warning=always" => self.cics_return_warning = CicsReturnWarning::Always,
961            "--cics-return-warning=never" => self.cics_return_warning = CicsReturnWarning::Never,
962            // The compiler invocation's OPTIMIZE, which a card's outranks.
963            "--optimize=0" => self.optimize = 0,
964            "--optimize=1" => self.optimize = 1,
965            "--optimize=2" => self.optimize = 2,
966            f if f.starts_with("--compliance=") => match Compliance::named(&f["--compliance=".len()..]) {
967                Some(c) => self.compliance = c,
968                None => return Err(OptionError::UnknownFlag(flag.to_owned())),
969            },
970            f if f.starts_with("--dialect=") => match Dialect::named(&f["--dialect=".len()..]) {
971                Some(d) => self.dialect = d,
972                None => return Err(OptionError::UnknownFlag(flag.to_owned())),
973            },
974            f if f.starts_with("--assume=") => match Assumed::parse(&f["--assume=".len()..]) {
975                Ok((i, mark)) => self.assumed.given[i] = mark,
976                Err(_) => return Err(OptionError::UnknownFlag(flag.to_owned())),
977            },
978            _ => return Err(OptionError::UnknownFlag(flag.to_owned())),
979        }
980        Ok(())
981    }
982
983    /// The COMPILE option in force: a card's, which outranks the command line as a PROCESS
984    /// statement outranks the compiler's invocation (Programming Guide SC27-8714-03, p. 273), else
985    /// NOCOMPILE(W) under `-warnings-block`, else IBM's default NOCOMPILE(S).
986    pub fn object_code(&self) -> Compile {
987        self.compile.unwrap_or(match self.warnings {
988            Warnings::Block => Compile::Until(Stop::W),
989            Warnings::Proceed => Compile::default(),
990        })
991    }
992
993    /// Whether an unsigned zoned integer compared with zero, or with an unsigned zoned integer of
994    /// its own length, is compared by its bytes, zones included: under INVDATA(NOFORCENUMCMP)
995    /// (assumption C223), and under NOINVDATA at OPTIMIZE(1) or OPTIMIZE(2) (C262).
996    pub fn zones_compared(&self) -> bool {
997        match self.invdata {
998            Some(i) => !i.forcenumcmp,
999            None => self.optimize > 0,
1000        }
1001    }
1002
1003    /// Whether an unsigned zoned integer compared with zero is compared by its bytes: where zones
1004    /// are compared, but under NOINVDATA and C262 gnucobol as a number at every OPTIMIZE
1005    /// level, as cobc compares it (C262).
1006    pub fn zones_compared_with_zero(&self) -> bool {
1007        self.zones_compared() && !self.cobc_zoned_compare()
1008    }
1009
1010    /// Whether an unsigned zoned integer compared with one of its own length is compared by its
1011    /// bytes: where zones are compared, and under NOINVDATA and C262 gnucobol at every
1012    /// OPTIMIZE level, as cobc compares two such items with memcmp (C262).
1013    pub fn zones_compared_between_items(&self) -> bool {
1014        self.zones_compared() || self.cobc_zoned_compare()
1015    }
1016
1017    fn cobc_zoned_compare(&self) -> bool {
1018        self.invdata.is_none() && self.dialect_of(Switched::OptimizedZonesCompared) == Dialect::Gnucobol
1019    }
1020
1021    /// The place in its switch's list of the value a switched assumption takes: `--assume`'s, else
1022    /// the dialect's.
1023    fn switch_value(&self, i: usize) -> usize {
1024        match (self.assumed.given[i], self.dialect) {
1025            (0, Dialect::Ibm) => 0,
1026            (0, Dialect::Gnucobol) => 1,
1027            (mark, _) => usize::from(mark) - 1,
1028        }
1029    }
1030
1031    /// Whose result a switched assumption gives. C101's `off` is [`Options::extra_place`]'s alone.
1032    pub fn dialect_of(&self, switched: Switched) -> Dialect {
1033        if self.switch_value(switched as usize) == 1 { Dialect::Gnucobol } else { Dialect::Ibm }
1034    }
1035
1036    pub fn extra_place(&self) -> ExtraPlace {
1037        match self.switch_value(Switched::RoundedExtraPlace as usize) {
1038            0 => ExtraPlace::Every,
1039            1 => ExtraPlace::Last,
1040            _ => ExtraPlace::Off,
1041        }
1042    }
1043
1044    /// The `--assume` flags that give these options' choices, for a compile that repeats them.
1045    pub fn assume_flags(&self) -> impl Iterator<Item = String> {
1046        SWITCHES.iter().zip(self.assumed.given).filter(|&(_, mark)| mark > 0).map(|((id, values), mark)| format!("--assume={id}={}", values[usize::from(mark) - 1]))
1047    }
1048
1049    /// Each switched assumption whose value in force is not `ibm`, with that value.
1050    pub fn alternatives_in_force(&self) -> impl Iterator<Item = (&'static str, &'static str)> {
1051        SWITCHES.iter().enumerate().map(|(i, (id, values))| (*id, values[self.switch_value(i)])).filter(|&(_, value)| value != "ibm")
1052    }
1053
1054    pub fn code_page(&self) -> &'static CodePage {
1055        CodePage::by_ccsid(self.codepage).expect("codepage validated when applied")
1056    }
1057
1058    /// The CURRENCY option's character, a hexadecimal literal's read in the program's code page;
1059    /// Err with that character when the page gives one the option may not name.
1060    pub fn currency_symbol(&self) -> Option<Result<char, char>> {
1061        self.currency.map(|c| match c {
1062            Currency::Char(c) => Ok(c),
1063            Currency::Hex(b) => {
1064                let c = self.code_page().decode_byte(b);
1065                if can_be_currency(c) { Ok(c) } else { Err(c) }
1066            }
1067        })
1068    }
1069}
1070
1071#[cfg(test)]
1072mod tests {
1073    use super::*;
1074
1075    #[test]
1076    fn defaults_are_ibms() {
1077        let o = Options::default();
1078        assert_eq!((o.arith, o.trunc, o.numproc, o.codepage, o.fastsrt, o.adv), (Arith::Compat, Trunc::Std, Numproc::Nopfd, 1140, false, true));
1079        assert_eq!((o.thread, o.dll, o.rent, o.dbcs, o.dynam), (false, false, true, true, false));
1080    }
1081
1082    #[test]
1083    fn invdata_zonedata_and_zwb() {
1084        let mut o = Options::default();
1085        assert_eq!((o.invdata, o.zwb), (None, true));
1086        assert_eq!(o.apply("INVDATA"), Ok(true));
1087        assert_eq!(o.invdata, Some(Invdata { forcenumcmp: false, cleansign: true }));
1088        assert_eq!(o.apply("INVD(FNC,NOCS)"), Ok(true));
1089        assert_eq!(o.invdata, Some(Invdata { forcenumcmp: true, cleansign: false }));
1090        assert_eq!(o.apply("NOINVDATA"), Ok(true));
1091        assert_eq!(o.invdata, None);
1092        assert_eq!(o.apply("ZD(MIG)"), Ok(true));
1093        assert_eq!(o.invdata, Some(Invdata { forcenumcmp: true, cleansign: true }));
1094        assert_eq!(o.apply("ZONEDATA(NOPFD)"), Ok(true));
1095        assert_eq!(o.invdata, Some(Invdata::default()));
1096        assert_eq!(o.apply("ZONEDATA(PFD)"), Ok(true));
1097        assert_eq!(o.invdata, None);
1098        assert!(o.apply("INVDATA(SOMETIMES)").is_err());
1099        assert_eq!(o.apply("NOZWB"), Ok(true));
1100        assert!(!o.zwb);
1101    }
1102
1103    #[test]
1104    fn optimize_levels_and_the_removed_spellings_table_51_maps() {
1105        let mut o = Options::default();
1106        assert_eq!(o.optimize, 0);
1107        for (option, level) in [("OPT(1)", 1), ("OPTIMIZE(0)", 0), ("opt(2)", 2), ("NOOPTIMIZE", 0), ("OPTIMIZE", 2), ("NOOPTIMIZE", 0), ("OPTIMIZE(STD)", 2), ("OPT(0)", 0), ("OPTIMIZE(FULL)", 2)] {
1108            assert_eq!(o.apply(option), Ok(true), "{option}");
1109            assert_eq!(o.optimize, level, "{option}");
1110        }
1111        assert!(o.apply("OPT(3)").is_err());
1112        assert!(o.apply("NOOPTIMIZE(2)").is_err());
1113        assert_eq!(o.optimize, 2);
1114    }
1115
1116    #[test]
1117    fn zones_are_compared_under_invdata_noforcenumcmp_or_noinvdata_optimized() {
1118        let compared = |options: &[&str]| {
1119            let mut o = Options::default();
1120            options.iter().for_each(|x| assert_eq!(o.apply(x), Ok(true)));
1121            o.zones_compared()
1122        };
1123        assert!(!compared(&[]));
1124        assert!(compared(&["OPT(1)"]));
1125        assert!(compared(&["OPT(2)"]));
1126        assert!(compared(&["INVDATA"]));
1127        assert!(!compared(&["INVDATA(FNC)", "OPT(2)"]));
1128        assert!(!compared(&["ZONEDATA(MIG)", "OPT(2)"]));
1129    }
1130
1131    #[test]
1132    fn dynam_and_its_abbreviations() {
1133        let mut o = Options::default();
1134        assert_eq!(o.apply("DYN"), Ok(true));
1135        assert!(o.dynam);
1136        assert_eq!(o.apply("NODYNAM"), Ok(true));
1137        assert!(!o.dynam);
1138    }
1139
1140    #[test]
1141    fn adv_and_noadv_have_no_abbreviations() {
1142        let mut o = Options::default();
1143        assert_eq!(o.apply("noadv"), Ok(true));
1144        assert!(!o.adv);
1145        assert_eq!(o.apply("ADV"), Ok(true));
1146        assert!(o.adv);
1147        assert_eq!(o.apply("NOAD"), Ok(false));
1148    }
1149
1150    #[test]
1151    fn thread_dll_rent_and_dbcs_and_their_negatives() {
1152        let mut o = Options::default();
1153        for option in ["thread", "DLL", "NORENT", "NODBCS"] {
1154            assert_eq!(o.apply(option), Ok(true));
1155        }
1156        assert_eq!((o.thread, o.dll, o.rent, o.dbcs), (true, true, false, false));
1157        for option in ["NOTHREAD", "NODLL", "RENT", "DBCS"] {
1158            assert_eq!(o.apply(option), Ok(true));
1159        }
1160        assert_eq!((o.thread, o.dll, o.rent, o.dbcs), (false, false, true, true));
1161    }
1162
1163    #[test]
1164    fn abbreviations_and_case() {
1165        let mut o = Options::default();
1166        assert_eq!(o.apply("ar(e)"), Ok(true));
1167        assert_eq!(o.apply("CP(1047)"), Ok(true));
1168        assert_eq!(o.apply("TRUNC(BIN)"), Ok(true));
1169        assert_eq!(o.apply("fsrt"), Ok(true));
1170        assert_eq!((o.arith, o.codepage, o.trunc, o.fastsrt), (Arith::Extend, 1047, Trunc::Bin, true));
1171        assert_eq!(o.apply("NOFASTSRT"), Ok(true));
1172        assert!(!o.fastsrt);
1173    }
1174
1175    #[test]
1176    fn ibms_table_is_whole_and_no_spelling_names_two_options() {
1177        let all: Vec<Documented> = documented().collect();
1178        assert_eq!(all.len(), 85, "Table 45 lists 85 options");
1179        let mut seen = std::collections::HashMap::new();
1180        for o in &all {
1181            for s in o.spellings() {
1182                assert!(seen.insert(s, o.name).is_none(), "{s} names {} and {}", seen[s], o.name);
1183            }
1184        }
1185        assert!(TABLE.lines().nth(1).is_some_and(|l| l.contains("cobolwork's provenance/enterprise-options.json")));
1186        let adata = all.iter().find(|o| o.name == "ADATA").unwrap();
1187        assert!(!adata.process && adata.page == 345);
1188    }
1189
1190    #[test]
1191    fn every_spelling_ibm_documents_for_an_option_read_here_is_read() {
1192        let suboption = |name| match name {
1193            "ARITH" => "(E)",
1194            "CODEPAGE" => "(1047)",
1195            "TRUNC" => "(OPT)",
1196            "NUMPROC" => "(PFD)",
1197            "ZONEDATA" => "(MIG)",
1198            _ => "",
1199        };
1200        for name in ["ARITH", "CODEPAGE", "TRUNC", "NUMPROC", "FASTSRT", "COMPILE", "INVDATA", "ZONEDATA", "ZWB", "OPTIMIZE"] {
1201            let o = documented().find(|o| o.name == name).unwrap();
1202            for s in o.spellings() {
1203                assert_eq!(Options::default().apply(&format!("{s}{}", suboption(name))), Ok(true), "{s}");
1204            }
1205        }
1206        let mut o = Options::default();
1207        o.apply("FSRT").unwrap();
1208        o.apply("NOFSRT").unwrap();
1209        assert!(!o.fastsrt);
1210        assert_eq!(switch("ssr(zlen)", "SSRANGE"), Some(true));
1211        assert_eq!(switch("SSRANGE(NOZLEN,MSG)", "SSRANGE"), Some(true));
1212        assert_eq!(switch("NOSSR", "SSRANGE"), Some(false));
1213        assert_eq!(switch("TRUNC(OPT)", "SSRANGE"), None);
1214    }
1215
1216    /// Run with IRONWORK_COBOLWORK_DIR naming a cobolwork checkout to check the vendored copy.
1217    #[test]
1218    fn the_vendored_table_is_cobolworks() {
1219        let Ok(dir) = std::env::var("IRONWORK_COBOLWORK_DIR") else { return };
1220        let theirs = std::fs::read_to_string(std::path::Path::new(&dir).join("provenance/enterprise-options.tsv")).expect("cobolwork's table");
1221        assert!(theirs == TABLE, "crates/numeric/data/enterprise-options.tsv differs from cobolwork's: run tools/sync-option-table.sh");
1222    }
1223
1224    #[test]
1225    fn options_this_layer_does_not_read_pass_through() {
1226        assert_eq!(Options::default().apply("SSRANGE"), Ok(false));
1227    }
1228
1229    #[test]
1230    fn an_option_that_cannot_be_applied_says_why_and_leaves_the_options_as_they_were() {
1231        let mut o = Options::default();
1232        o.apply("NUMPROC(PFD)").unwrap();
1233        o.apply("TRUNC(BIN)").unwrap();
1234        assert!(matches!(o.apply("TRUNC(FAST)"), Err(OptionError::BadSuboption { .. })));
1235        assert_eq!(o.apply("CODEPAGE(290)"), Err(OptionError::UnsupportedCodePage(290)));
1236        assert!(matches!(o.apply("CP(X)"), Err(OptionError::BadSuboption { .. })));
1237        for (option, warns) in [("LIB", false), ("SIZE(MAX)", false), ("sz(2097152)", false), ("FLAGSAA", true), ("NOFDUMP", true)] {
1238            assert!(matches!(o.apply(option), Err(OptionError::NoEffect { warning, .. }) if warning == warns), "{option}");
1239        }
1240        assert_eq!((o.apply("NOLIB"), o.apply("FDUMP")), (Ok(false), Ok(false)));
1241        assert_eq!((o.numproc, o.trunc, o.codepage), (Numproc::Pfd, Trunc::Bin, 1140));
1242        let removed = o.apply("NUMPROC(MIG)").unwrap_err();
1243        assert_eq!(removed.to_string(), "NUMPROC(MIG) was removed in Enterprise COBOL V5, so NUMPROC(NOPFD) is in effect");
1244        assert_eq!(o.numproc, Numproc::Nopfd, "the default NUMPROC, not the one before");
1245    }
1246
1247    #[test]
1248    fn codepage_takes_the_mixed_pages_dbcs_programs_compile_with() {
1249        let mut o = Options::default();
1250        for ccsid in [930, 939, 1390, 1399, 5026, 5035, 933, 1364, 935, 1388, 937] {
1251            o.apply(&format!("CODEPAGE({ccsid})")).unwrap();
1252            assert!(o.code_page().dbcs_ccsid().is_some(), "{ccsid}");
1253        }
1254    }
1255
1256    #[test]
1257    fn silent_flag_turns_off_trunc_reports() {
1258        let mut o = Options::default();
1259        o.apply_flag("-silent").unwrap();
1260        assert_eq!(o.trunc_check, TruncCheck::Silent);
1261        o.apply_flag("-strict-sort-keys").unwrap();
1262        assert_eq!(o.sort_keys, SortKeys::Strict);
1263        assert!(o.apply_flag("-quiet").is_err());
1264    }
1265
1266    #[test]
1267    fn warnings_proceed_unless_the_flag_blocks_them() {
1268        let mut o = Options::default();
1269        assert_eq!(o.warnings, Warnings::Proceed);
1270        o.apply_flag("-warnings-block").unwrap();
1271        assert_eq!(o.warnings, Warnings::Block);
1272        assert!(o.apply_flag("-Werror").is_err());
1273    }
1274
1275    #[test]
1276    fn compile_and_nocompile_with_each_severity_and_their_abbreviations() {
1277        let given = |option: &str| {
1278            let mut o = Options::default();
1279            o.apply(option).map(|_| o.compile)
1280        };
1281        assert_eq!(Options::default().object_code(), Compile::Until(Stop::S));
1282        assert_eq!(given("COMPILE"), Ok(Some(Compile::Full)));
1283        assert_eq!(given("c"), Ok(Some(Compile::Full)));
1284        assert_eq!(given("NOCOMPILE"), Ok(Some(Compile::SyntaxOnly)));
1285        assert_eq!(given("NOC(w)"), Ok(Some(Compile::Until(Stop::W))));
1286        assert_eq!(given("NOCOMPILE(E)"), Ok(Some(Compile::Until(Stop::E))));
1287        assert_eq!(given("NOC(S)"), Ok(Some(Compile::Until(Stop::S))));
1288        for bad in ["NOCOMPILE(U)", "NOC(I)", "COMPILE(S)", "C(E)"] {
1289            assert!(matches!(given(bad), Err(OptionError::BadSuboption { .. })), "{bad}");
1290        }
1291        let codes = [Compile::Full, Compile::Until(Stop::S), Compile::Until(Stop::E), Compile::Until(Stop::W), Compile::SyntaxOnly].map(Compile::stops_at);
1292        assert_eq!(codes, [16, 12, 8, 4, 0]);
1293    }
1294
1295    #[test]
1296    fn a_card_outranks_warnings_block() {
1297        let mut o = Options::default();
1298        o.apply_flag("-warnings-block").unwrap();
1299        assert_eq!(o.object_code(), Compile::Until(Stop::W));
1300        o.apply("NOCOMPILE(S)").unwrap();
1301        assert_eq!(o.object_code(), Compile::Until(Stop::S));
1302        o.apply("NOCOMPILE(E)").unwrap();
1303        assert_eq!(o.object_code(), Compile::Until(Stop::E), "the last card wins");
1304    }
1305
1306    #[test]
1307    fn fastsrt_adv_print_excludes_unless_included() {
1308        let mut o = Options::default();
1309        assert_eq!(o.fastsrt_adv_print, FastsrtAdvPrint::Exclude);
1310        o.apply_flag("--fastsrt-adv-print=include").unwrap();
1311        assert_eq!(o.fastsrt_adv_print, FastsrtAdvPrint::Include);
1312        o.apply_flag("--fastsrt-adv-print=exclude").unwrap();
1313        assert_eq!(o.fastsrt_adv_print.flag(), "--fastsrt-adv-print=exclude");
1314        assert!(o.apply_flag("--fastsrt-adv-print=maybe").is_err());
1315        assert!(o.apply_flag("--fastsrt-adv-print").is_err());
1316    }
1317
1318    #[test]
1319    fn the_options_of_roadmap_2_10_to_2_12_default_to_ibms_and_take_each_documented_suboption() {
1320        let o = Options::default();
1321        assert_eq!((o.quote, o.currency, o.nsymbol, o.dispsign, o.intdate), (Quote::Quote, None, Nsymbol::National, DispSign::Compat, IntDate::Ansi));
1322        assert_eq!((o.qualify, o.initial, o.vlr, o.vsamopenfs), (Qualify::Compat, false, Vlr::Standard, VsamOpenFs::Compat));
1323        let given = |cards: &[&str]| {
1324            let mut o = Options::default();
1325            cards.iter().for_each(|c| assert_eq!(o.apply(c), Ok(true), "{c}"));
1326            o
1327        };
1328        assert_eq!(given(&["APOST"]).quote, Quote::Apost);
1329        assert_eq!(given(&["apost", "Q"]).quote, Quote::Quote);
1330        assert_eq!(given(&["NS(DBCS)"]).nsymbol, Nsymbol::Dbcs);
1331        assert_eq!(given(&["NSYMBOL(DBCS)", "NS(NAT)"]).nsymbol, Nsymbol::National);
1332        assert_eq!(given(&["DS(S)"]).dispsign, DispSign::Sep);
1333        assert_eq!(given(&["DISPSIGN(SEP)", "DISPSIGN(COMPAT)"]).dispsign, DispSign::Compat);
1334        assert_eq!(given(&["INTDATE(LILIAN)"]).intdate, IntDate::Lilian);
1335        assert_eq!(given(&["QUA(E)"]).qualify, Qualify::Extend);
1336        assert_eq!(given(&["QUALIFY(EXTEND)", "QUA(C)"]).qualify, Qualify::Compat);
1337        assert!(given(&["INITIAL"]).initial);
1338        assert!(!given(&["INITIAL", "NOINITIAL"]).initial);
1339        assert_eq!(given(&["VLR(C)"]).vlr, Vlr::Compat);
1340        assert_eq!(given(&["VLR(COMPAT)", "VLR(STANDARD)"]).vlr, Vlr::Standard);
1341        assert_eq!(given(&["VS(S)"]).vsamopenfs, VsamOpenFs::Succ);
1342        assert_eq!(given(&["VSAMOPENFS(SUCC)", "VSAMOPENFS(COMPAT)"]).vsamopenfs, VsamOpenFs::Compat);
1343        for bad in ["APOST(X)", "NSYMBOL(N)", "DS(X)", "INTDATE(JULIAN)", "QUA(X)", "INITIAL(Y)", "VLR(X)", "VS(X)", "INTDATE"] {
1344            assert!(matches!(Options::default().apply(bad), Err(OptionError::BadSuboption { .. })), "{bad}");
1345        }
1346    }
1347
1348    #[test]
1349    fn currency_takes_one_character_it_may_name_in_either_delimiter_or_a_hexadecimal_byte() {
1350        let currency = |card: &str| {
1351            let mut o = Options::default();
1352            o.apply(card).map(|_| o.currency)
1353        };
1354        assert_eq!(currency("CURRENCY('£')"), Ok(Some(Currency::Char('£'))));
1355        assert_eq!(currency("curr(\"f\")"), Ok(Some(Currency::Char('f'))), "the literal keeps its case");
1356        assert_eq!(currency("CURRENCY(X'5B')"), Ok(Some(Currency::Hex(0x5B))));
1357        assert_eq!(currency("NOCURR"), Ok(None));
1358        for bad in ["CURRENCY('E')", "CURRENCY('e')", "CURRENCY('1')", "CURRENCY(' ')", "CURRENCY('*')", "CURRENCY('EUR')", "CURRENCY(SPACE)", "CURRENCY(N'£')", "CURRENCY(Z'£')", "CURRENCY(X'5B5B')", "CURRENCY", "NOCURRENCY('£')"] {
1359            assert!(matches!(currency(bad), Err(OptionError::BadSuboption { .. })), "{bad}");
1360        }
1361        let mut o = Options::default();
1362        o.apply("CURRENCY(X'4A')").unwrap();
1363        assert_eq!(o.currency_symbol(), Some(Ok('¢')), "X'4A' is the cent sign in CCSID 1140");
1364        o.apply("CURRENCY(X'F1')").unwrap();
1365        assert_eq!(o.currency_symbol(), Some(Err('1')));
1366        assert_eq!(Options::default().currency_symbol(), None);
1367    }
1368
1369    #[test]
1370    fn numcheck_takes_ibms_suboption_defaults_and_zonecheck_is_its_zoned_check() {
1371        let numcheck = |card: &str| {
1372            let mut o = Options::default();
1373            o.apply(card).map(|_| o.numcheck)
1374        };
1375        let all = Numcheck::default();
1376        assert_eq!(all, Numcheck { zon: Some(ZonCheck { alphnum: true, lax: false }), pac: true, bin: Some(BinCheck { truncbin: true }), abd: false });
1377        assert_eq!(numcheck("NUMCHECK"), Ok(Some(all)));
1378        assert_eq!(numcheck("NC(ABD)"), Ok(Some(Numcheck { abd: true, ..all })));
1379        assert_eq!(numcheck("NUMCHECK(BIN)"), Ok(Some(Numcheck { zon: None, pac: false, bin: Some(BinCheck { truncbin: true }), abd: false })));
1380        assert_eq!(
1381            numcheck("NUMCHECK(ZON(NOALPHNUM,LAX),NOPAC,BIN(NOTRUNCBIN),ABD)"),
1382            Ok(Some(Numcheck { zon: Some(ZonCheck { alphnum: false, lax: true }), pac: false, bin: Some(BinCheck { truncbin: false }), abd: true }))
1383        );
1384        assert_eq!(numcheck("NUMCHECK(ZON(LAXREDEF))"), Ok(Some(Numcheck { zon: Some(ZonCheck { alphnum: true, lax: true }), pac: false, bin: None, abd: false })));
1385        assert_eq!(numcheck("NUMCHECK(NOZON,NOPAC,NOBIN)"), Ok(None));
1386        assert_eq!(numcheck("NONC"), Ok(None));
1387        for bad in ["NUMCHECK(ZON(X))", "NUMCHECK(PAC(X))", "NUMCHECK(BIN(X))", "NUMCHECK(X)", "ZONECHECK", "ZC(X)"] {
1388            assert!(matches!(numcheck(bad), Err(OptionError::BadSuboption { .. })), "{bad}");
1389        }
1390        assert_eq!(numcheck("ZC(ABD)"), Ok(Some(Numcheck { zon: Some(ZonCheck::default()), pac: false, bin: None, abd: true })));
1391        let mut o = Options::default();
1392        o.apply("NUMCHECK").unwrap();
1393        o.apply("NOZONECHECK").unwrap();
1394        assert_eq!(o.numcheck, Some(Numcheck { zon: None, ..all }));
1395        o.apply("ZONECHECK(MSG)").unwrap();
1396        o.apply("NOZC").unwrap();
1397        assert_eq!(o.numcheck, None);
1398    }
1399
1400    #[test]
1401    fn parmcheck_and_initcheck_take_their_suboptions_and_ibms_defaults() {
1402        let parmcheck = |card: &str| {
1403            let mut o = Options::default();
1404            o.apply(card).map(|_| o.parmcheck)
1405        };
1406        assert_eq!(parmcheck("PARMCHECK"), Ok(Some(Parmcheck { abd: false, bytes: 100 })));
1407        assert_eq!(parmcheck("PC(ABD)"), Ok(Some(Parmcheck { abd: true, bytes: 100 })));
1408        assert_eq!(parmcheck("PC(5000)"), Ok(Some(Parmcheck { abd: false, bytes: 5000 })));
1409        assert_eq!(parmcheck("PARMCHECK(ABD,1)"), Ok(Some(Parmcheck { abd: true, bytes: 1 })));
1410        assert_eq!(parmcheck("NOPC"), Ok(None));
1411        for bad in ["PC(0)", "PC(10000)", "PC(5000,ABD)", "PC(MSG,1,2)", "PC(X)"] {
1412            assert!(matches!(parmcheck(bad), Err(OptionError::BadSuboption { .. })), "{bad}");
1413        }
1414        let initcheck = |card: &str| {
1415            let mut o = Options::default();
1416            o.apply(card).map(|_| o.initcheck)
1417        };
1418        assert_eq!(initcheck("INITCHECK"), Ok(Some(Initcheck::Lax)));
1419        assert_eq!(initcheck("IC(STRICT)"), Ok(Some(Initcheck::Strict)));
1420        assert_eq!(initcheck("NOIC"), Ok(None));
1421        assert!(matches!(initcheck("IC(X)"), Err(OptionError::BadSuboption { .. })));
1422        let o = Options::default();
1423        assert_eq!((o.numcheck, o.parmcheck, o.initcheck), (None, None, None));
1424    }
1425
1426    #[test]
1427    fn cics_return_warning_is_once_unless_the_flag_says_always_or_never() {
1428        let mut o = Options::default();
1429        assert_eq!(o.cics_return_warning, CicsReturnWarning::Once);
1430        for mode in [CicsReturnWarning::Always, CicsReturnWarning::Never, CicsReturnWarning::Once] {
1431            o.apply_flag(mode.flag()).unwrap();
1432            assert_eq!(o.cics_return_warning, mode);
1433        }
1434        assert!(o.apply_flag("--cics-return-warning=sometimes").is_err());
1435        assert!(o.apply_flag("--cics-return-warning").is_err());
1436    }
1437
1438    #[test]
1439    fn compliance_is_strict_unless_the_flag_says_extended() {
1440        let mut o = Options::default();
1441        assert_eq!(o.compliance, Compliance::Strict);
1442        for level in [Compliance::Extended, Compliance::Strict] {
1443            o.apply_flag(level.flag()).unwrap();
1444            assert_eq!(o.compliance, level);
1445            assert_eq!(Compliance::named(level.name()), Some(level));
1446        }
1447        for bad in ["--compliance=EXTENDED", "--compliance=", "--compliance", "--compliance=mf"] {
1448            assert!(o.apply_flag(bad).is_err(), "{bad}");
1449        }
1450        let flags = |given: &[&str]| Compliance::of(&given.iter().map(|f| f.to_string()).collect::<Vec<_>>());
1451        assert_eq!(flags(&[]), Compliance::Strict);
1452        assert_eq!(flags(&["-silent", "--compliance=extended"]), Compliance::Extended);
1453        assert_eq!(flags(&["--compliance=extended", "--compliance=strict"]), Compliance::Strict);
1454    }
1455
1456    #[test]
1457    fn the_dialect_is_ibm_unless_the_flag_says_gnucobol() {
1458        let mut o = Options::default();
1459        assert_eq!(o.dialect, Dialect::Ibm);
1460        for dialect in [Dialect::Gnucobol, Dialect::Ibm] {
1461            o.apply_flag(dialect.flag()).unwrap();
1462            assert_eq!(o.dialect, dialect);
1463            assert_eq!(Dialect::named(dialect.name()), Some(dialect));
1464        }
1465        for bad in ["--dialect=GNUCOBOL", "--dialect=", "--dialect", "--dialect=mf"] {
1466            assert!(o.apply_flag(bad).is_err(), "{bad}");
1467        }
1468        assert_eq!(o.dialect, Dialect::Ibm);
1469    }
1470
1471    #[test]
1472    fn each_switch_names_its_assumption_in_the_order_switched_lists_them() {
1473        use assumptions::*;
1474        let ids = [ROUNDED_EXTRA_PLACE, DISPLAY_OF_NONDISPLAY_NUMERIC, DECIMAL_COMMA_DISPLAY_LITERAL, ACCEPT_AT_END, ENTRY_CALLS, EXTERNAL_STORAGE, OPTIMIZED_ZONES_COMPARED];
1475        let switched = [
1476            Switched::RoundedExtraPlace,
1477            Switched::DisplayOfNondisplayNumeric,
1478            Switched::DecimalCommaDisplayLiteral,
1479            Switched::AcceptAtEnd,
1480            Switched::EntryCalls,
1481            Switched::ExternalStorage,
1482            Switched::OptimizedZonesCompared,
1483        ];
1484        for (s, id) in switched.into_iter().zip(ids) {
1485            let (switch, values) = SWITCHES[s as usize];
1486            assert_eq!(switch, id);
1487            assert_eq!(values[..2], ["ibm", "gnucobol"], "{id}");
1488            assert_eq!(get(id).basis, Basis::Chosen, "{id}");
1489        }
1490    }
1491
1492    #[test]
1493    fn assume_switches_one_assumption_and_wins_over_the_dialect_whatever_the_order() {
1494        let mut o = Options::default();
1495        assert_eq!((o.extra_place(), o.dialect_of(Switched::AcceptAtEnd)), (ExtraPlace::Every, Dialect::Ibm));
1496        o.apply_flag("--assume=C15=gnucobol").unwrap();
1497        assert_eq!((o.extra_place(), o.dialect_of(Switched::AcceptAtEnd)), (ExtraPlace::Every, Dialect::Gnucobol));
1498        o.apply_flag("--dialect=gnucobol").unwrap();
1499        o.apply_flag("--assume=C101=off").unwrap();
1500        assert_eq!((o.extra_place(), o.dialect_of(Switched::EntryCalls)), (ExtraPlace::Off, Dialect::Gnucobol));
1501        o.apply_flag("--assume=C101=ibm").unwrap();
1502        assert_eq!(o.extra_place(), ExtraPlace::Every);
1503        assert_eq!(o.assume_flags().collect::<Vec<_>>(), ["--assume=C101=ibm", "--assume=C15=gnucobol"]);
1504        assert_eq!(o.alternatives_in_force().map(|(id, _)| id).collect::<Vec<_>>(), ["C14", "C95", "C15", "C51", "C180", "C262"]);
1505        o.apply_flag("--dialect=ibm").unwrap();
1506        assert_eq!(o.alternatives_in_force().collect::<Vec<_>>(), [("C15", "gnucobol")]);
1507        assert!(o.apply_flag("--assume=C101=on").is_err());
1508        assert_eq!(o.extra_place(), ExtraPlace::Every);
1509    }
1510
1511    #[test]
1512    fn assume_refuses_by_name_what_it_cannot_switch() {
1513        assert_eq!(Assumed::parse("C101=off"), Ok((0, 3)));
1514        assert_eq!(Assumed::parse("C262=ibm"), Ok((6, 1)));
1515        for (spec, said) in [
1516            ("C101", "--assume C101: needs ID=VALUE, such as C101=off"),
1517            ("C1=gnucobol", "--assume C1=gnucobol: assumption C1 (documented) has no alternative; --assume switches C101, C14, C95, C15, C51, C180 and C262"),
1518            ("C16=gnucobol", "--assume C16=gnucobol: assumption C16 (chosen) has no alternative; --assume switches C101, C14, C95, C15, C51, C180 and C262"),
1519            ("C9999=off", "--assume C9999=off: the register has no assumption C9999; ironwork assumptions lists them"),
1520            ("C14=off", "--assume C14=off: C14 takes ibm or gnucobol"),
1521            ("C101=GNUCOBOL", "--assume C101=GNUCOBOL: C101 takes ibm, gnucobol or off"),
1522        ] {
1523            assert_eq!(Assumed::parse(spec), Err(said.to_owned()), "{spec}");
1524        }
1525    }
1526}