Coverage Report

Created: 2022-07-16 07:03

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