Coverage Report

Created: 2020-09-22 08:39

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Parse/ParseTentative.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- ParseTentative.cpp - Ambiguity Resolution Parsing ----------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file implements the tentative parsing portions of the Parser
10
//  interfaces, for ambiguity resolution.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/Parse/Parser.h"
15
#include "clang/Parse/ParseDiagnostic.h"
16
#include "clang/Sema/ParsedTemplate.h"
17
using namespace clang;
18
19
/// isCXXDeclarationStatement - C++-specialized function that disambiguates
20
/// between a declaration or an expression statement, when parsing function
21
/// bodies. Returns true for declaration, false for expression.
22
///
23
///         declaration-statement:
24
///           block-declaration
25
///
26
///         block-declaration:
27
///           simple-declaration
28
///           asm-definition
29
///           namespace-alias-definition
30
///           using-declaration
31
///           using-directive
32
/// [C++0x]   static_assert-declaration
33
///
34
///         asm-definition:
35
///           'asm' '(' string-literal ')' ';'
36
///
37
///         namespace-alias-definition:
38
///           'namespace' identifier = qualified-namespace-specifier ';'
39
///
40
///         using-declaration:
41
///           'using' typename[opt] '::'[opt] nested-name-specifier
42
///                 unqualified-id ';'
43
///           'using' '::' unqualified-id ;
44
///
45
///         using-directive:
46
///           'using' 'namespace' '::'[opt] nested-name-specifier[opt]
47
///                 namespace-name ';'
48
///
49
1.97M
bool Parser::isCXXDeclarationStatement() {
50
1.97M
  switch (Tok.getKind()) {
51
    // asm-definition
52
34.5k
  case tok::kw_asm:
53
    // namespace-alias-definition
54
34.5k
  case tok::kw_namespace:
55
    // using-declaration
56
    // using-directive
57
34.5k
  case tok::kw_using:
58
    // static_assert-declaration
59
34.5k
  case tok::kw_static_assert:
60
34.5k
  case tok::kw__Static_assert:
61
34.5k
    return true;
62
    // simple-declaration
63
1.94M
  default:
64
1.94M
    return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
65
1.97M
  }
66
1.97M
}
67
68
/// isCXXSimpleDeclaration - C++-specialized function that disambiguates
69
/// between a simple-declaration or an expression-statement.
70
/// If during the disambiguation process a parsing error is encountered,
71
/// the function returns true to let the declaration parsing code handle it.
72
/// Returns false if the statement is disambiguated as expression.
73
///
74
/// simple-declaration:
75
///   decl-specifier-seq init-declarator-list[opt] ';'
76
///   decl-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
77
///                      brace-or-equal-initializer ';'    [C++17]
78
///
79
/// (if AllowForRangeDecl specified)
80
/// for ( for-range-declaration : for-range-initializer ) statement
81
///
82
/// for-range-declaration:
83
///    decl-specifier-seq declarator
84
///    decl-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
85
///
86
/// In any of the above cases there can be a preceding attribute-specifier-seq,
87
/// but the caller is expected to handle that.
88
2.07M
bool Parser::isCXXSimpleDeclaration(bool AllowForRangeDecl) {
89
  // C++ 6.8p1:
90
  // There is an ambiguity in the grammar involving expression-statements and
91
  // declarations: An expression-statement with a function-style explicit type
92
  // conversion (5.2.3) as its leftmost subexpression can be indistinguishable
93
  // from a declaration where the first declarator starts with a '('. In those
94
  // cases the statement is a declaration. [Note: To disambiguate, the whole
95
  // statement might have to be examined to determine if it is an
96
  // expression-statement or a declaration].
97
98
  // C++ 6.8p3:
99
  // The disambiguation is purely syntactic; that is, the meaning of the names
100
  // occurring in such a statement, beyond whether they are type-names or not,
101
  // is not generally used in or changed by the disambiguation. Class
102
  // templates are instantiated as necessary to determine if a qualified name
103
  // is a type-name. Disambiguation precedes parsing, and a statement
104
  // disambiguated as a declaration may be an ill-formed declaration.
105
106
  // We don't have to parse all of the decl-specifier-seq part. There's only
107
  // an ambiguity if the first decl-specifier is
108
  // simple-type-specifier/typename-specifier followed by a '(', which may
109
  // indicate a function-style cast expression.
110
  // isCXXDeclarationSpecifier will return TPResult::Ambiguous only in such
111
  // a case.
112
113
2.07M
  bool InvalidAsDeclaration = false;
114
2.07M
  TPResult TPR = isCXXDeclarationSpecifier(TPResult::False,
115
2.07M
                                           &InvalidAsDeclaration);
116
2.07M
  if (TPR != TPResult::Ambiguous)
117
2.02M
    return TPR != TPResult::False; // Returns true for TPResult::True or
118
                                   // TPResult::Error.
119
120
  // FIXME: TryParseSimpleDeclaration doesn't look past the first initializer,
121
  // and so gets some cases wrong. We can't carry on if we've already seen
122
  // something which makes this statement invalid as a declaration in this case,
123
  // since it can cause us to misparse valid code. Revisit this once
124
  // TryParseInitDeclaratorList is fixed.
125
51.6k
  if (InvalidAsDeclaration)
126
39.3k
    return false;
127
128
  // FIXME: Add statistics about the number of ambiguous statements encountered
129
  // and how they were resolved (number of declarations+number of expressions).
130
131
  // Ok, we have a simple-type-specifier/typename-specifier followed by a '(',
132
  // or an identifier which doesn't resolve as anything. We need tentative
133
  // parsing...
134
135
12.3k
  {
136
12.3k
    RevertingTentativeParsingAction PA(*this);
137
12.3k
    TPR = TryParseSimpleDeclaration(AllowForRangeDecl);
138
12.3k
  }
139
140
  // In case of an error, let the declaration parsing code handle it.
141
12.3k
  if (TPR == TPResult::Error)
142
0
    return true;
143
144
  // Declarations take precedence over expressions.
145
12.3k
  if (TPR == TPResult::Ambiguous)
146
302
    TPR = TPResult::True;
147
148
12.3k
  assert(TPR == TPResult::True || TPR == TPResult::False);
149
12.3k
  return TPR == TPResult::True;
150
12.3k
}
151
152
/// Try to consume a token sequence that we've already identified as
153
/// (potentially) starting a decl-specifier.
154
76.5k
Parser::TPResult Parser::TryConsumeDeclarationSpecifier() {
155
76.5k
  switch (Tok.getKind()) {
156
0
  case tok::kw__Atomic:
157
0
    if (NextToken().isNot(tok::l_paren)) {
158
0
      ConsumeToken();
159
0
      break;
160
0
    }
161
0
    LLVM_FALLTHROUGH;
162
14
  case tok::kw_typeof:
163
14
  case tok::kw___attribute:
164
14
  case tok::kw___underlying_type: {
165
14
    ConsumeToken();
166
14
    if (Tok.isNot(tok::l_paren))
167
0
      return TPResult::Error;
168
14
    ConsumeParen();
169
14
    if (!SkipUntil(tok::r_paren))
170
0
      return TPResult::Error;
171
14
    break;
172
14
  }
173
174
5
  case tok::kw_class:
175
5
  case tok::kw_struct:
176
5
  case tok::kw_union:
177
5
  case tok::kw___interface:
178
5
  case tok::kw_enum:
179
    // elaborated-type-specifier:
180
    //     class-key attribute-specifier-seq[opt]
181
    //         nested-name-specifier[opt] identifier
182
    //     class-key nested-name-specifier[opt] template[opt] simple-template-id
183
    //     enum nested-name-specifier[opt] identifier
184
    //
185
    // FIXME: We don't support class-specifiers nor enum-specifiers here.
186
5
    ConsumeToken();
187
188
    // Skip attributes.
189
5
    if (!TrySkipAttributes())
190
0
      return TPResult::Error;
191
192
5
    if (TryAnnotateOptionalCXXScopeToken())
193
0
      return TPResult::Error;
194
5
    if (Tok.is(tok::annot_cxxscope))
195
1
      ConsumeAnnotationToken();
196
5
    if (Tok.is(tok::identifier))
197
3
      ConsumeToken();
198
2
    else if (Tok.is(tok::annot_template_id))
199
1
      ConsumeAnnotationToken();
200
1
    else
201
1
      return TPResult::Error;
202
4
    break;
203
204
513
  case tok::annot_cxxscope:
205
513
    ConsumeAnnotationToken();
206
513
    LLVM_FALLTHROUGH;
207
76.5k
  default:
208
76.5k
    ConsumeAnyToken();
209
210
76.5k
    if (getLangOpts().ObjC && 
Tok.is(tok::less)2.87k
)
211
0
      return TryParseProtocolQualifiers();
212
76.5k
    break;
213
76.5k
  }
214
215
76.5k
  return TPResult::Ambiguous;
216
76.5k
}
217
218
/// simple-declaration:
219
///   decl-specifier-seq init-declarator-list[opt] ';'
220
///
221
/// (if AllowForRangeDecl specified)
222
/// for ( for-range-declaration : for-range-initializer ) statement
223
/// for-range-declaration:
224
///    attribute-specifier-seqopt type-specifier-seq declarator
225
///
226
12.3k
Parser::TPResult Parser::TryParseSimpleDeclaration(bool AllowForRangeDecl) {
227
12.3k
  if (TryConsumeDeclarationSpecifier() == TPResult::Error)
228
0
    return TPResult::Error;
229
230
  // Two decl-specifiers in a row conclusively disambiguate this as being a
231
  // simple-declaration. Don't bother calling isCXXDeclarationSpecifier in the
232
  // overwhelmingly common case that the next token is a '('.
233
12.3k
  if (Tok.isNot(tok::l_paren)) {
234
678
    TPResult TPR = isCXXDeclarationSpecifier();
235
678
    if (TPR == TPResult::Ambiguous)
236
0
      return TPResult::True;
237
678
    if (TPR == TPResult::True || TPR == TPResult::Error)
238
0
      return TPR;
239
678
    assert(TPR == TPResult::False);
240
678
  }
241
242
12.3k
  TPResult TPR = TryParseInitDeclaratorList();
243
12.3k
  if (TPR != TPResult::Ambiguous)
244
9.29k
    return TPR;
245
246
3.02k
  if (Tok.isNot(tok::semi) && 
(2.72k
!AllowForRangeDecl2.72k
||
Tok.isNot(tok::colon)8
))
247
2.72k
    return TPResult::False;
248
249
302
  return TPResult::Ambiguous;
250
302
}
251
252
/// Tentatively parse an init-declarator-list in order to disambiguate it from
253
/// an expression.
254
///
255
///       init-declarator-list:
256
///         init-declarator
257
///         init-declarator-list ',' init-declarator
258
///
259
///       init-declarator:
260
///         declarator initializer[opt]
261
/// [GNU]   declarator simple-asm-expr[opt] attributes[opt] initializer[opt]
262
///
263
///       initializer:
264
///         brace-or-equal-initializer
265
///         '(' expression-list ')'
266
///
267
///       brace-or-equal-initializer:
268
///         '=' initializer-clause
269
/// [C++11] braced-init-list
270
///
271
///       initializer-clause:
272
///         assignment-expression
273
///         braced-init-list
274
///
275
///       braced-init-list:
276
///         '{' initializer-list ','[opt] '}'
277
///         '{' '}'
278
///
279
12.3k
Parser::TPResult Parser::TryParseInitDeclaratorList() {
280
12.3k
  while (1) {
281
    // declarator
282
12.3k
    TPResult TPR = TryParseDeclarator(false/*mayBeAbstract*/);
283
12.3k
    if (TPR != TPResult::Ambiguous)
284
7.68k
      return TPR;
285
286
    // [GNU] simple-asm-expr[opt] attributes[opt]
287
4.67k
    if (Tok.isOneOf(tok::kw_asm, tok::kw___attribute))
288
8
      return TPResult::True;
289
290
    // initializer[opt]
291
4.67k
    if (Tok.is(tok::l_paren)) {
292
      // Parse through the parens.
293
11
      ConsumeParen();
294
11
      if (!SkipUntil(tok::r_paren, StopAtSemi))
295
0
        return TPResult::Error;
296
4.66k
    } else if (Tok.is(tok::l_brace)) {
297
      // A left-brace here is sufficient to disambiguate the parse; an
298
      // expression can never be followed directly by a braced-init-list.
299
2
      return TPResult::True;
300
4.65k
    } else if (Tok.is(tok::equal) || 
isTokIdentifier_in()3.05k
) {
301
      // MSVC and g++ won't examine the rest of declarators if '=' is
302
      // encountered; they just conclude that we have a declaration.
303
      // EDG parses the initializer completely, which is the proper behavior
304
      // for this case.
305
      //
306
      // At present, Clang follows MSVC and g++, since the parser does not have
307
      // the ability to parse an expression fully without recording the
308
      // results of that parse.
309
      // FIXME: Handle this case correctly.
310
      //
311
      // Also allow 'in' after an Objective-C declaration as in:
312
      // for (int (^b)(void) in array). Ideally this should be done in the
313
      // context of parsing for-init-statement of a foreach statement only. But,
314
      // in any other context 'in' is invalid after a declaration and parser
315
      // issues the error regardless of outcome of this decision.
316
      // FIXME: Change if above assumption does not hold.
317
1.61k
      return TPResult::True;
318
1.61k
    }
319
320
3.05k
    if (!TryConsumeToken(tok::comma))
321
3.04k
      break;
322
3.05k
  }
323
324
3.04k
  return TPResult::Ambiguous;
325
12.3k
}
326
327
struct Parser::ConditionDeclarationOrInitStatementState {
328
  Parser &P;
329
  bool CanBeExpression = true;
330
  bool CanBeCondition = true;
331
  bool CanBeInitStatement;
332
  bool CanBeForRangeDecl;
333
334
  ConditionDeclarationOrInitStatementState(Parser &P, bool CanBeInitStatement,
335
                                           bool CanBeForRangeDecl)
336
      : P(P), CanBeInitStatement(CanBeInitStatement),
337
617k
        CanBeForRangeDecl(CanBeForRangeDecl) {}
338
339
621k
  bool resolved() {
340
621k
    return CanBeExpression + CanBeCondition + CanBeInitStatement +
341
621k
               CanBeForRangeDecl < 2;
342
621k
  }
343
344
1.13k
  void markNotExpression() {
345
1.13k
    CanBeExpression = false;
346
347
1.13k
    if (!resolved()) {
348
      // FIXME: Unify the parsing codepaths for condition variables and
349
      // simple-declarations so that we don't need to eagerly figure out which
350
      // kind we have here. (Just parse init-declarators until we reach a
351
      // semicolon or right paren.)
352
644
      RevertingTentativeParsingAction PA(P);
353
644
      if (CanBeForRangeDecl) {
354
        // Skip until we hit a ')', ';', or a ':' with no matching '?'.
355
        // The final case is a for range declaration, the rest are not.
356
126
        while (true) {
357
126
          unsigned QuestionColonDepth = 0;
358
126
          P.SkipUntil({tok::r_paren, tok::semi, tok::question, tok::colon},
359
126
                      StopBeforeMatch);
360
126
          if (P.Tok.is(tok::question))
361
1
            ++QuestionColonDepth;
362
125
          else if (P.Tok.is(tok::colon)) {
363
37
            if (QuestionColonDepth)
364
0
              --QuestionColonDepth;
365
37
            else {
366
37
              CanBeCondition = CanBeInitStatement = false;
367
37
              return;
368
37
            }
369
88
          } else {
370
88
            CanBeForRangeDecl = false;
371
88
            break;
372
88
          }
373
1
          P.ConsumeToken();
374
1
        }
375
519
      } else {
376
        // Just skip until we hit a ')' or ';'.
377
519
        P.SkipUntil(tok::r_paren, tok::semi, StopBeforeMatch);
378
519
      }
379
607
      if (P.Tok.isNot(tok::r_paren))
380
179
        CanBeCondition = CanBeForRangeDecl = false;
381
607
      if (P.Tok.isNot(tok::semi))
382
430
        CanBeInitStatement = false;
383
607
    }
384
1.13k
  }
385
386
22
  bool markNotCondition() {
387
22
    CanBeCondition = false;
388
22
    return resolved();
389
22
  }
390
391
22
  bool markNotForRangeDecl() {
392
22
    CanBeForRangeDecl = false;
393
22
    return resolved();
394
22
  }
395
396
618k
  bool update(TPResult IsDecl) {
397
618k
    switch (IsDecl) {
398
1.12k
    case TPResult::True:
399
1.12k
      markNotExpression();
400
1.12k
      assert(resolved() && "can't continue after tentative parsing bails out");
401
1.12k
      break;
402
615k
    case TPResult::False:
403
615k
      CanBeCondition = CanBeInitStatement = CanBeForRangeDecl = false;
404
615k
      break;
405
1.73k
    case TPResult::Ambiguous:
406
1.73k
      break;
407
0
    case TPResult::Error:
408
0
      CanBeExpression = CanBeCondition = CanBeInitStatement =
409
0
          CanBeForRangeDecl = false;
410
0
      break;
411
618k
    }
412
618k
    return resolved();
413
618k
  }
414
415
617k
  ConditionOrInitStatement result() const {
416
617k
    assert(CanBeExpression + CanBeCondition + CanBeInitStatement +
417
617k
                   CanBeForRangeDecl < 2 &&
418
617k
           "result called but not yet resolved");
419
617k
    if (CanBeExpression)
420
615k
      return ConditionOrInitStatement::Expression;
421
1.13k
    if (CanBeCondition)
422
916
      return ConditionOrInitStatement::ConditionDecl;
423
216
    if (CanBeInitStatement)
424
90
      return ConditionOrInitStatement::InitStmtDecl;
425
126
    if (CanBeForRangeDecl)
426
37
      return ConditionOrInitStatement::ForRangeDecl;
427
89
    return ConditionOrInitStatement::Error;
428
89
  }
429
};
430
431
144
bool Parser::isEnumBase(bool AllowSemi) {
432
144
  assert(Tok.is(tok::colon) && "should be looking at the ':'");
433
434
144
  RevertingTentativeParsingAction PA(*this);
435
  // ':'
436
144
  ConsumeToken();
437
438
  // type-specifier-seq
439
144
  bool InvalidAsDeclSpec = false;
440
  // FIXME: We could disallow non-type decl-specifiers here, but it makes no
441
  // difference: those specifiers are ill-formed regardless of the
442
  // interpretation.
443
144
  TPResult R = isCXXDeclarationSpecifier(/*BracedCastResult*/ TPResult::True,
444
144
                                         &InvalidAsDeclSpec);
445
144
  if (R == TPResult::Ambiguous) {
446
    // We either have a decl-specifier followed by '(' or an undeclared
447
    // identifier.
448
13
    if (TryConsumeDeclarationSpecifier() == TPResult::Error)
449
0
      return true;
450
451
    // If we get to the end of the enum-base, we hit either a '{' or a ';'.
452
    // Don't bother checking the enumerator-list.
453
13
    if (Tok.is(tok::l_brace) || 
(11
AllowSemi11
&&
Tok.is(tok::semi)11
))
454
2
      return true;
455
456
    // A second decl-specifier unambiguously indicatges an enum-base.
457
11
    R = isCXXDeclarationSpecifier(TPResult::True, &InvalidAsDeclSpec);
458
11
  }
459
460
142
  return R != TPResult::False;
461
144
}
462
463
/// Disambiguates between a declaration in a condition, a
464
/// simple-declaration in an init-statement, and an expression for
465
/// a condition of a if/switch statement.
466
///
467
///       condition:
468
///         expression
469
///         type-specifier-seq declarator '=' assignment-expression
470
/// [C++11] type-specifier-seq declarator '=' initializer-clause
471
/// [C++11] type-specifier-seq declarator braced-init-list
472
/// [GNU]   type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
473
///             '=' assignment-expression
474
///       simple-declaration:
475
///         decl-specifier-seq init-declarator-list[opt] ';'
476
///
477
/// Note that, unlike isCXXSimpleDeclaration, we must disambiguate all the way
478
/// to the ';' to disambiguate cases like 'int(x))' (an expression) from
479
/// 'int(x);' (a simple-declaration in an init-statement).
480
Parser::ConditionOrInitStatement
481
Parser::isCXXConditionDeclarationOrInitStatement(bool CanBeInitStatement,
482
617k
                                                 bool CanBeForRangeDecl) {
483
617k
  ConditionDeclarationOrInitStatementState State(*this, CanBeInitStatement,
484
617k
                                                 CanBeForRangeDecl);
485
486
617k
  if (State.update(isCXXDeclarationSpecifier()))
487
616k
    return State.result();
488
489
  // It might be a declaration; we need tentative parsing.
490
848
  RevertingTentativeParsingAction PA(*this);
491
492
  // FIXME: A tag definition unambiguously tells us this is an init-statement.
493
848
  if (State.update(TryConsumeDeclarationSpecifier()))
494
0
    return State.result();
495
848
  assert(Tok.is(tok::l_paren) && "Expected '('");
496
497
854
  while (true) {
498
    // Consume a declarator.
499
854
    if (State.update(TryParseDeclarator(false/*mayBeAbstract*/)))
500
819
      return State.result();
501
502
    // Attributes, asm label, or an initializer imply this is not an expression.
503
    // FIXME: Disambiguate properly after an = instead of assuming that it's a
504
    // valid declaration.
505
35
    if (Tok.isOneOf(tok::equal, tok::kw_asm, tok::kw___attribute) ||
506
26
        (getLangOpts().CPlusPlus11 && 
Tok.is(tok::l_brace)25
)) {
507
11
      State.markNotExpression();
508
11
      return State.result();
509
11
    }
510
511
    // A colon here identifies a for-range declaration.
512
24
    if (State.CanBeForRangeDecl && 
Tok.is(tok::colon)3
)
513
2
      return ConditionOrInitStatement::ForRangeDecl;
514
515
    // At this point, it can't be a condition any more, because a condition
516
    // must have a brace-or-equal-initializer.
517
22
    if (State.markNotCondition())
518
0
      return State.result();
519
520
    // Likewise, it can't be a for-range declaration any more.
521
22
    if (State.markNotForRangeDecl())
522
1
      return State.result();
523
524
    // A parenthesized initializer could be part of an expression or a
525
    // simple-declaration.
526
21
    if (Tok.is(tok::l_paren)) {
527
1
      ConsumeParen();
528
1
      SkipUntil(tok::r_paren, StopAtSemi);
529
1
    }
530
531
21
    if (!TryConsumeToken(tok::comma))
532
15
      break;
533
21
  }
534
535
  // We reached the end. If it can now be some kind of decl, then it is.
536
15
  if (State.CanBeCondition && 
Tok.is(tok::r_paren)0
)
537
0
    return ConditionOrInitStatement::ConditionDecl;
538
15
  else if (State.CanBeInitStatement && Tok.is(tok::semi))
539
2
    return ConditionOrInitStatement::InitStmtDecl;
540
13
  else
541
13
    return ConditionOrInitStatement::Expression;
542
15
}
543
544
  /// Determine whether the next set of tokens contains a type-id.
