Skip to main content

rucc_driver/
preprocess.rs

1//! Running phase 4 and writing what came out, which is what `-E` asks for.
2//!
3//! Design: `spec/04-driver-and-cli.md` sections 4.3 and 4.4, and `spec/05-preprocessor.md`.
4//!
5//! This is the first phase the driver actually runs, so it is also where the file system
6//! implementation lives. Everything below the driver reads through the [`FileSystem`] trait,
7//! and [`OsFileSystem`] is the one implementation of it that talks to the disk. Keeping it
8//! here rather than in `rucc-session` is what keeps the layer rule true: a preprocessor test
9//! is a map from path to bytes and cannot accidentally read the machine it runs on.
10
11use std::io;
12use std::path::Path;
13
14use rucc_diag::{Diagnostic, Severity, SourceBytes, SourceMap};
15use rucc_pp::{Context, Predef, Preprocessor, PrintOptions};
16use rucc_session::{FileSystem, Options, Session};
17
18/// The file system the compiler reads through when it is a compiler rather than a library.
19#[derive(Debug, Clone, Copy, Default)]
20pub struct OsFileSystem;
21
22impl OsFileSystem {
23    /// The one value of this type.
24    #[must_use]
25    pub fn new() -> OsFileSystem {
26        OsFileSystem
27    }
28}
29
30impl FileSystem for OsFileSystem {
31    fn read(&self, path: &Path) -> io::Result<SourceBytes> {
32        // Bytes rather than a string. A source file that is not valid UTF-8 is a file this
33        // compiler still has to have an opinion about, and phase 1 is where that opinion
34        // belongs, not here. Whether the bytes are a mapping or a buffer is `map`'s decision
35        // and is invisible from here.
36        crate::map::read(path)
37    }
38}
39
40/// What preprocessing one file produced.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct Preprocessed {
43    /// The text to write, empty when the file could not be read.
44    pub text: String,
45    /// The diagnostics, already rendered, one per line, in the order they were reported.
46    pub messages: Vec<String>,
47    /// How many of them were errors.
48    pub errors: u32,
49}
50
51impl Preprocessed {
52    /// Whether anything went wrong badly enough that the output should not be used.
53    #[must_use]
54    pub fn failed(&self) -> bool {
55        self.errors > 0
56    }
57}
58
59/// Preprocesses one file and renders the result.
60///
61/// `name` is the path as the user wrote it, which is the name the output and every diagnostic
62/// about the file use. It is not canonicalised, because a message naming a path nobody typed
63/// is a message that is harder to act on.
64#[must_use]
65pub fn preprocess(opts: &Options, name: &str, fs: &dyn FileSystem) -> Preprocessed {
66    let mut sess = Session::new(opts.clone());
67    let bytes = match fs.read(Path::new(name)) {
68        Ok(bytes) => bytes,
69        Err(e) => return failure(format!("{name}: {e}")),
70    };
71    let Ok(file) = sess.sources.add_shared(name, bytes, None) else {
72        return failure(format!("{name}: the source map has no room left for this file"));
73    };
74
75    let mut pp = Preprocessor::new();
76    let predef = Predef::for_options(opts);
77    let mut cx = Context::new(&mut sess.interner, &mut sess.sources, fs, &opts.search);
78    cx.lex = rucc_lex::Options::for_dialect(opts.std, opts.gnu_extensions);
79    if pp.predefine(&sess.target, &predef, &mut cx).is_err() {
80        return failure(format!("{name}: the source map has no room left for the built in macros"));
81    }
82    let tokens = pp.run(file, &mut cx);
83    // `-dM` replaces the output rather than adding to it. The run still happens, and it has
84    // to: the table at the end is the one the file left behind, so a `#define` inside an
85    // `#ifdef` that was false is correctly absent.
86    let text = if opts.dumps.macros {
87        rucc_pp::dump_macros(pp.macros(), &sess.interner)
88    } else {
89        rucc_pp::print(
90            file,
91            &tokens,
92            pp.line_directives(),
93            &sess.sources,
94            &sess.interner,
95            PrintOptions { line_markers: opts.line_markers },
96        )
97    };
98
99    let mut messages = Vec::new();
100    let mut errors = 0;
101    for diag in pp.take_diagnostics() {
102        let fatal = diag.severity.is_fatal()
103            || (diag.severity == Severity::Warning && opts.warnings_are_errors);
104        if fatal {
105            errors += 1;
106        }
107        messages.push(render(&diag, &sess.sources, opts.warnings_are_errors));
108    }
109    Preprocessed { text, messages, errors }
110}
111
112/// A result that is nothing but one message, for the failures that happen before there is
113/// anything to preprocess.
114fn failure(message: String) -> Preprocessed {
115    Preprocessed {
116        text: String::new(),
117        messages: vec![format!("rucc: error: {message}")],
118        errors: 1,
119    }
120}
121
122/// One diagnostic as the lines it prints.
123///
124/// GCC's shape: the position, the severity, the message, then the code, then any notes
125/// underneath. The chain of includes that reached the file comes first, because a diagnostic
126/// in a header three levels down is unactionable without the path that got there.
127pub(crate) fn render(diag: &Diagnostic, sources: &SourceMap, warnings_are_errors: bool) -> String {
128    let mut out = String::new();
129    let mut chain = sources.include_stack(diag.span.lo);
130    chain.reverse();
131    for (at, from) in chain.iter().enumerate() {
132        let lead = if at == 0 { "In file included from" } else { "                 from" };
133        out.push_str(&format!("{lead} {}:\n", sources.render_position(from.lo)));
134    }
135    out.push_str(&line(diag, sources, warnings_are_errors));
136    for child in &diag.children {
137        out.push('\n');
138        out.push_str(&line(child, sources, false));
139    }
140    out
141}
142
143/// The one line a diagnostic or one of its notes prints.
144fn line(diag: &Diagnostic, sources: &SourceMap, warnings_are_errors: bool) -> String {
145    let severity = if diag.severity == Severity::Warning && warnings_are_errors {
146        // Not a relabelling for its own sake. A build that turned warnings into errors and
147        // then reads "warning" next to a failed compilation has to go looking for why it
148        // failed, and the answer is right here.
149        "error"
150    } else {
151        diag.severity.as_str()
152    };
153    let position = if diag.span.is_dummy() {
154        "rucc".to_owned()
155    } else {
156        sources.render_position(diag.span.lo)
157    };
158    match diag.code {
159        Some(code) => format!("{position}: {severity}: {} [{code}]", diag.message),
160        None => format!("{position}: {severity}: {}", diag.message),
161    }
162}
163
164#[cfg(test)]
165mod tests {
166    use rucc_session::MemoryFileSystem;
167    use rucc_target::Triple;
168
169    use super::*;
170
171    fn options() -> Options {
172        Options::new("x86_64-unknown-linux-gnu".parse::<Triple>().unwrap())
173    }
174
175    /// The path an include search produces for `name` under `dir`.
176    ///
177    /// The search joins the two with the platform's separator, so an expectation with a slash
178    /// written into it is an expectation about Unix rather than about the preprocessor, and it
179    /// fails on Windows for a reason that has nothing to do with what the test is checking.
180    fn at(dir: &str, name: &str) -> String {
181        Path::new(dir).join(name).display().to_string()
182    }
183
184    fn run(opts: &Options, files: &[(&str, &str)]) -> Preprocessed {
185        let mut fs = MemoryFileSystem::new();
186        for (path, text) in files {
187            fs.insert(*path, (*text).to_owned().into_bytes());
188        }
189        preprocess(opts, files[0].0, &fs)
190    }
191
192    #[test]
193    fn a_file_that_is_not_there_says_so_and_produces_nothing() {
194        let fs = MemoryFileSystem::new();
195        let result = preprocess(&options(), "/nope.c", &fs);
196        assert!(result.failed());
197        assert!(result.messages[0].contains("/nope.c"), "{:?}", result.messages);
198        assert!(result.text.is_empty());
199    }
200
201    #[test]
202    fn the_output_is_the_expanded_text_with_a_line_marker_on_top() {
203        let result = run(&options(), &[("/main.c", "#define N 2\nint a[N];\n")]);
204        assert_eq!(result.messages, Vec::<String>::new());
205        assert_eq!(result.text, "# 1 \"/main.c\"\n\nint a[2];\n");
206    }
207
208    #[test]
209    fn the_predefined_macros_are_there_without_being_asked_for() {
210        let result = run(&options(), &[("/main.c", "__SIZEOF_LONG__ __x86_64__\n")]);
211        assert_eq!(result.text, "# 1 \"/main.c\"\n8 1\n");
212    }
213
214    #[test]
215    fn dash_d_and_dash_u_reach_the_macro_table() {
216        let mut opts = options();
217        opts.defines.push("FOO=41+1".to_owned());
218        opts.defines.push("BAR".to_owned());
219        opts.undefines.push("__x86_64__".to_owned());
220        let result = run(&opts, &[("/main.c", "FOO BAR\n#ifdef __x86_64__\ngone\n#endif\n")]);
221        // `41+1` with no space in it, which is what it was written as on the command line and
222        // what GCC prints. The three tokens all came out of the one expansion of `FOO`, and a
223        // paste is only worth avoiding where a macro put two tokens together that the person
224        // did not write together.
225        assert_eq!(result.text, "# 1 \"/main.c\"\n41+1 1\n");
226    }
227
228    #[test]
229    fn dash_i_is_where_an_angled_include_looks() {
230        let mut opts = options();
231        opts.search.push_bracket("/inc");
232        let files = [("/main.c", "#include <one.h>\nint after;\n"), ("/inc/one.h", "int in_it;\n")];
233        let result = run(&opts, &files);
234        // A line marker's file name is a string literal, so a separator that is a backslash
235        // comes out escaped, which is what GCC does and what a reader of the output has to be
236        // able to parse back.
237        let one = at("/inc", "one.h").replace('\\', "\\\\");
238        let expected = format!(
239            "# 1 \"/main.c\"\n# 1 \"{one}\" 1\nint in_it;\n# 2 \"/main.c\" 2\nint after;\n"
240        );
241        assert_eq!(result.text, expected);
242    }
243
244    #[test]
245    fn dash_p_leaves_the_markers_out() {
246        let mut opts = options();
247        opts.line_markers = false;
248        opts.search.push_bracket("/inc");
249        let files = [("/main.c", "#include <one.h>\nint after;\n"), ("/inc/one.h", "int in_it;\n")];
250        assert_eq!(run(&opts, &files).text, "int in_it;\nint after;\n");
251    }
252
253    #[test]
254    fn a_diagnostic_says_where_it_is_and_carries_its_code() {
255        let result = run(&options(), &[("/main.c", "#error no\n")]);
256        assert_eq!(result.errors, 1);
257        assert!(
258            result.messages[0].starts_with("/main.c:1:8: error: no ["),
259            "{:?}",
260            result.messages
261        );
262    }
263
264    #[test]
265    fn a_diagnostic_in_a_header_prints_the_chain_that_reached_it() {
266        let mut opts = options();
267        opts.search.push_bracket("/inc");
268        let files = [
269            ("/main.c", "#include <one.h>\n"),
270            ("/inc/one.h", "#include <two.h>\n"),
271            ("/inc/two.h", "#error deep\n"),
272        ];
273        let result = run(&opts, &files);
274        let text = result.messages.join("\n");
275        assert!(text.starts_with("In file included from /main.c:1:1:\n"), "{text}");
276        assert!(
277            text.contains(&format!("                 from {}:1:1:\n", at("/inc", "one.h"))),
278            "{text}"
279        );
280        assert!(text.contains(&format!("{}:1:8: error: deep", at("/inc", "two.h"))), "{text}");
281    }
282
283    #[test]
284    fn werror_turns_a_warning_into_an_error_in_the_count_and_in_the_word() {
285        let source = "#warning careful\n";
286        let plain = run(&options(), &[("/main.c", source)]);
287        assert_eq!(plain.errors, 0);
288        assert!(plain.messages[0].contains("warning: careful"), "{:?}", plain.messages);
289
290        let mut opts = options();
291        opts.warnings_are_errors = true;
292        let strict = run(&opts, &[("/main.c", source)]);
293        assert_eq!(strict.errors, 1);
294        assert!(strict.messages[0].contains("error: careful"), "{:?}", strict.messages);
295    }
296
297    #[test]
298    fn dash_dm_prints_the_macros_the_file_left_behind_and_not_the_file() {
299        let source = "#define KEPT 1\n#define GONE 2\n#undef GONE\n#ifdef NEVER\n#define \
300                      HIDDEN 3\n#endif\nint x;\n";
301        let result = run(&options(), &[("/main.c", source)]);
302        assert_eq!(result.errors, 0);
303        assert!(result.text.contains("int x;"), "the output is the file without -dM");
304        assert!(!result.text.contains("#define"), "a directive line is not part of the output");
305
306        let mut opts = options();
307        opts.dumps.macros = true;
308        let dumped = run(&opts, &[("/main.c", source)]);
309        assert!(dumped.text.contains("#define KEPT 1\n"), "{}", dumped.text);
310        assert!(!dumped.text.contains("int x;"), "-dM replaces the output rather than adding");
311        // Undefined is gone, and a define the conditional skipped was never made. The dump is
312        // the table at the end of the run and not a list of the lines that were written.
313        assert!(!dumped.text.contains("GONE"), "{}", dumped.text);
314        assert!(!dumped.text.contains("HIDDEN"), "{}", dumped.text);
315        // The predefined set is in there too, because it is defined the same way everything
316        // else is, which is the whole reason this output can be diffed against GCC's.
317        assert!(dumped.text.contains("#define __x86_64__ 1\n"), "{}", dumped.text);
318    }
319
320    #[test]
321    fn the_dialect_reaches_the_predefined_set() {
322        let mut opts = options();
323        opts.std = rucc_session::Std::C99;
324        opts.gnu_extensions = false;
325        let result = run(&opts, &[("/main.c", "__STDC_VERSION__ __STRICT_ANSI__\n")]);
326        assert_eq!(result.text, "# 1 \"/main.c\"\n199901L 1\n");
327    }
328}