cpp_parser 0.1.4

A lossless C++ parser over the preprocessed text: the tree every layer above it reads.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
//! Expression nodes.
//!
//! C++ expressions form a deep nesting of *forms* rather than a single `Expr` node kind with an
//! operator field: `a + b` is a `BinaryExpr` whose children are two expressions, `f(x)` is a
//! `CallExpr` whose first child is the callee. That makes the tree easy to walk structurally, which
//! is what an editor wants — "give me everything inside this call's arguments" is a child query, not
//! a re-parse.
//!
//! [`CppExpr`] is the sum type over all of them. Its `cast` is what makes
//! [`CppAstNode::child`] work for expressions, so every node kind that can appear in expression
//! position has to be listed there.

use crate::{
    CppSyntaxNode,
    kind::{CppKind, CppSyntaxKind, CppTokenKind},
    syntax::traits::{CppAstChildren, CppAstNode, CppAstToken},
};

use super::{CppDeclaration, CppDeclarator, CppTypeId};
use crate::syntax::node::token::{CppLiteralToken, CppNameToken, CppOperatorToken};

/// Any expression.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum CppExpr {
    LiteralExpr(CppLiteralExpr),
    NameExpr(CppNameExpr),
    ParenExpr(CppParenExpr),
    UnaryExpr(CppUnaryExpr),
    BinaryExpr(CppBinaryExpr),
    TernaryExpr(CppTernaryExpr),
    CallExpr(CppCallExpr),
    IndexExpr(CppIndexExpr),
    MemberExpr(CppMemberExpr),
    /// `(int)x` and the named casts — see [`CppCastExpr`].
    CastExpr(CppCastExpr),
    InitListExpr(CppInitListExpr),
    DesignatedInitExpr(CppDesignatedInitExpr),
    LambdaExpr(CppLambdaExpr),
    ThisExpr(CppThisExpr),
    /// A C11 generic selection — `_Generic(x, int: "int", default: "other")`.
    GenericSelectionExpr(CppGenericSelectionExpr),
    /// An expression the parser could not classify, kept so the tree stays lossless.
    ErrorNode(CppUnknownExpr),
}

impl CppAstNode for CppExpr {
    fn syntax(&self) -> &CppSyntaxNode {
        match self {
            CppExpr::LiteralExpr(node) => node.syntax(),
            CppExpr::NameExpr(node) => node.syntax(),
            CppExpr::ParenExpr(node) => node.syntax(),
            CppExpr::UnaryExpr(node) => node.syntax(),
            CppExpr::BinaryExpr(node) => node.syntax(),
            CppExpr::TernaryExpr(node) => node.syntax(),
            CppExpr::CallExpr(node) => node.syntax(),
            CppExpr::IndexExpr(node) => node.syntax(),
            CppExpr::MemberExpr(node) => node.syntax(),
            CppExpr::CastExpr(node) => node.syntax(),
            CppExpr::InitListExpr(node) => node.syntax(),
            CppExpr::DesignatedInitExpr(node) => node.syntax(),
            CppExpr::LambdaExpr(node) => node.syntax(),
            CppExpr::ThisExpr(node) => node.syntax(),
            CppExpr::ErrorNode(node) => node.syntax(),
            CppExpr::GenericSelectionExpr(node) => node.syntax(),
        }
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        matches!(
            kind,
            CppSyntaxKind::LiteralExpr
                | CppSyntaxKind::IdentifierExpr
                | CppSyntaxKind::NameExpr
                | CppSyntaxKind::ParenExpr
                | CppSyntaxKind::UnaryExpr
                | CppSyntaxKind::BinaryExpr
                | CppSyntaxKind::TernaryExpr
                | CppSyntaxKind::CallExpr
                | CppSyntaxKind::IndexExpr
                | CppSyntaxKind::MemberExpr
                | CppSyntaxKind::ArrowExpr
                | CppSyntaxKind::CastExpr
                | CppSyntaxKind::InitListExpr
                | CppSyntaxKind::DesignatedInitExpr
                | CppSyntaxKind::LambdaExpr
                | CppSyntaxKind::ClosureExpr
                | CppSyntaxKind::ThisExpr
                | CppSyntaxKind::GenericSelectionExpr
                | CppSyntaxKind::ErrorNode
        )
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        match CppSyntaxKind::from(syntax.kind()) {
            CppSyntaxKind::LiteralExpr => CppLiteralExpr::cast(syntax).map(CppExpr::LiteralExpr),
            CppSyntaxKind::IdentifierExpr | CppSyntaxKind::NameExpr => {
                CppNameExpr::cast(syntax).map(CppExpr::NameExpr)
            }
            CppSyntaxKind::ParenExpr => CppParenExpr::cast(syntax).map(CppExpr::ParenExpr),
            CppSyntaxKind::UnaryExpr => CppUnaryExpr::cast(syntax).map(CppExpr::UnaryExpr),
            CppSyntaxKind::BinaryExpr => CppBinaryExpr::cast(syntax).map(CppExpr::BinaryExpr),
            CppSyntaxKind::TernaryExpr => CppTernaryExpr::cast(syntax).map(CppExpr::TernaryExpr),
            CppSyntaxKind::CallExpr => CppCallExpr::cast(syntax).map(CppExpr::CallExpr),
            CppSyntaxKind::IndexExpr => CppIndexExpr::cast(syntax).map(CppExpr::IndexExpr),
            CppSyntaxKind::MemberExpr | CppSyntaxKind::ArrowExpr => {
                CppMemberExpr::cast(syntax).map(CppExpr::MemberExpr)
            }
            CppSyntaxKind::CastExpr => CppCastExpr::cast(syntax).map(CppExpr::CastExpr),
            CppSyntaxKind::InitListExpr => CppInitListExpr::cast(syntax).map(CppExpr::InitListExpr),
            CppSyntaxKind::DesignatedInitExpr => {
                CppDesignatedInitExpr::cast(syntax).map(CppExpr::DesignatedInitExpr)
            }
            CppSyntaxKind::LambdaExpr | CppSyntaxKind::ClosureExpr => {
                CppLambdaExpr::cast(syntax).map(CppExpr::LambdaExpr)
            }
            CppSyntaxKind::ThisExpr => CppThisExpr::cast(syntax).map(CppExpr::ThisExpr),
            CppSyntaxKind::GenericSelectionExpr => {
                CppGenericSelectionExpr::cast(syntax).map(CppExpr::GenericSelectionExpr)
            }
            CppSyntaxKind::ErrorNode => CppUnknownExpr::cast(syntax).map(CppExpr::ErrorNode),
            _ => None,
        }
    }
}

