Skip to main content

rucc_session/
fs.rs

1//! The file system the compiler reads through, and the include search path.
2//!
3//! Design: `spec/04-driver-and-cli.md` section 4.4 for the search order, and
4//! `spec/05-preprocessor.md` section 5.4 for what `#include_next` means.
5//!
6//! Nothing below the driver calls `std::fs`. That is what makes the compiler usable as a
7//! library, and it is what makes a preprocessor test a value rather than a temporary
8//! directory: [`MemoryFileSystem`] is a map from path to bytes, and a test that needs a
9//! twelve deep header nest builds one in twelve lines with no clean up to forget.
10//!
11//! ```
12//! use rucc_session::{FileSystem, IncludeForm, MemoryFileSystem, SearchPath};
13//!
14//! let mut fs = MemoryFileSystem::new();
15//! fs.insert("/usr/include/stdio.h", *b"int puts(const char *);\n");
16//!
17//! let mut search = SearchPath::new();
18//! search.push_system("/usr/include");
19//!
20//! let found = search.resolve(&fs, "stdio.h", IncludeForm::Angled, None, 0).unwrap();
21//! assert_eq!(found.name.replace('\\', "/"), "/usr/include/stdio.h");
22//! assert!(found.is_system);
23//! ```
24
25use std::collections::BTreeMap;
26use std::fmt;
27use std::io;
28use std::path::{Path, PathBuf};
29
30use rucc_diag::SourceBytes;
31
32use crate::runtime;
33
34/// Where the compiler reads source from.
35///
36/// There is no `exists`, deliberately. Whether a file is there is answered by trying to read
37/// it, and an interface with a separate question invites the race where the answer changes
38/// between the two calls.
39pub trait FileSystem: fmt::Debug + Send + Sync {
40    /// Reads a file.
41    ///
42    /// # Errors
43    ///
44    /// Whatever the underlying file system says. [`io::ErrorKind::NotFound`] is the ordinary
45    /// case during an include search and is not by itself a problem.
46    fn read(&self, path: &Path) -> io::Result<SourceBytes>;
47
48    /// What this file system calls a file, for deciding that two names are one file.
49    ///
50    /// The multiple include optimization has to answer whether a header has been read
51    /// already, and the name in the directive is not that answer. One header found through
52    /// `-I .` and found again through `-I /tree` arrives under two names, and a project with
53    /// more than one include directory reaches the same header both ways all day. So does a
54    /// file that includes itself, which is the whole point of `#pragma once` in a main file.
55    ///
56    /// The default is [`path_key`], the text with the `.` components taken out, which is all
57    /// a map from name to bytes can say. An implementation backed by a real file system
58    /// resolves the name instead, so that a symlink, a `..` and a relative path all land on
59    /// the same answer. Only called for a file that has already been read, so it is a
60    /// question about a file that is there rather than a probe.
61    fn identity(&self, path: &Path) -> PathBuf {
62        path_key(path)
63    }
64}
65
66/// A file system held in memory, for tests and for embedding the compiler.
67#[derive(Debug, Default)]
68pub struct MemoryFileSystem {
69    files: BTreeMap<PathBuf, SourceBytes>,
70}
71
72impl MemoryFileSystem {
73    /// An empty file system.
74    pub fn new() -> MemoryFileSystem {
75        MemoryFileSystem::default()
76    }
77
78    /// Adds a file, replacing any file already at that path.
79    pub fn insert(
80        &mut self,
81        path: impl Into<PathBuf>,
82        contents: impl AsRef<[u8]> + Send + Sync + 'static,
83    ) {
84        self.files.insert(path_key(&path.into()), SourceBytes::new(contents));
85    }
86
87    /// How many files it holds.
88    pub fn len(&self) -> usize {
89        self.files.len()
90    }
91
92    /// Whether it holds nothing.
93    pub fn is_empty(&self) -> bool {
94        self.files.is_empty()
95    }
96}
97
98impl FileSystem for MemoryFileSystem {
99    fn read(&self, path: &Path) -> io::Result<SourceBytes> {
100        // Through [`path_key`], so that `./dir/x.h` and `dir/x.h` find one file here the way
101        // they do on a real file system. A test that behaves differently from the thing it
102        // stands in for is worse than no test.
103        self.files
104            .get(&path_key(path))
105            .cloned()
106            .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no such file"))
107    }
108}
109
110/// Which spelling an `#include` used.
111#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
112pub enum IncludeForm {
113    /// `#include "local.h"`, which looks next to the including file first.
114    Quoted,
115    /// `#include <stdio.h>`, which does not.
116    Angled,
117}
118
119/// One directory on the search path.
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct Dir {
122    /// The directory, as the user spelled it. Not canonicalised, because a diagnostic that
123    /// says `../include/foo.h` is more use than one naming a path the user never typed.
124    pub path: PathBuf,
125    /// Whether headers found here are system headers, which suppresses warnings in them and
126    /// sets the `3` flag on a `-E` line marker.
127    pub is_system: bool,
128}
129
130/// The key that every spelling of one path shares, as far as text can say.
131///
132/// `Path::components` is what does the work: it drops a trailing separator and the `.` inside
133/// a path, so `/usr/include/` and `/usr/include` are one directory, and `./dir/x.h` and
134/// `dir/x.h` are one file. `..` is left alone, since a component above a symlink does not go
135/// where reading the path suggests.
136///
137/// This is text, not identity. Two names for one file through a symlink or a hard link are two
138/// keys here, where a compiler that asked the file system would get one answer. Asking would
139/// mean a `stat` per include on a path where the whole point is not to open the file at all.
140pub fn path_key(path: &Path) -> PathBuf {
141    path.components().filter(|c| !matches!(c, std::path::Component::CurDir)).collect()
142}
143
144/// Whether two spellings name the same directory, as far as text can say.
145fn same_dir(a: &Path, b: &Path) -> bool {
146    path_key(a) == path_key(b)
147}
148
149/// A header that was found.
150#[derive(Debug, Clone)]
151pub struct Found {
152    /// The path to open, which is the directory joined with the name as written.
153    pub path: PathBuf,
154    /// That path as a string, for the source map and for diagnostics.
155    pub name: String,
156    /// Whether it came from a system directory.
157    pub is_system: bool,
158    /// Where an `#include_next` written in this file should start looking.
159    ///
160    /// One past the entry this header came from, or zero for a header found next to the file
161    /// that included it, because that directory is not on the path and there is nothing to
162    /// continue past. Carrying the answer rather than the position is what keeps the two
163    /// cases from being confused at the call site.
164    pub next: usize,
165    /// The contents.
166    pub bytes: SourceBytes,
167}
168
169/// The directories a header is looked for in, in order.
170///
171/// GCC's order, because a different one produces header shadowing bugs that are miserable to
172/// diagnose: `-iquote` first and only for a quoted include, then `-I`, then `-isystem`, then
173/// the configured system directories, then `-idirafter`. The directory of the including file
174/// comes before all of it for a quoted include, and it is not part of the numbered list
175/// because `#include_next` must not be able to land back on it.
176#[derive(Debug, Default, Clone, PartialEq, Eq)]
177pub struct SearchPath {
178    dirs: Vec<Dir>,
179    /// Where the `-I` directories begin, which is where an angled include starts looking.
180    quote_end: usize,
181    /// Where the `-isystem` and configured system directories begin.
182    bracket_end: usize,
183    /// Where the `-idirafter` directories begin.
184    system_end: usize,
185    /// Whether the directory of the including file has been taken off the front of the quoted
186    /// chain, which is half of what `-I-` does.
187    no_current_dir: bool,
188}
189
190impl SearchPath {
191    /// An empty search path.
192    pub fn new() -> SearchPath {
193        SearchPath::default()
194    }
195
196    /// Adds a `-iquote` directory, searched only for a quoted include.
197    pub fn push_quote(&mut self, dir: impl Into<PathBuf>) {
198        let at = self.quote_end;
199        self.insert(at, dir.into(), false);
200        self.quote_end += 1;
201        self.bracket_end += 1;
202        self.system_end += 1;
203    }
204
205    /// Adds a `-I` directory.
206    pub fn push_bracket(&mut self, dir: impl Into<PathBuf>) {
207        let at = self.bracket_end;
208        self.insert(at, dir.into(), false);
209        self.bracket_end += 1;
210        self.system_end += 1;
211    }
212
213    /// Adds a `-isystem` directory, or one of the target's configured system directories.
214    pub fn push_system(&mut self, dir: impl Into<PathBuf>) {
215        let at = self.system_end;
216        self.insert(at, dir.into(), true);
217        self.system_end += 1;
218    }
219
220    /// Adds a `-idirafter` directory, which is searched after everything else.
221    pub fn push_after(&mut self, dir: impl Into<PathBuf>) {
222        let at = self.dirs.len();
223        self.insert(at, dir.into(), true);
224    }
225
226    fn insert(&mut self, at: usize, path: PathBuf, is_system: bool) {
227        self.dirs.insert(at, Dir { path, is_system });
228    }
229
230    /// Makes every directory added so far reachable only by a quoted include, which is `-I-`.
231    ///
232    /// The flag GCC deprecated in favour of `-iquote` and still supports, because a build system
233    /// old enough to be worth compiling is old enough to pass it. It does two things at once. The
234    /// `-I` directories written before it move into the quoted chain, so `#include <x.h>` stops
235    /// seeing them, and the directory of the including file comes off the front of that chain, so
236    /// `#include "x.h"` stops looking next to the file that wrote it.
237    ///
238    /// The second half is the reason the flag was worth having and the reason it was worth
239    /// dropping. It is the only way to say that a quoted include means a directory the command
240    /// line named rather than whatever happens to sit beside the source, which is what a project
241    /// with two headers of the same name in two directories needs. It is also a global answer to
242    /// a question every include asks separately, which is why `-iquote` replaced it.
243    ///
244    /// A `-iquote` directory given before this stays in the quoted chain, and lands after the
245    /// `-I` directories that just joined it. That is GCC's order and not an accident of the
246    /// implementation: GCC holds `-iquote` back until every `-I` and `-I-` has been dealt with,
247    /// so a `-iquote` is always later in the chain than an `-I` whatever order they were written.
248    pub fn split_quote_chain(&mut self) {
249        let moved: Vec<Dir> = self.dirs.drain(self.quote_end..self.bracket_end).collect();
250        for (at, dir) in moved.into_iter().enumerate() {
251            self.dirs.insert(at, dir);
252        }
253        self.quote_end = self.bracket_end;
254        self.no_current_dir = true;
255    }
256
257    /// Whether the directory of the including file is searched for a quoted include.
258    ///
259    /// False once `-I-` has been given. A caller that has a directory to offer still passes it,
260    /// and this is where it is refused, so that the rule lives with the search path rather than at
261    /// every call site that knows where a file came from.
262    pub fn searches_current_dir(&self) -> bool {
263        !self.no_current_dir
264    }
265
266    /// Drops the directories that are already on the path, the way GCC does.
267    ///
268    /// A duplicate is not a harmless extra entry that costs one failed open. It changes what
269    /// `#include_next` means, which is defined as continuing past the directory the current
270    /// file came from: a header found in the first `/usr/include` writes `#include_next
271    /// <stdint.h>` meaning "the one below me" and finds itself in the second, and a header set
272    /// that ends in a fixed point of its own is one that includes itself forever or answers
273    /// `__has_include_next` yes where the compiler it was written for said no. It shows up as
274    /// soon as somebody passes the system directories on the command line, which the compat
275    /// harness does deliberately and a build system does by accident.
276    ///
277    /// A `-I` that names a system directory loses to the system entry rather than the other way
278    /// round, and that is GCC's rule and is documented as one: keeping the earlier one would
279    /// move a system directory up the order and take the system treatment off the headers in
280    /// it, so the `-I` is the one that goes.
281    ///
282    /// Two names for one directory are two directories here, where GCC compares the device and
283    /// the inode and sees through a symlink. That wants a file system that can answer the
284    /// question and this one deliberately only reads.
285    pub fn remove_duplicates(&mut self) {
286        let mut keep = vec![true; self.dirs.len()];
287        for i in 0..self.dirs.len() {
288            for j in i + 1..self.dirs.len() {
289                if !keep[i] {
290                    break;
291                }
292                if !keep[j] || !same_dir(&self.dirs[i].path, &self.dirs[j].path) {
293                    continue;
294                }
295                if self.dirs[j].is_system && !self.dirs[i].is_system {
296                    keep[i] = false;
297                } else {
298                    keep[j] = false;
299                }
300            }
301        }
302        let (quote, bracket, system) = (self.quote_end, self.bracket_end, self.system_end);
303        let mut at = 0;
304        self.dirs.retain(|_| {
305            let kept = keep[at];
306            if !kept {
307                self.quote_end -= usize::from(at < quote);
308                self.bracket_end -= usize::from(at < bracket);
309                self.system_end -= usize::from(at < system);
310            }
311            at += 1;
312            kept
313        });
314    }
315
316    /// Every directory, in search order.
317    pub fn dirs(&self) -> &[Dir] {
318        &self.dirs
319    }
320
321    /// The first entry an include of this form looks at.
322    ///
323    /// An angled include skips the `-iquote` directories, which is the only difference
324    /// between the two chains once the including file's own directory is out of the way.
325    pub fn start(&self, form: IncludeForm) -> usize {
326        match form {
327            IncludeForm::Quoted => 0,
328            IncludeForm::Angled => self.quote_end,
329        }
330    }
331
332    /// Finds `name`, starting at entry `from` of the search path.
333    ///
334    /// `relative_to` is the directory of the file doing the including, tried first for a
335    /// quoted include and ignored otherwise. Pass `None` for an `#include_next`, which is
336    /// defined as continuing past the directory the current file was found in and so must not
337    /// look next to it again. It is also ignored after [`SearchPath::split_quote_chain`], which
338    /// is what `-I-` asks for.
339    ///
340    /// An absolute name is opened directly and the search path is not consulted, which is
341    /// what every C compiler does and what a generated header with an absolute path needs.
342    pub fn resolve(
343        &self,
344        fs: &dyn FileSystem,
345        name: &str,
346        form: IncludeForm,
347        relative_to: Option<&Path>,
348        from: usize,
349    ) -> Option<Found> {
350        let as_path = Path::new(name);
351        if is_absolute(as_path) {
352            let bytes = open(fs, as_path).ok()?;
353            return Some(Found {
354                path: as_path.to_path_buf(),
355                name: name.to_owned(),
356                is_system: false,
357                next: 0,
358                bytes,
359            });
360        }
361        if form == IncludeForm::Quoted && self.searches_current_dir() {
362            if let Some(dir) = relative_to {
363                let path = dir.join(as_path);
364                if let Ok(bytes) = open(fs, &path) {
365                    return Some(Found {
366                        name: display(&path),
367                        path,
368                        is_system: false,
369                        // The including file's own directory is not an entry on the path, so
370                        // an `#include_next` from a header found there starts at the top of
371                        // the path rather than one past a position that does not exist.
372                        next: 0,
373                        bytes,
374                    });
375                }
376            }
377        }
378        for (at, dir) in self.dirs.iter().enumerate().skip(from) {
379            let path = dir.path.join(as_path);
380            if let Ok(bytes) = open(fs, &path) {
381                return Some(Found {
382                    name: display(&path),
383                    path,
384                    is_system: dir.is_system,
385                    next: at + 1,
386                    bytes,
387                });
388            }
389        }
390        None
391    }
392
393    /// The directories a failed [`SearchPath::resolve`] with the same arguments looked in.
394    ///
395    /// `spec/05-preprocessor.md` section 5.7 makes printing this the required behaviour for a
396    /// failed include, because "file not found" without the list of places that were tried is
397    /// the diagnostic that wastes the most time in this part of the compiler.
398    pub fn tried(
399        &self,
400        name: &str,
401        form: IncludeForm,
402        relative_to: Option<&Path>,
403        from: usize,
404    ) -> Vec<PathBuf> {
405        if is_absolute(Path::new(name)) {
406            return Vec::new();
407        }
408        let mut list = Vec::new();
409        if form == IncludeForm::Quoted && self.searches_current_dir() {
410            if let Some(dir) = relative_to {
411                list.push(dir.to_path_buf());
412            }
413        }
414        list.extend(self.dirs.iter().skip(from).map(|d| d.path.clone()));
415        list
416    }
417}
418
419/// Reads a path the search produced, from the shipped headers first and the disk after.
420///
421/// This is the one place the compiler's own headers are handed out, and it is here rather
422/// than in a [`FileSystem`] implementation on purpose. They are not files, they belong to
423/// every implementation of the trait equally, and the only way to reach them is through a
424/// search path entry spelled [`runtime::DIR`], which no real directory can be spelled as.
425fn open(fs: &dyn FileSystem, path: &Path) -> io::Result<SourceBytes> {
426    match runtime::read(path) {
427        Some(bytes) => Ok(bytes),
428        None => fs.read(path),
429    }
430}
431
432/// A path as a string, lossily, because a diagnostic has to say something.
433fn display(path: &Path) -> String {
434    path.to_string_lossy().into_owned()
435}
436
437/// Whether an include name names a file outright rather than one to be searched for.
438///
439/// `Path::is_absolute` is false for `/usr/include/stdio.h` on Windows, because it has no
440/// drive letter. A C file that says `#include "/usr/include/stdio.h"` means a path from the
441/// root whatever host is compiling it, so a leading separator counts here as well.
442fn is_absolute(path: &Path) -> bool {
443    path.is_absolute() || path.has_root()
444}
445
446#[cfg(test)]
447mod tests {
448    use super::*;
449
450    fn fs_with(files: &[&str]) -> MemoryFileSystem {
451        let mut fs = MemoryFileSystem::new();
452        for f in files {
453            fs.insert(*f, format!("/* {f} */\n").into_bytes());
454        }
455        fs
456    }
457
458    fn text(found: &Found) -> String {
459        String::from_utf8_lossy(found.bytes.as_slice()).into_owned()
460    }
461
462    /// A path with forward slashes, because `Path::join` uses a backslash on Windows and
463    /// these tests are about the search order rather than about separators.
464    fn norm(path: &str) -> String {
465        path.replace('\\', "/")
466    }
467
468    #[test]
469    fn a_missing_file_is_not_found_rather_than_an_error() {
470        let fs = MemoryFileSystem::new();
471        let kind = fs.read(Path::new("/nope.h")).err().map(|e| e.kind());
472        assert_eq!(kind, Some(io::ErrorKind::NotFound));
473        assert!(fs.is_empty());
474    }
475
476    #[test]
477    fn quote_directories_are_invisible_to_an_angled_include() {
478        let fs = fs_with(&["/q/a.h", "/i/a.h"]);
479        let mut search = SearchPath::new();
480        search.push_quote("/q");
481        search.push_bracket("/i");
482
483        let quoted = search.resolve(&fs, "a.h", IncludeForm::Quoted, None, 0).unwrap();
484        assert_eq!(norm(&quoted.name), "/q/a.h");
485        let angled = search
486            .resolve(&fs, "a.h", IncludeForm::Angled, None, search.start(IncludeForm::Angled))
487            .unwrap();
488        assert_eq!(norm(&angled.name), "/i/a.h");
489    }
490
491    #[test]
492    fn the_including_files_own_directory_comes_first_for_a_quoted_include() {
493        let fs = fs_with(&["/src/a.h", "/i/a.h"]);
494        let mut search = SearchPath::new();
495        search.push_bracket("/i");
496        let here = Path::new("/src");
497
498        let quoted = search.resolve(&fs, "a.h", IncludeForm::Quoted, Some(here), 0).unwrap();
499        assert_eq!(norm(&quoted.name), "/src/a.h");
500        // An angled include does not look there, even though it was passed.
501        let angled = search.resolve(&fs, "a.h", IncludeForm::Angled, Some(here), 0).unwrap();
502        assert_eq!(norm(&angled.name), "/i/a.h");
503    }
504
505    #[test]
506    fn the_order_is_iquote_then_i_then_isystem_then_idirafter() {
507        let fs = fs_with(&["/after/a.h", "/sys/a.h", "/i/a.h", "/q/a.h"]);
508        let mut search = SearchPath::new();
509        // Pushed in an order that is not the search order, because a driver reads the command
510        // line left to right and the groups interleave.
511        search.push_after("/after");
512        search.push_system("/sys");
513        search.push_bracket("/i");
514        search.push_quote("/q");
515        let order: Vec<_> = search.dirs().iter().map(|d| norm(&d.path.to_string_lossy())).collect();
516        assert_eq!(order, ["/q", "/i", "/sys", "/after"]);
517
518        let found = search.resolve(&fs, "a.h", IncludeForm::Quoted, None, 0).unwrap();
519        assert_eq!(norm(&found.name), "/q/a.h");
520        assert_eq!(found.next, 1);
521    }
522
523    #[test]
524    fn a_directory_already_on_the_path_is_dropped_rather_than_searched_twice() {
525        let mut search = SearchPath::new();
526        search.push_system("/usr/local/include");
527        search.push_system("/usr/include");
528        search.push_system("/usr/local/include");
529        search.push_system("/usr/include/");
530        search.remove_duplicates();
531        let order: Vec<_> = search.dirs().iter().map(|d| norm(&d.path.to_string_lossy())).collect();
532        // The first spelling is the one kept, trailing separator and all, because it is the one
533        // a diagnostic will name and the two are the same directory.
534        assert_eq!(order, ["/usr/local/include", "/usr/include"]);
535    }
536
537    #[test]
538    fn a_duplicate_is_what_makes_include_next_find_the_file_it_is_standing_in() {
539        // The bug this exists for. A header found in the first `/usr/include` writes
540        // `#include_next <a.h>` meaning the copy below it, and with the directory on the path
541        // twice the copy below it is itself.
542        let fs = fs_with(&["/usr/include/a.h"]);
543        let mut search = SearchPath::new();
544        search.push_system("/usr/include");
545        search.push_system("/usr/include");
546        let first = search.resolve(&fs, "a.h", IncludeForm::Angled, None, 0).unwrap();
547        assert!(search.resolve(&fs, "a.h", IncludeForm::Angled, None, first.next).is_some());
548        search.remove_duplicates();
549        let first = search.resolve(&fs, "a.h", IncludeForm::Angled, None, 0).unwrap();
550        assert!(search.resolve(&fs, "a.h", IncludeForm::Angled, None, first.next).is_none());
551    }
552
553    #[test]
554    fn a_bracket_directory_that_names_a_system_one_is_the_entry_that_goes() {
555        // GCC's documented rule. Keeping the `-I` would move a system directory up the order
556        // and take the system treatment off every header in it.
557        let fs = fs_with(&["/usr/include/a.h"]);
558        let mut search = SearchPath::new();
559        search.push_bracket("/usr/include");
560        search.push_bracket("/i");
561        search.push_system("/usr/include");
562        search.remove_duplicates();
563        let order: Vec<_> = search.dirs().iter().map(|d| norm(&d.path.to_string_lossy())).collect();
564        assert_eq!(order, ["/i", "/usr/include"]);
565        assert!(search.resolve(&fs, "a.h", IncludeForm::Angled, None, 0).unwrap().is_system);
566    }
567
568    #[test]
569    fn dropping_an_entry_keeps_the_group_boundaries_where_the_groups_are() {
570        let fs = fs_with(&["/q/a.h", "/i/a.h"]);
571        let mut search = SearchPath::new();
572        search.push_quote("/q");
573        search.push_quote("/q");
574        search.push_bracket("/i");
575        search.push_bracket("/i");
576        search.remove_duplicates();
577        // An angled include still skips the one `-iquote` entry left rather than a stale two.
578        let at = search.start(IncludeForm::Angled);
579        let found = search.resolve(&fs, "a.h", IncludeForm::Angled, None, at).unwrap();
580        assert_eq!(norm(&found.name), "/i/a.h");
581    }
582
583    #[test]
584    fn splitting_the_chain_takes_the_bracket_directories_out_of_an_angled_search() {
585        let fs = fs_with(&["/i/a.h", "/sys/a.h"]);
586        let mut search = SearchPath::new();
587        search.push_bracket("/i");
588        search.push_system("/sys");
589        search.split_quote_chain();
590
591        let quoted = search.resolve(&fs, "a.h", IncludeForm::Quoted, None, 0).unwrap();
592        assert_eq!(norm(&quoted.name), "/i/a.h");
593        let at = search.start(IncludeForm::Angled);
594        let angled = search.resolve(&fs, "a.h", IncludeForm::Angled, None, at).unwrap();
595        assert_eq!(norm(&angled.name), "/sys/a.h");
596    }
597
598    #[test]
599    fn a_quote_directory_given_before_the_split_lands_after_the_bracket_ones() {
600        // `-Iinc1 -iquote inc2 -I-`, which GCC answers with a quoted chain of `inc1` then
601        // `inc2`, because it holds `-iquote` back until every `-I` has been dealt with.
602        let mut search = SearchPath::new();
603        search.push_bracket("/inc1");
604        search.push_quote("/inc2");
605        search.push_system("/sys");
606        search.split_quote_chain();
607        let order: Vec<_> = search.dirs().iter().map(|d| norm(&d.path.to_string_lossy())).collect();
608        assert_eq!(order, ["/inc1", "/inc2", "/sys"]);
609        assert_eq!(search.start(IncludeForm::Angled), 2);
610    }
611
612    #[test]
613    fn a_bracket_directory_given_after_the_split_is_visible_to_both_chains() {
614        // `-Iinc1 -I- -Iinc2`. `inc1` is quoted only and `inc2` is an ordinary `-I`, which a
615        // quoted include reaches as well because the quoted chain runs on into the bracket one.
616        let fs = fs_with(&["/inc1/a.h", "/inc2/b.h"]);
617        let mut search = SearchPath::new();
618        search.push_bracket("/inc1");
619        search.split_quote_chain();
620        search.push_bracket("/inc2");
621
622        let at = search.start(IncludeForm::Angled);
623        assert!(search.resolve(&fs, "a.h", IncludeForm::Angled, None, at).is_none());
624        assert!(search.resolve(&fs, "b.h", IncludeForm::Angled, None, at).is_some());
625        assert!(search.resolve(&fs, "a.h", IncludeForm::Quoted, None, 0).is_some());
626        assert!(search.resolve(&fs, "b.h", IncludeForm::Quoted, None, 0).is_some());
627    }
628
629    #[test]
630    fn splitting_the_chain_stops_a_quoted_include_looking_next_to_the_file_that_wrote_it() {
631        let fs = fs_with(&["/src/a.h"]);
632        let mut search = SearchPath::new();
633        let here = Path::new("/src");
634        assert!(search.resolve(&fs, "a.h", IncludeForm::Quoted, Some(here), 0).is_some());
635        search.split_quote_chain();
636        assert!(search.resolve(&fs, "a.h", IncludeForm::Quoted, Some(here), 0).is_none());
637        // And the directory is not named among the places that were tried, since it was not one.
638        assert!(search.tried("a.h", IncludeForm::Quoted, Some(here), 0).is_empty());
639    }
640
641    #[test]
642    fn a_system_directory_marks_what_it_holds_as_a_system_header() {
643        let fs = fs_with(&["/i/a.h", "/sys/b.h", "/after/c.h"]);
644        let mut search = SearchPath::new();
645        search.push_bracket("/i");
646        search.push_system("/sys");
647        search.push_after("/after");
648        let get = |n| search.resolve(&fs, n, IncludeForm::Angled, None, 0).unwrap();
649        assert!(!get("a.h").is_system);
650        assert!(get("b.h").is_system);
651        assert!(get("c.h").is_system);
652    }
653
654    #[test]
655    fn include_next_continues_past_the_directory_the_current_file_came_from() {
656        let fs = fs_with(&["/a/limits.h", "/b/limits.h", "/c/limits.h"]);
657        let mut search = SearchPath::new();
658        search.push_bracket("/a");
659        search.push_bracket("/b");
660        search.push_bracket("/c");
661
662        let first = search.resolve(&fs, "limits.h", IncludeForm::Angled, None, 0).unwrap();
663        assert_eq!(norm(&first.name), "/a/limits.h");
664        let second =
665            search.resolve(&fs, "limits.h", IncludeForm::Angled, None, first.next).unwrap();
666        assert_eq!(norm(&second.name), "/b/limits.h");
667        let third =
668            search.resolve(&fs, "limits.h", IncludeForm::Angled, None, second.next).unwrap();
669        assert_eq!(norm(&third.name), "/c/limits.h");
670        assert!(search.resolve(&fs, "limits.h", IncludeForm::Angled, None, third.next).is_none());
671    }
672
673    #[test]
674    fn a_name_with_a_directory_in_it_is_joined_onto_each_entry() {
675        let fs = fs_with(&["/i/sys/types.h"]);
676        let mut search = SearchPath::new();
677        search.push_bracket("/i");
678        let found = search.resolve(&fs, "sys/types.h", IncludeForm::Angled, None, 0).unwrap();
679        assert_eq!(norm(&found.name), "/i/sys/types.h");
680        assert_eq!(text(&found), "/* /i/sys/types.h */\n");
681    }
682
683    #[test]
684    fn an_absolute_name_ignores_the_search_path() {
685        let fs = fs_with(&["/gen/config.h", "/i/gen/config.h"]);
686        let mut search = SearchPath::new();
687        search.push_bracket("/i");
688        let found = search.resolve(&fs, "/gen/config.h", IncludeForm::Angled, None, 0).unwrap();
689        assert_eq!(norm(&found.name), "/gen/config.h");
690        assert!(search.tried("/gen/config.h", IncludeForm::Angled, None, 0).is_empty());
691    }
692
693    #[test]
694    fn the_list_of_places_tried_is_the_list_that_was_searched() {
695        let fs = MemoryFileSystem::new();
696        let mut search = SearchPath::new();
697        search.push_quote("/q");
698        search.push_bracket("/i");
699        search.push_system("/sys");
700        let here = Path::new("/src");
701
702        assert!(search.resolve(&fs, "a.h", IncludeForm::Quoted, Some(here), 0).is_none());
703        let tried = search.tried("a.h", IncludeForm::Quoted, Some(here), 0);
704        let tried: Vec<_> = tried.iter().map(|p| norm(&p.to_string_lossy())).collect();
705        assert_eq!(tried, ["/src", "/q", "/i", "/sys"]);
706
707        let start = search.start(IncludeForm::Angled);
708        let tried = search.tried("a.h", IncludeForm::Angled, Some(here), start);
709        let tried: Vec<_> = tried.iter().map(|p| norm(&p.to_string_lossy())).collect();
710        assert_eq!(tried, ["/i", "/sys"]);
711    }
712
713    #[test]
714    fn a_header_found_next_to_its_includer_does_not_skip_the_whole_path_afterwards() {
715        // `at` for a file found beside its includer has to leave `at + 1` at the top of the
716        // path, because the directory it was found in is not on the path at all.
717        let fs = fs_with(&["/src/a.h", "/i/b.h"]);
718        let mut search = SearchPath::new();
719        search.push_bracket("/i");
720        let found =
721            search.resolve(&fs, "a.h", IncludeForm::Quoted, Some(Path::new("/src")), 0).unwrap();
722        assert_eq!(found.next, 0);
723        let next = search.resolve(&fs, "b.h", IncludeForm::Angled, None, found.next).unwrap();
724        assert_eq!(norm(&next.name), "/i/b.h");
725    }
726}