Coverage Report

Created: 2020-09-19 12:23

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