/// An expression that can name something: the left-hand side of an assignment, and the target of a
/// "go to definition".
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum CppVarExpr {
    NameExpr(CppNameExpr),
    IndexExpr(CppIndexExpr),
    MemberExpr(CppMemberExpr),
}

impl CppAstNode for CppVarExpr {
    fn syntax(&self) -> &CppSyntaxNode {
        match self {
            CppVarExpr::NameExpr(node) => node.syntax(),
            CppVarExpr::IndexExpr(node) => node.syntax(),
            CppVarExpr::MemberExpr(node) => node.syntax(),
        }
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        matches!(
            kind,
            CppSyntaxKind::IdentifierExpr
                | CppSyntaxKind::NameExpr
                | CppSyntaxKind::IndexExpr
                | CppSyntaxKind::MemberExpr
                | CppSyntaxKind::ArrowExpr
        )
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        match CppSyntaxKind::from(syntax.kind()) {
            CppSyntaxKind::IdentifierExpr | CppSyntaxKind::NameExpr => {
                CppNameExpr::cast(syntax).map(CppVarExpr::NameExpr)
            }
            CppSyntaxKind::IndexExpr => CppIndexExpr::cast(syntax).map(CppVarExpr::IndexExpr),
            CppSyntaxKind::MemberExpr | CppSyntaxKind::ArrowExpr => {
                CppMemberExpr::cast(syntax).map(CppVarExpr::MemberExpr)
            }
            _ => None,
        }
    }
}

impl From<CppVarExpr> for CppExpr {
    fn from(expr: CppVarExpr) -> Self {
        match expr {
            CppVarExpr::NameExpr(node) => CppExpr::NameExpr(node),
            CppVarExpr::IndexExpr(node) => CppExpr::IndexExpr(node),
            CppVarExpr::MemberExpr(node) => CppExpr::MemberExpr(node),
        }
    }
}

