Coverage Report

Created: 2021-08-24 07:12

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/include/clang/Parse/Parser.h
Line
Count
Source (jump to first uncovered line)
1
//===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===//
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 defines the Parser interface.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#ifndef LLVM_CLANG_PARSE_PARSER_H
14
#define LLVM_CLANG_PARSE_PARSER_H
15
16
#include "clang/AST/Availability.h"
17
#include "clang/Basic/BitmaskEnum.h"
18
#include "clang/Basic/OpenMPKinds.h"
19
#include "clang/Basic/OperatorPrecedence.h"
20
#include "clang/Basic/Specifiers.h"
21
#include "clang/Lex/CodeCompletionHandler.h"
22
#include "clang/Lex/Preprocessor.h"
23
#include "clang/Sema/DeclSpec.h"
24
#include "clang/Sema/Sema.h"
25
#include "llvm/ADT/SmallVector.h"
26
#include "llvm/Frontend/OpenMP/OMPContext.h"
27
#include "llvm/Support/Compiler.h"
28
#include "llvm/Support/PrettyStackTrace.h"
29
#include "llvm/Support/SaveAndRestore.h"
30
#include <memory>
31
#include <stack>
32
33
namespace clang {
34
  class PragmaHandler;
35
  class Scope;
36
  class BalancedDelimiterTracker;
37
  class CorrectionCandidateCallback;
38
  class DeclGroupRef;
39
  class DiagnosticBuilder;
40
  struct LoopHint;
41
  class Parser;
42
  class ParsingDeclRAIIObject;
43
  class ParsingDeclSpec;
44
  class ParsingDeclarator;
45
  class ParsingFieldDeclarator;
46
  class ColonProtectionRAIIObject;
47
  class InMessageExpressionRAIIObject;
48
  class PoisonSEHIdentifiersRAIIObject;
49
  class OMPClause;
50
  class ObjCTypeParamList;
51
  struct OMPTraitProperty;
52
  struct OMPTraitSelector;
53
  struct OMPTraitSet;
54
  class OMPTraitInfo;
55
56
/// Parser - This implements a parser for the C family of languages.  After
57
/// parsing units of the grammar, productions are invoked to handle whatever has
58
/// been read.
59
///
60
class Parser : public CodeCompletionHandler {
61
  friend class ColonProtectionRAIIObject;
62
  friend class ParsingOpenMPDirectiveRAII;
63
  friend class InMessageExpressionRAIIObject;
64
  friend class PoisonSEHIdentifiersRAIIObject;
65
  friend class ObjCDeclContextSwitch;
66
  friend class ParenBraceBracketBalancer;
67
  friend class BalancedDelimiterTracker;
68
69
  Preprocessor &PP;
70
71
  /// Tok - The current token we are peeking ahead.  All parsing methods assume
72
  /// that this is valid.
73
  Token Tok;
74
75
  // PrevTokLocation - The location of the token we previously
76
  // consumed. This token is used for diagnostics where we expected to
77
  // see a token following another token (e.g., the ';' at the end of
78
  // a statement).
79
  SourceLocation PrevTokLocation;
80
81
  /// Tracks an expected type for the current token when parsing an expression.
82
  /// Used by code completion for ranking.
83
  PreferredTypeBuilder PreferredType;
84
85
  unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0;
86
  unsigned short MisplacedModuleBeginCount = 0;
87
88
  /// Actions - These are the callbacks we invoke as we parse various constructs
89
  /// in the file.
90
  Sema &Actions;
91
92
  DiagnosticsEngine &Diags;
93
94
  /// ScopeCache - Cache scopes to reduce malloc traffic.
95
  enum { ScopeCacheSize = 16 };
96
  unsigned NumCachedScopes;
97
  Scope *ScopeCache[ScopeCacheSize];
98
99
  /// Identifiers used for SEH handling in Borland. These are only
100
  /// allowed in particular circumstances
101
  // __except block
102
  IdentifierInfo *Ident__exception_code,
103
                 *Ident___exception_code,
104
                 *Ident_GetExceptionCode;
105
  // __except filter expression
106
  IdentifierInfo *Ident__exception_info,
107
                 *Ident___exception_info,
108
                 *Ident_GetExceptionInfo;
109
  // __finally
110
  IdentifierInfo *Ident__abnormal_termination,
111
                 *Ident___abnormal_termination,
112
                 *Ident_AbnormalTermination;
113
114
  /// Contextual keywords for Microsoft extensions.
115
  IdentifierInfo *Ident__except;
116
  mutable IdentifierInfo *Ident_sealed;
117
  mutable IdentifierInfo *Ident_abstract;
118
119
  /// Ident_super - IdentifierInfo for "super", to support fast
120
  /// comparison.
121
  IdentifierInfo *Ident_super;
122
  /// Ident_vector, Ident_bool, Ident_Bool - cached IdentifierInfos for "vector"
123
  /// and "bool" fast comparison.  Only present if AltiVec or ZVector are
124
  /// enabled.
125
  IdentifierInfo *Ident_vector;
126
  IdentifierInfo *Ident_bool;
127
  IdentifierInfo *Ident_Bool;
128
  /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison.
129
  /// Only present if AltiVec enabled.
130
  IdentifierInfo *Ident_pixel;
131
132
  /// Objective-C contextual keywords.
133
  IdentifierInfo *Ident_instancetype;
134
135
  /// Identifier for "introduced".
136
  IdentifierInfo *Ident_introduced;
137
138
  /// Identifier for "deprecated".
139
  IdentifierInfo *Ident_deprecated;
140
141
  /// Identifier for "obsoleted".
142
  IdentifierInfo *Ident_obsoleted;
143
144
  /// Identifier for "unavailable".
145
  IdentifierInfo *Ident_unavailable;
146
147
  /// Identifier for "message".
148
  IdentifierInfo *Ident_message;
149
150
  /// Identifier for "strict".
151
  IdentifierInfo *Ident_strict;
152
153
  /// Identifier for "replacement".
154
  IdentifierInfo *Ident_replacement;
155
156
  /// Identifiers used by the 'external_source_symbol' attribute.
157
  IdentifierInfo *Ident_language, *Ident_defined_in,
158
      *Ident_generated_declaration;
159
160
  /// C++11 contextual keywords.
161
  mutable IdentifierInfo *Ident_final;
162
  mutable IdentifierInfo *Ident_GNU_final;
163
  mutable IdentifierInfo *Ident_override;
164
165
  // C++2a contextual keywords.
166
  mutable IdentifierInfo *Ident_import;
167
  mutable IdentifierInfo *Ident_module;
168
169
  // C++ type trait keywords that can be reverted to identifiers and still be
170
  // used as type traits.
171
  llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits;
172
173
  std::unique_ptr<PragmaHandler> AlignHandler;
174
  std::unique_ptr<PragmaHandler> GCCVisibilityHandler;
175
  std::unique_ptr<PragmaHandler> OptionsHandler;
176
  std::unique_ptr<PragmaHandler> PackHandler;
177
  std::unique_ptr<PragmaHandler> MSStructHandler;
178
  std::unique_ptr<PragmaHandler> UnusedHandler;
179
  std::unique_ptr<PragmaHandler> WeakHandler;
180
  std::unique_ptr<PragmaHandler> RedefineExtnameHandler;
181
  std::unique_ptr<PragmaHandler> FPContractHandler;
182
  std::unique_ptr<PragmaHandler> OpenCLExtensionHandler;
183
  std::unique_ptr<PragmaHandler> OpenMPHandler;
184
  std::unique_ptr<PragmaHandler> PCSectionHandler;
185
  std::unique_ptr<PragmaHandler> MSCommentHandler;
186
  std::unique_ptr<PragmaHandler> MSDetectMismatchHandler;
187
  std::unique_ptr<PragmaHandler> FloatControlHandler;
188
  std::unique_ptr<PragmaHandler> MSPointersToMembers;
189
  std::unique_ptr<PragmaHandler> MSVtorDisp;
190
  std::unique_ptr<PragmaHandler> MSInitSeg;
191
  std::unique_ptr<PragmaHandler> MSDataSeg;
192
  std::unique_ptr<PragmaHandler> MSBSSSeg;
193
  std::unique_ptr<PragmaHandler> MSConstSeg;
194
  std::unique_ptr<PragmaHandler> MSCodeSeg;
195
  std::unique_ptr<PragmaHandler> MSSection;
196
  std::unique_ptr<PragmaHandler> MSRuntimeChecks;
197
  std::unique_ptr<PragmaHandler> MSIntrinsic;
198
  std::unique_ptr<PragmaHandler> MSOptimize;
199
  std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler;
200
  std::unique_ptr<PragmaHandler> OptimizeHandler;
201
  std::unique_ptr<PragmaHandler> LoopHintHandler;
202
  std::unique_ptr<PragmaHandler> UnrollHintHandler;
203
  std::unique_ptr<PragmaHandler> NoUnrollHintHandler;
204
  std::unique_ptr<PragmaHandler> UnrollAndJamHintHandler;
205
  std::unique_ptr<PragmaHandler> NoUnrollAndJamHintHandler;
206
  std::unique_ptr<PragmaHandler> FPHandler;
207
  std::unique_ptr<PragmaHandler> STDCFenvAccessHandler;
208
  std::unique_ptr<PragmaHandler> STDCFenvRoundHandler;
209
  std::unique_ptr<PragmaHandler> STDCCXLIMITHandler;
210
  std::unique_ptr<PragmaHandler> STDCUnknownHandler;
211
  std::unique_ptr<PragmaHandler> AttributePragmaHandler;
212
  std::unique_ptr<PragmaHandler> MaxTokensHerePragmaHandler;
213
  std::unique_ptr<PragmaHandler> MaxTokensTotalPragmaHandler;
214
215
  std::unique_ptr<CommentHandler> CommentSemaHandler;
216
217
  /// Whether the '>' token acts as an operator or not. This will be
218
  /// true except when we are parsing an expression within a C++
219
  /// template argument list, where the '>' closes the template
220
  /// argument list.
221
  bool GreaterThanIsOperator;
222
223
  /// ColonIsSacred - When this is false, we aggressively try to recover from
224
  /// code like "foo : bar" as if it were a typo for "foo :: bar".  This is not
225
  /// safe in case statements and a few other things.  This is managed by the
226
  /// ColonProtectionRAIIObject RAII object.
227
  bool ColonIsSacred;
228
229
  /// Parsing OpenMP directive mode.
230
  bool OpenMPDirectiveParsing = false;
231
232
  /// When true, we are directly inside an Objective-C message
233
  /// send expression.
234
  ///
235
  /// This is managed by the \c InMessageExpressionRAIIObject class, and
236
  /// should not be set directly.
237
  bool InMessageExpression;
238
239
  /// Gets set to true after calling ProduceSignatureHelp, it is for a
240
  /// workaround to make sure ProduceSignatureHelp is only called at the deepest
241
  /// function call.
242
  bool CalledSignatureHelp = false;
243
244
  /// The "depth" of the template parameters currently being parsed.
245
  unsigned TemplateParameterDepth;
246
247
  /// Current kind of OpenMP clause
248
  OpenMPClauseKind OMPClauseKind = llvm::omp::OMPC_unknown;
249
250
  /// RAII class that manages the template parameter depth.
251
  class TemplateParameterDepthRAII {
252
    unsigned &Depth;
253
    unsigned AddedLevels;
254
  public:
255
    explicit TemplateParameterDepthRAII(unsigned &Depth)
256
8.04M
      : Depth(Depth), AddedLevels(0) {}
257
258
8.04M
    ~TemplateParameterDepthRAII() {
259
8.04M
      Depth -= AddedLevels;
260
8.04M
    }
261
262
1.19M
    void operator++() {
263
1.19M
      ++Depth;
264
1.19M
      ++AddedLevels;
265
1.19M
    }
266
768k
    void addDepth(unsigned D) {
267
768k
      Depth += D;
268
768k
      AddedLevels += D;
269
768k
    }
270
2.06k
    void setAddedDepth(unsigned D) {
271
2.06k
      Depth = Depth - AddedLevels + D;
272
2.06k
      AddedLevels = D;
273
2.06k
    }
274
275
2.51M
    unsigned getDepth() const { return Depth; }
276
3.58k
    unsigned getOriginalDepth() const { return Depth - AddedLevels; }
277
  };
278
279
  /// Factory object for creating ParsedAttr objects.
280
  AttributeFactory AttrFactory;
281
282
  /// Gathers and cleans up TemplateIdAnnotations when parsing of a
283
  /// top-level declaration is finished.
284
  SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
285
286
72.8M
  void MaybeDestroyTemplateIds() {
287
72.8M
    if (!TemplateIds.empty() &&
288
72.8M
        
(2.00M
Tok.is(tok::eof)2.00M
||
!PP.mightHavePendingAnnotationTokens()1.99M
))
289
1.33M
      DestroyTemplateIds();
290
72.8M
  }
291
  void DestroyTemplateIds();
292
293
  /// RAII object to destroy TemplateIdAnnotations where possible, from a
294
  /// likely-good position during parsing.
295
  struct DestroyTemplateIdAnnotationsRAIIObj {
296
    Parser &Self;
297
298
62.1M
    DestroyTemplateIdAnnotationsRAIIObj(Parser &Self) : Self(Self) {}
299
62.1M
    ~DestroyTemplateIdAnnotationsRAIIObj() { Self.MaybeDestroyTemplateIds(); }
300
  };
301
302
  /// Identifiers which have been declared within a tentative parse.
303
  SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers;
304
305
  /// Tracker for '<' tokens that might have been intended to be treated as an
306
  /// angle bracket instead of a less-than comparison.
307
  ///
308
  /// This happens when the user intends to form a template-id, but typoes the
309
  /// template-name or forgets a 'template' keyword for a dependent template
310
  /// name.
311
  ///
312
  /// We track these locations from the point where we see a '<' with a
313
  /// name-like expression on its left until we see a '>' or '>>' that might
314
  /// match it.
315
  struct AngleBracketTracker {
316
    /// Flags used to rank candidate template names when there is more than one
317
    /// '<' in a scope.
318
    enum Priority : unsigned short {
319
      /// A non-dependent name that is a potential typo for a template name.
320
      PotentialTypo = 0x0,
321
      /// A dependent name that might instantiate to a template-name.
322
      DependentName = 0x2,
323
324
      /// A space appears before the '<' token.
325
      SpaceBeforeLess = 0x0,
326
      /// No space before the '<' token
327
      NoSpaceBeforeLess = 0x1,
328
329
      LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue*/ DependentName)
330
    };
331
332
    struct Loc {
333
      Expr *TemplateName;
334
      SourceLocation LessLoc;
335
      AngleBracketTracker::Priority Priority;
336
      unsigned short ParenCount, BracketCount, BraceCount;
337
338
191k
      bool isActive(Parser &P) const {
339
191k
        return P.ParenCount == ParenCount && 
P.BracketCount == BracketCount182k
&&
340
191k
               
P.BraceCount == BraceCount182k
;
341
191k
      }
342
343
189k
      bool isActiveOrNested(Parser &P) const {
344
189k
        return isActive(P) || 
P.ParenCount > ParenCount7.25k
||
345
189k
               
P.BracketCount > BracketCount90
||
P.BraceCount > BraceCount25
;
346
189k
      }
347
    };
348
349
    SmallVector<Loc, 8> Locs;
350
351
    /// Add an expression that might have been intended to be a template name.
352
    /// In the case of ambiguity, we arbitrarily select the innermost such
353
    /// expression, for example in 'foo < bar < baz', 'bar' is the current
354
    /// candidate. No attempt is made to track that 'foo' is also a candidate
355
    /// for the case where we see a second suspicious '>' token.
356
    void add(Parser &P, Expr *TemplateName, SourceLocation LessLoc,
357
189k
             Priority Prio) {
358
189k
      if (!Locs.empty() && 
Locs.back().isActive(P)1.49k
) {
359
753
        if (Locs.back().Priority <= Prio) {
360
749
          Locs.back().TemplateName = TemplateName;
361
749
          Locs.back().LessLoc = LessLoc;
362
749
          Locs.back().Priority = Prio;
363
749
        }
364
189k
      } else {
365
189k
        Locs.push_back({TemplateName, LessLoc, Prio,
366
189k
                        P.ParenCount, P.BracketCount, P.BraceCount});
367
189k
      }
368
189k
    }
369
370
    /// Mark the current potential missing template location as having been
371
    /// handled (this happens if we pass a "corresponding" '>' or '>>' token
372
    /// or leave a bracket scope).
373
268M
    void clear(Parser &P) {
374
268M
      while (!Locs.empty() && 
Locs.back().isActiveOrNested(P)189k
)
375
189k
        Locs.pop_back();
376
268M
    }
377
378
    /// Get the current enclosing expression that might hve been intended to be
379
    /// a template name.
380
5.78M
    Loc *getCurrent(Parser &P) {
381
5.78M
      if (!Locs.empty() && 
Locs.back().isActive(P)803
)
382
65
        return &Locs.back();
383
5.78M
      return nullptr;
384
5.78M
    }
385
  };
386
387
  AngleBracketTracker AngleBrackets;
388
389
  IdentifierInfo *getSEHExceptKeyword();
390
391
  /// True if we are within an Objective-C container while parsing C-like decls.
392
  ///
393
  /// This is necessary because Sema thinks we have left the container
394
  /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will
395
  /// be NULL.
396
  bool ParsingInObjCContainer;
397
398
  /// Whether to skip parsing of function bodies.
399
  ///
400
  /// This option can be used, for example, to speed up searches for
401
  /// declarations/definitions when indexing.
402
  bool SkipFunctionBodies;
403
404
  /// The location of the expression statement that is being parsed right now.
405
  /// Used to determine if an expression that is being parsed is a statement or
406
  /// just a regular sub-expression.
407
  SourceLocation ExprStatementTokLoc;
408
409
  /// Flags describing a context in which we're parsing a statement.
410
  enum class ParsedStmtContext {
411
    /// This context permits declarations in language modes where declarations
412
    /// are not statements.
413
    AllowDeclarationsInC = 0x1,
414
    /// This context permits standalone OpenMP directives.
415
    AllowStandaloneOpenMPDirectives = 0x2,
416
    /// This context is at the top level of a GNU statement expression.
417
    InStmtExpr = 0x4,
418
419
    /// The context of a regular substatement.
420
    SubStmt = 0,
421
    /// The context of a compound-statement.
422
    Compound = AllowDeclarationsInC | AllowStandaloneOpenMPDirectives,
423
424
    LLVM_MARK_AS_BITMASK_ENUM(InStmtExpr)
425
  };
426
427
  /// Act on an expression statement that might be the last statement in a
428
  /// GNU statement expression. Checks whether we are actually at the end of
429
  /// a statement expression and builds a suitable expression statement.
430
  StmtResult handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx);
431
432
public:
433
  Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
434
  ~Parser() override;
435
436
2.93G
  const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
437
169k
  const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
438
3.10M
  Preprocessor &getPreprocessor() const { return PP; }
439
126M
  Sema &getActions() const { return Actions; }
440
41.3M
  AttributeFactory &getAttrFactory() { return AttrFactory; }
441
442
2.94M
  const Token &getCurToken() const { return Tok; }
443
681M
  Scope *getCurScope() const { return Actions.getCurScope(); }
444
361k
  void incrementMSManglingNumber() const {
445
361k
    return Actions.incrementMSManglingNumber();
446
361k
  }
447
448
39.9M
  Decl  *getObjCDeclContext() const { return Actions.getObjCDeclContext(); }
449
450
  // Type forwarding.  All of these are statically 'void*', but they may all be
