Fix verbatim paths used with include!

When using `concat!` to join paths, the Unix path separator (`/`) is often used. This breaks on Windows if the base path is a verbatim path (i.e. starts with `\\?\`).
This commit is contained in:
Chris Denton 2024-05-17 08:22:29 +00:00
parent 83dcdb3a5d
commit edc97a0df2
No known key found for this signature in database
GPG Key ID: 713472F2F45627DE
4 changed files with 28 additions and 1 deletions

View File

@ -1,5 +1,6 @@
use std::default::Default; use std::default::Default;
use std::iter; use std::iter;
use std::path::Component::Prefix;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::rc::Rc; use std::rc::Rc;
@ -1293,7 +1294,12 @@ pub fn resolve_path(sess: &Session, path: impl Into<PathBuf>, span: Span) -> PRe
base_path.push(path); base_path.push(path);
Ok(base_path) Ok(base_path)
} else { } else {
Ok(path) // This ensures that Windows verbatim paths are fixed if mixed path separators are used,
// which can happen when `concat!` is used to join paths.
match path.components().next() {
Some(Prefix(prefix)) if prefix.kind().is_verbatim() => Ok(path.components().collect()),
_ => Ok(path),
}
} }
} }

View File

@ -0,0 +1 @@
static TEST: &str = "Hello World!";

View File

@ -0,0 +1,8 @@
//@ only-windows other platforms do not have Windows verbatim paths
use run_make_support::rustc;
fn main() {
// Canonicalizing the path ensures that it's verbatim (i.e. starts with `\\?\`)
let mut path = std::fs::canonicalize(file!()).unwrap();
path.pop();
rustc().input("verbatim.rs").env("VERBATIM_DIR", path).run();
}

View File

@ -0,0 +1,12 @@
//! Include a file by concating the verbatim path using `/` instead of `\`
include!(concat!(env!("VERBATIM_DIR"), "/include/include.txt"));
fn main() {
assert_eq!(TEST, "Hello World!");
let s = include_str!(concat!(env!("VERBATIM_DIR"), "/include/include.txt"));
assert_eq!(s, "static TEST: &str = \"Hello World!\";\n");
let b = include_bytes!(concat!(env!("VERBATIM_DIR"), "/include/include.txt"));
assert_eq!(b, b"static TEST: &str = \"Hello World!\";\n");
}