/// A literal: number, character, string, boolean or `nullptr`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppLiteralExpr {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppLiteralExpr {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::LiteralExpr
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppLiteralExpr {
    pub fn get_literal_token(&self) -> Option<CppLiteralToken> {
        self.token()
    }

    /// The literal as written, including any suffix. No interpretation: whether `1'000` is 1000 or
    /// something else is the semantic layer's business.
    pub fn get_literal_text(&self) -> Option<String> {
        self.get_literal_token()
            .map(|it| it.get_literal_text().to_string())
    }

    pub fn is_null_literal(&self) -> bool {
        self.syntax()
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .any(|token| {
                matches!(
                    token.kind(),
                    CppKind::Token(CppTokenKind::NullptrKeyword)
                        | CppKind::Token(CppTokenKind::NullptrLiteral)
                )
            })
    }

    pub fn is_bool_literal(&self) -> bool {
        self.syntax()
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .any(|token| {
                matches!(
                    token.kind(),
                    CppKind::Token(CppTokenKind::TrueKeyword)
                        | CppKind::Token(CppTokenKind::FalseKeyword)
                        | CppKind::Token(CppTokenKind::BoolLiteral)
                )
            })
    }
}

/// A name used as an expression: `foo`, `ns::foo`, `Foo<int>`, `operator+`.
///
/// This is also the node the parser produces for a *type* name, because without a symbol table the
/// two are the same shape. A consumer that needs to tell them apart has to look at the parent.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppNameExpr {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppNameExpr {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        matches!(
            kind,
            CppSyntaxKind::IdentifierExpr | CppSyntaxKind::NameExpr
        )
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppNameExpr {
    /// The identifier this name refers to.
    ///
    /// For a qualified name (`ns::foo`) this is the *first* identifier, and for
    /// [`CppNameExpr::get_last_name_token`] the last. Both are useful: the first is what the name
    /// starts with, the last is the entity being named.
    pub fn get_name_token(&self) -> Option<CppNameToken> {
        self.token()
    }

    pub fn get_last_name_token(&self) -> Option<CppNameToken> {
        self.syntax()
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .filter_map(CppNameToken::cast)
            .last()
    }

    pub fn get_name_text(&self) -> Option<String> {
        self.get_name_token()
            .map(|it| it.get_name_text().to_string())
    }

    /// The whole name as written, without whitespace: `std::vector<int>`.
    ///
    /// Taken from the node's text rather than from its direct tokens, because a template-id carries
    /// a `TemplateArgumentList` *node*: walking tokens alone would drop `<int>` and report plain
    /// `std::vector` for a name that is not plain at all.
    pub fn get_qualified_name(&self) -> String {
        self.syntax()
            .text()
            .to_string()
            .chars()
            .filter(|it| !it.is_whitespace())
            .collect()
    }

    /// Is this a qualified name (`ns::foo`)?
    pub fn is_qualified(&self) -> bool {
        self.syntax()
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .any(|token| token.kind() == CppKind::Token(CppTokenKind::Scope))
    }

    /// The template argument lists in this name, for `Foo<int>`.
    pub fn get_template_arg_lists(&self) -> CppAstChildren<super::CppTemplateArgList> {
        self.children()
    }
}

/// A parenthesized expression. Also what the parser produces for an `if`/`while`/`switch`
/// condition, so check the parent before assuming it is an expression.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppParenExpr {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppParenExpr {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::ParenExpr
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppParenExpr {
    /// The expression inside the parentheses.
    pub fn get_expr(&self) -> Option<CppExpr> {
        self.child()
    }

    /// A declaration inside the parentheses, for `if (Foo* p = f())`.
    pub fn get_declaration(&self) -> Option<CppDeclaration> {
        self.child()
    }
}

/// **A cast**: `(int)x`, `(Widget*)p`, and the C++ named casts, which the parser also builds as `CastExpr`.
///
/// # Why this type exists at all
///
/// It did not, and the omission was silent: `CppExpr`'s `can_cast` had no `CastExpr` kind, so
/// [`CppCallExpr::get_args`] — which is `children::<CppExpr>()` — **dropped every cast from an argument list**.
/// `three((int)x, 2, 3)` then counted two arguments, and `argument-count` reported a call that passes three as
/// "needs 3 argument(s) and this call passes fewer". Measured on neovim's `arglist.c`
/// (`do_arg_all((int)eap->line2, eap->forceit, eap->cmdidx == CMD_drop)`) — the one remaining finding in that file
/// after the language and parser fixes, and a false one.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppCastExpr {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppCastExpr {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::CastExpr
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppCastExpr {
    /// What is being cast.
    pub fn get_operand(&self) -> Option<CppExpr> {
        self.children::<CppExpr>().next()
    }

    /// The type it is cast to, when the parser recorded one: `(int)` in `(int)x`, and no type for
    /// `static_cast<int>(x)` — that spelling carries a template-argument list instead.
    pub fn get_type_id(&self) -> Option<CppTypeId> {
        self.child()
    }
}