451
  // different actual classes based on the actions in place.
452
  typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
453
  typedef OpaquePtr<TemplateName> TemplateTy;
454
455
  typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists;
456
457
  typedef Sema::FullExprArg FullExprArg;
458
459
  // Parsing methods.
460
461
  /// Initialize - Warm up the parser.
462
  ///
463
  void Initialize();
464
465
  /// Parse the first top-level declaration in a translation unit.
466
  bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result);
467
468
  /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if
469
  /// the EOF was encountered.
470
  bool ParseTopLevelDecl(DeclGroupPtrTy &Result, bool IsFirstDecl = false);
471
59.8k
  bool ParseTopLevelDecl() {
472
59.8k
    DeclGroupPtrTy Result;
473
59.8k
    return ParseTopLevelDecl(Result);
474
59.8k
  }
475
476
  /// ConsumeToken - Consume the current 'peek token' and lex the next one.
477
  /// This does not work with special tokens: string literals, code completion,
478
  /// annotation tokens and balanced tokens must be handled using the specific
479
  /// consume methods.
480
  /// Returns the location of the consumed token.
481
569M
  SourceLocation ConsumeToken() {
482
569M
    assert(!isTokenSpecial() &&
483
569M
           "Should consume special tokens with Consume*Token");
484
0
    PrevTokLocation = Tok.getLocation();
485
569M
    PP.Lex(Tok);
486
569M
    return PrevTokLocation;
487
569M
  }
488
489
552M
  bool TryConsumeToken(tok::TokenKind Expected) {
490
552M
    if (Tok.isNot(Expected))
491
393M
      return false;
492
158M
    assert(!isTokenSpecial() &&
493
158M
           "Should consume special tokens with Consume*Token");
494
0
    PrevTokLocation = Tok.getLocation();
495
158M
    PP.Lex(Tok);
496
158M
    return true;
497
552M
  }
498
499
244M
  bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) {
500
244M
    if (!TryConsumeToken(Expected))
501
232M
      return false;
502
11.9M
    Loc = PrevTokLocation;
503
11.9M
    return true;
504
244M
  }
505
506
  /// ConsumeAnyToken - Dispatch to the right Consume* method based on the
507
  /// current token type.  This should only be used in cases where the type of
508
  /// the token really isn't known, e.g. in error recovery.
509
379M
  SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) {
510
379M
    if (isTokenParen())
511
279M
      return ConsumeParen();
512
99.5M
    if (isTokenBracket())
513
61.6k
      return ConsumeBracket();
514
99.5M
    if (isTokenBrace())
515
703k
      return ConsumeBrace();
516
98.8M
    if (isTokenStringLiteral())
517
35.2k
      return ConsumeStringToken();
518
98.7M
    if (Tok.is(tok::code_completion))
519
129
      return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken()
520
129
                                      : 
handleUnexpectedCodeCompletionToken()0
;
521
98.7M
    if (Tok.isAnnotation())
522
172k
      return ConsumeAnnotationToken();
523
98.6M
    return ConsumeToken();
524
98.7M
  }
525
526
527
84
  SourceLocation getEndOfPreviousToken() {
528
84
    return PP.getLocForEndOfToken(PrevTokLocation);
529
84
  }
530
531
  /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds
532
  /// to the given nullability kind.
533
351k
  IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) {
534
351k
    return Actions.getNullabilityKeyword(nullability);
535
351k
  }
536
537
private:
538
  //===--------------------------------------------------------------------===//
539
  // Low-Level token peeking and consumption methods.
540
  //
541
542
  /// isTokenParen - Return true if the cur token is '(' or ')'.
543
1.53G
  bool isTokenParen() const {
544
1.53G
    return Tok.isOneOf(tok::l_paren, tok::r_paren);
545
1.53G
  }
546
  /// isTokenBracket - Return true if the cur token is '[' or ']'.
547
829M
  bool isTokenBracket() const {
548
829M
    return Tok.isOneOf(tok::l_square, tok::r_square);
549
829M
  }
550
  /// isTokenBrace - Return true if the cur token is '{' or '}'.
551
840M
  bool isTokenBrace() const {
552
840M
    return Tok.isOneOf(tok::l_brace, tok::r_brace);
553
840M
  }
554
  /// isTokenStringLiteral - True if this token is a string-literal.
555
847M
  bool isTokenStringLiteral() const {
556
847M
    return tok::isStringLiteral(Tok.getKind());
557
847M
  }
558
  /// isTokenSpecial - True if this token requires special consumption methods.
559
728M
  bool isTokenSpecial() const {
560
728M
    return 
isTokenStringLiteral()728M
|| isTokenParen() ||
isTokenBracket()728M
||
561
728M
           isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation();
562
728M
  }
563
564
  /// Returns true if the current token is '=' or is a type of '='.
565
  /// For typos, give a fixit to '='
566
  bool isTokenEqualOrEqualTypo();
567
568
  /// Return the current token to the token stream and make the given
569
  /// token the current token.
570
17
  void UnconsumeToken(Token &Consumed) {
571
17
      Token Next = Tok;
572
17
      PP.EnterToken(Consumed, /*IsReinject*/true);
573
17
      PP.Lex(Tok);
574
17
      PP.EnterToken(Next, /*IsReinject*/true);
575
17
  }
576
577
47.9M
  SourceLocation ConsumeAnnotationToken() {
578
47.9M
    assert(Tok.isAnnotation() && "wrong consume method");
579
0
    SourceLocation Loc = Tok.getLocation();
580
47.9M
    PrevTokLocation = Tok.getAnnotationEndLoc();
581
47.9M
    PP.Lex(Tok);
582
47.9M
    return Loc;
583
47.9M
  }
584
585
  /// ConsumeParen - This consume method keeps the paren count up-to-date.
586
  ///
587
426M
  SourceLocation ConsumeParen() {
588
426M
    assert(isTokenParen() && "wrong consume method");
589
426M
    if (Tok.getKind() == tok::l_paren)
590
217M
      ++ParenCount;
591
208M
    else if (ParenCount) {
592
208M
      AngleBrackets.clear(*this);
593
208M
      --ParenCount;       // Don't let unbalanced )'s drive the count negative.
594
208M
    }
595
426M
    PrevTokLocation = Tok.getLocation();
596
426M
    PP.Lex(Tok);
597
426M
    return PrevTokLocation;
598
426M
  }
599
600
  /// ConsumeBracket - This consume method keeps the bracket count up-to-date.
601
  ///
602
1.43M
  SourceLocation ConsumeBracket() {
603
1.43M
    assert(isTokenBracket() && "wrong consume method");
604
1.43M
    if (Tok.getKind() == tok::l_square)
605
719k
      ++BracketCount;
606
717k
    else if (BracketCount) {
607
717k
      AngleBrackets.clear(*this);
608
717k
      --BracketCount;     // Don't let unbalanced ]'s drive the count negative.
609
717k
    }
610
611
1.43M
    PrevTokLocation = Tok.getLocation();
612
1.43M
    PP.Lex(Tok);
613
1.43M
    return PrevTokLocation;
614
1.43M
  }
615
616
  /// ConsumeBrace - This consume method keeps the brace count up-to-date.
617
  ///
618
13.3M
  SourceLocation ConsumeBrace() {
619
13.3M
    assert(isTokenBrace() && "wrong consume method");
620
13.3M
    if (Tok.getKind() == tok::l_brace)
621
6.66M
      ++BraceCount;
622
6.65M
    else if (BraceCount) {
623
6.65M
      AngleBrackets.clear(*this);
624
6.65M
      --BraceCount;     // Don't let unbalanced }'s drive the count negative.
625
6.65M
    }
626
627
13.3M
    PrevTokLocation = Tok.getLocation();
628
13.3M
    PP.Lex(Tok);
629
13.3M
    return PrevTokLocation;
630
13.3M
  }
631
632
  /// ConsumeStringToken - Consume the current 'peek token', lexing a new one
633
  /// and returning the token kind.  This method is specific to strings, as it
634
  /// handles string literal concatenation, as per C99 5.1.1.2, translation
635
  /// phase #6.
636
3.99M
  SourceLocation ConsumeStringToken() {
637
3.99M
    assert(isTokenStringLiteral() &&
638
3.99M
           "Should only consume string literals with this method");
639
0
    PrevTokLocation = Tok.getLocation();
640
3.99M
    PP.Lex(Tok);
641
3.99M
    return PrevTokLocation;
642
3.99M
  }
643
644
  /// Consume the current code-completion token.
645
  ///
646
  /// This routine can be called to consume the code-completion token and
647
  /// continue processing in special cases where \c cutOffParsing() isn't
648
  /// desired, such as token caching or completion with lookahead.
649
176
  SourceLocation ConsumeCodeCompletionToken() {
650
176
    assert(Tok.is(tok::code_completion));
651
0
    PrevTokLocation = Tok.getLocation();
652
176
    PP.Lex(Tok);
653
176
    return PrevTokLocation;
654
176
  }
655
656
  ///\ brief When we are consuming a code-completion token without having
657
  /// matched specific position in the grammar, provide code-completion results
658
  /// based on context.
659
  ///
660
  /// \returns the source location of the code-completion token.
661
  SourceLocation handleUnexpectedCodeCompletionToken();
662
663
  /// Abruptly cut off parsing; mainly used when we have reached the
664
  /// code-completion point.
665
1.30k
  void cutOffParsing() {
666
1.30k
    if (PP.isCodeCompletionEnabled())
667
1.29k
      PP.setCodeCompletionReached();
668
    // Cut off parsing by acting as if we reached the end-of-file.
669
1.30k
    Tok.setKind(tok::eof);
670
1.30k
  }
671
672
  /// Determine if we're at the end of the file or at a transition
673
  /// between modules.
674
961k
  bool isEofOrEom() {
675
961k
    tok::TokenKind Kind = Tok.getKind();
676
961k
    return Kind == tok::eof || 
Kind == tok::annot_module_begin961k
||
677
961k
           
Kind == tok::annot_module_end961k
||
Kind == tok::annot_module_include961k
;
678
961k
  }
679
680
  /// Checks if the \p Level is valid for use in a fold expression.
681
  bool isFoldOperator(prec::Level Level) const;
682
683
  /// Checks if the \p Kind is a valid operator for fold expressions.
684
  bool isFoldOperator(tok::TokenKind Kind) const;
685
686
  /// Initialize all pragma handlers.
687
  void initializePragmaHandlers();
688
689
  /// Destroy and reset all pragma handlers.
690
  void resetPragmaHandlers();
691
692
  /// Handle the annotation token produced for #pragma unused(...)
693
  void HandlePragmaUnused();
694
695
  /// Handle the annotation token produced for
696
  /// #pragma GCC visibility...
697
  void HandlePragmaVisibility();
698
699
  /// Handle the annotation token produced for
700
  /// #pragma pack...
701
  void HandlePragmaPack();
702
703
  /// Handle the annotation token produced for
704
  /// #pragma ms_struct...
705
  void HandlePragmaMSStruct();
706
707
  void HandlePragmaMSPointersToMembers();
708
709
  void HandlePragmaMSVtorDisp();
710
711
  void HandlePragmaMSPragma();
712
  bool HandlePragmaMSSection(StringRef PragmaName,
713
                             SourceLocation PragmaLocation);
714
  bool HandlePragmaMSSegment(StringRef PragmaName,
715
                             SourceLocation PragmaLocation);
716
  bool HandlePragmaMSInitSeg(StringRef PragmaName,
717
                             SourceLocation PragmaLocation);
718
719
  /// Handle the annotation token produced for
720
  /// #pragma align...
721
  void HandlePragmaAlign();
722
723
  /// Handle the annotation token produced for
724
  /// #pragma clang __debug dump...
725
  void HandlePragmaDump();
726
727
  /// Handle the annotation token produced for
728
  /// #pragma weak id...
729
  void HandlePragmaWeak();
730
731
  /// Handle the annotation token produced for
732
  /// #pragma weak id = id...
733
  void HandlePragmaWeakAlias();
734
735
  /// Handle the annotation token produced for
736
  /// #pragma redefine_extname...
737
  void HandlePragmaRedefineExtname();
738
739
  /// Handle the annotation token produced for
740
  /// #pragma STDC FP_CONTRACT...
741
  void HandlePragmaFPContract();
742
743
  /// Handle the annotation token produced for
744
  /// #pragma STDC FENV_ACCESS...
745
  void HandlePragmaFEnvAccess();
746
747
  /// Handle the annotation token produced for
748
  /// #pragma STDC FENV_ROUND...
749
  void HandlePragmaFEnvRound();
750
751
  /// Handle the annotation token produced for
752
  /// #pragma float_control
753
  void HandlePragmaFloatControl();
754
755
  /// \brief Handle the annotation token produced for
756
  /// #pragma clang fp ...
757
  void HandlePragmaFP();
758
759
  /// Handle the annotation token produced for
760
  /// #pragma OPENCL EXTENSION...
761
  void HandlePragmaOpenCLExtension();
762
763
  /// Handle the annotation token produced for
764
  /// #pragma clang __debug captured
765
  StmtResult HandlePragmaCaptured();
766
767
  /// Handle the annotation token produced for
768
  /// #pragma clang loop and #pragma unroll.
769
  bool HandlePragmaLoopHint(LoopHint &Hint);
770
771
  bool ParsePragmaAttributeSubjectMatchRuleSet(
772
      attr::ParsedSubjectMatchRuleSet &SubjectMatchRules,
773
      SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc);
774
775
  void HandlePragmaAttribute();
776
777
  /// GetLookAheadToken - This peeks ahead N tokens and returns that token
778
  /// without consuming any tokens.  LookAhead(0) returns 'Tok', LookAhead(1)
779
  /// returns the token after Tok, etc.
780
  ///
781
  /// Note that this differs from the Preprocessor's LookAhead method, because
782
  /// the Parser always has one token lexed that the preprocessor doesn't.
783
  ///
784
3.62M
  const Token &GetLookAheadToken(unsigned N) {
785
3.62M
    if (N == 0 || 
Tok.is(tok::eof)3.59M
)
return Tok27.7k
;
786
3.59M
    return PP.LookAhead(N-1);
787
3.62M
  }
788
789
public:
790
  /// NextToken - This peeks ahead one token and returns it without
791
  /// consuming it.
792
223M
  const Token &NextToken() {
793
223M
    return PP.LookAhead(0);
794
223M
  }
795
796
  /// getTypeAnnotation - Read a parsed type out of an annotation token.
797
39.6M
  static TypeResult getTypeAnnotation(const Token &Tok) {
798
39.6M
    if (!Tok.getAnnotationValue())
799
1.65k
      return TypeError();
800
39.6M
    return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
801
39.6M
  }
802
803
private:
804
39.4M
  static void setTypeAnnotation(Token &Tok, TypeResult T) {
805
39.4M
    assert((T.isInvalid() || T.get()) &&
806
39.4M
           "produced a valid-but-null type annotation?");
807
39.4M
    Tok.setAnnotationValue(T.isInvalid() ? 
nullptr1.65k
:
T.get().getAsOpaquePtr()39.4M
);
808
39.4M
  }
809
810
1.91M
  static NamedDecl *getNonTypeAnnotation(const Token &Tok) {
811
1.91M
    return static_cast<NamedDecl*>(Tok.getAnnotationValue());
812
1.91M
  }
813
814
1.91M
  static void setNonTypeAnnotation(Token &Tok, NamedDecl *ND) {
815
1.91M
    Tok.setAnnotationValue(ND);
816
1.91M
  }
817
818
2.76k
  static IdentifierInfo *getIdentifierAnnotation(const Token &Tok) {
819
2.76k
    return static_cast<IdentifierInfo*>(Tok.getAnnotationValue());
820
2.76k
  }
821
822
2.76k
  static void setIdentifierAnnotation(Token &Tok, IdentifierInfo *ND) {
823
2.76k
    Tok.setAnnotationValue(ND);
824
2.76k
  }
825
826
  /// Read an already-translated primary expression out of an annotation
827
  /// token.
828
715k
  static ExprResult getExprAnnotation(const Token &Tok) {
829
715k
    return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue());
830
715k
  }
831
832
  /// Set the primary expression corresponding to the given annotation
833
  /// token.
834
715k
  static void setExprAnnotation(Token &Tok, ExprResult ER) {
835
715k
    Tok.setAnnotationValue(ER.getAsOpaquePointer());
836
715k
  }
837
838
public:
839
  // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to
840
  // find a type name by attempting typo correction.
841
  bool TryAnnotateTypeOrScopeToken();
842
  bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS,
843
                                                 bool IsNewScope);
844
  bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
845
846
27.7M
  bool MightBeCXXScopeToken() {
847
27.7M
    return Tok.is(tok::identifier) || 
Tok.is(tok::coloncolon)213k
||
848
27.7M
           
(212k
Tok.is(tok::annot_template_id)212k
&&
849
212k
            
NextToken().is(tok::coloncolon)0
) ||
850
27.7M
           
Tok.is(tok::kw_decltype)212k
||
Tok.is(tok::kw___super)186k
;
851
27.7M
  }
852
204k
  bool TryAnnotateOptionalCXXScopeToken(bool EnteringContext = false) {
853
204k
    return MightBeCXXScopeToken() && 
TryAnnotateCXXScopeToken(EnteringContext)18.3k
;
854
204k
  }
855
856
private:
857
  enum AnnotatedNameKind {
858
    /// Annotation has failed and emitted an error.
859
    ANK_Error,
860
    /// The identifier is a tentatively-declared name.
861
    ANK_TentativeDecl,
862
    /// The identifier is a template name. FIXME: Add an annotation for that.
863
    ANK_TemplateName,
864
    /// The identifier can't be resolved.
865
    ANK_Unresolved,
866
    /// Annotation was successful.
867
    ANK_Success
868
  };
869
  AnnotatedNameKind TryAnnotateName(CorrectionCandidateCallback *CCC = nullptr);
870
871
  /// Push a tok::annot_cxxscope token onto the token stream.
872
  void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
873
874
  /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
875
  /// replacing them with the non-context-sensitive keywords.  This returns
876
  /// true if the token was replaced.
877
  bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
878
                       const char *&PrevSpec, unsigned &DiagID,
879
91.3M
                       bool &isInvalid) {
880
91.3M
    if (!getLangOpts().AltiVec && 
!getLangOpts().ZVector90.8M
)
881
90.8M
      return false;
882
883
458k
    if (Tok.getIdentifierInfo() != Ident_vector &&
884
458k
        
Tok.getIdentifierInfo() != Ident_bool134k
&&
885
458k
        
Tok.getIdentifierInfo() != Ident_Bool35.8k
&&
886
458k
        
(35.8k
!getLangOpts().AltiVec35.8k
||
Tok.getIdentifierInfo() != Ident_pixel35.8k
))
887
22.8k
      return false;
888
889
435k
    return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
890
458k
  }
891
892
  /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
893
  /// identifier token, replacing it with the non-context-sensitive __vector.
894
  /// This returns true if the token was replaced.
895
53.7M
  bool TryAltiVecVectorToken() {
896
53.7M
    if ((!getLangOpts().AltiVec && 
!getLangOpts().ZVector53.2M
) ||
897
53.7M
        
Tok.getIdentifierInfo() != Ident_vector467k
)
return false53.3M
;
898
358k
    return TryAltiVecVectorTokenOutOfLine();
899
53.7M
  }
900
901
  bool TryAltiVecVectorTokenOutOfLine();
902
  bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
903
                                const char *&PrevSpec, unsigned &DiagID,
904
                                bool &isInvalid);
905
906
  /// Returns true if the current token is the identifier 'instancetype'.
