cpp_parser 0.3.0

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
//! Typed token wrappers.
//!
//! A token type exists when the token has behaviour beyond its kind: a name has text, a number has a
//! value, an operator has a precedence. Tokens that carry nothing extra use [`CppGeneralToken`].
//!
//! The shape follows the reference implementation (`reference/README.md`): a newtype over a
//! [`CppSyntaxToken`] plus a `CppAstToken` impl, with accessors as inherent methods.

use crate::{
    CppSyntaxToken,
    kind::{CppKind, CppSyntaxKind, CppTokenKind},
    syntax::traits::CppAstToken,
};

/// Any token. The fallback for tokens with no special behaviour.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppGeneralToken {
    token: CppSyntaxToken,
}

impl CppAstToken for CppGeneralToken {
    fn syntax(&self) -> &CppSyntaxToken {
        &self.token
    }

    fn can_cast(_: CppTokenKind) -> bool
    where
        Self: Sized,
    {
        true
    }

    fn cast(syntax: CppSyntaxToken) -> Option<Self>
    where
        Self: Sized,
    {
        Some(CppGeneralToken { token: syntax })
    }
}

impl CppGeneralToken {
    pub fn get_text(&self) -> &str {
        self.token.text()
    }
}

/// An identifier: a name being declared or referenced.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppNameToken {
    token: CppSyntaxToken,
}

impl CppAstToken for CppNameToken {
    fn syntax(&self) -> &CppSyntaxToken {
        &self.token
    }

    fn can_cast(kind: CppTokenKind) -> bool
    where
        Self: Sized,
    {
        kind == CppTokenKind::Identifier
    }

    fn cast(syntax: CppSyntaxToken) -> Option<Self>
    where
        Self: Sized,
    {
        if Self::can_cast(syntax.kind().into()) {
            Some(CppNameToken { token: syntax })
        } else {
            None
        }
    }
}

impl CppNameToken {
    pub fn get_name_text(&self) -> &str {
        self.token.text()
    }
}

/// A keyword token, for the handful of places that need to look at one directly.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppKeywordToken {
    token: CppSyntaxToken,
}

impl CppAstToken for CppKeywordToken {
    fn syntax(&self) -> &CppSyntaxToken {
        &self.token
    }

    fn can_cast(kind: CppTokenKind) -> bool
    where
        Self: Sized,
    {
        is_keyword(kind)
    }

    fn cast(syntax: CppSyntaxToken) -> Option<Self>
    where
        Self: Sized,
    {
        if Self::can_cast(syntax.kind().into()) {
            Some(CppKeywordToken { token: syntax })
        } else {
            None
        }
    }
}

impl CppKeywordToken {
    pub fn get_keyword_text(&self) -> &str {
        self.token.text()
    }

    pub fn get_keyword_kind(&self) -> CppKind {
        self.token.kind()
    }
}

