Skip to content

Commit 3427e71

Browse files
committed
fix: the path tests read the same on Linux as on Windows
Seven tests failed on the CI's Linux runner and passed here, and the difference was `std::path`'s *host* semantics leaking into what the tests assert. **`normalize_path` is now a text splitter rather than a `std::path` walk.** `Path::components()` reads `C:` as a prefix and `\` as a separator only on Windows, so on Linux `C:\work\src\main.cpp` was one opaque component and every assertion about it failed. The spelling is what this function exists to normalize — a compiler's output, which may have been produced on another machine — so the prefix (`C:`, `\\server\share`) is recognized in the text, both separators split, and the answer is the same everywhere. The doc comment already said "a Windows path has a prefix component that is not a directory"; that rule just stopped depending on the host. **The alignment tests take their expected spelling from one helper**, which folds case on Windows only — two files that differ in case are one file there and two here. Three tests had `c:/…` written out, which is the Windows answer. **The `PATH`-order test moved its fixture off the conventional install roots** (`/usr/bin`, `/usr/local/bin`, …). A compiler found there is step 3's answer, and on Linux the fixture in `/usr/bin` was found before `PATH` was consulted at all — while Windows looked for `/usr/bin/clang++.exe`, found nothing, and reached the `PATH` step this test is about. The fixture lives in `/p/bin` now, so the test says what it means on both platforms. Still platform-specific, and deliberately: the case-folding flag itself (a caller's fact, passed in), and the fixtures that quote a MinGW compiler's output — those are strings, not paths.
1 parent 8e85673 commit 3427e71

3 files changed

Lines changed: 94 additions & 56 deletions

File tree

‎crates/cpp_code_analysis/src/align.rs‎

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1441,6 +1441,17 @@ mod tests {
14411441
use super::*;
14421442
use cpp_parser::SourceRange;
14431443

1444+
/// **The spelling an origin is recorded in.** Case is folded on Windows only — two files that differ in
1445+
/// case are one file there and two here — so a test that asserted the folded spelling everywhere would be
1446+
/// asserting the Windows rule on a file system that does not have it.
1447+
fn as_recorded(path: &str) -> String {
1448+
if cfg!(windows) {
1449+
path.to_lowercase()
1450+
} else {
1451+
path.to_string()
1452+
}
1453+
}
1454+
14441455
fn plain(spellings: &[&str]) -> Vec<StreamToken> {
14451456
spellings
14461457
.iter()
@@ -1803,15 +1814,15 @@ mod tests {
18031814
],
18041815
"the markers are not tokens: {tokens:?}"
18051816
);
1806-
assert_eq!(tokens[0].origin(), "c:/src/main.cpp:1");
1817+
assert_eq!(tokens[0].origin(), as_recorded("C:/src/main.cpp:1"));
18071818
assert_eq!(
18081819
tokens[6].origin(),
1809-
"c:/inc/xstring:1",
1820+
as_recorded("C:/inc/xstring:1"),
18101821
"the header's own tokens carry the header's name and line: {tokens:?}"
18111822
);
18121823
assert_eq!(
18131824
tokens[11].origin(),
1814-
"c:/src/main.cpp:7",
1825+
as_recorded("C:/src/main.cpp:7"),
18151826
"and the file comes back when the marker says so"
18161827
);
18171828
}
@@ -1829,12 +1840,11 @@ mod tests {
18291840
let tokens = tokenize_preprocessed(output);
18301841

18311842
assert_eq!(spelled(&tokens), ["int", "x", ";"]);
1832-
let expected = if cfg!(windows) {
1833-
"c:/src/main.cpp:12"
1834-
} else {
1835-
"C:/src/main.cpp:12"
1836-
};
1837-
assert_eq!(tokens[0].origin(), expected, "{tokens:?}");
1843+
assert_eq!(
1844+
tokens[0].origin(),
1845+
as_recorded("C:/src/main.cpp:12"),
1846+
"{tokens:?}"
1847+
);
18381848
}
18391849

18401850
/// **A path with a backslash that is not a C escape keeps its backslash, and is normalized like every other
@@ -1855,7 +1865,7 @@ mod tests {
18551865
// that.
18561866
assert_eq!(
18571867
tokens[0].origin(),
1858-
"c:/work/src/main.cpp:1",
1868+
as_recorded("C:/work/src/main.cpp:1"),
18591869
"the path survives with its separators, in the spelling comparisons are made in: {tokens:?}"
18601870
);
18611871
}

‎crates/cpp_code_analysis/src/file/paths.rs‎

Lines changed: 59 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
//! once per distinct file, and everything downstream compares numbers.
2121
2222
use std::collections::HashMap;
23-
use std::path::{Component, Path, PathBuf};
23+
use std::path::{Path, PathBuf};
2424

2525
/// A file's identity within one analysis.
2626
///
@@ -481,46 +481,61 @@ pub fn normalize_path(path: &Path, case_insensitive: bool) -> String {
481481
// `\\?\UNC\server\share` comes back as `\\server\share`, which is the same path in the spelling the rest of
482482
// this crate compares.
483483
let raw = path.to_string_lossy();
484-
let stripped = raw
485-
.strip_prefix(r"\\?\UNC\")
486-
.map(|rest| format!(r"\\{rest}"))
487-
.or_else(|| raw.strip_prefix(r"\\?\").map(str::to_string));
488-
let path = match &stripped {
489-
Some(stripped) => Path::new(stripped),
490-
None => path,
484+
let text: String = match raw.strip_prefix(r"\\?\UNC\") {
485+
Some(rest) => format!(r"\\{rest}"),
486+
None => match raw.strip_prefix(r"\\?\") {
487+
Some(rest) => rest.to_string(),
488+
None => raw.into_owned(),
489+
},
491490
};
491+
let text = text.as_str();
492492

493+
// **The prefix is text, not a `std::path` component.** `Path::components()` reads a drive letter or a UNC root
494+
// only on Windows, so the rule this function exists for was invisible to a test run anywhere else — and a
495+
// rendering made on one machine may be read on another. Splitting the spelling itself makes the answer the same
496+
// everywhere, which is what "normalized" has to mean for two spellings to compare equal.
493497
let mut parts: Vec<String> = Vec::new();
494-
495-
for component in path.components() {
496-
match component {
497-
Component::Prefix(prefix) => {
498-
parts.push(prefix.as_os_str().to_string_lossy().into_owned())
499-
}
500-
Component::RootDir => {
501-
// A prefix directly before the root is part of it: `C:` + `/` is `C:/`.
502-
if let Some(last) = parts.last_mut()
503-
&& last.ends_with(':')
504-
{
505-
last.push('/');
506-
continue;
507-
}
508-
parts.push("/".to_string());
509-
}
510-
Component::CurDir => {}
511-
Component::ParentDir => {
512-
// `..` pops a real directory. It is kept when there is nothing to pop — above a relative
513-
// path's start that changes what the path means — but **not** above the root, where `..`
514-
// is defined to be the root itself: `/../a.h` and `/a.h` are one file.
515-
match parts.last() {
516-
Some(last) if last == "/" || last.ends_with(":/") => {}
517-
Some(last) if last != ".." => {
518-
parts.pop();
519-
}
520-
_ => parts.push("..".to_string()),
498+
let mut rest: &str = text;
499+
500+
if let Some(unc) = rest.strip_prefix(r"\\") {
501+
// `\\server\share\dir` — the first two segments are the root, and they are kept in that spelling.
502+
let mut segments = unc.split(['/', '\\']);
503+
let server = segments.next().unwrap_or_default();
504+
let share = segments.next().unwrap_or_default();
505+
if !server.is_empty() {
506+
parts.push(format!(r"\\{server}\{share}"));
507+
rest = unc
508+
.get(server.len() + 1 + share.len()..)
509+
.unwrap_or_default();
510+
}
511+
} else if rest.len() >= 2 && rest.as_bytes()[1] == b':' {
512+
// `C:` is a *prefix*, not a directory: `C:\a` is `C:/a`. A drive with no separator after it (`C:foo`) is
513+
// drive-relative, and the answer keeps the prefix as it was written.
514+
let drive = &rest[..2];
515+
rest = &rest[2..];
516+
let rooted = rest.starts_with('/') || rest.starts_with('\\');
517+
parts.push(if rooted {
518+
format!("{drive}/")
519+
} else {
520+
drive.to_string()
521+
});
522+
} else if rest.starts_with('/') || rest.starts_with('\\') {
523+
parts.push("/".to_string());
524+
}
525+
526+
for segment in rest.split(['/', '\\']) {
527+
match segment {
528+
"" | "." => {}
529+
".." => match parts.last() {
530+
// `..` above the root is defined to be the root: `/../a.h` and `/a.h` are one file. Above a
531+
// relative path it is kept, because there it changes what the path means.
532+
Some(last) if is_a_root(last) => {}
533+
Some(last) if last != ".." => {
534+
parts.pop();
521535
}
522-
}
523-
Component::Normal(name) => parts.push(name.to_string_lossy().into_owned()),
536+
_ => parts.push("..".to_string()),
537+
},
538+
name => parts.push(name.to_string()),
524539
}
525540
}
526541

@@ -541,6 +556,13 @@ pub fn normalize_path(path: &Path, case_insensitive: bool) -> String {
541556
}
542557
}
543558

559+
/// **Is this part a root rather than a directory?** — `/`, `C:/`, and a UNC root (`\\server\share`). `..` at a root is
560+
/// the root itself, and popping it would leave a relative path where an absolute one was written.
561+
fn is_a_root(part: &str) -> bool {
562+
part == "/"
563+
|| part.ends_with(":/")
564+
|| (part.starts_with(r"\\") && part.matches('\\').count() >= 2)
565+
}
544566
/// Join a directory and a relative path, then normalize.
545567
pub fn join_normalized(directory: &Path, relative: &Path, case_insensitive: bool) -> PathBuf {
546568
let joined = directory.join(relative);

‎crates/cpp_code_analysis/src/include/toolchain/tests.rs‎

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -393,19 +393,25 @@ fn a_bare_name_is_searched_on_the_path_and_a_path_is_used_where_it_says() {
393393

394394
#[test]
395395
fn the_path_is_searched_in_the_order_the_names_are_tried() {
396-
// Nothing in the environment: the machine's default is whatever is installed, and `g++` is tried before
397-
// `clang++` because that is the order a person reading `COMPILER_NAMES` expects.
398-
let files = MemoryFiles::new().with_file("/usr/bin/clang++", "");
399-
let found = find_compiler(&files, None, Path::new("/p/main.cpp"), &environment());
400-
assert_eq!(found, Some(Path::new("/usr/bin/clang++").to_path_buf()));
396+
// **The directory is not a conventional install root** (`/usr/bin`, `/opt/homebrew/bin`, …), because a compiler
397+
// found *there* is step 3's answer rather than this test's: with the fixture in `/usr/bin`, a Unix-like machine
398+
// found `clang++` before `PATH` was consulted at all, while Windows looked for `/usr/bin/clang++.exe` and found
399+
// nothing. `PATH` is what this test is about, so the fixture lives only on it.
400+
let mut environment = environment();
401+
environment.path = vec![Path::new("/p/bin").into()];
402+
403+
// `g++` is tried before `clang++`, because that is the order a person reading `COMPILER_NAMES` expects.
404+
let files = MemoryFiles::new().with_file("/p/bin/clang++", "");
405+
let found = find_compiler(&files, None, Path::new("/p/main.cpp"), &environment);
406+
assert_eq!(found, Some(Path::new("/p/bin/clang++").to_path_buf()));
401407

402408
let files = MemoryFiles::new()
403-
.with_file("/usr/bin/clang++", "")
404-
.with_file("/usr/bin/g++", "");
405-
let found = find_compiler(&files, None, Path::new("/p/main.cpp"), &environment());
409+
.with_file("/p/bin/clang++", "")
410+
.with_file("/p/bin/g++", "");
411+
let found = find_compiler(&files, None, Path::new("/p/main.cpp"), &environment);
406412
assert_eq!(
407413
found,
408-
Some(Path::new("/usr/bin/g++").to_path_buf()),
414+
Some(Path::new("/p/bin/g++").to_path_buf()),
409415
"the first name on the list that exists, not the first directory that has any of them"
410416
);
411417

0 commit comments

Comments
 (0)