Coverage Report

Created: 2019-02-23 12:57

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