907
  ///
908
  /// Should only be used in Objective-C language modes.
909
220k
  bool isObjCInstancetype() {
910
220k
    assert(getLangOpts().ObjC);
911
220k
    if (Tok.isAnnotation())
912
2
      return false;
913
220k
    if (!Ident_instancetype)
914
595
      Ident_instancetype = PP.getIdentifierInfo("instancetype");
915
220k
    return Tok.getIdentifierInfo() == Ident_instancetype;
916
220k
  }
917
918
  /// TryKeywordIdentFallback - For compatibility with system headers using
919
  /// keywords as identifiers, attempt to convert the current token to an
920
  /// identifier and optionally disable the keyword for the remainder of the
921
  /// translation unit. This returns false if the token was not replaced,
922
  /// otherwise emits a diagnostic and returns true.
923
  bool TryKeywordIdentFallback(bool DisableKeyword);
924
925
  /// Get the TemplateIdAnnotation from the token.
926
  TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
927
928
  /// TentativeParsingAction - An object that is used as a kind of "tentative
929
  /// parsing transaction". It gets instantiated to mark the token position and
930
  /// after the token consumption is done, Commit() or Revert() is called to
931
  /// either "commit the consumed tokens" or revert to the previously marked
932
  /// token position. Example:
933
  ///
934
  ///   TentativeParsingAction TPA(*this);
935
  ///   ConsumeToken();
936
  ///   ....
937
  ///   TPA.Revert();
938
  ///
939
  class TentativeParsingAction {
940
    Parser &P;
941
    PreferredTypeBuilder PrevPreferredType;
942
    Token PrevTok;
943
    size_t PrevTentativelyDeclaredIdentifierCount;
944
    unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
945
    bool isActive;
946
947
  public:
948
    explicit TentativeParsingAction(Parser &p)
949
10.7M
        : P(p), PrevPreferredType(P.PreferredType) {
950
10.7M
      PrevTok = P.Tok;
951
10.7M
      PrevTentativelyDeclaredIdentifierCount =
952
10.7M
          P.TentativelyDeclaredIdentifiers.size();
953
10.7M
      PrevParenCount = P.ParenCount;
954
10.7M
      PrevBracketCount = P.BracketCount;
955
10.7M
      PrevBraceCount = P.BraceCount;
956
10.7M
      P.PP.EnableBacktrackAtThisPos();
957
10.7M
      isActive = true;
958
10.7M
    }
959
41.3k
    void Commit() {
960
41.3k
      assert(isActive && "Parsing action was finished!");
961
0
      P.TentativelyDeclaredIdentifiers.resize(
962
41.3k
          PrevTentativelyDeclaredIdentifierCount);
963
41.3k
      P.PP.CommitBacktrackedTokens();
964
41.3k
      isActive = false;
965
41.3k
    }
966
10.7M
    void Revert() {
967
10.7M
      assert(isActive && "Parsing action was finished!");
968
0
      P.PP.Backtrack();
969
10.7M
      P.PreferredType = PrevPreferredType;
970
10.7M
      P.Tok = PrevTok;
971
10.7M
      P.TentativelyDeclaredIdentifiers.resize(
972
10.7M
          PrevTentativelyDeclaredIdentifierCount);
973
10.7M
      P.ParenCount = PrevParenCount;
974
10.7M
      P.BracketCount = PrevBracketCount;
975
10.7M
      P.BraceCount = PrevBraceCount;
976
10.7M
      isActive = false;
977
10.7M
    }
978
10.7M
    ~TentativeParsingAction() {
979
10.7M
      assert(!isActive && "Forgot to call Commit or Revert!");
980
10.7M
    }
981
  };
982
  /// A TentativeParsingAction that automatically reverts in its destructor.
983
  /// Useful for disambiguation parses that will always be reverted.
984
  class RevertingTentativeParsingAction
985
      : private Parser::TentativeParsingAction {
986
  public:
987
    RevertingTentativeParsingAction(Parser &P)
988
9.41M
        : Parser::TentativeParsingAction(P) {}
989
9.41M
    ~RevertingTentativeParsingAction() { Revert(); }
990
  };
991
992
  class UnannotatedTentativeParsingAction;
993
994
  /// ObjCDeclContextSwitch - An object used to switch context from
995
  /// an objective-c decl context to its enclosing decl context and
996
  /// back.
997
  class ObjCDeclContextSwitch {
998
    Parser &P;
999
    Decl *DC;
1000
    SaveAndRestore<bool> WithinObjCContainer;
1001
  public:
1002
    explicit ObjCDeclContextSwitch(Parser &p)
1003
      : P(p), DC(p.getObjCDeclContext()),
1004
39.9M
        WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) {
1005
39.9M
      if (DC)
1006
1.69M
        P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC));
1007
39.9M
    }
1008
39.9M
    ~ObjCDeclContextSwitch() {
1009
39.9M
      if (DC)
1010
1.69M
        P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC));
1011
39.9M
    }
1012
  };
1013
1014
  /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
1015
  /// input.  If so, it is consumed and false is returned.
1016
  ///
1017
  /// If a trivial punctuator misspelling is encountered, a FixIt error
1018
  /// diagnostic is issued and false is returned after recovery.
1019
  ///
1020
  /// If the input is malformed, this emits the specified diagnostic and true is
1021
  /// returned.
1022
  bool ExpectAndConsume(tok::TokenKind ExpectedTok,
1023
                        unsigned Diag = diag::err_expected,
1024
                        StringRef DiagMsg = "");
1025
1026
  /// The parser expects a semicolon and, if present, will consume it.
1027
  ///
1028
  /// If the next token is not a semicolon, this emits the specified diagnostic,
1029
  /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
1030
  /// to the semicolon, consumes that extra token.
1031
  bool ExpectAndConsumeSemi(unsigned DiagID);
1032
1033
  /// The kind of extra semi diagnostic to emit.
1034
  enum ExtraSemiKind {
1035
    OutsideFunction = 0,
1036
    InsideStruct = 1,
1037
    InstanceVariableList = 2,
1038
    AfterMemberFunctionDefinition = 3
1039
  };
1040
1041
  /// Consume any extra semi-colons until the end of the line.
1042
  void ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST T = TST_unspecified);
1043
1044
  /// Return false if the next token is an identifier. An 'expected identifier'
1045
  /// error is emitted otherwise.
1046
  ///
1047
  /// The parser tries to recover from the error by checking if the next token
1048
  /// is a C++ keyword when parsing Objective-C++. Return false if the recovery
1049
  /// was successful.
1050
  bool expectIdentifier();
1051
1052
  /// Kinds of compound pseudo-tokens formed by a sequence of two real tokens.
1053
  enum class CompoundToken {
1054
    /// A '(' '{' beginning a statement-expression.
1055
    StmtExprBegin,
1056
    /// A '}' ')' ending a statement-expression.
1057
    StmtExprEnd,
1058
    /// A '[' '[' beginning a C++11 or C2x attribute.
1059
    AttrBegin,
1060
    /// A ']' ']' ending a C++11 or C2x attribute.
1061
    AttrEnd,
1062
    /// A '::' '*' forming a C++ pointer-to-member declaration.
1063
    MemberPtr,
1064
  };
1065
1066
  /// Check that a compound operator was written in a "sensible" way, and warn
1067
  /// if not.
1068
  void checkCompoundToken(SourceLocation FirstTokLoc,
1069
                          tok::TokenKind FirstTokKind, CompoundToken Op);
1070
1071
public:
1072
  //===--------------------------------------------------------------------===//
1073
  // Scope manipulation
1074
1075
  /// ParseScope - Introduces a new scope for parsing. The kind of
1076
  /// scope is determined by ScopeFlags. Objects of this type should
1077
  /// be created on the stack to coincide with the position where the
1078
  /// parser enters the new scope, and this object's constructor will
1079
  /// create that new scope. Similarly, once the object is destroyed
1080
  /// the parser will exit the scope.
1081
  class ParseScope {
1082
    Parser *Self;
1083
    ParseScope(const ParseScope &) = delete;
1084
    void operator=(const ParseScope &) = delete;
1085
1086
  public:
1087
    // ParseScope - Construct a new object to manage a scope in the
1088
    // parser Self where the new Scope is created with the flags
1089
    // ScopeFlags, but only when we aren't about to enter a compound statement.
1090
    ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true,
1091
               bool BeforeCompoundStmt = false)
1092
41.0M
      : Self(Self) {
1093
41.0M
      if (EnteredScope && 
!BeforeCompoundStmt41.0M
)
1094
40.6M
        Self->EnterScope(ScopeFlags);
1095
361k
      else {
1096
361k
        if (BeforeCompoundStmt)
1097
361k
          Self->incrementMSManglingNumber();
1098
1099
361k
        this->Self = nullptr;
1100
361k
      }
1101
41.0M
    }
1102
1103
    // Exit - Exit the scope associated with this object now, rather
1104
    // than waiting until the object is destroyed.
1105
80.4M
    void Exit() {
1106
80.4M
      if (Self) {
1107
40.6M
        Self->ExitScope();
1108
40.6M
        Self = nullptr;
1109
40.6M
      }
1110
80.4M
    }
1111
1112
41.0M
    ~ParseScope() {
1113
41.0M
      Exit();
1114
41.0M
    }
1115
  };
1116
1117
  /// Introduces zero or more scopes for parsing. The scopes will all be exited
1118
  /// when the object is destroyed.
1119
  class MultiParseScope {
1120
    Parser &Self;
1121
    unsigned NumScopes = 0;
1122
1123
    MultiParseScope(const MultiParseScope&) = delete;
1124
1125
  public:
1126
5.17M
    MultiParseScope(Parser &Self) : Self(Self) {}
1127
1.47M
    void Enter(unsigned ScopeFlags) {
1128
1.47M
      Self.EnterScope(ScopeFlags);
1129
1.47M
      ++NumScopes;
1130
1.47M
    }
1131
5.27M
    void Exit() {
1132
6.75M
      while (NumScopes) {
1133
1.47M
        Self.ExitScope();
1134
1.47M
        --NumScopes;
1135
1.47M
      }
1136
5.27M
    }
1137
5.17M
    ~MultiParseScope() {
1138
5.17M
      Exit();
1139
5.17M
    }
1140
  };
1141
1142
  /// EnterScope - Start a new scope.
1143
  void EnterScope(unsigned ScopeFlags);
1144
1145
  /// ExitScope - Pop a scope off the scope stack.
1146
  void ExitScope();
1147
1148
  /// Re-enter the template scopes for a declaration that might be a template.
1149
  unsigned ReenterTemplateScopes(MultiParseScope &S, Decl *D);
1150
1151
private:
1152
  /// RAII object used to modify the scope flags for the current scope.
1153
  class ParseScopeFlags {
1154
    Scope *CurScope;
1155
    unsigned OldFlags;
1156
    ParseScopeFlags(const ParseScopeFlags &) = delete;
1157
    void operator=(const ParseScopeFlags &) = delete;
1158
1159
  public:
1160
    ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
1161
    ~ParseScopeFlags();
1162
  };
1163
1164
  //===--------------------------------------------------------------------===//
1165
  // Diagnostic Emission and Error recovery.
1166
1167
public:
1168
  DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
1169
  DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
1170
737
  DiagnosticBuilder Diag(unsigned DiagID) {
1171
737
    return Diag(Tok, DiagID);
1172
737
  }
1173
1174
private:
1175
  void SuggestParentheses(SourceLocation Loc, unsigned DK,
1176
                          SourceRange ParenRange);
1177
  void CheckNestedObjCContexts(SourceLocation AtLoc);
1178
1179
public:
1180
1181
  /// Control flags for SkipUntil functions.
1182
  enum SkipUntilFlags {
1183
    StopAtSemi = 1 << 0,  ///< Stop skipping at semicolon
1184
    /// Stop skipping at specified token, but don't skip the token itself
1185
    StopBeforeMatch = 1 << 1,
1186
    StopAtCodeCompletion = 1 << 2 ///< Stop at code completion
1187
  };
1188
1189
  friend constexpr SkipUntilFlags operator|(SkipUntilFlags L,
1190
52.5k
                                            SkipUntilFlags R) {
1191
52.5k
    return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) |
1192
52.5k
                                       static_cast<unsigned>(R));
1193
52.5k
  }
1194
1195
  /// SkipUntil - Read tokens until we get to the specified token, then consume
1196
  /// it (unless StopBeforeMatch is specified).  Because we cannot guarantee
1197
  /// that the token will ever occur, this skips to the next token, or to some
1198
  /// likely good stopping point.  If Flags has StopAtSemi flag, skipping will
1199
  /// stop at a ';' character. Balances (), [], and {} delimiter tokens while
1200
  /// skipping.
1201
  ///
1202
  /// If SkipUntil finds the specified token, it returns true, otherwise it
1203
  /// returns false.
1204
  bool SkipUntil(tok::TokenKind T,
1205
113k
                 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
1206
113k
    return SkipUntil(llvm::makeArrayRef(T), Flags);
1207
113k
  }
1208
  bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2,
1209
35.0k
                 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
1210
35.0k
    tok::TokenKind TokArray[] = {T1, T2};
1211
35.0k
    return SkipUntil(TokArray, Flags);
1212
35.0k
  }
1213
  bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3,
1214
37.2k
                 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
1215
37.2k
    tok::TokenKind TokArray[] = {T1, T2, T3};
1216
37.2k
    return SkipUntil(TokArray, Flags);
1217
37.2k
  }
1218
  bool SkipUntil(ArrayRef<tok::TokenKind> Toks,
1219
                 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0));
1220
1221
  /// SkipMalformedDecl - Read tokens until we get to some likely good stopping
1222
  /// point for skipping past a simple-declaration.
1223
  void SkipMalformedDecl();
1224
1225
  /// The location of the first statement inside an else that might
1226
  /// have a missleading indentation. If there is no
1227
  /// MisleadingIndentationChecker on an else active, this location is invalid.
1228
  SourceLocation MisleadingIndentationElseLoc;
1229
1230
private:
1231
  //===--------------------------------------------------------------------===//
1232
  // Lexing and parsing of C++ inline methods.
1233
1234
  struct ParsingClass;
1235
1236
  /// [class.mem]p1: "... the class is regarded as complete within
1237
  /// - function bodies
1238
  /// - default arguments
1239
  /// - exception-specifications (TODO: C++0x)
1240
  /// - and brace-or-equal-initializers for non-static data members
1241
  /// (including such things in nested classes)."
1242
  /// LateParsedDeclarations build the tree of those elements so they can
1243
  /// be parsed after parsing the top-level class.
1244
  class LateParsedDeclaration {
1245
  public:
1246
    virtual ~LateParsedDeclaration();
1247
1248
    virtual void ParseLexedMethodDeclarations();
1249
    virtual void ParseLexedMemberInitializers();
1250
    virtual void ParseLexedMethodDefs();
1251
    virtual void ParseLexedAttributes();
1252
    virtual void ParseLexedPragmas();
1253
  };
1254
1255
  /// Inner node of the LateParsedDeclaration tree that parses
1256
  /// all its members recursively.
1257
  class LateParsedClass : public LateParsedDeclaration {
1258
  public:
1259
    LateParsedClass(Parser *P, ParsingClass *C);
1260
    ~LateParsedClass() override;
1261
1262
    void ParseLexedMethodDeclarations() override;
1263
    void ParseLexedMemberInitializers() override;
1264
    void ParseLexedMethodDefs() override;
1265
    void ParseLexedAttributes() override;
1266
    void ParseLexedPragmas() override;
1267
1268
  private:
1269
    Parser *Self;
1270
    ParsingClass *Class;
1271
  };
1272
1273
  /// Contains the lexed tokens of an attribute with arguments that
1274
  /// may reference member variables and so need to be parsed at the
1275
  /// end of the class declaration after parsing all other member
1276
  /// member declarations.
1277
  /// FIXME: Perhaps we should change the name of LateParsedDeclaration to
1278
  /// LateParsedTokens.
1279
  struct LateParsedAttribute : public LateParsedDeclaration {
1280
    Parser *Self;
1281
    CachedTokens Toks;
1282
    IdentifierInfo &AttrName;
1283
    IdentifierInfo *MacroII = nullptr;
1284
    SourceLocation AttrNameLoc;
1285
    SmallVector<Decl*, 2> Decls;
1286
1287
    explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
1288
                                 SourceLocation Loc)
1289
10.6k
      : Self(P), AttrName(Name), AttrNameLoc(Loc) {}
1290
1291
    void ParseLexedAttributes() override;
1292
1293
10.6k
    void addDecl(Decl *D) { Decls.push_back(D); }
1294
  };
1295
1296
  /// Contains the lexed tokens of a pragma with arguments that
1297
  /// may reference member variables and so need to be parsed at the
1298
  /// end of the class declaration after parsing all other member
1299
  /// member declarations.
1300
  class LateParsedPragma : public LateParsedDeclaration {
1301
    Parser *Self = nullptr;
1302
    AccessSpecifier AS = AS_none;
1303
    CachedTokens Toks;
1304
1305
  public:
1306
    explicit LateParsedPragma(Parser *P, AccessSpecifier AS)
1307
86
        : Self(P), AS(AS) {}
1308
1309
86
    void takeToks(CachedTokens &Cached) { Toks.swap(Cached); }
1310
86
    const CachedTokens &toks() const { return Toks; }
1311
86
    AccessSpecifier getAccessSpecifier() const { return AS; }
1312
1313
    void ParseLexedPragmas() override;
1314
  };
1315
1316
  // A list of late-parsed attributes.  Used by ParseGNUAttributes.
1317
  class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> {
1318
  public:
1319
40.1M
    LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { }
1320
1321
2.89M
    bool parseSoon() { return ParseSoon; }
1322
1323
  private:
1324
    bool ParseSoon;  // Are we planning to parse these shortly after creation?
1325
  };
1326
1327
  /// Contains the lexed tokens of a member function definition
1328
  /// which needs to be parsed at the end of the class declaration
1329
  /// after parsing all other member declarations.
1330
  struct LexedMethod : public LateParsedDeclaration {
1331
    Parser *Self;
1332
    Decl *D;
1333
    CachedTokens Toks;
1334
1335
642k
    explicit LexedMethod(Parser *P, Decl *MD) : Self(P), D(MD) {}
1336
1337
    void ParseLexedMethodDefs() override;
1338
  };
1339
1340
  /// LateParsedDefaultArgument - Keeps track of a parameter that may
1341
  /// have a default argument that cannot be parsed yet because it
1342
  /// occurs within a member function declaration inside the class
1343
  /// (C++ [class.mem]p2).
1344
  struct LateParsedDefaultArgument {
1345
    explicit LateParsedDefaultArgument(Decl *P,
1346
                                       std::unique_ptr<CachedTokens> Toks = nullptr)
1347
167k
      : Param(P), Toks(std::move(Toks)) { }
1348
1349
    /// Param - The parameter declaration for this parameter.
1350
    Decl *Param;
1351
1352
    /// Toks - The sequence of tokens that comprises the default
1353
    /// argument expression, not including the '=' or the terminating
1354
    /// ')' or ','. This will be NULL for parameters that have no
1355
    /// default argument.
1356
    std::unique_ptr<CachedTokens> Toks;
1357
  };
1358
1359
  /// LateParsedMethodDeclaration - A method declaration inside a class that
1360
  /// contains at least one entity whose parsing needs to be delayed
1361
  /// until the class itself is completely-defined, such as a default
1362
  /// argument (C++ [class.mem]p2).
