cpp_parser/syntax/node/cpp/mod.rs
1//! Declaration, type and module nodes.
2
3use crate::{
4 CppSyntaxNode,
5 kind::{CppKind, CppSyntaxKind, CppTokenKind},
6 syntax::traits::{CppAstChildren, CppAstNode, CppAstToken},
7};
8
9use super::{CppKeywordToken, CppNameToken, CppPunctuationToken, CppStat};
10
11mod expr;
12mod modules;
13mod stat;
14
15pub use expr::*;
16pub use modules::*;
17pub use stat::*;
18
19// ============================================================================
20// Root
21// ============================================================================
22
23/// The root of a parsed file.
24#[derive(Debug, Clone, PartialEq, Eq, Hash)]
25pub struct CppTranslationUnit {
26 syntax: CppSyntaxNode,
27}
28
29impl CppAstNode for CppTranslationUnit {
30 fn syntax(&self) -> &CppSyntaxNode {
31 &self.syntax
32 }
33
34 fn can_cast(kind: CppSyntaxKind) -> bool {
35 kind == CppSyntaxKind::TranslationUnit
36 }
37
38 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
39 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
40 }
41}
42
43impl CppTranslationUnit {
44 /// Every top-level declaration and directive, in order.
45 ///
46 /// Namespaces are *not* included: `namespace ns { ... }` is a [`CppNamespaceDecl`], a different
47 /// node kind, so iterate [`CppTranslationUnit::get_namespaces`] for those.
48 pub fn get_declarations(&self) -> CppAstChildren<CppDeclaration> {
49 self.children()
50 }
51
52 /// Every top-level namespace definition, in order.
53 pub fn get_namespaces(&self) -> CppAstChildren<CppNamespaceDecl> {
54 self.children()
55 }
56
57 pub fn get_module_decl(&self) -> Option<CppModuleDecl> {
58 self.child()
59 }
60}
61
62// ============================================================================
63// Declarations
64// ============================================================================
65
66/// One declaration: `specifiers declarators ;`, a function definition, a class, a namespace, ...
67///
68/// A single type rather than one per declaration form, because the forms differ only in which child
69/// nodes are present. Use the `get_*` accessors — or [`CppDeclaration::kind_name`] — to see which.
70#[derive(Debug, Clone, PartialEq, Eq, Hash)]
71pub struct CppDeclaration {
72 syntax: CppSyntaxNode,
73}
74
75impl CppAstNode for CppDeclaration {
76 fn syntax(&self) -> &CppSyntaxNode {
77 &self.syntax
78 }
79
80 /// Narrow on purpose, unlike [`CppDeclaration::cast`].
81 ///
82 /// `can_cast` is what [`CppAstChildren`](crate::syntax::traits::CppAstChildren) uses on every step
83 /// of an iteration, so widening it would put every `using` directive — including
84 /// `using namespace std;`, which declares nothing — into
85 /// [`CppTranslationUnit::get_declarations`].
86 fn can_cast(kind: CppSyntaxKind) -> bool {
87 kind == CppSyntaxKind::Declaration
88 }
89
90 /// Wider than [`CppDeclaration::can_cast`]: it also accepts a `using` alias, which declares a name
91 /// but has a shape that is not `specifiers declarators` and therefore its own node kind.
92 ///
93 /// This is the same asymmetry [`CppEnumDef`] has — a deliberate cast target that is not reachable
94 /// by iterating children — and it exists because the two questions differ. "List this file's
95 /// declarations" should not be polluted by directives; "what declaration does this comment
96 /// document?" must not miss `/// Doc.` in front of `using Point = shapes::Point;`.
97 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
98 // **A `typedef` is a declaration too**: it declares a name, and its declarator layer is the same as any other's. It was
99 // excluded for one reason — a `descendants::<CppDeclaration>` walk would then visit it — and the walk uses `can_cast`,
100 // which stays narrow, so the exclusion never bought anything.
101 matches!(
102 CppSyntaxKind::from(syntax.kind()),
103 CppSyntaxKind::Declaration | CppSyntaxKind::UsingDecl | CppSyntaxKind::TypedefDecl
104 )
105 .then_some(Self { syntax })
106 }
107}
108
109impl CppDeclaration {
110 /// The `decl-specifier-seq`: the type and the specifiers.
111 pub fn get_decl_specifiers(&self) -> Option<CppDeclSpecifierSeq> {
112 self.child()
113 }
114
115 /// **Is this the `typedef` form of a declaration?** — `typedef struct { … } Object;`.
116 ///
117 /// The parser produces two spellings of it: a `TypedefDecl` node of its own, and a general `Declaration` whose specifiers
118 /// begin with the keyword. Both declare the same name, and this is the one question that answers for both.
119 pub fn is_a_typedef(&self) -> bool {
120 CppSyntaxKind::from(self.syntax().kind()) == CppSyntaxKind::TypedefDecl
121 || self
122 .get_decl_specifiers()
123 .is_some_and(|specifiers| specifiers.has_keyword(CppTokenKind::TypedefKeyword))
124 }
125
126 /// Every `init-declarator`. A declaration of several entities has several of these.
127 pub fn get_init_declarators(&self) -> CppAstChildren<CppInitDeclarator> {
128 self.children()
129 }
130
131 /// The first `init-declarator`, which is the one every declaration has.
132 pub fn get_init_declarator(&self) -> Option<CppInitDeclarator> {
133 self.child()
134 }
135
136 /// **The type this declaration writes for the declarator named `name`** — `int*` for the `a` of `int* a, b;`, and `int`
137 /// for its `b`.
138 ///
139 /// A declaration carries one specifier sequence and one or more declarators, and each declarator has its own pointer,
140 /// reference and array parts. Answering "what type does this declaration give this name" without slicing the
141 /// declaration's text is what this accessor exists for; it is the question a `return` of a local asks.
142 pub fn get_type_text_of(&self, name: &str) -> Option<String> {
143 let base = self
144 .get_decl_specifiers()
145 .map(|specifiers| specifiers.get_type_text())
146 .unwrap_or_default();
147 for declarator in self.get_init_declarators() {
148 let declares_it = declarator
149 .get_name()
150 .is_some_and(|written| written.get_name_text() == name);
151 if !declares_it {
152 continue;
153 }
154 let mut the_type = base.clone();
155 if let Some(declarator) = declarator.get_declarator() {
156 the_type.push_str(&declarator.get_type_suffix());
157 }
158 let the_type = the_type.trim().to_string();
159 if !the_type.is_empty() {
160 return Some(the_type);
161 }
162 }
163 None
164 }
165
166 /// The name this declaration introduces, if it has one.
167 ///
168 /// Four places a name can live, and they are tried in order:
169 ///
170 /// * a class, struct, union or enum definition — the name is on the definition node;
171 /// * a namespace — same;
172 /// * everything else — the name is the first declarator's;
173 /// * a **forward declaration** — `class Widget;` — has no declarator at all, and the name is the type
174 /// written beside the class-like keyword. See [`CppDeclaration::elaborated_type_name`].
175 ///
176 /// Taken from the first declarator, which is what almost every caller wants. A declaration of
177 /// several entities (`int a, b;`) has more — use `get_init_declarators` for those.
178 pub fn get_name(&self) -> Option<CppNameToken> {
179 // A `using` alias: the name comes before the `=`, so it is the first `NameExpr` child. The
180 // target is a second one, nested inside a `TypeId`, which is why this is the *child* search
181 // rather than a descendant one.
182 if CppSyntaxKind::from(self.syntax.kind()) == CppSyntaxKind::UsingDecl {
183 return crate::syntax::node::traits::first_child_of_kind(
184 self.syntax(),
185 &[CppSyntaxKind::NameExpr],
186 )
187 .and_then(CppNameExpr::cast)
188 .and_then(|name| name.get_name_token());
189 }
190
191 // **A class-like specifier names the declaration only when it is a definition.** `struct S { … };` declares
192 // `S`, and the name lives on the definition node. But the *elaborated* spelling — `struct S x;`,
193 // `struct S *(lines[2]) = …` — is a **type** written in the specifier sequence, not a declaration of `S`,
194 // and the name this declaration introduces is the declarator's. Without the body test the elaborated form
195 // won: `static struct S *(lines[2]) = { 0 };` reported `S`, so every consumer that asks a declaration for
196 // its name — scopes, the fact builder, a hover — was told the variable was a type it only mentions.
197 if let Some(class) = self.get_class_def()
198 && class.get_body().is_some()
199 && let Some(name) = class.get_name()
200 {
201 return Some(name);
202 }
203
204 if let Some(enum_def) = self.get_enum_def()
205 && let Some(name) = enum_def.get_name()
206 {
207 return Some(name);
208 }
209
210 // A forward declaration — `class Widget;` — names the class through its *specifier*: there is no
211 // declarator, and the keyword and the name are all the declaration has. It is the elaborated-type-
212 // specifier spelling, so the name to report is the type written after the keyword.
213 //
214 // Checked after the declarator, not before: `class Widget x;` declares the *variable* `x` and mentions
215 // `Widget` as its type, and the declarator is the answer there.
216 if let Some(declarator) = self.get_init_declarator()
217 && let Some(name) = declarator.get_name()
218 {
219 return Some(name);
220 }
221
222 // **A constructor is a bare `Declarator`, not an `InitDeclarator`.** Its declaration has no
223 // `decl-specifier-seq` — there is no return type to write — so the grammar puts the name straight under the
224 // declaration:
225 //
226 // ```text
227 // Name(const int f); Declaration > Declarator > NameExpr, ParameterList
228 // void set(const int v); Declaration > DeclSpecifierSeq, InitDeclarator > Declarator
229 // ```
230 //
231 // Without this arm the name is not found and `get_name_text` answers `None` for a declaration that plainly
232 // has one — which `sema::scopes`' `is_unnamed_declaration` reads as *"this is a call statement, not a
233 // declaration"* and skips entirely. Measured on the pair above: the constructor's parameters were bound
234 // **nowhere**, so they were missing from completion and uncoloured by semantic tokens, while the member
235 // function's beside them were both right.
236 if let Some(declarator) = self.child::<CppDeclarator>()
237 && let Some(name) = declarator.get_name()
238 && !name.get_text().is_empty()
239 {
240 return Some(name);
241 }
242
243 // **A constructor's declaration wraps a declaration.** The grammar reads the name, the parameter list and the
244 // member-initializer list as one declaration, then reopens a declaration around the body with
245 // `CompleteMarker::precede` — so the node this is asked about has no declarator of its own and the name lives
246 // one level down:
247 //
248 // ```text
249 // Declaration ← the wrapper, which this is asked about
250 // Declaration ← the declaration proper: Declarator, MemberInitializer
251 // CompoundStat ← the body `precede` wrapped it with
252 // ```
253 //
254 // Without this the wrapper has no name, `get_name_text` answers `None`, and `sema::scopes`'
255 // `is_unnamed_declaration` reads that as *"this is a call statement, not a declaration"* and skips the whole
256 // thing: measured, the tree held only `TranslationUnit` and `Class` — no function scope at all — so a
257 // constructor's parameters were bound nowhere and neither its member-initializer list nor its body could see
258 // them.
259 if let Some(wrapped) = self.child::<CppDeclaration>()
260 && let Some(name) = wrapped.get_name()
261 && !name.get_text().is_empty()
262 {
263 return Some(name);
264 }
265
266 // **A constructor whose name the specifier sequence holds.** `explicit A(int x) : x_(x) {}` parses
267 // `explicit A` as the specifiers — the declarator is `(int x)` and names nothing — so every arm above answers
268 // `None` for a declaration that plainly has a name: no fact was made for it (`inspect facts` on
269 // `struct A { explicit A(int x); }` listed none), and `missing-return` read it as a function with a return type
270 // and reported "declared to return `` and its body has no `return`".
271 //
272 // The name is the sequence's **last** name, and it is the declaration's own when nothing in the sequence is a
273 // type: `explicit`, `inline`, `constexpr`, `virtual` and `friend` are specifiers. Guarded by the parameter
274 // list, because only a function-shaped declaration names itself this way (`A A;` writes its name in the
275 // declarator and never reaches here).
276 if self.get_param_list().is_some()
277 && let Some(specifiers) = self.get_decl_specifiers()
278 && specifiers.get_builtin_type().is_none()
279 && let Some(name) = specifiers
280 .descendants::<CppNameExpr>()
281 .last()
282 .and_then(|name| name.get_name_token())
283 {
284 return Some(name);
285 }
286
287 self.elaborated_type_name()
288 }
289
290 /// The class name of an elaborated type specifier: the `Widget` of `class Widget;`.
291 ///
292 /// `None` for every declaration whose specifiers are not a class-like keyword followed by a name, which is
293 /// what keeps this from answering for `class { ... } x;` — an unnamed class with a declarator — or for
294 /// `int x;`.
295 fn elaborated_type_name(&self) -> Option<CppNameToken> {
296 let specifiers = self.get_decl_specifiers()?;
297
298 let builtin = specifiers.get_builtin_type();
299 let has_class_keyword = builtin
300 .as_ref()
301 .is_some_and(|builtin| builtin.is_class_like());
302 if !has_class_keyword {
303 return None;
304 }
305
306 specifiers
307 .get_type_name()
308 .and_then(|name| name.get_name_token())
309 }
310
311 /// The text of the declared name.
312 pub fn get_name_text(&self) -> Option<String> {
313 self.get_name().map(|it| it.get_name_text().to_string())
314 }
315
316 /// A class name without its template arguments — `Box<T>` is `Box`.
317 ///
318 /// For comparing a constructor's last segment with its class's name: `Box<T>::Box` and `Box` are the same class,
319 /// and a comparison of the spellings would say otherwise.
320 fn without_template_arguments(written: &str) -> &str {
321 match written.find('<') {
322 Some(at) => written[..at].trim_end(),
323 None => written,
324 }
325 }
326
327 /// **Is this declaration a constructor or a destructor** — the two functions that promise no return?
328 ///
329 /// Asked of the **name**, not of the specifier sequence. `explicit A(int x) : x_(x) {}`, `virtual ~A() {}` and
330 /// `constexpr C(int x) : x_(x) {}` all carry specifiers (`explicit`, `virtual`, `constexpr` — and the first and
331 /// third keep the constructor's own name there), so a rule that asked "does this declaration write a specifier
332 /// sequence" answered *"yes: a function returning"* for every one of them. Measured: `missing-return` reported all
333 /// three as *"this function is declared to return `` and its body has no `return`"*.
334 pub fn promises_no_return(&self) -> bool {
335 // **A destructor writes `~` before its name**, wherever the parser kept the name — so the tokens before the
336 // first `(` of the declaration are what say it. A `~` inside the body (`p->~T()`) is after that paren and
337 // cannot be read here.
338 let tilde = self
339 .syntax()
340 .descendants_with_tokens()
341 .filter_map(|element| element.into_token())
342 .take_while(|token| CppTokenKind::from(token.kind()) != CppTokenKind::LeftParen)
343 .any(|token| CppTokenKind::from(token.kind()) == CppTokenKind::Tilde);
344 if tilde {
345 return true;
346 }
347
348 // **A constructor's last segment is its class's name** — `A::A`, `ns::A::A`, `Box<T>::Box`. The *qualified*
349 // spelling is the declarator's name node when the declaration writes one (an out-of-class definition), and the
350 // declared name otherwise (an in-class `explicit A(int)`).
351 let written = self
352 .get_declarator()
353 .or_else(|| self.child::<CppDeclarator>())
354 .and_then(|declarator| declarator.child::<CppNameExpr>())
355 .map(|name| name.get_qualified_name())
356 .filter(|name| !name.trim().is_empty())
357 .or_else(|| self.get_name_text());
358 let Some(written) = written else {
359 return false;
360 };
361 let written = written.trim();
362 let segments: Vec<&str> = written
363 .split("::")
364 .map(str::trim)
365 .filter(|part| !part.is_empty())
366 .collect();
367 let last = segments
368 .last()
369 .map(|part| Self::without_template_arguments(part));
370 let before = segments
371 .len()
372 .checked_sub(2)
373 .map(|at| Self::without_template_arguments(segments[at]));
374 if let (Some(last), Some(before)) = (last, before)
375 && last == before
376 {
377 return true;
378 }
379
380 // Inside a class, its own name is the constructor's.
381 let enclosing = crate::syntax::node::traits::typed_ancestors::<CppClassDef>(self.syntax())
382 .next()
383 .and_then(|class| class.get_name_text());
384 match (enclosing, last) {
385 (Some(class), Some(last)) => Self::without_template_arguments(class.trim()) == last,
386 _ => false,
387 }
388 }
389
390 /// The declarator of the first `init-declarator`.
391 pub fn get_declarator(&self) -> Option<CppDeclarator> {
392 self.get_init_declarator()?.get_declarator()
393 }
394
395 /// The initializer of the first `init-declarator`, if it has one.
396 pub fn get_initializer(&self) -> Option<CppInitializer> {
397 self.get_init_declarator()?.get_initializer()
398 }
399
400 /// The function body, if this declaration is a function definition.
401 ///
402 /// The body is a direct child of the declaration, not of the declarator: `int f() { ... }` is one
403 /// declaration whose last init-declarator is followed by a block.
404 pub fn get_body(&self) -> Option<CppCompoundStat> {
405 self.child()
406 }
407
408 /// **The parameter list this declaration writes**, when it declares a function.
409 ///
410 /// Asked of the **declarator**, not of the declaration's subtree: a function's body is a child of the declaration, so
411 /// `descendants()` over the declaration reaches every lambda in that body and answers *their* parameters as well — measured,
412 /// `auto f(int a) { auto g = [](int b) { … }; }` answered two parameters for `f`. A constructor writes its declarator
413 /// directly (`S(std::string s)`), which is the second branch.
414 pub fn get_param_list(&self) -> Option<CppParamList> {
415 self.get_init_declarator()
416 .and_then(|init| init.get_declarator())
417 .and_then(|declarator| declarator.get_param_list())
418 .or_else(|| {
419 self.children::<CppDeclarator>()
420 .find_map(|declarator| declarator.get_param_list())
421 })
422 }
423
424 /// The class, struct, union or enum this declaration defines, if any.
425 pub fn get_class_def(&self) -> Option<CppClassDef> {
426 self.get_decl_specifiers()?.get_class_def()
427 }
428
429 /// The enum this declaration defines, if any.
430 ///
431 /// A scoped enum (`enum class E`) is parsed as a single `BuiltinType` specifier rather than as an
432 /// `EnumDef`, because `class` belongs to the same specifier as `enum` — so the search has to be
433 /// by *shape* rather than by direct child. [`CppEnumDef::can_cast`] accepts both node kinds, and
434 /// only a node that actually has a body counts as a definition; an elaborated type specifier
435 /// (`enum E x;`) has no body and yields `None`.
436 pub fn get_enum_def(&self) -> Option<CppEnumDef> {
437 self.get_decl_specifiers()?
438 .syntax()
439 .descendants()
440 .filter_map(CppEnumDef::cast)
441 .find(|it| it.get_body().is_some())
442 }
443
444 pub fn get_namespace_decl(&self) -> Option<CppNamespaceDecl> {
445 self.child()
446 }
447
448 /// The template head, if this declaration is templated.
449 pub fn get_template_decl(&self) -> Option<CppTemplateDecl> {
450 self.child()
451 }
452
453 /// Is this a function definition (a declarator with a parameter list plus a body)?
454 pub fn is_function_def(&self) -> bool {
455 self.get_body().is_some() && self.get_declarator().is_some_and(|it| it.is_function())
456 }
457
458 /// Is this declaration exported? (`export` is a token, so this is a token test, not a node test.)
459 pub fn is_exported(&self) -> bool {
460 self.syntax()
461 .children_with_tokens()
462 .filter_map(|it| it.into_token())
463 .any(|token| token.kind() == CppKind::Token(CppTokenKind::ExportKeyword))
464 }
465
466 /// Which of the declaration forms this is, for diagnostics and tests.
467 ///
468 /// A namespace is not one of the answers: `namespace ns { ... }` is a `NamespaceDecl` node, not
469 /// a `Declaration`, so it never reaches here — ask the translation unit for namespaces.
470 pub fn kind_name(&self) -> &'static str {
471 // A `using` alias is its own node kind, reached through `CppDeclaration::cast` for consumers
472 // that ask "what does this document?" rather than by iterating declarations. It is an alias
473 // for the same reason `using A = B;` is, so it reports the same word.
474 if CppSyntaxKind::from(self.syntax.kind()) == CppSyntaxKind::UsingDecl {
475 "alias"
476 } else if self.get_enum_def().is_some() {
477 "enum"
478 } else if self.get_class_def().is_some() {
479 "class"
480 } else if self.get_declarator().is_some_and(|it| it.is_function()) {
481 // A parameter list is what makes a declaration a function — a body is only what makes it
482 // a *definition*, and `void reset();` is a function declaration.
483 "function"
484 } else if self.get_decl_specifiers().is_some_and(|it| it.is_alias()) {
485 "alias"
486 } else {
487 "variable"
488 }
489 }
490}
491
492/// The `decl-specifier-seq` of a declaration.
493///
494/// Deliberately flat: C++ allows the specifiers in almost any order and repeats them freely
495/// (`long long unsigned int`), so anything more structured would invent an order the language does
496/// not have. Consumers ask for what they want — the base type, the qualifiers, whether it is
497/// `static` — through the accessors here.
498#[derive(Debug, Clone, PartialEq, Eq, Hash)]
499pub struct CppDeclSpecifierSeq {
500 syntax: CppSyntaxNode,
501}
502
503impl CppAstNode for CppDeclSpecifierSeq {
504 fn syntax(&self) -> &CppSyntaxNode {
505 &self.syntax
506 }
507
508 fn can_cast(kind: CppSyntaxKind) -> bool {
509 kind == CppSyntaxKind::DeclSpecifierSeq
510 }
511
512 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
513 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
514 }
515}
516
517impl CppDeclSpecifierSeq {
518 /// **Is the type `void`** — `void f()`, `(void)x`?
519 pub fn is_void(&self) -> bool {
520 self.has_keyword(CppTokenKind::VoidKeyword)
521 }
522
523 /// **Is the type deduced from the initialiser or the returns?** — `auto`, `auto&`, `decltype(auto)`.
524 ///
525 /// A function declared with one of these promises nothing about what it returns, which is why `missing-return` asks this
526 /// rather than comparing a spelling against `"auto"`.
527 pub fn is_deduced_return_type(&self) -> bool {
528 self.has_keyword(CppTokenKind::AutoKeyword)
529 || self.has_keyword(CppTokenKind::DecltypeKeyword)
530 }
531
532 /// The built-in type specifier, if the type is a fundamental one (`int`, `const char`, ...).
533 pub fn get_builtin_type(&self) -> Option<CppBuiltinType> {
534 self.child()
535 }
536
537 /// The user-written type name, if the type is a name (`Foo`, `std::vector<int>`).
538 ///
539 /// Two spellings reach here: a **plain** name is a `NameExpr` child, while a **template-id**
540 /// (`std::vector<int>`) is wrapped — in a `NamedType` when it is a plain name and a `TemplateType` when it
541 /// carries template arguments. Both are "the name the user wrote", so both are accepted, and the wrapper is
542 /// read for either kind: this reader's question is the name, not whether the type was a template-id.
543 pub fn get_type_name(&self) -> Option<CppNameExpr> {
544 if let Some(name) = self.child::<CppNameExpr>() {
545 return Some(name);
546 }
547
548 let wrapped = crate::syntax::node::traits::first_child_of_kind(
549 self.syntax(),
550 &[CppSyntaxKind::TemplateType, CppSyntaxKind::NamedType],
551 )?;
552 wrapped.children().find_map(CppNameExpr::cast)
553 }
554
555 /// The class-like definition this specifier sequence defines, if any.
556 pub fn get_class_def(&self) -> Option<CppClassDef> {
557 self.child()
558 }
559
560 pub fn get_enum_def(&self) -> Option<CppEnumDef> {
561 self.child()
562 }
563
564 /// The `=` of a `using Alias = type;`.
565 pub fn is_alias(&self) -> bool {
566 self.syntax()
567 .children_with_tokens()
568 .filter_map(|it| it.into_token())
569 .any(|token| token.kind() == CppKind::Token(CppTokenKind::Assign))
570 }
571
572 /// Is one of these keywords present in the specifier sequence?
573 /// **The attribute lists written in this specifier sequence** — `[[maybe_unused]] int x;` inside a class body puts the
574 /// list here (measured), while at file scope it is a sibling of the declaration.
575 pub fn get_attribute_lists(&self) -> CppAstChildren<CppAttributeList> {
576 self.children()
577 }
578
579 /// Does this declaration say the attribute named `name` — `maybe_unused`, `nodiscard`?
580 pub fn has_attribute(&self, name: &str) -> bool {
581 self.get_attribute_lists().any(|list| list.has_a_name(name))
582 }
583
584 pub fn has_keyword(&self, kind: CppTokenKind) -> bool {
585 // **The keyword may sit in a specifier node of its own.** Measured: `static int x` is
586 // `DeclSpecifierSeq > [StaticSpec > Token(StaticKeyword), BuiltinType > Token(IntKeyword)]`, so a question about the
587 // *sequence's* keywords has to mean its subtree, not its direct children — a direct scan answered `false` for every
588 // `static` (which made a static local look automatic) and for `auto` inside a builtin type.
589 self.syntax()
590 .descendants_with_tokens()
591 .filter_map(|it| it.into_token())
592 .any(|token| token.kind() == kind.into())
593 }
594
595 pub fn is_const(&self) -> bool {
596 self.has_keyword(CppTokenKind::ConstKeyword)
597 }
598
599 pub fn is_static(&self) -> bool {
600 self.has_keyword(CppTokenKind::StaticKeyword)
601 }
602
603 pub fn is_virtual(&self) -> bool {
604 self.has_keyword(CppTokenKind::VirtualKeyword)
605 }
606
607 /// The text of the whole specifier sequence, trivia removed.
608 ///
609 /// Useful for presenting a type to a user without building a type model first. Walks the whole
610 /// subtree, because the type itself is a child node (`BuiltinType`, `TemplateType`), not a token
611 /// of this node.
612 pub fn get_type_text(&self) -> String {
613 crate::syntax::node::traits::subtree_text_spaced(self.syntax())
614 }
615}
616
617/// A built-in type specifier: `int`, `const char`, `decltype(x)`.
618#[derive(Debug, Clone, PartialEq, Eq, Hash)]
619pub struct CppBuiltinType {
620 syntax: CppSyntaxNode,
621}
622
623impl CppAstNode for CppBuiltinType {
624 fn syntax(&self) -> &CppSyntaxNode {
625 &self.syntax
626 }
627
628 fn can_cast(kind: CppSyntaxKind) -> bool {
629 kind == CppSyntaxKind::BuiltinType
630 }
631
632 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
633 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
634 }
635}
636
637impl CppBuiltinType {
638 /// The keyword, if the specifier is a single keyword.
639 pub fn get_keyword(&self) -> Option<CppKeywordToken> {
640 self.token()
641 }
642
643 pub fn get_type_text(&self) -> String {
644 crate::syntax::node::traits::subtree_text_spaced(self.syntax())
645 }
646
647 /// Is this specifier a class-like keyword — `class`, `struct`, `union` or `enum`?
648 ///
649 /// Asked by callers that need to tell an **elaborated type specifier** — `class Widget;`, where the keyword
650 /// names a kind of type and the name after it is the type — from every other use of those keywords, where a
651 /// body or a base clause follows and the keyword is the head of a definition.
652 pub fn is_class_like(&self) -> bool {
653 matches!(
654 self.syntax()
655 .children_with_tokens()
656 .next()
657 .and_then(|element| element.into_token())
658 .map(|token| token.kind()),
659 Some(CppKind::Token(CppTokenKind::ClassKeyword))
660 | Some(CppKind::Token(CppTokenKind::StructKeyword))
661 | Some(CppKind::Token(CppTokenKind::UnionKeyword))
662 | Some(CppKind::Token(CppTokenKind::EnumKeyword))
663 )
664 }
665}
666
667/// The `type-id` of a cast, `sizeof`, parameter or template argument.
668#[derive(Debug, Clone, PartialEq, Eq, Hash)]
669pub struct CppTypeId {
670 syntax: CppSyntaxNode,
671}
672
673impl CppAstNode for CppTypeId {
674 fn syntax(&self) -> &CppSyntaxNode {
675 &self.syntax
676 }
677
678 fn can_cast(kind: CppSyntaxKind) -> bool {
679 matches!(
680 kind,
681 CppSyntaxKind::TypeId | CppSyntaxKind::TrailingReturnType
682 )
683 }
684
685 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
686 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
687 }
688}
689
690impl CppTypeId {
691 /// **Is this type spelled `void`** — `(void)expr`, the cast that discards its operand?
692 pub fn is_void(&self) -> bool {
693 self.get_decl_specifiers()
694 .is_some_and(|specifiers| specifiers.has_keyword(CppTokenKind::VoidKeyword))
695 }
696
697 pub fn get_decl_specifiers(&self) -> Option<CppDeclSpecifierSeq> {
698 self.child()
699 }
700
701 pub fn get_type_text(&self) -> String {
702 let text = self.syntax().text().to_string();
703 text.split_whitespace().collect::<Vec<_>>().join(" ")
704 }
705}
706
707/// A `declarator`: the part that names the entity, possibly wrapped in pointers, references, arrays,
708/// function parameter lists and template argument lists.
709#[derive(Debug, Clone, PartialEq, Eq, Hash)]
710pub struct CppDeclarator {
711 syntax: CppSyntaxNode,
712}
713
714impl CppAstNode for CppDeclarator {
715 fn syntax(&self) -> &CppSyntaxNode {
716 &self.syntax
717 }
718
719 fn can_cast(kind: CppSyntaxKind) -> bool {
720 kind == CppSyntaxKind::Declarator
721 }
722
723 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
724 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
725 }
726}
727
728impl CppDeclarator {
729 /// The declared name.
730 ///
731 /// Found among the child nodes rather than the direct tokens: a qualified or templated name
732 /// (`ns::Foo<int>`) is itself a node, so the identifier is one level down.
733 ///
734 /// **A parenthesised declarator keeps it further down still** — `int (*f)(int)` is `Declarator > Declarator >
735 /// NameExpr`, and the parentheses exist precisely to bind the operators to that name rather than to the
736 /// function's. A walk that stopped at the first level answered `None` for every shape the language uses to
737 /// declare a function pointer: measured on `int (*f)(int);`, `int (&f)(void);` and neovim's
738 /// `static char *(names[3]) = …` — three declarations that plainly name something and that
739 /// `sema::scopes::is_unnamed_declaration` read as *"a call statement, not a declaration"*.
740 pub fn get_name(&self) -> Option<CppNameToken> {
741 if let Some(name) = self.token().or_else(|| {
742 self.child::<CppNameExpr>()
743 .and_then(|it| it.get_name_token())
744 }) {
745 return Some(name);
746 }
747
748 // A nested declarator names the same entity: the group holds the declarator, and the operators the grammar
749 // put in front of it decorate that one name.
750 self.child::<CppDeclarator>()?.get_name()
751 }
752
753 pub fn get_name_text(&self) -> Option<String> {
754 self.get_name().map(|it| it.get_name_text().to_string())
755 }
756
757 /// **The pointer and reference types this declarator writes**, its nested declarators' included.
758 ///
759 /// `int* p` is `Declarator > Declarator > PointerType` (measured), so a one-level search finds nothing; a declaration's own
760 /// type parts are the chain of `PointerType`/`ReferenceType`/`RValueReferenceType` nodes under it.
761 pub fn get_pointer_types(&self) -> Vec<CppPointerType> {
762 let mut found = Vec::new();
763 let mut current = Some(self.clone());
764 while let Some(declarator) = current {
765 for child in declarator.syntax().children() {
766 if let Some(pointer) = CppPointerType::cast(child) {
767 found.push(pointer);
768 }
769 }
770 current = declarator.child::<CppDeclarator>();
771 }
772 found
773 }
774
775 /// Is this the declarator of a **reference** — `int& r`, `int&& rr`?
776 pub fn is_a_reference(&self) -> bool {
777 self.get_pointer_types()
778 .iter()
779 .any(|pointer| pointer.is_reference())
780 }
781
782 /// Is this the declarator of a **pointer** — `int* p`? A pointer-to-a-reference is not a C++ type, so the two answers
783 /// cannot both be true for one declarator in practice; the reference is checked first by the callers that care.
784 pub fn is_a_pointer(&self) -> bool {
785 self.get_pointer_types()
786 .iter()
787 .any(|pointer| !pointer.is_reference())
788 }
789
790 /// **The declarator's type parts, without its name**: `*`, `&`, `&&`, `[3]`, in source order.
791 ///
792 /// What a type spelling needs from a declarator. The name is the declarator's own and not part of the type, and the
793 /// parameter list of a function declarator is a signature rather than a type.
794 pub fn get_type_suffix(&self) -> String {
795 let mut out = String::new();
796 for element in self.syntax().children_with_tokens() {
797 match element {
798 rowan::NodeOrToken::Node(child) => match CppSyntaxKind::from(child.kind()) {
799 // `CppPointerType` covers all three of `*`, `&` and `&&`.
800 CppSyntaxKind::PointerType
801 | CppSyntaxKind::ReferenceType
802 | CppSyntaxKind::RValueReferenceType => {
803 if let Some(pointer) = CppPointerType::cast(child) {
804 out.push_str(&pointer.get_operator_text());
805 }
806 }
807 CppSyntaxKind::ArrayType => {
808 if let Some(array) = CppArrayType::cast(child) {
809 out.push_str(&array.get_type_text());
810 }
811 }
812 // **A nested declarator is where a pointer lives**: `int* p` is `Declarator > Declarator > PointerType`,
813 // measured, so the outer level has to hand the question down rather than answer nothing.
814 CppSyntaxKind::Declarator => {
815 if let Some(inner) = CppDeclarator::cast(child) {
816 out.push_str(&inner.get_type_suffix());
817 }
818 }
819 _ => {}
820 },
821 rowan::NodeOrToken::Token(token) => match token.kind() {
822 CppKind::Token(CppTokenKind::Star)
823 | CppKind::Token(CppTokenKind::Ampersand)
824 | CppKind::Token(CppTokenKind::LogicalAnd) => {
825 out.push_str(token.text());
826 }
827 _ => {}
828 },
829 }
830 }
831 out
832 }
833
834 /// The full spelling of this declarator including the name, trivia removed.
835 pub fn get_declarator_text(&self) -> String {
836 self.syntax()
837 .children_with_tokens()
838 .filter_map(|it| it.into_token())
839 .filter(|token| !crate::syntax::node::traits::is_trivia(token.kind().into()))
840 .map(|token| token.text().to_string())
841 .collect::<Vec<_>>()
842 .join("")
843 .chars()
844 .filter(|it| !it.is_whitespace())
845 .collect()
846 }
847
848 /// The parameter list, if this declarator declares a function.
849 ///
850 /// # The parenthesised declarator, whose list is a **sibling**
851 ///
852 /// `void (foo) (int a, char *b);` parses as
853 ///
854 /// ```text
855 /// InitDeclarator "(foo) (int a, char *b)"
856 /// Declarator "(foo)"
857 /// Declarator "foo"
858 /// ParameterList "(int a, char *b)" <- beside the declarator, not inside it
859 /// ```
860 ///
861 /// so the direct-child search found nothing and the declaration read as a function with **no** parameters. Lua
862 /// writes its whole public API that way (`LUA_API void (lua_setfield) (lua_State *L, int idx, const char *k);`),
863 /// and the measurements were: a `Function` fact with no `parameter_list` (the hover card printed `lua_setfield(…)`
864 /// and no inlay hint was placed), and its parameters filed as **file-scope variables**.
865 ///
866 /// The guard is the `*`: `void (*bar)(int a);` has the same node shape and is a *variable* declared as a function
867 /// pointer, whose list belongs to the pointed-to type rather than to `bar`. A parenthesised declarator with a
868 /// pointer or a reference inside it is that shape, and it keeps answering `None`.
869 pub fn get_param_list(&self) -> Option<CppParamList> {
870 self.child().or_else(|| {
871 let parent = self.syntax().parent()?;
872 if CppSyntaxKind::from(parent.kind()) != CppSyntaxKind::InitDeclarator {
873 return None;
874 }
875 if self.is_a_pointer() || self.is_a_reference() {
876 return None;
877 }
878 parent.children().find_map(CppParamList::cast)
879 })
880 }
881
882 /// The trailing return type after `->`, if this declarator has one.
883 ///
884 /// The returned node is the `TypeId` inside the `TrailingReturnType` wrapper, so its text is the
885 /// type as written (`int*`) and does not include the `->`.
886 pub fn get_trailing_return_type(&self) -> Option<CppTypeId> {
887 let wrapper = crate::syntax::node::traits::first_child_of_kind(
888 self.syntax(),
889 &[CppSyntaxKind::TrailingReturnType],
890 );
891
892 match wrapper {
893 Some(wrapper) => wrapper.children().find_map(CppTypeId::cast),
894 // A grammar that puts the `TypeId` directly under the declarator is still understood.
895 None => crate::syntax::node::traits::first_child_of_kind(
896 self.syntax(),
897 &[CppSyntaxKind::TypeId],
898 )
899 .and_then(CppTypeId::cast),
900 }
901 }
902
903 /// The first pointer/reference operator, if any.
904 pub fn get_pointer_type(&self) -> Option<CppPointerType> {
905 self.child()
906 }
907
908 /// Is this a function declarator?
909 ///
910 /// True when there is a parameter list or a trailing return type. This is the test that decides
911 /// whether a following `{` is a function body or a brace initializer.
912 pub fn is_function(&self) -> bool {
913 self.get_param_list().is_some() || self.get_trailing_return_type().is_some()
914 }
915
916 /// Is this an array declarator?
917 pub fn is_array(&self) -> bool {
918 self.get_array_type().is_some()
919 }
920
921 pub fn get_array_type(&self) -> Option<CppArrayType> {
922 self.child()
923 }
924
925 /// The structured binding this declarator introduces, if it is one: the `[a, b]` of
926 /// `auto [a, b] = pair;`.
927 ///
928 /// Two shapes reach here, because the `&` of `auto& [k, v]` is an abstract declarator and the
929 /// pattern comes after it: the `StructuredBinding` is either a child of this declarator or a
930 /// child of the `InitDeclarator` beside it. Both are searched, so a caller asking "is this a
931 /// binding?" gets one answer rather than having to know which spelling produced the node.
932 pub fn get_structured_binding(&self) -> Option<CppStructuredBinding> {
933 if let Some(binding) = self.child::<CppStructuredBinding>() {
934 return Some(binding);
935 }
936
937 self.syntax()
938 .parent()
939 .and_then(|parent| {
940 crate::syntax::node::traits::first_child_of_kind(
941 &parent,
942 &[CppSyntaxKind::StructuredBinding],
943 )
944 })
945 .and_then(CppStructuredBinding::cast)
946 }
947
948 /// Is this a structured binding declarator?
949 pub fn is_structured_binding(&self) -> bool {
950 self.get_structured_binding().is_some()
951 }
952
953 /// The names a structured binding introduces. Empty for an ordinary declarator.
954 pub fn get_binding_names(&self) -> Vec<CppNameToken> {
955 self.get_structured_binding()
956 .map(|binding| binding.get_names().collect())
957 .unwrap_or_default()
958 }
959}
960
961/// A structured binding's name list: the `[a, b]` of `auto [a, b] = pair;`.
962///
963/// The names are `NameExpr` children rather than declarators, because that is the node a name
964/// reference gets — so "which names does this declaration introduce?" is one query over one kind.
965#[derive(Debug, Clone, PartialEq, Eq, Hash)]
966pub struct CppStructuredBinding {
967 syntax: CppSyntaxNode,
968}
969
970impl CppAstNode for CppStructuredBinding {
971 fn syntax(&self) -> &CppSyntaxNode {
972 &self.syntax
973 }
974
975 fn can_cast(kind: CppSyntaxKind) -> bool {
976 kind == CppSyntaxKind::StructuredBinding
977 }
978
979 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
980 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
981 }
982}
983
984impl CppStructuredBinding {
985 /// The identifiers bound, in order.
986 ///
987 /// A pack expansion (`[... xs]`) contributes the names it names and nothing for the `...`: what it
988 /// expands to is a semantic question, and a syntactic layer that guessed would be wrong for every
989 /// pack whose size is not yet known.
990 pub fn get_names(&self) -> impl Iterator<Item = CppNameToken> {
991 self.syntax()
992 .descendants()
993 .filter_map(CppNameExpr::cast)
994 .filter_map(|name| name.get_name_token())
995 }
996
997 /// The names as text.
998 pub fn get_name_texts(&self) -> Vec<String> {
999 self.get_names()
1000 .map(|name| name.get_name_text().to_string())
1001 .collect()
1002 }
1003
1004 /// How many names the pattern binds.
1005 pub fn len(&self) -> usize {
1006 self.get_names().count()
1007 }
1008
1009 pub fn is_empty(&self) -> bool {
1010 self.len() == 0
1011 }
1012
1013 /// Is any of the names a pack expansion (`...`)?
1014 pub fn is_pack_expansion(&self) -> bool {
1015 self.syntax()
1016 .children_with_tokens()
1017 .filter_map(|it| it.into_token())
1018 .any(|token| token.kind() == CppKind::Token(CppTokenKind::Ellipsis))
1019 }
1020}
1021
1022/// An `init-declarator`: a declarator plus an optional initializer.
1023#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1024pub struct CppInitDeclarator {
1025 syntax: CppSyntaxNode,
1026}
1027
1028impl CppAstNode for CppInitDeclarator {
1029 fn syntax(&self) -> &CppSyntaxNode {
1030 &self.syntax
1031 }
1032
1033 fn can_cast(kind: CppSyntaxKind) -> bool {
1034 kind == CppSyntaxKind::InitDeclarator
1035 }
1036
1037 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
1038 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
1039 }
1040}
1041
1042impl CppInitDeclarator {
1043 pub fn get_declarator(&self) -> Option<CppDeclarator> {
1044 self.child()
1045 }
1046
1047 pub fn get_name(&self) -> Option<CppNameToken> {
1048 // A structured binding has no single name: `auto [a, b] = pair;` declares two. The declarator
1049 // is where the pattern lives, so this answers with the first of them rather than with the
1050 // rendered pattern, and [`CppDeclarator::get_binding_names`] is the accessor for all of them.
1051 if let Some(binding) = self.get_structured_binding() {
1052 return binding.get_names().next();
1053 }
1054
1055 self.get_declarator()?.get_name()
1056 }
1057
1058 /// **The `requires`-clause written after the declarator**, when the declaration has one.
1059 ///
1060 /// `void constrained(int x) const requires (x > 0) {}` is an `InitDeclarator` holding the declarator (with its
1061 /// `const`) and a `RequiresClause` after it, so the clause is this node's sibling rather than part of the declarator.
1062 pub fn get_requires_clause(&self) -> Option<CppRequiresClause> {
1063 self.child()
1064 }
1065
1066 pub fn get_initializer(&self) -> Option<CppInitializer> {
1067 self.child()
1068 }
1069
1070 /// The structured binding this init-declarator introduces, in either spelling.
1071 ///
1072 /// `auto [a, b] = pair;` puts the pattern directly under the init-declarator, while
1073 /// `auto& [k, v] = map;` puts it inside the declarator, after the `&`. This is the one place that
1074 /// knows both, so a caller asking "is this a binding?" gets one answer.
1075 pub fn get_structured_binding(&self) -> Option<CppStructuredBinding> {
1076 if let Some(binding) = self.child::<CppStructuredBinding>() {
1077 return Some(binding);
1078 }
1079
1080 self.get_declarator()?.get_structured_binding()
1081 }
1082
1083 pub fn is_structured_binding(&self) -> bool {
1084 self.get_structured_binding().is_some()
1085 }
1086}
1087
1088/// What follows `=`, or a brace-or-equal initializer.
1089#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1090pub struct CppInitializer {
1091 syntax: CppSyntaxNode,
1092}
1093
1094impl CppAstNode for CppInitializer {
1095 fn syntax(&self) -> &CppSyntaxNode {
1096 &self.syntax
1097 }
1098
1099 fn can_cast(kind: CppSyntaxKind) -> bool {
1100 kind == CppSyntaxKind::Initializer
1101 }
1102
1103 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
1104 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
1105 }
1106}
1107
1108impl CppInitializer {
1109 /// The initializing expression, if it is an expression rather than a braced list.
1110 pub fn get_expr(&self) -> Option<CppExpr> {
1111 self.child()
1112 }
1113
1114 /// The braced initializer list, if this is `{...}`.
1115 pub fn get_init_list(&self) -> Option<CppInitListExpr> {
1116 self.child()
1117 }
1118}
1119
1120/// A pointer or reference operator in a declarator.
1121#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1122pub struct CppPointerType {
1123 syntax: CppSyntaxNode,
1124}
1125
1126impl CppAstNode for CppPointerType {
1127 fn syntax(&self) -> &CppSyntaxNode {
1128 &self.syntax
1129 }
1130
1131 fn can_cast(kind: CppSyntaxKind) -> bool {
1132 matches!(
1133 kind,
1134 CppSyntaxKind::PointerType
1135 | CppSyntaxKind::ReferenceType
1136 | CppSyntaxKind::RValueReferenceType
1137 )
1138 }
1139
1140 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
1141 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
1142 }
1143}
1144
1145impl CppPointerType {
1146 pub fn is_rvalue_reference(&self) -> bool {
1147 CppSyntaxKind::from(self.syntax().kind()) == CppSyntaxKind::RValueReferenceType
1148 }
1149
1150 pub fn is_reference(&self) -> bool {
1151 matches!(
1152 CppSyntaxKind::from(self.syntax().kind()),
1153 CppSyntaxKind::ReferenceType | CppSyntaxKind::RValueReferenceType
1154 )
1155 }
1156
1157 /// The `*`, `&` or `&&` this pointer type is written with.
1158 ///
1159 /// Asked by **token kind**, which is what the grammar guarantees: the token *class* is a lexer's classification, and a
1160 /// `*` is an operator rather than punctuation — a `CppPunctuationToken` cast of it answers `None`.
1161 pub fn get_operator_text(&self) -> String {
1162 for kind in [
1163 CppTokenKind::Star,
1164 CppTokenKind::Ampersand,
1165 CppTokenKind::LogicalAnd,
1166 ] {
1167 if let Some(token) = self.token_by_kind(kind) {
1168 return token.get_text().to_string();
1169 }
1170 }
1171 String::new()
1172 }
1173
1174 pub fn get_operator_token(&self) -> Option<CppPunctuationToken> {
1175 self.token()
1176 }
1177}
1178
1179/// An array declarator: `arr[10]`.
1180#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1181pub struct CppArrayType {
1182 syntax: CppSyntaxNode,
1183}
1184
1185impl CppAstNode for CppArrayType {
1186 fn syntax(&self) -> &CppSyntaxNode {
1187 &self.syntax
1188 }
1189
1190 fn can_cast(kind: CppSyntaxKind) -> bool {
1191 kind == CppSyntaxKind::ArrayType
1192 }
1193
1194 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
1195 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
1196 }
1197}
1198
1199impl CppArrayType {
1200 /// The array bound, if it is written. `int a[]` has none.
1201 pub fn get_size_expr(&self) -> Option<CppExpr> {
1202 self.child()
1203 }
1204
1205 /// The array part of a spelling — `[3]`, `[]`, `[N + 1]` — with trivia dropped, so a type reads `int[3]`.
1206 pub fn get_type_text(&self) -> String {
1207 crate::syntax::node::traits::subtree_text(self.syntax())
1208 }
1209}
1210
1211/// **Append a spelling to a type being composed**, with a space only where two word-like tokens would otherwise merge.
1212///
1213/// The one rule a token walk needs to produce `const std::string&` and `int*` from the same code: `unsigned` `char` keeps the
1214/// space, `int` `*` does not, and `std` `::` does not either.
1215fn push_a_spelling(out: &mut String, spelling: &str) {
1216 let word_like = |character: char| character.is_alphanumeric() || character == '_';
1217 if out.chars().next_back().is_some_and(word_like)
1218 && spelling.chars().next().is_some_and(word_like)
1219 {
1220 out.push(' ');
1221 }
1222 out.push_str(spelling);
1223}
1224
1225/// A trailing return type: the `-> Widget` of `auto make() -> Widget`.
1226#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1227pub struct CppTrailingReturnType {
1228 syntax: CppSyntaxNode,
1229}
1230
1231impl CppAstNode for CppTrailingReturnType {
1232 fn syntax(&self) -> &CppSyntaxNode {
1233 &self.syntax
1234 }
1235
1236 fn can_cast(kind: CppSyntaxKind) -> bool {
1237 kind == CppSyntaxKind::TrailingReturnType
1238 }
1239
1240 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
1241 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
1242 }
1243}
1244
1245impl CppTrailingReturnType {
1246 /// The type after the arrow.
1247 pub fn get_type_id(&self) -> Option<CppTypeId> {
1248 self.child()
1249 }
1250}
1251
1252/// A `friend` declaration: `friend class B;`, `friend void f();`, `friend std::ostream& operator<<(…);`.
1253#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1254pub struct CppFriendDecl {
1255 syntax: CppSyntaxNode,
1256}
1257
1258impl CppAstNode for CppFriendDecl {
1259 fn syntax(&self) -> &CppSyntaxNode {
1260 &self.syntax
1261 }
1262
1263 fn can_cast(kind: CppSyntaxKind) -> bool {
1264 kind == CppSyntaxKind::FriendDecl
1265 }
1266
1267 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
1268 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
1269 }
1270}
1271
1272impl CppFriendDecl {
1273 /// The declaration the `friend` introduces — `friend class B;` wraps `class B;`.
1274 pub fn get_declaration(&self) -> Option<CppDeclaration> {
1275 self.child()
1276 }
1277
1278 /// **The name this friendship grants** — `B` for `friend class B;`, `f` for `friend void f();`.
1279 pub fn get_name_text(&self) -> Option<String> {
1280 self.get_declaration()?.get_name_text()
1281 }
1282}
1283
1284/// One entry of a constructor's member-initializer list: `: v(s)`, `: v{s}`, `: Base(args)`.
1285#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1286pub struct CppMemberInitializer {
1287 syntax: CppSyntaxNode,
1288}
1289
1290impl CppAstNode for CppMemberInitializer {
1291 fn syntax(&self) -> &CppSyntaxNode {
1292 &self.syntax
1293 }
1294
1295 fn can_cast(kind: CppSyntaxKind) -> bool {
1296 kind == CppSyntaxKind::MemberInitializer
1297 }
1298
1299 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
1300 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
1301 }
1302}
1303
1304impl CppMemberInitializer {
1305 /// The member (or base) this initialises.
1306 pub fn get_name(&self) -> Option<CppNameToken> {
1307 self.child::<CppNameExpr>()?.get_name_token()
1308 }
1309
1310 pub fn get_name_text(&self) -> Option<String> {
1311 self.get_name().map(|name| name.get_name_text().to_string())
1312 }
1313
1314 /// **The expression it initialises with** — `s` in `: v(s)`, and the braced element in `: v{s}`.
1315 pub fn get_argument(&self) -> Option<CppExpr> {
1316 if let Some(list) = self.child::<CppArgList>() {
1317 return list.get_args().next();
1318 }
1319 if let Some(braced) = self.child::<CppInitListExpr>() {
1320 return braced.get_elements().next();
1321 }
1322 self.children::<CppExpr>().next()
1323 }
1324}
1325
1326/// A requires-expression: `requires (T value) { value.size(); }` — a **question** about a type, not a definition.
1327#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1328pub struct CppRequiresExpr {
1329 syntax: CppSyntaxNode,
1330}
1331
1332impl CppAstNode for CppRequiresExpr {
1333 fn syntax(&self) -> &CppSyntaxNode {
1334 &self.syntax
1335 }
1336
1337 fn can_cast(kind: CppSyntaxKind) -> bool {
1338 kind == CppSyntaxKind::RequiresExpr
1339 }
1340
1341 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
1342 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
1343 }
1344}
1345
1346/// A `requires`-clause: `requires (x > 0)`, `requires std::integral<T>`.
1347#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1348pub struct CppRequiresClause {
1349 syntax: CppSyntaxNode,
1350}
1351
1352impl CppAstNode for CppRequiresClause {
1353 fn syntax(&self) -> &CppSyntaxNode {
1354 &self.syntax
1355 }
1356
1357 fn can_cast(kind: CppSyntaxKind) -> bool {
1358 kind == CppSyntaxKind::RequiresClause
1359 }
1360
1361 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
1362 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
1363 }
1364}
1365
1366impl CppRequiresClause {
1367 /// The clause **as the file spells it**, keyword included — what a card prints after a signature.
1368 pub fn get_clause_text(&self) -> String {
1369 crate::syntax::node::traits::subtree_text_spaced(self.syntax())
1370 }
1371}
1372
1373/// An attribute list: `[[maybe_unused]]`, `[[nodiscard("why")]]`, `[[gnu::always_inline]]`.
1374///
1375/// The layer names it so that a caller can ask **whether a declaration says an attribute** instead of searching the text in
1376/// front of it — and so that the walk over several lists (`[[a]] [[b]] int x;`) is a sibling walk rather than a string scan.
1377#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1378pub struct CppAttributeList {
1379 syntax: CppSyntaxNode,
1380}
1381
1382impl CppAstNode for CppAttributeList {
1383 fn syntax(&self) -> &CppSyntaxNode {
1384 &self.syntax
1385 }
1386
1387 fn can_cast(kind: CppSyntaxKind) -> bool {
1388 kind == CppSyntaxKind::AttributeList
1389 }
1390
1391 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
1392 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
1393 }
1394}
1395
1396impl CppAttributeList {
1397 /// Every name the list writes — `maybe_unused` for `[[maybe_unused]]`, and both halves of `[[gnu::always_inline]]`.
1398 ///
1399 /// The identifiers are the list's own tokens; a namespace prefix (`gnu::`) is a name of its own, which is what a caller
1400 /// matching a whole attribute spelling needs to see.
1401 pub fn get_names(&self) -> Vec<String> {
1402 self.syntax()
1403 .descendants_with_tokens()
1404 .filter_map(|element| element.into_token())
1405 .filter(|token| token.kind() == CppKind::Token(CppTokenKind::Identifier))
1406 .map(|token| token.text().to_string())
1407 .collect()
1408 }
1409
1410 /// Does the list name this attribute?
1411 pub fn has_a_name(&self, name: &str) -> bool {
1412 self.get_names().iter().any(|known| known == name)
1413 }
1414}
1415
1416/// A function parameter list, including its parentheses.
1417#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1418pub struct CppParamList {
1419 syntax: CppSyntaxNode,
1420}
1421
1422impl CppAstNode for CppParamList {
1423 fn syntax(&self) -> &CppSyntaxNode {
1424 &self.syntax
1425 }
1426
1427 fn can_cast(kind: CppSyntaxKind) -> bool {
1428 kind == CppSyntaxKind::ParameterList
1429 }
1430
1431 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
1432 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
1433 }
1434}
1435
1436impl CppParamList {
1437 pub fn get_params(&self) -> CppAstChildren<CppParam> {
1438 self.children()
1439 }
1440
1441 /// Is the list `(...)` — an old-style variadic function?
1442 pub fn is_variadic(&self) -> bool {
1443 self.syntax()
1444 .children_with_tokens()
1445 .filter_map(|it| it.into_token())
1446 .any(|token| token.kind() == CppKind::Token(CppTokenKind::Ellipsis))
1447 }
1448}
1449
1450/// One function parameter.
1451#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1452pub struct CppParam {
1453 syntax: CppSyntaxNode,
1454}
1455
1456impl CppAstNode for CppParam {
1457 fn syntax(&self) -> &CppSyntaxNode {
1458 &self.syntax
1459 }
1460
1461 fn can_cast(kind: CppSyntaxKind) -> bool {
1462 kind == CppSyntaxKind::Parameter
1463 }
1464
1465 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
1466 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
1467 }
1468}
1469
1470impl CppParam {
1471 pub fn get_decl_specifiers(&self) -> Option<CppDeclSpecifierSeq> {
1472 self.child()
1473 }
1474
1475 pub fn get_declarator(&self) -> Option<CppDeclarator> {
1476 self.child()
1477 }
1478
1479 /// The parameter name. Unnamed parameters (`void f(int)`) have none.
1480 pub fn get_name(&self) -> Option<CppNameToken> {
1481 self.get_declarator()?.get_name()
1482 }
1483
1484 /// The parameter's name as text, for comparing one name against another.
1485 pub fn get_name_text(&self) -> Option<String> {
1486 self.get_name().map(|name| name.get_name_text().to_string())
1487 }
1488
1489 /// **Is this parameter written `auto`** — the placeholder of a generic lambda (`[](auto v) { … }`)?
1490 ///
1491 /// Asked by **token kind**, and of the tokens written **before the declarator**, because that is where a type goes: the
1492 /// parameter's own `auto` is a token beside the declarator rather than inside a specifier node (measured:
1493 /// `Parameter "auto v" > [Declarator "v"]`, with `auto` a token child), so a `DeclSpecifierSeq` search alone would miss
1494 /// it.
1495 pub fn is_auto(&self) -> bool {
1496 // **The keyword lives inside the builtin type**, not as a direct token of the specifier sequence: measured,
1497 // `Parameter > [DeclSpecifierSeq > BuiltinType > Token(AutoKeyword), Declarator]`. `has_keyword` asks the specifier's
1498 // own children and therefore misses it, which is why this asks the builtin type's keyword.
1499 self.get_decl_specifiers()
1500 .and_then(|specifiers| specifiers.get_builtin_type())
1501 .and_then(|builtin| builtin.get_keyword())
1502 .is_some_and(|keyword| {
1503 keyword.get_keyword_kind() == CppKind::Token(CppTokenKind::AutoKeyword)
1504 })
1505 }
1506
1507 /// **The type this parameter is written with**, as the file spells it: `const std::string&` for
1508 /// `const std::string& name`, `int*` for `int* p`, `int` for `int`.
1509 ///
1510 /// Composed from the tree — the specifier sequence's own type text and the declarator's pointer, reference and array
1511 /// parts — rather than by cutting the parameter's text at its name. The cut is wrong for a name that occurs in the type as
1512 /// well (`int int_`), and it has to decide what to do with a default value and a pack expansion.
1513 pub fn get_type_text(&self) -> String {
1514 let mut the_type = String::new();
1515 for element in self.syntax().children_with_tokens() {
1516 match element {
1517 rowan::NodeOrToken::Node(child) => {
1518 // **The declarator's type parts and then nothing**: what follows a declarator is a default value or a
1519 // trailing qualifier, neither of which is the type.
1520 if let Some(declarator) = CppDeclarator::cast(child.clone()) {
1521 the_type.push_str(&declarator.get_type_suffix());
1522 break;
1523 }
1524 if let Some(specifiers) = CppDeclSpecifierSeq::cast(child) {
1525 push_a_spelling(&mut the_type, &specifiers.get_type_text());
1526 }
1527 }
1528 rowan::NodeOrToken::Token(token) => {
1529 if !crate::syntax::node::traits::is_trivia(token.kind().into()) {
1530 push_a_spelling(&mut the_type, token.text());
1531 }
1532 }
1533 }
1534 }
1535 the_type.trim().to_string()
1536 }
1537
1538 pub fn get_default_value(&self) -> Option<CppInitializer> {
1539 self.child()
1540 }
1541}
1542
1543// ============================================================================
1544// Class-like definitions
1545// ============================================================================
1546
1547/// A class, struct or union definition: `class Foo : public Bar { ... };`.
1548#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1549pub struct CppClassDef {
1550 syntax: CppSyntaxNode,
1551}
1552
1553impl CppAstNode for CppClassDef {
1554 fn syntax(&self) -> &CppSyntaxNode {
1555 &self.syntax
1556 }
1557
1558 fn can_cast(kind: CppSyntaxKind) -> bool {
1559 matches!(
1560 kind,
1561 CppSyntaxKind::ClassDef | CppSyntaxKind::StructDef | CppSyntaxKind::UnionDef
1562 )
1563 }
1564
1565 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
1566 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
1567 }
1568}
1569
1570impl CppClassDef {
1571 /// The class name. Anonymous classes have none.
1572 pub fn get_name(&self) -> Option<CppNameToken> {
1573 self.child::<CppNameExpr>()
1574 .and_then(|it| it.get_name_token())
1575 }
1576
1577 pub fn get_name_text(&self) -> Option<String> {
1578 self.get_name().map(|it| it.get_name_text().to_string())
1579 }
1580
1581 pub fn is_struct(&self) -> bool {
1582 CppSyntaxKind::from(self.syntax().kind()) == CppSyntaxKind::StructDef
1583 }
1584
1585 pub fn is_union(&self) -> bool {
1586 CppSyntaxKind::from(self.syntax().kind()) == CppSyntaxKind::UnionDef
1587 }
1588
1589 /// The body, including its access specifier sections.
1590 pub fn get_body(&self) -> Option<CppClassBody> {
1591 self.child()
1592 }
1593
1594 /// The base classes.
1595 pub fn get_base_specifiers(&self) -> CppAstChildren<CppBaseSpecifier> {
1596 self.children()
1597 }
1598}
1599
1600/// The `{ ... }` of a class definition.
1601#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1602pub struct CppClassBody {
1603 syntax: CppSyntaxNode,
1604}
1605
1606impl CppAstNode for CppClassBody {
1607 fn syntax(&self) -> &CppSyntaxNode {
1608 &self.syntax
1609 }
1610
1611 fn can_cast(kind: CppSyntaxKind) -> bool {
1612 kind == CppSyntaxKind::ClassBody
1613 }
1614
1615 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
1616 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
1617 }
1618}
1619
1620impl CppClassBody {
1621 /// The member declarations of the class.
1622 pub fn get_members(&self) -> CppAstChildren<CppDeclaration> {
1623 self.children()
1624 }
1625
1626 /// The access specifier sections: `public:`, `private:`, `protected:`.
1627 pub fn get_access_specifiers(&self) -> Vec<CppAccessSpecifier> {
1628 self.syntax()
1629 .children()
1630 .filter_map(CppAccessSpecifier::cast)
1631 .collect()
1632 }
1633}
1634
1635/// An access specifier section header: `public:`.
1636#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1637pub struct CppAccessSpecifier {
1638 syntax: CppSyntaxNode,
1639}
1640
1641impl CppAstNode for CppAccessSpecifier {
1642 fn syntax(&self) -> &CppSyntaxNode {
1643 &self.syntax
1644 }
1645
1646 fn can_cast(kind: CppSyntaxKind) -> bool {
1647 matches!(
1648 kind,
1649 CppSyntaxKind::PublicAccess
1650 | CppSyntaxKind::PrivateAccess
1651 | CppSyntaxKind::ProtectedAccess
1652 )
1653 }
1654
1655 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
1656 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
1657 }
1658}
1659
1660impl CppAccessSpecifier {
1661 pub fn get_keyword(&self) -> Option<CppKeywordToken> {
1662 self.token()
1663 }
1664}
1665
1666/// A base class in a class definition's base clause.
1667#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1668pub struct CppBaseSpecifier {
1669 syntax: CppSyntaxNode,
1670}
1671
1672impl CppAstNode for CppBaseSpecifier {
1673 fn syntax(&self) -> &CppSyntaxNode {
1674 &self.syntax
1675 }
1676
1677 fn can_cast(kind: CppSyntaxKind) -> bool {
1678 kind == CppSyntaxKind::BaseSpecifier
1679 }
1680
1681 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
1682 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
1683 }
1684}
1685
1686impl CppBaseSpecifier {
1687 pub fn get_name(&self) -> Option<CppNameExpr> {
1688 self.child()
1689 }
1690
1691 pub fn is_virtual(&self) -> bool {
1692 self.syntax()
1693 .children_with_tokens()
1694 .filter_map(|it| it.into_token())
1695 .any(|token| token.kind() == CppKind::Token(CppTokenKind::VirtualKeyword))
1696 }
1697
1698 pub fn get_access(&self) -> Option<CppAccessSpecifier> {
1699 self.child()
1700 }
1701}
1702
1703/// An enum definition: `enum class Color : int { Red, Green };`.
1704#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1705pub struct CppEnumDef {
1706 syntax: CppSyntaxNode,
1707}
1708
1709impl CppAstNode for CppEnumDef {
1710 fn syntax(&self) -> &CppSyntaxNode {
1711 &self.syntax
1712 }
1713
1714 fn can_cast(kind: CppSyntaxKind) -> bool {
1715 matches!(
1716 kind,
1717 CppSyntaxKind::EnumDef | CppSyntaxKind::EnumClassDef | CppSyntaxKind::BuiltinType
1718 )
1719 }
1720
1721 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
1722 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
1723 }
1724}
1725
1726impl CppEnumDef {
1727 /// The `{ ... }` body holding the enumerators, if this really is an enum definition.
1728 ///
1729 /// This is what separates `enum class E { ... }` from an elaborated type specifier such as
1730 /// `enum E x;`: both are `BuiltinType` nodes, and only one of them defines anything.
1731 pub fn get_body(&self) -> Option<CppSyntaxNode> {
1732 self.syntax()
1733 .children()
1734 .find(|it| CppSyntaxKind::from(it.kind()) == CppSyntaxKind::CompoundStat)
1735 }
1736
1737 /// The `enum` keyword, if this node really is an enum.
1738 pub fn get_enum_keyword(&self) -> Option<CppKeywordToken> {
1739 self.syntax()
1740 .descendants_with_tokens()
1741 .filter_map(|it| it.into_token())
1742 .filter_map(CppKeywordToken::cast)
1743 .find(|it| it.get_keyword_kind() == CppKind::Token(CppTokenKind::EnumKeyword))
1744 }
1745
1746 /// The enum's name.
1747 ///
1748 /// **Written between the keyword and the body**, and read there rather than searched for in the subtree: the
1749 /// subtree also holds the enumerators, and an initializer's identifiers are the first `NameExpr` in it as soon as
1750 /// one enumerator is written in terms of another. Measured on `src/nvim/state_defs.h`:
1751 ///
1752 /// ```c
1753 /// enum { MODE_NORMAL = 0x01, …, MAP_ALL_MODES = 0xff, REPLACE_FLAG = 0x100,
1754 /// MODE_REPLACE = REPLACE_FLAG | MODE_INSERT, … };
1755 /// ```
1756 ///
1757 /// The first `NameExpr` below the node is the `REPLACE_FLAG` of `MODE_REPLACE`'s initializer, so the enumeration
1758 /// was named `REPLACE_FLAG` — one *type* fact at that use, and **every enumerator filed inside a scope named
1759 /// after it**: `MODE_INSERT` came out as `variable in REPLACE_FLAG`, and go-to-definition from `mouse.c` answered
1760 /// `NotDeclaredHere`. The same defect in a two-line fixture: `enum { A = 1, B = A };` named the enum `A` after
1761 /// `B`'s initializer.
1762 ///
1763 /// `enum class E` is one specifier whose `class` belongs to the `enum`, so the walk skips the scope keyword; a
1764 /// `:` (the underlying type) or the `{` before any identifier means the enumeration is anonymous.
1765 pub fn get_name(&self) -> Option<CppNameToken> {
1766 self.get_enum_keyword()?;
1767 let mut past_the_keyword = false;
1768 for element in self.syntax().descendants_with_tokens() {
1769 let Some(token) = element.into_token() else {
1770 continue;
1771 };
1772 match token.kind() {
1773 CppKind::Token(CppTokenKind::EnumKeyword) => past_the_keyword = true,
1774 CppKind::Token(CppTokenKind::ClassKeyword | CppTokenKind::StructKeyword)
1775 if past_the_keyword => {}
1776 CppKind::Token(CppTokenKind::Identifier) if past_the_keyword => {
1777 return CppNameToken::cast(token);
1778 }
1779 CppKind::Token(CppTokenKind::LeftBrace | CppTokenKind::Colon)
1780 if past_the_keyword =>
1781 {
1782 return None;
1783 }
1784 _ => {}
1785 }
1786 }
1787 None
1788 }
1789
1790 /// Is this a scoped enum (`enum class` / `enum struct`)?
1791 pub fn is_scoped(&self) -> bool {
1792 self.syntax()
1793 .children_with_tokens()
1794 .filter_map(|it| it.into_token())
1795 .any(|token| {
1796 matches!(
1797 token.kind(),
1798 CppKind::Token(CppTokenKind::ClassKeyword)
1799 | CppKind::Token(CppTokenKind::StructKeyword)
1800 )
1801 })
1802 }
1803
1804 /// Every enumerator, in order.
1805 ///
1806 /// The enumerators live inside the body node rather than directly under the enum, so this walks
1807 /// one level down instead of using `children()` — which is why it needs `first_child_of_kind`
1808 /// rather than `child::<N>()`: the body is a `CompoundStat`, the same kind a block statement
1809 /// uses, so there is no distinct type to ask for.
1810 pub fn get_enumerators(&self) -> impl Iterator<Item = CppEnumerator> {
1811 crate::syntax::node::traits::first_child_of_kind(
1812 self.syntax(),
1813 &[CppSyntaxKind::CompoundStat],
1814 )
1815 .into_iter()
1816 .flat_map(|body| CppAstChildren::<CppEnumerator>::new(&body))
1817 }
1818}
1819
1820/// One enumerator: `Red` or `Green = 2`.
1821#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1822pub struct CppEnumerator {
1823 syntax: CppSyntaxNode,
1824}
1825
1826impl CppAstNode for CppEnumerator {
1827 fn syntax(&self) -> &CppSyntaxNode {
1828 &self.syntax
1829 }
1830
1831 fn can_cast(kind: CppSyntaxKind) -> bool {
1832 kind == CppSyntaxKind::EnumeratorDecl
1833 }
1834
1835 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
1836 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
1837 }
1838}
1839
1840impl CppEnumerator {
1841 pub fn get_name(&self) -> Option<CppNameToken> {
1842 self.token()
1843 }
1844
1845 pub fn get_value_expr(&self) -> Option<CppExpr> {
1846 self.child()
1847 }
1848}
1849
1850// ============================================================================
1851// Namespaces and templates
1852// ============================================================================
1853
1854/// A namespace definition or an alias: `namespace a { ... }`, `namespace fs = std::filesystem;`.
1855#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1856pub struct CppNamespaceDecl {
1857 syntax: CppSyntaxNode,
1858}
1859
1860impl CppAstNode for CppNamespaceDecl {
1861 fn syntax(&self) -> &CppSyntaxNode {
1862 &self.syntax
1863 }
1864
1865 fn can_cast(kind: CppSyntaxKind) -> bool {
1866 kind == CppSyntaxKind::NamespaceDecl
1867 }
1868
1869 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
1870 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
1871 }
1872}
1873
1874impl CppNamespaceDecl {
1875 pub fn get_name(&self) -> Option<CppNameExpr> {
1876 self.child()
1877 }
1878
1879 /// **The name this namespace declares** — `ns` for `namespace ns { … }`, the last segment for `namespace a::b { … }`.
1880 ///
1881 /// `None` for the unnamed namespace, which declares none.
1882 pub fn get_name_text(&self) -> Option<String> {
1883 let name = self.get_name()?;
1884 Some(name.syntax().text().to_string().trim().to_string())
1885 }
1886
1887 /// Everything declared inside the namespace, in order.
1888 ///
1889 /// The sum type rather than [`CppDeclaration`], because a namespace body holds more than plain
1890 /// declarations: `template <...> class Grid { ... };` is a `TemplateDecl` at this level, and
1891 /// asking for `CppDeclaration` alone silently drops every template in the namespace.
1892 ///
1893 /// `namespace ns { ... }` holds a `CompoundStat` body, because a namespace body is
1894 /// grammatically a block and C++ makes declarations a kind of statement. This walks one level
1895 /// down so callers do not have to.
1896 pub fn get_declarations(&self) -> impl Iterator<Item = CppStat> {
1897 self.get_body()
1898 .into_iter()
1899 .flat_map(|body| body.get_stats())
1900 }
1901
1902 /// The body block, if this is a definition rather than an alias.
1903 pub fn get_body(&self) -> Option<CppCompoundStat> {
1904 self.child()
1905 }
1906
1907 /// Is this `namespace name = target;`?
1908 pub fn is_alias(&self) -> bool {
1909 self.syntax()
1910 .children_with_tokens()
1911 .filter_map(|it| it.into_token())
1912 .any(|token| token.kind() == CppKind::Token(CppTokenKind::Assign))
1913 }
1914}
1915
1916/// A template head: `template <typename T, int N>`.
1917#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1918pub struct CppTemplateDecl {
1919 syntax: CppSyntaxNode,
1920}
1921
1922impl CppAstNode for CppTemplateDecl {
1923 fn syntax(&self) -> &CppSyntaxNode {
1924 &self.syntax
1925 }
1926
1927 fn can_cast(kind: CppSyntaxKind) -> bool {
1928 kind == CppSyntaxKind::TemplateDecl
1929 }
1930
1931 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
1932 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
1933 }
1934}
1935
1936impl CppTemplateDecl {
1937 pub fn get_param_list(&self) -> Option<CppTemplateParamList> {
1938 self.child()
1939 }
1940
1941 /// Is this `template <>` — an explicit specialization?
1942 pub fn is_explicit_specialization(&self) -> bool {
1943 self.get_param_list().is_none()
1944 }
1945}
1946
1947/// A template parameter list, including its angle brackets.
1948#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1949pub struct CppTemplateParamList {
1950 syntax: CppSyntaxNode,
1951}
1952
1953impl CppAstNode for CppTemplateParamList {
1954 fn syntax(&self) -> &CppSyntaxNode {
1955 &self.syntax
1956 }
1957
1958 fn can_cast(kind: CppSyntaxKind) -> bool {
1959 kind == CppSyntaxKind::TemplateParameterList
1960 }
1961
1962 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
1963 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
1964 }
1965}
1966
1967impl CppTemplateParamList {
1968 pub fn get_params(&self) -> CppAstChildren<CppTemplateParam> {
1969 self.children()
1970 }
1971}
1972
1973/// One template parameter.
1974#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1975pub struct CppTemplateParam {
1976 syntax: CppSyntaxNode,
1977}
1978
1979impl CppAstNode for CppTemplateParam {
1980 fn syntax(&self) -> &CppSyntaxNode {
1981 &self.syntax
1982 }
1983
1984 fn can_cast(kind: CppSyntaxKind) -> bool {
1985 kind == CppSyntaxKind::TemplateParameter
1986 }
1987
1988 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
1989 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
1990 }
1991}
1992
1993impl CppTemplateParam {
1994 pub fn get_decl_specifiers(&self) -> Option<CppDeclSpecifierSeq> {
1995 self.child()
1996 }
1997
1998 /// The parameter's name — `T` in `typename T`, `N` in `int N`, `Args` in `class... Args`.
1999 ///
2000 /// **Two shapes, one question.** A non-type parameter is a declaration and names itself through its declarator
2001 /// (`int N`); a type parameter has no declarator at all — `typename T` is a specifier holding `T` as a name — so the
2002 /// declarator search answered `None` for every type parameter, and a hover rendered
2003 /// `template <typename T, typename Alloc = int>` as `template <typename, typename = int>`. The fallback is the
2004 /// **first** name in the subtree: the parameter's own name precedes its default's (`typename Alloc = std::allocator<T>`
2005 /// names `Alloc` first), and `T` in that default is a different question.
2006 pub fn get_name(&self) -> Option<CppNameToken> {
2007 self.get_declarator()
2008 .and_then(|declarator| declarator.get_name())
2009 .or_else(|| {
2010 self.syntax()
2011 .descendants()
2012 .find_map(CppNameExpr::cast)
2013 .and_then(|name| name.get_name_token())
2014 })
2015 }
2016
2017 pub fn get_declarator(&self) -> Option<CppDeclarator> {
2018 self.child()
2019 }
2020
2021 /// Is this `typename T` / `class T`?
2022 ///
2023 /// **Searched as a subtree**: the keyword is inside the parameter's `DeclSpecifierSeq`
2024 /// (`TemplateParameter > DeclSpecifierSeq > TypenameType > TypenameKeyword`), not a direct token of it — so the
2025 /// child-token search answered `false` for every type parameter, and a hover that asked it rendered
2026 /// `template <typename T, typename Alloc = int>` as `template <T, Alloc = int>`. Measured with `inspect hover`
2027 /// on a fixture. `concept` is a type parameter's keyword too, in a constrained one.
2028 pub fn is_type_param(&self) -> bool {
2029 self.syntax()
2030 .descendants_with_tokens()
2031 .filter_map(|it| it.into_token())
2032 .any(|token| {
2033 matches!(
2034 token.kind(),
2035 CppKind::Token(CppTokenKind::TypenameKeyword)
2036 | CppKind::Token(CppTokenKind::ClassKeyword)
2037 )
2038 })
2039 }
2040}
2041
2042/// A template argument list, including its angle brackets.
2043#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2044pub struct CppTemplateArgList {
2045 syntax: CppSyntaxNode,
2046}
2047
2048impl CppAstNode for CppTemplateArgList {
2049 fn syntax(&self) -> &CppSyntaxNode {
2050 &self.syntax
2051 }
2052
2053 fn can_cast(kind: CppSyntaxKind) -> bool {
2054 kind == CppSyntaxKind::TemplateArgumentList
2055 }
2056
2057 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
2058 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
2059 }
2060}
2061
2062impl CppTemplateArgList {
2063 pub fn get_args(&self) -> CppAstChildren<CppTemplateArg> {
2064 self.children()
2065 }
2066}
2067
2068/// One template argument: a type or a constant expression.
2069#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2070pub struct CppTemplateArg {
2071 syntax: CppSyntaxNode,
2072}
2073
2074impl CppAstNode for CppTemplateArg {
2075 fn syntax(&self) -> &CppSyntaxNode {
2076 &self.syntax
2077 }
2078
2079 fn can_cast(kind: CppSyntaxKind) -> bool {
2080 kind == CppSyntaxKind::TemplateArgument
2081 }
2082
2083 fn cast(syntax: CppSyntaxNode) -> Option<Self> {
2084 Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
2085 }
2086}
2087
2088impl CppTemplateArg {
2089 pub fn get_type_id(&self) -> Option<CppTypeId> {
2090 self.child()
2091 }
2092
2093 pub fn get_expr(&self) -> Option<CppExpr> {
2094 self.child()
2095 }
2096}