Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

requirements.references.selector_duplicate_names

Requirements index · View definition

evidence Valid

Example

Two sibling declarations named run in one file, guarded by different #[cfg] attributes, have selectors fn[run]#1 and fn[run]#2 in source order. Their source line numbers are not part of either selector. cite requirements.references.rust_item_selectors

Rationale

The example is covered by passing-style tests that match its scenario and expected outcomes.

Implementation. disambiguate in src/outline/mod.rs (lines 623–651) groups sibling nodes by their base segment, such as fn[run]. When a group has more than one member, it appends #N, numbering from 1 in child order, which is source order. The segment text contains no line information, so line numbers are not part of any selector.

Tests. Three tests reference selector_duplicate_names:

  • duplicate_names_are_numbered_in_source_order_without_line_numbers (src/outline/tests.rs 903–935) is the direct test.
    • It uses two sibling fn run items guarded by #[cfg(a)] and #[cfg(b)].
    • It asserts the selectors are exactly ["fn[run]#1", "fn[run]#2"].
    • It checks that #1 is the first declaration in the file, using byte offsets.
    • It swaps the two declarations and confirms the ordinals swap, so the ordinal follows source order.
    • It prefixes three blank lines, which moves the line numbers (line_start becomes 4). The selectors and the structural hash of #1 stay unchanged, so line numbers are not part of the selector.
  • rust_selectors_follow_syntactic_ancestry (35–100) covers fn[repeated]#1 and fn[repeated]#2 for cfg-guarded siblings. It also checks that each selector resolves back to its own node and that the bare fn[repeated] is rejected as ambiguous.
  • selectors_name_syntactic_ancestry_and_duplicates (662–706) covers the same cfg-guarded duplicates alongside other item kinds.

Gaps. I found none. The cited requirement rust_item_selectors is context only and is not reassessed.

Inputs

Tests

Input 3: outline src/outline/tests.rs fn[rust_selectors_follow_syntactic_ancestry]
// {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 4: outline src/outline/tests.rs fn[selectors_name_syntactic_ancestry_and_duplicates]
// {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 5: outline src/outline/tests.rs fn[duplicate_names_are_numbered_in_source_order_without_line_numbers]
// {test}`requirements.references.selector_duplicate_names`
// {test}`requirements.references.outlines`
#[test]
fn duplicate_names_are_numbered_in_source_order_without_line_numbers() {
    let source = "#[cfg(a)]\nfn run() { a() }\n#[cfg(b)]\nfn run() { b() }\n";
    let first = outline("src/lib.rs", source);
    assert_eq!(selectors(&first), ["fn[run]#1", "fn[run]#2"]);
    let node = |outline: &Outline, selector: &str| {
        outline.nodes[outline.resolve(selector).unwrap()].clone()
    };
    assert_eq!(node(&first, "fn[run]#1").line_start, 1);
    assert_eq!(node(&first, "fn[run]#2").line_start, 3);
    assert!(
        source[node(&first, "fn[run]#1").byte_start..].starts_with("fn run() { a() }"),
        "#1 is the first declaration in the file"
    );
    let swapped = outline(
        "src/lib.rs",
        "#[cfg(b)]\nfn run() { b() }\n#[cfg(a)]\nfn run() { a() }\n",
    );
    assert_eq!(
        node(&swapped, "fn[run]#1").structural_hash,
        node(&first, "fn[run]#2").structural_hash,
        "swapping the declarations swaps their ordinals"
    );
    let moved = outline("src/lib.rs", &format!("\n\n\n{source}"));
    assert_eq!(selectors(&moved), ["fn[run]#1", "fn[run]#2"]);
    assert_eq!(node(&moved, "fn[run]#1").line_start, 4);
    assert_eq!(
        node(&moved, "fn[run]#1").structural_hash,
        node(&first, "fn[run]#1").structural_hash,
        "moving the declarations changes neither selector"
    );
}

Referenced definitions

Input 2: requirements selection requirements.references.rust_item_selectors
:::{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.
:::

Other sources

Input 1: requirements selection requirements.references.selector_duplicate_names
:::{example} selector_duplicate_names
Two sibling declarations named `run` in one file, guarded by different `#[cfg]` attributes, have selectors `fn[run]#1` and `fn[run]#2` in source order. Their source line numbers are not part of either selector. {cite}`requirements.references.rust_item_selectors`
:::
Input 6: outline src/outline/mod.rs fn[disambiguate]
/// Adds `#N` to sibling segments that would otherwise be identical, except
/// `line` nodes, and builds full selectors.
fn disambiguate(nodes: &mut [OutlineNode]) {
    for parent in 0..nodes.len() {
        let mut groups = BTreeMap::<String, Vec<usize>>::new();
        for child in &nodes[parent].children {
            groups
                .entry(nodes[*child].segment.clone())
                .or_default()
                .push(*child);
        }
        for group in groups.values().filter(|group| group.len() > 1) {
            for (ordinal, child) in group.iter().enumerate() {
                if nodes[*child].kind != "line" {
                    nodes[*child].segment = format!("{}#{}", nodes[*child].segment, ordinal + 1);
                }
            }
        }
    }
    for index in 1..nodes.len() {
        let parent = nodes[index].parent.unwrap_or(0);
        nodes[index].selector = if parent == 0 {
            nodes[index].segment.clone()
        } else {
            format!("{}/{}", nodes[parent].selector, nodes[index].segment)
        };
    }
}
Input 7: outline src/outline/selector.rs struct[Segment]
/// One parsed selector segment.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Segment {
    pub(crate) kind: String,
    pub(crate) label: Label,
    pub(crate) ordinal: Option<usize>,
}
Input 8: outline src/outline/selector.rs impl[Segment]
impl Segment {
    /// The segment without its `#N` ordinal.
    pub(crate) fn base(kind: &str, label: &Label) -> String {
        match label {
            Label::Named(parts) => format!(
                "{kind}[{}]",
                parts
                    .iter()
                    .map(|part| encode_name(part))
                    .collect::<Vec<_>>()
                    .join("/")
            ),
            Label::Hash(hash) => format!("{kind}@{hash}"),
        }
    }
}
Input 9: outline src/outline/selector.rs impl[Segment/fmt::Display]/fn[fmt]
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&Self::base(&self.kind, &self.label))?;
        if let Some(ordinal) = self.ordinal {
            write!(formatter, "#{ordinal}")?;
        }
        Ok(())
    }
