ironwork-syntax 0.4.1

ironwork for COBOL: fixed-format source reader, lexer and parser
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
use crate::Pos;

mod oo;
pub use oo::*;

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Program {
    pub id: String,
    /// Options from CBL and PROCESS cards, in the order written.
    pub options: Vec<String>,
    /// PROGRAM-ID ... IS INITIAL, or once compiled the INITIAL option: WORKING-STORAGE starts
    /// afresh on every CALL.
    pub initial: bool,
    pub recursive: bool,
    /// PROGRAM-ID ... IS COMMON, for a program another contains.
    pub common: bool,
    pub working_storage: Vec<DataEntry>,
    /// LOCAL-STORAGE: fresh for every activation of the program.
    pub local_storage: Vec<DataEntry>,
    pub linkage: Vec<DataEntry>,
    /// PROCEDURE DIVISION USING: the LINKAGE items the caller's arguments address.
    pub using: Vec<Param>,
    pub returning: Option<String>,
    pub paragraphs: Vec<Paragraph>,
    /// Files declared by SELECT and described by FD, with their record descriptions.
    pub files: Vec<FileDecl>,
    /// The program's source file, then each COPY member, as positions index them.
    pub sources: Vec<String>,
    /// EXEC blocks in the DATA DIVISION: SQL declarations, cursors and DECLARE SECTION markers.
    pub exec_declarations: Vec<ExecBlock>,
    /// The REPORT SECTION, and the DECLARATIVES that serve it.
    pub report_writer: crate::report::ReportWriter,
    /// The DECLARATIVES' USE AFTER EXCEPTION/ERROR and USE FOR DEBUGGING procedures.
    pub declaratives: Declaratives,
    /// The REPOSITORY's classes, and for a class definition or a method what it is.
    pub oo: Option<Box<Oo>>,
    pub environment: Environment,
    /// The PROGRAM-IDs of the programs it directly contains.
    pub nested: Vec<String>,
    /// The programs that contain it, innermost first, with the names each declares GLOBAL.
    pub containers: Vec<Container>,
    /// The messages reading its source gave that did not stop the parse, in the order found.
    pub messages: Vec<crate::Error>,
    /// FUNCTION-ID in place of PROGRAM-ID: a user-defined function, or a prototype of one.
    pub function: Option<Function>,
    /// The user-defined functions it may invoke: those defined or prototyped before it in its
    /// source, and a function itself.
    pub prototypes: Vec<Prototype>,
}

impl Program {
    /// The name a CALL or a function invocation loads it by: a function's external name.
    pub fn load_name(&self) -> &str {
        self.function.as_ref().map_or(&self.id, |f| &f.external)
    }

