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/// What the two spellings of a header name mean, and the name itself.
145#[derive(Debug, Clone, PartialEq, Eq)]
146pub(crate) struct Header {
147    pub(crate) name: String,
148    pub(crate) angled: bool,
149}
150
151/// Reads a header name out of the token the lexer produced for one.
152///
153/// The delimiters come off and nothing else happens: a header name is not a string literal,
154/// so a backslash in it is a backslash and `\t` names a file whose name contains a `t`
155/// preceded by a backslash, which is what a Windows path needs.
156pub(crate) fn header_from_token(spelling: &str) -> Option<Header> {
157    let angled = spelling.starts_with('<');
158    let close = if angled { '>' } else { '"' };
159    let inner = spelling.strip_prefix(if angled { '<' } else { '"' })?;
160    let inner = inner.strip_suffix(close).unwrap_or(inner);
161    if inner.is_empty() {
162        return None;
163    }
164    Some(Header { name: inner.to_owned(), angled })
165}
166
167/// Reads a header name out of the tokens a macro expanded to.
168///
169/// `#include MACRO` is the computed include, and the standard says only that the tokens are
170/// combined in an implementation defined manner. The manner is that spellings are
171/// concatenated with nothing between them, which is what GCC does in every case that occurs
172/// in real code and is the only choice that makes `<sys/types.h>` come back out as itself.
173pub(crate) fn header_from_tokens(spellings: &[&str]) -> Option<Header> {
174    let first = *spellings.first()?;
175    if first.starts_with('"') && spellings.len() == 1 {
176        return header_from_token(first);
177    }
178    if first != "<" {
179        return None;
180    }
181    let close = spellings.iter().rposition(|s| *s == ">")?;
182    if close < 2 {
183        return None;
184    }
185    let name: String = spellings[1..close].concat();
186    Some(Header { name, angled: true })
187}
188
189/// What a file name is called when the position it was asked about is in no file at all.
190///
191/// The same spelling the diagnostic renderer uses, so there is one word for this and not two.
192pub(crate) const UNKNOWN: &str = "<unknown>";
193
194/// A file name as the string literal `__FILE__` expands to.
195///
196/// A backslash and a double quote are escaped. That is not a nicety on Windows: `__FILE__` for
197/// `C:\src\a.c` has to be a literal that means that path, and leaving the backslashes alone
198/// would produce `\s` and `\a`, one of which is an unknown escape and the other of which is a
199/// bell character.
200pub(crate) fn quoted(name: &str) -> String {
201    let mut out = String::with_capacity(name.len() + 2);
202    out.push('"');
203    for ch in name.chars() {
204        if ch == '\\' || ch == '"' {
205            out.push('\\');
206        }
207        out.push(ch);
208    }
209    out.push('"');
210    out
211}
212
213/// The last component of a path, which is what `__FILE_NAME__` is.
214///
215/// Both separators are cut rather than the platform's own, because a header included as
216/// `sys/types.h` on Windows is found at a path with one of each in it.
217pub(crate) fn base_name(name: &str) -> &str {
218    match name.rfind(['/', '\\']) {
219        Some(at) => &name[at + 1..],
220        None => name,
221    }
222}
223
224/// The directory a file is in, for a quoted include written inside it.
225pub(crate) fn directory_of(name: &str) -> Option<PathBuf> {
226    Path::new(name).parent().map(Path::to_path_buf)
227}
228
229/// The spelling of a token, for the computed include path.
230pub(crate) fn spelling(token: Tok, interner: &Interner) -> &str {
231    match token.kind {
232        PpTokenKind::Punct(p) => p.as_str(),
233        _ => token.value.map_or("", |v| interner.resolve(v)),
234    }
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240
241    #[test]
242    fn a_header_name_keeps_everything_between_the_delimiters() {
243        assert_eq!(
244            header_from_token("<sys/types.h>"),
245            Some(Header { name: "sys/types.h".to_owned(), angled: true })
246        );
247        assert_eq!(
248            header_from_token("\"local.h\""),
249            Some(Header { name: "local.h".to_owned(), angled: false })
250        );
251    }
252
253    #[test]
254    fn a_backslash_in_a_header_name_is_a_backslash() {
255        // Not an escape. A header name is not a string literal, and `\t` here names a file.
256        let header = header_from_token("\"win32\\types.h\"").unwrap();
257        assert_eq!(header.name, "win32\\types.h");
258    }
259
260    #[test]
261    fn an_empty_header_name_is_not_a_header_name() {
262        assert_eq!(header_from_token("<>"), None);
263        assert_eq!(header_from_token("\"\""), None);
264    }
265
266    #[test]
267    fn a_computed_include_concatenates_the_spellings() {
268        let header = header_from_tokens(&["<", "sys", "/", "types", ".", "h", ">"]).unwrap();
269        assert_eq!(header.name, "sys/types.h");
270        assert!(header.angled);
271    }
272
273    #[test]
274    fn a_computed_include_can_expand_to_a_string_literal() {
275        let header = header_from_tokens(&["\"local.h\""]).unwrap();
276        assert_eq!(header.name, "local.h");
277        assert!(!header.angled);
278    }
279
280    #[test]
281    fn a_computed_include_that_is_neither_is_refused() {
282        assert_eq!(header_from_tokens(&[]), None);
283        assert_eq!(header_from_tokens(&["1"]), None);
284        assert_eq!(header_from_tokens(&["<", "a"]), None);
285        assert_eq!(header_from_tokens(&["<", ">"]), None);
286    }
287
288    #[test]
289    fn the_last_angle_bracket_closes_the_name() {
290        // `<a>b>` is not something anyone writes on purpose, but taking the first `>` would
291        // silently drop the rest, and taking the last one at least round trips.
292        let header = header_from_tokens(&["<", "a", ">", "b", ">"]).unwrap();
293        assert_eq!(header.name, "a>b");
294    }
295}