545
  ///
546
  /// The context parameter states what context we're parsing right
547
  /// now, which affects how this routine copes with the token
548
  /// following the type-id. If the context is TypeIdInParens, we have
549
  /// already parsed the '(' and we will cease lookahead when we hit
550
  /// the corresponding ')'. If the context is
551
  /// TypeIdAsTemplateArgument, we've already parsed the '<' or ','
552
  /// before this template argument, and will cease lookahead when we
553
  /// hit a '>', '>>' (in C++0x), or ','; or, in C++0x, an ellipsis immediately
554
  /// preceding such. Returns true for a type-id and false for an expression.
555
  /// If during the disambiguation process a parsing error is encountered,
556
  /// the function returns true to let the declaration parsing code handle it.
557
  ///
558
  /// type-id:
559
  ///   type-specifier-seq abstract-declarator[opt]
560
  ///
561
5.25M
bool Parser::isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous) {
562
563
5.25M
  isAmbiguous = false;
564
565
  // C++ 8.2p2:
566
  // The ambiguity arising from the similarity between a function-style cast and
567
  // a type-id can occur in different contexts. The ambiguity appears as a
568
  // choice between a function-style cast expression and a declaration of a
569
  // type. The resolution is that any construct that could possibly be a type-id
570
  // in its syntactic context shall be considered a type-id.
571
572
5.25M
  TPResult TPR = isCXXDeclarationSpecifier();
573
5.25M
  if (TPR != TPResult::Ambiguous)
574
5.19M
    return TPR != TPResult::False; // Returns true for TPResult::True or
575
                                     // TPResult::Error.
576
577
  // FIXME: Add statistics about the number of ambiguous statements encountered
578
  // and how they were resolved (number of declarations+number of expressions).
579
580
  // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
581
  // We need tentative parsing...
582
583
53.3k
  RevertingTentativeParsingAction PA(*this);
584
585
  // type-specifier-seq
586
53.3k
  TryConsumeDeclarationSpecifier();
587
53.3k
  assert(Tok.is(tok::l_paren) && "Expected '('");
588
589
  // declarator
590
53.3k
  TPR = TryParseDeclarator(true/*mayBeAbstract*/, false/*mayHaveIdentifier*/);
591
592
  // In case of an error, let the declaration parsing code handle it.
593
53.3k
  if (TPR == TPResult::Error)
594
1
    TPR = TPResult::True;
595
596
53.3k
  if (TPR == TPResult::Ambiguous) {
597
    // We are supposed to be inside parens, so if after the abstract declarator
598
    // we encounter a ')' this is a type-id, otherwise it's an expression.
599
51.4k
    if (Context == TypeIdInParens && 
Tok.is(tok::r_paren)2.14k
) {
600
1.92k
      TPR = TPResult::True;
601
1.92k
      isAmbiguous = true;
602
603
    // We are supposed to be inside a template argument, so if after
604
    // the abstract declarator we encounter a '>', '>>' (in C++0x), or
605
    // ','; or, in C++0x, an ellipsis immediately preceding such, this
606
    // is a type-id. Otherwise, it's an expression.
607
49.5k
    } else if (Context == TypeIdAsTemplateArgument &&
608
49.2k
               (Tok.isOneOf(tok::greater, tok::comma) ||
609
20
                (getLangOpts().CPlusPlus11 &&
610
20
                 (Tok.isOneOf(tok::greatergreater,
611
20
                              tok::greatergreatergreater) ||
612
13
                  (Tok.is(tok::ellipsis) &&
613
4
                   NextToken().isOneOf(tok::greater, tok::greatergreater,
614
4
                                       tok::greatergreatergreater,
615
49.2k
                                       tok::comma)))))) {
616
49.2k
      TPR = TPResult::True;
617
49.2k
      isAmbiguous = true;
618
619
49.2k
    } else
620
229
      TPR = TPResult::False;
621
51.4k
  }
622
623
53.3k
  assert(TPR == TPResult::True || TPR == TPResult::False);
624
53.3k
  return TPR == TPResult::True;
625
53.3k
}
626
627
/// Returns true if this is a C++11 attribute-specifier. Per
628
/// C++11 [dcl.attr.grammar]p6, two consecutive left square bracket tokens
629
/// always introduce an attribute. In Objective-C++11, this rule does not
630
/// apply if either '[' begins a message-send.
631
///
632
/// If Disambiguate is true, we try harder to determine whether a '[[' starts
633
/// an attribute-specifier, and return CAK_InvalidAttributeSpecifier if not.
634
///
635
/// If OuterMightBeMessageSend is true, we assume the outer '[' is either an
636
/// Obj-C message send or the start of an attribute. Otherwise, we assume it
637
/// is not an Obj-C message send.
638
///
639
/// C++11 [dcl.attr.grammar]:
640
///
641
///     attribute-specifier:
642
///         '[' '[' attribute-list ']' ']'
643
///         alignment-specifier
644
///
645
///     attribute-list:
646
///         attribute[opt]
647
///         attribute-list ',' attribute[opt]
648
///         attribute '...'
649
///         attribute-list ',' attribute '...'
650
///
651
///     attribute:
652
///         attribute-token attribute-argument-clause[opt]
653
///
654
///     attribute-token:
655
///         identifier
656
///         identifier '::' identifier
657
///
658
///     attribute-argument-clause:
659
///         '(' balanced-token-seq ')'
660
Parser::CXX11AttributeKind
661
Parser::isCXX11AttributeSpecifier(bool Disambiguate,
662
36.1M
                                  bool OuterMightBeMessageSend) {
663
36.1M
  if (Tok.is(tok::kw_alignas))
664
7.39k
    return CAK_AttributeSpecifier;
665
666
36.1M
  if (Tok.isNot(tok::l_square) || 
NextToken().isNot(tok::l_square)141k
)
667
36.1M
    return CAK_NotAttributeSpecifier;
668
669
  // No tentative parsing if we don't need to look for ']]' or a lambda.
670
12.7k
  if (!Disambiguate && 
!getLangOpts().ObjC12.6k
)
671
12.3k
    return CAK_AttributeSpecifier;
672
673
  // '[[using ns: ...]]' is an attribute.
674
379
  if (GetLookAheadToken(2).is(tok::kw_using))
675
0
    return CAK_AttributeSpecifier;
676
677
379
  RevertingTentativeParsingAction PA(*this);
678
679
  // Opening brackets were checked for above.
680
379
  ConsumeBracket();
681
682
379
  if (!getLangOpts().ObjC) {
683
8
    ConsumeBracket();
684
685
8
    bool IsAttribute = SkipUntil(tok::r_square);
686
8
    IsAttribute &= Tok.is(tok::r_square);
687
688
4
    return IsAttribute ? CAK_AttributeSpecifier : CAK_InvalidAttributeSpecifier;
689
8
  }
690
691
  // In Obj-C++11, we need to distinguish four situations:
692
  //  1a) int x[[attr]];                     C++11 attribute.
693
  //  1b) [[attr]];                          C++11 statement attribute.
694
  //   2) int x[[obj](){ return 1; }()];     Lambda in array size/index.
695
  //  3a) int x[[obj get]];                  Message send in array size/index.
696
  //  3b) [[Class alloc] init];              Message send in message send.
697
  //   4) [[obj]{ return self; }() doStuff]; Lambda in message send.
698
  // (1) is an attribute, (2) is ill-formed, and (3) and (4) are accepted.
699
700
  // Check to see if this is a lambda-expression.
701
  // FIXME: If this disambiguation is too slow, fold the tentative lambda parse
702
  // into the tentative attribute parse below.
703
371
  {
704
371
    RevertingTentativeParsingAction LambdaTPA(*this);
705
371
    LambdaIntroducer Intro;
706
371
    LambdaIntroducerTentativeParse Tentative;
707
371
    if (ParseLambdaIntroducer(Intro, &Tentative)) {
708
      // We hit a hard error after deciding this was not an attribute.
709
      // FIXME: Don't parse and annotate expressions when disambiguating
710
      // against an attribute.
711
0
      return CAK_NotAttributeSpecifier;
712
0
    }
713
714
371
    switch (Tentative) {
715
32
    case LambdaIntroducerTentativeParse::MessageSend:
716
      // Case 3: The inner construct is definitely a message send, so the
717
      // outer construct is definitely not an attribute.
718
32
      return CAK_NotAttributeSpecifier;
719
720
262
    case LambdaIntroducerTentativeParse::Success:
721
262
    case LambdaIntroducerTentativeParse::Incomplete:
722
      // This is a lambda-introducer or attribute-specifier.
723
262
      if (Tok.is(tok::r_square))
724
        // Case 1: C++11 attribute.
725
256
        return CAK_AttributeSpecifier;
726
727
6
      if (OuterMightBeMessageSend)
728
        // Case 4: Lambda in message send.
729
5
        return CAK_NotAttributeSpecifier;
730
731
      // Case 2: Lambda in array size / index.
732
1
      return CAK_InvalidAttributeSpecifier;
733
734
77
    case LambdaIntroducerTentativeParse::Invalid:
735
      // No idea what this is; we couldn't parse it as a lambda-introducer.
736
      // Might still be an attribute-specifier or a message send.
737
77
      break;
738
77
    }
739
77
  }
740
741
77
  ConsumeBracket();
742
743
  // If we don't have a lambda-introducer, then we have an attribute or a
744
  // message-send.
745
77
  bool IsAttribute = true;
746
81
  while (Tok.isNot(tok::r_square)) {
747
81
    if (Tok.is(tok::comma)) {
748
      // Case 1: Stray commas can only occur in attributes.
749
1
      return CAK_AttributeSpecifier;
750
1
    }
751
752
    // Parse the attribute-token, if present.
753
    // C++11 [dcl.attr.grammar]:
754
    //   If a keyword or an alternative token that satisfies the syntactic
755
    //   requirements of an identifier is contained in an attribute-token,
756
    //   it is considered an identifier.
757
80
    SourceLocation Loc;
758
80
    if (!TryParseCXX11AttributeIdentifier(Loc)) {
759
10
      IsAttribute = false;
760
10
      break;
761
10
    }
762
70
    if (Tok.is(tok::coloncolon)) {
763
58
      ConsumeToken();
764
58
      if (!TryParseCXX11AttributeIdentifier(Loc)) {
765
0
        IsAttribute = false;
766
0
        break;
767
0
      }
768
70
    }
769
770
    // Parse the attribute-argument-clause, if present.
771
70
    if (Tok.is(tok::l_paren)) {
772
11
      ConsumeParen();
773
11
      if (!SkipUntil(tok::r_paren)) {
774
0
        IsAttribute = false;
775
0
        break;
776
0
      }
777
70
    }
778
779
70
    TryConsumeToken(tok::ellipsis);
780
781
70
    if (!TryConsumeToken(tok::comma))
782
66
      break;
783
70
  }
784
785
  // An attribute must end ']]'.
786
76
  if (IsAttribute) {
787
66
    if (Tok.is(tok::r_square)) {
788
59
      ConsumeBracket();
789
59
      IsAttribute = Tok.is(tok::r_square);
790
7
    } else {
791
7
      IsAttribute = false;
792
7
    }
793
66
  }
794
795
76
  if (IsAttribute)
796
    // Case 1: C++11 statement attribute.
797
59
    return CAK_AttributeSpecifier;
798
799
  // Case 3: Message send.
800
17
  return CAK_NotAttributeSpecifier;
801
17
}
802
803
55.1k
bool Parser::TrySkipAttributes() {
804
55.1k
  while (Tok.isOneOf(tok::l_square, tok::kw___attribute, tok::kw___declspec,
805
15
                     tok::kw_alignas)) {
806
15
    if (Tok.is(tok::l_square)) {
807
8
      ConsumeBracket();
808
8
      if (Tok.isNot(tok::l_square))
809
1
        return false;
810
7
      ConsumeBracket();
811
7
      if (!SkipUntil(tok::r_square) || Tok.isNot(tok::r_square))
812
0
        return false;
813
      // Note that explicitly checking for `[[` and `]]` allows to fail as
814
      // expected in the case of the Objective-C message send syntax.
815
7
      ConsumeBracket();
816
7
    } else {
817
7
      ConsumeToken();
818
7
      if (Tok.isNot(tok::l_paren))
819
0
        return false;
820
7
      ConsumeParen();
821
7
      if (!SkipUntil(tok::r_paren))
822
0
        return false;
823
7
    }
824
15
  }
825
826
55.1k
  return true;
827
55.1k
}
828
829
125k
Parser::TPResult Parser::TryParsePtrOperatorSeq() {
830
180k
  while (true) {
831
180k
    if (TryAnnotateOptionalCXXScopeToken(true))
832
0
      return TPResult::Error;
833
834
180k
    if (Tok.isOneOf(tok::star, tok::amp, tok::caret, tok::ampamp) ||
835
144k
        (Tok.is(tok::annot_cxxscope) && 
NextToken().is(tok::star)21.8k
)) {
836
      // ptr-operator
837
55.1k
      ConsumeAnyToken();
838
839
      // Skip attributes.
840
55.1k
      if (!TrySkipAttributes())
841
1
        return TPResult::Error;
842
843
57.5k
      
while (55.1k
Tok.isOneOf(tok::kw_const, tok::kw_volatile, tok::kw_restrict,
844
57.5k
                         tok::kw__Nonnull, tok::kw__Nullable,
845
57.5k
                         tok::kw__Null_unspecified, tok::kw__Atomic))
846
2.40k
        ConsumeToken();
847
125k
    } else {
848
125k
      return TPResult::True;
849
125k
    }
850
180k
  }
851
125k
}
852
853
///         operator-function-id:
854
///           'operator' operator
855
///
856
///         operator: one of
857
///           new  delete  new[]  delete[]  +  -  *  /  %  ^  [...]
858
///
859
///         conversion-function-id:
860
///           'operator' conversion-type-id
861
///
862
///         conversion-type-id:
863
///           type-specifier-seq conversion-declarator[opt]
864
///
865
///         conversion-declarator:
866
///           ptr-operator conversion-declarator[opt]
867
///
868
///         literal-operator-id:
869
///           'operator' string-literal identifier
870
///           'operator' user-defined-string-literal
871
16
Parser::TPResult Parser::TryParseOperatorId() {
872
16
  assert(Tok.is(tok::kw_operator));
873
16
  ConsumeToken();
874
875
  // Maybe this is an operator-function-id.
876
16
  switch (Tok.getKind()) {
877
0
  case tok::kw_new: case tok::kw_delete:
878
0
    ConsumeToken();
879
0
    if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
880
0
      ConsumeBracket();
881
0
      ConsumeBracket();
882
0
    }
883
0
    return TPResult::True;
884
885
0
#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemOnly) \
886
608
  case tok::Token:
887
0
#define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemOnly)
888
16
#include 
"clang/Basic/OperatorKinds.def"0
889
16
    ConsumeToken();
890
16
    return TPResult::True;
891
892
0
  case tok::l_square:
893
0
    if (NextToken().is(tok::r_square)) {
894
0
      ConsumeBracket();
895
0
      ConsumeBracket();
896
0
      return TPResult::True;
897
0
    }
898
0
    break;
899
900
0
  case tok::l_paren:
901
0
    if (NextToken().is(tok::r_paren)) {
902
0
      ConsumeParen();
903
0
      ConsumeParen();
904
0
      return TPResult::True;
905
0
    }
906
0
    break;
907
908
0
  default:
909
0
    break;
910
0
  }
