Coverage Report

Created: 2022-05-17 06:19

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