requirements.references.rust_item_selectors
Requirements index · View definition
Requirement
The Rust outline profile under
MUST identify items by segments describing their syntactic ancestry within the file, such as
fn[run],struct[Packet], andmod[local]/fn[run], and MUST NOT resolve Rust modules across files. Functions, methods, structs, enums, unions, traits, impls, modules, macros, constants, statics, type aliases, and extern blocks MUST be outline nodes. Impl segments MUST be named by their syntactic self type and optional trait path, asimpl[Thing]andimpl[Thing/Trait].usedeclarations and other items without a suitable name MUST be anonymous. Selector spelling MUST be documented.
Rationale
I found no gaps. Each obligation maps to code in src/outline/rust.rs and to a test in src/outline/tests.rs.
Outline nodes for the listed item kinds. The KINDS table in src/outline/rust.rs, reached from static[PROFILE], maps every kind the requirement lists:
- Functions and methods:
function_itemandfunction_signature_itemmap tofn. - Types:
struct_item,enum_itemandunion_itemmap tostruct,enumandunion. - Traits and impls:
trait_itemandimpl_itemmap totraitandimpl. - Modules and macros:
mod_itemmaps tomod, andmacro_definitionmaps tomacro. - Constants, statics and type aliases:
const_item,static_item,type_itemandassociated_typemap toconst,staticandtype. - Extern blocks:
foreign_mod_itemmaps toextern. extern_crate_declarationmaps toextern-crate, which the requirement does not list.
Tests for node kinds. rust_selectors_follow_syntactic_ancestry in src/outline/tests.rs asserts the selector of every one of these kinds. It checks macro[make], union[U], enum[E], const[C], static[S], type[Alias], extern[C]/fn[puts] and extern[Rust]/fn[other].
Selectors from syntactic ancestry. Selectors are built from nested outline ancestry within one file. The tests assert mod[local]/fn[run], fn[outer]/fn[inner], trait[Trait]/fn[read] and trait[Trait]/type[Item]. Duplicates get ordinals: fn[repeated]#1 and fn[repeated]#2.
No cross-file module resolution.
- Nothing in the profile follows a
moddeclaration to another file. - The tests assert
mod[external]formod external;, a node with no children, so no cross-file resolution happens.
Impl names.
impl_namenames an impl by the text of itstypefield plus the optionaltraitfield.- Tests assert
impl[Thing],impl[Thing/Trait]andimpl[%5Bu8;%204%5D], where the bracketed self type is percent-encoded. - They also assert
impl[Wrapper<T>/Trait]for a generic impl.
Anonymous items. Both use_declaration and item-position macro_invocation use NameRule::Anonymous.
selectors_name_syntactic_ancestry_and_duplicatesasserts thatuseselectors start withuse@and differ from each other.item_macros_are_anonymous_nodes_and_expression_macros_are_notasserts^macro@[0-9a-f]{12}$for item macros.- The same test asserts that macros inside function bodies are not nodes.
Documentation. md/reference.md has a “Rust items” section that gives the selector spelling: examples, impl naming, and anonymous use and macro forms. The outline-profile table in the same file lists the kinds and how each is named, including extern and extern-crate.
No test-only gap, no unspecified behavior and no {fixme} needs acknowledging.
Inputs
Implementation
Input 3: outline src/outline/rust.rs static[PROFILE]
- File:
src/outline/rust.rs - Selector:
static[PROFILE] - Kind:
static src/outline/rust.rs:142–156
// {impl}`requirements.references.rust_item_selectors`
// {impl}`requirements.references.outline_comments`
// {impl}`requirements.references.structural_hash`
pub(crate) static PROFILE: Profile = Profile {
name: "rust",
extensions: &["rs"],
language: Some(|| tree_sitter_rust::LANGUAGE.into()),
kinds: KINDS,
is_comment,
hashes_comment: is_doc_comment,
comment_prose: doc_prose,
comment_binds_to_container: is_inner_doc_comment,
trailing_comments_outside: false,
attaches,
};
Input 7: outline src/outline/rust.rs (whole file)
- File:
src/outline/rust.rs - Selector:
(root) - Kind:
file src/outline/rust.rs:1–156
//! Rust outline profile.
use tree_sitter::Node;
use super::profile::{KindRule, NameRule, Profile, text};
/// Names an impl by its syntactic self type and optional trait path.
fn impl_name(node: Node<'_>, source: &str) -> Option<(Vec<String>, usize)> {
let self_type = node.child_by_field_name("type")?;
let name = text(self_type, source).to_owned();
// The name begins at whichever of the trait and self type comes first.
Some(match node.child_by_field_name("trait") {
Some(path) => (
vec![name, text(path, source).to_owned()],
path.start_byte().min(self_type.start_byte()),
),
None => (vec![name], self_type.start_byte()),
})
}
/// Names an extern block by its ABI string, `Rust` when absent.
fn extern_name(node: Node<'_>, source: &str) -> Option<(Vec<String>, usize)> {
let mut cursor = node.walk();
let modifier = node
.named_children(&mut cursor)
.find(|child| child.kind() == "extern_modifier");
let abi = modifier.and_then(|modifier| {
let mut cursor = modifier.walk();
let literal = modifier
.named_children(&mut cursor)
.find(|child| child.kind() == "string_literal")?;
let mut cursor = literal.walk();
let content = literal
.named_children(&mut cursor)
.find(|child| child.kind() == "string_content")
.map_or_else(String::new, |content| text(content, source).to_owned());
Some((content, literal.start_byte()))
});
// Without an ABI string the name is not written, so the block is declared
// where it starts.
Some(match abi {
Some((abi, byte)) => (vec![abi], byte),
None => (vec!["Rust".to_owned()], node.start_byte()),
})
}
/// Whether a grammar node sits directly in an item list.
fn in_item_list(node: Node<'_>) -> bool {
node.parent()
.is_some_and(|parent| matches!(parent.kind(), "source_file" | "declaration_list"))
}
/// Whether a macro invocation is an item rather than an expression.
fn item_macro(node: Node<'_>) -> bool {
in_item_list(node)
|| node
.parent()
.is_some_and(|parent| parent.kind() == "expression_statement" && in_item_list(parent))
}
fn is_comment(node: Node<'_>, _source: &str) -> bool {
matches!(node.kind(), "line_comment" | "block_comment")
}
/// Whether a comment has the given doc comment marker child.
fn has_marker(node: Node<'_>, marker: &str) -> bool {
let mut cursor = node.walk();
is_comment(node, "")
&& node
.children(&mut cursor)
.any(|child| child.kind() == marker)
}
/// Doc comments, outer and inner, are hashed.
fn is_doc_comment(node: Node<'_>, _source: &str) -> bool {
has_marker(node, "outer_doc_comment_marker") || has_marker(node, "inner_doc_comment_marker")
}
/// Inner doc comments document the item enclosing them, and their prose is
/// hashed in its own group, apart from outer doc comments.
// {impl}`requirements.references.outline_comments`
fn is_inner_doc_comment(node: Node<'_>, _source: &str) -> bool {
has_marker(node, "inner_doc_comment_marker")
}
/// A doc comment's prose group, inner or outer, and its text without the
/// `///`, `//!`, `/**`, `/*!`, and `*/` delimiters or the leading `*` of a
/// block comment's continuation lines.
fn doc_prose(node: Node<'_>, body: &str) -> (&'static str, String) {
let group = if is_inner_doc_comment(node, body) {
"inner_doc_comment"
} else {
"outer_doc_comment"
};
let prose = if let Some(line) = body.strip_prefix("//") {
line.strip_prefix(['/', '!']).unwrap_or(line).to_owned()
} else {
let inner = body.strip_prefix("/*").unwrap_or(body);
let inner = inner.strip_suffix("*/").unwrap_or(inner);
let inner = inner.strip_prefix(['*', '!']).unwrap_or(inner);
let mut lines = inner.lines();
let first = lines.next().unwrap_or("").to_owned();
lines.fold(first, |mut prose, line| {
let line = line.trim_start();
prose.push('\n');
prose.push_str(line.strip_prefix('*').unwrap_or(line));
prose
})
};
(group, prose)
}
/// Attributes and outer doc comments attach to the following item.
fn attaches(node: Node<'_>, _source: &str) -> bool {
node.kind() == "attribute_item" || has_marker(node, "outer_doc_comment_marker")
}
const KINDS: &[KindRule] = &[
KindRule::new("function_item", "fn", NameRule::Field("name")),
KindRule::new("function_signature_item", "fn", NameRule::Field("name")),
KindRule::new("struct_item", "struct", NameRule::Field("name")),
KindRule::new("enum_item", "enum", NameRule::Field("name")),
KindRule::new("union_item", "union", NameRule::Field("name")),
KindRule::new("trait_item", "trait", NameRule::Field("name")),
KindRule::new("impl_item", "impl", NameRule::Custom(impl_name)),
KindRule::new("mod_item", "mod", NameRule::Field("name")),
KindRule::new("macro_definition", "macro", NameRule::Field("name")),
KindRule::new("macro_invocation", "macro", NameRule::Anonymous).when(item_macro),
KindRule::new("const_item", "const", NameRule::Field("name")),
KindRule::new("static_item", "static", NameRule::Field("name")),
KindRule::new("type_item", "type", NameRule::Field("name")),
KindRule::new("associated_type", "type", NameRule::Field("name")),
KindRule::new("foreign_mod_item", "extern", NameRule::Custom(extern_name)),
KindRule::new(
"extern_crate_declaration",
"extern-crate",
NameRule::Field("name"),
),
KindRule::new("use_declaration", "use", NameRule::Anonymous),
];
// {impl}`requirements.references.rust_item_selectors`
// {impl}`requirements.references.outline_comments`
// {impl}`requirements.references.structural_hash`
pub(crate) static PROFILE: Profile = Profile {
name: "rust",
extensions: &["rs"],
language: Some(|| tree_sitter_rust::LANGUAGE.into()),
kinds: KINDS,
is_comment,
hashes_comment: is_doc_comment,
comment_prose: doc_prose,
comment_binds_to_container: is_inner_doc_comment,
trailing_comments_outside: false,
attaches,
};
Tests
Input 4: outline src/outline/tests.rs fn[rust_selectors_follow_syntactic_ancestry]
- File:
src/outline/tests.rs - Selector:
fn[rust_selectors_follow_syntactic_ancestry] - Kind:
fn src/outline/tests.rs:192–258
// {test}`requirements.references.outline_selectors`
// {test}`requirements.references.rust_item_selectors`
// {test}`requirements.references.selector_nested`
// {test}`requirements.references.selector_impl_and_trait`
// {test}`requirements.references.selector_inline_and_foreign`
// {test}`requirements.references.selector_duplicate_names`
// {test}`requirements.references.outlines`
#[test]
fn rust_selectors_follow_syntactic_ancestry() {
let source = r#"
mod local { fn run() {} }
mod external;
struct Thing;
impl Thing { fn run() {} }
impl Trait for Thing { fn run() {} }
impl [u8; 4] { fn edge() {} }
trait Trait { fn read(&self); type Item; }
extern "C" { fn puts(); }
extern { fn other(); }
fn outer() { fn inner() {} }
#[cfg(a)] fn repeated() {}
#[cfg(b)] fn repeated() {}
macro_rules! make { () => {} }
union U { a: u8 }
enum E { A }
const C: u8 = 1;
static S: u8 = 1;
type Alias = u8;
extern crate core;
"#;
let outline = outline("src/lib.rs", source);
let selectors = selectors(&outline);
for selector in [
"mod[local]/fn[run]",
"mod[external]",
"struct[Thing]",
"impl[Thing]/fn[run]",
"impl[Thing/Trait]/fn[run]",
"impl[%5Bu8;%204%5D]/fn[edge]",
"trait[Trait]/fn[read]",
"trait[Trait]/type[Item]",
"extern[C]/fn[puts]",
"extern[Rust]/fn[other]",
"fn[outer]/fn[inner]",
"fn[repeated]#1",
"fn[repeated]#2",
"macro[make]",
"union[U]",
"enum[E]",
"const[C]",
"static[S]",
"type[Alias]",
"extern-crate[core]",
] {
assert!(
selectors.contains(&selector.to_owned()),
"{selector}: {selectors:?}"
);
assert_eq!(
outline.nodes[outline.resolve(selector).unwrap()].selector,
selector
);
}
assert_eq!(outline.resolve("").unwrap(), 0);
assert!(outline.resolve("fn[repeated]").is_err());
assert!(outline.resolve("fn[missing]").is_err());
}
Input 5: outline src/outline/tests.rs fn[selectors_name_syntactic_ancestry_and_duplicates]
- File:
src/outline/tests.rs - Selector:
fn[selectors_name_syntactic_ancestry_and_duplicates] - Kind:
fn src/outline/tests.rs:840–885
// {test}`requirements.references.rust_item_selectors`
// {test}`requirements.references.selector_nested`
// {test}`requirements.references.selector_impl_and_trait`
// {test}`requirements.references.selector_inline_and_foreign`
// {test}`requirements.references.selector_duplicate_names`
// {test}`requirements.references.selector_use`
// {test}`requirements.references.outlines`
#[test]
fn selectors_name_syntactic_ancestry_and_duplicates() {
let source = r#"
use alpha::A;
use beta::B;
mod local { fn run() {} }
mod external;
struct Thing;
impl Thing { fn run() {} }
impl Trait for Thing { fn run() {} }
impl [u8; 4] { fn edge() {} }
trait Trait { fn read(&self); }
extern "C" { fn puts(); }
fn outer() { fn inner() {} }
#[cfg(a)] fn repeated() {}
#[cfg(b)] fn repeated() {}
"#;
let selectors = selectors(&outline("lib.rs", source));
assert!(selectors[0].starts_with("use@") && selectors[1].starts_with("use@"));
assert_ne!(selectors[0], selectors[1]);
for selector in [
"mod[local]/fn[run]",
"mod[external]",
"struct[Thing]",
"impl[Thing]/fn[run]",
"impl[Thing/Trait]/fn[run]",
"impl[%5Bu8;%204%5D]/fn[edge]",
"trait[Trait]/fn[read]",
"extern[C]/fn[puts]",
"fn[outer]/fn[inner]",
"fn[repeated]#1",
"fn[repeated]#2",
] {
assert!(
selectors.contains(&selector.to_owned()),
"{selector}: {selectors:?}"
);
}
}
Input 6: outline src/outline/tests.rs fn[item_macros_are_anonymous_nodes_and_expression_macros_are_not]
- File:
src/outline/tests.rs - Selector:
fn[item_macros_are_anonymous_nodes_and_expression_macros_are_not] - Kind:
fn src/outline/tests.rs:1117–1151
// {test}`requirements.references.rust_item_selectors`
// {test}`requirements.references.outlines`
#[test]
fn item_macros_are_anonymous_nodes_and_expression_macros_are_not() {
let source = "\
thread_local! { static X: u8 = 1; }
println!();
impl<T> Trait for Wrapper<T> {
m!();
fn run() { inner!(); let x = vec![1]; }
}
mod local { other! {} }
";
let outline = outline("src/lib.rs", source);
let selectors = selectors(&outline);
let anonymous = regex::Regex::new("^macro@[0-9a-f]{12}$").unwrap();
assert!(anonymous.is_match(&selectors[0]), "{selectors:?}");
assert!(anonymous.is_match(&selectors[1]), "{selectors:?}");
assert_ne!(selectors[0], selectors[1]);
assert_eq!(selectors[2], "impl[Wrapper<T>/Trait]");
assert!(
selectors[3].starts_with("impl[Wrapper<T>/Trait]/macro@"),
"{selectors:?}"
);
assert_eq!(selectors[4], "impl[Wrapper<T>/Trait]/fn[run]");
assert!(
selectors[5].starts_with("mod[local]") && selectors[6].starts_with("mod[local]/macro@"),
"{selectors:?}"
);
assert_eq!(
selectors.len(),
7,
"macros inside a function body are expressions, not nodes: {selectors:?}"
);
}
Referenced definitions
Input 2: requirements selection requirements.references.outlines
requirements.references.outlines:md/requirements/references.md:358–378
:::{req} outlines
Habeas MUST parse Rust, Python, TypeScript, CSS, Markdown, TOML, and YAML
sources with pinned tree-sitter grammars, selected by file extension compared
case-insensitively. A source with any syntax error MUST fail to parse, reporting
the line of its first error. Every
other text file MUST use a plain-text profile in which each line that is not
blank is an anonymous outline node of kind `line`. Each supported language MUST
have an outline profile that maps grammar node kinds to short outline kind names
and, for each mapped kind, states whether a node is named, and by which fields
or children, or anonymous. Only mapped kinds MUST appear in the outline; other
nodes MUST be transparent, so their outline descendants appear under the
nearest outline ancestor. A profile MAY attach grammar siblings to an outline
node, such as Rust attributes and doc comments preceding an item, so the outline
tree need not match the grammar tree exactly; attached siblings are part of that
node for its line range and hash. Every file's outline MUST have a root node
for the whole file, independent of language. Source in no other outline node,
such as top-level statements no profile maps, MUST belong to the root node;
profiles MUST NOT invent fallback kinds for it. Comments MUST NOT be outline nodes. Profiles MUST be
documented. Upgrading a grammar or profile MAY change outlines and MUST be
treated as a deliberate change.
:::
Other sources
Input 1: requirements selection requirements.references.rust_item_selectors
requirements.references.rust_item_selectors:md/requirements/references.md:344–354
:::{req} rust_item_selectors
The Rust outline profile under {cite}`requirements.references.outlines` MUST
identify items by segments describing their syntactic ancestry within the file,
such as `fn[run]`, `struct[Packet]`, and `mod[local]/fn[run]`, and MUST NOT
resolve Rust modules across files. Functions, methods, structs, enums, unions,
traits, impls, modules, macros, constants, statics, type aliases, and extern
blocks MUST be outline nodes. Impl segments MUST be named by their syntactic self
type and optional trait path, as `impl[Thing]` and `impl[Thing/Trait]`. `use`
declarations and other items without a suitable name MUST be anonymous. Selector
spelling MUST be documented.
:::