911
912
  // Maybe this is a literal-operator-id.
913
0
  if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
914
0
    bool FoundUDSuffix = false;
915
0
    do {
916
0
      FoundUDSuffix |= Tok.hasUDSuffix();
917
0
      ConsumeStringToken();
918
0
    } while (isTokenStringLiteral());
919
920
0
    if (!FoundUDSuffix) {
921
0
      if (Tok.is(tok::identifier))
922
0
        ConsumeToken();
923
0
      else
924
0
        return TPResult::Error;
925
0
    }
926
0
    return TPResult::True;
927
0
  }
928
929
  // Maybe this is a conversion-function-id.
930
0
  bool AnyDeclSpecifiers = false;
931
0
  while (true) {
932
0
    TPResult TPR = isCXXDeclarationSpecifier();
933
0
    if (TPR == TPResult::Error)
934
0
      return TPR;
935
0
    if (TPR == TPResult::False) {
936
0
      if (!AnyDeclSpecifiers)
937
0
        return TPResult::Error;
938
0
      break;
939
0
    }
940
0
    if (TryConsumeDeclarationSpecifier() == TPResult::Error)
941
0
      return TPResult::Error;
942
0
    AnyDeclSpecifiers = true;
943
0
  }
944
0
  return TryParsePtrOperatorSeq();
