Skip to main content

ironwork_syntax/
source.rs

1//! Fixed-format reference format: columns 1-6 sequence, 7 indicator, 8-72 program text, 73 on
2//! ignored. The result is one logical text with continuation lines joined, and the options of any
3//! CBL or PROCESS cards ahead of the program.
4
5use crate::{Error, Pos};
6
7pub struct Source {
8    pub text: String,
9    /// For each char of `text`, where it came from.
10    pub positions: Vec<Pos>,
11    pub options: Vec<String>,
12    /// None when debugging lines (D in column 7) were read as comments; else the file and line of
13    /// each one read as program text.
14    pub debugging: Option<Vec<(u16, u32)>>,
15}
16
17const TEXT_START: usize = 7;
18const AREA_B: usize = 11;
19const TEXT_END: usize = 72;
20
21/// The IDENTIFICATION DIVISION paragraphs whose entry is a comment-entry (LR SC27-8713-03 p. 117),
22/// and REMARKS, which Enterprise COBOL does not have (numeric::assumptions::COMMENT_ENTRY_REMARKS).
23const COMMENT_PARAGRAPHS: &[&str] = &["AUTHOR", "INSTALLATION", "DATE-WRITTEN", "DATE-COMPILED", "SECURITY", "REMARKS"];
24
25pub fn read(input: &str) -> Result<Source, Error> {
26    read_file(input, 0)
27}
28
29/// Reads one file's text; `file` indexes its name in the program's file table. A comment-entry is
30/// left out of the text, so neither COPY nor the lexer sees it (LR pp. 117, 700).
31pub fn read_file(input: &str, file: u16) -> Result<Source, Error> {
32    read_lines(input, file, false)
33}
34
35/// Reads one file's text with its debugging lines as program text.
36pub fn read_file_debugging(input: &str, file: u16) -> Result<Source, Error> {
37    read_lines(input, file, true)
38}
39
40fn read_lines(input: &str, file: u16, debugging: bool) -> Result<Source, Error> {
41    let mut out = Source { text: String::new(), positions: Vec::new(), options: Vec::new(), debugging: debugging.then(Vec::new) };
42    let mut seen_program = false;
43    let mut open_quote: Option<char> = None;
44    let mut closed_at_72: Option<char> = None;
45    let (mut identification, mut comment_entry) = (false, false);
46    for (index, raw) in input.lines().enumerate() {
47        let line = index as u32 + 1;
48        let chars: Vec<char> = raw.trim_end_matches('\r').chars().map(|c| if c == '\t' { ' ' } else { c }).collect();
49        let body: String = chars.iter().take(TEXT_END).collect();
50        if !seen_program && let Some(options) = option_card(&body) {
51            out.options.extend(options);
52            continue;
53        }
54        let indicator = chars.get(6).copied().unwrap_or(' ');
55        let debugging_line = matches!(indicator, 'D' | 'd');
56        if indicator == '*' || indicator == '/' || (debugging_line && out.debugging.is_none()) {
57            continue;
58        }
59        let area: Vec<char> = chars.iter().take(TEXT_END).skip(TEXT_START).copied().collect();
60        if area.iter().all(|c| *c == ' ') {
61            continue;
62        }
63        if debugging_line && let Some(lines) = &mut out.debugging {
64            lines.push((file, line));
65        }
66        seen_program = true;
67        let area_a_blank = area.iter().take(AREA_B - TEXT_START).all(|c| *c == ' ');
68        if comment_entry && area_a_blank {
69            continue;
70        }
71        comment_entry = false;
72        let start_col = TEXT_START as u32 + 1;
73        if indicator == '-' {
74            let first = area.iter().position(|c| *c != ' ').unwrap();
75            let skip = match open_quote {
76                Some(q) if area[first] == q => first + 1,
77                Some(_) => return Err(Error::at(Pos { file, line, col: start_col + first as u32 }, "a continued literal must resume with its quote")),
78                // A closing quote in column 72 and the continuation's first two quotes are one doubled
79                // quote (LR p. 58).
80                None if closed_at_72.is_some_and(|q| area[first] == q && area.get(first + 1) == Some(&q)) => first + 1,
81                None => {
82                    while out.text.ends_with(' ') {
83                        out.text.pop();
84                        out.positions.pop();
85                    }
86                    // After a closed literal, a quote starts a second literal (LR p. 58).
87                    if matches!(area[first], '\'' | '"') && out.text.ends_with(['\'', '"']) {
88                        out.text.push(' ');
89                        out.positions.push(Pos { file, line, col: start_col + first as u32 });
90                    }
91                    first
92                }
93            };
94            for (i, &c) in area.iter().enumerate().skip(skip) {
95                if floating_comment(&area, i, open_quote) {
96                    break;
97                }
98                push(&mut out, c, Pos { file, line, col: start_col + i as u32 }, &mut open_quote);
99            }
100        } else {
101            if open_quote.is_some() {
102                return Err(Error::at(Pos { file, line, col: 1 }, "a literal runs to the end of the line with no continuation"));
103            }
104            if let Some(entering) = division_header(&area) {
105                identification = entering;
106            }
107            let header_end = if identification { comment_paragraph(&area) } else { None };
108            out.text.push('\n');
109            out.positions.push(Pos { file, line, col: 0 });
110            for (i, &c) in area.iter().enumerate().take(header_end.map_or(area.len(), |period| period + 1)) {
111                if floating_comment(&area, i, open_quote) {
112                    break;
113                }
114                push(&mut out, c, Pos { file, line, col: start_col + i as u32 }, &mut open_quote);
115            }
116            comment_entry = header_end.is_some();
117            if open_quote.is_some() {
118                for i in area.len()..TEXT_END - TEXT_START {
119                    push(&mut out, ' ', Pos { file, line, col: start_col + i as u32 }, &mut open_quote);
120                }
121            }
122        }
123        closed_at_72 = match (out.text.chars().next_back(), out.positions.last()) {
124            (Some(q @ ('\'' | '"')), Some(p)) if open_quote.is_none() && p.line == line && p.col == TEXT_END as u32 => Some(q),
125            _ => None,
126        };
127    }
128    if open_quote.is_some() {
129        return Err(Error::at(out.positions.last().copied().unwrap_or_default(), "an unterminated literal"));
130    }
131    Ok(out)
132}
133
134/// `*>` outside a literal starts a comment that runs to the end of the line.
135fn floating_comment(area: &[char], i: usize, open_quote: Option<char>) -> bool {
136    open_quote.is_none() && area[i] == '*' && area.get(i + 1) == Some(&'>')
137}
138
139/// The word that starts at or after `from`, uppercased, and the index just past it.
140fn word_from(area: &[char], from: usize) -> Option<(String, usize)> {
141    let start = from + area.get(from..)?.iter().position(|c| *c != ' ')?;
142    let len = area[start..].iter().take_while(|c| c.is_ascii_alphanumeric() || **c == '-' || **c == '_').count();
143    (len > 0).then(|| (area[start..start + len].iter().collect::<String>().to_ascii_uppercase(), start + len))
144}
145
146/// For a line that starts with a division header, whether it is the IDENTIFICATION DIVISION's.
147fn division_header(area: &[char]) -> Option<bool> {
148    let (first, end) = word_from(area, 0)?;
149    let (second, _) = word_from(area, end)?;
150    (second == "DIVISION").then(|| first == "IDENTIFICATION" || first == "ID")
151}
152
153/// Where the period is, for a line that starts with a paragraph header whose entry is a
154/// comment-entry.
155fn comment_paragraph(area: &[char]) -> Option<usize> {
156    let (word, end) = word_from(area, 0)?;
157    let period = end + area[end..].iter().position(|c| *c != ' ')?;
158    (area[period] == '.' && COMMENT_PARAGRAPHS.contains(&word.as_str())).then_some(period)
159}
160
161fn push(out: &mut Source, c: char, pos: Pos, open_quote: &mut Option<char>) {
162    match *open_quote {
163        Some(q) if c == q => *open_quote = None,
164        None if c == '\'' || c == '"' => *open_quote = Some(c),
165        _ => {}
166    }
167    out.text.push(c);
168    out.positions.push(pos);
169}
170
171/// A CBL or PROCESS card: its options, split at commas and spaces outside parentheses.
172fn option_card(line: &str) -> Option<Vec<String>> {
173    let sequence: String = line.chars().take(6).collect();
174    let line = if sequence.len() == 6 && sequence.chars().all(|c| c.is_ascii_digit() || c == ' ') { &line[6..] } else { line };
175    let trimmed = line.trim_start();
176    let keyword = trimmed.split(' ').next().unwrap_or("");
177    let rest = (keyword.eq_ignore_ascii_case("CBL") || keyword.eq_ignore_ascii_case("PROCESS")).then(|| &trimmed[keyword.len()..])?;
178    let (mut options, mut current, mut depth) = (Vec::new(), String::new(), 0i32);
179    for c in rest.chars() {
180        match c {
181            '(' => depth += 1,
182            ')' => depth -= 1,
183            _ => {}
184        }
185        if depth == 0 && (c == ',' || c == ' ') {
186            if !current.is_empty() {
187                options.push(std::mem::take(&mut current));
188            }
189        } else {
190            current.push(c);
191        }
192    }
193    if !current.is_empty() {
194        options.push(current);
195    }
196    Some(options)
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202
203    #[test]
204    fn option_cards_ahead_of_the_program_are_collected() {
205        let s = read("       CBL TRUNC(OPT),NUMPROC(PFD) ARITH(EXTEND)\n       PROCESS SSRANGE\n       IDENTIFICATION DIVISION.\n").unwrap();
206        assert_eq!(s.options, ["TRUNC(OPT)", "NUMPROC(PFD)", "ARITH(EXTEND)", "SSRANGE"]);
207        assert_eq!(s.text.trim(), "IDENTIFICATION DIVISION.");
208    }
209
210    #[test]
211    fn a_suboption_list_stays_whole() {
212        assert_eq!(option_card("CBL FLAG(I,W),X").unwrap(), ["FLAG(I,W)", "X"]);
213    }
214
215    #[test]
216    fn sequence_numbers_comments_and_columns_past_72_are_dropped() {
217        let s = read("000100 IDENTIFICATION DIVISION.                                         SEQ00001\n000200*a comment\n000300/page\n").unwrap();
218        assert_eq!(s.text.trim(), "IDENTIFICATION DIVISION.");
219    }
220
221    #[test]
222    fn a_continued_literal_keeps_its_trailing_spaces() {
223        let first = format!("       01 A PIC X(70) VALUE 'ABC{}", " ".repeat(72 - 34));
224        let text = format!("{first}\n      -    'DEF'.\n");
225        let s = read(&text).unwrap();
226        let literal = &s.text[s.text.find('\'').unwrap()..];
227        assert_eq!(literal.trim_end(), format!("'ABC{}DEF'.", " ".repeat(40)));
228    }
229
230    #[test]
231    fn an_option_card_may_be_lowercase() {
232        assert_eq!(read(" cbl dll,thread\n process ssrange\n").unwrap().options, ["dll", "thread", "ssrange"]);
233    }
234
235    #[test]
236    fn an_option_card_may_carry_a_sequence_number() {
237        assert_eq!(read("000010 CBL ARITH(EXTEND)\n").unwrap().options, ["ARITH(EXTEND)"]);
238    }
239
240    #[test]
241    fn a_continued_word_joins_without_a_space() {
242        let s = read("           MOVE ABC\n      -    DEF TO X.\n").unwrap();
243        assert!(s.text.contains("MOVE ABCDEF TO X."));
244    }
245
246    #[test]
247    fn a_floating_comment_ends_the_line_but_not_inside_a_literal() {
248        let s = read("           MOVE 1 TO X *> set X\n           DISPLAY '*> kept'\n").unwrap();
249        assert!(s.text.contains("MOVE 1 TO X") && !s.text.contains("set X"));
250        assert!(s.text.contains("'*> kept'"));
251    }
252
253    #[test]
254    fn a_comment_entry_is_left_out_of_the_text() {
255        let s = read(concat!(
256            "       IDENTIFICATION DIVISION.\n",
257            "       PROGRAM-ID. CE1.\n",
258            "       AUTHOR. James O'Grady & Sons @ ACME.\n",
259            "       security.\n",
260            "           THIS PROGRAM CHECKS THE COMPILER\"S ABILITY.\n",
261            "\n",
262            "      * a comment line\n",
263            "      -    A HYPHEN IN COLUMN 7.\n",
264            "           COPY NOTHERE.\n",
265            "       DATE-COMPILED.\n",
266            "       ENVIRONMENT DIVISION.\n",
267        ))
268        .unwrap();
269        let words: Vec<&str> = s.text.split_whitespace().collect();
270        assert_eq!(words, ["IDENTIFICATION", "DIVISION.", "PROGRAM-ID.", "CE1.", "AUTHOR.", "security.", "DATE-COMPILED.", "ENVIRONMENT", "DIVISION."]);
271    }
272
273    #[test]
274    fn comment_entries_belong_to_the_identification_division_alone() {
275        let s = read(concat!(
276            "       IDENTIFICATION DIVISION.\n",
277            "       PROGRAM-ID. P.\n",
278            "       REMARKS. KEPT OUT.\n",
279            "       PROCEDURE DIVISION.\n",
280            "       REMARKS.\n",
281            "           DISPLAY 'IT''S'.\n",
282            "       IDENTIFICATION DIVISION.\n",
283            "       PROGRAM-ID. INNER.\n",
284            "       AUTHOR. O'GRADY.\n",
285        ))
286        .unwrap();
287        assert!(!s.text.contains("KEPT OUT") && !s.text.contains("GRADY"), "{}", s.text);
288        assert!(s.text.contains("DISPLAY 'IT''S'."), "{}", s.text);
289    }
290
291    #[test]
292    fn a_quote_in_column_72_doubled_on_the_continuation_is_one_quote() {
293        let head = "           MOVE \"";
294        let first = format!("{head}{}\"", "A".repeat(TEXT_END - head.len() - 1));
295        let s = read(&format!("{first}\n      -    \"\"B\" TO X.\n")).unwrap();
296        assert!(s.text.contains(&format!("\"{}\"\"B\" TO X.", "A".repeat(TEXT_END - head.len() - 1))), "{}", s.text);
297    }
298
299    #[test]
300    fn a_quote_after_a_closed_literal_starts_another() {
301        let s = read("           88 V VALUE 'ABC'\n      -    'DEF'.\n").unwrap();
302        assert!(s.text.contains("'ABC' 'DEF'."), "{}", s.text);
303        let head = "           88 V VALUE '";
304        let first = format!("{head}{}'", "A".repeat(TEXT_END - head.len() - 1));
305        let s = read(&format!("{first}\n      -    'B'.\n")).unwrap();
306        assert!(s.text.ends_with("A' 'B'."), "{}", s.text);
307    }
308
309    #[test]
310    fn debugging_lines_are_comments_unless_read_as_text() {
311        let text = "           MOVE 1 TO X\n      D    DISPLAY X\n      d    DISPLAY Y\n      D\n";
312        let plain = read(text).unwrap();
313        assert!(!plain.text.contains("DISPLAY") && plain.debugging.is_none());
314        let debugging = read_file_debugging(text, 3).unwrap();
315        assert!(debugging.text.contains("DISPLAY X") && debugging.text.contains("DISPLAY Y"));
316        assert_eq!(debugging.debugging, Some(vec![(3, 2), (3, 3)]));
317    }
318
319    #[test]
320    fn positions_point_at_the_source() {
321        let s = read("       IDENTIFICATION DIVISION.\n").unwrap();
322        let i = s.text.find('D').unwrap();
323        assert_eq!(s.positions[i], Pos { file: 0, line: 1, col: 9 });
324    }
325}