/// Is this token kind one of the keyword kinds?
///
/// `false` for `final` and `override`: they *look* like keywords but are identifiers with special
/// meaning, which is why the parser matches them by text.
///
/// **`bool` is here and its spelling is why.** The lexer's table says `"bool" => BoolLiteral`, so the *type* shares
/// a kind with the boolean literals — and the literals have kinds of their own (`"true" => TrueKeyword`,
/// `"false" => FalseKeyword`), so `BoolLiteral` is reached only by the type. It was left out while that was not so,
/// and the effect was that a highlighter had nothing to say about `bool` at all: measured while classifying
/// keywords by kind, every other type name was drawn as a type and `bool` was not drawn.
pub fn is_keyword(kind: CppTokenKind) -> bool {
    matches!(
        kind,
        CppTokenKind::AutoKeyword
            | CppTokenKind::BoolLiteral
            | CppTokenKind::BreakKeyword
            | CppTokenKind::CaseKeyword
            | CppTokenKind::CatchKeyword
            | CppTokenKind::CharKeyword
            | CppTokenKind::ClassKeyword
            | CppTokenKind::ConstKeyword
            | CppTokenKind::ConstexprKeyword
            | CppTokenKind::ConstevalKeyword
            | CppTokenKind::ConstinitKeyword
            | CppTokenKind::ContinueKeyword
            | CppTokenKind::DecltypeKeyword
            | CppTokenKind::DefaultKeyword
            | CppTokenKind::DeleteKeyword
            | CppTokenKind::DoKeyword
            | CppTokenKind::DoubleKeyword
            | CppTokenKind::ElseKeyword
            | CppTokenKind::EnumKeyword
            | CppTokenKind::ExplicitKeyword
            | CppTokenKind::ExportKeyword
            | CppTokenKind::ExternKeyword
            | CppTokenKind::FalseKeyword
            | CppTokenKind::FloatKeyword
            | CppTokenKind::ForKeyword
            | CppTokenKind::FriendKeyword
            | CppTokenKind::GotoKeyword
            | CppTokenKind::IfKeyword
            | CppTokenKind::InlineKeyword
            | CppTokenKind::IntKeyword
            | CppTokenKind::LongKeyword
            | CppTokenKind::MutableKeyword
            | CppTokenKind::NamespaceKeyword
            | CppTokenKind::NewKeyword
            | CppTokenKind::NoexceptKeyword
            | CppTokenKind::NullptrKeyword
            | CppTokenKind::OperatorKeyword
            | CppTokenKind::PrivateKeyword
            | CppTokenKind::ProtectedKeyword
            | CppTokenKind::PublicKeyword
            | CppTokenKind::RegisterKeyword
            | CppTokenKind::ReturnKeyword
            | CppTokenKind::ShortKeyword
            | CppTokenKind::SignedKeyword
            | CppTokenKind::SizeofKeyword
            | CppTokenKind::StaticKeyword
            | CppTokenKind::StaticAssertKeyword
            | CppTokenKind::StructKeyword
            | CppTokenKind::SwitchKeyword
            | CppTokenKind::TemplateKeyword
            | CppTokenKind::ThisKeyword
            | CppTokenKind::ThreadLocalKeyword
            | CppTokenKind::ThrowKeyword
            | CppTokenKind::TrueKeyword
            | CppTokenKind::TryKeyword
            | CppTokenKind::TypedefKeyword
            | CppTokenKind::TypeidKeyword
            | CppTokenKind::TypenameKeyword
            | CppTokenKind::UnionKeyword
            | CppTokenKind::UnsignedKeyword
            | CppTokenKind::UsingKeyword
            | CppTokenKind::VirtualKeyword
            | CppTokenKind::VoidKeyword
            | CppTokenKind::VolatileKeyword
            | CppTokenKind::WhileKeyword
            | CppTokenKind::AlignasKeyword
            | CppTokenKind::AlignofKeyword
            | CppTokenKind::CoAwaitKeyword
            | CppTokenKind::CoReturnKeyword
            | CppTokenKind::CoYieldKeyword
            // **The four cast operators are keywords too**, and leaving them out meant a highlighter had nothing to
            // say about `static_cast` — reported from an editor: `static_cast<std::size_t>(index)` was the one word
            // in the line the client's own grammar drew. They are also word-shaped, which the macro expander asks
            // about (`finishes_a_word`): a `static_cast` pasted onto a following name is the same hazard as any
            // other keyword's.
            | CppTokenKind::StaticCastKeyword
            | CppTokenKind::DynamicCastKeyword
            | CppTokenKind::ConstCastKeyword
            | CppTokenKind::ReinterpretCastKeyword
    )
}

/// Is this token kind a type specifier keyword?
///
/// `class`, `struct`, `union` and `enum` are included: they name a type, and `Foo` in
/// `class Foo;` is a class *type*.
pub fn is_type_keyword(kind: CppTokenKind) -> bool {
    matches!(
        kind,
        CppTokenKind::VoidKeyword
            | CppTokenKind::CharKeyword
            | CppTokenKind::ShortKeyword
            | CppTokenKind::IntKeyword
            | CppTokenKind::LongKeyword
            | CppTokenKind::FloatKeyword
            | CppTokenKind::DoubleKeyword
            | CppTokenKind::SignedKeyword
            | CppTokenKind::UnsignedKeyword
            | CppTokenKind::BoolLiteral
            | CppTokenKind::AutoKeyword
            | CppTokenKind::DecltypeKeyword
            | CppTokenKind::ClassKeyword
            | CppTokenKind::StructKeyword
            | CppTokenKind::UnionKeyword
            | CppTokenKind::EnumKeyword
            | CppTokenKind::TypenameKeyword
    )
}

/// An operator token, in either a unary or a binary position.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppOperatorToken {
    token: CppSyntaxToken,
}