945
0
}
946
947
///         declarator:
948
///           direct-declarator
949
///           ptr-operator declarator
950
///
951
///         direct-declarator:
952
///           declarator-id
953
///           direct-declarator '(' parameter-declaration-clause ')'
954
///                 cv-qualifier-seq[opt] exception-specification[opt]
955
///           direct-declarator '[' constant-expression[opt] ']'
956
///           '(' declarator ')'
957
/// [GNU]     '(' attributes declarator ')'
958
///
959
///         abstract-declarator:
960
///           ptr-operator abstract-declarator[opt]
961
///           direct-abstract-declarator
962
///
963
///         direct-abstract-declarator:
964
///           direct-abstract-declarator[opt]
965
///                 '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
966
///                 exception-specification[opt]
967
///           direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
968
///           '(' abstract-declarator ')'
969
/// [C++0x]   ...
970
///
971
///         ptr-operator:
972
///           '*' cv-qualifier-seq[opt]
973
///           '&'
974
/// [C++0x]   '&&'                                                        [TODO]
975
///           '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
976
///
977
///         cv-qualifier-seq:
978
///           cv-qualifier cv-qualifier-seq[opt]
979
///
980
///         cv-qualifier:
981
///           'const'
982
///           'volatile'
983
///
984
///         declarator-id:
985
///           '...'[opt] id-expression
986
///
987
///         id-expression:
988
///           unqualified-id
989
///           qualified-id                                                [TODO]
990
///
991
///         unqualified-id:
992
///           identifier
993
///           operator-function-id
994
///           conversion-function-id
995
///           literal-operator-id
996
///           '~' class-name                                              [TODO]
997
///           '~' decltype-specifier                                      [TODO]
998
///           template-id                                                 [TODO]
999
///
1000
Parser::TPResult Parser::TryParseDeclarator(bool mayBeAbstract,
1001
                                            bool mayHaveIdentifier,
1002
125k
                                            bool mayHaveDirectInit) {
1003
  // declarator:
1004
  //   direct-declarator
1005
  //   ptr-operator declarator
1006
125k
  if (TryParsePtrOperatorSeq() == TPResult::Error)
1007
1
    return TPResult::Error;
1008
1009
  // direct-declarator:
1010
  // direct-abstract-declarator:
1011
125k
  if (Tok.is(tok::ellipsis))
1012
18
    ConsumeToken();
1013
1014
125k
  if ((Tok.isOneOf(tok::identifier, tok::kw_operator) ||
1015
112k
       (Tok.is(tok::annot_cxxscope) && 
(2.87k
NextToken().is(tok::identifier)2.87k
||
1016
378
                                        NextToken().is(tok::kw_operator)))) &&
1017
15.4k
      mayHaveIdentifier) {
1018
    // declarator-id
1019
15.3k
    if (Tok.is(tok::annot_cxxscope)) {
1020
2.47k
      CXXScopeSpec SS;
1021
2.47k
      Actions.RestoreNestedNameSpecifierAnnotation(
1022
2.47k
          Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
1023
2.47k
      if (SS.isInvalid())
1024
1
        return TPResult::Error;
1025
2.47k
      ConsumeAnnotationToken();
1026
12.8k
    } else if (Tok.is(tok::identifier)) {
1027
12.8k
      TentativelyDeclaredIdentifiers.push_back(Tok.getIdentifierInfo());
1028
12.8k
    }
1029
15.3k
    if (Tok.is(tok::kw_operator)) {
1030
16
      if (TryParseOperatorId() == TPResult::Error)
1031
0
        return TPResult::Error;
1032
15.3k
    } else
1033
15.3k
      ConsumeToken();
1034
110k
  } else if (Tok.is(tok::l_paren)) {
1035
75.9k
    ConsumeParen();
1036
75.9k
    if (mayBeAbstract &&
1037
63.3k
        (Tok.is(tok::r_paren) ||       // 'int()' is a function.
1038
         // 'int(...)' is a function.
1039
62.2k
         (Tok.is(tok::ellipsis) && 
NextToken().is(tok::r_paren)5
) ||
1040
62.2k
         isDeclarationSpecifier())) {   // 'int(int)' is a function.
1041
      // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1042
      //        exception-specification[opt]
1043
26.9k
      TPResult TPR = TryParseFunctionDeclarator();
1044
26.9k
      if (TPR != TPResult::Ambiguous)
1045
1
        return TPR;
1046
49.0k
    } else {
1047
      // '(' declarator ')'
1048
      // '(' attributes declarator ')'
1049
      // '(' abstract-declarator ')'
1050
49.0k
      if (Tok.isOneOf(tok::kw___attribute, tok::kw___declspec, tok::kw___cdecl,
1051
49.0k
                      tok::kw___stdcall, tok::kw___fastcall, tok::kw___thiscall,
1052
49.0k
                      tok::kw___regcall, tok::kw___vectorcall))
1053
1
        return TPResult::True; // attributes indicate declaration
1054
49.0k
      TPResult TPR = TryParseDeclarator(mayBeAbstract, mayHaveIdentifier);
1055
49.0k
      if (TPR != TPResult::Ambiguous)
1056
4.11k
        return TPR;
1057
44.9k
      if (Tok.isNot(tok::r_paren))
1058
6.09k
        return TPResult::False;
1059
38.8k
      ConsumeParen();
1060
38.8k
    }
1061
34.4k
  } else if (!mayBeAbstract) {
1062
4.73k
    return TPResult::False;
1063
4.73k
  }
1064
1065
110k
  if (mayHaveDirectInit)
1066
53
    return TPResult::Ambiguous;
1067
1068
146k
  
while (110k
1) {
1069
146k
    TPResult TPR(TPResult::Ambiguous);
1070
1071
146k
    if (Tok.is(tok::l_paren)) {
1072
      // Check whether we have a function declarator or a possible ctor-style
1073
      // initializer that follows the declarator. Note that ctor-style
1074
      // initializers are not possible in contexts where abstract declarators
1075
      // are allowed.
1076
33.4k
      if (!mayBeAbstract && 
!isCXXFunctionDeclarator()3.72k
)
1077
2.45k
        break;
1078
1079
      // direct-declarator '(' parameter-declaration-clause ')'
1080
      //        cv-qualifier-seq[opt] exception-specification[opt]
1081
31.0k
      ConsumeParen();
1082
31.0k
      TPR = TryParseFunctionDeclarator();
1083
113k
    } else if (Tok.is(tok::l_square)) {
1084
      // direct-declarator '[' constant-expression[opt] ']'
1085
      // direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
1086
4.89k
      TPR = TryParseBracketDeclarator();
1087
108k
    } else if (Tok.is(tok::kw_requires)) {
1088
      // declarator requires-clause
1089
      // A requires clause indicates a function declaration.
1090
3
      TPR = TPResult::True;
1091
108k
    } else {
1092
108k
      break;
1093
108k
    }
1094
1095
35.9k
    if (TPR != TPResult::Ambiguous)
1096
7
      return TPR;
1097
35.9k
  }
1098
1099
110k
  return TPResult::Ambiguous;
1100
110k
}
1101
1102
6.75M
bool Parser::isTentativelyDeclared(IdentifierInfo *II) {
1103
6.75M
  return std::find(TentativelyDeclaredIdentifiers.begin(),
1104
6.75M
                   TentativelyDeclaredIdentifiers.end(), II)
1105
6.75M
      != TentativelyDeclaredIdentifiers.end();
1106
6.75M
}
1107
1108
namespace {
1109
class TentativeParseCCC final : public CorrectionCandidateCallback {
1110
public:
1111
4.49M
  TentativeParseCCC(const Token &Next) {
1112
4.49M
    WantRemainingKeywords = false;
1113
4.49M
    WantTypeSpecifiers =
1114
4.49M
        Next.isOneOf(tok::l_paren, tok::r_paren, tok::greater, tok::l_brace,
1115
4.49M
                     tok::identifier, tok::comma);
1116
4.49M
  }
1117
1118
180
  bool ValidateCandidate(const TypoCorrection &Candidate) override {
1119
    // Reject any candidate that only resolves to instance members since they
1120
    // aren't viable as standalone identifiers instead of member references.
1121
180
    if (Candidate.isResolved() && !Candidate.isKeyword() &&
1122
157
        llvm::all_of(Candidate,
1123
157
                     [](NamedDecl *ND) { return ND->isCXXInstanceMember(); }))
1124
4
      return false;
1125
1126
176
    return CorrectionCandidateCallback::ValidateCandidate(Candidate);
1127
176
  }
1128
1129
203
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
1130
203
    return std::make_unique<TentativeParseCCC>(*this);
1131
203
  }
1132
};
1133
}
1134
/// isCXXDeclarationSpecifier - Returns TPResult::True if it is a declaration
1135
/// specifier, TPResult::False if it is not, TPResult::Ambiguous if it could
1136
/// be either a decl-specifier or a function-style cast, and TPResult::Error
1137
/// if a parsing error was found and reported.
1138
///
1139
/// If InvalidAsDeclSpec is not null, some cases that would be ill-formed as
1140
/// declaration specifiers but possibly valid as some other kind of construct
1141
/// return TPResult::Ambiguous instead of TPResult::False. When this happens,
1142
/// the intent is to keep trying to disambiguate, on the basis that we might
1143
/// find a better reason to treat this construct as a declaration later on.
1144
/// When this happens and the name could possibly be valid in some other
1145
/// syntactic context, *InvalidAsDeclSpec is set to 'true'. The current cases
1146
/// that trigger this are:
1147
///
1148
///   * When parsing X::Y (with no 'typename') where X is dependent
1149
///   * When parsing X<Y> where X is undeclared
1150
///
1151
///         decl-specifier:
1152
///           storage-class-specifier
1153
///           type-specifier
1154
///           function-specifier
1155
///           'friend'
1156
///           'typedef'
1157
/// [C++11]   'constexpr'
1158
/// [C++20]   'consteval'
1159
/// [GNU]     attributes declaration-specifiers[opt]
1160
///
1161
///         storage-class-specifier:
1162
///           'register'
1163
///           'static'
1164
///           'extern'
1165
///           'mutable'
1166
///           'auto'
1167
/// [GNU]     '__thread'
1168
/// [C++11]   'thread_local'
1169
/// [C11]     '_Thread_local'
1170
///
1171
///         function-specifier:
1172
///           'inline'
1173
///           'virtual'
1174
///           'explicit'
1175
///
1176
///         typedef-name:
1177
///           identifier
1178
///
1179
///         type-specifier:
1180
///           simple-type-specifier
1181
///           class-specifier
1182
///           enum-specifier
1183
///           elaborated-type-specifier
1184
///           typename-specifier
1185
///           cv-qualifier
1186
///
1187
///         simple-type-specifier:
1188
///           '::'[opt] nested-name-specifier[opt] type-name
1189
///           '::'[opt] nested-name-specifier 'template'
1190
///                 simple-template-id                              [TODO]
1191
///           'char'
1192
///           'wchar_t'
1193
///           'bool'
1194
///           'short'
1195
///           'int'
1196
///           'long'
1197
///           'signed'
1198
///           'unsigned'
1199
///           'float'
1200
///           'double'
1201
///           'void'
1202
/// [GNU]     typeof-specifier
1203
/// [GNU]     '_Complex'
1204
/// [C++11]   'auto'
1205
/// [GNU]     '__auto_type'
1206
/// [C++11]   'decltype' ( expression )
1207
/// [C++1y]   'decltype' ( 'auto' )
1208
///
1209
///         type-name:
1210
///           class-name
1211
///           enum-name
1212
///           typedef-name
1213
///
1214
///         elaborated-type-specifier:
1215
///           class-key '::'[opt] nested-name-specifier[opt] identifier
1216
///           class-key '::'[opt] nested-name-specifier[opt] 'template'[opt]
1217
///               simple-template-id
1218
///           'enum' '::'[opt] nested-name-specifier[opt] identifier
1219
///
1220
///         enum-name:
1221
///           identifier
1222
///
1223
///         enum-specifier:
1224
///           'enum' identifier[opt] '{' enumerator-list[opt] '}'
1225
///           'enum' identifier[opt] '{' enumerator-list ',' '}'
1226
///
1227
///         class-specifier:
1228
///           class-head '{' member-specification[opt] '}'
1229
///
1230
///         class-head:
1231
///           class-key identifier[opt] base-clause[opt]
1232
///           class-key nested-name-specifier identifier base-clause[opt]
1233
///           class-key nested-name-specifier[opt] simple-template-id
1234
///               base-clause[opt]
1235
///
1236
///         class-key:
1237
///           'class'
1238
///           'struct'
1239
///           'union'
1240
///
1241
///         cv-qualifier:
1242
///           'const'
1243
///           'volatile'
1244
/// [GNU]     restrict
1245
///
1246
Parser::TPResult
1247
Parser::isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult,
1248
14.9M
                                  bool *InvalidAsDeclSpec) {
1249
14.9M
  auto IsPlaceholderSpecifier = [&] (TemplateIdAnnotation *TemplateId,
1250
39.5k
                                     int Lookahead) {
1251
    // We have a placeholder-constraint (we check for 'auto' or 'decltype' to
1252
    // distinguish 'C<int>;' from 'C<int> auto c = 1;')
1253
39.5k
    return TemplateId->Kind == TNK_Concept_template &&
1254
58
        GetLookAheadToken(Lookahead + 1).isOneOf(tok::kw_auto, tok::kw_decltype,
1255
            // If we have an identifier here, the user probably forgot the
1256
            // 'auto' in the placeholder constraint, e.g. 'C<int> x = 2;'
1257
            // This will be diagnosed nicely later, so disambiguate as a
1258
            // declaration.
1259
58
            tok::identifier);
1260
39.5k
  };
1261
14.9M
  switch (Tok.getKind()) {
1262
5.55M
  case tok::identifier: {
1263
    // Check for need to substitute AltiVec __vector keyword
1264
    // for "vector" identifier.
1265
5.55M
    if (TryAltiVecVectorToken())
1266
30.2k
      return TPResult::True;
1267
1268
5.52M
    const Token &Next = NextToken();
1269
    // In 'foo bar', 'foo' is always a type name outside of Objective-C.
1270
5.52M
    if (!getLangOpts().ObjC && 
Next.is(tok::identifier)5.06M
)
1271
325k
      return TPResult::True;
1272
1273
5.19M
    if (Next.isNot(tok::coloncolon) && 
Next.isNot(tok::less)5.01M
) {
1274
      // Determine whether this is a valid expression. If not, we will hit
1275
      // a parse error one way or another. In that case, tell the caller that
1276
      // this is ambiguous. Typo-correct to type and expression keywords and
1277
      // to types and identifiers, in order to try to recover from errors.
1278
4.49M
      TentativeParseCCC CCC(Next);
1279
4.49M
      switch (TryAnnotateName(&CCC)) {
1280
0
      case ANK_Error:
1281
0
        return TPResult::Error;
1282
24
      case ANK_TentativeDecl:
1283
24
        return TPResult::False;
1284
3.62k
      case ANK_TemplateName:
1285
        // In C++17, this could be a type template for class template argument
1286
        // deduction. Try to form a type annotation for it. If we're in a
1287
        // template template argument, we'll undo this when checking the
1288
        // validity of the argument.
1289
3.62k
        if (getLangOpts().CPlusPlus17) {
1290
298
          if (TryAnnotateTypeOrScopeToken())
1291
0
            return TPResult::Error;
1292
298
          if (Tok.isNot(tok::identifier))
1293
298
            break;
1294
3.32k
        }
1295
1296
        // A bare type template-name which can't be a template template
1297
        // argument is an error, and was probably intended to be a type.
1298
3.32k
        return GreaterThanIsOperator ? 
TPResult::True6
:
TPResult::False3.32k
;
1299
792
      case ANK_Unresolved:
1300
683
        return InvalidAsDeclSpec ? TPResult::Ambiguous : 
TPResult::False109
;
1301
4.49M
      case ANK_Success:
1302
4.49M
        break;
1303
4.49M
      }
1304
4.49M
      assert(Tok.isNot(tok::identifier) &&
1305
4.49M
             "TryAnnotateName succeeded without producing an annotation");
1306
695k
    } else {
1307
      // This might possibly be a type with a dependent scope specifier and
1308
      // a missing 'typename' keyword. Don't use TryAnnotateName in this case,
1309
      // since it will annotate as a primary expression, and we want to use the
1310
      // "missing 'typename'" logic.
1311
695k
      if (TryAnnotateTypeOrScopeToken())
1312
29
        return TPResult::Error;
1313
      // If annotation failed, assume it's a non-type.
1314
      // FIXME: If this happens due to an undeclared identifier, treat it as
1315
      // ambiguous.
1316
695k
      if (Tok.is(tok::identifier))
1317
146k
        return TPResult::False;
1318
5.04M
    }
1319
1320
    // We annotated this token as something. Recurse to handle whatever we got.
1321
5.04M
    return isCXXDeclarationSpecifier(BracedCastResult, InvalidAsDeclSpec);
1322
5.04M
  }
1323
1324
152k
  case tok::kw_typename:  // typename T::type
1325
    // Annotate typenames and C++ scope specifiers.  If we get one, just
1326
    // recurse to handle whatever we get.
1327
152k
    if (TryAnnotateTypeOrScopeToken())
1328
10
      return TPResult::Error;
1329
152k
    return isCXXDeclarationSpecifier(BracedCastResult, InvalidAsDeclSpec);
1330
1331
14.9k
  case tok::coloncolon: {    // ::foo::bar
1332
14.9k
    const Token &Next = NextToken();
1333
14.9k
    if (Next.isOneOf(tok::kw_new,       // ::new
1334
14.9k
                     tok::kw_delete))   // ::delete
1335
14.5k
      return TPResult::False;
1336
378
    LLVM_FALLTHROUGH;
1337
378
  }
1338
7.66k
  case tok::kw___super:
1339
7.66k
  case tok::kw_decltype:
1340
    // Annotate typenames and C++ scope specifiers.  If we get one, just
1341
    // recurse to handle whatever we get.
1342
7.66k
    if (TryAnnotateTypeOrScopeToken())
1343
2
      return TPResult::Error;
1344
7.65k
    return isCXXDeclarationSpecifier(BracedCastResult, InvalidAsDeclSpec);
1345
1346
    // decl-specifier:
1347
    //   storage-class-specifier
1348
    //   type-specifier
1349
    //   function-specifier
1350
    //   'friend'
1351
    //   'typedef'
1352
    //   'constexpr'
1353
499k
  case tok::kw_friend:
1354
499k
  case tok::kw_typedef:
1355
499k
  case tok::kw_constexpr:
1356
499k
  case tok::kw_consteval:
1357
499k
  case tok::kw_constinit:
1358
    // storage-class-specifier
1359
499k
  case tok::kw_register:
1360
499k
  case tok::kw_static:
1361
499k
  case tok::kw_extern:
1362
499k
  case tok::kw_mutable:
1363
499k
  case tok::kw_auto:
1364
499k
  case tok::kw___thread:
1365
499k
  case tok::kw_thread_local:
1366
499k
  case tok::kw__Thread_local:
1367
    // function-specifier
1368
499k
  case tok::kw_inline:
1369
499k
  case tok::kw_virtual:
1370
499k
  case tok::kw_explicit:
1371
1372
    // Modules
1373
499k
  case tok::kw___module_private__:
1374
1375
    // Debugger support
1376
499k
  case tok::kw___unknown_anytype:
1377
1378
    // type-specifier:
1379
    //   simple-type-specifier
1380
    //   class-specifier
1381
    //   enum-specifier
1382
    //   elaborated-type-specifier
1383
    //   typename-specifier
1384
    //   cv-qualifier
1385
1386
    // class-specifier
1387
    // elaborated-type-specifier
1388
499k
  case tok::kw_class:
1389
499k
  case tok::kw_struct:
1390
499k
  case tok::kw_union:
1391
499k
  case tok::kw___interface:
1392
    // enum-specifier
1393
499k
  case tok::kw_enum:
1394
    // cv-qualifier
1395
499k
  case tok::kw_const:
1396
499k
  case tok::kw_volatile:
1397
499k
    return TPResult::True;
1398
1399
    // OpenCL address space qualifiers
1400
8
  case tok::kw_private:
1401
8
    if (!getLangOpts().OpenCL)
1402
1
      return TPResult::False;
1403
7
    LLVM_FALLTHROUGH;
1404
2.47k
  case tok::kw___private:
1405
2.47k
  case tok::kw___local:
1406
2.47k
  case tok::kw___global:
1407
2.47k
  case tok::kw___constant:
1408
2.47k
  case tok::kw___generic:
1409
    // OpenCL access qualifiers
1410
2.47k
  case tok::kw___read_only:
1411
2.47k
  case tok::kw___write_only:
1412
2.47k
  case tok::kw___read_write:
1413
    // OpenCL pipe
1414
2.47k
  case tok::kw_pipe:
1415
1416
    // GNU
1417
2.47k
  case tok::kw_restrict:
1418
2.47k
  case tok::kw__Complex:
1419
2.47k
  case tok::kw___attribute:
1420
2.47k
  case tok::kw___auto_type:
1421
2.47k
    return TPResult::True;
1422
1423
    // Microsoft
1424
433
  case tok::kw___declspec:
1425
433
  case tok::kw___cdecl:
1426
433
  case tok::kw___stdcall:
1427
433
  case tok::kw___fastcall:
1428
433
  case tok::kw___thiscall:
1429
433
  case tok::kw___regcall:
1430
433
  case tok::kw___vectorcall:
1431
433
  case tok::kw___w64:
1432
433
  case tok::kw___sptr:
1433
433
  case tok::kw___uptr:
1434
433
  case tok::kw___ptr64:
1435
433
  case tok::kw___ptr32:
1436
433
  case tok::kw___forceinline:
1437
433
  case tok::kw___unaligned:
1438
433
  case tok::kw__Nonnull:
1439
433
  case tok::kw__Nullable:
1440
433
  case tok::kw__Null_unspecified:
1441
433
  case tok::kw___kindof:
1442
433
    return TPResult::True;
1443
1444
    // Borland
1445
4
  case tok::kw___pascal:
1446
4
    return TPResult::True;
1447
1448
    // AltiVec
1449
30
  case tok::kw___vector:
1450
30
    return TPResult::True;
1451
1452
21.5k
  case tok::annot_template_id: {
1453
21.5k
    TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1454
    // If lookup for the template-name found nothing, don't assume we have a
1455
    // definitive disambiguation result yet.
1456
21.5k
    if ((TemplateId->hasInvalidName() ||
1457
21.5k
         TemplateId->Kind == TNK_Undeclared_template) &&
1458
37
        InvalidAsDeclSpec) {
1459
      // 'template-id(' can be a valid expression but not a valid decl spec if
1460
      // the template-name is not declared, but we don't consider this to be a
1461
      // definitive disambiguation. In any other context, it's an error either
1462
      // way.
1463
36
      *InvalidAsDeclSpec = NextToken().is(tok::l_paren);
1464
36
      return TPResult::Ambiguous;
1465
36
    }
1466
21.5k
    if (TemplateId->hasInvalidName())
1467
0
      return TPResult::Error;
1468
21.5k
    if (IsPlaceholderSpecifier(TemplateId, /*Lookahead=*/0))
1469
45
      return TPResult::True;
1470
21.4k
    if (TemplateId->Kind != TNK_Type_template)
1471
21.4k
      return TPResult::False;
1472
3
    CXXScopeSpec SS;
1473
3
    AnnotateTemplateIdTokenAsType(SS);
1474
3
    assert(Tok.is(tok::annot_typename));
1475
3
    goto case_typename;
1476
3
  }
1477
1478
326k
  case tok::annot_cxxscope: // foo::bar or ::foo::bar, but already parsed
1479
    // We've already annotated a scope; try to annotate a type.
1480
326k
    if (TryAnnotateTypeOrScopeToken())
1481
0
      return TPResult::Error;
1482
326k
    if (!Tok.is(tok::annot_typename)) {
1483
326k
      if (Tok.is(tok::annot_cxxscope) &&
1484
326k
          NextToken().is(tok::annot_template_id)) {
1485
18.0k
        TemplateIdAnnotation *TemplateId =
1486
18.0k
            takeTemplateIdAnnotation(NextToken());
1487
18.0k
        if (TemplateId->hasInvalidName()) {
1488
1
          if (InvalidAsDeclSpec) {
1489
1
            *InvalidAsDeclSpec = NextToken().is(tok::l_paren);
1490
1
            return TPResult::Ambiguous;
1491
1
          }
1492
0
          return TPResult::Error;
1493
0
        }
1494
18.0k
        if (IsPlaceholderSpecifier(TemplateId, /*Lookahead=*/1))
1495
4
          return TPResult::True;
1496
326k
      }
1497
      // If the next token is an identifier or a type qualifier, then this
1498
      // can't possibly be a valid expression either.
1499
326k
      if (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier)) {
1500
295k
        CXXScopeSpec SS;
1501
295k
        Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
1502
295k
                                                     Tok.getAnnotationRange(),
1503
295k
                                                     SS);
1504
295k
        if (SS.getScopeRep() && 
SS.getScopeRep()->isDependent()295k
) {
1505
231k
          RevertingTentativeParsingAction PA(*this);
1506
231k
          ConsumeAnnotationToken();
1507
231k
          ConsumeToken();
1508
231k
          bool isIdentifier = Tok.is(tok::identifier);
1509
231k
          TPResult TPR = TPResult::False;
1510
231k
          if (!isIdentifier)
1511
231k
            TPR = isCXXDeclarationSpecifier(BracedCastResult,
1512
231k
                                            InvalidAsDeclSpec);
1513
1514
231k
          if (isIdentifier ||
1515
231k
              TPR == TPResult::True || 
TPR == TPResult::Error231k
)
1516
21
            return TPResult::Error;
1517
1518
231k
          if (InvalidAsDeclSpec) {
1519
            // We can't tell whether this is a missing 'typename' or a valid
1520
            // expression.
1521
39.7k
            *InvalidAsDeclSpec = true;
1522
39.7k
            return TPResult::Ambiguous;
1523
191k
          } else {
1524
            // In MS mode, if InvalidAsDeclSpec is not provided, and the tokens
1525
            // are or the form *) or &) *> or &> &&>, this can't be an expression.
1526
            // The typename must be missing.
1527
191k
            if (getLangOpts().MSVCCompat) {
1528
41
              if (((Tok.is(tok::amp) || 
Tok.is(tok::star)37
) &&
1529
6
                   (NextToken().is(tok::r_paren) ||
1530
5
                    NextToken().is(tok::greater))) ||
1531
39
                  (Tok.is(tok::ampamp) && 
NextToken().is(tok::greater)0
))
1532
2
                return TPResult::True;
1533
63.4k
            }
1534
191k
          }
1535
63.4k
        } else {
1536
          // Try to resolve the name. If it doesn't exist, assume it was
1537
          // intended to name a type and keep disambiguating.
1538
63.4k
          switch (TryAnnotateName()) {
1539
4
          case ANK_Error:
1540
4
            return TPResult::Error;
1541
0
          case ANK_TentativeDecl:
1542
0
            return TPResult::False;
1543
47
          case ANK_TemplateName:
1544
            // In C++17, this could be a type template for class template
1545
            // argument deduction.
1546
47
            if (getLangOpts().CPlusPlus17) {
1547
0
              if (TryAnnotateTypeOrScopeToken())
1548
0
                return TPResult::Error;
1549
0
              if (Tok.isNot(tok::identifier))
1550
0
                break;
1551
47
            }
1552
1553
            // A bare type template-name which can't be a template template
1554
            // argument is an error, and was probably intended to be a type.
1555
            // In C++17, this could be class template argument deduction.
1556
47
            return (getLangOpts().CPlusPlus17 || GreaterThanIsOperator)
1557
9
                       ? TPResult::True
1558
38
                       : TPResult::False;
1559
147
          case ANK_Unresolved:
1560
134
            return InvalidAsDeclSpec ? TPResult::Ambiguous : 
TPResult::False13
;
1561
63.2k
          case ANK_Success:
1562
63.2k
            break;
1563
63.2k
          }
1564
1565
          // Annotated it, check again.
1566
63.2k
          assert(Tok.isNot(tok::annot_cxxscope) ||
1567
63.2k
                 NextToken().isNot(tok::identifier));
1568
63.2k
          return isCXXDeclarationSpecifier(BracedCastResult, InvalidAsDeclSpec);
1569
63.2k
        }
1570
295k
      }
1571
223k
      return TPResult::False;
1572
223k
    }
