1use std::io;
12use std::path::{Path, PathBuf};
13
14use rucc_diag::{Diagnostic, Severity, SourceBytes, SourceMap};
15use rucc_pp::{Context, Predef, Preprocessor, PrintOptions};
16use rucc_session::{FileSystem, Options, Session};
17
18#[derive(Debug, Clone, Copy, Default)]
20pub struct OsFileSystem;
21
22impl OsFileSystem {
23 #[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 crate::map::read(path)
37 }
38
39 fn identity(&self, path: &Path) -> PathBuf {
40 std::fs::canonicalize(path).unwrap_or_else(|_| rucc_session::path_key(path))
46 }
47}
48
49#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct Preprocessed {
52 pub text: String,
54 pub messages: Vec<String>,
56 pub errors: u32,
58}
59
60impl Preprocessed {
61 #[must_use]
63 pub fn failed(&self) -> bool {
64 self.errors > 0
65 }
66}
67
68#[must_use]
74pub fn preprocess(opts: &Options, name: &str, fs: &dyn FileSystem) -> Preprocessed {
75 let mut sess = Session::new(opts.clone());
76 let bytes = match fs.read(Path::new(name)) {
77 Ok(bytes) => bytes,
78 Err(e) => return failure(format!("{name}: {e}")),
79 };
80 let Ok(file) = sess.sources.add_shared(name, bytes, None) else {
81 return failure(format!("{name}: the source map has no room left for this file"));
82 };
83
84 let mut pp = Preprocessor::new();
85 let predef = Predef::for_options(opts);
86 let mut cx = Context::new(&mut sess.interner, &mut sess.sources, fs, &opts.search);
87 cx.lex = rucc_lex::Options::for_dialect(opts.std, opts.gnu_extensions);
88 if pp.predefine(&sess.target, &predef, &mut cx).is_err() {
89 return failure(format!("{name}: the source map has no room left for the built in macros"));
90 }
91 let tokens = pp.run(file, &mut cx);
92 let text = if opts.dumps.macros {
96 rucc_pp::dump_macros(pp.macros(), &sess.interner)
97 } else {
98 rucc_pp::print(
99 file,
100 &tokens,
101 pp.line_directives(),
102 &sess.sources,
103 &sess.interner,
104 PrintOptions { line_markers: opts.line_markers },
105 )
106 };
107
108 let mut messages = Vec::new();
109 let mut errors = 0;
110 for diag in pp.take_diagnostics() {
111 if !opts.warnings && diag.severity == Severity::Warning {
113 continue;
114 }
115 let fatal = diag.severity.is_fatal()
116 || (diag.severity == Severity::Warning && opts.warnings_are_errors);
117 if fatal {
118 errors += 1;
119 }
120 messages.push(render(&diag, &sess.sources, opts.warnings_are_errors));
121 }
122 Preprocessed { text, messages, errors }
123}
124
125fn failure(message: String) -> Preprocessed {
128 Preprocessed {
129 text: String::new(),
130 messages: vec![format!("rucc: error: {message}")],
131 errors: 1,
132 }
133}
134
135pub(crate) fn render(diag: &Diagnostic, sources: &SourceMap, warnings_are_errors: bool) -> String {
141 let mut out = String::new();
142 let mut chain = sources.include_stack(diag.span.lo);
143 chain.reverse();
144 for (at, from) in chain.iter().enumerate() {
145 let lead = if at == 0 { "In file included from" } else { " from" };
146 out.push_str(&format!("{lead} {}:\n", sources.render_position(from.lo)));
147 }
148 out.push_str(&line(diag, sources, warnings_are_errors));
149 for child in &diag.children {
150 out.push('\n');
151 out.push_str(&line(child, sources, false));
152 }
153 out
154}
155
156fn line(diag: &Diagnostic, sources: &SourceMap, warnings_are_errors: bool) -> String {
158 let severity = if diag.severity == Severity::Warning && warnings_are_errors {
159 "error"
163 } else {
164 diag.severity.as_str()
165 };
166 let position = if diag.span.is_dummy() {
167 "rucc".to_owned()
168 } else {
169 sources.render_position(diag.span.lo)
170 };
171 match diag.code {
172 Some(code) => format!("{position}: {severity}: {} [{code}]", diag.message),
173 None => format!("{position}: {severity}: {}", diag.message),
174 }
175}
176
177#[cfg(test)]
178mod tests {
179 use rucc_session::MemoryFileSystem;
180 use rucc_target::Triple;
181
182 use super::*;
183
184 fn options() -> Options {
185 Options::new("x86_64-unknown-linux-gnu".parse::<Triple>().unwrap())
186 }
187
188 fn at(dir: &str, name: &str) -> String {
194 Path::new(dir).join(name).display().to_string()
195 }
196
197 fn run(opts: &Options, files: &[(&str, &str)]) -> Preprocessed {
198 let mut fs = MemoryFileSystem::new();
199 for (path, text) in files {
200 fs.insert(*path, (*text).to_owned().into_bytes());
201 }
202 preprocess(opts, files[0].0, &fs)
203 }
204
205 #[test]
206 fn a_file_that_is_not_there_says_so_and_produces_nothing() {
207 let fs = MemoryFileSystem::new();
208 let result = preprocess(&options(), "/nope.c", &fs);
209 assert!(result.failed());
210 assert!(result.messages[0].contains("/nope.c"), "{:?}", result.messages);
211 assert!(result.text.is_empty());
212 }
213
214 #[test]
215 fn the_output_is_the_expanded_text_with_a_line_marker_on_top() {
216 let result = run(&options(), &[("/main.c", "#define N 2\nint a[N];\n")]);
217 assert_eq!(result.messages, Vec::<String>::new());
218 assert_eq!(result.text, "# 1 \"/main.c\"\n\nint a[2];\n");
219 }
220
221 #[test]
222 fn the_predefined_macros_are_there_without_being_asked_for() {
223 let result = run(&options(), &[("/main.c", "__SIZEOF_LONG__ __x86_64__\n")]);
224 assert_eq!(result.text, "# 1 \"/main.c\"\n8 1\n");
225 }
226
227 #[test]
228 fn dash_d_and_dash_u_reach_the_macro_table() {
229 let mut opts = options();
230 opts.defines.push("FOO=41+1".to_owned());
231 opts.defines.push("BAR".to_owned());
232 opts.undefines.push("__x86_64__".to_owned());
233 let result = run(&opts, &[("/main.c", "FOO BAR\n#ifdef __x86_64__\ngone\n#endif\n")]);
234 assert_eq!(result.text, "# 1 \"/main.c\"\n41+1 1\n");
239 }
240
241 #[test]
242 fn dash_i_is_where_an_angled_include_looks() {
243 let mut opts = options();
244 opts.search.push_bracket("/inc");
245 let files = [("/main.c", "#include <one.h>\nint after;\n"), ("/inc/one.h", "int in_it;\n")];
246 let result = run(&opts, &files);
247 let one = at("/inc", "one.h").replace('\\', "\\\\");
251 let expected = format!(
252 "# 1 \"/main.c\"\n# 1 \"{one}\" 1\nint in_it;\n# 2 \"/main.c\" 2\nint after;\n"
253 );
254 assert_eq!(result.text, expected);
255 }
256
257 #[test]
258 fn dash_p_leaves_the_markers_out() {
259 let mut opts = options();
260 opts.line_markers = false;
261 opts.search.push_bracket("/inc");
262 let files = [("/main.c", "#include <one.h>\nint after;\n"), ("/inc/one.h", "int in_it;\n")];
263 assert_eq!(run(&opts, &files).text, "int in_it;\nint after;\n");
264 }
265
266 #[test]
267 fn a_diagnostic_says_where_it_is_and_carries_its_code() {
268 let result = run(&options(), &[("/main.c", "#error no\n")]);
269 assert_eq!(result.errors, 1);
270 assert!(
271 result.messages[0].starts_with("/main.c:1:8: error: no ["),
272 "{:?}",
273 result.messages
274 );
275 }
276
277 #[test]
278 fn a_diagnostic_in_a_header_prints_the_chain_that_reached_it() {
279 let mut opts = options();
280 opts.search.push_bracket("/inc");
281 let files = [
282 ("/main.c", "#include <one.h>\n"),
283 ("/inc/one.h", "#include <two.h>\n"),
284 ("/inc/two.h", "#error deep\n"),
285 ];
286 let result = run(&opts, &files);
287 let text = result.messages.join("\n");
288 assert!(text.starts_with("In file included from /main.c:1:1:\n"), "{text}");
289 assert!(
290 text.contains(&format!(" from {}:1:1:\n", at("/inc", "one.h"))),
291 "{text}"
292 );
293 assert!(text.contains(&format!("{}:1:8: error: deep", at("/inc", "two.h"))), "{text}");
294 }
295
296 #[test]
297 fn werror_turns_a_warning_into_an_error_in_the_count_and_in_the_word() {
298 let source = "#warning careful\n";
299 let plain = run(&options(), &[("/main.c", source)]);
300 assert_eq!(plain.errors, 0);
301 assert!(plain.messages[0].contains("warning: careful"), "{:?}", plain.messages);
302
303 let mut opts = options();
304 opts.warnings_are_errors = true;
305 let strict = run(&opts, &[("/main.c", source)]);
306 assert_eq!(strict.errors, 1);
307 assert!(strict.messages[0].contains("error: careful"), "{:?}", strict.messages);
308 }
309
310 #[test]
311 fn dash_dm_prints_the_macros_the_file_left_behind_and_not_the_file() {
312 let source = "#define KEPT 1\n#define GONE 2\n#undef GONE\n#ifdef NEVER\n#define \
313 HIDDEN 3\n#endif\nint x;\n";
314 let result = run(&options(), &[("/main.c", source)]);
315 assert_eq!(result.errors, 0);
316 assert!(result.text.contains("int x;"), "the output is the file without -dM");
317 assert!(!result.text.contains("#define"), "a directive line is not part of the output");
318
319 let mut opts = options();
320 opts.dumps.macros = true;
321 let dumped = run(&opts, &[("/main.c", source)]);
322 assert!(dumped.text.contains("#define KEPT 1\n"), "{}", dumped.text);
323 assert!(!dumped.text.contains("int x;"), "-dM replaces the output rather than adding");
324 assert!(!dumped.text.contains("GONE"), "{}", dumped.text);
327 assert!(!dumped.text.contains("HIDDEN"), "{}", dumped.text);
328 assert!(dumped.text.contains("#define __x86_64__ 1\n"), "{}", dumped.text);
331 }
332
333 #[test]
334 fn the_dialect_reaches_the_predefined_set() {
335 let mut opts = options();
336 opts.std = rucc_session::Std::C99;
337 opts.gnu_extensions = false;
338 let result = run(&opts, &[("/main.c", "__STDC_VERSION__ __STRICT_ANSI__\n")]);
339 assert_eq!(result.text, "# 1 \"/main.c\"\n199901L 1\n");
340 }
341}