/// A unary expression: `-x`, `!flag`, `*ptr`, `&var`, `++i`, `i++`.
///
/// Prefix and postfix forms share this type; `is_prefix` tells them apart, which matters because
/// only the prefix form has the operator before its operand in the token stream.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppUnaryExpr {
    syntax: CppSyntaxNode,
}
impl CppAstNode for CppUnaryExpr {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::UnaryExpr
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppUnaryExpr {
    pub fn get_operator_token(&self) -> Option<CppOperatorToken> {
        self.token()
    }

    pub fn get_operator_text(&self) -> Option<String> {
        self.get_operator_token()
            .map(|it| it.get_operator_text().to_string())
    }

    /// The operand.
    pub fn get_operand(&self) -> Option<CppExpr> {
        self.child()
    }

    /// Is the operator written before its operand?
    pub fn is_prefix(&self) -> bool {
        let Some(operator) = self
            .syntax()
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .find(|token| !crate::syntax::node::traits::is_trivia(token.kind().into()))
        else {
            return true;
        };
        let Some(operand) = self.get_operand() else {
            return true;
        };
        operator.text_range().start() < operand.syntax().text_range().start()
    }
}

/// A binary expression: `a + b`, `x == y`, `a && b`, and the member-access forms.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppBinaryExpr {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppBinaryExpr {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::BinaryExpr
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppBinaryExpr {
    /// The left operand.
    pub fn get_lhs(&self) -> Option<CppExpr> {
        self.children().next()
    }

    /// The right operand.
    pub fn get_rhs(&self) -> Option<CppExpr> {
        self.children().nth(1)
    }

    pub fn get_operator_token(&self) -> Option<CppOperatorToken> {
        self.token()
    }

    pub fn get_operator_text(&self) -> Option<String> {
        self.get_operator_token()
            .map(|it| it.get_operator_text().to_string())
    }
}

/// A conditional expression: `cond ? a : b`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppTernaryExpr {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppTernaryExpr {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::TernaryExpr
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppTernaryExpr {
    pub fn get_condition(&self) -> Option<CppExpr> {
        self.children().next()
    }

    pub fn get_then_expr(&self) -> Option<CppExpr> {
        self.children().nth(1)
    }

    pub fn get_else_expr(&self) -> Option<CppExpr> {
        self.children().nth(2)
    }
}

/// A function call: `f(x)`, `obj.method(x)`, `T{}`.
///
/// The callee is the first child expression, which is what a "go to definition" on a call site has
/// to resolve.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppCallExpr {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppCallExpr {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::CallExpr
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppCallExpr {
    /// What is being called.
    pub fn get_callee(&self) -> Option<CppExpr> {
        self.children().next()
    }

    /// The argument list, if the parser wrapped the arguments in one.
    pub fn get_arg_list(&self) -> Option<CppArgList> {
        self.child()
    }

    /// The arguments, in order.
    ///
    /// The parser does not create an `ArgList` node: the arguments are direct children of the call,
    /// after the callee and between the parentheses. `get_arg_list` is kept for grammars that do
    /// wrap them, and this handles both so callers do not have to know which they are looking at.
    pub fn get_args(&self) -> Vec<CppExpr> {
        if let Some(list) = self.get_arg_list() {
            return list.get_args().collect();
        }

        self.children::<CppExpr>().skip(1).collect()
    }

    /// **Does this call expand a pack?** — `sum_head(rest...)`.
    ///
    /// A call whose argument is a pack expression passes however many arguments the pattern says, which is not a fact
    /// about the text and not a number a checker can compare against a declaration's parameter count. The evidence is
    /// the parser's own `PackExpansionExpr`.
    ///
    /// **The call's own subtree, not `get_args`**: `sum_head(rest...)` names the expansion as a direct child of the
    /// call, and it is not one of the expression kinds `get_args` accepts — measured, the arguments came back empty and
    /// the arity check reported "passes fewer" for a call that passes a whole pack. A nested lambda's expansion inside
    /// an argument would count too, which is the silence direction: no arity is claimed about a call whose count is not
    /// a fact about the text.
    pub fn has_a_pack_expansion(&self) -> bool {
        self.syntax()
            .descendants()
            .any(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::PackExpansionExpr)
    }
}

/// An argument list: `(a, b, c)`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppArgList {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppArgList {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        matches!(
            kind,
            CppSyntaxKind::ArgumentList | CppSyntaxKind::CallArgList
        )
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppArgList {
    pub fn get_args(&self) -> CppAstChildren<CppExpr> {
        self.children()
    }
}