1573
    // If that succeeded, fallthrough into the generic simple-type-id case.
1574
14
    LLVM_FALLTHROUGH;
1575
1576
    // The ambiguity resides in a simple-type-specifier/typename-specifier
1577
    // followed by a '('. The '(' could either be the start of:
1578
    //
1579
    //   direct-declarator:
1580
    //     '(' declarator ')'
1581
    //
1582
    //   direct-abstract-declarator:
1583
    //     '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1584
    //              exception-specification[opt]
1585
    //     '(' abstract-declarator ')'
1586
    //
1587
    // or part of a function-style cast expression:
1588
    //
1589
    //     simple-type-specifier '(' expression-list[opt] ')'
1590
    //
1591
1592
    // simple-type-specifier:
1593
1594
4.37M
  case tok::annot_typename:
1595
4.37M
  case_typename:
1596
    // In Objective-C, we might have a protocol-qualified type.
1597
4.37M
    if (getLangOpts().ObjC && 
NextToken().is(tok::less)372k
) {
1598
      // Tentatively parse the protocol qualifiers.
1599
0
      RevertingTentativeParsingAction PA(*this);
1600
0
      ConsumeAnyToken(); // The type token
1601
1602
0
      TPResult TPR = TryParseProtocolQualifiers();
1603
0
      bool isFollowedByParen = Tok.is(tok::l_paren);
1604
0
      bool isFollowedByBrace = Tok.is(tok::l_brace);
1605
1606
0
      if (TPR == TPResult::Error)
1607
0
        return TPResult::Error;
1608
1609
0
      if (isFollowedByParen)
1610
0
        return TPResult::Ambiguous;
1611
1612
0
      if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
1613
0
        return BracedCastResult;
1614
1615
0
      return TPResult::True;
1616
0
    }
