Coverage Report

Created: 2021-01-19 06:58

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