Skip to main content

name_token_of

Function name_token_of 

Source
pub fn name_token_of(function: &CppSyntaxNode) -> Option<CppSyntaxToken>
Expand description

The name token a declaration or definition writes — the last non-trivia token before its parameter list.

This is the one place that answers where the name is, and everything that needs the name comes through it: name_declared_by takes its text and a diagnostic takes its range. One question, one implementation — the alternative is what this replaced, which was two readers of the same fact that disagreed.

§Why the parameter list is the anchor

Because a function’s name is written immediately before its (, in every spelling this layer sees: int f(), void C::f(), Name::~Name(), operator int(), int (S::*p)(). A reader that anchored on anything else had to decide which of the tokens before the list is the name, and both earlier attempts got that wrong in a different way:

  "the last child ending before the parameter list starts"
      `take_while` stops at the FIRST child that ends after it — and the first child of
      `int unfinished() { }` is `DeclSpecifierSeq \"int \"`, which does not. So the head was
      empty and name_declared_by answered None for every definition. Measured.
  "the first identifier spelled like the name"
      matched the return type, and produced a range from `int` to the end of the file. Measured.

The list is found through the typed AST (CppParamList) rather than by comparing node kinds: the kind is ParameterList, a kind this grammar does not have under that name, so a kind comparison silently matched nothing — which is the trap status.md §5 records and the reason its rule is to use cast.

The token is returned rather than its text, because the two callers want different halves of it and both are cheaper from here: name_declared_by takes the spelling, and a diagnostic takes the range.