1617
4.37M
    LLVM_FALLTHROUGH;
1618
1619
5.32M
  case tok::kw_char:
1620
5.32M
  case tok::kw_wchar_t:
1621
5.32M
  case tok::kw_char8_t:
1622
5.32M
  case tok::kw_char16_t:
1623
5.32M
  case tok::kw_char32_t:
1624
5.32M
  case tok::kw_bool:
1625
5.32M
  case tok::kw_short:
1626
5.32M
  case tok::kw_int:
1627
5.32M
  case tok::kw_long:
1628
5.32M
  case tok::kw___int64:
1629
5.32M
  case tok::kw___int128:
1630
5.32M
  case tok::kw_signed:
1631
5.32M
  case tok::kw_unsigned:
1632
5.32M
  case tok::kw_half:
1633
5.32M
  case tok::kw_float:
1634
5.32M
  case tok::kw_double:
1635
5.32M
  case tok::kw___bf16:
1636
5.32M
  case tok::kw__Float16:
1637
5.32M
  case tok::kw___float128:
1638
5.32M
  case tok::kw_void:
1639
5.32M
  case tok::annot_decltype:
1640
63.9M
#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1641
63.9M
#include 
"clang/Basic/OpenCLImageTypes.def"5.32M
1642
5.32M
    if (NextToken().is(tok::l_paren))
