mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-27 13:17:41 +00:00
Merge pull request #1373 from dotCooCoo/feat/craft-testkit-guards
craft-testkit: add source guards for muda's Quit item, WGSL float literals and std Instant
This commit is contained in:
Generated
+3
@@ -4229,6 +4229,9 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-testkit"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"rustix 1.1.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-text"
|
||||
|
||||
@@ -10,5 +10,8 @@ publish = false
|
||||
|
||||
[dependencies]
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
rustix = { version = "1.1", default-features = false, features = ["std", "fs"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
+523
-60
@@ -151,12 +151,22 @@ impl Token {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `c` can start a Rust identifier: `_`, a letter, or another non-ASCII character that is not white
|
||||
/// space (see [`non_ascii_word`]).
|
||||
fn is_ident_start(c: char) -> bool {
|
||||
c == '_' || c.is_alphabetic()
|
||||
c == '_' || c.is_alphabetic() || non_ascii_word(c)
|
||||
}
|
||||
|
||||
/// Whether `c` can continue a Rust identifier: `_`, a letter or digit, or another non-ASCII character that is
|
||||
/// not white space, such as the combining mark U+0301.
|
||||
fn is_ident_continue(c: char) -> bool {
|
||||
c == '_' || c.is_alphanumeric()
|
||||
c == '_' || c.is_alphanumeric() || non_ascii_word(c)
|
||||
}
|
||||
|
||||
/// Whether `c` is a non-ASCII character other than Rust's white space and the byte order mark U+FEFF. Outside
|
||||
/// literals and comments, Rust allows such a character only in an identifier, so it is read as part of one.
|
||||
fn non_ascii_word(c: char) -> bool {
|
||||
!c.is_ascii() && !c.is_whitespace() && !matches!(c, '\u{200E}' | '\u{200F}' | '\u{FEFF}')
|
||||
}
|
||||
|
||||
/// Split Rust source into tokens with 1-based line numbers.
|
||||
@@ -178,7 +188,9 @@ fn lex_rust(code: &str) -> Vec<Token> {
|
||||
if c == '\n' {
|
||||
line += 1;
|
||||
i += 1;
|
||||
} else if c.is_whitespace() {
|
||||
} else if c.is_whitespace() || matches!(c, '\u{200E}' | '\u{200F}' | '\u{FEFF}') {
|
||||
// Rust also reads the left-to-right and right-to-left marks as white space, and skips a byte
|
||||
// order mark at the start of a file.
|
||||
i += 1;
|
||||
} else if c == '/' && at(i + 1) == Some('/') {
|
||||
while i < len && chars[i] != '\n' {
|
||||
@@ -529,7 +541,8 @@ fn parse_use_tree(
|
||||
Kind::Ident(name) => {
|
||||
*pos += 1;
|
||||
if toks.get(*pos).is_some_and(|t| t.is_punct(':')) && toks.get(*pos + 1).is_some_and(|t| t.is_punct(':')) {
|
||||
if prefix.is_empty() && time_aliases.contains(name) {
|
||||
// After a leading `::` the first segment names an external crate, never a local alias.
|
||||
if prefix.is_empty() && !absolute && time_aliases.contains(name) {
|
||||
prefix.extend([Rc::from("std"), Rc::from("time")]);
|
||||
via = Some(*pos - 1);
|
||||
} else {
|
||||
@@ -629,8 +642,9 @@ impl Tri {
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluate the `cfg` predicate at `toks[*pos]` for `wasm32-unknown-unknown`.
|
||||
fn eval_cfg(toks: &[Token], pos: &mut usize, depth: usize) -> Tri {
|
||||
/// Evaluate the `cfg` predicate at `toks[*pos]` for `wasm32-unknown-unknown`, or with `every` for every
|
||||
/// configuration at once, where only `true`, `false` and the operators over them have a known value.
|
||||
fn eval_cfg(toks: &[Token], pos: &mut usize, depth: usize, every: bool) -> Tri {
|
||||
let Some(Kind::Ident(name)) = toks.get(*pos).map(|t| &t.kind) else {
|
||||
return Tri::Unknown;
|
||||
};
|
||||
@@ -641,6 +655,9 @@ fn eval_cfg(toks: &[Token], pos: &mut usize, depth: usize) -> Tri {
|
||||
_ => return Tri::Unknown,
|
||||
};
|
||||
*pos += 2;
|
||||
if every {
|
||||
return Tri::Unknown;
|
||||
}
|
||||
let expected = match name.as_str() {
|
||||
"target_arch" => "wasm32",
|
||||
"target_os" | "target_vendor" => "unknown",
|
||||
@@ -670,7 +687,7 @@ fn eval_cfg(toks: &[Token], pos: &mut usize, depth: usize) -> Tri {
|
||||
continue;
|
||||
}
|
||||
let before = *pos;
|
||||
values.push(eval_cfg(toks, pos, depth + 1));
|
||||
values.push(eval_cfg(toks, pos, depth + 1, every));
|
||||
if *pos == before {
|
||||
*pos += 1;
|
||||
}
|
||||
@@ -687,7 +704,8 @@ fn eval_cfg(toks: &[Token], pos: &mut usize, depth: usize) -> Tri {
|
||||
};
|
||||
}
|
||||
match name.as_str() {
|
||||
"unix" | "windows" | "false" => Tri::False,
|
||||
"false" => Tri::False,
|
||||
"unix" | "windows" if !every => Tri::False,
|
||||
"true" => Tri::True,
|
||||
_ => Tri::Unknown,
|
||||
}
|
||||
@@ -781,11 +799,21 @@ fn operand_expected(toks: &[Token], j: usize) -> bool {
|
||||
/// `&&` in a chain) or of a `for` opens a struct pattern and does not end the item. An `else` chain ends
|
||||
/// at its last block.
|
||||
///
|
||||
/// An `if` or `match` expression in a condition, scrutinee or iterator, as in
|
||||
/// `for x in if a { b } else { c } { ... }`, is read to the end of its last block (up to [`MAX_NESTING`]
|
||||
/// levels of such expressions), and the body is the next `{` after it.
|
||||
///
|
||||
/// In the head of an `fn`, `impl`, `trait`, `struct`, `enum` or `union` item, a block inside angle
|
||||
/// brackets (a const generic default or argument such as `<const N: usize = { 1 + 2 }>`, also in a
|
||||
/// return type or a `where` clause) does not end the item. The `>` of `->` does not close an angle
|
||||
/// bracket.
|
||||
fn item_end(toks: &[Token], start: usize, inner: bool) -> usize {
|
||||
item_end_at(toks, start, inner, 0)
|
||||
}
|
||||
|
||||
/// [`item_end`] for an item or, with `nested` above 0, for an `if` or `match` expression inside the head of
|
||||
/// another one, `nested` levels deep, which ends right after its last block.
|
||||
fn item_end_at(toks: &[Token], start: usize, inner: bool, nested: usize) -> usize {
|
||||
let mut depth = 0usize;
|
||||
let mut block_item = false;
|
||||
let mut arm = false;
|
||||
@@ -800,6 +828,12 @@ fn item_end(toks: &[Token], start: usize, inner: bool) -> usize {
|
||||
block_item = true;
|
||||
}
|
||||
match &toks[j].kind {
|
||||
// An `if` or `match` expression in the condition ends at its last block, so its blocks do not
|
||||
// read as the body.
|
||||
Kind::Ident(k) if at_top && condition == Condition::Expression && matches!(k.as_str(), "if" | "match") && nested < MAX_NESTING => {
|
||||
j = item_end_at(toks, j, false, nested + 1).max(j + 1);
|
||||
continue;
|
||||
}
|
||||
Kind::Ident(k) if at_top && head && (BLOCK_KEYWORDS.contains(&k.as_str()) || starts_block(toks, j)) => {
|
||||
if !block_item {
|
||||
condition = match k.as_str() {
|
||||
@@ -859,12 +893,18 @@ fn item_end(toks: &[Token], start: usize, inner: bool) -> usize {
|
||||
if depth == 0 && *c == '}' && block_item && !inner && condition == Condition::Done && angle == 0 {
|
||||
if toks.get(j + 1).is_some_and(|t| t.is_ident("else")) {
|
||||
// `else if` has a condition of its own before its body; `else {` opens the body.
|
||||
// The `if` is stepped over, so it does not read as an `if` inside the condition.
|
||||
if toks.get(j + 2).is_some_and(|t| t.is_ident("if")) {
|
||||
condition = Condition::Expression;
|
||||
j += 3;
|
||||
} else {
|
||||
j += 1;
|
||||
}
|
||||
j += 1;
|
||||
continue;
|
||||
}
|
||||
if nested > 0 {
|
||||
return j + 1;
|
||||
}
|
||||
if toks.get(j + 1).is_some_and(|t| t.is_punct('.') || t.is_punct('?')) {
|
||||
// A method call, field or `?` after the block continues the expression to its `;` or `,`.
|
||||
block_item = false;
|
||||
@@ -890,12 +930,23 @@ fn item_end(toks: &[Token], start: usize, inner: bool) -> usize {
|
||||
/// An outer attribute (`#[cfg(...)]`) covers the item after it; an inner attribute (`#![cfg(...)]`)
|
||||
/// covers the rest of the module or block it is in.
|
||||
fn native_only(toks: &[Token]) -> Vec<bool> {
|
||||
cfg_covered(toks, false)
|
||||
cfg_covered(toks, Cover::NativeOnly)
|
||||
}
|
||||
|
||||
/// Mark the tokens of every item that a `cfg` attribute covers: with `any`, whatever its predicate,
|
||||
/// otherwise only when the predicate is false on `wasm32-unknown-unknown`, as [`native_only`] does.
|
||||
fn cfg_covered(toks: &[Token], any: bool) -> Vec<bool> {
|
||||
/// Which `cfg` attributes [`cfg_covered`] marks the items of.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Cover {
|
||||
/// Every `cfg` attribute, whatever its predicate.
|
||||
Any,
|
||||
/// A `cfg` attribute whose predicate is false on `wasm32-unknown-unknown`, as [`native_only`] reads it.
|
||||
NativeOnly,
|
||||
/// A `cfg` attribute whose predicate is false on every configuration, such as `cfg(any())` or
|
||||
/// `cfg(false)`, so the item is never compiled.
|
||||
Never,
|
||||
}
|
||||
|
||||
/// Mark the tokens of every item that a `cfg` attribute selected by `cover` covers.
|
||||
fn cfg_covered(toks: &[Token], cover: Cover) -> Vec<bool> {
|
||||
let mut skip = vec![false; toks.len()];
|
||||
let mut i = 0;
|
||||
while i < toks.len() {
|
||||
@@ -916,7 +967,7 @@ fn cfg_covered(toks: &[Token], any: bool) -> Vec<bool> {
|
||||
}
|
||||
let excluded = toks.get(open + 1).is_some_and(|t| t.is_ident("cfg")) && toks.get(open + 2).is_some_and(|t| t.is_punct('(')) && {
|
||||
let mut pos = open + 3;
|
||||
any || eval_cfg(&toks[..close], &mut pos, 0) == Tri::False
|
||||
cover == Cover::Any || eval_cfg(&toks[..close], &mut pos, 0, cover == Cover::Never) == Tri::False
|
||||
};
|
||||
if !excluded {
|
||||
i = close + 1;
|
||||
@@ -956,7 +1007,7 @@ fn cfg_items(toks: &[Token]) -> BTreeSet<usize> {
|
||||
break;
|
||||
}
|
||||
let mut pos = i + 4;
|
||||
if eval_cfg(&toks[..close], &mut pos, 0) == Tri::True {
|
||||
if eval_cfg(&toks[..close], &mut pos, 0, false) == Tri::True {
|
||||
i = close + 1;
|
||||
continue;
|
||||
}
|
||||
@@ -993,7 +1044,9 @@ struct ModDecl {
|
||||
/// The inline modules (`mod a { ... }`) the declaration is inside, outermost first, shared between the
|
||||
/// declarations inside them.
|
||||
inline: Vec<Rc<ModName>>,
|
||||
/// Whether the declaration is inside an item whose `cfg` is false on `wasm32-unknown-unknown`.
|
||||
/// Whether the `skip` tokens given to [`module_decls`] cover the declaration: for [`std_instant`], an
|
||||
/// item whose `cfg` is false on `wasm32-unknown-unknown`, and for [`predefined_quit`], one that is never
|
||||
/// compiled.
|
||||
native: bool,
|
||||
}
|
||||
|
||||
@@ -1408,23 +1461,44 @@ fn report(findings: &mut Vec<Finding>, path: &str, content: &str, lines: &BTreeS
|
||||
/// name to the muda crate, and whether one binds it to something else.
|
||||
type CrateBindings<'a> = BTreeMap<(&'a str, Option<usize>), (bool, bool)>;
|
||||
|
||||
/// The names of the muda crate in a file, and where each is bound. The names are `muda` itself and each
|
||||
/// name that `use muda as m;`, `use muda::{self as m};` or `extern crate muda as m;` gives it. For each
|
||||
/// name and each pair of braces, the bindings record whether a `use` or an `extern crate` in them binds
|
||||
/// the name to the crate, and whether a `use`, an `extern crate` or a `mod` in them binds it to something
|
||||
/// else. A binding to something else inside an item with a `cfg` attribute, or through `crate::`, `self::`
|
||||
/// or `super::` (which may be a re-export of the crate), is left out.
|
||||
fn muda_crate_bindings<'a>(
|
||||
toks: &'a [Token],
|
||||
leaves: &'a [UseLeaf],
|
||||
around: &[Option<usize>],
|
||||
gated: &[bool],
|
||||
) -> (BTreeSet<&'a str>, CrateBindings<'a>) {
|
||||
// Each `extern crate c;` or `extern crate c as n;`: whether `c` is muda, and the index of the name it
|
||||
// binds.
|
||||
let mut externs: Vec<(bool, &'a str, usize)> = Vec::new();
|
||||
/// For each token, whether it is in a macro's input, `m!(...)`, `m![...]` or `m! { ... }`, in an
|
||||
/// attribute, `#[...]` or `#![...]`, or in the body of a `macro_rules!` definition, whose templates are not
|
||||
/// expanded where they are written. Tokens in a block inside other parentheses or brackets, such as a call's
|
||||
/// argument, are not marked.
|
||||
fn macro_tokens(toks: &[Token]) -> Vec<bool> {
|
||||
let mut marked = Vec::with_capacity(toks.len());
|
||||
// For each open delimiter, whether it starts a macro's input, an attribute or a `macro_rules!` body; and
|
||||
// how many of those are open.
|
||||
let mut open = Vec::new();
|
||||
let mut in_macro = 0usize;
|
||||
for i in 0..toks.len() {
|
||||
if toks[i].is_ident("extern")
|
||||
if toks[i].is_punct('(') || toks[i].is_punct('[') || toks[i].is_punct('{') {
|
||||
let ident = |k: usize| matches!(toks[k].kind, Kind::Ident(_));
|
||||
let definition = i >= 3 && ident(i - 1) && toks[i - 2].is_punct('!') && toks[i - 3].is_ident("macro_rules");
|
||||
let input = i >= 2 && toks[i - 1].is_punct('!') && ident(i - 2);
|
||||
let attribute =
|
||||
toks[i].is_punct('[') && i >= 1 && (toks[i - 1].is_punct('#') || (i >= 2 && toks[i - 1].is_punct('!') && toks[i - 2].is_punct('#')));
|
||||
let skip = input || definition || attribute;
|
||||
open.push(skip);
|
||||
in_macro += usize::from(skip);
|
||||
} else if (toks[i].is_punct(')') || toks[i].is_punct(']') || toks[i].is_punct('}')) && open.pop() == Some(true) {
|
||||
in_macro = in_macro.saturating_sub(1);
|
||||
}
|
||||
marked.push(in_macro > 0);
|
||||
}
|
||||
marked
|
||||
}
|
||||
|
||||
/// Each `extern crate c;` or `extern crate c as n;` in a file: whether `c` is muda, the name it binds, and
|
||||
/// the index of that name. A declaration in an item that `never` marks (see [`Cover::Never`]) is left out,
|
||||
/// and so is one in a macro's input, an attribute or a `macro_rules!` body (see [`macro_tokens`]).
|
||||
fn extern_crates<'a>(toks: &'a [Token], never: &[bool]) -> Vec<(bool, &'a str, usize)> {
|
||||
let mut externs = Vec::new();
|
||||
let in_macro = macro_tokens(toks);
|
||||
for i in 0..toks.len() {
|
||||
if !in_macro[i]
|
||||
&& !never.get(i).copied().unwrap_or(false)
|
||||
&& toks[i].is_ident("extern")
|
||||
&& toks.get(i + 1).is_some_and(|t| t.is_ident("crate"))
|
||||
&& let Some(Kind::Ident(krate)) = toks.get(i + 2).map(|t| &t.kind)
|
||||
{
|
||||
@@ -1436,18 +1510,222 @@ fn muda_crate_bindings<'a>(
|
||||
}
|
||||
}
|
||||
}
|
||||
externs
|
||||
}
|
||||
|
||||
/// For each of `paths`, the names that an `extern crate muda as m;` outside any braces of its crate root adds
|
||||
/// to the crate's extern prelude, so that a path starting with `::m` names muda anywhere in the crate.
|
||||
///
|
||||
/// The crate roots follow Cargo's layout: `src/lib.rs` and `src/main.rs`, except one below another package's
|
||||
/// `src` folder that a declaration outside its own package folder names; each file that [`cargo_target`]
|
||||
/// accepts; another `build.rs`, `lib.rs` or `main.rs` when no `mod` declaration in another of the files names
|
||||
/// it, plainly or through a `#[path]` attribute; and each other file directly in a `bin`, `examples`, `tests`
|
||||
/// or `benches` folder other than `mod.rs` when no package folder holds it and no declaration without a
|
||||
/// `#[path]` attribute names it. A root's
|
||||
/// names reach every file that a chain of declarations
|
||||
/// from it names, where a crate root and a file loaded through a `#[path]` attribute have their modules in their
|
||||
/// own folder, as [`module_files`] reads them. A declaration in an item whose `cfg` is false on every
|
||||
/// configuration neither adds a name nor loads a file.
|
||||
fn extern_prelude_names(paths: &[String], contents: &[&str]) -> Vec<BTreeSet<String>> {
|
||||
let mut index: BTreeMap<&str, Vec<usize>> = BTreeMap::new();
|
||||
for (i, path) in paths.iter().enumerate() {
|
||||
index.entry(path.as_str()).or_default().push(i);
|
||||
}
|
||||
let mut decls: Vec<Vec<ModDecl>> = Vec::with_capacity(paths.len());
|
||||
let mut aliases: Vec<Vec<String>> = Vec::with_capacity(paths.len());
|
||||
for content in contents {
|
||||
let toks = lex_rust(content);
|
||||
// A declaration in an item that is never compiled loads no file, and its alias is not in the prelude.
|
||||
let never = cfg_covered(&toks, Cover::Never);
|
||||
// Nor does one in a macro's input, an attribute or a `macro_rules!` body.
|
||||
let skip: Vec<bool> = macro_tokens(&toks).into_iter().zip(&never).map(|(in_macro, &never)| in_macro || never).collect();
|
||||
decls.push(module_decls(&toks, &skip).into_iter().filter(|decl| !decl.native).collect());
|
||||
let (around, _) = brace_scopes(&toks);
|
||||
aliases.push(
|
||||
extern_crates(&toks, &never)
|
||||
.into_iter()
|
||||
.filter(|&(muda, _, at)| muda && around[at].is_none())
|
||||
.map(|(_, name, _)| name.to_owned())
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
// Node `2 * file` is the file loaded plainly (or as a crate root) and node `2 * file + 1` the file loaded
|
||||
// through a `#[path]` attribute. Each node lists the nodes its declarations name.
|
||||
let mut named = vec![false; paths.len()];
|
||||
let mut named_plainly = vec![false; paths.len()];
|
||||
// Whether a `src/lib.rs` or `src/main.rs` is named by a declaration in a file other than its package's
|
||||
// `build.rs` and the files in its `src`, `tests`, `examples` and `benches` folders.
|
||||
let mut named_from_outside = vec![false; paths.len()];
|
||||
let edges: Vec<Vec<usize>> = (0..paths.len() * 2)
|
||||
.map(|node| {
|
||||
let (file, path_loaded) = (node / 2, node % 2 == 1);
|
||||
let mut targets = Vec::new();
|
||||
for decl in &decls[file] {
|
||||
let by_path = usize::from(decl.module.path_attribute.is_some());
|
||||
for candidate in module_files(&paths[file], decl, path_loaded) {
|
||||
for &j in index.get(candidate.as_str()).into_iter().flatten() {
|
||||
if j != file {
|
||||
named[j] = true;
|
||||
named_plainly[j] |= by_path == 0;
|
||||
let package = paths[j].strip_suffix("src/lib.rs").or_else(|| paths[j].strip_suffix("src/main.rs"));
|
||||
let own = |package: &str| {
|
||||
paths[file].strip_prefix(package).is_some_and(|rest| {
|
||||
rest == "build.rs" || ["src/", "tests/", "examples/", "benches/"].iter().any(|dir| rest.starts_with(dir))
|
||||
})
|
||||
};
|
||||
named_from_outside[j] |= package.is_none_or(|package| !own(package));
|
||||
targets.push(2 * j + by_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
targets
|
||||
})
|
||||
.collect();
|
||||
let packages = package_folders(paths);
|
||||
// Whether `path` is below the `src` folder of a package, other than directly in it.
|
||||
let in_package_src = |path: &str| {
|
||||
packages.iter().any(|package| {
|
||||
let src = if package.is_empty() { "src/".to_owned() } else { format!("{package}/src/") };
|
||||
path.strip_prefix(src.as_str()).is_some_and(|rest| rest.contains('/'))
|
||||
})
|
||||
};
|
||||
let root = |file: usize| {
|
||||
if cargo_target(&paths[file], &packages) {
|
||||
return true;
|
||||
}
|
||||
let mut segments = paths[file].rsplit('/');
|
||||
match (segments.next(), segments.next()) {
|
||||
// A `src/lib.rs` that a declaration in a package's `src` folder loads is a module there.
|
||||
(Some("lib.rs" | "main.rs"), Some("src")) => !(named_from_outside[file] && in_package_src(&paths[file])),
|
||||
(Some("lib.rs" | "main.rs" | "build.rs"), _) => !named[file],
|
||||
// In a known package, `cargo_target` has already placed the target folders.
|
||||
(Some(name), Some("bin" | "examples" | "tests" | "benches")) => {
|
||||
name.ends_with(".rs") && name != "mod.rs" && !named_plainly[file] && package_relative(&paths[file], &packages).is_none()
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
};
|
||||
let mut prelude = vec![BTreeSet::new(); paths.len()];
|
||||
for start in (0..paths.len()).filter(|&file| !aliases[file].is_empty() && root(file)) {
|
||||
// A crate root declares its modules in its own folder, as a file loaded through `#[path]` does, so
|
||||
// `mod child;` in `src/bin/tool.rs` names `src/bin/child.rs`.
|
||||
let mut seen = vec![false; paths.len() * 2];
|
||||
let mut queue = vec![2 * start + 1];
|
||||
seen[2 * start + 1] = true;
|
||||
while let Some(node) = queue.pop() {
|
||||
prelude[node / 2].extend(aliases[start].iter().cloned());
|
||||
for &next in &edges[node] {
|
||||
if !seen[next] {
|
||||
seen[next] = true;
|
||||
queue.push(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
prelude
|
||||
}
|
||||
|
||||
/// The package folders among `paths`: each folder that holds a `src/lib.rs` or `src/main.rs`, and each folder
|
||||
/// that holds a file directly in `src/bin` and is not inside the `src` folder of one of the first kind. A
|
||||
/// relative `src/lib.rs` gives the empty folder.
|
||||
fn package_folders(paths: &[String]) -> BTreeSet<&str> {
|
||||
fn folder(dir: &str) -> Option<&str> {
|
||||
dir.strip_suffix('/').or_else(|| dir.is_empty().then_some(""))
|
||||
}
|
||||
let roots: BTreeSet<&str> =
|
||||
paths.iter().filter_map(|path| path.strip_suffix("src/lib.rs").or_else(|| path.strip_suffix("src/main.rs"))).filter_map(folder).collect();
|
||||
let in_src = |dir: &str| {
|
||||
roots.iter().any(|root| {
|
||||
let src = if root.is_empty() { "src".to_owned() } else { format!("{root}/src") };
|
||||
dir == src || dir.starts_with(&format!("{src}/"))
|
||||
})
|
||||
};
|
||||
let bins: Vec<&str> = paths
|
||||
.iter()
|
||||
.filter_map(|path| path.rsplit_once('/').map(|(dir, _)| dir))
|
||||
.filter_map(|dir| dir.strip_suffix("src/bin"))
|
||||
.filter_map(folder)
|
||||
.filter(|dir| !in_src(dir))
|
||||
.collect();
|
||||
roots.into_iter().chain(bins).collect()
|
||||
}
|
||||
|
||||
/// Whether Cargo builds `path` as a crate root of its own, also when another file declares it as a module:
|
||||
/// each file directly in a `src/bin` folder and each `main.rs` one folder below it; and in a package folder,
|
||||
/// `build.rs`, each file directly in its `tests`, `examples` or `benches` folder, and each `main.rs` one
|
||||
/// folder below those. Cargo's auto-discovery takes a `mod.rs` directly in those folders as a target too.
|
||||
/// The package folder is the nearest folder above `path` in `packages` (see [`package_folders`]). Without
|
||||
/// one, a package folder is one that is not directly inside `src` and has no `bin`, `tests`, `examples` or
|
||||
/// `benches` folder above it, so a folder of that name inside `src` or inside one of those folders holds
|
||||
/// modules. With one, only those places directly below it count, so `src/foo/tests/helper.rs` and
|
||||
/// `src/foo/src/bin/helper.rs` hold modules.
|
||||
fn cargo_target(path: &str, packages: &BTreeSet<&str>) -> bool {
|
||||
let inside = package_relative(path, packages);
|
||||
let mut segments = inside.unwrap_or(path).rsplit('/');
|
||||
let Some(name) = segments.next() else { return false };
|
||||
if !name.ends_with(".rs") {
|
||||
return false;
|
||||
}
|
||||
let folders: Vec<&str> = segments.collect();
|
||||
if inside.is_some() {
|
||||
return match folders.as_slice() {
|
||||
["bin", "src"] | ["tests" | "examples" | "benches"] => true,
|
||||
[_, "bin", "src"] | [_, "tests" | "examples" | "benches"] => name == "main.rs",
|
||||
[] => name == "build.rs",
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
let package = |rest: &[&str]| rest.first() != Some(&"src") && !rest.iter().any(|s| matches!(*s, "bin" | "tests" | "examples" | "benches"));
|
||||
match folders.as_slice() {
|
||||
["bin", "src", ..] => true,
|
||||
[_, "bin", "src", ..] if name == "main.rs" => true,
|
||||
["tests" | "examples" | "benches", rest @ ..] => package(rest),
|
||||
[_, "tests" | "examples" | "benches", rest @ ..] if name == "main.rs" => package(rest),
|
||||
rest if name == "build.rs" => package(rest),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// `path` relative to the nearest folder above it in `packages` (see [`package_folders`]), or `None` when no
|
||||
/// package folder holds it.
|
||||
fn package_relative<'a>(path: &'a str, packages: &BTreeSet<&str>) -> Option<&'a str> {
|
||||
let inside = path.rmatch_indices('/').map(|(i, _)| i).find(|&i| i > 0 && packages.contains(&path[..i])).map(|i| &path[i + 1..]);
|
||||
inside.or_else(|| (packages.contains("") && !path.starts_with('/')).then_some(path))
|
||||
}
|
||||
|
||||
/// The names of the muda crate in a file, and where each is bound. The names are `muda` itself, each name
|
||||
/// in `prelude` (see [`extern_prelude_names`]), which names the crate as `muda` does, and each name that
|
||||
/// `use muda as m;`, `use muda::{self as m};` or `extern crate muda as m;` gives it. For each
|
||||
/// name and each pair of braces, the bindings record whether a `use` or an `extern crate` in them binds
|
||||
/// the name to the crate, and whether a `use`, an `extern crate` or a `mod` in them binds it to something
|
||||
/// else. A binding to something else inside an item with a `cfg` attribute, or through `crate::`, `self::`
|
||||
/// or `super::` (which may be a re-export of the crate), is left out, and so is an `extern crate` in an
|
||||
/// item that `never` marks, in a macro's input, in an attribute or in a `macro_rules!` body (see [`extern_crates`]).
|
||||
fn muda_crate_bindings<'a>(
|
||||
toks: &'a [Token],
|
||||
leaves: &'a [UseLeaf],
|
||||
around: &[Option<usize>],
|
||||
gated: &[bool],
|
||||
never: &[bool],
|
||||
prelude: &'a BTreeSet<String>,
|
||||
) -> (BTreeSet<&'a str>, CrateBindings<'a>) {
|
||||
let externs = extern_crates(toks, never);
|
||||
// Whether a `use` path names the crate itself: `muda`, or a name of the crate in the extern prelude.
|
||||
let crate_path = |leaf: &UseLeaf| leaf.path.len() == 1 && (leaf.path[0] == "muda" || prelude.contains(&leaf.path[0]));
|
||||
let mut names: BTreeSet<&'a str> = BTreeSet::from(["muda"]);
|
||||
names.extend(leaves.iter().filter(|leaf| leaf.path == ["muda"]).filter_map(UseLeaf::binding));
|
||||
names.extend(prelude.iter().map(String::as_str));
|
||||
names.extend(leaves.iter().filter(|leaf| crate_path(leaf)).filter_map(UseLeaf::binding));
|
||||
names.extend(externs.iter().filter(|&&(muda, _, _)| muda).map(|&(_, name, _)| name));
|
||||
let mut bound: CrateBindings<'a> = BTreeMap::new();
|
||||
// `use muda as m;` binds `m` to the crate only where `muda` itself names the crate, so it is read
|
||||
// after every other binding.
|
||||
let renames = |leaf: &UseLeaf| leaf.path == ["muda"] && leaf.binding() != Some("muda");
|
||||
// after every other binding. The same holds for a name of the crate in the extern prelude.
|
||||
let renames = |leaf: &UseLeaf| crate_path(leaf) && leaf.binding() != Some(leaf.path[0].as_str());
|
||||
for leaf in leaves.iter().filter(|leaf| !renames(leaf)) {
|
||||
let Some(name) = leaf.binding().filter(|name| names.contains(name)) else { continue };
|
||||
let local = leaf.root.as_deref().is_some_and(|s| matches!(s, "crate" | "self" | "super"));
|
||||
let entry = bound.entry((name, around.get(leaf.start).copied().flatten()));
|
||||
if leaf.path == ["muda"] {
|
||||
if crate_path(leaf) {
|
||||
entry.or_default().0 = true;
|
||||
} else if !local && !gated.get(leaf.start).copied().unwrap_or(false) {
|
||||
entry.or_default().1 = true;
|
||||
@@ -1475,8 +1753,8 @@ fn muda_crate_bindings<'a>(
|
||||
let mut renamed = Vec::new();
|
||||
for leaf in leaves.iter().filter(|leaf| renames(leaf)) {
|
||||
let Some(name) = leaf.binding() else { continue };
|
||||
let crate_here =
|
||||
leaf.absolute || !matches!(lookup(toks, around, leaf.start, |scope| bound.get(&("muda", scope)).copied()), Some(Some((false, true))));
|
||||
let crate_here = leaf.absolute
|
||||
|| !matches!(lookup(toks, around, leaf.start, |scope| bound.get(&(leaf.path[0].as_str(), scope)).copied()), Some(Some((false, true))));
|
||||
let local = leaf.root.as_deref().is_some_and(|s| matches!(s, "crate" | "self" | "super"));
|
||||
let scope = around.get(leaf.start).copied().flatten();
|
||||
if crate_here {
|
||||
@@ -1509,7 +1787,21 @@ fn muda_crate_bindings<'a>(
|
||||
/// braces binding it bind only to something else (`use other_menu as muda;`, `mod muda`), read like a name
|
||||
/// used on its own below; `::muda::PredefinedMenuItem` always names the crate. A name that the crate is
|
||||
/// imported under (`use muda as menu;`, `use muda::{self as menu};`, `extern crate muda as menu;`) is read
|
||||
/// like `muda` in the braces that bind it, so `menu::PredefinedMenuItem::quit` is reported there. It also
|
||||
/// like `muda` in the braces that bind it, so `menu::PredefinedMenuItem::quit` is reported there. An
|
||||
/// `extern crate muda as menu;` outside any braces of a crate root (`src/lib.rs` and `src/main.rs`; `build.rs`,
|
||||
/// another `lib.rs` or `main.rs`, or a file outside any package folder directly in a `bin`, `examples`, `tests`
|
||||
/// or `benches` folder other than `mod.rs`, unless a `mod` declaration in another of `files` names it, for a file in those folders one
|
||||
/// without a `#[path]` attribute; a file directly in `src/bin`, a package's `build.rs`, a file directly in its
|
||||
/// `tests`, `examples` or `benches` folder, `mod.rs` included, and a `main.rs` one folder below those, are crate
|
||||
/// roots even when a declaration names them, where the package folder is the nearest folder above the file
|
||||
/// that holds a `src/lib.rs` or `src/main.rs` of `files`, and without one, a folder not directly inside `src`
|
||||
/// with no `bin`, `tests`, `examples` or `benches` folder above it) also adds `menu` to
|
||||
/// the crate's extern prelude, so in that file and in every file of `files` that a chain of `mod`
|
||||
/// declarations from it names, `menu` is read like `muda` and `::menu::PredefinedMenuItem::quit` is
|
||||
/// reported. An `extern crate` or `mod` declaration in an item whose `cfg` is false on every configuration
|
||||
/// (`cfg(any())`, `cfg(false)`) is read as absent, and so are the tokens of an `extern crate` in a macro's
|
||||
/// input (`m!(...)`, `m![...]`, `m! { ... }`), in an attribute or in a `macro_rules!` body. Elsewhere a path that starts with `::` names the crate
|
||||
/// only through `muda`. It also
|
||||
/// follows a `use` or a `type` alias that renames muda's type (`use muda::PredefinedMenuItem as Item;` then
|
||||
/// `Item::quit`); a rename of another crate's `PredefinedMenuItem` is not followed, including one through a
|
||||
/// name `muda` that the braces around the `use` or `type` bind to something else, read as for a qualified
|
||||
@@ -1528,28 +1820,35 @@ where
|
||||
I: IntoIterator,
|
||||
I::Item: AsFileSource,
|
||||
{
|
||||
let files: Vec<I::Item> = files.into_iter().collect();
|
||||
let paths: Vec<String> = files.iter().map(|file| normalize_path(file.path())).collect();
|
||||
let contents: Vec<&str> = files.iter().map(|file| file.content()).collect();
|
||||
let prelude = extern_prelude_names(&paths, &contents);
|
||||
let mut findings = Vec::new();
|
||||
for file in files {
|
||||
for (index, file) in files.iter().enumerate() {
|
||||
let path = file.path();
|
||||
let content = file.content();
|
||||
let toks = lex_rust(content);
|
||||
let leaves = use_leaves(&toks, &BTreeSet::new());
|
||||
let (around, opener) = brace_scopes(&toks);
|
||||
let gated = cfg_covered(&toks, true);
|
||||
let (crate_names, crate_bound) = muda_crate_bindings(&toks, &leaves, &around, &gated);
|
||||
let gated = cfg_covered(&toks, Cover::Any);
|
||||
let never = cfg_covered(&toks, Cover::Never);
|
||||
let (crate_names, crate_bound) = muda_crate_bindings(&toks, &leaves, &around, &gated, &never, &prelude[index]);
|
||||
let names_crate = |s: &str| crate_names.contains(s);
|
||||
// Whether `name`, read at token `i`, names the crate. After a leading `::` only `muda` does.
|
||||
// Otherwise `muda` does unless the innermost braces around `i` that bind `muda` bind it only to
|
||||
// something else, and another name of the crate does when those braces bind it to the crate, or
|
||||
// only to nothing else.
|
||||
// Whether `name`, read at token `i`, names the crate. After a leading `::`, `muda` does, and so
|
||||
// does a name that `extern crate muda as name;` outside any braces of the file's crate root gives it
|
||||
// (a name in the extern prelude). Otherwise `muda` and a name in the extern prelude do unless the
|
||||
// innermost braces around `i` that bind the name bind it only to something else, and another name
|
||||
// of the crate does when those braces bind it to the crate, or only to nothing else.
|
||||
let in_prelude = |name: &str| name == "muda" || prelude[index].contains(name);
|
||||
let crate_name_at = |name: &str, i: usize, absolute: bool| {
|
||||
if absolute || !names_crate(name) {
|
||||
return name == "muda";
|
||||
return in_prelude(name);
|
||||
}
|
||||
match lookup(&toks, &around, i, |scope| crate_bound.get(&(name, scope)).copied()) {
|
||||
None => true,
|
||||
Some(Some((muda, other))) => muda || !other,
|
||||
Some(None) => name == "muda",
|
||||
Some(None) => in_prelude(name),
|
||||
}
|
||||
};
|
||||
// Whether the identifier at `i` names the crate.
|
||||
@@ -1559,7 +1858,7 @@ where
|
||||
crate_name_at(name, i, absolute)
|
||||
};
|
||||
// A `use` path to muda's type, read through a name of the crate bound where the `use` is. After
|
||||
// a leading `::` the first segment is an external crate, so only `muda` names it.
|
||||
// a leading `::` the first segment is an external crate, so only a name in the extern prelude names it.
|
||||
let is_muda =
|
||||
|leaf: &UseLeaf| leaf.path.len() == 2 && leaf.path[1] == "PredefinedMenuItem" && crate_name_at(&leaf.path[0], leaf.start, leaf.absolute);
|
||||
// Whether the braces opened at `o` are the body of an `impl` or a `trait`, whose `type` items are
|
||||
@@ -1755,7 +2054,8 @@ where
|
||||
/// braces of its `use` (or the file), down to but not into the body of a nested `mod`; nearer braces whose
|
||||
/// `use` or `mod` binds the same name to something else hide it, unless that `use` or `mod` carries a `cfg`
|
||||
/// attribute of its own that is not known to be true on `wasm32-unknown-unknown`, which may leave it out of
|
||||
/// the web build.
|
||||
/// the web build. A path that starts with `::` names an external crate, so `::m::Instant` and
|
||||
/// `use ::m::Instant;` are not read through an alias `m`.
|
||||
pub fn std_instant<I>(files: I) -> Vec<Finding>
|
||||
where
|
||||
I: IntoIterator,
|
||||
@@ -1854,7 +2154,9 @@ where
|
||||
let hit = if name == "std" {
|
||||
then_path(&toks, i + 1, |s| s == "time") && then_path(&toks, i + 4, |s| s == "Instant")
|
||||
} else {
|
||||
modules.contains(name) && then_path(&toks, i + 1, |s| s == "Instant") && time_alias(name, i)
|
||||
// After a leading `::` the name is an external crate, not a local alias of `std::time`.
|
||||
let absolute = i >= 2 && toks[i - 1].is_punct(':') && toks[i - 2].is_punct(':');
|
||||
!absolute && modules.contains(name) && then_path(&toks, i + 1, |s| s == "Instant") && time_alias(name, i)
|
||||
};
|
||||
if hit {
|
||||
lines.insert(tok.line);
|
||||
@@ -2129,18 +2431,74 @@ impl Default for SourceLimits {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const CACHEDIR_SIGNATURE: &[u8] = b"Signature: 8a477f597d28d172789f06886806bc55";
|
||||
|
||||
/// Open `path` for reading when it is a regular file. Returns `Ok(None)` when `path` is a symbolic
|
||||
/// link, a folder, a FIFO or another special file.
|
||||
///
|
||||
/// On Unix the open does not follow a symbolic link (`O_NOFOLLOW`) and does not wait for a writer on a
|
||||
/// FIFO (`O_NONBLOCK`), and the type is then read from the opened file, so a file replaced between a
|
||||
/// directory listing and the open is checked as it is when opened. On Windows the open does not follow
|
||||
/// a reparse point (`FILE_FLAG_OPEN_REPARSE_POINT`), so an opened symbolic link or junction is the link
|
||||
/// itself and returns `Ok(None)`. On other platforms a
|
||||
/// path that is a symbolic link is skipped before the open, and the opened file must be a regular file.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn open_regular_file(path: &Path) -> std::io::Result<Option<std::fs::File>> {
|
||||
#[cfg(unix)]
|
||||
let opened = {
|
||||
use rustix::fs::{Mode, OFlags};
|
||||
rustix::fs::open(path, OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC, Mode::empty())
|
||||
.map(std::fs::File::from)
|
||||
.map_err(std::io::Error::from)
|
||||
};
|
||||
#[cfg(windows)]
|
||||
let opened = open_without_following(path);
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
let opened = {
|
||||
if std::fs::symlink_metadata(path)?.file_type().is_symlink() {
|
||||
return Ok(None);
|
||||
}
|
||||
std::fs::File::open(path)
|
||||
};
|
||||
let file = match opened {
|
||||
Ok(file) => file,
|
||||
// `O_NOFOLLOW` fails on a symbolic link (ELOOP on Linux and macOS, EMLINK on FreeBSD).
|
||||
Err(_) if std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) => return Ok(None),
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
Ok(file.metadata()?.file_type().is_file().then_some(file))
|
||||
}
|
||||
|
||||
/// The Win32 `FILE_FLAG_OPEN_REPARSE_POINT` flag: open a reparse point itself instead of its target.
|
||||
#[cfg(windows)]
|
||||
const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
|
||||
|
||||
/// Open `path` for reading without following a reparse point: a symbolic link or junction opens as the
|
||||
/// link itself.
|
||||
#[cfg(windows)]
|
||||
fn open_without_following(path: &Path) -> std::io::Result<std::fs::File> {
|
||||
use std::os::windows::fs::OpenOptionsExt;
|
||||
std::fs::OpenOptions::new().read(true).custom_flags(FILE_FLAG_OPEN_REPARSE_POINT).open(path)
|
||||
}
|
||||
|
||||
/// The Win32 `FILE_ATTRIBUTE_REPARSE_POINT` attribute of a file that is a reparse point.
|
||||
#[cfg(windows)]
|
||||
const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0400;
|
||||
|
||||
/// Whether `dir` holds a `CACHEDIR.TAG` regular file that starts with [`CACHEDIR_SIGNATURE`]. A marker
|
||||
/// that is a symbolic link, a folder, a FIFO or another special file is not opened and does not count.
|
||||
/// that is a symbolic link, a folder, a FIFO or another special file is not read and does not count.
|
||||
/// On Windows a marker that is a reparse point of any kind, cloud placeholders included, does not count.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn is_cache_dir(dir: &Path) -> bool {
|
||||
use std::io::Read;
|
||||
let marker = dir.join("CACHEDIR.TAG");
|
||||
if !std::fs::symlink_metadata(&marker).is_ok_and(|m| m.file_type().is_file()) {
|
||||
return false;
|
||||
}
|
||||
let Ok(file) = std::fs::File::open(&marker) else {
|
||||
let Ok(Some(file)) = open_regular_file(&dir.join("CACHEDIR.TAG")) else {
|
||||
return false;
|
||||
};
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::fs::MetadataExt;
|
||||
if !file.metadata().is_ok_and(|m| m.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
let mut head = Vec::with_capacity(CACHEDIR_SIGNATURE.len());
|
||||
file.take(CACHEDIR_SIGNATURE.len() as u64).read_to_end(&mut head).is_ok() && head == CACHEDIR_SIGNATURE
|
||||
}
|
||||
@@ -2158,7 +2516,8 @@ fn is_cache_dir(dir: &Path) -> bool {
|
||||
/// name starts with `.`, or that holds a `CACHEDIR.TAG` regular file starting with the signature line
|
||||
/// `Signature: 8a477f597d28d172789f06886806bc55` (a build output folder with another name). A
|
||||
/// `CACHEDIR.TAG` that is a symbolic link or a special file such as a FIFO is not read, and its folder
|
||||
/// is listed.
|
||||
/// is listed. On Windows a `CACHEDIR.TAG` that is a reparse point of any kind, cloud placeholders
|
||||
/// included, does not mark its folder either.
|
||||
/// * Symbolic links (and, on Windows, junctions) to files or folders, which are not followed.
|
||||
///
|
||||
/// Results are sorted lexicographically by file path for deterministic behavior across platforms.
|
||||
@@ -2208,12 +2567,15 @@ pub fn rust_sources_with_limits(dir: impl AsRef<Path>, limits: SourceLimits) ->
|
||||
format!("more than {} Rust source files under {}", limits.max_files, root.display()),
|
||||
));
|
||||
}
|
||||
let Some(file) = open_regular_file(&p)? else {
|
||||
continue;
|
||||
};
|
||||
let over_file = || Error::new(ErrorKind::FileTooLarge, format!("{} is larger than {} bytes", p.display(), limits.max_file_bytes));
|
||||
if entry.metadata()?.len() > limits.max_file_bytes {
|
||||
if file.metadata()?.len() > limits.max_file_bytes {
|
||||
return Err(over_file());
|
||||
}
|
||||
let mut content = String::new();
|
||||
std::fs::File::open(&p)?.take(limits.max_file_bytes.saturating_add(1)).read_to_string(&mut content)?;
|
||||
file.take(limits.max_file_bytes.saturating_add(1)).read_to_string(&mut content)?;
|
||||
let size = content.len() as u64;
|
||||
if size > limits.max_file_bytes {
|
||||
return Err(over_file());
|
||||
@@ -2244,6 +2606,107 @@ mod tests {
|
||||
use_leaves(&lex_rust(source), &BTreeSet::new()).into_iter().map(|leaf| (leaf.path, leaf.name.map(|name| name.to_string()))).collect()
|
||||
}
|
||||
|
||||
/// A new empty folder under the system temporary folder, removed when dropped.
|
||||
#[cfg(any(unix, windows))]
|
||||
struct TempDir(std::path::PathBuf);
|
||||
|
||||
#[cfg(any(unix, windows))]
|
||||
impl TempDir {
|
||||
fn new(tag: &str) -> Self {
|
||||
let path = std::env::temp_dir().join(format!("craft-testkit-unit-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&path);
|
||||
std::fs::create_dir_all(&path).expect("create temp dir");
|
||||
Self(path)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(unix, windows))]
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(unix, windows))]
|
||||
#[test]
|
||||
fn open_regular_file_opens_a_regular_file() {
|
||||
let dir = TempDir::new("open_regular");
|
||||
let tag = dir.0.join("CACHEDIR.TAG");
|
||||
std::fs::write(&tag, super::CACHEDIR_SIGNATURE).expect("write tag");
|
||||
assert!(super::open_regular_file(&tag).expect("open").is_some());
|
||||
assert!(super::is_cache_dir(&dir.0));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn open_regular_file_does_not_follow_a_symlink() {
|
||||
let dir = TempDir::new("open_symlink");
|
||||
let target = dir.0.join("target.tag");
|
||||
std::fs::write(&target, super::CACHEDIR_SIGNATURE).expect("write target");
|
||||
let link = dir.0.join("CACHEDIR.TAG");
|
||||
std::os::unix::fs::symlink(&target, &link).expect("symlink");
|
||||
assert!(super::open_regular_file(&link).expect("open").is_none());
|
||||
assert!(!super::is_cache_dir(&dir.0));
|
||||
}
|
||||
|
||||
/// The FIFO has no writer, so an open that waited for one would not return.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn open_regular_file_does_not_wait_on_a_fifo() {
|
||||
let dir = TempDir::new("open_fifo");
|
||||
let fifo = dir.0.join("CACHEDIR.TAG");
|
||||
match std::process::Command::new("mkfifo").arg(&fifo).status() {
|
||||
Ok(status) if status.success() => {}
|
||||
other => {
|
||||
eprintln!("skipped: mkfifo is not available here ({other:?})");
|
||||
return;
|
||||
}
|
||||
}
|
||||
assert!(super::open_regular_file(&fifo).expect("open").is_none());
|
||||
assert!(!super::is_cache_dir(&dir.0));
|
||||
}
|
||||
|
||||
/// A file symbolic link to `target` at `link`, or `None` with a printed note when this account may not
|
||||
/// create symbolic links.
|
||||
#[cfg(windows)]
|
||||
fn windows_file_symlink(target: &std::path::Path, link: &std::path::Path) -> Option<()> {
|
||||
match std::os::windows::fs::symlink_file(target, link) {
|
||||
Ok(()) => Some(()),
|
||||
Err(err) => {
|
||||
eprintln!("skipped: symbolic links cannot be created here ({err})");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn open_without_following_opens_the_link_itself() {
|
||||
let dir = TempDir::new("open_no_follow");
|
||||
let target = dir.0.join("target.tag");
|
||||
std::fs::write(&target, super::CACHEDIR_SIGNATURE).expect("write target");
|
||||
let link = dir.0.join("CACHEDIR.TAG");
|
||||
if windows_file_symlink(&target, &link).is_none() {
|
||||
return;
|
||||
}
|
||||
let opened = super::open_without_following(&link).expect("open");
|
||||
assert!(opened.metadata().expect("metadata").file_type().is_symlink());
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_symlinked_cachedir_tag_does_not_mark_its_folder() {
|
||||
let dir = TempDir::new("tag_symlink");
|
||||
let target = dir.0.join("target.tag");
|
||||
std::fs::write(&target, super::CACHEDIR_SIGNATURE).expect("write target");
|
||||
let link = dir.0.join("CACHEDIR.TAG");
|
||||
if windows_file_symlink(&target, &link).is_none() {
|
||||
return;
|
||||
}
|
||||
assert!(super::open_regular_file(&link).expect("open").is_none());
|
||||
assert!(!super::is_cache_dir(&dir.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn use_leaves_keep_no_path_longer_than_the_limit() {
|
||||
let source = format!("use {}{{x, y::z, *}};\nuse std::time::{{Instant, self as t}};\n", "a::".repeat(MAX_USE_PATH));
|
||||
|
||||
@@ -532,6 +532,254 @@ mod shadowed {
|
||||
assert_eq!(lines(&predefined_quit([("src/menu.rs", source)])), vec![4, 5, 10, 15, 20]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn predefined_quit_reads_an_absolute_path_through_a_root_extern_crate_alias() {
|
||||
let source = r#"
|
||||
extern crate muda as menu;
|
||||
use ::menu::PredefinedMenuItem as Item;
|
||||
fn menu_bar() {
|
||||
let a = ::menu::PredefinedMenuItem::quit(None);
|
||||
let b = <::menu::PredefinedMenuItem>::quit(None);
|
||||
let c = Item::quit(None);
|
||||
}
|
||||
mod nested {
|
||||
extern crate muda as native;
|
||||
fn menu_bar() { let d = ::native::PredefinedMenuItem::quit(None); let e = ::menu::PredefinedMenuItem::quit(None); }
|
||||
}
|
||||
"#;
|
||||
assert_eq!(lines(&predefined_quit([("src/main.rs", source)])), vec![5, 6, 7, 11]);
|
||||
// In a module file the declaration binds `menu` in that module only; `::menu` is the crate root's.
|
||||
let module = "extern crate muda as menu;\nfn menu_bar() {\n let a = ::menu::PredefinedMenuItem::quit(None);\n let b = menu::PredefinedMenuItem::quit(None);\n}\n";
|
||||
assert_eq!(lines(&predefined_quit([("src/child.rs", module)])), vec![4]);
|
||||
assert_eq!(lines(&predefined_quit([("src/bin/tool.rs", module)])), vec![3, 4]);
|
||||
// Cargo's auto-discovery builds a `mod.rs` directly in `src/bin` or `tests` as a target, but not one below.
|
||||
assert_eq!(lines(&predefined_quit([("src/bin/mod.rs", module)])), vec![3, 4]);
|
||||
assert_eq!(lines(&predefined_quit([("tests/mod.rs", module)])), vec![3, 4]);
|
||||
assert_eq!(lines(&predefined_quit([("src/bin/tool/mod.rs", module)])), vec![4]);
|
||||
// A `lib.rs` that another file loads through a `#[path]` attribute is a module.
|
||||
let root = "#[path = \"nested/lib.rs\"]\nmod nested;\n";
|
||||
assert_eq!(lines(&predefined_quit([("src/lib.rs", root), ("src/nested/lib.rs", module)])), vec![4]);
|
||||
// The root's alias reaches the module files it declares.
|
||||
let root = "extern crate muda as menu;\nmod child;\n";
|
||||
let child = "fn menu_bar() {\n let a = ::menu::PredefinedMenuItem::quit(None);\n}\nuse ::menu::PredefinedMenuItem as Item;\nfn b() { Item::quit(None); }\n\
|
||||
fn c() { menu::PredefinedMenuItem::quit(None); }\nuse menu::PredefinedMenuItem as Other;\nfn d() { Other::quit(None); }\n\
|
||||
mod shadowed {\n use other_menu as menu;\n fn e() { menu::PredefinedMenuItem::quit(None); }\n}\n";
|
||||
let found = predefined_quit([("src/lib.rs", root), ("src/child.rs", child)]);
|
||||
assert_eq!(
|
||||
found.iter().map(|f| (f.path.as_str(), f.line)).collect::<Vec<_>>(),
|
||||
vec![("src/child.rs", 2), ("src/child.rs", 5), ("src/child.rs", 6), ("src/child.rs", 8)]
|
||||
);
|
||||
// Without the root that declares the alias, `menu` is not muda.
|
||||
assert!(predefined_quit([("src/child.rs", child)]).is_empty());
|
||||
// The alias follows the library's modules, not the binary's module of the same name, and `src/lib.rs`
|
||||
// stays a root when another file also declares it as a module.
|
||||
let call = "fn f() { ::menu::PredefinedMenuItem::quit(None); }\n";
|
||||
let found = predefined_quit([
|
||||
("src/lib.rs", "extern crate muda as menu;\nmod outer;\nfn g() { ::menu::PredefinedMenuItem::quit(None); }\n"),
|
||||
("src/outer.rs", "mod child;\n"),
|
||||
("src/outer/child.rs", call),
|
||||
("src/main.rs", "mod child;\n#[path = \"lib.rs\"]\nmod lib;\n"),
|
||||
("src/child.rs", call),
|
||||
]);
|
||||
assert_eq!(found.iter().map(|f| (f.path.as_str(), f.line)).collect::<Vec<_>>(), vec![("src/lib.rs", 3), ("src/outer/child.rs", 1)]);
|
||||
// A module file in a folder named `tests` is not a test crate's root.
|
||||
let local = "extern crate muda as menu;\nfn f() { ::menu::PredefinedMenuItem::quit(None); }\n";
|
||||
assert!(predefined_quit([("src/tests/mod.rs", "mod child;\n"), ("src/tests/child.rs", local)]).is_empty());
|
||||
assert_eq!(lines(&predefined_quit([("tests/child.rs", local)])), vec![2]);
|
||||
// A test that another test also loads by path stays a root, and its alias reaches its modules, which
|
||||
// are in the root's own folder.
|
||||
let found = predefined_quit([
|
||||
("tests/foo.rs", "extern crate muda as menu;\nmod part;\n"),
|
||||
("tests/part.rs", call),
|
||||
("tests/foo/part.rs", call),
|
||||
("tests/bar.rs", "#[path = \"foo.rs\"]\nmod foo;\n"),
|
||||
]);
|
||||
assert_eq!(found.iter().map(|f| (f.path.as_str(), f.line)).collect::<Vec<_>>(), vec![("tests/part.rs", 1)]);
|
||||
// A binary's root in `src/bin` declares its modules beside it, not in a folder named after it.
|
||||
let found = predefined_quit([
|
||||
("src/bin/tool.rs", "extern crate muda as menu;\nmod child;\n"),
|
||||
("src/bin/child/mod.rs", call),
|
||||
("src/bin/tool/child.rs", call),
|
||||
]);
|
||||
assert_eq!(found.iter().map(|f| (f.path.as_str(), f.line)).collect::<Vec<_>>(), vec![("src/bin/child/mod.rs", 1)]);
|
||||
// A file in `tests` or `src/bin` is its own crate's root also when another target declares it as a module.
|
||||
let found = predefined_quit([
|
||||
("tests/foo.rs", "mod part;\n"),
|
||||
("tests/part.rs", local),
|
||||
("src/bin/tool.rs", "mod helper;\n"),
|
||||
("src/bin/helper.rs", local),
|
||||
]);
|
||||
assert_eq!(found.iter().map(|f| (f.path.as_str(), f.line)).collect::<Vec<_>>(), vec![("tests/part.rs", 2), ("src/bin/helper.rs", 2)]);
|
||||
// A package's `build.rs` and a binary's `main.rs` stay roots when a file loads them through `#[path]`.
|
||||
let found = predefined_quit([
|
||||
("src/lib.rs", "#[path = \"../build.rs\"]\nmod build;\n#[path = \"bin/tool/main.rs\"]\nmod tool;\n"),
|
||||
("build.rs", local),
|
||||
("src/bin/tool/main.rs", local),
|
||||
]);
|
||||
assert_eq!(found.iter().map(|f| (f.path.as_str(), f.line)).collect::<Vec<_>>(), vec![("build.rs", 2), ("src/bin/tool/main.rs", 2)]);
|
||||
// A folder named `src` above the package, as in a path `rust_sources` returns, does not change that.
|
||||
let found = predefined_quit([
|
||||
("/home/dev/src/app/src/bin/tool.rs", "mod helper;\n"),
|
||||
("/home/dev/src/app/src/bin/helper.rs", local),
|
||||
("/home/dev/src/app/src/lib.rs", "#[path = \"../build.rs\"]\nmod build;\n"),
|
||||
("/home/dev/src/app/build.rs", local),
|
||||
]);
|
||||
assert_eq!(
|
||||
found.iter().map(|f| (f.path.as_str(), f.line)).collect::<Vec<_>>(),
|
||||
vec![("/home/dev/src/app/src/bin/helper.rs", 2), ("/home/dev/src/app/build.rs", 2)]
|
||||
);
|
||||
// A `tests` folder inside a test's module folder holds modules, so a declared file there is not a root.
|
||||
assert!(
|
||||
predefined_quit([
|
||||
("tests/support/mod.rs", "mod tests;\n"),
|
||||
("tests/support/tests/mod.rs", "mod helper;\n"),
|
||||
("tests/support/tests/helper.rs", local)
|
||||
])
|
||||
.is_empty()
|
||||
);
|
||||
// A child's own `menu` module, imported through `self::`, is not the crate.
|
||||
let found = predefined_quit([
|
||||
("src/lib.rs", "extern crate muda as menu;\nmod child;\n"),
|
||||
("src/child.rs", "mod menu {}\nuse self::menu as other;\nfn f() { other::PredefinedMenuItem::quit(None); }\n"),
|
||||
]);
|
||||
assert!(found.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn predefined_quit_skips_root_aliases_that_are_never_compiled_or_in_macro_input() {
|
||||
let call = "fn f() { ::menu::PredefinedMenuItem::quit(None); }\n";
|
||||
let paths = |found: &[Finding]| found.iter().map(|f| (f.path.clone(), f.line)).collect::<Vec<_>>();
|
||||
// A module declaration that is never compiled does not carry the alias to the file it names.
|
||||
for gate in ["#[cfg(any())]", "#[cfg(false)]", "#[cfg(not(all()))]"] {
|
||||
let lib = format!("extern crate muda as menu;\n{gate}\nmod shared;\n{gate}\n#[path = \"other.rs\"]\nmod other;\n");
|
||||
let main = "extern crate other_menu as menu;\nmod shared;\n";
|
||||
let found = predefined_quit([("src/lib.rs", lib.as_str()), ("src/main.rs", main), ("src/shared.rs", call), ("src/other.rs", call)]);
|
||||
assert!(found.is_empty(), "{gate}: {found:?}");
|
||||
}
|
||||
// One that a target may compile still does, plainly or through `#[path]`.
|
||||
let lib = "extern crate muda as menu;\n#[cfg(unix)]\nmod shared;\n#[cfg(feature = \"x\")]\n#[path = \"other.rs\"]\nmod other;\n";
|
||||
let found = predefined_quit([("src/lib.rs", lib), ("src/shared.rs", call), ("src/other.rs", call)]);
|
||||
assert_eq!(paths(&found), vec![("src/shared.rs".to_owned(), 1), ("src/other.rs".to_owned(), 1)]);
|
||||
// An `extern crate` that is never compiled adds no name to the prelude; one that is false only on some
|
||||
// targets does.
|
||||
let lib = "#[cfg(any())]\nextern crate muda as menu;\nextern crate other_menu as menu;\nmod child;\nfn g() { ::menu::PredefinedMenuItem::quit(None); }\n";
|
||||
assert!(predefined_quit([("src/lib.rs", lib), ("src/child.rs", call)]).is_empty());
|
||||
let lib = "#[cfg(target_os = \"macos\")]\nextern crate muda as menu;\nmod child;\n";
|
||||
assert_eq!(paths(&predefined_quit([("src/lib.rs", lib), ("src/child.rs", call)])), vec![("src/child.rs".to_owned(), 1)]);
|
||||
// Neither does an `extern crate` in a macro's input, while a real one beside it does.
|
||||
for input in ["ignore!(extern crate muda as menu;);", "ignore![extern crate muda as menu;];", "ignore! { extern crate muda as menu; }"] {
|
||||
let lib = format!("{input}\nmod child;\n");
|
||||
assert!(predefined_quit([("src/lib.rs", lib.as_str()), ("src/child.rs", call)]).is_empty(), "{input}");
|
||||
let lib = format!("{input}\nextern crate muda as native;\nmod child;\n");
|
||||
let child = "fn f() { ::native::PredefinedMenuItem::quit(None); ::menu::PredefinedMenuItem::quit(None); }\n";
|
||||
assert_eq!(paths(&predefined_quit([("src/lib.rs", lib.as_str()), ("src/child.rs", child)])), vec![("src/child.rs".to_owned(), 1)]);
|
||||
}
|
||||
// In a file, a never-compiled or macro-input `extern crate muda as menu;` does not bind `menu` to muda.
|
||||
let module = "mod a {\n #[cfg(any())]\n extern crate muda as menu;\n fn f() { menu::PredefinedMenuItem::quit(None); }\n}\n\
|
||||
mod b {\n ignore!(extern crate muda as menu;);\n fn f() { menu::PredefinedMenuItem::quit(None); }\n}\n";
|
||||
assert!(predefined_quit([("src/child.rs", module)]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn predefined_quit_reads_target_folders_below_the_package_folder_only() {
|
||||
let local = "extern crate muda as menu;\nfn f() { ::menu::PredefinedMenuItem::quit(None); }\n";
|
||||
let lib = "#[path = \"../build.rs\"]\nmod build;\n#[path = \"../tests/t.rs\"]\nmod t;\n";
|
||||
for dir in ["/work/tests/app", "tests/app", "C:/src/bin/app"] {
|
||||
let (lib_path, build, test) = (format!("{dir}/src/lib.rs"), format!("{dir}/build.rs"), format!("{dir}/tests/t.rs"));
|
||||
let found = predefined_quit([(lib_path.as_str(), lib), (build.as_str(), local), (test.as_str(), local)]);
|
||||
let found: Vec<(&str, usize)> = found.iter().map(|f| (f.path.as_str(), f.line)).collect();
|
||||
assert_eq!(found, vec![(build.as_str(), 2), (test.as_str(), 2)], "{dir}");
|
||||
}
|
||||
// Inside the package a `tests` folder in `src` still holds modules.
|
||||
let lib = "mod tests;\n";
|
||||
assert!(predefined_quit([("/work/tests/app/src/lib.rs", lib), ("/work/tests/app/src/tests/mod.rs", local)]).is_empty());
|
||||
// So do target folder names deeper in the package's modules.
|
||||
let found = predefined_quit([
|
||||
("src/lib.rs", "mod foo;\nmod src;\n"),
|
||||
("src/foo.rs", "mod tests;\nmod src;\n"),
|
||||
("src/foo/tests.rs", "mod helper;\n"),
|
||||
("src/foo/tests/helper.rs", local),
|
||||
("src/foo/src.rs", "mod bin;\n"),
|
||||
("src/foo/src/bin.rs", "mod helper;\n"),
|
||||
("src/foo/src/bin/helper.rs", local),
|
||||
("src/src.rs", "mod bin;\n"),
|
||||
("src/src/bin.rs", "mod helper;\n"),
|
||||
("src/src/bin/helper.rs", local),
|
||||
]);
|
||||
assert!(found.is_empty(), "{found:?}");
|
||||
// A package with only binaries, beside the one with a library, keeps its binaries as roots.
|
||||
let found =
|
||||
predefined_quit([("outer/src/lib.rs", ""), ("outer/tools/src/bin/tool.rs", "mod helper;\n"), ("outer/tools/src/bin/helper.rs", local)]);
|
||||
assert_eq!(found.iter().map(|f| (f.path.as_str(), f.line)).collect::<Vec<_>>(), vec![("outer/tools/src/bin/helper.rs", 2)]);
|
||||
// A file in the package's modules that a `#[path]` attribute loads from a `tests` folder is a module too,
|
||||
// so its `extern crate` does not reach the crate's extern prelude.
|
||||
let lib = "extern crate other_menu as menu;\n#[path = \"foo/tests/helper.rs\"]\nmod helper;\n";
|
||||
let found = predefined_quit([("src/lib.rs", lib), ("src/foo/tests/helper.rs", local)]);
|
||||
assert!(found.is_empty(), "{found:?}");
|
||||
// So is a `src/lib.rs` below the package's `src` folder that a `#[path]` attribute loads.
|
||||
let lib = "extern crate other_menu as menu;\n#[path = \"nested/src/lib.rs\"]\nmod nested;\n";
|
||||
let found = predefined_quit([("src/lib.rs", lib), ("src/nested/src/lib.rs", local)]);
|
||||
assert!(found.is_empty(), "{found:?}");
|
||||
// A nested package's library that only its own binary loads stays a crate root, so its alias reaches its modules.
|
||||
let nested = "extern crate muda as menu;\nmod child;\n";
|
||||
let found = predefined_quit([
|
||||
("src/lib.rs", ""),
|
||||
("src/nested/src/lib.rs", nested),
|
||||
("src/nested/src/child.rs", "fn f() { ::menu::PredefinedMenuItem::quit(None); }\n"),
|
||||
("src/nested/src/bin/tool.rs", "#[path = \"../lib.rs\"]\nmod lib;\n"),
|
||||
]);
|
||||
assert_eq!(found.iter().map(|f| (f.path.as_str(), f.line)).collect::<Vec<_>>(), vec![("src/nested/src/child.rs", 1)]);
|
||||
// One that a module beside its `src` folder loads is a module of the outer crate.
|
||||
let found = predefined_quit([
|
||||
("src/lib.rs", "mod nested;\n"),
|
||||
("src/nested/mod.rs", "#[path = \"src/lib.rs\"]\nmod inner;\n"),
|
||||
("src/nested/src/lib.rs", nested),
|
||||
("src/nested/src/child.rs", "fn f() { ::menu::PredefinedMenuItem::quit(None); }\n"),
|
||||
]);
|
||||
assert!(found.is_empty(), "{found:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn predefined_quit_does_not_follow_a_mod_declaration_in_a_macro_input() {
|
||||
let call = "fn f() { ::menu::PredefinedMenuItem::quit(None); }\n";
|
||||
for lib in [
|
||||
"extern crate muda as menu;\nignore!(mod child;);\n",
|
||||
"extern crate muda as menu;\nignore! {\n mod child;\n}\n",
|
||||
"extern crate muda as menu;\n#[attr(mod child;)]\nfn h() {}\n",
|
||||
] {
|
||||
assert!(predefined_quit([("src/lib.rs", lib), ("src/child.rs", call)]).is_empty(), "{lib}");
|
||||
}
|
||||
let lib = "extern crate muda as menu;\nmod child;\n";
|
||||
assert_eq!(lines(&predefined_quit([("src/lib.rs", lib), ("src/child.rs", call)])), vec![1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn predefined_quit_reads_an_extern_crate_in_a_block_inside_call_arguments() {
|
||||
let call = "fn f() {\n consume({\n extern crate muda as menu;\n menu::PredefinedMenuItem::quit(None)\n });\n}\n";
|
||||
assert_eq!(lines(&predefined_quit([("src/child.rs", call)])), vec![4]);
|
||||
let array = "fn f() {\n let items = [{\n extern crate muda as menu;\n menu::PredefinedMenuItem::quit(None)\n }];\n}\n";
|
||||
assert_eq!(lines(&predefined_quit([("src/child.rs", array)])), vec![4]);
|
||||
// In a crate root, a block in an argument binds the name in the block, not in the extern prelude.
|
||||
let lib = "fn f() {\n consume({\n extern crate muda as menu;\n });\n}\nmod child;\n";
|
||||
let child = "fn g() { ::menu::PredefinedMenuItem::quit(None); }\n";
|
||||
assert!(predefined_quit([("src/lib.rs", lib), ("src/child.rs", child)]).is_empty());
|
||||
// A `macro_rules!` template is not a declaration where it is written, in any delimiter.
|
||||
for body in [
|
||||
"macro_rules! m {\n () => (\n extern crate muda as menu;\n menu::PredefinedMenuItem::quit(None)\n );\n}\n",
|
||||
"macro_rules! m {\n () => [\n extern crate muda as menu;\n menu::PredefinedMenuItem::quit(None)\n ];\n}\n",
|
||||
"macro_rules! m (\n () => {\n extern crate muda as menu;\n menu::PredefinedMenuItem::quit(None)\n };\n);\n",
|
||||
] {
|
||||
assert!(predefined_quit([("src/child.rs", body)]).is_empty(), "{body}");
|
||||
}
|
||||
// Nor is an attribute's input, in a crate root or a module.
|
||||
for attr in ["#[attr(extern crate muda as menu;)]\nfn h() {}\n", "#![attr(extern crate muda as menu;)]\n"] {
|
||||
let lib = format!("{attr}mod child;\n");
|
||||
assert!(predefined_quit([("src/lib.rs", lib.as_str()), ("src/child.rs", child)]).is_empty(), "{attr}");
|
||||
let module = format!("{attr}fn g() {{ menu::PredefinedMenuItem::quit(None); }}\n");
|
||||
assert!(predefined_quit([("src/child.rs", module.as_str())]).is_empty(), "{attr}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn predefined_quit_reads_a_crate_name_in_an_import_where_the_import_is() {
|
||||
let source = r#"
|
||||
@@ -1008,6 +1256,32 @@ fn run(ready: bool, items: Vec<u64>) {
|
||||
assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![5, 8, 11, 14, 17, 20, 23, 26]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn std_instant_ends_a_native_cfg_loop_at_its_body_after_an_if_or_match_in_its_head() {
|
||||
let source = r#"
|
||||
fn run(flag: bool, n: u8) {
|
||||
#[cfg(unix)]
|
||||
for _ in if flag { [0] } else { [1] } {
|
||||
let _a = std::time::Instant::now();
|
||||
}
|
||||
let b = std::time::Instant::now();
|
||||
#[cfg(unix)]
|
||||
for _ in if flag { [0] } else if n > 1 { [1] } else { [2] }.iter() { let _c = std::time::Instant::now(); }
|
||||
let d = std::time::Instant::now();
|
||||
#[cfg(unix)]
|
||||
if let Some(_) = match n { 0 => None, _ => Some(n) } { let _e = std::time::Instant::now(); }
|
||||
let f = std::time::Instant::now();
|
||||
#[cfg(unix)]
|
||||
while n == if if flag { true } else { false } { 1 } else { 2 } { let _g = std::time::Instant::now(); }
|
||||
let h = std::time::Instant::now();
|
||||
#[cfg(unix)]
|
||||
if flag { let _i = std::time::Instant::now(); } else if if flag { true } else { false } { let _j = std::time::Instant::now(); }
|
||||
let k = std::time::Instant::now();
|
||||
}
|
||||
"#;
|
||||
assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![7, 10, 13, 16, 19]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn std_instant_ends_a_native_cfg_let_else_and_match_with_struct_patterns_where_they_end() {
|
||||
let source = r#"
|
||||
@@ -1229,6 +1503,22 @@ fn run() {
|
||||
assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![4, 8, 9]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn std_instant_does_not_read_an_absolute_path_through_a_local_alias() {
|
||||
let source = r#"
|
||||
use std::time as web_time;
|
||||
use ::web_time::{Instant};
|
||||
use ::web_time::Instant as Clock;
|
||||
|
||||
fn now() {
|
||||
let a = ::web_time::Instant::now();
|
||||
let b = web_time::Instant::now();
|
||||
let c = ::std::time::Instant::now();
|
||||
}
|
||||
"#;
|
||||
assert_eq!(lines(&std_instant([("src/now.rs", source)])), vec![8, 9]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn std_instant_reads_a_use_group_split_over_several_lines() {
|
||||
let source = r#"
|
||||
@@ -1303,6 +1593,21 @@ fn a_long_name_shared_by_many_use_leaves_is_read_without_copying_it_to_each() {
|
||||
assert!(predefined_quit([("src/wide.rs", source.as_str())]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guards_read_names_that_hold_combining_marks() {
|
||||
// `t` with U+0301 (a nonspacing mark) and Devanagari `ka` with U+093E (a spacing mark) are each one
|
||||
// identifier, as rustc reads them.
|
||||
let time = "use std::time as t\u{301};\nuse std::time as \u{915}\u{93E};\nfn run() {\n let a = t\u{301}::Instant::now();\n let b = \u{915}\u{93E}::Instant::now();\n}\n";
|
||||
assert_eq!(lines(&std_instant([("src/run.rs", time)])), vec![4, 5]);
|
||||
|
||||
let menu = "use muda::{PredefinedMenuItem as Ite\u{301}m};\nfn menu() {\n let a = Ite\u{301}m::quit(None);\n}\n";
|
||||
assert_eq!(lines(&predefined_quit([("src/menu.rs", menu)])), vec![3]);
|
||||
|
||||
// A byte order mark and the left-to-right and right-to-left marks are not part of a name.
|
||||
let marked = "\u{FEFF}use std::time::Instant;\nuse std::time as\u{200E}t;\nfn run() { t\u{200F}::Instant::now(); }\n";
|
||||
assert_eq!(lines(&std_instant([("src/marked.rs", marked)])), vec![1, 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn std_instant_reports_a_grouped_import_through_a_long_alias_of_std_time() {
|
||||
let source = r#"
|
||||
|
||||
Reference in New Issue
Block a user