Skip to main content

rucc_pp/
include.rs

1//! Reading a file, and the parts of `#include` that are not the directive itself.
2//!
3//! Design: `spec/05-preprocessor.md` section 5.4 and `spec/04-driver-and-cli.md` section 4.4.
4//!
5//! Phase 4 drives the lexer rather than being handed a finished token vector, and the reason
6//! is header names. `<stdio.h>` and a run of comparisons are the same bytes, and only the
7//! directive knows which one is possible, so [`rucc_lex::Lexer::header_name`] exists and has
8//! to be called at exactly the right moment. Scanning the file first and reconstructing the
9//! name from the tokens afterwards works until a header name contains `//`, or a backslash on
10//! a Windows path, and then it silently produces a different name.
11//!
12//! Driving the lexer also means a file is read one line at a time rather than all at once,
13//! which is what the memory mapped input and the header cache both want later.
14
15use std::path::{Path, PathBuf};
16
17use rucc_base::Interner;
18use rucc_diag::{BytePos, Diagnostic, SourceMap, Span};
19use rucc_lex::{Lexer, Options, PpToken, PpTokenKind, TokenFlags};
20use rucc_session::{FileSystem, SearchPath};
21
22use crate::token::Tok;
23
24/// Everything phase 4 needs from outside itself.
25///
26/// Grouped into one struct because `#include` needs all of it at once and threading five
27/// references through every directive handler is how a parameter list becomes unreadable.
28/// The lifetime is the compilation, and every field of it lives on the session.
29pub struct Context<'a> {
30    /// The one interner.
31    pub interner: &'a mut Interner,
32    /// Where an included file is added, and what a span is resolved against.
33    pub sources: &'a mut SourceMap,
34    /// Where a header is read from.
35    pub fs: &'a dyn FileSystem,
36    /// Where a header is looked for.
37    pub search: &'a SearchPath,
38    /// The dialect knobs phase 1 cares about.
39    pub lex: Options,
40    /// How deep `#include` may nest before it is called a cycle.
41    ///
42    /// A header that includes itself with no guard is the common way to reach this, and the
43    /// alternative to a limit is a stack overflow with no diagnostic at all.
44    pub max_include_depth: u32,
45}
46
47impl<'a> Context<'a> {
48    /// A context with GCC's include depth limit.
49    pub fn new(
50        interner: &'a mut Interner,
51        sources: &'a mut SourceMap,
52        fs: &'a dyn FileSystem,
53        search: &'a SearchPath,
54    ) -> Context<'a> {
55        Context { interner, sources, fs, search, lex: Options::new(), max_include_depth: 200 }
56    }
57}
58
59impl std::fmt::Debug for Context<'_> {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        f.debug_struct("Context")
62            .field("lex", &self.lex)
63            .field("max_include_depth", &self.max_include_depth)
64            .finish_non_exhaustive()
65    }
66}
67
68/// One open file, and what an `#include` written in it resolves against.
69#[derive(Debug)]
70pub(crate) struct Frame {
71    /// Where the file was included from, for the too deeply nested diagnostic.
72    pub(crate) at: Span,
73    /// The file itself, as the include that found it named it. This is what diagnostics and
74    /// `#include_next` are written against, so it stays the name that was used rather than
75    /// the name the file system would rather it had.
76    pub(crate) path: PathBuf,
77    /// What the file system calls the same file, which is what `#pragma once` and the guard
78    /// optimization remember it by. Two names for one file share this and do not share the
79    /// path, and reaching one header through two spellings is ordinary on any project with
80    /// more than one include directory.
81    pub(crate) id: PathBuf,
82    /// The directory the file is in, which a quoted include looks in first.
83    pub(crate) dir: Option<PathBuf>,
84    /// Where an `#include_next` written in this file starts looking.
85    pub(crate) next: usize,
86}
87
88/// Pulls tokens out of the lexer one logical line at a time.
89///
90/// One token of lookahead, because a line ends when the next token says it starts a line and
91/// there is no other way to find that out.
92pub(crate) struct Reader<'a> {
93    lexer: Lexer<'a>,
94    pending: Option<PpToken>,
95}
96
97impl<'a> Reader<'a> {
98    pub(crate) fn new(src: &'a [u8], start: BytePos, opts: Options) -> Reader<'a> {
99        Reader { lexer: Lexer::new(src, start, opts), pending: None }
100    }
101
102    /// The next token, which is an end of file token forever once the file runs out.
103    pub(crate) fn next(&mut self, interner: &mut Interner) -> PpToken {
104        match self.pending.take() {
105            Some(token) => token,
106            None => self.lexer.next_token(interner),
107        }
108    }
109
110    /// Puts a token back, so the next call to [`Reader::next`] returns it again.
111    pub(crate) fn put_back(&mut self, token: PpToken) {
112        self.pending = Some(token);
113    }
114
115    /// Appends the rest of the current line to `out`, leaving the next line's first token
116    /// where the next call will find it.
117    pub(crate) fn line(&mut self, interner: &mut Interner, out: &mut Vec<PpToken>) {
118        loop {
119            let token = self.next(interner);
120            if token.is_eof() || token.flags.has(TokenFlags::START_OF_LINE) {
121                self.put_back(token);
122                return;
123            }
124            out.push(token);
125        }
126    }
127
128    /// Scans a header name here, which only an include directive may ask for.
129    ///
130    /// `None` when the line does not begin with `<` or `"`, which is the computed include
131    /// case and has to be answered by macro expansion instead.
132    pub(crate) fn header_name(&mut self, interner: &mut Interner) -> Option<PpToken> {
133        // Asking after the line has been read would scan the wrong bytes, and the borrow
134        // checker cannot see the difference, so the invariant is stated here instead.
135        debug_assert!(self.pending.is_none(), "the header name has to be asked for first");
136        self.lexer.header_name(interner)
137    }
138
139    pub(crate) fn take_diagnostics(&mut self) -> Vec<Diagnostic> {
140        self.lexer.take_diagnostics()
141    }
142}
143
144/// One file an `#include` found, for the `-M` family.
145///
146/// The path is the one the search resolved to rather than the name the directive wrote, because
147/// a make rule naming `stdio.h` would say nothing about which `stdio.h`, and it is left relative
148/// where the directory it was found under was relative, which is what makes the rule readable
149/// and what GCC does.
150#[derive(Debug, Clone, PartialEq, Eq)]
151pub struct Dependency {
152    /// Where the file was found.
153    pub path: PathBuf,
154    /// Whether the directory it was found under is a system one, which is what `-MM` drops.
155    pub is_system: bool,
156}
157
158/// What the two spellings of a header name mean, and the name itself.
159#[derive(Debug, Clone, PartialEq, Eq)]
160pub(crate) struct Header {
161    pub(crate) name: String,
162    pub(crate) angled: bool,
163}
164
165/// Reads a header name out of the token the lexer produced for one.
166///
167/// The delimiters come off and nothing else happens: a header name is not a string literal,
168/// so a backslash in it is a backslash and `\t` names a file whose name contains a `t`
169/// preceded by a backslash, which is what a Windows path needs.
170pub(crate) fn header_from_token(spelling: &str) -> Option<Header> {
171    let angled = spelling.starts_with('<');
172    let close = if angled { '>' } else { '"' };
173    let inner = spelling.strip_prefix(if angled { '<' } else { '"' })?;
174    let inner = inner.strip_suffix(close).unwrap_or(inner);
175    if inner.is_empty() {
176        return None;
177    }
178    Some(Header { name: inner.to_owned(), angled })
179}
180
181/// Reads a header name out of the tokens a macro expanded to.
182///
183/// `#include MACRO` is the computed include, and the standard says only that the tokens are
184/// combined in an implementation defined manner. The manner is that spellings are
185/// concatenated with nothing between them, which is what GCC does in every case that occurs
186/// in real code and is the only choice that makes `<sys/types.h>` come back out as itself.
187pub(crate) fn header_from_tokens(spellings: &[&str]) -> Option<Header> {
188    let first = *spellings.first()?;
189    if first.starts_with('"') && spellings.len() == 1 {
190        return header_from_token(first);
191    }
192    if first != "<" {
193        return None;
194    }
195    let close = spellings.iter().rposition(|s| *s == ">")?;
196    if close < 2 {
197        return None;
198    }
199    let name: String = spellings[1..close].concat();
200    Some(Header { name, angled: true })
201}
202
203/// What a file name is called when the position it was asked about is in no file at all.
204///
205/// The same spelling the diagnostic renderer uses, so there is one word for this and not two.
206pub(crate) const UNKNOWN: &str = "<unknown>";
207
208/// A file name as the string literal `__FILE__` expands to.
209///
210/// A backslash and a double quote are escaped. That is not a nicety on Windows: `__FILE__` for
211/// `C:\src\a.c` has to be a literal that means that path, and leaving the backslashes alone
212/// would produce `\s` and `\a`, one of which is an unknown escape and the other of which is a
213/// bell character.
214pub(crate) fn quoted(name: &str) -> String {
215    let mut out = String::with_capacity(name.len() + 2);
216    out.push('"');
217    for ch in name.chars() {
218        if ch == '\\' || ch == '"' {
219            out.push('\\');
220        }
221        out.push(ch);
222    }
223    out.push('"');
224    out
225}
226
227/// The last component of a path, which is what `__FILE_NAME__` is.
228///
229/// Both separators are cut rather than the platform's own, because a header included as
230/// `sys/types.h` on Windows is found at a path with one of each in it.
231pub(crate) fn base_name(name: &str) -> &str {
232    match name.rfind(['/', '\\']) {
233        Some(at) => &name[at + 1..],
234        None => name,
235    }
236}
237
238/// The directory a file is in, for a quoted include written inside it.
239pub(crate) fn directory_of(name: &str) -> Option<PathBuf> {
240    Path::new(name).parent().map(Path::to_path_buf)
241}
242
243/// The spelling of a token, for the computed include path.
244pub(crate) fn spelling(token: Tok, interner: &Interner) -> &str {
245    match token.kind {
246        PpTokenKind::Punct(p) => p.as_str(),
247        _ => token.value.map_or("", |v| interner.resolve(v)),
248    }
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254
255    #[test]
256    fn a_header_name_keeps_everything_between_the_delimiters() {
257        assert_eq!(
258            header_from_token("<sys/types.h>"),
259            Some(Header { name: "sys/types.h".to_owned(), angled: true })
260        );
261        assert_eq!(
262            header_from_token("\"local.h\""),
263            Some(Header { name: "local.h".to_owned(), angled: false })
264        );
265    }
266
267    #[test]
268    fn a_backslash_in_a_header_name_is_a_backslash() {
269        // Not an escape. A header name is not a string literal, and `\t` here names a file.
270        let header = header_from_token("\"win32\\types.h\"").unwrap();
271        assert_eq!(header.name, "win32\\types.h");
272    }
273
274    #[test]
275    fn an_empty_header_name_is_not_a_header_name() {
276        assert_eq!(header_from_token("<>"), None);
277        assert_eq!(header_from_token("\"\""), None);
278    }
279
280    #[test]
281    fn a_computed_include_concatenates_the_spellings() {
282        let header = header_from_tokens(&["<", "sys", "/", "types", ".", "h", ">"]).unwrap();
283        assert_eq!(header.name, "sys/types.h");
284        assert!(header.angled);
285    }
286
287    #[test]
288    fn a_computed_include_can_expand_to_a_string_literal() {
289        let header = header_from_tokens(&["\"local.h\""]).unwrap();
290        assert_eq!(header.name, "local.h");
291        assert!(!header.angled);
292    }
293
294    #[test]
295    fn a_computed_include_that_is_neither_is_refused() {
296        assert_eq!(header_from_tokens(&[]), None);
297        assert_eq!(header_from_tokens(&["1"]), None);
298        assert_eq!(header_from_tokens(&["<", "a"]), None);
299        assert_eq!(header_from_tokens(&["<", ">"]), None);
300    }
301
302    #[test]
303    fn the_last_angle_bracket_closes_the_name() {
304        // `<a>b>` is not something anyone writes on purpose, but taking the first `>` would
305        // silently drop the rest, and taking the last one at least round trips.
306        let header = header_from_tokens(&["<", "a", ">", "b", ">"]).unwrap();
307        assert_eq!(header.name, "a>b");
308    }
309}