1363
  struct LateParsedMethodDeclaration : public LateParsedDeclaration {
1364
    explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
1365
95.4k
        : Self(P), Method(M), ExceptionSpecTokens(nullptr) {}
1366
1367
    void ParseLexedMethodDeclarations() override;
1368
1369
    Parser *Self;
1370
1371
    /// Method - The method declaration.
1372
    Decl *Method;
1373
1374
    /// DefaultArgs - Contains the parameters of the function and
1375
    /// their default arguments. At least one of the parameters will
1376
    /// have a default argument, but all of the parameters of the
1377
    /// method will be stored so that they can be reintroduced into
1378
    /// scope at the appropriate times.
1379
    SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
1380
1381
    /// The set of tokens that make up an exception-specification that
1382
    /// has not yet been parsed.
1383
    CachedTokens *ExceptionSpecTokens;
1384
  };
1385
1386
  /// LateParsedMemberInitializer - An initializer for a non-static class data
1387
  /// member whose parsing must to be delayed until the class is completely
1388
  /// defined (C++11 [class.mem]p2).
1389
  struct LateParsedMemberInitializer : public LateParsedDeclaration {
1390
    LateParsedMemberInitializer(Parser *P, Decl *FD)
1391
3.29k
      : Self(P), Field(FD) { }
1392
1393
    void ParseLexedMemberInitializers() override;
1394
1395
    Parser *Self;
1396
1397
    /// Field - The field declaration.
1398
    Decl *Field;
1399
1400
    /// CachedTokens - The sequence of tokens that comprises the initializer,
1401
    /// including any leading '='.
1402
    CachedTokens Toks;
1403
  };
1404
1405
  /// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
1406
  /// C++ class, its method declarations that contain parts that won't be
1407
  /// parsed until after the definition is completed (C++ [class.mem]p2),
1408
  /// the method declarations and possibly attached inline definitions
1409
  /// will be stored here with the tokens that will be parsed to create those
1410
  /// entities.
1411
  typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer;
1412
1413
  /// Representation of a class that has been parsed, including
1414
  /// any member function declarations or definitions that need to be
1415
  /// parsed after the corresponding top-level class is complete.
1416
  struct ParsingClass {
1417
    ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface)
1418
        : TopLevelClass(TopLevelClass), IsInterface(IsInterface),
1419
672k
          TagOrTemplate(TagOrTemplate) {}
1420
1421
    /// Whether this is a "top-level" class, meaning that it is
1422
    /// not nested within another class.
1423
    bool TopLevelClass : 1;
1424
1425
    /// Whether this class is an __interface.
1426
    bool IsInterface : 1;
1427
1428
    /// The class or class template whose definition we are parsing.
1429
    Decl *TagOrTemplate;
1430
1431
    /// LateParsedDeclarations - Method declarations, inline definitions and
1432
    /// nested classes that contain pieces whose parsing will be delayed until
1433
    /// the top-level class is fully defined.
1434
    LateParsedDeclarationsContainer LateParsedDeclarations;
1435
  };
1436
1437
  /// The stack of classes that is currently being
1438
  /// parsed. Nested and local classes will be pushed onto this stack
1439
  /// when they are parsed, and removed afterward.
1440
  std::stack<ParsingClass *> ClassStack;
1441
1442
9.00M
  ParsingClass &getCurrentClass() {
1443
9.00M
    assert(!ClassStack.empty() && "No lexed method stacks!");
1444
0
    return *ClassStack.top();
1445
9.00M
  }
1446
1447
  /// RAII object used to manage the parsing of a class definition.
1448
  class ParsingClassDefinition {
1449
    Parser &P;
1450
    bool Popped;
1451
    Sema::ParsingClassState State;
1452
1453
  public:
1454
    ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass,
1455
                           bool IsInterface)
1456
      : P(P), Popped(false),
1457
672k
        State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
1458
672k
    }
1459
1460
    /// Pop this class of the stack.
1461
672k
    void Pop() {
1462
672k
      assert(!Popped && "Nested class has already been popped");
1463
0
      Popped = true;
1464
672k
      P.PopParsingClass(State);
1465
672k
    }
1466
1467
672k
    ~ParsingClassDefinition() {
1468
672k
      if (!Popped)
1469
68
        P.PopParsingClass(State);
1470
672k
    }
1471
  };
1472
1473
  /// Contains information about any template-specific
1474
  /// information that has been parsed prior to parsing declaration
1475
  /// specifiers.
1476
  struct ParsedTemplateInfo {
1477
    ParsedTemplateInfo()
1478
177M
      : Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { }
1479
1480
    ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
1481
                       bool isSpecialization,
1482
                       bool lastParameterListWasEmpty = false)
1483
      : Kind(isSpecialization? ExplicitSpecialization : Template),
1484
        TemplateParams(TemplateParams),
1485
1.22M
        LastParameterListWasEmpty(lastParameterListWasEmpty) { }
1486
1487
    explicit ParsedTemplateInfo(SourceLocation ExternLoc,
1488
                                SourceLocation TemplateLoc)
1489
      : Kind(ExplicitInstantiation), TemplateParams(nullptr),
1490
        ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
1491
52.9k
        LastParameterListWasEmpty(false){ }
1492
1493
    /// The kind of template we are parsing.
1494
    enum {
1495
      /// We are not parsing a template at all.
1496
      NonTemplate = 0,
1497
      /// We are parsing a template declaration.
1498
      Template,
1499
      /// We are parsing an explicit specialization.
1500
      ExplicitSpecialization,
1501
      /// We are parsing an explicit instantiation.
1502
      ExplicitInstantiation
1503
    } Kind;
1504
1505
    /// The template parameter lists, for template declarations
1506
    /// and explicit specializations.
1507
    TemplateParameterLists *TemplateParams;
1508
1509
    /// The location of the 'extern' keyword, if any, for an explicit
1510
    /// instantiation
1511
    SourceLocation ExternLoc;
1512
1513
    /// The location of the 'template' keyword, for an explicit
1514
    /// instantiation.
1515
    SourceLocation TemplateLoc;
1516
1517
    /// Whether the last template parameter list was empty.
1518
    bool LastParameterListWasEmpty;
1519
1520
    SourceRange getSourceRange() const LLVM_READONLY;
1521
  };
1522
1523
  // In ParseCXXInlineMethods.cpp.
1524
  struct ReenterTemplateScopeRAII;
1525
  struct ReenterClassScopeRAII;
1526
1527
  void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
1528
  void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
1529
1530
  static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
1531
1532
  Sema::ParsingClassState
1533
  PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface);
1534
  void DeallocateParsedClasses(ParsingClass *Class);
1535
  void PopParsingClass(Sema::ParsingClassState);
1536
1537
  enum CachedInitKind {
1538
    CIK_DefaultArgument,
1539
    CIK_DefaultInitializer
1540
  };
1541
1542
  NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS,
1543
                                     ParsedAttributes &AccessAttrs,
1544
                                     ParsingDeclarator &D,
1545
                                     const ParsedTemplateInfo &TemplateInfo,
1546
                                     const VirtSpecifiers &VS,
1547
                                     SourceLocation PureSpecLoc);
1548
  void ParseCXXNonStaticMemberInitializer(Decl *VarD);
1549
  void ParseLexedAttributes(ParsingClass &Class);
1550
  void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1551
                               bool EnterScope, bool OnDefinition);
1552
  void ParseLexedAttribute(LateParsedAttribute &LA,
1553
                           bool EnterScope, bool OnDefinition);
1554
  void ParseLexedMethodDeclarations(ParsingClass &Class);
1555
  void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
1556
  void ParseLexedMethodDefs(ParsingClass &Class);
1557
  void ParseLexedMethodDef(LexedMethod &LM);
1558
  void ParseLexedMemberInitializers(ParsingClass &Class);
1559
  void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
1560
  void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod);
1561
  void ParseLexedPragmas(ParsingClass &Class);
1562
  void ParseLexedPragma(LateParsedPragma &LP);
1563
  bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
1564
  bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK);
1565
  bool ConsumeAndStoreConditional(CachedTokens &Toks);
1566
  bool ConsumeAndStoreUntil(tok::TokenKind T1,
1567
                            CachedTokens &Toks,
1568
                            bool StopAtSemi = true,
1569
1.83M
                            bool ConsumeFinalToken = true) {
1570
1.83M
    return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
1571
1.83M
  }
1572
  bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
1573
                            CachedTokens &Toks,
1574
                            bool StopAtSemi = true,
1575
                            bool ConsumeFinalToken = true);
1576
1577
  //===--------------------------------------------------------------------===//
1578
  // C99 6.9: External Definitions.
1579
  DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
1580
                                          ParsingDeclSpec *DS = nullptr);
1581
  bool isDeclarationAfterDeclarator();
1582
  bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
1583
  DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(
1584
                                                  ParsedAttributesWithRange &attrs,
1585
                                                  ParsingDeclSpec *DS = nullptr,
1586
                                                  AccessSpecifier AS = AS_none);
1587
  DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
1588
                                                ParsingDeclSpec &DS,
1589
                                                AccessSpecifier AS);
1590
1591
  void SkipFunctionBody();
1592
  Decl *ParseFunctionDefinition(ParsingDeclarator &D,
1593
                 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1594
                 LateParsedAttrList *LateParsedAttrs = nullptr);
1595
  void ParseKNRParamDeclarations(Declarator &D);
1596
  // EndLoc is filled with the location of the last token of the simple-asm.
1597
  ExprResult ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc);
1598
  ExprResult ParseAsmStringLiteral(bool ForAsmLabel);
1599
1600
  // Objective-C External Declarations
1601
  void MaybeSkipAttributes(tok::ObjCKeywordKind Kind);
1602
  DeclGroupPtrTy ParseObjCAtDirectives(ParsedAttributesWithRange &Attrs);
1603
  DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
1604
  Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
1605
                                        ParsedAttributes &prefixAttrs);
1606
  class ObjCTypeParamListScope;
1607
  ObjCTypeParamList *parseObjCTypeParamList();
1608
  ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs(
1609
      ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
1610
      SmallVectorImpl<IdentifierLocPair> &protocolIdents,
1611
      SourceLocation &rAngleLoc, bool mayBeProtocolList = true);
1612
1613
  void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
1614
                                        BalancedDelimiterTracker &T,
1615
                                        SmallVectorImpl<Decl *> &AllIvarDecls,
1616
                                        bool RBraceMissing);
1617
  void ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1618
                                       tok::ObjCKeywordKind visibility,
1619
                                       SourceLocation atLoc);
1620
  bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P,
1621
                                   SmallVectorImpl<SourceLocation> &PLocs,
1622
                                   bool WarnOnDeclarations,
1623
                                   bool ForObjCContainer,
1624
                                   SourceLocation &LAngleLoc,
1625
                                   SourceLocation &EndProtoLoc,
1626
                                   bool consumeLastToken);
1627
1628
  /// Parse the first angle-bracket-delimited clause for an
1629
  /// Objective-C object or object pointer type, which may be either
1630
  /// type arguments or protocol qualifiers.
1631
  void parseObjCTypeArgsOrProtocolQualifiers(
1632
         ParsedType baseType,
1633
         SourceLocation &typeArgsLAngleLoc,
1634
         SmallVectorImpl<ParsedType> &typeArgs,
1635
         SourceLocation &typeArgsRAngleLoc,
1636
         SourceLocation &protocolLAngleLoc,
1637
         SmallVectorImpl<Decl *> &protocols,
1638
         SmallVectorImpl<SourceLocation> &protocolLocs,
1639
         SourceLocation &protocolRAngleLoc,
1640
         bool consumeLastToken,
1641
         bool warnOnIncompleteProtocols);
1642
1643
  /// Parse either Objective-C type arguments or protocol qualifiers; if the
1644
  /// former, also parse protocol qualifiers afterward.
1645
  void parseObjCTypeArgsAndProtocolQualifiers(
1646
         ParsedType baseType,
1647
         SourceLocation &typeArgsLAngleLoc,
1648
         SmallVectorImpl<ParsedType> &typeArgs,
1649
         SourceLocation &typeArgsRAngleLoc,
1650
         SourceLocation &protocolLAngleLoc,
1651
         SmallVectorImpl<Decl *> &protocols,
1652
         SmallVectorImpl<SourceLocation> &protocolLocs,
1653
         SourceLocation &protocolRAngleLoc,
1654
         bool consumeLastToken);
1655
1656
  /// Parse a protocol qualifier type such as '<NSCopying>', which is
1657
  /// an anachronistic way of writing 'id<NSCopying>'.
1658
  TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc);
1659
1660
  /// Parse Objective-C type arguments and protocol qualifiers, extending the
1661
  /// current type with the parsed result.
1662
  TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc,
1663
                                                    ParsedType type,
1664
                                                    bool consumeLastToken,
1665
                                                    SourceLocation &endLoc);
1666
1667
  void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
1668
                                  Decl *CDecl);
1669
  DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
1670
                                                ParsedAttributes &prefixAttrs);
1671
1672
  struct ObjCImplParsingDataRAII {
1673
    Parser &P;
1674
    Decl *Dcl;
1675
    bool HasCFunction;
1676
    typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer;
1677
    LateParsedObjCMethodContainer LateParsedObjCMethods;
1678
1679
    ObjCImplParsingDataRAII(Parser &parser, Decl *D)
1680
5.33k
      : P(parser), Dcl(D), HasCFunction(false) {
1681
5.33k
      P.CurParsedObjCImpl = this;
1682
5.33k
      Finished = false;
1683
5.33k
    }
1684
    ~ObjCImplParsingDataRAII();
1685
1686
    void finish(SourceRange AtEnd);
1687
20.0k
    bool isFinished() const { return Finished; }
1688
1689
  private:
1690
    bool Finished;
1691
  };
1692
  ObjCImplParsingDataRAII *CurParsedObjCImpl;
1693
  void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl);
1694
1695
  DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc,
1696
                                                      ParsedAttributes &Attrs);
1697
  DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
1698
  Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
1699
  Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
1700
  Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
1701
1702
  IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
1703
  // Definitions for Objective-c context sensitive keywords recognition.
1704
  enum ObjCTypeQual {
1705
    objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
1706
    objc_nonnull, objc_nullable, objc_null_unspecified,
1707
    objc_NumQuals
1708
  };
1709
  IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
1710
1711
  bool isTokIdentifier_in() const;
1712
1713
  ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx,
1714
                               ParsedAttributes *ParamAttrs);
1715
  Decl *ParseObjCMethodPrototype(
1716
            tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1717
            bool MethodDefinition = true);
1718
  Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
1719
            tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1720
            bool MethodDefinition=true);
1721
  void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
1722
1723
  Decl *ParseObjCMethodDefinition();
1724
1725
public:
1726
  //===--------------------------------------------------------------------===//
1727
  // C99 6.5: Expressions.
1728
1729
  /// TypeCastState - State whether an expression is or may be a type cast.
1730
  enum TypeCastState {
1731
    NotTypeCast = 0,
1732
    MaybeTypeCast,
1733
    IsTypeCast
1734
  };
1735
1736
  ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast);
1737
  ExprResult ParseConstantExpressionInExprEvalContext(
1738
      TypeCastState isTypeCast = NotTypeCast);
1739
  ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast);
1740
  ExprResult ParseCaseExpression(SourceLocation CaseLoc);
1741
  ExprResult ParseConstraintExpression();
1742
  ExprResult
1743
  ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause);
1744
  ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause);
1745
  // Expr that doesn't include commas.
1746
  ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast);
1747
1748
  ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1749
                                  unsigned &NumLineToksConsumed,
1750
                                  bool IsUnevaluated);
1751
1752
  ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
1753
1754
private:
1755
  ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
1756
1757
  ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
1758
1759
  ExprResult ParseRHSOfBinaryExpression(ExprResult LHS,
1760
                                        prec::Level MinPrec);
1761
  /// Control what ParseCastExpression will parse.
1762
  enum CastParseKind {
1763
    AnyCastExpr = 0,
1764
    UnaryExprOnly,
1765
    PrimaryExprOnly
1766
  };
1767
  ExprResult ParseCastExpression(CastParseKind ParseKind,
1768
                                 bool isAddressOfOperand,
1769
                                 bool &NotCastExpr,
1770
                                 TypeCastState isTypeCast,
1771
                                 bool isVectorLiteral = false,
1772
                                 bool *NotPrimaryExpression = nullptr);
1773
  ExprResult ParseCastExpression(CastParseKind ParseKind,
1774
                                 bool isAddressOfOperand = false,
1775
                                 TypeCastState isTypeCast = NotTypeCast,
1776
                                 bool isVectorLiteral = false,
1777
                                 bool *NotPrimaryExpression = nullptr);
1778
1779
  /// Returns true if the next token cannot start an expression.
1780
  bool isNotExpressionStart();
1781
1782
  /// Returns true if the next token would start a postfix-expression
1783
  /// suffix.
1784
126k
  bool isPostfixExpressionSuffixStart() {
1785
126k
    tok::TokenKind K = Tok.getKind();
1786
126k
    return (K == tok::l_square || 
K == tok::l_paren118k
||
1787
126k
            
K == tok::period117k
||
K == tok::arrow110k
||
1788
126k
            
K == tok::plusplus95.8k
||
K == tok::minusminus95.8k
);
1789
126k
  }
1790
1791
  bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less);
1792
  void checkPotentialAngleBracket(ExprResult &PotentialTemplateName);
1793
  bool checkPotentialAngleBracketDelimiter(const AngleBracketTracker::Loc &,
1794
                                           const Token &OpToken);
1795
5.78M
  bool checkPotentialAngleBracketDelimiter(const Token &OpToken) {
1796
5.78M
    if (auto *Info = AngleBrackets.getCurrent(*this))
1797
65
      return checkPotentialAngleBracketDelimiter(*Info, OpToken);
1798
5.78M
    return false;
1799
5.78M
  }
1800
1801
  ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
1802
  ExprResult ParseUnaryExprOrTypeTraitExpression();
1803
  ExprResult ParseBuiltinPrimaryExpression();
1804
  ExprResult ParseSYCLUniqueStableNameExpression();
1805
1806
  ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1807
                                                     bool &isCastExpr,
1808
                                                     ParsedType &CastTy,
1809
                                                     SourceRange &CastRange);
1810
1811
  typedef SmallVector<SourceLocation, 20> CommaLocsTy;
1812
1813
  /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1814
  bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
1815
                           SmallVectorImpl<SourceLocation> &CommaLocs,
1816
                           llvm::function_ref<void()> ExpressionStarts =
1817
                               llvm::function_ref<void()>());
1818
1819
  /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
1820
  /// used for misc language extensions.
1821
  bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
1822
                                 SmallVectorImpl<SourceLocation> &CommaLocs);
1823
1824
1825
  /// ParenParseOption - Control what ParseParenExpression will parse.
1826
  enum ParenParseOption {
1827
    SimpleExpr,      // Only parse '(' expression ')'
1828
    FoldExpr,        // Also allow fold-expression <anything>
1829
    CompoundStmt,    // Also allow '(' compound-statement ')'
1830
    CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
1831
    CastExpr         // Also allow '(' type-name ')' <anything>
1832
  };
1833
  ExprResult ParseParenExpression(ParenParseOption &ExprType,
1834
                                        bool stopIfCastExpr,
1835
                                        bool isTypeCast,
1836
                                        ParsedType &CastTy,
1837
                                        SourceLocation &RParenLoc);
1838
1839
  ExprResult ParseCXXAmbiguousParenExpression(
1840
      ParenParseOption &ExprType, ParsedType &CastTy,
1841
      BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt);
1842
  ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
1843
                                                  SourceLocation LParenLoc,
1844
                                                  SourceLocation RParenLoc);
1845
1846
  ExprResult ParseGenericSelectionExpression();
