Skip to main content

ironwork_syntax/
lib.rs

1//! ironwork for COBOL: from fixed-format source text to a syntax tree. Nothing here knows about
2//! storage or execution.
3
4pub mod ast;
5pub mod bms;
6pub mod copy;
7pub mod csd;
8mod debugging;
9pub mod feedback;
10pub mod jni;
11pub mod lexer;
12pub mod parser;
13pub mod report;
14pub mod source;
15pub mod sql;
16pub mod system;
17
18use std::fmt;
19
20pub use rt::vocab::Pos;
21
22/// The severity of a compiler message, IBM's five levels in order (Programming Guide SC27-8714-03,
23/// Table 38, p. 282).
24#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
25pub enum Severity {
26    /// I: the program runs correctly.
27    Informational,
28    /// W: a possible error; the program probably runs correctly.
29    Warning,
30    /// E: an error IBM's compiler corrects, though the program may not run as expected.
31    Error,
32    /// S: an error the compiler cannot correct; the program should not be run.
33    Severe,
34    /// U: the compilation ended.
35    Unrecoverable,
36}
37
38impl Severity {
39    /// The return code a compilation ends with when this is its most severe message.
40    pub const fn return_code(self) -> u8 {
41        match self {
42            Self::Informational => 0,
43            Self::Warning => 4,
44            Self::Error => 8,
45            Self::Severe => 12,
46            Self::Unrecoverable => 16,
47        }
48    }
49
50    /// The word a message's line carries after its position; an error's carries none.
51    pub const fn label(self) -> Option<&'static str> {
52        match self {
53            Self::Informational => Some("informational"),
54            Self::Warning => Some("warning"),
55            Self::Error | Self::Severe | Self::Unrecoverable => None,
56        }
57    }
58}
59
60/// A compiler message; [`Error::at`] makes a severe one.
61#[derive(Clone, Debug, PartialEq, Eq)]
62pub struct Error {
63    pub pos: Pos,
64    pub message: String,
65    /// The COPY member the position is in, when it is not the program itself.
66    pub file: Option<String>,
67    pub severity: Severity,
68}
69
70impl Error {
71    pub fn at(pos: Pos, message: impl Into<String>) -> Self {
72        Self { pos, message: message.into(), file: None, severity: Severity::Severe }
73    }
74
75    pub fn warning(pos: Pos, message: impl Into<String>) -> Self {
76        Self::at(pos, message).graded(Severity::Warning)
77    }
78
79    pub fn graded(mut self, severity: Severity) -> Self {
80        self.severity = severity;
81        self
82    }
83
84    /// Names the member a position in a COPY member came from.
85    pub fn in_files(mut self, files: &[String]) -> Self {
86        self.file = files.get(self.pos.file as usize).filter(|f| !f.is_empty()).cloned();
87        self
88    }
89
90    /// `file:line:col: message`, with `main` naming the program itself; a warning or informational
91    /// message puts its label before the message: `file:line:col: warning: message`.
92    pub fn place(&self, main: &str) -> String {
93        match (&self.file, self.pos.line) {
94            (Some(f), _) => format!("{f}:{self}"),
95            (None, 0) => format!("{main}: {}", self.labelled()),
96            (None, _) => format!("{main}:{self}"),
97        }
98    }
99
100    /// The message, after its severity's label when it has one.
101    pub fn labelled(&self) -> String {
102        match self.severity.label() {
103            Some(label) => format!("{label}: {}", self.message),
104            None => self.message.clone(),
105        }
106    }
107}
108
109impl fmt::Display for Error {
110    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111        write!(f, "{}: {}", self.pos, self.labelled())
112    }
113}
114
115/// The return code of a compilation that gave these messages: the highest of theirs, 0 for none.
116pub fn return_code(messages: &[Error]) -> u8 {
117    messages.iter().map(|m| m.severity.return_code()).max().unwrap_or(0)
118}
119
120/// The message a refusal names: the first of the most severe.
121pub fn most_severe(messages: &[Error]) -> Option<&Error> {
122    messages.iter().rev().max_by_key(|m| m.severity)
123}
124
125impl std::error::Error for Error {}
126
127/// The first program in the source.
128pub fn parse(text: &str) -> Result<ast::Program, Error> {
129    parse_with(text, &copy::Libraries::default())
130}
131
132/// The first program in the source, with COPY members resolved from `libraries`.
133pub fn parse_with(text: &str, libraries: &copy::Libraries) -> Result<ast::Program, Error> {
134    Ok(parse_all_with(text, libraries)?.remove(0))
135}
136
137/// Every program in the source, in order, nested programs after the one that contains them.
138pub fn parse_all_with(text: &str, libraries: &copy::Libraries) -> Result<Vec<ast::Program>, Error> {
139    let mut files = vec![String::new()];
140    let mut source = source::read(text).and_then(|s| copy::expand(s, libraries, &mut files)).map_err(|e| e.in_files(&files))?;
141    let mut tokens = lexer::lex(&source).map_err(|e| e.in_files(&files))?;
142    if debugging::requested(&tokens) {
143        files.truncate(1);
144        source = source::read_file_debugging(text, 0).and_then(|s| copy::expand(s, libraries, &mut files)).map_err(|e| e.in_files(&files))?;
145        let lexed = lexer::lex(&source).map_err(|e| e.in_files(&files))?;
146        tokens = debugging::keep(lexed, source.debugging.as_deref().unwrap_or_default());
147    }
148    let mut programs = parser::parse(&tokens, source.options).map_err(|e| e.in_files(&files))?;
149    for p in &mut programs {
150        p.sources = files.clone();
151    }
152    Ok(programs)
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158
159    const ALL: [Severity; 5] = [Severity::Informational, Severity::Warning, Severity::Error, Severity::Severe, Severity::Unrecoverable];
160
161    fn message(severity: Severity, line: u32) -> Error {
162        Error::at(Pos { file: 0, line, col: 8 }, format!("m{line}")).graded(severity)
163    }
164
165    #[test]
166    fn severities_rise_with_ibms_return_codes() {
167        assert_eq!(ALL.map(Severity::return_code), [0, 4, 8, 12, 16]);
168        assert!(ALL.windows(2).all(|w| w[0] < w[1]));
169        assert_eq!(Error::at(Pos::default(), "m").severity, Severity::Severe);
170        assert_eq!(Error::warning(Pos::default(), "m").severity, Severity::Warning);
171    }
172
173    #[test]
174    fn a_compilation_returns_the_highest_code_of_its_messages() {
175        let codes = |severities: &[Severity]| return_code(&severities.iter().enumerate().map(|(i, &s)| message(s, i as u32 + 1)).collect::<Vec<_>>());
176        use Severity::*;
177        assert_eq!(codes(&[]), 0);
178        assert_eq!(codes(&[Informational, Informational]), 0);
179        assert_eq!(codes(&[Informational, Warning]), 4);
180        assert_eq!(codes(&[Warning, Error, Informational]), 8);
181        assert_eq!(codes(&[Error, Severe, Warning]), 12);
182        assert_eq!(codes(&[Informational, Warning, Error, Severe]), 12);
183        assert_eq!(codes(&[Severe, Unrecoverable]), 16);
184    }
185
186    #[test]
187    fn the_message_a_refusal_names_is_the_first_of_the_most_severe() {
188        let messages = [message(Severity::Warning, 1), message(Severity::Severe, 2), message(Severity::Error, 3), message(Severity::Severe, 4)];
189        assert_eq!(most_severe(&messages).map(|m| m.pos.line), Some(2));
190        assert!(most_severe(&[]).is_none());
191    }
192
193    #[test]
194    fn an_error_line_carries_no_label_and_a_warning_or_informational_one_says_which_it_is() {
195        let lines: Vec<String> = ALL.map(|s| message(s, 7).place("p.cbl")).to_vec();
196        assert_eq!(lines, ["p.cbl:7:8: informational: m7", "p.cbl:7:8: warning: m7", "p.cbl:7:8: m7", "p.cbl:7:8: m7", "p.cbl:7:8: m7"]);
197        let unplaced = |s: Severity| Error::at(Pos::default(), "m").graded(s).place("p.cbl");
198        assert_eq!((unplaced(Severity::Severe), unplaced(Severity::Warning)), ("p.cbl: m".to_string(), "p.cbl: warning: m".to_string()));
199        let in_member = Error::warning(Pos { file: 1, line: 3, col: 8 }, "m3").in_files(&[String::new(), "COPYA".into()]);
200        assert_eq!(in_member.place("p.cbl"), "COPYA:3:8: warning: m3");
201        assert_eq!(message(Severity::Severe, 3).to_string(), "3:8: m3");
202    }
203}