/// An index expression: `arr[i]`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppIndexExpr {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppIndexExpr {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::IndexExpr
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppIndexExpr {
    /// What is being indexed.
    pub fn get_object(&self) -> Option<CppExpr> {
        self.children().next()
    }

    /// The subscript.
    pub fn get_index(&self) -> Option<CppExpr> {
        self.children().nth(1)
    }
}

/// A member access: `obj.member` or `ptr->member`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppMemberExpr {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppMemberExpr {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        matches!(kind, CppSyntaxKind::MemberExpr | CppSyntaxKind::ArrowExpr)
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppMemberExpr {
    /// The object whose member is accessed.
    pub fn get_object(&self) -> Option<CppExpr> {
        self.children().next()
    }

    /// The member name.
    pub fn get_member_name(&self) -> Option<CppNameToken> {
        self.token()
    }

    /// Is this `->` rather than `.`?
    pub fn is_arrow(&self) -> bool {
        self.syntax()
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .any(|token| token.kind() == CppKind::Token(CppTokenKind::Arrow))
    }
}

/// A braced initializer list: `{1, 2, 3}`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppInitListExpr {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppInitListExpr {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        matches!(
            kind,
            CppSyntaxKind::InitListExpr
                | CppSyntaxKind::TableArrayExpr
                | CppSyntaxKind::TableEmptyExpr
        )
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppInitListExpr {
    /// The elements, in order.
    pub fn get_elements(&self) -> CppAstChildren<CppExpr> {
        self.children()
    }

    /// The designated initializers (`.field = v`, `[i] = v`).
    pub fn get_designators(&self) -> CppAstChildren<CppDesignatedInitExpr> {
        self.children()
    }

    pub fn is_empty(&self) -> bool {
        self.get_elements().next().is_none()
    }
}

/// A designated initializer: `.field = value` or `[index] = value`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppDesignatedInitExpr {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppDesignatedInitExpr {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::DesignatedInitExpr
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppDesignatedInitExpr {
    /// The field or index designator.
    pub fn get_designator(&self) -> Option<CppNameToken> {
        self.token()
    }

    /// The initializing value.
    pub fn get_value(&self) -> Option<CppExpr> {
        self.child()
    }
}

/// A lambda: `[capture](params) -> ret { body }`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppLambdaExpr {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppLambdaExpr {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        matches!(kind, CppSyntaxKind::LambdaExpr | CppSyntaxKind::ClosureExpr)
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppLambdaExpr {
    pub fn get_param_list(&self) -> Option<super::CppParamList> {
        self.child()
    }

    pub fn get_body(&self) -> Option<super::CppCompoundStat> {
        self.child()
    }

    pub fn get_trailing_return_type(&self) -> Option<super::CppTypeId> {
        crate::syntax::node::traits::first_child_of_kind(
            self.syntax(),
            &[CppSyntaxKind::TrailingReturnType],
        )
        .and_then(CppTypeId::cast)
    }
}

/// `this`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppThisExpr {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppThisExpr {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::ThisExpr || kind == CppSyntaxKind::IdentifierExpr
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        // `this` is parsed as an identifier expression when it is not the whole expression, so this
        // only casts when the token really is `this`.
        let is_this = syntax
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .any(|token| token.kind() == CppKind::Token(CppTokenKind::ThisKeyword));
        (Self::can_cast(syntax.kind().into()) && is_this).then_some(Self { syntax })
    }
}

/// **C11's generic selection** — `_Generic(expr, type: value, …, default: value)`.
///
/// Its own expression kind rather than an `ErrorNode`, because everything that walks expressions has to see it:
/// `CppCallExpr::get_args` filters its children through [`CppExpr::cast`], so a selection the cast did not know was
/// dropped from a call's argument list — `strlen(TYPE_NAME(x))` counted **zero** arguments for `strlen`, which takes
/// one, and `argument-count` reported five of those calls on a nine-file C corpus.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppGenericSelectionExpr {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppGenericSelectionExpr {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::GenericSelectionExpr
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

/// An expression the parser could not classify.
///
/// Exists so that [`CppExpr::cast`] is total over the kinds the parser can emit in expression
/// position: an `ErrorNode` is still an expression as far as an editor is concerned, and a caller
/// walking a broken file should not have to special-case it.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppUnknownExpr {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppUnknownExpr {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::ErrorNode
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

/// A `declarator` seen through an expression: the parser reuses `Declarator` inside expressions in a
/// few places (parenthesized declarators), and this lets callers reach it.
pub type CppExprDeclarator = CppDeclarator;