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 /// Why the target's own system directories are not on here, when somebody knows.
189 missing_system: Option<String>,
190}
191
192impl SearchPath {
193 /// An empty search path.
194 pub fn new() -> SearchPath {
195 SearchPath::default()
196 }
197
198 /// Adds a `-iquote` directory, searched only for a quoted include.
199 pub fn push_quote(&mut self, dir: impl Into<PathBuf>) {
200 let at = self.quote_end;
201 self.insert(at, dir.into(), false);
202 self.quote_end += 1;
203 self.bracket_end += 1;
204 self.system_end += 1;
205 }
206
207 /// Adds a `-I` directory.
208 pub fn push_bracket(&mut self, dir: impl Into<PathBuf>) {
209 let at = self.bracket_end;
210 self.insert(at, dir.into(), false);
211 self.bracket_end += 1;
212 self.system_end += 1;
213 }
214
215 /// Adds a `-isystem` directory, or one of the target's configured system directories.
216 pub fn push_system(&mut self, dir: impl Into<PathBuf>) {
217 let at = self.system_end;
218 self.insert(at, dir.into(), true);
219 self.system_end += 1;
220 }
221
222 /// Adds a `-idirafter` directory, which is searched after everything else.
223 pub fn push_after(&mut self, dir: impl Into<PathBuf>) {
224 let at = self.dirs.len();
225 self.insert(at, dir.into(), true);
226 }
227
228 fn insert(&mut self, at: usize, path: PathBuf, is_system: bool) {
229 self.dirs.insert(at, Dir { path, is_system });
230 }
231
232 /// Makes every directory added so far reachable only by a quoted include, which is `-I-`.
233 ///
234 /// The flag GCC deprecated in favour of `-iquote` and still supports, because a build system
235 /// old enough to be worth compiling is old enough to pass it. It does two things at once. The
236 /// `-I` directories written before it move into the quoted chain, so `#include <x.h>` stops
237 /// seeing them, and the directory of the including file comes off the front of that chain, so
238 /// `#include "x.h"` stops looking next to the file that wrote it.
239 ///
240 /// The second half is the reason the flag was worth having and the reason it was worth
241 /// dropping. It is the only way to say that a quoted include means a directory the command
242 /// line named rather than whatever happens to sit beside the source, which is what a project
243 /// with two headers of the same name in two directories needs. It is also a global answer to
244 /// a question every include asks separately, which is why `-iquote` replaced it.
245 ///
246 /// A `-iquote` directory given before this stays in the quoted chain, and lands after the
247 /// `-I` directories that just joined it. That is GCC's order and not an accident of the
248 /// implementation: GCC holds `-iquote` back until every `-I` and `-I-` has been dealt with,
249 /// so a `-iquote` is always later in the chain than an `-I` whatever order they were written.
250 pub fn split_quote_chain(&mut self) {
251 let moved: Vec<Dir> = self.dirs.drain(self.quote_end..self.bracket_end).collect();
252 for (at, dir) in moved.into_iter().enumerate() {
253 self.dirs.insert(at, dir);
254 }
255 self.quote_end = self.bracket_end;
256 self.no_current_dir = true;
257 }
258
259 /// Records why this target has no system directories, for whoever has to report a header that
260 /// was not found.
261 ///
262 /// The driver is the only thing that knows the answer and the preprocessor is the only thing in
263 /// a position to use it, and a header that could not be found is the one moment where it helps.
264 /// Saying it earlier would mean refusing a program that includes none of the library, which for
265 /// a target whose headers nobody may redistribute is exactly the program that has to keep
266 /// working, so the reason travels with the path and waits.
267 pub fn explain_missing_system(&mut self, why: impl Into<String>) {
268 self.missing_system = Some(why.into());
269 }
270
271 /// What to add to a header that was not found, or [`None`] when nobody left a reason.
272 pub fn missing_system(&self) -> Option<&str> {
273 self.missing_system.as_deref()
274 }
275
276 /// Whether the directory of the including file is searched for a quoted include.
277 ///
278 /// False once `-I-` has been given. A caller that has a directory to offer still passes it,
279 /// and this is where it is refused, so that the rule lives with the search path rather than at
280 /// every call site that knows where a file came from.
281 pub fn searches_current_dir(&self) -> bool {
282 !self.no_current_dir
283 }
284
285 /// Drops the directories that are already on the path, the way GCC does.
286 ///
287 /// A duplicate is not a harmless extra entry that costs one failed open. It changes what
288 /// `#include_next` means, which is defined as continuing past the directory the current
289 /// file came from: a header found in the first `/usr/include` writes `#include_next
290 /// <stdint.h>` meaning "the one below me" and finds itself in the second, and a header set
291 /// that ends in a fixed point of its own is one that includes itself forever or answers
292 /// `__has_include_next` yes where the compiler it was written for said no. It shows up as
293 /// soon as somebody passes the system directories on the command line, which the compat
294 /// harness does deliberately and a build system does by accident.
295 ///
296 /// A `-I` that names a system directory loses to the system entry rather than the other way
297 /// round, and that is GCC's rule and is documented as one: keeping the earlier one would
298 /// move a system directory up the order and take the system treatment off the headers in
299 /// it, so the `-I` is the one that goes.
300 ///
301 /// Two names for one directory are two directories here, where GCC compares the device and
302 /// the inode and sees through a symlink. That wants a file system that can answer the
303 /// question and this one deliberately only reads.
304 pub fn remove_duplicates(&mut self) {
305 let mut keep = vec![true; self.dirs.len()];
306 for i in 0..self.dirs.len() {
307 for j in i + 1..self.dirs.len() {
308 if !keep[i] {
309 break;
310 }
311 if !keep[j] || !same_dir(&self.dirs[i].path, &self.dirs[j].path) {
312 continue;
313 }
314 if self.dirs[j].is_system && !self.dirs[i].is_system {
315 keep[i] = false;
316 } else {
317 keep[j] = false;
318 }
319 }
320 }
321 let (quote, bracket, system) = (self.quote_end, self.bracket_end, self.system_end);
322 let mut at = 0;
323 self.dirs.retain(|_| {
324 let kept = keep[at];
325 if !kept {
326 self.quote_end -= usize::from(at < quote);
327 self.bracket_end -= usize::from(at < bracket);
328 self.system_end -= usize::from(at < system);
329 }
330 at += 1;
331 kept
332 });
333 }
334
335 /// Every directory, in search order.
336 pub fn dirs(&self) -> &[Dir] {
337 &self.dirs
338 }
339
340 /// The first entry an include of this form looks at.
341 ///
342 /// An angled include skips the `-iquote` directories, which is the only difference
343 /// between the two chains once the including file's own directory is out of the way.
344 pub fn start(&self, form: IncludeForm) -> usize {
345 match form {
346 IncludeForm::Quoted => 0,
347 IncludeForm::Angled => self.quote_end,
348 }
349 }
350
351 /// Finds `name`, starting at entry `from` of the search path.
352 ///
353 /// `relative_to` is the directory of the file doing the including, tried first for a
354 /// quoted include and ignored otherwise. Pass `None` for an `#include_next`, which is
355 /// defined as continuing past the directory the current file was found in and so must not
356 /// look next to it again. It is also ignored after [`SearchPath::split_quote_chain`], which
357 /// is what `-I-` asks for.
358 ///
359 /// An absolute name is opened directly and the search path is not consulted, which is
360 /// what every C compiler does and what a generated header with an absolute path needs.
361 pub fn resolve(
362 &self,
363 fs: &dyn FileSystem,
364 name: &str,
365 form: IncludeForm,
366 relative_to: Option<&Path>,
367 from: usize,
368 ) -> Option<Found> {
369 let as_path = Path::new(name);
370 if is_absolute(as_path) {
371 let bytes = open(fs, as_path).ok()?;
372 return Some(Found {
373 path: as_path.to_path_buf(),
374 name: name.to_owned(),
375 is_system: false,
376 next: 0,
377 bytes,
378 });
379 }
380 if form == IncludeForm::Quoted && self.searches_current_dir() {
381 if let Some(dir) = relative_to {
382 let path = dir.join(as_path);
383 if let Ok(bytes) = open(fs, &path) {
384 return Some(Found {
385 name: display(&path),
386 path,
387 is_system: false,
388 // The including file's own directory is not an entry on the path, so
389 // an `#include_next` from a header found there starts at the top of
390 // the path rather than one past a position that does not exist.
391 next: 0,
392 bytes,
393 });
394 }
395 }
396 }
397 for (at, dir) in self.dirs.iter().enumerate().skip(from) {
398 let path = dir.path.join(as_path);
399 if let Ok(bytes) = open(fs, &path) {
400 return Some(Found {
401 name: display(&path),
402 path,
403 is_system: dir.is_system,
404 next: at + 1,
405 bytes,
406 });
407 }
408 }
409 None
410 }
411
412 /// The directories a failed [`SearchPath::resolve`] with the same arguments looked in.
413 ///
414 /// `spec/05-preprocessor.md` section 5.7 makes printing this the required behaviour for a
415 /// failed include, because "file not found" without the list of places that were tried is
416 /// the diagnostic that wastes the most time in this part of the compiler.
417 pub fn tried(
418 &self,
419 name: &str,
420 form: IncludeForm,
421 relative_to: Option<&Path>,
422 from: usize,
423 ) -> Vec<PathBuf> {
424 if is_absolute(Path::new(name)) {
425 return Vec::new();
426 }
427 let mut list = Vec::new();
428 if form == IncludeForm::Quoted && self.searches_current_dir() {
429 if let Some(dir) = relative_to {
430 list.push(dir.to_path_buf());
431 }
432 }
433 list.extend(self.dirs.iter().skip(from).map(|d| d.path.clone()));
434 list
435 }
436}
437
438/// Reads a path the search produced, from the shipped headers first and the disk after.
439///
440/// This is the one place the compiler's own headers are handed out, and it is here rather
441/// than in a [`FileSystem`] implementation on purpose. They are not files, they belong to
442/// every implementation of the trait equally, and the only way to reach them is through a
443/// search path entry spelled [`runtime::DIR`], which no real directory can be spelled as.
444fn open(fs: &dyn FileSystem, path: &Path) -> io::Result<SourceBytes> {
445 match runtime::read(path) {
446 Some(bytes) => Ok(bytes),
447 None => fs.read(path),
448 }
449}
450
451/// A path as a string, lossily, because a diagnostic has to say something.
452fn display(path: &Path) -> String {
453 path.to_string_lossy().into_owned()
454}
455
456/// Whether an include name names a file outright rather than one to be searched for.
457///
458/// `Path::is_absolute` is false for `/usr/include/stdio.h` on Windows, because it has no
459/// drive letter. A C file that says `#include "/usr/include/stdio.h"` means a path from the
460/// root whatever host is compiling it, so a leading separator counts here as well.
461fn is_absolute(path: &Path) -> bool {
462 path.is_absolute() || path.has_root()
463}
464
465#[cfg(test)]
466mod tests {
467 use super::*;
468
469 fn fs_with(files: &[&str]) -> MemoryFileSystem {
470 let mut fs = MemoryFileSystem::new();
471 for f in files {
472 fs.insert(*f, format!("/* {f} */\n").into_bytes());
473 }
474 fs
475 }
476
477 fn text(found: &Found) -> String {
478 String::from_utf8_lossy(found.bytes.as_slice()).into_owned()
479 }
480
481 /// A path with forward slashes, because `Path::join` uses a backslash on Windows and
482 /// these tests are about the search order rather than about separators.
483 fn norm(path: &str) -> String {
484 path.replace('\\', "/")
485 }
486
487 #[test]
488 fn a_missing_file_is_not_found_rather_than_an_error() {
489 let fs = MemoryFileSystem::new();
490 let kind = fs.read(Path::new("/nope.h")).err().map(|e| e.kind());
491 assert_eq!(kind, Some(io::ErrorKind::NotFound));
492 assert!(fs.is_empty());
493 }
494
495 #[test]
496 fn quote_directories_are_invisible_to_an_angled_include() {
497 let fs = fs_with(&["/q/a.h", "/i/a.h"]);
498 let mut search = SearchPath::new();
499 search.push_quote("/q");
500 search.push_bracket("/i");
501
502 let quoted = search.resolve(&fs, "a.h", IncludeForm::Quoted, None, 0).unwrap();
503 assert_eq!(norm("ed.name), "/q/a.h");
504 let angled = search
505 .resolve(&fs, "a.h", IncludeForm::Angled, None, search.start(IncludeForm::Angled))
506 .unwrap();
507 assert_eq!(norm(&angled.name), "/i/a.h");
508 }
509
510 #[test]
511 fn the_including_files_own_directory_comes_first_for_a_quoted_include() {
512 let fs = fs_with(&["/src/a.h", "/i/a.h"]);
513 let mut search = SearchPath::new();
514 search.push_bracket("/i");
515 let here = Path::new("/src");
516
517 let quoted = search.resolve(&fs, "a.h", IncludeForm::Quoted, Some(here), 0).unwrap();
518 assert_eq!(norm("ed.name), "/src/a.h");
519 // An angled include does not look there, even though it was passed.
520 let angled = search.resolve(&fs, "a.h", IncludeForm::Angled, Some(here), 0).unwrap();
521 assert_eq!(norm(&angled.name), "/i/a.h");
522 }
523
524 #[test]
525 fn the_order_is_iquote_then_i_then_isystem_then_idirafter() {
526 let fs = fs_with(&["/after/a.h", "/sys/a.h", "/i/a.h", "/q/a.h"]);
527 let mut search = SearchPath::new();
528 // Pushed in an order that is not the search order, because a driver reads the command
529 // line left to right and the groups interleave.
530 search.push_after("/after");
531 search.push_system("/sys");
532 search.push_bracket("/i");
533 search.push_quote("/q");
534 let order: Vec<_> = search.dirs().iter().map(|d| norm(&d.path.to_string_lossy())).collect();
535 assert_eq!(order, ["/q", "/i", "/sys", "/after"]);
536
537 let found = search.resolve(&fs, "a.h", IncludeForm::Quoted, None, 0).unwrap();
538 assert_eq!(norm(&found.name), "/q/a.h");
539 assert_eq!(found.next, 1);
540 }
541
542 #[test]
543 fn a_directory_already_on_the_path_is_dropped_rather_than_searched_twice() {
544 let mut search = SearchPath::new();
545 search.push_system("/usr/local/include");
546 search.push_system("/usr/include");
547 search.push_system("/usr/local/include");
548 search.push_system("/usr/include/");
549 search.remove_duplicates();
550 let order: Vec<_> = search.dirs().iter().map(|d| norm(&d.path.to_string_lossy())).collect();
551 // The first spelling is the one kept, trailing separator and all, because it is the one
552 // a diagnostic will name and the two are the same directory.
553 assert_eq!(order, ["/usr/local/include", "/usr/include"]);
554 }
555
556 #[test]
557 fn a_duplicate_is_what_makes_include_next_find_the_file_it_is_standing_in() {
558 // The bug this exists for. A header found in the first `/usr/include` writes
559 // `#include_next <a.h>` meaning the copy below it, and with the directory on the path
560 // twice the copy below it is itself.
561 let fs = fs_with(&["/usr/include/a.h"]);
562 let mut search = SearchPath::new();
563 search.push_system("/usr/include");
564 search.push_system("/usr/include");
565 let first = search.resolve(&fs, "a.h", IncludeForm::Angled, None, 0).unwrap();
566 assert!(search.resolve(&fs, "a.h", IncludeForm::Angled, None, first.next).is_some());
567 search.remove_duplicates();
568 let first = search.resolve(&fs, "a.h", IncludeForm::Angled, None, 0).unwrap();
569 assert!(search.resolve(&fs, "a.h", IncludeForm::Angled, None, first.next).is_none());
570 }
571
572 #[test]
573 fn a_bracket_directory_that_names_a_system_one_is_the_entry_that_goes() {
574 // GCC's documented rule. Keeping the `-I` would move a system directory up the order
575 // and take the system treatment off every header in it.
576 let fs = fs_with(&["/usr/include/a.h"]);
577 let mut search = SearchPath::new();
578 search.push_bracket("/usr/include");
579 search.push_bracket("/i");
580 search.push_system("/usr/include");
581 search.remove_duplicates();
582 let order: Vec<_> = search.dirs().iter().map(|d| norm(&d.path.to_string_lossy())).collect();
583 assert_eq!(order, ["/i", "/usr/include"]);
584 assert!(search.resolve(&fs, "a.h", IncludeForm::Angled, None, 0).unwrap().is_system);
585 }
586
587 #[test]
588 fn dropping_an_entry_keeps_the_group_boundaries_where_the_groups_are() {
589 let fs = fs_with(&["/q/a.h", "/i/a.h"]);
590 let mut search = SearchPath::new();
591 search.push_quote("/q");
592 search.push_quote("/q");
593 search.push_bracket("/i");
594 search.push_bracket("/i");
595 search.remove_duplicates();
596 // An angled include still skips the one `-iquote` entry left rather than a stale two.
597 let at = search.start(IncludeForm::Angled);
598 let found = search.resolve(&fs, "a.h", IncludeForm::Angled, None, at).unwrap();
599 assert_eq!(norm(&found.name), "/i/a.h");
600 }
601
602 #[test]
603 fn splitting_the_chain_takes_the_bracket_directories_out_of_an_angled_search() {
604 let fs = fs_with(&["/i/a.h", "/sys/a.h"]);
605 let mut search = SearchPath::new();
606 search.push_bracket("/i");
607 search.push_system("/sys");
608 search.split_quote_chain();
609
610 let quoted = search.resolve(&fs, "a.h", IncludeForm::Quoted, None, 0).unwrap();
611 assert_eq!(norm("ed.name), "/i/a.h");
612 let at = search.start(IncludeForm::Angled);
613 let angled = search.resolve(&fs, "a.h", IncludeForm::Angled, None, at).unwrap();
614 assert_eq!(norm(&angled.name), "/sys/a.h");
615 }
616
617 #[test]
618 fn a_quote_directory_given_before_the_split_lands_after_the_bracket_ones() {
619 // `-Iinc1 -iquote inc2 -I-`, which GCC answers with a quoted chain of `inc1` then
620 // `inc2`, because it holds `-iquote` back until every `-I` has been dealt with.
621 let mut search = SearchPath::new();
622 search.push_bracket("/inc1");
623 search.push_quote("/inc2");
624 search.push_system("/sys");
625 search.split_quote_chain();
626 let order: Vec<_> = search.dirs().iter().map(|d| norm(&d.path.to_string_lossy())).collect();
627 assert_eq!(order, ["/inc1", "/inc2", "/sys"]);
628 assert_eq!(search.start(IncludeForm::Angled), 2);
629 }
630
631 #[test]
632 fn a_bracket_directory_given_after_the_split_is_visible_to_both_chains() {
633 // `-Iinc1 -I- -Iinc2`. `inc1` is quoted only and `inc2` is an ordinary `-I`, which a
634 // quoted include reaches as well because the quoted chain runs on into the bracket one.
635 let fs = fs_with(&["/inc1/a.h", "/inc2/b.h"]);
636 let mut search = SearchPath::new();
637 search.push_bracket("/inc1");
638 search.split_quote_chain();
639 search.push_bracket("/inc2");
640
641 let at = search.start(IncludeForm::Angled);
642 assert!(search.resolve(&fs, "a.h", IncludeForm::Angled, None, at).is_none());
643 assert!(search.resolve(&fs, "b.h", IncludeForm::Angled, None, at).is_some());
644 assert!(search.resolve(&fs, "a.h", IncludeForm::Quoted, None, 0).is_some());
645 assert!(search.resolve(&fs, "b.h", IncludeForm::Quoted, None, 0).is_some());
646 }
647
648 #[test]
649 fn splitting_the_chain_stops_a_quoted_include_looking_next_to_the_file_that_wrote_it() {
650 let fs = fs_with(&["/src/a.h"]);
651 let mut search = SearchPath::new();
652 let here = Path::new("/src");
653 assert!(search.resolve(&fs, "a.h", IncludeForm::Quoted, Some(here), 0).is_some());
654 search.split_quote_chain();
655 assert!(search.resolve(&fs, "a.h", IncludeForm::Quoted, Some(here), 0).is_none());
656 // And the directory is not named among the places that were tried, since it was not one.
657 assert!(search.tried("a.h", IncludeForm::Quoted, Some(here), 0).is_empty());
658 }
659
660 #[test]
661 fn a_system_directory_marks_what_it_holds_as_a_system_header() {
662 let fs = fs_with(&["/i/a.h", "/sys/b.h", "/after/c.h"]);
663 let mut search = SearchPath::new();
664 search.push_bracket("/i");
665 search.push_system("/sys");
666 search.push_after("/after");
667 let get = |n| search.resolve(&fs, n, IncludeForm::Angled, None, 0).unwrap();
668 assert!(!get("a.h").is_system);
669 assert!(get("b.h").is_system);
670 assert!(get("c.h").is_system);
671 }
672
673 #[test]
674 fn include_next_continues_past_the_directory_the_current_file_came_from() {
675 let fs = fs_with(&["/a/limits.h", "/b/limits.h", "/c/limits.h"]);
676 let mut search = SearchPath::new();
677 search.push_bracket("/a");
678 search.push_bracket("/b");
679 search.push_bracket("/c");
680
681 let first = search.resolve(&fs, "limits.h", IncludeForm::Angled, None, 0).unwrap();
682 assert_eq!(norm(&first.name), "/a/limits.h");
683 let second =
684 search.resolve(&fs, "limits.h", IncludeForm::Angled, None, first.next).unwrap();
685 assert_eq!(norm(&second.name), "/b/limits.h");
686 let third =
687 search.resolve(&fs, "limits.h", IncludeForm::Angled, None, second.next).unwrap();
688 assert_eq!(norm(&third.name), "/c/limits.h");
689 assert!(search.resolve(&fs, "limits.h", IncludeForm::Angled, None, third.next).is_none());
690 }
691
692 #[test]
693 fn a_name_with_a_directory_in_it_is_joined_onto_each_entry() {
694 let fs = fs_with(&["/i/sys/types.h"]);
695 let mut search = SearchPath::new();
696 search.push_bracket("/i");
697 let found = search.resolve(&fs, "sys/types.h", IncludeForm::Angled, None, 0).unwrap();
698 assert_eq!(norm(&found.name), "/i/sys/types.h");
699 assert_eq!(text(&found), "/* /i/sys/types.h */\n");
700 }
701
702 #[test]
703 fn an_absolute_name_ignores_the_search_path() {
704 let fs = fs_with(&["/gen/config.h", "/i/gen/config.h"]);
705 let mut search = SearchPath::new();
706 search.push_bracket("/i");
707 let found = search.resolve(&fs, "/gen/config.h", IncludeForm::Angled, None, 0).unwrap();
708 assert_eq!(norm(&found.name), "/gen/config.h");
709 assert!(search.tried("/gen/config.h", IncludeForm::Angled, None, 0).is_empty());
710 }
711
712 #[test]
713 fn the_list_of_places_tried_is_the_list_that_was_searched() {
714 let fs = MemoryFileSystem::new();
715 let mut search = SearchPath::new();
716 search.push_quote("/q");
717 search.push_bracket("/i");
718 search.push_system("/sys");
719 let here = Path::new("/src");
720
721 assert!(search.resolve(&fs, "a.h", IncludeForm::Quoted, Some(here), 0).is_none());
722 let tried = search.tried("a.h", IncludeForm::Quoted, Some(here), 0);
723 let tried: Vec<_> = tried.iter().map(|p| norm(&p.to_string_lossy())).collect();
724 assert_eq!(tried, ["/src", "/q", "/i", "/sys"]);
725
726 let start = search.start(IncludeForm::Angled);
727 let tried = search.tried("a.h", IncludeForm::Angled, Some(here), start);
728 let tried: Vec<_> = tried.iter().map(|p| norm(&p.to_string_lossy())).collect();
729 assert_eq!(tried, ["/i", "/sys"]);
730 }
731
732 #[test]
733 fn a_header_found_next_to_its_includer_does_not_skip_the_whole_path_afterwards() {
734 // `at` for a file found beside its includer has to leave `at + 1` at the top of the
735 // path, because the directory it was found in is not on the path at all.
736 let fs = fs_with(&["/src/a.h", "/i/b.h"]);
737 let mut search = SearchPath::new();
738 search.push_bracket("/i");
739 let found =
740 search.resolve(&fs, "a.h", IncludeForm::Quoted, Some(Path::new("/src")), 0).unwrap();
741 assert_eq!(found.next, 0);
742 let next = search.resolve(&fs, "b.h", IncludeForm::Angled, None, found.next).unwrap();
743 assert_eq!(norm(&next.name), "/i/b.h");
744 }
745}