impl CppAstToken for CppOperatorToken {
    fn syntax(&self) -> &CppSyntaxToken {
        &self.token
    }

    fn can_cast(kind: CppTokenKind) -> bool
    where
        Self: Sized,
    {
        is_operator(kind)
    }

    fn cast(syntax: CppSyntaxToken) -> Option<Self>
    where
        Self: Sized,
    {
        if Self::can_cast(syntax.kind().into()) {
            Some(CppOperatorToken { token: syntax })
        } else {
            None
        }
    }
}

impl CppOperatorToken {
    pub fn get_operator_text(&self) -> &str {
        self.token.text()
    }

    pub fn get_operator_kind(&self) -> CppKind {
        self.token.kind()
    }
}

/// Is this token kind an operator?
pub fn is_operator(kind: CppTokenKind) -> bool {
    matches!(
        kind,
        CppTokenKind::Plus
            | CppTokenKind::Minus
            | CppTokenKind::Star
            | CppTokenKind::Slash
            | CppTokenKind::Percent
            | CppTokenKind::Assign
            | CppTokenKind::PlusAssign
            | CppTokenKind::MinusAssign
            | CppTokenKind::StarAssign
            | CppTokenKind::SlashAssign
            | CppTokenKind::PercentAssign
            | CppTokenKind::Equal
            | CppTokenKind::NotEqual
            | CppTokenKind::Less
            | CppTokenKind::LessEqual
            | CppTokenKind::Greater
            | CppTokenKind::GreaterEqual
            | CppTokenKind::Spaceship
            | CppTokenKind::LogicalAnd
            | CppTokenKind::LogicalOr
            | CppTokenKind::LogicalNot
            | CppTokenKind::Ampersand
            | CppTokenKind::Pipe
            | CppTokenKind::Caret
            | CppTokenKind::Tilde
            | CppTokenKind::LeftShift
            | CppTokenKind::RightShift
            | CppTokenKind::AmpersandAssign
            | CppTokenKind::PipeAssign
            | CppTokenKind::CaretAssign
            | CppTokenKind::LeftShiftAssign
            | CppTokenKind::RightShiftAssign
            | CppTokenKind::PlusPlus
            | CppTokenKind::MinusMinus
            | CppTokenKind::Dot
            | CppTokenKind::Arrow
            | CppTokenKind::DotStar
            | CppTokenKind::ArrowStar
            | CppTokenKind::Scope
            | CppTokenKind::Question
    )
}

/// A punctuation token.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppPunctuationToken {
    token: CppSyntaxToken,
}

impl CppAstToken for CppPunctuationToken {
    fn syntax(&self) -> &CppSyntaxToken {
        &self.token
    }

    fn can_cast(kind: CppTokenKind) -> bool
    where
        Self: Sized,
    {
        is_punctuation(kind)
    }

    fn cast(syntax: CppSyntaxToken) -> Option<Self>
    where
        Self: Sized,
    {
        if Self::can_cast(syntax.kind().into()) {
            Some(CppPunctuationToken { token: syntax })
        } else {
            None
        }
    }
}

/// Is this token kind a delimiter?
pub fn is_punctuation(kind: CppTokenKind) -> bool {
    matches!(
        kind,
        CppTokenKind::LeftParen
            | CppTokenKind::RightParen
            | CppTokenKind::LeftBrace
            | CppTokenKind::RightBrace
            | CppTokenKind::LeftBracket
            | CppTokenKind::RightBracket
            | CppTokenKind::Semicolon
            | CppTokenKind::Comma
            | CppTokenKind::Colon
            | CppTokenKind::Ellipsis
            | CppTokenKind::Hash
            | CppTokenKind::HashHash
    )
}

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

impl CppAstToken for CppLiteralToken {
    fn syntax(&self) -> &CppSyntaxToken {
        &self.token
    }

    fn can_cast(kind: CppTokenKind) -> bool
    where
        Self: Sized,
    {
        is_literal(kind)
    }

    fn cast(syntax: CppSyntaxToken) -> Option<Self>
    where
        Self: Sized,
    {
        if Self::can_cast(syntax.kind().into()) {
            Some(CppLiteralToken { token: syntax })
        } else {
            None
        }
    }
}

impl CppLiteralToken {
    pub fn get_literal_text(&self) -> &str {
        self.token.text()
    }
}