1847
1848
  ExprResult ParseObjCBoolLiteral();
1849
1850
  ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T);
1851
1852
  //===--------------------------------------------------------------------===//
1853
  // C++ Expressions
1854
  ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
1855
                                     Token &Replacement);
1856
  ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
1857
1858
  bool areTokensAdjacent(const Token &A, const Token &B);
1859
1860
  void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
1861
                                  bool EnteringContext, IdentifierInfo &II,
1862
                                  CXXScopeSpec &SS);
1863
1864
  bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
1865
                                      ParsedType ObjectType,
1866
                                      bool ObjectHasErrors,
1867
                                      bool EnteringContext,
1868
                                      bool *MayBePseudoDestructor = nullptr,
1869
                                      bool IsTypename = false,
1870
                                      IdentifierInfo **LastII = nullptr,
1871
                                      bool OnlyNamespace = false,
1872
                                      bool InUsingDeclaration = false);
1873
1874
  //===--------------------------------------------------------------------===//
1875
  // C++11 5.1.2: Lambda expressions
1876
1877
  /// Result of tentatively parsing a lambda-introducer.
1878
  enum class LambdaIntroducerTentativeParse {
1879
    /// This appears to be a lambda-introducer, which has been fully parsed.
1880
    Success,
1881
    /// This is a lambda-introducer, but has not been fully parsed, and this
1882
    /// function needs to be called again to parse it.
1883
    Incomplete,
1884
    /// This is definitely an Objective-C message send expression, rather than
1885
    /// a lambda-introducer, attribute-specifier, or array designator.
1886
    MessageSend,
1887
    /// This is not a lambda-introducer.
1888
    Invalid,
1889
  };
1890
1891
  // [...] () -> type {...}
1892
  ExprResult ParseLambdaExpression();
1893
  ExprResult TryParseLambdaExpression();
1894
  bool
1895
  ParseLambdaIntroducer(LambdaIntroducer &Intro,
1896
                        LambdaIntroducerTentativeParse *Tentative = nullptr);
1897
  ExprResult ParseLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro);
1898
1899
  //===--------------------------------------------------------------------===//
1900
  // C++ 5.2p1: C++ Casts
1901
  ExprResult ParseCXXCasts();
1902
1903
  /// Parse a __builtin_bit_cast(T, E), used to implement C++2a std::bit_cast.
1904
  ExprResult ParseBuiltinBitCast();
1905
1906
  //===--------------------------------------------------------------------===//
1907
  // C++ 5.2p1: C++ Type Identification
1908
  ExprResult ParseCXXTypeid();
1909
1910
  //===--------------------------------------------------------------------===//
1911
  //  C++ : Microsoft __uuidof Expression
1912
  ExprResult ParseCXXUuidof();
1913
1914
  //===--------------------------------------------------------------------===//
1915
  // C++ 5.2.4: C++ Pseudo-Destructor Expressions
1916
  ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1917
                                            tok::TokenKind OpKind,
1918
                                            CXXScopeSpec &SS,
1919
                                            ParsedType ObjectType);
1920
1921
  //===--------------------------------------------------------------------===//
1922
  // C++ 9.3.2: C++ 'this' pointer
1923
  ExprResult ParseCXXThis();
1924
1925
  //===--------------------------------------------------------------------===//
1926
  // C++ 15: C++ Throw Expression
1927
  ExprResult ParseThrowExpression();
1928
1929
  ExceptionSpecificationType tryParseExceptionSpecification(
1930
                    bool Delayed,
1931
                    SourceRange &SpecificationRange,
1932
                    SmallVectorImpl<ParsedType> &DynamicExceptions,
1933
                    SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
1934
                    ExprResult &NoexceptExpr,
1935
                    CachedTokens *&ExceptionSpecTokens);
1936
1937
  // EndLoc is filled with the location of the last token of the specification.
1938
  ExceptionSpecificationType ParseDynamicExceptionSpecification(
1939
                                  SourceRange &SpecificationRange,
1940
                                  SmallVectorImpl<ParsedType> &Exceptions,
1941
                                  SmallVectorImpl<SourceRange> &Ranges);
1942
1943
  //===--------------------------------------------------------------------===//
1944
  // C++0x 8: Function declaration trailing-return-type
1945
  TypeResult ParseTrailingReturnType(SourceRange &Range,
1946
                                     bool MayBeFollowedByDirectInit);
1947
1948
  //===--------------------------------------------------------------------===//
1949
  // C++ 2.13.5: C++ Boolean Literals
1950
  ExprResult ParseCXXBoolLiteral();
1951
1952
  //===--------------------------------------------------------------------===//
1953
  // C++ 5.2.3: Explicit type conversion (functional notation)
1954
  ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
1955
1956
  /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1957
  /// This should only be called when the current token is known to be part of
1958
  /// simple-type-specifier.
1959
  void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
1960
1961
  bool ParseCXXTypeSpecifierSeq(DeclSpec &DS);
1962
1963
  //===--------------------------------------------------------------------===//
1964
  // C++ 5.3.4 and 5.3.5: C++ new and delete
1965
  bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs,
1966
                                   Declarator &D);
1967
  void ParseDirectNewDeclarator(Declarator &D);
1968
  ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
1969
  ExprResult ParseCXXDeleteExpression(bool UseGlobal,
1970
                                            SourceLocation Start);
1971
1972
  //===--------------------------------------------------------------------===//
1973
  // C++ if/switch/while/for condition expression.
1974
  struct ForRangeInfo;
1975
  Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt,
1976
                                          SourceLocation Loc,
1977
                                          Sema::ConditionKind CK,
1978
                                          ForRangeInfo *FRI = nullptr,
1979
                                          bool EnterForConditionScope = false);
1980
1981
  //===--------------------------------------------------------------------===//
1982
  // C++ Coroutines
1983
1984
  ExprResult ParseCoyieldExpression();
1985
1986
  //===--------------------------------------------------------------------===//
1987
  // C++ Concepts
1988
1989
  ExprResult ParseRequiresExpression();
1990
  void ParseTrailingRequiresClause(Declarator &D);
1991
1992
  //===--------------------------------------------------------------------===//
1993
  // C99 6.7.8: Initialization.
1994
1995
  /// ParseInitializer
1996
  ///       initializer: [C99 6.7.8]
1997
  ///         assignment-expression
1998
  ///         '{' ...
1999
1.28M
  ExprResult ParseInitializer() {
2000
1.28M
    if (Tok.isNot(tok::l_brace))
2001
1.20M
      return ParseAssignmentExpression();
2002
81.7k
    return ParseBraceInitializer();
2003
1.28M
  }
2004
  bool MayBeDesignationStart();
2005
  ExprResult ParseBraceInitializer();
2006
  struct DesignatorCompletionInfo {
2007
    SmallVectorImpl<Expr *> &InitExprs;
2008
    QualType PreferredBaseType;
2009
  };
2010
  ExprResult ParseInitializerWithPotentialDesignator(DesignatorCompletionInfo);
2011
2012
  //===--------------------------------------------------------------------===//
2013
  // clang Expressions
2014
2015
  ExprResult ParseBlockLiteralExpression();  // ^{...}
2016
2017
  //===--------------------------------------------------------------------===//
2018
  // Objective-C Expressions
2019
  ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
2020
  ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
2021
  ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
2022
  ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
2023
  ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
2024
  ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
2025
  ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
2026
  ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
2027
  ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
2028
  ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
2029
  ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
2030
  bool isSimpleObjCMessageExpression();
2031
  ExprResult ParseObjCMessageExpression();
2032
  ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
2033
                                            SourceLocation SuperLoc,
2034
                                            ParsedType ReceiverType,
2035
                                            Expr *ReceiverExpr);
2036
  ExprResult ParseAssignmentExprWithObjCMessageExprStart(
2037
      SourceLocation LBracloc, SourceLocation SuperLoc,
2038
      ParsedType ReceiverType, Expr *ReceiverExpr);
2039
  bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
2040
2041
  //===--------------------------------------------------------------------===//
2042
  // C99 6.8: Statements and Blocks.
2043
2044
  /// A SmallVector of statements, with stack size 32 (as that is the only one
2045
  /// used.)
2046
  typedef SmallVector<Stmt*, 32> StmtVector;
2047
  /// A SmallVector of expressions, with stack size 12 (the maximum used.)
2048
  typedef SmallVector<Expr*, 12> ExprVector;
2049
  /// A SmallVector of types.
2050
  typedef SmallVector<ParsedType, 12> TypeVector;
2051
2052
  StmtResult
2053
  ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
2054
                 ParsedStmtContext StmtCtx = ParsedStmtContext::SubStmt);
2055
  StmtResult ParseStatementOrDeclaration(
2056
      StmtVector &Stmts, ParsedStmtContext StmtCtx,
2057
      SourceLocation *TrailingElseLoc = nullptr);
2058
  StmtResult ParseStatementOrDeclarationAfterAttributes(
2059
                                         StmtVector &Stmts,
2060
                                         ParsedStmtContext StmtCtx,
2061
                                         SourceLocation *TrailingElseLoc,
2062
                                         ParsedAttributesWithRange &Attrs);
2063
  StmtResult ParseExprStatement(ParsedStmtContext StmtCtx);
2064
  StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs,
2065
                                   ParsedStmtContext StmtCtx);
2066
  StmtResult ParseCaseStatement(ParsedStmtContext StmtCtx,
2067
                                bool MissingCase = false,
2068
                                ExprResult Expr = ExprResult());
2069
  StmtResult ParseDefaultStatement(ParsedStmtContext StmtCtx);
2070
  StmtResult ParseCompoundStatement(bool isStmtExpr = false);
2071
  StmtResult ParseCompoundStatement(bool isStmtExpr,
2072
                                    unsigned ScopeFlags);
2073
  void ParseCompoundStatementLeadingPragmas();
2074
  bool ConsumeNullStmt(StmtVector &Stmts);
2075
  StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
2076
  bool ParseParenExprOrCondition(StmtResult *InitStmt,
2077
                                 Sema::ConditionResult &CondResult,
2078
                                 SourceLocation Loc, Sema::ConditionKind CK,
2079
                                 SourceLocation *LParenLoc = nullptr,
2080
                                 SourceLocation *RParenLoc = nullptr);
2081
  StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
2082
  StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
2083
  StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
2084
  StmtResult ParseDoStatement();
2085
  StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
2086
  StmtResult ParseGotoStatement();
2087
  StmtResult ParseContinueStatement();
2088
  StmtResult ParseBreakStatement();
2089
  StmtResult ParseReturnStatement();
2090
  StmtResult ParseAsmStatement(bool &msAsm);
2091
  StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
2092
  StmtResult ParsePragmaLoopHint(StmtVector &Stmts,
2093
                                 ParsedStmtContext StmtCtx,
2094
                                 SourceLocation *TrailingElseLoc,
2095
                                 ParsedAttributesWithRange &Attrs);
2096
2097
  /// Describes the behavior that should be taken for an __if_exists
2098
  /// block.
2099
  enum IfExistsBehavior {
2100
    /// Parse the block; this code is always used.
2101
    IEB_Parse,
2102
    /// Skip the block entirely; this code is never used.
2103
    IEB_Skip,
2104
    /// Parse the block as a dependent block, which may be used in
2105
    /// some template instantiations but not others.
2106
    IEB_Dependent
2107
  };
2108
2109
  /// Describes the condition of a Microsoft __if_exists or
2110
  /// __if_not_exists block.
2111
  struct IfExistsCondition {
2112
    /// The location of the initial keyword.
2113
    SourceLocation KeywordLoc;
2114
    /// Whether this is an __if_exists block (rather than an
2115
    /// __if_not_exists block).
2116
    bool IsIfExists;
2117
2118
    /// Nested-name-specifier preceding the name.
2119
    CXXScopeSpec SS;
2120
2121
    /// The name we're looking for.
2122
    UnqualifiedId Name;
2123
2124
    /// The behavior of this __if_exists or __if_not_exists block
2125
    /// should.
2126
    IfExistsBehavior Behavior;
2127
  };
2128
2129
  bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
2130
  void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
2131
  void ParseMicrosoftIfExistsExternalDeclaration();
2132
  void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
2133
                                              ParsedAttributes &AccessAttrs,
2134
                                              AccessSpecifier &CurAS);
2135
  bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
2136
                                              bool &InitExprsOk);
2137
  bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
2138
                           SmallVectorImpl<Expr *> &Constraints,
2139
                           SmallVectorImpl<Expr *> &Exprs);
2140
2141
  //===--------------------------------------------------------------------===//
2142
  // C++ 6: Statements and Blocks
2143
2144
  StmtResult ParseCXXTryBlock();
2145
  StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
2146
  StmtResult ParseCXXCatchBlock(bool FnCatch = false);
2147
2148
  //===--------------------------------------------------------------------===//
2149
  // MS: SEH Statements and Blocks
2150
2151
  StmtResult ParseSEHTryBlock();
2152
  StmtResult ParseSEHExceptBlock(SourceLocation Loc);
2153
  StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
2154
  StmtResult ParseSEHLeaveStatement();
2155
2156
  //===--------------------------------------------------------------------===//
2157
  // Objective-C Statements
2158
2159
  StmtResult ParseObjCAtStatement(SourceLocation atLoc,
2160
                                  ParsedStmtContext StmtCtx);
2161
  StmtResult ParseObjCTryStmt(SourceLocation atLoc);
2162
  StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
2163
  StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
2164
  StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
2165
2166
2167
  //===--------------------------------------------------------------------===//
2168
  // C99 6.7: Declarations.
2169
2170
  /// A context for parsing declaration specifiers.  TODO: flesh this
2171
  /// out, there are other significant restrictions on specifiers than
2172
  /// would be best implemented in the parser.
2173
  enum class DeclSpecContext {
2174
    DSC_normal, // normal context
2175
    DSC_class,  // class context, enables 'friend'
2176
    DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
2177
    DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
2178
    DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration
2179
    DSC_top_level, // top-level/namespace declaration context
2180
    DSC_template_param, // template parameter context
2181
    DSC_template_type_arg, // template type argument context
2182
    DSC_objc_method_result, // ObjC method result context, enables 'instancetype'
2183
    DSC_condition // condition declaration context
2184
  };
2185
2186
  /// Is this a context in which we are parsing just a type-specifier (or
2187
  /// trailing-type-specifier)?
2188
14.5M
  static bool isTypeSpecifier(DeclSpecContext DSC) {
2189
14.5M
    switch (DSC) {
2190
8.53M
    case DeclSpecContext::DSC_normal:
2191
8.53M
    case DeclSpecContext::DSC_template_param:
2192
8.74M
    case DeclSpecContext::DSC_class:
2193
9.51M
    case DeclSpecContext::DSC_top_level:
2194
10.1M
    case DeclSpecContext::DSC_objc_method_result:
2195
10.1M
    case DeclSpecContext::DSC_condition:
2196
10.1M
      return false;
2197
2198
3.78M
    case DeclSpecContext::DSC_template_type_arg:
2199
4.26M
    case DeclSpecContext::DSC_type_specifier:
2200
4.28M
    case DeclSpecContext::DSC_trailing:
2201
4.35M
    case DeclSpecContext::DSC_alias_declaration:
2202
4.35M
      return true;
2203
14.5M
    }
2204
0
    llvm_unreachable("Missing DeclSpecContext case");
2205
0
  }
2206
2207
  /// Whether a defining-type-specifier is permitted in a given context.
2208
  enum class AllowDefiningTypeSpec {
2209
    /// The grammar doesn't allow a defining-type-specifier here, and we must
2210
    /// not parse one (eg, because a '{' could mean something else).
2211
    No,
2212
    /// The grammar doesn't allow a defining-type-specifier here, but we permit
2213
    /// one for error recovery purposes. Sema will reject.
2214
    NoButErrorRecovery,
2215
    /// The grammar allows a defining-type-specifier here, even though it's
2216
    /// always invalid. Sema will reject.
2217
    YesButInvalid,
2218
    /// The grammar allows a defining-type-specifier here, and one can be valid.
2219
    Yes
2220
  };
2221
2222
  /// Is this a context in which we are parsing defining-type-specifiers (and
2223
  /// so permit class and enum definitions in addition to non-defining class and
2224
  /// enum elaborated-type-specifiers)?
2225
  static AllowDefiningTypeSpec
2226
2.71M
  isDefiningTypeSpecifierContext(DeclSpecContext DSC) {
2227
2.71M
    switch (DSC) {
2228
613k
    case DeclSpecContext::DSC_normal:
2229
872k
    case DeclSpecContext::DSC_class:
2230
2.71M
    case DeclSpecContext::DSC_top_level:
2231
2.71M
    case DeclSpecContext::DSC_alias_declaration:
2232
2.71M
    case DeclSpecContext::DSC_objc_method_result:
2233
2.71M
      return AllowDefiningTypeSpec::Yes;
2234
2235
27
    case DeclSpecContext::DSC_condition:
2236
53
    case DeclSpecContext::DSC_template_param:
2237
53
      return AllowDefiningTypeSpec::YesButInvalid;
2238
2239
377
    case DeclSpecContext::DSC_template_type_arg:
2240
1.24k
    case DeclSpecContext::DSC_type_specifier:
2241
1.24k
      return AllowDefiningTypeSpec::NoButErrorRecovery;
2242
2243
61
    case DeclSpecContext::DSC_trailing:
2244
61
      return AllowDefiningTypeSpec::No;
2245
2.71M
    }
2246
0
    llvm_unreachable("Missing DeclSpecContext case");
2247
0
  }
2248
2249
  /// Is this a context in which an opaque-enum-declaration can appear?
2250
859k
  static bool isOpaqueEnumDeclarationContext(DeclSpecContext DSC) {
2251
859k
    switch (DSC) {
2252
402k
    case DeclSpecContext::DSC_normal:
2253
414k
    case DeclSpecContext::DSC_class:
2254
859k
    case DeclSpecContext::DSC_top_level:
2255
859k
      return true;
2256
2257
5
    case DeclSpecContext::DSC_alias_declaration:
2258
5
    case DeclSpecContext::DSC_objc_method_result:
2259
6
    case DeclSpecContext::DSC_condition:
2260
9
    case DeclSpecContext::DSC_template_param:
2261
16
    case DeclSpecContext::DSC_template_type_arg:
2262
57
    case DeclSpecContext::DSC_type_specifier:
2263
112
    case DeclSpecContext::DSC_trailing:
2264
112
      return false;
2265
859k
    }
2266
0
    llvm_unreachable("Missing DeclSpecContext case");
2267
0
  }
2268
2269
  /// Is this a context in which we can perform class template argument
2270
  /// deduction?
2271
90.6M
  static bool isClassTemplateDeductionContext(DeclSpecContext DSC) {
2272
90.6M
    switch (DSC) {
2273
60.5M
    case DeclSpecContext::DSC_normal:
2274
60.6M
    case DeclSpecContext::DSC_template_param:
2275
61.8M
    case DeclSpecContext::DSC_class:
2276
90.1M
    case DeclSpecContext::DSC_top_level:
2277
90.1M
    case DeclSpecContext::DSC_condition:
2278
90.5M
    case DeclSpecContext::DSC_type_specifier:
2279
90.5M
      return true;
2280
2281
642
    case DeclSpecContext::DSC_objc_method_result:
2282
81.3k
    case DeclSpecContext::DSC_template_type_arg:
2283
82.7k
    case DeclSpecContext::DSC_trailing:
2284
95.4k
    case DeclSpecContext::DSC_alias_declaration:
2285
95.4k
      return false;
2286
90.6M
    }
2287
0
    llvm_unreachable("Missing DeclSpecContext case");
2288
0
  }