Input 10: outline src/outline/selector.rs fn[parse_segment]
/// Parses one segment.
fn parse_segment(selector: &str, segment: &str) -> Result<Segment, SelectorError> {
    let kind_end = segment
        .find(|character: char| !(character.is_ascii_alphanumeric() || "_-".contains(character)))
        .unwrap_or(segment.len());
    let kind = &segment[..kind_end];
    if kind.is_empty() {
        return Err(SelectorError::new(
            selector,
            format!("segment {segment:?} has no kind"),
        ));
    }
    let rest = &segment[kind_end..];
    let (label, rest) = if let Some(rest) = rest.strip_prefix('[') {
        let close = rest
            .find(']')
            .ok_or_else(|| SelectorError::new(selector, "unclosed `[`"))?;
        let parts = rest[..close]
            .split('/')
            .map(decode_name)
            .collect::<Result<Vec<_>, _>>()
            .map_err(|error| SelectorError::new(selector, error.message))?;
        (Label::Named(parts), &rest[close + 1..])
    } else if let Some(rest) = rest.strip_prefix('@') {
        let digits = rest
            .find(|character: char| !character.is_ascii_hexdigit())
            .unwrap_or(rest.len());
        if digits != HASH_DIGITS {
            return Err(SelectorError::new(
                selector,
                format!("segment {segment:?} must have {HASH_DIGITS} hex digits after `@`"),
            ));
        }
        (
            Label::Hash(rest[..digits].to_ascii_lowercase()),
            &rest[digits..],
        )
    } else {
        return Err(SelectorError::new(
            selector,
            format!("segment {segment:?} must be `kind[name]` or `kind@hash`"),
        ));
    };
    let ordinal = if rest.is_empty() {
        None
    } else {
        let ordinal = rest
            .strip_prefix('#')
            .and_then(|digits| digits.parse::<usize>().ok())
            .filter(|ordinal| *ordinal > 0)
            .ok_or_else(|| {
                SelectorError::new(
                    selector,
                    format!("segment {segment:?} has trailing text {rest:?}"),
                )
            })?;
        Some(ordinal)
    };
    Ok(Segment {
        kind: kind.to_owned(),
        label,
        ordinal,
    })
}
Input 11: outline src/outline/selector.rs mod[tests]/fn[parses_named_anonymous_and_ordinal_segments]
    // {test}`requirements.references.outline_selectors`
    #[test]
    fn parses_named_anonymous_and_ordinal_segments() {
        assert!(parse_selector("").unwrap().is_empty());
        let segments =
            parse_selector("impl[Thing/Trait%3CT%3E]/fn[run]#2/use@0123456789AB").unwrap();
        assert_eq!(
            segments[0].label,
            Label::Named(vec!["Thing".into(), "Trait<T>".into()])
        );
        assert_eq!(segments[1].ordinal, Some(2));
        assert_eq!(segments[2].label, Label::Hash("0123456789ab".into()));
        assert_eq!(segments[2].to_string(), "use@0123456789ab");
        for invalid in [
            "fn",
            "fn[run",
            "[run]",
            "fn[run]#0",
            "use@123",
            "fn[run]x",
            "a//b",
        ] {
            assert!(parse_selector(invalid).is_err(), "{invalid}");
        }
    }
Input 12: outline src/outline/tests.rs fn[a_comment_after_another_comment_on_its_line_forms_its_own_run]
// {test}`requirements.references.outline_comments`
#[test]
fn a_comment_after_another_comment_on_its_line_forms_its_own_run() {
    let source = "fn a() {}\n/* first */ /* second */\nfn b() {}\n";
    let outline = outline("src/lib.rs", source);
    assert_eq!(comment_owner(&outline, source, "first"), "fn[b]");
    // The second comment follows other text on its line, so it forms a run
    // by itself and belongs to the innermost node containing that line; no
    // item contains line 2, so that is the root.
    assert_eq!(comment_owner(&outline, source, "second"), "");
}