1643
77.3k
      return TPResult::Ambiguous;
1644
1645
    // This is a function-style cast in all cases we disambiguate other than
1646
    // one:
1647
    //   struct S {
1648
    //     enum E : int { a = 4 }; // enum
1649
    //     enum E : int { 4 };     // bit-field
1650
    //   };
1651
5.24M
    if (getLangOpts().CPlusPlus11 && 
NextToken().is(tok::l_brace)5.19M
)
1652
806
      return BracedCastResult;
1653
1654
5.24M
    if (isStartOfObjCClassMessageMissingOpenBracket())
1655
3
      return TPResult::False;
1656
1657
5.24M
    return TPResult::True;
1658
1659
  // GNU typeof support.
1660
696
  case tok::kw_typeof: {
1661
696
    if (NextToken().isNot(tok::l_paren))
1662
3
      return TPResult::True;
1663
1664
693
    RevertingTentativeParsingAction PA(*this);
1665
1666
693
    TPResult TPR = TryParseTypeofSpecifier();
1667
693
    bool isFollowedByParen = Tok.is(tok::l_paren);
1668
693
    bool isFollowedByBrace = Tok.is(tok::l_brace);
1669
1670
693
    if (TPR == TPResult::Error)
1671
0
      return TPResult::Error;
1672
1673
693
    if (isFollowedByParen)
1674
14
      return TPResult::Ambiguous;
1675
1676
679
    if (getLangOpts().CPlusPlus11 && 
isFollowedByBrace643
)
1677
0
      return BracedCastResult;
1678
1679
679
    return TPResult::True;
1680
679
  }
1681
1682
  // C++0x type traits support
1683
7
  case tok::kw___underlying_type:
1684
7
    return TPResult::True;
1685
1686
  // C11 _Atomic
1687
33
  case tok::kw__Atomic:
1688
33
    return TPResult::True;
1689
1690
112
  case tok::kw__ExtInt: {
1691
112
    if (NextToken().isNot(tok::l_paren))
1692
0
      return TPResult::Error;
1693
112
    RevertingTentativeParsingAction PA(*this);
1694
112
    ConsumeToken();
1695
112
    ConsumeParen();
1696
1697
112
    if (!SkipUntil(tok::r_paren, StopAtSemi))
1698
0
      return TPResult::Error;
1699
1700
112
    if (Tok.is(tok::l_paren))
1701
0
      return TPResult::Ambiguous;
1702
1703
112
    if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))
1704
0
      return BracedCastResult;
1705
1706
112
    return TPResult::True;
1707
112
  }
1708
3.06M
  default:
1709
3.06M
    return TPResult::False;
1710
14.9M
  }
1711
14.9M
}
1712
1713
10.0k
bool Parser::isCXXDeclarationSpecifierAType() {
1714
10.0k
  switch (Tok.getKind()) {
1715
    // typename-specifier
1716
6.12k
  case tok::annot_decltype:
1717
6.12k
  case tok::annot_template_id:
1718
6.12k
  case tok::annot_typename:
1719
6.12k
  case tok::kw_typeof:
1720
6.12k
  case tok::kw___underlying_type:
1721
6.12k
    return true;
1722
1723
    // elaborated-type-specifier
1724
5
  case tok::kw_class:
1725
5
  case tok::kw_struct:
1726
5
  case tok::kw_union:
1727
5
  case tok::kw___interface:
1728
5
  case tok::kw_enum:
1729
5
    return true;
1730
1731
    // simple-type-specifier
1732
3.48k
  case tok::kw_char:
1733
3.48k
  case tok::kw_wchar_t:
1734
3.48k
  case tok::kw_char8_t:
1735
3.48k
  case tok::kw_char16_t:
1736
3.48k
  case tok::kw_char32_t:
1737
3.48k
  case tok::kw_bool:
1738
3.48k
  case tok::kw_short:
1739
3.48k
  case tok::kw_int:
1740
3.48k
  case tok::kw__ExtInt:
1741
3.48k
  case tok::kw_long:
1742
3.48k
  case tok::kw___int64:
1743
3.48k
  case tok::kw___int128:
1744
3.48k
  case tok::kw_signed:
1745
3.48k
  case tok::kw_unsigned:
1746
3.48k
  case tok::kw_half:
1747
3.48k
  case tok::kw_float:
1748
3.48k
  case tok::kw_double:
1749
3.48k
  case tok::kw___bf16:
1750
3.48k
  case tok::kw__Float16:
1751
3.48k
  case tok::kw___float128:
1752
3.48k
  case tok::kw_void:
1753
3.48k
  case tok::kw___unknown_anytype:
1754
3.48k
  case tok::kw___auto_type:
1755
41.8k
#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1756
3.48k
#include "clang/Basic/OpenCLImageTypes.def"
1757
3.48k
    return true;
1758
1759
0
  case tok::kw_auto:
1760
0
    return getLangOpts().CPlusPlus11;
1761
1762
0
  case tok::kw__Atomic:
1763
    // "_Atomic foo"
1764
0
    return NextToken().is(tok::l_paren);
1765
1766
432
  default:
1767
432
    return false;
1768
10.0k
  }
1769
10.0k
}
1770
1771
/// [GNU] typeof-specifier:
1772
///         'typeof' '(' expressions ')'
1773
///         'typeof' '(' type-name ')'
1774
///
1775
693
Parser::TPResult Parser::TryParseTypeofSpecifier() {
1776
693
  assert(Tok.is(tok::kw_typeof) && "Expected 'typeof'!");
1777
693
  ConsumeToken();
1778
1779
693
  assert(Tok.is(tok::l_paren) && "Expected '('");
1780
  // Parse through the parens after 'typeof'.
1781
693
  ConsumeParen();
1782
693
  if (!SkipUntil(tok::r_paren, StopAtSemi))
1783
0
    return TPResult::Error;
1784
1785
693
  return TPResult::Ambiguous;
1786
693
}
1787
1788
/// [ObjC] protocol-qualifiers:
1789
////         '<' identifier-list '>'
1790
0
Parser::TPResult Parser::TryParseProtocolQualifiers() {
1791
0
  assert(Tok.is(tok::less) && "Expected '<' for qualifier list");
1792
0
  ConsumeToken();
1793
0
  do {
1794
0
    if (Tok.isNot(tok::identifier))
1795
0
      return TPResult::Error;
1796
0
    ConsumeToken();
1797
1798
0
    if (Tok.is(tok::comma)) {
1799
0
      ConsumeToken();
1800
0
      continue;
1801
0
    }
1802
1803
0
    if (Tok.is(tok::greater)) {
1804
0
      ConsumeToken();
1805
0
      return TPResult::Ambiguous;
1806
0
    }
1807
0
  } while (false);
1808
1809
0
  return TPResult::Error;
1810
0
}
1811
1812
/// isCXXFunctionDeclarator - Disambiguates between a function declarator or
1813
/// a constructor-style initializer, when parsing declaration statements.
1814
/// Returns true for function declarator and false for constructor-style
1815
/// initializer.
1816
/// If during the disambiguation process a parsing error is encountered,
1817
/// the function returns true to let the declaration parsing code handle it.
1818
///
1819
/// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1820
///         exception-specification[opt]
1821
///
1822
1.51M
bool Parser::isCXXFunctionDeclarator(bool *IsAmbiguous) {
1823
1824
  // C++ 8.2p1:
1825
  // The ambiguity arising from the similarity between a function-style cast and
1826
  // a declaration mentioned in 6.8 can also occur in the context of a
1827
  // declaration. In that context, the choice is between a function declaration
1828
  // with a redundant set of parentheses around a parameter name and an object
1829
  // declaration with a function-style cast as the initializer. Just as for the
1830
  // ambiguities mentioned in 6.8, the resolution is to consider any construct
1831
  // that could possibly be a declaration a declaration.
1832
1833
1.51M
  RevertingTentativeParsingAction PA(*this);
1834
1835
1.51M
  ConsumeParen();
1836
1.51M
  bool InvalidAsDeclaration = false;
1837
1.51M
  TPResult TPR = TryParseParameterDeclarationClause(&InvalidAsDeclaration);
1838
1.51M
  if (TPR == TPResult::Ambiguous) {
1839
99.8k
    if (Tok.isNot(tok::r_paren))
1840
5
      TPR = TPResult::False;
1841
99.8k
    else {
1842
99.8k
      const Token &Next = NextToken();
1843
99.8k
      if (Next.isOneOf(tok::amp, tok::ampamp, tok::kw_const, tok::kw_volatile,
1844
99.8k
                       tok::kw_throw, tok::kw_noexcept, tok::l_square,
1845
99.8k
                       tok::l_brace, tok::kw_try, tok::equal, tok::arrow) ||
1846
15.5k
          isCXX11VirtSpecifier(Next))
1847
        // The next token cannot appear after a constructor-style initializer,
1848
        // and can appear next in a function definition. This must be a function
1849
        // declarator.
1850
84.2k
        TPR = TPResult::True;
1851
15.5k
      else if (InvalidAsDeclaration)
1852
        // Use the absence of 'typename' as a tie-breaker.
1853
66
        TPR = TPResult::False;
1854
99.8k
    }
1855
99.8k
  }
1856
1857
1.51M
  if (IsAmbiguous && 
TPR == TPResult::Ambiguous1.50M
)
1858
15.4k
    *IsAmbiguous = true;
1859
1860
  // In case of an error, let the declaration parsing code handle it.
1861
1.51M
  return TPR != TPResult::False;
1862
1.51M
}
1863
1864
/// parameter-declaration-clause:
1865
///   parameter-declaration-list[opt] '...'[opt]
1866
///   parameter-declaration-list ',' '...'
1867
///
1868
/// parameter-declaration-list:
1869
///   parameter-declaration
1870
///   parameter-declaration-list ',' parameter-declaration
1871
///
1872
/// parameter-declaration:
1873
///   attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
1874
///   attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
1875
///     '=' assignment-expression
1876
///   attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
1877
///     attributes[opt]
1878
///   attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
1879
///     attributes[opt] '=' assignment-expression
1880
///
1881
Parser::TPResult
1882
Parser::TryParseParameterDeclarationClause(bool *InvalidAsDeclaration,
1883
1.57M
                                           bool VersusTemplateArgument) {
1884
1885
1.57M
  if (Tok.is(tok::r_paren))
1886
98.3k
    return TPResult::Ambiguous;
1887
1888
  //   parameter-declaration-list[opt] '...'[opt]
1889
  //   parameter-declaration-list ',' '...'
1890
  //
1891
  // parameter-declaration-list:
1892
  //   parameter-declaration
1893
  //   parameter-declaration-list ',' parameter-declaration
1894
  //
1895
1.47M
  
while (1.47M
1) {
1896
    // '...'[opt]
1897
1.47M
    if (Tok.is(tok::ellipsis)) {
1898
1.23k
      ConsumeToken();
1899
1.23k
      if (Tok.is(tok::r_paren))
1900
1.23k
        return TPResult::True; // '...)' is a sign of a function declarator.
1901
0
      else
1902
0
        return TPResult::False;
1903
1.47M
    }
1904
1905
    // An attribute-specifier-seq here is a sign of a function declarator.
1906
1.47M
    if (isCXX11AttributeSpecifier(/*Disambiguate*/false,
1907
1.47M
                                  /*OuterMightBeMessageSend*/true))
1908
9
      return TPResult::True;
1909
1910
1.47M
    ParsedAttributes attrs(AttrFactory);
1911
1.47M
    MaybeParseMicrosoftAttributes(attrs);
1912
1913
    // decl-specifier-seq
1914
    // A parameter-declaration's initializer must be preceded by an '=', so
1915
    // decl-specifier-seq '{' is not a parameter in C++11.
1916
1.47M
    TPResult TPR = isCXXDeclarationSpecifier(TPResult::False,
1917
1.47M
                                             InvalidAsDeclaration);
1918
    // A declaration-specifier (not followed by '(' or '{') means this can't be
1919
    // an expression, but it could still be a template argument.
1920
1.47M
    if (TPR != TPResult::Ambiguous &&
1921
1.46M
        !(VersusTemplateArgument && 
TPR == TPResult::True38
))
1922
1.46M
      return TPR;
1923
1924
10.0k
    bool SeenType = false;
1925
10.0k
    do {
1926
10.0k
      SeenType |= isCXXDeclarationSpecifierAType();
1927
10.0k
      if (TryConsumeDeclarationSpecifier() == TPResult::Error)
1928
1
        return TPResult::Error;
1929
1930
      // If we see a parameter name, this can't be a template argument.
1931
10.0k
      if (SeenType && 
Tok.is(tok::identifier)9.61k
)
1932
11
        return TPResult::True;
1933
1934
10.0k
      TPR = isCXXDeclarationSpecifier(TPResult::False,
1935
10.0k
                                      InvalidAsDeclaration);
1936
10.0k
      if (TPR == TPResult::Error)
1937
0
        return TPR;
1938
1939
      // Two declaration-specifiers means this can't be an expression.
1940
10.0k
      if (TPR == TPResult::True && 
!VersusTemplateArgument1
)
1941
1
        return TPR;
1942
10.0k
    } while (TPR != TPResult::False);
1943
1944
    // declarator
1945
    // abstract-declarator[opt]
1946
10.0k
    TPR = TryParseDeclarator(true/*mayBeAbstract*/);
1947
10.0k
    if (TPR != TPResult::Ambiguous)
1948
348
      return TPR;
1949
1950
    // [GNU] attributes[opt]
1951
9.68k
    if (Tok.is(tok::kw___attribute))
1952
1
      return TPResult::True;
1953
1954
    // If we're disambiguating a template argument in a default argument in
1955
    // a class definition versus a parameter declaration, an '=' here
1956
    // disambiguates the parse one way or the other.
1957
    // If this is a parameter, it must have a default argument because
1958
    //   (a) the previous parameter did, and
1959
    //   (b) this must be the first declaration of the function, so we can't
1960
    //       inherit any default arguments from elsewhere.
1961
    // FIXME: If we reach a ')' without consuming any '>'s, then this must
1962
    // also be a function parameter (that's missing its default argument).
1963
9.68k
    if (VersusTemplateArgument)
1964
30
      return Tok.is(tok::equal) ? 
TPResult::True3
:
TPResult::False27
;
1965
1966
9.65k
    if (Tok.is(tok::equal)) {
1967
      // '=' assignment-expression
1968
      // Parse through assignment-expression.
1969
9
      if (!SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch))
1970
0
        return TPResult::Error;
1971
9.65k
    }
1972
1973
9.65k
    if (Tok.is(tok::ellipsis)) {
1974
2
      ConsumeToken();
1975
2
      if (Tok.is(tok::r_paren))
1976
1
        return TPResult::True; // '...)' is a sign of a function declarator.
1977
1
      else
1978
1
        return TPResult::False;
1979
9.65k
    }
1980
1981
9.65k
    if (!TryConsumeToken(tok::comma))
1982
8.12k
      break;
1983
9.65k
  }
