1use crate::assumptions;
2use std::fmt;
3use zarch::ebcdic::{self, CodePage};
4use zarch::hfp::Precision;
5
6const TABLE: &str = include_str!("../data/enterprise-options.tsv");
9
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub struct Documented {
13 pub name: &'static str,
14 spellings: &'static str,
15 pub process: bool,
17 pub first_program_only: bool,
19 pub installation_default: bool,
20 pub page: u16,
22}
23
24impl Documented {
25 pub fn spellings(&self) -> impl Iterator<Item = &'static str> {
26 self.spellings.split(' ')
27 }
28}
29
30pub 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
39pub 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
46pub 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
103pub enum TruncCheck {
104 #[default]
105 Report,
106 Silent,
107}
108
109#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
113pub enum SortKeys {
114 #[default]
115 Dfsort,
116 Strict,
117}
118
119#[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#[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#[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#[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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
188pub struct BinCheck {
189 pub truncbin: bool,
190}
191
192#[derive(Clone, Copy, Debug, PartialEq, Eq)]
196pub struct Parmcheck {
197 pub abd: bool,
198 pub bytes: u16,
199}
200
201#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
205pub enum Initcheck {
206 #[default]
207 Lax,
208 Strict,
209}
210
211#[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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
235pub enum Quote {
236 #[default]
237 Quote,
238 Apost,
239}
240
241impl Quote {
242 pub const fn byte(self) -> u8 {
244 match self {
245 Self::Quote => ebcdic::QUOTE,
246 Self::Apost => ebcdic::APOSTROPHE,
247 }
248 }
249
250 pub const fn unit(self) -> u16 {
252 match self {
253 Self::Quote => 0x0022,
254 Self::Apost => 0x0027,
255 }
256 }
257}
258
259#[derive(Clone, Copy, Debug, PartialEq, Eq)]
262pub enum Currency {
263 Char(char),
264 Hex(u8),
265}
266
267#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
270pub enum Nsymbol {
271 #[default]
272 National,
273 Dbcs,
274}
275
276#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
280pub enum DispSign {
281 #[default]
282 Compat,
283 Sep,
284}
285
286#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
289pub enum IntDate {
290 #[default]
291 Ansi,
292 Lilian,
293}
294
295#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
298pub enum Qualify {
299 #[default]
300 Compat,
301 Extend,
302}
303
304#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
308pub enum Vlr {
309 #[default]
310 Standard,
311 Compat,
312}
313
314#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
318pub enum VsamOpenFs {
319 #[default]
320 Compat,
321 Succ,
322}
323
324#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
327pub enum Warnings {
328 #[default]
329 Proceed,
330 Block,
331}
332
333#[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 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#[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
379pub 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
395pub enum ExtraPlace {
396 Every,
397 Last,
398 Off,
399}
400
401#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
404pub struct Assumed {
405 pub given: [u8; SWITCHES.len()],
406}
407
408impl Assumed {
409 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
429fn 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
441pub enum Compile {
442 Full,
444 Until(Stop),
446 SyntaxOnly,
448}
449
450#[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 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#[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 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 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 pub fastsrt: bool,
523 pub fastsrt_adv_print: FastsrtAdvPrint,
524 pub sort_keys: SortKeys,
525 pub adv: bool,
528 pub thread: bool,
530 pub dll: bool,
531 pub rent: bool,
532 pub dbcs: bool,
533 pub warnings: Warnings,
534 pub compile: Option<Compile>,
536 pub dynam: bool,
538 pub debug: bool,
541 pub cics_return_warning: CicsReturnWarning,
542 pub invdata: Option<Invdata>,
544 pub zwb: bool,
546 pub quote: Quote,
547 pub currency: Option<Currency>,
550 pub nsymbol: Nsymbol,
551 pub dispsign: DispSign,
552 pub intdate: IntDate,
553 pub qualify: Qualify,
554 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 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#[derive(Clone, Debug, PartialEq, Eq)]
616pub enum OptionError {
617 BadSuboption { option: String, given: String },
619 Removed { option: String, since: &'static str, instead: &'static str },
621 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
640fn 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
654fn 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
673fn inner(option: &str) -> &str {
675 option.split_once('(').map_or("", |(_, rest)| rest.trim_end().strip_suffix(')').unwrap_or(rest)).trim()
676}
677
678fn 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
696fn 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
748fn 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
766pub 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 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 "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 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 "--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 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 pub fn zones_compared(&self) -> bool {
997 match self.invdata {
998 Some(i) => !i.forcenumcmp,
999 None => self.optimize > 0,
1000 }
1001 }
1002
1003 pub fn zones_compared_with_zero(&self) -> bool {
1007 self.zones_compared() && !self.cobc_zoned_compare()
1008 }
1009
1010 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 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 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 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 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 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 #[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}