2289
2290
  /// Information on a C++0x for-range-initializer found while parsing a
2291
  /// declaration which turns out to be a for-range-declaration.
2292
  struct ForRangeInit {
2293
    SourceLocation ColonLoc;
2294
    ExprResult RangeExpr;
2295
2296
1.27M
    bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
2297
  };
2298
  struct ForRangeInfo : ForRangeInit {
2299
    StmtResult LoopVar;
2300
  };
2301
2302
  DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context,
2303
                                  SourceLocation &DeclEnd,
2304
                                  ParsedAttributesWithRange &attrs,
2305
                                  SourceLocation *DeclSpecStart = nullptr);
2306
  DeclGroupPtrTy
2307
  ParseSimpleDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd,
2308
                         ParsedAttributesWithRange &attrs, bool RequireSemi,
2309
                         ForRangeInit *FRI = nullptr,
2310
                         SourceLocation *DeclSpecStart = nullptr);
2311
  bool MightBeDeclarator(DeclaratorContext Context);
2312
  DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context,
2313
                                SourceLocation *DeclEnd = nullptr,
2314
                                ForRangeInit *FRI = nullptr);
2315
  Decl *ParseDeclarationAfterDeclarator(Declarator &D,
2316
               const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
2317
  bool ParseAsmAttributesAfterDeclarator(Declarator &D);
2318
  Decl *ParseDeclarationAfterDeclaratorAndAttributes(
2319
      Declarator &D,
2320
      const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2321
      ForRangeInit *FRI = nullptr);
2322
  Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
2323
  Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
2324
2325
  /// When in code-completion, skip parsing of the function/method body
2326
  /// unless the body contains the code-completion point.
2327
  ///
2328
  /// \returns true if the function body was skipped.
2329
  bool trySkippingFunctionBody();
2330
2331
  bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2332
                        const ParsedTemplateInfo &TemplateInfo,
2333
                        AccessSpecifier AS, DeclSpecContext DSC,
2334
                        ParsedAttributesWithRange &Attrs);
2335
  DeclSpecContext
2336
  getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context);
2337
  void ParseDeclarationSpecifiers(
2338
      DeclSpec &DS,
2339
      const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2340
      AccessSpecifier AS = AS_none,
2341
      DeclSpecContext DSC = DeclSpecContext::DSC_normal,
2342
      LateParsedAttrList *LateAttrs = nullptr);
2343
  bool DiagnoseMissingSemiAfterTagDefinition(
2344
      DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext,
2345
      LateParsedAttrList *LateAttrs = nullptr);
2346
2347
  void ParseSpecifierQualifierList(
2348
      DeclSpec &DS, AccessSpecifier AS = AS_none,
2349
      DeclSpecContext DSC = DeclSpecContext::DSC_normal);
2350
2351
  void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
2352
                                  DeclaratorContext Context);
2353
2354
  void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
2355
                          const ParsedTemplateInfo &TemplateInfo,
2356
                          AccessSpecifier AS, DeclSpecContext DSC);
2357
  void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
2358
  void ParseStructUnionBody(SourceLocation StartLoc, DeclSpec::TST TagType,
2359
                            RecordDecl *TagDecl);
2360
2361
  void ParseStructDeclaration(
2362
      ParsingDeclSpec &DS,
2363
      llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback);
2364
2365
  bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
2366
  bool isTypeSpecifierQualifier();
2367
2368
  /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
2369
  /// is definitely a type-specifier.  Return false if it isn't part of a type
2370
  /// specifier or if we're not sure.
2371
  bool isKnownToBeTypeSpecifier(const Token &Tok) const;
2372
2373
  /// Return true if we know that we are definitely looking at a
2374
  /// decl-specifier, and isn't part of an expression such as a function-style
2375
  /// cast. Return false if it's no a decl-specifier, or we're not sure.
2376
41.9k
  bool isKnownToBeDeclarationSpecifier() {
2377
41.9k
    if (getLangOpts().CPlusPlus)
2378
41.4k
      return isCXXDeclarationSpecifier() == TPResult::True;
2379
574
    return isDeclarationSpecifier(true);
2380
41.9k
  }
2381
2382
  /// isDeclarationStatement - Disambiguates between a declaration or an
2383
  /// expression statement, when parsing function bodies.
2384
  /// Returns true for declaration, false for expression.
2385
3.24M
  bool isDeclarationStatement() {
2386
3.24M
    if (getLangOpts().CPlusPlus)
2387
2.17M
      return isCXXDeclarationStatement();
2388
1.07M
    return isDeclarationSpecifier(true);
2389
3.24M
  }
2390
2391
  /// isForInitDeclaration - Disambiguates between a declaration or an
2392
  /// expression in the context of the C 'clause-1' or the C++
2393
  // 'for-init-statement' part of a 'for' statement.
2394
  /// Returns true for declaration, false for expression.
2395
150k
  bool isForInitDeclaration() {
2396
150k
    if (getLangOpts().OpenMP)
2397
111k
      Actions.startOpenMPLoop();
2398
150k
    if (getLangOpts().CPlusPlus)
2399
141k
      return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
2400
8.63k
    return isDeclarationSpecifier(true);
2401
150k
  }
2402
2403
  /// Determine whether this is a C++1z for-range-identifier.
2404
  bool isForRangeIdentifier();
2405
2406
  /// Determine whether we are currently at the start of an Objective-C
2407
  /// class message that appears to be missing the open bracket '['.
2408
  bool isStartOfObjCClassMessageMissingOpenBracket();
2409
2410
  /// Starting with a scope specifier, identifier, or
2411
  /// template-id that refers to the current class, determine whether
2412
  /// this is a constructor declarator.
2413
  bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false);
2414
2415
  /// Specifies the context in which type-id/expression
2416
  /// disambiguation will occur.
2417
  enum TentativeCXXTypeIdContext {
2418
    TypeIdInParens,
2419
    TypeIdUnambiguous,
2420
    TypeIdAsTemplateArgument
2421
  };
2422
2423
2424
  /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
2425
  /// whether the parens contain an expression or a type-id.
2426
  /// Returns true for a type-id and false for an expression.
2427
5.75M
  bool isTypeIdInParens(bool &isAmbiguous) {
2428
5.75M
    if (getLangOpts().CPlusPlus)
2429
1.13M
      return isCXXTypeId(TypeIdInParens, isAmbiguous);
2430
4.61M
    isAmbiguous = false;
2431
4.61M
    return isTypeSpecifierQualifier();
2432
5.75M
  }
2433
36.1k
  bool isTypeIdInParens() {
2434
36.1k
    bool isAmbiguous;
2435
36.1k
    return isTypeIdInParens(isAmbiguous);
2436
36.1k
  }
2437
2438
  /// Checks if the current tokens form type-id or expression.
2439
  /// It is similar to isTypeIdInParens but does not suppose that type-id
2440
  /// is in parenthesis.
2441
190k
  bool isTypeIdUnambiguously() {
2442
190k
    bool IsAmbiguous;
2443
190k
    if (getLangOpts().CPlusPlus)
2444
190k
      return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous);
2445
645
    return isTypeSpecifierQualifier();
2446
190k
  }
2447
2448
  /// isCXXDeclarationStatement - C++-specialized function that disambiguates
2449
  /// between a declaration or an expression statement, when parsing function
2450
  /// bodies. Returns true for declaration, false for expression.
2451
  bool isCXXDeclarationStatement();
2452
2453
  /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
2454
  /// between a simple-declaration or an expression-statement.
2455
  /// If during the disambiguation process a parsing error is encountered,
2456
  /// the function returns true to let the declaration parsing code handle it.
2457
  /// Returns false if the statement is disambiguated as expression.
2458
  bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
2459
2460
  /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
2461
  /// a constructor-style initializer, when parsing declaration statements.
2462
  /// Returns true for function declarator and false for constructor-style
2463
  /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
2464
  /// might be a constructor-style initializer.
2465
  /// If during the disambiguation process a parsing error is encountered,
2466
  /// the function returns true to let the declaration parsing code handle it.
2467
  bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr);
2468
2469
  struct ConditionDeclarationOrInitStatementState;
2470
  enum class ConditionOrInitStatement {
2471
    Expression,    ///< Disambiguated as an expression (either kind).
2472
    ConditionDecl, ///< Disambiguated as the declaration form of condition.
2473
    InitStmtDecl,  ///< Disambiguated as a simple-declaration init-statement.
2474
    ForRangeDecl,  ///< Disambiguated as a for-range declaration.
2475
    Error          ///< Can't be any of the above!
2476
  };
2477
  /// Disambiguates between the different kinds of things that can happen
2478
  /// after 'if (' or 'switch ('. This could be one of two different kinds of
2479
  /// declaration (depending on whether there is a ';' later) or an expression.
2480
  ConditionOrInitStatement
2481
  isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt,
2482
                                           bool CanBeForRangeDecl);
2483
2484
  bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
2485
4.39M
  bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
2486
4.39M
    bool isAmbiguous;
2487
4.39M
    return isCXXTypeId(Context, isAmbiguous);
2488
4.39M
  }
2489
2490
  /// TPResult - Used as the result value for functions whose purpose is to
2491
  /// disambiguate C++ constructs by "tentatively parsing" them.
2492
  enum class TPResult {
2493
    True, False, Ambiguous, Error
2494
  };
2495
2496
  /// Determine whether we could have an enum-base.
2497
  ///
2498
  /// \p AllowSemi If \c true, then allow a ';' after the enum-base; otherwise
2499
  /// only consider this to be an enum-base if the next token is a '{'.
2500
  ///
2501
  /// \return \c false if this cannot possibly be an enum base; \c true
2502
  /// otherwise.
2503
  bool isEnumBase(bool AllowSemi);
2504
2505
  /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a
2506
  /// declaration specifier, TPResult::False if it is not,
2507
  /// TPResult::Ambiguous if it could be either a decl-specifier or a
2508
  /// function-style cast, and TPResult::Error if a parsing error was
2509
  /// encountered. If it could be a braced C++11 function-style cast, returns
2510
  /// BracedCastResult.
2511
  /// Doesn't consume tokens.
2512
  TPResult
2513
  isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False,
2514
                            bool *InvalidAsDeclSpec = nullptr);
2515
2516
  /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
2517
  /// \c TPResult::Ambiguous, determine whether the decl-specifier would be
2518
  /// a type-specifier other than a cv-qualifier.
2519
  bool isCXXDeclarationSpecifierAType();
2520
2521
  /// Determine whether the current token sequence might be
2522
  ///   '<' template-argument-list '>'
2523
  /// rather than a less-than expression.
2524
  TPResult isTemplateArgumentList(unsigned TokensToSkip);
2525
2526
  /// Determine whether an '(' after an 'explicit' keyword is part of a C++20
2527
  /// 'explicit(bool)' declaration, in earlier language modes where that is an
2528
  /// extension.
2529
  TPResult isExplicitBool();
2530
2531
  /// Determine whether an identifier has been tentatively declared as a
2532
  /// non-type. Such tentative declarations should not be found to name a type
2533
  /// during a tentative parse, but also should not be annotated as a non-type.
2534
  bool isTentativelyDeclared(IdentifierInfo *II);
2535
2536
  // "Tentative parsing" functions, used for disambiguation. If a parsing error
2537
  // is encountered they will return TPResult::Error.
2538
  // Returning TPResult::True/False indicates that the ambiguity was
2539
  // resolved and tentative parsing may stop. TPResult::Ambiguous indicates
2540
  // that more tentative parsing is necessary for disambiguation.
2541
  // They all consume tokens, so backtracking should be used after calling them.
2542
2543
  TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
2544
  TPResult TryParseTypeofSpecifier();
2545
  TPResult TryParseProtocolQualifiers();
2546
  TPResult TryParsePtrOperatorSeq();
2547
  TPResult TryParseOperatorId();
2548
  TPResult TryParseInitDeclaratorList();
2549
  TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true,
2550
                              bool mayHaveDirectInit = false);
2551
  TPResult
2552
  TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr,
2553
                                     bool VersusTemplateArg = false);
2554
  TPResult TryParseFunctionDeclarator();
2555
  TPResult TryParseBracketDeclarator();
2556
  TPResult TryConsumeDeclarationSpecifier();
2557
2558
  /// Try to skip a possibly empty sequence of 'attribute-specifier's without
2559
  /// full validation of the syntactic structure of attributes.
2560
  bool TrySkipAttributes();
2561
2562
public:
2563
  TypeResult
2564
  ParseTypeName(SourceRange *Range = nullptr,
2565
                DeclaratorContext Context = DeclaratorContext::TypeName,
2566
                AccessSpecifier AS = AS_none, Decl **OwnedType = nullptr,
2567
                ParsedAttributes *Attrs = nullptr);
2568
2569
private:
2570
  void ParseBlockId(SourceLocation CaretLoc);
2571
2572
  /// Are [[]] attributes enabled?
2573
279M
  bool standardAttributesAllowed() const {
2574
279M
    const LangOptions &LO = getLangOpts();
2575
279M
    return LO.DoubleSquareBracketAttributes;
2576
279M
  }
2577
2578
  // Check for the start of an attribute-specifier-seq in a context where an
2579
  // attribute is not allowed.
2580
602k
  bool CheckProhibitedCXX11Attribute() {
2581
602k
    assert(Tok.is(tok::l_square));
2582
602k
    if (!standardAttributesAllowed() || 
NextToken().isNot(tok::l_square)273k
)
2583
602k
      return false;
2584
12
    return DiagnoseProhibitedCXX11Attribute();
2585
602k
  }
2586
2587
  bool DiagnoseProhibitedCXX11Attribute();
2588
  void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2589
639k
                                    SourceLocation CorrectLocation) {
2590
639k
    if (!standardAttributesAllowed())
2591
4.57k
      return;
2592
634k
    if ((Tok.isNot(tok::l_square) || 
NextToken().isNot(tok::l_square)19
) &&
2593
634k
        
Tok.isNot(tok::kw_alignas)634k
)
2594
634k
      return;
2595
24
    DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
2596
24
  }
2597
  void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2598
                                       SourceLocation CorrectLocation);
2599
2600
  void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
2601
                                      DeclSpec &DS, Sema::TagUseKind TUK);
2602
2603
  // FixItLoc = possible correct location for the attributes
2604
  void ProhibitAttributes(ParsedAttributesWithRange &Attrs,
2605
147M
                          SourceLocation FixItLoc = SourceLocation()) {
2606
147M
    if (Attrs.Range.isInvalid())
2607
147M
      return;
2608
107
    DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc);
2609
107
    Attrs.clear();
2610
107
  }
2611
2612
  void ProhibitAttributes(ParsedAttributesViewWithRange &Attrs,
2613
36.3k
                          SourceLocation FixItLoc = SourceLocation()) {
2614
36.3k
    if (Attrs.Range.isInvalid())
2615
36.3k
      return;
2616
5
    DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc);
2617
5
    Attrs.clearListOnly();
2618
5
  }
2619
  void DiagnoseProhibitedAttributes(const SourceRange &Range,
2620
                                    SourceLocation FixItLoc);
2621
2622
  // Forbid C++11 and C2x attributes that appear on certain syntactic locations
2623
  // which standard permits but we don't supported yet, for example, attributes
2624
  // appertain to decl specifiers.
2625
  void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
2626
                               unsigned DiagID,
2627
                               bool DiagnoseEmptyAttrs = false);
2628
2629
  /// Skip C++11 and C2x attributes and return the end location of the
2630
  /// last one.
2631
  /// \returns SourceLocation() if there are no attributes.
2632
  SourceLocation SkipCXX11Attributes();
2633
2634
  /// Diagnose and skip C++11 and C2x attributes that appear in syntactic
2635
  /// locations where attributes are not allowed.
2636
  void DiagnoseAndSkipCXX11Attributes();
2637
2638
  /// Emit warnings for C++11 and C2x attributes that are in a position that
2639
  /// clang accepts as an extension.
2640
  void DiagnoseCXX11AttributeExtension(ParsedAttributesWithRange &Attrs);
2641
2642
  /// Parses syntax-generic attribute arguments for attributes which are
2643
  /// known to the implementation, and adds them to the given ParsedAttributes
2644
  /// list with the given attribute syntax. Returns the number of arguments
2645
  /// parsed for the attribute.
2646
  unsigned
2647
  ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2648
                           ParsedAttributes &Attrs, SourceLocation *EndLoc,
2649
                           IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2650
                           ParsedAttr::Syntax Syntax);
2651
2652
  enum ParseAttrKindMask {
2653
    PAKM_GNU = 1 << 0,
2654
    PAKM_Declspec = 1 << 1,
2655
    PAKM_CXX11 = 1 << 2,
2656
  };
2657
2658
  /// \brief Parse attributes based on what syntaxes are desired, allowing for
2659
  /// the order to vary. e.g. with PAKM_GNU | PAKM_Declspec:
2660
  /// __attribute__((...)) __declspec(...) __attribute__((...)))
2661
  /// Note that Microsoft attributes (spelled with single square brackets) are
2662
  /// not supported by this because of parsing ambiguities with other
2663
  /// constructs.
2664
  ///
2665
  /// There are some attribute parse orderings that should not be allowed in
2666
  /// arbitrary order. e.g.,
2667
  ///
2668
  ///   [[]] __attribute__(()) int i; // OK
2669
  ///   __attribute__(()) [[]] int i; // Not OK
2670
  ///
2671
  /// Such situations should use the specific attribute parsing functionality.
2672
  void ParseAttributes(unsigned WhichAttrKinds,
2673
                       ParsedAttributesWithRange &Attrs,
2674
                       SourceLocation *End = nullptr,
2675
                       LateParsedAttrList *LateAttrs = nullptr);
2676
  void ParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs,
2677
                       SourceLocation *End = nullptr,
2678
30.0M
                       LateParsedAttrList *LateAttrs = nullptr) {
2679
30.0M
    ParsedAttributesWithRange AttrsWithRange(AttrFactory);
2680
30.0M
    ParseAttributes(WhichAttrKinds, AttrsWithRange, End, LateAttrs);
2681
30.0M
    Attrs.takeAllFrom(AttrsWithRange);
2682
30.0M
  }
2683
  /// \brief Possibly parse attributes based on what syntaxes are desired,
2684
  /// allowing for the order to vary.
2685
  bool MaybeParseAttributes(unsigned WhichAttrKinds,
2686
                            ParsedAttributesWithRange &Attrs,
2687
                            SourceLocation *End = nullptr,
2688
4.84M
                            LateParsedAttrList *LateAttrs = nullptr) {
2689
4.84M
    if (Tok.isOneOf(tok::kw___attribute, tok::kw___declspec) ||
2690
4.84M
        
(4.35M
standardAttributesAllowed()4.35M
&&
isCXX11AttributeSpecifier()2.21M
)) {
2691
497k
      ParseAttributes(WhichAttrKinds, Attrs, End, LateAttrs);
2692
497k
      return true;
2693
497k
    }
2694
4.34M
    return false;
2695
4.84M
  }
2696
  bool MaybeParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs,
2697
                            SourceLocation *End = nullptr,
2698
2.27M
                            LateParsedAttrList *LateAttrs = nullptr) {
2699
2.27M
    if (Tok.isOneOf(tok::kw___attribute, tok::kw___declspec) ||
2700
2.27M
        
(2.04M
standardAttributesAllowed()2.04M
&&
isCXX11AttributeSpecifier()248k
)) {
2701
233k
      ParseAttributes(WhichAttrKinds, Attrs, End, LateAttrs);
2702
233k
      return true;
2703
233k
    }
2704
2.04M
    return false;
2705
2.27M
  }