1984
1985
8.12k
  return TPResult::Ambiguous;
1986
1.47M
}
1987
1988
/// TryParseFunctionDeclarator - We parsed a '(' and we want to try to continue
1989
/// parsing as a function declarator.
1990
/// If TryParseFunctionDeclarator fully parsed the function declarator, it will
1991
/// return TPResult::Ambiguous, otherwise it will return either False() or
1992
/// Error().
1993
///
1994
/// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1995
///         exception-specification[opt]
1996
///
1997
/// exception-specification:
1998
///   'throw' '(' type-id-list[opt] ')'
1999
///
2000
57.9k
Parser::TPResult Parser::TryParseFunctionDeclarator() {
2001
  // The '(' is already parsed.
2002
2003
57.9k
  TPResult TPR = TryParseParameterDeclarationClause();
2004
57.9k
  if (TPR == TPResult::Ambiguous && 
Tok.isNot(tok::r_paren)6.70k
)
2005
0
    TPR = TPResult::False;
2006
2007
57.9k
  if (TPR == TPResult::False || 
TPR == TPResult::Error57.9k
)
2008
1
    return TPR;
2009
2010
  // Parse through the parens.
2011
57.9k
  if (!SkipUntil(tok::r_paren, StopAtSemi))
2012
1
    return TPResult::Error;
2013
2014
  // cv-qualifier-seq
2015
74.8k
  
while (57.9k
Tok.isOneOf(tok::kw_const, tok::kw_volatile, tok::kw___unaligned,
2016
74.8k
                     tok::kw_restrict))
2017
16.9k
    ConsumeToken();
2018
2019
  // ref-qualifier[opt]
2020
57.9k
  if (Tok.isOneOf(tok::amp, tok::ampamp))
2021
7.16k
    ConsumeToken();
2022
2023
  // exception-specification
2024
57.9k
  if (Tok.is(tok::kw_throw)) {
2025
75
    ConsumeToken();
2026
75
    if (Tok.isNot(tok::l_paren))
2027
0
      return TPResult::Error;
2028
2029
    // Parse through the parens after 'throw'.
2030
75
    ConsumeParen();
2031
75
    if (!SkipUntil(tok::r_paren, StopAtSemi))
2032
0
      return TPResult::Error;
2033
57.9k
  }
2034
57.9k
  if (Tok.is(tok::kw_noexcept)) {
2035
119
    ConsumeToken();
2036
    // Possibly an expression as well.
2037
119
    if (Tok.is(tok::l_paren)) {
2038
      // Find the matching rparen.
2039
27
      ConsumeParen();
2040
27
      if (!SkipUntil(tok::r_paren, StopAtSemi))
2041
0
        return TPResult::Error;
2042
57.9k
    }
2043
119
  }
2044
2045
57.9k
  return TPResult::Ambiguous;
2046
57.9k
}
2047
2048
/// '[' constant-expression[opt] ']'
2049
///
2050
4.89k
Parser::TPResult Parser::TryParseBracketDeclarator() {
2051
4.89k
  ConsumeBracket();
2052
2053
  // A constant-expression cannot begin with a '{', but the
2054
  // expr-or-braced-init-list of a postfix-expression can.
2055
4.89k
  if (Tok.is(tok::l_brace))
2056
2
    return TPResult::False;
2057
2058
4.89k
  if (!SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch))
2059
0
    return TPResult::Error;
2060
2061
  // If we hit a comma before the ']', this is not a constant-expression,
2062
  // but might still be the expr-or-braced-init-list of a postfix-expression.
2063
4.89k
  if (Tok.isNot(tok::r_square))
2064
1
    return TPResult::False;
2065
2066
4.89k
  ConsumeBracket();
2067
4.89k
  return TPResult::Ambiguous;
2068
4.89k
}
2069
2070
/// Determine whether we might be looking at the '<' template-argument-list '>'
2071
/// of a template-id or simple-template-id, rather than a less-than comparison.
2072
/// This will often fail and produce an ambiguity, but should never be wrong
2073
/// if it returns True or False.
2074
4.81k
Parser::TPResult Parser::isTemplateArgumentList(unsigned TokensToSkip) {
2075
4.81k
  if (!TokensToSkip) {
2076
2.25k
    if (Tok.isNot(tok::less))
2077
0
      return TPResult::False;
2078
2.25k
    if (NextToken().is(tok::greater))
2079
0
      return TPResult::True;
2080
4.81k
  }
2081
2082
4.81k
  RevertingTentativeParsingAction PA(*this);
2083
2084
7.38k
  while (TokensToSkip) {
2085
2.56k
    ConsumeAnyToken();
2086
2.56k
    --TokensToSkip;
2087
2.56k
  }
2088
2089
4.81k
  if (!TryConsumeToken(tok::less))
2090
0
    return TPResult::False;
2091
2092
  // We can't do much to tell an expression apart from a template-argument,
2093
  // but one good distinguishing factor is that a "decl-specifier" not
2094
  // followed by '(' or '{' can't appear in an expression.
2095
4.81k
  bool InvalidAsTemplateArgumentList = false;
2096
4.81k
  if (isCXXDeclarationSpecifier(TPResult::False,
2097
4.81k
                                       &InvalidAsTemplateArgumentList) ==
2098
4.81k
             TPResult::True)
2099
212
    return TPResult::True;
2100
4.60k
  if (InvalidAsTemplateArgumentList)
2101
14
    return TPResult::False;
2102
2103
  // FIXME: In many contexts, X<thing1, Type> can only be a
2104
  // template-argument-list. But that's not true in general:
2105
  //
2106
  // using b = int;
2107
  // void f() {
2108
  //   int a = A<B, b, c = C>D; // OK, declares b, not a template-id.
2109
  //
2110
  // X<Y<0, int> // ', int>' might be end of X's template argument list
2111
  //
2112
  // We might be able to disambiguate a few more cases if we're careful.
2113
2114
  // A template-argument-list must be terminated by a '>'.
2115
4.59k
  if (SkipUntil({tok::greater, tok::greatergreater, tok::greatergreatergreater},
2116
4.59k
                StopAtSemi | StopBeforeMatch))
2117
105
    return TPResult::Ambiguous;
2118
4.48k
  return TPResult::False;
2119
4.48k
}
2120
2121
/// Determine whether we might be looking at the '(' of a C++20 explicit(bool)
2122
/// in an earlier language mode.
2123
37
Parser::TPResult Parser::isExplicitBool() {
2124
37
  assert(Tok.is(tok::l_paren) && "expected to be looking at a '(' token");
2125
2126
37
  RevertingTentativeParsingAction PA(*this);
2127
37
  ConsumeParen();
2128
2129
  // We can only have 'explicit' on a constructor, conversion function, or
2130
  // deduction guide. The declarator of a deduction guide cannot be
2131
  // parenthesized, so we know this isn't a deduction guide. So the only
2132
  // thing we need to check for is some number of parens followed by either
2133
  // the current class name or 'operator'.
2134
39
  while (Tok.is(tok::l_paren))
2135
2
    ConsumeParen();
2136
2137
37
  if (TryAnnotateOptionalCXXScopeToken())
2138
0
    return TPResult::Error;
2139
2140
  // Class-scope constructor and conversion function names can't really be
2141
  // qualified, but we get better diagnostics if we assume they can be.
2142
37
  CXXScopeSpec SS;
2143
37
  if (Tok.is(tok::annot_cxxscope)) {
2144
6
    Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
2145
6
                                                 Tok.getAnnotationRange(),
2146
6
                                                 SS);
2147
6
    ConsumeAnnotationToken();
2148
6
  }
2149
2150
  // 'explicit(operator' might be explicit(bool) or the declaration of a
2151
  // conversion function, but it's probably a conversion function.
2152
37
  if (Tok.is(tok::kw_operator))
2153
3
    return TPResult::Ambiguous;
2154
2155
  // If this can't be a constructor name, it can only be explicit(bool).
2156
34
  if (Tok.isNot(tok::identifier) && 
Tok.isNot(tok::annot_template_id)9
)
2157
9
    return TPResult::True;
2158
25
  if (!Actions.isCurrentClassName(Tok.is(tok::identifier)
2159
25
                                      ? *Tok.getIdentifierInfo()
2160
0
                                      : *takeTemplateIdAnnotation(Tok)->Name,
2161
25
                                  getCurScope(), &SS))
2162
22
    return TPResult::True;
2163
  // Formally, we must have a right-paren after the constructor name to match
2164
  // the grammar for a constructor. But clang permits a parenthesized
2165
  // constructor declarator, so also allow a constructor declarator to follow
2166
  // with no ')' token after the constructor name.
2167
3
  if (!NextToken().is(tok::r_paren) &&
2168
1
      !isConstructorDeclarator(/*Unqualified=*/SS.isEmpty(),
2169
1
                               /*DeductionGuide=*/false))
2170
0
    return TPResult::True;
2171
2172
  // Might be explicit(bool) or a parenthesized constructor name.
2173
3
  return TPResult::Ambiguous;
2174
3
}