/// Is this token kind a literal?
pub fn is_literal(kind: CppTokenKind) -> bool {
    matches!(
        kind,
        CppTokenKind::IntegerLiteral
            | CppTokenKind::FloatingLiteral
            | CppTokenKind::CharLiteral
            | CppTokenKind::StringLiteral
            | CppTokenKind::UserDefinedLiteral
            | CppTokenKind::BoolLiteral
            | CppTokenKind::NullptrLiteral
            | CppTokenKind::TrueKeyword
            | CppTokenKind::FalseKeyword
            | CppTokenKind::NullptrKeyword
    )
}

/// Is this token kind a comment?
pub fn is_comment(kind: CppTokenKind) -> bool {
    matches!(kind, CppTokenKind::LineComment | CppTokenKind::BlockComment)
}

/// The kind of a comment token, for the comment section of the AST.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CppCommentKind {
    Line,
    Block,
}

impl From<CppKind> for CppCommentKind {
    fn from(kind: CppKind) -> Self {
        match kind {
            CppKind::Token(CppTokenKind::BlockComment) => CppCommentKind::Block,
            _ => CppCommentKind::Line,
        }
    }
}

#[allow(dead_code)]
impl From<CppTokenKind> for CppCommentKind {
    fn from(kind: CppTokenKind) -> Self {
        match kind {
            CppTokenKind::BlockComment => CppCommentKind::Block,
            _ => CppCommentKind::Line,
        }
    }
}

/// A comment token.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppCommentToken {
    token: CppSyntaxToken,
}

impl CppAstToken for CppCommentToken {
    fn syntax(&self) -> &CppSyntaxToken {
        &self.token
    }

    fn can_cast(kind: CppTokenKind) -> bool
    where
        Self: Sized,
    {
        is_comment(kind)
    }

    fn cast(syntax: CppSyntaxToken) -> Option<Self>
    where
        Self: Sized,
    {
        if Self::can_cast(syntax.kind().into()) {
            Some(CppCommentToken { token: syntax })
        } else {
            None
        }
    }
}

impl CppCommentToken {
    pub fn get_comment_kind(&self) -> CppCommentKind {
        CppCommentKind::from(self.token.kind())
    }

    /// The comment text without its delimiters, and without the leading `*` most block comments put
    /// on continuation lines.
    pub fn get_comment_text(&self) -> String {
        let raw = self.token.text();
        match self.get_comment_kind() {
            CppCommentKind::Line => raw.trim_start_matches('/').trim().to_string(),
            CppCommentKind::Block => {
                let inner = raw
                    .strip_prefix("/*")
                    .and_then(|it| it.strip_suffix("*/"))
                    .unwrap_or(raw);
                inner
                    .lines()
                    .map(|line| line.trim().trim_start_matches('*').trim())
                    .filter(|line| !line.is_empty())
                    .collect::<Vec<_>>()
                    .join("\n")
            }
        }
    }

    /// Is this a documentation comment (`///`, `//!`, `/**`, `/*!`)?
    ///
    /// The distinction matters because only these are handed to the Doxygen layer; an ordinary
    /// comment is trivia and nothing more.
    pub fn is_doc_comment(&self) -> bool {
        let raw = self.token.text();
        match self.get_comment_kind() {
            CppCommentKind::Line => raw.starts_with("///") || raw.starts_with("//!"),
            CppCommentKind::Block => raw.starts_with("/**") || raw.starts_with("/*!"),
        }
    }
}

/// The `::` in a qualified name.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppScopeToken {
    token: CppSyntaxToken,
}

impl CppAstToken for CppScopeToken {
    fn syntax(&self) -> &CppSyntaxToken {
        &self.token
    }

    fn can_cast(kind: CppTokenKind) -> bool
    where
        Self: Sized,
    {
        kind == CppTokenKind::Scope
    }

    fn cast(syntax: CppSyntaxToken) -> Option<Self>
    where
        Self: Sized,
    {
        if Self::can_cast(syntax.kind().into()) {
            Some(CppScopeToken { token: syntax })
        } else {
            None
        }
    }
}

/// Nodes have no tokens of their own; this alias exists so `CppAstToken` implementations can name
/// the syntax kind of a token's parent without importing rowan.
pub type CppTokenParentKind = CppSyntaxKind;