2706
2707
  void MaybeParseGNUAttributes(Declarator &D,
2708
159M
                               LateParsedAttrList *LateAttrs = nullptr) {
2709
159M
    if (Tok.is(tok::kw___attribute)) {
2710
2.04M
      ParsedAttributes attrs(AttrFactory);
2711
2.04M
      SourceLocation endLoc;
2712
2.04M
      ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D);
2713
2.04M
      D.takeAttributes(attrs, endLoc);
2714
2.04M
    }
2715
159M
  }
2716
2717
  /// Parses GNU-style attributes and returns them without source range
2718
  /// information.
2719
  ///
2720
  /// This API is discouraged. Use the version that takes a
2721
  /// ParsedAttributesWithRange instead.
2722
  bool MaybeParseGNUAttributes(ParsedAttributes &Attrs,
2723
                               SourceLocation *EndLoc = nullptr,
2724
1.53M
                               LateParsedAttrList *LateAttrs = nullptr) {
2725
1.53M
    if (Tok.is(tok::kw___attribute)) {
2726
53.5k
      ParsedAttributesWithRange AttrsWithRange(AttrFactory);
2727
53.5k
      ParseGNUAttributes(Attrs, EndLoc, LateAttrs);
2728
53.5k
      Attrs.takeAllFrom(AttrsWithRange);
2729
53.5k
      return true;
2730
53.5k
    }
2731
1.47M
    return false;
2732
1.53M
  }
2733
2734
  bool MaybeParseGNUAttributes(ParsedAttributesWithRange &Attrs,
2735
                               SourceLocation *EndLoc = nullptr,
2736
65.0M
                               LateParsedAttrList *LateAttrs = nullptr) {
2737
65.0M
    if (Tok.is(tok::kw___attribute)) {
2738
30.6M
      ParseGNUAttributes(Attrs, EndLoc, LateAttrs);
2739
30.6M
      return true;
2740
30.6M
    }
2741
34.4M
    return false;
2742
65.0M
  }
2743
2744
  /// Parses GNU-style attributes and returns them without source range
2745
  /// information.
2746
  ///
2747
  /// This API is discouraged. Use the version that takes a
2748
  /// ParsedAttributesWithRange instead.
2749
  void ParseGNUAttributes(ParsedAttributes &Attrs,
2750
                          SourceLocation *EndLoc = nullptr,
2751
                          LateParsedAttrList *LateAttrs = nullptr,
2752
2.14M
                          Declarator *D = nullptr) {
2753
2.14M
    ParsedAttributesWithRange AttrsWithRange(AttrFactory);
2754
2.14M
    ParseGNUAttributes(AttrsWithRange, EndLoc, LateAttrs, D);
2755
2.14M
    Attrs.takeAllFrom(AttrsWithRange);
2756
2.14M
  }
2757
2758
  void ParseGNUAttributes(ParsedAttributesWithRange &Attrs,
2759
                          SourceLocation *EndLoc = nullptr,
2760
                          LateParsedAttrList *LateAttrs = nullptr,
2761
                          Declarator *D = nullptr);
2762
  void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
2763
                             SourceLocation AttrNameLoc,
2764
                             ParsedAttributes &Attrs, SourceLocation *EndLoc,
2765
                             IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2766
                             ParsedAttr::Syntax Syntax, Declarator *D);
2767
  IdentifierLoc *ParseIdentifierLoc();
2768
2769
  unsigned
2770
  ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2771
                          ParsedAttributes &Attrs, SourceLocation *EndLoc,
2772
                          IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2773
                          ParsedAttr::Syntax Syntax);
2774
2775
24.1k
  void ReplayOpenMPAttributeTokens(CachedTokens &OpenMPTokens) {
2776
    // If parsing the attributes found an OpenMP directive, emit those tokens
2777
    // to the parse stream now.
2778
24.1k
    if (!OpenMPTokens.empty()) {
2779
632
      PP.EnterToken(Tok, /*IsReinject*/ true);
2780
632
      PP.EnterTokenStream(OpenMPTokens, /*DisableMacroExpansion*/ true,
2781
632
                          /*IsReinject*/ true);
2782
632
      ConsumeAnyToken(/*ConsumeCodeCompletionTok*/ true);
2783
632
    }
2784
24.1k
  }
2785
67.9M
  void MaybeParseCXX11Attributes(Declarator &D) {
2786
67.9M
    if (standardAttributesAllowed() && 
isCXX11AttributeSpecifier()16.7M
) {
2787
299
      ParsedAttributesWithRange attrs(AttrFactory);
2788
299
      SourceLocation endLoc;
2789
299
      ParseCXX11Attributes(attrs, &endLoc);
2790
299
      D.takeAttributes(attrs, endLoc);
2791
299
    }
2792
67.9M
  }
2793
  bool MaybeParseCXX11Attributes(ParsedAttributes &attrs,
2794
91.6M
                                 SourceLocation *endLoc = nullptr) {
2795
91.6M
    if (standardAttributesAllowed() && 
isCXX11AttributeSpecifier()25.8M
) {
2796
54
      ParsedAttributesWithRange attrsWithRange(AttrFactory);
2797
54
      ParseCXX11Attributes(attrsWithRange, endLoc);
2798
54
      attrs.takeAllFrom(attrsWithRange);
2799
54
      return true;
2800
54
    }
2801
91.6M
    return false;
2802
91.6M
  }
2803
  bool MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2804
                                 SourceLocation *endLoc = nullptr,
2805
64.8M
                                 bool OuterMightBeMessageSend = false) {
2806
64.8M
    if (standardAttributesAllowed() &&
2807
64.8M
        
isCXX11AttributeSpecifier(false, OuterMightBeMessageSend)32.4M
) {
2808
23.5k
      ParseCXX11Attributes(attrs, endLoc);
2809
23.5k
      return true;
2810
23.5k
    }
2811
64.8M
    return false;
2812
64.8M
  }
2813
2814
  void ParseOpenMPAttributeArgs(IdentifierInfo *AttrName,
2815
                                CachedTokens &OpenMPTokens);
2816
2817
  void ParseCXX11AttributeSpecifierInternal(ParsedAttributes &Attrs,
2818
                                            CachedTokens &OpenMPTokens,
2819
                                            SourceLocation *EndLoc = nullptr);
2820
  void ParseCXX11AttributeSpecifier(ParsedAttributes &Attrs,
2821
24.1k
                                    SourceLocation *EndLoc = nullptr) {
2822
24.1k
    CachedTokens OpenMPTokens;
2823
24.1k
    ParseCXX11AttributeSpecifierInternal(Attrs, OpenMPTokens, EndLoc);
2824
24.1k
    ReplayOpenMPAttributeTokens(OpenMPTokens);
2825
24.1k
  }
2826
  void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2827
                            SourceLocation *EndLoc = nullptr);
2828
  /// Parses a C++11 (or C2x)-style attribute argument list. Returns true
2829
  /// if this results in adding an attribute to the ParsedAttributes list.
2830
  bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
2831
                               SourceLocation AttrNameLoc,
2832
                               ParsedAttributes &Attrs, SourceLocation *EndLoc,
2833
                               IdentifierInfo *ScopeName,
2834
                               SourceLocation ScopeLoc,
2835
                               CachedTokens &OpenMPTokens);
2836
2837
  IdentifierInfo *TryParseCXX11AttributeIdentifier(
2838
      SourceLocation &Loc,
2839
      Sema::AttributeCompletion Completion = Sema::AttributeCompletion::None,
2840
      const IdentifierInfo *EnclosingScope = nullptr);
2841
2842
  void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
2843
135M
                                     SourceLocation *endLoc = nullptr) {
2844
135M
    if (getLangOpts().MicrosoftExt && 
Tok.is(tok::l_square)338k
)
2845
76
      ParseMicrosoftAttributes(attrs, endLoc);
2846
135M
  }
2847
  void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs);
2848
  void ParseMicrosoftAttributes(ParsedAttributes &attrs,
2849
                                SourceLocation *endLoc = nullptr);
2850
  bool MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2851
60.3M
                                    SourceLocation *End = nullptr) {
2852
60.3M
    const auto &LO = getLangOpts();
2853
60.3M
    if (LO.DeclSpecKeyword && 
Tok.is(tok::kw___declspec)183k
) {
2854
10.6k
      ParseMicrosoftDeclSpecs(Attrs, End);
2855
10.6k
      return true;
2856
10.6k
    }
2857
60.3M
    return false;
2858
60.3M
  }
2859
  void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2860
                               SourceLocation *End = nullptr);
2861
  bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
2862
                                  SourceLocation AttrNameLoc,
2863
                                  ParsedAttributes &Attrs);
2864
  void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
2865
  void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2866
  SourceLocation SkipExtendedMicrosoftTypeAttributes();
2867
  void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
2868
  void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
2869
  void ParseOpenCLKernelAttributes(ParsedAttributes &attrs);
2870
  void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
2871
  void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
2872
2873
  VersionTuple ParseVersionTuple(SourceRange &Range);
2874
  void ParseAvailabilityAttribute(IdentifierInfo &Availability,
2875
                                  SourceLocation AvailabilityLoc,
2876
                                  ParsedAttributes &attrs,
2877
                                  SourceLocation *endLoc,
2878
                                  IdentifierInfo *ScopeName,
2879
                                  SourceLocation ScopeLoc,
2880
                                  ParsedAttr::Syntax Syntax);
2881
2882
  Optional<AvailabilitySpec> ParseAvailabilitySpec();
2883
  ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc);
2884
2885
  void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol,
2886
                                          SourceLocation Loc,
2887
                                          ParsedAttributes &Attrs,
2888
                                          SourceLocation *EndLoc,
2889
                                          IdentifierInfo *ScopeName,
2890
                                          SourceLocation ScopeLoc,
2891
                                          ParsedAttr::Syntax Syntax);
2892
2893
  void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
2894
                                       SourceLocation ObjCBridgeRelatedLoc,
2895
                                       ParsedAttributes &attrs,
2896
                                       SourceLocation *endLoc,
2897
                                       IdentifierInfo *ScopeName,
2898
                                       SourceLocation ScopeLoc,
2899
                                       ParsedAttr::Syntax Syntax);
2900
2901
  void ParseSwiftNewTypeAttribute(IdentifierInfo &AttrName,
2902
                                  SourceLocation AttrNameLoc,
2903
                                  ParsedAttributes &Attrs,
2904
                                  SourceLocation *EndLoc,
2905
                                  IdentifierInfo *ScopeName,
2906
                                  SourceLocation ScopeLoc,
2907
                                  ParsedAttr::Syntax Syntax);
2908
2909
  void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
2910
                                        SourceLocation AttrNameLoc,
2911
                                        ParsedAttributes &Attrs,
2912
                                        SourceLocation *EndLoc,
2913
                                        IdentifierInfo *ScopeName,
2914
                                        SourceLocation ScopeLoc,
2915
                                        ParsedAttr::Syntax Syntax);
2916
2917
  void
2918
  ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
2919
                            SourceLocation AttrNameLoc, ParsedAttributes &Attrs,
2920
                            SourceLocation *EndLoc, IdentifierInfo *ScopeName,
2921
                            SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax);
2922
2923
  void ParseTypeofSpecifier(DeclSpec &DS);
2924
  SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
2925
  void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
2926
                                         SourceLocation StartLoc,
2927
                                         SourceLocation EndLoc);
2928
  void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
2929
  void ParseAtomicSpecifier(DeclSpec &DS);
2930
2931
  ExprResult ParseAlignArgument(SourceLocation Start,
2932
                                SourceLocation &EllipsisLoc);
2933
  void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2934
                               SourceLocation *endLoc = nullptr);
2935
  ExprResult ParseExtIntegerArgument();
2936
2937
  VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
2938
6.49M
  VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
2939
6.49M
    return isCXX11VirtSpecifier(Tok);
2940
6.49M
  }
2941
  void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface,
2942
                                          SourceLocation FriendLoc);
2943
2944
  bool isCXX11FinalKeyword() const;
2945
  bool isClassCompatibleKeyword() const;
2946
2947
  /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
2948
  /// enter a new C++ declarator scope and exit it when the function is
2949
  /// finished.
2950
  class DeclaratorScopeObj {
2951
    Parser &P;
2952
    CXXScopeSpec &SS;
2953
    bool EnteredScope;
2954
    bool CreatedScope;
2955
  public:
2956
    DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
2957
142M
      : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
2958
2959
274k
    void EnterDeclaratorScope() {
2960
274k
      assert(!EnteredScope && "Already entered the scope!");
2961
0
      assert(SS.isSet() && "C++ scope was not set!");
2962
2963
0
      CreatedScope = true;
2964
274k
      P.EnterScope(0); // Not a decl scope.
2965
2966
274k
      if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
2967
274k
        EnteredScope = true;
2968
274k
    }
2969
2970
142M
    ~DeclaratorScopeObj() {
2971
142M
      if (EnteredScope) {
2972
274k
        assert(SS.isSet() && "C++ scope was cleared ?");
2973
0
        P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
2974
274k
      }
2975
142M
      if (CreatedScope)
2976
274k
        P.ExitScope();
2977
142M
    }
2978
  };
2979
2980
  /// ParseDeclarator - Parse and verify a newly-initialized declarator.
2981
  void ParseDeclarator(Declarator &D);
2982
  /// A function that parses a variant of direct-declarator.
2983
  typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
2984
  void ParseDeclaratorInternal(Declarator &D,
2985
                               DirectDeclParseFunction DirectDeclParser);
2986
2987
  enum AttrRequirements {
2988
    AR_NoAttributesParsed = 0, ///< No attributes are diagnosed.
2989
    AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes.
2990
    AR_GNUAttributesParsed = 1 << 1,
2991
    AR_CXX11AttributesParsed = 1 << 2,
2992
    AR_DeclspecAttributesParsed = 1 << 3,
2993
    AR_AllAttributesParsed = AR_GNUAttributesParsed |
2994
                             AR_CXX11AttributesParsed |
2995
                             AR_DeclspecAttributesParsed,
2996
    AR_VendorAttributesParsed = AR_GNUAttributesParsed |
2997
                                AR_DeclspecAttributesParsed
2998
  };
2999
3000
  void ParseTypeQualifierListOpt(
3001
      DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed,
3002
      bool AtomicAllowed = true, bool IdentifierRequired = false,
3003
      Optional<llvm::function_ref<void()>> CodeCompletionHandler = None);
3004
  void ParseDirectDeclarator(Declarator &D);
3005
  void ParseDecompositionDeclarator(Declarator &D);
3006
  void ParseParenDeclarator(Declarator &D);
3007
  void ParseFunctionDeclarator(Declarator &D,
3008
                               ParsedAttributes &attrs,
3009
                               BalancedDelimiterTracker &Tracker,
3010
                               bool IsAmbiguous,
3011
                               bool RequiresArg = false);
3012
  void InitCXXThisScopeForDeclaratorIfRelevant(
3013
      const Declarator &D, const DeclSpec &DS,
3014
      llvm::Optional<Sema::CXXThisScopeRAII> &ThisScope);
3015
  bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
3016
                         SourceLocation &RefQualifierLoc);
3017
  bool isFunctionDeclaratorIdentifierList();
3018
  void ParseFunctionDeclaratorIdentifierList(
3019
         Declarator &D,
3020
         SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
3021
  void ParseParameterDeclarationClause(
3022
         DeclaratorContext DeclaratorContext,
3023
         ParsedAttributes &attrs,
3024
         SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
3025
         SourceLocation &EllipsisLoc);
3026
  void ParseBracketDeclarator(Declarator &D);
3027
  void ParseMisplacedBracketDeclarator(Declarator &D);
3028
3029
  //===--------------------------------------------------------------------===//
3030
  // C++ 7: Declarations [dcl.dcl]
3031
3032
  /// The kind of attribute specifier we have found.
3033
  enum CXX11AttributeKind {
3034
    /// This is not an attribute specifier.
3035
    CAK_NotAttributeSpecifier,
3036
    /// This should be treated as an attribute-specifier.
3037
    CAK_AttributeSpecifier,
3038
    /// The next tokens are '[[', but this is not an attribute-specifier. This
3039
    /// is ill-formed by C++11 [dcl.attr.grammar]p6.
3040
    CAK_InvalidAttributeSpecifier
3041
  };
3042
  CXX11AttributeKind
3043
  isCXX11AttributeSpecifier(bool Disambiguate = false,
3044
                            bool OuterMightBeMessageSend = false);
3045
3046
  void DiagnoseUnexpectedNamespace(NamedDecl *Context);
3047
3048
  DeclGroupPtrTy ParseNamespace(DeclaratorContext Context,
3049
                                SourceLocation &DeclEnd,
3050
                                SourceLocation InlineLoc = SourceLocation());
3051
3052
  struct InnerNamespaceInfo {
3053
    SourceLocation NamespaceLoc;
3054
    SourceLocation InlineLoc;
3055
    SourceLocation IdentLoc;
3056
    IdentifierInfo *Ident;
3057
  };
3058
  using InnerNamespaceInfoList = llvm::SmallVector<InnerNamespaceInfo, 4>;
3059
3060
  void ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs,
3061
                           unsigned int index, SourceLocation &InlineLoc,
3062
                           ParsedAttributes &attrs,
3063
                           BalancedDelimiterTracker &Tracker);
3064
  Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context);
3065
  Decl *ParseExportDeclaration();
3066
  DeclGroupPtrTy ParseUsingDirectiveOrDeclaration(
3067
      DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
3068
      SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs);
3069
  Decl *ParseUsingDirective(DeclaratorContext Context,
3070
                            SourceLocation UsingLoc,
3071
                            SourceLocation &DeclEnd,
3072
                            ParsedAttributes &attrs);
3073
3074
  struct UsingDeclarator {
3075
    SourceLocation TypenameLoc;
3076
    CXXScopeSpec SS;
3077
    UnqualifiedId Name;
3078
    SourceLocation EllipsisLoc;
3079
3080
211k
    void clear() {
3081
211k
      TypenameLoc = EllipsisLoc = SourceLocation();
3082
211k
      SS.clear();
3083
211k
      Name.clear();
3084
211k
    }
3085
  };
3086
3087
  bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D);
3088
  DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context,
3089
                                       const ParsedTemplateInfo &TemplateInfo,
3090
                                       SourceLocation UsingLoc,
3091
                                       SourceLocation &DeclEnd,
3092
                                       ParsedAttributesWithRange &Attrs,
3093
                                       AccessSpecifier AS = AS_none);
3094
  Decl *ParseAliasDeclarationAfterDeclarator(
3095
      const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
3096
      UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
3097
      ParsedAttributes &Attrs, Decl **OwnedType = nullptr);
3098
3099
  Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
3100
  Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
3101
                            SourceLocation AliasLoc, IdentifierInfo *Alias,
3102
                            SourceLocation &DeclEnd);
3103
3104
  //===--------------------------------------------------------------------===//
3105
  // C++ 9: classes [class] and C structs/unions.
3106
  bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
3107
  void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
3108
                           DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo,
3109
                           AccessSpecifier AS, bool EnteringContext,
3110
                           DeclSpecContext DSC,
3111
                           ParsedAttributesWithRange &Attributes);
3112
  void SkipCXXMemberSpecification(SourceLocation StartLoc,
3113
                                  SourceLocation AttrFixitLoc,
3114
                                  unsigned TagType,
3115
                                  Decl *TagDecl);
3116
  void ParseCXXMemberSpecification(SourceLocation StartLoc,
3117
                                   SourceLocation AttrFixitLoc,
3118
                                   ParsedAttributesWithRange &Attrs,
3119
                                   unsigned TagType,
3120
                                   Decl *TagDecl);
