Coverage Report

Created: 2018-11-16 02:38

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