//! Owner-return pins (#4478): an `assert_eq!` whose operand is a call of //! the changed owner pins the owner's whole return value, so it observes a //! changed `return_value` expression without sharing a token with it. //! //! Crediting that assertion is only sound when three facts hold, and each //! gate below fails closed when ripr cannot establish one: //! //! 1. The call names the owner. A bare `name(..)` names a module-level //! function, never an associated function or a trait method — and the //! test's binding of the name must resolve to it: no same-named //! `static`, `const`, tuple struct or competing `use` in reach, an //! explicit `use` or glob resolving to a module holding the owner //! (directly or through one re-export), else the test beside the //! owner. A method //! call `recv.name(..)` names a function with a `self` receiver, and only //! when the receiver's type dispatches to the owner: the test binds the //! receiver to a type ripr can read, no type declaration in the test's //! own module scope shadows that name, that type reaches the owner's //! `impl` or trait, and no other definition of `name` in the workspace //! could take the call instead. //! 2. The call's return value came through the changed expression. The //! changed expression must be the owner's tail and must evaluate all of //! its parts on every input (no closure, `&&`/`||`, branch, or skipping //! combinator such as `map_or`). When the owner has other //! exits (`?`, `return`), the changed expression must be the owner's only //! `Ok(..)` (or `Some(..)`) constructor and the pinned value must be that //! constructor too: an `Err(..)` pin observes an early exit that never //! evaluates the changed `Ok(..)`. //! 3. The pinned value is the whole return value: one plain `assert_eq!` //! in the test's own body with the call as a complete operand, nothing //! chained after it, and an expected value that does not call the owner //! again. `assert_ne!`, `debug_assert_eq!` and a `#[should_panic]` test //! pin nothing. Its exact parser context must also establish an eager //! statement path (or a directly invoked bounded closure), and no visible //! workspace macro definition/import may compete with `assert_eq!`. //! Deferred, conditional and ambiguous contexts do not supply this pin. //! //! This is bounded syntax, not name resolution. The documented residuals: //! methods generated by derive or attribute macros are invisible, a //! `macro_rules!` body that defines the method counts only when ripr can //! read its `fn` text, and an out-of-workspace trait in scope that also //! names the method is not detected. mod call_term_fold; pub(super) mod closure_adaptor; mod expected_binding; mod fallible_check; mod fixture_receiver; mod helper_arguments; pub(in crate::analysis::classify) mod path_value; pub(super) mod result_map; pub(super) mod returned_closure; mod shared_macro_scan; pub(super) mod short_circuit; pub(in crate::analysis) use fallible_check::{FallibleCheckReceipt, fallible_check_receipt}; use shared_macro_scan::ScanPart; pub(in crate::analysis) use shared_macro_scan::SharedMacroScans; use super::super::rust_index::{FunctionSummary, OracleFact, RustIndex, TestSummary}; use super::call_identity::{CallTarget, ConstantTable, OwnerCallIdentity}; use super::reveal::{ UsePath, assertion_comparison_operands, contains_as_whole_word, file_imports_foreign_callee_name, file_imports_own_item, file_use_statements, flattened_use_paths, split_top_level_arguments, use_statement_binds_name, use_statement_first_segment, }; use crate::analysis::extract::{ err_return_guard_twin, fact_body_defines_callee_fn, fact_body_let_shadow_line, mask_comments_and_strings, outer_assertion_condition, test_body_defines_callee_fn, test_body_let_shadow_line, }; use crate::analysis::facts::drop_in::DropInManifests; use crate::analysis::facts::expanded_assertion_view; use crate::analysis::facts::{ DOCTEST_FUNCTION_NAME, ExecutionContext, FileFactsView, FunctionContainer, ModulePathTarget, RustIncludeLimitation, SourceRoleProvenanceEdgeKind, literal_include_fragments, }; use crate::analysis::sync_memo::SyncMemo; use crate::analysis::syntax::constant_items::{ConstantSyntax, span_text}; use crate::analysis::syntax::fn_signature::{LocalTypeEquality, local_type_equality}; use crate::analysis::syntax::ra::LineIndex; use crate::analysis::syntax::{ AssertionContextRefusal, ClaimsMacroKind, GeneratedTestPins, HelperLoan, ItemNesting, MacroBindingCandidates, MacroBindingKind, MacroBindingSite, OwnerPinAssertions, PatternPins, RootShadow, TRUSTED_MACRO_NAMES, attribute_settles_test_outcome, cfg_if_module_name, claims_macro_names, claims_payload_variant, drop_in_assertion_leaf, empty_macro_binding_ambiguities, err_return_guard_key, generated_test_pins, is_test_scoped_trusted_macro, local_empty_macro_names, macro_binding_scan, module_path_targets, owner_pin_assertions, owner_pin_assertions_with_default_features, parse_clean_source_file, pattern_pins, qualified_matches_paths, returns_leave_the_function, source_binds_value_name, source_declares_value_name, source_imported_claims_macros, trusted_macro_binding_site_sets, trusted_macro_binding_sites, }; use crate::analysis::workspace::declared_crate_root_paths_from_manifest; use crate::domain::{Probe, ProbeFamily}; use ra_ap_syntax::{ AstNode, SyntaxNode, ast::{self, HasArgList, HasAttrs, HasGenericArgs, HasGenericParams, HasModuleItem, HasName}, }; use rayon::prelude::*; use std::cell::{Cell, OnceCell}; use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::sync::OnceLock; /// The owner-side half of the pin, established once per probe. pub(in crate::analysis) struct OwnerReturnPin { name: String, call: PinCall, path: ReturnPathGate, /// Argument positions of slice-like parameters the changed expression /// walks; a pinned call passing only an empty literal there never /// reaches the change (#9444). walked_positions: Vec, /// Where the owner `fn` starts. It serves the #6957 exemption, where a /// same-name type declaration in the owner's own enclosing module is the /// production declaration, not a test-local shadow. It also places the /// owner among its file's inline modules and crate root, which a /// path-qualified call (`crate::m::name(..)`, `krate::name(..)`) must /// reach (#6974). owner_file: PathBuf, owner_start_line: usize, /// The owner declares `-> bool`, so `assert!(owner(..))` pins its whole /// return value to `true` and `assert!(!owner(..))` to `false`. returns_bool: bool, /// The owner declares a primitive scalar return (`u32`, `bool`, `char`, /// ...). An immutable `let` of its result is `Copy` with no interior /// mutability, so no later statement can change it (cell-0094). returns_scalar: bool, /// A [`Self::returns_scalar`] owner whose return type is a built-in /// integer, so `.min(K)`, `.max(K)`, `* 1` and `+ 0` keep their std /// meaning on it (trap-ceiling-wide-min-control). returns_integer: bool, /// A masked integer tail needs an individually discriminating literal /// pointer input; the direct-call mask guard reads original owner names. pointer_mask_gate: super::mask_pin::PointerMaskGate, /// A typed pointer must observe a value that differs from the baseline. pointer_return_change: Option, /// The changed tail is the whole value `T(e)` / `Self(e)` of a tuple /// struct `T` built from one argument, so `owner(..).0` is exactly `e` /// (#12796). The test side still checks that `T` is a plain /// single-integer-field struct. tuple_projection: Option, /// #12808: what the closed subset needs to lower the tuple-struct owner /// and read both of its versions, when `tuple_projection` is set. tuple_change: Option, /// The owner is an `async fn`, so a test reads its return value as /// `owner(..).await` (RIPR-SPEC-0197 rule 1, `#[tokio::test]`). awaited: bool, /// Test-local helpers that poll one future to completion and return its /// output, so `helper(owner(..))` reads as `owner(..).await` (RIPR-SPEC-0197 /// rule 1). Empty unless the owner is `async`. poll_helpers: BTreeSet, /// Every record type the owner's return expression constructs has at /// most a plain (empty) `Drop` impl in the workspace, so dropping the /// receiver while unwinding from a failed assertion cannot exit the /// process before the failure is reported (#8480). drop_plain: bool, /// Per test file: whether the owner's trait is in scope. The trait is /// fixed per pin and the scan masks the whole file, so it runs once. trait_scope_by_file: SyncMemo>, /// Same-named module-level rivals in the owner's package, settled per /// test by the call's spelled path (#6544). `None` when there are none. /// Shared per analysis run with the relation stage's identity (#7716). identity: Option>, /// #12716: the owner before and after the diff, read as the closed /// arithmetic subset, when both are and it is called by its bare name. It /// lets a pinned literal that neither version returns withhold the credit. closed_owner: Option, /// #8361: the edit only drops or adds whole guard operands of the bool /// owner's `&&` / `||` tail. A pinned call whose literal arguments leave /// every such operand at its chain's identity value runs both versions /// to the same result, so it withholds the credit. guard_operands: Option, /// #13005: set only while [`Self::literal_check_withholds`] asks whether /// the current-owner literal check is the one gate refusing an assertion. skip_current_literal_check: Cell, } /// The tuple-struct owner's text, changed line and old text, and whether /// `Self` names the returned tuple struct (#12808). struct TupleChange { definition: String, changed_line: usize, before: String, self_is_type: bool, } /// A file's `std`/`core`-rooted `assert_eq!` paths and, for the rooted /// spellings a caller asks about, whether the file can rebind that root. #[derive(Debug, Default)] struct StdRootedCalls { calls: BTreeSet, matches_calls: BTreeSet, /// The spellings in `proved` whose root the file leaves unrebound. unrebound: BTreeSet, /// The rooted spellings whose root proof ran while the tree was in hand: /// the file's own rooted calls and the `assert` twins of its rooted /// `matches!` calls, the spellings the context gate asks about. Each /// proof walks the whole file several times and most test files spell /// no rooted call at all: proving all 24 spellings for every file read /// was 31% of a `check` run's 1.47 billion allocations on this /// repository (#13703). Any other spelling is proved on demand by /// [`Self::is_unrebound`]. proved: BTreeSet<&'static str>, /// On-demand answers, kept so a spelling the read did not prove (one an /// assertion's text shows but the tree walk did not report as a call) /// costs one parse per file, not one per assertion asked. on_demand: std::sync::Mutex>, } /// The assertion macros whose execution the shared admission can establish /// (#8927, #8983): the equality family and the boolean family, each with its /// `debug_` twin. `assert_ne!` and the `debug_` spellings run the same /// argument-evaluating, early-diverging expansion as `assert_eq!`/`assert!`, /// so a context that never runs one never runs the others. const ADMITTED_ASSERTION_MACROS: [&str; 6] = [ "assert_eq", "assert_ne", "debug_assert_eq", "debug_assert_ne", "assert", "debug_assert", ]; /// Whether the masked assertion text holds a token that can leave the test /// before the comparison runs (`return`, `break`, `continue`, `yield`, `?`). fn operand_holds_exit_token(text: &str) -> bool { let masked = mask_comments_and_strings(text); masked.contains('?') || ["return", "break", "continue", "yield"] .iter() .any(|word| !whole_word_offsets(&masked, word).is_empty()) } /// Pure comparison macros that may nest in a boolean assertion's operand, /// each with the crate that exports it. Their expansions compare two values /// and never leave the enclosing function. const KNOWN_COMPARISON_MACROS: [(&str, &str); 4] = [ ("approx_eq", "float_cmp"), ("relative_eq", "approx"), ("abs_diff_eq", "approx"), ("ulps_eq", "approx"), ]; /// The [`KNOWN_COMPARISON_MACROS`] names `source` imports by name from their /// crate (no glob, no `as` alias). fn imported_comparison_macros(source: &str) -> BTreeSet<&'static str> { let imports = mask_comments_and_strings(source); // Every `use` statement that names a macro, as its `use` tree and whether // an attribute (`#[cfg(..)]`) precedes it. let trees: Vec<(&str, bool)> = imports .split(';') .filter_map(|statement| { let (before, tree) = statement.trim().rsplit_once("use ")?; // Only an attribute attached to this `use` gates it, not one on // an enclosing `mod` or an earlier item. let attached = before .rfind(['{', '}']) .map_or(before, |at| &before[at + 1..]); Some((tree, attached.contains("#["))) }) .collect(); KNOWN_COMPARISON_MACROS .iter() .filter(|(name, krate)| { // A `use` of the same name from anywhere else, or a gated one, // could be the binding the assertion resolves to. let mut from_crate = false; for (tree, gated) in &trees { if whole_word_offsets(tree, name).is_empty() { continue; } // The name must be a direct item of the crate's path: `krate::name` // or one entry of `krate::{.., name, ..}`. let direct = tree .trim() .strip_prefix(&format!("{krate}::")) .is_some_and(|rest| { let rest = rest.trim(); // A nested group (`{inner::{x, name}}`) is not a direct // item list, so it is refused rather than split. rest.strip_prefix('{') .and_then(|group| group.strip_suffix('}')) .map_or(vec![rest], |group| { if group.contains(['{', '}']) { Vec::new() } else { group.split(',').collect() } }) .iter() .any(|item| item.trim() == *name) }); let clean = !gated && direct && !tree.contains('*') && !tree.contains(" as "); if !clean { return false; } from_crate = true; } from_crate }) .map(|(name, _)| *name) .collect() } /// Every name some `macro_rules!` in the index defines. fn macro_rules_names(index: &RustIndex) -> BTreeSet { let mut names = BTreeSet::new(); for file in index.files().values() { let masked = mask_comments_and_strings(&file.source); for at in whole_word_offsets(&masked, "macro_rules") { let Some(rest) = masked[at + "macro_rules".len()..] .trim_start() .strip_prefix('!') else { continue; }; let name: String = rest .trim_start() .chars() .take_while(|ch| ch.is_ascii_alphanumeric() || *ch == '_') .collect(); if !name.is_empty() { names.insert(name); } } } names } /// The rooted spellings of every admitted assertion macro: each needs the /// same root proof. const STD_ROOTED_ASSERT_EQ: [&str; 24] = [ "std::assert_eq", "core::assert_eq", "::std::assert_eq", "::core::assert_eq", "std::assert_ne", "core::assert_ne", "::std::assert_ne", "::core::assert_ne", "std::debug_assert_eq", "core::debug_assert_eq", "::std::debug_assert_eq", "::core::debug_assert_eq", "std::debug_assert_ne", "core::debug_assert_ne", "::std::debug_assert_ne", "::core::debug_assert_ne", "std::assert", "core::assert", "::std::assert", "::core::assert", "std::debug_assert", "core::debug_assert", "::std::debug_assert", "::core::debug_assert", ]; #[cfg(test)] thread_local! { static PROJECTED_WORKSPACE_FILE_VISITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static PROJECTED_WORKSPACE_FILE_PARSES: std::cell::Cell = const { std::cell::Cell::new(0) }; static STD_ROOTED_FILE_PARSES: std::cell::Cell = const { std::cell::Cell::new(0) }; static STD_ROOT_PROOFS: std::cell::Cell = const { std::cell::Cell::new(0) }; } impl StdRootedCalls { fn of(source: &str) -> Self { #[cfg(test)] STD_ROOTED_FILE_PARSES.with(|count| count.set(count.get() + 1)); let Some(file) = parse_clean_source_file(source) else { return Self::default(); }; let root = file.tree().syntax().clone(); let calls = std_rooted_assert_eq_calls(&root); let matches_calls = qualified_matches_paths(&root); let asked: BTreeSet = calls .iter() .cloned() .chain(matches_calls.iter().filter_map(|path| { path.strip_suffix("matches") .map(|root| format!("{root}assert")) })) .collect(); let proved: BTreeSet<&'static str> = STD_ROOTED_ASSERT_EQ .iter() .copied() .filter(|path| asked.contains(*path)) .collect(); let unrebound = proved .iter() .filter(|path| std_root_proof(path, &root)) .map(|path| (*path).to_string()) .collect(); Self { calls, matches_calls, unrebound, proved, on_demand: std::sync::Mutex::default(), } } /// Whether `source` (the text this value was read from) leaves the root /// of the rooted spelling `path` unrebound: exactly the answer an eager /// proof of every spelling at read time gives. A spelling outside /// [`STD_ROOTED_ASSERT_EQ`] or a refused parse is never unrebound. fn is_unrebound(&self, path: &str, source: &str) -> bool { if self.proved.contains(path) { return self.unrebound.contains(path); } let Some(spelling) = STD_ROOTED_ASSERT_EQ .iter() .copied() .find(|known| *known == path) else { return false; }; if let Some(known) = self .on_demand .lock() .ok() .and_then(|answers| answers.get(spelling).copied()) { return known; } let answer = parse_clean_source_file(source) .is_some_and(|file| std_root_proof(spelling, file.tree().syntax())); if let Ok(mut answers) = self.on_demand.lock() { answers.insert(spelling, answer); } answer } } /// [`crate::analysis::syntax::ra::std_macro_root_is_unrebound`], counted in /// test builds so a test can pin which spellings a file read proves. fn std_root_proof(path: &str, root: &ra_ap_syntax::SyntaxNode) -> bool { #[cfg(test)] STD_ROOT_PROOFS.with(|count| count.set(count.get() + 1)); crate::analysis::syntax::ra::std_macro_root_is_unrebound(path, root) } /// Run-scoped syntax decisions shared by every probe against one index. /// No cache outlives that immutable index; no public/file facts are changed. #[derive(Clone, Debug, Default)] pub(in crate::analysis) struct OwnerPinSyntax { /// Per test file, its `std`/`core`-rooted `assert_eq!` calls and which /// of those roots the file itself leaves unrebound (#7857). Parsed once /// per file, not once per assertion. std_rooted: SyncMemo>>, /// #8051: per test file, its bare `debug_assert_eq!` calls, parsed once /// per file rather than once per (probe, related test). debug_assert_eq_calls: SyncMemo>>>, fallible_dependencies: SyncMemo)>>, ambiguous_macro_bindings: SyncMemo>>, /// RIPR-SPEC-0352: per package root, the names the package's own files /// make ambiguous without a scope (the unplaced receiver limit reads /// only these, never another package's sites). own_package_macro_ambiguities: SyncMemo, /// Definitions confined to one inline module or function body, keyed by /// file: they make a name ambiguous only for tests inside that scope. scoped_macro_bindings: SyncMemo>, /// Crate-local sites keyed by the recognized target root that holds /// them: they make a name ambiguous only for tests in that crate. crate_macro_bindings: SyncMemo>, /// #8255: the workspace-wide sites the single trusted-macro ambiguity /// pass retained, completed on demand, so naming a refusal never /// rescans the workspace per (name, test root). workspace_site_scan: SyncMemo>, /// #13269: per module file, whether it may carry an ancestor's private /// glob import down to its own modules (see [`source_may_carry_glob_chain`]). glob_chain_by_file: SyncMemo>, /// Files that may import from an ancestor beyond their immediate parent. glob_jump_by_file: SyncMemo>, /// #8255 test witness: full-index macro-site passes this run paid. #[cfg(test)] workspace_scan_passes: SyncMemo, /// Disclosure memo: each test file's sites per refused name. A file's /// sites depend only on the name and the index, and parsing the file /// once per (probe, test, assertion) made a diff with many related tests /// run for an hour. test_file_macro_sites: SyncMemo, /// Per test file, read with the assertion-context macro list. A file that /// is also a module parent has a second, separate entry in /// `module_parents`: the two lists differ (`json`), and one shared key /// made the entry depend on which probe reached the file first, which /// with workers is scheduling (#8797). by_file: SyncMemo>>, /// Same shared syntax authority with the bounded matches! outcome policy. matches_by_file: SyncMemo>>, /// Existing expansion authority excludes opaque generated panic sources. matches_panic_expansions: super::implicit_effect::ImplicitExpansionMemo, /// Whether every matches-binding candidate is this file's verified /// standard assertion argument, rather than a real or opaque binding. matches_arguments_clear: SyncMemo>, /// #10389: per test file, the known comparison macros it imports by name. comparison_imports: SyncMemo>>>, /// #10389: every name a `macro_rules!` in the index defines, scanned once. macro_rules_names: SyncMemo>>, /// Per module-parent file, read with the plain trusted-macro list. module_parents: SyncMemo>>, /// #6648 (RIPR-SPEC-0279): per doc example test (file, start line), its /// assertion admission read from its synthetic source, parsed once per /// run. A doctest is its own crate, so the file holding the comment /// declares no function its assertions could be read under. doctest_pins: SyncMemo>, /// Only generation-owned provider receipts can populate this source view. proptest_pins: SyncMemo>, /// Per file: the exact pattern pins of its tests through a verified /// local `assert_matches!` (#6616), parsed once per run. pattern_pins: SyncMemo>, empty_macro_ambiguities: SyncMemo>>>, /// Per file: the expansion-coordinate admission facts of the tests a /// same-file `macro_rules!` generated (#5334). generated: SyncMemo>>, /// The macro definitions a file sees from other files (#6925), the same /// resolution the generated-test pass applied. macro_visibility: OnceLock, resolved_modules: OnceLock>, execution_contexts: SyncMemo>>>, /// Workspace-wide inputs to [`TargetRoots::root`], computed once. target_roots: OnceLock, /// Names of the workspace's `macro_rules!` macros, scanned once per run /// (RIPR-SPEC-0351 out-parameter owner scan). workspace_macro_names: OnceLock>, /// Whether a workspace trait could answer `write_str`-style calls on the /// std buffers, scanned once per run. user_buffer_traits: OnceLock, /// #6974: path-call memos. A path-shaped assertion is read once per /// probe, test and assertion, and each input below scans the workspace, /// so every answer is kept for the run under the key it depends on. path_memo: SyncMemo, /// Pure workspace-source checks for projected collection equality, /// keyed by the retained source identities of the indexed files. projected_collection_workspace: SyncMemo, /// #7097: bare-call binding verdicts per [`BareCallKey`]. bare_call_memo: SyncMemo>, /// #7097: out-of-line module children per (parent file, `mod` name): /// the composed child file, or `None` when declarations conflict. /// Built once per run; the index is immutable. mod_children: OnceLock>>, /// #7172: [`unit_struct_value`]'s workspace-wide scan verdicts, /// computed once per run over the once-built module-name set. /// The index is immutable, so the memo never goes stale. unit_struct_facts: OnceLock, /// RIPR-SPEC-0225 decision 9: whether the workspace is closed for /// iteration, a whole-index scan computed once per run. iteration_closed: OnceLock, /// The same closed-field premise without the array iteration restriction. field_projection_workspace_closed: OnceLock, /// RIPR-SPEC-0225 decision 9: the names a workspace macro may declare a /// type under, `None` when any name may be declared. macro_type_names: OnceLock>>, /// RIPR-SPEC-0225 decision 9: [`field_builtin_integer`] answers per /// [`FieldIntegerKey`]; the index is immutable, so none goes stale. field_integer_memo: SyncMemo>>, withheld: WithheldMacroBindings, } /// RIPR-SPEC-0352: per (package, declaring parents of the test file), the /// names the test's own scope makes ambiguous. type OwnScopeAmbiguities = BTreeMap<(String, Vec), Arc>>; /// #8051: one bare `debug_assert_eq!` call: its line and source text. type DebugAssertEqCall = (usize, String); /// #7097: a bare-call binding verdict key: owner file, owner line, owner /// name, test file, test line. type BareCallKey = (PathBuf, usize, String, PathBuf, usize); /// RIPR-SPEC-0225 decision 9: a field-integer key: owner file, owner name, /// record type name, field name. type FieldIntegerKey = (PathBuf, String, String, String); /// #6974: run-scoped answers for [`OwnerReturnPin::path_reaches_owner`]. #[derive(Clone, Debug, Default)] struct PathCallMemo { /// Per (owner file, owner start line, owner name, path prefix, test /// file, test line): the verdict. verdicts: BTreeMap<(PathBuf, usize, String, String, PathBuf, usize), bool>, /// Per (file, name, line): the pure item-nesting facts (#6974). nesting: BTreeMap<(PathBuf, String, usize), Option>, /// Per (owner crate root, owner name): whether the crate may hold an /// item of the name ripr cannot see. hidden: BTreeMap<(PathBuf, String), bool>, /// Per file: whether a `cfg` may drop the whole file (#7082). file_gated: BTreeMap, /// Per (test crate root, path root): whether the test's crate may bind /// the root itself. test_crate_binds: BTreeMap<(PathBuf, String), bool>, } /// Only pure workspace-source verdicts belong here. The retained strong /// references prevent address reuse from making a different source look equal. #[derive(Clone, Debug, Default)] struct ProjectedCollectionWorkspaceMemo { sources: Vec<(PathBuf, std::sync::Arc)>, verdicts: BTreeMap, } #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] enum ProjectedCollectionWorkspaceKey { StandardRoots, Constructor(PathBuf, String), } impl ProjectedCollectionWorkspaceMemo { fn refresh(&mut self, index: &RustIndex) { let files = index.files(); if self.sources.len() != files.len() || !self .sources .iter() .zip(files.iter()) .all(|((path, source), (file, facts))| { path == file && std::sync::Arc::ptr_eq(source, &facts.source) }) { self.sources = files .iter() .map(|(path, facts)| (path.clone(), facts.source.clone())) .collect(); self.verdicts.clear(); } } fn verdict( memo: &SyncMemo, index: &RustIndex, key: ProjectedCollectionWorkspaceKey, scan: impl FnOnce() -> bool, ) -> bool { { let mut memo = memo.borrow_mut(); memo.refresh(index); if let Some(verdict) = memo.verdicts.get(&key) { return *verdict; } } // A resolver may itself consult syntax. Never hold a memo lock while // computing a miss, including a refused/invalid-source verdict. let verdict = scan(); let mut memo = memo.borrow_mut(); memo.refresh(index); memo.verdicts.insert(key, verdict); verdict } } /// The macro bindings of files a narrowed diff index withheld (#5320). /// The ambiguity unions below run over every indexed file, so the withheld /// files' share is folded in to keep the decision the full selection made. /// Name-specific empty-macro bindings need no entry here: the diff scope /// admits every file that spells a test file's local empty-macro name. #[derive(Clone, Debug, Default)] pub(in crate::analysis) struct WithheldMacroBindings { /// Some withheld file may shadow any macro name. any_name: bool, /// A crate-local site routed by root may shadow any macro name. The /// trusted set stays per root, but a test file's local empty-macro names /// are refused workspace-wide, as the full scan's empty-macro check /// reads every indexed file without crate routing. root_any_name: bool, /// Trusted macro names withheld files may shadow. trusted: BTreeSet, /// The first withheld site per trusted name, so a refusal can still /// name where the binding is. sites: BTreeMap, /// Crate-local sites in a withheld crate root file, keyed by that root: /// as in the full scan, they reach only tests in the same crate. by_root: CrateMacroBindings, /// The first such site per trusted name and root, for disclosure. root_sites: BTreeMap<(String, PathBuf), (PathBuf, MacroBindingSite)>, /// Withheld binary roots whose sites were confined to themselves. A file /// that composes one of them (`#[path]`, `include!`) puts its macros in /// another crate, which [`Self::widen_composed`] undoes. confined_binaries: BTreeSet, } impl WithheldMacroBindings { /// Fold one withheld file in. Returns `true` once nothing further can /// change the result, so the caller can stop reading. #[cfg(test)] pub(in crate::analysis) fn absorb( &mut self, path: &Path, source: &str, packages: &BTreeSet, drop_ins: &DropInManifests, ) -> bool { self.absorb_with_members(path, source, packages, drop_ins, &Default::default()) } pub(in crate::analysis) fn absorb_with_members( &mut self, path: &Path, source: &str, packages: &BTreeSet, drop_ins: &DropInManifests, members: &crate::analysis::facts::member_crates::MemberCrates, ) -> bool { if self.any_name { return true; } let drop_in_verified = |krate: &str| { if krate == "serde_json" { drop_ins.verified_literal_json(path) } else { drop_ins.verified_root(path, krate) } }; let root = withheld_crate_root(path); let binary_root = OnceCell::new(); for (name, site) in macro_binding_scan( source, packages, &assertion_context_macros(), &drop_in_verified, ) { let binary = *binary_root.get_or_init(|| members.is_binary_target_root(path)); let local_root = if binary { Some(path) } else { root.as_deref().filter(|_| site.crate_local) }; if let Some(root) = local_root { if binary { self.confined_binaries.insert(path.to_path_buf()); } self.root_any_name |= site.kind.binds_any_name(); self.by_root .entry(root.to_path_buf()) .or_default() .insert(name.clone()); self.root_sites .entry((name, root.to_path_buf())) .or_insert_with(|| (path.to_path_buf(), site)); continue; } self.any_name |= site.kind.binds_any_name(); self.trusted.insert(name.clone()); self.sites .entry(name) .or_insert_with(|| (path.to_path_buf(), site)); } self.any_name } /// A withheld unparsable file disables crate-root routing the way /// `used_lexical_fallback` does in the full index (#6919). pub(in crate::analysis) fn disable_crate_root_routing(&mut self) { if self.any_name { self.by_root.clear(); self.root_sites.clear(); self.root_any_name = false; self.confined_binaries.clear(); return; } for (root, names) in std::mem::take(&mut self.by_root) { for name in names { let Some((path, site)) = self.root_sites.remove(&(name.clone(), root.clone())) else { continue; }; self.any_name |= site.kind.binds_any_name(); self.trusted.insert(name.clone()); self.sites.entry(name).or_insert((path, site)); } } self.root_any_name = false; self.confined_binaries.clear(); } } impl WithheldMacroBindings { /// A withheld binary's macros stay in its own crate only while no file /// composes it into another one. `composed` holds the file names that /// path/include compositions spell, with `"*"` standing for a /// composition ripr cannot read; a binary so named, or any binary under /// `"*"`, keeps its sites workspace-wide again. Returns `any_name`. pub(in crate::analysis) fn widen_composed(&mut self, composed: &BTreeSet) -> bool { let unreadable = composed.contains("*"); let widened = std::mem::take(&mut self.confined_binaries) .into_iter() .filter(|binary| { unreadable || binary .file_name() .and_then(|name| name.to_str()) .is_some_and(|name| composed.contains(name)) }) .collect::>(); for binary in widened { let Some(names) = self.by_root.remove(&binary) else { continue; }; for name in names { let Some((path, site)) = self.root_sites.remove(&(name.clone(), binary.clone())) else { continue; }; self.any_name |= site.kind.binds_any_name(); self.trusted.insert(name.clone()); self.sites.entry(name).or_insert((path, site)); } } self.any_name } } /// A withheld file is not indexed, so its module edges are unknown; only a /// file that is itself a `src/lib.rs`, `src/main.rs`, `src/bin/*.rs` or /// `src/bin/NAME/main.rs` crate root has a root known from its path, matching /// [`target_root`] for it. /// Any other withheld file keeps its sites workspace-wide (fails closed). fn withheld_crate_root(path: &Path) -> Option { let names: Vec<&str> = path .iter() .map(|part| part.to_str().unwrap_or_default()) .collect(); let recognized = matches!( names.as_slice(), [.., "src", "lib.rs" | "main.rs"] | [.., "src", "bin", _] | [.., "src", "bin", _, "main.rs"] ); (recognized && path.extension().is_some_and(|extension| extension == "rs")) .then(|| path.to_path_buf()) } impl OwnerPinSyntax { /// #8051: the bare `debug_assert_eq!` calls of `file` from `start_line` /// to `end_line`, from a per-file parse kept for the run. pub(in crate::analysis) fn debug_assert_eq_calls( &self, file: &PathBuf, source: &str, start_line: usize, end_line: usize, ) -> Vec<(usize, String)> { self.debug_assert_eq_calls .get_or_build(file, || { crate::analysis::syntax::debug_assert_eq_calls(source) }) .iter() .filter(|(line, _)| (start_line..=end_line).contains(line)) .cloned() .collect() } /// The run's memo of a whole-index verdict that `compute` reads once. pub(in crate::analysis) fn iteration_closed(&self, compute: impl FnOnce() -> bool) -> bool { *self.iteration_closed.get_or_init(compute) } pub(in crate::analysis) fn field_projection_workspace_closed( &self, compute: impl FnOnce() -> bool, ) -> bool { *self.field_projection_workspace_closed.get_or_init(compute) } /// Whether a macro in the workspace may declare a type named `name`. pub(super) fn macro_may_declare(&self, name: &str, index: &RustIndex) -> bool { self.macro_type_names .get_or_init(|| macro_type_names(index)) .as_ref() .is_none_or(|names| names.contains("$") || names.contains(name)) } /// Bounded targeted-selection identity for a non-generic inherent call. /// Cross-file imports, nested type paths and receiver inference stay /// unresolved; this is not a general Rust name resolver. pub(in crate::analysis) fn targeted_inherent_call_is_local( &self, test: &TestSummary, owner: &FunctionSummary, prefix: &str, index: &RustIndex, ) -> bool { let FunctionContainer::Inherent { self_ty } = &owner.item.container else { return false; }; if owner.file != test.file || !is_plain_identifier(self_ty) { return false; } let Some(facts) = index.files().get(&test.file) else { return false; }; if facts.used_lexical_fallback || file_aliases_type(&facts.source, self_ty) || file_renames_to(&facts.source, self_ty) || file_imports_foreign_callee_name(&facts.source, self_ty, &index.package_names) || declares_type(&mask_comments_and_strings(&test.body), self_ty) || file_aliases_type(&test.body, self_ty) { return false; } let (Some(owner_scope), Some(test_scope)) = ( indexed_item_nesting(index, &owner.file, &owner.name, owner.start_line, true), self.item_nesting(index, &test.file, &test.name, test.start_line), ) else { return false; }; if owner_scope.cfg_gated || self.file_cfg_gated(index, &owner.file) { return false; } if prefix == self_ty { // Imported bindings and globs can shadow the local type, including // evidence-only support owners excluded from candidate collection. // Without scope resolution, conservatively refuse any such import // in this file; an explicit crate-root path is checked separately. owner_scope.modules == test_scope.modules && !file_use_statements(&facts.source).iter().any(|statement| { // Include raw bindings and grouped `Type::{self}` imports; // unrelated mentions of this type also stay conservative. contains_as_whole_word(statement, self_ty) || statement.contains('*') }) } else if prefix == format!("crate::{self_ty}") { owner_scope.modules.is_empty() && self.target_roots(index).root(&owner.file, index).as_ref() == Some(&owner.file) } else { false } } /// #6974: reuse compact nesting facts only for the same retained source. fn item_nesting( &self, index: &RustIndex, file: &Path, name: &str, line: usize, ) -> Option { let key = (file.to_path_buf(), name.to_string(), line); if let Some(known) = self.path_memo.borrow().nesting.get(&key) { return known.clone(); } let nesting = indexed_item_nesting(index, file, name, line, false); self.path_memo .borrow_mut() .nesting .insert(key, nesting.clone()); nesting } /// #7082: whether a `cfg` may drop `file` as a whole, kept per file: a /// dropping inner attribute ([`has_cfg_that_may_drop`]) at the top of /// the file or of any file on the chain that compiles it into its /// crate, or a dropping attribute on any `mod` declaration on that /// chain. A complementary cfg may then compile a same-named module in /// its place. An include edge, an unresolved chain, an unparsable file, /// or a non-root file with no recorded chain (ripr records no edge for /// a `mod` whose `#[path]` it cannot resolve, such as one under /// `cfg_attr`) fails closed. The root test is per file, not the /// workspace-wide [`TargetRoots`] switch, so an unrelated unresolvable /// module elsewhere keeps other owners pinned (#7104 review). fn file_cfg_gated(&self, index: &RustIndex, file: &Path) -> bool { if let Some(known) = self.path_memo.borrow().file_gated.get(file) { return *known; } let roots = self.target_roots(index); let inner_gated = |path: &Path| { index.files().get(path).is_none_or(|facts| { parse_clean_source_file(&facts.source) .is_none_or(|parse| has_cfg_that_may_drop(&parse.tree())) }) }; let context = self.execution_context(&file.to_path_buf(), index); let gated = inner_gated(file) || context.as_ref().as_ref().is_none_or(|context| { (context.edges.is_empty() && target_root(file, index, &roots.src_dirs).as_deref() != Some(file)) || context.edges.iter().any(|edge| { inner_gated(&edge.parent) || module_declaration_cfg_gated( index, &edge.parent, &edge.declaration, edge.line, ) }) }); self.path_memo .borrow_mut() .file_gated .insert(file.to_path_buf(), gated); gated } /// #6974: whether the crate rooted at `owner_root` may hold an item /// named `name` that ripr cannot see, kept per (root, name): a raw /// `r#name` anywhere in the workspace, or a macro invocation in the /// crate whose input names it (`twin!(name)` may emit a `fn name` under /// a cfg that drops the owner). fn crate_may_hide_name( &self, index: &RustIndex, owner_root: &Path, name: &str, roots: &TargetRoots, ) -> bool { let key = (owner_root.to_path_buf(), name.to_string()); if let Some(known) = self.path_memo.borrow().hidden.get(&key) { return *known; } let hidden = workspace_mentions_raw(index, name) || index.files().iter().any(|(path, facts)| { facts.source.contains(name) && roots.may_belong(path, owner_root, index) && bound_by_macro(&mask_comments_and_strings(&facts.source), name) }); self.path_memo.borrow_mut().hidden.insert(key, hidden); hidden } /// Fold in the macro bindings of files the diff index withheld. pub(in crate::analysis) fn with_withheld(mut self, withheld: WithheldMacroBindings) -> Self { self.withheld = withheld; self } /// Shared assertion admission for the bounded supported families. /// Execution provenance is independent of the error/boundary/value/effect matcher. /// Applicability is the invocation /// identity, not the more restrictive owner-pin operand shape, so token /// matches and nested diagnostic syntax cannot bypass the same refusal. pub(in crate::analysis) fn admits_equality_assertion( &self, probe: &Probe, owner: Option<&FunctionSummary>, test: &TestSummary, assertion: &OracleFact, index: &RustIndex, ) -> bool { self.admits_assertion_family(probe.family.clone(), owner, test, assertion, index) && self .matches_expected_panic_refusal(probe, test, assertion, index) .is_none() } /// The execution and macro-binding admission for a plain returned-value /// equality. A caller must separately establish the value-flow relation. pub(super) fn admits_tier_return_assertion( &self, test: &TestSummary, assertion: &OracleFact, index: &RustIndex, ) -> bool { !test.attrs.iter().any(|attr| attr.contains("should_panic")) && self.admits_assertion_family(ProbeFamily::ReturnValue, None, test, assertion, index) } fn matches_expected_panic_refusal( &self, probe: &Probe, test: &TestSummary, assertion: &OracleFact, index: &RustIndex, ) -> Option { if !matches_return_assertion(&probe.family, assertion) || !test.attrs.iter().any(|attr| { parse_clean_source_file(&format!("{attr}\nfn t() {{}}")).is_some_and(|parse| { parse .tree() .syntax() .descendants() .filter_map(ast::Attr::cast) .any(|attr| attr.simple_name().as_deref() == Some("should_panic")) }) }) { return None; } bounded_matches_panic_owner(probe, test, assertion, index, self) .is_none() .then_some(AssertionRefusal::ExpectedPanicUnresolved) } /// Collection seam consumers share the effect admission, including the /// effect-only live duplicate exception, without inventing a Probe seam. pub(in crate::analysis) fn admits_effect_assertion( &self, test: &TestSummary, assertion: &OracleFact, index: &RustIndex, ) -> bool { self.admits_assertion_family(ProbeFamily::SideEffect, None, test, assertion, index) } /// The family-aware refusal for one assertion, including the #14537 /// gated-`mod` exception. `None` when the family admits it. Shared by the /// admission and its disclosure note so the note names the refusal that /// actually withheld credit. fn assertion_family_refusal( &self, family: ProbeFamily, owner: Option<&FunctionSummary>, test: &TestSummary, assertion: &OracleFact, index: &RustIndex, matches_context: bool, ) -> Option { let refusal = if matches_context { self.context_refusal(test, assertion, index, true) } else { self.refusal(test, assertion, index) }; // #14537: a predicate equality whose test file is composed through a // gated `mod` declaration shares the bare `assert!`'s admission for // that build-availability step only, and only under the #14463 // shared-gate rule: the owner must be reached solely through that same // declaration, so the gate cannot separate the test from the owner. // An owner reachable without the gate (an ungated `lib.rs` item), a // provably-off gate, an include-only context, a shadowed macro, an // uncalled closure or a conditional path still withholds credit // (RIPR-SPEC-0197: an unknown gate grants no credit on its own). if family != ProbeFamily::Predicate { return refusal; } let Some(module_refusal) = refusal .as_ref() .filter(|refusal| matches!(refusal, AssertionRefusal::ModuleDeclaration { .. })) else { return refusal; }; let shared_gate = owner.is_some_and(|owner| { super::refusal_miss::owner_compiled_only_under_refused_declaration( index, owner, test, module_refusal, ) }); // Read the rest of the execution context with only that Module edge // skipped. A refusal that survives the skip is the real reason credit // is withheld (a dead branch, an ignored test, a shadowed macro), so // the disclosure names it rather than the gate. With nothing left to // refuse, the shared gate decides: admitted when the owner is reached // only through the declaration, otherwise the gate itself withholds. let skip = self.module_edge_child_for_test(module_refusal, test, index); let inner = self.context_refusal_without_provenance( test, assertion, index, matches_context, skip.as_deref(), ); if let Some(inner) = inner { // #14537 review: only an unestablished gate lets the rest of the // context speak. When the declaration's gate is not unestablished // (`cfg(any())`, an always-off `cfg_attr`, or a declaration ripr // cannot read), no build compiles that code, so a refusal read // past it is not this assertion's limit - and under RIPR-SPEC-0240 // only a real limit withholds a gap. Keep the declaration. if !self.module_gate_is_unestablished(module_refusal, index) { return refusal; } return Some(Self::refusal_with_value_guard(inner, assertion)); } if shared_gate { return None; } refusal } /// Whether the `mod` declaration behind `refusal` carries a `cfg` ripr /// cannot evaluate (so the shared-gate rule can apply), as opposed to a /// provably-off gate, a declaration it cannot read, or a plain module. /// The gate reader is the syntax layer's, the same one the producer and /// the shared-gate rule use (#14537 review). fn module_gate_is_unestablished(&self, refusal: &AssertionRefusal, index: &RustIndex) -> bool { let Some((parent, line, declaration)) = refusal.module_declaration_site() else { return false; }; index .files() .get(parent) .filter(|facts| !facts.used_lexical_fallback) .and_then(|facts| { crate::analysis::syntax::module_declaration_unestablished_gate( &facts.source, line, declaration, ) }) == Some(true) } fn admits_assertion_family( &self, family: ProbeFamily, owner: Option<&FunctionSummary>, test: &TestSummary, assertion: &OracleFact, index: &RustIndex, ) -> bool { let outer = Self::assertion_macro_name(&assertion.text); let matches_context = matches_return_assertion(&family, assertion); // An oracle whose text is a compound statement (`loop { break; // assert_eq!(..); }`, `'a: { .. }`, a `macro_rules!` body, a // cfg-dropped `let`) names no invocation the admission can identify: // its "macro path" is statement text, so it would skip the gate. An // effect oracle that merely contains an assertion macro takes the same // admission and is refused unless that exact invocation is // established (#8927). // Fail-closed root rule: the oracle is ungated only when its text // STARTS with a recognized assertion invocation (leaf `assert_eq` or // `assert`). Any other leading shape (a different macro, an empty or // non-identifier path, a prefix keyword or expression) is compound and // takes the context gate whenever an assertion macro sits in its tail. let compound = outer .as_deref() .is_none_or(|name| !ADMITTED_ASSERTION_MACROS.contains(&name)); let gated = match outer.as_deref() { _ if compound => { let masked = mask_comments_and_strings(&assertion.text); matches!(family, ProbeFamily::SideEffect | ProbeFamily::CallDeletion) && ADMITTED_ASSERTION_MACROS.iter().any(|name| { whole_word_offsets(&masked, name) .into_iter() .any(|at| masked[at + name.len()..].trim_start().starts_with('!')) }) } Some("assert_eq" | "assert_ne" | "debug_assert_eq" | "debug_assert_ne") => matches!( family, ProbeFamily::ReturnValue | ProbeFamily::FieldConstruction | ProbeFamily::ErrorPath | ProbeFamily::Predicate | ProbeFamily::SideEffect | ProbeFamily::CallDeletion ), Some("assert" | "debug_assert") => { matches!( family, ProbeFamily::ReturnValue | ProbeFamily::MatchArm | ProbeFamily::SideEffect | ProbeFamily::CallDeletion ) || matches_context } _ => false, }; if !gated { return true; } let refusal = self.assertion_family_refusal( family.clone(), owner, test, assertion, index, matches_context, ); match refusal { None => true, // Identical spellings on one line, one of which provably runs // (`A; return; A;`): the effect oracle is that same check, so it // keeps its credit. The return family keeps refusing (#8927). Some(AssertionRefusal::Syntax(AssertionContextRefusal::DuplicateSpellingOneRuns)) => { matches!(family, ProbeFamily::SideEffect | ProbeFamily::CallDeletion) } // #10389: a boolean `assert!` whose operand only nests a known // pure comparison macro (`assert!(approx_eq!(f64, ..))`) is not // shown dead, only unresolved: ripr does not expand third-party // macros. The return family keeps the credit it had before this // gate, because `rust_assertion_context_unestablished` would // demote live rows of the verdict corpus. Any other nested // macro (it may hide a `return`), an operand with an exit token, // a test with any attribute besides `#[test]` (the function-level // macro scan reports first and would hide `TestAttribute`), and // every other refusal still withhold it. Some(AssertionRefusal::Syntax(AssertionContextRefusal::MacroOperandExit(_))) => { family == ProbeFamily::ReturnValue && matches!(outer.as_deref(), Some("assert" | "debug_assert")) && test.attrs.iter().all(|attr| { attr.chars() .filter(|ch| !ch.is_whitespace()) .eq("#[test]".chars()) }) && !operand_holds_exit_token(&assertion.text) && self.nested_macros_are_known_comparisons(&assertion.text, &test.file, index) && self .refusal_trusting_comparison_macros(test, assertion, index) .is_none() } // Field construction: only a real shadow (a definition or import // of the assertion name), a manifest-selected literal MacroUse // export, or an opaque in-scope expansion that mentions it refuses // credit. Other `#[macro_use] extern crate` and foreign-glob sites // retain the operand-whitespace field contracts; an incomplete // export lookup never clears a separately retained/withheld blocker. Some(AssertionRefusal::Syntax(AssertionContextRefusal::MacroBinding(name))) => { family == ProbeFamily::FieldConstruction && self .macro_binding_site(test, assertion.line, &name, index) .is_some() && self .field_blocking_macro_site(test, assertion.line, &name, index) .is_none() } Some(_) => false, } } /// The outer assertion's identity, shared by admission and its refusal note. pub(in crate::analysis) fn assertion_macro_name(text: &str) -> Option { let path = outer_macro_path(text)?; let leaf = drop_in_assertion_leaf(&path).unwrap_or(&path); Some(leaf.strip_prefix("r#").unwrap_or(leaf).to_string()) } /// Why [`Self::admits_equality_assertion`] refused this assertion, for /// disclosure only. `None` when it is admitted. Computed after the /// decision, so it never changes what is credited. pub(in crate::analysis) fn equality_assertion_refusal( &self, probe: &Probe, owner: Option<&FunctionSummary>, test: &TestSummary, assertion: &OracleFact, index: &RustIndex, ) -> Option { if self.admits_equality_assertion(probe, owner, test, assertion, index) { return None; } let matches_context = matches_return_assertion(&probe.family, assertion); let refusal = self .assertion_family_refusal( probe.family.clone(), owner, test, assertion, index, matches_context, ) .or_else(|| self.matches_expected_panic_refusal(probe, test, assertion, index)) .unwrap_or(AssertionRefusal::Syntax( AssertionContextRefusal::UnidentifiedTest, )); Some(match refusal { AssertionRefusal::Syntax(AssertionContextRefusal::MacroBinding(name)) => { let site = if probe.family == ProbeFamily::FieldConstruction { self.field_blocking_macro_site(test, assertion.line, &name, index) .or_else(|| self.macro_binding_site(test, assertion.line, &name, index)) } else { self.macro_binding_site(test, assertion.line, &name, index) }; let roots = self.target_roots(index); let carries = |file: &Path| self.file_may_carry_glob_chain(file, index); let jumps = |file: &Path| self.file_may_skip_glob_parent(file, index); let placement_include = match site.as_ref() { Some((path, site)) if path != &test.file && matches!(&site.kind, MacroBindingKind::ForeignGlob(_)) && placement_include_explains( site, path, &test.file, roots, index, &carries, &jumps, ) => { roots.workspace_include.clone() } _ => None, }; AssertionRefusal::MacroBinding { name, site, placement_include, } } refusal => refusal, }) } /// The binding site behind a `MacroBinding` refusal for `name`: a real /// local rebinding outranks a workspace site that only may rebind it. fn macro_binding_site( &self, test: &TestSummary, assertion_line: usize, name: &str, index: &RustIndex, ) -> Option<(PathBuf, MacroBindingSite)> { let resolved_modules = self.resolved_module_declarations(index); let resolved = |path: &Path, line: usize, declaration: &str| { module_declaration_resolved(resolved_modules, index, path, line, declaration) }; let test_roots = self.target_roots(index).roots(&test.file, index); // #8255: the single ambiguity pass retained the earliest // sites; a lookup completes that pass once when it stopped // early, instead of rescanning the workspace per // (name, test root). let workspace = self .workspace_macro_site_in(name, test_roots.as_ref(), Some(&test.file), index) .or_else(|| self.withheld.sites.get(name).cloned()) .or_else(|| { self.withheld .root_sites .iter() .find_map(|((site_name, root), site)| { (*site_name == name && test_roots.as_ref().is_none_or(|roots| roots.contains(root))) .then(|| site.clone()) }) }); // A definition or `use` covering the test is a real // rebinding; it outranks a workspace site that only may // rebind the name, or the refusal would read as an analyzer // limit (RIPR-SPEC-0240) for a macro that is really replaced. let bytes = SiteCoverBytes::for_assertion(self, index, test, assertion_line); let local = test_macro_binding_site( name, test, assertion_line, index, bytes, &self.test_file_macro_sites, self.target_roots(index), &resolved, ); if local.as_ref().is_some_and(|(_, site)| rebinds(site)) { local } else { workspace.or(local) } } // Unlike disclosure's single selected site, admission must consider every // relevant blocking kind. Withheld scans retain only one site and can stop // early, so any reaching withheld ambiguity cannot establish absence. fn field_blocking_macro_site( &self, test: &TestSummary, assertion_line: usize, name: &str, index: &RustIndex, ) -> Option<(PathBuf, MacroBindingSite)> { let roots = self.target_roots(index).roots(&test.file, index); let resolved_modules = self.resolved_module_declarations(index); let resolved = |path: &Path, line: usize, declaration: &str| { resolved_modules.contains(&(path.to_path_buf(), line, declaration.to_string())) }; self.workspace_macro_site_in_mode(name, roots.as_ref(), Some(&test.file), index, true) .or_else(|| self.withheld.sites.get(name).cloned()) .or_else(|| { self.withheld .root_sites .iter() .find_map(|((site_name, root), site)| { (site_name == name && roots.as_ref().is_none_or(|r| r.contains(root))) .then(|| site.clone()) }) }) .or_else(|| { let facts = index.files().get(&test.file)?; let bytes = SiteCoverBytes::for_assertion(self, index, test, assertion_line); self.test_file_macro_sites .borrow_mut() .entry((name.to_string(), test.file.clone())) .or_insert_with(|| { macro_binding_sites( name, &test.file, &facts.source, facts.macro_candidates.as_deref(), index, self.target_roots(index), &resolved, ) }) .iter() .find(|(_, site)| { site_covers_assertion(site, test, assertion_line, bytes) && field_site_blocks(site) }) .map(|(_, site)| (test.file.clone(), site.clone())) }) } /// #13269: memoized [`source_may_carry_glob_chain`] for an indexed file; /// an unindexed file is read as carrying one. fn file_may_carry_glob_chain(&self, file: &Path, index: &RustIndex) -> bool { if let Some(known) = self.glob_chain_by_file.borrow().get(file) { return *known; } let carries = index .files() .get(file) .is_none_or(|facts| source_may_carry_glob_chain(facts.data().source.as_ref())); self.glob_chain_by_file .borrow_mut() .insert(file.to_path_buf(), carries); carries } fn file_may_skip_glob_parent(&self, file: &Path, index: &RustIndex) -> bool { if let Some(known) = self.glob_jump_by_file.borrow().get(file) { return *known; } let jumps = index .files() .get(file) .is_none_or(|facts| source_may_skip_glob_parent(facts.data().source.as_ref())); self.glob_jump_by_file .borrow_mut() .insert(file.to_path_buf(), jumps); jumps } fn execution_context( &self, file: &PathBuf, index: &RustIndex, ) -> Arc> { self.execution_contexts .get_or_build(file, || index.execution_context(file)) } /// Every out-of-line `mod name;` the module composition resolved to an /// indexed file, keyed by declaring file, line and declaration text. fn resolved_module_declarations( &self, index: &RustIndex, ) -> &BTreeSet<(PathBuf, usize, String)> { self.resolved_modules.get_or_init(|| { index .execution_module_parents .as_ref() .into_iter() .flat_map(|parents| parents.values()) .flatten() .map(|edge| (edge.parent.clone(), edge.line, edge.declaration.clone())) .collect() }) } pub(in crate::analysis) fn admits( &self, test: &TestSummary, assertion: &OracleFact, index: &RustIndex, ) -> bool { self.refusal(test, assertion, index).is_none() } /// The context gates every assertion shares (parser-backed file, /// resolved module composition) with no visible binding that may rebind /// `assert!`, `assert_ne!` or `matches!` on the assertion's line. /// RIPR-SPEC-0231 sibling exclusion credits an `assert_ne!` or /// `assert!(!matches!(..))` only through it. pub(in crate::analysis) fn admits_assertion_context( &self, test: &TestSummary, assertion: &OracleFact, index: &RustIndex, ) -> bool { self.context_ambiguities(test, assertion.line, index, None) .is_ok_and(|ambiguous| { !["assert", "assert_ne", "matches"] .iter() .any(|name| ambiguous.contains(*name)) }) } /// The test-local check helper an `assertion` this admission admits is /// borrowed from (#6482); `None` for the test's own assertion or one it /// refuses. pub(in crate::analysis) fn helper_loan( &self, test: &TestSummary, assertion: &OracleFact, index: &RustIndex, ) -> Option { if !self.admits(test, assertion, index) { return None; } if index.doctest_source(test).is_some() { return self .doctest_pins .borrow() .get(&(test.file.clone(), test.start_line))? .helper_loan( (test.start_line, test.end_line, DOCTEST_FUNCTION_NAME), (assertion.line, &assertion.text), ) .cloned(); } let assertions = self.by_file.borrow().get(&test.file).cloned()?; assertions .helper_loan( (test.start_line, test.end_line, &test.name), (assertion.line, &assertion.text), ) .cloned() } /// Exact call syntax is authority only when the selected source composes /// through admitted module declarations. This shares the assertion gate, /// including its supported test-build cfg rules. pub(in crate::analysis) fn targeted_source_provenance_is_admitted( &self, test: &TestSummary, index: &RustIndex, ) -> bool { if self.source_provenance_refusal(test, index, None).is_some() { return false; } let Some(_facts) = index.files().get(&test.file) else { return false; }; let context = self.execution_context(&test.file, index); let Some(context) = context.as_ref() else { return false; }; context.edges.iter().all(|edge| { let Some(parent) = index.files().get(&edge.parent) else { return false; }; self.module_parent_assertions(&edge.parent, &parent.source, index) .admits_targeted_module_declaration(edge.line, &edge.declaration) }) } /// Call occurrence parsing borrows binding authority only. It does not /// grant assertion execution, oracle strength or receiver identity. pub(in crate::analysis) fn targeted_macro_binding_is_unambiguous( &self, test: &TestSummary, line: usize, name: &str, index: &RustIndex, ) -> bool { self.macro_binding_is_unambiguous(test, line, name, index, false) } /// RIPR-SPEC-0352: the same decision with exactly one input lifted, the /// target-root placement a `std`/`core`-rooted path needs to verify the /// manifests of the crates that compile the file. Every other refusal /// (bare-name ambiguity, scoped and crate-local bindings, the file's own /// manifest, provenance, source-level rebinding of the root or macro, module /// declarations) stays in force. Used only to name a limit; it never credits. pub(in crate::analysis) fn macro_binding_is_unambiguous_if_unplaced( &self, test: &TestSummary, line: usize, name: &str, index: &RustIndex, ) -> bool { self.macro_binding_is_unambiguous(test, line, name, index, true) } fn macro_binding_is_unambiguous( &self, test: &TestSummary, line: usize, name: &str, index: &RustIndex, trust_unplaced_standard_root: bool, ) -> bool { let name = if let Some(leaf) = drop_in_assertion_leaf(name) { let Some((root, _)) = name.strip_prefix("::").unwrap_or(name).split_once("::") else { return false; }; let context = self.execution_context(&test.file, index); let Some(context) = context.as_ref() else { return false; }; let placement = if trust_unplaced_standard_root && matches!(root, "std" | "core") && self.target_roots(index).disabled { Vec::new() } else { let Some(placement) = self.target_roots(index).roots(&test.file, index) else { return false; }; placement.into_iter().collect() }; let verified = std::iter::once(&test.file) .chain(placement.iter()) .all(|file| { if matches!(root, "std" | "core") { matches!( leaf, "assert" | "assert_eq" | "assert_ne" | "debug_assert" | "debug_assert_eq" | "debug_assert_ne" ) && index.drop_in_manifests.unbound_standard_root(file, root) } else { matches!(leaf, "assert_eq" | "assert_ne") && index.drop_in_manifests.verified(file, root) } }); if !verified { return false; } // A qualified root does not borrow a custom bare leaf's ambiguity. return self.targeted_source_provenance_is_admitted(test, index) && std::iter::once(&test.file) .chain(context.edges.iter().map(|e| &e.parent)) .all(|path| { index.files().get(path).is_some_and(|facts| { crate::analysis::syntax::parse_clean_source_file(&facts.source) .is_some_and(|file| { // Cargo identity does not prove the source // root: `use fake as std;` or a module named // `std` re-exporting a non-asserting macro // must not receive the qualified credit. crate::analysis::syntax::ra::assertion_root_is_available( name, file.tree().syntax(), ) && if matches!(root, "std" | "core") { crate::analysis::syntax::ra::std_macro_root_is_unrebound( name, file.tree().syntax(), ) } else { crate::analysis::syntax::ra::assertion_root_binding_is_unrebound( name, file.tree().syntax(), ) } }) }) }) && context.edges.iter().all(|edge| { parse_clean_source_file(&edge.declaration).is_some_and(|file| { file.tree() .syntax() .descendants() .filter_map(ast::Module::cast) .all(|module| { crate::analysis::syntax::ra::assertion_root_is_available( name, module.syntax(), ) }) }) }); } else { if name.contains("::") { return false; } name }; let unplaced = trust_unplaced_standard_root && self.target_roots(index).disabled; let own_package = unplaced .then(|| self.own_package_ambiguities(test, index)) .flatten(); self.targeted_source_provenance_is_admitted(test, index) && !match own_package { // RIPR-SPEC-0352: with placement unavailable, a site in // another package reaches this test only through a file // mounted into its target, which unavailable placement can // neither establish nor rule out; that class is the doubt // this limit names. A site in the test's own package, and // any withheld file, still refuses. Some(names) => { // Populate the scoped and crate-local bindings below. self.trusted_macro_ambiguities(index); names.contains(name) || self.withheld.any_name || self.withheld.trusted.contains(name) } None => self.trusted_macro_ambiguities(index).contains(name), } && !self .scoped_names_for(test, line, index) .iter() .any(|candidate| candidate == name) && !self .crate_names_for(test, index) .iter() .any(|candidate| candidate == name) && !self .module_names_for(test, index) .iter() .any(|candidate| candidate == name) } /// The names the test's own scope makes ambiguous without a scope of /// their own (RIPR-SPEC-0352). The own scope is the test's package, every /// file a resolved `mod` declaration mounts from the scope (a literal /// `#[path]` into another package included) together with the declaring /// parents of the test file, and every package the scope reaches through /// an explicit import edge (`use dep::*`, `use dep::x`, `extern crate dep`). /// `None` when the test's package cannot be named from its path (the caller /// keeps the workspace-wide answer). A file whose package cannot be named /// counts as the test's own. fn own_package_ambiguities( &self, test: &TestSummary, index: &RustIndex, ) -> Option>> { use crate::analysis::workspace::package_root; let package = package_root(&test.file)?; let mut mounted: BTreeSet = BTreeSet::new(); if let Some(context) = self.execution_context(&test.file, index).as_ref() { mounted.extend(context.edges.iter().map(|edge| edge.parent.clone())); } // The scope depends on the test file's declaring parents as well as // its package, so both key the memo. let key = (package.clone(), mounted.iter().cloned().collect::>()); if let Some(names) = self.own_package_macro_ambiguities.borrow().get(&key) { return Some(names.clone()); } let mut packages: BTreeSet = BTreeSet::from([package.clone()]); // Directory name of every package that holds an indexed file, the // crate name a path dependency is imported under. let directories: BTreeMap = index .files() .iter() .filter_map(|(path, _)| package_root(path)) .filter(|root| !root.is_empty()) .map(|root| { let name = root .trim_end_matches('/') .rsplit('/') .next() .unwrap_or_default() .replace('-', "_"); (root, name) }) .collect(); let owned = index.macro_scope_crates(); loop { let in_scope = |path: &Path, packages: &BTreeSet, mounted: &BTreeSet| { mounted.contains(path) || package_root(path).is_none_or(|root| packages.contains(&root)) }; let mut changed = false; if let Some(parents) = index.execution_module_parents.as_ref() { for (child, edges) in parents { if !in_scope(child, &packages, &mounted) && edges .iter() .any(|edge| in_scope(&edge.parent, &packages, &mounted)) { mounted.insert(child.clone()); changed = true; } } } let mut roots = BTreeSet::new(); for (path, facts) in index.files().iter() { if in_scope(path, &packages, &mounted) { imported_crate_roots(facts.data().source.as_ref(), &mut roots); } } // A workspace-owned crate imported under a name no package // directory carries (a renamed dependency) cannot be pinned to // one package, so every package is reached. let reach_all = roots.iter().any(|root| { let matching = directories.values().filter(|name| *name == root).count(); (owned.contains(root) || index.package_names.contains(root)) && matching == 0 || matching > 1 }) || own_scope_manifests_defeat_names(index, &packages, &directories, &roots); for (directory, name) in &directories { if (reach_all || roots.contains(name)) && packages.insert(directory.clone()) { changed = true; } } if !changed { break; } } let files: Vec> = index .files() .iter() .filter(|(path, _)| { mounted.contains(path.as_path()) || package_root(path).is_none_or(|root| packages.contains(&root)) }) .map(|(path, facts)| { let data = facts.data(); (path, data.source.as_ref(), data.macro_candidates.as_deref()) }) .collect(); let resolved_modules = self.resolved_module_declarations(index); let module_resolved = |file: &Path, line: usize, declaration: &str| { resolved_modules.contains(&(file.to_path_buf(), line, declaration.to_string())) }; // Limit naming only (#12886): with placement unavailable, a drop-in // assertion import the test file's own manifest verifies is a // binding to a macro that evaluates its operands. This scan feeds // only the unplaced limit pass; the credit path never reads it. let sites = scan_macro_sites( &files, index, self.target_roots(index), &module_resolved, true, ); let names: BTreeSet = sites .ambiguities .into_iter() .filter(|(_, _, site)| site.scope.is_none()) .map(|(_, name, _)| name) .collect(); let names = Arc::new(names); self.own_package_macro_ambiguities .borrow_mut() .insert(key, names.clone()); Some(names) } fn trusted_macro_ambiguities(&self, index: &RustIndex) -> BTreeSet { let resolved_modules = self.resolved_module_declarations(index); let module_resolved = |file: &Path, line: usize, declaration: &str| { module_declaration_resolved(resolved_modules, index, file, line, declaration) }; let mut ambiguous = self.ambiguous_macro_bindings.borrow_mut(); ambiguous .get_or_insert_with(|| { let (mut global, scoped, by_root, retained) = trusted_macro_sites_in(index, self.target_roots(index), &module_resolved); *self.scoped_macro_bindings.borrow_mut() = Some(scoped); #[cfg(test)] { *self.workspace_scan_passes.borrow_mut() += 1; } let mut by_root = by_root; for (root, names) in &self.withheld.by_root { by_root .entry(root.clone()) .or_default() .extend(names.iter().cloned()); } *self.crate_macro_bindings.borrow_mut() = Some(by_root); *self.workspace_site_scan.borrow_mut() = Some(retained); // Withheld crate-root files' crate-local sites are routed by // root below; every other withheld site is workspace-wide. global.extend(self.withheld.trusted.iter().cloned()); global }) .clone() } /// The workspace-wide site that makes `name` ambiguous for a test /// rooted at `test_root`: the earliest rebinding site in path order, /// else the earliest site that only may rebind it, each over the sites /// that reach the test — the same selection the replaced per-(name, /// test root) scan made, served from the single ambiguity pass (#8255). /// `None` when no retained site reaches the test. #[cfg(test)] fn workspace_macro_site( &self, name: &str, test_root: Option<&Path>, index: &RustIndex, ) -> Option<(PathBuf, MacroBindingSite)> { self.workspace_macro_site_for(name, test_root, test_root, index) } /// [`Self::workspace_macro_site`] for a test whose file is not its root. #[cfg(test)] fn workspace_macro_site_for( &self, name: &str, test_root: Option<&Path>, test_file: Option<&Path>, index: &RustIndex, ) -> Option<(PathBuf, MacroBindingSite)> { let roots = test_root.map(|root| BTreeSet::from([root.to_path_buf()])); self.workspace_macro_site_in(name, roots.as_ref(), test_file, index) } fn workspace_macro_site_in( &self, name: &str, test_roots: Option<&BTreeSet>, test_file: Option<&Path>, index: &RustIndex, ) -> Option<(PathBuf, MacroBindingSite)> { self.workspace_macro_site_in_mode(name, test_roots, test_file, index, false) } fn workspace_macro_site_in_mode( &self, name: &str, test_roots: Option<&BTreeSet>, test_file: Option<&Path>, index: &RustIndex, field_only: bool, ) -> Option<(PathBuf, MacroBindingSite)> { if !assertion_context_macros().contains(&name) { return None; } self.complete_workspace_site_scan(index); let ancestry = test_file.and_then(|file| { let context = self.execution_context(&file.to_path_buf(), index); module_ancestry(&context, file, self.target_roots(index), index) }); let carries = |file: &Path| self.file_may_carry_glob_chain(file, index); let jumps = |file: &Path| self.file_may_skip_glob_parent(file, index); let scan = self.workspace_site_scan.borrow(); let retained = scan.as_ref()?; let mut rebinding: Option<&OrderedMacroSite> = None; let mut may_rebind: Option<&OrderedMacroSite> = None; let mut field_blocking: Option<&OrderedMacroSite> = None; if let Some(rank) = retained.global.get(name) { merge_macro_site_rank(&mut rebinding, &mut may_rebind, rank); keep_earliest_site(&mut field_blocking, rank.field_blocking.as_ref()); } for (root, names) in &retained.by_root { if test_roots.is_none_or(|roots| roots.contains(root)) && let Some(rank) = names.get(name) { merge_macro_site_rank(&mut rebinding, &mut may_rebind, rank); keep_earliest_site(&mut field_blocking, rank.field_blocking.as_ref()); } } for (file, binding) in &retained.by_module { if module_binding_reaches( file, binding, ancestry.as_ref(), test_roots, &carries, &jumps, ) && let Some(rank) = binding.sites.get(name) { merge_macro_site_rank(&mut rebinding, &mut may_rebind, rank); keep_earliest_site(&mut field_blocking, rank.field_blocking.as_ref()); } } let selected = if field_only { field_blocking } else { rebinding.or(may_rebind) }; selected.map(|site| (site.path.clone(), site.site.clone())) } /// #8255: finish the retained-site scan the ambiguity pass skipped. It /// stops once every trusted name is already ambiguous — later files /// cannot change an admission — but an earlier file's site can still be /// the one a refusal names, so the first site lookup completes the pass /// once. At most one full-index completion runs, however many (name, /// test root) lookups follow. fn complete_workspace_site_scan(&self, index: &RustIndex) { if self .workspace_site_scan .borrow() .as_ref() .is_some_and(|scan| scan.complete) { return; } // Runs the single pass when a refusal lookup is its first consumer. self.trusted_macro_ambiguities(index); { let scan = self.workspace_site_scan.borrow(); if scan.as_ref().is_none_or(|scan| scan.complete) { return; } } let resolved_modules = self.resolved_module_declarations(index); let module_resolved = |file: &Path, line: usize, declaration: &str| { module_declaration_resolved(resolved_modules, index, file, line, declaration) }; // #11509: the index-owned scan, shared with every other instance. let sites = index.call_identity_memos.macro_site_scans.scan( ScanPart::Rest, index, self.target_roots(index), &module_resolved, ); // Resolved before the map borrow: target roots never re-enter the // site scan, and the mutable borrow must not outlive its purpose. let roots = self.target_roots(index); let mut scan = self.workspace_site_scan.borrow_mut(); let Some(retained) = scan.as_mut() else { return; }; if retained.complete { return; } retain_macro_sites(&sites.retained, retained, roots, index); retained.complete = true; #[cfg(test)] { *self.workspace_scan_passes.borrow_mut() += 1; } } /// Every `matches` binding site in the workspace, including opaque /// imports that never spell the name, in index path order. Memoized per /// index (#13754), so every owner-pin syntax instance over one index /// shares one scan. It stays lazy: priming it before the probes cost a /// large diff that never reaches this check more than it saved. fn matches_binding_sites(index: &RustIndex) -> &[(PathBuf, MacroBindingSite)] { index .call_identity_memos .matches_binding_sites .get_or_init(|| { let files: Vec<(&PathBuf, crate::analysis::rust_index::FileFactsView<'_>)> = index.files().iter().collect(); map_scans(&files, |(file, facts)| { // The stored candidates over-approximate every context's // sites, so a file that cannot bind `matches` reports // none and is not parsed (#5363). A file without stored // candidates is always scanned. if facts .macro_candidates .as_deref() .is_some_and(|candidates| !candidates.may_bind("matches")) { return Vec::new(); } trusted_macro_binding_sites( &facts.source, index.macro_scope_crates(), &assertion_context_macros(), &|_, _| false, &|_| false, ) .into_iter() .filter(|(name, _)| name == "matches") .map(|(_, site)| ((*file).clone(), site)) .collect::>() }) .into_iter() .flatten() .collect() }) } /// The per-file `matches` argument verdict, memoized by test file. The /// workspace site scan is resolved before the memo lock is taken, so a /// worker that pays it does not hold every sibling on that lock (#13754). fn matches_arguments_clear_for( &self, test: &TestSummary, index: &RustIndex, clear: impl FnOnce(&[(PathBuf, MacroBindingSite)]) -> bool, ) -> bool { let sites = Self::matches_binding_sites(index); *self .matches_arguments_clear .borrow_mut() .entry(test.file.clone()) .or_insert_with(|| clear(sites)) } /// #9211: pay the whole workspace macro-site scan once, before the /// classify workers start. The first consumer otherwise runs it in line on /// one worker while holding the memo lock, and every sibling worker sleeps /// on that lock until the whole corpus is parsed. Called on a thread of /// the classify pool before any probe is queued, so the scan fans out over /// that pool (the large-stack workers the parse needs) and the probes only /// read the filled memos. The memo content is what the first consumer /// would have produced, so no output changes. pub(in crate::analysis) fn prime_workspace_macro_scan(&self, index: &RustIndex) { let _fan_out = PrimedScanFanOut::enter(); self.complete_workspace_site_scan(index); } /// #8255 test witness: how many full-index macro-site passes this run /// paid, bounded at two (the ambiguity pass plus at most one /// completion) however many (name, test root) refusals follow. #[cfg(test)] pub(in crate::analysis) fn workspace_scan_passes(&self) -> u32 { *self.workspace_scan_passes.borrow() } /// File composition authority shared by assertion admission and targeted /// assertion operands. Syntax in an included or unadmitted module cannot /// borrow a standard macro binding from an incomplete scope view. fn source_provenance_refusal( &self, test: &TestSummary, index: &RustIndex, skip_module_child: Option<&Path>, ) -> Option { let Some(facts) = index .files() .get(&test.file) .filter(|facts| !facts.used_lexical_fallback) else { return Some(AssertionRefusal::LexicalFallback); }; if let Some(reason) = &facts.role_provenance.earliest_unresolved_reason { return Some(AssertionRefusal::UnresolvedModule(reason.clone())); } let context = self.execution_context(&test.file, index); let edges = context .as_ref() .as_ref() .map_or(&facts.role_provenance.edges, |context| &context.edges); for edge in edges { // #14537: a caller that has already accounted for the gated `mod` // that composes the test file skips only that Module edge, so an // Include edge further up the chain is still evaluated. if edge.kind == SourceRoleProvenanceEdgeKind::Module && skip_module_child.is_some_and(|child| edge.child == child) { continue; } // Module composition already owns resolution. Include expansions // lack an exact declaration coordinate here, so remain unknown. if edge.kind != SourceRoleProvenanceEdgeKind::Module { return Some(AssertionRefusal::IncludedFile { parent: edge.parent.clone(), line: edge.line, }); } let Some(parent) = index .files() .get(&edge.parent) .filter(|facts| !facts.used_lexical_fallback) else { return Some(AssertionRefusal::LexicalFallback); }; if !self .module_parent_assertions(&edge.parent, &parent.source, index) .admits_module_declaration(edge.line, &edge.declaration) { return Some(AssertionRefusal::ModuleDeclaration { parent: edge.parent.clone(), line: edge.line, declaration: edge.declaration.clone(), }); } } if context.as_ref().is_none() { return Some(AssertionRefusal::UnresolvedModule( "rust_module_context_unavailable".into(), )); } None } /// A module-parent file's declaration admissions, read once per run with /// the plain trusted-macro list (see `module_parents`) and the default /// features of the parent's own package, so a declaration gate those /// features settle on admits its module (#14116). fn module_parent_assertions( &self, file: &PathBuf, source: &str, index: &RustIndex, ) -> Arc { self.module_parents.get_or_build(file, || { owner_pin_assertions_with_default_features( source, NON_RETURNING_MACROS, false, index.member_crates.default_test_features(file).as_ref(), ) }) } /// The gates every assertion of `test` shares, whatever its macro: a /// parser-backed file, resolved module composition, and each module /// declaration on the chain admitted. `Ok` holds the macro names some /// visible binding may rebind for an assertion on `line`. fn context_ambiguities( &self, test: &TestSummary, line: usize, index: &RustIndex, skip_module_child: Option<&Path>, ) -> Result, Box> { if let Some(refusal) = self.source_provenance_refusal(test, index, skip_module_child) { return Err(Box::new(refusal)); } if index.proptest_source(test).is_some() { // These ordinary assertion spellings are a checked interpretation // of $crate-bound property assertions, not caller macro imports. return Ok(BTreeSet::new()); } let resolved_modules = self.resolved_module_declarations(index); let module_resolved = |file: &Path, line: usize, declaration: &str| { module_declaration_resolved(resolved_modules, index, file, line, declaration) }; let ambiguous = self.trusted_macro_ambiguities(index); let Some(facts) = index .files() .get(&test.file) .filter(|facts| !facts.used_lexical_fallback) else { return Err(Box::new(AssertionRefusal::LexicalFallback)); }; let empty_ambiguities = self.empty_macro_ambiguities.get_or_build(&test.file, || { let names = local_empty_macro_names(&facts.source); if names.is_empty() { return BTreeSet::new(); } index .files() .iter() .flat_map(|(path, file)| { empty_macro_binding_ambiguities( &file.source, index.macro_scope_crates(), &names, path == &test.file, &|line, declaration| module_resolved(path, line, declaration), ) }) .chain( (self.withheld.any_name || self.withheld.root_any_name) .then(|| names.clone()) .into_iter() .flatten(), ) .collect() }); let mut ambiguous: BTreeSet<_> = ambiguous.union(&empty_ambiguities).cloned().collect(); // Recheck provenance for every admission even when syntax is memoized. if facts.source.contains("json") && !macro_root_verified_in_contexts( &test.file, "serde_json", index, self.target_roots(index), ) { ambiguous.insert("json".to_string()); } ambiguous.extend(self.scoped_names_for(test, line, index)); ambiguous.extend(self.crate_names_for(test, index)); ambiguous.extend(self.module_names_for(test, index)); Ok(ambiguous) } /// RIPR-SPEC-0229 (#6616): the value operand of `assertion` when it is /// an exact pattern pin through the test file's verified local /// `assert_matches!` (see `syntax::pattern_pins`), under the gates every /// assertion of the test shares and with no visible rebinding of a /// standard macro the pin relies on. `None` refuses. pub(in crate::analysis) fn exact_pattern_pin_value( &self, test: &TestSummary, assertion: &OracleFact, index: &RustIndex, ) -> Option { if !assertion.text.starts_with("assert_matches") { return None; } let facts = index.files().get(&test.file)?; // Look the cached pin up first; the ambiguity scan only matters when // a pin exists. The memo borrow ends before that scan runs. let pin = { let mut memo = self.pattern_pins.borrow_mut(); let pins = memo .entry(test.file.clone()) .or_insert_with(|| pattern_pins(&facts.source)); pins.pin( (test.start_line, test.end_line, &test.name), &test.body, (assertion.line, &assertion.text), )? .clone() }; let ambiguous = self .context_ambiguities(test, assertion.line, index, None) .ok()?; pin.macros.is_disjoint(&ambiguous).then_some(pin.value) } /// Whether every macro nested in the boolean assertion `text` is one of /// [`KNOWN_COMPARISON_MACROS`], imported by name from its crate in the /// test file and not defined by a `macro_rules!` anywhere in the index. A /// nested path-qualified, glob-imported or locally defined macro may hide /// an exit. The import and definition scans run once per file and index. fn nested_macros_are_known_comparisons( &self, text: &str, test_file: &Path, index: &RustIndex, ) -> bool { let masked = mask_comments_and_strings(text); let mut names = Vec::new(); for (at, _) in masked.match_indices('!') { let after = masked[at + 1..].trim_start(); if !after.starts_with(['(', '[', '{']) { continue; } let before = masked[..at].trim_end(); let start = before .char_indices() .rev() .find(|&(_, ch)| !(ch.is_ascii_alphanumeric() || ch == '_' || !ch.is_ascii())) .map_or(0, |(last, ch)| last + ch.len_utf8()); let name = &before[start..]; // A `!` with no identifier before it negates a parenthesized // expression; it is not a macro invocation. if name.is_empty() { continue; } if before[..start].ends_with("::") { return false; } names.push(name); } // The outer assertion is the first invocation; the rest are nested. let Some((_, nested)) = names.split_first() else { return false; }; let Some(file) = index.files().get(test_file) else { return false; }; let imported = self .comparison_imports .get_or_build(&test_file.to_path_buf(), || { imported_comparison_macros(&file.source) }); let mut defined = self.macro_rules_names.borrow_mut(); let defined = defined.get_or_insert_with(|| macro_rules_names(index)); nested .iter() .all(|name| imported.contains(name) && !defined.contains(*name)) } /// The file-text verdict for `assertion` with the known nested comparison /// macros read as plain, so the function-level `MacroOperandExit` does not /// hide a dead context (`return`, `loop {}`, an uncalled `fn`, `if /// cfg!(any())`) the per-assertion gates would refuse (#10389). Anything /// not read from the file's own text (doc examples, generated tests) /// refuses. fn refusal_trusting_comparison_macros( &self, test: &TestSummary, assertion: &OracleFact, index: &RustIndex, ) -> Option { if index.doctest_source(test).is_some() { return Some(AssertionContextRefusal::UnidentifiedTest); } let Some(facts) = index.files().get(&test.file) else { return Some(AssertionContextRefusal::UnidentifiedTest); }; let Ok(ambiguous) = self.context_ambiguities(test, assertion.line, index, None) else { return Some(AssertionContextRefusal::UnidentifiedTest); }; self.by_file .get_or_build(&test.file, || { owner_pin_assertions_with_default_features( &expanded_assertion_view(&facts.source, facts.tests.iter()), &assertion_context_macros(), false, index .member_crates .default_test_features(&test.file) .as_ref(), ) }) .refusal_trusting_comparison_macros( (test.start_line, test.end_line, &test.name), &test.body, (assertion.line, &assertion.text), &ambiguous, ) } fn refusal_with_value_guard( refusal: AssertionRefusal, assertion: &OracleFact, ) -> AssertionRefusal { match refusal { AssertionRefusal::Syntax(AssertionContextRefusal::GuardedReturn(condition)) => { match value_guard_subject(&condition, &assertion.text) { Some(subject) => AssertionRefusal::ValueGuard { condition, subject: subject.to_string(), }, None => { AssertionRefusal::Syntax(AssertionContextRefusal::GuardedReturn(condition)) } } } refusal => refusal, } } fn refusal( &self, test: &TestSummary, assertion: &OracleFact, index: &RustIndex, ) -> Option { Some(Self::refusal_with_value_guard( self.context_refusal(test, assertion, index, false)?, assertion, )) } fn context_refusal( &self, test: &TestSummary, assertion: &OracleFact, index: &RustIndex, matches_context: bool, ) -> Option { self.context_refusal_inner(test, assertion, index, matches_context, None) } /// [`Self::context_refusal`] with only the Module edge that composes the /// test file skipped, so a caller that has already accounted for that /// build-availability step can read the rest of the execution context /// (#14537). An Include edge further up the chain is still evaluated. fn context_refusal_without_provenance( &self, test: &TestSummary, assertion: &OracleFact, index: &RustIndex, matches_context: bool, skip_module_child: Option<&Path>, ) -> Option { self.context_refusal_inner(test, assertion, index, matches_context, skip_module_child) } /// The Module edge child to skip for a predicate equality whose test file /// is composed through a gated `mod`. The edge is the refused declaration, /// so a test in an ungated child module of that `mod` /// (`lib.rs: mod python;`, `src/python.rs: mod tests;`) skips /// `src/python.rs` rather than the inner declaration (#14537 review). An /// include fragment keeps its parent, and anything unreadable falls back to /// the test file. The Include edge further up the chain is left in place, /// so an include fragment still refuses as `IncludedFile` (#14537). fn module_edge_child_for_test( &self, refusal: &AssertionRefusal, test: &TestSummary, index: &RustIndex, ) -> Option { let facts = index.files().get(&test.file)?; let context = self.execution_context(&test.file, index); let edges = context .as_ref() .as_ref() .map_or(&facts.role_provenance.edges, |context| &context.edges); if let Some((parent, line, declaration)) = refusal.module_declaration_site() && let Some(edge) = edges.iter().find(|edge| { edge.kind == SourceRoleProvenanceEdgeKind::Module && edge.parent == parent && edge.line == line && edge.declaration == declaration }) { return Some(edge.child.clone()); } edges .iter() .find(|edge| { edge.kind == SourceRoleProvenanceEdgeKind::Include && edge.child == test.file }) .map(|edge| edge.parent.clone()) .or_else(|| Some(test.file.clone())) } fn context_refusal_inner( &self, test: &TestSummary, assertion: &OracleFact, index: &RustIndex, matches_context: bool, skip_module_child: Option<&Path>, ) -> Option { if let Some((source, offset)) = index.proptest_source(test) { if let Some(refusal) = self.source_provenance_refusal(test, index, skip_module_child) { return Some(refusal); } let (Some(start), Some(end), Some(line)) = ( test.start_line.checked_sub(offset), test.end_line.checked_sub(offset), assertion.line.checked_sub(offset), ) else { return Some(AssertionRefusal::Syntax( AssertionContextRefusal::UnidentifiedTest, )); }; return self .proptest_pins .borrow_mut() .entry((test.file.clone(), test.start_line)) .or_insert_with(|| owner_pin_assertions(source, &assertion_context_macros())) .refusal( (start, end, &test.name), &test.body, (line, &assertion.text), &BTreeSet::new(), ) .map(AssertionRefusal::Syntax); } let mut ambiguous = match self.context_ambiguities(test, assertion.line, index, skip_module_child) { Ok(ambiguous) => ambiguous, Err(refusal) => return Some(*refusal), }; let Some(facts) = index.files().get(&test.file) else { return Some(AssertionRefusal::LexicalFallback); }; // #6648 (RIPR-SPEC-0279): a doc example is its own crate, so its // assertions are read from its synthetic source under the synthetic // name, never from the file that holds the comment. if let Some(source) = index.doctest_source(test) { return self.doctest_refusal(test, assertion, source, ambiguous, index); } // #7857: a `std`/`core`-rooted `assert_eq!` needs the same root proof // as targeted call syntax (manifest, crate provenance) plus the // test's real file, which a generated test's expansion does not show. // The escape scan admits every such call in the file's tests and // helpers on file-local evidence, so each one anywhere in the file // needs the proof, not only the credited assertion: an unproved // `std::assert_eq!` may expand to an early return that skips it. let rooted = self .std_rooted .get_or_build(&test.file, || StdRootedCalls::of(&facts.source)); let mut qualified: BTreeSet = ADMITTED_ASSERTION_MACROS .iter() .filter_map(|name| std_rooted_macro_path(&assertion.text, name)) .chain(rooted.calls.iter().cloned()) .collect(); if matches_context { qualified.extend(rooted.matches_calls.iter().filter_map(|path| { path.strip_suffix("matches") .map(|root| format!("{root}assert")) })); } if let Some(path) = qualified.into_iter().find(|path| { !(rooted.is_unrebound(path, &facts.source) && self.targeted_macro_binding_is_unambiguous(test, assertion.line, path, index)) }) { return Some(AssertionRefusal::Syntax( AssertionContextRefusal::OpaqueMacro(path), )); } if matches_context && ambiguous.contains("matches") { let withheld = &self.withheld; let clear = !withheld.any_name && !withheld.root_any_name && !withheld.trusted.contains("matches") && !withheld.sites.contains_key("matches") && !withheld .by_root .values() .any(|names| names.contains("matches")) && !withheld .root_sites .keys() .any(|(name, _)| name == "matches") && self.matches_arguments_clear_for(test, index, |sites| { // Check every site, not only the earliest disclosure site: // a later definition must not hide behind std::assert!. sites.iter().all(|(file, site)| { let MacroBindingKind::MacroArgument(path) = &site.kind else { return false; }; let path: String = path.split_whitespace().collect(); file == &test.file && STD_ROOTED_ASSERT_EQ.contains(&path.as_str()) && rooted.is_unrebound(&path, &facts.source) && self.targeted_macro_binding_is_unambiguous( test, assertion.line, &path, index, ) }) }); if clear { ambiguous.remove("matches"); } } // A terminal Err-return guard is keyed by its condition; the oracle // text may join continuation lines or elide the Err payload. let guard_key = err_return_guard_twin(&assertion.text) .map(|(condition, _)| err_return_guard_key(condition)); let admissions = if matches_context { &self.matches_by_file } else { &self.by_file }; let file_refusal = admissions .get_or_build(&test.file, || { // A gate the package's default features switch on is // compiled by a plain `cargo test`, so it does not refuse // (#8780). owner_pin_assertions_with_default_features( &expanded_assertion_view(&facts.source, facts.tests.iter()), &assertion_context_macros(), matches_context, index .member_crates .default_test_features(&test.file) .as_ref(), ) }) .refusal( (test.start_line, test.end_line, &test.name), &test.body, ( assertion.line, guard_key.as_deref().unwrap_or(&assertion.text), ), &ambiguous, ); let file_refusal = file_refusal?; // A generated test is not in the file's text: the same admission // runs over its invocation's expansion, matched by name, attributes, // body and assertion text in the expansion's own coordinates. A // matched assertion carries the expansion's own verdict — admitted // reads like the hand-written twin, and a refusal surfaces the // expansion's reason, not the file text's "test not identified" // (the invocation line holds no `fn`), so both twins refuse as the // same kind. let generated_verdicts = self .generated .borrow_mut() .entry(test.file.clone()) .or_insert_with(|| { let imported = self .macro_visibility .get_or_init(|| { crate::analysis::facts::macro_visibility::MacroVisibility::new( index .files() .iter() .map(|(path, file)| (path.clone(), file.source.clone())), ) }) .imported_macros(&test.file); generated_test_pins(&test.file, &facts.source, &imported, NON_RETURNING_MACROS) }) .iter() .filter(|invocation| { invocation.start_line == test.start_line && invocation.end_line == test.end_line }) .flat_map(|invocation| { invocation .tests .iter() .filter(|local| { local.name == test.name && local.attrs == test.attrs && local.body == test.body }) .map(move |local| (invocation, local)) }) .flat_map(|(invocation, local)| { local .assertions .iter() .filter(|local_assertion| local_assertion.text == assertion.text) .map(|local_assertion| { invocation.pins.refusal( (local.start_line, local.end_line, &local.name), &local.body, (local_assertion.line, &local_assertion.text), &ambiguous, ) }) }) .collect::>(); if !generated_verdicts.is_empty() { // #6749: a generated test's module is not in the file's text, so // its expansion cannot show a rebound `test`; the file answers. if admissions .borrow() .get(&test.file) .is_some_and(|assertions| assertions.file_binds_test()) { return Some(AssertionRefusal::Syntax( AssertionContextRefusal::TestRebound, )); } } if generated_verdicts.iter().any(|verdict| verdict.is_none()) { return None; } if let Some(Some(generated_refusal)) = generated_verdicts.into_iter().next() { return Some(AssertionRefusal::Syntax(generated_refusal)); } Some(AssertionRefusal::Syntax(file_refusal)) } } impl OwnerPinSyntax { /// #6648 (RIPR-SPEC-0279): the shared admission over a doc example's /// synthetic source. `ambiguous` already holds what the workspace and /// the holding file may rebind (conservative: that file's items are not /// in the example's scope, but its exported macros may be). The /// example's own bindings are added on top; no module of it resolves /// and no drop-in crate is verified for it, so each stays broad. A /// `std::`/`core::`-rooted `assert_eq!` needs root proof this path does /// not establish for the example's crate, so it refuses. fn doctest_refusal( &self, test: &TestSummary, assertion: &OracleFact, source: &str, mut ambiguous: BTreeSet, index: &RustIndex, ) -> Option { let context_macros = assertion_context_macros(); ambiguous.extend( trusted_macro_binding_sites( source, index.macro_scope_crates(), &context_macros, &|_, _| false, &|_| false, ) .into_iter() .map(|(name, _)| name), ); if let Some(path) = ADMITTED_ASSERTION_MACROS .iter() .find_map(|name| std_rooted_macro_path(&assertion.text, name)) .or_else(|| StdRootedCalls::of(source).calls.into_iter().next()) { return Some(AssertionRefusal::Syntax( AssertionContextRefusal::OpaqueMacro(path), )); } let guard_key = err_return_guard_twin(&assertion.text) .map(|(condition, _)| err_return_guard_key(condition)); self.doctest_pins .borrow_mut() .entry((test.file.clone(), test.start_line)) .or_insert_with(|| owner_pin_assertions(source, &context_macros)) .refusal( (test.start_line, test.end_line, DOCTEST_FUNCTION_NAME), &test.body, ( assertion.line, guard_key.as_deref().unwrap_or(&assertion.text), ), &ambiguous, ) .map(AssertionRefusal::Syntax) } } type ScopedMacroBindings = BTreeMap>; type CrateMacroBindings = BTreeMap>; /// Keyed by trusted name and the test's recognized root. type TestFileMacroSites = BTreeMap<(String, PathBuf), Vec<(String, MacroBindingSite)>>; /// The earliest unscoped workspace-wide binding sites per trusted name, /// retained by the single ambiguity pass (`trusted_macro_sites_in`) so a /// refusal names its site without rescanning the workspace (#8255). A /// crate-local site reaches only tests whose recognized root matches the /// site's; every other retained site reaches all of them, exactly the /// reach rule the replaced per-(name, root) scan applied. #[derive(Clone, Debug, Default)] struct WorkspaceMacroSiteIndex { /// Per name: the earliest sites over the files that reach every test. global: BTreeMap, /// Per recognized root: the same retention over that root's /// crate-local sites; a test consults only its own root. by_root: BTreeMap>, /// Private file-level foreign globs, per declaring file, whose module /// ancestry is established: they reach only that file's own tests and /// the tests of modules declared beneath it. by_module: BTreeMap, /// Whether every indexed file contributed. The ambiguity pass stops /// after the likely files once every trusted name is already ambiguous /// — later files cannot change an admission, but an earlier file's /// site can still be the one a refusal names — so the first site /// lookup completes the pass once, bounded by the index (#8255). complete: bool, } /// What one file's private file-level foreign globs bind (a `use` without /// visibility is visible in its module and the modules declared beneath it). #[derive(Clone, Debug, Default)] struct ModuleLocalBinding { /// The crate roots the file routes to as a crate-local site, or `None` /// for every test. Used only for a test whose own ancestry is unknown, /// which then reads the site exactly as it did before confinement. roots: Option>, /// Trusted names the file's globs may rebind. names: BTreeSet, /// The earliest sites per trusted name, for refusal disclosure. sites: BTreeMap, } /// Whether a module-local binding in `file` reaches a test. With the test's /// module ancestry the declaring file must be the test's file or an ancestor. /// A private `use` is not inherited by a child module, but qualified globs /// can skip intermediate modules. Such imports, macro expansion and unknown /// syntax retain the refusal; otherwise follow possible single-parent chains. /// Without the ancestry the binding keeps its crate-local /// reach: every test of its crate roots, or every test when unrooted. /// Whether a private file-level foreign glob declared in `glob_file` reaches /// the test through module edges alone, i.e. with placement established. /// A private `use` is not inherited by a child module, but a qualified glob, /// macro expansion or unknown syntax can hide that chain. fn glob_reaches_through_modules( glob_file: &Path, ancestry: &ModuleAncestry, carries: &dyn Fn(&Path) -> bool, jumps: &dyn Fn(&Path) -> bool, ) -> bool { ancestry.files.contains(glob_file) && (glob_file == ancestry.test_file || ancestry .files .iter() .any(|child| child != glob_file && jumps(child)) || glob_chain_reaches(glob_file, ancestry, carries)) } fn module_binding_reaches( file: &Path, binding: &ModuleLocalBinding, ancestry: Option<&ModuleAncestry>, test_roots: Option<&BTreeSet>, carries: &dyn Fn(&Path) -> bool, jumps: &dyn Fn(&Path) -> bool, ) -> bool { match ancestry { Some(ancestry) => glob_reaches_through_modules(file, ancestry, carries, jumps), None => match (test_roots, binding.roots.as_ref()) { (Some(test), Some(site)) => !test.is_disjoint(site), _ => true, }, } } /// Whether some path of module edges leads from the glob's file down to the /// test's file with every file entered after the glob's own possibly carrying /// a glob. A file ripr cannot establish is read as carrying one. fn glob_chain_reaches( glob_file: &Path, ancestry: &ModuleAncestry, carries: &dyn Fn(&Path) -> bool, ) -> bool { let mut seen: BTreeSet<&Path> = BTreeSet::from([glob_file]); let mut frontier = vec![glob_file]; while let Some(parent) = frontier.pop() { for (edge_parent, child) in &ancestry.edges { if edge_parent != parent || seen.contains(child.as_path()) || !carries(child) { continue; } if child == &ancestry.test_file { return true; } seen.insert(child); frontier.push(child); } } false } /// Whether a file may import an ancestor module's private glob into its own /// modules (#13269): it holds a glob `use` anywhere, or an item-position macro /// call whose expansion could emit one, or it does not parse cleanly. A file /// with none cannot name the parent's glob-imported items, so the parent's /// glob stops there. fn source_may_carry_glob_chain(source: &str) -> bool { let Some(parse) = parse_clean_source_file(source) else { return true; }; parse.tree().syntax().descendants().any(|node| { if let Some(tree) = ast::UseTree::cast(node.clone()) { return tree.star_token().is_some(); } ast::MacroCall::can_cast(node.kind()) && node.parent().is_some_and(|parent| { ast::SourceFile::can_cast(parent.kind()) || ast::ItemList::can_cast(parent.kind()) }) }) } /// A qualified glob can jump over a file edge, and macro expansion or a broken /// parse can hide one. Only a plain single-parent glob is known not to jump; /// unknown attributes and other forms deliberately over-refuse. fn source_may_skip_glob_parent(source: &str) -> bool { const BUILTIN_DERIVES: &[&str] = &[ "Clone", "Copy", "Debug", "Default", "PartialEq", "Eq", "PartialOrd", "Ord", "Hash", ]; let Some(parse) = parse_clean_source_file(source) else { return true; }; parse.tree().syntax().descendants().any(|node| { if let Some(attr) = ast::Attr::cast(node.clone()) { let compact: String = attr .syntax() .text() .to_string() .chars() .filter(|ch| !ch.is_whitespace()) .collect(); let builtin_derive = compact .strip_prefix("#[derive(") .and_then(|value| value.strip_suffix(")]")) .is_some_and(|names| names.split(',').all(|name| BUILTIN_DERIVES.contains(&name))); let inert = compact == "#[test]" || builtin_derive || compact.starts_with("///") || compact.starts_with("//!") || compact.starts_with("#[doc=") || ["cfg", "allow", "warn", "deny", "forbid"] .iter() .any(|name| { compact.starts_with(&format!("#[{name}(")) && compact.ends_with(")]") }); if !inert { return true; } } if let Some(item) = ast::Use::cast(node.clone()) { let text = item.syntax().text().to_string(); // A named assertion import can reach a child file outside the // declaring file's scoped lookup. An imported `test` can also // shadow the built-in attribute and expand to a glob. if text.contains("test") || BUILTIN_DERIVES.iter().any(|name| text.contains(*name)) || assertion_context_macros() .iter() .any(|name| text.contains(*name)) { return true; } let has_glob = item .syntax() .descendants() .filter_map(ast::UseTree::cast) .any(|tree| tree.star_token().is_some()); if has_glob { let compact: String = text.chars().filter(|ch| !ch.is_whitespace()).collect(); return compact != "usesuper::*;"; } } ast::MacroCall::can_cast(node.kind()) && node.parent().is_some_and(|parent| { ast::SourceFile::can_cast(parent.kind()) || ast::ItemList::can_cast(parent.kind()) }) }) } /// A test file's established module ancestry: the files whose module subtree /// holds it, with the module edges that compose them. struct ModuleAncestry { files: BTreeSet, edges: Vec<(PathBuf, PathBuf)>, test_file: PathBuf, } /// Whether a site can be confined to its file's module subtree: a private /// file-level glob in a file with established module composition (no /// `include!` fragment among its ancestors, nothing unresolved workspace-wide /// that could mount a module through an unrecorded edge) inside a recognized /// crate, whose out-of-line modules the producer saw resolve. fn module_confined( site: &MacroBindingSite, path: &Path, roots: &TargetRoots, index: &RustIndex, ) -> bool { site.module_local && site.crate_local && site.scope.is_none() && !roots.disabled && index.execution_context(path).is_some() // An unplaced file may be compiled into any crate (see `roots`), so // only a file inside a recognized crate is confined to its subtree. && roots.roots(path, index).is_some() } /// Whether an include is the only reason this site is not module-confined: /// every input [`module_confined`] checks holds except `!roots.disabled`, the /// scan is disabled by the include alone, and the glob would not reach the /// test even with placement on. A public glob (not `crate_local`) is /// unconfined by construction and a scoped import is confined lexically, so /// for those the include is not the cause; the same holds for a file no /// recognized crate places, one whose own out-of-line modules did not /// resolve, one whose ambiguity has another disabling cause, and a glob that /// reaches the assertion through module edges anyway. Naming the include /// there would repeat the unrelated-cause defect this disclosure exists to /// remove. fn placement_include_explains( site: &MacroBindingSite, path: &Path, test_file: &Path, roots: &TargetRoots, index: &RustIndex, carries: &dyn Fn(&Path) -> bool, jumps: &dyn Fn(&Path) -> bool, ) -> bool { site.crate_local && site.module_local && site.scope.is_none() && roots.disabled && index.execution_context(path).is_some() // What `roots` would answer with placement on: the file is in a // recognized crate that the include does not taint, so the disabled // scan is the only reason this glob is not confined. && target_context_roots(path, index, &roots.src_dirs) .is_some_and(|placed| placed.is_disjoint(&roots.tainted)) // The include must be the whole reason placement is off: a lexical // fallback, unknown `#[path]` or unseen member elsewhere keeps it off // after the include is removed. && !roots.non_include_disabled // And the glob must be ambiguous only because placement is off. With // placement on it is confined to the test's module subtree, so it // would still refuse if it reaches the assertion from an ancestor // module or along the module chain. && { let test_context = index.execution_context(test_file); placed_module_ancestry(&test_context, test_file, roots, index).is_some_and(|ancestry| { !glob_reaches_through_modules(path, &ancestry, carries, jumps) }) } } /// The files whose module subtree holds `file`: itself and every ancestor /// along the approved `mod` edges. `None` when ancestry is not established /// (an unresolved composition anywhere, an `include!` fragment, a file with /// no execution context). fn module_ancestry( context: &Option, file: &Path, roots: &TargetRoots, index: &RustIndex, ) -> Option { // A file no recognized target places may be compiled under any module the // indexer never recorded (a `mod` inside a macro body), so its context of // just itself is not an established ancestry. if roots.disabled || roots.roots(file, index).is_none() { return None; } let context = context.as_ref()?; if context .edges .iter() .any(|edge| edge.kind != SourceRoleProvenanceEdgeKind::Module) { return None; } let mut ancestors: BTreeSet = context.roots.clone(); ancestors.insert(file.to_path_buf()); for edge in &context.edges { ancestors.insert(edge.parent.clone()); ancestors.insert(edge.child.clone()); } Some(ModuleAncestry { files: ancestors, edges: context .edges .iter() .map(|edge| (edge.parent.clone(), edge.child.clone())) .collect(), test_file: file.to_path_buf(), }) } /// The ancestry `file` would have with placement available: its module /// composition resolved and its recognized root clear of every include the /// scan cannot place. `None` when placement would still be unavailable. fn placed_module_ancestry( context: &Option, file: &Path, roots: &TargetRoots, index: &RustIndex, ) -> Option { let context = context.as_ref()?; if context .edges .iter() .any(|edge| edge.kind != SourceRoleProvenanceEdgeKind::Module) { return None; } if !target_context_roots(file, index, &roots.src_dirs) .is_some_and(|placed| placed.is_disjoint(&roots.tainted)) { return None; } let mut ancestors: BTreeSet = context.roots.clone(); ancestors.insert(file.to_path_buf()); for edge in &context.edges { ancestors.insert(edge.parent.clone()); ancestors.insert(edge.child.clone()); } Some(ModuleAncestry { files: ancestors, edges: context .edges .iter() .map(|edge| (edge.parent.clone(), edge.child.clone())) .collect(), test_file: file.to_path_buf(), }) } /// The earliest rebinding site, else the earliest site that only may /// rebind the name: the replaced per-(name, root) scan answered the first /// rebinding in path order, wherever it sits, else the first may-rebind /// site. #[derive(Clone, Debug, Default)] struct MacroSiteRank { rebinding: Option, may_rebind: Option, field_blocking: Option, } /// Producer position, rather than line number, preserves same-line order /// when global and crate-local buckets are merged. #[derive(Clone, Debug)] struct OrderedMacroSite { path: PathBuf, position: usize, site: MacroBindingSite, } impl OrderedMacroSite { fn precedes(&self, other: &Self) -> bool { (&self.path, self.position) < (&other.path, other.position) } } impl MacroSiteRank { fn absorb(&mut self, path: &Path, position: usize, site: &MacroBindingSite) { if field_site_blocks(site) && self .field_blocking .as_ref() .is_none_or(|kept| (path, position) < (kept.path.as_path(), kept.position)) { self.field_blocking = Some(OrderedMacroSite { path: path.to_path_buf(), position, site: site.clone(), }); } let slot = if rebinds(site) { &mut self.rebinding } else { &mut self.may_rebind }; if slot .as_ref() .is_none_or(|kept| (path, position) < (kept.path.as_path(), kept.position)) { *slot = Some(OrderedMacroSite { path: path.to_path_buf(), position, site: site.clone(), }); } } } fn keep_earliest_site<'a>( slot: &mut Option<&'a OrderedMacroSite>, candidate: Option<&'a OrderedMacroSite>, ) { if let Some(candidate) = candidate && slot.as_ref().is_none_or(|kept| candidate.precedes(kept)) { *slot = Some(candidate); } } fn merge_macro_site_rank<'a>( rebinding: &mut Option<&'a OrderedMacroSite>, may_rebind: &mut Option<&'a OrderedMacroSite>, rank: &'a MacroSiteRank, ) { keep_earliest_site(rebinding, rank.rebinding.as_ref()); keep_earliest_site(may_rebind, rank.may_rebind.as_ref()); } /// The crate root whose module tree holds `file`, when that root is one of /// Cargo's autodiscovered targets (`src/lib.rs`, `src/main.rs`, /// `src/bin/*.rs`, `tests/*.rs`, `benches/*.rs`, `examples/*.rs`, /// `build.rs`) and every module edge to it resolved. `None` keeps a /// binding workspace-wide: an unlinked file may belong to any crate. /// /// A file another crate can also compile is never charged to one root: /// an `include!` fragment (its text lands in every includer, with or /// without a recorded edge), a shared integration-test helper whose /// provenance keeps only the first of several `tests/*.rs` owners, and /// every file while any `include!` is unresolved in the workspace: an /// ambiguous, cfg-conflicting, capped or unindexed include leaves its /// fragment, and the fragment's module children, looking like a root. #[derive(Clone, Debug)] struct TargetRoots { /// An unresolved `include!`, an unresolvable `#[path]` (which records /// no module edge for its target), or an unindexed member that may /// mount other crates that way, may compile any file into another /// crate, so no file is charged to one root. disabled: bool, /// A lexical fallback, unknown module target, or unseen unindexed member /// also disabled placement. When one is present, the include is not the /// sole reason confinement is unavailable and must not be named as it. non_include_disabled: bool, /// The first include limitation whose paste reaches the workspace. This /// explains placement loss without blaming an inert include or a separate /// unresolved `#[path]` / unindexed member; it is disclosed only for a /// glob that would otherwise be module-confined /// ([`placement_include_explains`]). workspace_include: Option, /// #14116: integration test, bench and example roots holding an /// `include!` whose inert fragment may bind an assertion macro. The /// binding lands in that crate only and nothing imports it, so files /// under these roots are unplaced while every other crate keeps /// placement. tainted: BTreeSet, /// Every indexed `/src` directory, for the `tests/`, `benches/`, /// `examples/` and `build.rs` roots beside one. src_dirs: BTreeSet, /// Per-file answers, so repeated admissions do not recompute them. memo: SyncMemo>>>, /// #10191: all contexts must be non-importable binary crates before /// opaque expansions or exported bindings can be confined to them. binary_macro_roots: SyncMemo>>>, } /// Draft/Fast indexes omit members that are not the changed package or its /// reverse path-dependents. An omitted member is an unseen compilation /// *target* of indexed files only when it may mount them (`include!` or /// `#[path]`): that is the #10149 generated-B case. A namesake sibling /// with no such mount is not a target of the receiver, so indexed members /// across packages stay placeable. fn unindexed_member_is_unseen_compilation_target(index: &RustIndex) -> bool { let Some(root) = index .workspace_authority .as_ref() .map(|authority| authority.root.as_path()) else { return false; }; index.workspace_member_dirs.iter().any(|member_dir| { let member_canon = member_dir .canonicalize() .unwrap_or_else(|_| member_dir.to_path_buf()); let Some(relative) = member_canon.strip_prefix(root).ok() else { return false; }; let indexed = index.files().iter().any(|(path, _)| { let path = path.as_path(); let path = path.strip_prefix("./").unwrap_or(path); path.starts_with(relative) }); !indexed && unindexed_member_may_mount_foreign_files(&member_canon) }) } const UNINDEXED_MEMBER_ROOTS: &[&str] = &["src/lib.rs", "src/main.rs", "build.rs", "lib.rs", "main.rs"]; const UNINDEXED_MEMBER_SOURCE_BYTES: usize = 256 * 1024; /// The most `#[path]`-named files one unindexed member's walk follows before /// it fails closed. Crate roots, including every explicitly declared target, /// are not counted. const UNINDEXED_MEMBER_PATH_FILES: usize = 64; /// Whether an unindexed member's crate-root sources look like they could /// compile another crate's files. Unreadable, oversized, or missing crate /// roots fail closed: the member exists and its compilation effect is /// unknown. A readable crate root with no `include!` / `#[path]` is not a /// mount, so a namesake dependency of an indexed test crate does not /// disable placement. /// /// #14260: a literal `#[path]` on a top-level `mod name;` whose target is a /// file inside the member's own directory names the member's own file, as a /// plain `mod name;` would. That file is read under the same rule instead /// of failing closed; a missing or unreadable one still fails closed. fn unindexed_member_may_mount_foreign_files(member_dir: &Path) -> bool { let Some((inspected, saw_path)) = walk_unindexed_member(member_dir, false) else { return true; }; // Once a `#[path]` is accepted the member is no longer the plain layout // the roots above describe, so the walk repeats strictly: Cargo's // auto-discovered roots are read and no file may declare a default-layout // child this walk would not read. if saw_path && walk_unindexed_member(member_dir, true).is_none() { return true; } !inspected } /// Crate roots Cargo discovers without a manifest entry: `src/bin/*.rs`, /// `src/bin/*/main.rs`, and the same shapes under `tests`, `examples` and /// `benches`. `None` when a directory cannot be listed. fn auto_discovered_roots(member_dir: &Path) -> Option> { let mut roots = Vec::new(); for directory in ["src/bin", "tests", "examples", "benches"] { let entries = match std::fs::read_dir(member_dir.join(directory)) { Ok(entries) => entries, Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue, Err(_) => return None, }; for entry in entries { let path = entry.ok()?.path(); if path.is_dir() { roots.push(path.join("main.rs")); } else if path.extension().is_some_and(|extension| extension == "rs") { roots.push(path); } } } Some(roots) } /// One walk of an unindexed member's sources. `None` when something may /// compile a file outside the member; otherwise `(inspected, saw_path)`: /// whether any source was read and whether any own-file `#[path]` was seen. /// `strict` adds the auto-discovered roots and refuses default-layout /// children in every file, not only in files reached through `#[path]`. fn walk_unindexed_member(member_dir: &Path, strict: bool) -> Option<(bool, bool)> { let mut pending: Vec<(PathBuf, bool)> = UNINDEXED_MEMBER_ROOTS .iter() .map(|candidate| (member_dir.join(candidate), false)) .collect(); match std::fs::read_to_string(member_dir.join("Cargo.toml")) { Ok(manifest) => { for relative in declared_crate_root_paths_from_manifest(&manifest, member_dir) { pending.push((member_dir.join(relative), false)); } } Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} Err(_) => return None, } if strict { pending.extend( auto_discovered_roots(member_dir)? .into_iter() .map(|root| (root, false)), ); } let mut seen = BTreeSet::new(); let mut followed = 0; let mut inspected = false; let mut saw_path = false; // `required`: a `#[path]` named the file, so its absence is not a guess // that missed but a module whose source ripr cannot read. while let Some((path, required)) = pending.pop() { if !seen.insert(path.clone()) { continue; } if required { followed += 1; if followed > UNINDEXED_MEMBER_PATH_FILES { return None; } } match std::fs::read(&path) { Ok(bytes) => { // A root that links outside the member is another file's // compilation context, not the member's own source. if !path .canonicalize() .is_ok_and(|target| target.starts_with(member_dir)) { return None; } if bytes.len() > UNINDEXED_MEMBER_SOURCE_BYTES { return None; } let source = std::str::from_utf8(&bytes).ok()?; inspected = true; for literal in own_path_literals(source, required || strict)? { saw_path = true; pending.push((member_own_file(&path, &literal, member_dir)?, true)); } } Err(error) if !required && error.kind() == std::io::ErrorKind::NotFound => {} Err(_) => return None, } } Some((inspected, saw_path)) } /// The `#[path]` literals of `source` when they are all it could mount /// through: no `include!`, no inner `#![path]`, and every `#[path` in the /// text is the one plain literal of a top-level out-of-line `mod name;`. /// A file reached through `#[path]` (`followed`) must also declare no /// default-layout `mod child;`, whose file this walk would not read. /// `None` for anything else, which the caller reads as a foreign mount. fn own_path_literals(source: &str, followed: bool) -> Option> { let masked = mask_comments_and_strings(source); let includes = whole_word_offsets(&masked, "include") .into_iter() .any(|offset| { masked .get(offset + "include".len()..) .is_some_and(|rest| rest.trim_start().starts_with('!')) }); let compact: String = masked.chars().filter(|ch| !ch.is_whitespace()).collect(); // `#![path]`, a raw-identifier `r#path`, and a `cfg_attr` that may // introduce a `path` are spellings the `#[path` count below cannot see. if includes || compact.contains("#![path") || compact.contains("r#path") || cfg_attr_may_introduce_path(&compact) { return None; } let attributes = compact.matches("#[path").count(); if attributes == 0 && !followed { return Some(Vec::new()); } let mut literals = Vec::new(); for target in module_path_targets(source)? { match target { ModulePathTarget::Literal(literal) => literals.push(literal), ModulePathTarget::Default if !followed => {} ModulePathTarget::Default | ModulePathTarget::Unknown => return None, } } (literals.len() == attributes).then_some(literals) } /// Whether a `cfg_attr(..)` in whitespace-stripped source lists `path = ..` /// among the attributes it applies. Only the `cfg_attr` argument list is read, /// so an unrelated `path` elsewhere in the file (`use std::path::PathBuf;`) /// does not count. fn cfg_attr_may_introduce_path(compact: &str) -> bool { const NEEDLE: &str = "cfg_attr("; let mut rest = compact; while let Some(at) = rest.find(NEEDLE) { let body = &rest[at + NEEDLE.len()..]; let mut depth = 1usize; let mut end = body.len(); for (index, ch) in body.char_indices() { match ch { '(' => depth += 1, ')' => { depth -= 1; if depth == 0 { end = index; break; } } _ => {} } } if body[..end].contains(",path=") { return true; } rest = body; } false } /// The existing file a `#[path = "literal"]` in `declaring` names, when it /// lies inside `member_dir` (canonical). A non-inline `#[path]` is relative /// to the declaring file's directory. Symlinks are followed first, so a link /// out of the member is not the member's own file. fn member_own_file(declaring: &Path, literal: &str, member_dir: &Path) -> Option { let target = declaring.parent()?.join(literal).canonicalize().ok()?; (target.is_file() && target.starts_with(member_dir)).then_some(target) } /// #14116: how far one include limitation reaches. enum IncludeReach { /// The paste may compile unread source into any crate, or bind a macro /// another crate can import: placement is off for the whole workspace. Workspace, /// The paste stays inside these crate roots, which lose placement. Empty /// when every fragment is read and binds no assertion macro. Roots(BTreeSet), } /// #14116: the reach of an include limitation. Only an `include!` naming /// repository-local files by literal path (inside an inline module, or at /// file level with a target the index does not hold) is narrower than the /// workspace, and only when every fragment is inert: it declares no /// out-of-line module and names no `include!` or `#[path]`, so the paste /// compiles no further file. /// /// - An indexed inert fragment that no `mod` edge or recognized target shape /// charges to a crate reaches nothing more: [`TargetRoots::roots`] answers /// `None` for it, so its macros, globs and bindings are read as sites of a /// file that may be compiled anywhere, exactly like the target of a /// resolved file-level `include!`. /// - An inert fragment the index does not hold (a `fixtures` directory, a /// file no module declares) is read from disk with the scan every indexed /// file gets. A fragment that binds no assertion macro reaches nothing. /// - One that may bind an assertion macro stays inside the including crate /// only when that crate is an integration test, bench or example, which /// no other crate can import: those roots lose placement and every other /// crate keeps it. /// /// Everything else (a dynamic expression, a missing, unreadable or oversized /// target, a fragment that mounts files or is itself a module of some crate, /// a possible binding inside a library or binary) keeps the workspace-wide /// refusal. fn include_limitation_reach( index: &RustIndex, limitation: &RustIncludeLimitation, src_dirs: &BTreeSet, ) -> IncludeReach { let Some(fragments) = literal_include_fragments(index, limitation) else { return IncludeReach::Workspace; }; let mut reach = BTreeSet::new(); for fragment in &fragments { if let Some(facts) = index.files().get(fragment) { if facts.used_lexical_fallback || !facts.module_declarations.is_empty() || !own_path_literals(&facts.source, false) .is_some_and(|literals| literals.is_empty()) || target_context_roots(fragment, index, src_dirs).is_some() { return IncludeReach::Workspace; } continue; } let Some(source) = unindexed_inert_fragment(index, fragment) else { return IncludeReach::Workspace; }; if fragment_binds_no_assertion_macro(index, &source) { continue; } match target_context_roots(&limitation.parent, index, src_dirs) { Some(roots) if roots .iter() .all(|root| root_is_unimportable_target(index, root)) => { reach.extend(roots); } _ => return IncludeReach::Workspace, } } IncludeReach::Roots(reach) } /// The text of a fragment the index does not hold, when it resolves inside /// the repository and is readable, bounded, UTF-8 and mounts nothing. fn unindexed_inert_fragment(index: &RustIndex, fragment: &Path) -> Option { let root = index .workspace_authority .as_ref() .map(|authority| authority.root.as_path())?; // The same boundary the include producer keeps: a path that resolves // outside the repository (a symlink) is never read. let canonical_root = std::fs::canonicalize(root).ok()?; let target = std::fs::canonicalize(root.join(fragment)).ok()?; if !target.starts_with(&canonical_root) { return None; } let bytes = std::fs::read(&target).ok()?; if bytes.len() > UNINDEXED_MEMBER_SOURCE_BYTES { return None; } String::from_utf8(bytes).ok().filter(|source| { own_path_literals(source, false).is_some_and(|literals| literals.is_empty()) && !source_may_declare_file_module(source) }) } /// Whether the scan every indexed file gets finds no site in `source` that /// could bind an assertion macro: no definition, import, glob, opaque /// item-position expansion or prelude switch. No module or drop-in crate is /// taken as verified, and a file that does not parse reports a site. fn fragment_binds_no_assertion_macro(index: &RustIndex, source: &str) -> bool { let names = assertion_context_macros(); let (sites, _) = trusted_macro_binding_site_sets( source, index.macro_scope_crates(), &names, &names, &|_, _| false, &|_| false, ); sites.is_empty() } /// Whether `root` is an integration test, bench or example crate root: a /// crate no other crate can depend on, so nothing it defines is importable. /// A manifest may move a library there (`[lib] path = "tests/lib.rs"`); that /// root is importable and answers no. fn root_is_unimportable_target(index: &RustIndex, root: &Path) -> bool { !index.member_crates.is_custom_lib_path_root(root) && root .parent() .and_then(Path::file_name) .is_some_and(|directory| { directory == "tests" || directory == "benches" || directory == "examples" }) } /// Whether source text may hold an out-of-line `mod name;`, read lexically /// so a declaration inside a macro body counts too. fn source_may_declare_file_module(source: &str) -> bool { let masked = mask_comments_and_strings(source); whole_word_offsets(&masked, "mod") .into_iter() .any(|offset| { masked.get(offset + "mod".len()..).is_some_and(|rest| { rest.trim_start() .trim_start_matches(|ch: char| ch.is_alphanumeric() || ch == '_' || ch == '#') .trim_start() .starts_with(';') }) }) } impl TargetRoots { fn new(index: &RustIndex) -> Self { // A lexical-fallback file records no module declarations, so its // children get no edge either. let src_dirs: BTreeSet = index .files() .iter() .flat_map(|(path, _)| path.ancestors().skip(1)) .filter(|directory| directory.file_name().is_some_and(|name| name == "src")) .map(Path::to_path_buf) .collect(); let mut tainted = BTreeSet::new(); let mut include_reaches_workspace = false; let mut workspace_include = None; for limitation in &index.include_limitations { match include_limitation_reach(index, limitation, &src_dirs) { IncludeReach::Workspace => { include_reaches_workspace = true; workspace_include.get_or_insert_with(|| limitation.clone()); } IncludeReach::Roots(roots) => tainted.extend(roots), } } let non_include_disabled = unindexed_member_is_unseen_compilation_target(index) || index.files().iter().any(|(_, facts)| { facts.used_lexical_fallback || facts .module_declarations .iter() .any(|declaration| declaration.path_target == ModulePathTarget::Unknown) }); Self { disabled: include_reaches_workspace || non_include_disabled, non_include_disabled, workspace_include, tainted, src_dirs, memo: SyncMemo::default(), binary_macro_roots: SyncMemo::default(), } } fn roots(&self, file: &Path, index: &RustIndex) -> Option> { if self.disabled { return None; } if let Some(roots) = self.memo.borrow().get(file) { return roots.clone(); } let roots = target_context_roots(file, index, &self.src_dirs) .filter(|roots| roots.is_disjoint(&self.tainted)); self.memo .borrow_mut() .insert(file.to_path_buf(), roots.clone()); roots } fn root(&self, file: &Path, index: &RustIndex) -> Option { let roots = self.roots(file, index)?; (roots.len() == 1) .then(|| roots.into_iter().next()) .flatten() } fn binding_roots( &self, file: &Path, site: &MacroBindingSite, index: &RustIndex, ) -> Option> { if self.disabled { return None; } if site.crate_local { if let Some(roots) = self.roots(file, index) { return Some(roots); } // #14116: a crate-local site cannot leave its crate, and a crate // that only lost placement to its own unread include is still // known. The site is charged to that crate instead of to every // test in the workspace. if !self.tainted.is_empty() && let Some(roots) = target_context_roots(file, index, &self.src_dirs) && !roots.is_disjoint(&self.tainted) { return Some(roots); } } self.binary_roots(file, index) } fn binary_roots(&self, file: &Path, index: &RustIndex) -> Option> { if self.disabled { return None; } if let Some(roots) = self.binary_macro_roots.borrow().get(file) { return roots.clone(); } let roots = index.execution_context(file).and_then(|context| { (!context.roots.is_empty() && context.roots.is_disjoint(&self.tainted) && context .roots .iter() .all(|root| index.member_crates.is_binary_target_root(root))) .then_some(context.roots) }); self.binary_macro_roots .borrow_mut() .insert(file.to_path_buf(), roots.clone()); roots } fn may_belong(&self, file: &Path, root: &Path, index: &RustIndex) -> bool { self.roots(file, index) .is_none_or(|roots| roots.contains(root)) } /// #11123: whether `file` composes, through established module edges, /// only under crate roots that the manifest declares as explicit targets /// (`[[bin]]`, `[[example]]`, `[[test]]`, `[[bench]]` `path`) other than /// `root`. Such a root is a crate of its own, so the file is not in /// `root`'s crate even though no autodiscovered layout recognizes its /// root. An undeclared orphan root, a root shared with `root`, an /// `include!` fragment, unresolved placement or an unresolvable /// `#[path]` anywhere (`disabled`) answer no. fn only_under_other_declared_targets( &self, file: &Path, root: &Path, index: &RustIndex, ) -> bool { if self.disabled { return false; } index.execution_context(file).is_some_and(|context| { !context.roots.is_empty() && context.roots.iter().all(|file_root| { file_root != root && index.member_crates.is_declared_target_entry(file_root) }) }) } } /// The crate root file `file` composes under: a recognized Cargo target root /// (`src/lib.rs`, `src/main.rs`, `src/bin/*.rs`, `src/bin/NAME/main.rs`, an integration test, bench, /// example or build script), a root the package manifest names (`[lib] path`, /// or an explicit `[[bin]]`, `[[example]]`, `[[test]]` or `[[bench]]` /// `path`), or `None` when composition is unresolved, goes through /// `include!`, or ends at a file no target is known to root. pub(super) fn target_root( file: &Path, index: &RustIndex, src_dirs: &BTreeSet, ) -> Option { let roots = target_context_roots(file, index, src_dirs)?; (roots.len() == 1) .then(|| roots.into_iter().next()) .flatten() } fn target_context_roots( file: &Path, index: &RustIndex, src_dirs: &BTreeSet, ) -> Option> { let context = index.execution_context(file)?; if context.roots.is_empty() || context.roots.iter().any(|root| { // Preserve the existing conservative integration-helper boundary. (root != file && root .parent() .and_then(Path::file_name) .is_some_and(|p| p == "tests")) || !(recognized_target_root(root, src_dirs) || index.member_crates.is_custom_lib_path_root(root) || index.member_crates.is_declared_target_entry(root)) }) { return None; } Some(context.roots) } fn recognized_target_root(root: &Path, src_dirs: &BTreeSet) -> bool { let names: Vec<&str> = root .iter() .map(|part| part.to_str().unwrap_or_default()) .collect(); let package_has_src = |package: &[&str]| { let prefix: PathBuf = package.iter().chain(&["src"]).collect(); src_dirs.contains(&prefix) }; let recognized = match names.as_slice() { [.., "src", "lib.rs" | "main.rs"] | [.., "src", "bin", _] | [.., "src", "bin", _, "main.rs"] => true, [package @ .., "tests" | "benches" | "examples", _] => package_has_src(package), [package @ .., "build.rs"] => package_has_src(package), _ => false, }; recognized && root.extension().is_some_and(|extension| extension == "rs") } impl OwnerPinSyntax { /// Whether a workspace trait could answer `write_str`-style calls on /// `String`/`Vec`/`VecDeque`, scanned once per run. pub(in crate::analysis) fn user_buffer_traits(&self, index: &RustIndex) -> bool { *self .user_buffer_traits .get_or_init(|| super::out_parameter::workspace_has_user_buffer_traits(index)) } /// The workspace's `macro_rules!` macro names, scanned once per run. pub(in crate::analysis) fn workspace_macro_names(&self, index: &RustIndex) -> &[String] { self.workspace_macro_names .get_or_init(|| super::out_parameter::workspace_macro_names(index)) } /// Whether no file can be placed in a Cargo target, because an include or /// `#[path]` somewhere in the workspace cannot be resolved. pub(in crate::analysis) fn target_placement_unavailable(&self, index: &RustIndex) -> bool { self.target_roots(index).disabled } /// Workspace routing inputs, computed once per run. fn target_roots(&self, index: &RustIndex) -> &TargetRoots { self.target_roots.get_or_init(|| TargetRoots::new(index)) } /// Trusted names a crate-local site makes ambiguous for `test`: those in /// the test's own recognized root, or every one when that root is not /// established. fn crate_names_for(&self, test: &TestSummary, index: &RustIndex) -> Vec { let by_root = self.crate_macro_bindings.borrow(); let Some(by_root) = by_root.as_ref().filter(|by_root| !by_root.is_empty()) else { return Vec::new(); }; match self.target_roots(index).roots(&test.file, index) { Some(roots) => roots .iter() .flat_map(|root| by_root.get(root).into_iter().flatten()) .cloned() .collect(), None => by_root.values().flatten().cloned().collect(), } } /// Trusted names a private file-level foreign glob makes ambiguous for /// `test`: those declared in the test's own file or a file whose module /// tree holds it. A test whose ancestry is not established reads each /// such glob as a crate-local site, as before the confinement. fn module_names_for(&self, test: &TestSummary, index: &RustIndex) -> Vec { let scan = self.workspace_site_scan.borrow(); let Some(by_module) = scan .as_ref() .map(|scan| &scan.by_module) .filter(|by_module| !by_module.is_empty()) else { return Vec::new(); }; let context = self.execution_context(&test.file, index); let roots = self.target_roots(index); let ancestry = module_ancestry(&context, &test.file, roots, index); let test_roots = roots.roots(&test.file, index); let carries = |file: &Path| self.file_may_carry_glob_chain(file, index); let jumps = |file: &Path| self.file_may_skip_glob_parent(file, index); by_module .iter() .filter(|(file, binding)| { module_binding_reaches( file, binding, ancestry.as_ref(), test_roots.as_ref(), &carries, &jumps, ) }) .flat_map(|(_, binding)| binding.names.iter().cloned()) .collect() } /// Trusted names that a scoped definition or import makes ambiguous for /// `test`, or for the invocation at `assertion_line`: an assertion a /// check helper lends (#6482) sits in the helper's body, whose scoped /// bindings never overlap the test's span. Filled by the workspace scan /// in `refusal`. fn scoped_names_for( &self, test: &TestSummary, assertion_line: usize, index: &RustIndex, ) -> Vec { let bytes = SiteCoverBytes::for_assertion(self, index, test, assertion_line); self.scoped_macro_bindings .borrow() .as_ref() .and_then(|scoped| scoped.get(&test.file)) .into_iter() .flatten() .filter(|(_, site)| site_covers_assertion(site, test, assertion_line, bytes)) .map(|(name, _)| name.clone()) .collect() } } /// Whether a scoped site may reach the invocation at `assertion_line` in /// `test`: it overlaps the test, or (for an assertion a check helper lends, /// #6482) its scope holds the assertion's own line in the helper's body. #[derive(Clone, Copy)] struct SiteCoverBytes { test: Option<(u32, u32)>, assertion: Option<(u32, u32)>, } impl SiteCoverBytes { fn for_assertion( syntax: &OwnerPinSyntax, index: &RustIndex, test: &TestSummary, assertion_line: usize, ) -> Self { let needs = syntax .scoped_macro_bindings .borrow() .as_ref() .and_then(|scoped| { scoped.get(&test.file).map(|sites| { sites.iter().any(|(_, site)| { site_cover_needs_test_fn_bytes(site, test) || site_cover_needs_assertion_bytes(site, assertion_line) }) }) }); let needs = needs.unwrap_or(false); if !needs { return Self { test: None, assertion: None, }; } Self { test: test_fn_byte_range(syntax, index, test), assertion: assertion_byte_range(index, test, assertion_line), } } } /// Byte containment is required only when a scoped site records `scope_bytes` /// and the same-line disambiguation path applies (#5695). fn site_cover_needs_test_fn_bytes(site: &MacroBindingSite, test: &TestSummary) -> bool { site.scope_bytes.is_some() && site.scope.is_some_and(|(start, end)| { start == end && test.start_line == test.end_line && test.start_line == start }) } fn site_cover_needs_assertion_bytes(site: &MacroBindingSite, assertion_line: usize) -> bool { site.scope_bytes.is_some() && site .scope .is_some_and(|(start, end)| start == end && assertion_line == start) } fn site_covers_assertion( site: &MacroBindingSite, test: &TestSummary, assertion_line: usize, bytes: SiteCoverBytes, ) -> bool { if site_covers(site, test, bytes.test) { return true; } let Some((start, end)) = site.scope else { return false; }; if !(start..=end).contains(&assertion_line) { return false; } let same_line_scope = start == end && assertion_line == start; if !same_line_scope { return true; } match (site.scope_bytes, bytes.assertion) { (Some((scope_start, scope_end)), Some((assert_start, assert_end))) => { scope_start <= assert_start && assert_end <= scope_end } (None, _) => true, // A borrowed oracle (a check helper lends its own assertion, #6482) // never resolves to bytes: `assertion_byte_range` reads only the // test's own assertions. With no range to contain, keep the pre-#5695 // conservative cover instead of dropping the shadow and admitting a // possibly replaced macro's expansion as a genuine check (#12461). (Some(_), None) => true, } } /// Whether a scoped site may reach `test`: line spans must overlap, and when /// byte spans are available the test function must sit inside the scoped item /// (#5695). A `use` in the test's own body is scoped to the body block, which /// starts after the `fn` line when the signature wraps, so containment would /// miss it; [`site_covers_assertion`] also matches the assertion line. fn site_covers( site: &MacroBindingSite, test: &TestSummary, test_bytes: Option<(u32, u32)>, ) -> bool { let Some((start, end)) = site.scope else { return false; }; if test.start_line > end || test.end_line < start { return false; } let same_line_scope = start == end && test.start_line == test.end_line && test.start_line == start; if !same_line_scope { return true; } match (site.scope_bytes, test_bytes) { (Some((scope_start, scope_end)), Some((test_start, test_end))) => { scope_start <= test_start && test_end <= scope_end } (Some(_), None) => false, _ => true, } } fn test_fn_byte_range( syntax: &OwnerPinSyntax, index: &RustIndex, test: &TestSummary, ) -> Option<(u32, u32)> { index.files().get(&test.file)?; let name = test.name.trim_start_matches("r#"); if let Some(scopes) = syntax.file_scopes(index, &test.file) && let Some(function) = scopes .fns .iter() .find(|function| function.name == name && function.start_line == test.start_line) { return Some((function.start, function.end)); } let tree = index.source_syntax.get(index, &test.file)?.tree()?; build_file_scopes(&tree) .fns .into_iter() .find(|function| function.name == name && function.start_line == test.start_line) .map(|function| (function.start, function.end)) } fn assertion_byte_range(index: &RustIndex, test: &TestSummary, line: usize) -> Option<(u32, u32)> { let facts = index.files().get(&test.file)?; let oracle = test .assertions .iter() .find(|assertion| assertion.line == line)?; let tree = index.source_syntax.get(index, &test.file)?.tree()?; let lines = LineIndex::new(&facts.source); // The oracle text keeps its statement terminator while the `MacroCall` // node's text stops before it; strip one trailing `;` so the test's own // invocation still resolves to bytes (#12461). let needle = oracle.text.trim().trim_end_matches(';').trim_end(); if needle.is_empty() { return None; } for call in tree.syntax().descendants().filter_map(ast::MacroCall::cast) { let range = call.syntax().text_range(); if lines.line(range.start()) != line { continue; } let invoked = call.syntax().text().to_string(); let invoked = invoked.trim(); if invoked == needle || invoked.contains(needle) { return Some((u32::from(range.start()), u32::from(range.end()))); } } None } /// Why an `assert_eq!` was not credited as executing the standard macro. #[derive(Clone, Debug, PartialEq, Eq)] pub(in crate::analysis) enum AssertionRefusal { /// The test file was indexed by the lexical fallback, not the parser. LexicalFallback, /// Module composition could not place the test file; the reason code. UnresolvedModule(String), /// The test file is composed through `include!`, so its declaration /// context is not exact. IncludedFile { parent: PathBuf, line: usize }, /// The `mod` declaration that brings the test file in is gated or nested. ModuleDeclaration { parent: PathBuf, line: usize, declaration: String, }, /// A test-local reason from the parser-backed scan. Syntax(AssertionContextRefusal), /// `name!` may be rebound somewhere in the workspace; the first site /// that does so, when ripr could find it. MacroBinding { name: String, site: Option<(PathBuf, MacroBindingSite)>, /// The first include that disabled placement, when a private unscoped /// foreign glob that would otherwise be module-confined is ambiguous /// because it cannot be. `None` when placement is not the cause. placement_include: Option, }, /// The test's only `return` sits under `if { return; }`, /// whose condition compares `subject` (the call the assertion compares) /// with a literal and does not hold for the value the assertion /// expects: the assertion runs for that value, and whether it runs for /// another depends on a value ripr does not evaluate. ValueGuard { condition: String, subject: String }, /// A sole expected-panic matches assertion can invert its check, but /// another panic in its owner, arguments or destructor is unresolved. ExpectedPanicUnresolved, } impl AssertionRefusal { /// The call a [`Self::ValueGuard`] reads, so a caller can require it to /// be the owner's. pub(in crate::analysis) fn value_guard_subject(&self) -> Option<&str> { match self { Self::ValueGuard { subject, .. } => Some(subject), _ => None, } } /// Whether the refusal rests on a limit of ripr's own reading (the file, /// module, test identity, or a binding that only *may* rebind), rather /// than on a shape that can keep the assertion from running or rebind it /// for real. Runtime controls pin the second kind as real gaps /// (`tests/owner_pin_execution.rs`), so only the first kind lets /// RIPR-SPEC-0240 withhold a gap. pub(in crate::analysis) fn is_analyzer_limit(&self) -> bool { match self { Self::LexicalFallback | Self::UnresolvedModule(_) | Self::IncludedFile { .. } => true, // trap-tally-reached-assert-control: the guard spares the // expected value, so the assertion's reach is value-dependent. Self::ValueGuard { .. } | Self::ExpectedPanicUnresolved => true, // A gated `mod` declaration may be `cfg(any())`, which never runs. Self::ModuleDeclaration { .. } => false, Self::Syntax(refusal) => match refusal { AssertionContextRefusal::UnparsedFile | AssertionContextRefusal::UnidentifiedTest | AssertionContextRefusal::AsyncTest | AssertionContextRefusal::TestRebound | AssertionContextRefusal::DuplicateSpelling | AssertionContextRefusal::DuplicateSpellingOneRuns | AssertionContextRefusal::ModelCheckClosure | AssertionContextRefusal::StaleSource => true, AssertionContextRefusal::TestAttribute(attribute) => { !attribute_settles_test_outcome(attribute) } AssertionContextRefusal::NestedItem | AssertionContextRefusal::GatedItem(_) | AssertionContextRefusal::OpaqueMacro(_) | AssertionContextRefusal::MacroOperandExit(_) | AssertionContextRefusal::ClosureExit | AssertionContextRefusal::ConditionalPath(_) | AssertionContextRefusal::GuardedReturn(_) | AssertionContextRefusal::MacroBinding(_) => false, }, // A definition or `use` of the name in reach is a real rebinding; // a foreign glob, unresolved `#[macro_use]`, macro argument, or an // unparsed file only may rebind it. Self::MacroBinding { site, .. } => { !site.as_ref().is_some_and(|(_, site)| rebinds(site)) } } } /// Whether the refusal is an enclosing `cfg` gate on the test (#9643). pub(in crate::analysis) fn is_gated_item(&self) -> bool { matches!(self, Self::Syntax(AssertionContextRefusal::GatedItem(_))) } /// The out-of-line `mod name;` declaration that refused the test's file: /// the declaring file, its line and the declaration text (#14463). pub(in crate::analysis) fn module_declaration_site(&self) -> Option<(&Path, usize, &str)> { match self { Self::ModuleDeclaration { parent, line, declaration, } => Some((parent.as_path(), *line, declaration.as_str())), _ => None, } } /// The test's own in-file refusal of each assertion, read without the /// module provenance that refused its file first (#14463). A shared gated /// declaration only explains the provenance refusal; an ignored test, an /// expected panic or a conditional assertion still keeps the gap. `None` /// when the test's file is not in the index, or the test is a property or /// doc test whose assertions are not read from the file's own text. pub(in crate::analysis) fn test_local_refusals( test: &TestSummary, index: &RustIndex, ) -> Option>> { if index.proptest_source(test).is_some() || index.doctest_source(test).is_some() { return None; } let facts = index.files().get(&test.file)?; let pins = owner_pin_assertions( &expanded_assertion_view(&facts.source, facts.tests.iter()), &assertion_context_macros(), ); Some( test.assertions .iter() .map(|assertion| { pins.refusal( (test.start_line, test.end_line, &test.name), &test.body, (assertion.line, &assertion.text), &BTreeSet::new(), ) .map(Self::Syntax) }) .collect(), ) } /// One reader-facing clause: what blocked crediting the assertion. pub(in crate::analysis) fn describe(&self) -> String { // Evidence text is host-independent: use the stable slash spelling // so Windows and Unix emit identical bytes (#2337 family). let at = |path: &Path, line: usize| { let text = crate::analysis::stable_path_text(path); if line == 0 { text } else { format!("{text}:{line}") } }; match self { Self::LexicalFallback => { "its file did not parse cleanly, so ripr read it with a lexical fallback".into() } Self::UnresolvedModule(reason) => { format!("ripr could not place its file in the crate's module tree ({reason})") } Self::IncludedFile { parent, line } => { format!( "its file is pulled in by `include!` at {}", at(parent, *line) ) } Self::ModuleDeclaration { parent, line, declaration, } => format!( "`{declaration}` at {} is gated by a `cfg` ripr cannot evaluate, or nested", at(parent, *line) ), Self::Syntax(refusal) => match refusal { AssertionContextRefusal::UnparsedFile => "its file did not parse cleanly".into(), AssertionContextRefusal::UnidentifiedTest => { "ripr could not identify the test function uniquely".into() } AssertionContextRefusal::AsyncTest => { "the test is `async`, and ripr does not model its executor".into() } AssertionContextRefusal::TestRebound => { "an import in this file may rebind `test` (for example `use .. as test`), so `#[test]` may not be the built-in attribute and may change whether or how the test runs".into() } AssertionContextRefusal::TestAttribute(attribute) => { format!( "the test carries `{attribute}`, which may change whether or how it runs" ) } AssertionContextRefusal::NestedItem => { "the test is declared inside a function body, which ripr does not model".into() } AssertionContextRefusal::GatedItem(attribute) => format!( "an enclosing module carries `{attribute}`, which ripr cannot evaluate for test builds" ), AssertionContextRefusal::OpaqueMacro(name) => format!( "the test calls `{name}!`, whose expansion ripr cannot see, so a hidden `return` or `?` could skip the assertion" ), AssertionContextRefusal::MacroOperandExit(name) => format!( "an argument of `{name}!` contains a `return`, `?` or nested macro that may leave the test before the comparison" ), AssertionContextRefusal::ClosureExit => { "a closure in the test can return early, or the test yields".into() } AssertionContextRefusal::DuplicateSpelling | AssertionContextRefusal::DuplicateSpellingOneRuns => { "the same assertion text appears twice on one line".into() } AssertionContextRefusal::ConditionalPath(construct) => { format!("the assertion is inside {construct}") } AssertionContextRefusal::ModelCheckClosure => { "the assertion is inside a closure a model-checking runner (`loom::model`, `shuttle::check_*`) calls, and ripr does not read how often the runner calls it".into() } AssertionContextRefusal::GuardedReturn(condition) => format!( "the assertion is inside a block that an earlier `if {condition} {{ return; }}` can skip" ), AssertionContextRefusal::MacroBinding(name) => { format!("`{name}!` may be redefined somewhere in the workspace") } AssertionContextRefusal::StaleSource => { "the test's source changed while ripr was reading it".into() } }, Self::ValueGuard { condition, subject } => format!( "an earlier `if {condition} {{ return; }}` spares the value the assertion expects, so whether the assertion runs depends on the value of `{subject}`, which ripr does not evaluate" ), Self::ExpectedPanicUnresolved => "the expected-panic matches check has an unresolved panic source or expected diagnostic, which ripr cannot establish".into(), Self::MacroBinding { name, site, placement_include, } => match site { None => format!("`{name}!` may be redefined somewhere in the workspace"), Some((path, site)) => { let place = at(path, site.line); if let (Some(limitation), MacroBindingKind::ForeignGlob(import)) = (placement_include, &site.kind) { return format!( "`{import}` at {place} could not be confined to its module because placement is unavailable, so it may bring in a different `{name}!`; first include limitation: `{}` at {} ({})", limitation.expression, at(&limitation.parent, limitation.line), limitation.reason_code ); } match &site.kind { MacroBindingKind::Unparsed => format!( "{} did not parse cleanly, so it may redefine `{name}!`", crate::analysis::stable_path_text(path) ), MacroBindingKind::NoImplicitPrelude => format!( "`#![no_implicit_prelude]` at {place} removes the standard `{name}!`" ), MacroBindingKind::MacroUse(item) | MacroBindingKind::ExternMacroUse { item, .. } => format!( "`#[macro_use] {item}` at {place} imports macros from code ripr did not index, which may redefine `{name}!`" ), MacroBindingKind::MacroUseExport { item, exporter, line } => format!( "`#[macro_use] {item}` at {place} imports a manifest-selected local `{name}!` exported at {}, whose behavior ripr did not expand", at(exporter, *line) ), MacroBindingKind::ForeignGlob(import) => format!( "`{import}` at {place} glob-imports from outside the workspace, which may bring in a different `{name}!`" ), MacroBindingKind::Definition => { format!("{place} defines a macro named `{name}`") } MacroBindingKind::Import => { format!("{place} imports a different `{name}` by name") } MacroBindingKind::UnverifiedDropIn(krate) => format!( "{place} imports `{name}` from `{krate}`, and no Cargo.toml ripr read declares `{krate}` as the plain registry package; declare it by version only (no `package`, `path`, `git`, `registry` or `[patch]`)" ), MacroBindingKind::MacroArgument(macro_name) => format!( "`{macro_name}!` at {place} mentions `{name}` in its arguments, so its expansion may define it" ), MacroBindingKind::ArgumentAttribute { wrapper, attribute } => format!( "`{wrapper}!` at {place} carries `{attribute}` in its arguments, which its expansion may apply, bringing in a different `{name}!`" ), MacroBindingKind::MacroBody(macro_name) => format!( "the body of `{macro_name}!` at {place} defines or imports `{name}`, so its expansion may rebind it" ), MacroBindingKind::BodyBindsAny { macro_name, binding, } => format!( "the body of `{macro_name}!` at {place} carries `{binding}`, which its expansion may apply, bringing in a different `{name}!`" ), } } }, } } } /// A workspace site, in path order, whose scan makes `name` ambiguous /// everywhere. The admission decision uses the set; the site decides only /// whether the refusal is an analyzer limit (RIPR-SPEC-0240). A definition or /// `use` of the name is a real rebinding, so it outranks a site that only may /// rebind the name, wherever each sits. /// /// #8255 reference oracle: production answers come from the single-pass /// retention ([`OwnerPinSyntax::workspace_macro_site`]); this scan stays as /// the test-side authority that the retention answers identically. #[cfg(test)] fn workspace_macro_binding_site( name: &str, test_root: Option<&Path>, index: &RustIndex, roots: &TargetRoots, module_resolved: &(dyn Fn(&Path, usize, &str) -> bool + Sync), ) -> Option<(PathBuf, MacroBindingSite)> { workspace_macro_binding_site_for(name, test_root, test_root, index, roots, module_resolved) } /// [`workspace_macro_binding_site`] for a test whose file is not its root. #[cfg(test)] fn workspace_macro_binding_site_for( name: &str, test_root: Option<&Path>, test_file: Option<&Path>, index: &RustIndex, roots: &TargetRoots, module_resolved: &(dyn Fn(&Path, usize, &str) -> bool + Sync), ) -> Option<(PathBuf, MacroBindingSite)> { if !assertion_context_macros().contains(&name) { return None; } // Independent of the production retention: a private file-level glob in // a file with established composition reaches the test's own file and // the files that file's module tree holds, nothing else. let ancestry = test_file.and_then(|file| { if roots.disabled || roots.roots(file, index).is_none() { return None; } let context = index.execution_context(file)?; let mut ancestors: BTreeSet = context.roots.iter().cloned().collect(); ancestors.insert(file.to_path_buf()); for edge in &context.edges { ancestors.insert(edge.parent.clone()); ancestors.insert(edge.child.clone()); } Some(ancestors) }); // Every file may be parsed for this one name, which was a quarter of a // warm `ripr check` on ripr-swarm when run serially. Each file's answer // is independent, so files are scanned on the rayon pool in path-ordered // batches: the earliest file still wins, and a rebinding in an early // batch still stops the scan before later files are parsed. // Roots memoize behind a lock, so they are resolved before the pool. let files: Vec<_> = index .files() .iter() .map(|(path, facts)| { // Preserve the selected manifest overlay before entering rayon. if test_root.is_some() { let _ = roots.roots(path, index); let _ = roots.binary_roots(path, index); } let placed = roots.roots(path, index).is_some(); (path, facts, placed) }) .collect(); let scan = |(path, facts, placed): &(&PathBuf, FileFactsView<'_>, bool)| { // The same rule as the decision: a crate-local site in another // recognized root does not reach this test. let reaches = |site: &MacroBindingSite| { if site.module_local && !roots.disabled && index.execution_context(path).is_some() && *placed && let Some(ancestors) = &ancestry { return ancestors.contains(path.as_path()); } test_root.is_none_or(|test_root| { roots .binding_roots(path, site, index) .is_none_or(|site_roots| site_roots.contains(test_root)) }) }; let mut first = None; for (_, site) in macro_binding_sites( name, path, &facts.source, facts.macro_candidates.as_deref(), index, roots, module_resolved, ) { if site.scope.is_some() || !reaches(&site) { continue; } if rebinds(&site) { return (Some(site), first); } first.get_or_insert(site); } (None, first) }; // Wide enough that one large file does not stall the pool for long. let batch = rayon::current_num_threads().max(1) * 32; let mut first = None; for chunk in files.chunks(batch) { let per_file: Vec<_> = if nested_parallelism_allowed() { chunk.par_iter().map(scan).collect() } else { chunk.iter().map(scan).collect() }; for ((path, _, _), (rebinding, site)) in chunk.iter().zip(per_file) { if let Some(site) = rebinding { return Some(((*path).clone(), site)); } if first.is_none() { first = site.map(|site| ((*path).clone(), site)); } } } first } fn field_site_blocks(site: &MacroBindingSite) -> bool { rebinds(site) || matches!( site.kind, MacroBindingKind::MacroUseExport { .. } | MacroBindingKind::MacroArgument(_) | MacroBindingKind::MacroBody(_) | MacroBindingKind::BodyBindsAny { .. } | MacroBindingKind::ArgumentAttribute { .. } ) } /// Whether the module declaration `declaration` on `line` of `file` resolves /// to an indexed file. A parsed `mod NAME;` is answered by the module edges; /// a [`cfg_if_module_declaration`] key (#5993), which exists only as tokens in /// a `cfg_if!`, by the default layout: the one `NAME.rs` or `NAME/mod.rs` /// beside a crate-root-named or `mod.rs` declaring file. Other declaring /// files nest their children one directory deeper, which this does not model. fn module_declaration_resolved( resolved: &BTreeSet<(PathBuf, usize, String)>, index: &RustIndex, file: &Path, line: usize, declaration: &str, ) -> bool { let Some(name) = cfg_if_module_name(declaration) else { return resolved.contains(&(file.to_path_buf(), line, declaration.to_string())); }; if !cfg_if_layout_file(file) { return false; } let directory = file.parent().unwrap_or(Path::new("")); let files = index.files(); let flat = files.get(&directory.join(format!("{name}.rs"))).is_some(); let nested = files.get(&directory.join(name).join("mod.rs")).is_some(); // Both layouts present is a rustc error (E0761), never one module. flat != nested } /// Whether `file` places its child modules in its own directory: `mod.rs`, /// or a `lib.rs`/`main.rs` that is an actual crate root (`src/lib.rs`, /// `src/main.rs`, `src/bin/NAME/main.rs`). A `lib.rs` or `main.rs` declared by /// `mod lib;` nests children under `lib/`, so file name alone is not enough. fn cfg_if_layout_file(file: &Path) -> bool { let parts: Vec<&str> = file .components() .filter_map(|component| component.as_os_str().to_str()) .collect(); matches!( parts.as_slice(), [.., "mod.rs"] | [.., "src", "lib.rs" | "main.rs"] | [.., "src", "bin", _, "main.rs"] ) } /// A definition or `use` of the name: a real rebinding, not one that only /// may rebind it. fn rebinds(site: &MacroBindingSite) -> bool { matches!( site.kind, MacroBindingKind::Definition | MacroBindingKind::Import ) } /// The scoped site in the test's own file that covers the test. #[allow( clippy::too_many_arguments, reason = "macro-site lookup threads memo, roots, module resolution and byte cover context" )] fn test_macro_binding_site( name: &str, test: &TestSummary, assertion_line: usize, index: &RustIndex, bytes: SiteCoverBytes, memo: &SyncMemo, roots: &TargetRoots, module_resolved: &dyn Fn(&Path, usize, &str) -> bool, ) -> Option<(PathBuf, MacroBindingSite)> { if !assertion_context_macros().contains(&name) { return None; } let facts = index.files().get(&test.file)?; memo.borrow_mut() .entry((name.to_string(), test.file.clone())) .or_insert_with(|| { macro_binding_sites( name, &test.file, &facts.source, facts.macro_candidates.as_deref(), index, roots, module_resolved, ) }) .iter() .find(|(_, site)| site_covers_assertion(site, test, assertion_line, bytes)) .map(|(_, site)| (test.file.clone(), site.clone())) } /// `candidates` are the file's stored [`MacroBindingCandidates`]: a name /// they rule out has no site, so the file is not parsed for it. fn macro_binding_sites( name: &str, path: &Path, source: &str, candidates: Option<&MacroBindingCandidates>, index: &RustIndex, roots: &TargetRoots, module_resolved: &dyn Fn(&Path, usize, &str) -> bool, ) -> Vec<(String, MacroBindingSite)> { if candidates.is_some_and(|candidates| !candidates.may_bind(name)) { return Vec::new(); } let resolved = |line: usize, declaration: &str| module_resolved(path, line, declaration); let verified = |krate: &str| macro_root_verified_in_contexts(path, krate, index, roots); // #14115: an assertion-context name is read in the union's trust context, // as the retained workspace sites are, so a call to another standard // macro is a wrapper only when that macro is itself bound in this file. let names = assertion_context_macros(); let mut sites = if names.contains(&name) { trusted_macro_binding_site_sets( source, index.macro_scope_crates(), &names, &[name], &resolved, &verified, ) .1 } else { trusted_macro_binding_sites( source, index.macro_scope_crates(), &[name], &resolved, &verified, ) }; bind_literal_macro_use_exports(path, &mut sites, index, roots); sites } /// Enrich an existing ambiguity with a negative-only local export witness. /// Every approved consumer placement must bind the same library export; an /// incomplete placement or lookup leaves the original ambiguity untouched. /// Both the retained scan and per-test query use this one decision. fn bind_literal_macro_use_exports( path: &Path, sites: &mut [(String, MacroBindingSite)], index: &RustIndex, roots: &TargetRoots, ) { for (name, site) in sites { let MacroBindingKind::ExternMacroUse { item, krate } = &site.kind else { continue; }; let Some(contexts) = roots.binding_roots(path, site, index) else { continue; }; let mut witness = None; let complete = !contexts.is_empty() && contexts.iter().all(|consumer| { let Some(export) = index .member_crates .imported_literal_macro_export(consumer, krate, name) else { return false; }; if witness.as_ref().is_some_and(|previous| *previous != export) { return false; } witness = Some(export); true }); if complete && let Some((exporter, line)) = witness { site.kind = MacroBindingKind::MacroUseExport { item: item.clone(), exporter, line, }; } } } /// A closed placement set is required to certify a trusted import. The /// recorded DAG is still useful for local availability when unrelated /// unresolved syntax disables placement; it cannot certify a partial set. fn macro_root_verified_in_contexts( path: &Path, krate: &str, index: &RustIndex, roots: &TargetRoots, ) -> bool { if roots.disabled { return false; } let Some(context) = index.execution_context(path) else { return false; }; if !context.roots.is_disjoint(&roots.tainted) { return false; } // Import authority needs every approved placement, not a uniquely // recognized Cargo target. Unlinked source stems retain their physical // manifest check; they still cannot establish positive owner identity. std::iter::once(path) .chain(context.roots.iter().map(PathBuf::as_path)) .all(|file| { if krate == "serde_json" { index.drop_in_manifests.verified_literal_json(file) } else { index.drop_in_manifests.verified_root(file, krate) } }) } /// Whether the file's own physical manifest resolves `krate` to the drop-in /// package, with no placement. Names a limit only; it never certifies a /// binding for credit (#12886). `std` and `core` roots keep their existing /// unplaced handling; only a drop-in crate name widens here. fn own_manifest_verifies_root(path: &Path, krate: &str, index: &RustIndex) -> bool { if krate == "serde_json" { index.drop_in_manifests.verified_literal_json(path) } else { index.drop_in_manifests.verified_root(path, krate) } } /// Trusted macro names some workspace file may rebind for every test, and /// the scoped sites (an inline module or block) kept per file. /// /// Parses workspace files, so on a warm `ripr check` of a large workspace /// this scan dominated wall time (37% on ripr-swarm). Files are independent, /// so the scan runs on the rayon pool; the ordered collect keeps each file's /// scoped sites in source order. /// /// #8255: the pass also retains, per trusted name, the earliest unscoped /// rebinding and may-rebind sites (workspace-wide and per crate-local /// root), so a refused assertion names its site from this pass instead of /// rescanning the workspace per (name, test root). fn trusted_macro_sites_in( index: &RustIndex, roots: &TargetRoots, module_resolved: &(dyn Fn(&Path, usize, &str) -> bool + Sync), ) -> ( BTreeSet, ScopedMacroBindings, CrateMacroBindings, WorkspaceMacroSiteIndex, ) { let mut global = BTreeSet::new(); let mut scoped = ScopedMacroBindings::new(); // A crate-local site in a recognized target root other than the test's // (a bench's `#[macro_use] extern crate bencher;`) is kept per root. let mut by_root = CrateMacroBindings::new(); let mut retained = WorkspaceMacroSiteIndex::default(); // One foreign glob import, `#[macro_use]` or unparsable file makes // every trusted name ambiguous, and most workspaces have one. Scan // the files that can do that first; once every name is ambiguous for // every test, no later file (scoped sites included) changes an answer, // so the rest are skipped. A refusal that needs a site completes the // retained scan once instead (#8255). let shared = &index.call_identity_memos.macro_site_scans; absorb_macro_sites( &shared.scan(ScanPart::Likely, index, roots, module_resolved), &mut global, &mut scoped, &mut by_root, &mut retained, roots, index, ); if global.len() < assertion_context_macros().len() { absorb_macro_sites( &shared.scan(ScanPart::Rest, index, roots, module_resolved), &mut global, &mut scoped, &mut by_root, &mut retained, roots, index, ); retained.complete = true; } (global, scoped, by_root, retained) } /// One indexed file ready for the trusted-macro site scan: its path, source /// and stored [`MacroBindingCandidates`]. type MacroScanFile<'a> = (&'a PathBuf, &'a str, Option<&'a MacroBindingCandidates>); /// The scan-order partition behind [`trusted_macro_sites_in`]: files that /// may saturate the ambiguity on their own, then the rest, each in path /// order. #8255 recomputes it for the one on-demand completion of the /// retained sites; the partition reads no file contents beyond cheap /// substring checks. fn partition_macro_scan_files( index: &RustIndex, ) -> (Vec>, Vec>) { index .files() .iter() .map(|(path, facts)| { let data = facts.data(); (path, data.source.as_ref(), data.macro_candidates.as_deref()) }) .partition(|(_, source, _)| may_saturate_macro_ambiguity(source)) } #[derive(Default)] struct ScannedMacroSites { ambiguities: Vec<(PathBuf, String, MacroBindingSite)>, retained: Vec<(PathBuf, String, usize, MacroBindingSite)>, } fn is_uncompiled_lexical_source(facts: FileFactsView<'_>) -> bool { facts.used_lexical_fallback && facts.role_provenance.outside_module_tree } /// One parse per candidate file in the bounded pass. Singleton queries share /// that tree/index, and stored candidates prune impossible names. fn scan_macro_sites( files: &[MacroScanFile<'_>], index: &RustIndex, roots: &TargetRoots, module_resolved: &(dyn Fn(&Path, usize, &str) -> bool + Sync), own_manifest_when_unplaced: bool, ) -> ScannedMacroSites { #[cfg(test)] { use std::hash::{Hash, Hasher}; let fanned_out = scan_fans_out(); if let Ok(mut log) = SCAN_LOG.lock() { for (_, source, _) in files { let mut hasher = std::collections::hash_map::DefaultHasher::new(); source.hash(&mut hasher); log.push((hasher.finish(), fanned_out)); } } } let names = assertion_context_macros(); let scan_file = |(path, source, candidates): &MacroScanFile<'_>| { // Composition established that this parser-refused text cannot be // compiled. Its fallback cannot make a real test's macro ambiguous. if index .files() .get(path) .is_some_and(is_uncompiled_lexical_source) { return None; } // A file whose stored candidates rule out every trusted name // reports no site, so it is not parsed. if !candidates.is_none_or(MacroBindingCandidates::may_bind_any_trusted) { return None; } Some({ let singleton_names: Vec<_> = names .iter() .copied() .filter(|name| candidates.is_none_or(|c| c.may_bind(name))) .collect(); let (union, singleton) = trusted_macro_binding_site_sets( source, index.macro_scope_crates(), &names, &singleton_names, &|line, declaration| module_resolved(path, line, declaration), &|krate| { macro_root_verified_in_contexts(path, krate, index, roots) || (own_manifest_when_unplaced && roots.disabled && !matches!(krate, "std" | "core") && own_manifest_verifies_root(path, krate, index)) }, ); ((*path).clone(), union, singleton) }) }; let per_file: Vec<_> = map_scans(files, scan_file).into_iter().flatten().collect(); let mut scanned = ScannedMacroSites::default(); for (path, mut union, mut singleton) in per_file { bind_literal_macro_use_exports(&path, &mut union, index, roots); bind_literal_macro_use_exports(&path, &mut singleton, index, roots); scanned.ambiguities.extend( union .into_iter() .map(|(name, site)| (path.clone(), name, site)), ); scanned.retained.extend( singleton .into_iter() .enumerate() .map(|(position, (name, site))| (path.clone(), name, position, site)), ); } scanned } /// Both initial absorption and deferred completion exclude every scoped site. fn retain_macro_sites( sites: &[(PathBuf, String, usize, MacroBindingSite)], retained: &mut WorkspaceMacroSiteIndex, roots: &TargetRoots, index: &RustIndex, ) { for (path, name, position, site) in sites { if site.scope.is_some() { continue; } if module_confined(site, path, roots, index) { let binding = retained.by_module.entry(path.clone()).or_default(); binding.roots = roots.roots(path, index); binding .sites .entry(name.clone()) .or_default() .absorb(path, *position, site); continue; } if let Some(contexts) = roots.binding_roots(path, site, index) { for root in contexts { retained .by_root .entry(root) .or_default() .entry(name.clone()) .or_default() .absorb(path, *position, site); } } else { retained .global .entry(name.clone()) .or_default() .absorb(path, *position, site); } } } #[cfg(test)] thread_local! { /// What the last [`map_scans`] on this thread decided: `Some(true)` when /// it took the rayon branch, `Some(false)` when it took the in-line branch. static LAST_SCAN_FAN_OUT: std::cell::Cell> = const { std::cell::Cell::new(None) }; } /// Maps `scan` over `items` in order, on the rayon pool only where /// [`nested_parallelism_allowed`]. Every production scan that can be reached /// from classification goes through here, so that guard has one seam (the /// `#[cfg(test)]` oracle `workspace_macro_binding_site` keeps its own copy). fn map_scans(items: &[T], scan: impl Fn(&T) -> R + Sync + Send) -> Vec { if scan_fans_out() { #[cfg(test)] LAST_SCAN_FAN_OUT.with(|last| last.set(Some(true))); items.par_iter().map(scan).collect() } else { #[cfg(test)] LAST_SCAN_FAN_OUT.with(|last| last.set(Some(false))); items.iter().map(scan).collect() } } thread_local! { /// Set while [`OwnerPinSyntax::prime_workspace_macro_scan`] runs on a /// classify-pool thread before any probe is queued (#9211). static PRIMED_SCAN_FAN_OUT: std::cell::Cell = const { std::cell::Cell::new(false) }; } /// Lets the priming scan fan out over the pool it runs on. Safe where /// [`nested_parallelism_allowed`] refuses: no sibling probe is queued yet, so /// the blocked thread has nothing to steal that could need the memo lock it /// holds (#8756). struct PrimedScanFanOut(bool); impl PrimedScanFanOut { fn enter() -> Self { Self(PRIMED_SCAN_FAN_OUT.with(|flag| flag.replace(true))) } } impl Drop for PrimedScanFanOut { fn drop(&mut self) { PRIMED_SCAN_FAN_OUT.with(|flag| flag.set(self.0)); } } /// Whether a production macro-site scan on this thread maps over the pool. fn scan_fans_out() -> bool { nested_parallelism_allowed() || PRIMED_SCAN_FAN_OUT.with(std::cell::Cell::get) } /// Test witness (#9211): the `(source hash, fanned out)` of every file a /// [`scan_macro_sites`] call mapped, from any thread. #[cfg(test)] pub(in crate::analysis) static SCAN_LOG: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); /// Whether a scan may fan out on the rayon pool. A probe classified on a pool /// worker already runs beside its siblings, and a worker blocked in a nested /// `par_iter` steals sibling probes onto its own stack while it may hold a /// memo lock that those probes need (#8756), which `SyncMemo` cannot survive. /// Scans reached from classification therefore run in line. pub(in crate::analysis) fn nested_parallelism_allowed() -> bool { rayon::current_thread_index().is_none() } /// Route scanned sites into the ambiguity name sets, the scoped-site map, /// the per-root name sets and #8255's retained earliest sites. Sites arrive /// in path then source order; scoped sites never reach the retained index, /// exactly as the replaced per-(name, test root) scan skipped them. #[allow( clippy::too_many_arguments, reason = "one ordered fold over four run-scoped ambiguity outputs and the retention index" )] fn absorb_macro_sites( sites: &ScannedMacroSites, global: &mut BTreeSet, scoped: &mut ScopedMacroBindings, by_root: &mut CrateMacroBindings, retained: &mut WorkspaceMacroSiteIndex, roots: &TargetRoots, index: &RustIndex, ) { retain_macro_sites(&sites.retained, retained, roots, index); for (path, name, site) in &sites.ambiguities { if site.scope.is_some() { scoped .entry(path.clone()) .or_default() .push((name.clone(), site.clone())); continue; } if module_confined(site, path, roots, index) { let binding = retained.by_module.entry(path.clone()).or_default(); binding.roots = roots.roots(path, index); binding.names.insert(name.clone()); continue; } if let Some(contexts) = roots.binding_roots(path, site, index) { for root in contexts { by_root.entry(root).or_default().insert(name.clone()); } } else { global.insert(name.clone()); } } } /// Whether the manifests in the own scope make a directory name an unreliable /// stand-in for the crate an import names (RIPR-SPEC-0352). Fails closed: a /// renamed dependency, an unreadable manifest, or a matching directory that /// holds a crate of another name sends the import to every package. fn own_scope_manifests_defeat_names( index: &RustIndex, packages: &BTreeSet, directories: &BTreeMap, roots: &BTreeSet, ) -> bool { let Some(workspace) = index.drop_in_manifests.root() else { return true; }; let read = |directory: &str| { std::fs::read_to_string(workspace.join(directory).join("Cargo.toml")).ok() }; let renames = |text: &str| { text.match_indices("package").any(|(at, _)| { let before = text[..at].chars().next_back(); let after = text[at + 7..].trim_start(); !before.is_some_and(|c| c.is_ascii_alphanumeric() || c == '_') && after.starts_with('=') }) }; let mut scope: Vec<&str> = packages.iter().map(String::as_str).collect(); scope.push(""); for directory in scope { match read(directory) { Some(text) if !renames(&text) => {} // A workspace root with no package of its own may have no manifest // in a narrowed checkout; a package directory without one cannot // be trusted. None if directory.is_empty() => {} _ => return true, } } for (directory, name) in directories { if !roots.contains(name) { continue; } let Some(table) = read(directory).and_then(|text| text.parse::().ok()) else { return true; }; let declared = |section: &str| { table .get(section) .and_then(|section| section.get("name")) .and_then(toml::Value::as_str) .map(|name| name.replace('-', "_")) }; if declared("package").as_ref() != Some(name) && declared("lib").as_ref() != Some(name) { return true; } } false } /// The first path segment of every `use` item and `extern crate` in `source`, /// read lexically: a name inside a comment or string only adds a segment, /// which widens the own scope and never narrows it. fn imported_crate_roots(source: &str, roots: &mut BTreeSet) { let ident = |text: &str| -> Option { let text = text.trim_start().trim_start_matches("::").trim_start(); let end = text .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) .unwrap_or(text.len()); (end > 0).then(|| text[..end].to_string()) }; // Comments are masked and `use`/`extern crate` are found as whole words, so // a tab, newline or comment between the keyword and the path is still read. let masked = mask_comments_and_strings(source); for offset in whole_word_offsets(&masked, "use") { let statement = masked[offset + 3..].split(';').next().unwrap_or_default(); for part in statement.split([',', '{']) { roots.extend(ident(part)); } } for offset in whole_word_offsets(&masked, "extern") { let rest = masked[offset + 6..].trim_start(); if let Some(rest) = rest.strip_prefix("crate") && rest.starts_with(|c: char| c.is_whitespace()) { roots.extend(ident(rest)); } } } /// Scan-order hint for the trusted-macro ambiguity scan, never its answer: /// a glob import not rooted at `super`/`self`/`crate`, `#[macro_use]` or /// `no_implicit_prelude`. `use super::*;` in nearly every test module is /// workspace-owned and would otherwise put every file first. fn may_saturate_macro_ambiguity(source: &str) -> bool { source.contains("macro_use") || source.contains("no_implicit_prelude") || source.match_indices("::*").any(|(offset, _)| { let before = source[..offset].trim_end_matches(|character: char| { character.is_ascii_alphanumeric() || character == '_' }); !matches!(&source[before.len()..offset], "super" | "self" | "crate") }) } /// Whether a test file imports a name from outside the workspace; the /// caller supplies its run-scoped memo. pub(in crate::analysis) type ForeignImport<'a> = &'a dyn Fn(&Path, &str) -> bool; enum PinCall { /// `name(..)`: the owner is a module-level function. Bare, /// `recv.name(..)`: the receiver's type must be one of `receivers`, and /// a trait method also needs its trait in the test's scope. Method { receivers: Vec, trait_scope: Option, }, /// `T::name(..)` (#6617, RIPR-SPEC-0172): the owner is an associated /// function (no `self`) of an inherent `impl T`, and the test must name /// the owner's own `T` through a direct import of the owner's library. /// A bare `name(..)` never takes it: that call names a module-level /// function, never an associated one. Associated { type_name: String }, } /// Which call syntax [`other_definition_competes`] judges. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum CallKind { /// `name(..)` or a module path `a::b::name(..)`. Bare, /// `recv.name(..)`. Method, /// `T::name(..)` on an inherent associated function (#6617). Associated, } impl PinCall { fn kind(&self) -> CallKind { match self { Self::Bare => CallKind::Bare, Self::Method { .. } => CallKind::Method, Self::Associated { .. } => CallKind::Associated, } } } /// A trait method is callable with method syntax only while its trait is /// in scope. struct TraitScope { trait_name: String, } #[derive(Clone, Debug, PartialEq, Eq)] enum ReceiverType { /// A struct, enum or union declared in the workspace. Named(String), /// `&[u8]`, read from `&[..][..]` or `&b".."[..]`. ByteSlice, } enum ReturnPathGate { /// The changed expression is the owner's only exit. Any, /// #13037 Defect A: the changed exit (`return ;` or the tail) is a /// whole decimal scalar literal and every other exit builds a different /// whole decimal scalar literal, so the changed exit is the owner's only /// source of ``. A passing exact pin at `` on an owner call /// then proves the changed exit ran: any other exit would return its own /// distinct literal and fail the pin. A second source of the same /// literal, a parameter/computed exit (which may alias `` under /// some input), a `?`, or a nested-closure return refuses (fail closed). EarlyScalar { literal: String }, /// The pinned value must start with this constructor. `Head("Err")` /// comes only from an early `return Err(..)`, and like `EarlyHead` it /// refuses an owner file that binds `Ok` or `Err` as a value. Head(&'static str), /// #7581: a changed early `return Some(..)` / `return Ok(..)` beside /// exits that build only `None` / `Err(..)`. Admits like `Head`; the /// owner's file must not bind `None`, `Some`, `Ok` or `Err`, since a /// rebound opposite name could build a second `Some` / `Ok` exit. EarlyHead(&'static str), /// The pinned value must be exactly this unit variant (`None`). Exact(&'static str), /// #7063: a changed early `return Err(Type::Variant ..);` that is the /// owner's only exit building `Type::Variant`, beside other exits that /// build only `Ok(..)` or another variant of `Type`. The pinned value /// must be one `Err(..)` call constructing that same `Type::Variant`, and /// `Type` is a workspace enum compared by its derived `==`, so a /// whole-value pin compares the variant's payload too. /// /// `siblings` are the other variants the remaining exits build; each, /// like `variant`, must be a declared variant of `Type` /// ([`error_enum_admits_variant_pin`]), so an associated constant /// (`Type::NO_EQUALS`) never passes for a sibling. ErrVariant { qualifier: String, variant: String, siblings: Vec, }, /// #6692: a field of a hand-written `Clone::clone`'s returned struct /// literal. The pinned value must be the clone's own receiver /// (`assert_eq!(w.clone(), w)`), compared through a derived /// `PartialEq`, so every field of the clone is compared with the /// original's. CloneReceiver, /// RIPR-SPEC-0265 rule 2: the changed tail is the owner's whole body, /// `P.iter().A(|x| E)[.T()]`, whose closure runs once per element of /// the parameter at `position`. The pinned call must pass that /// parameter a non-empty literal sequence, so the closure runs at least /// once on the pinned input. A `Result, ..>` collect stops at the /// first `Err` and discards the earlier `Ok` values, so it also needs the /// pinned value to be an `Ok(..)` that every element reached /// (`requires_ok`, #9490). Adaptor { position: usize, requires_ok: bool }, /// RIPR-SPEC-0265 rule 5: the changed tail is the owner's whole body and /// one closure over its own parameters. The pinned operand must apply /// the returned closure to `arity` distinct nonzero numeric literals, so /// the closure runs once and the bounded typed body discriminates the /// supported arithmetic replacements, including through literal captures. ReturnedClosure { arity: usize, arithmetic: returned_closure::ArithmeticPin, }, /// RIPR-SPEC-0360: the changed statement adds into (or subtracts from) a /// zero-initialized local that the owner returns, once per element of the /// slice-like parameter at `position`. The pinned call must pass that /// parameter a non-empty literal sequence, and the pinned value must be /// a nonzero integer literal: from zero, a nonzero result separates the /// update from a flipped sign, a product, a quotient and a deleted /// statement. LoopAccumulator { position: usize, /// RIPR-SPEC-0360 call-in-term: the callee the pinned run folds through. term: Option, }, /// RIPR-SPEC-0197 rule 3: the changed tail is the owner's whole body and /// one pure `&&` or `||` chain over its parameters. The pinned call /// must evaluate every operand on some run. ShortCircuit(short_circuit::ShortCircuitTail), /// #9766: literal helper data reaches a receiver-field tuple projection. FixtureReceiver(fixture_receiver::FixtureReceiver), /// RIPR-SPEC-0225: field `field` of the `type_name { .. }` literal the /// owner returns (inside `wrapper(..)` when the owner returns /// `Result`/`Option`). The pinned value must be a literal of that type, /// in the same wrapper, naming the field with an independent value. WholeValueField(WholeValueField), /// #14387: the changed line is `return ;` inside one guard /// `if COND { return ..; }` of an owner the closed integer subset reads /// in both versions (`owner_value::ClosedChange`). The pinned call must /// pass literal arguments on which the two versions provably return /// different values, and the pinned value must be one of the two, so the /// exact pin fails on one version. Any shape the subset cannot evaluate /// refuses. ClosedGuardReturn { change: super::owner_value::ClosedChange, /// The changed line's old text as the gate rebuilt it, which the /// diff's own old line must match. old_line: String, }, } /// The owner-side facts [`ReturnPathGate::WholeValueField`] checks a test's /// expected literal against. struct WholeValueField { type_name: String, field: String, wrapper: Option<&'static str>, /// The field is declared `String`, so `"x".into()` converts through the /// standard library, not a workspace `From` impl. field_is_string: bool, /// CamelCase names the workspace gives a `const`, `static` or `fn`: an /// expected value naming one may be computed, not a constructor. computed_names: BTreeSet, /// Struct, enum, union and variant names the workspace declares, plus /// the standard `None`/`Some`/`Ok`/`Err`: a bare CamelCase name outside /// this set may be a test-local binding (`let Expected = ..;`). constructor_names: BTreeSet, /// `String` may name a workspace item (`mod String`, a type, fn, const, /// static, trait, macro or variant of that name, a rename to it, or a /// non-std `use` of it), so an expected `String::from(..)` is not the /// standard conversion and gives no credit (#7066 review). string_from_may_be_rebound: bool, /// #12394 item 5: the changed field's initializer before and after the /// diff, when both read as the closed integer subset. A pinned field value /// that neither computes for the call fails on both versions. closed: Option>, } /// #8480: records constructed in exit positions of `body`: the block /// tail and every `return` value of the owner itself (a `return` inside /// a nested closure or item returns from that closure or item, not the /// owner), plus records a `let` or assignment binds and an exit value /// then names. Deduplicated by source range. fn exit_position_records(body: &ast::BlockExpr) -> Vec { let mut records: Vec = Vec::new(); let mut roots: Vec = Vec::new(); if let Some(tail) = body.stmt_list().and_then(|list| list.tail_expr()) { roots.push(tail); } for node in body.syntax().descendants() { let Some(returned) = ast::ReturnExpr::cast(node) else { continue; }; let nested = returned .syntax() .ancestors() .take_while(|ancestor| ancestor != body.syntax()) .any(|ancestor| { ast::ClosureExpr::can_cast(ancestor.kind()) || ast::Fn::can_cast(ancestor.kind()) }); if !nested && let Some(value) = returned.expr() { roots.push(value); } } for root in &roots { collect_exit_records(root, &mut records); } // A record bound by a `let` or an assignment becomes the result // when an exit value names the binding; follow such names through // binding initializers to a fixed point. Bindings no exit value // names stay local. let mut sought: BTreeSet = roots .iter() .flat_map(|root| syntax_identifiers(root.syntax())) .collect(); let mut bindings: Vec<(String, ast::Expr)> = Vec::new(); for node in body.syntax().descendants() { if let Some(binding) = ast::LetStmt::cast(node.clone()) && let Some(initializer) = binding.initializer() { let names: Vec = binding .pat() .map(|pat| { pat.syntax() .descendants() .filter_map(ast::IdentPat::cast) .filter_map(|ident| ident.name().map(|name| name.text().to_string())) .collect() }) .unwrap_or_default(); // A pattern binding no name (`let _ = ..`, a literal // pattern) cannot carry the value into an exit value. for name in names { bindings.push((name, initializer.clone())); } } if let Some(binary) = ast::BinExpr::cast(node) && matches!(binary.op_kind(), Some(ast::BinaryOp::Assignment { .. })) && let (Some(lhs), Some(rhs)) = (binary.lhs(), binary.rhs()) && let ast::Expr::PathExpr(path) = unwrap_exit_parens(&lhs) && let Some(name) = path .path() .and_then(|path| path.segment()) .map(|segment| segment.syntax().text().to_string()) { bindings.push((name, rhs)); } } let mut resolved: BTreeSet<(usize, usize)> = BTreeSet::new(); loop { let mut progressed = false; for (name, initializer) in &bindings { let range = initializer.syntax().text_range(); let key = (usize::from(range.start()), usize::from(range.end())); if !sought.contains(name) || !resolved.insert(key) { continue; } collect_exit_records(initializer, &mut records); for identifier in syntax_identifiers(initializer.syntax()) { sought.insert(identifier); } progressed = true; } if !progressed { break; } } records } fn syntax_identifiers(node: &SyntaxNode) -> Vec { node.descendants_with_tokens() .filter_map(|element| element.into_token()) .filter(|token| token.kind() == ra_ap_syntax::SyntaxKind::IDENT) .map(|token| token.text().to_string()) .collect() } fn push_record(record: &ast::RecordExpr, records: &mut Vec) { let range = record.syntax().text_range(); if !records .iter() .any(|known| known.syntax().text_range() == range) { records.push(record.clone()); } } fn collect_all_records(node: &SyntaxNode, records: &mut Vec) { for descendant in node.descendants() { if let Some(record) = ast::RecordExpr::cast(descendant) { push_record(&record, records); } } } fn unwrap_exit_parens(expression: &ast::Expr) -> ast::Expr { let mut expression = expression.clone(); while let ast::Expr::ParenExpr(paren) = &expression { let Some(inner) = paren.expr() else { break; }; expression = inner; } expression } /// Collect records in `expression`, which sits in an exit position. /// Only wrappers that carry a value into the result are followed; /// every other shape in an exit position fails closed and contributes /// all of its records. fn collect_exit_records(expression: &ast::Expr, records: &mut Vec) { match expression { ast::Expr::RecordExpr(record) => { push_record(record, records); if let Some(fields) = record.record_expr_field_list() { for field in fields.fields() { if let Some(value) = field.expr() { collect_exit_records(&value, records); } } if let Some(spread) = fields.spread() { collect_exit_records(&spread, records); } } } ast::Expr::ParenExpr(paren) => { if let Some(inner) = paren.expr() { collect_exit_records(&inner, records); } } ast::Expr::BlockExpr(block) => { if let Some(tail) = block.stmt_list().and_then(|list| list.tail_expr()) { collect_exit_records(&tail, records); } } ast::Expr::IfExpr(if_expr) => { if let Some(then_branch) = if_expr.then_branch() { collect_exit_records(&ast::Expr::BlockExpr(then_branch), records); } match if_expr.else_branch() { Some(ast::ElseBranch::Block(block)) => { collect_exit_records(&ast::Expr::BlockExpr(block), records); } Some(ast::ElseBranch::IfExpr(else_if)) => { collect_exit_records(&ast::Expr::IfExpr(else_if), records); } None => {} } } ast::Expr::MatchExpr(match_expr) => { if let Some(arms) = match_expr.match_arm_list() { for arm in arms.arms() { if let Some(value) = arm.expr() { collect_exit_records(&value, records); } } } } ast::Expr::CallExpr(call) => { if let Some(args) = call.arg_list() { for arg in args.args() { collect_exit_records(&arg, records); } } } ast::Expr::TupleExpr(tuple) => { for field in tuple.fields() { collect_exit_records(&field, records); } } ast::Expr::ArrayExpr(array) => { for element in array.exprs() { collect_exit_records(&element, records); } } ast::Expr::ReturnExpr(returned) => { if let Some(value) = returned.expr() { collect_exit_records(&value, records); } } ast::Expr::BreakExpr(break_expr) => { if let Some(value) = break_expr.expr() { collect_exit_records(&value, records); } } ast::Expr::TryExpr(try_expr) => { if let Some(value) = try_expr.expr() { collect_exit_records(&value, records); } } ast::Expr::AwaitExpr(await_expr) => { if let Some(value) = await_expr.expr() { collect_exit_records(&value, records); } } ast::Expr::PathExpr(_) | ast::Expr::Literal(_) | ast::Expr::ContinueExpr(_) | ast::Expr::UnderscoreExpr(_) => {} other => collect_all_records(other.syntax(), records), } } /// A changed whole returned closure can confirm observation only through /// its admitted application pin, even when the arithmetic model is unknown. pub(in crate::analysis) fn returned_closure_pin_required( probe: &Probe, owner: &FunctionSummary, ) -> bool { matches!(probe.family, ProbeFamily::ReturnValue) && returned_closure::owner_returned_closure_tail(owner) .is_some_and(|tail| tail.tail_is(&probe.expression)) } impl OwnerReturnPin { /// The owner's changed value is its unconditional whole boolean tail. /// A wrapper pin may reuse boundary pairing only for this shape; the /// short-circuit and adaptor paths require their own pinned-input gates. pub(in crate::analysis) fn is_unconditional_boolean_tail(&self) -> bool { self.returns_bool && matches!(self.path, ReturnPathGate::Any) } /// #14387: whether a guard-return pin's rebuilt old line is the diff's own /// old text for the owner's only changed line (`sole_change`). Every /// other gate does not read it and answers `true`. pub(in crate::analysis) fn closed_guard_old_line_matches( &self, sole_change: Option<&str>, ) -> bool { match &self.path { ReturnPathGate::ClosedGuardReturn { old_line, .. } => { sole_change.is_some_and(|old| old.trim() == old_line.trim()) } _ => true, } } /// The owner-side gates: `None` when the probe is not a return value /// (or a changed `return Err(..)`, filed as `error_path`), /// the owner's declaration or return paths are not established, or /// another workspace definition could take a call by the owner's name. pub(in crate::analysis) fn establish( probe: &Probe, owner: &FunctionSummary, index: &RustIndex, ) -> Option { if matches!(probe.family, ProbeFamily::FieldConstruction) { // A `clone` owner is #6692's alone: which `Clone` impl a call // runs is that path's question, not one this one asks. return if owner.name == "clone" { Self::establish_clone_field(probe, owner, index) } else { Self::establish_whole_value_field(probe, owner, index) .or_else(|| Self::establish_err_variant_field(probe, owner, index)) }; } if !owner.item.has_body { return None; } let returns_bool = declared_return_type(&owner.body).as_deref() == Some("bool"); // A predicate that is a bool owner's whole tail is the owner's return // value, so the same pin observes it. match probe.family { ProbeFamily::ReturnValue | ProbeFamily::ErrorPath => {} ProbeFamily::Predicate if returns_bool => {} _ => return None, } let parser_backed = index .files() .get(&owner.file) .is_some_and(|facts| !facts.used_lexical_fallback); if !parser_backed { return None; } let name = owner.name.as_str(); let changed_line = probe.location.line.checked_sub(owner.start_line)?; let path = match return_path_gate_from( &owner.body, &probe.expression, probe.before.as_deref(), changed_line, ) { Some(path) => path, // #9870: an exact Result.map rewrite needs an Ok pin, which // establishes that its callback ran. SPEC-0265's iterator tail // instead reads the pinned input on the test side. // This fallback implements that spec's amendment of the pin's // closure refusal ("a closure in the tail no longer refuses it // on this shape") and must stay unguarded: 0265's keeping-pair // registry is what tells a closure-carried change apart there. None if matches!(probe.family, ProbeFamily::ReturnValue) && let Some(accumulator) = crate::analysis::syntax::loop_accumulator::loop_accumulator_at( &owner.body, changed_line, ) // A call term needs its owner type, or it has no pin at all. && let Some(term) = call_term_fold::admit(accumulator.term.clone(), owner) => { ReturnPathGate::LoopAccumulator { position: accumulator.walked_position, term, } } None if matches!(probe.family, ProbeFamily::ReturnValue) => { if result_map::admitted_rewrite(probe, owner, index).is_some() { ReturnPathGate::Head("Ok") } else { closure_adaptor::admitted_owner_adaptor_tail(owner, index) .filter(|tail| tail.tail_is(&probe.expression)) .map(|tail| ReturnPathGate::Adaptor { position: tail.position, requires_ok: tail.collects_result(), }) .or_else(|| { fixture_receiver::FixtureReceiver::establish( owner, &probe.expression, probe.before.as_deref(), index, ) .map(ReturnPathGate::FixtureReceiver) }) // RIPR-SPEC-0265 rule 5: a returned closure applied in the // pinned expression. .or_else(|| { returned_closure::owner_returned_closure_tail(owner) .filter(|tail| tail.tail_is(&probe.expression)) .and_then(|tail| { Some(ReturnPathGate::ReturnedClosure { arity: tail.arity, arithmetic: returned_closure::ArithmeticPin::establish( owner, index, )?, }) }) }) // #14387: a changed early `return` inside a guard of // an owner the closed subset reads in both versions. .or_else(|| { closed_guard_return( &owner.body, name, changed_line, &probe.expression, probe.before.as_deref(), ) })? } } None => return None, }; // #7063: an early error-variant pin reads the other exits' variants // of the owner's own error enum, and the pinned `==` must compare the // variant's payload. // A payload-carrying `Err(Type::Variant ..)` of a workspace enum // under the `Err` head gate is held to the same variant rules: its // payload is pinned only through `Type`'s derived `==` // (RIPR-SPEC-0197 early error-variant pins, rule 3). An associated // function call (`Err(String::from(..))`) keeps the `Err` head gate. let path = match path { ReturnPathGate::Head("Err") => match payload_variant_construction(&probe.expression) .filter(|(qualifier, variant)| { workspace_enum_declares_variant(qualifier, variant, index) }) { Some((qualifier, variant)) => ReturnPathGate::ErrVariant { qualifier, variant, siblings: Vec::new(), }, None => ReturnPathGate::Head("Err"), }, other => other, }; if let ReturnPathGate::ErrVariant { qualifier, variant, siblings, } = &path && !error_enum_admits_variant_pin(qualifier, variant, siblings, owner, index) { return None; } // The early `Some`/`Ok`/`Err` gates read the other exits' `None`, // `Err(..)` and `Ok(..)` as the prelude variants; a `const None` or // `fn Ok` in the owner's file can build a second source of the // changed value under that spelling (#7581 and #7712 reviews). if path.prelude_names().iter().any(|name| { index .files() .get(&owner.file) .is_none_or(|facts| source_binds_value_name(&facts.source, name)) }) { return None; } if matches!(path, ReturnPathGate::ClosedGuardReturn { .. }) && !owner_file_keeps_integer_names(owner, index) { return None; } let call = pin_call(owner, index)?; // #6544: a bare call's same-package module-level rivals are settled // per test by the import or path that spells the call; every other // competing definition still refuses the pin here. let identity = match call.kind() { CallKind::Bare => super::call_identity::shared_owner_call_identity(index, owner), CallKind::Method | CallKind::Associated => None, }; if other_definition_competes(owner, index, call.kind(), identity.as_deref()) { return None; } let walked_positions = closure_adaptor::iterated_slice_positions(&owner.body, &probe.expression); let tuple_projection = matches!(path, ReturnPathGate::Any) .then(|| tuple_projection_type(owner, probe)) .flatten(); let tuple_change = tuple_projection .as_deref() .zip(probe.before.as_deref()) .map(|(type_name, before)| TupleChange { definition: owner.body.to_string(), changed_line, before: before.to_string(), self_is_type: matches!( &owner.item.container, FunctionContainer::Inherent { self_ty } | FunctionContainer::TraitImpl { self_ty, .. } if path_base_name(self_ty) == Some(type_name) ), }); let closed_owner = probe .before .as_deref() .filter(|_| matches!(call, PinCall::Bare)) .and_then(|before| { super::owner_value::ClosedChange::read(&owner.body, name, changed_line, before) }); let guard_operands = probe .before .as_deref() .filter(|_| returns_bool) .and_then(|before| { short_circuit::GuardOperandChange::read( &owner.body, probe.expression.trim().trim_end_matches(';').trim(), before, ) }); Some(Self { name: name.to_string(), call, path, walked_positions, returns_bool, returns_scalar: returns_primitive_scalar(owner, index), returns_integer: returns_primitive_scalar(owner, index) && declared_return_type(&owner.body) .is_some_and(|returned| INTEGER_TYPES.contains(&returned.as_str())), pointer_mask_gate: super::mask_pin::PointerMaskGate::for_owner( &probe.expression, name, &owner.body, index, ), pointer_return_change: crate::analysis::test_grip_evidence::PointerReturnChange::new( owner, probe.before.as_deref(), &probe.expression, ), tuple_projection, tuple_change, awaited: declares_async(owner, index), poll_helpers: if declares_async(owner, index) { super::poll_helper::verified_helpers(index) } else { BTreeSet::new() }, drop_plain: Self::returned_types_drop_plain(owner, index), owner_file: owner.file.clone(), owner_start_line: owner.start_line, trait_scope_by_file: SyncMemo::default(), identity, closed_owner, guard_operands, skip_current_literal_check: Cell::new(false), }) } /// Whether every record type constructed in an exit position of /// the owner has at most a plain `Drop` impl in the workspace /// (#8480). Exit positions are values that can become the function /// result: the block tail, a `return` value, branch and match-arm /// tails feeding one of those, and records nested in wrappers along /// such a path. Records built only in non-exit positions (let /// initializers that are not returned, statement expressions, /// conditions, loop bodies, statement call arguments) drop inside /// the owner and do not refuse. Shapes ripr cannot place in one of /// those positions fail closed and still count as exit positions. /// Types constructed in no exit position (scalar returns, calls) /// have nothing to refuse. pub(in crate::analysis) fn returned_types_drop_plain( owner: &FunctionSummary, index: &RustIndex, ) -> bool { let source = owner.body.as_str(); let Some(parse) = parse_clean_source_file(source) else { return false; }; let Some(function) = parse.tree().syntax().descendants().find_map(ast::Fn::cast) else { return false; }; let Some(body) = function.body() else { return false; }; exit_position_records(&body).iter().all(|record| { record .path() .and_then(|path| path.segment()) .is_some_and(|segment| { super::element_field_pin::drop_is_plain( index, &segment.syntax().text().to_string(), ) }) }) } /// #6692: the owner-side gates for a `field_construction` probe in a /// hand-written `impl Clone for T`. Established only when the changed /// line is a field of the struct literal that is `clone`'s only exit, /// `T` is declared once in the workspace with `#[derive(PartialEq)]` /// and has no hand-written `PartialEq` impl, no workspace trait is /// named `Clone`, and no other `fn clone` with a receiver competes. /// The test-side gate then requires `assert_eq!(recv.clone(), recv)`. fn establish_clone_field( probe: &Probe, owner: &FunctionSummary, index: &RustIndex, ) -> Option { if owner.name != "clone" || !owner.item.has_body || !owner.item.has_self_param { return None; } let FunctionContainer::TraitImpl { trait_path, self_ty, } = &owner.item.container else { return None; }; // The standard `Clone`: bare, or a `std`/`core` path; the owner's // file may not import, glob or rename `Clone` from elsewhere // (`impl dupe::Clone for Window`, `use dupe::Clone;`). let trait_path = trait_path.trim().trim_start_matches("::"); if !matches!( trait_path, "Clone" | "std::clone::Clone" | "core::clone::Clone" ) { return None; } // `extern crate other as std;` makes `std::clone::Clone` foreign. if let Some((root, _)) = trait_path.split_once("::") && workspace_renames_to(index, root) { return None; } let owner_source = index .files() .get(&owner.file) .filter(|facts| !facts.used_lexical_fallback) .map(|facts| facts.data().source.clone())?; if declaring_file_rebinds(&owner_source, "Clone", false, index) { return None; } // `impl Clone for W`: an instantiation of a generic type, // whose type parameters ripr does not substitute. if self_ty.contains('<') { return None; } let receiver = declared_receiver(self_ty, index)?; let ReceiverType::Named(type_name) = &receiver else { return None; }; let changed_line = probe.location.line.checked_sub(owner.start_line)?; let field = initialized_field_name(&probe.expression)?; if !clone_tail_literal_spans(&owner.body, type_name, changed_line, &probe.expression) || !field_compares_with_derived_equality(type_name, field, index) || derives_clone(type_name, index) || workspace_declares_trait(index, "Clone") || other_definition_competes(owner, index, CallKind::Method, None) { return None; } Some(Self { name: owner.name.clone(), call: PinCall::Method { receivers: vec![receiver], // `Clone` is in the prelude; a workspace `trait Clone` is // refused above and a foreign import in `admits`. trait_scope: None, }, path: ReturnPathGate::CloneReceiver, walked_positions: Vec::new(), returns_bool: false, returns_scalar: false, returns_integer: false, pointer_mask_gate: super::mask_pin::PointerMaskGate::Refuse, pointer_return_change: None, tuple_projection: None, tuple_change: None, closed_owner: None, guard_operands: None, skip_current_literal_check: Cell::new(false), awaited: declares_async(owner, index), poll_helpers: if declares_async(owner, index) { super::poll_helper::verified_helpers(index) } else { BTreeSet::new() }, drop_plain: Self::returned_types_drop_plain(owner, index), owner_file: owner.file.clone(), owner_start_line: owner.start_line, trait_scope_by_file: SyncMemo::default(), identity: None, }) } /// RIPR-SPEC-0225: the owner-side gates for a `field_construction` /// probe on a field of the struct literal the owner returns. The literal /// (or `Ok(..)`/`Some(..)` around it, matching the declared return type) /// is the owner's tail and only value exit, the changed line is one whole /// field initializer of it that evaluates on every input, and `==` on the /// literal's type compares that field by value (rules 3 and 4). fn establish_whole_value_field( probe: &Probe, owner: &FunctionSummary, index: &RustIndex, ) -> Option { if !owner.item.has_body || index .files() .get(&owner.file) .is_none_or(|facts| facts.used_lexical_fallback) { return None; } let changed_line = probe.location.line.checked_sub(owner.start_line)?; let field = initialized_field_name(&probe.expression)?; let tail = whole_value_tail(&owner.body, changed_line, field, &probe.expression)?; let type_name = if tail.type_name == "Self" { match &owner.item.container { FunctionContainer::Inherent { self_ty } | FunctionContainer::TraitImpl { self_ty, .. } if !self_ty.contains('<') => { path_base_name(self_ty)?.to_string() } _ => return None, } } else { tail.type_name }; let declared = declared_return_type(&owner.body)?; let names_type = |ty: &str| ty == type_name || ty == "Self"; let declared_matches = match tail.wrapper { None => names_type(&declared), Some(wrapper) => { let (path, arguments) = declared.split_once('<')?; let arguments = arguments.strip_suffix('>')?; let first = top_level_arguments(arguments).into_iter().next()?; let container = if wrapper == "Ok" { "Result" } else { "Option" }; path_base_name(path) == Some(container) && !type_declared_in_workspace(container, index) && names_type(first.trim()) } }; if !declared_matches || !field_compares_with_derived_equality(&type_name, field, index) { return None; } // The owner's file must name the workspace declaration: a `use // other::Config;` there makes the literal another crate's type. let owner_source = &index.files().get(&owner.file)?.source; if declaring_file_rebinds(owner_source, &type_name, true, index) || tail .wrapper .into_iter() .chain(tail.early_exit) .any(|constructor| wrapper_may_be_rebound(constructor, index)) { return None; } let field_is_string = derived_equality(&type_name, index).is_some_and(|(facts, _)| { facts.fields.iter().any(|candidate| { candidate.name.as_deref() == Some(field) && candidate.ty == "String" }) }); let field_ty = derived_equality(&type_name, index).and_then(|(facts, _)| { facts .fields .iter() .find(|candidate| candidate.name.as_deref() == Some(field)) .map(|candidate| candidate.ty.clone()) }); let closed = probe .before .as_deref() .zip(field_ty.as_deref()) .and_then(|(before, field_ty)| { super::owner_value::ClosedChange::read_field( &owner.body, &owner.name, changed_line, before, field, field_ty, ) .map(Box::new) }); let call = pin_call(owner, index)?; // #6617 keeps the associated-function pin to a return value: a // `T::new()` whole-value field pin is a separate claim. if matches!(call, PinCall::Associated { .. }) || other_definition_competes(owner, index, call.kind(), None) { return None; } Some(Self { name: owner.name.clone(), call, path: ReturnPathGate::WholeValueField(WholeValueField { type_name, field: field.to_string(), wrapper: tail.wrapper, field_is_string, computed_names: camel_case_value_items(index), constructor_names: declared_constructor_names(index), string_from_may_be_rebound: wrapper_may_be_rebound("String", index), closed, }), walked_positions: Vec::new(), returns_bool: false, returns_scalar: false, returns_integer: false, pointer_mask_gate: super::mask_pin::PointerMaskGate::Refuse, pointer_return_change: None, tuple_projection: None, tuple_change: None, closed_owner: None, guard_operands: None, skip_current_literal_check: Cell::new(false), awaited: declares_async(owner, index), poll_helpers: if declares_async(owner, index) { super::poll_helper::verified_helpers(index) } else { BTreeSet::new() }, drop_plain: Self::returned_types_drop_plain(owner, index), owner_file: owner.file.clone(), owner_start_line: owner.start_line, trait_scope_by_file: SyncMemo::default(), identity: None, }) } /// #7063: the owner-side gates for a `field_construction` probe on one /// field initializer of a changed early `return Err(Type::Variant { .. });` /// written on one line. The construction must pass the early /// error-variant gate ([`err_variant_gate`]), so a pin expecting /// `Err(Type::Variant { .. })` observes this return and, through the /// derived `==` of `Type`, compares the changed field. fn establish_err_variant_field( probe: &Probe, owner: &FunctionSummary, index: &RustIndex, ) -> Option { if !owner.item.has_body || index .files() .get(&owner.file) .is_none_or(|facts| facts.used_lexical_fallback) { return None; } let changed_line = probe.location.line.checked_sub(owner.start_line)?; initialized_field_name(&probe.expression)?; let initializer = collapse_whitespace(probe.expression.trim().trim_end_matches(',')); let statement = owner.body.lines().nth(changed_line)?.trim(); let construction = statement .strip_prefix("return ")? .trim() .strip_suffix(';')? .trim_end(); constructor_call_span(construction, "Err")?; let (qualifier, variant) = error_variant_key(construction)?; // One brace-delimited payload, closed right before the `Err(..)` // closes, whose top-level fields include the changed initializer. let masked = mask_comments_and_strings(construction); let open = masked.find('{')?; let close = masked.rfind('}')?; if masked.matches('{').count() != 1 || masked.matches('}').count() != 1 || close < open || masked[close + 1..].trim() != ")" { return None; } let names_field = top_level_arguments(&construction[open + 1..close]) .into_iter() .any(|field| collapse_whitespace(field) == initializer); if !names_field { return None; } let siblings = match return_path_gate_from(&owner.body, statement, None, changed_line)? { ReturnPathGate::Head("Err") => Vec::new(), ReturnPathGate::ErrVariant { siblings, .. } => siblings, _ => return None, }; if !error_enum_admits_variant_pin(&qualifier, &variant, &siblings, owner, index) { return None; } let path = ReturnPathGate::ErrVariant { qualifier, variant, siblings, }; if path.prelude_names().iter().any(|name| { index .files() .get(&owner.file) .is_none_or(|facts| source_binds_value_name(&facts.source, name)) }) { return None; } let call = pin_call(owner, index)?; // As for a whole-value field: no associated-function pin, and no // other definition may take a call by the owner's name. if matches!(call, PinCall::Associated { .. }) || other_definition_competes(owner, index, call.kind(), None) { return None; } Some(Self { name: owner.name.clone(), call, path, walked_positions: Vec::new(), returns_bool: false, returns_scalar: false, returns_integer: false, pointer_mask_gate: super::mask_pin::PointerMaskGate::Refuse, pointer_return_change: None, tuple_projection: None, tuple_change: None, closed_owner: None, guard_operands: None, skip_current_literal_check: Cell::new(false), awaited: declares_async(owner, index), poll_helpers: if declares_async(owner, index) { super::poll_helper::verified_helpers(index) } else { BTreeSet::new() }, drop_plain: Self::returned_types_drop_plain(owner, index), owner_file: owner.file.clone(), owner_start_line: owner.start_line, trait_scope_by_file: SyncMemo::default(), identity: None, }) } /// RIPR-SPEC-0197 check-helper argument pins: the test-scope texts a /// borrowed helper assertion's two compared parameters stand for, read /// only for a whole-return owner pin whose assertion is /// `assert_eq!(a, b)` or `assert!(a == b)` over two plain parameters of /// a helper that never names the owner. fn substituted_helper_operands( &self, test: &TestSummary, assertion: &OracleFact, index: &RustIndex, syntax: &OwnerPinSyntax, compared: &[String; 2], skip: usize, ) -> Option<[String; 2]> { if !matches!(self.path, ReturnPathGate::Any) || (test.start_line..=test.end_line).contains(&assertion.line) || !compared.iter().all(|operand| is_plain_identifier(operand)) { return None; } let loan = syntax.helper_loan(test, assertion, index)?; // A helper that names the owner may feed it into either side. if contains_as_whole_word(&mask_comments_and_strings(&loan.helper), &self.name) { return None; } helper_arguments::substituted_operands( test, &loan, [compared[0].as_str(), compared[1].as_str()], &self.name, index, |operands| self.substituted_pin(operands, index).is_some(), skip, ) } /// The owner call, the literal expected value and the call text of a /// substituted helper comparison: one side is the owner call (or a /// template rendering of a scalar owner's call), the other a literal. fn substituted_pin<'a>( &self, operands: &'a [String; 2], index: &RustIndex, ) -> Option<(CallShape<'a>, String, Option<&'a str>, Option<&'a str>)> { [(0, 1), (1, 0)].into_iter().find_map(|(at, other)| { let expected = helper_arguments::expected_literal(&operands[other], index)?; if let Some(call) = self.awaited_call_shape(None, &operands[at], &self.name) { return Some((call, expected, Some(operands[at].as_str()), None)); } let rendered = self .returns_scalar .then(|| helper_arguments::rendered_template_call(&operands[at], &expected)) .flatten()?; // #14194 review: a rendered call is still text this owner appears // in exactly once, so the guard-operand agreement check can read // its arguments. It is kept out of the `call_text` slot because // the adaptor gates must keep refusing a rendered operand. self.awaited_call_shape(None, rendered, &self.name) .map(|call| (call, expected, None, Some(rendered))) }) } /// A credited pin with this gate reads nonempty literal receiver data /// through the whole returned sum. Reveal must credit the pin before /// the classifier may use this owner-side flow fact. pub(in crate::analysis) fn reads_literal_fixture_receiver(&self) -> bool { matches!(self.path, ReturnPathGate::FixtureReceiver(_)) } /// The test-side gates: whether `assertion` in `test` pins the owner's /// return value through a call that names the owner. /// [`owner_call_shape`], reading an `async` owner's result through one /// trailing `.await` (`total(&[1, 2]).await`). A sync owner's `.await` /// awaits a future it returns, whose output its return expression does /// not hold, so that stays refused. /// #12796: the comparison operands with one `.0` projection removed, when /// the changed tail is the whole `T(e)` of a one-field built-in integer /// tuple struct and the other operand is not itself projected. `T(e).0` /// is `e` on every input, so comparing it pins the changed expression /// exactly as comparing `owner(..)` with `T(literal)` does. fn projected_operands<'a>( &self, operands: [&'a str; 2], index: &RustIndex, syntax: &OwnerPinSyntax, ) -> Option<[&'a str; 2]> { let type_name = self.tuple_projection.as_deref()?; let strip = |operand: &'a str| { operand .trim() .strip_suffix(".0") .map(str::trim_end) .filter(|base| !base.is_empty()) }; let stripped = match (strip(operands[0]), strip(operands[1])) { (Some(base), None) => [base, operands[1]], (None, Some(base)) => [operands[0], base], _ => return None, }; let owner = index.functions().iter().find(|function| { function.file == self.owner_file && function.name == self.name && function.start_line == self.owner_start_line })?; field_builtin_integer_of(owner, type_name, "0", true, index, syntax)?; Some(stripped) } /// #12808: whether both versions of a tuple-struct owner provably return /// the same value for the literal operands `call` passes, so no assertion /// on that call can tell the change apart, while some other operands do /// (a rewrite equal on every input keeps its reading). The owner and its operands are /// lowered to the closed integer subset; anything outside it answers /// `false` and keeps the reading. fn tuple_versions_agree(&self, call: &str, index: &RustIndex, syntax: &OwnerPinSyntax) -> bool { let (Some(type_name), Some(change)) = (self.tuple_projection.as_deref(), &self.tuple_change) else { return false; }; let Some(owner) = index.functions().iter().find(|function| { function.file == self.owner_file && function.name == self.name && function.start_line == self.owner_start_line }) else { return false; }; let Some(inner) = field_builtin_integer_of(owner, type_name, "0", true, index, syntax) else { return false; }; let tuple = super::owner_value::TupleOwner { type_name, inner, self_is_type: change.self_is_type, }; let (Some(closed), Some(lowered)) = ( super::owner_value::ClosedChange::read_tuple( &change.definition, &self.name, change.changed_line, &change.before, &tuple, ), super::owner_value::lower_tuple_call(call, &self.name, type_name), ) else { return false; }; closed.versions_agree(&self.name, &lowered) && closed.versions_differ_somewhere() } fn awaited_call_shape<'a>( &self, poll_context: Option<(&TestSummary, &RustIndex, &OwnerPinSyntax)>, operand: &'a str, name: &str, ) -> Option> { let operand = operand.trim(); // RIPR-SPEC-0265 rule 5: the pinned value is the returned closure // applied to its arguments; the call shape is the owner call inside. let operand = match &self.path { ReturnPathGate::ReturnedClosure { arity, .. } => { returned_closure::strip_applied(operand, *arity)? } _ => operand, }; // An async owner's bare call is its future, not its return value. match (self.awaited, operand.strip_suffix(".await")) { (true, Some(call)) => owner_call_shape(call.trim_end(), name), (true, None) => { let future = super::poll_helper::strip_helper_call(operand, &self.poll_helpers)?; let (test, index, syntax) = poll_context?; let helper = operand[..operand.find('(')?].trim(); super::poll_helper::binding_is_verified(test, helper, index, syntax) .then(|| owner_call_shape(future, name)) .flatten() } (false, _) => owner_call_shape(operand, name).or_else(|| { matches!(self.path, ReturnPathGate::FixtureReceiver(_)) .then(|| fixture_receiver::FixtureReceiver::inline_call(operand, name)) .flatten() }), } } pub(in crate::analysis) fn admits( &self, test: &TestSummary, assertion: &OracleFact, index: &RustIndex, imports_foreign: ForeignImport<'_>, syntax: &OwnerPinSyntax, ) -> bool { self.admits_spelled(test, assertion, index, imports_foreign, syntax, "assert_eq") } /// #12394 item 3: the repo-wide audit has no diff, so the one owner version /// it can read is the current one. A literal that version provably does not /// return fails at baseline and is withheld, as `ripr check` withholds a /// literal neither version returns (#12716). Anything the closed subset /// cannot evaluate keeps the reading. pub(in crate::analysis) fn with_current_owner_literal_check( mut self, owner: &FunctionSummary, ) -> Self { if self.closed_owner.is_none() && matches!(self.call, PinCall::Bare) { self.closed_owner = super::owner_value::ClosedChange::current(&owner.body, &self.name); } self } /// #13005: whether the closed subset can read `owner` as it stands. A cheap /// pre-check on the owner's text alone, so the audit builds a pin for a /// plain `assert_eq!` only where the literal check could ever withhold. pub(in crate::analysis) fn owner_literal_readable(owner: &FunctionSummary) -> bool { super::owner_value::ClosedChange::current(&owner.body, &owner.name).is_some() } /// #13005: whether the current-owner literal check (see /// [`Self::with_current_owner_literal_check`]) is the one gate that /// refuses `assertion`: [`Self::admits`] refuses it, and would admit it /// without that check. The repo-wide audit credits a plain `assert_eq!` /// from its extracted oracle, so it asks this to withhold a literal the /// current owner provably does not return, the audit twin of the diff /// path's neither-version check (#12716). Every other refusal reading is /// left to the audit's existing credit. pub(in crate::analysis) fn literal_check_withholds( &self, test: &TestSummary, assertion: &OracleFact, index: &RustIndex, imports_foreign: ForeignImport<'_>, syntax: &OwnerPinSyntax, ) -> bool { if self.closed_owner.is_none() || self.admits(test, assertion, index, imports_foreign, syntax) { return false; } self.skip_current_literal_check.set(true); let admitted_without = self.admits(test, assertion, index, imports_foreign, syntax); self.skip_current_literal_check.set(false); admitted_without } /// RIPR-SPEC-0197 claims payload equality: whether `assert_ok_eq!(call, /// literal)` or `assert_some_eq!(call, literal)` pins the owner under every /// gate [`Self::admits`] applies to the unwrapped `assert_eq!` pin, on a /// verified `use claims::..` import under the macro's own name. The text /// only nominates the macro; this decision (import, direction, literal /// expected operand, owner identity) is the only authority, so a refusal /// leaves the oracle `unknown`. pub(in crate::analysis) fn admits_claims_payload_eq( &self, test: &TestSummary, assertion: &OracleFact, index: &RustIndex, imports_foreign: ForeignImport<'_>, syntax: &OwnerPinSyntax, ) -> bool { claims_eq_macros().any(|name| { assertion.text.contains(name) && claims_eq_operands(&assertion.text, name).is_some() && self.admits_spelled(test, assertion, index, imports_foreign, syntax, name) }) } /// #8051: whether a bare `debug_assert_eq!` would pin the owner under /// every gate [`Self::admits`] applies to `assert_eq!`. It runs only /// where debug assertions are on, so this is never credit: the /// gap-admission post-pass reads it as a profile limit. pub(in crate::analysis) fn admits_debug_assert_eq( &self, test: &TestSummary, assertion: &OracleFact, index: &RustIndex, imports_foreign: ForeignImport<'_>, syntax: &OwnerPinSyntax, ) -> bool { self.admits_spelled( test, assertion, index, imports_foreign, syntax, "debug_assert_eq", ) } fn admits_spelled( &self, test: &TestSummary, assertion: &OracleFact, index: &RustIndex, imports_foreign: ForeignImport<'_>, syntax: &OwnerPinSyntax, spelling: &'static str, ) -> bool { // A selected check-helper argument pin that a later gate refuses // (another owner of the same name, a scope or identity gate) leaves // the helper's later eager calls to try: an unrelated earlier call // must not hide the genuine pin. let mut probe = HelperCallProbe { spelling, skip: 0, selected: Cell::new(false), }; loop { if self.admits_candidate(test, assertion, index, imports_foreign, syntax, &probe) { return true; } if !probe.selected.get() { return false; } probe.skip += 1; probe.selected.set(false); } } fn admits_candidate( &self, test: &TestSummary, assertion: &OracleFact, index: &RustIndex, imports_foreign: ForeignImport<'_>, syntax: &OwnerPinSyntax, probe: &HelperCallProbe, ) -> bool { let spelling = probe.spelling; // A borrowed assertion runs in its helper's scope, which this // polling rule does not resolve. Direct .await keeps its own gates. let poll_context = (test.start_line..=test.end_line) .contains(&assertion.line) .then_some((test, index, syntax)); // A `#[should_panic]` test passes when the values differ. if test .attrs .iter() .map(String::as_str) .chain(std::iter::once(test.body.as_str())) .any(|text| text.contains("should_panic")) { return false; } // #8480: a non-plain `Drop` on a constructed return type runs // while unwinding from a failed assertion and may exit 0 first. if !self.drop_plain { return false; } // #6648 (RIPR-SPEC-0279): a doc example's scope is its synthetic // source, not the file that holds the comment. let doctest = index.doctest_source(test); let condition; let matches_operands: [String; 2]; let expect_operands: [String; 2]; let pointer_call; let path_value_call: Option<(usize, String)>; // RIPR-SPEC-0197: `assert!(owner(..) == v)` and its guard twin // `if owner(..) != v { return Err(..) }` read like `assert_eq!`. A // guard reads only its condition, never a macro inside its body, // since the syntax gate admits the guard's path, not the body's. let is_guard = err_return_guard_twin(&assertion.text).is_some(); // RIPR-SPEC-0197 claims payload equality pins: `assert_ok_eq!(call, // literal)` is its own reading, never the `assert_eq!` ones below. Its // operands are read once here; a shape that is not exactly one plain // two-operand invocation refuses (fail closed). let claims_eq = claims_eq_macros().any(|name| name == spelling); let claims_operands = if claims_eq { match claims_eq_operands(&assertion.text, spelling) { Some(operands) if !is_guard => Some(operands), _ => return false, } } else { None }; // A nested `format!` is read only as a rendered scalar pin, and a // nested `vec!` only as a single-element index. let renders = !claims_eq && !is_guard && is_assert_eq_over(&assertion.text, spelling, "format"); let indexes = !claims_eq && !is_guard && is_assert_eq_over(&assertion.text, spelling, "vec"); let reads_assert_eq = renders || indexes || (!claims_eq && !is_guard // #8637: the `debug_` spelling takes the same `std`/`core` // root, under the same root proof (#7857). && if spelling == "assert_eq" || spelling == "debug_assert_eq" { is_plain_or_std_macro(&assertion.text, spelling) } else { is_plain_macro(&assertion.text, spelling) }); let equality = if reads_assert_eq || claims_eq { None } else { equality_condition_operands(&assertion.text) }; // RIPR-SPEC-0225 decision 6: beside an `Ok(..)`/`Some(..)` tail, the // test may compare `owner(..).unwrap()` (or `.expect("..")`) with the // bare literal; that reads as comparing the call with the wrapped one. // #7063: beside an early error-variant gate the test may compare // `owner(..).unwrap_err()` (or `.expect_err("..")`) with the bare // variant; that reads as comparing the call with `Err(..)` of it. // Beside a changed `Ok(..)`/`Some(..)` constructor whose other exits // build only `Err`/`None`, `owner(..).unwrap()` equals the literal only // when the call is `Ok(literal)`/`Some(literal)`: any other exit panics // the unwrap. The exits are read by spelling, so an owner file that // binds the wrapper or its opposite as a value (`const Ok`, `fn Err`) // refuses. let unwrap_wrapper = match &self.path { ReturnPathGate::WholeValueField(gate) => gate.wrapper, ReturnPathGate::ErrVariant { .. } => Some("Err"), ReturnPathGate::Head(head @ ("Ok" | "Some")) | ReturnPathGate::EarlyHead(head @ ("Ok" | "Some")) => { // The opposite exit is read by spelling too: an imported // `Err` that returns `Ok(3)` would pass the unwrap without // reaching the changed tail. let opposite = if *head == "Ok" { "Err" } else { "None" }; let owner_binds_exit_names = index.files().get(&self.owner_file).is_none_or(|facts| { [*head, opposite] .into_iter() .any(|name| source_binds_value_name(&facts.source, name)) }); (!owner_binds_exit_names).then_some(*head) } _ => None, }; let unwrap_read: fn(&str) -> Option<&str> = if matches!(self.path, ReturnPathGate::ErrVariant { .. }) { unwrapped_err_call } else { unwrapped_call }; let mut unwrapped = false; // RIPR-SPEC-0197 check-helper argument pins: a borrowed helper // assertion that compares two of the helper's own parameters reads // as comparing the arguments the test's eager call passes. let compared = if is_guard || renders || indexes { None } else if reads_assert_eq { assertion_comparison_operands(&assertion.text) .map(|[left, right]| [left.trim().to_string(), right.trim().to_string()]) } else { equality.clone() }; let substituted = compared.and_then(|compared| { self.substituted_helper_operands(test, assertion, index, syntax, &compared, probe.skip) }); if probe.skip > 0 && substituted.is_none() { // Every eligible call was already tried; the plain readings // below were not what the first attempt selected. return false; } probe.selected.set(substituted.is_some()); let substituted_expected; // #14194 review: a rendered, indexed or unwrapped twin supplies the // call text the guard-operand check reads, while `call_text` stays // `None` so the adaptor gates keep refusing those forms. let derived_call: Cell> = Cell::new(None); // RIPR-SPEC-0265: the text of the owner call, when one operand is it, // so an adaptor gate can read the argument the call passes. let (call, expected, call_text): (_, _, Option<&str>) = if let Some(operands) = &substituted { let Some((call, expected, call_text, derived_call_text)) = self.substituted_pin(operands, index) else { return false; }; derived_call.set(derived_call_text); substituted_expected = expected; (call, substituted_expected.as_str(), call_text) } else if let Some([first, second]) = claims_operands { // The macro panics unless `first` holds the named variant and // compares that payload with `second`, so it reads as // `assert_eq!(first.unwrap(), second)` (the unwrapped pin) and only // on the verified `use claims::..` import under its own name, in a // test's own file (a doc example is its own crate). // The opposite exit panics the macro before any comparison, so // only a pin on the macro's own variant reads. let direction = claims_payload_variant(spelling) .is_some_and(|variant| unwrap_wrapper == Some(variant)); // Only a literal expected operand is a discriminator. A whole-value // field gate reads the struct literal itself (`Config { .. }` // beside an `Ok(..)` tail), so it judges that operand below; // every other gate needs a scalar literal here. The cheap // refusals come first: the import check parses the whole file. let literal_expected = matches!(self.path, ReturnPathGate::WholeValueField(_)) || helper_arguments::expected_literal(second, index).is_some(); if !direction || !literal_expected || doctest.is_some() || !index.files().get(&test.file).is_some_and(|facts| { source_imported_claims_macros(&facts.source, (test.start_line, test.end_line)) .contains(&spelling) }) { return false; } let Some(call) = self.awaited_call_shape(poll_context, first, &self.name) else { return false; }; unwrapped = true; (call, second, Some(first)) } else if reads_assert_eq { let Some(operands) = assertion_comparison_operands(&assertion.text) else { return false; }; // #12796: `owner(..).0` / `let r = owner(..); r.0` of a one-field // integer tuple struct is the changed `T(e)`'s own `e`, so the // projection reads as the whole-value pin on the owner call. let (operands, projection) = match self.projected_operands(operands, index, syntax) { Some(stripped) => (stripped, ".0"), None => (operands, ""), }; // #9478: a typed immutable function pointer lends its exact call, // not an arbitrary use of the owner as a value. Keep this bounded // to a sync scalar free-function tail compared with a literal; // every identity, expected-value and execution gate below remains. pointer_call = (!self.awaited && self.returns_scalar && matches!(self.call, PinCall::Bare) && matches!(self.path, ReturnPathGate::Any) && (test.start_line..=test.end_line).contains(&assertion.line)) .then(|| { [(0, 1), (1, 0)].into_iter().find_map(|(at, other)| { if self .awaited_call_shape(poll_context, operands[at], &self.name) .is_some() { return None; } helper_arguments::expected_literal(operands[other], index)?; let call = crate::analysis::extract::local_fn_pointer_call( &test.body, operands[at], &assertion.text, assertion.line.checked_sub(test.start_line)?, )?; self.awaited_call_shape(poll_context, &call, &self.name)?; self.pointer_mask_gate.admits(&call).then_some(())?; if self .pointer_return_change .as_ref() .is_some_and(|change| change.is_invisible_at_call(&call)) { return None; } Some((at, call)) }) }) .flatten(); path_value_call = if pointer_call.is_none() { (!self.awaited && self.returns_scalar && matches!(self.call, PinCall::Bare) && matches!(self.path, ReturnPathGate::Any) && (test.start_line..=test.end_line).contains(&assertion.line) // Only a `.map(owner)` chain can substitute; skip the owner // lookup for every other assertion. && operands.iter().any(|operand| operand.contains("map"))) .then(|| { index.functions().iter().find(|function| { function.name == self.name && function.start_line == self.owner_start_line && function.file == self.owner_file }) }) .flatten() .and_then(|owner| { [(0usize, 1usize), (1, 0)] .into_iter() .find_map(|(at, other)| { let calls = path_value::substitute_owner_calls( test, operands[at], operands[other], owner, index, )?; // The first input at which the change is visible // represents the chain; invisible at every input // refuses. let call = calls.into_iter().find(|call| { self.awaited_call_shape(poll_context, call, &self.name) .is_some() && self.pointer_mask_gate.admits(call) && !self .pointer_return_change .as_ref() .is_some_and(|change| change.is_invisible_at_call(call)) })?; Some((at, call)) }) }) } else { None }; let operands = match (&pointer_call, &path_value_call) { (Some((0, call)), _) | (_, Some((0, call))) => [call.as_str(), operands[1]], (Some((1, call)), _) | (_, Some((1, call))) => [operands[0], call.as_str()], _ => operands, }; // trap-shine-debug-exact-control: the std rendering of a // primitive scalar names its value, so an exact string pins it. let rendered = (self.returns_scalar && matches!(self.path, ReturnPathGate::Any)) .then(|| { [(0, 1), (1, 0)].into_iter().find_map(|(at, other)| { helper_arguments::rendered_template_call(operands[at], operands[other]) .and_then(|call| { let shape = self.awaited_call_shape(poll_context, call, &self.name)?; derived_call.set(Some(call)); Some(shape) }) .map(|call| (call, operands[other], None)) }) }) .flatten() // trap-ceiling-wide-min-control / trap-muffle-times-one-control: // a projection that keeps every value of an integer owner the // literal expected value can name. .or_else(|| { (self.returns_integer && matches!(self.path, ReturnPathGate::Any) && !renders) .then(|| { [(0, 1), (1, 0)].into_iter().find_map(|(at, other)| { exact_integer_projection(operands[at], operands[other]) .filter(|_| !ord_method_rebindable(operands[at], test, index)) .and_then(|call| { let shape = self.awaited_call_shape( poll_context, call, &self.name, )?; derived_call.set(Some(call)); Some(shape) }) .map(|call| (call, operands[other], None)) }) }) .flatten() }) // trap-pile-first-element-control: `vec![call][0]` is the // call's own value. .or_else(|| { (self.returns_scalar && matches!(self.path, ReturnPathGate::Any) && indexes) .then(|| { [(0, 1), (1, 0)].into_iter().find_map(|(at, other)| { single_element_index(operands[at]) .and_then(|call| { let shape = self.awaited_call_shape( poll_context, call, &self.name, )?; derived_call.set(Some(call)); Some(shape) }) .map(|call| (call, operands[other], None)) }) }) .flatten() }); let unwrapped_direct = unwrap_wrapper.and_then(|_| { let shape = |at: usize| { unwrap_read(operands[at]) .and_then(|call| self.awaited_call_shape(poll_context, call, &self.name)) }; match (shape(0), shape(1)) { (Some(call), None) => Some((call, operands[1], None)), (None, Some(call)) => Some((call, operands[0], None)), _ => None, } }); match ( self.awaited_call_shape(poll_context, operands[0], &self.name), self.awaited_call_shape(poll_context, operands[1], &self.name), rendered, ) { (_, _, Some(pin)) if renders || indexes => pin, // A `vec!` elsewhere (the expected value, the message) leaves // the direct readings below. _ if renders => return false, (Some(call), None, _) => (call, operands[1], Some(operands[0])), (None, Some(call), _) => (call, operands[0], Some(operands[1])), (None, None, Some(pin)) => pin, (None, None, _) if unwrapped_direct.is_some() => { let Some(pair) = unwrapped_direct else { return false; }; unwrapped = true; pair } // #6974: `let result = owner(..); assert_eq!(result, 7);`. // Only a test that names the owner outside this assertion // can bind its result, and only in the test's own body: a // borrowed helper assertion names the helper's parameters, // not the test's bindings (#6482). (None, None, None) if (test.start_line..=test.end_line).contains(&assertion.line) && owner_named_outside(test, &assertion.text, &self.name) => { let bound = |at: usize| { let_bound_owner_call( test, assertion, operands[at], projection, &self.name, self.returns_scalar, false, ) .and_then(|text| { self.awaited_call_shape(poll_context, text, &self.name) .map(|call| (call, text)) }) }; match (bound(0), bound(1)) { (Some((call, text)), None) => (call, operands[1], Some(text)), (None, Some((call, text))) => (call, operands[0], Some(text)), // RIPR-SPEC-0225 rule 1: `let c = owner(..);` named // only by its `let` and this comparison. (None, None) if matches!( self.path, ReturnPathGate::WholeValueField(_) | ReturnPathGate::ErrVariant { .. } ) || (unwrap_wrapper.is_some() && matches!( self.path, ReturnPathGate::Head(_) | ReturnPathGate::EarlyHead(_) )) => { let bound_whole = |at: usize| { let initializer = bound_owner_initializer(test, operands[at], &self.name)?; self.awaited_call_shape(poll_context, initializer, &self.name) .map(|call| (call, false)) .or_else(|| { unwrap_wrapper .and(unwrap_read(initializer)) .and_then(|call| { self.awaited_call_shape( poll_context, call, &self.name, ) }) .map(|call| (call, true)) }) // claims' `assert_ok!(call)` / `assert_some!(call)` // yield the payload exactly as `.unwrap()` does, // on a verified `use claims::..` import. .or_else(|| { let (name, call) = claims_payload_call(initializer)?; // #12462: the example's own synthetic source when // the test is a doc example (its test fn opens on // the fence line, so the span is valid there), the // holding file otherwise. let imported = doctest .or_else(|| { index .files() .get(&test.file) .map(|facts| facts.data().source.as_ref()) }) .is_some_and(|source| { source_imported_claims_macros( source, (test.start_line, test.end_line), ) .contains(&name) }); // The macro panics on the other variant and yields // the payload, so only a pin on that same payload // reads: an `Err` pin (`ErrVariant`, or a field // gate wrapped in `Err`) is the opposite direction. let direction = claims_payload_variant(name) .is_some_and(|variant| unwrap_wrapper == Some(variant)); (direction && imported) .then(|| { self.awaited_call_shape( poll_context, call, &self.name, ) }) .flatten() .map(|call| (call, true)) }) }; match (bound_whole(0), bound_whole(1)) { (Some((call, unwraps)), None) => { unwrapped = unwraps; (call, operands[1], None) } (None, Some((call, unwraps))) => { unwrapped = unwraps; (call, operands[0], None) } _ => return false, } } _ => return false, } } _ => return false, } } else if let Some([left, right]) = &equality { match ( self.awaited_call_shape(poll_context, left, &self.name), self.awaited_call_shape(poll_context, right, &self.name), ) { (Some(call), None) => (call, right.as_str(), Some(left.as_str())), (None, Some(call)) => (call, left.as_str(), Some(right.as_str())), // `let v = owner(..); assert!(v == 4);` fails exactly when // `assert_eq!(v, 4)` does, so the #6974 binding rules decide // whether `v` is the call. A guard twin reads only its own // condition, and a borrowed helper assertion names the // helper's parameters, not the test's bindings (#6482). (None, None) if !is_guard && (test.start_line..=test.end_line).contains(&assertion.line) && owner_named_outside(test, &assertion.text, &self.name) => { let bound = |operand: &str| { let_bound_owner_call( test, assertion, operand, "", &self.name, self.returns_scalar, false, ) .and_then(|text| { self.awaited_call_shape(poll_context, text, &self.name) .map(|call| (call, text)) }) }; match (bound(left), bound(right)) { (Some((call, text)), None) => (call, right.as_str(), Some(text)), (None, Some((call, text))) => (call, left.as_str(), Some(text)), _ => return false, } } _ => return false, } } else if let Some(operands) = matches_pin_condition(&assertion.text) .as_deref() .and_then(literal_matches_operands) { // RIPR-SPEC-0197 literal `matches!` pins: `assert!(matches!(owner(..), Ok(5)))` // with a literal-only pattern pins the value as // `assert_eq!(owner(..), Ok(5))` does. #10121: so does its // Err-return guard twin `if !matches!(owner(..), Ok(5)) { return // Err(..) }` (RIPR-SPEC-0154 example 2). matches_operands = operands; let Some(call) = owner_call_shape(&matches_operands[0], &self.name) else { return false; }; // A pattern resolves `None` or `Some(..)` in the test's scope, so // a `const None` there matches some other value (#7581 review). let pattern = &matches_operands[1]; if ["Some", "None", "Ok", "Err"].iter().any(|name| { contains_as_whole_word(pattern, name) && (index .files() .get(&test.file) .is_none_or(|facts| source_binds_value_name(&facts.source, name)) || doctest.is_some_and(|source| source_binds_value_name(source, name))) }) { return false; } ( call, matches_operands[1].as_str(), Some(matches_operands[0].as_str()), ) } else if let Some(operands) = inline_expect_operands(&assertion.text) { // #6578: `expect![["alice: 42"]].assert_eq(&render_row("alice", 41))` // compares the actual text with the inline literal and panics on // a mismatch, as `assert_eq!(render_row("alice", 41), "alice: 42")` // does. expect_operands = operands; // #6578 review: a golden file the test itself writes (from the // owner, say) before comparing fixes nothing, so a test that // writes, copies or renames a file, or sets `UPDATE_EXPECT`, // lends no golden-file pin. if is_golden_file_comparison(&assertion.text) && (test_may_write_files(&test.body) || index .files() .get(&test.file) .is_none_or(|facts| file_renames_fs_or_env_import(&facts.source))) { return false; } let Some(call) = self.awaited_call_shape(poll_context, &expect_operands[0], &self.name) else { return false; }; ( call, expect_operands[1].as_str(), Some(expect_operands[0].as_str()), ) } else if !is_guard && self.returns_bool && is_plain_or_std_macro(&assertion.text, "assert") { // `assert!(owner(..))` is `assert_eq!(owner(..), true)` and // `assert!(!owner(..))` is `assert_eq!(owner(..), false)`. The // message arguments never decide whether the test fails. let Some(text) = outer_assertion_condition(&assertion.text) else { return false; }; condition = text; let operand = condition.trim(); let (operand, expected) = match operand.strip_prefix('!') { Some(negated) => (negated.trim_start(), "false"), None => (operand, "true"), }; if let Some(call) = self.awaited_call_shape(poll_context, operand, &self.name) { (call, expected, Some(operand)) } else if (test.start_line..=test.end_line).contains(&assertion.line) && owner_named_outside(test, &assertion.text, &self.name) // `let hit = owner(..); assert!(hit);` reads like // `assert_eq!(hit, true)`: the same binding rules as the // `assert_eq!` reading (an immutable once-bound scalar // used only in assertions) decide whether `hit` is the call. && let Some(text) = let_bound_owner_call( test, assertion, operand, "", &self.name, self.returns_scalar, true, ) && let Some(call) = self.awaited_call_shape(poll_context, text, &self.name) { (call, expected, Some(text)) } else { return false; } } else { return false; }; if !syntax.admits(test, assertion, index) { return false; } // The assertion must be the test's own, or an assertion the // shared admission borrows from a test-local check helper the test // calls eagerly (#6482). A harness trial's body is only its // registration, and an assertion attributed to it from anywhere else // sees bindings that are not in it. let loan = syntax.helper_loan(test, assertion, index); let loaned = loan.as_ref().map(|loan| loan.helper.clone()); let in_body = (test.start_line..=test.end_line).contains(&assertion.line); if in_body == loaned.is_some() { return false; } // A substituted pin reads both operands in the test's own scope, so // the gates below treat it as the test's assertion, not the helper's. let helper = loaned.filter(|_| substituted.is_none()); // #6578 review: a borrowed helper assertion compares the helper's // parameters, which the test may fill from a fixture that calls the // owner (`check(want)` with `#[fixture] fn want() { weight(4) }`). // The expected-operand scan below reads the test's names, not the // helper's, so a test with a fixture lends no helper assertion. if helper.is_some() && fixture_parameters(test, &mask_comments_and_strings(&test.body)) .is_none_or(|fixtures| !fixtures.is_empty()) { return false; } // SPEC-0225 example 5: resolve only the adjacent, immutable, // once-used literal binding in this test's own block. Helpers keep // their own scope, and every existing literal/owner gate below still // checks the initializer rather than trusting its identifier. let expected_literal = if matches!(self.path, ReturnPathGate::WholeValueField(_)) && is_plain_identifier(expected.trim()) { if !reads_assert_eq || helper.is_some() { return false; } let Some(literal) = expected_binding::expected_literal_binding(test, assertion, expected) else { return false; }; Some(literal) } else if let ReturnPathGate::WholeValueField(gate) = &self.path && reads_assert_eq && helper.is_none() && let Some(literal) = expected_binding::expected_item_literal(index, expected, &gate.type_name) { // SPEC-0225 decision 7: `expected()` and `T { .., ..T::default() }` // read as the one literal each stands for; the gates below check // that literal. Some(literal) } else { None }; let expected = match &expected_literal { Some(literal) => literal.as_str(), None => expected, }; let wrapped_expected; let expected = match (unwrapped, unwrap_wrapper) { (true, Some(wrapper)) => { wrapped_expected = format!("{wrapper}({expected})"); wrapped_expected.as_str() } (true, None) => return false, (false, _) => expected, }; // #12716: a literal that neither the owner before the diff nor after // it returns for this call's literal arguments fails on both versions, // so it cannot notice the change. The closed subset answers only that // provable case; every shape it cannot evaluate keeps the reading // above. if helper.is_none() && substituted.is_none() && !self.skip_current_literal_check.get() && let Some(closed) = &self.closed_owner && let Some(call) = call_text .map(str::to_string) .or_else(|| owner_call_in(&assertion.text, &self.name, unwrapped)) && closed.provably_unpinned(&self.name, call.trim_end_matches(".unwrap()"), expected) { return false; } // #14387: a guard-return pin holds only where the two versions // provably return different values for this call's literal arguments // and the pin names one of them. if let ReturnPathGate::ClosedGuardReturn { change: closed, .. } = &self.path && !(helper.is_none() && substituted.is_none() && !unwrapped && matches!(self.call, PinCall::Bare) && call_text .map(str::to_string) .or_else(|| owner_call_in(&assertion.text, &self.name, false)) .is_some_and(|call| closed.pin_discriminates(&self.name, &call, expected))) { return false; } // #12808: a tuple-struct owner whose two versions return the same // value for the call's literal operands is invisible to the call. if helper.is_none() && self.tuple_change.is_some() && let Some(call) = call_text && self.tuple_versions_agree(call, index, syntax) { return false; } // #12394 item 5: the same for a whole-value field pin. The field's // pinned value is read against both versions of the changed field's // initializer; a value neither computes for the call's literal // arguments fails the test on both versions. if helper.is_none() && substituted.is_none() && let ReturnPathGate::WholeValueField(gate) = &self.path && let Some(closed) = &gate.closed && let Some(call) = call_text .map(str::to_string) .or_else(|| owner_call_in(&assertion.text, &self.name, unwrapped)) && let Some(pinned) = gate.pinned_field_text(expected) && closed.provably_unpinned(&self.name, call.trim_end_matches(".unwrap()"), &pinned) { return false; } // #8097: an expected operand read from a file the test itself may // write fixes nothing: the test rewrites the golden from the owner // before comparing, so every mutant of the owner survives. // Fail-closed like the neighbouring golden guard: unknown file // facts cannot prove the import set is rename-free. let renamed_fs_import = index .files() .get(&test.file) .is_none_or(|facts| file_renames_fs_or_env_import(&facts.source)); if expected_reads_written_file(test, renamed_fs_import, expected) { return false; } // `assert_eq!(f(4), f(2) + f(2))` compares the owner with itself. if expected_reaches_owner(test, &assertion.text, expected, &self.name) || expected_reaches_fixture(test, expected) || expected_constant_reaches_owner( index, test, expected, &self.name, &self.call, &self.owner_file, ) { return false; } // #7714: a test-file helper that computes its value from the owner // (`fn expected() -> String { check(99).unwrap_err() }`) makes the // expected operand the owner's own value, however it is bound. if test_file_helpers_reaching_owner(index, test, expected, &self.name) .iter() .any(|helper| { expected_reaches_owner(test, &assertion.text, expected, helper) || expected_constant_reaches_owner( index, test, expected, helper, &PinCall::Bare, &self.owner_file, ) }) { return false; } match (&self.path, call) { // #6692: the clone must be compared with its own receiver, and // the test's file must not import some other `Clone`. // The receiver's type is read from the test's own bindings, // which do not bind a helper's parameters. (ReturnPathGate::CloneReceiver, _) if helper.is_some() => return false, (ReturnPathGate::CloneReceiver, CallShape::Method(receiver)) => { let independent = match &self.call { PinCall::Method { receivers, .. } => receivers.iter().any(|receiver_type| { matches!(receiver_type, ReceiverType::Named(type_name) if clone_receiver_is_independent(test, receiver, type_name, index)) }), PinCall::Bare | PinCall::Associated { .. } => false, }; if expected.trim() != receiver || imports_foreign(&test.file, "Clone") || !independent { return false; } } ( ReturnPathGate::CloneReceiver, CallShape::Bare | CallShape::Path(_) | CallShape::Associated(_), ) => return false, (path, _) => { if !path.admits(expected) { return false; } // RIPR-SPEC-0265 rule 2: the pinned call must run the // closure at least once. if let ReturnPathGate::Adaptor { position, .. } = path && !call_text.is_some_and(|text| { closure_adaptor::pinned_call_runs_closure( test, loan.as_ref(), text, &self.name, *position, ) }) { return false; } if let ReturnPathGate::FixtureReceiver(fixture) = path && !call_text.is_some_and(|text| { fixture .admits(test, assertion, text, expected, index, syntax) .is_some() }) { return false; } // RIPR-SPEC-0265 rule 5: the application must tell the // closure's operators apart. if let ReturnPathGate::ReturnedClosure { arity, arithmetic } = path && !call_text.is_some_and(|text| { returned_closure::applied_inputs_are_distinct_literals(text, *arity) && arithmetic.discriminates(text) }) { return false; } // RIPR-SPEC-0360: some pinned run walks a non-empty literal // sequence and pins a nonzero integer. if let ReturnPathGate::LoopAccumulator { position, term } = path && !call_text.is_some_and(|text| match term { None => closure_adaptor::pinned_run_sums_to_nonzero( test, loan.as_ref(), text, &self.name, *position, expected, ), // Folded through the callee: the run must give the // pinned value and tell every neighbour apart. Some(term) => closure_adaptor::pinned_run_accepts( test, loan.as_ref(), text, &self.name, *position, expected, &|elements, want| { call_term_fold::pinned_run_separates( term, &self.owner_file, index, elements, want, ) }, ), }) { return false; } // #9444: a walk over an empty literal visits nothing. // A rendered or indexed comparison (`format!("{}", call)`, // `vec![call][0]`) carries no call text, so the assertion's // own text is read for the first call of the owner. let walk_site = call_text.unwrap_or(assertion.text.as_str()); if self.walked_positions.iter().any(|position| { closure_adaptor::pinned_call_passes_only_empty( test, loan.as_ref(), walk_site, &self.name, *position, ) }) { return false; } // RIPR-SPEC-0197 rule 3: a short-circuit tail pins only on a // call that evaluates every operand. if let ReturnPathGate::ShortCircuit(chain) = path && !call_text.is_some_and(|text| { chain.pinned_call_evaluates_every_operand( test, loan.as_ref(), text, assertion.line, &self.name, ) }) { return false; } // #8361: a dropped or added guard operand that every run of // this call leaves at its chain's identity value gives both // versions the same result here. The wrapper forms carry no // `call_text`, so the call text this arm derived is used: the // assertion's own text is a helper assertion like // `assert_eq!(actual, expected)` and does not name the owner, // which is why reading `walk_site` here left every wrapper // pin open (#14194 review). let guard_site = call_text .or_else(|| derived_call.get()) .unwrap_or(assertion.text.as_str()); if let Some(guards) = &self.guard_operands && guards.pinned_call_agrees( test, // A substituted pin reads its call in the test's own // scope, so a helper parameter that shares a name with // a test binding must not supply the argument value // (#14194 review). loan.as_ref().filter(|_| substituted.is_none()), guard_site, assertion.line, &self.name, ) { return false; } // The expected `Err(..)` / `Ok(..)` / `Some(..)` / `None` // resolves in the test's scope: a test-local `fn Err` // returning `Ok` passes the pin without the changed return // (#7712 review). Opaque globs do not count here; see // `source_declares_value_name`. if ["Some", "None", "Ok", "Err"].iter().any(|name| { starts_with_word(expected.trim(), name) && (index .files() .get(&test.file) .is_none_or(|facts| source_declares_value_name(&facts.source, name)) || doctest .is_some_and(|source| source_declares_value_name(source, name))) }) { return false; } } } // The expected literal's bare name must reach the workspace type in // the test's file too (`use external::Config;` there makes it another). if let ReturnPathGate::WholeValueField(gate) = &self.path && (index.files().get(&test.file).is_none_or(|facts| { declaring_file_rebinds(&facts.source, &gate.type_name, true, index) }) || doctest .is_some_and(|source| declaring_file_rebinds(source, &gate.type_name, true, index))) { return false; } // #7063: the same for the expected variant's enum. if let ReturnPathGate::ErrVariant { qualifier, .. } = &self.path && index .files() .get(&test.file) .is_none_or(|facts| declaring_file_rebinds(&facts.source, qualifier, true, index)) { return false; } // #6648 (RIPR-SPEC-0279): a doc example reaches the owner only by a // free call through the library's import name. A method or // associated call types its receiver from file scopes, and a rival // owner settles in the holding file's scopes; neither is the // example's, so both refuse. if doctest.is_some() && (self.identity.is_some() || !matches!( (&self.call, &call), (PinCall::Bare, CallShape::Bare | CallShape::Path(_)) )) { return false; } let test_source = doctest.or_else(|| { index .files() .get(&test.file) .map(|facts| facts.data().source.as_ref()) }); // The single-file exemption resolves the owner's enclosing module // in the test file's own parse (#6957), while the parent-chain walk // resolves it in whichever chain file holds the owner (#6950); a // cross-file owner keeps the fail-closed single-file check. let owner_scope = OwnerScope::new(self.name.as_str(), self.owner_start_line, &self.owner_file); let masked_body = mask_comments_and_strings(&test.body); // claims' assertion macros the test's file imports from the crate // (the syntax admission settles the manifest and shadowing): they // evaluate their operand and bind nothing, so an owner call inside // one is no rebinding. // #12462: scoped to the asserting test (a doc example reads its own // synthetic source, whose test fn opens on the fence line). let claims_span = (test.start_line, test.end_line); let claims_macros: Vec<&str> = test_source .map(|source| source_imported_claims_macros(source, claims_span)) .unwrap_or_default(); match (&self.call, call) { // #7082: a cfg on the owner or an enclosing module may compile // a same-named `static`, `const` or `use` in its place, which // the bare name then reaches instead. (PinCall::Bare, CallShape::Bare) => { !syntax .item_nesting(index, &self.owner_file, &self.name, self.owner_start_line) .is_none_or(|owner| owner.cfg_gated) && !syntax.file_cfg_gated(index, &self.owner_file) // #6544: among same-named rivals, the asserted bare call // itself must name the owner, resolved in the test's // scopes; another call elsewhere in the test that names // the owner lends this one nothing. A helper's call sits // in the helper's scopes, which this does not read. && self.identity.as_ref().is_none_or(|identity| { helper.is_none() && identity.resolve_call(test, index, &[]) == CallTarget::Owner }) && !test_body_shadows_owner(test, &self.name) && !binds_outside_let(&masked_body, &self.name) && !bound_by_macro_with(&masked_body, &self.name, &claims_macros) && helper.as_deref().is_none_or(|helper| { helper_pins_owner_call(helper, &masked_body, &self.name) }) && test_source.is_some_and(|source| { !file_renames_to(source, &self.name) && self.bare_call_reaches_owner(test, source, index, syntax) }) } // As for the clone receiver: a helper's parameters are not the // test's bindings. (PinCall::Method { .. }, _) if helper.is_some() => false, // #6974: a path names the owner without the bare name's scope, // so a test-local binding of the name cannot capture it; the // path itself must reach the owner. (PinCall::Bare, CallShape::Path(prefix)) => { helper.is_none() && self.identity.as_ref().is_none_or(|identity| { identity.resolve_call(test, index, &path_prefix_segments(prefix)) == CallTarget::Owner }) && test_source.is_some_and(|source| { self.path_reaches_owner(prefix, test, source, index, syntax) }) } ( PinCall::Method { receivers, trait_scope, }, CallShape::Method(_) | CallShape::Constructed(_), ) => { let receiver_type = if let ReturnPathGate::FixtureReceiver(fixture) = &self.path { // The gate above read the actual helper value, not merely // its return type. Existing type/shadow/import authority // still binds the record to this owner. named_or_slice( &fixture.type_name, test, test_source, index, imports_foreign, owner_scope, ) } else { match call { CallShape::Method(receiver) => { if bound_by_macro(&masked_body, receiver) { return false; } test_receiver_type( test, receiver, test_source, index, imports_foreign, owner_scope, syntax, ) } // An inline constructor types the receiver the same way // a `let receiver = Type::constructor(..);` binding does. CallShape::Constructed(receiver) => binding_type( &format!("= {receiver}"), test, test_source, index, imports_foreign, owner_scope, syntax, ), CallShape::Bare | CallShape::Path(_) | CallShape::Associated(_) => None, } }; let Some(receiver_type) = receiver_type else { return false; }; if !receivers.contains(&receiver_type) { return false; } let shadowed_by_std = match &receiver_type { ReceiverType::ByteSlice => BYTE_SLICE_METHODS.contains(&self.name.as_str()), ReceiverType::Named(_) => method_may_dispatch_through_prelude(&self.name), }; !shadowed_by_std && trait_scope.as_ref().is_none_or(|scope| { self.trait_in_scope(test, test_source, &scope.trait_name, index) }) } // #6617: `T::name(..)` names the owner only through the owner's // own `T`. A module path `a::b::name(..)` is `CallShape::Path` // (its segments are never CamelCase), so it never reaches here. // // A cfg on the owner, its `impl`, an enclosing module or its file // may drop it from the build, and `T::name` then reaches a trait // default the index never sees (#7082, #7724). (PinCall::Associated { type_name }, CallShape::Associated(named)) => { helper.is_none() && named == type_name && indexed_item_nesting( index, &self.owner_file, &self.name, self.owner_start_line, true, ) .is_some_and(|owner| !owner.cfg_gated) && !syntax.file_cfg_gated(index, &self.owner_file) && !bound_by_macro(&masked_body, type_name) && !body_rebinds_type(&masked_body, type_name) && test_source.is_some_and(|source| { self.associated_type_reaches_owner(type_name, test, source, index, syntax) }) } _ => false, } } fn binding(&self) -> FreeOwnerBinding<'_> { FreeOwnerBinding { name: &self.name, owner_file: &self.owner_file, owner_start_line: self.owner_start_line, } } fn path_reaches_owner( &self, prefix: &str, test: &TestSummary, test_source: &str, index: &RustIndex, syntax: &OwnerPinSyntax, ) -> bool { self.binding() .path_reaches_owner(prefix, test, test_source, index, syntax) } fn bare_call_reaches_owner( &self, test: &TestSummary, test_source: &str, index: &RustIndex, syntax: &OwnerPinSyntax, ) -> bool { self.binding() .bare_call_reaches_owner(test, test_source, index, syntax) } /// #6617 (RIPR-SPEC-0172): whether a top-level test's `T::name(..)` /// names the owner's own `T`. The owner-side gate already made `T` the /// one workspace type of that name, with no `mod`, `trait` or `type` of /// it and no competing path-callable `fn name`. Here the test's file /// must import `T` directly, `use ::T;`, at file level, /// where `` names the owner's library from the test's crate (the /// RIPR-SPEC-0197 manifest authority) and nothing in the test's crate /// binds it, and the library must not export another `T`. Every `use` /// of the file that names `T` must be such an import: an alias (`as`), /// a glob, a brace list or another root refuses, and so does a /// declaration of `T` in the test's file. Any doubt refuses. fn associated_type_reaches_owner( &self, type_name: &str, test: &TestSummary, test_source: &str, index: &RustIndex, syntax: &OwnerPinSyntax, ) -> bool { // Only file-level imports reach a test at the file's top level. if syntax .item_nesting(index, &test.file, &test.name, test.start_line) .is_none_or(|nesting| !nesting.modules.is_empty()) { return false; } if file_renames_to(test_source, type_name) || file_aliases_type(test_source, type_name) { return false; } let masked = mask_comments_and_strings(test_source); let declares_name = ["struct", "enum", "union", "trait", "mod"] .iter() .any(|keyword| { whole_word_offsets(&masked, keyword) .into_iter() .any(|offset| { starts_with_word(masked[offset + keyword.len()..].trim_start(), type_name) }) }); if declares_name { return false; } let file_level = file_use_statements(&super::related_tests::file_level_use_text(&masked)); if !file_level .iter() .any(|statement| contains_as_whole_word(statement, type_name)) { return false; } let binding = self.binding(); let imports_owner_type = |statement: &String| { let Some(path) = statement.trim_start().strip_prefix("use") else { return false; }; let path = path.trim(); let path = path.strip_prefix("::").map_or(path, str::trim_start); if path.contains(['{', '}', '*']) || !whole_word_offsets(path, "as").is_empty() { return false; } // Only `use ::T;`: a middle segment can be a `pub use` // of another crate (`pub use other as fs;`), whose own `T` this // check cannot place. let segments: Vec<&str> = path.split("::").map(str::trim).collect(); let [root, last] = segments[..] else { return false; }; last == type_name && is_plain_identifier(root) && binding.krate_root_names_owner_crate(root, &test.file, test_source, index) && !test_crate_binds_root(test, root, index, syntax) }; if !file_use_statements(test_source) .iter() .filter(|statement| contains_as_whole_word(statement, type_name)) .all(imports_owner_type) { return false; } syntax .target_roots(index) .root(&self.owner_file, index) .is_some_and(|owner_root| !library_may_export_other(index, &owner_root, type_name)) } fn trait_in_scope( &self, test: &TestSummary, test_source: Option<&str>, trait_name: &str, index: &RustIndex, ) -> bool { let Some(source) = test_source else { return false; }; if let Some(known) = self.trait_scope_by_file.borrow().get(&test.file) { return *known; } let in_scope = trait_in_scope(source, trait_name, index); self.trait_scope_by_file .borrow_mut() .insert(test.file.clone(), in_scope); in_scope } } /// Identity-only view shared by return pins and targeted owner selection. /// It carries no return-value probe, expected-value oracle or pin credit. struct FreeOwnerBinding<'a> { name: &'a String, owner_file: &'a PathBuf, owner_start_line: usize, } impl FreeOwnerBinding<'_> { /// #6974: whether `prefix::name` can only name the owner. The path must /// resolve to exactly the module that declares the owner. An explicit /// `fn` there takes the value name from every glob, and any other item /// of the name in the same module fails to compile, so a rename, a /// re-export or a type elsewhere cannot capture the path. The path is: /// - `self::`/`super::` from a test in the owner's own file, resolved /// from the test's inline modules without leaving the file; /// - `crate::` from a test that composes under the owner's crate root, /// when the owner's file is that root; or /// - an import name of the owner's library from the test's crate /// manifest (`krate::name(..)` in an integration test) that nothing /// renames or binds in the test's crate, when the owner's file is the /// library root. /// /// Any `r#name` in the workspace (a raw twin the name match misses) and /// a macro invocation naming the owner in its crate (it may emit a /// twin under another cfg) fail closed. fn path_reaches_owner( &self, prefix: &str, test: &TestSummary, test_source: &str, index: &RustIndex, syntax: &OwnerPinSyntax, ) -> bool { let key = ( (*self.owner_file).clone(), self.owner_start_line, (*self.name).clone(), prefix.to_string(), test.file.clone(), test.start_line, ); if let Some(known) = syntax.path_memo.borrow().verdicts.get(&key) { return *known; } let verdict = self.path_reaches_owner_uncached(prefix, test, test_source, index, syntax); syntax.path_memo.borrow_mut().verdicts.insert(key, verdict); verdict } fn path_reaches_owner_uncached( &self, prefix: &str, test: &TestSummary, test_source: &str, index: &RustIndex, syntax: &OwnerPinSyntax, ) -> bool { let segments: Vec<&str> = prefix.split("::").collect(); let Some((root, rest)) = segments.split_first() else { return false; }; // #6648 (RIPR-SPEC-0279): in a doc example `crate`, `self` and // `super` name the example's own crate, never the library. if index.doctest_source(test).is_some() && matches!(*root, "self" | "super" | "crate") { return false; } let roots = syntax.target_roots(index); let Some(owner_root) = roots.root(self.owner_file, index) else { return false; }; let owner_is_root = *self.owner_file == owner_root; let mut module = match *root { "self" | "super" => { if test.file != *self.owner_file { return false; } let Some(ItemNesting { modules: mut module, .. }) = syntax.item_nesting(index, &test.file, &test.name, test.start_line) else { return false; }; if *root == "super" && module.pop().is_none() { return false; } module } "crate" => { if !owner_is_root || roots.root(&test.file, index).as_ref() != Some(&owner_root) { return false; } Vec::new() } _ => { if !owner_is_root || !self.library_root_names_owner(root, test, test_source, index, syntax) { return false; } Vec::new() } }; let leading_supers = rest .iter() .take_while(|segment| **segment == "super") .count(); if leading_supers > 0 && !matches!(*root, "self" | "super") { return false; } for _ in 0..leading_supers { if module.pop().is_none() { return false; } } for segment in &rest[leading_supers..] { if matches!(*segment, "self" | "super" | "crate") { return false; } module.push((*segment).to_string()); } syntax .item_nesting(index, self.owner_file, self.name, self.owner_start_line) .is_some_and(|owner| !owner.cfg_gated && owner.modules == module) && !syntax.file_cfg_gated(index, self.owner_file) && !syntax.crate_may_hide_name(index, &owner_root, self.name, roots) } /// #6974: whether `root::` in `test` names the owner's library: an /// import name of it in the test crate's manifest that no workspace /// file renames another item to and the test's crate does not bind. fn library_root_names_owner( &self, root: &str, test: &TestSummary, test_source: &str, index: &RustIndex, syntax: &OwnerPinSyntax, ) -> bool { let roots = syntax.target_roots(index); let Some(owner_root) = roots.root(self.owner_file, index) else { return false; }; if file_renames_to(test_source, root) || !index .member_crates .import_names(&test.file, &owner_root) .iter() .any(|import| import == root) { return false; } !test_crate_binds_root(test, root, index, syntax) } /// #7097: whether the test's bare `name(..)` can only reach the /// owner. The establish gate refused every other `fn` of the name, but /// a same-named `static`, `const`, tuple struct or `use` still takes a /// bare call: an item in the test's body or own module scope shadows /// every import, an explicit `use` must name the owner's own path, a /// glob must deliver the owner from a twin-free module, and with /// neither the test must sit beside the owner. Anything unplaced /// refuses. fn bare_call_reaches_owner( &self, test: &TestSummary, test_source: &str, index: &RustIndex, syntax: &OwnerPinSyntax, ) -> bool { let key = ( (*self.owner_file).clone(), self.owner_start_line, (*self.name).clone(), test.file.clone(), test.start_line, ); if let Some(known) = syntax.bare_call_memo.borrow().get(&key) { return *known; } let verdict = self.bare_call_reaches_owner_uncached(test, test_source, index, syntax, false); syntax.bare_call_memo.borrow_mut().insert(key, verdict); verdict } fn bare_call_reaches_owner_uncached( &self, test: &TestSummary, test_source: &str, index: &RustIndex, syntax: &OwnerPinSyntax, local_helper: bool, ) -> bool { let Some(owner_inline) = syntax .item_nesting(index, self.owner_file, self.name, self.owner_start_line) .map(|nesting| nesting.modules) else { return false; }; if let Some(source) = index.doctest_source(test) { return self.doctest_bare_call_reaches_owner( test, source, &owner_inline, index, syntax, ); } if index.proptest_singleton_value(test).is_some() { return self.property_import_reaches_owner( test, test_source, &owner_inline, index, syntax, ); } let Some(scopes) = syntax.file_scopes(index, &test.file) else { return false; }; let Some(scope) = scopes.scope_of_test(test_source, test) else { return false; }; // The body binds first: an item there shadows every import, an // explicit `use` there shadows the module scope, and a glob there // shadows the module scope too. if body_defines_value_twin(&test.body, self.name) { return false; } let body_uses = flattened_use_paths(&test.body); let (body_bindings, body_globs) = partition_name_uses(&body_uses, self.name); if !body_bindings.is_empty() { let context = ScopeContext { file: &test.file, source: test_source, stack: &scope.stack, }; return body_bindings.len() == 1 && self.use_names_owner(body_bindings[0], context, &owner_inline, index, syntax); } if !body_globs.is_empty() { let context = ScopeContext { file: &test.file, source: test_source, stack: &scope.stack, }; return body_globs .iter() .all(|glob| self.glob_delivers_owner(glob, context, &owner_inline, index, syntax)); } // The test's own module scope: a twin item takes the call from a // glob or lexical resolution, and an explicit `use` takes it from // a glob. Ancestor items are invisible without a glob, which the // glob rule below places. if scope.has_twin(self.name) { return false; } let (bindings, globs) = partition_name_uses(&scope.uses, self.name); // A verified test-local function beside the test wins module globs. // Body bindings above and explicit module imports/twins still refuse. // This helper-only route is uncached: production identity is unchanged. if local_helper && test.file == *self.owner_file && scope.stack == owner_inline { return bindings.is_empty(); } if !bindings.is_empty() { let context = ScopeContext { file: &test.file, source: test_source, stack: &scope.stack, }; return bindings.len() == 1 && self.use_names_owner(bindings[0], context, &owner_inline, index, syntax); } if !globs.is_empty() { let context = ScopeContext { file: &test.file, source: test_source, stack: &scope.stack, }; return globs .iter() .all(|glob| self.glob_delivers_owner(glob, context, &owner_inline, index, syntax)); } // Neither: the owner is lexically visible only beside the test. // Anywhere else the bare name is unresolved, the prelude, or a // macro-emitted import ripr cannot see — never the owner. test.file == *self.owner_file && scope.stack == owner_inline } /// The closed empty-string property has an explicit file-root import and /// a generation-owned scope containing every sibling function binding. /// Its known proptest token tree cannot invent a second value declaration /// merely by mentioning the owner. Re-enter the ordinary import/module /// authority; the receipt does not establish the imported owner by itself. fn property_import_reaches_owner( &self, test: &TestSummary, test_source: &str, owner_inline: &[String], index: &RustIndex, syntax: &OwnerPinSyntax, ) -> bool { let Some(scopes) = index.proptest_name_scopes(test) else { return false; }; let [body, root] = scopes.scopes.as_slice() else { return false; }; if !body.fn_body || root.fn_body || !root.modules.is_empty() || !body.imports.is_empty() || !body.globs.is_empty() || body.block_globs || body.defines.contains(self.name) || body.block_bindings.contains(self.name) || root.defines.contains(self.name) || root.child_modules.contains(self.name) || !root.globs.is_empty() { return false; } let imports = root.imports_of(self.name).collect::>(); let [crate::analysis::syntax::UseBinding::Path(path)] = imports.as_slice() else { return false; }; let Some(first) = path.first() else { return false; }; if matches!(first.as_str(), "crate" | "self" | "super") || root.defines.contains(first) || root.child_modules.contains(first) || root.imports_of(first).next().is_some() { return false; } let import = UsePath { path: path.join("::"), alias: None, }; let context = ScopeContext { file: &test.file, source: test_source, stack: &[], }; if self.use_names_owner(&import, context, owner_inline, index, syntax) { return true; } // The original property imports a library-root re-export spelled // `pub use convert::owner`. Keep this additional transport local to // the registered property: one unrenamed, relative, composed child // of the owner's library root, with no competing binding or alias. let Some((first, middle)) = split_binding_use(&import, self.name) else { return false; }; let Some((target_file, target_stack)) = self.resolve_use_prefix(first, &middle, context, index, syntax, 1) else { return false; }; if target_file != composed_root(self.owner_file, index) || !target_stack.is_empty() || !owner_inline.is_empty() { return false; } let Some(target_scopes) = syntax.file_scopes(index, &target_file) else { return false; }; let Some(target) = target_scopes.scope_with_stack(&[]) else { return false; }; if target.has_twin(self.name) { return false; } let (transports, _) = partition_name_uses(&target.uses, self.name); let [transport] = transports.as_slice() else { return false; }; if transport.alias.is_some() || transport.path.starts_with("::") { return false; } let Some((child, middle)) = split_binding_use(transport, self.name) else { return false; }; if !middle.is_empty() || matches!(child, "crate" | "self" | "super") || target.has_twin(child) || !partition_name_uses(&target.uses, child).0.is_empty() { return false; } syntax .mod_children(index) .get(&(target_file, child.to_owned())) .and_then(Option::as_ref) .is_some_and(|file| file == self.owner_file) } /// #6648 (RIPR-SPEC-0279): whether a doc example's bare `name(..)` /// can only reach the owner. The example is its own crate, so the name /// resolves only through the example's own `use`: exactly one binding /// `use ::..::name;`, or globs `use ::..::*;` that each /// deliver the owner, where `` is an import name of the owner's /// library (a local `mod` or rename of that name in the example is /// refused by the twin, rename and single-binding checks). A `crate`, /// `self` or `super` root names the example's crate, a twin item in the /// example takes the call, and with no `use` the name is not the /// owner's. fn doctest_bare_call_reaches_owner( &self, test: &TestSummary, source: &str, owner_inline: &[String], index: &RustIndex, syntax: &OwnerPinSyntax, ) -> bool { if body_defines_value_twin(&test.body, self.name) { return false; } let uses = flattened_use_paths(&test.body); let (bindings, globs) = partition_name_uses(&uses, self.name); let library_rooted = |path: &str| { let stripped = path.strip_prefix("::").unwrap_or(path); let first = stripped.split("::").next().map_or("", strip_raw); !matches!(first, "" | "crate" | "self" | "super") }; let context = ScopeContext { file: &test.file, source, stack: &[], }; if let [binding] = bindings.as_slice() { return globs.is_empty() && library_rooted(&binding.path) && self.use_names_owner(binding, context, owner_inline, index, syntax); } bindings.is_empty() && !globs.is_empty() && globs.iter().all(|glob| { library_rooted(&glob.path) && self.glob_delivers_owner(glob, context, owner_inline, index, syntax) }) } /// #7097: whether the binding `use_path` delivers the owner to /// `scope`: its module prefix resolves, and that module holds the /// owner with no twin — the owner itself, or one `use` hop /// re-exporting it. A twin's path, a foreign crate, a bare crate /// name, a renamed root, or a re-export chain past one hop refuses. fn use_names_owner( &self, use_path: &UsePath, scope: ScopeContext<'_>, owner_inline: &[String], index: &RustIndex, syntax: &OwnerPinSyntax, ) -> bool { let Some((first, middle)) = split_binding_use(use_path, self.name) else { return false; }; let Some((target_file, target_stack)) = self.resolve_use_prefix(first, &middle, scope, index, syntax, 1) else { return false; }; self.resolved_module_delivers_owner(target_file, target_stack, owner_inline, index, syntax) } /// #7097: whether the binding `use_path` resolves exactly to the /// owner's module from `scope`: no re-export hop, so one-hop /// transport and twin checks end here and import cycles cannot /// recurse. fn use_resolves_to_owner_module( &self, use_path: &UsePath, scope: ScopeContext<'_>, owner_inline: &[String], index: &RustIndex, syntax: &OwnerPinSyntax, ) -> bool { let Some((first, middle)) = split_binding_use(use_path, self.name) else { return false; }; self.resolve_use_prefix(first, &middle, scope, index, syntax, 0) .is_some_and(|(file, stack)| { file == *self.owner_file && stack.as_slice() == owner_inline }) } /// #7097: resolve a `use` path's module prefix to its (file, inline /// stack): `self`/`super` walk from the scope, `crate` and the /// owner's library crate name walk from the owner's crate root, each /// step an inline child module or a composed out-of-line `mod`. /// `None` when a step is foreign, renamed, ambiguous, or unplaced. fn resolve_use_prefix( &self, first: &str, segments: &[&str], scope: ScopeContext<'_>, index: &RustIndex, syntax: &OwnerPinSyntax, reexport_hops: u8, ) -> Option<(PathBuf, Vec)> { match first { "self" | "super" => { let (file, stack, rest) = pop_super_across_files( index, syntax, scope.file, scope.stack, first, segments, )?; self.resolve_module_path(index, syntax, scope, &file, &stack, &rest, reexport_hops) } "crate" => { let root = composed_root(self.owner_file, index); if composed_root(scope.file, index) != root { return None; } self.resolve_module_path(index, syntax, scope, &root, &[], segments, reexport_hops) } _ => { if !self.krate_root_names_owner_crate(first, scope.file, scope.source, index) { return None; } let root = composed_root(self.owner_file, index); self.resolve_module_path(index, syntax, scope, &root, &[], segments, reexport_hops) } } } fn local_module_child( file: &Path, stack: &[String], segment: &str, index: &RustIndex, syntax: &OwnerPinSyntax, ) -> Option<(PathBuf, Vec)> { let scopes = syntax.file_scopes(index, file)?; let mut child = stack.to_vec(); child.push(segment.to_string()); if scopes.scope_with_stack(&child).is_some() { return Some((file.to_path_buf(), child)); } let key = (file.to_path_buf(), segment.to_string()); syntax .mod_children(index) .get(&key) .and_then(|next| Some((next.clone()?, Vec::new()))) } /// #9971: follow exactly one module `use` re-export in the current /// scope when an inline or out-of-line child module is absent. fn follow_module_reexport( &self, index: &RustIndex, syntax: &OwnerPinSyntax, parent_scope: ScopeContext<'_>, segment: &str, reexport_hops: u8, ) -> Option<(PathBuf, Vec)> { let scopes = syntax.file_scopes(index, parent_scope.file)?; let module = scopes.scope_with_stack(parent_scope.stack)?; let reexports: Vec<&UsePath> = module .uses .iter() .filter(|use_path| { use_path.alias.is_none() && !use_path.path.contains('*') && split_binding_use(use_path, segment).is_some() }) .collect(); if reexports.len() != 1 { return None; } let use_path = reexports[0]; let stripped = use_path.path.strip_prefix("::").unwrap_or(&use_path.path); let module_segments: Vec<&str> = stripped.split("::").map(strip_raw).collect(); if module_segments.last().copied() != Some(segment) { return None; } if use_path.path.starts_with("::") { let root = composed_root(parent_scope.file, index); let source = index.files().get(&root)?.data().source.as_ref(); let scope_at_root = ScopeContext { file: &root, source, stack: &[], }; let [first, rest @ ..] = module_segments.as_slice() else { return None; }; return self.resolve_use_prefix( first, rest, scope_at_root, index, syntax, reexport_hops, ); } let [first, rest @ ..] = module_segments.as_slice() else { return None; }; if let Some((file, stack)) = Self::local_module_child(parent_scope.file, parent_scope.stack, first, index, syntax) { return self.resolve_module_path( index, syntax, parent_scope, &file, &stack, rest, reexport_hops, ); } self.resolve_use_prefix(first, rest, parent_scope, index, syntax, reexport_hops) } #[allow( clippy::too_many_arguments, reason = "policy:9971: module path walk carries file, inline stack, segments, and one re-export hop budget" )] fn resolve_module_path( &self, index: &RustIndex, syntax: &OwnerPinSyntax, _scope: ScopeContext<'_>, file: &Path, stack: &[String], segments: &[&str], reexport_hops: u8, ) -> Option<(PathBuf, Vec)> { let mut file = file.to_path_buf(); let mut stack = stack.to_vec(); for segment in segments { let source = index.files().get(&file)?.data().source.as_ref(); let scopes = syntax.file_scopes(index, &file)?; let mut child = stack.clone(); child.push(segment.to_string()); if scopes.scope_with_stack(&child).is_some() { stack = child; continue; } let key = (file.clone(), segment.to_string()); if let Some(next) = syntax.mod_children(index).get(&key) { file = next.clone()?; stack = Vec::new(); continue; } if reexport_hops == 0 { return None; } let parent_scope = ScopeContext { file: &file, source, stack: &stack, }; let (next_file, next_stack) = self.follow_module_reexport( index, syntax, parent_scope, segment, reexport_hops - 1, )?; file = next_file; stack = next_stack; } Some((file, stack)) } /// #7097: whether a resolved module delivers the owner: it holds no /// twin of the name, and either is the owner's own module or /// transports one `use` resolving exactly to it. fn resolved_module_delivers_owner( &self, target_file: PathBuf, target_stack: Vec, owner_inline: &[String], index: &RustIndex, syntax: &OwnerPinSyntax, ) -> bool { let Some(target_source) = index .files() .get(&target_file) .map(|facts| facts.data().source.clone()) else { return false; }; let Some(target_scopes) = syntax.file_scopes(index, &target_file) else { return false; }; let Some(target) = target_scopes.scope_with_stack(&target_stack) else { return false; }; if self.scope_has_twin_binding( target, &target_file, &target_source, owner_inline, index, syntax, ) { return false; } if target_file == *self.owner_file && target_stack.as_slice() == owner_inline { return true; } let context = ScopeContext { file: &target_file, source: &target_source, stack: &target.stack, }; let (transports, _) = partition_name_uses(&target.uses, self.name); transports.iter().any(|transport| { self.use_resolves_to_owner_module(transport, context, owner_inline, index, syntax) }) } /// #7097: whether the glob `use_path` (`*`-terminated) delivers /// the owner's binding to `scope`: its target module resolves and /// holds the owner with no twin — the owner itself, or one `use` hop /// re-exporting it. An unplaced glob refuses: it may import a twin, /// and it can never import the workspace owner from a foreign crate. fn glob_delivers_owner( &self, use_path: &UsePath, scope: ScopeContext<'_>, owner_inline: &[String], index: &RustIndex, syntax: &OwnerPinSyntax, ) -> bool { let Some((first, prefix)) = split_glob_prefix(&use_path.path) else { return false; }; let Some((target_file, target_stack)) = self.resolve_use_prefix(first, &prefix, scope, index, syntax, 1) else { return false; }; self.resolved_module_delivers_owner(target_file, target_stack, owner_inline, index, syntax) } /// #7097: whether the first segment of a `use` path names the owner's /// library crate from `scope_file`'s crate: a manifest import name, or /// — in synthetic indexes without manifest authority — a workspace /// package name. A rename to the segment refuses. fn krate_root_names_owner_crate( &self, first: &str, scope_file: &Path, scope_source: &str, index: &RustIndex, ) -> bool { if first.is_empty() || file_renames_to(scope_source, first) { return false; } let owner_root = composed_root(self.owner_file, index); if index .member_crates .import_names(scope_file, &owner_root) .iter() .any(|name| name == first) { return true; } !index.member_crates.has_manifest_root() && crate_names_package(first, &index.package_names) } /// #7097: whether `scope` binds the owner's name to anything but the /// owner: a twin item or macro, or a `use` resolving anywhere but /// the owner's module. Globs need no hop here: a further glob only /// matters beside an owner binding (an ambiguity error either way) /// or without one (already refused). fn scope_has_twin_binding( &self, scope: &ModuleScope, scope_file: &Path, scope_source: &str, owner_inline: &[String], index: &RustIndex, syntax: &OwnerPinSyntax, ) -> bool { if scope.has_twin(self.name) { return true; } let context = ScopeContext { file: scope_file, source: scope_source, stack: &scope.stack, }; let (bindings, _) = partition_name_uses(&scope.uses, self.name); bindings.iter().any(|binding| { !self.use_resolves_to_owner_module(binding, context, owner_inline, index, syntax) }) } } /// #9971: whether a test-crate `use self::..` import in an integration test /// delivers the entry through the scope-aware resolver (including one library /// re-export hop through a test module). pub(in crate::analysis) fn integration_test_relative_import_delivers_entry( index: &RustIndex, test: &TestSummary, import_path: &str, entry: &FunctionSummary, ) -> bool { use super::call_identity::{source_may_splice_items, under_tests_dir}; if !under_tests_dir(&test.file) { return false; } let Some(facts) = index.files().get(&test.file) else { return false; }; if import_path.split("::").next() != Some("self") { return false; } if source_may_splice_items(&facts.source, true) { return false; } if flattened_use_paths(&facts.source) .iter() .any(|import| import.path.ends_with('*')) { return false; } let syntax = OwnerPinSyntax::default(); let Some(owner_inline) = syntax .item_nesting(index, &entry.file, &entry.name, entry.start_line) .map(|nesting| nesting.modules) else { return false; }; let binding = FreeOwnerBinding { name: &entry.name, owner_file: &entry.file, owner_start_line: entry.start_line, }; let Some(scopes) = syntax.file_scopes(index, &test.file) else { return false; }; let Some(scope) = scopes.scope_of_test(&facts.source, test) else { return false; }; let context = ScopeContext { file: &test.file, source: &facts.source, stack: &scope.stack, }; let use_path = UsePath { path: import_path.to_string(), alias: None, }; binding.use_names_owner(&use_path, context, &owner_inline, index, &syntax) } /// The bare-call identity gates applied to a borrowed check helper (#6482): /// the helper binds the owner's name nowhere (parameter, `let`, pattern, /// closure, nested `fn` or macro), and the calling test never names the /// owner, so no call-site argument can feed the owner's own value back in /// as the expected one (`check(4, weight(4))`). pub(in crate::analysis) fn helper_pins_owner_call( helper: &str, masked_test_body: &str, name: &str, ) -> bool { let masked = mask_comments_and_strings(helper); !binds_outside_let(&masked, name) && !bound_by_macro(&masked, name) && !test_body_defines_callee_fn(&masked, name) && test_body_let_shadow_line(&masked, name).is_none() && !contains_as_whole_word(masked_test_body, name) && whole_word_count(&masked, name) == 1 } /// How often `name` occurs as a whole identifier in `text`. A helper that /// names the owner anywhere besides its asserted call (`let e = owner(b);`, /// `let f = owner;`, `super::owner(b)`) may compare the owner with itself, /// and the test-body self-comparison scan never reads the helper. fn whole_word_count(text: &str, name: &str) -> usize { let is_ident = |ch: Option| ch.is_some_and(|ch| ch.is_alphanumeric() || ch == '_'); text.match_indices(name) .filter(|(at, found)| { !is_ident(text[..*at].chars().next_back()) && !is_ident(text[at + found.len()..].chars().next()) }) .count() } /// How a test calls `owner`: a bare call for a free function, a method call /// on a receiver of one of the owner's `impl` types, or `T::name(..)` for an /// associated function of an inherent `impl T` (#6617). `None` for a shape /// no pin reads (a trait or trait-impl associated function, a generic or /// ambiguous self type, a free fn with `self`). fn pin_call(owner: &FunctionSummary, index: &RustIndex) -> Option { Some(match (&owner.item.container, owner.item.has_self_param) { (FunctionContainer::Free, false) => PinCall::Bare, (FunctionContainer::Inherent { self_ty }, false) => PinCall::Associated { type_name: associated_owner_type(self_ty, index)?, }, (FunctionContainer::Inherent { self_ty }, true) => PinCall::Method { receivers: vec![declared_receiver(self_ty, index)?], trait_scope: None, }, ( FunctionContainer::TraitImpl { trait_path, self_ty, }, true, ) => PinCall::Method { receivers: vec![declared_receiver(self_ty, index)?], trait_scope: Some(TraitScope { trait_name: path_base_name(trait_path)?.to_string(), }), }, (FunctionContainer::Trait { trait_name }, true) => { let receivers = trait_impl_receivers(trait_name, index); if receivers.is_empty() { return None; } PinCall::Method { receivers, trait_scope: Some(TraitScope { trait_name: trait_name.clone(), }), } } _ => return None, }) } impl ReturnPathGate { /// The prelude variant names this gate's exit reasoning relies on. fn prelude_names(&self) -> &'static [&'static str] { match self { Self::EarlyHead("Some") => &["Some", "None"], Self::EarlyHead(_) | Self::Head("Err") | Self::ErrVariant { .. } => &["Ok", "Err"], Self::Adaptor { requires_ok: true, .. } => &["Ok", "Err"], // The closed subset reads `Ok(..)`, `Some(..)` and `None` by // spelling (#14786 review). Self::ClosedGuardReturn { .. } => &["Ok", "Err", "Some", "None"], _ => &[], } } fn admits(&self, expected: &str) -> bool { match self { Self::Any | Self::ReturnedClosure { .. } | Self::ShortCircuit(_) | Self::FixtureReceiver(_) => true, Self::Adaptor { requires_ok, .. } => { !requires_ok || constructor_call_span(expected.trim(), "Ok").is_some() } Self::LoopAccumulator { .. } => true, Self::Head(head) | Self::EarlyHead(head) => { constructor_call_span(expected.trim(), head).is_some() } Self::Exact(value) => expected.trim() == *value, Self::EarlyScalar { literal } => { super::boundary_pairing::same_scalar_literal(expected.trim(), literal) } Self::ErrVariant { qualifier, variant, .. } => { constructor_call_span(expected.trim(), "Err").is_some() && error_variant_key(expected.trim()) .is_some_and(|(q, v)| q == *qualifier && v == *variant) } Self::CloneReceiver => false, Self::WholeValueField(gate) => gate.admits(expected), // Read per call in `admits_candidate`, where the call's literal // arguments are known. Self::ClosedGuardReturn { .. } => true, } } } /// The module segments of a `CallShape::Path` prefix, which /// `path_call_prefix` admits only as `::`-separated plain identifiers. fn path_prefix_segments(prefix: &str) -> Vec { prefix .split("::") .map(|segment| segment.trim().to_string()) .collect() } #[derive(Clone, Copy)] enum CallShape<'a> { Bare, Method(&'a str), /// `Type::constructor(..).name(..)`: the receiver is built inline. Constructed(&'a str), /// `a::b::name(..)`: a free-function call through a module path of /// plain identifiers; holds the path before `::name` (#6974). Path(&'a str), /// `T::name(..)` with one CamelCase identifier `T` (#6617): an /// associated-function call; holds `T`. A module path never has a /// CamelCase segment ([`path_call_prefix`]), so the two never overlap. Associated(&'a str), } /// #12716: the one bare owner call in an assertion's text, for a pin whose /// reading kept no call text (`assert_eq!(owner(..).unwrap(), 4)`). It must be /// the only spelling of the owner and, for an unwrapped pin, be followed by /// exactly `.unwrap()`; the text through that suffix is returned. fn owner_call_in(assertion: &str, name: &str, unwrapped: bool) -> Option { let masked = mask_comments_and_strings(assertion); let mut found = None; let mut from = 0; while let Some(offset) = masked[from..].find(name) { let start = from + offset; from = start + name.len(); let before = masked[..start].chars().next_back(); let after = masked[from..].chars().next(); if before.is_some_and(|c| c.is_alphanumeric() || c == '_') || after.is_some_and(|c| c.is_alphanumeric() || c == '_') { continue; } if found.is_some() || before.is_some_and(|c| c == '.' || c == ':') { return None; } found = Some(start); } let start = found?; let open = start + masked[start..].find('(')?; let close = matching_close(&masked, open, b'(', b')')?; let rest = masked[close + 1..].trim_start(); let call = &masked[start..=close]; if unwrapped { rest.starts_with(".unwrap()") .then(|| format!("{call}.unwrap()")) } else { // Without call text and without an unwrap there is no exact shape. None } } /// Whether `owner` is declared `async fn`, read from the parsed `async` /// token of the one `fn ` item whose span holds the owner's start /// line. No parse, or no single match, reads as sync: an async owner then /// gets no `.await` credit, and its bare call (a future) does not compile. pub(super) fn declares_async(owner: &FunctionSummary, index: &RustIndex) -> bool { function_declaration_is_async(owner, index).unwrap_or(false) } /// Whether `owner` is a directly callable, always-available inherent /// associated fn of `ty` with no generic parameter spelled `ty`; unknown /// declarations are not authoritative. pub(in crate::analysis) fn inherent_factory_declaration_is_authoritative( owner: &FunctionSummary, ty: &str, index: &RustIndex, ) -> bool { index .source_syntax .get(index, &owner.file) .and_then(|snapshot| snapshot.inherent_factory_declaration_is_authoritative(owner, ty)) == Some(true) } /// Read the complete source declaration: indexed body slices start at `fn` /// and omit qualifiers such as `async`. Unknown/ambiguous declarations stay /// distinct from a synchronous declaration for execution admission. pub(in crate::analysis) fn function_declaration_is_async( owner: &FunctionSummary, index: &RustIndex, ) -> Option { index .source_syntax .get(index, &owner.file)? .declaration_is_async(owner) } /// A whole free call, not an unrelated method or associated call with the /// same name and a free call nested inside its arguments. Definition identity /// remains the caller's authority. pub(super) fn is_whole_free_owner_call(operand: &str, name: &str) -> bool { matches!( owner_call_shape(operand, name), Some(CallShape::Bare | CallShape::Path(_)) ) } /// #12796: the tuple struct `T` when the changed tail is exactly `T(e)` or /// `Self(e)`, the owner declares that type (or `Self`) as its return, and the /// constructor takes one argument. A tuple constructor's arity is its field /// count, so `owner(..).0` then reads exactly `e`, the changed expression. /// Whether `T` is a plain one-field integer struct is the test side's check /// ([`field_builtin_integer`]), which needs the shared syntax scan. fn tuple_projection_type(owner: &FunctionSummary, probe: &Probe) -> Option { let expression = collapse_whitespace(probe.expression.trim().trim_end_matches(';')); let open = expression.find('(')?; let head = expression[..open].trim(); let masked = mask_comments_and_strings(&expression); let closing = matching_close(&masked, open, b'(', b')')?; if closing + 1 != expression.len() || top_level_arguments(&expression[open + 1..closing]).len() != 1 { return None; } let impl_type = match &owner.item.container { FunctionContainer::Inherent { self_ty } | FunctionContainer::TraitImpl { self_ty, .. } if !self_ty.contains('<') => { Some(path_base_name(self_ty)?.to_string()) } _ => None, }; let type_name = if head == "Self" { impl_type.clone()? } else if is_plain_identifier(head) && head.starts_with(|ch: char| ch.is_ascii_uppercase()) { head.to_string() } else { return None; }; let declared = declared_return_type(&owner.body)?; (declared == type_name || (declared == "Self" && impl_type.as_deref() == Some(&type_name))) .then_some(type_name) } /// A method receiver written inline in the assertion operand: a struct /// literal or one parenthesized subexpression, not a binding name (#9092). fn inline_method_receiver(receiver: &str) -> bool { let receiver = receiver.trim(); if let Some(inner) = group_inner(receiver, '(', ')') { return inline_method_receiver(inner); } // A tuple-struct constructor call (`Money(2)`), typed by the same // binding authority as `let m = Money(2);` (#12796). if let Some(open) = receiver.find('(') { let head = receiver[..open].trim(); if is_plain_identifier(head) && head.starts_with(|ch: char| ch.is_ascii_uppercase()) { let masked = mask_comments_and_strings(receiver); return matching_close(&masked, open, b'(', b')') .is_some_and(|closing| receiver[closing + 1..].trim().is_empty()); } } let Some(open) = receiver.find('{') else { return false; }; let head = receiver[..open].trim(); if !head.is_empty() && !is_plain_identifier(head) { return false; } let masked = mask_comments_and_strings(receiver); let Some(closing) = matching_close(&masked, open, b'{', b'}') else { return false; }; receiver[closing + 1..].trim().is_empty() } /// The operand as a complete call of `name`: `name(..)` or `recv.name(..)` /// with a plain identifier receiver and nothing chained after the call. fn owner_call_shape<'a>(operand: &'a str, name: &str) -> Option> { let operand = operand.trim(); if let Some(inner) = unsafe_block_value(operand) { return owner_call_shape(inner, name); } if let Some(receiver) = constructed_receiver(operand, name) { let call_start = receiver.len() + 1; let masked = mask_comments_and_strings(operand); let closing = matching_close(&masked, call_start + name.len(), b'(', b')')?; return operand[closing + 1..] .trim() .is_empty() .then_some(CallShape::Constructed(receiver)); } if let Some(prefix) = path_call_prefix(operand, name) { let opening = prefix.len() + "::".len() + name.len(); let masked = mask_comments_and_strings(operand); let closing = matching_close(&masked, opening, b'(', b')')?; return operand[closing + 1..] .trim() .is_empty() .then_some(CallShape::Path(prefix)); } if let Some(type_name) = associated_call_type(operand, name) { let opening = type_name.len() + "::".len() + name.len(); let masked = mask_comments_and_strings(operand); let closing = matching_close(&masked, opening, b'(', b')')?; return operand[closing + 1..] .trim() .is_empty() .then_some(CallShape::Associated(type_name)); } let (call_start, constructed) = if operand.starts_with(name) { (0, false) } else { let dot = operand.find('.')?; let receiver = operand[..dot].trim(); if receiver == "self" || !operand[dot + 1..].starts_with(name) { return None; } let constructed = if is_plain_identifier(receiver) { false } else if inline_method_receiver(receiver) { true } else { return None; }; (dot + 1, constructed) }; let after_name = &operand[call_start + name.len()..]; if !after_name.starts_with('(') { return None; } let masked = mask_comments_and_strings(operand); let opening = call_start + name.len(); let closing = matching_close(&masked, opening, b'(', b')')?; if !operand[closing + 1..].trim().is_empty() { return None; } Some(if call_start == 0 { CallShape::Bare } else if constructed { CallShape::Constructed(&operand[..call_start - 1]) } else { CallShape::Method(&operand[..call_start - 1]) }) } /// RIPR-SPEC-0225 rule 1: the initializer of the local binding an operand /// names, which the caller then reads as the owner call (or, under decision /// 6, its `.unwrap()`). The operand is a plain name that the test binds /// once, with `let name = ;` (an optional type annotation, never `mut`), /// and mentions nowhere else: any other use could borrow it mutably, /// shadow it, write through it or copy a field of it into the expected /// value. A macro that may bind the name refuses it too. fn bound_owner_initializer<'a>( test: &'a TestSummary, operand: &str, owner: &str, ) -> Option<&'a str> { let name = operand.trim(); if !is_plain_identifier(name) || name == owner { return None; } let masked = mask_comments_and_strings(&test.body); let uses = whole_word_offsets(&masked, name); let [first_use, _] = uses[..] else { return None; }; if bound_by_macro(&masked, name) { return None; } let mut bindings = whole_word_offsets(&masked, "let") .into_iter() .filter_map(|start| { // Only the test block's own statements: a `let` in an inner // block goes out of scope, and the operand may then name an // outer item. let before = &masked[..start]; if before.matches('{').count() != before.matches('}').count() + 1 { return None; } // An attribute (`#[cfg(..)] let c = ..;`) may compile the // binding away, leaving the operand naming some outer item. if before.trim_end().ends_with(']') { return None; } // The binding is the name's first occurrence, so the // assertion's use comes after it, not before a shadowing `let`. let named = masked[start + 3..].trim_start(); if masked.len() - named.len() != first_use { return None; } let rest = named.strip_prefix(name)?; if rest.starts_with(|ch: char| ch.is_ascii_alphanumeric() || ch == '_') { return None; } let rest = rest.trim_start(); // `let c = ..` or `let c: T = ..`; a type cannot hold `=`. if !rest.starts_with(['=', ':']) { return None; } let equals = masked.len() - rest.len() + rest.find('=')?; if masked[equals + 1..].starts_with(['=', '>']) { return None; } let end = equals + masked[equals..].find(';')?; Some((equals, end)) }); let (Some((equals, end)), None) = (bindings.next(), bindings.next()) else { return None; }; test.body.get(equals + 1..end) } /// The claims macros that compare an `Ok`/`Some` payload with an expected /// operand (RIPR-SPEC-0197 claims payload equality pins). fn claims_eq_macros() -> impl Iterator { claims_macro_names(ClaimsMacroKind::PayloadEq) } /// Whether `text` is exactly one plain `assert_ok_eq!(..)` / /// `assert_some_eq!(..)` statement. Text only nominates a candidate; the /// owner pin's verified-import decision grades it. pub(in crate::analysis) fn is_claims_payload_eq_text(text: &str) -> bool { claims_eq_macros().any(|name| claims_eq_operands(text, name).is_some()) } /// Plain `assert_ok_eq!(..)` / `assert_some_eq!(..)` statements of `test` /// that extraction did not list, on one line or spread over several. Extraction /// stays text-only and lists no oracle for these macros (RIPR-SPEC-0120), so /// reveal nominates them here as `unknown` / none candidates and keeps one only /// when the owner pin admits it. A statement that starts a line is read through /// its matching `)`; anything else on the closing line besides the `;` and a /// comment (a second statement, a chained call) is not nominated (fail closed). pub(in crate::analysis) fn claims_payload_eq_candidates(test: &TestSummary) -> Vec { if !claims_eq_macros().any(|name| test.body.contains(name)) { return Vec::new(); } let masked_body = mask_comments_and_strings(&test.body); let mut line_start = 0usize; let mut candidates: Vec = Vec::new(); for (offset, raw_line) in test.body.split_inclusive('\n').enumerate() { let start_of_line = line_start; line_start += raw_line.len(); let line = raw_line.trim_end_matches(['\n', '\r']); let text = line.trim(); let at = test.start_line + offset; // The invocation alone, with its statement `;`: a trailing comment // is not part of the key the syntax admission looks up. let masked = mask_comments_and_strings(text); let single = masked.rfind(')').and_then(|close| { let terminated = masked[close + 1..].contains(';'); let mut call = text.get(..=close)?.to_string(); if terminated { call.push(';'); } is_claims_payload_eq_text(&call).then_some(call) }); let Some(call) = single.or_else(|| { multiline_claims_eq_text( &test.body, &masked_body, start_of_line + (line.len() - line.trim_start().len()), ) }) else { continue; }; if test.assertions.iter().any(|fact| fact.line == at) { continue; } candidates.push(OracleFact { line: at, observed_tokens: crate::analysis::extract::extract_identifier_tokens(&call), text: call, kind: crate::domain::OracleKind::Unknown, strength: crate::domain::OracleStrength::None, ok_value_observed: None, }); } // The statements extraction drops as never run (after `panic!`, `todo!`, // `return`, ...) are not nominated either; the owner pin does not read the // diverging macros, so this is the only gate for them. crate::analysis::extract::retain_reached_oracles(&mut candidates, &test.body, test.start_line); candidates } /// The raw text of a claims payload-equality statement that opens at byte /// `start` of `body` and closes on a later line, as the syntax admission keys /// it: from the macro name through the `;` that ends it on the closing line /// (or through the `)` without one). `None` when the statement closes on its /// own line (the single-line path reads it), is not a claims equality macro, /// or shares its closing line with anything but a `;` and a comment. fn multiline_claims_eq_text(body: &str, masked: &str, start: usize) -> Option { let name = claims_eq_macros().find(|name| { masked .get(start..) .is_some_and(|rest| rest.starts_with(name)) })?; let after_bang = masked[start + name.len()..] .trim_start() .strip_prefix('!')? .trim_start(); let open = masked.len() - after_bang.len(); let close = matching_close(masked, open, b'(', b')')?; if !masked[start..close].contains('\n') { return None; } let rest_of_line = masked[close + 1..].split('\n').next().unwrap_or(""); let semicolon = rest_of_line.trim_start().strip_prefix(';'); let tail = semicolon.unwrap_or(rest_of_line); if !tail.trim().is_empty() { return None; } let end = match semicolon { Some(_) => close + 1 + rest_of_line.find(';')? + 1, None => close + 1, }; let text = body.get(start..end)?; is_claims_payload_eq_text(text).then(|| text.to_string()) } /// RIPR-SPEC-0197 claims payload equality: the two compared operands of one /// plain `assert_ok_eq!(left, right[, message..])` / `assert_some_eq!(..)` /// invocation named `spelling`. `left` is evaluated once and must hold the /// named variant; its payload is compared with `right`. Message arguments /// decide nothing. `None` for a path-qualified invocation, extra /// invocations in the statement or fewer than two arguments, so the caller /// refuses. The caller verifies the `claims` import. fn claims_eq_operands<'a>(text: &'a str, spelling: &str) -> Option<[&'a str; 2]> { if !is_plain_macro(text, spelling) { return None; } let masked = mask_comments_and_strings(text); let start = masked.find(spelling)?; let after_bang = masked[start + spelling.len()..] .trim_start() .strip_prefix('!')? .trim_start(); let open = masked.len() - after_bang.len(); if masked.as_bytes().get(open) != Some(&b'(') { return None; } let close = matching_close(&masked, open, b'(', b')')?; // Whatever follows the call is at most the statement's `;`. if !masked[close + 1..] .trim() .trim_start_matches(';') .trim() .is_empty() { return None; } match split_top_level_arguments(&text[open + 1..close])?.as_slice() { [left, right, ..] => Some([left.trim(), right.trim()]), _ => None, } } /// The claims macro name and operand call when `operand` is exactly /// `assert_ok!()` or `assert_some!()`: each evaluates its operand /// once, panics on the other variant and yields the payload, so a passing /// test read the call's `Ok`/`Some` payload as `.unwrap()` would. The caller /// verifies the `claims` import. fn claims_payload_call(operand: &str) -> Option<(&'static str, &str)> { let operand = operand.trim(); let masked = mask_comments_and_strings(operand); let name = claims_macro_names(ClaimsMacroKind::Payload).find(|name| masked.starts_with(name))?; let after_bang = masked[name.len()..] .trim_start() .strip_prefix('!')? .trim_start(); let open = masked.len() - after_bang.len(); if masked.as_bytes().get(open) != Some(&b'(') { return None; } let close = matching_close(&masked, open, b'(', b')')?; masked[close + 1..] .trim() .is_empty() .then_some((name, operand[open + 1..close].trim())) } /// RIPR-SPEC-0225 decision 6: the call `operand` unwraps, when it is /// `.unwrap()` or `.expect("..")` with one plain string literal /// message. Both panic on `Err`/`None`, so a passing comparison of the /// unwrapped value reads the call's `Ok`/`Some` payload. `Result::unwrap` /// and `Option::unwrap` are inherent, so no trait method can stand in. fn unwrapped_call(operand: &str) -> Option<&str> { let operand = operand.trim(); if let Some(call) = operand.strip_suffix(".unwrap()") { return Some(call.trim_end()); } let (call, message) = operand.strip_suffix(')')?.rsplit_once(".expect(")?; let message = message.trim(); let literal = message .strip_prefix('"') .and_then(|rest| rest.strip_suffix('"')) .is_some_and(|inner| !inner.contains(['"', '\\'])); literal.then(|| call.trim_end()) } /// #7063: the call `operand` unwraps the error of, when it is /// `.unwrap_err()` or `.expect_err("..")` with one plain string /// literal message. Both panic on `Ok`, so a passing comparison of the /// unwrapped value reads the call's `Err` payload. fn unwrapped_err_call(operand: &str) -> Option<&str> { let operand = operand.trim(); if let Some(call) = operand.strip_suffix(".unwrap_err()") { return Some(call.trim_end()); } let (call, message) = operand.strip_suffix(')')?.rsplit_once(".expect_err(")?; let message = message.trim(); let literal = message .strip_prefix('"') .and_then(|rest| rest.strip_suffix('"')) .is_some_and(|inner| !inner.contains(['"', '\\'])); literal.then(|| call.trim_end()) } /// #6974: whether `test`'s crate (or the workspace) may bind `root` before /// the extern prelude does: a rename to it, a raw twin, or a `mod`, `use`, /// type or glob in the test's crate. An unplaced test crate binds. fn test_crate_binds_root( test: &TestSummary, root: &str, index: &RustIndex, syntax: &OwnerPinSyntax, ) -> bool { // #6648 (RIPR-SPEC-0279): a doc example is its own crate; only its // own source binds there. if let Some(source) = index.doctest_source(test) { return workspace_renames_to(index, root) || workspace_mentions_raw(index, root) || source_may_bind_root(source, root); } let roots = syntax.target_roots(index); let Some(test_root) = roots.root(&test.file, index) else { return true; }; let binds_key = (test_root, root.to_string()); let known = syntax .path_memo .borrow() .test_crate_binds .get(&binds_key) .copied(); known.unwrap_or_else(|| { let binds = workspace_renames_to(index, root) || workspace_mentions_raw(index, root) || test_crate_may_bind(&binds_key.0, root, index, roots); syntax .path_memo .borrow_mut() .test_crate_binds .insert(binds_key.clone(), binds); binds }) } /// #6974 review: whether the test's own crate may bind `root` before the /// extern prelude does: a `mod root`, a `use` binding `root`, or any glob /// in a file of the test's crate. A module or import of the name shadows /// the dependency, and a glob may bring one in. fn test_crate_may_bind( test_root: &Path, root: &str, index: &RustIndex, roots: &TargetRoots, ) -> bool { index.files().iter().any(|(path, facts)| { // An established out-of-line integration helper's private imports cannot // bind its crate root. A root glob is already checked at that root. // Missing ancestry/placement keeps possible shadows, rather than // borrowing this namespace exclusion from a representative chain. let private_helper = !roots.disabled && index.execution_context(path).is_some_and(|context| { !context.edges.is_empty() && context.roots.iter().all(|root| { root.parent() .and_then(Path::file_name) .is_some_and(|name| name == "tests") }) }); !private_helper && roots.may_belong(path, test_root, index) && !roots.only_under_other_declared_targets(path, test_root, index) && source_may_bind_root(&facts.source, root) }) } /// Whether `source` may bind `root` before the extern prelude does: a /// `mod root`, a type, trait or alias of the name, a `use` binding it, or /// a glob. fn source_may_bind_root(source: &str, root: &str) -> bool { let masked = mask_comments_and_strings(source); declared_module_names(&masked).contains(&root) // A type, trait or alias of the root's name shadows the // extern prelude too, turning `root::name` into an // associated item (#6974 rev-4 review). || declares_type(&masked, root) || ["trait", "type"].iter().any(|keyword| { whole_word_offsets(&masked, keyword).into_iter().any(|offset| { starts_with_word(masked[offset + keyword.len()..].trim_start(), root) }) }) || file_use_statements(source).iter().any(|statement| { use_statement_binds_name(statement, root) || statement.contains('*') }) } pub(super) use crate::analysis::syntax::has_cfg_attr; fn indexed_item_nesting( index: &RustIndex, file: &Path, name: &str, line: usize, allow_impl: bool, ) -> Option { index .source_syntax .get(index, file)? .item_nesting(name, line, allow_impl) } /// #7082: whether the out-of-line `mod ;` that `declaration` names, /// with its `mod` token on `line` of `parent`, carries a `cfg` or /// `cfg_attr`. An unreadable parent or declaration, or no such declaration /// on that line, fails closed. fn module_declaration_cfg_gated( index: &RustIndex, parent: &Path, declaration: &str, line: usize, ) -> bool { let name = declaration .split_whitespace() .skip_while(|word| *word != "mod") .nth(1) .map(|word| word.trim_end_matches(';')); let Some(name) = name.filter(|name| !name.is_empty()) else { return true; }; let name = name.strip_prefix("r#").unwrap_or(name); let Some(facts) = index.files().get(parent) else { return true; }; let source = &facts.source; let Some(parse) = parse_clean_source_file(source) else { return true; }; let line_of = |offset: u32| source[..offset as usize].matches('\n').count() + 1; let mut on_line = parse .tree() .syntax() .descendants() .filter_map(ast::Module::cast) .filter(|module| module.item_list().is_none()) .filter(|module| { module .mod_token() .is_some_and(|token| line_of(token.text_range().start().into()) == line) && module.name().is_some_and(|ident| { let text = ident.text().to_string(); text.strip_prefix("r#").unwrap_or(&text) == name }) }) .peekable(); on_line.peek().is_none() || on_line.any(|module| has_cfg_that_may_drop(&module)) } /// #7082: whether `node` carries an attribute that may drop or relocate it /// under some cfg: a `cfg`, or a `cfg_attr` whose attributes name `cfg`, /// `cfg_attr` or `path`. `#![cfg_attr(docsrs, feature(doc_cfg))]` and other /// lint or doc toggles cannot, so they keep the pin (#7104 review). fn has_cfg_that_may_drop(node: &impl ast::HasAttrs) -> bool { node.attrs().any(|attr| match attr.meta() { Some(ast::Meta::CfgMeta(_)) => true, Some(ast::Meta::CfgAttrMeta(meta)) => { cfg_attr_payload_may_drop(&meta.syntax().text().to_string()) } _ => false, }) } /// The attributes after a `cfg_attr(predicate, ..)`'s first top-level /// comma name `cfg`, `cfg_attr` or `path`; unreadable text fails closed. fn cfg_attr_payload_may_drop(text: &str) -> bool { let Some(open) = text.find('(') else { return true; }; let inner = &text[open + 1..]; // Scan the masked text: a comma inside a predicate string must not // select the payload boundary (#7104 review). Splitting the unmasked // text at a string comma leaves a dangling quote whose masking then // hides the real payload (`cfg_attr(mode = "a,b", cfg(..))` would // admit a droppable owner). The masker preserves byte length and the // matched comma is a literal `,` byte in both, so `at` slices the // original soundly. let masked_inner = mask_comments_and_strings(inner); let mut depth = 0_i32; let mut payload = None; for (at, character) in masked_inner.char_indices() { match character { '(' | '[' | '{' => depth += 1, ')' | ']' | '}' => depth -= 1, ',' if depth == 0 => { payload = Some(&inner[at + 1..]); break; } _ => {} } } // Strings and comments are masked first, so `doc = "path"` names no // `path` attribute. payload.is_none_or(|payload| { let payload = mask_comments_and_strings(payload); ["cfg", "cfg_attr", "path"] .iter() .any(|word| contains_as_whole_word(&payload, word)) }) } /// #6974 review: whether any workspace file spells `r#name`, a raw /// identifier that word matches on `name` miss. fn workspace_mentions_raw(index: &RustIndex, name: &str) -> bool { let raw = format!("r#{name}"); index.files().values().any(|facts| { facts.source.contains(raw.as_str()) && whole_word_offsets(&mask_comments_and_strings(&facts.source), name) .into_iter() .any(|offset| offset >= 2 && facts.source.get(offset - 2..offset) == Some("r#")) }) } /// The module path before `::name(` when `operand` starts `a::b::name(` /// with every segment a plain identifier: no leading `::`, generics, /// whitespace or type-cased segment (`Type::name(..)` is an associated /// function, not a free one). fn path_call_prefix<'a>(operand: &'a str, name: &str) -> Option<&'a str> { let mut end = 0; loop { let segment_end = end + operand[end..].find("::")?; let segment = &operand[end..segment_end]; if !is_plain_identifier(segment) || segment.starts_with(|character: char| character.is_ascii_uppercase()) { return None; } end = segment_end + "::".len(); if operand[end..] .strip_prefix(name) .is_some_and(|after| after.starts_with('(')) { return Some(&operand[..segment_end]); } } } /// #6617: `T` when `operand` starts `T::name(` with `T` one CamelCase /// identifier other than `Self`. fn associated_call_type<'a>(operand: &'a str, name: &str) -> Option<&'a str> { let (head, tail) = operand.split_once("::")?; (is_plain_identifier(head) && head != "Self" && head.starts_with(|character: char| character.is_ascii_uppercase()) && tail .strip_prefix(name) .is_some_and(|after| after.starts_with('('))) .then_some(head) } /// The value expression of `unsafe { }` when `operand` is exactly that /// block and the block holds one expression and no statement. Calling an /// `unsafe fn` needs the block, and the block's value is the call's value. fn unsafe_block_value(operand: &str) -> Option<&str> { let rest = operand.strip_prefix("unsafe")?; let open = operand.len() - rest.trim_start().len(); if !operand[open..].starts_with('{') { return None; } let masked = mask_comments_and_strings(operand); let close = matching_close(&masked, open, b'{', b'}')?; if !operand[close + 1..].trim().is_empty() || masked[open + 1..close].contains(';') { return None; } // Trim by the masked text so a `// SAFETY:` or `/* .. */` comment around // the call is not read as part of it. The call starts with its name and // ends with `)`, neither of which masking touches. let body = &masked[open + 1..close]; let start = body.len() - body.trim_start().len(); let end = body.trim_end().len(); (start < end).then(|| &operand[open + 1 + start..open + 1 + end]) } /// The receiver of `Type::constructor(..).name(` when `operand` starts with /// one associated-function call on a capitalized type path and the method /// call follows it directly. fn constructed_receiver<'a>(operand: &'a str, name: &str) -> Option<&'a str> { let separator = operand.find("::")?; let type_name = &operand[..separator]; if !is_plain_identifier(type_name) || !type_name.starts_with(|character: char| character.is_ascii_uppercase()) { return None; } let call = &operand[separator + 2..]; let call_end = call.find(|character: char| !(character.is_ascii_alphanumeric() || character == '_'))?; if call_end == 0 || !call[call_end..].starts_with('(') { return None; } let opening = separator + 2 + call_end; let masked = mask_comments_and_strings(operand); let closing = matching_close(&masked, opening, b'(', b')')?; let after = &operand[closing + 1..]; let method = after.strip_prefix('.')?; (method.starts_with(name) && method[name.len()..].starts_with('(')) .then_some(&operand[..=closing]) } /// The span of `head(..)` when `text` is exactly one `head(..)` call. fn constructor_call_span(text: &str, head: &str) -> Option { let rest = text.strip_prefix(head)?; if !rest.starts_with('(') { return None; } let masked = mask_comments_and_strings(text); let closing = matching_close(&masked, head.len(), b'(', b')')?; text[closing + 1..].trim().is_empty().then_some(closing) } /// #14387: [`ReturnPathGate::ClosedGuardReturn`] when the changed line is /// the whole statement `return ;` (the changed expression `return /// ` before and after) or a tail branch's bare ``, so the change /// moves only that exit's returned value, and the closed integer subset reads /// the owner in both versions. The /// guard condition and every other exit are then the same in both, and the /// pin's literal arguments decide per call which exit runs. fn closed_guard_return( body: &str, name: &str, changed_line: usize, expression: &str, before: Option<&str>, ) -> Option { let (expression, before) = (expression.trim(), before?.trim()); let value = |text: &str| !text.trim().is_empty() && !text.contains([';', '{', '}']); let returned = |text: &str| text.strip_prefix("return ").is_some_and(value); let after = body.lines().nth(changed_line)?; // A guard's `return ;`, or a tail branch's bare `` on its // own line (`if c { .. } else { .. }`, probed since #14385): the closed subset then // reads both versions, so the line's place in the owner is its reading. let (statement, old_statement) = if returned(expression) && returned(before) { (format!("{expression};"), format!("{before};")) } else if value(expression) && value(before) && !expression.starts_with("return ") && !before.starts_with("return ") { (expression.to_string(), before.to_string()) } else { return None; }; if after.trim() != statement { return None; } let old_line = after.replacen(&statement, &old_statement, 1); let change = super::owner_value::ClosedChange::read(body, name, changed_line, &old_line)?; Some(ReturnPathGate::ClosedGuardReturn { change, old_line }) } /// Whether the owner's return value can only have come through the changed /// expression, and if so what the pinned value must look like. /// `changed_line` is the changed line's offset from the body's first line; /// the tail must span it, so an identical expression elsewhere in the body /// is not mistaken for the changed one. #[cfg(test)] fn return_path_gate(body: &str, expression: &str, changed_line: usize) -> Option { return_path_gate_from(body, expression, None, changed_line) } /// [`return_path_gate`] with the changed line's old text, when the diff /// pairs one: only the part that differs must be evaluated on every input /// (see [`changed_part_evaluates_conditionally`]). fn return_path_gate_from( body: &str, expression: &str, before: Option<&str>, changed_line: usize, ) -> Option { let masked = mask_comments_and_strings(body); let open = body_block_open(&masked)?; let close = matching_close(&masked, open, b'{', b'}')?; let inner = &masked[open + 1..close]; let inner_text = &body[open + 1..close]; let changed = collapse_whitespace(expression.trim().trim_end_matches(';')); let changed = changed .strip_prefix("return ") .map_or(changed.as_str(), str::trim); if changed.is_empty() { return None; } let spans_changed_line = |start: usize, end: usize| { let line_of = |offset: usize| body[..open + 1 + offset].matches('\n').count(); let text = &inner_text[start..end]; let first = start + (text.len() - text.trim_start().len()); let last = start + text.trim_end().len(); (line_of(first)..=line_of(last)).contains(&changed_line) }; let (after_semicolon, after_brace) = top_level_tail_starts(inner); // Comments between the last statement and the tail (`// SAFETY: ..` // before an `unsafe` block) are not part of the tail, so the tail is // compared with comments and strings masked on both sides. Masking // also hides string contents, so the unmasked tail must still end // with the changed text (`Ok("a")` is not `Ok("b")`). let masked_changed = collapse_whitespace(&mask_comments_and_strings(changed)); let tail_is_changed = [after_semicolon, after_brace].into_iter().any(|start| { // A comment after the tail (`1 + x // assert_eq!(..)`) is masked to // blanks, so the code ends where the masked tail does; reading the // unmasked rest would compare the comment with the changed text. // Masking also blanks string and char literals, so the code ends at // the masked end only when a real comment starts there. let masked_end = start + inner[start..].trim_end().len(); let rest = inner_text[masked_end..].trim_start(); let comment_follows = rest.starts_with("//") || rest.starts_with("/*"); let code_end = if comment_follows { masked_end } else { inner_text.len() }; let tail = collapse_whitespace(&inner_text[start..code_end]); (tail == changed || (collapse_whitespace(&inner[start..]) == masked_changed && tail.ends_with(changed))) && spans_changed_line(start, inner_text.len()) }); // `return ;` as the final statement is also the tail. let final_return_is_changed = !tail_is_changed && inner[after_semicolon..].trim().is_empty() && final_statement(inner, after_semicolon).is_some_and(|(start, end)| { collapse_whitespace(&inner_text[start..end]) .strip_prefix("return ") .is_some_and(|value| value.trim() == changed) && spans_changed_line(start, end) }); if !tail_is_changed && !final_return_is_changed { if has_unbounded_macro(inner) { return None; } return early_return_gate(body, inner, inner_text, changed, &spans_changed_line) .or_else(|| err_variant_gate(body, inner, inner_text, changed, &spans_changed_line)) .or_else(|| { scalar_early_return_gate(body, inner, inner_text, changed, &spans_changed_line) }); } if has_unbounded_macro(inner) { return None; } let returns = whole_word_offsets(inner, "return"); let other_returns = returns.len() - usize::from(final_return_is_changed); let early_exits = inner.bytes().filter(|byte| *byte == b'?').count() + other_returns; // The uncollapsed expression: collapsing would also merge whitespace // inside a string literal that the change touched. // RIPR-SPEC-0265 rule 4: a `std::thread::spawn(move || e).join().unwrap()` // tail runs `e` once on every input and returns its value, so the closure's // own `||` is not a short circuit and the change is read inside `e`. let thread_pair = spawn_join_body(expression).zip(before.and_then(spawn_join_body)); let conditional = match &thread_pair { Some((body, before_body)) => changed_part_evaluates_conditionally(body, Some(before_body)), None => changed_part_evaluates_conditionally(expression, before), }; if conditional { // RIPR-SPEC-0197 rule 3: a pure `&&`/`||` chain is the one // conditional tail a pin may observe, and only on a pinned call // that evaluates every operand (checked per test). return (early_exits == 0) .then(|| short_circuit::ShortCircuitTail::parse(body, changed)) .flatten() .map(ReturnPathGate::ShortCircuit); } if early_exits == 0 { return Some(ReturnPathGate::Any); } // #13037 Defect A: a scalar literal tail beside early returns that build // only different scalar literals is the owner's only source of its value, // like `Any` but multi-exit. Refused when any exit may alias the tail // value (a parameter, computed exit or same literal elsewhere). if !conditional && !inner.contains('?') && scalar_exits_are_distinct_literals(inner, inner_text, changed).is_some() { return Some(ReturnPathGate::EarlyScalar { literal: changed.to_string(), }); } let (head, other) = if constructor_call_span(changed, "Ok").is_some() { ("Ok", "Err") } else if constructor_call_span(changed, "Some").is_some() { ("Some", "None") } else { return None; }; let head_calls = whole_word_offsets(inner, head) .into_iter() .filter(|offset| inner[offset + head.len()..].trim_start().starts_with('(')) .count(); if head_calls != 1 { return None; } // Every other `return` must build the other constructor. When the // changed expression is the final `return`, it is the last one. let last = returns.len().checked_sub(1); let returns_agree = returns.iter().enumerate().all(|(position, offset)| { (final_return_is_changed && Some(position) == last) || starts_with_word(inner[offset + "return".len()..].trim_start(), other) }); returns_agree.then_some(ReturnPathGate::Head(head)) } /// #13037 Defect A, the propagation witness's owner-side question: whether the /// changed early `return ;` on `changed_line` is the owner's only exit /// producing ``. Returns the literal when the same fail-closed exit rule /// as the [`ReturnPathGate::EarlyScalar`] pin gate establishes it; the witness /// may then complete the direct-return edge, and reveal's per-test pin /// admission (the value check) remains the authority for whether a test /// observes the exit. pub(in crate::analysis) fn scalar_early_return_exit( body: &str, expression: &str, changed_line: usize, ) -> Option { let masked = mask_comments_and_strings(body); let open = body_block_open(&masked)?; let close = matching_close(&masked, open, b'{', b'}')?; let inner = &masked[open + 1..close]; let inner_text = &body[open + 1..close]; let changed = collapse_whitespace(expression.trim().trim_end_matches(';')); let changed = changed .strip_prefix("return ") .map_or(changed.as_str(), str::trim); let spans_changed_line = |start: usize, end: usize| { let line_of = |offset: usize| body[..open + 1 + offset].matches('\n').count(); let text = &inner_text[start..end]; let first = start + (text.len() - text.trim_start().len()); let last = start + text.trim_end().len(); (line_of(first)..=line_of(last)).contains(&changed_line) }; match scalar_early_return_gate(body, inner, inner_text, changed, &spans_changed_line)? { ReturnPathGate::EarlyScalar { literal } => Some(literal), _ => None, } } /// An early `return None;` / `return Err(..);` is the only source of that /// value when every other exit builds the opposite constructor: each other /// `return` and the tail are one `Some(..)` / `Ok(..)` call, and no `?` can /// produce a second `None` / `Err`. A pin expecting that value then observes /// the changed return. A second return of the same value, a `?`, or any /// other exit shape leaves the source ambiguous. /// /// RIPR-SPEC-0231 example 23: the mirror holds for an early /// `return Some(..);` / `return Ok(..);` when every other `return` and the /// tail are exactly `None` / one `Err(..)` call. A `?` there builds only the /// opposite constructor, so it does not compete. fn early_return_gate( body: &str, inner: &str, inner_text: &str, changed: &str, spans_changed_line: &dyn Fn(usize, usize) -> bool, ) -> Option { let some_call = |value: &str| constructor_call_span(value, "Some").is_some(); let ok_call = |value: &str| constructor_call_span(value, "Ok").is_some(); let err_call = |value: &str| constructor_call_span(value, "Err").is_some(); let is_none = |value: &str| value == "None"; // `other` names the changed value's constructor; `opposite` is the only // shape every other exit may build. A `?` builds `None` / `Err`, so it // is a second source of those but never of `Some(..)` / `Ok(..)`. let (gate, other, opposite, question_mark_agrees): (_, _, &dyn Fn(&str) -> bool, _) = if changed == "None" { (ReturnPathGate::Exact("None"), "None", &some_call, false) } else if err_call(changed) { (ReturnPathGate::Head("Err"), "Err", &ok_call, false) } else if some_call(changed) { (ReturnPathGate::EarlyHead("Some"), "Some", &is_none, true) } else if ok_call(changed) { (ReturnPathGate::EarlyHead("Ok"), "Ok", &err_call, true) } else { return None; }; // `return Err(if .. { A } else { B })`: a pin on `A` never evaluates a // changed `B`, as on the tail path. if (inner.contains('?') && !question_mark_agrees) || !returns_leave_the_function(body) || evaluates_conditionally(&mask_comments_and_strings(changed)) { return None; } let mut changed_returns = 0usize; for offset in whole_word_offsets(inner, "return") { let value_start = offset + "return".len(); let value_end = value_start + inner[value_start..].find(';')?; let value = collapse_whitespace(&inner_text[value_start..value_end]); let value = value.trim(); if starts_with_word(value, other) { if value != changed || !spans_changed_line(offset, value_end) { return None; } changed_returns += 1; } else if !opposite(value) { return None; } } let (after_semicolon, after_brace) = top_level_tail_starts(inner); let tail = collapse_whitespace(&inner_text[after_semicolon.max(after_brace)..]); let tail = tail.trim(); // The tail must itself build the opposite constructor: an empty tail // after a trailing `if .. { .. } else { None }` hides a second source. (changed_returns == 1 && opposite(tail)).then_some(gate) } /// #13037 Defect A: an early `return ;` whose value is a whole decimal /// scalar literal is the owner's only source of `` when every other /// `return` builds a different whole scalar literal and the tail is also a /// different whole scalar literal. A pin expecting `` on an owner call /// then observes the changed return: the sibling exits would return their own /// distinct literals and fail the pin, so a passing pin proves the changed /// exit ran. Fail closed (no gate) for a second source of the same literal /// (`return 0; .. 0`), a parameter or computed exit (which may alias `` /// for some input the gate does not read), a `?`, a nested-closure return, an /// unbounded macro, or a conditionally-evaluated changed value. fn scalar_early_return_gate( body: &str, inner: &str, inner_text: &str, changed: &str, spans_changed_line: &dyn Fn(usize, usize) -> bool, ) -> Option { if !super::boundary_pairing::is_whole_decimal_literal(changed) || evaluates_conditionally(&mask_comments_and_strings(changed)) || inner.contains('?') || !returns_leave_the_function(body) { return None; } let mut changed_returns = 0usize; for offset in whole_word_offsets(inner, "return") { let value_start = offset + "return".len(); let value_end = value_start + inner[value_start..].find(';')?; let value = collapse_whitespace(&inner_text[value_start..value_end]); let value = value.trim(); if !super::boundary_pairing::is_whole_decimal_literal(value) { // A parameter, const or computed exit may alias the changed // literal under an input this static read does not evaluate. return None; } if super::boundary_pairing::same_scalar_literal(value, changed) { // Only the changed line may produce this literal; a second // `return` of it elsewhere is a second source. if !spans_changed_line(offset, value_end) { return None; } changed_returns += 1; } } let (after_semicolon, after_brace) = top_level_tail_starts(inner); let tail = collapse_whitespace(&inner_text[after_semicolon.max(after_brace)..]); let tail = tail.trim(); (changed_returns == 1 && super::boundary_pairing::is_whole_decimal_literal(tail) && !super::boundary_pairing::same_scalar_literal(tail, changed)) .then(|| ReturnPathGate::EarlyScalar { literal: changed.to_string(), }) } /// #13037 Defect A, tail direction: whether every early `return` in `inner` /// builds a whole decimal scalar literal different from `changed`. Used for a /// scalar literal tail beside early returns: with the tail established as the /// changed expression and no `?` in the body, the tail is then the owner's /// only source of its value. A parameter, computed or same-literal return /// refuses (fail closed), as does a second return of the tail's own literal. fn scalar_exits_are_distinct_literals(inner: &str, inner_text: &str, changed: &str) -> Option<()> { if !super::boundary_pairing::is_whole_decimal_literal(changed) { return None; } for offset in whole_word_offsets(inner, "return") { let value_start = offset + "return".len(); let value_end = value_start + inner[value_start..].find(';')?; let value = collapse_whitespace(&inner_text[value_start..value_end]); let value = value.trim(); if !super::boundary_pairing::is_whole_decimal_literal(value) || super::boundary_pairing::same_scalar_literal(value, changed) { // A parameter/computed exit may alias the tail value; a return of // the tail's own literal is a second source of it. return None; } } Some(()) } /// #7063: the enum and variant segments (`ConfigError`, `MissingEquals`) of /// the one exact error variant an `Err(..)` construction builds, read by the /// shared RIPR-SPEC-0106 identity owner. A bare `Err(Variant ..)` (a glob /// import of the variants) names no enum and is refused. /// /// The text must be exactly one `Err(..)` call whose argument is the path, /// optionally followed by one `(..)` or `{ .. }` payload that ends the /// argument: `Err(E::V { line: 0 }.relabel())` or `Err(E::V(1) + x)` is a /// computed value that may be any variant, and is refused. Whether the last /// segment is a declared variant (not an associated constant such as /// `E::NO_EQUALS`) is [`error_enum_admits_variant_pin`]'s question. fn error_variant_key(text: &str) -> Option<(String, String)> { let text = text.trim(); constructor_call_span(text, "Err")?; let argument = text.strip_prefix("Err(")?.strip_suffix(')')?.trim(); let head_len = argument .find(|ch: char| !(ch.is_ascii_alphanumeric() || ch == '_' || ch == ':')) .unwrap_or(argument.len()); let head = &argument[..head_len]; let rest = argument[head_len..].trim_start(); if !rest.is_empty() { let masked = mask_comments_and_strings(rest); let (open, close) = match masked.as_bytes().first() { Some(b'(') => (b'(', b')'), Some(b'{') => (b'{', b'}'), _ => return None, }; if matching_close(&masked, 0, open, close)? + 1 != masked.len() { return None; } } local_variant_path(head) } /// #7063: the enum and variant of a variant path written `Type::Variant` or /// `crate::Type::Variant`. Any other prefix (`external::Type::Variant`, /// `self::`, `super::`, a leading `::`) may name a different enum that only /// shares the trailing names of a workspace one, so it names none here. fn local_variant_path(path: &str) -> Option<(String, String)> { let path = path.trim(); let path = path.strip_prefix("crate::").unwrap_or(path); let (qualifier, variant) = path.split_once("::")?; let (qualifier, variant) = (qualifier.trim(), variant.trim()); (is_plain_identifier(variant) && is_plain_identifier(qualifier)) .then(|| (qualifier.to_string(), variant.to_string())) } /// #7063: the enum and variant of a changed `[return ]Err(Type::Variant(..))` /// or `Err(Type::Variant { .. })` whose variant carries a payload. fn payload_variant_construction(expression: &str) -> Option<(String, String)> { let text = expression.trim().trim_end_matches(';').trim_end(); let text = text.strip_prefix("return ").map_or(text, str::trim); let key = error_variant_key(text)?; let argument = text.strip_prefix("Err(")?.strip_suffix(')')?; argument.trim_end().ends_with([')', '}']).then_some(key) } /// #7063: a changed early `return Err(Type::Variant ..);` beside other /// `return Err(..)` exits. A pin expecting `Err(Type::Variant ..)` observes /// the changed return when no other exit can build that variant: every other /// `return` and the tail build one `Ok(..)` call or one `Err(..)` call of a /// different variant of the same `Type` (an opaque `Err(e)` may hold any /// variant), the body has no `?` (a converted callee error may be any /// variant), and the changed value evaluates all of its parts. Exits are /// read by spelling, so the owner file's binding of `Ok` or `Err` refuses /// it as for the other early gates ([`ReturnPathGate::prelude_names`]). fn err_variant_gate( body: &str, inner: &str, inner_text: &str, changed: &str, spans_changed_line: &dyn Fn(usize, usize) -> bool, ) -> Option { constructor_call_span(changed, "Err")?; let (qualifier, variant) = error_variant_key(changed)?; if inner.contains('?') || !returns_leave_the_function(body) || evaluates_conditionally(&mask_comments_and_strings(changed)) { return None; } // `Some` when `value` is an exit that cannot build the changed variant, // `None` when it may. let siblings = std::cell::RefCell::new(BTreeSet::new()); let other_exit = |value: &str| { if constructor_call_span(value, "Ok").is_some() { return true; } match error_variant_key(value) { Some((q, v)) if q == qualifier && v != variant => { siblings.borrow_mut().insert(v); true } _ => false, } }; let mut changed_returns = 0usize; for offset in whole_word_offsets(inner, "return") { let value_start = offset + "return".len(); let value_end = value_start + inner[value_start..].find(';')?; let value = collapse_whitespace(&inner_text[value_start..value_end]); let value = value.trim(); if other_exit(value) { continue; } if value != changed || !spans_changed_line(offset, value_end) { return None; } changed_returns += 1; } let (after_semicolon, after_brace) = top_level_tail_starts(inner); let tail = collapse_whitespace(&inner_text[after_semicolon.max(after_brace)..]); (changed_returns == 1 && other_exit(tail.trim())).then(|| ReturnPathGate::ErrVariant { qualifier, variant, siblings: siblings.into_inner().into_iter().collect(), }) } /// Whether `text` starts with the whole word `word`. fn starts_with_word(text: &str, word: &str) -> bool { text.strip_prefix(word).is_some_and(|after| { !after.starts_with(|character: char| character.is_ascii_alphanumeric() || character == '_') }) } /// Byte offset of the `{` that opens the function body: the first brace /// after the parameter list closes. fn body_block_open(masked: &str) -> Option { let params = masked.find('(')?; let params_close = matching_close(masked, params, b'(', b')')?; masked[params_close..] .find('{') .map(|offset| params_close + offset) } /// Where the tail expression may start: after the last top-level `;`, and /// after the last top-level `}` (a block-like statement needs no `;`). fn top_level_tail_starts(inner: &str) -> (usize, usize) { let mut depth = 0usize; let mut after_semicolon = 0usize; let mut after_brace = 0usize; for (offset, byte) in inner.bytes().enumerate() { match byte { b'(' | b'[' | b'{' => depth += 1, b')' | b']' => depth = depth.saturating_sub(1), b'}' => { depth = depth.saturating_sub(1); if depth == 0 { after_brace = offset + 1; } } b';' if depth == 0 => after_semicolon = offset + 1, _ => {} } } (after_semicolon, after_brace.max(after_semicolon)) } /// The span of the top-level statement that ends at the `;` just before /// `end`, without the `;`. fn final_statement(masked: &str, end: usize) -> Option<(usize, usize)> { let statement_end = end.checked_sub(1)?; let (previous_semicolon, previous_brace) = top_level_tail_starts(&masked[..statement_end]); Some((previous_semicolon.max(previous_brace), statement_end)) } /// Macros that cannot return a value from the enclosing function. Any other /// macro in the owner body (`bail!`, `ensure!`, a crate's own macro) may /// hide a `return`, so the return paths are not established. The list is /// owned by the syntax scan, which also bounds the names a file's stored /// [`crate::analysis::syntax::MacroBindingCandidates`] can report. const NON_RETURNING_MACROS: &[&str] = TRUSTED_MACRO_NAMES; // `json` is a construction candidate only in assertion context. It must never // enter the owner-side generic non-returning list: an opaque owner macro can exit. fn assertion_context_macros() -> Vec<&'static str> { NON_RETURNING_MACROS .iter() .copied() .chain(["json"]) .collect() } /// Whether a macro named `name` neither returns nor binds a name, whatever /// file it sits in. fn is_bounded_macro(name: &str) -> bool { NON_RETURNING_MACROS.contains(&name) && !is_test_scoped_trusted_macro(name) } fn has_unbounded_macro(masked: &str) -> bool { macro_invocations(masked) .into_iter() .any(|(name, _)| !is_bounded_macro(name)) } /// Every `name!` macro invocation in masked text, with the offset of its /// opening delimiter. Whitespace may separate the name, the `!` and the /// delimiter (`ensure !(..)`); a keyword before `!` is a negation /// (`if !done`), not a macro. fn macro_invocations(masked: &str) -> Vec<(&str, usize)> { let bytes = masked.as_bytes(); let mut invocations = Vec::new(); for (offset, byte) in bytes.iter().enumerate() { if *byte != b'!' || bytes.get(offset + 1) == Some(&b'=') { continue; } let before = masked[..offset].trim_end(); // Step past the whole boundary character: a non-ASCII one is more // than one byte, and `position + 1` would split it (#7926 review). let start = before .char_indices() .rev() .find(|(_, character)| !(character.is_ascii_alphanumeric() || *character == '_')) .map_or(0, |(position, character)| position + character.len_utf8()); let name = &before[start..]; if !is_plain_identifier(name) || NEGATING_KEYWORDS.contains(&name) { continue; } let after = &masked[offset + 1..]; let delimiter = offset + 1 + (after.len() - after.trim_start().len()); if matches!(bytes.get(delimiter), Some(b'(' | b'[' | b'{')) { invocations.push((name, delimiter)); } } invocations } /// Keywords a `!` negation can follow; never macro names. const NEGATING_KEYWORDS: &[&str] = &[ "if", "while", "return", "match", "in", "else", "break", "let", "mut", "move", "as", "yield", "ref", "unsafe", "async", ]; /// The closure body of a tail that is exactly /// `std::thread::spawn().join().unwrap()`: the spawned /// closure runs once on every call and the join returns its value. `None` for /// any other text, including a `thread::spawn` path that `use` could rebind. pub(in crate::analysis) fn spawn_join_body(text: &str) -> Option { // The masked text keeps the byte layout of `text`, so structure is read // from it and the closure argument is cut from the unmasked text. let masked = mask_comments_and_strings(text); let start = masked.len() - masked.trim_start().len(); let end = masked.trim_end().trim_end_matches(';').trim_end().len(); let prefix = "std::thread::spawn"; let after = masked.get(start..end)?.strip_prefix(prefix)?; let open = start + prefix.len() + (after.len() - after.trim_start().len()); if masked.as_bytes().get(open) != Some(&b'(') { return None; } let close = matching_close(&masked, open, b'(', b')')?; let rest: String = masked .get(close + 1..end)? .chars() .filter(|ch| !ch.is_whitespace()) .collect(); if rest != ".join().unwrap()" { return None; } let argument = text.get(open + 1..close)?.trim(); let body = argument .strip_prefix("move") .map_or(argument, str::trim_start) .strip_prefix("||")? .trim(); (!body.is_empty()).then(|| body.to_string()) } /// #6578: whether the part of the changed tail that differs from its old /// text (`before`) is evaluated only on some inputs, or passes through code /// that may not use it. In `lines.iter().map(|l| l.cents).sum::() + 50` /// → `.. + 25 * 2` the closure is unchanged and the changed operand of the /// outer `+` runs on every input and reaches the sum directly, so the /// closure does not make the change conditional. /// /// Only a tail the whole-text check refuses is read more closely, and it is /// admitted only in one narrow shape: the changed span (the text between /// the longest common prefix and suffix) holds no closure, block, /// assignment or conditional text, and every node from it up to and /// including the tail is an operator that evaluates all its operands /// (arithmetic, comparison or bitwise; not `&&`, `||` or an assignment), a /// parenthesis, prefix operator or cast, or a call to a named function or /// method that is no skipping combinator and holds no closure anywhere. A /// closure beside the change in a call (`items.iter().map(|l| ..)` with /// `items` changed, `fold(51, |a, l| ..)`) may discard or transform it, and /// a block, labeled `break`, `const` or `async` around it may skip or /// rebind it, so each refuses. Without a paired old text, or when the tail /// does not parse as one expression, the whole tail is read as before. pub(super) fn changed_part_evaluates_conditionally(changed: &str, before: Option<&str>) -> bool { if !evaluates_conditionally(&mask_comments_and_strings(changed)) { return false; } let Some(span) = super::changed_span::ChangedSpan::of(changed, before) else { return true; }; // What the change removed may itself have been a closure, block, macro // or branch that gave the same value (`(|| 51)()` → `51`), so it must // be as plain as what replaced it. The removed text may start inside a // string, so it is read unmasked: a quoted `|` or `if` also refuses. let removed = span.removed.as_str(); if evaluates_conditionally(removed) || removed.contains(['|', '{', '!', '?']) || has_keyword( removed, &["return", "break", "async", "unsafe", "const", "static"], ) { return true; } if evaluates_conditionally(&mask_comments_and_strings( &span.covering.text().to_string(), )) || span.covering.descendants().any(|node| { ast::ClosureExpr::can_cast(node.kind()) || ast::BlockExpr::can_cast(node.kind()) || ast::Item::can_cast(node.kind()) || is_short_circuit_or_assignment(&node) }) { return true; } !span .enclosing() .iter() .all(|(ancestor, _)| evaluates_every_operand(ancestor)) } /// Whether `text` holds one of `keywords` as a whole word. fn has_keyword(text: &str, keywords: &[&str]) -> bool { text.split(|character: char| !character.is_alphanumeric() && character != '_') .any(|word| keywords.contains(&word)) } /// A `&&`/`||` or an assignment (`=`, `+=`, ..) operator. fn is_short_circuit_or_assignment(node: &SyntaxNode) -> bool { ast::BinExpr::cast(node.clone()).is_some_and(|binary| { binary.op_token().is_some_and(|op| { let op = op.text(); op == "&&" || op == "||" || (op.ends_with('=') && !matches!(op, "==" | "!=" | "<=" | ">=")) }) }) } /// Whether `node`, enclosing the changed span, evaluates every operand and /// passes the changed one on without a closure or skipping combinator. fn evaluates_every_operand(node: &SyntaxNode) -> bool { // An argument list is judged by the call that holds it. if ast::ArgList::can_cast(node.kind()) || ast::ParenExpr::can_cast(node.kind()) || ast::PrefixExpr::can_cast(node.kind()) || ast::CastExpr::can_cast(node.kind()) { return true; } if ast::BinExpr::can_cast(node.kind()) { return !is_short_circuit_or_assignment(node); } let name = if let Some(method) = ast::MethodCallExpr::cast(node.clone()) { method.name_ref().map(|name| name.text().to_string()) } else if let Some(call) = ast::CallExpr::cast(node.clone()) { match call.expr() { Some(ast::Expr::PathExpr(path)) => path .path() .and_then(|path| path.segment()) .and_then(|segment| segment.name_ref()) .map(|name| name.text().to_string()), _ => None, } } else { return false; }; name.is_some_and(|name| !CONDITIONAL_COMBINATORS.contains(&name.as_str())) && !node .descendants() .any(|inner| ast::ClosureExpr::can_cast(inner.kind())) } /// Whether the changed tail evaluates some of its parts only on some /// inputs: a closure or `|`/`||`/`&&` operator, a branch or loop, or a /// combinator that skips its argument (`map_or(0, ..)` on `None`). A pin on /// such an input never evaluates the changed part, so the tail's value is /// not established to come through it. /// /// A binary bitwise `|` evaluates both operands on every input, so it is /// not conditional (#6675); every other pipe (`||`, `|=`, a closure's /// parameter list) still is. See [`has_non_bitwise_pipe`]. fn evaluates_conditionally(masked_tail: &str) -> bool { if has_non_bitwise_pipe(masked_tail) || masked_tail.contains("&&") { return true; } if [ "if", "match", "else", "loop", "while", "for", "break", "continue", ] .iter() .any(|keyword| contains_as_whole_word(masked_tail, keyword)) { return true; } CONDITIONAL_COMBINATORS.iter().any(|combinator| { whole_word_offsets(masked_tail, combinator) .into_iter() .any(|offset| { let before = masked_tail[..offset].trim_end(); (before.ends_with('.') || before.ends_with("::")) && masked_tail[offset + combinator.len()..] .trim_start() .starts_with(['(', ':']) }) }) } /// #6692: whether the changed line (`changed_line`, offset from the body's /// first line) lies in a struct literal of `type_name` (or `Self`) that is /// the whole tail of `body`, and that literal is the body's only exit: no /// `?`, no `return`, no macro that may hide an exit, and no part evaluated /// only on some inputs. The changed line must be one whole field /// initializer of that literal's own braces (depth 1): a field of a nested /// literal or an argument of a call inside a field is not the outer /// field's value. fn clone_tail_literal_spans( body: &str, type_name: &str, changed_line: usize, expression: &str, ) -> bool { let masked = mask_comments_and_strings(body); let Some(open) = body_block_open(&masked) else { return false; }; let Some(close) = matching_close(&masked, open, b'{', b'}') else { return false; }; let inner = &masked[open + 1..close]; if has_unbounded_macro(inner) || inner.contains('?') || !whole_word_offsets(inner, "return").is_empty() { return false; } let (after_semicolon, _) = top_level_tail_starts(inner); let tail = &inner[after_semicolon..]; let tail_start = after_semicolon + (tail.len() - tail.trim_start().len()); let tail = tail.trim(); let Some(after_type) = tail .strip_prefix(type_name) .or_else(|| tail.strip_prefix("Self")) else { return false; }; let after_type = after_type.trim_start(); if !after_type.starts_with('{') { return false; } let literal_open = tail.len() - after_type.len(); let Some(literal_close) = matching_close(tail, literal_open, b'{', b'}') else { return false; }; if literal_close + 1 != tail.len() || evaluates_conditionally(tail) { return false; } let line_of = |offset: usize| masked[..open + 1 + offset].matches('\n').count(); let first = line_of(tail_start + literal_open); let last = line_of(tail_start + literal_close); if !(first < changed_line && changed_line < last) { return false; } let Some(line_start) = masked .match_indices('\n') .nth(changed_line - 1) .map(|(position, _)| position + 1) else { return false; }; let line_end = masked[line_start..] .find('\n') .map_or(masked.len(), |position| line_start + position); let literal_start = open + 1 + tail_start + literal_open; let depth = masked[literal_start..line_start] .bytes() .fold(0_isize, |depth, byte| match byte { b'{' | b'(' | b'[' => depth + 1, b'}' | b')' | b']' => depth - 1, _ => depth, }); let line = masked[line_start..line_end].trim(); let field_text = |text: &str| collapse_whitespace(text.trim().trim_end_matches(',').trim()); depth == 1 && !line.contains(['{', '}']) && field_text(&body[line_start..line_end]) == field_text(expression) } /// The struct literal an owner returns, as [`whole_value_tail`] reads it. struct WholeValueTail { /// The literal's type as written: its last path segment, or `Self`. type_name: String, /// `Ok` or `Some` when the tail wraps the literal in that constructor. wrapper: Option<&'static str>, /// `Err` or `None` when the owner also exits early through that /// constructor; it must be the prelude's, like the wrapper. early_exit: Option<&'static str>, } /// RIPR-SPEC-0225: the literal whose field `field` the changed line /// initializes, when that literal is the owner's tail value (directly, or as /// the one argument of a tail `Ok(..)`/`Some(..)`). The body may not /// `return`, nor hold a macro that may hide an exit, and `?` is allowed only /// around a wrapped tail, where it exits with `Err`/`None`, never the pinned /// constructor. The changed line must be the field's whole initializer, at /// the literal's top level, with a value evaluated on every input and no /// functional-update base in the literal. Fails closed on anything else. fn whole_value_tail( body: &str, changed_line: usize, field: &str, expression: &str, ) -> Option { let masked = mask_comments_and_strings(body); if has_unbounded_macro(&masked) { return None; } let returns = !whole_word_offsets(&masked, "return").is_empty(); let parse = parse_clean_source_file(body)?; let function = parse .tree() .syntax() .descendants() .find_map(ast::Fn::cast)?; let block = function.body()?; let mut tail = block.tail_expr()?; while let ast::Expr::ParenExpr(inner) = &tail { tail = inner.expr()?; } let (literal, wrapper) = match tail { ast::Expr::RecordExpr(literal) => (literal, None), ast::Expr::CallExpr(call) => { let wrapper = match call.expr()?.syntax().text().to_string().as_str() { "Ok" => "Ok", "Some" => "Some", _ => return None, }; let mut arguments = call.arg_list()?.args(); let (Some(ast::Expr::RecordExpr(literal)), None) = (arguments.next(), arguments.next()) else { return None; }; (literal, Some(wrapper)) } _ => return None, }; // RIPR-SPEC-0225 decision 6: beside an `Ok(..)`/`Some(..)` tail, an // early `return Err(..)`/`return None` exits with the other variant, as // `?` does, so every `Ok`/`Some` the owner returns is the tail literal. // Any other `return` may hand back another value of the wrapped type. if returns && !wrapper.is_some_and(|wrapper| { let returned = function .syntax() .descendants() .filter_map(ast::ReturnExpr::cast) .collect::>(); returned.len() == whole_word_offsets(&masked, "return").len() && returned .iter() .all(|exit| returns_other_variant(exit, wrapper)) }) { return None; } if wrapper.is_none() && block .syntax() .descendants() .any(|node| ast::TryExpr::can_cast(node.kind())) { return None; } let path = literal.path()?; // `Self::Variant { .. }` or `module::Type { .. }` names something other // than the type the equality gates read. if path.qualifier().is_some() || path .segments() .any(|segment| segment.generic_arg_list().is_some()) { return None; } let type_name = path.segment()?.name_ref()?.text().to_string(); let fields = literal.record_expr_field_list()?; if fields.spread().is_some() || fields.dotdot_token().is_some() { return None; } let mut named = fields.fields().filter(|candidate| { candidate .field_name() .is_some_and(|name| name.text().trim_start_matches("r#") == field) }); let (Some(initializer), None) = (named.next(), named.next()) else { return None; }; let range = initializer.syntax().text_range(); let line_of = |offset: usize| body[..offset].matches('\n').count(); let (first, last) = ( line_of(usize::from(range.start())), line_of(usize::from(range.end())), ); let value = initializer.expr()?; let field_text = |text: &str| collapse_whitespace(text.trim().trim_end_matches(',').trim()); (first == changed_line && last == changed_line && field_text(&initializer.syntax().text().to_string()) == field_text(expression) && !evaluates_conditionally(&mask_comments_and_strings( &value.syntax().text().to_string(), ))) .then_some(WholeValueTail { type_name, wrapper, early_exit: wrapper .filter(|_| returns) .map(|wrapper| if wrapper == "Ok" { "Err" } else { "None" }), }) } /// Whether `exit` is `return Err(..)` beside an `Ok` tail, or `return None` /// beside a `Some` tail: an exit with the variant the tail does not build. fn returns_other_variant(exit: &ast::ReturnExpr, wrapper: &str) -> bool { match (wrapper, exit.expr()) { ("Ok", Some(ast::Expr::CallExpr(call))) => call .expr() .is_some_and(|callee| callee.syntax().text() == "Err"), ("Some", Some(ast::Expr::PathExpr(path))) => path.syntax().text() == "None", _ => false, } } impl WholeValueField { /// The source text a literal `expected` gives the field (`3` for /// `Ok(Config { retries: 3 })`), when [`Self::admits`] reads it. fn pinned_field_text(&self, expected: &str) -> Option { let parse = parse_clean_source_file(&format!("fn ripr_expected() {{ ({expected}); }}"))?; let mut value = parse .tree() .syntax() .descendants() .find_map(ast::ParenExpr::cast)? .expr()?; if self.wrapper.is_some() { let ast::Expr::CallExpr(call) = value else { return None; }; value = call.arg_list()?.args().next()?; } let ast::Expr::RecordExpr(literal) = value else { return None; }; literal .record_expr_field_list()? .fields() .find(|candidate| { candidate .field_name() .is_some_and(|name| name.text().trim_start_matches("r#") == self.field) })? .expr() .map(|pinned| pinned.syntax().text().to_string()) } /// RIPR-SPEC-0225 rule 2: `expected` is a literal of the owner's type, /// in the owner's wrapper, that names the field once, explicitly, with an /// independent value ([`independent_value`]), and no functional-update /// base anywhere in it. fn admits(&self, expected: &str) -> bool { let Some(parse) = parse_clean_source_file(&format!("fn ripr_expected() {{ ({expected}); }}")) else { return false; }; let Some(mut value) = parse .tree() .syntax() .descendants() .find_map(ast::ParenExpr::cast) .and_then(|paren| paren.expr()) else { return false; }; if let Some(wrapper) = self.wrapper { let ast::Expr::CallExpr(call) = value else { return false; }; if call .expr() .is_none_or(|callee| callee.syntax().text() != wrapper) { return false; } let Some(mut arguments) = call.arg_list().map(|list| list.args()) else { return false; }; let (Some(inner), None) = (arguments.next(), arguments.next()) else { return false; }; value = inner; } let ast::Expr::RecordExpr(literal) = value else { return false; }; if literal.syntax().descendants().any(|node| { ast::RecordExprFieldList::cast(node) .is_some_and(|list| list.spread().is_some() || list.dotdot_token().is_some()) }) { return false; } // A bare name only: a qualified path (`external::Config`) may name // another type whose equality with the owner's ignores the field. let names_type = literal.path().is_some_and(|path| { path.qualifier().is_none() && path .segments() .all(|segment| segment.generic_arg_list().is_none()) && path .segment() .and_then(|segment| segment.name_ref()) .is_some_and(|name| name.text() == self.type_name.as_str()) }); let Some(fields) = literal.record_expr_field_list() else { return false; }; let mut named = fields.fields().filter(|candidate| { candidate .field_name() .is_some_and(|name| name.text().trim_start_matches("r#") == self.field) }); let (Some(pinned), None) = (named.next(), named.next()) else { return false; }; // A shorthand `field` reads a local binding of that name. names_type && pinned.name_ref().is_some() && pinned.expr().is_some_and(|value| { independent_value( &value, self.field_is_string, self.string_from_may_be_rebound, ) }) && !literal.syntax().descendants().any(|node| { ast::NameRef::cast(node.clone()) .is_some_and(|name| self.computed_names.contains(name.text())) // #7066 review: a bare CamelCase value the workspace never // declares as a type or variant may be a local binding. || ast::PathExpr::cast(node) .and_then(|path| path.path()) .filter(|path| path.qualifier().is_none()) .and_then(|path| path.segment()?.name_ref()) .is_some_and(|name| { !self.constructor_names.contains(name.text()) }) }) } } /// RIPR-SPEC-0225 rule 2: an expected value that cannot carry the owner's /// result: literals (negated too), tuples and arrays of them, unit and tuple /// variants or structs and struct literals named by a CamelCase path, and a /// string literal's `.to_string()`, `.to_owned()`, `String::from(..)`, or /// `.into()` when the field is a `String`. `String::from(..)` counts only /// when `String` names the standard type workspace-wide; a workspace /// `mod String` or rename makes the call an unknown function (#7066 review). /// A local binding, a constant, a workspace function or any other method can /// carry the owner's output (`retries: c.retries`, `RETRIES` from a /// `const fn`) and gives no credit. fn independent_value( value: &ast::Expr, string_field: bool, string_from_may_be_rebound: bool, ) -> bool { let string_literal = |expr: Option| { matches!(expr, Some(ast::Expr::Literal(literal)) if matches!(literal.kind(), ast::LiteralKind::String(_))) }; match value { ast::Expr::Literal(_) => true, ast::Expr::PrefixExpr(prefix) => { prefix.op_kind() == Some(ast::UnaryOp::Neg) && matches!(prefix.expr(), Some(ast::Expr::Literal(_))) } ast::Expr::ParenExpr(inner) => inner.expr().is_some_and(|inner| { independent_value(&inner, string_field, string_from_may_be_rebound) }), ast::Expr::TupleExpr(tuple) => tuple .fields() .all(|item| independent_value(&item, string_field, string_from_may_be_rebound)), ast::Expr::ArrayExpr(items) => { items.semicolon_token().is_none() && items .exprs() .all(|item| independent_value(&item, string_field, string_from_may_be_rebound)) } ast::Expr::PathExpr(path) => path.path().is_some_and(|path| constructor_path(&path)), ast::Expr::CallExpr(call) => { let Some(ast::Expr::PathExpr(callee)) = call.expr() else { return false; }; let Some(path) = callee.path() else { return false; }; let arguments = call.arg_list().map(|list| list.args().collect::>()); if path.syntax().text() == "String::from" { return !string_from_may_be_rebound && arguments.is_some_and(|arguments| { arguments.len() == 1 && string_literal(arguments.into_iter().next()) }); } constructor_path(&path) && arguments.is_some_and(|arguments| { arguments .iter() .all(|argument| independent_value(argument, false, false)) }) } ast::Expr::RecordExpr(literal) => { literal.path().is_some_and(|path| constructor_path(&path)) && literal.record_expr_field_list().is_some_and(|fields| { fields.spread().is_none() && fields.dotdot_token().is_none() && fields.fields().all(|field| { field.name_ref().is_some() && field .expr() .is_some_and(|value| independent_value(&value, false, false)) }) }) } ast::Expr::MethodCallExpr(call) => { let Some(method) = call.name_ref() else { return false; }; let method = method.text(); call.generic_arg_list().is_none() && call .arg_list() .is_some_and(|list| list.args().next().is_none()) && (method == "to_string" || method == "to_owned" || (method == "into" && string_field)) && string_literal(call.receiver()) } _ => false, } } /// CamelCase names of `const`, `static` and `fn` items anywhere in the /// workspace, and CamelCase `use .. as` aliases (`use crate::four as Four;` /// names a fn). Naming lints only warn on them, so [`constructor_path`]'s /// case test alone cannot tell `Limits::Max` (a constant) from `Mode::Fast`. /// An alias of a real type or variant is refused too, which fails closed. fn camel_case_value_items(index: &RustIndex) -> BTreeSet { let mut names = BTreeSet::new(); for facts in index.files().values() { let masked = mask_comments_and_strings(&facts.source); for keyword in ["const", "static", "fn", "as"] { for start in whole_word_offsets(&masked, keyword) { // `*const T`, `&'static T` and a cast's `as T` name a type, // not a value item; only an import's `as` renames. let before = masked[..start].trim_end(); let names_type = match keyword { "const" => before.ends_with('*'), "static" => before.ends_with('\''), "as" => !in_import_item(&masked, start), _ => false, }; if names_type { continue; } let rest = masked[start + keyword.len()..].trim_start(); let rest = rest.strip_prefix("mut ").map_or(rest, str::trim_start); let name: String = rest .chars() .take_while(|ch| ch.is_ascii_alphanumeric() || *ch == '_') .collect(); if name.starts_with(|ch: char| ch.is_ascii_uppercase()) && name.chars().any(|ch| ch.is_ascii_lowercase()) { names.insert(name); } } } } names } /// Whether the `as` at `offset` of `masked` sits in a `use` or `extern /// crate` item: the item's keyword follows the previous `;` (or the file /// start), and only path tokens (`a::{b, c::*}`, earlier renames) lie /// between it and the `as`. A cast's operand has other tokens (`(`, `.`, /// `=`) or no import keyword at all. fn in_import_item(masked: &str, offset: usize) -> bool { let statement_start = masked[..offset].rfind(';').map_or(0, |index| index + 1); let statement = &masked[statement_start..offset]; let Some(keyword_end) = ["use", "crate"] .iter() .filter_map(|keyword| { whole_word_offsets(statement, keyword) .last() .map(|start| start + keyword.len()) }) .max() else { return false; }; // Raw (`r#async`) and non-ASCII identifiers are path tokens too. statement[keyword_end..].chars().all(|ch| { ch.is_alphanumeric() || ch.is_whitespace() || matches!(ch, '_' | '#' | ':' | '{' | '}' | ',' | '*') }) } /// #7066 review: the struct, enum and union names every indexed file /// declares, the variants of each `enum` (names that open an item at the /// body's top level), and the standard `None`, `Some`, `Ok` and `Err`. /// Lexical: a name missed here only withholds credit. fn declared_constructor_names(index: &RustIndex) -> BTreeSet { let mut names: BTreeSet = ["None", "Some", "Ok", "Err"] .into_iter() .map(str::to_string) .collect(); let ident = |text: &str| -> String { text.trim_start() .chars() .take_while(|ch| ch.is_alphanumeric() || *ch == '_') .collect() }; for facts in index.files().values() { let masked = mask_comments_and_strings(&facts.source); for keyword in ["struct", "enum", "union"] { for offset in whole_word_offsets(&masked, keyword) { let rest = &masked[offset + keyword.len()..]; let name = ident(rest); if name.is_empty() { continue; } names.insert(name); if keyword != "enum" { continue; } let Some(open) = rest.find('{') else { continue; }; let mut depth = 0usize; let mut item_start = true; for (at, ch) in rest[open..].char_indices() { match ch { '{' | '(' | '[' => { depth += 1; if depth == 1 { item_start = true; } } '}' | ')' | ']' => { depth = depth.saturating_sub(1); if depth == 0 { break; } // An attribute's `]` leaves the variant to come. if depth == 1 && ch == ']' { item_start = true; } } ',' if depth == 1 => item_start = true, '#' if depth == 1 => {} _ if depth == 1 && item_start && !ch.is_whitespace() => { let variant = ident(&rest[open + at..]); if !variant.is_empty() { names.insert(variant); } item_start = false; } _ => {} } } } } } names } /// A path that names a variant or a struct: its last segment is CamelCase /// (`None`, `Some`, `Count`, `Mode::Fast`) and no segment has generic /// arguments. A SCREAMING_CASE constant may be computed (a `const fn` of the /// workspace) and does not qualify. fn constructor_path(path: &ast::Path) -> bool { path.segments() .all(|segment| segment.generic_arg_list().is_none()) && path .segment() .and_then(|segment| segment.name_ref()) .is_some_and(|name| { let text = name.text(); text.starts_with(|ch: char| ch.is_ascii_uppercase()) && text.chars().any(|ch| ch.is_ascii_lowercase()) }) } /// The field a struct-literal initializer names: `start: self.start,` and /// the shorthand `start,` both name `start`. fn initialized_field_name(expression: &str) -> Option<&str> { let trimmed = expression.trim().trim_end_matches(',').trim(); let name = match trimmed.find(':') { Some(colon) if trimmed[colon..].starts_with("::") => return None, Some(colon) => trimmed[..colon].trim(), None => trimmed, }; let name = name.strip_prefix("r#").unwrap_or(name); (is_plain_identifier(name) && !name.starts_with(|ch: char| ch.is_ascii_digit())).then_some(name) } /// How deep [`type_compares_by_value`] follows workspace field types. const EQUALITY_DEPTH_LIMIT: usize = 4; /// RIPR-SPEC-0225 decision 9: the primitive integer type `field` of /// `type_name` is declared with, when `type_name` is the struct a record /// literal in the owner's body names, so comparing the field to an integer /// literal is the built-in `==`. The struct is declared exactly once in the /// owner's own file, in the owner's own inline module (a local item takes /// the name from every import), with no attribute that may compile it out /// or change it, no generic parameter, and no attribute on any enclosing /// module; no other indexed file declares a type of that name. The field is /// named once, carries no attribute, and its type is a standard integer /// name that no workspace type, alias, rename or foreign import rebinds in /// the owner's file. Anything else refuses. pub(in crate::analysis) fn field_builtin_integer( owner: &FunctionSummary, type_name: &str, field: &str, index: &RustIndex, syntax: &OwnerPinSyntax, ) -> Option<&'static str> { field_builtin_integer_of(owner, type_name, field, false, index, syntax) } /// [`field_builtin_integer`] for an owner that may be an `impl` method. A /// method is found only when it is the file's one `fn` of its name, so a /// second same-named method or function refuses (#12796). fn field_builtin_integer_of( owner: &FunctionSummary, type_name: &str, field: &str, methods: bool, index: &RustIndex, syntax: &OwnerPinSyntax, ) -> Option<&'static str> { let key = ( owner.file.clone(), owner.name.clone(), type_name.to_owned(), if methods { format!("method:{field}") } else { field.to_owned() }, ); if let Some(found) = syntax.field_integer_memo.borrow().get(&key) { return *found; } let found = field_builtin_integer_uncached(owner, type_name, field, methods, index, syntax); syntax.field_integer_memo.borrow_mut().insert(key, found); found } fn field_builtin_integer_uncached( owner: &FunctionSummary, type_name: &str, field: &str, methods: bool, index: &RustIndex, syntax: &OwnerPinSyntax, ) -> Option<&'static str> { let file = index.files().get(&owner.file)?; if file.used_lexical_fallback || index.files().iter().any(|(path, other)| { *path != owner.file && other.source.contains(type_name) && declares_type(&mask_comments_and_strings(&other.source), type_name) }) { return None; } let parse = parse_clean_source_file(&file.source)?; let tree = parse.tree(); let modules = |node: &SyntaxNode| { node.ancestors() .filter_map(ast::Module::cast) .collect::>() }; let mut owners = tree .syntax() .descendants() .filter_map(ast::Fn::cast) .filter(|function| { function .name() .is_some_and(|name| name.text() == owner.name.as_str()) && function.syntax().parent().is_some_and(|parent| { ast::SourceFile::can_cast(parent.kind()) || ast::ItemList::can_cast(parent.kind()) || (methods && ast::AssocItemList::can_cast(parent.kind())) }) }); let (Some(owner_fn), None) = (owners.next(), owners.next()) else { return None; }; let owner_modules = modules(owner_fn.syntax()); if owner_modules .iter() .any(|module| module.attrs().next().is_some()) { return None; } let mut declarations = tree .syntax() .descendants() .filter_map(ast::Adt::cast) .filter(|adt| adt.name().is_some_and(|name| name.text() == type_name)); let (Some(ast::Adt::Struct(declaration)), None) = (declarations.next(), declarations.next()) else { return None; }; if modules(declaration.syntax()) != owner_modules { return None; } let facts = local_type_equality(&file.source, type_name)?; if facts.generic_params || facts.other_attributes { return None; } // `.0` names the one field of a one-field tuple struct. let tuple_zero = methods && field == "0" && facts.fields.len() == 1; let mut named = facts.fields.iter().filter(|candidate| { candidate.name.as_deref() == Some(field) || (tuple_zero && candidate.name.is_none()) }); let (Some(found), None) = (named.next(), named.next()) else { return None; }; let ty = BUILTIN_INTEGERS .iter() .copied() .find(|integer| *integer == found.ty.trim())?; (!found.has_attributes && !type_declared_in_workspace(ty, index) && !syntax.macro_may_declare(ty, index) && !declaring_file_rebinds(&file.source, ty, false, index)) .then_some(ty) } /// The names a macro in the workspace may declare a type under: every /// identifier of a macro body or argument that also holds `struct`, `enum`, /// `union` or `type` (`$` among them when a metavariable may supply the /// name). `None` when any name may be declared: an unparsed file, or an /// item-level call of a macro the workspace does not define, whose output /// no scan reads (#8059 review: `shadow!(u32)` declared a local `u32`). fn macro_type_names(index: &RustIndex) -> Option> { const ITEM_MACROS: &[&str] = &["thread_local", "compile_error"]; let mut names = BTreeSet::new(); let mut defined = BTreeSet::new(); let mut called = Vec::new(); for facts in index.files().values() { if facts.used_lexical_fallback { return None; } let parse = parse_clean_source_file(&facts.source)?; for node in parse.tree().syntax().descendants() { if let Some(rules) = ast::MacroRules::cast(node.clone()) { defined.insert(rules.name()?.text().to_string()); } else if let Some(call) = ast::MacroCall::cast(node.clone()) { if call.syntax().parent().is_some_and(|parent| { ast::SourceFile::can_cast(parent.kind()) || ast::ItemList::can_cast(parent.kind()) || ast::MacroItems::can_cast(parent.kind()) }) { called.push(call.path()?.segment()?.syntax().text().to_string()); } } else if ast::TokenTree::can_cast(node.kind()) && !node .parent() .is_some_and(|parent| ast::TokenTree::can_cast(parent.kind())) { let tokens: Vec = node .descendants_with_tokens() .filter_map(|element| element.into_token()) .filter(|token| !token.kind().is_trivia()) .map(|token| token.text().trim_start_matches("r#").to_string()) .collect(); if tokens .iter() .any(|token| matches!(token.as_str(), "struct" | "enum" | "union" | "type")) { names.extend(tokens); } } } } called .iter() .all(|name| defined.contains(name) || ITEM_MACROS.contains(&name.as_str())) .then_some(names) } const BUILTIN_INTEGERS: &[&str] = &[ "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize", ]; /// #6692 (RIPR-SPEC-0225 rules 3-4): whether `==` on `type_name` compares /// its field `field` by value through the derived comparison. `type_name` /// must have derived equality ([`derived_equality`]); `field` must carry no /// attribute and its type must compare by value. Anything ripr cannot read /// fails closed. fn field_compares_with_derived_equality(type_name: &str, field: &str, index: &RustIndex) -> bool { derived_equality(type_name, index).is_some_and(|(facts, declaring)| { let mut named = facts .fields .iter() .filter(|candidate| candidate.name.as_deref() == Some(field)); match (named.next(), named.next()) { (Some(found), None) => { !found.has_attributes && type_compares_by_value(&found.ty, declaring, index, 0) } _ => false, } }) } /// The equality facts of `type_name` when its `==` is the derived one: it /// is declared in exactly one parser-backed indexed file, as the one type /// of that name there, with `PartialEq` in its `#[derive(..)]` list, no /// other attribute that may change equality, and no indexed file holds an /// `impl .. PartialEq .. for ` (gated or not). The declaring /// file's source comes back too: it decides what the field types' names /// refer to. fn derived_equality<'a>( type_name: &str, index: &'a RustIndex, ) -> Option<(LocalTypeEquality, &'a str)> { let mut declaring = index.files().values().filter(|facts| { facts.source.contains(type_name) && declares_type(&mask_comments_and_strings(&facts.source), type_name) }); let declaring_file = declaring.next()?; if declaring.next().is_some() || declaring_file.used_lexical_fallback { return None; } let facts = local_type_equality(&declaring_file.source, type_name)?; if !facts.derives.iter().any(|name| name == "PartialEq") || facts.other_attributes || facts.generic_params || facts.qualified_derives || declaring_file_rebinds(&declaring_file.source, "PartialEq", false, index) { return None; } let manual = index.files().values().any(|file| { trait_impl_self_types(&file.source, "PartialEq") .iter() .any(|self_ty| path_base_name(strip_type_arguments(self_ty)) == Some(type_name)) }); (!manual).then_some((facts, &*declaring_file.data().source)) } /// #7063: whether an early error-variant pin may read `qualifier` as the /// owner's own error enum and `variant` and `siblings` as its variants: /// - the owner's file names the one workspace declaration (no import or /// alias rebinds `qualifier`) and brings none of its variants in by `use` /// (`use ConfigError::*`, `use ConfigError::MissingEquals as M`), which /// would let a bare spelling build the variant unseen; /// - every one of them is a declared variant of `qualifier`, not an /// associated constant or function that may build any variant; /// - its `==` is the derived one over fields that each compare by value /// ([`error_enum_compares_payload`]). fn error_enum_admits_variant_pin( qualifier: &str, variant: &str, siblings: &[String], owner: &FunctionSummary, index: &RustIndex, ) -> bool { owner_file_names_enum(qualifier, owner, index) && derived_equality(qualifier, index).is_some_and(|(facts, _)| { std::iter::once(variant) .chain(siblings.iter().map(String::as_str)) .all(|name| facts.variants.iter().any(|declared| declared == name)) }) && error_enum_compares_payload(qualifier, index) } /// #7063: whether the owner's file names the one workspace declaration of /// `qualifier` (no import or alias rebinds it) and brings none of its /// variants in by `use`. fn owner_file_names_enum(qualifier: &str, owner: &FunctionSummary, index: &RustIndex) -> bool { index.files().get(&owner.file).is_some_and(|facts| { !declaring_file_rebinds(&facts.source, qualifier, true, index) && !file_use_statements(&facts.source).iter().any(|statement| { let masked = mask_comments_and_strings(statement); whole_word_offsets(&masked, qualifier) .into_iter() .any(|offset| { masked[offset + qualifier.len()..] .trim_start() .starts_with("::") }) }) }) } /// #7063: whether the error variant path `path` (`ConfigError::MissingEquals` /// or `crate::ConfigError::MissingEquals`, [`local_variant_path`]) built in `owner` names a variant that a /// declared workspace enum declares, under a name the owner's file does not /// rebind ([`owner_file_names_enum`]). An alias (`use .. as CE`, /// `type CE = ..`), `Self::` or a module path names no declared enum here. pub(in crate::analysis) fn owner_builds_declared_error_variant( path: &str, owner: &FunctionSummary, index: &RustIndex, ) -> bool { let Some((qualifier, variant)) = local_variant_path(path) else { return false; }; qualifier != "Self" && owner_file_names_enum(&qualifier, owner, index) && workspace_enum_declares_variant(&qualifier, &variant, index) } /// #7063: whether an indexed file declares an enum `qualifier` with a /// variant `variant`, whatever its `==`. fn workspace_enum_declares_variant(qualifier: &str, variant: &str, index: &RustIndex) -> bool { index.files().values().any(|facts| { facts.source.contains(qualifier) && declares_type(&mask_comments_and_strings(&facts.source), qualifier) && local_type_equality(&facts.source, qualifier) .is_some_and(|facts| facts.variants.iter().any(|name| name == variant)) }) } /// #7063: whether `qualifier` names one workspace type whose `==` is the /// derived one over fields that each compare by value, so an equality /// against one constructed variant compares that variant's payload. pub(super) fn error_enum_compares_payload(qualifier: &str, index: &RustIndex) -> bool { derived_equality(qualifier, index).is_some_and(|(facts, declaring)| { facts.fields.iter().all(|field| { !field.has_attributes && type_compares_by_value(&field.ty, declaring, index, 0) }) }) } /// Whether `type_name` also derives `Clone` (a hand-written `impl Clone` /// beside it is cfg-gated or otherwise not the one every build runs). fn derives_clone(type_name: &str, index: &RustIndex) -> bool { derived_equality(type_name, index) .is_none_or(|(facts, _)| facts.derives.iter().any(|name| name == "Clone")) } /// Standard types whose `==` compares by value. const STD_VALUE_TYPES: &[&str] = &[ "bool", "char", "str", "String", "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize", "f32", "f64", ]; /// Standard containers whose `==` compares their type arguments by value. const STD_VALUE_CONTAINERS: &[&str] = &[ "Option", "Result", "Vec", "VecDeque", "Box", "Rc", "Arc", "BTreeMap", "BTreeSet", "HashMap", "HashSet", ]; /// Bind a directly constructed test root's one field to the existing value /// equality authority. A callee's `&mut Vec<_>` alone does not establish the /// asserted field: a custom collection can coerce through `DerefMut`. pub(in crate::analysis::classify) fn projected_collection_has_value_equality( constructor: &str, field: &str, receiver_type: &str, owner: &FunctionSummary, test: &TestSummary, index: &RustIndex, syntax: &OwnerPinSyntax, ) -> bool { if owner.file != test.file || syntax.target_roots(index).root(&owner.file, index).as_ref() != Some(&owner.file) || targeted_type_name_is_unresolved(test, index, constructor) { return false; } let Some(source) = index .files() .get(&test.file) .map(|facts| &*facts.data().source) else { return false; }; if !index .drop_in_manifests .unbound_standard_root(&test.file, "std") || !index .drop_in_manifests .unbound_standard_root(&test.file, "core") || ProjectedCollectionWorkspaceMemo::verdict( &syntax.projected_collection_workspace, index, ProjectedCollectionWorkspaceKey::StandardRoots, || projected_standard_roots_shadowed(index), ) { return false; } let scope = OwnerScope::new(&owner.name, owner.start_line, &owner.file); if !matches!( named_or_slice(constructor, test, Some(source), index, &|_, name| file_imports_foreign_callee_name(source, name, &index.package_names), scope), Some(ReceiverType::Named(name)) if name == constructor ) { return false; } let Some(parse) = parse_clean_source_file(source) else { return false; }; // The type namespace does not rule out a callable/value that shadows a // tuple constructor. A competing local, function, constant or static // keeps this deliberately bounded binding unestablished. let names_constructor = |name: String| name.strip_prefix("r#").unwrap_or(&name) == constructor; if ProjectedCollectionWorkspaceMemo::verdict( &syntax.projected_collection_workspace, index, ProjectedCollectionWorkspaceKey::Constructor(test.file.clone(), constructor.to_owned()), || projected_constructor_shadowed(constructor, &test.file, index), ) { return false; } let definitions: Vec<_> = parse .tree() .syntax() .descendants() .filter_map(ast::Adt::cast) .filter(|item| { item.name() .is_some_and(|name| names_constructor(name.text().to_string())) }) .collect(); let [ast::Adt::Struct(definition)] = definitions.as_slice() else { return false; }; let Some(function) = resolve_owner_fn(parse.tree().syntax(), source, scope) else { return false; }; let (Some(owner_scope), Some(test_scope)) = ( syntax.item_nesting(index, &owner.file, &owner.name, owner.start_line), syntax.item_nesting(index, &test.file, &test.name, test.start_line), ) else { return false; }; if definition.syntax().parent() != function.syntax().parent() || !test_scope.modules.starts_with(&owner_scope.modules) { return false; } let Some(facts) = local_type_equality(source, constructor) else { return false; }; if facts.generic_params || facts.other_attributes { return false; } let selected = if let Ok(position) = field.parse::() { facts .fields .get(position) .filter(|field| field.name.is_none()) } else { facts .fields .iter() .find(|candidate| candidate.name.as_deref() == Some(field)) }; let Some(selected) = selected.filter(|field| !field.has_attributes) else { return false; }; // Raw type bindings denote the same names. Give the existing lexical // equality authority their normalized spelling, without changing source. let declaring = mask_comments_and_strings(source).replace("r#", ""); let standard_vec = |ty: &str| { let ty = collapse_whitespace(ty); let (path, arguments) = ty.split_once('<')?; let arguments = arguments.strip_suffix('>')?; let elements = top_level_arguments(arguments); let [element] = elements.as_slice() else { return None; }; (matches!(path, "Vec" | "std::vec::Vec" | "::std::vec::Vec") && INTEGER_TYPES.contains(element) && !index.files().values().any(|facts| { let masked = mask_comments_and_strings(&facts.source).replace("r#", ""); ["Vec", *element].iter().any(|name| { declares_type(&masked, name) || file_aliases_type(&masked, name) || file_renames_to(&masked, name) || flattened_use_paths(&masked).iter().any(|import| { let segments: Vec<_> = import.path.trim_start_matches("::").split("::").collect(); segments.first() == Some(&"alloc") && segments .last() .is_some_and(|last| *last == *name || *last == "*") }) }) }) && !declares_type(&declaring, "Vec") && !type_declared_in_workspace("Vec", index) && type_compares_by_value(&ty, &declaring, index, 0)) .then_some(collapse_whitespace(arguments)) }; standard_vec(&selected.ty) .zip(standard_vec(receiver_type)) .is_some_and(|(field, receiver)| field == receiver) } fn projected_standard_roots_shadowed(index: &RustIndex) -> bool { index.files().values().any(|facts| { #[cfg(test)] PROJECTED_WORKSPACE_FILE_VISITS.with(|count| count.set(count.get() + 1)); let masked = mask_comments_and_strings(&facts.source).replace("r#", ""); let modules = declared_module_names(&masked); let imports = file_use_statements(&masked); STD_ROOTS.iter().any(|root| { modules.contains(root) || declares_type(&masked, root) || binds_extern_crate(&masked, root) || file_renames_to(&masked, root) || imports .iter() .any(|item| use_statement_binds_name(item, root)) }) }) } fn projected_constructor_shadowed(constructor: &str, test_file: &Path, index: &RustIndex) -> bool { let names_constructor = |name: String| name.strip_prefix("r#").unwrap_or(&name) == constructor; index.files().iter().any(|(file, facts)| { #[cfg(test)] PROJECTED_WORKSPACE_FILE_VISITS.with(|count| count.set(count.get() + 1)); let masked = mask_comments_and_strings(&facts.source).replace("r#", ""); if file_aliases_type(&masked, constructor) || file_renames_to(&masked, constructor) || !fn_definition_offsets(&masked, constructor).is_empty() || file_use_statements(&masked).iter().any(|import| { ["test", "cfg"] .iter() .any(|name| use_statement_binds_name(import, name)) }) || flattened_use_paths(&masked).iter().any(|import| { let segments: Vec<_> = import.path.trim_start_matches("::").split("::").collect(); if !segments .last() .is_some_and(|name| *name == constructor || *name == "*") { return false; } // A constructor reached through another module may be a // callable re-export whose defining bytes were not indexed. // Only direct local namespace imports establish this bounded // same-file construction; a missing companion cannot clear it. !matches!(segments.as_slice(), ["crate" | "self" | "super", _]) }) { return true; } #[cfg(test)] PROJECTED_WORKSPACE_FILE_PARSES.with(|count| count.set(count.get() + 1)); let Some(parsed) = parse_clean_source_file(&facts.source) else { return true; }; parsed.tree().syntax().descendants().any(|node| { // Attribute/derive expansion can also manufacture a binding. // This bounded construction admits only the ordinary test // harness attributes; expansion is not type-identity evidence. ast::Attr::cast(node.clone()).is_some_and(|attr| { let text = attr.syntax().text().to_string(); collapse_whitespace(&text) != "#[test]" && !crate::analysis::facts::cfg_predicates::attribute_is_plain_test_gate(&text) }) || // Arbitrary expansion can introduce a constructor binding that // the parsed item index never saw. The two observation macros // still require their carried canonical binding authority. ast::MacroCall::cast(node.clone()).is_some_and(|call| { call.path().is_none_or(|path| { let path = collapse_whitespace(&path.syntax().text().to_string()); !matches!( path.as_str(), "assert_eq" | "vec" | "std::vec" | "::std::vec" ) && !STD_ROOTED_ASSERT_EQ.contains(&path.as_str()) }) }) || (file != test_file && ast::Adt::cast(node.clone()) .and_then(|item| item.name()) .is_some_and(|name| names_constructor(name.text().to_string()))) || ast::Fn::cast(node.clone()) .and_then(|item| item.name()) .is_some_and(|name| names_constructor(name.text().to_string())) || ast::Const::cast(node.clone()) .and_then(|item| item.name()) .is_some_and(|name| names_constructor(name.text().to_string())) || ast::Static::cast(node.clone()) .and_then(|item| item.name()) .is_some_and(|name| names_constructor(name.text().to_string())) || ast::IdentPat::cast(node) .and_then(|item| item.name()) .is_some_and(|name| names_constructor(name.text().to_string())) }) }) } /// RIPR-SPEC-0225 rule 4: whether a field type compares by value: a /// standard value type, a reference, tuple, array or standard container of /// such types, or a workspace type with derived equality whose own fields /// do too, recursively. A workspace type of a standard name shadows it. /// A multi-segment path must be rooted in `std`, `core` or `alloc` /// (`foreign::String` is not `String`), and the declaring file must not /// bind the base name some other way ([`declaring_file_rebinds`]). fn type_compares_by_value(ty: &str, declaring: &str, index: &RustIndex, depth: usize) -> bool { if depth > EQUALITY_DEPTH_LIMIT { return false; } let ty = ty.trim(); if let Some(referent) = ty.strip_prefix('&') { let referent = referent.trim_start(); let referent = if referent.starts_with('\'') { referent .split_once(char::is_whitespace) .map_or("", |(_, rest)| rest) } else { referent }; let referent = referent.strip_prefix("mut ").unwrap_or(referent); return type_compares_by_value(referent, declaring, index, depth + 1); } if let Some(inner) = ty.strip_prefix('(').and_then(|rest| rest.strip_suffix(')')) { return top_level_arguments(inner) .into_iter() .all(|element| type_compares_by_value(element, declaring, index, depth + 1)); } if let Some(inner) = ty.strip_prefix('[').and_then(|rest| rest.strip_suffix(']')) { let element = inner.split(';').next().unwrap_or(inner); return type_compares_by_value(element, declaring, index, depth + 1); } let (path, arguments) = match ty.split_once('<') { Some((path, rest)) => match rest.strip_suffix('>') { Some(arguments) => (path.trim(), Some(arguments)), None => return false, }, None => (ty, None), }; let Some(base) = path_base_name(path) else { return false; }; if let Some((root, _)) = path.trim_start_matches("::").split_once("::") && (!STD_ROOTS.contains(&root.trim()) || workspace_renames_to(index, root.trim())) { return false; } let workspace_type = type_declared_in_workspace(base, index); if declaring_file_rebinds(declaring, base, workspace_type, index) { return false; } if workspace_type { return arguments.is_none() && derived_equality(base, index).is_some_and(|(facts, declaring)| { facts.fields.iter().all(|field| { !field.has_attributes && type_compares_by_value(&field.ty, declaring, index, depth + 1) }) }); } match arguments { None => STD_VALUE_TYPES.contains(&base), Some(arguments) => { STD_VALUE_CONTAINERS.contains(&base) && top_level_arguments(arguments) .into_iter() .all(|argument| type_compares_by_value(argument, declaring, index, depth + 1)) } } } /// The roots of standard library paths. const STD_ROOTS: &[&str] = &["std", "core", "alloc"]; /// Whether `base`, named in a field type of a type declared in the file /// `declaring`, may denote something other than the standard type (or, /// when `workspace_type`, the one workspace declaration) of that name. It /// may when the file renames an item to it (`use x::Thing as String;`), /// aliases it (`type String = ..;`), or has a `use` that names it or globs /// (`use foreign::Vec;`, `use foreign::*;`) rooted outside `std`, `core` /// and `alloc`. A `crate`/`self`/`super` (or own-package) root is a /// workspace path: it may bring the workspace declaration, but never a /// standard name's own type, and only while no workspace `use` re-exports /// the name or a glob from elsewhere. Lexical and file-wide: a `use` in any /// module of the file counts. Anything else fails closed. fn declaring_file_rebinds( declaring: &str, base: &str, workspace_type: bool, index: &RustIndex, ) -> bool { if file_renames_to(declaring, base) || file_aliases_type(declaring, base) { return true; } file_use_statements(declaring).iter().any(|statement| { let names = contains_as_whole_word(statement, base); if !(names || statement.contains('*')) { return false; } match use_statement_first_segment(statement) { Some(root) if STD_ROOTS.contains(&root) => workspace_renames_to(index, root), // A workspace path that names a standard name imports some // other item of it; a workspace glob brings only workspace items. Some(root) if is_workspace_root(root, index) => { (names && !workspace_type) || workspace_may_export_other(index, base) } _ => true, } }) } /// `crate`, `self`, `super`, or the crate name of a workspace package. fn is_workspace_root(root: &str, index: &RustIndex) -> bool { matches!(root, "crate" | "self" | "super") || index .package_names .iter() .any(|name| name.replace('-', "_") == root) } #[cfg(test)] thread_local! { static LIBRARY_IMPORT_EXTRACTIONS: std::cell::Cell = const { std::cell::Cell::new(0) }; } fn library_import_statements(source: &str) -> Vec { #[cfg(test)] LIBRARY_IMPORT_EXTRACTIONS.with(|count| count.set(count.get() + 1)); file_use_statements(source) } /// Whether the library whose crate root is `owner_root` may export some other /// item named `name` than the owner, so that another crate's /// `use library::name;` could bind it. Fails closed (true) when: /// - an `include!` was unresolved anywhere, or a file under the package's /// `src/` has no established crate root (its exports are unread); /// - a library file uses `include!`, or declares a `const` or `static` named /// `name`; /// - a `pub use` in a library file names `name` or globs, and its path is /// rooted outside `crate`, `self` and `super` (`pub use fastscore::score;`) /// or passes through a segment that is not a `mod` the library declares /// (`use fastscore as fs; pub use self::fs::score;`). pub(super) fn library_may_export_other(index: &RustIndex, owner_root: &Path, name: &str) -> bool { let Some(source_dir) = owner_root.parent() else { return true; }; if !index.include_limitations.is_empty() { return true; } let src_dirs = BTreeSet::new(); let mut library = Vec::new(); for (path, facts) in index.files().iter() { if !path.starts_with(source_dir) { continue; } match target_root(path, index, &src_dirs) { None => return true, Some(root) if root == owner_root => { let masked = mask_comments_and_strings(&facts.source); let includes = whole_word_offsets(&masked, "include") .into_iter() .any(|offset| { masked[offset + "include".len()..] .trim_start() .starts_with('!') }); if includes || declares_value_named(&masked, name) { return true; } library.push(masked); } Some(_) => {} } } // A module name some `use` or `extern crate` also binds may name that // import instead (`pub use fastscore as fs;` beside an unrelated // `mod fs`), so it does not count as a library module. // Imports depend only on the captured file, not the module being checked. // Keep extraction lazy for files the short-circuiting walk never visits. let library_uses: Vec>> = (0..library.len()).map(|_| OnceCell::new()).collect(); let modules: BTreeSet<&str> = library .iter() .flat_map(|masked| declared_module_names(masked)) .filter(|module| { !library.iter().zip(&library_uses).any(|(masked, uses)| { uses.get_or_init(|| library_import_statements(masked)) .iter() .any(|statement| use_statement_binds_name(statement, module)) || binds_extern_crate(masked, module) }) }) .collect(); index.files().iter().any(|(path, facts)| { target_root(path, index, &src_dirs).as_deref() == Some(owner_root) && public_use_statements(&facts.source) .iter() .any(|statement| { (contains_as_whole_word(statement, name) || statement.contains('*')) && !reexports_library_module(statement, &modules) }) }) } /// Whether a `pub use` path stays inside the library: rooted at `crate`, /// `self` or `super`, with every segment before an imported item or glob a /// module the library declares, including each path inside a brace group /// (`pub use self::{fs::score};` reaches through `fs`). fn reexports_library_module(statement: &str, modules: &BTreeSet<&str>) -> bool { let Some(path) = statement.trim_start().strip_prefix("use") else { return false; }; let path = path.trim(); let root_end = path.find("::").unwrap_or(path.len()); matches!(path[..root_end].trim(), "crate" | "self" | "super") && use_tree_stays_local(path[root_end..].trim_start_matches("::"), modules) } /// Whether every path in a use tree (the text after its `crate`/`self`/ /// `super` root) passes only through `super` or declared library modules /// before its imported item, glob or brace group. An unbalanced group fails /// closed. fn use_tree_stays_local(tree: &str, modules: &BTreeSet<&str>) -> bool { let tree = tree.trim(); let Some(open) = tree.find('{') else { let mut segments: Vec<&str> = tree.split("::").map(str::trim).collect(); // The last segment is the imported item, glob or `x as y` binding. segments.pop(); return segments .iter() .all(|segment| *segment == "super" || modules.contains(segment)); }; let Some(close) = tree.rfind('}').filter(|close| *close > open) else { return false; }; let prefix_local = tree[..open] .split("::") .map(str::trim) .filter(|segment| !segment.is_empty()) .all(|segment| segment == "super" || modules.contains(segment)); prefix_local && top_level_items(&tree[open + 1..close]) .iter() .all(|item| use_tree_stays_local(item, modules)) } /// The comma-separated items of a brace group's body, splitting only at /// depth zero. fn top_level_items(body: &str) -> Vec<&str> { let mut items = Vec::new(); let mut depth = 0usize; let mut start = 0; for (offset, character) in body.char_indices() { match character { '{' => depth += 1, '}' => depth = depth.saturating_sub(1), ',' if depth == 0 => { items.push(&body[start..offset]); start = offset + 1; } _ => {} } } items.push(&body[start..]); items .into_iter() .map(str::trim) .filter(|item| !item.is_empty()) .collect() } /// Whether masked source has `extern crate ` or `extern crate .. as /// `. fn binds_extern_crate(masked: &str, name: &str) -> bool { whole_word_offsets(masked, "extern") .into_iter() .any(|offset| { let rest = masked[offset + "extern".len()..].trim_start(); let Some(rest) = rest.strip_prefix("crate") else { return false; }; let declaration = rest.split(';').next().unwrap_or_default(); let bound = declaration .rsplit_once(" as ") .map_or(declaration, |(_, alias)| alias) .trim(); bound == name }) } /// Names of `mod ` declarations in masked source. fn declared_module_names(masked: &str) -> Vec<&str> { whole_word_offsets(masked, "mod") .into_iter() .filter_map(|offset| { let rest = masked[offset + 3..].trim_start(); let end = rest .find(|character: char| !(character.is_ascii_alphanumeric() || character == '_')) .unwrap_or(rest.len()); (end > 0).then(|| &rest[..end]) }) .collect() } /// Whether masked source declares a `const` or `static` (optionally `mut`) /// named `name`. fn declares_value_named(masked: &str, name: &str) -> bool { ["const", "static"].iter().any(|keyword| { whole_word_offsets(masked, keyword) .into_iter() .any(|offset| { let rest = masked[offset + keyword.len()..].trim_start(); let rest = rest .strip_prefix("mut") .filter(|after| after.starts_with(char::is_whitespace)) .map_or(rest, str::trim_start); rest.strip_prefix(name).is_some_and(|after| { !after.starts_with(|character: char| { character.is_ascii_alphanumeric() || character == '_' }) }) }) }) } /// The `use ..;` text of every `pub use` declaration in `source` (plain /// `pub` only: a `pub(crate)` or `pub(in ..)` import is not visible to /// another crate). fn public_use_statements(source: &str) -> Vec<&str> { let masked = mask_comments_and_strings(source); let bytes = masked.as_bytes(); let word = |at: usize, text: &str| { masked[at..].starts_with(text) && (at == 0 || !is_ident_byte(bytes[at - 1])) && bytes .get(at + text.len()) .is_none_or(|byte| !is_ident_byte(*byte)) }; let mut statements = Vec::new(); let mut at = 0; while let Some(offset) = masked[at..].find("pub") { let start = at + offset; at = start + 3; if !word(start, "pub") { continue; } let use_at = at + (masked[at..].len() - masked[at..].trim_start().len()); if !word(use_at, "use") { continue; } let Some(end) = masked[use_at..].find(';') else { break; }; statements.push(&source[use_at..use_at + end]); at = use_at + end; } statements } /// Whether a workspace path may lead to some item named `base` other than /// its workspace declaration: a workspace `use` rooted outside the standard /// library and the workspace names `base` or globs (a re-export of a /// foreign item), or a workspace file renames an item to `base` or aliases /// a type as `base`. fn workspace_may_export_other(index: &RustIndex, base: &str) -> bool { index.files().values().any(|facts| { file_renames_to(&facts.source, base) || file_aliases_type(&facts.source, base) || file_use_statements(&facts.source).iter().any(|statement| { (contains_as_whole_word(statement, base) || statement.contains('*')) && use_statement_first_segment(statement).is_none_or(|root| { !(STD_ROOTS.contains(&root) || is_workspace_root(root, index)) }) }) }) } /// Whether any indexed file renames an item to `name` (`extern crate /// other as std;`). fn workspace_renames_to(index: &RustIndex, name: &str) -> bool { index .files() .values() .any(|facts| file_renames_to(&facts.source, name)) } /// The comma-separated items of `text` at bracket depth zero. fn top_level_arguments(text: &str) -> Vec<&str> { let mut items = Vec::new(); let mut depth = 0usize; let mut start = 0usize; for (offset, byte) in text.bytes().enumerate() { match byte { b'<' | b'(' | b'[' => depth += 1, b'>' | b')' | b']' => depth = depth.saturating_sub(1), b',' if depth == 0 => { items.push(text[start..offset].trim()); start = offset + 1; } _ => {} } } let last = text[start..].trim(); if !last.is_empty() { items.push(last); } items } /// `Window` -> `Window`. fn strip_type_arguments(self_ty: &str) -> &str { self_ty.split('<').next().unwrap_or(self_ty).trim() } /// #7066 review: whether `Ok` or `Some` may name something other than the /// standard variant anywhere in the workspace: a type, `fn`, `const`, /// `static`, `mod`, `trait` or macro of that name, a variant of a workspace /// `enum`, a rename to it, or a `use` naming it from outside `std`, `core` /// and `alloc`. Lexical and workspace-wide, so it fails closed. fn wrapper_may_be_rebound(wrapper: &str, index: &RustIndex) -> bool { index.files().values().any(|facts| { facts.source.contains(wrapper) && { let masked = mask_comments_and_strings(&facts.source); let declared_after = |keyword: &str| { whole_word_offsets(&masked, keyword) .into_iter() .any(|offset| { let rest = masked[offset + keyword.len()..].trim_start(); let rest = rest.strip_prefix('!').map_or(rest, str::trim_start); starts_with_word(rest, wrapper) }) }; declares_type(&masked, wrapper) || [ "fn", "const", "static", "mod", "trait", "type", "macro_rules", ] .into_iter() .any(declared_after) || whole_word_offsets(&masked, "enum") .into_iter() .any(|offset| { let Some(open) = masked[offset..].find('{').map(|at| offset + at) else { return true; }; let mut depth = 0usize; let close = masked[open..].char_indices().find_map(|(at, ch)| { match ch { '{' => depth += 1, '}' => { depth -= 1; if depth == 0 { return Some(open + at); } } _ => {} } None }); close.is_none_or(|close| { contains_as_whole_word(&masked[open..close], wrapper) }) }) || file_renames_to(&facts.source, wrapper) || file_use_statements(&facts.source).iter().any(|statement| { contains_as_whole_word(statement, wrapper) && use_statement_first_segment(statement) .is_none_or(|root| !STD_ROOTS.contains(&root)) }) } }) } /// Whether `text` starts with the identifier `name`, spelled bare or raw /// (`r#name` is the same identifier). fn starts_with_ident(text: &str, name: &str) -> bool { starts_with_word(text, name) || text .strip_prefix("r#") .is_some_and(|rest| starts_with_word(rest, name)) } /// Whether masked `text` declares a struct, enum or union named `name`. fn declares_type(text: &str, name: &str) -> bool { ["struct", "enum", "union"].iter().any(|keyword| { whole_word_offsets(text, keyword) .into_iter() .any(|offset| starts_with_ident(text[offset + keyword.len()..].trim_start(), name)) }) } /// Whether `source` declares a `struct`/`enum`/`union` named `name` anywhere, /// or aliases a type to that name, by a text scan of its comment- and /// string-masked code. Any scope counts, so a hit is only ever used to /// withhold credit (#14407). pub(in crate::analysis) fn source_declares_or_aliases_type(source: &str, name: &str) -> bool { declares_type(&mask_comments_and_strings(source), name) || file_aliases_type(source, name) } /// How many `struct`/`enum`/`union` declarations named `name` `source` /// holds at any scope, by a text scan of its comment- and string-masked code, /// plus each `as name` rename, plus one when it aliases a type to that name. Used only to withhold credit /// when a test shares the owner's file (#14407). pub(in crate::analysis) fn source_type_declaration_count(source: &str, name: &str) -> usize { if !source.contains(name) { return 0; } let masked = mask_comments_and_strings(source); let declarations = ["struct", "enum", "union"] .iter() .map(|keyword| { whole_word_offsets(&masked, keyword) .into_iter() .filter(|offset| { starts_with_ident(masked[offset + keyword.len()..].trim_start(), name) }) .count() }) .sum::(); // A `use path::Other as Name;` rename brings another type in under the // name, like an alias. let renames = whole_word_offsets(&masked, "as") .into_iter() .filter(|offset| starts_with_ident(masked[offset + "as".len()..].trim_start(), name)) .count(); declarations + renames + usize::from(file_aliases_type(source, name)) } /// Whether `source` declares a `struct`/`enum`/`union` named `name` on a line /// before file line `line` (1-based), by a text scan of its comment- and /// string-masked code (#14407). pub(in crate::analysis) fn source_declares_type_before_line( source: &str, name: &str, line: usize, ) -> bool { let masked = mask_comments_and_strings(source); ["struct", "enum", "union"].iter().any(|keyword| { whole_word_offsets(&masked, keyword) .into_iter() .any(|offset| { starts_with_ident(masked[offset + keyword.len()..].trim_start(), name) && masked[..offset].matches('\n').count() + 1 < line }) }) } /// Whether masked text declares a `trait` named `name`. fn declares_trait(masked: &str, name: &str) -> bool { whole_word_offsets(masked, "trait") .into_iter() .any(|offset| starts_with_word(masked[offset + "trait".len()..].trim_start(), name)) } /// Whether any indexed file declares a trait named `name`. fn workspace_declares_trait(index: &RustIndex, name: &str) -> bool { index.files().values().any(|facts| { facts.source.contains(name) && { let masked = mask_comments_and_strings(&facts.source); whole_word_offsets(&masked, "trait") .into_iter() .any(|offset| starts_with_word(masked[offset + "trait".len()..].trim_start(), name)) } }) } /// Whether masked text holds a `|` that is not a binary bitwise OR (#6675): /// a `||` (lazy OR, or an empty closure), a `|=`, or a pipe in operand /// position, which opens a closure parameter list (`map(|x| ..)`, /// `move |x| ..`). A pipe is read as binary only when it directly follows a /// completed operand: an identifier or number that is not a keyword, or a /// closing `)`/`]` or `?`. A closure's closing pipe may follow its /// parameter name, but its opening pipe never follows an operand, so every /// closure still fails here. A pipe inside a macro invocation's /// arguments (`matches!(k, A | B)`) or anywhere in a tail that binds with /// `let` may separate pattern alternatives, which short-circuit, so it is /// never read as binary. Anything else fails closed. fn has_non_bitwise_pipe(masked: &str) -> bool { const OPERAND_POSITION_KEYWORDS: &[&str] = &[ "async", "break", "else", "in", "let", "move", "mut", "return", "static", "yield", ]; if !masked.contains('|') { return false; } if contains_as_whole_word(masked, "let") { return true; } let bytes = masked.as_bytes(); // One entry per open delimiter: whether it opens a macro's arguments. let mut delimiters: Vec = Vec::new(); for (offset, byte) in bytes.iter().enumerate() { match byte { b'(' | b'[' | b'{' => { let before = masked[..offset].trim_end(); let opens_macro = before.strip_suffix('!').is_some_and(|head| { head.ends_with(|character: char| { character.is_alphanumeric() || character == '_' }) }); delimiters.push(opens_macro); continue; } b')' | b']' | b'}' => { delimiters.pop(); continue; } b'|' => {} _ => continue, } if delimiters.iter().any(|opens_macro| *opens_macro) { return true; } if matches!(bytes.get(offset + 1), Some(b'|' | b'=')) || (offset > 0 && bytes[offset - 1] == b'|') { return true; } let before = masked[..offset].trim_end(); let Some(previous) = before.bytes().last() else { return true; }; let binary = match previous { b')' | b']' | b'?' => true, byte if byte.is_ascii_alphanumeric() || byte == b'_' => { let start = before .char_indices() .rev() .find(|(_, character)| { !(character.is_ascii_alphanumeric() || *character == '_') }) .map_or(0, |(position, character)| position + character.len_utf8()); !OPERAND_POSITION_KEYWORDS.contains(&&before[start..]) } _ => false, }; if !binary { return true; } } false } /// `Option`/`Result`/`bool` methods that evaluate or apply an argument only /// on some inputs. pub(super) const CONDITIONAL_COMBINATORS: &[&str] = &[ "and", "and_then", "filter", "get_or_insert_with", "is_none_or", "is_ok_and", "is_some_and", "map", "map_err", "map_or", "map_or_else", "ok_or", "ok_or_else", "or", "or_else", "then", "then_some", "unwrap_or", "unwrap_or_default", "unwrap_or_else", "xor", "zip", ]; /// The outer invocation's path, without interpreting nested operand macros. fn outer_macro_path(text: &str) -> Option { let masked = mask_comments_and_strings(text); let mut invocation = masked.trim_start(); // The parser includes a macro statement's attributes in its fact text. // Skip only complete attributes; do not mistake an inner invocation in // another oracle's token tree for that oracle's own identity. while let Some(attribute) = invocation.strip_prefix('#') { let attribute = attribute.trim_start(); let close = matching_close(attribute, 0, b'[', b']')?; invocation = attribute[close + 1..].trim_start(); } let (path, _) = invocation.split_once('!')?; let path = path.trim(); // The oracle must BEGIN with the invocation path. Whitespace is legal only // beside a `::` separator (`similar_asserts :: assert_eq !(..)`); any other // whitespace means a prefix token precedes the macro (`if matches!(..) { // assert_eq!(..); }`, `if !cfg!(test) { .. }`), so stripping it would fuse // the prefix into a plain-looking identifier and skip the context gate. let chars: Vec = path.chars().collect(); for (at, ch) in chars.iter().enumerate() { if !ch.is_whitespace() { continue; } let before = chars[..at].iter().rev().find(|c| !c.is_whitespace()); let after = chars[at..].iter().find(|c| !c.is_whitespace()); if before != Some(&':') && after != Some(&':') { return None; } } let path: String = chars.into_iter().filter(|c| !c.is_whitespace()).collect(); const PREFIX_KEYWORDS: &[&str] = &[ "if", "while", "match", "loop", "for", "unsafe", "async", "move", "else", "return", "break", "continue", "let", "in", ]; // A keyword as any segment (`if ::core::matches!(..)` collapses to // `if::core::matches`) is a prefix token, not part of a macro path. if path .split("::") .any(|segment| PREFIX_KEYWORDS.contains(&segment)) { return None; } Some(path) } /// #6578: the actual operand and the expected literal of an inline /// expect-test comparison, `expect![["text"]].assert_eq(actual)`, as /// `[actual, "text"]`. `expect_test::Expect::assert_eq(&self, actual: &str)` /// compares `actual` with the literal (indentation-trimmed when it spans /// lines) and panics on a mismatch unless `UPDATE_EXPECT` is set. Only the /// bare `expect!` with one string literal (or none, the empty expectation) /// and one argument; a single leading `&` borrows the actual value and is /// dropped. `assert_debug_eq` and a qualified `expect_test::expect!` stay /// `snapshot` / medium (RIPR-SPEC-0231 step 6). /// /// `expect_file!["path"].assert_eq(actual)` compares `actual` with the /// committed file's whole text (CRLF read as LF; a missing file reads as /// "") and panics on a mismatch the same way, so it pins too. Its file is /// not read: the second operand is the path literal, standing in for a /// fixed text the analyzer does not inspect. Only a path gate that admits /// any value of the owner's type (`ReturnPathGate::Any` and the like) /// accepts that stand-in; a gate that checks the expected value refuses it. pub(in crate::analysis) fn inline_expect_operands(text: &str) -> Option<[String; 2]> { let statement = text.trim().trim_end_matches(';').trim_end(); let parse = parse_clean_source_file(&format!("fn ripr_expect() {{ {statement}; }}"))?; let function = parse .tree() .syntax() .descendants() .find_map(ast::Fn::cast)?; let body = function.body()?.stmt_list()?; let mut statements = body.statements(); let ast::Stmt::ExprStmt(only) = statements.next()? else { return None; }; if statements.next().is_some() || body.tail_expr().is_some() { return None; } let ast::Expr::MethodCallExpr(call) = only.expr()? else { return None; }; if call.name_ref()?.text() != "assert_eq" || call.generic_arg_list().is_some() { return None; } let ast::Expr::MacroExpr(receiver) = call.receiver()? else { return None; }; let receiver = receiver.macro_call()?; receiver.excl_token()?; let path = receiver.path()?.syntax().text(); let golden_file = if path == "expect" { false } else if path == "expect_file" { true } else { return None; }; let tokens: Vec<_> = receiver .token_tree()? .syntax() .descendants_with_tokens() .filter_map(|element| element.into_token()) .filter(|token| !token.kind().is_trivia()) .map(|token| (token.kind(), token.text().to_string())) .collect(); let texts: Vec<&str> = tokens.iter().map(|(_, text)| text.as_str()).collect(); let literal = match texts.as_slice() { // `expect_file!["path"]`: one string literal naming the file. ["[", path, "]"] if golden_file => { if tokens[1].0 != ra_ap_syntax::SyntaxKind::STRING || !is_in_tree_relative_path(path) { return None; } (*path).to_string() } _ if golden_file => return None, ["[", "[", _, "]", "]"] | ["[", _, "]"] => { let (kind, text) = &tokens[tokens.len() / 2]; // expect-test trims a multi-line literal's indentation before // comparing, so its raw text is not the compared value. if *kind != ra_ap_syntax::SyntaxKind::STRING || text.contains('\n') { return None; } text.clone() } ["[", "[", "]", "]"] | ["[", "]"] => "\"\"".to_string(), _ => return None, }; let mut arguments = call.arg_list()?.args(); let actual = arguments.next()?; if arguments.next().is_some() { return None; } let actual = match actual { ast::Expr::RefExpr(borrowed) => { if borrowed.mut_token().is_some() || borrowed.raw_token().is_some() { return None; } borrowed.expr()?.syntax().text().to_string() } other => other.syntax().text().to_string(), }; Some([actual, literal]) } /// #6578 review: `expect_file!` resolves its path against the test's own /// source directory, so a relative path without `..` names a file under the /// crate, which the commit fixes. An absolute path (`/tmp/x`, a drive-letter /// path, a UNC `\\\\host`), a home-relative `~` or any `..` segment may name text /// produced outside the commit, so it lends no pin. `path` is the literal's /// source text, quotes and any raw-string hashes included. fn is_in_tree_relative_path(path: &str) -> bool { let inner = path .trim_start_matches('r') .trim_matches('#') .trim_matches('"'); let absolute = inner.starts_with(['/', '\\', '~']) || inner.as_bytes().get(1) == Some(&b':'); // A non-raw literal's escapes (`\u{2e}\u{2e}/w.txt`) decode to segments // this text check cannot see, so any escape refuses. let escaped = !path.starts_with('r') && inner.contains('\\'); !inner.is_empty() && !absolute && !escaped && !inner.split(['/', '\\']).any(|segment| segment == "..") } /// #6578 review: whether a test file renames an import from `std::fs` or /// `std::env` (`use std::fs::write as save;`), which would let a bare /// `save(..)` write the golden or set `UPDATE_EXPECT` unseen by /// [`test_may_write_files`]. Fail-closed: any such rename refuses. fn file_renames_fs_or_env_import(source: &str) -> bool { let masked = mask_comments_and_strings(source); // Word tokens rather than a statement prefix: a `use` may follow `{`, an // item's `}`, an attribute or `pub(crate)` inside the same `;` fragment. masked.split(';').any(|statement| { let mut words = statement .split(|c: char| !(c.is_alphanumeric() || c == '_')) .filter(|word| !word.is_empty()) .skip_while(|word| *word != "use"); if words.next().is_none() { return false; } let tree: Vec<&str> = words.collect(); tree.iter().any(|word| matches!(*word, "fs" | "env")) && tree.contains(&"as") }) } /// Whether an expect-test comparison's receiver is `expect_file!`. fn is_golden_file_comparison(text: &str) -> bool { let masked = mask_comments_and_strings(text); let compact: String = masked.chars().filter(|c| !c.is_whitespace()).collect(); compact.starts_with("expect_file!") } /// #6578 review: whether a test body may write the file a golden-file /// comparison reads. Comments and strings are masked; anything that may /// create, overwrite, copy or rename a file, or turn on expect-test's /// `UPDATE_EXPECT` rewrite, counts. A bare `write(..)`/`create(..)` call /// counts too, since `use std::fs::write;` makes it the file write. /// Fail-closed: a test that writes some other file also lends no pin. fn test_may_write_files(body: &str) -> bool { let masked = mask_comments_and_strings(body); let compact: String = masked.chars().filter(|c| !c.is_whitespace()).collect(); const WRITERS: &[&str] = &[ "fs::write", "fs::copy", "fs::rename", "fs::hard_link", "File::create", "File::options", "OpenOptions", "UPDATE_EXPECT", "set_var", // A subprocess, a symlink or a persisted temp file may also produce it. "Command", "symlink", "soft_link", "persist", ]; WRITERS.iter().any(|writer| compact.contains(writer)) || [ "write(", "create(", "copy(", "rename(", "write::<", "create::<", "copy::<", "rename::<", ] .iter() .any(|call| { // A turbofish (`write::<_, _>(..)`) is the same call. compact.match_indices(call).any(|(at, _)| { let before = &compact[..at]; // A bare or path-qualified call (`save::write(`, `::create(`, // `fs_err::write(`) may write; a method call or `io::copy(` // between readers and writers does not. if before.ends_with("::") { return !before.ends_with("io::"); } before.chars().next_back().is_none_or(|previous| { !(previous.is_alphanumeric() || matches!(previous, '_' | '.' | ':')) }) }) }) } /// #8097: whether the expected operand's value comes from reading a file /// that the same test body may write. The read may be inline /// (`fs::read_to_string(..)`) or through plain bindings /// (`let want = fs::read_to_string(..); assert_eq!(.., want)`), following /// a few identifier hops and trivial wrappers (`&want`, `want.as_str()`). /// Fail-closed with [`test_may_write_files`]: any writer in the body /// taints any file read, and a file-scope renamed `std::fs`/`std::env` /// import taints it too, as for the golden-file guard above. A writer in /// a helper outside the test body is not visible here and remains a /// known limitation. fn expected_reads_written_file( test: &TestSummary, renamed_fs_import: bool, expected: &str, ) -> bool { let may_write = test_may_write_files(&test.body) || renamed_fs_import; if !may_write { return false; } let reads_file = |text: &str| { let compact: String = mask_comments_and_strings(text) .chars() .filter(|c| !c.is_whitespace()) .collect(); ["read_to_string", "fs::read", "read_to_end", "File::open"] .iter() .any(|marker| compact.contains(marker)) }; if reads_file(expected) { return true; } // Reduce wrappers (`&want`, `&mut want`, `(want)`, `want.as_str()`, // `want.clone()`, ...) until stable, leaving the plain identifier // whose binding may hold the file read. let reduce = |mut text: &str| -> String { loop { let before = text; text = text .trim() .trim_start_matches('&') .trim_start_matches('*') .trim(); if text.starts_with("mut ") { text = text[4..].trim_start(); } if text.starts_with('(') && text.ends_with(')') { text = text[1..text.len() - 1].trim(); } for suffix in [".as_str()", ".clone()", ".trim()", ".as_ref()", ".unwrap()"] { if let Some(stripped) = text.strip_suffix(suffix) { text = stripped.trim(); } } if text == before { return text.to_string(); } } }; let operand = reduce(expected); // A method/parse chain rooted at a plain binding // (`want.trim().parse::().unwrap()`) still draws its value from // that binding. let operand = if is_plain_identifier(&operand) { operand } else { let root: String = operand .chars() .take_while(|c| c.is_alphanumeric() || *c == '_') .collect(); if root.is_empty() || !is_plain_identifier(&root) { return false; } root }; // Follow plain-identifier bindings a few hops. Every statement that // binds the current identifier counts (`let [mut] x = ..`, `x = ..`, // also inside blocks); any of them reading a file settles it, and // each plain-identifier right-hand side is followed in turn. let masked = mask_comments_and_strings(&test.body); let statements: Vec<&str> = masked.split(';').collect(); let binding_rhs = |statement: &str, ident: &str| -> Option { // A `let` binding may sit behind a block opener fragment; a bare // assignment may sit behind a block opener too. let rest = match statement.find("let ") { Some(at) => { let rest = statement[at + 4..].trim_start(); rest.strip_prefix("mut ").unwrap_or(rest).to_string() } None => { let at = statement.match_indices(ident).find_map(|(at, _)| { // A field assignment (`holder.want = ..`) does not // bind the plain local `want`. let before_ok = at == 0 || !statement[..at] .chars() .next_back() .is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '.'); before_ok.then_some(at) })?; statement[at..].to_string() } }; let after = rest.trim_start().strip_prefix(ident)?; let boundary = after.trim_start(); // Skip an optional `: Type` annotation before the `=`. let boundary = if let Some(annotated) = boundary.strip_prefix(':') { let eq = annotated.find('=')?; if annotated[eq..].starts_with("==") { return None; } &annotated[eq..] } else { boundary }; if !boundary.starts_with('=') || boundary.starts_with("==") { return None; } Some(boundary[1..].to_string()) }; let mut frontier = vec![operand]; let mut visited: Vec = Vec::new(); for _ in 0..4 { let mut next: Vec = Vec::new(); for ident in &frontier { for statement in &statements { let Some(rhs) = binding_rhs(statement, ident) else { continue; }; if reads_file(&rhs) || reads_file(statement) { return true; } let reduced = reduce(&rhs); let reduced = if is_plain_identifier(&reduced) { reduced } else { reduced .chars() .take_while(|c| c.is_alphanumeric() || *c == '_') .collect() }; if is_plain_identifier(&reduced) && !visited.contains(&reduced) && !next.contains(&reduced) { next.push(reduced); } } } visited.extend(frontier); if next.is_empty() { return false; } frontier = next; } false } /// RIPR-SPEC-0197: the compared operands of a plain `assert!(lhs == rhs)` /// or of the assertion twin of a terminal Err-return guard /// `if lhs != rhs { return Err(..) }` (RIPR-SPEC-0154). The condition must /// be one top-level `==`; any other top-level comparison, `&&`, `||`, a /// closure or a negated condition refuses. Owned, since a guard's operands /// are read from its synthesized twin. pub(in crate::analysis) fn equality_condition_operands(text: &str) -> Option<[String; 2]> { let condition = if is_plain_macro(text, "assert") { outer_assertion_condition(text)? } else { let (condition, twin) = err_return_guard_twin(text)?; // `if !a == b` is `(!a) == b`; never read it as `!(a == b)`. if condition.starts_with('!') { return None; } outer_assertion_condition(&twin)? }; top_level_equality_operands(&condition) } /// The two sides of a condition's single top-level `==`, split outside /// parentheses, brackets, braces, comments and strings. fn top_level_equality_operands(condition: &str) -> Option<[String; 2]> { let condition = condition.trim(); if condition.starts_with('!') { return None; } let masked = mask_comments_and_strings(condition); let bytes = masked.as_bytes(); let mut depth = 0usize; let mut split = None; let mut at = 0; while let Some(&byte) = bytes.get(at) { let next = bytes.get(at + 1).copied(); match byte { b'(' | b'[' | b'{' => depth += 1, b')' | b']' | b'}' => depth = depth.checked_sub(1)?, _ if depth > 0 => {} // `<`, `>`, `<=`, `>=`, `->`, `=>`, shifts, generics, closures // and `||` all refuse. b'<' | b'>' | b'|' => return None, b'&' if next == Some(b'&') => return None, b'!' if next == Some(b'=') => return None, b'=' if next == Some(b'=') => { if split.replace(at).is_some() { return None; } at += 2; continue; } // An assignment or compound assignment is not a comparison. b'=' => return None, _ => {} } at += 1; } if depth != 0 { return None; } let split = split?; let left = condition.get(..split)?.trim(); let right = condition.get(split + 2..)?.trim(); (!left.is_empty() && !right.is_empty()).then(|| [left.to_string(), right.to_string()]) } /// Whether `text` is one plain `assert_eq!` invocation: not /// `debug_assert_eq!` (compiled out in release tests), not a crate's own /// `*_assert_eq!`, not a path-qualified or repeated one. /// The text is exactly one unqualified invocation of `macro_name`. pub(in crate::analysis) fn is_plain_macro(text: &str, macro_name: &str) -> bool { let masked = mask_comments_and_strings(text); let invocations = macro_invocations(&masked); let [(name, _)] = invocations.as_slice() else { return false; }; *name == macro_name && masked .find(macro_name) .is_some_and(|offset| !masked[..offset].trim_end().ends_with(':')) } /// [`is_plain_macro`], or the same single invocation under a `std` or `core` /// root (`std::assert_eq!(..)`, `::core::assert_eq!(..)`). Admission /// credits the qualified form only when [`OwnerPinSyntax`] proves the root /// unrebound (#7857). fn is_plain_or_std_macro(text: &str, macro_name: &str) -> bool { is_plain_macro(text, macro_name) || std_rooted_macro_path(text, macro_name).is_some() } /// The whitespace-free path of every `std`/`core`-rooted `assert_eq!` call /// under `root` (#7857). fn std_rooted_assert_eq_calls(root: &ra_ap_syntax::SyntaxNode) -> BTreeSet { root.descendants() .filter_map(ast::MacroCall::cast) .filter_map(|call| call.path()) .map(|path| { path.syntax() .text() .to_string() .split_whitespace() .collect::() }) .filter(|path| STD_ROOTED_ASSERT_EQ.contains(&path.as_str())) .collect() } /// The whitespace-free path (`std::assert_eq`, `::core::assert_eq`) when /// `text` is one `macro_name` invocation under a `std` or `core` root. fn std_rooted_macro_path(text: &str, macro_name: &str) -> Option { let masked = mask_comments_and_strings(text); let invocations = macro_invocations(&masked); let [(name, _)] = invocations.as_slice() else { return None; }; let offset = masked.find(macro_name)?; let root: String = masked[..offset] .chars() .filter(|character| !character.is_whitespace()) .collect(); (*name == macro_name && matches!(root.as_str(), "std::" | "core::" | "::std::" | "::core::")) .then(|| format!("{root}{macro_name}")) } /// `spelling` (`assert_eq` or `debug_assert_eq`) whose only nested macros are `expansion` (`format!`, which /// [`helper_arguments::rendered_template_call`] reads, or `vec!`, which /// [`single_element_index`] reads). fn is_assert_eq_over(text: &str, spelling: &str, expansion: &str) -> bool { let masked = mask_comments_and_strings(text); let invocations = macro_invocations(&masked); let [(first, _), nested @ ..] = invocations.as_slice() else { return false; }; *first == spelling && !nested.is_empty() && nested.iter().all(|(name, _)| *name == expansion) && masked .find(spelling) .is_some_and(|offset| !masked[..offset].trim_end().ends_with(':')) } /// Whether a macro other than a known non-binding one mentions `name` in /// its arguments: `let_assert!(Ok(p) = ..)` and similar macros bind /// patterns ripr does not read. fn bound_by_macro(masked: &str, name: &str) -> bool { bound_by_macro_with(masked, name, &[]) } /// [`bound_by_macro`] where the macros in `bounded` are also known to bind /// nothing: the caller verified their import (claims' assertion macros). fn bound_by_macro_with(masked: &str, name: &str, bounded: &[&str]) -> bool { macro_invocations(masked) .into_iter() .filter(|(macro_name, _)| !is_bounded_macro(macro_name) && !bounded.contains(macro_name)) .any(|(_, delimiter)| { let (open, close) = match masked.as_bytes()[delimiter] { b'(' => (b'(', b')'), b'[' => (b'[', b']'), _ => (b'{', b'}'), }; let end = matching_close(masked, delimiter, open, close).unwrap_or(masked.len()); contains_as_whole_word(&masked[delimiter..end], name) }) } /// Whether the file renames some item to `name` (`use a::b as name;`, /// `extern crate a as name;`), so `name` may not be the item it looks like. /// Related-test reach shares the single-file rename refusal (#7067). /// /// Only an `as` inside a `use` or `extern crate` item renames: a cast /// (`letters as u32`) or a qualified path (`::clone`) in plain /// code binds no name, so it does not make `u32` or `Clone` something /// else. Lexical, so a `use` in any module, function body or macro body /// counts. An `as` inside a macro invocation's arguments or an attribute /// counts too: the macro may expand it into a `use` /// (`import!(other::Fake as u32);`), and ripr does not expand macros. pub(in crate::analysis) fn file_renames_to(source: &str, name: &str) -> bool { if !source.contains(name) { return false; } if let Some(renamed) = renamed_names_memoized(source) && let Some(plain) = plain_rename_target(name) { return renamed.contains(plain); } file_renames_to_uncached(source, name) } fn file_renames_to_uncached(source: &str, name: &str) -> bool { let masked = mask_comments_and_strings(source); let spans = rename_item_spans(&masked); whole_word_offsets(&masked, "as").into_iter().any(|offset| { starts_with_word(masked[offset + "as".len()..].trim_start(), name) && spans.iter().any(|span| span.contains(&offset)) }) } /// `name` when it is one identifier, optionally raw (`r#name`): the only /// spellings whose "starts the word after `as`" test is a token equality. fn plain_rename_target(name: &str) -> Option<&str> { let bare = name.strip_prefix("r#").unwrap_or(name); is_plain_identifier(bare).then_some(name) } /// The identifier (with an `r#` prefix kept) that follows `as`, if any. fn word_after_as(rest: &str) -> &str { let rest = rest.trim_start(); let body = rest.strip_prefix("r#").unwrap_or(rest); let len = body .bytes() .take_while(|byte| byte.is_ascii_alphanumeric() || *byte == b'_') .count(); &rest[..rest.len() - body.len() + len] } /// Every word that follows an `as` inside a renaming item of `source`, /// computed once per distinct source text. A pilot asks `file_renames_to` /// for each (seam, test, type) triple; masking and scanning the whole test /// file each time dominated ripgrep's evidence stage. Content-keyed and verified against the stored text, so a /// changed file can never read a stale answer; bounded so a long-lived /// process cannot grow without limit. `None` if the lock is poisoned. fn renamed_names_memoized(source: &str) -> Option>> { // The full text is kept beside its answer and compared on a hit, so a // key collision can only miss, never hand one file another's renames // (which would drop a refusal). The key is the length plus a bounded // byte sample: a pilot asks per (seam, test, type) triple, and hashing the // whole file each time (SipHash over every byte) was a third of ripgrep's // evidence stage. Files that share a key sit side by side in one bucket. type Entry = (Arc, Arc>); static MEMO: std::sync::Mutex>> = std::sync::Mutex::new(BTreeMap::new()); const MAX_ENTRIES: usize = 2048; let key = source_sample_key(source); if let Ok(memo) = MEMO.lock() && let Some((_, found)) = memo .get(&key) .and_then(|bucket| bucket.iter().find(|(text, _)| &**text == source)) { return Some(Arc::clone(found)); } let masked = mask_comments_and_strings(source); let spans = rename_item_spans(&masked); let renamed: BTreeSet = whole_word_offsets(&masked, "as") .into_iter() .filter(|offset| spans.iter().any(|span| span.contains(offset))) .flat_map(|offset| { let word = word_after_as(&masked[offset + "as".len()..]); // `as r#Foo` also starts the word `r`, as the uncached check reads it. let bare_r = word.starts_with("r#").then_some("r"); std::iter::once(word).chain(bare_r) }) .filter(|word| !word.is_empty()) .map(str::to_string) .collect(); let renamed = Arc::new(renamed); let mut memo = MEMO.lock().ok()?; if memo.values().map(Vec::len).sum::() >= MAX_ENTRIES { memo.clear(); } let bucket = memo.entry(key).or_default(); if !bucket.iter().any(|(text, _)| &**text == source) { bucket.push((Arc::from(source), Arc::clone(&renamed))); } Some(renamed) } /// A cheap memo key for `source`: its length and a byte sample spread evenly /// across it (the whole file when it is under 2048 bytes, otherwise up to /// about 2047 bytes at a stride of `len / 1024`). Equal texts always share a key; unequal texts may, which /// callers resolve by comparing the full text. fn source_sample_key(source: &str) -> u64 { use std::hash::{Hash, Hasher}; let bytes = source.as_bytes(); let mut hasher = std::collections::hash_map::DefaultHasher::new(); bytes.len().hash(&mut hasher); let stride = (bytes.len() / 1024).max(1); for byte in bytes.iter().step_by(stride) { byte.hash(&mut hasher); } hasher.finish() } /// The byte spans in `masked` where an `as` may rename: every `use ..;` /// and `extern crate ..;` item, from the keyword to its `;` (or the end of /// the text when the `;` is missing, which keeps an unterminated item /// renaming), every macro invocation's delimited arguments and every /// attribute (`#[..]`, `#![..]`). An unmatched delimiter runs to the end of /// the text, which fails closed. fn rename_item_spans(masked: &str) -> Vec> { let bytes = masked.as_bytes(); let delimited = |open_at: usize| { let (open, close) = match bytes[open_at] { b'(' => (b'(', b')'), b'[' => (b'[', b']'), _ => (b'{', b'}'), }; open_at..matching_close(masked, open_at, open, close).unwrap_or(masked.len()) }; // Any `name!` followed by a delimiter, whatever the name: a Unicode or // keyword-like macro name still expands its arguments (#7926 review). // A negation such as `if !(x)` adds a span too, which only refuses more. let macro_spans = masked.match_indices('!').filter_map(|(bang, _)| { let named = masked[..bang] .trim_end() .chars() .next_back() .is_some_and(|character| character.is_alphanumeric() || character == '_'); let after = masked[bang + 1..].trim_start(); (named && after.starts_with(['(', '[', '{'])).then(|| delimited(masked.len() - after.len())) }); let attribute_spans = masked.match_indices('#').filter_map(|(hash, _)| { let after = masked[hash + 1..].trim_start(); let after = after.strip_prefix('!').map_or(after, str::trim_start); after .starts_with('[') .then(|| delimited(masked.len() - after.len())) }); let mut spans: Vec> = macro_spans.chain(attribute_spans).collect(); spans.extend(rename_statement_spans(masked)); spans } /// The `use ..;` and `extern crate ..;` items of [`rename_item_spans`]. fn rename_statement_spans(masked: &str) -> Vec> { let item_end = |from: usize| { masked[from..] .find(';') .map_or(masked.len(), |end| from + end) }; // `impl Trait + use<'a>` (precise capturing) is not an import. let mut spans: Vec> = whole_word_offsets(masked, "use") .into_iter() .filter(|offset| !masked[offset + "use".len()..].trim_start().starts_with('<')) // A raw identifier `r#use` is not the keyword (#7936). .filter(|offset| !masked[..*offset].ends_with("r#")) .map(|offset| offset..item_end(offset)) .collect(); spans.extend( whole_word_offsets(masked, "extern") .into_iter() .filter(|offset| { starts_with_word(masked[offset + "extern".len()..].trim_start(), "crate") }) .map(|offset| offset..item_end(offset)), ); spans } /// An alias cannot be excluded merely because its spelling differs from an /// indexed impl's self type. Retain a named refusal instead. pub(in crate::analysis) fn targeted_name_is_alias(index: &RustIndex, name: &str) -> bool { index .files() .values() .any(|facts| file_aliases_type(&facts.source, name) || file_renames_to(&facts.source, name)) } pub(in crate::analysis) fn targeted_type_name_is_unresolved( test: &TestSummary, index: &RustIndex, name: &str, ) -> bool { if name == "Self" || targeted_name_is_alias(index, name) { return true; } let Some(facts) = index.files().get(&test.file) else { return true; }; let Some(parse) = parse_clean_source_file(&facts.source) else { return true; }; let Some(function) = resolve_owner_fn( parse.tree().syntax(), &facts.source, OwnerScope::new(&test.name, test.start_line, &test.file), ) else { return true; }; function .syntax() .descendants() .filter_map(ast::TypeParam::cast) .any(|parameter| { parameter .name() .is_some_and(|parameter| parameter.text() == name) }) } /// Admit only an actual parser-established free owner through the existing /// binding authority. Candidate ambiguity is reported by the selector first; /// unindexed/unsupported competing definitions still refuse here. pub(in crate::analysis) fn targeted_free_call_reaches_owner( test: &TestSummary, owner: &FunctionSummary, prefix: Option<&str>, index: &RustIndex, syntax: &OwnerPinSyntax, ) -> bool { free_call_reaches_definition(test, owner, prefix, index, syntax, false) } /// A polling helper is available in the test build, unlike the production /// owner admitted by the targeted-call API. Its closed source reader checks /// supported_targeted_item_context; all binding/competition gates are shared. pub(super) fn polling_helper_call_reaches_definition( test: &TestSummary, helper: &FunctionSummary, index: &RustIndex, syntax: &OwnerPinSyntax, ) -> bool { free_call_reaches_definition(test, helper, None, index, syntax, true) } fn free_call_reaches_definition( test: &TestSummary, owner: &FunctionSummary, prefix: Option<&str>, index: &RustIndex, syntax: &OwnerPinSyntax, test_build_helper: bool, ) -> bool { if !owner.item.has_body || !matches!(pin_call(owner, index), Some(PinCall::Bare)) || other_definition_competes(owner, index, CallKind::Bare, None) || index .files() .get(&owner.file) .is_none_or(|facts| facts.used_lexical_fallback) || index .files() .get(&test.file) .is_none_or(|facts| facts.used_lexical_fallback) { return false; } let Some(facts) = index.files().get(&test.file) else { return false; }; let binding = FreeOwnerBinding { name: &owner.name, owner_file: &owner.file, owner_start_line: owner.start_line, }; if let Some(prefix) = prefix { return binding.path_reaches_owner(prefix, test, &facts.source, index, syntax); } let masked_body = mask_comments_and_strings(&test.body); (test_build_helper || (!syntax .item_nesting(index, &owner.file, &owner.name, owner.start_line) .is_none_or(|owner| owner.cfg_gated) && !syntax.file_cfg_gated(index, &owner.file))) && !test_body_shadows_owner(test, &owner.name) && !binds_outside_let(&masked_body, &owner.name) && !bound_by_macro(&masked_body, &owner.name) && !file_renames_to(&facts.source, &owner.name) && if test_build_helper { binding.bare_call_reaches_owner_uncached(test, &facts.source, index, syntax, true) } else { binding.bare_call_reaches_owner(test, &facts.source, index, syntax) } } /// Executable helper admission shares lexical call identity and item refusal, /// without imposing production-owner pin Cargo/cfg prerequisites on same-file /// test helpers. Every caller supplies an actual parsed call site. pub(in crate::analysis) fn same_file_free_helper_call_reaches_owner( caller: &TestSummary, helper: &FunctionSummary, prefix: Option<&str>, index: &RustIndex, syntax: &OwnerPinSyntax, ) -> bool { if caller.file != helper.file || index .files() .get(&helper.file) .is_none_or(|facts| facts.used_lexical_fallback) { return false; } let Some(identity) = super::call_identity::shared_same_file_helper_identity(index, helper) else { return false; }; let qualifier = prefix.map(path_prefix_segments).unwrap_or_default(); if identity.resolve_same_file_call(caller, index, &qualifier) != CallTarget::Owner { return false; } let masked_body = mask_comments_and_strings(&caller.body); if prefix.is_none() && (test_body_shadows_owner(caller, &helper.name) || binds_outside_let(&masked_body, &helper.name) || bound_by_macro(&masked_body, &helper.name)) { return false; } let Some(nesting) = syntax.item_nesting(index, &helper.file, &helper.name, helper.start_line) else { return false; }; let binding = FreeOwnerBinding { name: &helper.name, owner_file: &helper.file, owner_start_line: helper.start_line, }; binding.resolved_module_delivers_owner( helper.file.clone(), nesting.modules.clone(), &nesting.modules, index, syntax, ) } /// Whether the file declares a type alias `type name`. fn file_aliases_type(source: &str, name: &str) -> bool { if !source.contains(name) { return false; } let masked = mask_comments_and_strings(source); whole_word_offsets(&masked, "type") .into_iter() .any(|offset| starts_with_word(masked[offset + "type".len()..].trim_start(), name)) } /// #7097: one file's module scopes — the file top plus every inline /// module with a body — each with its direct `use`s and the items that /// can take a value call. A bare call resolves through the test's own /// scope only, so ancestor scopes are consulted solely as glob targets. #[derive(Clone, Debug, Default)] pub(super) struct FileScopes { scopes: Vec, /// Every `fn` in the file, at any depth, for test-fn ancestry. fns: Vec, } /// #7097: one `fn` item's name and byte span. #[derive(Clone, Debug)] struct ScopeFn { name: String, start: u32, end: u32, start_line: usize, } /// #7097: one module scope: its inline-module stack from the file top /// (empty at file top), its byte span, every direct `use` flattened, /// every direct value-taking item's name, and macro text that may emit /// or mention one. #[derive(Clone, Debug)] struct ModuleScope { stack: Vec, start: u32, end: u32, uses: Vec, twins: Vec, macro_args: Vec, macro_defs: Vec, } impl OwnerPinSyntax { /// #7097: out-of-line module children, built once per run from the /// recorded module edges. Two children under one (parent, name) — /// cfg'd alternatives — resolve to neither. fn mod_children(&self, index: &RustIndex) -> &BTreeMap<(PathBuf, String), Option> { self.mod_children.get_or_init(|| { let mut children: BTreeMap<(PathBuf, String), Option> = BTreeMap::new(); for (child, _) in index.files().iter() { let Some(context) = index.execution_context(child) else { continue; }; let mut direct = context.edges.iter().filter(|edge| &edge.child == child); let (Some(edge), None) = (direct.next(), direct.next()) else { continue; }; let Some(name) = module_declaration_name(&edge.declaration) else { continue; }; children .entry((edge.parent.clone(), name)) .and_modify(|slot| { if slot.as_ref() != Some(child) { *slot = None; } }) .or_insert_with(|| Some(child.clone())); } children }) } /// Complete-source lexical facts are shared across short-lived syntax /// owners too. Source identity is checked before serving any stored table. fn file_scopes(&self, index: &RustIndex, file: &Path) -> Option> { let facts = index.files().get(file)?; let source = &facts.data().source; let compute = || { Some(Arc::new(build_file_scopes( &index.source_syntax.get(index, file)?.tree()?, ))) }; // Build outside the index-wide lock; re-lock and keep the first entry // stored for this exact source so concurrent callers share one table. if let Ok(memo) = index.call_identity_memos.owner_file_scopes.lock() && let Some((known_source, scopes)) = memo.get(file) && Arc::ptr_eq(known_source, source) { return scopes.clone(); } let scopes = compute(); match index.call_identity_memos.owner_file_scopes.lock() { Ok(mut memo) => { if let Some((known_source, stored)) = memo.get(file) && Arc::ptr_eq(known_source, source) { return stored.clone(); } memo.insert(file.to_path_buf(), (Arc::clone(source), scopes.clone())); scopes } Err(_) => scopes, } } } /// #7097: the scope table of `source`, or `None` when it does not parse. fn build_file_scopes(tree: &ast::SourceFile) -> FileScopes { let end: u32 = tree.syntax().text_range().end().into(); let source = tree.syntax().text().to_string(); let lines = LineIndex::new(&source); let mut scopes = FileScopes::default(); scopes.push_scope(tree.syntax(), Vec::new(), 0, end); for func in tree.syntax().descendants().filter_map(ast::Fn::cast) { if let Some(name) = func.name() { let text = name.text().to_string(); let range = func.syntax().text_range(); let start: u32 = range.start().into(); let end: u32 = range.end().into(); scopes.fns.push(ScopeFn { name: strip_raw(&text).to_string(), start, end, start_line: lines.line(range.start()), }); } } scopes } impl FileScopes { /// Record `container` (the file root or an inline module body) as one /// scope, then recurse into its direct child modules. fn push_scope(&mut self, container: &SyntaxNode, stack: Vec, start: u32, end: u32) { let mut scope = ModuleScope { stack, start, end, uses: Vec::new(), twins: Vec::new(), macro_args: Vec::new(), macro_defs: Vec::new(), }; let mut children = Vec::new(); for item in container.children().filter_map(ast::Item::cast) { scope.absorb(&item); if let ast::Item::Module(module) = &item && let Some(body) = module.item_list() && let Some(name) = module.name() { let text = name.text().to_string(); let mut stack = scope.stack.clone(); stack.push(strip_raw(&text).to_string()); let range = module.syntax().text_range(); let start: u32 = range.start().into(); let end: u32 = range.end().into(); children.push((body.syntax().clone(), stack, start, end)); } } self.scopes.push(scope); for (container, stack, start, end) in children { self.push_scope(&container, stack, start, end); } } /// The test's own module scope: exact scope first, from the test /// fn's own span — line spans coincide for same-line siblings (`mod /// outer { mod nested { ... #[test] fn check() ... } }` on one line), /// where the line alone resolves to the file top. A macro-generated /// test has no matching `fn` node, so it keeps the line-span fallback /// to the module its invocation expands in. Duplicate `fn` nodes are /// already refused by assertion admission; here they fail closed. fn scope_of_test(&self, source: &str, test: &TestSummary) -> Option<&ModuleScope> { let wanted = strip_raw(&test.name); let line_of = |offset: u32| { source .get(..offset as usize) .map(|prefix| prefix.matches('\n').count() + 1) }; let found: Vec<&ScopeFn> = self .fns .iter() .filter(|func| { func.name == wanted && line_of(func.start).is_some_and(|start| start <= test.end_line) && line_of(func.end).is_some_and(|end| test.start_line <= end) }) .collect(); if let [func] = found.as_slice() { let offset = func.start; return self .scopes .iter() .filter(|scope| scope.start <= offset && offset <= scope.end) .max_by_key(|scope| scope.stack.len()); } if found.is_empty() { return self.scope_at(source, test.start_line); } None } /// The deepest scope containing `line` (1-based) in `source`: the /// test's own module, or the file top. fn scope_at(&self, source: &str, line: usize) -> Option<&ModuleScope> { let mut offset = 0usize; for _ in 1..line { let Some(relative) = source.get(offset..)?.find('\n') else { break; }; offset = offset.saturating_add(relative + 1); } let offset = u32::try_from(offset).ok()?; self.scopes .iter() .filter(|scope| scope.start <= offset && offset <= scope.end) .max_by_key(|scope| scope.stack.len()) } /// The scope with exactly `stack`, when the file declares it. fn scope_with_stack(&self, stack: &[String]) -> Option<&ModuleScope> { self.scopes.iter().find(|scope| scope.stack == stack) } } impl ModuleScope { /// One direct item: `use`s flatten, value-taking items record their /// name, and macros record the text that may emit or mention one. A /// direct `fn` is never a twin: the establish gate already refused /// every other `fn` of the name, so a remaining one is the owner /// itself. Type-only items (`mod`, `trait`, `type`, `enum`, `union`, /// non-tuple `struct`) share no namespace with a value call. fn absorb(&mut self, item: &ast::Item) { match item { ast::Item::Use(item) => { self.uses .extend(flattened_use_paths(&item.syntax().text().to_string())); } ast::Item::Static(item) => self.twin_name(item.name()), ast::Item::Const(item) => self.twin_name(item.name()), ast::Item::Struct(item) => { // Tuple and unit structs take the value namespace (a unit // struct's constructor collides with an imported fn, E0255; // braced structs do not conflict — both probed with rustc, // #7176 review). if matches!( item.kind(), ast::StructKind::Tuple(_) | ast::StructKind::Unit ) { self.twin_name(item.name()); } } ast::Item::ExternBlock(block) => { // Extern items hang under the EXTERN_ITEM_LIST node, not // under the block itself (#7176 review). if let Some(list) = block.extern_item_list() { for child in list.extern_items() { match &child { ast::ExternItem::Fn(item) => self.twin_name(item.name()), ast::ExternItem::Static(item) => self.twin_name(item.name()), _ => {} } } } } // An invocation may emit the name from its arguments (`emit!(weight)`); // only the token tree counts, never the macro's own name. ast::Item::MacroCall(call) => { if let Some(tree) = call.token_tree() { self.macro_args.push(tree.syntax().text().to_string()); } } // A definition may hardcode the twin; its text decides, as for // types (#6948). The parse is error-free, so no item is unparsed. ast::Item::MacroRules(rules) => { self.macro_defs.push(rules.syntax().text().to_string()); } ast::Item::MacroDef(def) => { self.macro_defs.push(def.syntax().text().to_string()); } _ => {} } } fn twin_name(&mut self, name: Option) { if let Some(name) = name { let text = name.text().to_string(); self.twins.push(strip_raw(&text).to_string()); } } /// Whether the scope holds a twin of `name`: a value-taking item, a /// macro invocation mentioning it, or a macro definition spelling a /// twin declaration of it. fn has_twin(&self, name: &str) -> bool { let name = strip_raw(name); self.twins.iter().any(|twin| twin == name) || self .macro_args .iter() .any(|text| contains_as_whole_word(&mask_comments_and_strings(text), name)) || self .macro_defs .iter() .any(|text| declares_value_twin(&mask_comments_and_strings(text), name)) } } /// #7097: where a `use` is read from: its file, that file's source, /// and the inline-module stack of the scope holding it. #[derive(Clone, Copy)] struct ScopeContext<'a> { file: &'a Path, source: &'a str, stack: &'a [String], } /// #7097: the module name a `mod name;` declaration binds, or `None` /// when the declaration is unreadable. fn module_declaration_name(declaration: &str) -> Option { let mut words = declaration .split_whitespace() .skip_while(|word| *word != "mod"); words.next()?; let name = words.next()?.trim_end_matches(';'); let name = strip_raw(name); (!name.is_empty() && is_plain_identifier(name)).then(|| name.to_string()) } /// Whether masked text declares a value-taking item of `name` outside a /// `fn`: a `static`/`const` (any form) or a tuple struct. Type-only /// items share no namespace with a value call. fn declares_value_twin(masked: &str, name: &str) -> bool { let name = strip_raw(name); ["static", "const"].iter().any(|keyword| { whole_word_offsets(masked, keyword) .into_iter() .any(|offset| { let rest = masked[offset + keyword.len()..].trim_start(); // `static mut name` carries a qualifier between the keyword // and the name (#7176 review); `const` never does. let rest = if *keyword == "static" { skip_mut_qualifier(rest) } else { rest }; strip_item_name(rest, name).is_some() }) }) || whole_word_offsets(masked, "struct") .into_iter() .any(|offset| { strip_item_name(masked[offset + "struct".len()..].trim_start(), name) .and_then(skip_generics) // Tuple structs take the call; unit structs collide with an // imported fn (E0255, rustc-probed); braced structs share // no namespace with the call (#7176 review). .is_some_and(|after| after.starts_with('(') || after.starts_with(';')) }) } /// The text after a `mut` qualifier, when `rest` opens with one as a /// whole word. Anything else (including `mutx`) passes through. fn skip_mut_qualifier(rest: &str) -> &str { let Some(after) = rest.strip_prefix("mut") else { return rest; }; if after.starts_with(|c: char| c.is_ascii_alphanumeric() || c == '_') { return rest; } after.trim_start() } /// Whether the test body declares a value-taking item of `name`. A body /// `fn` or `let` is already refused (`test_body_shadows_owner`); a /// `static` (plain or `mut`), `const`, tuple or unit struct there shadows /// every import the same way. Items in a nested block or `fn` cannot reach /// the call, so counting them over-refuses (residual). fn body_defines_value_twin(body: &str, name: &str) -> bool { declares_value_twin(&mask_comments_and_strings(body), name) } /// The text after an item name of `name` (raw marker dropped), or `None` /// when `rest` names something else. fn strip_item_name<'a>(rest: &'a str, name: &str) -> Option<&'a str> { let rest = strip_raw(rest); let after = rest.strip_prefix(name)?; if after.starts_with(|character: char| character.is_ascii_alphanumeric() || character == '_') { return None; } Some(after.trim_start()) } /// The text after one `<...>` generic group, or `text` when it opens /// with none; `None` when the group never closes. fn skip_generics(text: &str) -> Option<&str> { let Some(rest) = text.strip_prefix('<') else { return Some(text); }; let mut depth = 1u32; for (offset, byte) in rest.bytes().enumerate() { match byte { b'<' => depth += 1, b'>' => { depth -= 1; if depth == 0 { return Some(rest[offset + 1..].trim_start()); } } _ => {} } } None } /// #7097: the `use`s of `uses` that bind `name` explicitly, and the glob /// imports. A rename to the name (`use x::y as name`) binds it too, so /// it counts here; other aliases bind another name. The test file's own /// renames refuse file-wide already (`file_renames_to`). fn partition_name_uses<'a>( uses: &'a [UsePath], name: &str, ) -> (Vec<&'a UsePath>, Vec<&'a UsePath>) { let name = strip_raw(name); let mut bindings = Vec::new(); let mut globs = Vec::new(); for use_path in uses { if use_path.path.ends_with("::*") { globs.push(use_path); continue; } let binds = match use_path.alias.as_deref() { Some(alias) => strip_raw(alias) == name, None => use_path .path .rsplit("::") .next() .is_some_and(|terminal| strip_raw(terminal) == name), }; if binds { bindings.push(use_path); } } (bindings, globs) } /// #7097: the crate root file `file` composes under: the outermost /// recorded module edge's parent, or the file itself. Unlike /// [`target_root`], this ignores the workspace-wide disabled switch and /// the recognized-target shape: the manifest authority /// (`import_names`) validates the root itself, and the assertion and /// file rules already refused include-composed and unresolved files /// before this gate runs — so an unrelated unresolvable module /// elsewhere keeps other owners pinned, as the file rule requires. fn composed_root(file: &Path, index: &RustIndex) -> PathBuf { index .files() .get(file) .and_then(|facts| { facts .role_provenance .edges .first() .map(|edge| edge.parent.clone()) }) .unwrap_or_else(|| file.to_path_buf()) } /// Whether a `use` root segment names a workspace package: the manifest /// name or its crate identifier (`foo-bar` imports as `foo_bar`). fn crate_names_package(segment: &str, packages: &BTreeSet) -> bool { packages .iter() .any(|name| name == segment || name.replace('-', "_") == segment) } /// An identifier with its raw marker dropped. fn strip_raw(text: &str) -> &str { text.strip_prefix("r#").unwrap_or(text) } /// #7097: split a binding `use` path into its root segment and module /// segments (raw markers dropped): `demo::scale::weight` gives /// (`demo`, [`scale`]). `None` when the path binds another name, has a /// single segment (an extern crate in edition 2018+, never the owner /// fn), or renames another item to the name. fn split_binding_use<'a>(use_path: &'a UsePath, name: &str) -> Option<(&'a str, Vec<&'a str>)> { if use_path .alias .as_deref() .is_some_and(|alias| strip_raw(alias) != strip_raw(name)) { return None; } let stripped = use_path.path.strip_prefix("::").unwrap_or(&use_path.path); let segments: Vec<&str> = stripped.split("::").map(strip_raw).collect(); let [first, rest @ ..] = segments.as_slice() else { return None; }; let terminal = rest.last().copied()?; if strip_raw(terminal) != strip_raw(name) { return None; } Some((*first, rest[..rest.len() - 1].to_vec())) } /// #7097: split a glob `use` path into its root segment and full module /// prefix: `demo::scale::*` gives (`demo`, [`scale`]). fn split_glob_prefix(path: &str) -> Option<(&str, Vec<&str>)> { let stripped = path.strip_prefix("::").unwrap_or(path); let prefix = stripped.strip_suffix("::*")?; let segments: Vec<&str> = prefix.split("::").map(strip_raw).collect(); let [first, rest @ ..] = segments.as_slice() else { return None; }; Some((*first, rest.to_vec())) } /// #7097: `pop_super`, climbing past the file top into the declaring /// parent through module edges: an out-of-line `tests.rs` at file-top /// stack `[]` climbs `super::` into the inline scope holding its `mod` /// declaration (#7176 review). Include edges never climb (a textual /// paste has no parent module). Each pop consumes one `super`, so the /// walk terminates. fn pop_super_across_files<'a>( index: &RustIndex, syntax: &OwnerPinSyntax, file: &Path, stack: &[String], first: &str, segments: &[&'a str], ) -> Option<(PathBuf, Vec, Vec<&'a str>)> { let mut file = file.to_path_buf(); let mut module = stack.to_vec(); if first == "super" { climb_one_level(index, syntax, &mut file, &mut module)?; } let supers = segments .iter() .take_while(|segment| **segment == "super") .count(); for _ in 0..supers { climb_one_level(index, syntax, &mut file, &mut module)?; } if segments[supers..] .iter() .any(|segment| matches!(*segment, "self" | "super" | "crate")) { return None; } Some((file, module, segments[supers..].to_vec())) } /// #7097: climb one `super` level: pop the inline stack, or — at the /// file top — continue from the inline scope holding this file's `mod` /// declaration in its declaring parent. Include edges never climb. fn climb_one_level( index: &RustIndex, syntax: &OwnerPinSyntax, file: &mut PathBuf, stack: &mut Vec, ) -> Option<()> { if stack.pop().is_some() { return Some(()); } let context = index.execution_context(file)?; let mut direct = context.edges.iter().filter(|edge| edge.child == *file); let (Some(edge), None) = (direct.next(), direct.next()) else { return None; }; let parent = index.files().get(&edge.parent)?; let scopes = syntax.file_scopes(index, &edge.parent)?; *stack = scopes .scope_at(&parent.data().source, edge.line)? .stack .clone(); *file = edge.parent.clone(); Some(()) } /// Whether another workspace definition of the owner's name could take a /// call by that name. A bare call competes with every other module-level /// function of the name; a method call competes with every other method of /// the name that has a body (overrides, inherent methods of other types, /// other traits' methods), except a pure `(**self).name(..)` forward, which /// dispatches to the same method on the pointee. A definition whose item /// container is unknown (lexical fallback) always competes, and so does a /// `fn name` the parser never indexed (inside a `macro_rules!` body). /// /// An associated `T::name(..)` call (#6617, RIPR-SPEC-0172) competes with /// every other definition of the name that is not a module-level or local /// function: inherent and trait-impl functions of any type, trait items, /// unknown containers, and every unindexed `fn name`. A free function /// cannot be the target of a type path, so it never competes. fn other_definition_competes( owner: &FunctionSummary, index: &RustIndex, kind: CallKind, settled_per_test: Option<&OwnerCallIdentity>, ) -> bool { let method = kind == CallKind::Method; let associated = kind == CallKind::Associated; let name = owner.name.as_str(); let is_owner = |file: &PathBuf, line: usize| *file == owner.file && line == owner.start_line; let indexed_competes = index.functions().iter().any(|function| { if function.name != name || is_owner(&function.file, function.start_line) { return false; } match function.item.container { FunctionContainer::Unknown => true, FunctionContainer::Local => false, FunctionContainer::Free => { !method && !associated && !settled_per_test.is_some_and(|identity| identity.settles(function)) } _ if associated => true, _ => { method && function.item.has_self_param && function.item.has_body && !is_self_forward(&function.body, name) } } }); if indexed_competes { return true; } index.files().iter().any(|(path, facts)| { // Masking only erases text, so a file whose raw source has no // `fn ` has none after masking either; skip the mask. if !facts.source.contains(name) || fn_definition_offsets(&facts.source, name).is_empty() { return false; } let masked = mask_comments_and_strings(&facts.source); fn_definition_offsets(&masked, name) .into_iter() .any(|offset| { let line = masked[..offset] .bytes() .filter(|byte| *byte == b'\n') .count() + 1; let indexed = facts .functions .iter() .any(|function| function.name == name && function.start_line == line) || is_owner(path, line); if indexed { return false; } // An unindexed definition cannot be placed: it may be an // associated function of any type. if associated { return true; } let Some(definition) = unindexed_definition(&facts.source, &masked, offset) else { return true; }; match definition.body { None => false, Some(body) => definition.has_self == method && !is_self_forward(body, name), } }) }) } struct UnindexedDefinition<'a> { has_self: bool, body: Option<&'a str>, } /// The parameter receiver and body of a `fn` definition the parser did not /// index, read from its text. fn unindexed_definition<'a>( source: &'a str, masked: &str, offset: usize, ) -> Option> { let params = offset + masked[offset..].find('(')?; let params_close = matching_close(masked, params, b'(', b')')?; let first_param = masked[params + 1..params_close] .split(',') .next() .unwrap_or("") .trim(); let receiver = first_param.trim_start_matches('&').trim_start(); let receiver = if receiver.starts_with('\'') { receiver .split_once(char::is_whitespace) .map_or("", |(_, rest)| rest.trim_start()) } else { receiver }; let receiver = receiver .strip_prefix("mut ") .map_or(receiver, str::trim_start); let has_self = receiver == "self" || receiver.starts_with("self:") || receiver.starts_with("self "); let mut depth = 0usize; for (relative, byte) in masked[params_close..].bytes().enumerate() { match byte { b'(' | b'[' => depth += 1, b')' | b']' => depth = depth.saturating_sub(1), b';' if depth == 0 => { return Some(UnindexedDefinition { has_self, body: None, }); } b'{' if depth == 0 => { let open = params_close + relative; let close = matching_close(masked, open, b'{', b'}')?; return Some(UnindexedDefinition { has_self, body: Some(&source[open..=close]), }); } _ => {} } } None } /// Whether `body` only forwards to the same method on the pointee: /// `{ (**self).name(..) }` or `{ (*self).name(..) }`. fn is_self_forward(body: &str, name: &str) -> bool { let masked = mask_comments_and_strings(body); let Some(open) = masked.find('{') else { return false; }; let Some(close) = matching_close(&masked, open, b'{', b'}') else { return false; }; let inner = body[open + 1..close].trim(); ["(**self).", "(*self)."].iter().any(|prefix| { inner .strip_prefix(prefix) .is_some_and(|call| matches!(owner_call_shape(call, name), Some(CallShape::Bare))) }) } /// Offsets of the `fn` keyword in every `fn ` definition. fn fn_definition_offsets(masked: &str, name: &str) -> Vec { whole_word_offsets(masked, "fn") .into_iter() .filter(|offset| { let rest = masked[offset + 2..].trim_start(); rest.strip_prefix(name).is_some_and(|after| { let after = after.trim_start(); after.starts_with('(') || after.starts_with('<') }) }) .collect() } /// The name-keyed workspace scans [`OwnerReturnPin::establish`] runs for an /// owner that files outside the index could still change (#5320). Each scan /// is monotone in the files it sees, so once the index decides it, more /// files cannot change it; an undecided scan names what a file must spell. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub(in crate::analysis) struct PinScopeNeeds { /// No other indexed `fn ` competes yet; another file's could. pub(in crate::analysis) competing_definitions: bool, /// The receiver type is not declared in the index yet; another file's /// `struct`/`enum`/`union` of this name would declare it. pub(in crate::analysis) receiver_type: Option, /// A trait method's receivers come from every `impl for` block. pub(in crate::analysis) trait_impls: Option, /// A test binding `let x = T::ctor()` pins this receiver type only when /// exactly one inherent `impl T { fn ctor }` exists; another file's /// `impl` block for a same-named type changes that count. pub(in crate::analysis) constructor_type: Option, } /// What [`PinScopeNeeds`] says for `owner` over `index`. pub(in crate::analysis) fn pin_scope_needs( owner: &FunctionSummary, index: &RustIndex, ) -> PinScopeNeeds { let mut needs = PinScopeNeeds::default(); if !owner.item.has_body { return needs; } let kind = match (&owner.item.container, owner.item.has_self_param) { (FunctionContainer::Free, false) => CallKind::Bare, // #6617: another file's declaration of `T` (or a `mod`, `trait` or // `type` of its name) changes `associated_owner_type`, so the type // is always a need, declared yet or not. (FunctionContainer::Inherent { self_ty }, false) => { if !is_associated_type_name(self_ty) { return needs; } needs.receiver_type = Some(self_ty.clone()); CallKind::Associated } (FunctionContainer::Inherent { self_ty }, true) | (FunctionContainer::TraitImpl { self_ty, .. }, true) => { needs.constructor_type = path_base_name(self_ty).map(str::to_string); if declared_receiver(self_ty, index).is_none() { // A shape `declared_receiver` never accepts stays refused // whatever else is indexed. if self_ty.starts_with(['&', '[', '(', '*']) || self_ty.starts_with("dyn ") { return needs; } let Some(base) = path_base_name(self_ty) else { return needs; }; needs.receiver_type = Some(base.to_string()); } CallKind::Method } (FunctionContainer::Trait { trait_name }, true) => { needs.trait_impls = Some(trait_name.clone()); CallKind::Method } _ => return needs, }; // Same rivals `establish` settles per test (#6544): once indexed they no // longer refuse, but files that define more of them still widen scope. let identity = match kind { CallKind::Bare => super::call_identity::shared_owner_call_identity(index, owner), CallKind::Method | CallKind::Associated => None, }; needs.competing_definitions = !other_definition_competes(owner, index, kind, identity.as_deref()); needs } /// #6617: a self type an associated-function pin can name: one CamelCase /// identifier (no generics, path, reference or `Self`). fn is_associated_type_name(self_ty: &str) -> bool { is_plain_identifier(self_ty) && self_ty != "Self" && self_ty.starts_with(|character: char| character.is_ascii_uppercase()) } /// #6617: the type an associated-function owner's `T::name(..)` call must /// name. `T` must be one CamelCase identifier that exactly one `struct`, /// `enum` or `union` in the index declares, and no indexed file may give /// the name to a `mod`, `trait` or `type` alias: a module `T` would turn /// `T::name(..)` into a free-function path, and a second declaration or an /// alias could be the `T` a test imports. Anything else refuses. fn associated_owner_type(self_ty: &str, index: &RustIndex) -> Option { if !is_associated_type_name(self_ty) { return None; } let mut declarations = 0usize; for facts in index.files().values() { if whole_word_offsets(&facts.source, self_ty).is_empty() { continue; } let masked = mask_comments_and_strings(&facts.source); declarations += ["struct", "enum", "union"] .iter() .map(|keyword| { whole_word_offsets(&masked, keyword) .into_iter() .filter(|offset| { starts_with_word(masked[offset + keyword.len()..].trim_start(), self_ty) }) .count() }) .sum::(); let names_other_item = ["mod", "trait", "type"].iter().any(|keyword| { whole_word_offsets(&masked, keyword) .into_iter() .any(|offset| { starts_with_word(masked[offset + keyword.len()..].trim_start(), self_ty) }) }); if names_other_item || declarations > 1 { return None; } } (declarations == 1).then(|| self_ty.to_string()) } /// #6617: whether a test body may rebind `type_name` itself: any nested /// `use`, or a `struct`/`enum`/`union`/`type`/`trait`/`mod` item of that /// name. fn body_rebinds_type(masked: &str, type_name: &str) -> bool { !whole_word_offsets(masked, "use").is_empty() || ["struct", "enum", "union", "type", "trait", "mod"] .iter() .any(|keyword| { whole_word_offsets(masked, keyword) .into_iter() .any(|offset| { starts_with_word(masked[offset + keyword.len()..].trim_start(), type_name) }) }) } /// The receiver type an `impl` block's self type names, when it is one this /// module can match a test binding against. fn declared_receiver(self_ty: &str, index: &RustIndex) -> Option { if is_byte_slice_type(self_ty) { return Some(ReceiverType::ByteSlice); } if self_ty.starts_with(['&', '[', '(', '*']) || self_ty.starts_with("dyn ") { return None; } let base = path_base_name(self_ty)?; type_declared_in_workspace(base, index).then(|| ReceiverType::Named(base.to_string())) } /// Every receiver type with an `impl .. for ` block in /// the workspace. fn trait_impl_receivers(trait_name: &str, index: &RustIndex) -> Vec { let mut receivers = Vec::new(); for facts in index.files().values() { for self_ty in trait_impl_self_types(&facts.source, trait_name) { if let Some(receiver) = declared_receiver(&self_ty, index) && !receivers.contains(&receiver) { receivers.push(receiver); } } } receivers } /// The base names of the self types `source` implements `trait_name` for: /// the names whose declarations and inherent constructors decide a default /// method's receivers (#5320). pub(in crate::analysis) fn trait_impl_self_type_names( source: &str, trait_name: &str, ) -> BTreeSet { trait_impl_self_types(source, trait_name) .iter() .filter_map(|self_ty| path_base_name(self_ty).map(str::to_string)) .collect() } /// The self types of the `impl .. for ` headers in /// `source`. fn trait_impl_self_types(source: &str, trait_name: &str) -> Vec { let mut self_types = Vec::new(); if whole_word_offsets(source, trait_name).is_empty() { return self_types; } let masked = mask_comments_and_strings(source); for offset in whole_word_offsets(&masked, "impl") { let Some(header_end) = masked[offset..].find(['{', ';']) else { continue; }; let header = collapse_whitespace(&masked[offset + "impl".len()..offset + header_end]); let header = strip_leading_generics(&header); let Some((trait_path, self_ty)) = header.split_once(" for ") else { continue; }; let self_ty = self_ty.split(" where ").next().unwrap_or(self_ty).trim(); if path_base_name(trait_path.trim()) == Some(trait_name) { self_types.push(self_ty.to_string()); } } self_types } fn strip_leading_generics(header: &str) -> &str { let header = header.trim_start(); if !header.starts_with('<') { return header; } let mut depth = 0usize; for (offset, byte) in header.bytes().enumerate() { match byte { b'<' => depth += 1, b'>' => { depth = depth.saturating_sub(1); if depth == 0 { return header[offset + 1..].trim_start(); } } _ => {} } } header } fn type_declared_in_workspace(name: &str, index: &RustIndex) -> bool { let declares = |text: &str| { ["struct", "enum", "union"].iter().any(|keyword| { whole_word_offsets(text, keyword) .into_iter() .any(|offset| starts_with_word(text[offset + keyword.len()..].trim_start(), name)) }) }; // The raw check is a superset of the masked one; mask only on a hit. index.files().values().any(|facts| { facts.source.contains(name) && declares(&facts.source) && declares(&mask_comments_and_strings(&facts.source)) }) } /// A bounded intrinsic operand must name the primitive, including through /// enclosing imports and macro output. Reuse the pin's declaration/binding /// authorities; an unresolved shadow refuses the new evidence. pub(super) fn builtin_type_unshadowed( name: &str, index: &RustIndex, syntax: &OwnerPinSyntax, ) -> bool { [name.to_string(), format!("r#{name}")] .iter() .all(|spelling| { !type_declared_in_workspace(spelling, index) && !workspace_declares_trait(index, spelling) && !syntax.macro_may_declare(spelling, index) && index.files().values().all(|facts| { !facts.used_lexical_fallback && !declaring_file_rebinds(&facts.source, spelling, false, index) }) }) } /// The type the test binds `receiver` to: every `let` that binds the name /// is a simple `let [mut] receiver [: T] = ..;` whose type ripr can read, /// and all of them agree. Other uses of the binding (borrows, arguments, /// reassignments) cannot change a Rust binding's type; another binding of /// the same name in a pattern ripr does not read (a closure parameter, a /// `for` or match-arm pattern, a destructuring `let`, a nested `fn`) /// leaves the type unestablished. fn test_receiver_type( test: &TestSummary, receiver: &str, test_source: Option<&str>, index: &RustIndex, imports_foreign: ForeignImport<'_>, owner: OwnerScope<'_>, syntax: &OwnerPinSyntax, ) -> Option { let Some(bindings) = receiver_let_bindings(test, receiver) else { let annotation = parameter_annotation(test, receiver)?; return named_or_slice( &annotation, test, test_source, index, imports_foreign, owner, ); }; if bindings.is_empty() { // No `let` binds the receiver, so it is a path expression: a unit // struct names its own value (`Unit.advance()`). return binding_type( &format!("= {receiver}"), test, test_source, index, imports_foreign, owner, syntax, ); } let mut bound: Option = None; for binding in bindings { let receiver_type = binding_type( binding, test, test_source, index, imports_foreign, owner, syntax, )?; match &bound { None => bound = Some(receiver_type), Some(existing) if *existing == receiver_type => {} Some(_) => return None, } } bound } /// #6578: the declared type of a test parameter `[mut] receiver: T` that /// nothing in the body rebinds. rstest fills an unmarked parameter from the /// same-named `#[fixture]`, and its annotation types the receiver the way /// `let receiver: T = ..;` does: whatever the fixture builds, the call /// dispatches on `T`. Whether the test runs its body at all is the owner-pin /// syntax gate's decision, not this one. `None` when the name is not such a /// parameter or a `let`, closure, `for` or match pattern binds it again. fn parameter_annotation(test: &TestSummary, receiver: &str) -> Option { let masked = mask_comments_and_strings(&test.body); let fns = whole_word_offsets(&masked, "fn"); let [fn_at] = fns.as_slice() else { return None; }; let (open, close) = fn_param_range(&masked, *fn_at)?; let mut blanked = masked.clone(); blanked.replace_range(open + 1..close, &" ".repeat(close - open - 1)); if binds_outside_let(&blanked, receiver) || let_patterns_bind(&blanked, receiver) { return None; } let parse = parse_clean_source_file(&test.body)?; let function = parse .tree() .syntax() .descendants() .find_map(ast::Fn::cast)?; let list = function.param_list()?; if list.self_param().is_some() { return None; } let mut annotation = None; for param in list.params() { let ast::Pat::IdentPat(pat) = param.pat()? else { continue; }; if pat.name()?.text() != receiver { continue; } if pat.ref_token().is_some() || pat.pat().is_some() || annotation.is_some() { return None; } annotation = Some(param.ty()?.syntax().text().to_string()); } annotation } /// The text after the name in every `let [mut] receiver [: T] = ..;` of the /// test body (the optional annotation and the initializer), or `None` when /// the name may be bound some other way ripr does not read. fn receiver_let_bindings<'a>(test: &'a TestSummary, receiver: &str) -> Option> { use crate::analysis::syntax::run_memo::{Product, memoize_with}; // A pure function of the body text and the receiver name, asked again for // every seam and every expected operand of a naming test, so the run scope // reads each pair once and the per-call work is a digest lookup (#13577). let ranges = memoize_with( Product::ReceiverLetBindings, 0, receiver, &test.body, || receiver_let_binding_ranges(&test.body, receiver), )?; ranges .into_iter() .map(|(start, end)| test.body.get(start..end)) .collect() } #[cfg(test)] thread_local! { /// Times [`receiver_let_binding_ranges`] actually scanned on this thread. static RECEIVER_LET_SCANS: Cell = const { Cell::new(0) }; } /// [`receiver_let_bindings`] as byte ranges of `body`, so the answer can be /// stored for the run without borrowing the test. fn receiver_let_binding_ranges(body: &str, receiver: &str) -> Option> { #[cfg(test)] RECEIVER_LET_SCANS.with(|n| n.set(n.get() + 1)); let masked = mask_comments_and_strings(body); if binds_outside_let(&masked, receiver) { return None; } let mut bindings = Vec::new(); for offset in whole_word_offsets(&masked, "let") { let pattern_start = offset + "let".len(); let Some(relative_end) = top_level_semicolon(&masked[pattern_start..]) else { // A `let` ripr cannot bound (an `if let` closing its block): // its pattern may still bind the name. let rest = &masked[pattern_start..]; let end = rest.find(['=', '{']).unwrap_or(rest.len()); if contains_as_whole_word(&rest[..end], receiver) { return None; } continue; }; let statement_end = pattern_start + relative_end; let statement = &masked[pattern_start..statement_end]; let pattern_end = statement .match_indices('=') .map(|(position, _)| position) .find(|position| { !matches!(statement.as_bytes().get(position + 1), Some(b'=' | b'>')) && !matches!( statement.as_bytes().get(position.wrapping_sub(1)), Some(b'=' | b'!' | b'<' | b'>') ) }) .unwrap_or(statement.len()); if !contains_as_whole_word(&statement[..pattern_end], receiver) { continue; } let pattern = statement[..pattern_end].trim(); let pattern = pattern .strip_prefix("mut ") .map_or(pattern, str::trim_start); let annotation = pattern.strip_prefix(receiver)?.trim_start(); if !(annotation.is_empty() || annotation.starts_with(':')) { return None; } // The name's whole-word offset in the pattern (`let mut m`: not // the `m` inside `mut`). let name_at = whole_word_offsets(&statement[..pattern_end], receiver) .first() .copied()?; bindings.push((pattern_start + name_at + receiver.len(), statement_end)); } Some(bindings) } /// #6974: the initializer of `operand` when it is a plain identifier the /// test binds exactly once, by an immutable `let operand [: T] = ;`, /// and uses nowhere else but as a whole operand of its own `assert_eq!` /// assertions, or one whole side of a plain lone-equality `assert!(v == e)` /// (#14085), after that `let`. Any other use (a `mut` binding, a borrow, /// a method call, an argument, a second binding, a use before the `let`) /// could change or replace the value, so it fails closed. /// /// `bare_condition`: the reviewed assertion is a bool owner's `assert!(operand)` /// / `assert!(!operand)`, whose condition is the operand itself. /// /// `scalar` (cell-0094): the owner returns a primitive scalar, so the /// binding is `Copy` with no interior mutability and nothing can change /// it. Its other uses may then also sit in any other std assertion macro /// after the `let` (`assert!(b > 3); assert_eq!(b, 12);`), and statements /// may stand between the `let` and the assertion. Every use still lies in /// an assertion, so no item, pattern or macro outside one can rebind it. fn let_bound_owner_call<'a>( test: &'a TestSummary, assertion: &OracleFact, operand: &str, projection: &str, name: &str, scalar: bool, bare_condition: bool, ) -> Option<&'a str> { let operand = operand.trim(); if !is_plain_identifier(operand) || operand == name || operand == "self" { return None; } let bindings = receiver_let_bindings(test, operand)?; let [binding] = bindings.as_slice() else { return None; }; let binding: &'a str = binding; let masked = mask_comments_and_strings(&test.body); let binding_at = binding.as_ptr() as usize - test.body.as_ptr() as usize; let let_at = *whole_word_offsets(&masked[..binding_at], "let").last()?; // #7066 review: an attribute (`#[cfg(any())] let total = ..;`) may // compile the binding away, leaving the operand naming an outer item. if contains_as_whole_word(&masked[let_at..binding_at], "mut") || masked[..let_at].trim_end().ends_with(']') { return None; } let let_line = test.start_line + masked[..let_at].matches('\n').count(); let uses = whole_word_offsets(&masked, operand).len(); let mut asserted = 0; for other in &test.assertions { if !(test.start_line..=test.end_line).contains(&other.line) { continue; } let text = mask_comments_and_strings(&other.text); let in_text = whole_word_offsets(&text, operand).len(); if in_text == 0 { continue; } let whole_operand = is_plain_macro(&other.text, "assert_eq") && assertion_comparison_operands(&other.text).is_some_and(|operands| { operands .iter() .filter(|candidate| { candidate.trim().strip_suffix(projection).map(str::trim) == Some(operand) }) .count() == 1 && compared_mentions(&operands, operand) == 1 }) || lone_equality_names_operand_once(&other.text, operand, projection); // The reviewed assertion itself is always a whole operand, and // only once: `assert_eq!(b, b)` compares the result with itself. let reviewed = other.line == assertion.line && other.text == assertion.text; // A bare `assert!(operand)` / `assert!(!operand)` reads the operand // as the whole condition, which is the `assert_eq!(operand, bool)` // operand once; a further mention can only sit in its message // arguments, which are formatted after the condition has failed. let whole_operand = whole_operand || (reviewed && bare_condition); let read_only = scalar && !reviewed && READ_ONLY_ASSERTION_MACROS .iter() .any(|macro_name| is_plain_macro(&other.text, macro_name)); if !(whole_operand || read_only) || other.line <= let_line { return None; } asserted += in_text; } // The `let` pattern is the one use outside the assertions. if uses != asserted + 1 { return None; } if scalar { // The loop above bounded the reviewed assertion to one compared // mention; a mention in its message arguments is formatted only // when the assertion already fails. return (assertion.line > let_line && same_block_after(&masked, binding_at, test.start_line, assertion)) .then(|| let_initializer(binding)) .flatten(); } // Only the assertion right after the `let` is admitted: any statement // between them could change the value through a shared handle. let after_semicolon = binding_at + binding.len() + masked[binding_at + binding.len()..].find(';')? + 1; let gap = masked[after_semicolon..].len() - masked[after_semicolon..].trim_start().len(); let next_at = after_semicolon + gap; let next_line = test.start_line + masked[..next_at].matches('\n').count(); // The next statement must be an `assert_eq!` of the binding itself, not // `assert_eqx();`, and it must be the only statement on its lines. // Assertions carry a line but no column, so a second statement sharing // the line (`assert_eq!(v, f()); touch(); assert_eq!(v, 12);`) could // otherwise pass as the next one. let rest = &masked[next_at..]; let end = rest.find(';')?; let next = &rest[..end]; let after = &rest[end + 1..]; let tail_of_line = &after[..after.find('\n').unwrap_or(after.len())]; // A lone-equality `assert!(v == e)` opens the statement in place of the // `assert_eq!`; a bool owner's bare `assert!(v)` keeps the scalar route. let opener = if !bare_condition && is_plain_macro(&assertion.text, "assert") { "assert!" } else { "assert_eq!" }; if !next.starts_with(opener) || !contains_as_whole_word(next, operand) || !tail_of_line.trim().is_empty() || assertion.line != next_line { return None; } let_initializer(binding) } /// Whether `text` is one plain `assert!(lhs == rhs)` (RIPR-SPEC-0197 /// lone-equality pins) with `operand` as exactly one whole side and named /// nowhere else in the condition. It reads `operand` as the `assert_eq!` /// with the same two sides does. fn lone_equality_names_operand_once(text: &str, operand: &str, projection: &str) -> bool { is_plain_macro(text, "assert") && equality_condition_operands(text).is_some_and(|sides| { sides .iter() .filter(|side| side.trim().strip_suffix(projection).map(str::trim) == Some(operand)) .count() == 1 && compared_mentions(&sides, operand) == 1 }) } /// Whole-word mentions of `operand` among an assertion's compared operands. /// The message arguments are left out: they are formatted only once the /// comparison has already failed, so a binding named there /// (`assert_eq!(v, 4, "got {}", v)`) is never what decides the test. fn compared_mentions>(compared: &[S], operand: &str) -> usize { compared .iter() .map(|side| whole_word_offsets(&mask_comments_and_strings(side.as_ref()), operand).len()) .sum() } /// cell-0094 review: whether the line `assertion_line` starts with a /// statement in the same block as the `let` at `let_at`, at its depth. /// Leaving the `let`'s block (`{ let b = f(); } assert_eq!(b, 12);`) or /// entering a deeper one (`{ use super::*; assert_eq!(b, 12); }`) can put /// another `b` in scope, so either refuses. fn same_block_after( masked: &str, let_at: usize, start_line: usize, assertion: &OracleFact, ) -> bool { let assertion_line = assertion.line; let Some(line_start) = masked .match_indices('\n') .nth(assertion_line.saturating_sub(start_line + 1)) .map(|(offset, _)| offset + 1) else { return false; }; if line_start <= let_at || assertion_line <= start_line { return false; } let line = &masked[line_start..]; let line = &line[..line.find('\n').unwrap_or(line.len())]; // The assertion opens its line, so nothing before it on that line // (`a(); { use super::*; assert_eq!(b, 12); }`) escapes the scan. let reviewed = mask_comments_and_strings(&assertion.text); let reviewed = reviewed.lines().next().unwrap_or_default().trim(); if reviewed.is_empty() || !line.trim_start().starts_with(reviewed) { return false; } let mut depth = 0_i64; for byte in masked[let_at..line_start].bytes() { match byte { b'{' => depth += 1, b'}' => depth -= 1, _ => {} } if depth < 0 { return false; } } depth == 0 } /// The std assertion macros that only read their operands: a scalar /// result they name cannot change or be rebound through them. const READ_ONLY_ASSERTION_MACROS: &[&str] = &["assert", "assert_eq", "assert_ne"]; /// The initializer of one `let` binding's tail (`[: T] = `). fn let_initializer(binding: &str) -> Option<&str> { let initializer = binding.trim_start(); let initializer = match initializer.strip_prefix(':') { Some(annotated) => &annotated[annotated.find('=')?..], None => initializer, }; let initializer = initializer.strip_prefix('=')?; (!initializer.starts_with(['=', '>'])).then(|| initializer.trim()) } const INTEGER_TYPES: &[&str] = &[ "i8", "i16", "i32", "i64", "i128", "isize", "u8", "u16", "u32", "u64", "u128", "usize", ]; /// trap-ceiling-wide-min-control: the call inside `operand` when the /// projection still pins it against the literal `expected` value `e`: /// `call.min(k)` with `e < k` (a result of `e` below the bound means the /// call returned `e`), `call.max(k)` with `e > k`, and `call * 1`, /// `1 * call`, `call + 0` or `0 + call`, which keep every value. Both /// numbers are plain decimal literals; anything else refuses. fn exact_integer_projection<'a>(operand: &'a str, expected: &str) -> Option<&'a str> { let decimal = |text: &str| -> Option { let text = text.trim(); // `_12` is an identifier, not a literal: the first byte is a digit. (text.as_bytes().first().is_some_and(u8::is_ascii_digit) && text.bytes().all(|b| b.is_ascii_digit() || b == b'_')) .then(|| text.replace('_', "").parse().ok()) .flatten() }; let expected = decimal(expected)?; let operand = operand.trim(); for (method, keeps) in [ ( ".min(", (|e: u128, k: u128| e < k) as fn(u128, u128) -> bool, ), (".max(", |e, k| e > k), ] { if let Some(at) = operand.rfind(method) && let Some(bound) = operand[at + method.len()..].strip_suffix(')') && let Some(bound) = decimal(bound) { return keeps(expected, bound).then_some(operand[..at].trim_end()); } } let after = |text: &'a str, operator: char, identity: char| { text.strip_suffix(identity)? .trim_end() .strip_suffix(operator) .map(str::trim_end) }; let before = |text: &'a str, operator: char, identity: char| { text.strip_prefix(identity)? .trim_start() .strip_prefix(operator) .map(str::trim_start) }; after(operand, '*', '1') .or_else(|| after(operand, '+', '0')) .or_else(|| before(operand, '*', '1')) .or_else(|| before(operand, '+', '0')) .filter(|call| !call.is_empty()) } /// `.min(k)` and `.max(k)` on an integer resolve to the prelude's `Ord` /// only while nothing rebinds that name: a local `trait Ord` (or an import /// of one, including through a foreign glob) shadows it, and /// `no_implicit_prelude` drops it. A workspace that declares its own /// `fn min`/`fn max`, names `Ord` in a `use` or a `trait` item, drops the /// prelude, or whose test file globs a foreign module refuses the /// projection rather than crediting a method it may not bind (#7932 /// review). `* 1` and `+ 0` keep std's operator impls, which coherence /// forbids redefining for a primitive. fn ord_method_rebindable(operand: &str, test: &TestSummary, index: &RustIndex) -> bool { let method = match (operand.contains(".min("), operand.contains(".max(")) { (false, false) => return false, (true, false) => "min", (false, true) => "max", (true, true) => return true, }; let Some(test_source) = index .files() .get(&test.file) .map(|facts| facts.data().source.clone()) else { return true; }; if may_saturate_macro_ambiguity(&test_source) { return true; } let ident = |byte: u8| byte.is_ascii_alphanumeric() || byte == b'_'; // `keyword` as a whole word, followed by whitespace and `then`, which // `then` matches by its whole leading word or (for `use`) its item text. let declares = |masked: &str, keyword: &str, then: &dyn Fn(&str) -> bool| { masked.match_indices(keyword).any(|(offset, _)| { let rest = &masked[offset + keyword.len()..]; let item = rest.trim_start(); masked[..offset] .bytes() .next_back() .is_none_or(|byte| !ident(byte)) && item.len() < rest.len() && then(item) }) }; let leading = |word: &'static str| { move |item: &str| { item.strip_prefix(word) .is_some_and(|tail| !tail.bytes().next().is_some_and(ident)) } }; let names_ord = |item: &str| contains_as_whole_word(item.split(';').next().unwrap_or(item), "Ord"); index.files().iter().any(|(_, facts)| { let masked = mask_comments_and_strings(&facts.data().source); masked.contains("no_implicit_prelude") || declares(&masked, "fn", &leading(method)) || declares(&masked, "trait", &leading("Ord")) || declares(&masked, "use", &names_ord) }) } /// trap-pile-first-element-control: the call inside `vec![call][0]`, a /// one-element vector indexed at zero, which is the call's own value. A /// repeat form (`vec![call; n]`), a second element or any other index /// refuses. fn single_element_index(operand: &str) -> Option<&str> { let inner = operand .trim() .strip_suffix("[0]")? .trim_end() .strip_prefix("vec![")? .strip_suffix(']')?; // A `;` in a string or comment is not the repeat separator. if mask_comments_and_strings(inner).contains(';') { return None; } match split_top_level_arguments(inner)?.as_slice() { [call] => Some(call.trim()), [call, rest] if rest.trim().is_empty() => Some(call.trim()), _ => None, } } /// The callee of `subject` when it is one bare call `name(..)` whose first /// parenthesis closes at its end: no path, receiver, projection or operator /// around it (`weight(4).wrapping_sub(weight(4))`, `other::weight(4)`), so /// the compared value is the call's own return (#7974 review). pub(in crate::analysis) fn direct_call_name(subject: &str) -> Option<&str> { let subject = subject.trim(); let open = subject.find('(')?; let name = subject[..open].trim_end(); let mut chars = name.chars(); if !chars .next() .is_some_and(|first| first.is_ascii_alphabetic() || first == '_') || !chars.all(|c| c.is_ascii_alphanumeric() || c == '_') { return None; } let mut depth = 0usize; for (at, byte) in subject.bytes().enumerate().skip(open) { match byte { b'(' | b'[' | b'{' => depth += 1, b')' | b']' | b'}' => { depth = depth.checked_sub(1)?; if depth == 0 { return (at + 1 == subject.len()).then_some(name); } } _ => {} } } None } /// trap-tally-reached-assert-control: the compared call when `assertion` is /// `assert_eq!(subject, e)` (either order, `e` an integer literal) and /// `condition` is `subject k` or `k subject` (one comparison, /// `k` an integer literal) that does not hold at `e`, so an /// `if condition { return; }` before it spares the expected value. `None` /// when the guard fires at `e` (left to the guarded-return refusal) or /// either shape is anything else. fn value_guard_subject<'a>(condition: &str, assertion: &'a str) -> Option<&'a str> { let integer = |text: &str| -> Option { let text = text.trim(); let digits = text.strip_prefix('-').unwrap_or(text); (digits.as_bytes().first().is_some_and(u8::is_ascii_digit) && digits.bytes().all(|b| b.is_ascii_digit() || b == b'_')) .then(|| text.replace('_', "").parse().ok()) .flatten() }; let compact = |text: &str| text.split_whitespace().collect::(); if !is_plain_macro(assertion, "assert_eq") { return None; } let operands = assertion_comparison_operands(assertion)?; let (subject, expected) = match (integer(operands[0]), integer(operands[1])) { (None, Some(expected)) => (operands[0].trim(), expected), (Some(expected), None) => (operands[1].trim(), expected), _ => return None, }; // `compact` drops whitespace inside a string or char literal too, so a // call with one stays out (#7974 review). if direct_call_name(subject).is_none() || subject.contains(['"', '\'']) || ["&&", "||", "::<", "->"] .iter() .any(|op| condition.contains(op)) { return None; } // The one comparison operator outside brackets. let bytes = condition.as_bytes(); let mut depth = 0usize; let mut found = None; let mut at = 0; while at < bytes.len() { match bytes[at] { b'(' | b'[' | b'{' => depth += 1, b')' | b']' | b'}' => depth = depth.checked_sub(1)?, b'<' | b'>' | b'=' | b'!' if depth == 0 => { let width = if bytes.get(at + 1) == Some(&b'=') { 2 } else { 1 }; let operator = &condition[at..at + width]; if !matches!(operator, "<" | ">" | "<=" | ">=" | "==" | "!=") || found.is_some() { return None; } found = Some((at, operator)); at += width; continue; } _ => {} } at += 1; } let (at, operator) = found?; let (left, right) = (&condition[..at], &condition[at + operator.len()..]); // Read the guard as `subject k`; `k < subject` is `subject > k`. let (operator, bound) = if compact(left) == compact(subject) { (operator, integer(right)?) } else if compact(right) == compact(subject) { let flipped = match operator { "<" => ">", ">" => "<", "<=" => ">=", ">=" => "<=", same => same, }; (flipped, integer(left)?) } else { return None; }; // The guard must spare a wrong value, or the assertion runs only when // it passes and the test is a certain gap (#7932 tally review): `!=` // returns for every wrong value. ripr does not know the integer type, // so `e - 1` counts only where every type holding `e` holds it too // (`e >= 1`, or a negative `e` above every signed minimum), and // `e + 1` only where `e` is no type's maximum; a neighbour on the // threshold's side is a value of the guard's own type. let maxima: [i128; 9] = [ i8::MAX.into(), u8::MAX.into(), i16::MAX.into(), u16::MAX.into(), i32::MAX.into(), u32::MAX.into(), i64::MAX.into(), u64::MAX.into(), i128::MAX, ]; let minima: [i128; 5] = [ i8::MIN.into(), i16::MIN.into(), i32::MIN.into(), i64::MIN.into(), i128::MIN, ]; let below = expected >= 1 || (expected < 0 && !minima.contains(&expected)); let above = !maxima.contains(&expected); let spares_wrong = match operator { // Fires only at `k`: every other wrong value runs the assertion. "==" => bound != expected, // Spares `v <= k`, or `v <= k - 1` for `>=`. ">" => expected < bound || (expected == bound && below), ">=" => expected < bound && (expected.checked_add(1)? < bound || below), // Spares `v >= k`, or `v >= k + 1` for `<=`. "<" => expected > bound || (expected == bound && above), "<=" => expected > bound && (expected.checked_sub(1)? > bound || above), _ => false, }; spares_wrong.then_some(subject) } /// cell-0094: whether `owner` declares a primitive scalar return type that /// its own file does not shadow with a same-named item or import. /// Residuals: a non-std glob import, a generic parameter or a /// macro-generated item that names a type like the primitive. fn returns_primitive_scalar(owner: &FunctionSummary, index: &RustIndex) -> bool { const SCALARS: &[&str] = &[ "bool", "char", "f32", "f64", "i8", "i16", "i32", "i64", "i128", "isize", "u8", "u16", "u32", "u64", "u128", "usize", ]; let Some(returned) = declared_return_type(&owner.body) else { return false; }; if !SCALARS.contains(&returned.as_str()) { return false; } index .files() .get(&owner.file) .is_some_and(|facts| !source_binds_type_name(&facts.source, &returned)) } /// Whether `source` declares a type named `name` (`type u32 = u8;`, /// `struct u32`) or imports one under that name (`use a::Gauge as u32;`, /// `use a::{u32};`). fn source_binds_type_name(source: &str, name: &str) -> bool { let masked = mask_comments_and_strings(source); let declared = whole_word_offsets(&masked, name).into_iter().any(|offset| { // #7835 review: `type r#u32` declares the same name. let before = masked[..offset] .strip_suffix("r#") .unwrap_or(&masked[..offset]); let before = before.trim_end(); ["struct", "enum", "union", "type", "trait"] .iter() .any(|keyword| before.ends_with(keyword)) }); let imported = whole_word_offsets(&masked, "use") .into_iter() .any(|offset| { let rest = &masked[offset..]; let end = rest.find(';').unwrap_or(rest.len()); contains_as_whole_word(&rest[..end], name) }); declared || imported } /// #14387 (#14786 review): the closed subset checks arithmetic in the /// built-in range of each integer type it reads by spelling, so a guard-return /// credit needs the owner's file to leave every integer type name unbound /// (`type u32 = u8;` would narrow it) and to glob-import nothing beyond its /// parent module (`use crate::narrow::*;` could bind one). fn owner_file_keeps_integer_names(owner: &FunctionSummary, index: &RustIndex) -> bool { index.files().get(&owner.file).is_some_and(|facts| { let masked = mask_comments_and_strings(&facts.source); let foreign_glob = whole_word_offsets(&masked, "use") .into_iter() .any(|offset| { let rest = &masked[offset..]; let end = rest.find(';').unwrap_or(rest.len()); let item: String = rest[..end].split_whitespace().collect(); item.contains('*') && item != "usesuper::*" }); !foreign_glob && !INTEGER_TYPES .iter() .any(|name| source_binds_type_name(&facts.source, name)) }) } /// Whether the expected operand of `assertion` in `test` reaches the owner /// `name`: it names the owner, or names a test binding whose initializer /// does (`assert_eq!(f(4), f(2) + f(2))`, `let e = f(4); assert_eq!(f(4), /// e)`), so the assertion compares the owner with itself. Shared by the /// owner-return pin and RIPR-SPEC-0265 element pairing. pub(in crate::analysis::classify) fn expected_reaches_owner( test: &TestSummary, assertion: &str, expected: &str, name: &str, ) -> bool { contains_as_whole_word(&mask_comments_and_strings(expected), name) || (owner_named_outside(test, assertion, name) && expected_binding_calls_owner(test, expected, name)) } /// RIPR-SPEC-0035, reveal side: the value the expected `operand` stands /// for when it is a plain identifier the test binds once with a readable /// `let`, or that names exactly one in-scope workspace constant, followed /// through further such names (`let e = tax(2); let f = e;`). The reveal /// side reads that value in place of the operand, so a name weakens an /// assertion only where writing its initializer inline would. `None` when /// the operand is no such name; a name the scan cannot read keeps credit. pub(in crate::analysis) fn expected_operand_value( index: &RustIndex, test: &TestSummary, operand: &str, owner: &FunctionSummary, ) -> Option { let in_scope = constant_scope(index, test, &owner.file); let mut seen = BTreeSet::new(); let mut current = mask_comments_and_strings(operand).trim().to_string(); let mut value = None; while is_plain_identifier(¤t) && current != owner.name && seen.insert(current.clone()) { let next = match receiver_let_bindings(test, ¤t) { Some(bindings) => match bindings.as_slice() { [binding] => immutable_let_value(index, test, binding), [] => single_constant_value(index, ¤t, &in_scope), _ => None, }, None => None, }; let Some(next) = next else { break; }; current = next.trim().to_string(); value = Some(current.clone()); } value } /// The value of the test's one `let` binding `binding` (its text after the /// name), unless the `let` is `mut`, so a later assignment or `push` may /// change it, or carries an attribute (`#[cfg(..)] let`) that may compile /// it away (#7066 review), as [`let_bound_owner_call`] refuses. fn immutable_let_value(index: &RustIndex, test: &TestSummary, binding: &str) -> Option { let masked = mask_comments_and_strings(&test.body); let binding_at = (binding.as_ptr() as usize).checked_sub(test.body.as_ptr() as usize)?; let let_at = *whole_word_offsets(masked.get(..binding_at)?, "let").last()?; if contains_as_whole_word(masked.get(let_at..binding_at)?, "mut") || masked.get(..let_at)?.trim_end().ends_with(']') { return None; } let binding = mask_comments_and_strings(binding); let value = assigned_value(&binding)?; // #8112: an immutable binding of an interior-mutable value // (`let e = Cell::new(f(2)); e.set(6);`) can change after its initializer. let source = index .files() .get(&test.file) .map(|facts| facts.source.to_string()); if may_mutate_through_shared(declared_type(&binding), value, source.as_deref()) { return None; } Some(value.to_string()) } /// #8112: whether an initializer names a type that allows mutation through /// a shared binding, so the value the binding holds at the assertion may /// differ from its initializer. fn has_interior_mutability(initializer: &str) -> bool { [ "Cell", "RefCell", "UnsafeCell", "OnceCell", "OnceLock", "LazyCell", "LazyLock", "Mutex", "RwLock", "AtomicBool", "AtomicI8", "AtomicI16", "AtomicI32", "AtomicI64", "AtomicIsize", "AtomicU8", "AtomicU16", "AtomicU32", "AtomicU64", "AtomicUsize", "AtomicPtr", ] .iter() .any(|word| contains_as_whole_word(initializer, word)) } /// #8112: whether a binding or `static` whose declared type is `declared` /// (`None` when unannotated or unreadable) and whose initializer is /// `initializer` can change through a shared reference. The declared type /// decides when it names a known interior-mutable type (refuse) or is a /// plain scalar (`u32`, `&'static str`, `[u8; 4]`; keep, whatever the /// initializer block mentions). Any other type (a user type, an alias, an /// unannotated binding) falls back to the initializer text. Limit: a user /// type that merely holds an atomic (`Counter`) is not recognized from its /// name; only a known interior-mutable type name in the type or the /// initializer text refuses it. fn may_mutate_through_shared( declared: Option<&str>, initializer: &str, source: Option<&str>, ) -> bool { match declared { Some(declared) if has_interior_mutability(declared) => true, Some(declared) if is_plain_scalar_type(declared) && source.is_some_and(|source| !scalar_names_rebound(declared, source)) => { false } _ => has_interior_mutability(initializer), } } /// Whether every word of the type text is a primitive scalar, `str`, /// `'static` or an array length digit run: `u32`, `&'static str`, `[u8; 4]`. fn is_plain_scalar_type(declared: &str) -> bool { const SCALARS: [&str; 17] = [ "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize", "f32", "f64", "bool", "char", "str", ]; let mut words = declared .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) .filter(|word| !word.is_empty()) .peekable(); words.peek().is_some() && words.all(|word| { SCALARS.contains(&word) || word == "static" || word.chars().all(|c| c.is_ascii_digit()) }) } /// Whether the file may rebind a primitive name `declared` uses, so the /// name no longer proves a scalar: an item keyword before it (`type u32 = /// ..;`, `struct u32;`), or any mention of it inside a `use` or `extern /// crate` statement (`use x::u32;`, `use m::{Counter, u32};`, `use x as /// u32;`) unless it continues a path (`use std::u32::MAX;`) or is a /// generic argument. A glob import (`use m::*;`) may bring any name in, so /// it rebinds every name. A plain cast `n as u32` or `std::u32::MAX` does /// not. Limits: `include!`, `#[path]` and macro-generated types are not /// scanned. fn scalar_names_rebound(declared: &str, source: &str) -> bool { let masked = mask_comments_and_strings(source); let is_word = |c: char| c.is_ascii_alphanumeric() || c == '_'; let imports = |statement: &str| { !whole_word_offsets(statement, "use").is_empty() || !whole_word_offsets(statement, "extern").is_empty() }; if whole_word_offsets(&masked, "use") .into_iter() .any(|offset| { masked[offset..] .split(';') .next() .is_some_and(|statement| statement.contains('*')) }) { return true; } declared .split(|c: char| !is_word(c)) .filter(|word| !word.is_empty() && !word.chars().all(|c| c.is_ascii_digit())) .any(|word| { whole_word_offsets(&masked, word).into_iter().any(|offset| { let before = masked[..offset].trim_end(); let after = masked[offset + word.len()..].trim_start(); let statement = before.rsplit(';').next().unwrap_or(before); if imports(statement) { return !after.starts_with("::") && !before.ends_with('<'); } if before.ends_with("::") { return !after.starts_with("::"); } ["type", "struct", "enum", "trait", "union", "mod"] .iter() .any(|keyword| { before.ends_with(keyword) && before[..before.len() - keyword.len()] .chars() .next_back() .is_none_or(|c| !is_word(c)) }) }) }) } /// The `T` of `[: T] = value` text, when annotated. fn declared_type(text: &str) -> Option<&str> { let trimmed = text.trim_start(); let after = trimmed .strip_prefix(':') .filter(|after| !after.starts_with(':'))?; let end = assigned_value_offset(after)?; let declared = after.get(..end.saturating_sub(1))?; // A type holding `=` or a block (`Foo<{ A == B }>`, `[u8; { N }]`) makes // the split ambiguous: treat the declared type as unknown. (!declared.contains(['=', '{'])).then_some(declared) } /// #8112: whether `file` declares `static mut name`, whose value the test /// may have assigned before the assertion reads it. fn declares_static_mut(index: &RustIndex, file: &Path, name: &str) -> bool { declares_static_with(index, file, name, true) } /// #8112: whether `file` declares `static name`, `mut` or not, or the /// `lazy_static!` form `static ref name`. fn declares_static(index: &RustIndex, file: &Path, name: &str) -> bool { declares_static_with(index, file, name, false) } fn declares_static_with(index: &RustIndex, file: &Path, name: &str, require_mut: bool) -> bool { let Some(facts) = index.files().get(file) else { return false; }; let masked = mask_comments_and_strings(&facts.source); whole_word_offsets(&masked, "static") .into_iter() .any(|offset| { let mut rest = masked[offset + "static".len()..].trim_start(); if let Some(after) = rest .strip_prefix("mut") .filter(|after| after.starts_with(char::is_whitespace)) { rest = after.trim_start(); } else if require_mut { return false; } else if let Some(after) = rest .strip_prefix("ref") .filter(|after| after.starts_with(char::is_whitespace)) { // `lazy_static!` writes `static ref NAME: T = init;`. rest = after.trim_start(); } rest.strip_prefix(name).is_some_and(|tail| { !tail.starts_with(|c: char| c.is_ascii_alphanumeric() || c == '_') }) }) } /// The initializer of the one in-scope workspace constant named `name`. /// An item read from text (`: T = init`) yields the text after its `=`. fn single_constant_value( index: &RustIndex, name: &str, in_scope: &dyn Fn(&Path) -> bool, ) -> Option { let constants = index .call_identity_memos .workspace_constants(|| workspace_constant_table(index)); let mut matches = constants .get(name)? .iter() .filter(|(file, _, _)| in_scope(file)); let (file, initializer, declared) = matches.next()?; if matches.next().is_some() || declares_static_mut(index, file, name) { return None; } // #8112: a non-`mut` `static` of interior-mutable declared type // (`static C: AtomicUsize = ..; C.store(6)`) can change after its // initializer. A `const` is rebuilt at each use, so it stays readable. if declares_static(index, file, name) && may_mutate_through_shared( declared.as_deref(), initializer, index .files() .get(file) .map(|facts| facts.source.to_string()) .as_deref(), ) { return None; } let initializer_text = initializer.trim_start(); if initializer_text.starts_with(':') && !initializer_text.starts_with("::") { assigned_value(initializer).map(str::to_string) } else { Some(initializer.clone()) } } /// The text after the assignment `=` of `[: T] = value`: the first `=` /// outside angle brackets that is not part of `==`, `=>`, `<=`, `>=` or `!=`. fn assigned_value(text: &str) -> Option<&str> { text.get(assigned_value_offset(text)?..) } /// The offset just after the assignment `=` that [`assigned_value`] finds. fn assigned_value_offset(text: &str) -> Option { let bytes = text.as_bytes(); let mut depth = 0usize; for (position, byte) in bytes.iter().enumerate() { match byte { b'<' => depth += 1, b'>' if bytes.get(position.wrapping_sub(1)) != Some(&b'-') => { depth = depth.saturating_sub(1); } b'=' if depth == 0 && !matches!(bytes.get(position + 1), Some(b'=' | b'>')) && !matches!( bytes.get(position.wrapping_sub(1)), Some(b'=' | b'!' | b'<' | b'>') ) => { return Some(position + 1); } _ => {} } } None } /// A constant from a package the test neither belongs to, tests, nor names /// (`test_kit::EXPECTED` from `crates/test-kit/`) cannot be the one the /// test reads; unscopable paths keep every match. fn constant_scope( index: &RustIndex, test: &TestSummary, owner_file: &Path, ) -> impl Fn(&Path) -> bool { let test_package = super::related_tests::package_prefix(&test.file); let owner_package = super::related_tests::package_prefix(owner_file); let test_source = index .files() .get(&test.file) .map(|facts| facts.source.clone()); move |file: &Path| match (&test_package, &owner_package) { (Some(test_package), Some(owner_package)) => super::related_tests::package_prefix(file) .is_none_or(|package| { &package == test_package || &package == owner_package || package .trim_end_matches('/') .rsplit('/') .next() .is_some_and(|crate_dir| { test_source.as_deref().is_none_or(|source| { contains_as_whole_word(source, &crate_dir.replace('-', "_")) }) }) }), _ => true, } } /// RIPR-SPEC-0035: whether an identifier in the expected operand names a /// `const` or `static` whose initializer calls the owner, directly or /// through further constants (`const EXPECTED: u32 = quota(2); /// assert_eq!(quota(2), EXPECTED)` compares the owner with itself, as a /// `let` binding would). Constants come from one memoized workspace table /// keyed by name; any same-named item in the test's or the owner's package /// counts: matching too many only withholds the pin. The call must have the pin's own shape (a bare or /// module-path call for a free function, `T::name(..)` for an associated /// one, `.name(..)` or `T::name(..)` for a method), so a constant built /// with some other type's `new` or `len` keeps the pin. A test-file `use .. /// as` rename of a constant and a constant file's rename of the owner are /// followed. A constant computed through a test-file helper that calls the /// owner is refused by the caller (#7714). fn expected_constant_reaches_owner( index: &RustIndex, test: &TestSummary, expected: &str, name: &str, call: &PinCall, owner_file: &Path, ) -> bool { let constants = index .call_identity_memos .workspace_constants(|| workspace_constant_table(index)); if constants.is_empty() { return false; } let in_scope = constant_scope(index, test, owner_file); // `use .. as` renames of the file a text was read from: the test file // for the expected operand, the constant's own file for an initializer. let renames = |file: &Path| -> Vec { index .files() .get(file) .filter(|facts| facts.source.contains(" as ")) .map(|facts| flattened_use_paths(&facts.source)) .unwrap_or_default() }; let mut seen = BTreeSet::new(); let mut pending = vec![(mask_comments_and_strings(expected), test.file.clone())]; while let Some((text, file)) = pending.pop() { let mut words: Vec = text .split(|character: char| !(character.is_ascii_alphanumeric() || character == '_')) .filter(|word| is_plain_identifier(word) && *word != name) .map(str::to_string) .collect(); let renamed: Vec = renames(&file) .into_iter() .filter(|import| { import .alias .as_deref() .is_some_and(|alias| words.iter().any(|word| word == alias)) }) .filter_map(|import| import.path.rsplit("::").next().map(str::to_string)) .collect(); words.extend(renamed); for word in words { if !seen.insert(word.clone()) { continue; } let Some(initializers) = constants.get(&word) else { continue; }; for (file, initializer, _) in initializers.iter().filter(|(file, _, _)| in_scope(file)) { if initializer_calls_owner(initializer, name, call) || owner_aliases(index, file, name) .iter() .any(|alias| initializer_calls_owner(initializer, alias, call)) { return true; } pending.push((initializer.clone(), file.clone())); } } } false } /// #7714: names of the functions in the test's own file, other than the /// test, whose body names the owner `name` or, transitively, another such /// function. An expected value such a helper returns is computed from the /// owner, so comparing the owner with it compares the owner with itself. /// Matching a same-named item in another module only withholds the pin. fn test_file_helpers_reaching_owner( index: &RustIndex, test: &TestSummary, expected: &str, name: &str, ) -> Vec { // A literal or an operand with no name in it cannot reach a helper. let masked_expected = mask_comments_and_strings(expected); if !masked_expected .split(|character: char| !(character.is_ascii_alphanumeric() || character == '_')) .any(|word| is_plain_identifier(word) && word != name) { return Vec::new(); } let Some(facts) = index.files().get(&test.file) else { return Vec::new(); }; // Free non-test functions only: a method or a sibling test sharing a // common name (`new`, `len`) would otherwise withhold unrelated pins. let candidates: Vec<(&str, String)> = facts .functions .iter() .filter(|function| { function.start_line != test.start_line && function.name != name && matches!( function.impl_context, crate::analysis::facts::FunctionImplContext::Free ) && !function .attrs .iter() .any(|attr| attr.contains("test") || attr.contains("rstest")) }) .map(|function| (function.name.as_str(), function.body.as_str())) .map(|(helper, body)| (helper, mask_comments_and_strings(body))) .collect(); let mut reaching: BTreeSet = BTreeSet::new(); let mut frontier = vec![name.to_string()]; while let Some(target) = frontier.pop() { for (helper, body) in &candidates { if !reaching.contains(*helper) && contains_as_whole_word(body, &target) { reaching.insert((*helper).to_string()); frontier.push((*helper).to_string()); } } } reaching.into_iter().collect() } /// Names `file` imports the owner `name` under (`use crate::quota as q;`). fn owner_aliases(index: &RustIndex, file: &Path, name: &str) -> Vec { index .files() .get(file) .map(|facts| { flattened_use_paths(&facts.source) .into_iter() .filter(|import| import.path.rsplit("::").next() == Some(name)) .filter_map(|import| import.alias) .collect() }) .unwrap_or_default() } /// Whether the masked `initializer` calls `name` in the pin's call shape. /// A free function also counts when named as a value (`apply(quota, 2)`, /// `let f = quota;`), and a `<..>::name` qualifier the scan cannot read /// counts for every shape. fn initializer_calls_owner(initializer: &str, name: &str, call: &PinCall) -> bool { whole_word_offsets(initializer, name).into_iter().any(|offset| { let after = initializer[offset + name.len()..].trim_start(); let called = after.starts_with('(') || after.starts_with("::<"); // A struct-literal field (`Limits { quota: 2 }`) is not the owner. if after.starts_with(':') && !after.starts_with("::") { return false; } let before = initializer[..offset].trim_end(); let qualifier = before.strip_suffix("::").map(|path| { let path = path.trim_end(); let start = path .char_indices() .rev() .find(|(_, character)| !(character.is_alphanumeric() || *character == '_')) .map_or(0, |(index, character)| index + character.len_utf8()); &path[start..] }); if qualifier == Some("") { return true; } let type_like = |segment: &str| segment.starts_with(char::is_uppercase); match call { PinCall::Bare => !before.ends_with('.') && !qualifier.is_some_and(type_like), PinCall::Associated { type_name } => { called && qualifier.is_some_and(|segment| segment == type_name || segment == "Self") } PinCall::Method { receivers, .. } => { called && (before.ends_with('.') || qualifier.is_some_and(|segment| { segment == "Self" || receivers.iter().any(|receiver| { matches!(receiver, ReceiverType::Named(type_name) if type_name == segment) }) })) } } }) } /// Every `const` and `static` of the workspace, by name, with its file and /// masked initializer: one parse per file per index. Items a macro call /// declares (`thread_local!`, `lazy_static!`) and items of a file that does /// not parse cleanly are read from their text. /// /// The per-file parses are independent, so they go through [`map_scans`]: /// off the pool (the single-seam review stage of a cold `ripr check`) they /// fan out instead of parsing the whole corpus on one thread, and on a pool /// worker they stay in line under the #8756 memo-lock guard. Results are /// folded in index file order, so the table is the same either way. fn workspace_constant_table(index: &RustIndex) -> ConstantTable { let files: Vec> = index .files() .iter() .map(|(path, facts)| { let data = facts.data(); (path, data.source.as_ref(), data.constant_syntax.as_deref()) }) .collect(); let per_file = map_scans(&files, |(_, source, stored)| { stored .and_then(|stored| stored_file_constants(source, stored)) .unwrap_or_else(|| file_constants(source)) }); let mut table = ConstantTable::new(); for ((path, _, _), constants) in files.iter().zip(per_file) { for (name, initializer, declared) in constants { table .entry(name) .or_default() .push(((*path).clone(), initializer, declared)); } } table } /// A file of [`workspace_constant_table`]: its path, source text and the /// producer's stored constant syntax, when it has one. type ConstantScanFile<'a> = (&'a PathBuf, &'a str, Option<&'a [ConstantSyntax]>); /// One file's constants: `(name, masked initializer, declared type)`. type FileConstants = Vec<(String, String, Option)>; /// [`file_constants`] read from the producer's stored [`ConstantSyntax`] /// instead of a fresh parse (#13754). The stored ranges come from the same /// clean parse [`file_constants`] would make, in the same tree order, so the /// result is the same. `None` when a stored range does not lie on character /// boundaries of `source`; the caller then parses. fn stored_file_constants(source: &str, stored: &[ConstantSyntax]) -> Option { let mut found = Vec::new(); for entry in stored { match entry { ConstantSyntax::Item { name, body, ty } => { let name = span_text(source, *name)?; let body = span_text(source, *body)?; let ty = match ty { Some(ty) => Some(span_text(source, *ty)?), None => None, }; let name = name.strip_prefix("r#").unwrap_or(name); found.push(( name.to_string(), mask_comments_and_strings(body), ty.map(mask_comments_and_strings), )); } ConstantSyntax::MacroTokens(tokens) => { let text = mask_comments_and_strings(span_text(source, *tokens)?); for (name, initializer) in text_declared_constants(&text) { let declared = declared_type(&initializer).map(str::to_string); let name = name.strip_prefix("r#").unwrap_or(&name).to_string(); found.push((name, initializer, declared)); } } } } Some(found) } /// One file's `const`/`static` items for [`workspace_constant_table`], in /// source order: `(name, masked initializer, declared type)`. fn file_constants(source: &str) -> FileConstants { let mut found = Vec::new(); if !source.contains("const") && !source.contains("static") { return found; } let mut add = |name: &str, initializer: String, declared: Option| { let name = name.strip_prefix("r#").unwrap_or(name); found.push((name.to_string(), initializer, declared)); }; let Some(parsed) = parse_clean_source_file(source) else { for (name, initializer) in text_declared_constants(&mask_comments_and_strings(source)) { let declared = declared_type(&initializer).map(str::to_string); add(&name, initializer, declared); } return found; }; for node in parsed.tree().syntax().descendants() { let item = if let Some(item) = ast::Const::cast(node.clone()) { item.name() .zip(item.body()) .map(|(name, body)| (name, body, item.ty())) } else if let Some(item) = ast::Static::cast(node.clone()) { item.name() .zip(item.body()) .map(|(name, body)| (name, body, item.ty())) } else { if let Some(macro_call) = ast::MacroCall::cast(node) && let Some(tokens) = macro_call.token_tree() { let text = mask_comments_and_strings(&tokens.syntax().to_string()); for (name, initializer) in text_declared_constants(&text) { let declared = declared_type(&initializer).map(str::to_string); add(&name, initializer, declared); } } None }; if let Some((item_name, body, ty)) = item { add( item_name.text(), mask_comments_and_strings(&body.syntax().to_string()), ty.map(|ty| mask_comments_and_strings(&ty.syntax().to_string())), ); } } found } /// `const NAME: T = init;` and `static [ref] [mut] NAME: T = init;` read /// from masked text as their `: T = init` text, for macro bodies and unparsed files. The type /// annotation is required, so `const fn`, `*const u8` and `&'static str` /// are not declarations. fn text_declared_constants(text: &str) -> Vec<(String, String)> { let mut found = Vec::new(); for keyword in ["const", "static"] { for offset in whole_word_offsets(text, keyword) { let mut rest = text[offset + keyword.len()..].trim_start(); for modifier in ["ref", "mut"] { if let Some(stripped) = rest.strip_prefix(modifier) && stripped.starts_with(char::is_whitespace) { rest = stripped.trim_start(); } } let raw = rest.strip_prefix("r#"); let body = raw.unwrap_or(rest); let length = body .find(|character: char| !(character.is_ascii_alphanumeric() || character == '_')) .unwrap_or(body.len()); let name = &body[..length]; if !is_plain_identifier(name) || !body[length..].trim_start().starts_with(':') { continue; } // The item runs to its first `;` outside brackets, so an array // type (`[u32; 4]`) or a block initializer stays whole. One with // no `=` there (`extern { static X: u32; }`) has no initializer. // The type stays in the text: an `=` inside it (`Item = u32`) // cannot hide the initializer, and its words only withhold. let declaration = &body[length..]; let end = top_level_semicolon(declaration).unwrap_or(declaration.len()); let item = &declaration[..end]; if !item.contains('=') { continue; } found.push((name.to_string(), item.to_string())); } } found } /// Whether a `static`, `const` or `use` item in the body names `word` /// (#8929): an inner-block `static EXPECTED: AtomicU32 = ..` redeclares the /// name after a plain top-level `let`, so the later `&EXPECTED` borrows the /// static, which a callee may write. The item's header up to its `=` or `;` /// is scanned for the word. fn item_names_word(masked: &str, word: &str) -> bool { ["static", "const", "use"].iter().any(|keyword| { whole_word_offsets(masked, keyword).into_iter().any(|at| { let rest = &masked[at + keyword.len()..]; let end = rest.find([';', '=']).unwrap_or(rest.len()); let header = &rest[..end]; if *keyword == "use" { return use_header_binds_word(header, word); } contains_as_whole_word(header, word) }) }) } /// Whether a `use` header names `word` other than as the source of a rename /// (`use m::word as other` imports `other`, not `word`). Every other mention /// (a bare import, a path segment, a group member, `word as word`) counts, so /// the check stays conservative (#8944). fn use_header_binds_word(header: &str, word: &str) -> bool { whole_word_offsets(header, word).into_iter().any(|at| { let tail = header[at + word.len()..].trim_start(); let renamed = tail .strip_prefix("as") .filter(|after| after.starts_with(char::is_whitespace)) .map(|after| { // `as r#name` imports `name`: look past the raw marker. let target = after.trim_start(); let target = target.strip_prefix("r#").unwrap_or(target); let end = target .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) .unwrap_or(target.len()); &target[..end] }); renamed.is_none_or(|target| target.is_empty() || target == word) }) } /// #6974 review: whether the test body names the owner anywhere but the /// assertion under review. When it does not, no binding in the test can /// hold an owner call, so table-driven expected values (`#[case] want`, /// `for (x, want) in cases`) need no binding scan. fn owner_named_outside(test: &TestSummary, assertion: &str, name: &str) -> bool { let in_body = whole_word_offsets(&mask_comments_and_strings(&test.body), name).len(); let in_assertion = whole_word_offsets(&mask_comments_and_strings(assertion), name).len(); in_body > in_assertion } /// #6974 review: whether an identifier in the expected operand is a test /// `let` whose initializer mentions the owner, directly or through further /// `let`s (`let s = f(2) * 1; assert_eq!(f(2), s);` and /// `let a = f(2); let b = a; assert_eq!(f(2), b);` compare the owner with /// itself). fn expected_binding_calls_owner(test: &TestSummary, expected: &str, name: &str) -> bool { let masked_body = mask_comments_and_strings(&test.body); let mut seen = BTreeSet::new(); let mut pending = vec![mask_comments_and_strings(expected)]; while let Some(text) = pending.pop() { for word in text .split(|character: char| !(character.is_ascii_alphanumeric() || character == '_')) .filter(|word| is_plain_identifier(word) && *word != name) { if !seen.insert(word.to_string()) { continue; } // A binding the scan cannot read (a pattern, a shadowed // name) may hold an owner call: fail closed (#6974 review). // A word the scan refuses only because a `let` annotation // names it (`let w: Window = ..`) is a type, not a binding. // A statement macro may bind the word (`s!(expected);`), and the // test may write through it (`EXPECTED.store(f(4))`): neither // is a `let` the scan reads, so the owner may feed the operand // (#7847). let bindings = receiver_let_bindings(test, word); // A later `let` may shadow an earlier static or item of the same // name, so a plain `let` counts only when it is the name's first // use, at the test body's top level (#8795). let plain = bindings.as_deref().is_some_and(plain_let_values) && first_use_is_top_level_let(&masked_body, word) && !item_names_word(&masked_body, word); let read_only = plain && never_declared_mut(&masked_body, word) && !named_as_segment_or_call(&masked_body, word); if bound_by_macro(&masked_body, word) || written_by_test(&masked_body, word, plain, read_only) { return true; } let Some(bindings) = bindings else { if binds_outside_let(&masked_body, word) || let_patterns_bind(&masked_body, word) { return true; } continue; }; for binding in bindings { let initializer = mask_comments_and_strings(binding); if contains_as_whole_word(&initializer, name) { return true; } pending.push(initializer); } } } false } /// #7847: whether the masked test body writes through `name` outside a /// `let`: an assignment to the name or a place under it (`name = ..`, /// `name.field = ..`, `name.0 = ..`, `name[i] += ..`), a `&mut name` borrow, /// or a mutating call on it or a place under it (`name.store(..)`, /// `name.sort()`, `name.0.push(..)`, any `*_mut`, `*_assign`, `fetch_*` or /// `set_*` method). Lexical and conservative, so a static the test stores /// the owner's value in is no independent expected value. /// /// `plain` (#8795): every binding of `name` is a `let` of a plain value /// (`plain_let_values`), which holds no interior mutability and no callee can /// write through a shared borrow of it, so `&name` passed to a call is a /// read. Method names stay mutators regardless (a test-local type may define /// any `replace`/`take`). A static, a const or any other binding, and any /// constructor call (it may be test-local), is never plain. /// /// `read_only` (#8795 Part B, implies `plain`): additionally no `mut` precedes /// the name anywhere, so the one binding is an immutable `let` of a literal /// value. Such a value has no interior mutability, so no method call on it, /// whatever it is called or whichever test-local trait defines it, can write /// the binding: `expected.replace(..)`, `.take(n)` and `.lock()` read it. /// Assignments (`name = ..`, `name.0 += ..`) and every other write shape /// stay refusals. fn written_by_test(masked: &str, name: &str, plain: bool, read_only: bool) -> bool { whole_word_offsets(masked, name).into_iter().any(|offset| { // A raw identifier (`r#NAME`) is the same name: look past its `r#`. let before = strip_raw_ident_prefix(masked[..offset].trim_end()); // `let e: Config = ..`, `let e: crate::Config`, `let e: &Config` and // `let e: (Config, u8)` annotate a type: the `=` after it assigns the // binding, not the type name. Only a `let` pattern's annotation // qualifies; a struct-literal field value (`S { f: EXPECTED.swap(..) }`) // is an expression and stays scanned (#8795). if in_let_annotation(before) { return false; } // A mutable borrow, `addr_of_mut!` or `ref mut` scrutinee may wrap the // name in groups, tuples, arrays or blocks (`&mut (x, name)`, // `let (a, ref mut b) = (x, name)`): test the text before each // enclosing opener as well (#8944). let rest = &masked[offset + name.len()..]; if enclosing_heads(before) .into_iter() .enumerate() .any(|(open, head)| { mut_borrow_before(head) || addr_of_mut_before(head) || ref_mut_scrutinee(head, rest, open) }) { return true; } // A `let` (or `let mut`) declaration is the binding the let scan reads. if before.ends_with("let") || before.ends_with("mut") { return false; } // `write!(name, ..)` / `writeln!(name, ..)` write into their first // argument; the trusted-macro list keeps `bound_by_macro` from // seeing them. before.ends_with("write!(") || before.ends_with("writeln!(") || (!plain && borrowed_into_path_call(before)) || place_is_written(&masked[offset + name.len()..], !read_only) || (destructured_into(&masked[offset + name.len()..]) && !index_operand(before)) }) } /// A name passed by shared reference as an argument to any non-macro call /// (`AtomicU32::store(&EXPECTED, ..)`, `write(&EXPECTED, ..)`, /// `Cell::set(&expected, ..)`) may be written by the callee. A plain reader /// callee and a macro (`assert_eq!(f(4), &EXPECTED)`) do not count. fn borrowed_into_path_call(before: &str) -> bool { let Some(head) = before.strip_suffix('&') else { return false; }; let head = head.trim_end().trim_end_matches('&').trim_end(); if !head.ends_with(['(', ',']) { return false; } let mut depth = 0usize; let mut open = None; for (at, c) in head.char_indices().rev() { match c { ')' | ']' => depth += 1, '(' | '[' => { if depth == 0 { open = Some(at); break; } depth -= 1; } _ => {} } } let Some(open) = open else { return false; }; let callee = head[..open].trim_end(); if callee.ends_with('!') { return false; } // A turbofish callee (`store::(&X, ..)`) is unreadable: refuse. if callee.ends_with(['>', ')', ']', '}']) { return true; } let path: String = callee .chars() .rev() .take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == ':') .collect::>() .into_iter() .rev() .collect(); let last = path .rsplit_once("::") .map_or(path.as_str(), |(_, last)| last); !last.is_empty() && ![ "load", "get", "read", "eq", "ne", "len", "clone", "cmp", "partial_cmp", "contains", "starts_with", "ends_with", "is_empty", ] .contains(&last) } /// Whether the masked body uses `name` anywhere as something other than the /// local: a field or path segment (`st().name`, `S::name`) or a callee /// (`name(..)`, `name!(..)`). Such a use is unrelated to the `let`, and a /// method on it may write, so the read-only exemption does not apply. fn named_as_segment_or_call(masked: &str, name: &str) -> bool { whole_word_offsets(masked, name).into_iter().any(|offset| { let before = strip_raw_ident_prefix(masked[..offset].trim_end()); let after = masked[offset + name.len()..].trim_start(); before.ends_with('.') || before.ends_with("::") || after.starts_with('(') || after.starts_with('!') || after.starts_with("::") }) } /// Whether no whole-word use of `name` in the masked body follows `mut` /// (`let mut name`, `ref mut name`, `|mut name|`, `(mut name, ..)`), so the /// name is never declared mutable. fn never_declared_mut(masked: &str, name: &str) -> bool { whole_word_offsets(masked, name).into_iter().all(|offset| { let before = strip_raw_ident_prefix(masked[..offset].trim_end()); !before.strip_suffix("mut").is_some_and(|rest| { !rest .as_bytes() .last() .is_some_and(|byte| is_ident_byte(*byte)) }) }) } /// Whether the first whole-word use of `name` in the masked test body is a /// `let [mut] name` directly in the body block (brace depth one). Any earlier /// use, or a binding in an inner block, may name a different item. fn first_use_is_top_level_let(masked: &str, name: &str) -> bool { let Some(first) = whole_word_offsets(masked, name).into_iter().next() else { return false; }; let before = masked[..first].trim_end(); if before.matches('{').count() != before.matches('}').count() + 1 { return false; } let before = before .strip_suffix("mut") .filter(|rest| rest.ends_with(char::is_whitespace)) .map_or(before, str::trim_end); before.strip_suffix("let").is_some_and(|rest| { !rest .chars() .next_back() .is_some_and(|c| c.is_ascii_alphanumeric() || c == '_') }) } /// `before` without a trailing raw-identifier marker (`r#`), which sits /// between a borrow operator or path and the name it makes raw. fn strip_raw_ident_prefix(before: &str) -> &str { match before.strip_suffix("r#") { Some(rest) if !rest.as_bytes().last().is_some_and(|b| is_ident_byte(*b)) => rest.trim_end(), _ => before, } } /// `before` itself and, for every bracket (`(`, `[`, `{`) that is still open /// at its end, the text before that opener. A borrow or `ref mut` scrutinee /// applies to the whole enclosing group, so `(x, name)` and `{name}` are /// examined as the head that precedes them (#8944). A call or index opener /// simply yields a head ending in the callee, which no check accepts. fn enclosing_heads(before: &str) -> Vec<&str> { let mut heads = vec![before]; let mut depth = 0usize; for (at, character) in before.char_indices().rev() { match character { ')' | ']' | '}' => depth += 1, '(' | '[' | '{' => { if depth == 0 { heads.push(before[..at].trim_end()); } else { depth -= 1; } } _ => {} } } heads } /// `text` without a trailing balanced `<..>` generic argument list. A `->` /// (`fn() -> u8`) and anything inside a `{..}` const expression (`{ N > 1 }`) /// is no angle bracket, so neither closes or opens the list (#8960). fn strip_generic_args(text: &str) -> &str { if !text.ends_with('>') { return text; } let bytes = text.as_bytes(); let mut depth = 0usize; let mut braces = 0usize; for (at, character) in text.char_indices().rev() { match character { '}' => braces += 1, '{' => braces = braces.saturating_sub(1), _ if braces > 0 => {} '>' if at > 0 && bytes[at - 1] == b'-' => {} '>' => depth += 1, '<' => { depth = depth.saturating_sub(1); if depth == 0 { return text[..at].trim_end(); } } _ => {} } } text } /// `before` without the grouping and path qualifiers that sit between a /// borrow operator and the name it borrows: `(` (`&mut (name)`, /// `&mut (name).f`) and `crate::` / `self::` / `m::` path segments /// (`&mut crate::name`), generic/turbofish segments (`&mut ::name`, /// `&mut m::::name`) and dereferences (`&mut *name`), in any combination /// (#8929, #8944). A call opener /// (`&mut foo(name)`) leaves the callee ident, so it is not a borrow of the /// name. fn peel_group_and_path(before: &str) -> &str { let mut head = before.trim_end(); loop { if let Some(rest) = head.strip_suffix('(').or_else(|| head.strip_suffix('*')) { head = rest.trim_end(); } else if let Some(rest) = head.strip_suffix("::") { let rest = rest.trim_end(); let stripped = strip_generic_args(rest); if stripped.len() != rest.len() { // A generic list qualifies the path before it, not the // keyword: `match ::name` keeps `match` (#8960). head = stripped; continue; } let qualifier = rest.trim_end_matches(|c: char| c.is_ascii_alphanumeric() || c == '_'); // A raw-identifier segment (`r#m::name`) is consumed whole. let raw = strip_raw_ident_prefix(qualifier); // `& mut ::name` and the edition-2015 `match ::name` have an // empty qualifier: keep the keyword (#8944). head = if raw.len() != qualifier.len() { raw } else if matches!(&rest[qualifier.len()..], "mut" | "match") { rest } else { qualifier.trim_end() }; } else { return head; } } } /// Whether `before` ends in a mutable borrow operator: `&mut`, `& mut` or /// `&raw mut` (with any whitespace between the tokens), optionally followed /// by grouping parentheses or a path qualifier (`&mut (name)`, /// `&mut crate::name`). fn mut_borrow_before(before: &str) -> bool { let Some(head) = peel_group_and_path(before).strip_suffix("mut") else { return false; }; let head = head.trim_end(); head.ends_with('&') || head .strip_suffix("raw") .is_some_and(|rest| rest.trim_end().ends_with('&')) } /// Whether `before` ends in the opener of an `addr_of_mut!` call /// (`addr_of_mut!(name`, `ptr::addr_of_mut!(name`, /// `std::ptr::addr_of_mut!((name`): the macro form of `&raw mut`, and the /// idiomatic spelling of a mutable static borrow in edition 2024 (#8929). /// Shared `addr_of!` and a longer macro name (`my_addr_of_mut!`) do not match. fn addr_of_mut_before(before: &str) -> bool { // Peel path qualifiers and nested or spaced groups first // (`addr_of_mut!(crate::name`, `addr_of_mut!( (name`). let head = peel_group_and_path(before) .trim_end_matches(['(', '[', '{']) .trim_end(); let Some(head) = head.strip_suffix('!') else { return false; }; head.trim_end() .strip_suffix("addr_of_mut") .is_some_and(|rest| { !rest .as_bytes() .last() .is_some_and(|byte| is_ident_byte(*byte)) }) } /// Whether the name is the scrutinee of a pattern that binds `ref mut` /// (#8929): the right side of a `let` / `if let` / `while let` whose pattern /// contains `ref mut`, or the head of a `match` whose arms do. `rest` is the /// text after the name. The binding is a mutable reference into the place, /// so a later `*r = ..` writes it; the scan cannot follow `r`, so it refuses. fn ref_mut_scrutinee(before: &str, rest: &str, open: usize) -> bool { // `matches!(name, Some(ref mut r) if ..)` binds the pattern against the // first argument like a `match` does (#8944). if open > 0 && matches_macro_before(before) && macro_pattern_binds_ref_mut(rest, open - 1) { return true; } let head = peel_group_and_path(before); if let Some(pattern_end) = head.strip_suffix('=') { // `==`, `<=`, `+=` and the like compare or assign; only a bare `=` // after a `let` pattern binds. let Some(at) = whole_word_offsets(pattern_end, "let") .into_iter() .next_back() else { return false; }; let pattern = &pattern_end[at + "let".len()..]; // The pattern ends at a top-level `;`: a `ref mut` in an earlier // statement does not bind this scrutinee (#8944). if has_top_level_semicolon(pattern) { return false; } // `if let Some(ref mut r) = a { y = name; }`: a second bare `=` at the // top level of the text after `let` is the `=` of a later assignment, // so this `=` binds nothing of that pattern. An annotation colon may // hold an `=` (`Box>`), so it keeps the scan (#8944). if has_later_bare_assignment(pattern) { return false; } // `let ref mut r: Vec= name` closes a type annotation with the // `>` before `=`, so that `>` is no `>=` comparison. let annotation_close = pattern_end.ends_with('>') && has_ref_mut(pattern) && has_single_colon(pattern); if pattern_end.ends_with(['=', '!', '<', '+', '-', '*', '/', '%', '|', '&', '^']) || (pattern_end.ends_with('>') && !annotation_close) { return false; } return has_ref_mut(pattern); } if head .strip_suffix("match") .is_some_and(|rest| !rest.as_bytes().last().is_some_and(|b| is_ident_byte(*b))) { // `open` brackets are still open between the `match` keyword and the // name (`match ((name, 1), S { a: 1 }) { .. }` has two). The scrutinee // ends only when the depth returns to zero, so a sibling `{..}` inside // an outer group is never taken for the arm list (#8960). A nested // brace group holding `ref mut` refuses (conservative); at depth zero // after the scrutinee closed, the first `{..}` is the arm list. let mut depth = open; let mut closed = false; let mut seen_group = false; let mut at = 0usize; while let Some(character) = rest[at..].chars().next() { match character { '(' | '[' => depth += 1, ')' | ']' | '}' => { depth = depth.saturating_sub(1); if depth == 0 { closed = true; } } ';' if depth == 0 && (closed || seen_group) => return false, '{' => { let group = &rest[at..]; let end = skip_balanced(group, '{', '}') .map_or(group.len(), |after| group.len() - after.len()); if depth > 0 { if has_ref_mut(&group[..end]) { return true; } } else if closed { return arm_patterns_bind_ref_mut(&group[..end]); } else { if !seen_group && arm_patterns_bind_ref_mut(&group[..end]) { return true; } seen_group = true; } at += end; continue; } _ => {} } at += character.len_utf8(); } } false } /// Whether `before` ends in the opener of a `matches!`-family macro /// (`matches!(`, `std::matches!(`, `assert_matches!(`): `before` is the text /// before the opener, so it ends in the macro's `!`. fn matches_macro_before(before: &str) -> bool { let Some(head) = before.trim_end().strip_suffix('!') else { return false; }; // `matches !(..)` is the same macro: rustc allows space before the `!`. let head = head.trim_end(); ["matches", "assert_matches", "debug_assert_matches"] .iter() .any(|name| { head.strip_suffix(name) .is_some_and(|rest| !rest.as_bytes().last().is_some_and(|b| is_ident_byte(*b))) }) } /// Whether the rest of a `matches!(name, pattern if guard)` invocation holds /// `ref mut`. `inside` brackets are open between the macro's opener and the /// name; the invocation ends at the first closer that returns past it. fn macro_pattern_binds_ref_mut(rest: &str, inside: usize) -> bool { let mut depth = inside; for (at, character) in rest.char_indices() { match character { '(' | '[' | '{' => depth += 1, ')' | ']' | '}' => { if depth == 0 { return has_ref_mut(&rest[..at]); } depth -= 1; } _ => {} } } has_ref_mut(rest) } /// Whether a `match` arm list `{ .. }` binds `ref mut` in an arm pattern or /// guard: the text before each top-level `=>`. A block body (`=> { .. }`) is /// skipped. Every other text, a non-block body included, stays part of the /// scanned text up to the next `=>`, because a block-like body needs no comma /// and the next arm's pattern may follow it directly (#8944). fn arm_patterns_bind_ref_mut(group: &str) -> bool { let inner = group.strip_prefix('{').unwrap_or(group); let bytes = inner.as_bytes(); let mut depth = 0usize; let mut start = 0usize; let mut at = 0usize; while at < inner.len() { match bytes[at] { b'(' | b'[' | b'{' => depth += 1, b')' | b']' | b'}' => depth = depth.saturating_sub(1), b'=' if depth == 0 && bytes.get(at + 1) == Some(&b'>') => { if has_ref_mut(&inner[start..at]) { return true; } at += 2; let body = inner[at..].trim_start(); let body_at = inner.len() - body.len(); if body.starts_with('{') { at = match skip_balanced(body, '{', '}') { Some(after) => inner.len() - after.len(), None => return has_ref_mut(&inner[body_at..]), }; } else { at = body_at; } start = at; continue; } _ => {} } at += 1; } false } /// Whether the text after a `let` holds a second bare `=` at its top level /// (not `==`, `=>`, `<=`, `>=`, `!=`, `..=` or a compound assignment) before /// any top-level annotation colon. fn has_later_bare_assignment(pattern: &str) -> bool { let bytes = pattern.as_bytes(); let mut depth = 0usize; for (at, byte) in bytes.iter().enumerate() { match byte { b'(' | b'[' | b'{' => depth += 1, b')' | b']' | b'}' => depth = depth.saturating_sub(1), b':' if depth == 0 && bytes.get(at + 1) != Some(&b':') && (at == 0 || bytes[at - 1] != b':') => { return false; } b'=' if depth == 0 => { let prev = if at == 0 { b' ' } else { bytes[at - 1] }; let next = bytes.get(at + 1).copied().unwrap_or(b' '); if !b"=!<>+-*/%|&^.".contains(&prev) && next != b'=' && next != b'>' { return true; } } _ => {} } } false } /// Whether `text` has a `;` outside every bracket pair. fn has_top_level_semicolon(text: &str) -> bool { let mut depth = 0usize; for character in text.chars() { match character { '(' | '[' | '{' => depth += 1, ')' | ']' | '}' => depth = depth.saturating_sub(1), ';' if depth == 0 => return true, _ => {} } } false } /// Whether `text` contains the `ref mut` binding-mode tokens. fn has_ref_mut(text: &str) -> bool { whole_word_offsets(text, "ref").into_iter().any(|at| { let tail = text[at + "ref".len()..].trim_start(); tail.strip_prefix("mut") .is_some_and(|after| !after.as_bytes().first().is_some_and(|b| is_ident_byte(*b))) }) } /// Whether the text before a name sits inside a `let` pattern's type /// annotation (#8795): the nearest preceding `let` has no `=`, `;`, `{` or /// `}` after it, and a single `:` (not a `::` path separator) separates the /// pattern from the name. A pattern with no annotation colon /// (`let (a, name) = ..`) binds the name and is not an annotation; a struct /// pattern's field colon sits inside `{}` and is excluded. fn in_let_annotation(before: &str) -> bool { whole_word_offsets(before, "let") .into_iter() .next_back() .is_some_and(|at| { let tail = &before[at + "let".len()..]; !tail.contains(['=', ';', '{', '}']) && has_single_colon(tail) }) } fn has_single_colon(text: &str) -> bool { let bytes = text.as_bytes(); bytes.iter().enumerate().any(|(at, byte)| { *byte == b':' && bytes.get(at + 1) != Some(&b':') && (at == 0 || bytes.get(at - 1) != Some(&b':')) }) } /// Whether the name sits inside the `[..]` of an index expression /// (`v[name] = ..`): the nearest unclosed group before it is a `[` that /// directly follows an identifier or a closing bracket. The name is then an /// index read, not the place an enclosing assignment writes (#8795). An /// array pattern (`[name, ..] = p`) follows `;`, `=` or nothing, so it is not. fn index_operand(before: &str) -> bool { let mut depth = 0usize; for (at, character) in before.char_indices().rev() { match character { ')' | ']' | '}' => depth += 1, '(' | '[' | '{' => { if depth > 0 { depth -= 1; continue; } if character != '[' { return false; } let head = before[..at].trim_end(); // A keyword before `[` (`match [e, o] = p`, `return [e, o] = p`) // starts an array pattern or value, not an index. let word_start = head .char_indices() .rev() .find(|&(_, c)| !(c.is_ascii_alphanumeric() || c == '_' || !c.is_ascii())) .map_or(0, |(at, c)| at + c.len_utf8()); // A label (`break 'a [e, o] = p`, `continue 'a [..]`) is not an // indexed place either. if head[..word_start].ends_with('\'') || NEGATING_KEYWORDS.contains(&&head[word_start..]) { return false; } return head.chars().next_back().is_some_and(|prev| { prev.is_ascii_alphanumeric() || matches!(prev, '_' | ')' | ']') }); } ';' if depth == 0 => return false, _ => {} } } false } /// Whether every `let` binding of a name (the text after the name, as /// `receiver_let_bindings` returns it) initializes it with a plain value: a /// literal, or a tuple or array (`[plain; N]` included) of plain values. /// Such a value is a primitive aggregate with no interior mutability and no /// `Deref`, so a shared borrow of it cannot be written by a callee (#8795). /// Named struct literals and constructor calls are never plain. No binding at all (a static, a const) is /// not plain. fn plain_let_values(bindings: &[&str]) -> bool { !bindings.is_empty() && bindings.iter().all(|binding| { let statement = binding.trim_end().trim_end_matches(';'); let init = statement .match_indices('=') .map(|(position, _)| position) .find(|position| { !matches!(statement.as_bytes().get(position + 1), Some(b'=' | b'>')) && !matches!( statement.as_bytes().get(position.wrapping_sub(1)), Some(b'=' | b'!' | b'<' | b'>') ) }) .map(|position| &statement[position + 1..]); init.is_some_and(is_plain_value) }) } fn is_plain_value(expression: &str) -> bool { let expression = expression.trim(); let unsigned = expression .strip_prefix('-') .map_or(expression, str::trim_start); if unsigned.starts_with(|c: char| c.is_ascii_digit()) { return is_numeric_literal(unsigned); } if unsigned.len() != expression.len() { return false; } if matches!(expression, "true" | "false") || is_string_literal(expression) { return true; } if expression.len() >= 3 && expression.starts_with('\'') && expression.ends_with('\'') { return !expression[1..expression.len() - 1].contains('\''); } if let Some((element, length)) = group_inner(expression, '[', ']').and_then(|inner| inner.split_once(';')) { let length = length.trim(); return is_plain_value(element) && !length.is_empty() && length.chars().all(|c| c.is_ascii_digit() || c == '_'); } if let Some(inner) = group_inner(expression, '(', ')').or_else(|| group_inner(expression, '[', ']')) { return split_top_level(inner) .iter() .all(|part| part.trim().is_empty() || is_plain_value(part)); } // Anything else, including a named struct literal (it may `Deref` to an // interior-mutable type) or a constructor call, is not plain. false } /// A numeric literal: digits and `_`, at most one `.` that is followed by a /// digit (so `1..n` and `1.method()` are not literals), then an optional /// exponent or alphanumeric suffix (`1_000u32`, `0xff`, `1.5e3f64`). fn is_numeric_literal(text: &str) -> bool { let bytes = text.as_bytes(); let mut dots = 0; for (at, byte) in bytes.iter().enumerate() { match byte { b'.' => { dots += 1; if dots > 1 || !bytes.get(at + 1).is_some_and(u8::is_ascii_digit) { return false; } } b'-' | b'+' => { if !matches!(bytes.get(at.wrapping_sub(1)), Some(b'e' | b'E')) || !bytes.get(at + 1).is_some_and(u8::is_ascii_digit) { return false; } } byte if byte.is_ascii_alphanumeric() || *byte == b'_' => {} _ => return false, } } true } fn is_string_literal(text: &str) -> bool { let text = text.strip_prefix('b').unwrap_or(text); text.len() >= 2 && text.starts_with('"') && text.ends_with('"') && !text[1..text.len() - 1].contains(['"', '\\']) } /// The text inside `open..close` when `text` is exactly that one group. fn group_inner(text: &str, open: char, close: char) -> Option<&str> { let rest = text.strip_prefix(open)?; let after = skip_balanced(text, open, close)?; if after.trim().is_empty() { rest.rfind(close).map(|end| &rest[..end]) } else { None } } /// `text` split at commas outside any bracket pair. fn split_top_level(text: &str) -> Vec<&str> { let mut parts = Vec::new(); let mut depth = 0usize; let mut start = 0; for (at, character) in text.char_indices() { match character { '(' | '[' | '{' => depth += 1, ')' | ']' | '}' => depth = depth.saturating_sub(1), ',' if depth == 0 => { parts.push(&text[start..at]); start = at + 1; } _ => {} } } parts.push(&text[start..]); parts } /// Whether the place expression that continues `rest` (a chain of `.field`, /// `.0`, `[..]` and calls) is assigned, or ends in a mutating call. An /// unreadable chain fails closed. fn place_is_written(rest: &str, methods_mutate: bool) -> bool { let mut rest = rest.trim_start(); loop { if let Some(call) = rest.strip_prefix('.') { let call = call.trim_start(); let method: String = call .chars() .take_while(|character| character.is_ascii_alphanumeric() || *character == '_') .collect(); if method.is_empty() { return true; } rest = call[method.len()..].trim_start(); // A turbofish or `?` is a shape the scan does not read. if rest.starts_with("::") || rest.starts_with('?') { return true; } if rest.starts_with('(') { if methods_mutate && is_mutating_method(&method) { return true; } match skip_balanced(rest, '(', ')') { Some(after) => rest = after.trim_start(), None => return true, } } } else if rest.starts_with('[') { match skip_balanced(rest, '[', ']') { Some(after) => rest = after.trim_start(), None => return true, } } else if rest.starts_with('?') { return true; } else { break; } } assignment_operator_at(rest) } /// Whether the name sits in a pattern that is the left side of an assignment /// (`(name, _) = ..`, `[name, ..] = ..`, `S { f: name, .. } = ..`): after the /// enclosing group closes, an `=` (not `==` or `=>`) or compound operator /// follows. `rest` is the text after the name. fn destructured_into(rest: &str) -> bool { let mut depth = 0usize; for (at, character) in rest.char_indices() { match character { '(' | '[' | '{' => depth += 1, ')' | ']' | '}' => { if depth > 0 { depth -= 1; continue; } // The enclosing group closed: what follows decides. // What follows may be a place chain (`(name)[0] = ..`, // `m![name][i] = ..`): read it like any place expression. // A bare `?` or `.await` after the group is transparent // (`foo(name)?;`, `foo(name).await?`): the value is read, and // only a `.`, `[` or assignment after it writes (#8929). let mut tail = &rest[at..]; loop { let trimmed = tail.trim_start_matches([')', ']', '}']).trim_start(); let trimmed = trimmed.strip_prefix('?').unwrap_or(trimmed); let trimmed = match trimmed.trim_start().strip_prefix(".await") { Some(after) if !after.as_bytes().first().is_some_and(|b| is_ident_byte(*b)) => { after } _ => trimmed, }; if trimmed.len() == tail.len() { break; } tail = trimmed; } return place_is_written(tail.trim_start(), true); } ';' if depth == 0 => return false, _ => {} } } false } fn assignment_operator_at(rest: &str) -> bool { rest.strip_prefix('=') .is_some_and(|tail| !tail.starts_with(['=', '>'])) || ["+=", "-=", "*=", "/=", "%=", "|=", "&=", "^=", "<<=", ">>="] .iter() .any(|operator| rest.starts_with(operator)) } /// The text after the bracket that closes the one `text` opens with. fn skip_balanced(text: &str, open: char, close: char) -> Option<&str> { let mut depth = 0usize; for (at, character) in text.char_indices() { if character == open { depth += 1; } else if character == close { depth = depth.checked_sub(1)?; if depth == 0 { return Some(&text[at + close.len_utf8()..]); } } } None } /// Methods that may mutate their receiver (#7847). Name families cover the /// std mutators; an unlisted name is read-only to the scan. fn is_mutating_method(method: &str) -> bool { const MUTATORS: &[&str] = &[ "store", "set", "with", "nth", "splice", "replace_range", "replace", "swap", "append", "write", "lock", "take", "clear", "entry", "resize", "truncate", "get_or_init", "update", "next", "next_back", "next_chunk", "resize_with", "compare_and_swap", "try_lock", "try_write", "as_mut_ptr", "reverse", "split_off", "rotate_left", "rotate_right", "replace_with", "copy_within", ]; MUTATORS.contains(&method) || [ "push", "pop", "sort", "fill", "drain", "retain", "extend", "insert", "copy_", "clone_from", "remove", "or_insert", "get_or_insert", "dedup", "swap_", "write_", "make_ascii_", "compare_exchange", "next_if", "peek", "fetch_", "set_", ] .iter() .any(|prefix| method.starts_with(prefix)) || ["_mut", "_assign"] .iter() .any(|suffix| method.ends_with(suffix)) } /// #6578: whether the expected operand may carry a value an rstest fixture /// built. A fixture parameter (one not marked `#[case]`) is filled by a /// `#[fixture]` function outside the test body, which may call the owner /// (`#[fixture] fn want() -> u32 { weight(4) }` makes /// `assert_eq!(weight(4), want)` compare the owner with itself), and the /// body-only owner scan cannot see it. In a test with a fixture, the /// expected operand must name no fixture and nothing the body binds: a /// body binding may hold a fixture value through a `let`, an assignment or /// a mutation (`let mut w = 0; w = want;`, `v.push(want)`), so any `let`, /// closure, `for` or match binding of an expected word fails closed, a /// rebound `#[case]` parameter included. Unrebound `#[case]` parameters /// (rows the syntax gate holds to literals) and names bound outside the /// test (constants) pass. fn expected_reaches_fixture(test: &TestSummary, expected: &str) -> bool { let masked = mask_comments_and_strings(&test.body); let Some(fixtures) = fixture_parameters(test, &masked) else { return true; }; if fixtures.is_empty() { return false; } let Some((open, close)) = whole_word_offsets(&masked, "fn") .first() .and_then(|offset| fn_param_range(&masked, *offset)) else { return true; }; let mut body = masked.clone(); body.replace_range(open + 1..close, &" ".repeat(close - open - 1)); mask_comments_and_strings(expected) .split(|character: char| !(character.is_ascii_alphanumeric() || character == '_')) .filter(|word| is_plain_identifier(word)) .any(|word| { fixtures.contains(word) || binds_outside_let(&body, word) || let_patterns_bind(&body, word) }) } /// #6578: the names of the test's rstest fixture parameters (those not /// marked `#[case]`), empty when the test takes none, or `None` when it /// takes parameters ripr cannot read. `masked` is the test body with /// comments and strings masked. fn fixture_parameters(test: &TestSummary, masked: &str) -> Option> { // Most tests take no parameters: skip the parse. No readable `fn` // signature holds no fixture parameter; the owner-pin syntax gate // admits rstest only on a parsed `fn`. let Some((open, close)) = whole_word_offsets(masked, "fn") .first() .and_then(|offset| fn_param_range(masked, *offset)) else { return Some(BTreeSet::new()); }; if masked[open + 1..close].trim().is_empty() { return Some(BTreeSet::new()); } // A `#[test_case]` function has no fixtures: the syntax gate admits it // only when every row holds one scalar literal per parameter. if test.attrs.iter().any(|attr| is_test_case_attribute(attr)) { return Some(BTreeSet::new()); } let parse = parse_clean_source_file(&test.body)?; let function = parse .tree() .syntax() .descendants() .find_map(ast::Fn::cast)?; let mut fixtures = BTreeSet::new(); let Some(list) = function.param_list() else { return Some(fixtures); }; for param in list.params() { let Some(ast::Pat::IdentPat(pat)) = param.pat() else { return None; }; let name = pat.name()?; if !param .attrs() .any(|attr| attr.simple_name().as_deref() == Some("case")) { fixtures.insert(name.text().to_string()); } } Some(fixtures) } fn is_test_case_attribute(attribute: &str) -> bool { let compact: String = attribute.split_whitespace().collect(); compact.starts_with("#[test_case(") || compact.starts_with("#[test_case::test_case(") } /// The offsets of the parentheses around the parameter list of the `fn` /// keyword at `fn_at` in `masked`. fn fn_param_range(masked: &str, fn_at: usize) -> Option<(usize, usize)> { let open = fn_at + masked[fn_at..].find('(')?; let close = matching_close(masked, open, b'(', b')')?; Some((open, close)) } /// #6974 review: whether any `let` pattern in `masked` may bind `word`: /// the text after `let` up to its type annotation (a lone `:`), its `=` /// or its `;`, whichever comes first. fn let_patterns_bind(masked: &str, word: &str) -> bool { whole_word_offsets(masked, "let").into_iter().any(|offset| { let rest = &masked[offset + "let".len()..]; let bytes = rest.as_bytes(); let end = (0..bytes.len()) .find(|&at| match bytes[at] { b'=' | b';' => true, b':' => bytes.get(at + 1) != Some(&b':') && (at == 0 || bytes[at - 1] != b':'), _ => false, }) .unwrap_or(bytes.len()); contains_as_whole_word(&rest[..end], word) }) } /// Methods that may run the `clone` under test. const CLONING_METHODS: &[&str] = &["clone", "clone_from", "cloned", "to_owned"]; /// #6692: whether the clone's receiver was built without the clone under /// test, so a wrong `clone` cannot also have produced the value it is /// compared with (`let w: Window = base.clone(); assert_eq!(w.clone(), w)` /// passes for an idempotent wrong field). Every `let` of the receiver must /// initialize it with a `type_name { .. }` or `type_name(..)` literal, or a /// call to the type's one inherent constructor whose body clones nothing, /// and no part of an initializer may clone. The test may not reassign or /// mutably borrow the receiver. Anything else fails closed. fn clone_receiver_is_independent( test: &TestSummary, receiver: &str, type_name: &str, index: &RustIndex, ) -> bool { let masked = mask_comments_and_strings(&test.body); if receiver_is_reassigned(&masked, receiver) { return false; } let Some(bindings) = receiver_let_bindings(test, receiver) else { return false; }; !bindings.is_empty() && bindings .into_iter() .all(|binding| initializer_is_independent(binding, type_name, index)) } /// Whether the test may change `receiver` after binding it: an assignment /// (`w = ..`, `w += ..`), or any `mut` before the name (`let mut w`, /// `&mut w`, `ref mut w`, `|mut w|`). A `let mut` binding alone refuses: /// a field write (`w.start = w.end`), a `&mut w.start` borrow or a /// `&mut self` method call (`w.set_start(9)`) all need one, and ripr does /// not read them. fn receiver_is_reassigned(masked: &str, receiver: &str) -> bool { const COMPOUND: &[&str] = &["+=", "-=", "*=", "/=", "%=", "^=", "&=", "|=", "<<=", ">>="]; whole_word_offsets(masked, receiver) .into_iter() .any(|offset| { let after = masked[offset + receiver.len()..].trim_start(); let assigns = (after.starts_with('=') && !after.starts_with("==") && !after.starts_with("=>")) || COMPOUND.iter().any(|operator| after.starts_with(operator)); let before = masked[..offset].trim_end(); let mutable = before.strip_suffix("mut").is_some_and(|rest| { !rest .as_bytes() .last() .is_some_and(|byte| is_ident_byte(*byte)) }); let let_binding = before.strip_suffix("let").is_some_and(|rest| { !rest .as_bytes() .last() .is_some_and(|byte| is_ident_byte(*byte)) }); (assigns && !let_binding) || mutable }) } /// One receiver initializer: a `type_name { .. }` or `type_name(..)` /// literal, or a `type_name::ctor(..)` call to the type's one inherent /// constructor, whose fields or arguments are all [`is_trivial_expression`] /// without locals: no call, method, macro, index, block or local binding /// may supply a value (a helper or a local could carry a wrong clone's /// output, `Window::new(make(&base))`). The constructor body must be a /// bare `Self`/`type_name` literal of its parameters /// ([`constructor_body_is_plain_literal`]). fn initializer_is_independent(binding: &str, type_name: &str, index: &RustIndex) -> bool { let masked = mask_comments_and_strings(binding); let Some(equals) = masked.find('=') else { return false; }; let initializer = masked[equals + 1..].trim(); if CLONING_METHODS .iter() .any(|method| contains_as_whole_word(initializer, method)) { return false; } let Some(rest) = initializer.strip_prefix(type_name) else { return false; }; if let Some(call) = rest.strip_prefix("::") { let call_end = call .find(|character: char| !(character.is_ascii_alphanumeric() || character == '_')) .unwrap_or(call.len()); let constructor = &call[..call_end]; let arguments = call[call_end..].trim_start(); if !arguments.starts_with('(') || matching_close(arguments, 0, b'(', b')') != Some(arguments.len() - 1) || !literal_items_are_trivial(&arguments[1..arguments.len() - 1], false, false) { return false; } let mut definitions = index.functions().iter().filter(|function| { function.name == constructor && !function.item.has_self_param && matches!( &function.item.container, FunctionContainer::Inherent { self_ty } if path_base_name(self_ty) == Some(type_name) ) }); let (Some(definition), None) = (definitions.next(), definitions.next()) else { return false; }; return constructor_body_is_plain_literal(&definition.body, type_name); } plain_literal(rest.trim_start(), false) } /// Whether `rest` (the text after a type name) is exactly one `{ .. }` or /// `( .. )` literal body whose items are trivial; `locals` admits plain /// lowercase bindings (a constructor's parameters) and field shorthand. fn plain_literal(rest: &str, locals: bool) -> bool { let (open, close, braced) = match rest.as_bytes().first() { Some(b'{') => (b'{', b'}', true), Some(b'(') => (b'(', b')', false), _ => return false, }; matching_close(rest, 0, open, close) == Some(rest.len() - 1) && literal_items_are_trivial(&rest[1..rest.len() - 1], braced, locals) } /// Whether every comma-separated item of a literal or argument list is a /// trivial expression; in a braced literal each item is `field: expr` (or, /// with `locals`, the shorthand `field`). A `..base` update refuses. fn literal_items_are_trivial(items: &str, braced: bool, locals: bool) -> bool { if items.contains("..") { return false; } top_level_arguments(items).into_iter().all(|item| { if !braced { return is_trivial_expression(item, locals); } match item.split_once(':') { Some((field, value)) => { is_plain_identifier(field.trim()) && !value.starts_with(':') && is_trivial_expression(value, locals) } None => locals && is_plain_identifier(item.trim()), } }) } /// Whether a constructor's (masked) body is nothing but a `Self { .. }`, /// `type_name { .. }`, `Self(..)` or `type_name(..)` literal of trivial /// items over its parameters: no `let`, call, method, macro or helper that /// could run a clone. fn constructor_body_is_plain_literal(definition: &str, type_name: &str) -> bool { let masked = mask_comments_and_strings(definition); let Some(open) = masked .find('(') .and_then(|params| matching_close(&masked, params, b'(', b')')) .and_then(|params_close| { masked[params_close..] .find('{') .map(|offset| params_close + offset) }) else { return false; }; let Some(close) = matching_close(&masked, open, b'{', b'}') else { return false; }; if !masked[close + 1..].trim().is_empty() { return false; } let tail = masked[open + 1..close].trim(); let Some(rest) = tail .strip_prefix("Self") .or_else(|| tail.strip_prefix(type_name)) else { return false; }; plain_literal(rest.trim_start(), true) } /// Primitive type names a trivial expression may cast to. const CAST_TYPES: &[&str] = &[ "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize", "f32", "f64", "char", "bool", ]; /// Whether a (masked) expression only combines literals, `true`/`false`, /// constants and enum variants named by a path whose last segment starts /// uppercase, `as` casts to primitives and arithmetic, comparison and /// bitwise operators. Calls, methods, macros, indexing, blocks, closures, /// derefs, ranges, `?` and lowercase bindings (unless `locals`) refuse: /// any of them may carry a value the clone under test produced. fn is_trivial_expression(expression: &str, locals: bool) -> bool { let bytes = expression.as_bytes(); if expression.trim().is_empty() { return false; } let mut index = 0usize; let mut after_as = false; while index < bytes.len() { let byte = bytes[index]; if byte.is_ascii_digit() { index += 1; while index < bytes.len() && (is_ident_byte(bytes[index]) || (bytes[index] == b'.' && bytes.get(index + 1).is_some_and(u8::is_ascii_digit))) { index += 1; } continue; } if byte.is_ascii_alphabetic() || byte == b'_' { let start = index; while index < bytes.len() && (is_ident_byte(bytes[index]) || (bytes[index] == b':' && bytes.get(index + 1) == Some(&b':'))) { index += if bytes[index] == b':' { 2 } else { 1 }; } let path = &expression[start..index]; let last = path.rsplit("::").next().unwrap_or(path); let next = bytes.get(index).copied(); let string_prefix = matches!(path, "b" | "r" | "br" | "c" | "cr") && matches!(next, Some(b'"' | b'#' | b'\'')); let admitted = if after_as { CAST_TYPES.contains(&path) } else if path == "as" { after_as = true; continue; } else { string_prefix || matches!(path, "true" | "false") || last.starts_with(|character: char| character.is_ascii_uppercase()) || (locals && path == last && is_plain_identifier(path)) }; after_as = false; if !admitted || last.is_empty() { return false; } continue; } if byte.is_ascii_whitespace() || matches!( byte, b'"' | b'\'' | b'#' | b'-' | b'+' | b'/' | b'%' | b'&' | b'^' | b'<' | b'>' | b'=' ) { index += 1; continue; } return false; } !after_as } /// Whether `name` may be bound by a pattern that is not a `let`: a closure /// parameter list, a `for` pattern, a match arm, the test's own or a /// nested `fn`'s parameters. Lexical and conservative: a `|` operator or an unrelated /// match arm that mentions the name also counts. fn binds_outside_let(masked: &str, name: &str) -> bool { // A function-pointer type has no item name: its `fn` is followed by // `(`. Its parameter labels bind no values in the surrounding test. // Keep the existing conservative refusal for actual nested fn items. let fns: Vec<_> = whole_word_offsets(masked, "fn") .into_iter() .filter(|offset| !masked[offset + "fn".len()..].trim_start().starts_with('(')) .collect(); if fns.len() > 1 { return true; } // The test's own parameters (`#[case] name: T`) bind the name too. let parameters = fns.first().and_then(|offset| { let open = offset + masked[*offset..].find('(')?; let close = matching_close(masked, open, b'(', b')')?; Some(&masked[open..close]) }); if parameters.is_none_or(|parameters| contains_as_whole_word(parameters, name)) { return true; } let bytes = masked.as_bytes(); let pipes = bytes .iter() .enumerate() .filter(|(offset, byte)| { **byte == b'|' && bytes.get(offset + 1) != Some(&b'|') && (*offset == 0 || bytes[offset - 1] != b'|') }) .map(|(offset, _)| offset) .collect::>(); // Every region between two consecutive pipes: a `|` operator must not // shift a closure's parameter list out of the pairing. if pipes .windows(2) .any(|pair| contains_as_whole_word(&masked[pair[0]..pair[1]], name)) { return true; } let for_pattern = whole_word_offsets(masked, "for").into_iter().any(|offset| { let rest = &masked[offset + "for".len()..]; let end = whole_word_offsets(rest, "in") .first() .copied() .unwrap_or(rest.len()); contains_as_whole_word(&rest[..end], name) }); if for_pattern { return true; } masked.match_indices("=>").any(|(arrow, _)| { let start = masked[..arrow] .rfind(['{', ',', '}']) .map_or(0, |position| position + 1); contains_as_whole_word(&masked[start..arrow], name) }) } /// The type of one `let ...;` binding: its annotation, or a /// constructor-shaped initializer. fn binding_type( binding: &str, test: &TestSummary, test_source: Option<&str>, index: &RustIndex, imports_foreign: ForeignImport<'_>, owner: OwnerScope<'_>, syntax: &OwnerPinSyntax, ) -> Option { let binding = binding.trim(); let (annotation, initializer) = if let Some(rest) = binding.strip_prefix(':') { let (annotation, initializer) = rest.split_once('=')?; (Some(annotation.trim()), initializer.trim()) } else { (None, binding.strip_prefix('=')?.trim()) }; if let Some(annotation) = annotation { return named_or_slice(annotation, test, test_source, index, imports_foreign, owner); } if is_byte_slice_expression(initializer) { return Some(ReceiverType::ByteSlice); } let (initializer, unwrapped) = strip_unwrap(initializer); if !unwrapped && !initializer.is_empty() && initializer .bytes() .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') { // `= Unit`: only a unit struct's own name is a value of that type. // `named_or_slice` refuses a lower-case name anyway; checking first // skips the workspace scan for every local-variable receiver. if !initializer.starts_with(|character: char| character.is_ascii_uppercase()) || !unit_struct_value(initializer, &test.file, index, syntax) { return None; } return named_or_slice( initializer, test, test_source, index, imports_foreign, owner, ); } let type_end = initializer .find(|character: char| !(character.is_ascii_alphanumeric() || character == '_'))?; let type_name = &initializer[..type_end]; let rest = &initializer[type_end..]; let constructor = if let Some(call) = rest.strip_prefix("::") { let call_end = call.find(|character: char| !(character.is_ascii_alphanumeric() || character == '_'))?; let masked = mask_comments_and_strings(&call[call_end..]); masked.starts_with('(') && matching_close(&masked, 0, b'(', b')') .is_some_and(|closing| masked[closing + 1..].trim().is_empty()) && constructor_returns_self(type_name, &call[..call_end], unwrapped, index) } else { let rest = rest.trim_start(); let (open, close) = if rest.starts_with('{') { (b'{', b'}') } else { (b'(', b')') }; let masked = mask_comments_and_strings(rest); !unwrapped && masked.as_bytes().first() == Some(&open) && matching_close(&masked, 0, open, close) .is_some_and(|closing| masked[closing + 1..].trim().is_empty()) }; if !constructor { return None; } named_or_slice(type_name, test, test_source, index, imports_foreign, owner) } impl OwnerPinSyntax { /// #7172: [`unit_struct_value`]'s name-independent inputs, computed /// once per run; the index is immutable, so the memo never goes stale. fn unit_struct_facts(&self, index: &RustIndex) -> &UnitStructFacts { self.unit_struct_facts .get_or_init(|| UnitStructFacts::collect(index)) } } /// #7172: the name-independent inputs to [`unit_struct_value`], scanned /// once per run over the immutable index. A bare-name receiver check runs /// per assertion, and every call used to rebuild the module-name set and /// mask + scan every indexed file; the per-name spelling checks stay per /// call. Every verdict below conjoins exactly as the per-call scans did, /// so hoisting them changes no admission. #[derive(Clone, Debug, Default)] struct UnitStructFacts { /// A glob in some file may reach outside the workspace's modules. glob_outside: bool, /// Some file splices unread text (`include!`) or redirects a module /// (`#[path]`, either spelling). spliced: bool, /// Some file's `macro_rules!` matcher takes an `:ident` or `:tt` /// fragment, which could declare any name it is given. macro_takes_name: bool, /// Some file invokes a macro at item position whose /// definition is outside the indexed file text (#7160). external_defining_macro: bool, /// Files whose masked source mentions `macro_rules!`: only these can /// refuse a name by spelling it in a macro definition. Complete only /// while [`Self::refused`] is false: the scan stops at the first /// refusal verdict, and [`unit_struct_value`] reads this set only /// after that gate. macro_files: BTreeSet, } impl UnitStructFacts { /// Scan the workspace once, stopping at the first refusal verdict: /// the predicates are name-independent, so no later file can change /// one. The module-name set feeds the glob verdict and is dropped; /// the predicates are the name-independent halves of /// [`unit_struct_value`]'s per-file checks, unchanged. fn collect(index: &RustIndex) -> Self { let modules = workspace_module_names(index); let mut glob_outside = false; let mut spliced = false; let mut macro_takes_name = false; let mut external_defining_macro = false; let mut macro_files = BTreeSet::new(); for (file, facts) in index.files().iter() { // Once any refusal verdict holds, the remaining files cannot // change it, and the caller refuses before reading // `macro_files`; stop paying for their masking. if glob_outside || spliced || macro_takes_name || external_defining_macro { break; } external_defining_macro |= super::macro_item_names::file_has_non_local_defining_macro_invocation( &facts.source, ); if external_defining_macro { break; } let masked = mask_comments_and_strings(&facts.source); // A glob that reaches outside the workspace's modules, in any // file, can bring the name to the test without spelling it. glob_outside |= glob_reaches_outside(&masked, &modules); // `include!` and `#[path]` splice in text the index may never // read, so no spelling scan covers them. The cheap filter // matches the bare words: `# [ path` may carry whitespace, and // rustc accepts the raw-identifier spelling `#[r#path = ..]` // too (#7098 review). if masked.contains("include") || masked.contains("path") { let compact = without_rust_whitespace(&masked); spliced |= compact.contains("include!") || compact.contains("#[path") || compact.contains("#[r#path"); } // A macro may take the name as an `ident` or `tt` fragment; the // spelling half (no macro-defining file spells the name) stays // per name at the call. if masked.contains("macro_rules") { macro_files.insert(file.clone()); let compact = without_rust_whitespace(&masked); macro_takes_name |= compact.contains(":ident") || compact.contains(":tt"); } } Self { glob_outside, spliced, macro_takes_name, external_defining_macro, macro_files, } } /// Whether the workspace-wide scans refuse every name. fn refused(&self) -> bool { self.glob_outside || self.spliced || self.macro_takes_name || self.external_defining_macro } } /// Whether the bare name `name`, spelled in `test_file`, evaluates to the /// workspace unit struct `name` (#7083). Reading what a bare name resolves /// to needs name resolution, so the rule admits only a shape where nothing /// else can supply the name: /// /// - the workspace declares it exactly once, as a non-generic unit struct /// (`struct name;`), in the test's own file; /// - every other spelling of the name in the workspace is an `impl` header /// (`impl name {`, `impl Trait for name {`), a method call (`name.f(..)`) /// or a `let` initializer (`= name;`). An import, a type position, a raw /// identifier (`r#name`), a pattern, an enum variant, a macro argument or /// any `const`, `static`, `fn`, `type` or `as` rename refuses; /// - no workspace `macro_rules!` matcher takes an `ident` or `tt` fragment, /// which could declare the name from a spelling the scan reads as inert, /// and no file that defines a macro spells the name, since one `struct /// name;` in a macro body declares a type per invocation; /// - every workspace glob import is a `crate`, `self` or `super` path /// through declared workspace modules, so no glob brings in an outside /// item (directly or through a renamed or re-exported outside module); /// - the name is not a prelude value, and no workspace file uses `include!` /// or `#[path]` (either spelling, including raw `#[r#path]`), which /// splice in text the scan never reads. /// /// Items a derive or attribute proc macro emits stay invisible, as for /// every other pin rule. An item- or statement-position macro whose /// definition is not in the indexed workspace text may emit unread items, /// so the workspace-wide scan refuses (#7160). pub(super) fn unit_struct_value( name: &str, test_file: &Path, index: &RustIndex, syntax: &OwnerPinSyntax, ) -> bool { // A prelude value (`None`, `Some`, `Ok`, `Err`) is in scope without any // import, so the struct may not be the item the test names. if PRELUDE_VALUES.contains(&name) { return false; } // #7172: the workspace-wide scans ran once per call; they now come // from the run-scoped memo, and only the per-name spelling checks run. let unit_struct = syntax.unit_struct_facts(index); if unit_struct.refused() { return false; } let mut declared_in_test_file = 0usize; for (file, facts) in index.files().iter() { // Masking only blanks comments and strings, so a whole word in the // masked source is spelled in the raw source too: skipping files // without the name cannot skip a spelling the scan would refuse. if !facts.source.contains(name) { continue; } let masked = mask_comments_and_strings(&facts.source); // One spelling in a macro body declares a struct per invocation, // so no file that defines a macro may spell the name. if unit_struct.macro_files.contains(file) && !whole_word_offsets(&masked, name).is_empty() { return false; } for offset in whole_word_offsets(&masked, name) { let before = masked[..offset].trim_end(); let after = masked[offset + name.len()..].trim_start(); let word_start = before .char_indices() .rev() .find(|&(_, character)| { !(character.is_ascii_alphanumeric() || character == '_' || !character.is_ascii()) }) .map_or(0, |(position, character)| position + character.len_utf8()); let word = &before[word_start..]; let item_end = after.starts_with('{') || starts_with_word(after, "where"); let inert = match word { "struct" if after.starts_with(';') && file.as_path() == test_file => { declared_in_test_file += 1; true } "impl" | "for" => item_end, "" => { (after.starts_with('.') && !after.starts_with("..")) || (before.ends_with('=') && !before.ends_with("==") && !before.ends_with("!=") && !before.ends_with("<=") && !before.ends_with(">=") && after.starts_with(';')) } _ => false, }; if !inert { return false; } } } declared_in_test_file == 1 } /// Whether bare `name` in `test_file` is a variant of the one workspace enum /// `enum_name`, brought in by exactly one non-aliased `use` of that enum's /// glob or of the variant itself (#9676). Fail-closed: a prelude spelling, /// another import of `name`, a same-named local item or a `macro_rules!` in /// the file, or an enum that is not the single declaration all refuse. pub(super) fn imported_enum_variant_value( name: &str, enum_name: &str, test_file: &Path, index: &RustIndex, ) -> bool { if name.is_empty() || enum_name.is_empty() || PRELUDE_VALUES.contains(&name) { return false; } let declaring_path = index.call_identity_memos.sole_type_declarer(enum_name, || { let mut matching = index.files().iter().filter(|(_, facts)| { facts.source.contains(enum_name) && declares_type(&mask_comments_and_strings(&facts.source), enum_name) }); let first = matching.next()?; matching.next().is_none().then(|| first.0.clone()) }); let Some(declaring) = declaring_path.and_then(|path| index.files().get(&path)) else { return false; }; // Equality facts are not needed (and can be unavailable for an enum with // exotic derives): only the single non-test `enum` declaration's variants. let Some(parse) = parse_clean_source_file(&declaring.source) else { return false; }; let mut enums = parse .tree() .syntax() .descendants() .filter_map(ast::Enum::cast) .filter(|item| item.name().is_some_and(|ident| ident.text() == enum_name)); let (Some(item), None) = (enums.next(), enums.next()) else { return false; }; if !item.variant_list().is_some_and(|list| { list.variants().any(|variant| { variant.name().is_some_and(|ident| ident.text() == name) && variant.field_list().is_none() }) }) { return false; } let Some(file) = index.files().get(test_file) else { return false; }; let masked = mask_comments_and_strings(&file.source); if masked.contains("macro_rules") { return false; } let enum_glob = format!("{enum_name}::*"); let enum_variant = format!("{enum_name}::{name}"); let rooted = |path: &str, tail: &str| { path.strip_suffix(tail).is_some_and(|prefix| { prefix.is_empty() || prefix.strip_suffix("::").is_some_and(|prefix| { prefix .split("::") .all(|segment| matches!(segment, "self" | "super" | "crate")) }) }) }; let mut admitted = 0usize; for import in flattened_use_paths(&file.source) { let last = import.path.rsplit("::").next().unwrap_or(""); let binds_name = last == name || import.alias.as_deref() == Some(name); if import.alias.is_none() && (rooted(&import.path, &enum_glob) || rooted(&import.path, &enum_variant)) { admitted += 1; } else if binds_name || import.path.ends_with("::*") || import.path == "*" { // Another binding of the name, or any other glob that could // supply it: the use items are read file-wide rather than by the // test's lexical scope, so a second glob keeps the spelling // ambiguous (e.g. `std::cmp::Ordering::*` beside a sibling // module's `E::*`). return false; } } if admitted != 1 { return false; } // A same-named item (other than the enum's own variant list) would shadow // the glob; refuse any item keyword directly before the spelling. !whole_word_offsets(&masked, name).into_iter().any(|offset| { // A parameter or closure parameter of the same name shadows the // variant: `name:` (a single colon) or a leading `|` binds it. let after = masked[offset + name.len()..].trim_start(); if (after.starts_with(':') && !after.starts_with("::")) || masked[..offset].trim_end().ends_with('|') { return true; } let before = masked[..offset].trim_end(); [ "const", "static", "fn", "struct", "union", "type", "mod", "trait", "enum", "let", "mut", ] .iter() .any(|keyword| { before.ends_with(keyword) && before[..before.len() - keyword.len()] .chars() .next_back() .is_none_or(|ch| !(ch.is_ascii_alphanumeric() || ch == '_')) }) }) } /// The prelude's value-namespace names a unit struct could share. const PRELUDE_VALUES: &[&str] = &["None", "Some", "Ok", "Err"]; /// `text` without the characters rustc lexes as whitespace (Unicode /// `Pattern_White_Space`: `char::is_whitespace` plus the left-to-right and /// right-to-left marks). fn without_rust_whitespace(text: &str) -> String { text.chars() .filter(|character| { !(character.is_whitespace() || matches!(character, '\u{200E}' | '\u{200F}')) }) .collect() } /// Every name a workspace file declares with `mod`, less every name a `use` /// or `extern crate` anywhere in the workspace may introduce. Names are not /// resolved per crate or scope, so `use std::u32 as nums;` in one crate and /// `mod nums` in another must not let `use crate::nums::*` pass (#7098 /// review): a segment that some import binds is never treated as a /// workspace module. fn workspace_module_names(index: &RustIndex) -> BTreeSet { let mut modules = BTreeSet::new(); let mut imported = BTreeSet::new(); for (_, facts) in index.files().iter() { let masked = mask_comments_and_strings(&facts.source); for offset in whole_word_offsets(&masked, "mod") { let rest = masked[offset + "mod".len()..].trim_start(); let end = rest .find(|character: char| !(character.is_ascii_alphanumeric() || character == '_')) .unwrap_or(rest.len()); if end > 0 { modules.insert(rest[..end].to_string()); } } for keyword in ["use", "extern"] { for offset in whole_word_offsets(&masked, keyword) { let rest = &masked[offset + keyword.len()..]; let Some(end) = rest.find(';') else { continue; }; imported.extend(import_bound_names(&rest[..end])); } } } modules.retain(|module| !imported.contains(module)); modules } /// Every identifier in an import statement that is not followed by `::` /// (Rust whitespace allowed between): each name the statement may bind, /// whether a leaf, a group member or an `as` rename, plus harmless keywords. fn import_bound_names(statement: &str) -> Vec { let mut names = Vec::new(); let mut position = 0; while position < statement.len() { let rest = &statement[position..]; let length = rest .find(|character: char| !(character.is_alphanumeric() || character == '_')) .unwrap_or(rest.len()); if length == 0 { position += rest.chars().next().map_or(1, char::len_utf8); continue; } let word = &rest[..length]; let next = rest[length..].trim_start_matches(|character: char| { character.is_whitespace() || matches!(character, '\u{200E}' | '\u{200F}') }); if !next.starts_with("::") { names.push(word.to_string()); } position += length; } names } /// Whether `masked` holds a glob `use` that may reach items outside the /// workspace's own modules. Only a plain `crate::`, `self::` or `super::` /// path whose further segments are `super` or declared module names /// passes. A foreign root, a renamed or re-exported outside module /// (`use std::u32 as nums;` then `use crate::nums::*`), an enum's variants /// and a glob inside a `{..}` group all refuse. fn glob_reaches_outside(masked: &str, modules: &BTreeSet) -> bool { whole_word_offsets(masked, "use").into_iter().any(|start| { let rest = &masked[start + "use".len()..]; let Some(end) = rest.find(';') else { return false; }; let statement = without_rust_whitespace(&rest[..end]); if !statement.contains('*') { return false; } let Some(path) = statement.trim_start_matches("::").strip_suffix("::*") else { return true; }; let mut segments = path.split("::"); let rooted = segments .next() .is_some_and(|root| matches!(root, "crate" | "self" | "super")); !(rooted && segments.all(|segment| segment == "super" || modules.contains(segment))) }) } /// The initializer without a trailing `?`, `.unwrap()` or `.expect(..)`, /// and whether one was there. fn strip_unwrap(initializer: &str) -> (&str, bool) { let initializer = initializer.trim(); if let Some(rest) = initializer .strip_suffix('?') .or_else(|| initializer.strip_suffix(".unwrap()")) { return (rest.trim_end(), true); } let masked = mask_comments_and_strings(initializer); if masked.ends_with(')') && let Some(position) = masked.rfind(".expect(") && matching_close(&masked, position + ".expect".len(), b'(', b')') == Some(masked.len() - 1) { return (initializer[..position].trim_end(), true); } (initializer, false) } /// Whether `type_name::constructor(..)` (unwrapped when `unwrapped`) /// evaluates to a `type_name`. `default` and `from` return `Self` by their /// traits' signatures and `try_from` returns `Result`; any other /// associated function must be the type's one inherent definition of that /// name, returning `Self` (or the type) directly, or inside /// `Result`/`Option` when unwrapped. fn constructor_returns_self( type_name: &str, constructor: &str, unwrapped: bool, index: &RustIndex, ) -> bool { match constructor { "default" | "from" => return !unwrapped, "try_from" => return unwrapped, _ => {} } let mut definitions = index.functions().iter().filter(|function| { function.name == constructor && !function.item.has_self_param && matches!( &function.item.container, FunctionContainer::Inherent { self_ty } if path_base_name(self_ty) == Some(type_name) ) }); let (Some(definition), None) = (definitions.next(), definitions.next()) else { return false; }; let Some(returned) = declared_return_type(&definition.body) else { return false; }; let names_type = |text: &str| { let text = text.trim(); text == "Self" || path_base_name(text) == Some(type_name) }; if unwrapped { ["Result<", "Option<"].iter().any(|wrapper| { returned .strip_prefix(wrapper) .and_then(|inner| inner.strip_suffix('>')) .is_some_and(|inner| names_type(inner.split(',').next().unwrap_or(inner))) }) } else { names_type(&returned) } } /// The return type a `fn` definition declares, whitespace-collapsed. pub(super) fn declared_return_type(definition: &str) -> Option { let masked = mask_comments_and_strings(definition); let params = masked.find('(')?; let params_close = matching_close(&masked, params, b'(', b')')?; let body_open = params_close + masked[params_close..].find('{')?; let signature = collapse_whitespace(&definition[params_close + 1..body_open]); let signature = signature.split(" where ").next().unwrap_or(&signature); Some(signature.trim().strip_prefix("->")?.trim().to_string()) } fn named_or_slice( type_text: &str, test: &TestSummary, test_source: Option<&str>, index: &RustIndex, imports_foreign: ForeignImport<'_>, owner: OwnerScope<'_>, ) -> Option { if is_byte_slice_type(type_text) { return Some(ReceiverType::ByteSlice); } let base = path_base_name(type_text)?; if !base.starts_with(|character: char| character.is_ascii_uppercase()) { return None; } // A test file that imports the name from outside the workspace, renames // another item to it, aliases it, or declares it in the test's own // module scope — in its own file (#6905) or in an out-of-line parent // module (#6950) — binds a different type than the workspace declaration. let source = test_source?; // `r#Window` denotes `Window`: a raw-identifier alias rebinds the name // too (#7067, mirroring the #7051 parent-root check). let raw = format!("r#{base}"); if imports_foreign(&test.file, base) || file_renames_to(source, base) || file_renames_to(source, raw.as_str()) || file_aliases_type(source, base) || test_module_shadows_type(test, source, base, Some(owner), index) || parent_chain_shadows_type(test, base, owner, index) { return None; } Some(ReceiverType::Named(base.to_string())) } /// #9638: the workspace type name a test's receiver expression is established to /// be a value of, by the owner-pin receiver reader: a plain identifier the /// test binds only by `let [mut] x [: T] = ;`, or an inline /// constructor expression (`Pool::default()`, `Pool { .. }`). `None` when the /// type is not established (a std or external type, a rebound name, a /// foreign or aliased import of the type, a non-`Self` constructor), so the /// caller must fail closed. pub(in crate::analysis) fn test_receiver_named_type( test: &TestSummary, receiver: &str, owner: OwnerScope<'_>, index: &RustIndex, ) -> Option { let files = index.files(); let test_source: Option<&str> = files .get(&test.file) .map(|facts| facts.data().source.as_ref()); let imports_foreign = |_: &Path, name: &str| { test_source.is_none_or(|source| { super::reveal::file_imports_foreign_callee_name(source, name, &index.package_names) }) }; let syntax = OwnerPinSyntax::default(); let receiver = receiver.trim(); let typed = if is_plain_identifier(receiver) { test_receiver_type( test, receiver, test_source, index, &imports_foreign, owner, &syntax, ) } else { binding_type( &format!("= {receiver}"), test, test_source, index, &imports_foreign, owner, &syntax, ) }; match typed? { // The receiver reader resolves a bare type name. Two workspace types // (or a type and an alias) of one name, in any module or file, make // the name ambiguous (`alt::Pool` imported over the real `Pool`), so // identity is not established. ReceiverType::Named(name) if workspace_type_name_count(&name, index) == 1 => Some(name), ReceiverType::Named(_) | ReceiverType::ByteSlice => None, } } /// How many `struct`, `enum`, `union` or `type` items named `name` the /// workspace declares, across every module and file. The per-name table is /// built once per index (every file masked once), then looked up. pub(super) fn workspace_type_name_count(name: &str, index: &RustIndex) -> usize { index .call_identity_memos .type_name_counts(|| { let mut counts: BTreeMap = BTreeMap::new(); for facts in index.files().values() { let masked = mask_comments_and_strings(&facts.source); for keyword in ["struct", "enum", "union", "type"] { for offset in whole_word_offsets(&masked, keyword) { let rest = masked[offset + keyword.len()..].trim_start(); let end = rest .find(|ch: char| !(ch.is_ascii_alphanumeric() || ch == '_')) .unwrap_or(rest.len()); if end > 0 { *counts.entry(rest[..end].to_string()).or_default() += 1; } } } } counts }) .get(name) .copied() .unwrap_or(0) } /// The owner's identity, for the #6957 shadow exemption: the owner's own /// scope holds the production declaration, so it is not a test-local /// shadow. The single-file check resolves the scope in the test file's own /// parse only ([`OwnerScope::in_file`]); the parent-chain walk resolves it /// in whichever chain file holds the owner (#6950). #[derive(Clone, Copy)] pub(in crate::analysis) struct OwnerScope<'a> { name: &'a str, start_line: usize, file: &'a Path, } impl<'a> OwnerScope<'a> { /// The owner's total identity. pub(in crate::analysis) fn new(name: &'a str, start_line: usize, file: &'a Path) -> Self { Self { name, start_line, file, } } /// This scope when the owner lives in `test_file`, or `None` when a /// cross-file owner keeps the fail-closed single-file check. /// Related-test reach reuses the #6957 exemption through this (#6951). pub(in crate::analysis) fn in_file(&self, test_file: &Path) -> Option { (test_file == self.file).then_some(*self) } } /// Whether the test's own inline-module scope declares the receiver type /// name (#6905): a `struct`, `enum`, `union` or `type` alias that is a /// direct item of an enclosing `mod` shadows the production type for the /// test, so a binding of that name names the test-local type, not the /// changed owner, and the pin is refused. Only direct items of enclosing /// inline modules count: a same-name declaration in a sibling module or at /// the file root (the production declaration itself, for same-file tests) /// does not shadow the test's view. Nor does one in the owner's own /// enclosing module (#6957): when the production declaration sits in an /// enclosing non-root module, that module is the owner's scope, not a /// shadow. A same-name declaration in any other enclosing module — the /// test's own `mod tests` included — still refuses. An explicit import /// naming the type in an inner scope would disambiguate, but this stays /// lexical and fails closed. A file that textually declares the name /// nowhere needs no parse; one that fails to parse fails closed. /// /// Shared with related-test classification (#6951): a shadowed receiver /// type also refuses `direct_owner_call` reach credit, for the same /// entity-identity reason. pub(in crate::analysis) fn test_module_shadows_type( test: &TestSummary, source: &str, base: &str, owner: Option>, index: &RustIndex, ) -> bool { test_module_shadows_item(test, source, base, owner, ShadowKind::Type, index) } /// Whether the test's own inline-module scope declares a `trait` named like /// the owner's trait (#7053): inside that module `Render::render(..)` and /// `.render()` name the test-local trait and its impls, so a call there is /// no evidence about the production `impl Render for T`. Same scope rules /// as [`test_module_shadows_type`]. pub(in crate::analysis) fn test_module_shadows_trait( test: &TestSummary, source: &str, trait_name: &str, owner: Option>, index: &RustIndex, ) -> bool { test_module_shadows_item(test, source, trait_name, owner, ShadowKind::Trait, index) } /// The kind of declaration a test-module shadow check looks for. #[derive(Clone, Copy, PartialEq, Eq)] enum ShadowKind { Type, Trait, } fn test_module_shadows_item( test: &TestSummary, source: &str, base: &str, owner: Option>, kind: ShadowKind, index: &RustIndex, ) -> bool { // Every shadow below needs `base` spelled in `source`: a declaration // (`declares_type`/`declares_trait` over the masked copy, which keeps the // code bytes in place), a `type` alias, or the raw `r#base` spelling all // contain it. A file that never spells it is answered without fetching // (and possibly re-parsing) the file's snapshot, which dominated probe // classification on large test files (#12947). if !source.contains(base) { return false; } // A caller supplying different source bytes must never borrow the indexed // snapshot. Standalone/macro-shaped inputs retain the same fallback logic. let snapshot = index .files() .get(&test.file) .filter(|facts| std::ptr::eq(facts.source.as_ref(), source)) .and_then(|_| index.source_syntax.get(index, &test.file)) .unwrap_or_else(|| Arc::new(crate::analysis::syntax::SourceSnapshot::new(source))); let key = ( test.name.clone(), test.start_line, test.end_line, base.to_string(), kind == ShadowKind::Trait, owner.map(|o| (o.file.to_path_buf(), o.name.to_string(), o.start_line)), ); snapshot.shadow_answer(key, || { // The snapshot is built from `source` (or is the index's snapshot of // those same bytes), so its masked copy is the same text; mask once // per file instead of once per (test, owner, name) key. let masked = snapshot.masked_source(|| mask_comments_and_strings(source)); let raw = format!("r#{base}"); let declared = match kind { ShadowKind::Type => declares_type(masked, base) || file_aliases_type(source, base), ShadowKind::Trait => declares_trait(masked, base), }; if !declared && !masked.contains(raw.as_str()) { return false; } let Some(scopes) = snapshot.lexical_items() else { return true; }; let Some(tree) = snapshot.tree() else { return true; }; let root = tree.syntax(); let owner_module = owner.and_then(|o| o.in_file(&test.file)).and_then(|o| { let name = o.name.strip_prefix("r#").unwrap_or(o.name); let mut found = scopes.functions.iter().filter(|f| { f.name == name && f.start_line <= o.start_line && o.start_line <= f.end_line }); let first = found.next()?; found .next() .is_none() .then(|| first.modules.first().copied()) .flatten() }); let counts = |range| owner_module != Some(range); let names = |module: ast::Module| { module.item_list().is_some_and(|items| { items .items() .any(|item| module_item_names(&item, base, kind)) }) }; let name = test.name.strip_prefix("r#").unwrap_or(&test.name); let mut found = scopes .functions .iter() .filter(|f| { f.name == name && f.start_line <= test.end_line && test.start_line <= f.end_line }) .peekable(); // Keep all ambiguous same-line matches, never choose the first one. if found.peek().is_some() { return found.any(|f| { scopes.modules.iter().any(|m| { f.modules.contains(&m.range) && counts(m.range) && names(m.item.to_node(root)) }) }); } // Macro-shaped tests retain inclusive-line fallback, including end lines. scopes.modules.iter().any(|m| { m.start_line <= test.start_line && test.end_line <= m.end_line && counts(m.range) && names(m.item.to_node(root)) }) }) } /// Whether an out-of-line parent module of the test file declares the /// receiver type name (#6950): the parent chain through out-of-line `mod` /// declarations (the test file's composed role provenance) is the test's /// enclosing module scope beyond its own file. A `struct`, `enum`, `union` /// or `type` alias that is a direct item of a parent file's root shadows /// the production type for the test exactly as an enclosing inline /// declaration does (#6905), as does a root-level `use ... as ` /// rebinding, so a binding of that name names the test-local type and /// the pin is refused. /// /// Only parent roots count: the module-declaration producer emits /// top-level declarations only, so a recorded edge's parent scope is the /// file root, and a sibling inline module is out of scope by the same /// precision rule as same-file siblings. The test file's own root stays /// exempt (the #6905 single-file behavior, via /// [`test_module_shadows_type`]); each parent root counts unless it is the /// owner's own scope — the file holding the owner with the owner at its /// root (the transposed #6957 exemption). /// /// Shared with related-test classification like [`test_module_shadows_type`]: /// a shadowed receiver also refuses `direct_owner_call` reach credit. /// Fail-closed throughout: an unresolved chain /// (`rust_module_ambiguous_parent` and its siblings), an `include!` edge /// (whose scope needs site localization this lexical check does not do), a /// missing parent file, and an unparseable parent that textually declares /// the name all refuse rather than guess. A parent that textually declares /// the name nowhere needs no parse. pub(in crate::analysis) fn parent_chain_shadows_type( test: &TestSummary, base: &str, owner: OwnerScope<'_>, index: &RustIndex, ) -> bool { parent_chain_shadows_item(test, base, owner, index, ShadowKind::Type) } /// [`parent_chain_shadows_type`] for the owner's trait (#7087): a `trait` /// item, or a macro whose own text declares one, at the root of an /// out-of-line parent module of the test file names the test-local trait, /// so `Trait::method(..)` and `.method()` there never reach the production /// `impl Trait for T`. Same chain, fail-closed and owner-scope rules as the /// type check; declarations only, like [`test_module_shadows_trait`]. pub(in crate::analysis) fn parent_chain_shadows_trait( test: &TestSummary, trait_name: &str, owner: OwnerScope<'_>, index: &RustIndex, ) -> bool { parent_chain_shadows_item(test, trait_name, owner, index, ShadowKind::Trait) } fn parent_chain_shadows_item( test: &TestSummary, base: &str, owner: OwnerScope<'_>, index: &RustIndex, kind: ShadowKind, ) -> bool { let Some(facts) = index.files().get(&test.file) else { return false; }; let chain = &facts.role_provenance; let owner_ancestors = match kind { ShadowKind::Type => Vec::new(), ShadowKind::Trait => owner_module_ancestors(owner, index), }; // The reason leads: an immediately ambiguous parent composes to empty // edges with the reason set, which is unresolved, not standalone. if chain.earliest_unresolved_reason.is_some() { return true; } if chain.edges.is_empty() { return false; } chain.edges.iter().any(|edge| { if edge.kind != SourceRoleProvenanceEdgeKind::Module { return true; } let Some(parent) = index.files().get(&edge.parent) else { return true; }; parent_root_shadows_item( index, &parent.source, &edge.parent, base, owner, kind, &owner_ancestors, ) }) } /// Whether one parent file's root declares the receiver type name: the /// per-edge step of [`parent_chain_shadows_type`] and /// [`parent_chain_shadows_trait`]. A root-level /// `use ... as ` rebinds the name to a different type and shadows /// too; a plain root-level `use` may re-export production, so only /// renames refuse. The owner's own root (the file holding a root-level /// owner) is the production declaration's scope, never a shadow; every /// other declaring root refuses. fn parent_root_shadows_item( index: &RustIndex, parent_source: &str, parent_file: &Path, base: &str, owner: OwnerScope<'_>, kind: ShadowKind, owner_ancestors: &[PathBuf], ) -> bool { // A parent that never mentions the name cannot declare, alias or rename // it, so it is answered from the text before a snapshot (and its parse) // is created for a file nothing else needed (#10809). if !parent_source.contains(base) { return false; } // The mask, the parse and the root-item scan depend only on the parent // file and the name, and every related test of every probe asks about the // same few parents, so they are answered once per file snapshot (#10809). // The owner exemptions below differ per call and stay out of the memo. let snapshot = index.source_syntax.get(index, parent_file); let candidate = || { let masked_here; let masked: &str = match snapshot.as_deref() { Some(snapshot) => snapshot.masked_source(|| mask_comments_and_strings(parent_source)), None => { masked_here = mask_comments_and_strings(parent_source); &masked_here } }; // `r#Window` denotes `Window`: a raw-identifier declaration shadows too. let raw = format!("r#{base}"); // Aliases and renames rebind a type name only; a trait is shadowed by a // declaration (#7087), matching the in-file trait check (#7053). let declared = match kind { ShadowKind::Type => { declares_type(masked, base) || file_aliases_type(parent_source, base) || file_renames_to(parent_source, base) } ShadowKind::Trait => declares_trait(masked, base), }; if !declared && !masked.contains(raw.as_str()) { return RootShadow::NotShadowing; } let Some(root) = parent_root_node(snapshot.as_deref(), parent_source) else { return RootShadow::Unparseable; }; let root_items: Vec = root.children().filter_map(ast::Item::cast).collect(); if !root_items .iter() .any(|item| module_item_names(item, base, kind)) && !root_items.iter().any(|item| { if kind == ShadowKind::Trait || !matches!(item, ast::Item::Use(_)) { return false; } let text = item.syntax().text().to_string(); // `r#Window` denotes `Window`: a raw-identifier alias rebinds // the name too. file_renames_to(&text, base) || file_renames_to(&text, raw.as_str()) }) { return RootShadow::NotShadowing; } RootShadow::Declared }; let answer = match snapshot.as_deref() { Some(snapshot) => snapshot.root_shadow(base, kind == ShadowKind::Trait, candidate), None => candidate(), }; match answer { RootShadow::NotShadowing => return false, RootShadow::Unparseable => return true, RootShadow::Declared => {} } if owner.file == parent_file && parent_root_node(snapshot.as_deref(), parent_source) .is_some_and(|root| owner_at_file_root(&root, parent_source, owner)) { return false; } // A trait is commonly declared in an ancestor file of the file holding // its impls (#7111): a declaring root on the owner's own module chain is // the production declaration, not a shadow. if owner_ancestors .iter() .any(|ancestor| ancestor == parent_file) { return false; } true } /// The root of a parent file's clean parse: the snapshot's shared green tree /// when the file is indexed, a fresh parse otherwise. `None` when the file /// does not parse cleanly. fn parent_root_node( snapshot: Option<&crate::analysis::syntax::SourceSnapshot>, source: &str, ) -> Option { match snapshot { Some(snapshot) => snapshot.tree().map(|tree| tree.syntax().clone()), None => parse_clean_source_file(source).map(|parse| parse.tree().syntax().clone()), } } /// The files whose module scope encloses the owner's file: the file itself /// (its root encloses every inline module in it) and the parents on its /// composed module chain. Empty when the owner file is not indexed, which /// keeps the fail-closed shadow check. fn owner_module_ancestors(owner: OwnerScope<'_>, index: &RustIndex) -> Vec { let Some(facts) = index.files().get(owner.file) else { return Vec::new(); }; std::iter::once(owner.file.to_path_buf()) .chain( facts .role_provenance .edges .iter() .filter(|edge| edge.kind == SourceRoleProvenanceEdgeKind::Module) .map(|edge| edge.parent.clone()), ) .collect() } /// Whether the owner fn resolves in `source` at the file root: exactly one /// same-name `fn` spans the owner's start line, with no enclosing inline /// module (#6950). A parent-file root holding both the receiver type and a /// root-level owner is the production scope, not a shadow; an unresolvable /// owner resolves to no scope and keeps the fail-closed check. fn owner_at_file_root(root: &SyntaxNode, source: &str, owner: OwnerScope<'_>) -> bool { resolve_owner_fn(root, source, owner).is_some_and(|found| { found .syntax() .ancestors() .filter_map(ast::Module::cast) .next() .is_none() }) } /// The owner's `fn` node in this file's parse: exactly one same-name `fn` /// spanning the owner's start line. Byte-exact ancestry, not line spans, /// decides, so a same-line sibling module is never the owner's scope; a /// nested same-name `fn` sharing the owner's start line resolves to no /// scope rather than the wrong one. fn resolve_owner_fn(root: &SyntaxNode, source: &str, owner: OwnerScope<'_>) -> Option { // 1-based file lines, matching `FunctionSummary`. let line_of = |offset: u32| source[..offset as usize].matches('\n').count() + 1; let name = owner.name.strip_prefix("r#").unwrap_or(owner.name); let mut owners = root.descendants().filter_map(ast::Fn::cast).filter(|func| { func.name().is_some_and(|func_name| { let text = func_name.text().to_string(); text.strip_prefix("r#").unwrap_or(&text) == name }) && { let range = func.syntax().text_range(); let start: u32 = range.start().into(); let end: u32 = range.end().into(); line_of(start) <= owner.start_line && owner.start_line <= line_of(end) } }); let found = owners.next()?; owners.next().is_none().then_some(found) } /// Whether a direct module item declares `base` as the given kind: a type /// (see [`module_item_names_type`]) or, for [`ShadowKind::Trait`] (#7053), a /// `trait` item or a macro whose own text declares one. fn module_item_names(item: &ast::Item, base: &str, kind: ShadowKind) -> bool { if kind == ShadowKind::Type { return module_item_names_type(item, base); } let named = match item { ast::Item::Trait(item) => item.name(), _ => None, }; if named.is_some_and(|name| { let text = name.text().to_string(); text.strip_prefix("r#").unwrap_or(&text) == base }) { return true; } // A macro can declare the trait; its text decides, as for types. matches!( item, ast::Item::MacroRules(_) | ast::Item::MacroDef(_) | ast::Item::MacroCall(_) ) && { let text = mask_comments_and_strings(&item.syntax().text().to_string()); declares_trait(&text, base) || declares_trait(&text, &format!("r#{base}")) } } /// Whether a direct module item declares the type name `base` (`r#Window` /// denotes `Window`). A macro definition or invocation may emit the type /// (#6948 review): the parsed item is the macro, not the struct, enum, /// union or alias it generates, so a lexical declaration of the name inside /// the macro's own text fails closed. fn module_item_names_type(item: &ast::Item, base: &str) -> bool { let name = match item { ast::Item::Struct(item) => item.name(), ast::Item::Enum(item) => item.name(), ast::Item::Union(item) => item.name(), ast::Item::TypeAlias(item) => item.name(), _ => None, }; if name.is_some_and(|name| { let text = name.text().to_string(); text.strip_prefix("r#").unwrap_or(&text) == base }) { return true; } if !matches!( item, ast::Item::MacroRules(_) | ast::Item::MacroDef(_) | ast::Item::MacroCall(_) ) { return false; } let text = mask_comments_and_strings(&item.syntax().text().to_string()); declares_type(&text, base) || declares_type(&text, &format!("r#{base}")) || file_aliases_type(&text, base) } /// A trait's methods are callable with method syntax only while the trait /// is in scope: the test's file imports it by name from the workspace, or /// declares it. fn trait_in_scope(source: &str, trait_name: &str, index: &RustIndex) -> bool { if file_imports_foreign_callee_name(source, trait_name, &index.package_names) { return std_operator_trait_imported(source, trait_name, index); } if file_imports_own_item(source, trait_name, &index.package_names) { return true; } let masked = mask_comments_and_strings(source); whole_word_offsets(&masked, "trait") .into_iter() .any(|offset| { masked[offset + "trait".len()..] .trim_start() .strip_prefix(trait_name) .is_some_and(|after| { !after.starts_with(|character: char| { character.is_ascii_alphanumeric() || character == '_' }) }) }) } /// #12796: the standard operator trait `trait_name` (`Add`, `Sub`, ..) is /// the one the file's single explicit import binds: exactly one `use` names it, /// through `std::ops::` or `core::ops::` with no rename, and no workspace file /// declares a trait of that name. An explicit import outranks globs, so no /// other `Add` can reach the file's scopes, and a method call `x.add(y)` /// then names this trait's method. fn std_operator_trait_imported(source: &str, trait_name: &str, index: &RustIndex) -> bool { const OPERATOR_TRAITS: &[&str] = &[ "Add", "Sub", "Mul", "Div", "Rem", "BitAnd", "BitOr", "BitXor", "Shl", "Shr", "Neg", "Not", ]; if !OPERATOR_TRAITS.contains(&trait_name) { return false; } let declared_in_workspace = index.files().values().any(|facts| { let masked = mask_comments_and_strings(&facts.source); whole_word_offsets(&masked, "trait") .into_iter() .any(|offset| { starts_with_word(masked[offset + "trait".len()..].trim_start(), trait_name) }) }); if declared_in_workspace { return false; } let paths = flattened_use_paths(source); let mut binding = paths.iter().filter(|use_path| { let last = use_path.path.rsplit("::").next(); last == Some(trait_name) || use_path.alias.as_deref() == Some(trait_name) }); let (Some(found), None) = (binding.next(), binding.next()) else { return false; }; found.alias.is_none() && (found.path == format!("std::ops::{trait_name}") || found.path == format!("core::ops::{trait_name}")) } fn test_body_shadows_owner(test: &TestSummary, owner: &str) -> bool { if fact_body_defines_callee_fn(&test.nested_fn_names, owner) || fact_body_let_shadow_line(&test.let_bindings, owner).is_some() { return true; } let masked = mask_comments_and_strings(&test.body); test_body_defines_callee_fn(&masked, owner) || test_body_let_shadow_line(&masked, owner).is_some() } fn is_byte_slice_type(text: &str) -> bool { let compact: String = text.split_whitespace().collect(); let Some(rest) = compact.strip_prefix('&') else { return false; }; let rest = match rest.strip_prefix('\'') { Some(lifetime) => lifetime.trim_start_matches(|character: char| { character.is_ascii_alphanumeric() || character == '_' }), None => rest, }; rest == "[u8]" } /// `&[..][..]` or `&b".."[..]`: a byte-slice expression. fn is_byte_slice_expression(initializer: &str) -> bool { let Some(rest) = initializer.trim().strip_prefix('&') else { return false; }; let Some(array) = rest.trim_end().strip_suffix("[..]") else { return false; }; let array = array.trim(); if let Some(bytes) = array.strip_prefix("b\"") { return bytes.ends_with('"'); } let masked = mask_comments_and_strings(array); masked.starts_with('[') && matching_close(&masked, 0, b'[', b']').is_some_and(|close| close + 1 == masked.len()) } /// The last `::` segment of a path, without generic arguments. fn path_base_name(path: &str) -> Option<&str> { let path = path.trim(); let without_generics = path.split('<').next()?.trim(); let base = without_generics.rsplit("::").next()?.trim(); is_plain_identifier(base).then_some(base) } fn is_plain_identifier(text: &str) -> bool { text.starts_with(|character: char| character.is_ascii_alphabetic() || character == '_') && text .chars() .all(|character| character.is_ascii_alphanumeric() || character == '_') } fn is_ident_byte(byte: u8) -> bool { byte.is_ascii_alphanumeric() || byte == b'_' } pub(super) fn whole_word_offsets(text: &str, word: &str) -> Vec { let bytes = text.as_bytes(); let mut offsets = Vec::new(); let mut search = 0usize; while let Some(relative) = text[search..].find(word) { let offset = search + relative; let end = offset + word.len(); let before_ok = offset == 0 || !is_ident_byte(bytes[offset - 1]); let after_ok = end >= bytes.len() || !is_ident_byte(bytes[end]); if before_ok && after_ok { offsets.push(offset); } search = end; } offsets } /// Offset of the first `;` outside brackets. fn top_level_semicolon(masked: &str) -> Option { let mut depth = 0usize; for (offset, byte) in masked.bytes().enumerate() { match byte { b'(' | b'[' | b'{' => depth += 1, b')' | b']' | b'}' => depth = depth.checked_sub(1)?, b';' if depth == 0 => return Some(offset), _ => {} } } None } /// The invocation identity that needs return/error matches! execution admission. fn matches_return_assertion(family: &ProbeFamily, assertion: &OracleFact) -> bool { matches!(family, ProbeFamily::ReturnValue | ProbeFamily::ErrorPath) && OwnerPinSyntax::assertion_macro_name(&assertion.text).as_deref() == Some("assert") && macro_invocations(&mask_comments_and_strings(&assertion.text)) .iter() .any(|(name, _)| *name == "matches") } /// A bounded exception to the expected-panic refusal, not a general panic /// evaluator. Reuse owner identity and Drop authority; only a direct unit /// error return, literal string inputs and an unguarded unit error pattern /// leave the assertion as the possible source of the expected panic. fn bounded_matches_panic_owner( probe: &Probe, test: &TestSummary, assertion: &OracleFact, index: &RustIndex, syntax: &OwnerPinSyntax, ) -> Option<()> { matches_panic_diagnostic(test, assertion)?; let owner_id = probe.owner.as_ref()?; let mut owners = index .functions() .iter() .filter(|owner| &owner.id == owner_id); let (Some(owner), None) = (owners.next(), owners.next()) else { return None; }; let pin = OwnerReturnPin::establish(probe, owner, index)?; let test_source = &index.files().get(&test.file)?.source; if pin.call.kind() != CallKind::Bare || !pin.bare_call_reaches_owner(test, test_source, index, syntax) || source_binds_value_name(&index.files().get(&owner.file)?.source, "Err") || source_binds_value_name(test_source, "Err") { return None; } let parse = parse_clean_source_file(&owner.body)?; let function = parse .tree() .syntax() .descendants() .find_map(ast::Fn::cast)?; if !owner.attrs.is_empty() || function.attrs().next().is_some() || function.async_token().is_some() || function.generic_param_list().is_some() { return None; } let list = function.body()?.stmt_list()?; if list.statements().next().is_some() { return None; } let ast::Expr::CallExpr(returned) = list.tail_expr()? else { return None; }; let ast::Expr::PathExpr(head) = returned.expr()? else { return None; }; if head.syntax().text() != "Err" { return None; } let mut values = returned.arg_list()?.args(); let (Some(ast::Expr::PathExpr(value)), None) = (values.next(), values.next()) else { return None; }; let value = value.syntax().text().to_string(); let (type_name, _) = local_variant_path(&value)?; if !owner_builds_declared_error_variant(&value, owner, index) || !syntax.matches_panic_expansions.admits(index, &type_name) || !super::element_field_pin::drop_is_plain(index, &type_name) { return None; } let condition = outer_assertion_condition(&assertion.text)?; let arguments = condition.trim().strip_prefix("matches!")?.trim(); let arguments = arguments.strip_prefix('(')?.strip_suffix(')')?; let operands = split_top_level_arguments(arguments)?; let [subject, pattern] = operands.as_slice() else { return None; }; let (pattern_type, pattern_variant) = error_variant_key(pattern)?; let compact_pattern: String = pattern.chars().filter(|ch| !ch.is_whitespace()).collect(); if compact_pattern != format!("Err({pattern_type}::{pattern_variant})") || pattern_type != type_name || !workspace_enum_declares_variant(&pattern_type, &pattern_variant, index) { return None; } if !matches!( owner_call_shape(subject, &owner.name), Some(CallShape::Bare) ) { return None; } let expression = parse_clean_source_file(&format!("fn t() {{ {subject} }}"))?; let call = expression .tree() .syntax() .descendants() .find_map(ast::CallExpr::cast)?; let arguments: Vec<_> = call.arg_list()?.args().collect(); let params: Vec<_> = function.param_list()?.params().collect(); if arguments.len() != params.len() || !arguments.iter().zip(params.iter()).all(|(argument, param)| { matches!(argument, ast::Expr::Literal(literal) if matches!(literal.kind(), ast::LiteralKind::String(_))) && param.ty().is_some_and(|ty| { ty.syntax().text().to_string().chars().filter(|ch| !ch.is_whitespace()).collect::() == "&str" }) }) { return None; } Some(()) } /// A named expected panic must accept the assertion's diagnostic. Otherwise /// both outcomes can fail the harness, despite opposite matches! values. /// Only a literal custom diagnostic without formatting is read here; implicit /// diagnostics and formatted messages remain outside this bounded admission. fn matches_panic_diagnostic(test: &TestSummary, assertion: &OracleFact) -> Option<()> { fn literal_string(text: &str) -> Option { let parsed = parse_clean_source_file(&format!("fn t() {{ {text} }}"))?; let function = parsed .tree() .syntax() .descendants() .find_map(ast::Fn::cast)?; let body = function.body()?.stmt_list()?; if body.statements().next().is_some() { return None; } let ast::Expr::Literal(literal) = body.tail_expr()? else { return None; }; let ast::LiteralKind::String(value) = literal.kind() else { return None; }; value.value().ok().map(|value| value.into_owned()) } for attribute in &test.attrs { let parsed = parse_clean_source_file(&format!("{attribute}\nfn t() {{}}"))?; let attr = parsed .tree() .syntax() .descendants() .find_map(ast::Attr::cast)?; if attr.simple_name().as_deref() != Some("should_panic") || attr.as_simple_atom().is_some() { continue; } let (_, expected) = attr.as_simple_call()?; let expected = expected.syntax().text().to_string(); let (key, value) = group_inner(&expected, '(', ')')?.trim().split_once('=')?; if key.trim() != "expected" { return None; } let expected = literal_string(value.trim().trim_end_matches(',').trim())?; let parsed = parse_clean_source_file(&format!("fn t() {{ {} }}", assertion.text))?; let call = parsed .tree() .syntax() .descendants() .find_map(ast::MacroCall::cast)?; let arguments = call.token_tree()?.syntax().text().to_string(); let arguments = split_top_level_arguments(group_inner(&arguments, '(', ')')?)?; let [_, message] = arguments.as_slice() else { return None; }; let message = literal_string(message)?; if message.contains(['{', '}']) || !message.contains(&expected) { return None; } } Some(()) } /// The `matches!(scrutinee, pattern)` condition a literal `matches!` pin reads /// from `text`: a plain `assert!(matches!(..))`, or the assertion twin of a /// terminal Err-return guard over a negated `matches!`. Guards are read through /// the same twin, so both spellings take one admission (#10121). fn matches_pin_condition(text: &str) -> Option { if is_plain_assert_of_matches(text) { return outer_assertion_condition(text); } let (_, twin) = err_return_guard_twin(text)?; if !is_plain_assert_of_matches(&twin) { return None; } outer_assertion_condition(&twin) } /// Whether `text` is one unqualified `assert!` whose only nested macro is a /// `matches!`, as [`is_plain_macro`] reads a lone `assert!`. fn is_plain_assert_of_matches(text: &str) -> bool { let masked = mask_comments_and_strings(text); let invocations = macro_invocations(&masked); let [("assert", _), ("matches", _)] = invocations.as_slice() else { return false; }; masked .find("assert") .is_some_and(|offset| !masked[..offset].trim_end().ends_with(':')) && masked .find("matches") .is_some_and(|offset| !masked[..offset].trim_end().ends_with(':')) } /// RIPR-SPEC-0197 literal `matches!` pins: the scrutinee and the pinned value of a /// `matches!(scrutinee, pattern)` condition whose pattern is literal-only, so /// that matching it is equality with one value. Anything else refuses: a /// guard, an or-pattern, a wildcard, a rest or range, a reference or slice /// pattern, a binding without a literal subpattern, and every path or /// constant, since the line cannot tell a constant from a binding or check /// that a path names the std `Option`/`Result` variants. fn literal_matches_operands(condition: &str) -> Option<[String; 2]> { let rest = condition.trim().strip_prefix("matches!")?.trim_start(); let masked = mask_comments_and_strings(rest); let close = matching_close(&masked, 0, b'(', b')')?; if close + 1 != rest.len() { return None; } let inner = masked.get(1..close)?; let mut depth = 0usize; let mut commas = Vec::new(); for (offset, byte) in inner.bytes().enumerate() { match byte { b'(' | b'[' | b'{' => depth += 1, b')' | b']' | b'}' => depth = depth.checked_sub(1)?, b',' if depth == 0 => commas.push(offset), _ => {} } } // `matches!` accepts one trailing comma after the pattern. let (comma, end) = match commas.as_slice() { [comma] => (*comma, inner.len()), [comma, trailing] if inner.get(trailing + 1..)?.trim().is_empty() => (*comma, *trailing), _ => return None, }; let scrutinee = rest.get(1..comma + 1)?.trim(); let pattern = literal_value_pattern(rest.get(comma + 2..end + 1)?)?; (!scrutinee.is_empty()).then(|| [scrutinee.to_string(), pattern]) } /// A literal-only pattern rewritten as the value it matches: `Some(x @ 3)` /// becomes `Some(3)`. Only `Some`, `Ok` and `Err` around a payload, `None`, /// `true`, `false`, a numeric literal (optionally negated) and a plain string /// literal are admitted. fn literal_value_pattern(pattern: &str) -> Option { let chars: Vec = pattern.trim().chars().collect(); let mut value = String::new(); let mut at = 0; let mut depth = 0usize; // Whether the next token starts a subpattern (after `(`, `,` or `@`). let mut expects_pattern = true; while let Some(&ch) = chars.get(at) { if ch.is_whitespace() { at += 1; continue; } if ch == '"' { if !expects_pattern { return None; } let start = at; at += 1; loop { match chars.get(at)? { '\\' => at += 2, '"' => break, _ => at += 1, } } at += 1; value.extend(&chars[start..at]); expects_pattern = false; continue; } if ch.is_ascii_digit() || (ch == '-' && expects_pattern) { if !expects_pattern { return None; } let start = at; at += 1; while chars .get(at) .is_some_and(|next| next.is_ascii_alphanumeric() || matches!(next, '_' | '.')) { at += 1; } let literal: String = chars[start..at].iter().collect(); let digits = literal.strip_prefix('-').unwrap_or(&literal); if !digits.starts_with(|first: char| first.is_ascii_digit()) || literal.contains("..") { return None; } value.push_str(&literal); expects_pattern = false; continue; } if ch.is_alphabetic() || ch == '_' { let start = at; while chars .get(at) .is_some_and(|next| next.is_alphanumeric() || *next == '_') { at += 1; } let word: String = chars[start..at].iter().collect(); let mut next = at; while chars.get(next).is_some_and(|next| next.is_whitespace()) { next += 1; } if !expects_pattern { return None; } match (word.as_str(), chars.get(next)) { ("Some" | "Ok" | "Err", Some('(')) => { value.push_str(&word); value.push('('); depth += 1; at = next + 1; } ("None" | "true" | "false", _) => { value.push_str(&word); expects_pattern = false; } // `name @ literal`: the binding names the value it matched. (_, Some('@')) if word != "_" && word.starts_with(|first: char| first.is_lowercase() || first == '_') && !matches!(word.as_str(), "ref" | "mut") => { at = next + 1; } _ => return None, } continue; } match ch { ')' if depth > 0 && !expects_pattern => { depth -= 1; value.push(')'); } // `Some(3,)`: one trailing comma before the constructor closes. ')' if depth > 0 && expects_pattern && value.ends_with(", ") => { depth -= 1; value.truncate(value.len() - ", ".len()); value.push(')'); expects_pattern = false; } ',' if depth > 0 && !expects_pattern => { value.push_str(", "); expects_pattern = true; } _ => return None, } at += 1; } (depth == 0 && !expects_pattern).then_some(value) } /// The offset of the bracket closing the one at `opening`, in masked text. fn matching_close(masked: &str, opening: usize, open: u8, close: u8) -> Option { let bytes = masked.as_bytes(); if bytes.get(opening) != Some(&open) { return None; } let mut depth = 0usize; for (offset, byte) in bytes.iter().enumerate().skip(opening) { if *byte == open { depth += 1; } else if *byte == close { depth = depth.checked_sub(1)?; if depth == 0 { return Some(offset); } } } None } fn collapse_whitespace(text: &str) -> String { text.split_whitespace().collect::>().join(" ") } /// Method names `&[u8]` resolves before a workspace trait's method: the /// inherent methods of slices and byte slices, and the methods of prelude /// and `std::io` traits implemented for them. A byte-slice receiver never /// credits a pin through one of these names. const BYTE_SLICE_METHODS: &[&str] = &[ "align_to", "align_to_mut", "array_chunks", "array_windows", "as_array", "as_ascii", "as_chunks", "as_flattened", "as_mut", "as_mut_ptr", "as_mut_ptr_range", "as_ptr", "as_ptr_range", "as_rchunks", "as_ref", "as_simd", "binary_search", "binary_search_by", "binary_search_by_key", "borrow", "by_ref", "bytes", "chain", "chunk_by", "chunks", "chunks_exact", "clone", "clone_from", "cmp", "concat", "connect", "consume", "contains", "copy_from_slice", "copy_within", "element_offset", "ends_with", "eq", "eq_ignore_ascii_case", "escape_ascii", "fill", "fill_buf", "fill_with", "first", "first_chunk", "fmt", "ge", "get", "get_mut", "get_unchecked", "gt", "hash", "into", "into_iter", "is_ascii", "is_empty", "is_sorted", "is_sorted_by", "is_sorted_by_key", "iter", "join", "last", "last_chunk", "le", "len", "lines", "lt", "make_ascii_lowercase", "make_ascii_uppercase", "max", "min", "ne", "partial_cmp", "partition_point", "rchunks", "rchunks_exact", "read", "read_buf", "read_exact", "read_line", "read_to_end", "read_to_string", "read_until", "read_vectored", "repeat", "reverse", "rotate_left", "rotate_right", "rsplit", "rsplit_once", "rsplitn", "select_nth_unstable", "skip_until", "sort", "sort_by", "sort_by_cached_key", "sort_by_key", "sort_unstable", "sort_unstable_by", "sort_unstable_by_key", "split", "split_at", "split_at_checked", "split_first", "split_first_chunk", "split_inclusive", "split_last", "split_last_chunk", "split_off", "split_off_first", "split_off_last", "split_once", "splitn", "starts_with", "strip_prefix", "strip_suffix", "subslice_range", "swap", "swap_with_slice", "take", "to_ascii_lowercase", "to_ascii_uppercase", "to_owned", "to_vec", "trim_ascii", "trim_ascii_end", "trim_ascii_start", "trim_prefix", "trim_suffix", "try_into", "type_id", "utf8_chunks", "windows", ]; /// Methods of prelude traits that take `self` by value. Method lookup /// tries the receiver type itself before `&T`, so for a receiver type that /// implements the trait (`Iterator`, `IntoIterator`, `Into`), one of these /// takes the call before an inherent `&self` method of the same name. ripr /// cannot see which std traits a workspace type implements (derives, /// blanket impls), so a named receiver never credits a pin through these /// names. pub(super) fn method_may_dispatch_through_prelude(name: &str) -> bool { BY_VALUE_PRELUDE_METHODS.contains(&name) } const BY_VALUE_PRELUDE_METHODS: &[&str] = &[ "all", "any", "chain", "clamp", "cloned", // Iterator's by-value comparisons (`self`) run before a trait's `&self` // method of the same name (#7083 review). "cmp", "collect", "copied", "count", "cycle", "enumerate", "eq", "filter", "filter_map", "find", "find_map", "flat_map", "flatten", "fold", "for_each", "fuse", "ge", "gt", "inspect", "into", "into_iter", // Edition 2024 prelude: `IntoFuture` for every `Future` (#7083). "into_future", // `Iterator::is_partitioned` is still unstable on the supported 1.95 // toolchain, so the name can only spell a custom default: listing it // here would refuse a genuine discriminator (#7098 review). Do not // re-add until the std method stabilizes. "is_sorted", "is_sorted_by", "is_sorted_by_key", "last", "le", "lt", "map", "map_while", "max", "max_by", "max_by_key", "min", "min_by", "min_by_key", "ne", "nth", "partial_cmp", "partition", "peekable", "position", "product", "reduce", "rev", "rfind", "rfold", "rposition", "scan", "size_hint", "skip", "skip_while", "step_by", "sum", "take", "take_while", "try_fold", "try_for_each", "try_into", "unzip", "zip", ]; #[cfg(test)] mod tests; /// Which eligible eager call of a borrowed check helper one admission attempt /// reads, and whether the attempt selected one (RIPR-SPEC-0197). struct HelperCallProbe { /// The assertion macro the admission reads: `assert_eq` or (#8051, never /// credit) `debug_assert_eq`. spelling: &'static str, skip: usize, selected: Cell, } #[cfg(test)] mod stored_constant_syntax_tests { use super::{file_constants, stored_file_constants, workspace_constant_table}; use crate::analysis::rust_index::RustIndex; use crate::analysis::syntax::nesting_parse_calls; use crate::analysis::syntax::{RaRustSyntaxAdapter, RustSyntaxAdapter}; use std::path::{Path, PathBuf}; const SOURCES: [(&str, &str); 6] = [ ("src/plain.rs", "pub fn plain() -> u32 { 1 }\n"), ( "src/items.rs", concat!( "pub const LIMIT: u32 = quota(2); // trailing \"note\"\n", "static mut COUNT: usize = 0;\n", "pub static r#NAME: &str = \"a /* not a comment */\";\n", "const _: () = ();\n", "pub const fn quota(n: u32) -> u32 { n }\n", "fn body() -> u32 { const INNER: [u32; 2] = [1, 2]; INNER[0] }\n", "extern \"C\" { static FOREIGN: u32; }\n", ), ), ( "src/macros.rs", concat!( "thread_local! { static CELL: std::cell::Cell = std::cell::Cell::new(3); }\n", "lazy_static::lazy_static! { static ref TABLE: Vec = vec![1]; }\n", "macro_rules! noop { () => {} }\n", "noop!();\n", ), ), ( "src/unicode.rs", "pub const ÉTÉ: &str = \"été\";\npub const AFTER: char = 'é';\n", ), ( "src/typed.rs", "pub const MAP: [(u8, &str); 1] = [(1, \"x\")];\nimpl S { pub const ASSOC: u8 = 4; }\npub struct S;\n", ), ( "src/static_lifetime.rs", "pub fn name() -> &'static str { \"n\" }\n", ), ]; fn parsed_index() -> Result { let mut index = RustIndex::default(); for (path, source) in SOURCES { let facts = RaRustSyntaxAdapter.summarize_file(Path::new(path), source)?; index.insert_file_only(PathBuf::from(path), facts); } Ok(index) } /// #13754: the constant table reads the producer's stored item ranges /// instead of parsing every workspace file again, and gets the same /// table. #[test] fn stored_constant_syntax_builds_the_same_table_without_parsing() -> Result<(), String> { let index = parsed_index()?; // Premise: every clean source carries stored syntax that answers // exactly what a fresh parse does, and the corpus exercises items, // raw names, nested items, macro bodies and multibyte text. for (path, source) in SOURCES { let file = index .files() .get(Path::new(path)) .ok_or_else(|| format!("{path} indexed"))?; let stored = file .data() .constant_syntax .as_deref() .ok_or_else(|| format!("{path} has stored constant syntax"))?; assert_eq!( stored_file_constants(source, stored), Some(file_constants(source)), "{path}" ); } let names: Vec = SOURCES .iter() .flat_map(|(_, source)| file_constants(source)) .map(|(name, _, _)| name) .collect(); for expected in [ "LIMIT", "COUNT", "NAME", "INNER", "CELL", "TABLE", "ÉTÉ", "AFTER", "MAP", "ASSOC", ] { assert!( names.iter().any(|name| name == expected), "{expected} in {names:?}" ); } // The counter is per thread, so build each table on one pool worker, // where `map_scans` stays in line on the calling thread. let pool = rayon::ThreadPoolBuilder::new() .num_threads(1) .build() .map_err(|error| error.to_string())?; let counted = |index: &RustIndex| { pool.install(|| { let before = nesting_parse_calls(); let table = workspace_constant_table(index); (table, nesting_parse_calls() - before) }) }; let (stored_table, stored_parses) = counted(&index); assert_eq!(stored_parses, 0, "stored syntax leaves nothing to parse"); // Hand-built facts carry no stored syntax: the table parses and agrees. let mut owned = index.clone(); for (path, _) in SOURCES { let mut facts = owned .owned_file(Path::new(path)) .ok_or_else(|| format!("{path} indexed"))?; facts.constant_syntax = None; owned.insert_file_only(PathBuf::from(path), facts); } let (parsed_table, parses) = counted(&owned); assert_eq!( parses, 5, "without stored syntax each file spelling `const` or `static` parses" ); assert_eq!(stored_table, parsed_table); Ok(()) } /// The fixtures above pin named shapes; this ratchet runs the same /// equivalence over a real tree, ripr's own syntax sources, so a later /// change to the producer's walk that drops or reorders an entry fails /// here instead of silently moving an owner-pin verdict. #[test] fn stored_constant_syntax_matches_a_fresh_parse_on_real_sources() -> Result<(), String> { let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/analysis/syntax"); let mut paths: Vec = std::fs::read_dir(&dir) .map_err(|error| error.to_string())? .filter_map(|entry| entry.ok().map(|entry| entry.path())) .filter(|path| path.extension().is_some_and(|extension| extension == "rs")) .collect(); paths.sort(); let mut compared = 0usize; let mut with_constants = 0usize; for path in &paths { let source = std::fs::read_to_string(path).map_err(|error| error.to_string())?; let Ok(facts) = RaRustSyntaxAdapter.summarize_file(path, &source) else { continue; }; let stored = facts .constant_syntax .as_deref() .ok_or_else(|| format!("{} has stored constant syntax", path.display()))?; let parsed = file_constants(&source); assert_eq!( stored_file_constants(&source, stored), Some(parsed.clone()), "{}", path.display() ); compared += 1; with_constants += usize::from(!parsed.is_empty()); } // Premise: the corpus is real and exercises the stored path. assert!( compared >= 15, "compared {compared} of {} files", paths.len() ); assert!( with_constants >= 10, "{with_constants} files declare constants" ); Ok(()) } /// A stored range off a character boundary (a corrupt or foreign cache /// entry) is not trusted: the caller falls back to parsing. #[test] fn a_stored_range_off_a_char_boundary_is_refused() { use crate::analysis::syntax::constant_items::ConstantSyntax; let source = "pub const ÉTÉ: u8 = 1;\n"; let stored = [ConstantSyntax::Item { name: (11, 13), body: (20, 21), ty: None, }]; assert_eq!(stored_file_constants(source, &stored), None); } }