3121
  ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
3122
                                       SourceLocation &EqualLoc);
3123
  bool
3124
  ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
3125
                                            VirtSpecifiers &VS,
3126
                                            ExprResult &BitfieldSize,
3127
                                            LateParsedAttrList &LateAttrs);
3128
  void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D,
3129
                                                               VirtSpecifiers &VS);
3130
  DeclGroupPtrTy ParseCXXClassMemberDeclaration(
3131
      AccessSpecifier AS, ParsedAttributes &Attr,
3132
      const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
3133
      ParsingDeclRAIIObject *DiagsFromTParams = nullptr);
3134
  DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas(
3135
      AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
3136
      DeclSpec::TST TagType, Decl *Tag);
3137
  void ParseConstructorInitializer(Decl *ConstructorDecl);
3138
  MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
3139
  void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
3140
                                      Decl *ThisDecl);
3141
3142
  //===--------------------------------------------------------------------===//
3143
  // C++ 10: Derived classes [class.derived]
3144
  TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
3145
                                    SourceLocation &EndLocation);
3146
  void ParseBaseClause(Decl *ClassDecl);
3147
  BaseResult ParseBaseSpecifier(Decl *ClassDecl);
3148
  AccessSpecifier getAccessSpecifierIfPresent() const;
3149
3150
  bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
3151
                                    ParsedType ObjectType,
3152
                                    bool ObjectHadErrors,
3153
                                    SourceLocation TemplateKWLoc,
3154
                                    IdentifierInfo *Name,
3155
                                    SourceLocation NameLoc,
3156
                                    bool EnteringContext,
3157
                                    UnqualifiedId &Id,
3158
                                    bool AssumeTemplateId);
3159
  bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
3160
                                  ParsedType ObjectType,
3161
                                  UnqualifiedId &Result);
3162
3163
  //===--------------------------------------------------------------------===//
3164
  // OpenMP: Directives and clauses.
3165
  /// Parse clauses for '#pragma omp declare simd'.
3166
  DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr,
3167
                                            CachedTokens &Toks,
3168
                                            SourceLocation Loc);
3169
3170
  /// Parse a property kind into \p TIProperty for the selector set \p Set and
3171
  /// selector \p Selector.
3172
  void parseOMPTraitPropertyKind(OMPTraitProperty &TIProperty,
3173
                                 llvm::omp::TraitSet Set,
3174
                                 llvm::omp::TraitSelector Selector,
3175
                                 llvm::StringMap<SourceLocation> &Seen);
3176
3177
  /// Parse a selector kind into \p TISelector for the selector set \p Set.
3178
  void parseOMPTraitSelectorKind(OMPTraitSelector &TISelector,
3179
                                 llvm::omp::TraitSet Set,
3180
                                 llvm::StringMap<SourceLocation> &Seen);
3181
3182
  /// Parse a selector set kind into \p TISet.
3183
  void parseOMPTraitSetKind(OMPTraitSet &TISet,
3184
                            llvm::StringMap<SourceLocation> &Seen);
3185
3186
  /// Parses an OpenMP context property.
3187
  void parseOMPContextProperty(OMPTraitSelector &TISelector,
3188
                               llvm::omp::TraitSet Set,
3189
                               llvm::StringMap<SourceLocation> &Seen);
3190
3191
  /// Parses an OpenMP context selector.
3192
  void parseOMPContextSelector(OMPTraitSelector &TISelector,
3193
                               llvm::omp::TraitSet Set,
3194
                               llvm::StringMap<SourceLocation> &SeenSelectors);
3195
3196
  /// Parses an OpenMP context selector set.
3197
  void parseOMPContextSelectorSet(OMPTraitSet &TISet,
3198
                                  llvm::StringMap<SourceLocation> &SeenSets);
3199
3200
  /// Parses OpenMP context selectors.
3201
  bool parseOMPContextSelectors(SourceLocation Loc, OMPTraitInfo &TI);
3202
3203
  /// Parse a `match` clause for an '#pragma omp declare variant'. Return true
3204
  /// if there was an error.
3205
  bool parseOMPDeclareVariantMatchClause(SourceLocation Loc, OMPTraitInfo &TI,
3206
                                         OMPTraitInfo *ParentTI);
3207
3208
  /// Parse clauses for '#pragma omp declare variant'.
3209
  void ParseOMPDeclareVariantClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks,
3210
                                     SourceLocation Loc);
3211
3212
  /// Parse 'omp [begin] assume[s]' directive.
3213
  void ParseOpenMPAssumesDirective(OpenMPDirectiveKind DKind,
3214
                                   SourceLocation Loc);
3215
3216
  /// Parse 'omp end assumes' directive.
3217
  void ParseOpenMPEndAssumesDirective(SourceLocation Loc);
3218
3219
  /// Parse clauses for '#pragma omp [begin] declare target'.
3220
  void ParseOMPDeclareTargetClauses(Sema::DeclareTargetContextInfo &DTCI);
3221
3222
  /// Parse '#pragma omp end declare target'.
3223
  void ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind BeginDKind,
3224
                                         OpenMPDirectiveKind EndDKind,
3225
                                         SourceLocation Loc);
3226
3227
  /// Skip tokens until a `annot_pragma_openmp_end` was found. Emit a warning if
3228
  /// it is not the current token.
3229
  void skipUntilPragmaOpenMPEnd(OpenMPDirectiveKind DKind);
3230
3231
  /// Check the \p FoundKind against the \p ExpectedKind, if not issue an error
3232
  /// that the "end" matching the "begin" directive of kind \p BeginKind was not
3233
  /// found. Finally, if the expected kind was found or if \p SkipUntilOpenMPEnd
3234
  /// is set, skip ahead using the helper `skipUntilPragmaOpenMPEnd`.
3235
  void parseOMPEndDirective(OpenMPDirectiveKind BeginKind,
3236
                            OpenMPDirectiveKind ExpectedKind,
3237
                            OpenMPDirectiveKind FoundKind,
3238
                            SourceLocation MatchingLoc,
3239
                            SourceLocation FoundLoc,
3240
                            bool SkipUntilOpenMPEnd);
3241
3242
  /// Parses declarative OpenMP directives.
3243
  DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl(
3244
      AccessSpecifier &AS, ParsedAttributesWithRange &Attrs,
3245
      bool Delayed = false, DeclSpec::TST TagType = DeclSpec::TST_unspecified,
3246
      Decl *TagDecl = nullptr);
3247
  /// Parse 'omp declare reduction' construct.
3248
  DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS);
3249
  /// Parses initializer for provided omp_priv declaration inside the reduction
3250
  /// initializer.
3251
  void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm);
3252
3253
  /// Parses 'omp declare mapper' directive.
3254
  DeclGroupPtrTy ParseOpenMPDeclareMapperDirective(AccessSpecifier AS);
3255
  /// Parses variable declaration in 'omp declare mapper' directive.
3256
  TypeResult parseOpenMPDeclareMapperVarDecl(SourceRange &Range,
3257
                                             DeclarationName &Name,
3258
                                             AccessSpecifier AS = AS_none);
3259
3260
  /// Tries to parse cast part of OpenMP array shaping operation:
3261
  /// '[' expression ']' { '[' expression ']' } ')'.
3262
  bool tryParseOpenMPArrayShapingCastPart();
3263
3264
  /// Parses simple list of variables.
3265
  ///
3266
  /// \param Kind Kind of the directive.
3267
  /// \param Callback Callback function to be called for the list elements.
3268
  /// \param AllowScopeSpecifier true, if the variables can have fully
3269
  /// qualified names.
3270
  ///
3271
  bool ParseOpenMPSimpleVarList(
3272
      OpenMPDirectiveKind Kind,
3273
      const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
3274
          Callback,
3275
      bool AllowScopeSpecifier);
3276
  /// Parses declarative or executable directive.
3277
  ///
3278
  /// \param StmtCtx The context in which we're parsing the directive.
3279
  StmtResult
3280
  ParseOpenMPDeclarativeOrExecutableDirective(ParsedStmtContext StmtCtx);
3281
  /// Parses clause of kind \a CKind for directive of a kind \a Kind.
3282
  ///
3283
  /// \param DKind Kind of current directive.
3284
  /// \param CKind Kind of current clause.
3285
  /// \param FirstClause true, if this is the first clause of a kind \a CKind
3286
  /// in current directive.
3287
  ///
3288
  OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
3289
                               OpenMPClauseKind CKind, bool FirstClause);
3290
  /// Parses clause with a single expression of a kind \a Kind.
3291
  ///
3292
  /// \param Kind Kind of current clause.
3293
  /// \param ParseOnly true to skip the clause's semantic actions and return
3294
  /// nullptr.
3295
  ///
3296
  OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind,
3297
                                         bool ParseOnly);
3298
  /// Parses simple clause of a kind \a Kind.
3299
  ///
3300
  /// \param Kind Kind of current clause.
3301
  /// \param ParseOnly true to skip the clause's semantic actions and return
3302
  /// nullptr.
3303
  ///
3304
  OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly);
3305
  /// Parses clause with a single expression and an additional argument
3306
  /// of a kind \a Kind.
3307
  ///
3308
  /// \param DKind Directive kind.
3309
  /// \param Kind Kind of current clause.
3310
  /// \param ParseOnly true to skip the clause's semantic actions and return
3311
  /// nullptr.
3312
  ///
3313
  OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPDirectiveKind DKind,
3314
                                                OpenMPClauseKind Kind,
3315
                                                bool ParseOnly);
3316
3317
  /// Parses the 'sizes' clause of a '#pragma omp tile' directive.
3318
  OMPClause *ParseOpenMPSizesClause();
3319
3320
  /// Parses clause without any additional arguments.
3321
  ///
3322
  /// \param Kind Kind of current clause.
3323
  /// \param ParseOnly true to skip the clause's semantic actions and return
3324
  /// nullptr.
3325
  ///
3326
  OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false);
3327
  /// Parses clause with the list of variables of a kind \a Kind.
3328
  ///
3329
  /// \param Kind Kind of current clause.
3330
  /// \param ParseOnly true to skip the clause's semantic actions and return
3331
  /// nullptr.
3332
  ///
3333
  OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
3334
                                      OpenMPClauseKind Kind, bool ParseOnly);
3335
3336
  /// Parses and creates OpenMP 5.0 iterators expression:
3337
  /// <iterators> = 'iterator' '(' { [ <iterator-type> ] identifier =
3338
  /// <range-specification> }+ ')'
3339
  ExprResult ParseOpenMPIteratorsExpr();
3340
3341
  /// Parses allocators and traits in the context of the uses_allocator clause.
3342
  /// Expected format:
3343
  /// '(' { <allocator> [ '(' <allocator_traits> ')' ] }+ ')'
3344
  OMPClause *ParseOpenMPUsesAllocatorClause(OpenMPDirectiveKind DKind);
3345
3346
  /// Parses clause with an interop variable of kind \a Kind.
3347
  ///
3348
  /// \param Kind Kind of current clause.
3349
  /// \param ParseOnly true to skip the clause's semantic actions and return
3350
  /// nullptr.
3351
  //
3352
  OMPClause *ParseOpenMPInteropClause(OpenMPClauseKind Kind, bool ParseOnly);
3353
3354
public:
3355
  /// Parses simple expression in parens for single-expression clauses of OpenMP
3356
  /// constructs.
3357
  /// \param RLoc Returned location of right paren.
3358
  ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc,
3359
                                   bool IsAddressOfOperand = false);
3360
3361
  /// Data used for parsing list of variables in OpenMP clauses.
3362
  struct OpenMPVarListDataTy {
3363
    Expr *DepModOrTailExpr = nullptr;
3364
    SourceLocation ColonLoc;
3365
    SourceLocation RLoc;
3366
    CXXScopeSpec ReductionOrMapperIdScopeSpec;
3367
    DeclarationNameInfo ReductionOrMapperId;
3368
    int ExtraModifier = -1; ///< Additional modifier for linear, map, depend or
3369
                            ///< lastprivate clause.
3370
    SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
3371
    MapTypeModifiers;
3372
    SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers>
3373
    MapTypeModifiersLoc;
3374
    SmallVector<OpenMPMotionModifierKind, NumberOfOMPMotionModifiers>
3375
        MotionModifiers;
3376
    SmallVector<SourceLocation, NumberOfOMPMotionModifiers> MotionModifiersLoc;
3377
    bool IsMapTypeImplicit = false;
3378
    SourceLocation ExtraModifierLoc;
3379
  };
3380
3381
  /// Parses clauses with list.
3382
  bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind,
3383
                          SmallVectorImpl<Expr *> &Vars,
3384
                          OpenMPVarListDataTy &Data);
3385
  bool ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType,
3386
                          bool ObjectHadErrors, bool EnteringContext,
3387
                          bool AllowDestructorName, bool AllowConstructorName,
3388
                          bool AllowDeductionGuide,
3389
                          SourceLocation *TemplateKWLoc, UnqualifiedId &Result);
3390
3391
  /// Parses the mapper modifier in map, to, and from clauses.
3392
  bool parseMapperModifier(OpenMPVarListDataTy &Data);
3393
  /// Parses map-type-modifiers in map clause.
3394
  /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list)
3395
  /// where, map-type-modifier ::= always | close | mapper(mapper-identifier)
3396
  bool parseMapTypeModifiers(OpenMPVarListDataTy &Data);
3397
3398
private:
3399
  //===--------------------------------------------------------------------===//
3400
  // C++ 14: Templates [temp]
3401
3402
  // C++ 14.1: Template Parameters [temp.param]
3403
  Decl *ParseDeclarationStartingWithTemplate(DeclaratorContext Context,
3404
                                             SourceLocation &DeclEnd,
3405
                                             ParsedAttributes &AccessAttrs,
3406
                                             AccessSpecifier AS = AS_none);
3407
  Decl *ParseTemplateDeclarationOrSpecialization(DeclaratorContext Context,
3408
                                                 SourceLocation &DeclEnd,
3409
                                                 ParsedAttributes &AccessAttrs,
3410
                                                 AccessSpecifier AS);
3411
  Decl *ParseSingleDeclarationAfterTemplate(
3412
      DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
3413
      ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd,
3414
      ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none);
3415
  bool ParseTemplateParameters(MultiParseScope &TemplateScopes, unsigned Depth,
3416
                               SmallVectorImpl<NamedDecl *> &TemplateParams,
3417
                               SourceLocation &LAngleLoc,
3418
                               SourceLocation &RAngleLoc);
3419
  bool ParseTemplateParameterList(unsigned Depth,
3420
                                  SmallVectorImpl<NamedDecl*> &TemplateParams);
3421
  TPResult isStartOfTemplateTypeParameter();
3422
  NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position);
3423
  NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position);
3424
  NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
3425
  NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
3426
  bool isTypeConstraintAnnotation();
3427
  bool TryAnnotateTypeConstraint();
3428
  void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
3429
                                 SourceLocation CorrectLoc,
3430
                                 bool AlreadyHasEllipsis,
3431
                                 bool IdentifierHasName);
3432
  void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
3433
                                             Declarator &D);
3434
  // C++ 14.3: Template arguments [temp.arg]
3435
  typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
3436
3437
  bool ParseGreaterThanInTemplateList(SourceLocation LAngleLoc,
3438
                                      SourceLocation &RAngleLoc,
3439
                                      bool ConsumeLastToken,
3440
                                      bool ObjCGenericList);
3441
  bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
3442
                                        SourceLocation &LAngleLoc,
3443
                                        TemplateArgList &TemplateArgs,
3444
                                        SourceLocation &RAngleLoc);
3445
3446
  bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
3447
                               CXXScopeSpec &SS,
3448
                               SourceLocation TemplateKWLoc,
3449
                               UnqualifiedId &TemplateName,
3450
                               bool AllowTypeAnnotation = true,
3451
                               bool TypeConstraint = false);
3452
  void AnnotateTemplateIdTokenAsType(CXXScopeSpec &SS,
3453
                                     bool IsClassName = false);
3454
  bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
3455
  ParsedTemplateArgument ParseTemplateTemplateArgument();
3456
  ParsedTemplateArgument ParseTemplateArgument();
3457
  Decl *ParseExplicitInstantiation(DeclaratorContext Context,
3458
                                   SourceLocation ExternLoc,
3459
                                   SourceLocation TemplateLoc,
3460
                                   SourceLocation &DeclEnd,
3461
                                   ParsedAttributes &AccessAttrs,
3462
                                   AccessSpecifier AS = AS_none);
3463
  // C++2a: Template, concept definition [temp]
3464
  Decl *
3465
  ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo,
3466
                         SourceLocation &DeclEnd);
3467
3468
  //===--------------------------------------------------------------------===//
3469
  // Modules
3470
  DeclGroupPtrTy ParseModuleDecl(bool IsFirstDecl);
3471
  Decl *ParseModuleImport(SourceLocation AtLoc);
3472
  bool parseMisplacedModuleImport();
3473
18.2M
  bool tryParseMisplacedModuleImport() {
3474
18.2M
    tok::TokenKind Kind = Tok.getKind();
3475
18.2M
    if (Kind == tok::annot_module_begin || 
Kind == tok::annot_module_end18.2M
||
3476
18.2M
        
Kind == tok::annot_module_include18.2M
)
3477
21
      return parseMisplacedModuleImport();
3478
18.2M
    return false;
3479
18.2M
  }
3480
3481
  bool ParseModuleName(
3482
      SourceLocation UseLoc,
3483
      SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
3484
      bool IsImport);
3485
3486
  //===--------------------------------------------------------------------===//
3487
  // C++11/G++: Type Traits [Type-Traits.html in the GCC manual]
3488
  ExprResult ParseTypeTrait();
3489
3490
  //===--------------------------------------------------------------------===//
3491
  // Embarcadero: Arary and Expression Traits
3492
  ExprResult ParseArrayTypeTrait();
3493
  ExprResult ParseExpressionTrait();
3494
3495
  //===--------------------------------------------------------------------===//
3496
  // Preprocessor code-completion pass-through
3497
  void CodeCompleteDirective(bool InConditional) override;
3498
  void CodeCompleteInConditionalExclusion() override;
3499
  void CodeCompleteMacroName(bool IsDefinition) override;
3500
  void CodeCompletePreprocessorExpression() override;
3501
  void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo,
3502
                                 unsigned ArgumentIndex) override;
3503
  void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) override;
3504
  void CodeCompleteNaturalLanguage() override;
3505
3506
  class GNUAsmQualifiers {
3507
    unsigned Qualifiers = AQ_unspecified;
3508
3509
  public:
3510
    enum AQ {
3511
      AQ_unspecified = 0,
3512
      AQ_volatile    = 1,
3513
      AQ_inline      = 2,
3514
      AQ_goto        = 4,
3515
    };
3516
    static const char *getQualifierName(AQ Qualifier);
3517
    bool setAsmQualifier(AQ Qualifier);
3518
6.53k
    inline bool isVolatile() const { return Qualifiers & AQ_volatile; };
3519
0
    inline bool isInline() const { return Qualifiers & AQ_inline; };
3520
18.9k
    inline bool isGoto() const { return Qualifiers & AQ_goto; }
3521
  };
3522
  bool isGCCAsmStatement(const Token &TokAfterAsm) const;
3523
  bool isGNUAsmQualifier(const Token &TokAfterAsm) const;
3524
  GNUAsmQualifiers::AQ getGNUAsmQualifier(const Token &Tok) const;
3525
  bool parseGNUAsmQualifierListOpt(GNUAsmQualifiers &AQ);
3526
};
3527
3528
}  // end namespace clang
3529
3530
#endif