    pub fn is_prototype(&self) -> bool {
        self.function.as_ref().is_some_and(|f| f.prototype)
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Function {
    /// AS literal-1, else the function-name.
    pub external: String,
    /// IS PROTOTYPE: a description for invocations to be checked against, with no code.
    pub prototype: bool,
    pub pos: Pos,
}

/// A user-defined function as its definition or prototype describes it to an invocation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Prototype {
    pub name: String,
    pub external: String,
    pub using: Vec<Param>,
    pub returning: Option<String>,
    pub linkage: Vec<DataEntry>,
    /// The PICTURE notation of its definition: DECIMAL-POINT IS COMMA and the currency signs.
    pub environment: Environment,
    pub pos: Pos,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Param {
    pub by_value: bool,
    pub name: String,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Organization {
    Sequential,
    LineSequential,
    Indexed,
    Relative,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Access {
    #[default]
    Sequential,
    Random,
    Dynamic,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FileDecl {
    pub name: String,
    /// The DD name ASSIGN gives, with any `UT-S-` style prefix removed.
    pub assign: String,
    pub organization: Organization,
    pub access: Access,
    pub record_key: Option<Ref>,
    /// ALTERNATE RECORD KEY items, and whether each allows duplicates.
    pub alternate_keys: Vec<(Ref, bool)>,
    pub relative_key: Option<Ref>,
    pub optional: bool,
    pub status: Option<Ref>,
    /// FILE STATUS's second data-name, for a VSAM file: the return, function and feedback codes.
    pub vsam_status: Option<Ref>,
    /// PASSWORD IS items, checked and of no effect, as files here have no passwords.
    pub passwords: Vec<Ref>,
    /// RECORDING MODE: F, V, U or S.
    pub recording: Option<char>,
    pub record_min: Option<u32>,
    pub record_max: Option<u32>,
    /// RECORD IS VARYING: `record_min` and `record_max` are its FROM and TO, each None when not
    /// written (Language Reference SC27-8713-03, p. 187).
    pub record_varying: bool,
    /// RECORD IS VARYING ... DEPENDING ON: the item holding each record's length.
    pub record_depending: Option<Ref>,
    pub records: Vec<DataEntry>,
    /// FD ... REPORT IS: the reports written to the file.
    pub reports: Vec<String>,
    /// FD ... LINAGE: the logical page. An SD's is read and dropped, as IBM ignores it.
    pub linage: Option<Linage>,
    /// Described by SD: a sort or merge file, which needs no data set.
    pub sort: bool,
    pub external: bool,
    pub global: bool,
    /// For a GLOBAL file of a program containing this one, that program's PROGRAM-ID.
    pub declared_in: Option<String>,
    pub pos: Pos,
}

/// A program containing another, as the contained program sees it: its PROGRAM-ID, and the 01
/// records and files it declares GLOBAL, each with what is subordinate to it.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Container {
    pub id: String,
    pub working_storage: Vec<DataEntry>,
    pub local_storage: Vec<DataEntry>,
    pub linkage: Vec<DataEntry>,
    pub files: Vec<FileDecl>,
}

/// LINAGE IS lines [WITH FOOTING AT footing] [LINES AT TOP top] [LINES AT BOTTOM bottom].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Linage {
    pub lines: LinageValue,
    pub footing: Option<LinageValue>,
    pub top: Option<LinageValue>,
    pub bottom: Option<LinageValue>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LinageValue {
    /// The digits as written, whose count sizes LINAGE-COUNTER.
    Integer(String),
    Data(Ref),
}

pub use rt::vocab::{Closing, OpenMode};

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Advancing {
    Lines { before: bool, count: Expr },
    Page { before: bool },
    /// A mnemonic-name of SPECIAL-NAMES, with the environment-name it stands for: C01 to C12,
    /// CSP, S01 to S05 or AFP-5A.
    Mnemonic { before: bool, name: String, environment: String },
}

impl Advancing {
    pub fn before(&self) -> bool {
        match self {
            Self::Lines { before, .. } | Self::Page { before } | Self::Mnemonic { before, .. } => *before,
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Usage {
    #[default]
    Display,
    Binary,
    /// COMP-5: binary, never truncated to the PICTURE.
    NativeBinary,
    Packed,
    Float1,
    Float2,
    National,
    Pointer,
    Index,
    ObjectReference,
    /// FUNCTION-POINTER or PROCEDURE-POINTER.
    ProgramPointer,
}

pub use rt::vocab::{SignClause, SignPosition};

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DataEntry {
    pub level: u8,
    /// None for FILLER or an unnamed entry.
    pub name: Option<String>,
    /// The name as the source spells it, where that is not all capitals: JSON and XML GENERATE
    /// keep it.
    pub spelled: Option<String>,
    pub picture: Option<String>,
    /// None when no USAGE is written; the item then inherits its group's.
    pub usage: Option<Usage>,
    pub value: Option<Literal>,
    pub redefines: Option<String>,
    /// OCCURS: the number of occurrences, or the most of them for OCCURS DEPENDING ON.
    pub occurs: Option<u32>,
    /// OCCURS ... DEPENDING ON: the fewest occurrences, 1 when no integer-1 TO is written
    /// (Language Reference SC27-8713-03, p. 204).
    pub occurs_min: Option<u32>,
    /// OCCURS ... DEPENDING ON: the item that holds how many occurrences there are.
    pub depending_on: Option<Ref>,
    pub sign: Option<SignClause>,
    pub justified: bool,
    pub sync: bool,
    pub blank_when_zero: bool,
    /// OCCURS ... INDEXED BY: the index names the table declares.
    pub indexed_by: Vec<String>,
    /// OCCURS ... ASCENDING/DESCENDING KEY: each key and whether it ascends, for SEARCH ALL.
    pub keys: Vec<(bool, Ref)>,
    /// Level 88: the values that make the condition true.
    /// Each value, or the low and high ends of a THRU range.
    pub condition_values: Vec<(Literal, Option<Literal>)>,
    /// Level 88 WHEN SET TO FALSE: the value SET ... TO FALSE stores.
    pub false_value: Option<Literal>,
    /// Level 66 RENAMES: the item renamed, or the first and last of a THRU range.
    pub renames: Option<(Ref, Option<Ref>)>,
    /// USAGE OBJECT REFERENCE class-name: the class; None for a universal reference.
    pub object_class: Option<String>,
    /// EXTERNAL, written on the entry or attained from its FD.
    pub external: bool,
    /// GLOBAL, written on the entry or attained from its FD.
    pub global: bool,
    pub pos: Pos,
}

pub use rt::vocab::Figurative;

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Literal {
    Alnum(String),
    Hex(Vec<u8>),
    National(String),
    /// As written: optional sign, digits, optional decimal point.
    Number(String),
    Figurative(Figurative),
    All(Box<Literal>),
}

/// A paragraph, or a section header holding the statements before the section's first paragraph.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Paragraph {
    pub name: String,
    pub statements: Vec<Stmt>,
    /// The section the paragraph belongs to, or the section's own name for its header.
    pub section: Option<String>,
    pub is_section: bool,
    /// The section's priority-number, 0 when it has none: 50 to 99 is an independent segment.
    pub priority: u8,
    pub pos: Pos,
}

/// A procedure name as written, with the section that qualifies it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProcName {
    pub name: String,
    pub section: Option<String>,
}

/// USE AFTER EXCEPTION/ERROR and USE FOR DEBUGGING sections; USE BEFORE REPORTING ones are the
/// Report Writer's.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Declaratives {
    pub errors: Vec<UseAfterError>,
    pub debugging: Vec<UseForDebugging>,
}

/// A USE AFTER STANDARD EXCEPTION/ERROR PROCEDURE section.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UseAfterError {
    /// The section's header among the program's paragraphs.
    pub section: usize,
    pub global: bool,
    pub on: ErrorUse,
    pub pos: Pos,
}

/// The files an EXCEPTION/ERROR procedure serves: those it names, or those open in one mode.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ErrorUse {
    Files(Vec<String>),
    Mode(OpenMode),
}

/// A USE FOR DEBUGGING section, which runs before each procedure it names.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UseForDebugging {
    pub section: usize,
    /// Empty for ALL PROCEDURES.
    pub procedures: Vec<ProcName>,
    pub pos: Pos,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ExitKind {
    Plain,
    Paragraph,
    Section,
    Perform,
    PerformCycle,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Subject {
    Bool(bool),
    Expr(Expr),
    Cond(Cond),
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Object {
    Any,
    Bool(bool),
    Cond(Cond),
    Value { not: bool, from: Expr, thru: Option<Expr> },
}

/// One WHEN group: any of its alternatives, each with an object per subject, selects the body.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct When {
    pub alternatives: Vec<Vec<Object>>,
    pub body: Vec<Stmt>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Ref {
    pub name: String,
    pub qualifiers: Vec<String>,
    pub subscripts: Vec<Expr>,
    pub refmod: Option<RefMod>,
    pub pos: Pos,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RefMod {
    pub start: Box<Expr>,
    pub length: Option<Box<Expr>>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FunctionCall {
    pub name: String,
    pub args: Vec<Expr>,
    /// A keyword argument, as in FUNCTION TRIM(X LEADING).
    pub modifier: Option<String>,
    pub refmod: Option<RefMod>,
    /// Each argument written as a table with ALL subscripts, as in FUNCTION SUM(T(ALL)): its index
    /// and the positions of those subscripts, where its reference holds 1.
    pub all_subscripts: Vec<(usize, Vec<usize>)>,
    pub pos: Pos,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Operand {
    Ref(Ref),
    Literal(Literal),
    Function(FunctionCall),
    LengthOf(Ref),
    AddressOf(Ref),
}

pub use rt::vocab::{AcceptFrom, BinOp, RelOp};

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Expr {
    Operand(Operand),
    Neg(Box<Expr>),
    Bin(Box<Expr>, BinOp, Box<Expr>),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Class {
    Numeric,
    Alphabetic,
    AlphabeticLower,
    AlphabeticUpper,
    Positive,
    Negative,
    Zero,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Cond {
    Rel(Expr, RelOp, Expr),
    Class(Expr, Class),
    Name(Ref),
    /// After AND or OR, a bare name that is either a condition-name or the object of an
    /// abbreviated relation; which one depends on what the name resolves to. `negated` is a NOT
    /// the relational operator carries, as in NOT =.
    NameOrRel { subject: Expr, op: RelOp, negated: bool, name: Ref },
    Not(Box<Cond>),
    And(Box<Cond>, Box<Cond>),
    Or(Box<Cond>, Box<Cond>),
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Target {
    pub r: Ref,
    pub rounded: bool,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Varying {
    pub var: Ref,
    pub from: Expr,
    pub by: Expr,
    pub until: Cond,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Loop {
    Once,
    Times(Expr),
    Until { cond: Cond, test_after: bool },
    /// VARYING, and each AFTER phrase, outermost first.
    Varying { varying: Box<Varying>, after: Vec<Varying>, test_after: bool },
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Stmt {
    Move { from: Operand, to: Vec<Ref>, pos: Pos },
    Compute { targets: Vec<Target>, expr: Expr, size_error: Option<SizeError>, pos: Pos },
    /// ADD, SUBTRACT, MULTIPLY and DIVIDE, reduced to their arithmetic.
    Arith(Box<Arith>),
    /// MOVE, ADD or SUBTRACT CORRESPONDING, which the compiler expands into a MOVE per pair of
    /// corresponding items, or one ADD or SUBTRACT over them all.
    Corresponding(Box<Corresponding>),
    If { cond: Cond, then: Vec<Stmt>, otherwise: Vec<Stmt>, pos: Pos },
    PerformInline { body: Vec<Stmt>, repeat: Loop, pos: Pos },
    PerformProc { from: ProcName, thru: Option<ProcName>, repeat: Loop, pos: Pos },
    Evaluate { subjects: Vec<Subject>, whens: Vec<When>, other: Vec<Stmt>, pos: Pos },
    Display { items: Vec<Operand>, no_advancing: bool, pos: Pos },
    Open { files: Vec<(OpenMode, String)>, pos: Pos },
    Close { files: Vec<(String, Option<Closing>)>, pos: Pos },
    Read(Box<ReadStmt>),
    Write { record: Ref, from: Option<Operand>, advancing: Option<Advancing>, invalid: Handlers, end_of_page: Handlers, pos: Pos },
    Rewrite { record: Ref, from: Option<Operand>, invalid: Handlers, pos: Pos },
    Delete { file: String, invalid: Handlers, pos: Pos },
    Start { file: String, key: Option<(RelOp, Ref)>, invalid: Handlers, pos: Pos },
    /// INITIALIZE; `with` holds its FILLER, VALUE, REPLACING and DEFAULT phrases, None without any.
    Initialize { targets: Vec<Ref>, with: Option<Box<InitializeWith>>, pos: Pos },
    /// GO TO; with no target, the altered GO TO that only an ALTER gives one.
    GoTo { target: Option<ProcName>, pos: Pos },
    /// GO TO ... DEPENDING ON: the procedure the item's value numbers, or on when none does.
    GoToDepending { targets: Vec<ProcName>, on: Ref, pos: Pos },
    /// ALTER: each paragraph whose GO TO is to go instead to the procedure paired with it.
    Alter { pairs: Vec<(ProcName, ProcName)>, pos: Pos },
    /// ENTRY: where a CALL of `name` begins, and the LINKAGE items its USING list addresses.
    Entry { name: String, using: Vec<Param>, pos: Pos },
    Goback { pos: Pos },
    /// EXIT PROGRAM: returns from a called program; in the first program it does nothing.
    ExitProgram { pos: Pos },
    Call(Box<Call>),
    Cancel { targets: Vec<Operand>, pos: Pos },
    Set { set: SetStmt, pos: Pos },
    Accept { target: Ref, from: AcceptFrom, pos: Pos },
    String(Box<StringStmt>),
    Unstring(Box<Unstring>),
    Inspect(Box<Inspect>),
    Search(Box<Search>),
    /// NEXT SENTENCE: control passes to the statement after the next separator period.
    NextSentence,
    /// A separator period in the PROCEDURE DIVISION: where NEXT SENTENCE resumes.
    SentenceEnd,
    Exec(Box<ExecBlock>),
    Report(Box<crate::report::ReportStmt>),
    Invoke(Box<Invoke>),
    JsonGenerate(Box<JsonGenerate>),
    JsonParse(Box<JsonParse>),
    XmlParse(Box<XmlParse>),
    XmlGenerate(Box<XmlGenerate>),
    ExitMethod { pos: Pos },
    Sorting(Box<Sorting>),
    StopRun { pos: Pos },
    Continue,
    Exit { kind: ExitKind, pos: Pos },
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SizeError {
    pub on: Vec<Stmt>,
    pub not_on: Vec<Stmt>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ArithVerb {
    Add,
    Subtract,
    Multiply,
    Divide,
}

/// One arithmetic statement: `targets` each receive `expr`, which is written in terms of the
/// statement's operands and, for the forms without GIVING, the target itself (`Operand::Ref` of
/// the target, placed by the parser).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Arith {
    pub verb: ArithVerb,
    pub computations: Vec<(Target, Expr)>,
    pub remainder: Option<(Target, Expr, Expr)>,
    pub size_error: Option<SizeError>,
    pub pos: Pos,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CorrespondingVerb {
    Move,
    Add,
    Subtract,
}

/// `from` is the sending group and `to` the receiving one; `rounded` and `size_error` are ADD's
/// and SUBTRACT's.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Corresponding {
    pub verb: CorrespondingVerb,
    pub from: Ref,
    pub to: Ref,
    pub rounded: bool,
    pub size_error: Option<SizeError>,
    pub pos: Pos,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ArgMode {
    Reference,
    Content,
    Value,
}

/// One CALL argument; `value` is None for OMITTED.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Arg {
    pub mode: ArgMode,
    pub value: Option<Operand>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Call {
    pub target: Operand,
    pub using: Vec<Arg>,
    pub returning: Option<Ref>,
    pub on_exception: Option<Vec<Stmt>>,
    pub not_on_exception: Option<Vec<Stmt>>,
    pub pos: Pos,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SetStmt {
    ConditionTrue(Vec<Ref>),
    /// SET condition-names TO FALSE: each conditional variable gets its WHEN SET TO FALSE value.
    ConditionFalse(Vec<Ref>),
    /// SET targets TO value: an index or integer to a number, a pointer to ADDRESS OF, NULL or another pointer.
    To { targets: Vec<Ref>, value: Operand },
    /// SET procedure-pointers or function-pointers TO ENTRY, the entry named by a literal or identifier.
    Entry { targets: Vec<Ref>, entry: Operand },
    /// SET ADDRESS OF targets TO pointer.
    AddressOf { targets: Vec<Ref>, value: Operand },
    UpDown { targets: Vec<Ref>, down: bool, by: Expr },
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Delimiter {
    Size,
    By(Operand),
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StringStmt {
    pub sources: Vec<(Operand, Delimiter)>,
    pub into: Ref,
    pub pointer: Option<Ref>,
    pub on_overflow: Option<Vec<Stmt>>,
    pub not_on_overflow: Option<Vec<Stmt>>,
    pub pos: Pos,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UnstringInto {
    pub target: Ref,
    pub delimiter_in: Option<Ref>,
    pub count_in: Option<Ref>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Unstring {
    pub source: Ref,
    /// Each delimiter, and whether ALL makes a run of it one delimiter.
    pub delimiters: Vec<(bool, Operand)>,
    pub into: Vec<UnstringInto>,
    pub pointer: Option<Ref>,
    pub tallying: Option<Ref>,
    pub on_overflow: Option<Vec<Stmt>>,
    pub not_on_overflow: Option<Vec<Stmt>>,
    pub pos: Pos,
}

/// BEFORE or AFTER INITIAL value: where in the inspected item a phrase applies.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Bound {
    pub after: bool,
    pub value: Operand,
}

pub use rt::vocab::InspectMode;

/// One TALLYING or REPLACING phrase. `pattern` is None for CHARACTERS; `by` is None for TALLYING.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct InspectPhrase {
    pub mode: InspectMode,
    pub pattern: Option<Operand>,
    pub by: Option<Operand>,
    pub counter: Option<Ref>,
    pub bounds: Vec<Bound>,
}

/// The categories INITIALIZE's VALUE and REPLACING phrases name (Language Reference SC27-8713-03,
/// p. 350); EGCS is DBCS.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DataCategory {
    Alphabetic,
    Alphanumeric,
    AlphanumericEdited,
    Dbcs,
    National,
    NationalEdited,
    Numeric,
    NumericEdited,
    Utf8,
}

impl DataCategory {
    pub const ALL: [Self; 9] = [
        Self::Alphabetic,
        Self::Alphanumeric,
        Self::AlphanumericEdited,
        Self::Dbcs,
        Self::National,
        Self::NationalEdited,
        Self::Numeric,
        Self::NumericEdited,
        Self::Utf8,
    ];

    pub fn from_word(word: &str) -> Option<Self> {
        Some(match word {
            "ALPHABETIC" => Self::Alphabetic,
            "ALPHANUMERIC" => Self::Alphanumeric,
            "ALPHANUMERIC-EDITED" => Self::AlphanumericEdited,
            "DBCS" | "EGCS" => Self::Dbcs,
            "NATIONAL" => Self::National,
            "NATIONAL-EDITED" => Self::NationalEdited,
            "NUMERIC" => Self::Numeric,
            "NUMERIC-EDITED" => Self::NumericEdited,
            "UTF-8" => Self::Utf8,
            _ => return None,
        })
    }

    pub fn word(self) -> &'static str {
        match self {
            Self::Alphabetic => "ALPHABETIC",
            Self::Alphanumeric => "ALPHANUMERIC",
            Self::AlphanumericEdited => "ALPHANUMERIC-EDITED",
            Self::Dbcs => "DBCS",
            Self::National => "NATIONAL",
            Self::NationalEdited => "NATIONAL-EDITED",
            Self::Numeric => "NUMERIC",
            Self::NumericEdited => "NUMERIC-EDITED",
            Self::Utf8 => "UTF-8",
        }
    }
}

/// INITIALIZE's phrases. `value` lists the VALUE phrase's categories, every one for ALL TO VALUE.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct InitializeWith {
    pub filler: bool,
    pub value: Vec<DataCategory>,
    pub replacing: Vec<(DataCategory, Operand)>,
    pub default: bool,
}

/// What an elementary receiver of INITIALIZE is sent.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InitialValue<'a> {
    /// The literal of the item's own VALUE clause.
    Value,
    Replacing(&'a Operand),
    /// SPACE, ZERO or NULL, by the item's category.
    Default,
}

impl InitializeWith {
    /// Rules 1c and 2 of INITIALIZE (Language Reference SC27-8713-03, pp. 352-353) for an
    /// elementary item of `category`, which `has_value` when its entry has a VALUE clause; None when
    /// the item is not a receiver.
    pub fn initial_value(&self, category: Option<DataCategory>, has_value: bool) -> Option<InitialValue<'_>> {
        let named = |c: DataCategory| category == Some(c);
        if has_value && self.value.iter().any(|&c| named(c)) {
            return Some(InitialValue::Value);
        }
        if let Some((_, by)) = self.replacing.iter().find(|(c, _)| named(*c)) {
            return Some(InitialValue::Replacing(by));
        }
        (self.default || self.value.is_empty() && self.replacing.is_empty()).then_some(InitialValue::Default)
    }
}

/// `target` is a data item or, for TALLYING alone, a function's value.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Inspect {
    pub target: Operand,
    pub tallying: Vec<InspectPhrase>,
    pub replacing: Vec<InspectPhrase>,
    pub converting: Option<(Operand, Operand, Vec<Bound>)>,
    pub pos: Pos,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Search {
    pub table: Ref,
    pub all: bool,
    pub varying: Option<Ref>,
    pub at_end: Option<Vec<Stmt>>,
    pub whens: Vec<(Cond, Vec<Stmt>)>,
    pub pos: Pos,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ExecKind {
    Sql,
    Cics,
    Dli,
    Other,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ExecArg {
    Operand(Operand),
    /// An argument that is not data: a paragraph for HANDLE CONDITION, or text that did not parse.
    Text(String),
}

/// An EXEC ... END-EXEC block, read but not translated.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExecBlock {
    pub kind: ExecKind,
    /// The command: SELECT, INCLUDE, DECLARE CURSOR, LINK, SEND MAP and so on.
    pub command: String,
    /// CICS options, each with its argument.
    pub options: Vec<(String, Option<ExecArg>)>,
    /// SQL host variables and indicator variables.
    pub host_variables: Vec<Ref>,
    /// The typed SQL statement, for EXEC SQL.
    pub sql: Option<crate::sql::Sql>,
    pub text: String,
    pub pos: Pos,
}

impl ExecBlock {
    /// Whether the block only declares, so a precompiler turns it into data or nothing.
    pub fn declarative(&self) -> bool {
        self.kind == ExecKind::Sql
            && matches!(self.command.as_str(), "INCLUDE" | "BEGIN DECLARE SECTION" | "END DECLARE SECTION" | "WHENEVER" | "DECLARE CURSOR" | "DECLARE TABLE" | "DECLARE STATEMENT")
    }
}

/// The statements of an ON phrase (AT END, INVALID KEY, ...) and of its NOT ON phrase.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Handlers {
    pub on: Option<Vec<Stmt>>,
    pub not_on: Option<Vec<Stmt>>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ReadStmt {
    pub file: String,
    /// READ NEXT or PREVIOUS: the next record by the key of reference, even under dynamic access.
    pub next: bool,
    pub previous: bool,
    pub into: Option<Ref>,
    /// READ ... KEY IS: the key of reference for a random read.
    pub key: Option<Ref>,
    pub at_end: Handlers,
    pub invalid: Handlers,
    pub pos: Pos,
}

/// What an ALPHABET clause relates its alphabet-name to.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Alphabet {
    Ebcdic,
    Native,
    Standard1,
    Standard2,
    /// A collating sequence of the program's own, lowest position first.
    Literal(Vec<AlphabetEntry>),
}

impl Alphabet {
    pub fn name(&self) -> &'static str {
        match self {
            Self::Ebcdic => "EBCDIC",
            Self::Native => "NATIVE",
            Self::Standard1 => "STANDARD-1",
            Self::Standard2 => "STANDARD-2",
            Self::Literal(_) => "literal",
        }
    }
}

/// One literal of an ALPHABET clause: its characters in successive positions, a THROUGH range of
/// characters in successive positions, or characters that ALSO share one position.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AlphabetEntry {
    Literal(Literal),
    Through(Literal, Literal),
    Also(Vec<Literal>),
}

/// ENVIRONMENT DIVISION clauses beyond SELECT that the program's meaning depends on.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Environment {
    /// SPECIAL-NAMES ALPHABET: each alphabet-name and what it is.
    pub alphabets: Vec<(String, Alphabet)>,
    /// OBJECT-COMPUTER PROGRAM COLLATING SEQUENCE.
    pub collating_sequence: Option<String>,
    /// I-O-CONTROL SAME RECORD AREA and SAME AREA clauses, each with the files it names.
    pub same_record_areas: Vec<Vec<String>>,
    pub same_areas: Vec<Vec<String>>,
    /// SPECIAL-NAMES entries naming a printer channel, space suppression, a punch pocket or AFP:
    /// each mnemonic-name and its environment-name.
    pub mnemonics: Vec<(String, String)>,
    /// SOURCE-COMPUTER ... WITH DEBUGGING MODE: debugging lines and USE FOR DEBUGGING sections are
    /// compiled rather than read as comments.
    pub debugging_mode: bool,
    /// SPECIAL-NAMES DECIMAL-POINT IS COMMA: the comma and the period exchange roles in PICTURE
    /// character-strings, numeric literals and the arguments of NUMVAL and NUMVAL-C.
    pub decimal_point_comma: bool,
    /// SPECIAL-NAMES CURRENCY SIGN clauses in order; none means the symbol and value $.
    pub currency: Vec<CurrencySign>,
}

/// A CURRENCY SIGN clause: the currency sign value, and the PICTURE symbol that stands for it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CurrencySign {
    pub value: String,
    pub symbol: char,
    /// CURRENCY SIGN IS X'...': the literal's bytes, which the program's code page makes `value`,
    /// and `symbol` too when there is no PICTURE SYMBOL (`symbol` is [`HEX_SYMBOL`] until then).
    pub hex: Option<Vec<u8>>,
}

/// The symbol of a hexadecimal CURRENCY SIGN without PICTURE SYMBOL before its code page decodes it.
pub const HEX_SYMBOL: char = '\0';

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Sorting {
    Sort(SortStmt),
    Release { record: Ref, from: Option<Operand>, pos: Pos },
    Return { file: String, into: Option<Ref>, at_end: Handlers, pos: Pos },
}

/// SORT or MERGE of an SD file, or SORT of a table (no input or output then).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SortStmt {
    pub merge: bool,
    /// The SD file, or the table.
    pub subject: Ref,
    /// Each key and whether it ascends, most significant first.
    pub keys: Vec<(bool, Ref)>,
    pub duplicates: bool,
    pub collating: Option<String>,
    pub input: Option<SortIo>,
    pub output: Option<SortIo>,
    pub pos: Pos,
}

/// USING or GIVING files, or an input or output procedure.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SortIo {
    Files(Vec<String>),
    Procedure { from: ProcName, thru: Option<ProcName> },
}


/// JSON GENERATE (Language Reference SC27-8713-03, pp. 369-382).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct JsonGenerate {
    pub receiver: Ref,
    pub from: Ref,
    pub count: Option<Ref>,
    /// NAME OF item IS literal; `None` for OMITTED.
    pub names: Vec<(Ref, Option<Literal>)>,
    pub suppress: Vec<Suppression>,
    pub converting: Vec<(Ref, JsonConversion)>,
    pub indicating: Vec<NullIndicator>,
    pub encoding: Option<Encoding>,
    pub on_exception: Option<Vec<Stmt>>,
    pub not_on_exception: Option<Vec<Stmt>>,
    pub pos: Pos,
}

/// A SUPPRESS phrase: an item, or EVERY item of a class (`Some(true)` NUMERIC, `Some(false)`
/// NONNUMERIC, `None` both) and, for XML GENERATE, of a form, suppressed always or only WHEN it
/// equals one of the figurative constants.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Suppression {
    Item { item: Ref, when: Vec<Figurative> },
    Every { numeric: Option<bool>, form: Option<XmlForm>, when: Vec<Figurative> },
}

/// A value that stands for true (CONVERTING ... TO JSON BOOLEAN) or for null (INDICATING): a
/// condition-name, or a one-character literal.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Marker {
    Condition(Ref),
    Literal(Literal),
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum JsonConversion {
    Boolean(Marker),
    Null(Figurative),
}

/// INDICATING item IS JSON NULL USING a condition-name of the indicator, or a literal IN it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NullIndicator {
    pub item: Ref,
    pub marker: Marker,
    pub indicator: Option<Ref>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Encoding {
    Ccsid(Operand),
    FromCodepage,
}

/// JSON PARSE (Language Reference SC27-8713-03, pp. 382-396).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct JsonParse {
    pub source: Ref,
    pub into: Ref,
    pub detail: bool,
    /// IGNORING JSON NULL FOR an item, or `None` FOR ALL.
    pub ignoring: Vec<Option<Ref>>,
    /// INDICATING item IS JSON NULL USING values, with IN and the indicator for two literals.
    pub indicating: Vec<(Ref, Flag, Option<Ref>)>,
    pub encoding: Option<Encoding>,
    /// NAME OF item IS literal; `None` for OMITTED.
    pub names: Vec<(Ref, Option<Literal>)>,
    pub suppress: Vec<Ref>,
    pub converting: Vec<(Ref, ParseConversion)>,
    pub on_exception: Option<Vec<Stmt>>,
    pub not_on_exception: Option<Vec<Stmt>>,
    pub pos: Pos,
}

/// What a USING phrase of JSON PARSE sets for true, or for null, and for false, or not null: a
/// condition-name set to true or to its WHEN SET TO FALSE value, one of two condition-names set to
/// true, or one of two literals moved in.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Flag {
    Condition(Ref),
    Conditions(Ref, Ref),
    Literals(Literal, Literal),
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ParseConversion {
    Boolean(Box<Flag>),
    Null(Figurative),
}

/// XML GENERATE (Language Reference SC27-8713-03, pp. 484-494).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct XmlGenerate {
    pub receiver: Ref,
    pub from: Ref,
    pub count: Option<Ref>,
    /// WITH ENCODING: the document's CCSID.
    pub encoding: Option<Operand>,
    pub declaration: bool,
    pub attributes: bool,
    pub namespace: Option<Operand>,
    pub prefix: Option<Operand>,
    pub names: Vec<(Ref, Literal)>,
    pub types: Vec<(Ref, XmlForm)>,
    pub suppress: Vec<Suppression>,
    pub on_exception: Option<Vec<Stmt>>,
    pub not_on_exception: Option<Vec<Stmt>>,
    pub pos: Pos,
}

/// How XML GENERATE expresses an item: as an attribute or an element, or as its parent's content.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum XmlForm {
    Attribute,
    Element,
    Content,
}

/// XML PARSE under XMLPARSE(XMLSS) (Language Reference SC27-8713-03, pp. 489-494).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct XmlParse {
    pub document: Ref,
    /// WITH ENCODING: the document's CCSID.
    pub encoding: Option<Operand>,
    pub returning_national: bool,
    pub procedure: ProcName,
    pub thru: Option<ProcName>,
    pub on_exception: Option<Vec<Stmt>>,
    pub not_on_exception: Option<Vec<Stmt>>,
    pub pos: Pos,
}