Skip to main content

rucc_pp/
directive.rs

1//! The directive engine: translation phase 4 over one file's preprocessing tokens.
2//!
3//! Design: `spec/05-preprocessor.md` section 5.4.
4//!
5//! A directive is a line whose first token is `#`. That is the whole of the recognition rule,
6//! and the two halves of it are both load bearing: `#` has to be first on the line, and the
7//! line is what the lexer says it is after splices and comments have been resolved, which is
8//! why `x /*\n*/ #define F 1` really does define `F`.
9//!
10//! The part that is easy to get wrong is skipped regions. Inside `#if 0` a line beginning with
11//! `#` still has to be recognised well enough to keep the conditional nesting balanced, and it
12//! must not be diagnosed for anything else. Real code puts prose, unbalanced quotes and future
13//! syntax inside `#if 0`, and a preprocessor that reports errors from there is unusable. So
14//! skipping looks at the directive name and nothing else, and only the seven conditional
15//! directives mean anything while it is going on.
16
17use std::collections::{HashMap, HashSet};
18use std::path::{Path, PathBuf};
19
20use rucc_base::{Interner, Symbol};
21use rucc_diag::{Diagnostic, FileId, SourceMapFull, Span};
22use rucc_gnu::Kind;
23use rucc_lex::{Options, PpToken, PpTokenKind, Punct, TokenFlags, tokenize};
24use rucc_session::{Found, IncludeForm, PrefixMap, Preinclude};
25use rucc_target::TargetInfo;
26
27use crate::cond;
28use crate::embed;
29use crate::expand::Expander;
30use crate::include::{
31    Context, Dependency, Frame, Header, Reader, directory_of, header_from_token,
32    header_from_tokens, spelling,
33};
34use crate::macros::{Builtin, MacroTable, parse_define};
35use crate::predef::{BUILT_IN, COMMAND_LINE, Predef, built_in, command_line};
36use crate::token::Tok;
37
38/// Why a file that has already been read does not need reading again.
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40enum Guard {
41    /// `#pragma once`, so the file is read once however many times it is named.
42    Once,
43    /// The whole file is wrapped in `#ifndef NAME`, and `NAME` is now defined, so reading it
44    /// again would produce nothing at all. This is the multiple-include optimization, and on
45    /// a real code base it is the difference between reading a header once and reading it a
46    /// few hundred times.
47    Macro(Symbol),
48}
49
50/// How far through the file the guard shape has been recognised.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52enum Scan {
53    /// Nothing has been seen yet, so the next line may open the guard.
54    Start,
55    /// Inside the conditional the file opened with.
56    Inside(Symbol),
57    /// The conditional closed and the file has to end here for the shape to hold.
58    Closed(Symbol),
59    /// Something else was seen, so this file has no guard.
60    No,
61}
62
63/// One `#if` and everything hanging off it.
64#[derive(Debug)]
65struct Cond {
66    /// Where the `#if` was written, so an unterminated one can point at it.
67    span: Span,
68    /// Whether tokens in the branch currently open are kept. Already accounts for whether the
69    /// enclosing region was live, so [`Preprocessor::live`] only has to look at the top.
70    live: bool,
71    /// Whether some branch of this chain has been taken. A later `#elif` is not evaluated once
72    /// this is set, which is what makes `#elif 1/0` after a taken branch legal.
73    taken: bool,
74    /// Whether the enclosing region was live.
75    enclosing_live: bool,
76    /// Whether `#else` has been seen, so a second one is an error.
77    seen_else: bool,
78}
79
80/// A `#line` directive, as read and as applied to the source map.
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct LineDirective {
83    /// Where the directive is.
84    pub span: Span,
85    /// The line number the next line is to be called.
86    pub line: u32,
87    /// The file name the following lines are to be called, if one was given.
88    pub file: Option<Symbol>,
89    /// How many tokens had been emitted when this was read, which is where it sits in the
90    /// stream.
91    ///
92    /// A position is not enough to say that. A file included from here is added to the source
93    /// map after this file, so its bytes come after every byte of this one, and the token
94    /// after the `#include` is at a lower position than the tokens of the header. `-E` has to
95    /// write a marker for a `#line` where the directive was written rather than where its
96    /// bytes are, and this is what says where that is.
97    pub at: usize,
98}
99
100/// Translation phase 4 over one file.
101///
102/// Holds the macro table and the conditional stack, so a single instance processes a whole
103/// translation unit and the definitions a header makes are visible after it.
104#[derive(Debug, Default)]
105pub struct Preprocessor {
106    macros: MacroTable,
107    expander: Expander,
108    diagnostics: Vec<Diagnostic>,
109    conds: Vec<Cond>,
110    lines: Vec<LineDirective>,
111    /// The files currently open, innermost last. Empty between runs.
112    stack: Vec<Frame>,
113    /// The files a line marker said were entered, innermost last, by the name in force when it
114    /// said so. This is the nesting a `2` flag claims to be leaving, and it is kept apart from
115    /// `stack` because a marker set describes a nesting the real files never had.
116    markers: Vec<String>,
117    /// Files that do not need reading again, and why. Keyed by what the file system calls the
118    /// file rather than by the name an include used, so that a header reached two ways is one
119    /// entry here.
120    seen: HashMap<PathBuf, Guard>,
121    /// Every file an `#include` found, in the order they were first reached.
122    ///
123    /// This is what the `-M` family reports. It is collected here rather than read off the
124    /// source map afterwards because the map holds the built in and command line macros as
125    /// files too, and because whether a header came from a system directory is something only
126    /// the search knew and the map never learns.
127    deps: Vec<Dependency>,
128    /// What is already in `deps`, by the name the file system gives the file.
129    ///
130    /// A header reached through two spellings is one dependency, and a header included a
131    /// hundred times is one line in the rule.
132    ///
133    /// This is the one place the rule is not what GCC writes. GCC keys its list on the pair of
134    /// the directory the search started from and the name the directive wrote, which is the key
135    /// of the cache it reads the file through rather than a decision, so `"x.h"` and `"./x.h"`
136    /// are two prerequisites there and a header two other headers in the same directory reach
137    /// by different relative paths is listed twice. Naming a file once is what the flag means,
138    /// and a duplicate prerequisite means nothing to `make` either way.
139    dep_ids: HashSet<PathBuf>,
140}
141
142impl Preprocessor {
143    /// A preprocessor with an empty macro table.
144    pub fn new() -> Preprocessor {
145        Preprocessor::default()
146    }
147
148    /// The same, with `__FILE__` and `__BASE_FILE__` rewritten by `map`.
149    ///
150    /// Handed in at construction rather than set afterwards because it is fixed for the whole
151    /// translation unit: the command line cannot change its mind halfway through a file, and a
152    /// `__FILE__` that answered differently at the top of a header than at the bottom would be a
153    /// worse bug than not having the flag.
154    pub fn with_prefix_map(map: PrefixMap) -> Preprocessor {
155        Preprocessor { expander: Expander::with_prefix_map(map), ..Preprocessor::default() }
156    }
157
158    /// The macros defined so far.
159    pub fn macros(&self) -> &MacroTable {
160        &self.macros
161    }
162
163    /// The macro table, for the driver to seed with `-D` and the predefined set.
164    pub fn macros_mut(&mut self) -> &mut MacroTable {
165        &mut self.macros
166    }
167
168    /// Everything reported so far.
169    pub fn diagnostics(&self) -> &[Diagnostic] {
170        &self.diagnostics
171    }
172
173    /// Takes the diagnostics, leaving the preprocessor able to carry on.
174    pub fn take_diagnostics(&mut self) -> Vec<Diagnostic> {
175        std::mem::take(&mut self.diagnostics)
176    }
177
178    /// Every file an `#include` found, in the order they were first reached.
179    ///
180    /// What the `-M` family writes into a make rule. The source file itself is not in here,
181    /// since nothing included it, and the caller that knows its name puts it first.
182    pub fn dependencies(&self) -> &[Dependency] {
183        &self.deps
184    }
185
186    /// The `#line` directives seen, in the order they appeared.
187    ///
188    /// Each one is also applied, to the source map, as it is read. This is the record of them
189    /// rather than the mechanism: what a caller wants it for is reporting on the directives
190    /// themselves, and asking the map is how to find out where anything is.
191    pub fn line_directives(&self) -> &[LineDirective] {
192        &self.lines
193    }
194
195    /// Defines the predefined macro set, and then `-D` and `-U` from the command line.
196    ///
197    /// Called before [`Preprocessor::run`], because a predefined macro is a macro like any
198    /// other by the time the source file is read. The set arrives as two synthetic files
199    /// rather than as a list of definitions, so a diagnostic about one of them points at
200    /// `<built-in>` or `<command-line>` the way GCC's does, and so that `-dM` has something
201    /// to print. The reasoning is in `crate::predef`.
202    ///
203    /// # Errors
204    ///
205    /// When the source map has no room left for the two synthetic files.
206    pub fn predefine(
207        &mut self,
208        target: &TargetInfo,
209        opts: &Predef,
210        cx: &mut Context<'_>,
211    ) -> Result<(), SourceMapFull> {
212        let names = Names::new(cx.interner);
213        let file = self.synthetic(BUILT_IN, built_in(target, opts), cx, &names)?;
214        // The macros that cannot be written as a `#define` line, because what they stand for
215        // depends on where they are used. They go in after the generated file and before the
216        // command line, so that `-U__FILE__` takes one away the way it takes any other away.
217        // The origin is the start of `<built-in>`, which is where a warning about redefining
218        // one points, and which is the truthful answer to where they came from.
219        let start = cx.sources.file(file).start;
220        for (spelling, builtin) in Builtin::ALL {
221            let name = cx.interner.intern(spelling);
222            self.macros.define_builtin(name, builtin, Span::new(start, start));
223        }
224        let text = command_line(opts);
225        if !text.is_empty() {
226            self.synthetic(COMMAND_LINE, text, cx, &names)?;
227        }
228        Ok(())
229    }
230
231    /// Reads a file the compiler wrote rather than one the user did.
232    fn synthetic(
233        &mut self,
234        name: &str,
235        text: String,
236        cx: &mut Context<'_>,
237        names: &Names,
238    ) -> Result<FileId, SourceMapFull> {
239        let file = cx.sources.add(name, text.into_bytes())?;
240        let mut out = Vec::new();
241        // A frame, so that the guard scan and the include depth see the same shape they see
242        // for a real file. There is no directory, because `#include "x.h"` written in a
243        // synthetic file has nowhere of its own to look.
244        let path = PathBuf::from(name);
245        let id = cx.fs.identity(&path);
246        self.stack.push(Frame { at: Span::DUMMY, path, id, dir: None, next: 0 });
247        self.process(file, &mut out, cx, names);
248        self.stack.clear();
249        debug_assert!(out.is_empty(), "{name} is directives only and produces no tokens");
250        Ok(file)
251    }
252
253    /// Reads the files `-imacros` and `-include` named, before the source file is opened.
254    ///
255    /// Called between [`Preprocessor::predefine`] and [`Preprocessor::run`], with the tokens the
256    /// `-include` files produce going in front of the ones the source file produces. That is what
257    /// the flags mean: the definitions arrive before the first line of the source, so a header
258    /// the source has no `#include` for is nevertheless in scope throughout it.
259    ///
260    /// Every `-imacros` file is read before every `-include` file, whatever order the command line
261    /// wrote them in, which is GCC's behaviour and is measured rather than read: two command lines
262    /// with the two flags the other way round produce the same output byte for byte. The text an
263    /// `-imacros` file produces is thrown away and only its definitions are kept, which is the
264    /// whole difference between the two flags.
265    ///
266    /// Each name is looked for the way a quoted include is looked for, starting from the working
267    /// directory rather than from the directory of the source file. A source in `sub/` and a
268    /// `-include` of a header sitting beside it is an error, not a file found, because the command
269    /// line is not written in `sub/`.
270    ///
271    /// # Errors
272    ///
273    /// When the source map has no room left for the record of the flags.
274    pub fn preinclude(
275        &mut self,
276        files: &[Preinclude],
277        out: &mut Vec<Tok>,
278        cx: &mut Context<'_>,
279    ) -> Result<(), SourceMapFull> {
280        if files.is_empty() {
281            return Ok(());
282        }
283        let names = Names::new(cx.interner);
284        // The flags as a file, so that a name that is not found has somewhere to point. The two
285        // spellings are the same length, which is what makes the offset of the name the length of
286        // the line so far and keeps this from needing a second pass.
287        let mut text = String::new();
288        let mut order: Vec<(usize, &Preinclude)> = Vec::new();
289        for macros_only in [true, false] {
290            for file in files.iter().filter(|f| f.macros_only == macros_only) {
291                text.push_str(if macros_only { "-imacros " } else { "-include " });
292                order.push((text.len(), file));
293                text.push_str(&file.name);
294                text.push('\n');
295            }
296        }
297        let record = cx.sources.add(COMMAND_LINE, text.into_bytes())?;
298        let start = cx.sources.file(record).start;
299        // A frame for the command line itself, so that the files below it are at the depth they
300        // would be at had the source file included them, and a `#pragma once` in one of them is
301        // not reported as a `#pragma once` in a main file.
302        let path = PathBuf::from(COMMAND_LINE);
303        let id = cx.fs.identity(&path);
304        self.stack.push(Frame { at: Span::DUMMY, path, id, dir: None, next: 0 });
305        let here = Path::new(".");
306        for (offset, file) in order {
307            let at = Span::new(start + offset as u32, start + (offset + file.name.len()) as u32);
308            let form = IncludeForm::Quoted;
309            let found = cx.search.resolve(cx.fs, &file.name, form, Some(here), 0);
310            let Some(found) = found else {
311                let tried = cx.search.tried(&file.name, form, Some(here), 0);
312                self.not_found(&file.name, at, &tried, cx.search.missing_system());
313                continue;
314            };
315            let mut discarded = Vec::new();
316            let sink = if file.macros_only { &mut discarded } else { &mut *out };
317            self.read(found, at, sink, cx, &names);
318        }
319        self.stack.clear();
320        Ok(())
321    }
322
323    /// Runs phase 4 over `file` and everything it includes.
324    ///
325    /// The result is the tokens that survived the conditionals, with macros expanded. Nothing
326    /// is thrown away silently: an unterminated `#if` and a stray `#endif` are both reported.
327    pub fn run(&mut self, file: FileId, cx: &mut Context<'_>) -> Vec<Tok> {
328        let names = Names::new(cx.interner);
329        let mut out = Vec::new();
330        let name = cx.sources.file(file).name.clone();
331        let dir = directory_of(&name);
332        // The file named on the command line was not found through the search path, so an
333        // `#include_next` written in it starts at the top rather than partway down.
334        let path = PathBuf::from(name);
335        let id = cx.fs.identity(&path);
336        self.stack.push(Frame { at: Span::DUMMY, path, id, dir, next: 0 });
337        self.process(file, &mut out, cx, &names);
338        self.stack.clear();
339        out
340    }
341
342    /// Reads one file, appending what survives to `out`.
343    fn process(&mut self, file: FileId, out: &mut Vec<Tok>, cx: &mut Context<'_>, names: &Names) {
344        // The bytes are taken out of the map by sharing rather than by borrowing, because the
345        // rest of this function needs the map back to add an included file to it.
346        let bytes = cx.sources.file(file).shared_bytes();
347        let start = cx.sources.file(file).start;
348        let mut reader = Reader::new(bytes.as_slice(), start, cx.lex);
349        let depth_on_entry = self.conds.len();
350        // Consecutive text lines are expanded as one run rather than line by line, because a
351        // function-like macro invocation may span lines. It may not span a directive, which is
352        // undefined behaviour, so a directive is where the run ends.
353        let mut text: Vec<Tok> = Vec::new();
354        let mut body: Vec<PpToken> = Vec::new();
355        let mut scan = Scan::Start;
356
357        loop {
358            let was_live = self.live();
359            let first = reader.next(cx.interner);
360            if first.is_eof() {
361                break;
362            }
363            if is_directive(first) {
364                self.flush(&mut text, out, cx, names);
365                body.clear();
366                let name_tok = reader.next(cx.interner);
367                // The null directive. A line of just `#` is legal and does nothing, and there
368                // is a surprising amount of it in real headers as a visual separator.
369                if name_tok.is_eof() || name_tok.flags.has(TokenFlags::START_OF_LINE) {
370                    reader.put_back(name_tok);
371                    continue;
372                }
373                body.push(name_tok);
374                // The header name has to be scanned here or not at all: `<stdio.h>` and a run
375                // of comparisons are the same bytes, and once the line has been scanned the
376                // other way the difference is gone. Not in a skipped region, because scanning
377                // one there can report an unterminated name that nobody asked about.
378                if was_live && is_include(ident_of(&name_tok), names) {
379                    if let Some(header) = reader.header_name(cx.interner) {
380                        body.push(header);
381                    }
382                }
383                reader.line(cx.interner, &mut body);
384                let opens =
385                    matches!(scan, Scan::Start).then(|| guard_opener(&body, names)).flatten();
386                self.directive(&body, first.span, out, cx, names);
387                scan = match scan {
388                    // The guard has to be the first line of the file and it has to open a
389                    // conditional, which is why the depth is checked after the dispatch
390                    // rather than the directive name being trusted on its own.
391                    Scan::Start => match opens {
392                        Some(name) if self.conds.len() == depth_on_entry + 1 => Scan::Inside(name),
393                        _ => Scan::No,
394                    },
395                    Scan::Inside(name) if self.conds.len() == depth_on_entry => Scan::Closed(name),
396                    Scan::Inside(name) => Scan::Inside(name),
397                    Scan::Closed(_) | Scan::No => Scan::No,
398                };
399            } else {
400                body.clear();
401                reader.line(cx.interner, &mut body);
402                if self.live() {
403                    // A run of text lines is expanded in one go, and a `_Pragma` is a directive
404                    // wearing an operator's clothes: `pop_macro` changes what the names after it
405                    // mean. So a line that spells one is expanded on its own, or the line after a
406                    // pop would go through the expander in the same batch as the line before it
407                    // and would still see the definition the pop was there to undo.
408                    let operator = ident_of(&first) == Some(names.pragma_op)
409                        || body.iter().any(|t| ident_of(t) == Some(names.pragma_op));
410                    if operator {
411                        self.flush(&mut text, out, cx, names);
412                    }
413                    text.push(Tok::new(first));
414                    text.extend(body.iter().copied().map(Tok::new));
415                    if operator {
416                        self.flush(&mut text, out, cx, names);
417                    }
418                }
419                // A token outside the guard is a token that would be produced twice.
420                if !matches!(scan, Scan::Inside(_)) {
421                    scan = Scan::No;
422                }
423            }
424            // What the lexer complained about while reading that line. A skipped region keeps
425            // its complaints to itself, for the same reason it keeps its directives to itself.
426            let complaints = reader.take_diagnostics();
427            if was_live || self.live() {
428                self.diagnostics.extend(complaints);
429            }
430        }
431        self.flush(&mut text, out, cx, names);
432        self.diagnostics.extend(reader.take_diagnostics());
433
434        // The guard only counts if the macro really did get defined. A file that opens with
435        // `#ifndef X` and never defines `X` is a file that has to be read again.
436        if let Scan::Closed(name) = scan {
437            if self.macros.is_defined(name) {
438                if let Some(frame) = self.stack.last() {
439                    self.seen.entry(frame.id.clone()).or_insert(Guard::Macro(name));
440                }
441            }
442        }
443
444        // A file may not close a conditional it did not open. GCC reports this at the `#if`,
445        // which is the line the user has to go and look at.
446        for cond in self.conds.drain(depth_on_entry..) {
447            self.diagnostics
448                .push(Diagnostic::error("unterminated `#if`", cond.span).with_code("E0330"));
449        }
450    }
451
452    /// Whether tokens are currently being kept.
453    fn live(&self) -> bool {
454        self.conds.last().is_none_or(|c| c.live)
455    }
456
457    /// Expands a run of text lines and appends it to the output.
458    fn flush(
459        &mut self,
460        text: &mut Vec<Tok>,
461        out: &mut Vec<Tok>,
462        cx: &mut Context<'_>,
463        names: &Names,
464    ) {
465        if text.is_empty() {
466            return;
467        }
468        let taken = std::mem::take(text);
469        let expanded = self.expander.expand_toks(taken, &self.macros, cx.interner, cx.sources);
470        self.diagnostics.append(&mut self.expander.take_diagnostics());
471        // To GCC and clang the `__has_*` family are builtin macros rather than something the
472        // conditional parser knows about, so they answer in ordinary text too. After expansion
473        // and not before it, because a macro is allowed to expand to a call of one and because
474        // the operand is expanded first, which is what happens on a `#if` line as well.
475        let expanded = self.resolve_has(expanded, cx, names, Pass::Text);
476        self.pragma_operator(expanded, out, cx.interner, names);
477    }
478
479    /// Dispatches one directive. `body` is the line after the `#`.
480    fn directive(
481        &mut self,
482        body: &[PpToken],
483        hash: Span,
484        out: &mut Vec<Tok>,
485        cx: &mut Context<'_>,
486        names: &Names,
487    ) {
488        let Some(first) = body.first().copied() else {
489            return;
490        };
491        let name = ident_of(&first);
492        let rest = &body[1..];
493
494        // Conditionals are handled whether or not the region is live, because the nesting has
495        // to stay balanced through a skipped block.
496        if name == Some(names.r#if) {
497            let value = self.live() && self.eval(rest, hash, cx, names);
498            self.open(hash, value);
499            return;
500        }
501        if name == Some(names.ifdef) || name == Some(names.ifndef) {
502            let want = name == Some(names.ifdef);
503            let value = self.live() && self.defined_check(rest, hash, want, names);
504            self.open(hash, value);
505            return;
506        }
507        if name == Some(names.elif) || name == Some(names.elifdef) || name == Some(names.elifndef) {
508            self.elif(name, rest, hash, cx, names);
509            return;
510        }
511        if name == Some(names.r#else) {
512            self.branch_else(rest, hash);
513            return;
514        }
515        if name == Some(names.endif) {
516            self.endif(rest, hash);
517            return;
518        }
519        if !self.live() {
520            // Everything else inside a skipped region is text, not a directive. `#error` in
521            // the branch that was not taken must not fire, and `# 42 "f.c"` from another
522            // preprocessor must not be diagnosed.
523            return;
524        }
525
526        // A `#` and a number is a GNU line marker rather than a directive whose name happens to
527        // be missing, and it is what `-E` output is full of, so it is answered before anything
528        // asks what the directive is called.
529        if name.is_none() && decimal(&first, cx.interner).is_some() {
530            self.line_marker(body, hash, out.len(), cx);
531            return;
532        }
533
534        let interner = &mut *cx.interner;
535        if name == Some(names.define) {
536            let (def, diagnostics) = parse_define(rest, interner);
537            self.diagnostics.extend(diagnostics);
538            if let Some(def) = def {
539                if let Some(problem) = self.macros.define(def, interner) {
540                    self.diagnostics.push(problem);
541                }
542            }
543        } else if name == Some(names.undef) {
544            self.undef(rest, hash, interner);
545        } else if name == Some(names.error) || name == Some(names.warning) {
546            self.message(rest, hash, name == Some(names.error), interner);
547        } else if name == Some(names.line) {
548            self.line(rest, hash, out.len(), cx);
549        } else if name == Some(names.pragma) {
550            // `#pragma once` is answered here and does not reach the output, because it is a
551            // question about the file rather than something a later phase can act on.
552            // Everything else is passed through unchanged, which is what `-E` has to print
553            // and what a later phase looking for `#pragma pack` will read. Inventing an
554            // internal representation now, with no consumer, would only be a thing to
555            // migrate later.
556            if rest.len() == 1 && ident_of(&rest[0]) == Some(names.once) {
557                self.pragma_once(rest[0].span);
558            } else if !self.macro_stack_pragma(rest, hash, interner, names) {
559                self.pass_through(body, hash, out);
560            }
561        } else if name == Some(names.include) || name == Some(names.include_next) {
562            self.include(rest, hash, name == Some(names.include_next), out, cx, names);
563        } else if name == Some(names.embed) {
564            self.embed(rest, hash, out, cx);
565        } else {
566            self.diagnostics.push(
567                Diagnostic::error("invalid preprocessing directive", first.span).with_code("E0332"),
568            );
569        }
570    }
571
572    /// Answers `#pragma push_macro("X")` and `#pragma pop_macro("X")`, or says it is not one.
573    ///
574    /// These are the two pragmas that act on the macro table, so this phase is the only one that
575    /// can answer them, and like `#pragma once` they do not reach the output: gcc consumes them
576    /// and a later phase given one could not do anything with it. That is what clang's
577    /// `__clang_cuda_complex_builtins.h` needs, which pushes `__DEVICE__`, redefines it for the
578    /// file and pops it at the end.
579    ///
580    /// The `GCC` namespaced spelling is deliberately not accepted, because gcc does not accept
581    /// it either: `#pragma GCC push_macro("X")` is passed through and does nothing, and matching
582    /// that matters more than the spelling looking symmetric with the pragmas that do take it.
583    fn macro_stack_pragma(
584        &mut self,
585        rest: &[PpToken],
586        at: Span,
587        interner: &mut Interner,
588        names: &Names,
589    ) -> bool {
590        let which = match rest.first().and_then(ident_of) {
591            Some(name) if name == names.push_macro => names.push_macro,
592            Some(name) if name == names.pop_macro => names.pop_macro,
593            _ => return false,
594        };
595        let word = if which == names.push_macro { "push_macro" } else { "pop_macro" };
596        // Once the word is recognised the line is one of these whatever follows it, so a line
597        // that is not the shape is an error rather than something to pass through. gcc says the
598        // same thing, and warns about anything after the closing parenthesis the way it warns
599        // about anything after any other directive.
600        let [_, open, text, close, extra @ ..] = rest else {
601            self.invalid_pragma(word, at);
602            return true;
603        };
604        if open.punct() != Some(Punct::LParen)
605            || text.kind != PpTokenKind::StringLit
606            || close.punct() != Some(Punct::RParen)
607        {
608            self.invalid_pragma(word, at);
609            return true;
610        }
611        self.extra_tokens(extra, "#pragma");
612        // A string that does not spell one identifier names no macro, and gcc neither complains
613        // about it nor does anything with it. `push_macro("a b")` is quietly nothing, which is
614        // worth matching rather than improving on: a header that has one is a header that has
615        // been building against gcc for years.
616        let Some(name) = identifier_in(*text, interner) else {
617            return true;
618        };
619        if which == names.push_macro {
620            self.macros.push_macro(name);
621        } else {
622            self.macros.pop_macro(name);
623        }
624        true
625    }
626
627    fn invalid_pragma(&mut self, word: &str, at: Span) {
628        self.diagnostics.push(
629            Diagnostic::error(format!("invalid `#pragma {word}` directive"), at).with_code("E0672"),
630        );
631    }
632
633    /// Records that the file currently being read asked to be read only once.
634    fn pragma_once(&mut self, at: Span) {
635        // In the main file this is worth saying something about, since the file the user named
636        // is not one anything includes and the line usually means the user thought it was a
637        // header. It is still applied, because a file that includes itself is exactly where the
638        // line does work in a main file, and GCC both warns and applies it.
639        if self.stack.len() <= 1 {
640            self.diagnostics.push(
641                Diagnostic::warning("`#pragma once` in the main file", at).with_code("W0332"),
642            );
643        }
644        if let Some(frame) = self.stack.last() {
645            self.seen.insert(frame.id.clone(), Guard::Once);
646        }
647    }
648
649    /// Whether a file has already given everything it has to give.
650    fn skip(&self, id: &Path) -> bool {
651        match self.seen.get(id) {
652            Some(Guard::Once) => true,
653            Some(Guard::Macro(name)) => self.macros.is_defined(*name),
654            None => false,
655        }
656    }
657
658    /// Copies a directive line into the output, `#` included.
659    fn pass_through(&mut self, body: &[PpToken], hash: Span, out: &mut Vec<Tok>) {
660        let _ = self;
661        out.push(Tok::synthetic(
662            PpTokenKind::Punct(Punct::Hash),
663            None,
664            TokenFlags::START_OF_LINE,
665            hash,
666        ));
667        // The space between the hash and the word comes off, so that a directive written
668        // `#  pragma` inside a nest of conditionals, which is how glibc indents them, prints
669        // back as `#pragma`. gcc does the same, and the rest of the line keeps the spacing it
670        // was written with.
671        for (at, token) in body.iter().copied().enumerate() {
672            let mut token = Tok::new(token);
673            if at == 0 {
674                token.flags = token.flags.without(TokenFlags::LEADING_SPACE);
675            }
676            out.push(token);
677        }
678    }
679
680    /// Resolves an `#include` or `#include_next` and reads what it names.
681    fn include(
682        &mut self,
683        rest: &[PpToken],
684        hash: Span,
685        is_next: bool,
686        out: &mut Vec<Tok>,
687        cx: &mut Context<'_>,
688        names: &Names,
689    ) {
690        let Some(header) = self.header_of(rest, hash, cx) else {
691            return;
692        };
693        let (form, relative_to, from) = self.where_to_look(&header, is_next, cx);
694        let found = cx.search.resolve(cx.fs, &header.name, form, relative_to.as_deref(), from);
695        let Some(found) = found else {
696            let tried = cx.search.tried(&header.name, form, relative_to.as_deref(), from);
697            self.not_found(&header.name, hash, &tried, cx.search.missing_system());
698            return;
699        };
700        self.read(found, hash, out, cx, names);
701    }
702
703    /// Reports an include of a file that is not anywhere the search looked.
704    ///
705    /// `why` is whatever the driver left on the search path about the target's own directories being
706    /// absent, which is the other half of the answer when the path is empty. It is a note rather
707    /// than the message because the message is about this include and the reason is about the
708    /// machine, and a program that includes nothing never asks.
709    fn not_found(&mut self, name: &str, at: Span, tried: &[PathBuf], why: Option<&str>) {
710        // Two ways to have looked nowhere. An absolute name is opened and not searched for,
711        // and a search path with nothing on it has nowhere to look. Saying the first when it
712        // was the second sends the reader after a path that is not there.
713        let where_looked = if tried.is_empty() && Path::new(name).is_absolute() {
714            "the name is an absolute path, so the search path was not used".to_owned()
715        } else if tried.is_empty() {
716            "the include search path is empty".to_owned()
717        } else {
718            let list: Vec<String> =
719                tried.iter().map(|d| d.to_string_lossy().into_owned()).collect();
720            format!("searched: {}", list.join(", "))
721        };
722        let mut said = Diagnostic::error(format!("`{name}` file not found"), at)
723            .with_code("E0341")
724            .note(where_looked, at);
725        if let Some(why) = why {
726            said = said.note(why, at);
727        }
728        self.diagnostics.push(said);
729    }
730
731    /// Reads the file a finished search named, appending what it produces to `out`.
732    ///
733    /// The half of an include that is about the file rather than about the directive, so that the
734    /// files `-include` and `-imacros` name go through it as well. They are includes with no
735    /// directive to parse, and everything from here down is what makes one an include: the
736    /// dependency record, the guard optimization, the depth limit and the frame.
737    fn read(
738        &mut self,
739        found: Found,
740        at: Span,
741        out: &mut Vec<Tok>,
742        cx: &mut Context<'_>,
743        names: &Names,
744    ) {
745        let id = cx.fs.identity(&found.path);
746        // Recorded before anything below can turn the include away, because every one of those
747        // refusals is about reading the file again rather than about whether the file is one
748        // this translation unit was built from. A header the guard optimization skips is still
749        // a header that, if it changed, would change the output.
750        if self.dep_ids.insert(id.clone()) {
751            // The `.` components come out, which is what GCC writes and is measured: `-I./d`
752            // gives a prerequisite of `d/f.h` there while the line marker and `__FILE__` for the
753            // same header both say `./d/f.h`. The two answers are to two different questions. A
754            // marker names the file the way the search reached it, which is what a debugger and
755            // a `#line` are about, and a prerequisite names a file `make` has to compare a
756            // timestamp against, which the leading `./` says nothing about.
757            let path = rucc_session::path_key(&found.path);
758            self.deps.push(Dependency { path, is_system: found.is_system });
759        }
760        // The multiple-include optimization. A file wrapped in an include guard whose macro
761        // is now defined, or one that asked for `#pragma once`, would produce nothing, so it
762        // is not opened at all. On a real code base this is the difference between reading a
763        // header once and reading it a few hundred times.
764        if self.skip(&id) {
765            return;
766        }
767        if self.stack.len() >= cx.max_include_depth as usize {
768            let mut diagnostic = Diagnostic::error("`#include` nested too deeply", at)
769                .with_code("E0342")
770                .note("a header that includes itself with no include guard is the usual cause", at);
771            if let Some(outer) = self.stack.first().filter(|f| !f.at.is_dummy()) {
772                diagnostic = diagnostic.note("the outermost include is here", outer.at);
773            }
774            self.diagnostics.push(diagnostic);
775            return;
776        }
777        let added = cx.sources.add_shared(found.name.clone(), found.bytes.clone(), Some(at));
778        let file = match added {
779            Ok(file) => file,
780            Err(full) => {
781                self.diagnostics.push(Diagnostic::error(full.to_string(), at).with_code("E0344"));
782                return;
783            }
784        };
785        self.stack.push(Frame {
786            at,
787            dir: found.path.parent().map(Path::to_path_buf),
788            id,
789            path: found.path,
790            next: found.next,
791        });
792        self.process(file, out, cx, names);
793        self.stack.pop();
794    }
795
796    /// Reads an `#embed` and puts the bytes of what it names into the output.
797    fn embed(&mut self, rest: &[PpToken], hash: Span, out: &mut Vec<Tok>, cx: &mut Context<'_>) {
798        let Some((header, params)) = self.embed_line(rest, hash, cx) else {
799            return;
800        };
801        let Some(found) = self.find(&header, false, cx) else {
802            self.diagnostics.push(
803                Diagnostic::error(format!("`{}` resource not found", header.name), hash)
804                    .with_code("E0341")
805                    .note("an `#embed` resource is looked for on the include path", hash),
806            );
807            return;
808        };
809        // The bytes are not added to the source map. Nothing will ever point a diagnostic
810        // into the middle of a PNG, and adding a few megabytes of binary to the map so that
811        // it can be sliced for a caret line nobody will print is the kind of cost that only
812        // shows up on the projects this directive exists for.
813        embed::tokens(found.bytes.as_slice(), &params, hash, cx.interner, out);
814    }
815
816    /// Splits an `#embed` line into the resource it names and the parameters after it.
817    fn embed_line(
818        &mut self,
819        rest: &[PpToken],
820        hash: Span,
821        cx: &mut Context<'_>,
822    ) -> Option<(Header, embed::Params)> {
823        if rest.is_empty() {
824            self.bad_header(hash);
825            return None;
826        }
827        let line: Vec<Tok> = rest.iter().copied().map(Tok::new).collect();
828        // A name the lexer already made a header name of is not expanded, exactly as with
829        // `#include`. A computed one has the whole line expanded, parameters included, which
830        // is a compromise: the end of the name cannot be found without expanding, and the
831        // parameter names would have to be found before expanding to protect them. A macro
832        // called `limit` in scope at an `#embed` is not a thing worth splitting the pass for.
833        let line = if line[0].kind == PpTokenKind::HeaderName {
834            line
835        } else {
836            let expanded = self.expander.expand_toks(line, &self.macros, cx.interner, cx.sources);
837            self.diagnostics.append(&mut self.expander.take_diagnostics());
838            expanded
839        };
840        let Some(used) = embed::header_length(&line) else {
841            self.bad_header(line.first().map_or(hash, |t| t.report_span()));
842            return None;
843        };
844        let header = if line[0].kind == PpTokenKind::HeaderName {
845            header_from_token(spelling(line[0], cx.interner))
846        } else {
847            let spellings: Vec<&str> =
848                line[..used].iter().map(|t| spelling(*t, cx.interner)).collect();
849            header_from_tokens(&spellings)
850        };
851        let Some(header) = header else {
852            self.bad_header(line[0].report_span());
853            return None;
854        };
855        let params = self.embed_params(&line[used..], hash, cx)?;
856        Some((header, params))
857    }
858
859    /// The parameter list of an `#embed`, or of the `__has_embed` that asks the same question.
860    fn embed_params(
861        &mut self,
862        line: &[Tok],
863        at: Span,
864        cx: &mut Context<'_>,
865    ) -> Option<embed::Params> {
866        let Preprocessor { expander, macros, diagnostics, .. } = self;
867        let sources = &mut *cx.sources;
868        let mut expand = |toks: Vec<Tok>, interner: &mut Interner| {
869            expander.expand_toks(toks, macros, interner, sources)
870        };
871        let params = embed::parse(line, at, cx.interner, diagnostics, &mut expand);
872        self.diagnostics.append(&mut self.expander.take_diagnostics());
873        params
874    }
875
876    /// Where a header written in the file being read is looked for.
877    ///
878    /// `#include_next` continues from the directory after the one the current file came from,
879    /// which is what glibc and the kernel use to wrap a system header with one of the same
880    /// name. It never looks next to the current file, because that directory is not on the
881    /// path and there would be nothing to continue past.
882    ///
883    /// `__has_include` has to ask the same question the directive would, so both go through
884    /// here. A header that answers yes and then fails to be found is the one outcome that
885    /// would make the operator useless.
886    fn where_to_look(
887        &self,
888        header: &Header,
889        is_next: bool,
890        cx: &Context<'_>,
891    ) -> (IncludeForm, Option<PathBuf>, usize) {
892        let form = if header.angled { IncludeForm::Angled } else { IncludeForm::Quoted };
893        let frame = self.stack.last();
894        let from = if is_next {
895            frame.map_or(0, |f| f.next).max(cx.search.start(form))
896        } else {
897            cx.search.start(form)
898        };
899        let relative_to = if is_next { None } else { frame.and_then(|f| f.dir.clone()) };
900        (form, relative_to, from)
901    }
902
903    /// Whether a header is there, which is all `__has_include` asks.
904    fn find(&self, header: &Header, is_next: bool, cx: &Context<'_>) -> Option<Found> {
905        let (form, relative_to, from) = self.where_to_look(header, is_next, cx);
906        cx.search.resolve(cx.fs, &header.name, form, relative_to.as_deref(), from)
907    }
908
909    /// The header name an include directive names, however it spelled it.
910    fn header_of(&mut self, rest: &[PpToken], hash: Span, cx: &mut Context<'_>) -> Option<Header> {
911        if let Some(first) = rest.first().copied() {
912            if first.kind == PpTokenKind::HeaderName {
913                let text = first.value.map_or("", |v| cx.interner.resolve(v));
914                let header = header_from_token(text);
915                if header.is_none() {
916                    self.bad_header(first.span);
917                }
918                self.extra_tokens(&rest[1..], "#include");
919                return header;
920            }
921        }
922        // The computed include, `#include MACRO`. The line is macro expanded and then has to
923        // look like a header name, which is the one place in the language where the spelling
924        // of a token matters after expansion.
925        if rest.is_empty() {
926            self.bad_header(hash);
927            return None;
928        }
929        let line: Vec<Tok> = rest.iter().copied().map(Tok::new).collect();
930        let expanded = self.expander.expand_toks(line, &self.macros, cx.interner, cx.sources);
931        self.diagnostics.append(&mut self.expander.take_diagnostics());
932        let spellings: Vec<&str> = expanded.iter().map(|t| spelling(*t, cx.interner)).collect();
933        let header = header_from_tokens(&spellings);
934        if header.is_none() {
935            let at = expanded.first().map_or(hash, |t| t.report_span());
936            self.bad_header(at);
937        }
938        header
939    }
940
941    /// The diagnostic for a `__has_*` operator whose operand is not an identifier.
942    fn bad_operand(&mut self, tok: Tok, at: Span, interner: &Interner) {
943        self.diagnostics.push(
944            Diagnostic::error(
945                format!("expected an identifier as the operand of `{}`", spelling(tok, interner)),
946                at,
947            )
948            .with_code("E0345"),
949        );
950    }
951
952    fn bad_header(&mut self, at: Span) {
953        self.diagnostics.push(
954            Diagnostic::error("expected a file name in `<>` or `\"\"`", at).with_code("E0343"),
955        );
956    }
957
958    /// Pushes a conditional whose first branch is or is not taken.
959    fn open(&mut self, span: Span, value: bool) {
960        let enclosing_live = self.live();
961        self.conds.push(Cond {
962            span,
963            live: enclosing_live && value,
964            taken: value,
965            enclosing_live,
966            seen_else: false,
967        });
968    }
969
970    fn elif(
971        &mut self,
972        name: Option<Symbol>,
973        rest: &[PpToken],
974        hash: Span,
975        cx: &mut Context<'_>,
976        names: &Names,
977    ) {
978        let Some(top) = self.conds.last() else {
979            self.stray("elif", hash);
980            return;
981        };
982        if top.seen_else {
983            self.diagnostics
984                .push(Diagnostic::error("`#elif` after `#else`", hash).with_code("E0333"));
985            return;
986        }
987        // Read what is needed before evaluating, because evaluation borrows the whole
988        // preprocessor to report into.
989        let (enclosing_live, already_taken) = (top.enclosing_live, top.taken);
990        let consider = enclosing_live && !already_taken;
991        let value = if !consider {
992            false
993        } else if name == Some(names.elif) {
994            self.eval(rest, hash, cx, names)
995        } else {
996            self.defined_check(rest, hash, name == Some(names.elifdef), names)
997        };
998        let top = self.conds.last_mut().expect("checked above and nothing popped");
999        top.live = consider && value;
1000        top.taken = already_taken || value;
1001    }
1002
1003    fn branch_else(&mut self, rest: &[PpToken], hash: Span) {
1004        let Some(top) = self.conds.last_mut() else {
1005            self.stray("else", hash);
1006            return;
1007        };
1008        if top.seen_else {
1009            self.diagnostics.push(Diagnostic::error("a second `#else`", hash).with_code("E0333"));
1010            return;
1011        }
1012        top.live = top.enclosing_live && !top.taken;
1013        top.taken = true;
1014        top.seen_else = true;
1015        let enclosing_live = top.enclosing_live;
1016        if enclosing_live {
1017            self.extra_tokens(rest, "#else");
1018        }
1019    }
1020
1021    fn endif(&mut self, rest: &[PpToken], hash: Span) {
1022        if self.conds.pop().is_none() {
1023            self.stray("endif", hash);
1024            return;
1025        }
1026        if self.live() {
1027            self.extra_tokens(rest, "#endif");
1028        }
1029    }
1030
1031    fn stray(&mut self, what: &str, hash: Span) {
1032        self.diagnostics
1033            .push(Diagnostic::error(format!("`#{what}` without `#if`"), hash).with_code("E0334"));
1034    }
1035
1036    /// Warns about tokens after a directive that takes none.
1037    ///
1038    /// A warning rather than an error, because `#endif FOO` as a hand written comment is
1039    /// everywhere in code written before `//` was portable.
1040    fn extra_tokens(&mut self, rest: &[PpToken], what: &str) {
1041        if let Some(first) = rest.first() {
1042            self.diagnostics.push(
1043                Diagnostic::warning(format!("extra tokens after `{what}`"), first.span)
1044                    .with_code("W0330"),
1045            );
1046        }
1047    }
1048
1049    /// Evaluates a `#if` or `#elif` expression.
1050    fn eval(&mut self, rest: &[PpToken], hash: Span, cx: &mut Context<'_>, names: &Names) -> bool {
1051        let line: Vec<Tok> = rest.iter().copied().map(Tok::new).collect();
1052        // `defined X` is resolved before expansion, so that `#if defined FOO` does not depend
1053        // on what `FOO` expands to. It is resolved again afterwards because a macro that
1054        // expands to `defined(X)` is undefined behaviour that GCC supports and headers use.
1055        // It goes first of all because `defined(__has_include)` is a question about the
1056        // operator rather than a use of it.
1057        let line = self.resolve_defined(line, cx.interner, names);
1058        // `__has_include` is resolved before expansion too, and for a stronger reason: its
1059        // operand is a header name, so expanding `<linux/version.h>` would turn `linux` into
1060        // `1` on a target where that macro is predefined. The rest of the family take an
1061        // identifier that GCC does expand, so they wait until afterwards.
1062        let line = self.resolve_has(line, cx, names, Pass::Headers);
1063        let line = self.expander.expand_toks(line, &self.macros, cx.interner, cx.sources);
1064        self.diagnostics.append(&mut self.expander.take_diagnostics());
1065        let line = self.resolve_defined(line, cx.interner, names);
1066        let line = self.resolve_has(line, cx, names, Pass::Rest);
1067        cond::evaluate(&line, cx.interner, &mut self.diagnostics, hash)
1068    }
1069
1070    /// Replaces `__has_include(<x.h>)` and the rest of the family with what they answer.
1071    ///
1072    /// `pass` says which of the three positions is asking, and each of them answers a
1073    /// different part of the family. See [`Pass`].
1074    fn resolve_has(
1075        &mut self,
1076        line: Vec<Tok>,
1077        cx: &mut Context<'_>,
1078        names: &Names,
1079        pass: Pass,
1080    ) -> Vec<Tok> {
1081        if !line.iter().any(|t| t.ident().is_some_and(|n| names.has.op(n).is_some())) {
1082            return line;
1083        }
1084        let mut out = Vec::with_capacity(line.len());
1085        let mut at = 0;
1086        while at < line.len() {
1087            let tok = line[at];
1088            let op = tok.ident().and_then(|n| names.has.op(n));
1089            let Some(op) = op.filter(|op| pass.answers(*op)) else {
1090                if pass == Pass::Text && op.is_some_and(Op::is_header) {
1091                    self.outside_a_directive(tok, cx);
1092                }
1093                out.push(tok);
1094                at += 1;
1095                continue;
1096            };
1097            let Some((operand, after)) = arguments(&line, at + 1) else {
1098                // Reported in the pass after expansion and not in the one before it, because
1099                // the operator is still there for that pass to find and one mistake is one
1100                // diagnostic.
1101                if pass != Pass::Headers {
1102                    self.diagnostics.push(
1103                        Diagnostic::error(
1104                            format!("expected `(` after `{}`", spelling(tok, cx.interner)),
1105                            tok.report_span(),
1106                        )
1107                        .with_code("E0345"),
1108                    );
1109                }
1110                out.push(tok);
1111                at += 1;
1112                continue;
1113            };
1114            at = after;
1115            // A number rather than a flag, because `__has_c_attribute` answers with the value
1116            // the standard gives the attribute and a header compares that against a date.
1117            let value = self.ask(op, operand, tok, cx);
1118            let sym = cx.interner.intern(&value.to_string());
1119            out.push(Tok::synthetic(PpTokenKind::Number, Some(sym), tok.flags, tok.report_span()));
1120        }
1121        out
1122    }
1123
1124    /// Refuses one of the header operators used in ordinary text.
1125    ///
1126    /// Their operand is a header name, and outside a directive the line was scanned as
1127    /// ordinary tokens, so `<stdio.h>` arrived as a chain of comparisons that no longer says
1128    /// which of the two it was meant to be. GCC and clang both refuse it for that reason, and
1129    /// a program that wants the answer in text can put the operator in a `#if` and define a
1130    /// macro from it, which is what every header that needs one does anyway.
1131    fn outside_a_directive(&mut self, tok: Tok, cx: &Context<'_>) {
1132        self.diagnostics.push(
1133            Diagnostic::error(
1134                format!(
1135                    "`{}` used outside of a preprocessing directive",
1136                    spelling(tok, cx.interner)
1137                ),
1138                tok.report_span(),
1139            )
1140            .with_code("E0350"),
1141        );
1142    }
1143
1144    /// What one `__has_*` operator answers for one operand.
1145    fn ask(&mut self, op: Op, operand: &[Tok], tok: Tok, cx: &mut Context<'_>) -> u32 {
1146        let at = operand.first().map_or(tok.report_span(), |t| t.report_span());
1147        match op {
1148            Op::Include | Op::IncludeNext => {
1149                let spellings: Vec<&str> =
1150                    operand.iter().map(|t| spelling(*t, cx.interner)).collect();
1151                let Some(header) = header_from_tokens(&spellings) else {
1152                    self.bad_header(at);
1153                    return 0;
1154                };
1155                u32::from(self.find(&header, op == Op::IncludeNext, cx).is_some())
1156            }
1157            Op::Embed => {
1158                // Three answers, and the third one is the reason the operator exists. A
1159                // resource that is present but empty cannot be told from one that is missing
1160                // by a yes or no, and the two need different code: the empty one still needs
1161                // its `if_empty` written, the missing one needs a fallback.
1162                let Some(used) = embed::header_length(operand) else {
1163                    self.bad_header(at);
1164                    return 0;
1165                };
1166                let header = if operand[0].kind == PpTokenKind::HeaderName {
1167                    header_from_token(spelling(operand[0], cx.interner))
1168                } else {
1169                    let spellings: Vec<&str> =
1170                        operand[..used].iter().map(|t| spelling(*t, cx.interner)).collect();
1171                    header_from_tokens(&spellings)
1172                };
1173                let Some(header) = header else {
1174                    self.bad_header(at);
1175                    return 0;
1176                };
1177                // The parameters are read even though only `limit` and `gnu::offset` can
1178                // change the answer, because a misspelled parameter is the same mistake here
1179                // as it is on the directive and finding it only on the directive would mean
1180                // the guard passes and the embed it guards fails.
1181                let Some(params) = self.embed_params(&operand[used..], at, cx) else {
1182                    return 0;
1183                };
1184                match self.find(&header, false, cx) {
1185                    None => 0,
1186                    Some(found) => {
1187                        let taken = params.taken(found.bytes.as_slice().len() as u64);
1188                        if taken == 0 { 2 } else { 1 }
1189                    }
1190                }
1191            }
1192            Op::BuildingModule => {
1193                if attribute_name(operand, cx.interner).is_none() {
1194                    self.bad_operand(tok, at, cx.interner);
1195                }
1196                // Clang answers this with one only while it is compiling the module named
1197                // here, and we do not have modules, so the answer is always no. It is
1198                // recognised rather than left alone because clang's own `stddef.h` asks it
1199                // inside an `#if`, and an unknown identifier there leaves the parenthesised
1200                // operand behind as extra tokens, which fails the whole line rather than the
1201                // one operator.
1202                0
1203            }
1204            Op::Table(kind) => {
1205                let Some(name) = attribute_name(operand, cx.interner) else {
1206                    self.bad_operand(tok, at, cx.interner);
1207                    return 0;
1208                };
1209                match kind {
1210                    Kind::Attribute => rucc_gnu::has_attribute(name),
1211                    Kind::CAttribute => rucc_gnu::has_c_attribute(name),
1212                    Kind::Builtin => rucc_gnu::has_builtin(name),
1213                    Kind::Feature => rucc_gnu::has_feature(name),
1214                    Kind::Extension => rucc_gnu::has_extension(name),
1215                }
1216            }
1217        }
1218    }
1219
1220    /// Replaces `defined X` and `defined(X)` with `1` or `0`.
1221    fn resolve_defined(
1222        &mut self,
1223        line: Vec<Tok>,
1224        interner: &mut Interner,
1225        names: &Names,
1226    ) -> Vec<Tok> {
1227        if !line.iter().any(|t| t.ident() == Some(names.defined)) {
1228            return line;
1229        }
1230        let mut out = Vec::with_capacity(line.len());
1231        let mut at = 0;
1232        while at < line.len() {
1233            let tok = line[at];
1234            if tok.ident() != Some(names.defined) {
1235                out.push(tok);
1236                at += 1;
1237                continue;
1238            }
1239            let parenthesised = line.get(at + 1).is_some_and(|t| t.is(Punct::LParen));
1240            let name_at = if parenthesised { at + 2 } else { at + 1 };
1241            let name = line.get(name_at).and_then(|t| t.ident());
1242            let Some(name) = name else {
1243                self.diagnostics.push(
1244                    Diagnostic::error("`defined` without a macro name", tok.report_span())
1245                        .with_code("E0335"),
1246                );
1247                out.push(tok);
1248                at += 1;
1249                continue;
1250            };
1251            at = name_at + 1;
1252            if parenthesised {
1253                if line.get(at).is_some_and(|t| t.is(Punct::RParen)) {
1254                    at += 1;
1255                } else {
1256                    self.diagnostics.push(
1257                        Diagnostic::error("expected `)` after `defined`", tok.report_span())
1258                            .with_code("E0335"),
1259                    );
1260                }
1261            }
1262            // A header asks `#ifdef __has_include` before using it, because the operator is
1263            // newer than some of the compilers it has to build under. It is not a macro, but
1264            // the question being asked is whether the name means something, and it does.
1265            let value = self.macros.is_defined(name) || names.has.op(name).is_some();
1266            out.push(number(value, tok.flags, tok.report_span(), interner));
1267        }
1268        out
1269    }
1270
1271    /// The body of `#ifdef`, `#ifndef`, `#elifdef` and `#elifndef`.
1272    fn defined_check(
1273        &mut self,
1274        rest: &[PpToken],
1275        hash: Span,
1276        want_defined: bool,
1277        names: &Names,
1278    ) -> bool {
1279        let Some(name) = rest.first().and_then(ident_of) else {
1280            self.diagnostics.push(
1281                Diagnostic::error("expected a macro name", rest.first().map_or(hash, |t| t.span))
1282                    .with_code("E0336"),
1283            );
1284            return false;
1285        };
1286        self.extra_tokens(&rest[1..], if want_defined { "#ifdef" } else { "#ifndef" });
1287        let defined = self.macros.is_defined(name) || names.has.op(name).is_some();
1288        defined == want_defined
1289    }
1290
1291    fn undef(&mut self, rest: &[PpToken], hash: Span, interner: &Interner) {
1292        let Some(name) = rest.first().and_then(ident_of) else {
1293            self.diagnostics.push(
1294                Diagnostic::error("expected a macro name", rest.first().map_or(hash, |t| t.span))
1295                    .with_code("E0336"),
1296            );
1297            return;
1298        };
1299        // The standard reserves these and GCC refuses to let them go, because code that
1300        // undefines `__FILE__` and then uses it is broken in a way that is very hard to see.
1301        let text = interner.resolve(name);
1302        if text == "defined" || text.starts_with("__STDC_") {
1303            self.diagnostics.push(
1304                Diagnostic::error(format!("`{text}` cannot be undefined"), rest[0].span)
1305                    .with_code("E0337"),
1306            );
1307            return;
1308        }
1309        self.macros.undef(name);
1310        self.extra_tokens(&rest[1..], "#undef");
1311    }
1312
1313    /// `#error` and `#warning`. The message is the rest of the line, spelled back.
1314    fn message(&mut self, rest: &[PpToken], hash: Span, fatal: bool, interner: &Interner) {
1315        let text = spell_line(rest, interner);
1316        let span = rest.first().map_or(hash, |t| t.span.to(last_span(rest)));
1317        let diag = if fatal {
1318            Diagnostic::error(text, span).with_code("E0338")
1319        } else {
1320            Diagnostic::warning(text, span).with_code("W0331")
1321        };
1322        self.diagnostics.push(diag);
1323    }
1324
1325    /// `#line 42` and `#line 42 "file.c"`.
1326    ///
1327    /// The argument is macro expanded first, which is the one place a directive other than
1328    /// `#if` does that, and which exists because `#line __LINE__ + 1` is real code.
1329    fn line(&mut self, rest: &[PpToken], hash: Span, at: usize, cx: &mut Context<'_>) {
1330        let line: Vec<Tok> = rest.iter().copied().map(Tok::new).collect();
1331        let line = self.expander.expand_toks(line, &self.macros, cx.interner, cx.sources);
1332        self.diagnostics.append(&mut self.expander.take_diagnostics());
1333        let interner = &mut *cx.interner;
1334
1335        let number_text = line
1336            .first()
1337            .filter(|t| t.kind == PpTokenKind::Number)
1338            .and_then(|t| t.value)
1339            .map(|v| interner.resolve(v));
1340        let Some(parsed) = number_text.and_then(|t| t.parse::<u64>().ok()) else {
1341            self.diagnostics.push(
1342                Diagnostic::error(
1343                    "`#line` needs a decimal line number",
1344                    line.first().map_or(hash, |t| t.report_span()),
1345                )
1346                .with_code("E0339"),
1347            );
1348            return;
1349        };
1350        // 2147483647 is the largest line number the standard requires support for, and it is
1351        // also where every other compiler stops, so matching that keeps diagnostics comparable.
1352        if parsed == 0 || parsed > 2_147_483_647 {
1353            self.diagnostics.push(
1354                Diagnostic::error("`#line` number is out of range", line[0].report_span())
1355                    .with_code("E0339"),
1356            );
1357            return;
1358        }
1359
1360        let mut file = None;
1361        if let Some(second) = line.get(1) {
1362            if second.kind == PpTokenKind::StringLit {
1363                file = second.value;
1364            } else {
1365                self.diagnostics.push(
1366                    Diagnostic::error(
1367                        "`#line` file name must be a string literal",
1368                        second.report_span(),
1369                    )
1370                    .with_code("E0339"),
1371                );
1372                return;
1373            }
1374        }
1375        if let Some(extra) = line.get(2) {
1376            self.diagnostics.push(
1377                Diagnostic::warning("extra tokens after `#line`", extra.report_span())
1378                    .with_code("W0330"),
1379            );
1380        }
1381        #[expect(
1382            clippy::cast_possible_truncation,
1383            reason = "the range check above keeps this inside i32, let alone u32"
1384        )]
1385        let number = parsed as u32;
1386        self.lines.push(LineDirective { span: hash, line: number, file, at });
1387        let name = file.map(|v| destringize(cx.interner.resolve(v)));
1388        cx.sources.set_presumed(hash.lo, number, name);
1389    }
1390
1391    /// A GNU line marker: `# 42`, `# 42 "file.c"`, and either of those with flags after it.
1392    ///
1393    /// This is the form `-E` writes, so a preprocessed file handed back to the compiler is full
1394    /// of them, and a compiler that cannot read its own output is not much of a compiler. The
1395    /// directive is a `#` and a number rather than a `#` and a name, which is why it arrives
1396    /// here having failed to be anything else.
1397    ///
1398    /// It is `#line` with three differences. Nothing is macro expanded, because the tokens came
1399    /// from a preprocessor rather than from a person. Zero is a line number, since a generator
1400    /// counting from zero is allowed to say so and `#line 0` is an error only because somebody
1401    /// wrote it. And there may be flags: `1` for entering a file, `2` for returning from one,
1402    /// `3` for a system header and `4` for one whose contents are `extern "C"`. The last two
1403    /// say nothing this phase acts on. The first two are the nesting, and a `2` that does not
1404    /// name the file it claims to be returning to is ignored with a warning rather than
1405    /// applied, which is what gcc does and is the only honest answer to a marker set that does
1406    /// not describe a nesting anything was ever in.
1407    fn line_marker(&mut self, body: &[PpToken], hash: Span, at: usize, cx: &mut Context<'_>) {
1408        let Some(number) = decimal(&body[0], cx.interner) else { return };
1409        let mut rest = &body[1..];
1410        let mut file = None;
1411        if let Some(first) = rest.first().filter(|t| t.kind == PpTokenKind::StringLit) {
1412            file = first.value;
1413            rest = &rest[1..];
1414        }
1415
1416        let (mut entering, mut leaving) = (false, false);
1417        for flag in rest {
1418            match decimal(flag, cx.interner) {
1419                Some(1) => entering = true,
1420                Some(2) => leaving = true,
1421                Some(3 | 4) => {}
1422                _ => {
1423                    let text = spell_line(std::slice::from_ref(flag), cx.interner);
1424                    self.diagnostics.push(
1425                        Diagnostic::error(
1426                            format!("invalid flag `{text}` in line directive"),
1427                            flag.span,
1428                        )
1429                        .with_code("E0339"),
1430                    );
1431                    return;
1432                }
1433            }
1434        }
1435
1436        let name = file.map(|v| destringize(cx.interner.resolve(v)));
1437        if leaving {
1438            if let Some(name) = &name {
1439                if !self.leave_marker(name) {
1440                    self.diagnostics.push(
1441                        Diagnostic::warning(
1442                            format!("file `{name}` linemarker ignored due to incorrect nesting"),
1443                            last_span(body),
1444                        )
1445                        .with_code("W0330"),
1446                    );
1447                    return;
1448                }
1449            } else {
1450                self.markers.pop();
1451            }
1452        }
1453        if entering {
1454            let here = cx.sources.presumed(hash.lo).map(|loc| loc.name.to_owned());
1455            self.markers.push(here.unwrap_or_default());
1456        }
1457
1458        self.lines.push(LineDirective { span: hash, line: number, file, at });
1459        cx.sources.set_presumed(hash.lo, number, name);
1460    }
1461
1462    /// Unwinds the marker nesting to `name`, saying whether it was in it at all.
1463    ///
1464    /// GCC asks whether the file being returned to is the one directly outside, and this asks
1465    /// whether it is anywhere outside, because a marker set is generated and a generator that
1466    /// leaves out a return marker is common. Every `-E` that writes markers where its tokens
1467    /// are rather than where its files change writes such a set, this compiler's own included,
1468    /// since a header that contributes no tokens between two `#include` lines never gets a
1469    /// marker of its own. Answering that with a warning on every file would make the warning
1470    /// noise, and the nesting it describes is still enough to say what a `2` means.
1471    ///
1472    /// A name in neither the markers nor the real include stack is the one that is refused.
1473    /// That is the marker set that describes a nesting nothing was ever in, and gcc refuses it
1474    /// too, so `# 200 "xyz" 2` written at the top of a file is a warning in both compilers.
1475    fn leave_marker(&mut self, name: &str) -> bool {
1476        if let Some(at) = self.markers.iter().rposition(|outer| outer == name) {
1477            self.markers.truncate(at);
1478            return true;
1479        }
1480        // A marker set may begin partway down a real nesting it did not open, which is what a
1481        // header full of them looks like when it is included rather than compiled on its own.
1482        let found = self.stack.iter().rev().skip(1).any(|f| f.path.as_os_str() == name);
1483        if found {
1484            self.markers.clear();
1485        }
1486        found
1487    }
1488
1489    /// Applies the `_Pragma` operator to an expanded run and appends the result.
1490    ///
1491    /// `_Pragma("x")` is a pragma written as an expression, which is what makes a pragma
1492    /// usable from inside a macro. It is handled after expansion because the string it takes
1493    /// is very often produced by one.
1494    fn pragma_operator(
1495        &mut self,
1496        expanded: Vec<Tok>,
1497        out: &mut Vec<Tok>,
1498        interner: &mut Interner,
1499        names: &Names,
1500    ) {
1501        if !expanded.iter().any(|t| t.ident() == Some(names.pragma_op)) {
1502            out.extend(expanded);
1503            return;
1504        }
1505        let mut at = 0;
1506        // A pragma is a line, so whatever comes after one has to start a line, even when the
1507        // source wrote `_Pragma("x") int y;` all on one. Without this the `int` would read as
1508        // part of the pragma to anything that takes the line as the unit, which is what the
1509        // phase that turns these into tokens does.
1510        let mut ends_a_line = false;
1511        while at < expanded.len() {
1512            let mut tok = expanded[at];
1513            if tok.ident() != Some(names.pragma_op) {
1514                if ends_a_line {
1515                    tok.flags = tok.flags.with(TokenFlags::START_OF_LINE);
1516                    ends_a_line = false;
1517                }
1518                out.push(tok);
1519                at += 1;
1520                continue;
1521            }
1522            let open = expanded.get(at + 1).is_some_and(|t| t.is(Punct::LParen));
1523            let text = expanded.get(at + 2).filter(|t| t.kind == PpTokenKind::StringLit);
1524            let close = expanded.get(at + 3).is_some_and(|t| t.is(Punct::RParen));
1525            let (Some(text), true, true) = (text, open, close) else {
1526                self.diagnostics.push(
1527                    Diagnostic::error("`_Pragma` takes a single string literal", tok.report_span())
1528                        .with_code("E0340"),
1529                );
1530                out.push(tok);
1531                at += 1;
1532                continue;
1533            };
1534            let literal = text.value.map(|v| interner.resolve(v)).unwrap_or_default();
1535            let body = destringize(literal);
1536            self.emit_pragma(&body, tok, out, interner, names);
1537            ends_a_line = true;
1538            at += 4;
1539        }
1540    }
1541
1542    /// Turns destringized `_Pragma` text into the `# pragma ...` tokens a later phase reads.
1543    fn emit_pragma(
1544        &mut self,
1545        body: &str,
1546        at: Tok,
1547        out: &mut Vec<Tok>,
1548        interner: &mut Interner,
1549        names: &Names,
1550    ) {
1551        let span = at.report_span();
1552        let (tokens, diagnostics) = tokenize(body.as_bytes(), 0, Options::new(), interner);
1553        // The text came out of a string literal, so a span into it would point at bytes the
1554        // user cannot see. Every token reports at the `_Pragma` instead.
1555        self.diagnostics.extend(
1556            diagnostics
1557                .into_iter()
1558                .map(|d| Diagnostic::new(d.severity, d.message, span).with_code("E0340")),
1559        );
1560        let tokens: Vec<PpToken> = tokens.into_iter().filter(|t| !t.is_eof()).collect();
1561        // `_Pragma("push_macro(\"X\")")` is the same pragma written the other way, and the two
1562        // spellings have to mean the same thing because a macro that wants to save a name has no
1563        // other way to say it: a `#pragma` line cannot come out of a macro body.
1564        if self.macro_stack_pragma(&tokens, span, interner, names) {
1565            return;
1566        }
1567        out.push(Tok::synthetic(
1568            PpTokenKind::Punct(Punct::Hash),
1569            None,
1570            TokenFlags::START_OF_LINE,
1571            span,
1572        ));
1573        out.push(Tok::synthetic(PpTokenKind::Ident, Some(names.pragma), TokenFlags::EMPTY, span));
1574        // The tokens keep the spacing they were written with inside the string, so
1575        // `_Pragma("pack(push)")` prints back as `pack(push)` rather than `pack ( push )`.
1576        // Only the first one is forced apart, from the `pragma` before it.
1577        for (at, t) in tokens.into_iter().enumerate() {
1578            // Start of line has to come off: the line is the `#pragma` we just emitted, not
1579            // the inside of the string these came from.
1580            let spaced = at == 0 || t.flags.has(TokenFlags::LEADING_SPACE);
1581            let flags = if spaced {
1582                TokenFlags::EMPTY.with(TokenFlags::LEADING_SPACE)
1583            } else {
1584                TokenFlags::EMPTY
1585            };
1586            out.push(Tok::synthetic(t.kind, t.value, flags, span));
1587        }
1588    }
1589}
1590
1591/// The macro a file's opening line guards the whole file with, if the line has that shape.
1592///
1593/// `#ifndef NAME` and both spellings of `#if !defined NAME`, which between them are what
1594/// every header in glibc, musl and the kernel is wrapped in.
1595fn guard_opener(body: &[PpToken], names: &Names) -> Option<Symbol> {
1596    let name = ident_of(body.first()?)?;
1597    let rest = &body[1..];
1598    if name == names.ifndef {
1599        let [only] = rest else {
1600            return None;
1601        };
1602        return ident_of(only);
1603    }
1604    if name != names.r#if {
1605        return None;
1606    }
1607    let [bang, defined, tail @ ..] = rest else {
1608        return None;
1609    };
1610    if bang.punct() != Some(Punct::Bang) || ident_of(defined) != Some(names.defined) {
1611        return None;
1612    }
1613    match tail {
1614        [only] => ident_of(only),
1615        [open, only, close]
1616            if open.punct() == Some(Punct::LParen) && close.punct() == Some(Punct::RParen) =>
1617        {
1618            ident_of(only)
1619        }
1620        _ => None,
1621    }
1622}
1623
1624/// Whether a directive name is one that may be followed by a header name.
1625fn is_include(name: Option<Symbol>, names: &Names) -> bool {
1626    name == Some(names.include) || name == Some(names.include_next) || name == Some(names.embed)
1627}
1628
1629/// Whether this token opens a directive line.
1630fn is_directive(tok: PpToken) -> bool {
1631    tok.flags.has(TokenFlags::START_OF_LINE) && tok.punct() == Some(Punct::Hash)
1632}
1633
1634fn ident_of(tok: &PpToken) -> Option<Symbol> {
1635    match tok.kind {
1636        PpTokenKind::Ident => tok.value,
1637        _ => None,
1638    }
1639}
1640
1641fn last_span(tokens: &[PpToken]) -> Span {
1642    tokens.last().map_or(Span::DUMMY, |t| t.span)
1643}
1644
1645/// The value of `tok` when it is a plain decimal number a line can be called.
1646///
1647/// A preprocessing number is a wider thing than a number: `1.5`, `0x10` and `1f` are all one,
1648/// and none of them is a line. Nothing but digits is accepted, so `# 1.5` stays what it was
1649/// before this existed, which is a directive nobody recognises.
1650fn decimal(tok: &PpToken, interner: &Interner) -> Option<u32> {
1651    if tok.kind != PpTokenKind::Number {
1652        return None;
1653    }
1654    let text = interner.resolve(tok.value?);
1655    if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) {
1656        return None;
1657    }
1658    // 2147483647 is the largest line number the standard requires support for, and it is also
1659    // where every other compiler stops, so matching that keeps diagnostics comparable.
1660    text.parse::<u32>().ok().filter(|n| *n <= 2_147_483_647)
1661}
1662
1663/// A synthetic `1` or `0`.
1664fn number(value: bool, flags: TokenFlags, span: Span, interner: &mut Interner) -> Tok {
1665    let sym = interner.intern(if value { "1" } else { "0" });
1666    Tok::synthetic(PpTokenKind::Number, Some(sym), flags, span)
1667}
1668
1669/// Spells a directive's tokens back for an `#error` message.
1670fn spell_line(tokens: &[PpToken], interner: &Interner) -> String {
1671    let mut out = String::new();
1672    for (index, tok) in tokens.iter().enumerate() {
1673        if index > 0 && tok.flags.has(TokenFlags::LEADING_SPACE) {
1674            out.push(' ');
1675        }
1676        match tok.value {
1677            Some(sym) => out.push_str(interner.resolve(sym)),
1678            None => {
1679                if let Some(p) = tok.punct() {
1680                    out.push_str(p.as_str());
1681                }
1682            }
1683        }
1684    }
1685    out
1686}
1687
1688/// The single identifier a string literal spells, if that is all it spells.
1689///
1690/// The name a `push_macro` saves lives inside a string, so it is destringized and lexed rather
1691/// than read off a token. Anything that is not exactly one identifier names no macro.
1692fn identifier_in(text: PpToken, interner: &mut Interner) -> Option<Symbol> {
1693    let literal = interner.resolve(text.value?).to_string();
1694    let (tokens, _) = tokenize(destringize(&literal).as_bytes(), 0, Options::new(), interner);
1695    let mut real = tokens.into_iter().filter(|t| !t.is_eof());
1696    let first = real.next()?;
1697    if first.kind != PpTokenKind::Ident || real.next().is_some() {
1698        return None;
1699    }
1700    first.value
1701}
1702
1703/// Undoes what `#` would have done, per C23 6.10.10.
1704///
1705/// The `L` or `u8` prefix and the quotes come off, then `\"` becomes `"` and `\\` becomes `\`.
1706/// No other escape is touched, because no other escape was introduced.
1707fn destringize(literal: &str) -> String {
1708    let body = literal
1709        .trim_start_matches(['L', 'u', 'U', '8'])
1710        .strip_prefix('"')
1711        .and_then(|s| s.strip_suffix('"'))
1712        .unwrap_or(literal);
1713    let mut out = String::with_capacity(body.len());
1714    let mut chars = body.chars();
1715    while let Some(c) = chars.next() {
1716        if c != '\\' {
1717            out.push(c);
1718            continue;
1719        }
1720        match chars.next() {
1721            Some('"') => out.push('"'),
1722            Some('\\') => out.push('\\'),
1723            Some(other) => {
1724                out.push('\\');
1725                out.push(other);
1726            }
1727            None => out.push('\\'),
1728        }
1729    }
1730    out
1731}
1732
1733/// The parenthesised operand of a `__has_*` operator, and where the line carries on.
1734///
1735/// `None` when the next token is not `(`, which is the only shape the operators take. Nesting
1736/// is counted rather than stopping at the first `)`, so that `__has_include(HEADER(x))` after
1737/// expansion still finds the end of its own operand.
1738fn arguments(line: &[Tok], at: usize) -> Option<(&[Tok], usize)> {
1739    if !line.get(at)?.is(Punct::LParen) {
1740        return None;
1741    }
1742    let mut depth = 1u32;
1743    let mut end = at + 1;
1744    while end < line.len() {
1745        if line[end].is(Punct::LParen) {
1746            depth += 1;
1747        } else if line[end].is(Punct::RParen) {
1748            depth -= 1;
1749            if depth == 0 {
1750                return Some((&line[at + 1..end], end + 1));
1751            }
1752        }
1753        end += 1;
1754    }
1755    None
1756}
1757
1758/// The name `__has_attribute` and its relatives are asked about.
1759///
1760/// A bare identifier, or the scoped form `gnu::always_inline` that C23 gives the attributes
1761/// that came from GCC. The scope is dropped: `__has_c_attribute(gnu::x)` and
1762/// `__has_attribute(x)` are the same question, and the matrix has one row for it.
1763fn attribute_name<'i>(operand: &[Tok], interner: &'i Interner) -> Option<&'i str> {
1764    let name = match operand {
1765        [one] => one,
1766        [_, scope, name] if scope.is(Punct::ColonColon) => name,
1767        _ => return None,
1768    };
1769    name.ident().map(|sym| interner.resolve(sym))
1770}
1771
1772/// Which of the three sweeps over a line is resolving the `__has_*` operators.
1773///
1774/// A `#if` line is swept twice, once either side of macro expansion, because the two halves of
1775/// the family disagree about whether their operand may be expanded. A text line is swept once,
1776/// after expansion, and the half whose operand is a header name is refused there rather than
1777/// answered.
1778#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1779enum Pass {
1780    /// Before expansion on a directive line, where only the header operators are answered.
1781    Headers,
1782    /// After expansion on a directive line, where everything left over is answered. That
1783    /// includes a header operator, which reaches here when a macro expanded to one.
1784    Rest,
1785    /// After expansion on a text line, where everything but the header operators is answered.
1786    Text,
1787}
1788
1789impl Pass {
1790    /// Whether this sweep is the one that answers `op`.
1791    fn answers(self, op: Op) -> bool {
1792        match self {
1793            Pass::Headers => op.is_header(),
1794            Pass::Rest => true,
1795            Pass::Text => !op.is_header(),
1796        }
1797    }
1798}
1799
1800/// Which `__has_*` operator a name is, and what answers it.
1801#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1802enum Op {
1803    /// `__has_include`, answered by looking for the header.
1804    Include,
1805    /// `__has_include_next`, the same question from further down the search path.
1806    IncludeNext,
1807    /// `__has_embed`, which answers with three values rather than two because a resource that
1808    /// exists and is empty is a case the program has to be able to tell apart.
1809    Embed,
1810    /// `__building_module`, which is always no because there are no modules.
1811    BuildingModule,
1812    /// The rest of the family, answered out of the matrix in `rucc-gnu`.
1813    Table(Kind),
1814}
1815
1816impl Op {
1817    /// Whether the operand is a header name, which must not be macro expanded.
1818    fn is_header(self) -> bool {
1819        matches!(self, Op::Include | Op::IncludeNext | Op::Embed)
1820    }
1821}
1822
1823/// The `__has_*` operators, interned once per file.
1824///
1825/// A short array rather than a map: there are nine of them, the comparison is on interned
1826/// symbols, and it is only reached for a line that mentions one.
1827struct HasOps {
1828    ops: [(Symbol, Op); 9],
1829    /// The lowest and the highest symbol in `ops`.
1830    ///
1831    /// Now that text lines are swept too, every identifier in the translation unit is offered
1832    /// to [`HasOps::op`], so the answer it almost always gives has to be cheap. These nine are
1833    /// interned before any file is read, so a name out of the source sorts above the range and
1834    /// one comparison turns it away.
1835    range: (Symbol, Symbol),
1836}
1837
1838impl HasOps {
1839    fn new(interner: &mut Interner) -> HasOps {
1840        let ops = [
1841            (interner.intern("__has_include"), Op::Include),
1842            (interner.intern("__has_include_next"), Op::IncludeNext),
1843            (interner.intern("__has_embed"), Op::Embed),
1844            (interner.intern("__has_attribute"), Op::Table(Kind::Attribute)),
1845            (interner.intern("__has_c_attribute"), Op::Table(Kind::CAttribute)),
1846            (interner.intern("__has_builtin"), Op::Table(Kind::Builtin)),
1847            (interner.intern("__has_feature"), Op::Table(Kind::Feature)),
1848            (interner.intern("__has_extension"), Op::Table(Kind::Extension)),
1849            (interner.intern("__building_module"), Op::BuildingModule),
1850        ];
1851        let mut range = (ops[0].0, ops[0].0);
1852        for &(sym, _) in &ops {
1853            range = (range.0.min(sym), range.1.max(sym));
1854        }
1855        HasOps { ops, range }
1856    }
1857
1858    /// The operator a name is, if it is one.
1859    #[inline]
1860    fn op(&self, name: Symbol) -> Option<Op> {
1861        if name < self.range.0 || name > self.range.1 {
1862            return None;
1863        }
1864        self.ops.iter().find(|(sym, _)| *sym == name).map(|(_, op)| *op)
1865    }
1866}
1867
1868/// The directive names and the two operators, interned once per file.
1869///
1870/// Comparing symbols rather than strings is the point: a directive line is recognised with
1871/// integer comparisons, and the identifiers were interned during the scan, so there is no
1872/// string work in the hot path.
1873struct Names {
1874    define: Symbol,
1875    undef: Symbol,
1876    r#if: Symbol,
1877    ifdef: Symbol,
1878    ifndef: Symbol,
1879    elif: Symbol,
1880    elifdef: Symbol,
1881    elifndef: Symbol,
1882    r#else: Symbol,
1883    endif: Symbol,
1884    line: Symbol,
1885    error: Symbol,
1886    warning: Symbol,
1887    pragma: Symbol,
1888    include: Symbol,
1889    include_next: Symbol,
1890    embed: Symbol,
1891    defined: Symbol,
1892    once: Symbol,
1893    push_macro: Symbol,
1894    pop_macro: Symbol,
1895    pragma_op: Symbol,
1896    has: HasOps,
1897}
1898
1899impl Names {
1900    fn new(interner: &mut Interner) -> Names {
1901        Names {
1902            define: interner.intern("define"),
1903            undef: interner.intern("undef"),
1904            r#if: interner.intern("if"),
1905            ifdef: interner.intern("ifdef"),
1906            ifndef: interner.intern("ifndef"),
1907            elif: interner.intern("elif"),
1908            elifdef: interner.intern("elifdef"),
1909            elifndef: interner.intern("elifndef"),
1910            r#else: interner.intern("else"),
1911            endif: interner.intern("endif"),
1912            line: interner.intern("line"),
1913            error: interner.intern("error"),
1914            warning: interner.intern("warning"),
1915            pragma: interner.intern("pragma"),
1916            include: interner.intern("include"),
1917            include_next: interner.intern("include_next"),
1918            embed: interner.intern("embed"),
1919            defined: interner.intern("defined"),
1920            once: interner.intern("once"),
1921            push_macro: interner.intern("push_macro"),
1922            pop_macro: interner.intern("pop_macro"),
1923            pragma_op: interner.intern("_Pragma"),
1924            has: HasOps::new(interner),
1925        }
1926    }
1927}
1928
1929#[cfg(test)]
1930mod tests {
1931    use rucc_diag::{Severity, SourceMap};
1932    use rucc_session::{MemoryFileSystem, SearchPath};
1933
1934    use super::*;
1935    use rucc_session::Std;
1936
1937    use crate::predef::Timestamp;
1938
1939    /// A whole file through phase 4, which is what almost every test here wants.
1940    ///
1941    /// The main file is always `/main.c`, so a quoted include with no search path set up
1942    /// finds a header the test put at `/name.h`.
1943    /// Any spelling of a path as forward slashes, doubled backslashes included, since a name this
1944    /// compiler built by joining a directory to a header holds the host's own separator and
1945    /// `__FILE__` escapes a backslash.
1946    fn slashes(text: &str) -> String {
1947        text.replace("\\\\", "/").replace('\\', "/")
1948    }
1949
1950    struct Run {
1951        interner: Interner,
1952        sources: SourceMap,
1953        fs: MemoryFileSystem,
1954        search: SearchPath,
1955        pp: Preprocessor,
1956    }
1957
1958    impl Run {
1959        fn new() -> Run {
1960            Run {
1961                interner: Interner::new(),
1962                sources: SourceMap::new(),
1963                fs: MemoryFileSystem::new(),
1964                search: SearchPath::new(),
1965                pp: Preprocessor::new(),
1966            }
1967        }
1968
1969        /// The same, with the `-fmacro-prefix-map=` rewrites `map` names, oldest first.
1970        fn mapping(map: &[(&str, &str)]) -> Run {
1971            let mut list = PrefixMap::new();
1972            for (old, new) in map {
1973                list.push(*old, *new);
1974            }
1975            Run { pp: Preprocessor::with_prefix_map(list), ..Run::new() }
1976        }
1977
1978        /// Puts a header where an include can find it.
1979        fn file(&mut self, path: &str, contents: &str) {
1980            self.fs.insert(path, contents.as_bytes().to_vec());
1981        }
1982
1983        /// Puts a resource where an `#embed` can find it. Bytes rather than text, because the
1984        /// whole point of the directive is the files that are not text.
1985        fn bytes(&mut self, path: &str, contents: &[u8]) {
1986            self.fs.insert(path, contents.to_vec());
1987        }
1988
1989        /// Adds a directory to the `-I` part of the search path.
1990        fn dir(&mut self, path: &str) {
1991            self.search.push_bracket(path);
1992        }
1993
1994        /// Defines the predefined set for a target, as the driver does before reading input.
1995        fn predefine(&mut self, triple: &str, opts: &Predef) {
1996            let target = TargetInfo::new(triple.parse().expect("a supported triple"));
1997            let mut cx =
1998                Context::new(&mut self.interner, &mut self.sources, &self.fs, &self.search);
1999            self.pp.predefine(&target, opts, &mut cx).expect("the map has room");
2000        }
2001
2002        /// The surviving tokens, spelled with one space wherever they were separated.
2003        fn go(&mut self, src: &str) -> String {
2004            self.go_named("/main.c", src)
2005        }
2006
2007        /// The surviving tokens themselves, for a test about a flag rather than a spelling.
2008        fn raw(&mut self, src: &str) -> Vec<Tok> {
2009            let file = self.sources.add("/main.c", src.as_bytes().to_vec()).expect("room");
2010            let mut cx =
2011                Context::new(&mut self.interner, &mut self.sources, &self.fs, &self.search);
2012            self.pp.run(file, &mut cx)
2013        }
2014
2015        /// Reads what `-imacros` and `-include` named, as the driver does before the source file.
2016        fn preinclude(&mut self, files: &[Preinclude]) -> String {
2017            let mut out = Vec::new();
2018            {
2019                let mut cx =
2020                    Context::new(&mut self.interner, &mut self.sources, &self.fs, &self.search);
2021                self.pp.preinclude(files, &mut out, &mut cx).expect("the map has room");
2022            }
2023            self.spell(&out)
2024        }
2025
2026        /// The same, for a test that cares what the main file is called.
2027        fn go_named(&mut self, path: &str, src: &str) -> String {
2028            let file = self.sources.add(path, src.as_bytes().to_vec()).expect("the map has room");
2029            let out = {
2030                let mut cx =
2031                    Context::new(&mut self.interner, &mut self.sources, &self.fs, &self.search);
2032                self.pp.run(file, &mut cx)
2033            };
2034            self.spell(&out)
2035        }
2036
2037        /// A run of tokens as text, with one space wherever they were separated.
2038        fn spell(&self, out: &[Tok]) -> String {
2039            let mut text = String::new();
2040            for (at, tok) in out.iter().enumerate() {
2041                let spaced = tok.flags.has(TokenFlags::LEADING_SPACE)
2042                    || tok.flags.has(TokenFlags::START_OF_LINE);
2043                if at > 0 && spaced {
2044                    text.push(' ');
2045                }
2046                match tok.kind {
2047                    PpTokenKind::Punct(p) => text.push_str(p.as_str()),
2048                    _ => text.push_str(
2049                        self.interner.resolve(tok.value.expect("every non-punctuator interns")),
2050                    ),
2051                }
2052            }
2053            text
2054        }
2055
2056        /// How many files were opened, main file included. A header that the guard
2057        /// optimization skipped never reaches the source map, so this is what says whether
2058        /// it was really skipped rather than read and thrown away.
2059        fn files(&self) -> usize {
2060            self.sources.files().len()
2061        }
2062
2063        fn messages(&mut self) -> Vec<String> {
2064            self.pp.take_diagnostics().into_iter().map(|d| d.message).collect()
2065        }
2066
2067        fn severities(&mut self) -> Vec<Severity> {
2068            self.pp.diagnostics().iter().map(|d| d.severity).collect()
2069        }
2070    }
2071
2072    fn clean(src: &str) -> String {
2073        let mut run = Run::new();
2074        let text = run.go(src);
2075        assert!(run.messages().is_empty(), "expected no diagnostics from {src:?}");
2076        text
2077    }
2078
2079    #[test]
2080    fn a_taken_branch_is_kept_and_the_other_is_not() {
2081        assert_eq!(clean("#if 1\nyes\n#else\nno\n#endif\n"), "yes");
2082        assert_eq!(clean("#if 0\nyes\n#else\nno\n#endif\n"), "no");
2083    }
2084
2085    #[test]
2086    fn ifdef_and_ifndef_ask_the_macro_table() {
2087        assert_eq!(clean("#define F 1\n#ifdef F\nyes\n#endif\n"), "yes");
2088        assert_eq!(clean("#ifdef F\nyes\n#endif\n"), "");
2089        assert_eq!(clean("#ifndef F\nyes\n#endif\n"), "yes");
2090        // C23 spells the two of them as `#elifdef` and `#elifndef` as well.
2091        assert_eq!(clean("#define F 1\n#if 0\na\n#elifdef F\nb\n#endif\n"), "b");
2092        assert_eq!(clean("#if 0\na\n#elifndef F\nb\n#endif\n"), "b");
2093    }
2094
2095    #[test]
2096    fn only_the_first_true_branch_of_a_chain_is_taken() {
2097        assert_eq!(clean("#if 0\na\n#elif 1\nb\n#elif 1\nc\n#else\nd\n#endif\n"), "b");
2098        assert_eq!(clean("#if 0\na\n#elif 0\nb\n#else\nc\n#endif\n"), "c");
2099    }
2100
2101    #[test]
2102    fn a_branch_after_one_that_was_taken_is_not_evaluated() {
2103        // `1/0` in a branch that cannot be reached is legal, and headers rely on it: the
2104        // guard that made the branch dead is often the thing that made the expression safe.
2105        assert_eq!(clean("#if 1\na\n#elif 1/0\nb\n#endif\n"), "a");
2106    }
2107
2108    #[test]
2109    fn a_skipped_region_is_not_read_for_anything_but_nesting() {
2110        // Prose, an unknown directive and a broken `#define` all have to pass silently.
2111        let src = "#if 0\nthis is not C at all\n#frobnicate\n#define\n#if 1\ninner\n#endif\n#endif\nafter\n";
2112        assert_eq!(clean(src), "after");
2113    }
2114
2115    #[test]
2116    fn nesting_inside_a_dead_branch_stays_balanced() {
2117        let src = "#if 0\n#ifdef X\na\n#else\nb\n#endif\n#else\nc\n#endif\n";
2118        assert_eq!(clean(src), "c");
2119    }
2120
2121    #[test]
2122    fn defined_works_in_both_spellings_and_before_expansion() {
2123        assert_eq!(clean("#define F 0\n#if defined F\nyes\n#endif\n"), "yes");
2124        assert_eq!(clean("#define F 0\n#if defined(F)\nyes\n#endif\n"), "yes");
2125        assert_eq!(clean("#if defined(F)\nyes\n#endif\n"), "");
2126        // `F` expands to 0, but `defined F` is answered before that happens, which is the
2127        // whole reason `defined` is resolved in a pass of its own.
2128        assert_eq!(clean("#define F 0\n#if defined F && !F\nyes\n#endif\n"), "yes");
2129    }
2130
2131    #[test]
2132    fn an_identifier_that_survived_expansion_is_zero() {
2133        assert_eq!(clean("#if NOT_DEFINED_ANYWHERE\nyes\n#else\nno\n#endif\n"), "no");
2134        assert_eq!(clean("#if !NOT_DEFINED_ANYWHERE\nyes\n#endif\n"), "yes");
2135    }
2136
2137    #[test]
2138    fn short_circuiting_keeps_a_guarded_expression_safe() {
2139        // The reason `&&` has to short circuit rather than merely produce the right answer:
2140        // the right hand side divides by zero when the guard is false.
2141        assert_eq!(clean("#if defined(F) && 1/F\nyes\n#else\nno\n#endif\n"), "no");
2142        assert_eq!(clean("#if 1 ? 2 : 1/0\nyes\n#endif\n"), "yes");
2143    }
2144
2145    #[test]
2146    fn the_operators_have_the_precedence_they_do_in_c() {
2147        assert_eq!(clean("#if 1 + 2 * 3 == 7\nyes\n#endif\n"), "yes");
2148        assert_eq!(clean("#if (1 + 2) * 3 == 9\nyes\n#endif\n"), "yes");
2149        assert_eq!(clean("#if 1 << 4 == 16\nyes\n#endif\n"), "yes");
2150        assert_eq!(clean("#if -8 / 3 == -2\nyes\n#endif\n"), "yes");
2151        assert_eq!(clean("#if (0xff & 0x0f) == 15\nyes\n#endif\n"), "yes");
2152    }
2153
2154    #[test]
2155    fn an_unsigned_operand_makes_the_whole_comparison_unsigned() {
2156        // The rule that catches everyone out in C catches them out here too, and a
2157        // preprocessor that quietly disagreed with the compiler would be worse than one that
2158        // is merely surprising.
2159        assert_eq!(clean("#if -1 < 0u\nyes\n#else\nno\n#endif\n"), "no");
2160        assert_eq!(clean("#if -1 < 0\nyes\n#else\nno\n#endif\n"), "yes");
2161    }
2162
2163    #[test]
2164    fn character_constants_evaluate() {
2165        assert_eq!(clean("#if 'A' == 65\nyes\n#endif\n"), "yes");
2166        assert_eq!(clean("#if '\\n' == 10\nyes\n#endif\n"), "yes");
2167    }
2168
2169    #[test]
2170    fn a_macro_is_expanded_before_the_expression_is_evaluated() {
2171        assert_eq!(clean("#define V 3\n#if V > 2\nyes\n#endif\n"), "yes");
2172        assert_eq!(clean("#define M(a) ((a) * 2)\n#if M(3) == 6\nyes\n#endif\n"), "yes");
2173    }
2174
2175    #[test]
2176    fn an_invocation_may_span_lines_within_a_run_of_text() {
2177        assert_eq!(clean("#define M(a, b) a + b\nM(1,\n2)\n"), "1 + 2");
2178    }
2179
2180    #[test]
2181    fn undef_removes_a_definition() {
2182        assert_eq!(clean("#define F 1\n#undef F\n#ifdef F\nyes\n#else\nno\n#endif\n"), "no");
2183        // Undefining something that was never defined is not an error, and configure scripts
2184        // emit it constantly.
2185        assert_eq!(clean("#undef NEVER_DEFINED\nok\n"), "ok");
2186    }
2187
2188    #[test]
2189    fn some_names_cannot_be_undefined() {
2190        let mut run = Run::new();
2191        run.go("#undef defined\n");
2192        assert_eq!(run.messages(), vec!["`defined` cannot be undefined".to_owned()]);
2193    }
2194
2195    #[test]
2196    fn error_reports_the_rest_of_the_line() {
2197        let mut run = Run::new();
2198        run.go("#if 0\n#error not this one\n#else\n#error unsupported target\n#endif\n");
2199        assert_eq!(run.messages(), vec!["unsupported target".to_owned()]);
2200    }
2201
2202    #[test]
2203    fn warning_is_a_warning() {
2204        let mut run = Run::new();
2205        run.go("#warning this is fine\n");
2206        assert_eq!(run.severities(), vec![Severity::Warning]);
2207        assert_eq!(run.messages(), vec!["this is fine".to_owned()]);
2208    }
2209
2210    #[test]
2211    fn an_unterminated_conditional_is_reported() {
2212        let mut run = Run::new();
2213        assert_eq!(run.go("#if 1\nyes\n"), "yes");
2214        assert_eq!(run.messages(), vec!["unterminated `#if`".to_owned()]);
2215    }
2216
2217    #[test]
2218    fn a_conditional_without_an_if_is_reported() {
2219        let mut run = Run::new();
2220        run.go("#endif\n");
2221        assert_eq!(run.messages(), vec!["`#endif` without `#if`".to_owned()]);
2222
2223        let mut run = Run::new();
2224        run.go("#if 1\n#else\n#else\n#endif\n");
2225        assert_eq!(run.messages(), vec!["a second `#else`".to_owned()]);
2226
2227        let mut run = Run::new();
2228        run.go("#if 1\n#else\n#elif 1\n#endif\n");
2229        assert_eq!(run.messages(), vec!["`#elif` after `#else`".to_owned()]);
2230    }
2231
2232    #[test]
2233    fn tokens_after_endif_are_a_warning_rather_than_an_error() {
2234        // `#endif FOO` as a hand written comment predates `//` being portable and there is a
2235        // great deal of it about. Refusing to compile it would be correct and useless.
2236        let mut run = Run::new();
2237        assert_eq!(run.go("#if 1\nyes\n#endif FOO\n"), "yes");
2238        assert_eq!(run.severities(), vec![Severity::Warning]);
2239        assert_eq!(run.messages(), vec!["extra tokens after `#endif`".to_owned()]);
2240    }
2241
2242    #[test]
2243    fn the_null_directive_does_nothing() {
2244        assert_eq!(clean("#\na\n#\nb\n"), "a b");
2245    }
2246
2247    #[test]
2248    fn an_unknown_directive_is_an_error_when_the_region_is_live() {
2249        let mut run = Run::new();
2250        run.go("#frobnicate\n");
2251        assert_eq!(run.messages(), vec!["invalid preprocessing directive".to_owned()]);
2252    }
2253
2254    #[test]
2255    fn line_is_recorded_for_the_source_map() {
2256        let mut run = Run::new();
2257        run.go("#line 42 \"other.c\"\n");
2258        assert!(run.messages().is_empty());
2259        let recorded = run.pp.line_directives();
2260        assert_eq!(recorded.len(), 1);
2261        assert_eq!(recorded[0].line, 42);
2262        let file = recorded[0].file.expect("a file name was given");
2263        assert_eq!(run.interner.resolve(file), "\"other.c\"");
2264    }
2265
2266    #[test]
2267    fn line_moves_what_line_and_file_the_lines_after_it_are_on() {
2268        let mut run = Run::new();
2269        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
2270        assert_eq!(run.go("#line 1000\n__LINE__ __FILE__\n__LINE__\n"), "1000 \"/main.c\" 1001");
2271    }
2272
2273    #[test]
2274    fn a_line_marker_moves_the_lines_after_it_the_way_line_does() {
2275        let mut run = Run::new();
2276        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
2277        assert_eq!(run.go("# 200 \"xyz\"\n__FILE__ __LINE__\n"), "\"xyz\" 200");
2278    }
2279
2280    #[test]
2281    fn a_line_marker_with_no_name_leaves_the_name_alone() {
2282        let mut run = Run::new();
2283        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
2284        assert_eq!(run.go("# 20\n__FILE__ __LINE__\n"), "\"/main.c\" 20");
2285    }
2286
2287    #[test]
2288    fn a_line_marker_may_say_line_zero() {
2289        // `#line 0` is an error and this is not, because a marker is written by a program and a
2290        // program counting from zero is allowed to say so.
2291        let mut run = Run::new();
2292        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
2293        assert_eq!(run.go("# 0 \"xyz\"\n__LINE__\n"), "0");
2294    }
2295
2296    #[test]
2297    fn entering_and_returning_are_a_nesting_the_marker_flags_keep() {
2298        let mut run = Run::new();
2299        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
2300        let text =
2301            run.go("# 200 \"xyz\" 1\n__FILE__\n# 5 \"/main.c\" 2\n__FILE__ __LINE__\n# 9 3 4\n");
2302        assert_eq!(text, "\"xyz\" \"/main.c\" 5");
2303        assert!(run.messages().is_empty());
2304    }
2305
2306    #[test]
2307    fn returning_to_a_file_nothing_was_ever_in_is_ignored() {
2308        let mut run = Run::new();
2309        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
2310        assert_eq!(run.go("# 200 \"xyz\" 2 3\n__FILE__ __LINE__\n"), "\"/main.c\" 2");
2311        assert_eq!(
2312            run.messages(),
2313            vec!["file `xyz` linemarker ignored due to incorrect nesting".to_owned()]
2314        );
2315    }
2316
2317    #[test]
2318    fn a_flag_that_is_not_one_of_the_four_is_an_error() {
2319        let mut run = Run::new();
2320        run.go("# 20 \"a\" 7\n");
2321        assert_eq!(run.messages(), vec!["invalid flag `7` in line directive".to_owned()]);
2322    }
2323
2324    #[test]
2325    fn a_hash_and_something_that_is_not_a_line_number_is_still_an_unknown_directive() {
2326        // A preprocessing number is a wider thing than a number, and `1.5` is one of them.
2327        let mut run = Run::new();
2328        run.go("# 1.5 \"a\"\n");
2329        assert_eq!(run.messages(), vec!["invalid preprocessing directive".to_owned()]);
2330    }
2331
2332    #[test]
2333    fn a_name_on_the_directive_is_the_name_from_there_on() {
2334        let mut run = Run::new();
2335        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
2336        assert_eq!(run.go("#line 7 \"gen.y\"\n__FILE__ __LINE__\n"), "\"gen.y\" 7");
2337    }
2338
2339    #[test]
2340    fn a_directive_with_no_name_keeps_the_one_already_in_force() {
2341        let mut run = Run::new();
2342        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
2343        assert_eq!(run.go("#line 7 \"gen.y\"\n#line 20\n__FILE__ __LINE__\n"), "\"gen.y\" 20");
2344    }
2345
2346    #[test]
2347    fn the_number_is_expanded_first_because_line_plus_one_is_real_code() {
2348        let mut run = Run::new();
2349        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
2350        assert_eq!(run.go("#define WHERE 300\n#line WHERE\n__LINE__\n"), "300");
2351    }
2352
2353    #[test]
2354    fn a_directive_in_a_header_does_not_move_the_file_that_included_it() {
2355        let mut run = Run::new();
2356        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
2357        run.file("/h.h", "#line 500\n__LINE__\n");
2358        run.dir("/");
2359        assert_eq!(run.go("#include <h.h>\n__LINE__\n"), "500 2");
2360    }
2361
2362    #[test]
2363    fn extra_tokens_after_the_file_name_are_a_warning_and_not_an_error() {
2364        let mut run = Run::new();
2365        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
2366        assert_eq!(run.go("#line 7 \"gen.y\" and more\n__LINE__\n"), "7");
2367        assert_eq!(run.messages(), vec!["extra tokens after `#line`".to_owned()]);
2368    }
2369
2370    #[test]
2371    fn a_line_number_out_of_range_is_refused() {
2372        let mut run = Run::new();
2373        run.go("#line 0\n");
2374        assert_eq!(run.messages(), vec!["`#line` number is out of range".to_owned()]);
2375
2376        let mut run = Run::new();
2377        run.go("#line notanumber\n");
2378        assert_eq!(run.messages(), vec!["`#line` needs a decimal line number".to_owned()]);
2379    }
2380
2381    #[test]
2382    fn a_pragma_passes_through_unchanged() {
2383        assert_eq!(clean("#pragma pack(1)\nint x;\n"), "#pragma pack(1) int x;");
2384    }
2385
2386    /// glibc indents a directive inside a nest of conditionals, one space per level, so
2387    /// `regex.h` writes `# pragma GCC diagnostic push`. gcc prints it back with the space
2388    /// gone, and a header preprocessed two ways that differ only there is a difference
2389    /// somebody has to read before deciding it does not matter.
2390    #[test]
2391    fn the_space_between_the_hash_and_the_word_comes_off_a_pragma_that_is_indented() {
2392        assert_eq!(clean("#if 1\n# pragma pack(1)\n#endif\n"), "#pragma pack(1)");
2393        assert_eq!(clean("#  pragma  pack( 1 )\n"), "#pragma pack( 1 )", "the rest is kept");
2394    }
2395
2396    #[test]
2397    fn the_pragma_operator_becomes_a_pragma() {
2398        assert_eq!(
2399            clean("_Pragma(\"GCC visibility push(default)\")\nint x;\n"),
2400            "#pragma GCC visibility push(default) int x;"
2401        );
2402    }
2403
2404    #[test]
2405    fn the_pragma_operator_works_from_inside_a_macro() {
2406        // This is the entire reason `_Pragma` exists: a `#pragma` cannot be written in a macro
2407        // body, so a header that wants to wrap one has no other option.
2408        let src = "#define PUSH _Pragma(\"pack(push)\")\nPUSH\nint x;\n";
2409        assert_eq!(clean(src), "#pragma pack(push) int x;");
2410    }
2411
2412    /// A pragma is a line even when it was written as an expression, so whatever follows one
2413    /// has to start a line. The phase that turns these back into a record takes the line as
2414    /// its unit, and without this the `int` would be read as part of the pragma.
2415    #[test]
2416    fn what_follows_a_pragma_operator_starts_a_line() {
2417        let mut run = Run::new();
2418        let out = run.raw("int x; _Pragma(\"pack(1)\") int y;\n");
2419        let starts: Vec<_> =
2420            out.iter().map(|tok| tok.flags.has(TokenFlags::START_OF_LINE)).collect();
2421        // `int x ;` then the six the pragma became, then `int y ;`. Only the first `int` was
2422        // at the start of a line in the source, and the second one is now.
2423        assert_eq!(
2424            starts,
2425            vec![true, false, false, true, false, false, false, false, false, true, false, false]
2426        );
2427    }
2428
2429    #[test]
2430    fn a_pragma_operator_that_is_not_given_a_string_is_reported() {
2431        let mut run = Run::new();
2432        run.go("_Pragma(x)\n");
2433        assert_eq!(run.messages(), vec!["`_Pragma` takes a single string literal".to_owned()]);
2434    }
2435
2436    #[test]
2437    fn an_include_reads_the_file_it_names() {
2438        let mut run = Run::new();
2439        run.file("/dir/one.h", "int from_the_header;\n");
2440        run.dir("/dir");
2441        assert_eq!(run.go("#include <one.h>\nint after;\n"), "int from_the_header; int after;");
2442        assert!(run.messages().is_empty());
2443    }
2444
2445    #[test]
2446    fn a_quoted_include_looks_next_to_the_including_file_first() {
2447        let mut run = Run::new();
2448        run.file("/local.h", "beside\n");
2449        run.file("/dir/local.h", "on the path\n");
2450        run.dir("/dir");
2451        assert_eq!(run.go("#include \"local.h\"\n"), "beside");
2452        assert!(run.messages().is_empty());
2453    }
2454
2455    #[test]
2456    fn an_angled_include_does_not_look_next_to_the_including_file() {
2457        let mut run = Run::new();
2458        run.file("/local.h", "beside\n");
2459        run.file("/dir/local.h", "on the path\n");
2460        run.dir("/dir");
2461        assert_eq!(run.go("#include <local.h>\n"), "on the path");
2462    }
2463
2464    #[test]
2465    fn a_macro_defined_in_a_header_is_visible_after_the_include() {
2466        let mut run = Run::new();
2467        run.file("/dir/defs.h", "#define N 42\n");
2468        run.dir("/dir");
2469        assert_eq!(run.go("#include <defs.h>\nint a = N;\n"), "int a = 42;");
2470        assert!(run.messages().is_empty());
2471    }
2472
2473    #[test]
2474    fn an_include_guard_keeps_the_second_read_empty() {
2475        let mut run = Run::new();
2476        run.file("/dir/g.h", "#ifndef G\n#define G\nonce\n#endif\n");
2477        run.dir("/dir");
2478        assert_eq!(run.go("#include <g.h>\n#include <g.h>\n"), "once");
2479        assert!(run.messages().is_empty());
2480        assert_eq!(run.files(), 2, "the second include is not opened at all");
2481    }
2482
2483    fn named(name: &str, macros_only: bool) -> Preinclude {
2484        Preinclude { name: name.to_owned(), macros_only }
2485    }
2486
2487    #[test]
2488    fn a_command_line_include_contributes_its_text_and_an_imacros_contributes_none() {
2489        let mut run = Run::new();
2490        run.file("i.h", "from_include\n#define I 1\n");
2491        run.file("m.h", "from_macros\n#define M 1\n");
2492        assert_eq!(run.preinclude(&[named("i.h", false), named("m.h", true)]), "from_include");
2493        // Both sets of definitions are in scope for the source file, whichever flag named them.
2494        assert_eq!(run.go("I M\n"), "1 1");
2495    }
2496
2497    #[test]
2498    fn every_imacros_runs_before_every_include_whatever_order_the_command_line_was_in() {
2499        // Measured against GCC: the two flags the other way round give the same output byte for
2500        // byte, so the order between the families is fixed and the order within one is not.
2501        for files in
2502            [[named("i.h", false), named("m.h", true)], [named("m.h", true), named("i.h", false)]]
2503        {
2504            let mut run = Run::new();
2505            run.file("i.h", "#ifdef M\nsaw_it\n#else\nmissed_it\n#endif\n");
2506            run.file("m.h", "#define M 1\n");
2507            assert_eq!(run.preinclude(&files), "saw_it");
2508        }
2509    }
2510
2511    #[test]
2512    fn a_header_read_for_its_macros_is_not_read_again_by_an_include_that_its_guard_covers() {
2513        // What makes `-imacros` usable on a header the source includes anyway: the definitions
2514        // arrive early and the declarations do not arrive twice.
2515        let mut run = Run::new();
2516        run.file("/dir/g.h", "#ifndef G\n#define G\ndeclarations\n#endif\n");
2517        run.dir("/dir");
2518        assert_eq!(run.preinclude(&[named("/dir/g.h", true)]), "");
2519        assert_eq!(run.go("#include <g.h>\n"), "");
2520        assert!(run.messages().is_empty());
2521    }
2522
2523    #[test]
2524    fn a_command_line_include_is_a_dependency_and_is_named_before_the_headers_it_reads() {
2525        let mut run = Run::new();
2526        run.file("i.h", "#include \"deep.h\"\n");
2527        run.file("deep.h", "\n");
2528        run.file("m.h", "\n");
2529        run.preinclude(&[named("i.h", false), named("m.h", true)]);
2530        let names: Vec<String> =
2531            run.pp.dependencies().iter().map(|d| d.path.to_string_lossy().into_owned()).collect();
2532        let names: Vec<String> = names.iter().map(|n| n.replace('\\', "/")).collect();
2533        assert_eq!(names, ["m.h", "i.h", "deep.h"]);
2534    }
2535
2536    #[test]
2537    fn a_prerequisite_is_spelled_without_the_dot_the_search_path_was_written_with() {
2538        // What GCC writes, and it disagrees with what the same header's line marker says. A
2539        // marker names the file the way the search reached it and a prerequisite names a file
2540        // `make` compares a timestamp against, and the leading `./` says nothing about that.
2541        let mut run = Run::new();
2542        run.file("d/f.h", "\n");
2543        run.dir("./d");
2544        run.go("#include <f.h>\n");
2545        let names: Vec<String> =
2546            run.pp.dependencies().iter().map(|d| d.path.to_string_lossy().into_owned()).collect();
2547        assert_eq!(names.iter().map(|n| n.replace('\\', "/")).collect::<Vec<_>>(), ["d/f.h"]);
2548    }
2549
2550    #[test]
2551    fn a_command_line_include_that_is_nowhere_is_reported_against_the_flag_that_named_it() {
2552        let mut run = Run::new();
2553        assert_eq!(run.preinclude(&[named("nope.h", false)]), "");
2554        assert_eq!(run.messages(), ["`nope.h` file not found"]);
2555    }
2556
2557    #[test]
2558    fn the_other_spelling_of_a_guard_is_recognised_too() {
2559        for guard in ["#if !defined(G)", "#if !defined G"] {
2560            let mut run = Run::new();
2561            run.file("/dir/g.h", &format!("{guard}\n#define G\nonce\n#endif\n"));
2562            run.dir("/dir");
2563            assert_eq!(run.go("#include <g.h>\n#include <g.h>\n"), "once");
2564            assert_eq!(run.files(), 2, "{guard} should be a guard");
2565        }
2566    }
2567
2568    #[test]
2569    fn a_conditional_that_is_not_a_guard_does_not_skip_anything() {
2570        // Nothing defines the macro, so the second read is not the same as the first and the
2571        // file has to be opened again.
2572        let mut run = Run::new();
2573        run.file("/dir/g.h", "#ifndef G\ntwice\n#endif\n");
2574        run.dir("/dir");
2575        assert_eq!(run.go("#include <g.h>\n#include <g.h>\n"), "twice twice");
2576        assert_eq!(run.files(), 3);
2577    }
2578
2579    #[test]
2580    fn a_token_outside_the_guard_stops_it_being_a_guard() {
2581        let mut run = Run::new();
2582        run.file("/dir/g.h", "#ifndef G\n#define G\n#endif\nalways\n");
2583        run.dir("/dir");
2584        assert_eq!(run.go("#include <g.h>\n#include <g.h>\n"), "always always");
2585        assert_eq!(run.files(), 3);
2586    }
2587
2588    #[test]
2589    fn pragma_once_skips_the_second_read_and_does_not_reach_the_output() {
2590        let mut run = Run::new();
2591        run.file("/dir/o.h", "#pragma once\nonce\n");
2592        run.dir("/dir");
2593        assert_eq!(run.go("#include <o.h>\n#include <o.h>\n"), "once");
2594        assert!(run.messages().is_empty());
2595        assert_eq!(run.files(), 2);
2596    }
2597
2598    #[test]
2599    fn pragma_once_in_the_main_file_is_a_warning_and_is_still_applied() {
2600        // The warning is about the usual case, a main file that meant to be a header. The
2601        // line is applied anyway, because the file that includes itself is the case where it
2602        // does work in a main file, and without it this is an infinite include.
2603        let mut run = Run::new();
2604        let src = "#pragma once\n#include <s.c>\nbody\n";
2605        run.file("/dir/s.c", src);
2606        run.dir("/dir");
2607        assert_eq!(run.go_named("/dir/s.c", src), "body");
2608        assert_eq!(run.severities(), vec![Severity::Warning]);
2609        assert_eq!(run.messages(), vec!["`#pragma once` in the main file".to_owned()]);
2610        assert_eq!(run.files(), 1);
2611    }
2612
2613    #[test]
2614    fn pragma_once_holds_across_two_spellings_of_the_one_path() {
2615        // `-I .` puts a `./` in front of everything it finds, and the file that asked to be
2616        // read once was named without one. Comparing the text as written would read it twice.
2617        let mut run = Run::new();
2618        run.file("dir/s.c", "#pragma once\nbody\n");
2619        run.dir(".");
2620        assert_eq!(run.go("#include <dir/s.c>\n#include <dir/s.c>\n"), "body");
2621        assert!(run.messages().is_empty());
2622        assert_eq!(run.files(), 2);
2623    }
2624
2625    #[test]
2626    fn any_other_pragma_still_passes_through() {
2627        assert_eq!(clean("#pragma once_upon_a_time\n"), "#pragma once_upon_a_time");
2628    }
2629
2630    /// clang's own `__clang_cuda_complex_builtins.h` opens with this, and a header that pushes a
2631    /// name, defines it for its own use and pops it at the end is the whole idiom.
2632    #[test]
2633    fn push_macro_and_pop_macro_put_a_definition_aside_and_bring_it_back() {
2634        let src = "#define X 1\n#pragma push_macro(\"X\")\n#undef X\n#define X 2\n                   a X\n#pragma pop_macro(\"X\")\nb X\n";
2635        assert_eq!(clean(src), "a 2 b 1");
2636    }
2637
2638    #[test]
2639    fn a_name_with_no_definition_pushes_and_pops_the_absence() {
2640        // The pragma is about the state, and "not defined" is a state. A header that pushes a
2641        // name it does not know about has to get an undefined name back, not the one it made.
2642        let src = "#pragma push_macro(\"X\")\n#define X 1\na X\n#pragma pop_macro(\"X\")\nb X\n";
2643        assert_eq!(clean(src), "a 1 b X");
2644    }
2645
2646    #[test]
2647    fn the_pushes_nest() {
2648        let src = "#define X 1\n#pragma push_macro(\"X\")\n#undef X\n#define X 2\n                   #pragma push_macro(\"X\")\n#undef X\n#define X 3\n                   a X\n#pragma pop_macro(\"X\")\nb X\n#pragma pop_macro(\"X\")\nc X\n";
2649        assert_eq!(clean(src), "a 3 b 2 c 1");
2650    }
2651
2652    #[test]
2653    fn a_pop_with_nothing_pushed_says_nothing() {
2654        // The two are written in pairs across headers that do not know about each other, so a
2655        // diagnostic here would fire on code that is not wrong. gcc is silent as well.
2656        assert_eq!(clean("#define X 1\n#pragma pop_macro(\"X\")\nX\n"), "1");
2657        assert_eq!(clean("#pragma pop_macro(\"Never\")\nx\n"), "x");
2658    }
2659
2660    #[test]
2661    fn the_pragma_operator_spelling_works_and_takes_effect_where_it_is_written() {
2662        // A `#pragma` cannot come out of a macro body, so a macro that wants to save a name has
2663        // only this spelling. The lines around it are one run of text to the expander, and the
2664        // pop has to be answered before the line after it is expanded or that line still sees
2665        // the definition the pop was there to undo.
2666        let src = "#define X 1\n_Pragma(\"push_macro(\\\"X\\\")\")\n#undef X\n#define X 2\n                   a X\n_Pragma(\"pop_macro(\\\"X\\\")\")\nb X\n";
2667        assert_eq!(clean(src), "a 2 b 1");
2668    }
2669
2670    #[test]
2671    fn the_gcc_spelling_is_not_one_of_these_and_passes_through() {
2672        // `#pragma GCC push_macro("X")` does nothing in gcc and is printed back, unlike the
2673        // namespaced spellings of the pragmas the compiler proper reads. Answering it here
2674        // would be a difference from gcc dressed up as a courtesy.
2675        let src = "#define X 1\n#pragma GCC push_macro(\"X\")\n#undef X\n#define X 2\nX\n";
2676        assert_eq!(clean(src), "#pragma GCC push_macro(\"X\") 2");
2677    }
2678
2679    #[test]
2680    fn a_push_macro_that_is_not_the_shape_is_an_error() {
2681        for src in ["#pragma push_macro\n", "#pragma push_macro(X)\n", "#pragma pop_macro()\n"] {
2682            let mut run = Run::new();
2683            run.go(src);
2684            let word = if src.contains("push") { "push" } else { "pop" };
2685            assert_eq!(
2686                run.messages(),
2687                vec![format!("invalid `#pragma {word}_macro` directive")],
2688                "from {src:?}"
2689            );
2690        }
2691    }
2692
2693    #[test]
2694    fn a_string_that_does_not_spell_one_identifier_names_no_macro() {
2695        // gcc neither complains about these nor does anything with them, and matching that is
2696        // worth more than improving on it: a header that has one has been building for years.
2697        assert_eq!(clean("#pragma push_macro(\"a b\")\nx\n"), "x");
2698        assert_eq!(clean("#pragma push_macro(\"2\")\nx\n"), "x");
2699    }
2700
2701    #[test]
2702    fn what_follows_the_closing_parenthesis_is_the_usual_warning() {
2703        let mut run = Run::new();
2704        assert_eq!(run.go("#define X 1\n#pragma push_macro(\"X\") junk\nX\n"), "1");
2705        assert_eq!(run.severities(), vec![Severity::Warning]);
2706        assert_eq!(run.messages(), vec!["extra tokens after `#pragma`".to_owned()]);
2707    }
2708
2709    #[test]
2710    fn has_include_answers_from_the_search_path() {
2711        let mut run = Run::new();
2712        run.file("/dir/there.h", "");
2713        run.dir("/dir");
2714        let src = "#if __has_include(<there.h>)\nyes\n#endif\n\
2715                   #if __has_include(<gone.h>)\nno\n#endif\n";
2716        assert_eq!(run.go(src), "yes");
2717        assert!(run.messages().is_empty(), "a header that is not there is an answer, not an error");
2718    }
2719
2720    #[test]
2721    fn has_include_asks_the_question_the_include_on_the_same_line_would() {
2722        // The quoted form looks next to the file that wrote it, so the two spellings answer
2723        // differently about the same header. A `__has_include` that did not agree with the
2724        // `#include` it guards would be worse than not having one.
2725        let mut run = Run::new();
2726        run.file("/beside.h", "");
2727        let src = "#if __has_include(\"beside.h\")\nquoted\n#endif\n\
2728                   #if __has_include(<beside.h>)\nangled\n#endif\n";
2729        assert_eq!(run.go(src), "quoted");
2730    }
2731
2732    #[test]
2733    fn has_include_next_starts_where_include_next_would() {
2734        let mut run = Run::new();
2735        run.file("/a/both.h", "#if __has_include_next(<both.h>)\nmore\n#endif\n");
2736        run.file("/b/both.h", "last\n");
2737        run.file("/a/only.h", "#if __has_include_next(<only.h>)\nmore\n#endif\n");
2738        run.dir("/a");
2739        run.dir("/b");
2740        assert_eq!(run.go("#include <both.h>\n"), "more");
2741        assert_eq!(run.go("#include <only.h>\n"), "", "there is nothing after /a to find it in");
2742    }
2743
2744    #[test]
2745    fn the_operand_of_has_include_is_not_macro_expanded() {
2746        // `linux` is a predefined macro on a Linux target, and `<linux/version.h>` is a real
2747        // header. Expanding the operand would ask about `<1/version.h>`.
2748        let mut run = Run::new();
2749        run.file("/dir/linux/version.h", "");
2750        run.dir("/dir");
2751        let src = "#define linux 1\n#if __has_include(<linux/version.h>)\nyes\n#endif\n";
2752        assert_eq!(run.go(src), "yes");
2753    }
2754
2755    #[test]
2756    fn a_macro_may_expand_to_a_has_include() {
2757        // Which is why the operators are resolved after expansion as well as before it.
2758        let mut run = Run::new();
2759        run.file("/dir/there.h", "");
2760        run.dir("/dir");
2761        let src = "#define HAVE __has_include(<there.h>)\n#if HAVE\nyes\n#endif\n";
2762        assert_eq!(run.go(src), "yes");
2763    }
2764
2765    #[test]
2766    fn defined_says_the_has_operators_are_there() {
2767        // The shape every header that uses them is written in, because they are newer than
2768        // some of the compilers it has to build under.
2769        let src = "#if defined(__has_include) && defined __has_builtin\nyes\n#endif\n";
2770        assert_eq!(clean(src), "yes");
2771        assert_eq!(clean("#ifdef __has_attribute\nyes\n#endif\n"), "yes");
2772    }
2773
2774    #[test]
2775    fn has_attribute_answers_out_of_the_matrix() {
2776        // Both answers matter. A yes for an attribute this compiler ignores sends a header down
2777        // a path that then fails to compile, and a no for one it honours sends it down a worse
2778        // path than it had to take.
2779        assert_eq!(clean("#if __has_attribute(packed)\nyes\n#endif\n"), "yes");
2780        assert_eq!(clean("#if __has_attribute(cold)\nyes\n#endif\n"), "");
2781        assert_eq!(clean("#if __has_attribute(no_such_attribute)\nyes\n#endif\n"), "");
2782        assert_eq!(clean("#if !__has_attribute(cold)\nno\n#endif\n"), "no");
2783    }
2784
2785    #[test]
2786    fn the_scoped_spelling_of_an_attribute_is_the_same_question() {
2787        // `[[gnu::packed]]` and `__attribute__((packed))` are one attribute, and
2788        // `__has_c_attribute` answers with the value the standard gives it rather than with
2789        // one. The scoped one answers zero even though the attribute is implemented, because
2790        // the scope is dropped and what is left is asked of the C attribute rows, which are the
2791        // seven the standard has. GCC answers one there, which is issue #315.
2792        assert_eq!(clean("#if __has_c_attribute(gnu::packed)\nyes\n#endif\n"), "");
2793        assert_eq!(clean("#if __has_c_attribute(deprecated)\nyes\n#endif\n"), "");
2794    }
2795
2796    #[test]
2797    fn has_builtin_answers_no_until_the_builtin_is_real() {
2798        assert_eq!(clean("#if __has_builtin(__builtin_expect)\nyes\n#endif\n"), "yes");
2799        assert_eq!(clean("#if __has_builtin(__builtin_clz)\nyes\n#endif\n"), "yes");
2800        assert_eq!(clean("#if __has_builtin(__builtin_alloca)\nyes\n#endif\n"), "yes");
2801        assert_eq!(clean("#if __has_builtin(__builtin_object_size)\nyes\n#endif\n"), "");
2802        assert_eq!(clean("#if __has_builtin(__builtin_nonesuch)\nyes\n#endif\n"), "");
2803    }
2804
2805    #[test]
2806    fn has_feature_and_has_extension_read_the_same_table() {
2807        // The preprocessor features are the ones that are real today, so they are the ones
2808        // that answer yes, and `__has_extension` answers yes wherever `__has_feature` does.
2809        assert_eq!(clean("#if __has_feature(pragma_once)\nyes\n#endif\n"), "yes");
2810        assert_eq!(clean("#if __has_extension(pragma_once)\nyes\n#endif\n"), "yes");
2811        assert_eq!(clean("#if __has_extension(include_next)\nyes\n#endif\n"), "yes");
2812        assert_eq!(clean("#if __has_feature(include_next)\nyes\n#endif\n"), "");
2813        assert_eq!(clean("#if __has_feature(statement_expressions)\nyes\n#endif\n"), "");
2814    }
2815
2816    #[test]
2817    fn building_module_is_always_no_and_is_recognised_so_that_the_line_parses() {
2818        // Clang's own stddef.h writes this, and the whole point of knowing the name is that
2819        // the operand disappears with it. An unknown identifier would leave `(m)` behind and
2820        // the `#if` would fail to parse rather than answering no.
2821        assert_eq!(clean("#if __building_module(m)\nyes\n#endif\n"), "");
2822        assert_eq!(clean("#if !__building_module(m)\nyes\n#endif\n"), "yes");
2823        assert_eq!(
2824            clean(
2825                "#if !defined(offsetof) || (__has_feature(modules) && !__building_module(x))\nyes\n#endif\n"
2826            ),
2827            "yes"
2828        );
2829        // Defined, the same as the rest of the family: a header asks before it uses one.
2830        assert_eq!(clean("#ifdef __building_module\nyes\n#endif\n"), "yes");
2831        assert_eq!(clean("#if defined(__building_module)\nyes\n#endif\n"), "yes");
2832    }
2833
2834    #[test]
2835    fn a_has_operator_without_an_operand_is_reported() {
2836        let mut run = Run::new();
2837        run.go("#if __has_include\nyes\n#endif\n");
2838        assert_eq!(run.messages(), ["expected `(` after `__has_include`"]);
2839        let mut run = Run::new();
2840        run.go("#if __has_include(1)\nyes\n#endif\n");
2841        assert_eq!(run.messages(), ["expected a file name in `<>` or `\"\"`"]);
2842        let mut run = Run::new();
2843        run.go("#if __has_attribute(\"packed\")\nyes\n#endif\n");
2844        assert_eq!(run.messages(), ["expected an identifier as the operand of `__has_attribute`"]);
2845    }
2846
2847    #[test]
2848    fn the_has_operators_answer_in_ordinary_text_too() {
2849        // GCC and clang both make these builtin macros rather than something only the
2850        // conditional parser knows, so a program may write one in a declaration. Real headers
2851        // do: an attribute macro is often written as the answer rather than as a `#if`.
2852        assert_eq!(clean("f __has_feature(pragma_once)\n"), "f 1");
2853        assert_eq!(clean("b __has_builtin(__builtin_expect)\n"), "b 1");
2854        assert_eq!(clean("a __has_attribute(packed)\n"), "a 1");
2855        assert_eq!(clean("c __has_c_attribute(deprecated)\n"), "c 0");
2856        assert_eq!(clean("m __building_module(foo)\n"), "m 0");
2857    }
2858
2859    #[test]
2860    fn a_macro_that_expands_to_a_has_operator_is_answered_where_it_is_used() {
2861        // The awkward half of the same feature. The answer is deferred to wherever the macro
2862        // lands, so the sweep has to run after expansion and not only before it.
2863        assert_eq!(clean("#define HAVE __has_feature(pragma_once)\nx HAVE\n"), "x 1");
2864        assert_eq!(clean("#define HAVE(x) __has_attribute(x)\ny HAVE(packed)\n"), "y 1");
2865    }
2866
2867    #[test]
2868    fn a_has_operator_in_text_still_needs_its_operand() {
2869        let mut run = Run::new();
2870        run.go("tail __has_attribute;\n");
2871        assert_eq!(run.messages(), ["expected `(` after `__has_attribute`"]);
2872    }
2873
2874    #[test]
2875    fn the_header_operators_are_refused_in_ordinary_text() {
2876        // `<stdio.h>` in a text line was scanned as a run of comparisons, so there is no
2877        // header name left to ask about. GCC and clang both say the same thing here.
2878        let mut run = Run::new();
2879        run.file("/dir/there.h", "");
2880        run.dir("/dir");
2881        run.go("a __has_include(<there.h>)\n");
2882        assert_eq!(run.messages(), ["`__has_include` used outside of a preprocessing directive"]);
2883        let mut run = Run::new();
2884        run.go("b __has_include_next(\"x.h\")\n");
2885        assert_eq!(
2886            run.messages(),
2887            ["`__has_include_next` used outside of a preprocessing directive"]
2888        );
2889    }
2890
2891    #[test]
2892    fn the_predefined_set_is_visible_to_the_source_file() {
2893        let mut run = Run::new();
2894        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
2895        let src = "#if defined(__x86_64__) && defined(__linux__) && __SIZEOF_LONG__ == 8\n\
2896                   yes\n#endif\n";
2897        assert_eq!(run.go(src), "yes");
2898        assert!(run.messages().is_empty());
2899    }
2900
2901    #[test]
2902    fn the_predefined_set_follows_the_target_and_not_the_host() {
2903        let mut run = Run::new();
2904        run.predefine("aarch64-unknown-linux-gnu", &Predef::new());
2905        assert_eq!(
2906            run.go("#ifdef __x86_64__\nno\n#endif\n#ifdef __aarch64__\nyes\n#endif\n"),
2907            "yes"
2908        );
2909    }
2910
2911    #[test]
2912    fn a_predefined_macro_expands_where_it_is_used() {
2913        let mut run = Run::new();
2914        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
2915        assert_eq!(run.go("__SIZE_TYPE__ n;\n"), "long unsigned int n;");
2916    }
2917
2918    #[test]
2919    fn a_command_line_define_is_a_definition_like_any_other() {
2920        let mut opts = Predef::new();
2921        opts.defines = vec!["FOO".to_owned(), "BAR=3".to_owned()];
2922        opts.undefines = vec!["__linux__".to_owned()];
2923        let mut run = Run::new();
2924        run.predefine("x86_64-unknown-linux-gnu", &opts);
2925        let src = "#if FOO && BAR == 3 && !defined(__linux__)\nyes\n#endif\n";
2926        assert_eq!(run.go(src), "yes");
2927        assert!(run.messages().is_empty());
2928    }
2929
2930    #[test]
2931    fn the_predefined_set_produces_no_tokens_of_its_own() {
2932        // It is a file of directives, so the output of the compilation is the source file
2933        // and nothing else. A stray token here would appear at the top of every `-E` run.
2934        let mut run = Run::new();
2935        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
2936        assert_eq!(run.go("alone\n"), "alone");
2937    }
2938
2939    #[test]
2940    fn the_predefined_files_are_named_the_way_gcc_names_them() {
2941        let mut run = Run::new();
2942        let mut opts = Predef::new();
2943        opts.defines = vec!["FOO=1".to_owned()];
2944        run.predefine("x86_64-unknown-linux-gnu", &opts);
2945        let names: Vec<&str> = run.sources.files().iter().map(|f| f.name.as_str()).collect();
2946        assert_eq!(names, ["<built-in>", "<command-line>"]);
2947    }
2948
2949    #[test]
2950    fn a_dialect_without_the_gnu_extensions_says_so() {
2951        let mut opts = Predef::new();
2952        opts.gnu_extensions = false;
2953        opts.std = Std::C99;
2954        let mut run = Run::new();
2955        run.predefine("x86_64-unknown-linux-gnu", &opts);
2956        let src = "#if defined(__STRICT_ANSI__) && __STDC_VERSION__ == 199901L && !defined(linux)\n\
2957                   yes\n#endif\n";
2958        assert_eq!(run.go(src), "yes");
2959    }
2960
2961    #[test]
2962    fn the_date_and_time_are_the_same_for_the_whole_translation_unit() {
2963        let mut opts = Predef::new();
2964        opts.timestamp = Timestamp::from_unix(0);
2965        let mut run = Run::new();
2966        run.predefine("x86_64-unknown-linux-gnu", &opts);
2967        assert_eq!(run.go("__DATE__ __TIME__\n"), "\"Jan  1 1970\" \"00:00:00\"");
2968    }
2969
2970    #[test]
2971    fn a_has_operator_in_a_dead_branch_is_not_asked_about() {
2972        // The line is not evaluated at all, so a malformed one inside `#if 0` is text.
2973        assert_eq!(clean("#if 0\n#if __has_include\n#endif\n#endif\nafter\n"), "after");
2974    }
2975
2976    #[test]
2977    fn a_conditional_may_not_span_an_include() {
2978        // GCC and Clang both refuse this, and the reason is that a header which opens a
2979        // conditional it does not close leaves the file that included it in a state nothing
2980        // downstream can reason about.
2981        let mut run = Run::new();
2982        run.file("/dir/open.h", "#if 1\n");
2983        run.dir("/dir");
2984        run.go("#include <open.h>\nkept\n#endif\n");
2985        let messages = run.messages();
2986        assert_eq!(messages.len(), 2);
2987        assert!(messages[0].contains("unterminated"));
2988        assert!(messages[1].contains("without"));
2989    }
2990
2991    #[test]
2992    fn include_next_continues_after_the_directory_the_file_came_from() {
2993        // The wrapper header trick: `/a` has a `limits.h` that pulls in the real one from
2994        // `/b`, and the two have the same name on purpose.
2995        let mut run = Run::new();
2996        run.file("/a/limits.h", "wrapper\n#include_next <limits.h>\n");
2997        run.file("/b/limits.h", "real\n");
2998        run.dir("/a");
2999        run.dir("/b");
3000        assert_eq!(run.go("#include <limits.h>\n"), "wrapper real");
3001        assert!(run.messages().is_empty());
3002    }
3003
3004    #[test]
3005    fn a_computed_include_is_expanded_first() {
3006        let mut run = Run::new();
3007        run.file("/dir/sub/thing.h", "computed\n");
3008        run.dir("/dir");
3009        let src = "#define HEADER <sub/thing.h>\n#include HEADER\n";
3010        assert_eq!(run.go(src), "computed");
3011        assert!(run.messages().is_empty());
3012        // The string literal form goes through the same path and keeps its delimiters.
3013        let mut run = Run::new();
3014        run.file("/dir/sub/thing.h", "computed\n");
3015        run.dir("/dir");
3016        assert_eq!(run.go("#define H \"sub/thing.h\"\n#include H\n"), "computed");
3017    }
3018
3019    #[test]
3020    fn a_header_that_is_not_there_says_where_it_looked() {
3021        let mut run = Run::new();
3022        run.dir("/dir");
3023        run.go("#include <nope.h>\n");
3024        let diagnostics = run.pp.take_diagnostics();
3025        assert_eq!(diagnostics.len(), 1);
3026        assert_eq!(diagnostics[0].code, Some("E0341"));
3027        assert_eq!(diagnostics[0].message, "`nope.h` file not found");
3028        assert!(diagnostics[0].children[0].message.contains("/dir"));
3029    }
3030
3031    /// And says why there was nowhere to look, when the driver left a reason on the path.
3032    ///
3033    /// What the reason is for is `rucc_sysroot::Wall`: a target whose system headers nobody may
3034    /// redistribute has no directories of its own on the path, and an include that failed is the one
3035    /// moment where saying so helps. It is a second note rather than the message, because the
3036    /// message is about this include and the reason is about the machine.
3037    #[test]
3038    fn a_header_that_is_not_there_says_why_the_system_directories_are_missing() {
3039        let mut run = Run::new();
3040        run.search.explain_missing_system("aarch64-macos needs a macOS SDK and there is none here");
3041        run.go("#include <stdio.h>\n");
3042        let diagnostics = run.pp.take_diagnostics();
3043        assert_eq!(diagnostics.len(), 1);
3044        assert_eq!(diagnostics[0].message, "`stdio.h` file not found");
3045        assert!(diagnostics[0].children[0].message.contains("search path is empty"));
3046        assert!(diagnostics[0].children[1].message.contains("needs a macOS SDK"));
3047        // And a run with nothing left on the path keeps the one note it had.
3048        let mut run = Run::new();
3049        run.dir("/dir");
3050        run.go("#include <nope.h>\n");
3051        assert_eq!(run.pp.take_diagnostics()[0].children.len(), 1);
3052    }
3053
3054    #[test]
3055    fn an_include_that_is_not_a_header_name_is_reported() {
3056        let mut run = Run::new();
3057        run.go("#include 3\n");
3058        let diagnostics = run.pp.take_diagnostics();
3059        assert_eq!(diagnostics[0].code, Some("E0343"));
3060    }
3061
3062    #[test]
3063    fn a_header_that_includes_itself_stops() {
3064        let mut run = Run::new();
3065        run.file("/dir/loop.h", "#include <loop.h>\n");
3066        run.dir("/dir");
3067        run.go("#include <loop.h>\n");
3068        let diagnostics = run.pp.take_diagnostics();
3069        assert_eq!(diagnostics.len(), 1, "one complaint, not one per level");
3070        assert_eq!(diagnostics[0].code, Some("E0342"));
3071    }
3072
3073    #[test]
3074    fn an_include_in_a_dead_branch_is_not_read() {
3075        let mut run = Run::new();
3076        assert_eq!(run.go("#if 0\n#include <nothing.h>\n#endif\nafter\n"), "after");
3077        assert!(run.messages().is_empty(), "a skipped include is not resolved");
3078    }
3079
3080    #[test]
3081    fn embed_writes_the_bytes_of_the_resource() {
3082        let mut run = Run::new();
3083        run.bytes("/logo.bin", &[0, 1, 127, 128, 255]);
3084        assert_eq!(run.go("#embed \"logo.bin\"\n"), "0, 1, 127, 128, 255");
3085        assert!(run.messages().is_empty());
3086    }
3087
3088    #[test]
3089    fn an_embed_is_a_valid_initializer_on_both_sides_of_empty() {
3090        // The reason `prefix` and `suffix` exist. An empty resource is `if_empty` alone, with
3091        // neither of them, so the same three lines are a well formed array whether the file
3092        // has bytes in it or not. Emitting `prefix` and `suffix` around nothing would leave a
3093        // trailing comma inside the braces and turn an empty file into a syntax error.
3094        let mut run = Run::new();
3095        run.bytes("/some.bin", &[7, 8]);
3096        run.bytes("/none.bin", &[]);
3097        let line = |name: &str| {
3098            format!("{{\n#embed \"{name}\" prefix(0xEF,) suffix(,0xFE) if_empty(0)\n}}\n")
3099        };
3100        assert_eq!(run.go(&line("some.bin")), "{ 0xEF,7, 8 ,0xFE }");
3101        assert_eq!(run.go_named("/other.c", &line("none.bin")), "{ 0 }");
3102        assert!(run.messages().is_empty());
3103    }
3104
3105    #[test]
3106    fn the_limit_and_the_offset_choose_a_window_of_the_resource() {
3107        let mut run = Run::new();
3108        run.bytes("/eight.bin", &[1, 2, 3, 4, 5, 6, 7, 8]);
3109        assert_eq!(run.go("#embed \"eight.bin\" limit(3)\n"), "1, 2, 3");
3110        assert_eq!(
3111            run.go_named("/b.c", "#embed \"eight.bin\" gnu::offset(4) limit(3)\n"),
3112            "5, 6, 7"
3113        );
3114        // A limit of zero is an empty embed, not an unlimited one, and an offset past the end
3115        // is empty rather than an error.
3116        assert_eq!(run.go_named("/c.c", "#embed \"eight.bin\" limit(0) if_empty(9)\n"), "9");
3117        assert_eq!(run.go_named("/d.c", "#embed \"eight.bin\" gnu::offset(99)\n"), "");
3118        assert!(run.messages().is_empty());
3119    }
3120
3121    #[test]
3122    fn the_limit_is_a_constant_expression_and_not_just_a_number() {
3123        // It is the `#if` language, so a macro and arithmetic both work. A header that writes
3124        // `limit(CHUNK * 2)` is doing the ordinary thing.
3125        let mut run = Run::new();
3126        run.bytes("/eight.bin", &[1, 2, 3, 4, 5, 6, 7, 8]);
3127        assert_eq!(
3128            run.go("#define CHUNK 2\n#embed \"eight.bin\" limit(CHUNK * 2)\n"),
3129            "1, 2, 3, 4"
3130        );
3131        assert!(run.messages().is_empty());
3132    }
3133
3134    #[test]
3135    fn a_misspelled_embed_parameter_is_refused_rather_than_ignored() {
3136        // Carrying on without it would produce an array with the wrong contents and no
3137        // message, which is the worst outcome available.
3138        let mut run = Run::new();
3139        run.bytes("/eight.bin", &[1, 2]);
3140        assert_eq!(run.go("#embed \"eight.bin\" limits(1)\n"), "");
3141        assert_eq!(run.messages(), vec!["unknown `#embed` parameter `limits`".to_owned()]);
3142        let mut vendor = Run::new();
3143        vendor.bytes("/eight.bin", &[1, 2]);
3144        assert_eq!(vendor.go("#embed \"eight.bin\" clang::offset(1)\n"), "");
3145        assert_eq!(
3146            vendor.messages(),
3147            vec!["unknown `#embed` parameter `clang::offset`".to_owned()]
3148        );
3149    }
3150
3151    #[test]
3152    fn a_missing_embed_resource_is_reported_as_a_resource() {
3153        let mut run = Run::new();
3154        run.go("#embed <nothing.bin>\n");
3155        assert_eq!(run.messages(), vec!["`nothing.bin` resource not found".to_owned()]);
3156    }
3157
3158    #[test]
3159    fn has_embed_tells_missing_from_present_from_empty() {
3160        // Three answers, which is the reason the operator is not `__has_include` with a
3161        // different name. A present but empty resource needs its `if_empty` written and a
3162        // missing one needs a fallback, and a yes or no cannot tell the two apart.
3163        let mut run = Run::new();
3164        run.bytes("/some.bin", &[1]);
3165        run.bytes("/none.bin", &[]);
3166        let src = "#if __has_embed(\"none.bin\") == __STDC_EMBED_EMPTY__\nempty\n#endif\n\
3167                   #if __has_embed(\"some.bin\") == __STDC_EMBED_FOUND__\nfound\n#endif\n\
3168                   #if __has_embed(\"gone.bin\") == __STDC_EMBED_NOT_FOUND__\ngone\n#endif\n";
3169        run.predefine("x86_64-unknown-linux-gnu", &Predef::default());
3170        assert_eq!(run.go(src), "empty found gone");
3171        assert!(run.messages().is_empty());
3172    }
3173
3174    #[test]
3175    fn has_embed_takes_the_limit_into_account() {
3176        // The guard has to answer the question the directive it guards will ask. A resource
3177        // that exists but has nothing left after `limit(0)` is empty to both of them.
3178        let mut run = Run::new();
3179        run.bytes("/some.bin", &[1, 2, 3]);
3180        run.predefine("x86_64-unknown-linux-gnu", &Predef::default());
3181        let src = "#if __has_embed(\"some.bin\" limit(0)) == __STDC_EMBED_EMPTY__\nempty\n#endif\n";
3182        assert_eq!(run.go(src), "empty");
3183        assert!(run.messages().is_empty());
3184    }
3185
3186    #[test]
3187    fn a_directive_may_have_space_before_the_hash_and_after_it() {
3188        assert_eq!(clean("  #  define F 1\n#ifdef F\nyes\n#endif\n"), "yes");
3189    }
3190
3191    #[test]
3192    fn a_definition_survives_across_a_conditional() {
3193        assert_eq!(clean("#if 1\n#define F 7\n#endif\nF\n"), "7");
3194    }
3195
3196    #[test]
3197    fn an_empty_if_expression_is_reported() {
3198        let mut run = Run::new();
3199        run.go("#if\n#endif\n");
3200        assert_eq!(run.messages(), vec!["`#if` with no expression".to_owned()]);
3201    }
3202
3203    #[test]
3204    fn the_file_and_the_line_say_where_the_use_is() {
3205        let mut run = Run::new();
3206        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3207        assert_eq!(run.go("__FILE__ __LINE__\n__LINE__\n"), "\"/main.c\" 1 2");
3208        assert!(run.messages().is_empty());
3209    }
3210
3211    #[test]
3212    fn a_macro_that_mentions_the_line_answers_with_the_call() {
3213        let mut run = Run::new();
3214        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3215        run.file("/where.h", "#define WHERE __FILE__ __LINE__\n");
3216        // The point of the whole arrangement. `assert` is this macro, and a version that
3217        // answered with the header the macro was written in would name a file the user has
3218        // never opened and a line that means nothing.
3219        assert_eq!(run.go("#include \"where.h\"\n\n\nWHERE\n"), "\"/main.c\" 4");
3220        assert!(run.messages().is_empty());
3221    }
3222
3223    #[test]
3224    fn the_file_name_is_the_file_without_the_directories() {
3225        let mut run = Run::new();
3226        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3227        assert_eq!(run.go_named("/deep/down/main.c", "__FILE_NAME__\n"), "\"main.c\"");
3228    }
3229
3230    #[test]
3231    fn a_backslash_in_the_name_is_escaped() {
3232        let mut run = Run::new();
3233        run.predefine("x86_64-pc-windows-msvc", &Predef::new());
3234        // The literal has to mean the path, so the separators are escaped. Getting this wrong
3235        // turns `\src` into an unknown escape and `\a` into a bell character.
3236        let text = run.go_named("C:\\src\\main.c", "__FILE__ __FILE_NAME__\n");
3237        assert_eq!(text, "\"C:\\\\src\\\\main.c\" \"main.c\"");
3238    }
3239
3240    #[test]
3241    fn the_base_file_is_the_one_named_on_the_command_line() {
3242        let mut run = Run::new();
3243        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3244        run.file("/deep.h", "__FILE__ __BASE_FILE__\n");
3245        assert_eq!(run.go("#include \"deep.h\"\n"), "\"/deep.h\" \"/main.c\"");
3246        assert!(run.messages().is_empty());
3247    }
3248
3249    #[test]
3250    fn a_prefix_map_rewrites_the_file_and_the_base_file_and_not_the_file_name() {
3251        let mut run = Run::mapping(&[("/build", ".")]);
3252        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3253        run.file("/build/deep.h", "__FILE__ __BASE_FILE__ __FILE_NAME__\n");
3254        // The header is rewritten and so is the file at the bottom of the stack, because both of
3255        // those are paths and a path is what the flag exists to hide. The last component is not,
3256        // because a mapping rewrites the front of a path and that is what is left after the front
3257        // has been taken off: a name with no directories in it is already what the flag is for.
3258        // gcc draws the line in exactly this place.
3259        let text = run.go_named("/build/main.c", "#include \"deep.h\"\n");
3260        // The separators are whatever the host joined the directory and the header with, and this
3261        // test is not about which of the two characters that is.
3262        assert_eq!(slashes(&text), "\"./deep.h\" \"./main.c\" \"deep.h\"");
3263        assert!(run.messages().is_empty());
3264    }
3265
3266    #[test]
3267    fn the_last_rewrite_that_matches_is_the_one_that_acts() {
3268        // Two roots mapped at once, which is what a distribution passes, and one of them inside
3269        // the other, which is what makes the order matter. The later flag wins where both match.
3270        let mut run = Run::mapping(&[("/build", "src"), ("/build/gen", "generated")]);
3271        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3272        assert_eq!(run.go_named("/build/gen/made.c", "__FILE__\n"), "\"generated/made.c\"");
3273
3274        let mut run = Run::mapping(&[("/build", "src"), ("/build/gen", "generated")]);
3275        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3276        assert_eq!(run.go_named("/build/hand.c", "__FILE__\n"), "\"src/hand.c\"");
3277
3278        // And a name the flags say nothing about comes out as it went in, rather than as an empty
3279        // string or as the first rewrite applied to nothing.
3280        let mut run = Run::mapping(&[("/build", "src")]);
3281        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3282        assert_eq!(run.go_named("/elsewhere/main.c", "__FILE__\n"), "\"/elsewhere/main.c\"");
3283    }
3284
3285    #[test]
3286    fn a_rewrite_matches_the_characters_and_not_the_directories() {
3287        // gcc compares the front of the string, not a sequence of path components, so a rewrite
3288        // that stops halfway through a directory name really does cut it in half. Surprising the
3289        // first time and relied on the second, because it is what lets `-ffile-prefix-map=/b=/a`
3290        // fix up a whole family of sibling roots at once, and a compiler that quietly rounded the
3291        // rewrite up to the nearest separator would be answering a different question.
3292        let mut run = Run::mapping(&[("/bui", "X")]);
3293        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3294        assert_eq!(run.go_named("/build/main.c", "__FILE__\n"), "\"Xld/main.c\"");
3295    }
3296
3297    #[test]
3298    fn the_include_level_counts_the_headers_above_it() {
3299        let mut run = Run::new();
3300        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3301        run.file("/one.h", "__INCLUDE_LEVEL__\n#include \"two.h\"\n");
3302        run.file("/two.h", "__INCLUDE_LEVEL__\n");
3303        assert_eq!(run.go("__INCLUDE_LEVEL__\n#include \"one.h\"\n"), "0 1 2");
3304        assert!(run.messages().is_empty());
3305    }
3306
3307    #[test]
3308    fn the_counter_is_a_different_number_every_time() {
3309        let mut run = Run::new();
3310        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3311        assert_eq!(run.go("__COUNTER__ __COUNTER__ __COUNTER__\n"), "0 1 2");
3312    }
3313
3314    #[test]
3315    fn the_counter_advances_once_per_argument_rather_than_once_per_use() {
3316        let mut run = Run::new();
3317        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3318        // An argument is expanded once however many times the body names it, so `TWICE`
3319        // produces the same number twice. That is what GCC does, and the reason for it is
3320        // that expanding an argument twice would report anything wrong inside it twice.
3321        assert_eq!(run.go("#define TWICE(x) x x\nTWICE(__COUNTER__) __COUNTER__\n"), "0 0 1");
3322    }
3323
3324    #[test]
3325    fn the_line_is_a_number_an_if_can_use() {
3326        let mut run = Run::new();
3327        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3328        assert_eq!(run.go("#if __LINE__ == 1 && __INCLUDE_LEVEL__ == 0\nyes\n#endif\n"), "yes");
3329        assert!(run.messages().is_empty());
3330    }
3331
3332    #[test]
3333    fn the_dynamic_macros_are_defined_like_any_others() {
3334        let mut run = Run::new();
3335        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3336        let src = "#ifdef __FILE__\nyes\n#endif\n#undef __LINE__\n#ifndef __LINE__\ngone\n#endif\n";
3337        assert_eq!(run.go(src), "yes gone");
3338        assert!(run.messages().is_empty(), "`#undef` of a builtin is allowed, as it is in GCC");
3339    }
3340
3341    #[test]
3342    fn redefining_a_dynamic_macro_warns_and_points_at_the_built_in_file() {
3343        let mut run = Run::new();
3344        run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3345        assert_eq!(run.go("#define __FILE__ \"mine.c\"\n__FILE__\n"), "\"mine.c\"");
3346        let complaints = run.pp.take_diagnostics();
3347        assert_eq!(complaints.len(), 1);
3348        assert_eq!(complaints[0].code, Some("W0301"));
3349        let previous = complaints[0].children.first().expect("a note saying where it was");
3350        assert_eq!(run.sources.lookup(previous.span.lo).map(|loc| loc.file), {
3351            let built_in = run.sources.files().iter().find(|f| f.name == BUILT_IN);
3352            built_in.map(|f| f.id)
3353        });
3354    }
3355
3356    #[test]
3357    fn destringizing_undoes_what_stringizing_did() {
3358        assert_eq!(destringize(r#""a \"b\" c""#), r#"a "b" c"#);
3359        assert_eq!(destringize(r#""a \\ b""#), r"a \ b");
3360        assert_eq!(destringize(r#"L"wide""#), "wide");
3361    }
3362}