Skip to main content

ironwork_syntax/
copy.rs

1//! COPY and COPY REPLACING, applied to the logical text before it is lexed. Matching is by
2//! text-words, as the standard defines them, and replacement edits the text itself, so a
3//! pseudo-text such as `==:TAG:==` can replace part of a word like `:TAG:-RECORD`.
4
5use crate::bms;
6use crate::source::{self, Source};
7use crate::system;
8use crate::{Error, Pos};
9use std::path::{Path, PathBuf};
10
11/// Directories searched for COPY members, in order. A `COPY X OF LIB` looks in `<dir>/LIB` first.
12/// The file being compiled, when named, is never one of its own members. The compliance level is
13/// how the program and its members are read.
14#[derive(Clone, Debug, Default)]
15pub struct Libraries {
16    dirs: Vec<PathBuf>,
17    program: Option<PathBuf>,
18    compliance: numeric::Compliance,
19}
20
21const COPYBOOKS: &[&str] = &[".cpy", ".CPY", ".copy", ".COPY"];
22const PROGRAM_SOURCES: &[&str] = &[".cbl", ".CBL", ".cob", ".COB"];
23const BARE: &[&str] = &[""];
24const MAX_DEPTH: usize = 32;
25
26impl Libraries {
27    pub fn new(dirs: Vec<PathBuf>) -> Self {
28        Self { dirs, program: None, compliance: numeric::Compliance::Strict }
29    }
30
31    /// These libraries, for compiling the program in `program`.
32    pub fn with_program(&self, program: &Path) -> Self {
33        Self { program: Some(program.to_path_buf()), ..self.clone() }
34    }
35
36    /// These libraries, read under `compliance`.
37    pub fn with_compliance(&self, compliance: numeric::Compliance) -> Self {
38        Self { compliance, ..self.clone() }
39    }
40
41    pub fn compliance(&self) -> numeric::Compliance {
42        self.compliance
43    }
44
45    /// A round of extensions searches every library before the next round starts, so a copybook in
46    /// any library is found before a program source (assumptions C85 to C87).
47    fn find(&self, name: &str, library: Option<&str>, literal: bool) -> Option<PathBuf> {
48        let rounds = if literal { [BARE, COPYBOOKS, PROGRAM_SOURCES] } else { [COPYBOOKS, PROGRAM_SOURCES, BARE] };
49        self.find_in_rounds(name, library, &rounds)
50    }
51
52    pub(crate) fn find_bms(&self, name: &str, library: Option<&str>) -> Option<PathBuf> {
53        self.find_in_rounds(name, library, &[&[".bms", ".BMS"]])
54    }
55
56    fn find_in_rounds(&self, name: &str, library: Option<&str>, rounds: &[&[&str]]) -> Option<PathBuf> {
57        let mut places: Vec<PathBuf> = Vec::new();
58        for d in &self.dirs {
59            if let Some(lib) = library {
60                places.extend([lib.to_owned(), lib.to_ascii_lowercase()].iter().map(|l| d.join(l)));
61            }
62            places.push(d.clone());
63        }
64        let mut names = vec![name.to_owned()];
65        for variant in [name.to_ascii_uppercase(), name.to_ascii_lowercase()] {
66            if !names.contains(&variant) {
67                names.push(variant);
68            }
69        }
70        let (places, names) = (&places, &names);
71        rounds
72            .iter()
73            .flat_map(|extensions| places.iter().flat_map(move |p| extensions.iter().flat_map(move |e| names.iter().map(move |n| p.join(format!("{n}{e}"))))))
74            .find(|p| p.is_file() && !self.program.as_deref().is_some_and(|program| same_file(program, p)))
75    }
76}
77
78/// Whether two paths name one file, however each is spelled.
79fn same_file(a: &Path, b: &Path) -> bool {
80    #[cfg(unix)]
81    {
82        use std::os::unix::fs::MetadataExt;
83        if let (Ok(x), Ok(y)) = (std::fs::metadata(a), std::fs::metadata(b)) {
84            return x.dev() == y.dev() && x.ino() == y.ino();
85        }
86    }
87    matches!((std::fs::canonicalize(a), std::fs::canonicalize(b)), (Ok(x), Ok(y)) if x == y)
88}
89
90/// Reads a source file's bytes: UTF-8 when valid, otherwise one character per byte (Latin-1).
91pub fn decode(bytes: &[u8]) -> String {
92    match std::str::from_utf8(bytes) {
93        Ok(s) => s.to_owned(),
94        Err(_) => bytes.iter().map(|&b| b as char).collect(),
95    }
96}
97
98#[derive(Clone, Debug, PartialEq, Eq)]
99struct Word {
100    start: usize,
101    end: usize,
102    text: String,
103}
104
105fn text_words(chars: &[char]) -> Vec<Word> {
106    let mut words = Vec::new();
107    let mut i = 0;
108    let separator_at = |i: usize| chars.get(i + 1).is_none_or(|c| c.is_whitespace());
109    while i < chars.len() {
110        let c = chars[i];
111        if c.is_whitespace() || ((c == ',' || c == ';') && separator_at(i)) {
112            i += 1;
113            continue;
114        }
115        let start = i;
116        if c == '\'' || c == '"' {
117            i += 1;
118            while i < chars.len() {
119                if chars[i] == c && chars.get(i + 1) == Some(&c) {
120                    i += 2;
121                } else if chars[i] == c {
122                    i += 1;
123                    break;
124                } else {
125                    i += 1;
126                }
127            }
128        } else if c == '=' && chars.get(i + 1) == Some(&'=') {
129            i += 2;
130        } else if matches!(c, '(' | ')' | ':') || (c == '.' && separator_at(i)) {
131            i += 1;
132        } else {
133            while i < chars.len() {
134                let d = chars[i];
135                let ends = d.is_whitespace()
136                    || matches!(d, '(' | ')' | ':' | '\'' | '"')
137                    || ((d == '.' || d == ',' || d == ';') && separator_at(i))
138                    || (d == '=' && chars.get(i + 1) == Some(&'='));
139                if ends {
140                    break;
141                }
142                i += 1;
143            }
144        }
145        words.push(Word { start, end: i, text: chars[start..i].iter().collect() });
146    }
147    words
148}
149
150fn same(a: &str, b: &str) -> bool {
151    if a.starts_with(['\'', '"']) { a == b } else { a.eq_ignore_ascii_case(b) }
152}
153
154#[derive(Clone, Debug)]
155enum Mode {
156    Whole,
157    Leading,
158    Trailing,
159}
160
161#[derive(Clone, Debug)]
162struct Replacing {
163    mode: Mode,
164    pattern: Vec<String>,
165    replacement: String,
166}
167
168struct Statement {
169    name: String,
170    /// Whether the name is a literal, which IBM takes as a file name as written.
171    literal: bool,
172    library: Option<String>,
173    replacing: Vec<Replacing>,
174    /// Index of the word after the terminating period.
175    next: usize,
176}
177
178fn copy_statement(words: &[Word], at: usize, pos: Pos) -> Result<Statement, Error> {
179    let err = |m: &str| Error::at(pos, format!("COPY: {m}"));
180    let text = |i: usize| words.get(i).map(|w| w.text.as_str());
181    let mut i = at + 1;
182    let quoted = |s: &str| s.starts_with(['\'', '"']);
183    let unquote = |s: &str| s.trim_matches(|c| c == '\'' || c == '"').to_owned();
184    // In `COPY X..` the separator period is the second, so the name is `X.` (assumption C88).
185    let word = |s: &str| {
186        if s.ends_with('.') && !quoted(s) {
187            return Err(Error::at(pos, format!("COPY {s}: the name ends in a period; the period that ends a COPY statement is the one followed by a space")));
188        }
189        Ok(unquote(s))
190    };
191    let first = text(i).ok_or_else(|| err("a member name"))?;
192    let (name, literal) = (word(first)?, quoted(first));
193    i += 1;
194    let mut library = None;
195    if text(i).is_some_and(|w| w.eq_ignore_ascii_case("OF") || w.eq_ignore_ascii_case("IN")) {
196        library = Some(word(text(i + 1).ok_or_else(|| err("a library name"))?)?);
197        i += 2;
198    }
199    if text(i).is_some_and(|w| w.eq_ignore_ascii_case("SUPPRESS")) {
200        i += 1;
201    }
202    let mut replacing = Vec::new();
203    if text(i).is_some_and(|w| w.eq_ignore_ascii_case("REPLACING")) {
204        (replacing, i) = operands(words, i + 1, "COPY", pos)?;
205    }
206    if text(i) != Some(".") {
207        return Err(err("a period to end the statement"));
208    }
209    Ok(Statement { name, literal, library, replacing, next: i + 1 })
210}
211
212/// The operand pairs of COPY REPLACING or of REPLACE, from word `at` to the period that ends the
213/// statement, and that period's index. REPLACE takes pseudo-text alone (Language Reference
214/// SC27-8713-03, p. 708).
215fn operands(words: &[Word], at: usize, verb: &str, pos: Pos) -> Result<(Vec<Replacing>, usize), Error> {
216    let err = |m: &str| Error::at(pos, format!("{verb}: {m}"));
217    let text = |i: usize| words.get(i).map(|w| w.text.as_str());
218    let replace = verb == "REPLACE";
219    let pseudo_text = |i: usize| !replace || text(i) == Some("==");
220    let (first, second) = if replace { ("pseudo-text between == delimiters to replace", "pseudo-text between == delimiters after BY") } else { ("an operand to replace", "an operand after BY") };
221    let (mut replacing, mut i) = (Vec::new(), at);
222    while text(i).is_some_and(|w| w != ".") {
223        let mode = match text(i) {
224            Some(w) if w.eq_ignore_ascii_case("LEADING") => Mode::Leading,
225            Some(w) if w.eq_ignore_ascii_case("TRAILING") => Mode::Trailing,
226            _ => Mode::Whole,
227        };
228        if !matches!(mode, Mode::Whole) {
229            i += 1;
230        }
231        let (pattern, after) = operand(words, i).filter(|_| pseudo_text(i)).ok_or_else(|| err(first))?;
232        if !text(after).is_some_and(|w| w.eq_ignore_ascii_case("BY")) {
233            return Err(err("BY"));
234        }
235        let (replacement, after) = operand(words, after + 1).filter(|_| pseudo_text(after + 1)).ok_or_else(|| err(second))?;
236        if pattern.is_empty() || (!matches!(mode, Mode::Whole) && pattern.len() != 1) {
237            return Err(err("LEADING and TRAILING take one word; an empty pattern matches nothing"));
238        }
239        replacing.push(Replacing { mode, pattern, replacement: replacement.join(" ") });
240        i = after;
241    }
242    Ok((replacing, i))
243}
244
245/// A REPLACING operand: pseudo-text `==...==` as its text-words, or one text-word.
246fn operand(words: &[Word], at: usize) -> Option<(Vec<String>, usize)> {
247    let first = words.get(at)?;
248    if first.text != "==" {
249        return Some((vec![first.text.clone()], at + 1));
250    }
251    let close = words[at + 1..].iter().position(|w| w.text == "==")? + at + 1;
252    Some((words[at + 1..close].iter().map(|w| w.text.clone()).collect(), close + 1))
253}
254
255/// Appends `chars[range]` to `out` with the positions they came from.
256fn copy_span(out: &mut Source, chars: &[char], positions: &[Pos], range: std::ops::Range<usize>) {
257    out.text.extend(&chars[range.clone()]);
258    out.positions.extend_from_slice(&positions[range]);
259}
260
261fn apply(src: &Source, replacing: &[Replacing]) -> Source {
262    if replacing.is_empty() {
263        return Source { text: src.text.clone(), positions: src.positions.clone(), options: Vec::new(), debugging: None, free: Vec::new() };
264    }
265    let chars: Vec<char> = src.text.chars().collect();
266    let words = text_words(&chars);
267    let mut out = Source { text: String::new(), positions: Vec::new(), options: Vec::new(), debugging: None, free: Vec::new() };
268    let emit = |out: &mut Source, text: &str, pos: Pos| {
269        for c in text.chars() {
270            out.text.push(c);
271            out.positions.push(pos);
272        }
273    };
274    let (mut cursor, mut i) = (0usize, 0usize);
275    while i < words.len() {
276        copy_span(&mut out, &chars, &src.positions, cursor..words[i].start);
277        let pos = src.positions[words[i].start];
278        let hit = replacing.iter().find_map(|r| match r.mode {
279            Mode::Whole => (words.len() - i >= r.pattern.len() && r.pattern.iter().zip(&words[i..]).all(|(p, w)| same(p, &w.text)))
280                .then(|| (r.replacement.clone(), r.pattern.len())),
281            Mode::Leading => {
282                let w = &words[i].text;
283                (w.len() > r.pattern[0].len() || w.eq_ignore_ascii_case(&r.pattern[0]))
284                    .then_some(())
285                    .filter(|_| w.to_ascii_uppercase().starts_with(&r.pattern[0].to_ascii_uppercase()))
286                    .map(|_| (format!("{}{}", r.replacement, &w[r.pattern[0].len()..]), 1))
287            }
288            Mode::Trailing => {
289                let w = &words[i].text;
290                w.to_ascii_uppercase()
291                    .ends_with(&r.pattern[0].to_ascii_uppercase())
292                    .then(|| (format!("{}{}", &w[..w.len() - r.pattern[0].len()], r.replacement), 1))
293            }
294        });
295        match hit {
296            Some((text, consumed)) => {
297                emit(&mut out, &text, pos);
298                cursor = words[i + consumed - 1].end;
299                i += consumed;
300            }
301            None => {
302                copy_span(&mut out, &chars, &src.positions, words[i].start..words[i].end);
303                cursor = words[i].end;
304                i += 1;
305            }
306        }
307    }
308    copy_span(&mut out, &chars, &src.positions, cursor..chars.len());
309    out
310}
311
312/// Replaces every COPY statement in `source` with its member's text, recursively. `files` names
313/// each source file; a position's `file` indexes it.
314pub fn expand(source: Source, libraries: &Libraries, files: &mut Vec<String>) -> Result<Source, Error> {
315    let mut stack = Vec::new();
316    expand_nested(source, libraries, files, &mut stack)
317}
318
319/// `EXEC SQL INCLUDE name END-EXEC`, which the Db2 precompiler treats as a COPY of its member (and
320/// of its own SQLCA or SQLDA): the member's name, whether it is quoted, and the word after END-EXEC
321/// and any period that ends it.
322fn sql_include(words: &[Word], at: usize) -> Option<(String, bool, usize)> {
323    let is = |k: usize, w: &str| words.get(at + k).is_some_and(|x| x.text.eq_ignore_ascii_case(w));
324    if !(is(0, "EXEC") && is(1, "SQL") && is(2, "INCLUDE") && is(4, "END-EXEC")) {
325        return None;
326    }
327    let word = &words[at + 3].text;
328    let name = word.trim_matches(|c| c == '\'' || c == '"').to_owned();
329    Some((name, word.starts_with(['\'', '"']), at + 5 + usize::from(is(5, "."))))
330}
331
332fn expand_nested(source: Source, libraries: &Libraries, files: &mut Vec<String>, stack: &mut Vec<String>) -> Result<Source, Error> {
333    let chars: Vec<char> = source.text.chars().collect();
334    let words = text_words(&chars);
335    if !words.iter().any(|w| w.text.eq_ignore_ascii_case("COPY") || w.text.eq_ignore_ascii_case("INCLUDE")) {
336        return Ok(source);
337    }
338    let mut out = Source { text: String::new(), positions: Vec::new(), options: source.options.clone(), debugging: source.debugging.clone(), free: source.free.clone() };
339    let read = |text: &str, file: u16| source::read_under(text, file, source.debugging.is_some(), libraries.compliance());
340    let (mut cursor, mut i) = (0usize, 0usize);
341    while i < words.len() {
342        let pos = source.positions[words[i].start];
343        let (name, literal, library, replacing, next, sql) = if words[i].text.eq_ignore_ascii_case("COPY") {
344            let st = copy_statement(&words, i, pos)?;
345            (st.name, st.literal, st.library, st.replacing, st.next, false)
346        } else if let Some((name, literal, next)) = sql_include(&words, i) {
347            (name, literal, None, Vec::new(), next, true)
348        } else {
349            i += 1;
350            continue;
351        };
352        copy_span(&mut out, &chars, &source.positions, cursor..words[i].start);
353        let own = sql && matches!(name.to_ascii_uppercase().as_str(), "SQLCA" | "SQLDA");
354        let path = if own { None } else { libraries.find(&name, library.as_deref(), literal) };
355        let verb = if sql { "EXEC SQL INCLUDE" } else { "COPY" };
356        let mapset = if own || path.is_some() { None } else { bms::load(libraries, &name, library.as_deref()) };
357        let (key, member) = match (path, mapset) {
358            (Some(path), _) => {
359                let copied_free = source.free_at(pos).is_some();
360                let copied = |text: &str, file: u16| source::read_copied(text, file, source.debugging.is_some(), libraries.compliance(), copied_free);
361                (path.display().to_string(), read_member(&path, pos, files, &copied)?)
362            }
363            (None, Some((path, mapset))) => {
364                let mapset = mapset.map_err(|e| Error::at(pos, format!("{verb} {name}: {}", e.place(&path.display().to_string()))))?;
365                let file = u16::try_from(files.len()).map_err(|_| Error::at(pos, "more than 65535 copy members"))?;
366                files.push(path.display().to_string());
367                (path.display().to_string(), read(&bms::symbolic_map(&mapset), file)?)
368            }
369            (None, None) => {
370                let text = system::member(&name).ok_or_else(|| Error::at(pos, format!("{verb} {name}: no such member in the copy libraries")))?;
371                let key = format!("(system member {})", name.to_ascii_uppercase());
372                let file = u16::try_from(files.len()).map_err(|_| Error::at(pos, "more than 65535 copy members"))?;
373                files.push(key.clone());
374                (key, read(&text, file)?)
375            }
376        };
377        if stack.contains(&key) || stack.len() >= MAX_DEPTH {
378            return Err(Error::at(pos, format!("{verb} {name}: copies itself, or nests deeper than {MAX_DEPTH}")));
379        }
380        stack.push(key);
381        let mut member = expand_nested(member, libraries, files, stack)?;
382        stack.pop();
383        if let (Some(lines), Some(copied)) = (&mut out.debugging, member.debugging.take()) {
384            // A COPY on a debugging line makes all of its member's text debugging lines.
385            if lines.contains(&(pos.file, pos.line)) {
386                lines.extend(member.positions.iter().map(|p| (p.file, p.line)));
387            }
388            lines.extend(copied);
389        }
390        out.free.extend(member.free.iter().cloned());
391        let replaced = apply(&member, &replacing);
392        out.text.push_str(&replaced.text);
393        out.positions.extend(replaced.positions);
394        out.text.push('\n');
395        out.positions.push(pos);
396        cursor = words.get(next - 1).map_or(chars.len(), |w| w.end);
397        i = next;
398    }
399    copy_span(&mut out, &chars, &source.positions, cursor..chars.len());
400    Ok(out)
401}
402
403/// Applies the REPLACE statements in `source`, which COPY has expanded (Language Reference
404/// SC27-8713-03, pp. 708-712): each one's operands act on the text from its period to the next
405/// REPLACE statement or the end of the source, with COPY REPLACING's matching, and the statements
406/// themselves are left out (assumption C160).
407pub fn replace(source: Source) -> Result<Source, Error> {
408    let chars: Vec<char> = source.text.chars().collect();
409    let words = text_words(&chars);
410    let starts = |i: usize| words[i].text.eq_ignore_ascii_case("REPLACE");
411    if !(0..words.len()).any(starts) {
412        return Ok(source);
413    }
414    let mut out = Source { text: String::new(), positions: Vec::new(), options: source.options.clone(), debugging: source.debugging.clone(), free: source.free.clone() };
415    let segment = |out: &mut Source, range: std::ops::Range<usize>, active: &[Replacing]| {
416        let text = Source { text: chars[range.clone()].iter().collect(), positions: source.positions[range].to_vec(), options: Vec::new(), debugging: None, free: Vec::new() };
417        let replaced = apply(&text, active);
418        out.text.push_str(&replaced.text);
419        out.positions.extend(replaced.positions);
420    };
421    let (mut active, mut cursor, mut i) = (Vec::new(), 0usize, 0usize);
422    while i < words.len() {
423        if !starts(i) {
424            i += 1;
425            continue;
426        }
427        let pos = source.positions[words[i].start];
428        let next = match words.get(i + 1).map(|w| w.text.to_ascii_uppercase()).as_deref() {
429            Some("OFF") if words.get(i + 2).is_some_and(|w| w.text == ".") => (Vec::new(), i + 3),
430            Some("OFF") => return Err(Error::at(pos, "REPLACE OFF: a period to end the statement")),
431            Some("ALSO" | "LAST") => return Err(Error::at(pos, "REPLACE ALSO and REPLACE LAST OFF are the 2014 COBOL standard's; Enterprise COBOL has REPLACE pseudo-text BY pseudo-text and REPLACE OFF")),
432            Some("==" | "LEADING" | "TRAILING") => {
433                let (replacing, period) = operands(&words, i + 1, "REPLACE", pos)?;
434                if words.get(period).is_none_or(|w| w.text != ".") {
435                    return Err(Error::at(pos, "REPLACE: a period to end the statement"));
436                }
437                (replacing, period + 1)
438            }
439            _ => {
440                i += 1;
441                continue;
442            }
443        };
444        segment(&mut out, cursor..words[i].start, &active);
445        (active, i) = next;
446        cursor = words[i - 1].end;
447    }
448    segment(&mut out, cursor..chars.len(), &active);
449    Ok(out)
450}
451
452fn read_member(path: &Path, pos: Pos, files: &mut Vec<String>, read: &dyn Fn(&str, u16) -> Result<Source, Error>) -> Result<Source, Error> {
453    let bytes = std::fs::read(path).map_err(|e| Error::at(pos, format!("COPY {}: {e}", path.display())))?;
454    let file = u16::try_from(files.len()).map_err(|_| Error::at(pos, "more than 65535 copy members"))?;
455    files.push(path.display().to_string());
456    read(&decode(&bytes), file)
457}
458
459#[cfg(test)]
460mod tests {
461    use super::*;
462
463    fn words(s: &str) -> Vec<String> {
464        text_words(&s.chars().collect::<Vec<_>>()).into_iter().map(|w| w.text).collect()
465    }
466
467    #[test]
468    fn text_words_follow_the_separators() {
469        assert_eq!(words("01 :TAG:-REC PIC X(3)."), ["01", ":", "TAG", ":", "-REC", "PIC", "X", "(", "3", ")", "."]);
470        assert_eq!(words("MOVE 'A B' TO X, Y."), ["MOVE", "'A B'", "TO", "X", "Y", "."]);
471        assert_eq!(words("==A== BY ==B==."), ["==", "A", "==", "BY", "==", "B", "==", "."]);
472        assert_eq!(words("GENAUW.CLAIM 0.1"), ["GENAUW.CLAIM", "0.1"]);
473    }
474
475    fn dir_with(files: &[(&str, &str)]) -> PathBuf {
476        let dir = std::env::temp_dir().join(format!("ironwork-copy-{}-{}", std::process::id(), files[0].0));
477        std::fs::create_dir_all(&dir).unwrap();
478        for (name, text) in files {
479            std::fs::write(dir.join(name), text).unwrap();
480        }
481        dir
482    }
483
484    fn expanded(main: &str, dir: &Path) -> Result<String, Error> {
485        let src = source::read(main)?;
486        let mut files = vec![String::new()];
487        expand(src, &Libraries::new(vec![dir.to_path_buf()]), &mut files).map(|s| s.text)
488    }
489
490    #[test]
491    fn copy_replacing_whole_words_and_tags_inside_words() {
492        let dir = dir_with(&[("RECS.cpy", "       01  :TAG:-REC.\n           05 :TAG:-ID PIC 9(4) VALUE OLD.\n")]);
493        let text = expanded("           COPY RECS REPLACING ==:TAG:== BY ==CUST== OLD BY 42.\n", &dir).unwrap();
494        assert!(text.contains("01  CUST-REC."), "{text}");
495        assert!(text.contains("05 CUST-ID PIC 9(4) VALUE 42."), "{text}");
496        assert!(!text.contains("COPY"));
497    }
498
499    #[test]
500    fn leading_and_trailing_replace_part_of_a_word() {
501        let dir = dir_with(&[("PART.cpy", "       01  WS-A PIC X.\n       01  B-WS PIC X.\n")]);
502        let text = expanded("           COPY PART REPLACING LEADING ==WS== BY ==LK==\n               TRAILING ==WS== BY ==XX==.\n", &dir).unwrap();
503        assert!(text.contains("LK-A") && text.contains("B-XX"), "{text}");
504    }
505
506    #[test]
507    fn nested_copies_and_a_missing_member() {
508        let dir = dir_with(&[("OUTER.cpy", "       COPY INNER.\n"), ("inner.cpy", "       01  X PIC X.\n")]);
509        assert!(expanded("       COPY OUTER.\n", &dir).unwrap().contains("01  X PIC X."));
510        let err = expanded("       COPY NOPE.\n", &dir).unwrap_err();
511        assert!(err.message.contains("NOPE"));
512    }
513
514    #[test]
515    fn system_members_answer_when_no_library_does() {
516        let dir = dir_with(&[("OTHER.cpy", "       01  O PIC X.\n")]);
517        let text = expanded("       COPY DFHAID.\n           EXEC SQL INCLUDE SQLCA END-EXEC.\n", &dir).unwrap();
518        assert!(text.contains("DFHENTER") && text.contains("SQLCODE"), "{text}");
519        assert!(!text.contains("END-EXEC"));
520        let dir = dir_with(&[("DFHAID.cpy", "       01  VENDORED PIC X.\n")]);
521        assert!(expanded("       COPY DFHAID.\n", &dir).unwrap().contains("VENDORED"));
522    }
523
524    #[test]
525    fn a_member_that_copies_itself_is_refused() {
526        let dir = dir_with(&[("LOOP.cpy", "       COPY LOOP.\n")]);
527        assert!(expanded("       COPY LOOP.\n", &dir).unwrap_err().message.contains("copies itself"));
528    }
529
530    /// A fresh directory holding `files`, each at its path under it.
531    fn tree(tag: &str, files: &[(&str, &str)]) -> PathBuf {
532        let root = std::env::temp_dir().join(format!("ironwork-copy-{}-{tag}", std::process::id()));
533        let _ = std::fs::remove_dir_all(&root);
534        for (name, text) in files {
535            let path = root.join(name);
536            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
537            std::fs::write(path, text).unwrap();
538        }
539        root
540    }
541
542    fn expanded_with(main: &str, libraries: &Libraries) -> Result<String, Error> {
543        let mut files = vec![String::new()];
544        expand(source::read(main)?, libraries, &mut files).map(|s| s.text)
545    }
546
547    #[test]
548    fn a_copybook_in_any_library_is_found_before_a_program_source() {
549        let root = tree(
550            "rounds",
551            &[
552                ("src/INQACC.cbl", "       01  PROGRAM-SOURCE PIC X.\n"),
553                ("src/ONLY.cbl", "       01  ONLY-SOURCE PIC X.\n"),
554                ("src/BARE", "       01  BARE-FILE PIC X.\n"),
555                ("cpy/INQACC.cpy", "       01  COPYBOOK PIC X.\n"),
556                ("cpy/BARE.copy", "       01  COPY-FILE PIC X.\n"),
557            ],
558        );
559        let libraries = Libraries::new(vec![root.join("src"), root.join("cpy")]);
560        assert!(expanded_with("       COPY INQACC.\n", &libraries).unwrap().contains("COPYBOOK"));
561        assert!(expanded_with("       COPY inqacc.\n", &libraries).unwrap().contains("COPYBOOK"));
562        assert!(expanded_with("       COPY BARE.\n", &libraries).unwrap().contains("COPY-FILE"));
563        assert!(expanded_with("       COPY ONLY.\n", &libraries).unwrap().contains("ONLY-SOURCE"));
564    }
565
566    #[test]
567    fn a_name_alone_is_tried_after_its_extensions_and_a_literal_first() {
568        let root = tree("bare", &[("lib/MEMBER", "       01  BARE-FILE PIC X.\n"), ("lib/MEMBER.cpy", "       01  COPYBOOK PIC X.\n"), ("lib/ALONE", "       01  ALONE PIC X.\n")]);
569        let libraries = Libraries::new(vec![root.join("lib")]);
570        assert!(expanded_with("       COPY MEMBER.\n", &libraries).unwrap().contains("COPYBOOK"));
571        assert!(expanded_with("       COPY \"MEMBER\".\n", &libraries).unwrap().contains("BARE-FILE"));
572        assert!(expanded_with("       COPY ALONE.\n", &libraries).unwrap().contains("01  ALONE"));
573    }
574
575    #[test]
576    fn the_program_being_compiled_is_never_its_own_member() {
577        let program = "       IDENTIFICATION DIVISION.\n       PROGRAM-ID. PGMC.\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       COPY PGMC.\n";
578        let root = tree("self", &[("src/PGMC.cbl", program), ("src/OUTER.cpy", "       COPY PGMC.\n"), ("lib/PGMC.cbl", "       01  PGMC-X PIC X.\n")]);
579        let main = root.join("src/../src/PGMC.cbl");
580        let libraries = Libraries::new(vec![root.join("src"), root.join("lib")]).with_program(&main);
581        assert!(expanded_with(program, &libraries).unwrap().contains("PGMC-X"));
582        assert!(expanded_with("       COPY OUTER.\n", &libraries).unwrap().contains("PGMC-X"));
583        let alone = Libraries::new(vec![root.join("src")]).with_program(&main);
584        assert!(expanded_with(program, &alone).unwrap_err().message.contains("no such member"));
585        assert!(expanded_with(program, &Libraries::new(vec![root.join("src")])).unwrap_err().message.contains("copies itself"));
586    }
587
588    #[test]
589    fn a_doubled_period_is_refused_by_name() {
590        let root = tree("period", &[("lib/COBCPARMS.cpy", "       01  PARMS PIC X.\n")]);
591        let libraries = Libraries::new(vec![root.join("lib")]);
592        let err = expanded_with("       COPY COBCPARMS..\n", &libraries).unwrap_err();
593        assert!(err.message.contains("COPY COBCPARMS.: the name ends in a period"), "{}", err.message);
594        let err = expanded_with("       COPY COBCPARMS OF LIB..\n", &libraries).unwrap_err();
595        assert!(err.message.contains("COPY LIB.: "), "{}", err.message);
596        assert!(expanded_with("       COPY COBCPARMS.\n", &libraries).unwrap().contains("PARMS"));
597    }
598
599    fn replaced(text: &str) -> Result<String, Error> {
600        replace(source::read(text)?).map(|s| s.text)
601    }
602
603    #[test]
604    fn replace_acts_from_its_period_to_the_next_replace() {
605        let text = replaced(concat!(
606            "       01  A PICTURE X.\n",
607            "       REPLACE ==PICTURE== BY ==PIC==.\n",
608            "       01  B PICTURE X.\n",
609            "       01  C PICTURE X VALUE 'PICTURE'.\n",
610            "       REPLACE OFF.\n",
611            "       01  D PICTURE X.\n",
612        ))
613        .unwrap();
614        let words: Vec<&str> = text.split_whitespace().collect();
615        assert_eq!(words, ["01", "A", "PICTURE", "X.", "01", "B", "PIC", "X.", "01", "C", "PIC", "X", "VALUE", "'PICTURE'.", "01", "D", "PICTURE", "X."]);
616    }
617
618    #[test]
619    fn replace_takes_the_language_references_example() {
620        let text = replaced(concat!(
621            "           REPLACE ==\"(Hello, World!)\"== BY ==\"(Hello, Mom!)\"==.\n",
622            "       01 WS-STRING1 PIC X(30) VALUE \"(Hello, World!)\".\n",
623            "           DISPLAY \"Modified: \" XX-WS-:TAG:1\n",
624            "           REPLACE LEADING ==XX-==  BY ====\n",
625            "                           ==:TAG:==  BY ==STRING==\n",
626            "                   TRAILING ==1== BY ==2==.\n",
627            "           DISPLAY \"Modified: \" XX-WS-:TAG:1\n",
628        ))
629        .unwrap();
630        assert!(text.contains("VALUE \"(Hello, Mom!)\"."), "{text}");
631        assert!(text.contains("DISPLAY \"Modified: \" XX-WS-:TAG:1\n") && text.ends_with("DISPLAY \"Modified: \" WS-STRING2"), "{text}");
632        assert!(!text.contains("REPLACE"), "{text}");
633    }
634
635    #[test]
636    fn a_later_replace_supersedes_and_several_words_match_as_one() {
637        let text = replaced(concat!(
638            "           REPLACE ==AO== BY ==TO== == = == BY ==EQUAL==.\n",
639            "           MOVE \"*\" AO X.\n",
640            "           REPLACE ==MOVE \"*\" TO X.\n",
641            "                      IF X = \"*\"== BY ==DISPLAY X==.\n",
642            "           MOVE \"*\" TO X.\n",
643            "           IF X = \"*\" DISPLAY Y.\n",
644        ))
645        .unwrap();
646        assert!(text.contains("MOVE \"*\" TO X."), "{text}");
647        assert!(text.contains("DISPLAY X DISPLAY Y."), "{text}");
648    }
649
650    #[test]
651    fn replace_takes_only_pseudo_text() {
652        let text = replaced("           MOVE REPLACE TO X.\n           DISPLAY Y.\n").unwrap();
653        assert!(text.contains("MOVE REPLACE TO X."));
654        assert!(replaced("       REPLACE A BY B.\n").unwrap().contains("REPLACE A BY B."));
655        let err = replaced("       REPLACE ==A== BY B.\n").unwrap_err();
656        assert_eq!(err.message, "REPLACE: pseudo-text between == delimiters after BY");
657        let err = replaced("       REPLACE ALSO ==A== BY ==B==.\n").unwrap_err();
658        assert!(err.message.starts_with("REPLACE ALSO and REPLACE LAST OFF are the 2014"), "{}", err.message);
659        assert_eq!(replaced("       REPLACE ==A== BY ==B==\n").unwrap_err().message, "REPLACE: a period to end the statement");
660    }
661
662    #[test]
663    fn replace_acts_on_copied_text() {
664        let dir = dir_with(&[("REPMEM.cpy", "       01  :TAG:-ID PIC 9.\n")]);
665        let src = source::read("       REPLACE ==:TAG:== BY ==CUST==.\n       COPY REPMEM.\n").unwrap();
666        let mut files = vec![String::new()];
667        let text = expand(src, &Libraries::new(vec![dir]), &mut files).and_then(replace).unwrap().text;
668        assert!(text.contains("01  CUST-ID PIC 9."), "{text}");
669    }
670
671    #[test]
672    fn positions_in_a_member_name_its_file() {
673        let dir = dir_with(&[("POS.cpy", "       01  Y PIC X.\n")]);
674        let src = source::read("       COPY POS.\n").unwrap();
675        let mut files = vec![String::new()];
676        let out = expand(src, &Libraries::new(vec![dir]), &mut files).unwrap();
677        let at = out.text.find('Y').unwrap();
678        assert_eq!(out.positions[at].file, 1);
679        assert!(files[1].ends_with("POS.cpy"));
680    }
681}