Coverage Report

Created: 2018-09-23 03:40

/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.63M
      : Depth(Depth), AddedLevels(0) {}
232
233
4.63M
    ~TemplateParameterDepthRAII() {
234
4.63M
      Depth -= AddedLevels;
235
4.63M
    }
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.58M
    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.0M
    void clear(Parser &P) {
327
68.2M
      while (!Locs.empty() && 
Locs.back().isActiveOrNested(P)230k
)
328
230k
        Locs.pop_back();
329
68.0M
    }
330
331
    /// Get the current enclosing expression that might hve been intended to be
332
    /// a template name.
333
5.27M
    Loc *getCurrent(Parser &P) {
334
5.27M
      if (!Locs.empty() && 
Locs.back().isActive(P)1.15k
)
335
185
        return &Locs.back();
336
5.27M
      return nullptr;
337
5.27M
    }
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
742M
  const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
367
72.7k
  const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
368
971k
  Preprocessor &getPreprocessor() const { return PP; }
369
27.4M
  Sema &getActions() const { return Actions; }
370
12.4M
  AttributeFactory &getAttrFactory() { return AttrFactory; }
371
372
140k
  const Token &getCurToken() const { return Tok; }
373
189M
  Scope *getCurScope() const { return Actions.getCurScope(); }
374
733k
  void incrementMSManglingNumber() const {
375
733k
    return Actions.incrementMSManglingNumber();
376
733k
  }
377
378
9.76M
  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
161M
  SourceLocation ConsumeToken() {
412
161M
    assert(!isTokenSpecial() &&
413
161M
           "Should consume special tokens with Consume*Token");
414
161M
    PrevTokLocation = Tok.getLocation();
415
161M
    PP.Lex(Tok);
416
161M
    return PrevTokLocation;
417
161M
  }
418
419
98.8M
  bool TryConsumeToken(tok::TokenKind Expected) {
420
98.8M
    if (Tok.isNot(Expected))
421
73.2M
      return false;
422
25.5M
    assert(!isTokenSpecial() &&
423
25.5M
           "Should consume special tokens with Consume*Token");
424
25.5M
    PrevTokLocation = Tok.getLocation();
425
25.5M
    PP.Lex(Tok);
426
25.5M
    return true;
427
25.5M
  }
428
429
46.3M
  bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) {
430
46.3M
    if (!TryConsumeToken(Expected))
431
40.7M
      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
69.4M
  SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) {
440
69.4M
    if (isTokenParen())
441
23.9M
      return ConsumeParen();
442
45.4M
    if (isTokenBracket())
443
220k
      return ConsumeBracket();
444
45.2M
    if (isTokenBrace())
445
1.23M
      return ConsumeBrace();
446
44.0M
    if (isTokenStringLiteral())
447
795k
      return ConsumeStringToken();
448
43.2M
    if (Tok.is(tok::code_completion))
449
113
      return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken()
450
113
                                      : 
handleUnexpectedCodeCompletionToken()0
;
451
43.2M
    if (Tok.isAnnotation())
452
149k
      return ConsumeAnnotationToken();
453
43.0M
    return ConsumeToken();
454
43.0M
  }
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
69.4M
  bool isTokenParen() const {
474
69.4M
    return Tok.isOneOf(tok::l_paren, tok::r_paren);
475
69.4M
  }
476
  /// isTokenBracket - Return true if the cur token is '[' or ']'.
477
45.4M
  bool isTokenBracket() const {
478
45.4M
    return Tok.isOneOf(tok::l_square, tok::r_square);
479
45.4M
  }
480
  /// isTokenBrace - Return true if the cur token is '{' or '}'.
481
45.2M
  bool isTokenBrace() const {
482
45.2M
    return Tok.isOneOf(tok::l_brace, tok::r_brace);
483
45.2M
  }
484
  /// isTokenStringLiteral - True if this token is a string-literal.
485
49.5M
  bool isTokenStringLiteral() const {
486
49.5M
    return tok::isStringLiteral(Tok.getKind());
487
49.5M
  }
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.0M
  SourceLocation ConsumeAnnotationToken() {
508
20.0M
    assert(Tok.isAnnotation() && "wrong consume method");
509
20.0M
    SourceLocation Loc = Tok.getLocation();
510
20.0M
    PrevTokLocation = Tok.getAnnotationEndLoc();
511
20.0M
    PP.Lex(Tok);
512
20.0M
    return Loc;
513
20.0M
  }
514
515
  /// ConsumeParen - This consume method keeps the paren count up-to-date.
516
  ///
517
70.8M
  SourceLocation ConsumeParen() {
518
70.8M
    assert(isTokenParen() && "wrong consume method");
519
70.8M
    if (Tok.getKind() == tok::l_paren)
520
36.5M
      ++ParenCount;
521
34.2M
    else if (ParenCount) {
522
34.2M
      AngleBrackets.clear(*this);
523
34.2M
      --ParenCount;       // Don't let unbalanced )'s drive the count negative.
524
34.2M
    }
525
70.8M
    PrevTokLocation = Tok.getLocation();
526
70.8M
    PP.Lex(Tok);
527
70.8M
    return PrevTokLocation;
528
70.8M
  }
529
530
  /// ConsumeBracket - This consume method keeps the bracket count up-to-date.
531
  ///
532
2.50M
  SourceLocation ConsumeBracket() {
533
2.50M
    assert(isTokenBracket() && "wrong consume method");
534
2.50M
    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.50M
541
2.50M
    PrevTokLocation = Tok.getLocation();
542
2.50M
    PP.Lex(Tok);
543
2.50M
    return PrevTokLocation;
544
2.50M
  }
545
546
  /// ConsumeBrace - This consume method keeps the brace count up-to-date.
547
  ///
548
12.2M
  SourceLocation ConsumeBrace() {
549
12.2M
    assert(isTokenBrace() && "wrong consume method");
550
12.2M
    if (Tok.getKind() == tok::l_brace)
551
6.14M
      ++BraceCount;
552
6.13M
    else if (BraceCount) {
553
6.13M
      AngleBrackets.clear(*this);
554
6.13M
      --BraceCount;     // Don't let unbalanced }'s drive the count negative.
555
6.13M
    }
556
12.2M
557
12.2M
    PrevTokLocation = Tok.getLocation();
558
12.2M
    PP.Lex(Tok);
559
12.2M
    return PrevTokLocation;
560
12.2M
  }
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.24M
  SourceLocation ConsumeStringToken() {
567
4.24M
    assert(isTokenStringLiteral() &&
568
4.24M
           "Should only consume string literals with this method");
569
4.24M
    PrevTokLocation = Tok.getLocation();
570
4.24M
    PP.Lex(Tok);
571
4.24M
    return PrevTokLocation;
572
4.24M
  }
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
150
  SourceLocation ConsumeCodeCompletionToken() {
580
150
    assert(Tok.is(tok::code_completion));
581
150
    PrevTokLocation = Tok.getLocation();
582
150
    PP.Lex(Tok);
583
150
    return PrevTokLocation;
584
150
  }
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
904
  void cutOffParsing() {
596
904
    if (PP.isCodeCompletionEnabled())
597
896
      PP.setCodeCompletionReached();
598
904
    // Cut off parsing by acting as if we reached the end-of-file.
599
904
    Tok.setKind(tok::eof);
600
904
  }
601
602
  /// Determine if we're at the end of the file or at a transition
603
  /// between modules.
604
72.1k
  bool isEofOrEom() {
605
72.1k
    tok::TokenKind Kind = Tok.getKind();
606
72.1k
    return Kind == tok::eof || 
Kind == tok::annot_module_begin71.9k
||
607
72.1k
           
Kind == tok::annot_module_end71.9k
||
Kind == tok::annot_module_include71.9k
;
608
72.1k
  }
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.41M
  const Token &GetLookAheadToken(unsigned N) {
711
4.41M
    if (N == 0 || 
Tok.is(tok::eof)4.41M
)
return Tok378
;
712
4.41M
    return PP.LookAhead(N-1);
713
4.41M
  }
714
715
public:
716
  /// NextToken - This peeks ahead one token and returns it without
717
  /// consuming it.
718
127M
  const Token &NextToken() {
719
127M
    return PP.LookAhead(0);
720
127M
  }
721
722
  /// getTypeAnnotation - Read a parsed type out of an annotation token.
723
10.4M
  static ParsedType getTypeAnnotation(const Token &Tok) {
724
10.4M
    return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
725
10.4M
  }
726
727
private:
728
10.1M
  static void setTypeAnnotation(Token &Tok, ParsedType T) {
729
10.1M
    Tok.setAnnotationValue(T.getAsOpaquePtr());
730
10.1M
  }
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.31M
                       bool &isInvalid) {
778
9.31M
    if (!getLangOpts().AltiVec && 
!getLangOpts().ZVector9.15M
)
779
9.14M
      return false;
780
165k
781
165k
    if (Tok.getIdentifierInfo() != Ident_vector &&
782
165k
        
Tok.getIdentifierInfo() != Ident_bool47.0k
&&
783
165k
        
(8.51k
!getLangOpts().AltiVec8.51k
||
Tok.getIdentifierInfo() != Ident_pixel8.49k
))
784
3.64k
      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
10.9M
  bool TryAltiVecVectorToken() {
793
10.9M
    if ((!getLangOpts().AltiVec && 
!getLangOpts().ZVector10.8M
) ||
794
10.9M
        
Tok.getIdentifierInfo() != Ident_vector145k
)
return false10.8M
;
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().ObjC1);
808
12.2k
    if (Tok.isAnnotation())
809
1
      return false;
810
12.2k
    if (!Ident_instancetype)
811
250
      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.69M
    explicit TentativeParsingAction(Parser& p) : P(p) {
845
3.69M
      PrevTok = P.Tok;
846
3.69M
      PrevTentativelyDeclaredIdentifierCount =
847
3.69M
          P.TentativelyDeclaredIdentifiers.size();
848
3.69M
      PrevParenCount = P.ParenCount;
849
3.69M
      PrevBracketCount = P.BracketCount;
850
3.69M
      PrevBraceCount = P.BraceCount;
851
3.69M
      P.PP.EnableBacktrackAtThisPos();
852
3.69M
      isActive = true;
853
3.69M
    }
854
20.5k
    void Commit() {
855
20.5k
      assert(isActive && "Parsing action was finished!");
856
20.5k
      P.TentativelyDeclaredIdentifiers.resize(
857
20.5k
          PrevTentativelyDeclaredIdentifierCount);
858
20.5k
      P.PP.CommitBacktrackedTokens();
859
20.5k
      isActive = false;
860
20.5k
    }
861
3.67M
    void Revert() {
862
3.67M
      assert(isActive && "Parsing action was finished!");
863
3.67M
      P.PP.Backtrack();
864
3.67M
      P.Tok = PrevTok;
865
3.67M
      P.TentativelyDeclaredIdentifiers.resize(
866
3.67M
          PrevTentativelyDeclaredIdentifierCount);
867
3.67M
      P.ParenCount = PrevParenCount;
868
3.67M
      P.BracketCount = PrevBracketCount;
869
3.67M
      P.BraceCount = PrevBraceCount;
870
3.67M
      isActive = false;
871
3.67M
    }
872
3.69M
    ~TentativeParsingAction() {
873
3.69M
      assert(!isActive && "Forgot to call Commit or Revert!");
874
3.69M
    }
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.29M
        : Parser::TentativeParsingAction(P) {}
883
2.29M
    ~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.76M
        WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) {
899
9.76M
      if (DC)
900
127k
        P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC));
901
9.76M
    }
902
9.76M
    ~ObjCDeclContextSwitch() {
903
9.76M
      if (DC)
904
127k
        P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC));
905
9.76M
    }
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.4M
      : Self(Self) {
968
22.4M
      if (EnteredScope && 
!BeforeCompoundStmt15.4M
)
969
14.7M
        Self->EnterScope(ScopeFlags);
970
7.72M
      else {
971
7.72M
        if (BeforeCompoundStmt)
972
733k
          Self->incrementMSManglingNumber();
973
7.72M
974
7.72M
        this->Self = nullptr;
975
7.72M
      }
976
22.4M
    }
977
978
    // Exit - Exit the scope associated with this object now, rather
979
    // than waiting until the object is destroyed.
980
35.2M
    void Exit() {
981
35.2M
      if (Self) {
982
14.7M
        Self->ExitScope();
983
14.7M
        Self = nullptr;
984
14.7M
      }
985
35.2M
    }
986
987
22.4M
    ~ParseScope() {
988
22.4M
      Exit();
989
22.4M
    }
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
504
  DiagnosticBuilder Diag(unsigned DiagID) {
1018
504
    return Diag(Tok, DiagID);
1019
504
  }
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
25.9k
                                            SkipUntilFlags R) {
1038
25.9k
    return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) |
1039
25.9k
                                       static_cast<unsigned>(R));
1040
25.9k
  }
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.7k
                 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
1056
18.7k
    tok::TokenKind TokArray[] = {T1, T2};
1057
18.7k
    return SkipUntil(TokArray, Flags);
1058
18.7k
  }
1059
  bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3,
1060
7.22k
                 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
1061
7.22k
    tok::TokenKind TokArray[] = {T1, T2, T3};
1062
7.22k
    return SkipUntil(TokArray, Flags);
1063
7.22k
  }
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.4M
    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.00M
      : 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
197k
      : 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
118k
        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.01k
      : 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
795k
        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.4M
  ParsingClass &getCurrentClass() {
1278
11.4M
    assert(!ClassStack.empty() && "No lexed method stacks!");
1279
11.4M
    return *ClassStack.top();
1280
11.4M
  }
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
795k
        State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
1293
795k
    }
1294
1295
    /// Pop this class of the stack.
1296
795k
    void Pop() {
1297
795k
      assert(!Popped && "Nested class has already been popped");
1298
795k
      Popped = true;
1299
795k
      P.PopParsingClass(State);
1300
795k
    }
1301
1302
795k
    ~ParsingClassDefinition() {
1303
795k
      if (!Popped)
1304
61
        P.PopParsingClass(State);
1305
795k
    }
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
34.9M
      : 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.25M
        LastParameterListWasEmpty(lastParameterListWasEmpty) { }
1321
1322
    explicit ParsedTemplateInfo(SourceLocation ExternLoc,
1323
                                SourceLocation TemplateLoc)
1324
      : Kind(ExplicitInstantiation), TemplateParams(nullptr),
1325
        ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
1326
25.0k
        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.68M
                            bool ConsumeFinalToken = true) {
1400
4.68M
    return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
1401
4.68M
  }
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
62.7M
      : ParsedAttributes(factory) {}
1412
1413
265k
    void clear() {
1414
265k
      ParsedAttributes::clear();
1415
265k
      Range = SourceRange();
1416
265k
    }
1417
1418
    SourceRange Range;
1419
  };
1420
  struct ParsedAttributesViewWithRange : ParsedAttributesView {
1421
3.76M
    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
243k
  bool isPostfixExpressionSuffixStart() {
1624
243k
    tok::TokenKind K = Tok.getKind();
1625
243k
    return (K == tok::l_square || 
K == tok::l_paren210k
||
1626
243k
            
K == tok::period208k
||
K == tok::arrow203k
||
1627
243k
            
K == tok::plusplus178k
||
K == tok::minusminus178k
);
1628
243k
  }
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.27M
  bool checkPotentialAngleBracketDelimiter(const Token &OpToken) {
1635
5.27M
    if (auto *Info = AngleBrackets.getCurrent(*this))
1636
185
      return checkPotentialAngleBracketDelimiter(*Info, OpToken);
1637
5.27M
    return false;
1638
5.27M
  }
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 condition expression.
1797
  Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt,
1798
                                          SourceLocation Loc,
1799
                                          Sema::ConditionKind CK);
1800
1801
  //===--------------------------------------------------------------------===//
1802
  // C++ Coroutines
1803
1804
  ExprResult ParseCoyieldExpression();
1805
1806
  //===--------------------------------------------------------------------===//
1807
  // C99 6.7.8: Initialization.
1808
1809
  /// ParseInitializer
1810
  ///       initializer: [C99 6.7.8]
1811
  ///         assignment-expression
1812
  ///         '{' ...
1813
2.50M
  ExprResult ParseInitializer() {
1814
2.50M
    if (Tok.isNot(tok::l_brace))
1815
2.41M
      return ParseAssignmentExpression();
1816
93.7k
    return ParseBraceInitializer();
1817
93.7k
  }
1818
  bool MayBeDesignationStart();
1819
  ExprResult ParseBraceInitializer();
1820
  ExprResult ParseInitializerWithPotentialDesignator();
1821
1822
  //===--------------------------------------------------------------------===//
1823
  // clang Expressions
1824
1825
  ExprResult ParseBlockLiteralExpression();  // ^{...}
1826
1827
  //===--------------------------------------------------------------------===//
1828
  // Objective-C Expressions
1829
  ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
1830
  ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
1831
  ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
1832
  ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
1833
  ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
1834
  ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
1835
  ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
1836
  ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
1837
  ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
1838
  ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
1839
  ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
1840
  bool isSimpleObjCMessageExpression();
1841
  ExprResult ParseObjCMessageExpression();
1842
  ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
1843
                                            SourceLocation SuperLoc,
1844
                                            ParsedType ReceiverType,
1845
                                            Expr *ReceiverExpr);
1846
  ExprResult ParseAssignmentExprWithObjCMessageExprStart(
1847
      SourceLocation LBracloc, SourceLocation SuperLoc,
1848
      ParsedType ReceiverType, Expr *ReceiverExpr);
1849
  bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
1850
1851
  //===--------------------------------------------------------------------===//
1852
  // C99 6.8: Statements and Blocks.
1853
1854
  /// A SmallVector of statements, with stack size 32 (as that is the only one
1855
  /// used.)
1856
  typedef SmallVector<Stmt*, 32> StmtVector;
1857
  /// A SmallVector of expressions, with stack size 12 (the maximum used.)
1858
  typedef SmallVector<Expr*, 12> ExprVector;
1859
  /// A SmallVector of types.
1860
  typedef SmallVector<ParsedType, 12> TypeVector;
1861
1862
  StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
1863
                            bool AllowOpenMPStandalone = false);
1864
  enum AllowedConstructsKind {
1865
    /// Allow any declarations, statements, OpenMP directives.
1866
    ACK_Any,
1867
    /// Allow only statements and non-standalone OpenMP directives.
1868
    ACK_StatementsOpenMPNonStandalone,
1869
    /// Allow statements and all executable OpenMP directives
1870
    ACK_StatementsOpenMPAnyExecutable
1871
  };
1872
  StmtResult
1873
  ParseStatementOrDeclaration(StmtVector &Stmts, AllowedConstructsKind Allowed,
1874
                              SourceLocation *TrailingElseLoc = nullptr);
1875
  StmtResult ParseStatementOrDeclarationAfterAttributes(
1876
                                         StmtVector &Stmts,
1877
                                         AllowedConstructsKind Allowed,
1878
                                         SourceLocation *TrailingElseLoc,
1879
                                         ParsedAttributesWithRange &Attrs);
1880
  StmtResult ParseExprStatement();
1881
  StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs);
1882
  StmtResult ParseCaseStatement(bool MissingCase = false,
1883
                                ExprResult Expr = ExprResult());
1884
  StmtResult ParseDefaultStatement();
1885
  StmtResult ParseCompoundStatement(bool isStmtExpr = false);
1886
  StmtResult ParseCompoundStatement(bool isStmtExpr,
1887
                                    unsigned ScopeFlags);
1888
  void ParseCompoundStatementLeadingPragmas();
1889
  StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
1890
  bool ParseParenExprOrCondition(StmtResult *InitStmt,
1891
                                 Sema::ConditionResult &CondResult,
1892
                                 SourceLocation Loc,
1893
                                 Sema::ConditionKind CK);
1894
  StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
1895
  StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
1896
  StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
1897
  StmtResult ParseDoStatement();
1898
  StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
1899
  StmtResult ParseGotoStatement();
1900
  StmtResult ParseContinueStatement();
1901
  StmtResult ParseBreakStatement();
1902
  StmtResult ParseReturnStatement();
1903
  StmtResult ParseAsmStatement(bool &msAsm);
1904
  StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
1905
  StmtResult ParsePragmaLoopHint(StmtVector &Stmts,
1906
                                 AllowedConstructsKind Allowed,
1907
                                 SourceLocation *TrailingElseLoc,
1908
                                 ParsedAttributesWithRange &Attrs);
1909
1910
  /// Describes the behavior that should be taken for an __if_exists
1911
  /// block.
1912
  enum IfExistsBehavior {
1913
    /// Parse the block; this code is always used.
1914
    IEB_Parse,
1915
    /// Skip the block entirely; this code is never used.
1916
    IEB_Skip,
1917
    /// Parse the block as a dependent block, which may be used in
1918
    /// some template instantiations but not others.
1919
    IEB_Dependent
1920
  };
1921
1922
  /// Describes the condition of a Microsoft __if_exists or
1923
  /// __if_not_exists block.
1924
  struct IfExistsCondition {
1925
    /// The location of the initial keyword.
1926
    SourceLocation KeywordLoc;
1927
    /// Whether this is an __if_exists block (rather than an
1928
    /// __if_not_exists block).
1929
    bool IsIfExists;
1930
1931
    /// Nested-name-specifier preceding the name.
1932
    CXXScopeSpec SS;
1933
1934
    /// The name we're looking for.
1935
    UnqualifiedId Name;
1936
1937
    /// The behavior of this __if_exists or __if_not_exists block
1938
    /// should.
1939
    IfExistsBehavior Behavior;
1940
  };
1941
1942
  bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
1943
  void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
1944
  void ParseMicrosoftIfExistsExternalDeclaration();
1945
  void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
1946
                                              ParsedAttributes &AccessAttrs,
1947
                                              AccessSpecifier &CurAS);
1948
  bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
1949
                                              bool &InitExprsOk);
1950
  bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
1951
                           SmallVectorImpl<Expr *> &Constraints,
1952
                           SmallVectorImpl<Expr *> &Exprs);
1953
1954
  //===--------------------------------------------------------------------===//
1955
  // C++ 6: Statements and Blocks
1956
1957
  StmtResult ParseCXXTryBlock();
1958
  StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
1959
  StmtResult ParseCXXCatchBlock(bool FnCatch = false);
1960
1961
  //===--------------------------------------------------------------------===//
1962
  // MS: SEH Statements and Blocks
1963
1964
  StmtResult ParseSEHTryBlock();
1965
  StmtResult ParseSEHExceptBlock(SourceLocation Loc);
1966
  StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
1967
  StmtResult ParseSEHLeaveStatement();
1968
1969
  //===--------------------------------------------------------------------===//
1970
  // Objective-C Statements
1971
1972
  StmtResult ParseObjCAtStatement(SourceLocation atLoc);
1973
  StmtResult ParseObjCTryStmt(SourceLocation atLoc);
1974
  StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
1975
  StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
1976
  StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
1977
1978
1979
  //===--------------------------------------------------------------------===//
1980
  // C99 6.7: Declarations.
1981
1982
  /// A context for parsing declaration specifiers.  TODO: flesh this
1983
  /// out, there are other significant restrictions on specifiers than
1984
  /// would be best implemented in the parser.
1985
  enum class DeclSpecContext {
1986
    DSC_normal, // normal context
1987
    DSC_class,  // class context, enables 'friend'
1988
    DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
1989
    DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
1990
    DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration
1991
    DSC_top_level, // top-level/namespace declaration context
1992
    DSC_template_param, // template parameter context
1993
    DSC_template_type_arg, // template type argument context
1994
    DSC_objc_method_result, // ObjC method result context, enables 'instancetype'
1995
    DSC_condition // condition declaration context
1996
  };
1997
1998
  /// Is this a context in which we are parsing just a type-specifier (or
1999
  /// trailing-type-specifier)?
2000
8.52M
  static bool isTypeSpecifier(DeclSpecContext DSC) {
2001
8.52M
    switch (DSC) {
2002
8.52M
    case DeclSpecContext::DSC_normal:
2003
4.68M
    case DeclSpecContext::DSC_template_param:
2004
4.68M
    case DeclSpecContext::DSC_class:
2005
4.68M
    case DeclSpecContext::DSC_top_level:
2006
4.68M
    case DeclSpecContext::DSC_objc_method_result:
2007
4.68M
    case DeclSpecContext::DSC_condition:
2008
4.68M
      return false;
2009
4.68M
2010
4.68M
    case DeclSpecContext::DSC_template_type_arg:
2011
3.84M
    case DeclSpecContext::DSC_type_specifier:
2012
3.84M
    case DeclSpecContext::DSC_trailing:
2013
3.84M
    case DeclSpecContext::DSC_alias_declaration:
2014
3.84M
      return true;
2015
0
    }
2016
0
    llvm_unreachable("Missing DeclSpecContext case");
2017
0
  }
2018
2019
  /// Is this a context in which we can perform class template argument
2020
  /// deduction?
2021
8.95M
  static bool isClassTemplateDeductionContext(DeclSpecContext DSC) {
2022
8.95M
    switch (DSC) {
2023
8.95M
    case DeclSpecContext::DSC_normal:
2024
8.86M
    case DeclSpecContext::DSC_template_param:
2025
8.86M
    case DeclSpecContext::DSC_class:
2026
8.86M
    case DeclSpecContext::DSC_top_level:
2027
8.86M
    case DeclSpecContext::DSC_condition:
2028
8.86M
    case DeclSpecContext::DSC_type_specifier:
2029
8.86M
      return true;
2030
8.86M
2031
8.86M
    case DeclSpecContext::DSC_objc_method_result:
2032
87.1k
    case DeclSpecContext::DSC_template_type_arg:
2033
87.1k
    case DeclSpecContext::DSC_trailing:
2034
87.1k
    case DeclSpecContext::DSC_alias_declaration:
2035
87.1k
      return false;
2036
0
    }
2037
0
    llvm_unreachable("Missing DeclSpecContext case");
2038
0
  }
2039
2040
  /// Information on a C++0x for-range-initializer found while parsing a
2041
  /// declaration which turns out to be a for-range-declaration.
2042
  struct ForRangeInit {
2043
    SourceLocation ColonLoc;
2044
    ExprResult RangeExpr;
2045
2046
124k
    bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
2047
  };
2048
2049
  DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context,
2050
                                  SourceLocation &DeclEnd,
2051
                                  ParsedAttributesWithRange &attrs);
2052
  DeclGroupPtrTy ParseSimpleDeclaration(DeclaratorContext Context,
2053
                                        SourceLocation &DeclEnd,
2054
                                        ParsedAttributesWithRange &attrs,
2055
                                        bool RequireSemi,
2056
                                        ForRangeInit *FRI = nullptr);
2057
  bool MightBeDeclarator(DeclaratorContext Context);
2058
  DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context,
2059
                                SourceLocation *DeclEnd = nullptr,
2060
                                ForRangeInit *FRI = nullptr);
2061
  Decl *ParseDeclarationAfterDeclarator(Declarator &D,
2062
               const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
2063
  bool ParseAsmAttributesAfterDeclarator(Declarator &D);
2064
  Decl *ParseDeclarationAfterDeclaratorAndAttributes(
2065
      Declarator &D,
2066
      const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2067
      ForRangeInit *FRI = nullptr);
2068
  Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
2069
  Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
2070
2071
  /// When in code-completion, skip parsing of the function/method body
2072
  /// unless the body contains the code-completion point.
2073
  ///
2074
  /// \returns true if the function body was skipped.
2075
  bool trySkippingFunctionBody();
2076
2077
  bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2078
                        const ParsedTemplateInfo &TemplateInfo,
2079
                        AccessSpecifier AS, DeclSpecContext DSC,
2080
                        ParsedAttributesWithRange &Attrs);
2081
  DeclSpecContext
2082
  getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context);
2083
  void ParseDeclarationSpecifiers(
2084
      DeclSpec &DS,
2085
      const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2086
      AccessSpecifier AS = AS_none,
2087
      DeclSpecContext DSC = DeclSpecContext::DSC_normal,
2088
      LateParsedAttrList *LateAttrs = nullptr);
2089
  bool DiagnoseMissingSemiAfterTagDefinition(
2090
      DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext,
2091
      LateParsedAttrList *LateAttrs = nullptr);
2092
2093
  void ParseSpecifierQualifierList(
2094
      DeclSpec &DS, AccessSpecifier AS = AS_none,
2095
      DeclSpecContext DSC = DeclSpecContext::DSC_normal);
2096
2097
  void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
2098
                                  DeclaratorContext Context);
2099
2100
  void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
2101
                          const ParsedTemplateInfo &TemplateInfo,
2102
                          AccessSpecifier AS, DeclSpecContext DSC);
2103
  void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
2104
  void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType,
2105
                            Decl *TagDecl);
2106
2107
  void ParseStructDeclaration(
2108
      ParsingDeclSpec &DS,
2109
      llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback);
2110
2111
  bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
2112
  bool isTypeSpecifierQualifier();
2113
2114
  /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
2115
  /// is definitely a type-specifier.  Return false if it isn't part of a type
2116
  /// specifier or if we're not sure.
2117
  bool isKnownToBeTypeSpecifier(const Token &Tok) const;
2118
2119
  /// Return true if we know that we are definitely looking at a
2120
  /// decl-specifier, and isn't part of an expression such as a function-style
2121
  /// cast. Return false if it's no a decl-specifier, or we're not sure.
2122
52.7k
  bool isKnownToBeDeclarationSpecifier() {
2123
52.7k
    if (getLangOpts().CPlusPlus)
2124
38.8k
      return isCXXDeclarationSpecifier() == TPResult::True;
2125
13.9k
    return isDeclarationSpecifier(true);
2126
13.9k
  }
2127
2128
  /// isDeclarationStatement - Disambiguates between a declaration or an
2129
  /// expression statement, when parsing function bodies.
2130
  /// Returns true for declaration, false for expression.
2131
4.40M
  bool isDeclarationStatement() {
2132
4.40M
    if (getLangOpts().CPlusPlus)
2133
3.31M
      return isCXXDeclarationStatement();
2134
1.08M
    return isDeclarationSpecifier(true);
2135
1.08M
  }
2136
2137
  /// isForInitDeclaration - Disambiguates between a declaration or an
2138
  /// expression in the context of the C 'clause-1' or the C++
2139
  // 'for-init-statement' part of a 'for' statement.
2140
  /// Returns true for declaration, false for expression.
2141
164k
  bool isForInitDeclaration() {
2142
164k
    if (getLangOpts().CPlusPlus)
2143
140k
      return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
2144
23.0k
    return isDeclarationSpecifier(true);
2145
23.0k
  }
2146
2147
  /// Determine whether this is a C++1z for-range-identifier.
2148
  bool isForRangeIdentifier();
2149
2150
  /// Determine whether we are currently at the start of an Objective-C
2151
  /// class message that appears to be missing the open bracket '['.
2152
  bool isStartOfObjCClassMessageMissingOpenBracket();
2153
2154
  /// Starting with a scope specifier, identifier, or
2155
  /// template-id that refers to the current class, determine whether
2156
  /// this is a constructor declarator.
2157
  bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false);
2158
2159
  /// Specifies the context in which type-id/expression
2160
  /// disambiguation will occur.
2161
  enum TentativeCXXTypeIdContext {
2162
    TypeIdInParens,
2163
    TypeIdUnambiguous,
2164
    TypeIdAsTemplateArgument
2165
  };
2166
2167
2168
  /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
2169
  /// whether the parens contain an expression or a type-id.
2170
  /// Returns true for a type-id and false for an expression.
2171
5.09M
  bool isTypeIdInParens(bool &isAmbiguous) {
2172
5.09M
    if (getLangOpts().CPlusPlus)
2173
2.32M
      return isCXXTypeId(TypeIdInParens, isAmbiguous);
2174
2.76M
    isAmbiguous = false;
2175
2.76M
    return isTypeSpecifierQualifier();
2176
2.76M
  }
2177
24.4k
  bool isTypeIdInParens() {
2178
24.4k
    bool isAmbiguous;
2179
24.4k
    return isTypeIdInParens(isAmbiguous);
2180
24.4k
  }
2181
2182
  /// Checks if the current tokens form type-id or expression.
2183
  /// It is similar to isTypeIdInParens but does not suppose that type-id
2184
  /// is in parenthesis.
2185
231k
  bool isTypeIdUnambiguously() {
2186
231k
    bool IsAmbiguous;
2187
231k
    if (getLangOpts().CPlusPlus)
2188
231k
      return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous);
2189
320
    return isTypeSpecifierQualifier();
2190
320
  }
2191
2192
  /// isCXXDeclarationStatement - C++-specialized function that disambiguates
2193
  /// between a declaration or an expression statement, when parsing function
2194
  /// bodies. Returns true for declaration, false for expression.
2195
  bool isCXXDeclarationStatement();
2196
2197
  /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
2198
  /// between a simple-declaration or an expression-statement.
2199
  /// If during the disambiguation process a parsing error is encountered,
2200
  /// the function returns true to let the declaration parsing code handle it.
2201
  /// Returns false if the statement is disambiguated as expression.
2202
  bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
2203
2204
  /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
2205
  /// a constructor-style initializer, when parsing declaration statements.
2206
  /// Returns true for function declarator and false for constructor-style
2207
  /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
2208
  /// might be a constructor-style initializer.
2209
  /// If during the disambiguation process a parsing error is encountered,
2210
  /// the function returns true to let the declaration parsing code handle it.
2211
  bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr);
2212
2213
  struct ConditionDeclarationOrInitStatementState;
2214
  enum class ConditionOrInitStatement {
2215
    Expression,    ///< Disambiguated as an expression (either kind).
2216
    ConditionDecl, ///< Disambiguated as the declaration form of condition.
2217
    InitStmtDecl,  ///< Disambiguated as a simple-declaration init-statement.
2218
    Error          ///< Can't be any of the above!
2219
  };
2220
  /// Disambiguates between the different kinds of things that can happen
2221
  /// after 'if (' or 'switch ('. This could be one of two different kinds of
2222
  /// declaration (depending on whether there is a ';' later) or an expression.
2223
  ConditionOrInitStatement
2224
  isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt);
2225
2226
  bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
2227
4.30M
  bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
2228
4.30M
    bool isAmbiguous;
2229
4.30M
    return isCXXTypeId(Context, isAmbiguous);
2230
4.30M
  }
2231
2232
  /// TPResult - Used as the result value for functions whose purpose is to
2233
  /// disambiguate C++ constructs by "tentatively parsing" them.
2234
  enum class TPResult {
2235
    True, False, Ambiguous, Error
2236
  };
2237
2238
  /// Based only on the given token kind, determine whether we know that
2239
  /// we're at the start of an expression or a type-specifier-seq (which may
2240
  /// be an expression, in C++).
2241
  ///
2242
  /// This routine does not attempt to resolve any of the trick cases, e.g.,
2243
  /// those involving lookup of identifiers.
2244
  ///
2245
  /// \returns \c TPR_true if this token starts an expression, \c TPR_false if
2246
  /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot
2247
  /// tell.
2248
  TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind);
2249
2250
  /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a
2251
  /// declaration specifier, TPResult::False if it is not,
2252
  /// TPResult::Ambiguous if it could be either a decl-specifier or a
2253
  /// function-style cast, and TPResult::Error if a parsing error was
2254
  /// encountered. If it could be a braced C++11 function-style cast, returns
2255
  /// BracedCastResult.
2256
  /// Doesn't consume tokens.
2257
  TPResult
2258
  isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False,
2259
                            bool *HasMissingTypename = nullptr);
2260
2261
  /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
2262
  /// \c TPResult::Ambiguous, determine whether the decl-specifier would be
2263
  /// a type-specifier other than a cv-qualifier.
2264
  bool isCXXDeclarationSpecifierAType();
2265
2266
  /// Determine whether an identifier has been tentatively declared as a
2267
  /// non-type. Such tentative declarations should not be found to name a type
2268
  /// during a tentative parse, but also should not be annotated as a non-type.
2269
  bool isTentativelyDeclared(IdentifierInfo *II);
2270
2271
  // "Tentative parsing" functions, used for disambiguation. If a parsing error
2272
  // is encountered they will return TPResult::Error.
2273
  // Returning TPResult::True/False indicates that the ambiguity was
2274
  // resolved and tentative parsing may stop. TPResult::Ambiguous indicates
2275
  // that more tentative parsing is necessary for disambiguation.
2276
  // They all consume tokens, so backtracking should be used after calling them.
2277
2278
  TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
2279
  TPResult TryParseTypeofSpecifier();
2280
  TPResult TryParseProtocolQualifiers();
2281
  TPResult TryParsePtrOperatorSeq();
2282
  TPResult TryParseOperatorId();
2283
  TPResult TryParseInitDeclaratorList();
2284
  TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true,
2285
                              bool mayHaveDirectInit = false);
2286
  TPResult
2287
  TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr,
2288
                                     bool VersusTemplateArg = false);
2289
  TPResult TryParseFunctionDeclarator();
2290
  TPResult TryParseBracketDeclarator();
2291
  TPResult TryConsumeDeclarationSpecifier();
2292
2293
public:
2294
  TypeResult ParseTypeName(SourceRange *Range = nullptr,
2295
                           DeclaratorContext Context
2296
                             = DeclaratorContext::TypeNameContext,
2297
                           AccessSpecifier AS = AS_none,
2298
                           Decl **OwnedType = nullptr,
2299
                           ParsedAttributes *Attrs = nullptr);
2300
2301
private:
2302
  void ParseBlockId(SourceLocation CaretLoc);
2303
2304
  /// Are [[]] attributes enabled?
2305
72.3M
  bool standardAttributesAllowed() const {
2306
72.3M
    const LangOptions &LO = getLangOpts();
2307
72.3M
    return LO.DoubleSquareBracketAttributes;
2308
72.3M
  }
2309
2310
  // Check for the start of an attribute-specifier-seq in a context where an
2311
  // attribute is not allowed.
2312
992k
  bool CheckProhibitedCXX11Attribute() {
2313
992k
    assert(Tok.is(tok::l_square));
2314
992k
    if (!standardAttributesAllowed() || 
NextToken().isNot(tok::l_square)473k
)
2315
992k
      return false;
2316
11
    return DiagnoseProhibitedCXX11Attribute();
2317
11
  }
2318
2319
  bool DiagnoseProhibitedCXX11Attribute();
2320
  void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2321
754k
                                    SourceLocation CorrectLocation) {
2322
754k
    if (!standardAttributesAllowed())
2323
71.8k
      return;
2324
682k
    if ((Tok.isNot(tok::l_square) || 
NextToken().isNot(tok::l_square)19
) &&
2325
682k
        
Tok.isNot(tok::kw_alignas)682k
)
2326
682k
      return;
2327
24
    DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
2328
24
  }
2329
  void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2330
                                       SourceLocation CorrectLocation);
2331
2332
  void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
2333
                                      DeclSpec &DS, Sema::TagUseKind TUK);
2334
2335
  // FixItLoc = possible correct location for the attributes
2336
  void ProhibitAttributes(ParsedAttributesWithRange &Attrs,
2337
33.9M
                          SourceLocation FixItLoc = SourceLocation()) {
2338
33.9M
    if (Attrs.Range.isInvalid())
2339
33.9M
      return;
2340
87
    DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc);
2341
87
    Attrs.clear();
2342
87
  }
2343
2344
  void ProhibitAttributes(ParsedAttributesViewWithRange &Attrs,
2345
42.3k
                          SourceLocation FixItLoc = SourceLocation()) {
2346
42.3k
    if (Attrs.Range.isInvalid())
2347
42.3k
      return;
2348
4
    DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc);
2349
4
    Attrs.clearListOnly();
2350
4
  }
2351
  void DiagnoseProhibitedAttributes(const SourceRange &Range,
2352
                                    SourceLocation FixItLoc);
2353
2354
  // Forbid C++11 and C2x attributes that appear on certain syntactic locations
2355
  // which standard permits but we don't supported yet, for example, attributes
2356
  // appertain to decl specifiers.
2357
  void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
2358
                               unsigned DiagID);
2359
2360
  /// Skip C++11 and C2x attributes and return the end location of the
2361
  /// last one.
2362
  /// \returns SourceLocation() if there are no attributes.
2363
  SourceLocation SkipCXX11Attributes();
2364
2365
  /// Diagnose and skip C++11 and C2x attributes that appear in syntactic
2366
  /// locations where attributes are not allowed.
2367
  void DiagnoseAndSkipCXX11Attributes();
2368
2369
  /// Parses syntax-generic attribute arguments for attributes which are
2370
  /// known to the implementation, and adds them to the given ParsedAttributes
2371
  /// list with the given attribute syntax. Returns the number of arguments
2372
  /// parsed for the attribute.
2373
  unsigned
2374
  ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2375
                           ParsedAttributes &Attrs, SourceLocation *EndLoc,
2376
                           IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2377
                           ParsedAttr::Syntax Syntax);
2378
2379
  void MaybeParseGNUAttributes(Declarator &D,
2380
23.3M
                               LateParsedAttrList *LateAttrs = nullptr) {
2381
23.3M
    if (Tok.is(tok::kw___attribute)) {
2382
330k
      ParsedAttributes attrs(AttrFactory);
2383
330k
      SourceLocation endLoc;
2384
330k
      ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D);
2385
330k
      D.takeAttributes(attrs, endLoc);
2386
330k
    }
2387
23.3M
  }
2388
  void MaybeParseGNUAttributes(ParsedAttributes &attrs,
2389
                               SourceLocation *endLoc = nullptr,
2390
3.52M
                               LateParsedAttrList *LateAttrs = nullptr) {
2391
3.52M
    if (Tok.is(tok::kw___attribute))
2392
249k
      ParseGNUAttributes(attrs, endLoc, LateAttrs);
2393
3.52M
  }
2394
  void ParseGNUAttributes(ParsedAttributes &attrs,
2395
                          SourceLocation *endLoc = nullptr,
2396
                          LateParsedAttrList *LateAttrs = nullptr,
2397
                          Declarator *D = nullptr);
2398
  void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
2399
                             SourceLocation AttrNameLoc,
2400
                             ParsedAttributes &Attrs, SourceLocation *EndLoc,
2401
                             IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2402
                             ParsedAttr::Syntax Syntax, Declarator *D);
2403
  IdentifierLoc *ParseIdentifierLoc();
2404
2405
  unsigned
2406
  ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2407
                          ParsedAttributes &Attrs, SourceLocation *EndLoc,
2408
                          IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2409
                          ParsedAttr::Syntax Syntax);
2410
2411
18.7M
  void MaybeParseCXX11Attributes(Declarator &D) {
2412
18.7M
    if (standardAttributesAllowed() && 
isCXX11AttributeSpecifier()11.6M
) {
2413
182
      ParsedAttributesWithRange attrs(AttrFactory);
2414
182
      SourceLocation endLoc;
2415
182
      ParseCXX11Attributes(attrs, &endLoc);
2416
182
      D.takeAttributes(attrs, endLoc);
2417
182
    }
2418
18.7M
  }
2419
  void MaybeParseCXX11Attributes(ParsedAttributes &attrs,
2420
10.0M
                                 SourceLocation *endLoc = nullptr) {
2421
10.0M
    if (standardAttributesAllowed() && 
isCXX11AttributeSpecifier()5.53M
) {
2422
44
      ParsedAttributesWithRange attrsWithRange(AttrFactory);
2423
44
      ParseCXX11Attributes(attrsWithRange, endLoc);
2424
44
      attrs.takeAllFrom(attrsWithRange);
2425
44
    }
2426
10.0M
  }
2427
  void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2428
                                 SourceLocation *endLoc = nullptr,
2429
30.0M
                                 bool OuterMightBeMessageSend = false) {
2430
30.0M
    if (standardAttributesAllowed() &&
2431
30.0M
      
isCXX11AttributeSpecifier(false, OuterMightBeMessageSend)22.5M
)
2432
16.8k
      ParseCXX11Attributes(attrs, endLoc);
2433
30.0M
  }
2434
2435
  void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
2436
                                    SourceLocation *EndLoc = nullptr);
2437
  void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2438
                            SourceLocation *EndLoc = nullptr);
2439
  /// Parses a C++11 (or C2x)-style attribute argument list. Returns true
2440
  /// if this results in adding an attribute to the ParsedAttributes list.
2441
  bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
2442
                               SourceLocation AttrNameLoc,
2443
                               ParsedAttributes &Attrs, SourceLocation *EndLoc,
2444
                               IdentifierInfo *ScopeName,
2445
                               SourceLocation ScopeLoc);
2446
2447
  IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc);
2448
2449
  void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
2450
19.5M
                                     SourceLocation *endLoc = nullptr) {
2451
19.5M
    if (getLangOpts().MicrosoftExt && 
Tok.is(tok::l_square)81.3k
)
2452
75
      ParseMicrosoftAttributes(attrs, endLoc);
2453
19.5M
  }
2454
  void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs);
2455
  void ParseMicrosoftAttributes(ParsedAttributes &attrs,
2456
                                SourceLocation *endLoc = nullptr);
2457
  void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2458
1.45M
                                    SourceLocation *End = nullptr) {
2459
1.45M
    const auto &LO = getLangOpts();
2460
1.45M
    if (LO.DeclSpecKeyword && 
Tok.is(tok::kw___declspec)9.38k
)
2461
1.63k
      ParseMicrosoftDeclSpecs(Attrs, End);
2462
1.45M
  }
2463
  void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2464
                               SourceLocation *End = nullptr);
2465
  bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
2466
                                  SourceLocation AttrNameLoc,
2467
                                  ParsedAttributes &Attrs);
2468
  void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
2469
  void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2470
  SourceLocation SkipExtendedMicrosoftTypeAttributes();
2471
  void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
2472
  void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
2473
  void ParseOpenCLKernelAttributes(ParsedAttributes &attrs);
2474
  void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
2475
  /// Parses opencl_unroll_hint attribute if language is OpenCL v2.0
2476
  /// or higher.
2477
  /// \return false if error happens.
2478
9.32M
  bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
2479
9.32M
    if (getLangOpts().OpenCL)
2480
4.33k
      return ParseOpenCLUnrollHintAttribute(Attrs);
2481
9.32M
    return true;
2482
9.32M
  }
2483
  /// Parses opencl_unroll_hint attribute.
2484
  /// \return false if error happens.
2485
  bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs);
2486
  void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
2487
2488
  VersionTuple ParseVersionTuple(SourceRange &Range);
2489
  void ParseAvailabilityAttribute(IdentifierInfo &Availability,
2490
                                  SourceLocation AvailabilityLoc,
2491
                                  ParsedAttributes &attrs,
2492
                                  SourceLocation *endLoc,
2493
                                  IdentifierInfo *ScopeName,
2494
                                  SourceLocation ScopeLoc,
2495
                                  ParsedAttr::Syntax Syntax);
2496
2497
  Optional<AvailabilitySpec> ParseAvailabilitySpec();
2498
  ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc);
2499
2500
  void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol,
2501
                                          SourceLocation Loc,
2502
                                          ParsedAttributes &Attrs,
2503
                                          SourceLocation *EndLoc,
2504
                                          IdentifierInfo *ScopeName,
2505
                                          SourceLocation ScopeLoc,
2506
                                          ParsedAttr::Syntax Syntax);
2507
2508
  void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
2509
                                       SourceLocation ObjCBridgeRelatedLoc,
2510
                                       ParsedAttributes &attrs,
2511
                                       SourceLocation *endLoc,
2512
                                       IdentifierInfo *ScopeName,
2513
                                       SourceLocation ScopeLoc,
2514
                                       ParsedAttr::Syntax Syntax);
2515
2516
  void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
2517
                                        SourceLocation AttrNameLoc,
2518
                                        ParsedAttributes &Attrs,
2519
                                        SourceLocation *EndLoc,
2520
                                        IdentifierInfo *ScopeName,
2521
                                        SourceLocation ScopeLoc,
2522
                                        ParsedAttr::Syntax Syntax);
2523
2524
  void
2525
  ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
2526
                            SourceLocation AttrNameLoc, ParsedAttributes &Attrs,
2527
                            SourceLocation *EndLoc, IdentifierInfo *ScopeName,
2528
                            SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax);
2529
2530
  void ParseTypeofSpecifier(DeclSpec &DS);
2531
  SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
2532
  void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
2533
                                         SourceLocation StartLoc,
2534
                                         SourceLocation EndLoc);
2535
  void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
2536
  void ParseAtomicSpecifier(DeclSpec &DS);
2537
2538
  ExprResult ParseAlignArgument(SourceLocation Start,
2539
                                SourceLocation &EllipsisLoc);
2540
  void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2541
                               SourceLocation *endLoc = nullptr);
2542
2543
  VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
2544
8.20M
  VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
2545
8.20M
    return isCXX11VirtSpecifier(Tok);
2546
8.20M
  }
2547
  void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface,
2548
                                          SourceLocation FriendLoc);
2549
2550
  bool isCXX11FinalKeyword() const;
2551
2552
  /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
2553
  /// enter a new C++ declarator scope and exit it when the function is
2554
  /// finished.
2555
  class DeclaratorScopeObj {
2556
    Parser &P;
2557
    CXXScopeSpec &SS;
2558
    bool EnteredScope;
2559
    bool CreatedScope;
2560
  public:
2561
    DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
2562
28.9M
      : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
2563
2564
314k
    void EnterDeclaratorScope() {
2565
314k
      assert(!EnteredScope && "Already entered the scope!");
2566
314k
      assert(SS.isSet() && "C++ scope was not set!");
2567
314k
2568
314k
      CreatedScope = true;
2569
314k
      P.EnterScope(0); // Not a decl scope.
2570
314k
2571
314k
      if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
2572
314k
        EnteredScope = true;
2573
314k
    }
2574
2575
28.9M
    ~DeclaratorScopeObj() {
2576
28.9M
      if (EnteredScope) {
2577
314k
        assert(SS.isSet() && "C++ scope was cleared ?");
2578
314k
        P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
2579
314k
      }
2580
28.9M
      if (CreatedScope)
2581
314k
        P.ExitScope();
2582
28.9M
    }
2583
  };
2584
2585
  /// ParseDeclarator - Parse and verify a newly-initialized declarator.
2586
  void ParseDeclarator(Declarator &D);
2587
  /// A function that parses a variant of direct-declarator.
2588
  typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
2589
  void ParseDeclaratorInternal(Declarator &D,
2590
                               DirectDeclParseFunction DirectDeclParser);
2591
2592
  enum AttrRequirements {
2593
    AR_NoAttributesParsed = 0, ///< No attributes are diagnosed.
2594
    AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes.
2595
    AR_GNUAttributesParsed = 1 << 1,
2596
    AR_CXX11AttributesParsed = 1 << 2,
2597
    AR_DeclspecAttributesParsed = 1 << 3,
2598
    AR_AllAttributesParsed = AR_GNUAttributesParsed |
2599
                             AR_CXX11AttributesParsed |
2600
                             AR_DeclspecAttributesParsed,
2601
    AR_VendorAttributesParsed = AR_GNUAttributesParsed |
2602
                                AR_DeclspecAttributesParsed
2603
  };
2604
2605
  void ParseTypeQualifierListOpt(
2606
      DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed,
2607
      bool AtomicAllowed = true, bool IdentifierRequired = false,
2608
      Optional<llvm::function_ref<void()>> CodeCompletionHandler = None);
2609
  void ParseDirectDeclarator(Declarator &D);
2610
  void ParseDecompositionDeclarator(Declarator &D);
2611
  void ParseParenDeclarator(Declarator &D);
2612
  void ParseFunctionDeclarator(Declarator &D,
2613
                               ParsedAttributes &attrs,
2614
                               BalancedDelimiterTracker &Tracker,
2615
                               bool IsAmbiguous,
2616
                               bool RequiresArg = false);
2617
  bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
2618
                         SourceLocation &RefQualifierLoc);
2619
  bool isFunctionDeclaratorIdentifierList();
2620
  void ParseFunctionDeclaratorIdentifierList(
2621
         Declarator &D,
2622
         SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
2623
  void ParseParameterDeclarationClause(
2624
         Declarator &D,
2625
         ParsedAttributes &attrs,
2626
         SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
2627
         SourceLocation &EllipsisLoc);
2628
  void ParseBracketDeclarator(Declarator &D);
2629
  void ParseMisplacedBracketDeclarator(Declarator &D);
2630
2631
  //===--------------------------------------------------------------------===//
2632
  // C++ 7: Declarations [dcl.dcl]
2633
2634
  /// The kind of attribute specifier we have found.
2635
  enum CXX11AttributeKind {
2636
    /// This is not an attribute specifier.
2637
    CAK_NotAttributeSpecifier,
2638
    /// This should be treated as an attribute-specifier.
2639
    CAK_AttributeSpecifier,
2640
    /// The next tokens are '[[', but this is not an attribute-specifier. This
2641
    /// is ill-formed by C++11 [dcl.attr.grammar]p6.
2642
    CAK_InvalidAttributeSpecifier
2643
  };
2644
  CXX11AttributeKind
2645
  isCXX11AttributeSpecifier(bool Disambiguate = false,
2646
                            bool OuterMightBeMessageSend = false);
2647
2648
  void DiagnoseUnexpectedNamespace(NamedDecl *Context);
2649
2650
  DeclGroupPtrTy ParseNamespace(DeclaratorContext Context,
2651
                                SourceLocation &DeclEnd,
2652
                                SourceLocation InlineLoc = SourceLocation());
2653
  void ParseInnerNamespace(std::vector<SourceLocation> &IdentLoc,
2654
                           std::vector<IdentifierInfo *> &Ident,
2655
                           std::vector<SourceLocation> &NamespaceLoc,
2656
                           unsigned int index, SourceLocation &InlineLoc,
2657
                           ParsedAttributes &attrs,
2658
                           BalancedDelimiterTracker &Tracker);
2659
  Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context);
2660
  Decl *ParseExportDeclaration();
2661
  DeclGroupPtrTy ParseUsingDirectiveOrDeclaration(
2662
      DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
2663
      SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs);
2664
  Decl *ParseUsingDirective(DeclaratorContext Context,
2665
                            SourceLocation UsingLoc,
2666
                            SourceLocation &DeclEnd,
2667
                            ParsedAttributes &attrs);
2668
2669
  struct UsingDeclarator {
2670
    SourceLocation TypenameLoc;
2671
    CXXScopeSpec SS;
2672
    UnqualifiedId Name;
2673
    SourceLocation EllipsisLoc;
2674
2675
150k
    void clear() {
2676
150k
      TypenameLoc = EllipsisLoc = SourceLocation();
2677
150k
      SS.clear();
2678
150k
      Name.clear();
2679
150k
    }
2680
  };
2681
2682
  bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D);
2683
  DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context,
2684
                                       const ParsedTemplateInfo &TemplateInfo,
2685
                                       SourceLocation UsingLoc,
2686
                                       SourceLocation &DeclEnd,
2687
                                       AccessSpecifier AS = AS_none);
2688
  Decl *ParseAliasDeclarationAfterDeclarator(
2689
      const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
2690
      UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
2691
      ParsedAttributes &Attrs, Decl **OwnedType = nullptr);
2692
2693
  Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
2694
  Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
2695
                            SourceLocation AliasLoc, IdentifierInfo *Alias,
2696
                            SourceLocation &DeclEnd);
2697
2698
  //===--------------------------------------------------------------------===//
2699
  // C++ 9: classes [class] and C structs/unions.
2700
  bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
2701
  void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
2702
                           DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo,
2703
                           AccessSpecifier AS, bool EnteringContext,
2704
                           DeclSpecContext DSC,
2705
                           ParsedAttributesWithRange &Attributes);
2706
  void SkipCXXMemberSpecification(SourceLocation StartLoc,
2707
                                  SourceLocation AttrFixitLoc,
2708
                                  unsigned TagType,
2709
                                  Decl *TagDecl);
2710
  void ParseCXXMemberSpecification(SourceLocation StartLoc,
2711
                                   SourceLocation AttrFixitLoc,
2712
                                   ParsedAttributesWithRange &Attrs,
2713
                                   unsigned TagType,
2714
                                   Decl *TagDecl);
2715
  ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2716
                                       SourceLocation &EqualLoc);
2717
  bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
2718
                                                 VirtSpecifiers &VS,
2719
                                                 ExprResult &BitfieldSize,
2720
                                                 LateParsedAttrList &LateAttrs);
2721
  void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D,
2722
                                                               VirtSpecifiers &VS);
2723
  DeclGroupPtrTy ParseCXXClassMemberDeclaration(
2724
      AccessSpecifier AS, ParsedAttributes &Attr,
2725
      const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2726
      ParsingDeclRAIIObject *DiagsFromTParams = nullptr);
2727
  DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas(
2728
      AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
2729
      DeclSpec::TST TagType, Decl *Tag);
2730
  void ParseConstructorInitializer(Decl *ConstructorDecl);
2731
  MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
2732
  void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2733
                                      Decl *ThisDecl);
2734
2735
  //===--------------------------------------------------------------------===//
2736
  // C++ 10: Derived classes [class.derived]
2737
  TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
2738
                                    SourceLocation &EndLocation);
2739
  void ParseBaseClause(Decl *ClassDecl);
2740
  BaseResult ParseBaseSpecifier(Decl *ClassDecl);
2741
  AccessSpecifier getAccessSpecifierIfPresent() const;
2742
2743
  bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
2744
                                    SourceLocation TemplateKWLoc,
2745
                                    IdentifierInfo *Name,
2746
                                    SourceLocation NameLoc,
2747
                                    bool EnteringContext,
2748
                                    ParsedType ObjectType,
2749
                                    UnqualifiedId &Id,
2750
                                    bool AssumeTemplateId);
2751
  bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2752
                                  ParsedType ObjectType,
2753
                                  UnqualifiedId &Result);
2754
2755
  //===--------------------------------------------------------------------===//
2756
  // OpenMP: Directives and clauses.
2757
  /// Parse clauses for '#pragma omp declare simd'.
2758
  DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr,
2759
                                            CachedTokens &Toks,
2760
                                            SourceLocation Loc);
2761
  /// Parses declarative OpenMP directives.
2762
  DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl(
2763
      AccessSpecifier &AS, ParsedAttributesWithRange &Attrs,
2764
      DeclSpec::TST TagType = DeclSpec::TST_unspecified,
2765
      Decl *TagDecl = nullptr);
2766
  /// Parse 'omp declare reduction' construct.
2767
  DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS);
2768
  /// Parses initializer for provided omp_priv declaration inside the reduction
2769
  /// initializer.
2770
  void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm);
2771
2772
  /// Parses simple list of variables.
2773
  ///
2774
  /// \param Kind Kind of the directive.
2775
  /// \param Callback Callback function to be called for the list elements.
2776
  /// \param AllowScopeSpecifier true, if the variables can have fully
2777
  /// qualified names.
2778
  ///
2779
  bool ParseOpenMPSimpleVarList(
2780
      OpenMPDirectiveKind Kind,
2781
      const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
2782
          Callback,
2783
      bool AllowScopeSpecifier);
2784
  /// Parses declarative or executable directive.
2785
  ///
2786
  /// \param Allowed ACK_Any, if any directives are allowed,
2787
  /// ACK_StatementsOpenMPAnyExecutable - if any executable directives are
2788
  /// allowed, ACK_StatementsOpenMPNonStandalone - if only non-standalone
2789
  /// executable directives are allowed.
2790
  ///
2791
  StmtResult
2792
  ParseOpenMPDeclarativeOrExecutableDirective(AllowedConstructsKind Allowed);
2793
  /// Parses clause of kind \a CKind for directive of a kind \a Kind.
2794
  ///
2795
  /// \param DKind Kind of current directive.
2796
  /// \param CKind Kind of current clause.
2797
  /// \param FirstClause true, if this is the first clause of a kind \a CKind
2798
  /// in current directive.
2799
  ///
2800
  OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
2801
                               OpenMPClauseKind CKind, bool FirstClause);
2802
  /// Parses clause with a single expression of a kind \a Kind.
2803
  ///
2804
  /// \param Kind Kind of current clause.
2805
  /// \param ParseOnly true to skip the clause's semantic actions and return
2806
  /// nullptr.
2807
  ///
2808
  OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind,
2809
                                         bool ParseOnly);
2810
  /// Parses simple clause of a kind \a Kind.
2811
  ///
2812
  /// \param Kind Kind of current clause.
2813
  /// \param ParseOnly true to skip the clause's semantic actions and return
2814
  /// nullptr.
2815
  ///
2816
  OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly);
2817
  /// Parses clause with a single expression and an additional argument
2818
  /// 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 *ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind,
2825
                                                bool ParseOnly);
2826
  /// Parses clause without any additional arguments.
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 *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false);
2833
  /// Parses clause with the list of variables of a kind \a Kind.
2834
  ///
2835
  /// \param Kind Kind of current clause.
2836
  /// \param ParseOnly true to skip the clause's semantic actions and return
2837
  /// nullptr.
2838
  ///
2839
  OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
2840
                                      OpenMPClauseKind Kind, bool ParseOnly);
2841
2842
public:
2843
  /// Parses simple expression in parens for single-expression clauses of OpenMP
2844
  /// constructs.
2845
  /// \param RLoc Returned location of right paren.
2846
  ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc);
2847
2848
  /// Data used for parsing list of variables in OpenMP clauses.
2849
  struct OpenMPVarListDataTy {
2850
    Expr *TailExpr = nullptr;
2851
    SourceLocation ColonLoc;
2852
    SourceLocation RLoc;
2853
    CXXScopeSpec ReductionIdScopeSpec;
2854
    DeclarationNameInfo ReductionId;
2855
    OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown;
2856
    OpenMPLinearClauseKind LinKind = OMPC_LINEAR_val;
2857
    OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
2858
    OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
2859
    bool IsMapTypeImplicit = false;
2860
    SourceLocation DepLinMapLoc;
2861
  };
2862
2863
  /// Parses clauses with list.
2864
  bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind,
2865
                          SmallVectorImpl<Expr *> &Vars,
2866
                          OpenMPVarListDataTy &Data);
2867
  bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2868
                          bool AllowDestructorName,
2869
                          bool AllowConstructorName,
2870
                          bool AllowDeductionGuide,
2871
                          ParsedType ObjectType,
2872
                          SourceLocation *TemplateKWLoc,
2873
                          UnqualifiedId &Result);
2874
2875
private:
2876
  //===--------------------------------------------------------------------===//
2877
  // C++ 14: Templates [temp]
2878
2879
  // C++ 14.1: Template Parameters [temp.param]
2880
  Decl *ParseDeclarationStartingWithTemplate(DeclaratorContext Context,
2881
                                             SourceLocation &DeclEnd,
2882
                                             ParsedAttributes &AccessAttrs,
2883
                                             AccessSpecifier AS = AS_none);
2884
  Decl *ParseTemplateDeclarationOrSpecialization(DeclaratorContext Context,
2885
                                                 SourceLocation &DeclEnd,
2886
                                                 ParsedAttributes &AccessAttrs,
2887
                                                 AccessSpecifier AS);
2888
  Decl *ParseSingleDeclarationAfterTemplate(
2889
      DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
2890
      ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd,
2891
      ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none);
2892
  bool ParseTemplateParameters(unsigned Depth,
2893
                               SmallVectorImpl<NamedDecl *> &TemplateParams,
2894
                               SourceLocation &LAngleLoc,
2895
                               SourceLocation &RAngleLoc);
2896
  bool ParseTemplateParameterList(unsigned Depth,
2897
                                  SmallVectorImpl<NamedDecl*> &TemplateParams);
2898
  bool isStartOfTemplateTypeParameter();
2899
  NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position);
2900
  NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position);
2901
  NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
2902
  NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
2903
  void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
2904
                                 SourceLocation CorrectLoc,
2905
                                 bool AlreadyHasEllipsis,
2906
                                 bool IdentifierHasName);
2907
  void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
2908
                                             Declarator &D);
2909
  // C++ 14.3: Template arguments [temp.arg]
2910
  typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
2911
2912
  bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
2913
                                      bool ConsumeLastToken,
2914
                                      bool ObjCGenericList);
2915
  bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
2916
                                        SourceLocation &LAngleLoc,
2917
                                        TemplateArgList &TemplateArgs,
2918
                                        SourceLocation &RAngleLoc);
2919
2920
  bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
2921
                               CXXScopeSpec &SS,
2922
                               SourceLocation TemplateKWLoc,
2923
                               UnqualifiedId &TemplateName,
2924
                               bool AllowTypeAnnotation = true);
2925
  void AnnotateTemplateIdTokenAsType(bool IsClassName = false);
2926
  bool IsTemplateArgumentList(unsigned Skip = 0);
2927
  bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
2928
  ParsedTemplateArgument ParseTemplateTemplateArgument();
2929
  ParsedTemplateArgument ParseTemplateArgument();
2930
  Decl *ParseExplicitInstantiation(DeclaratorContext Context,
2931
                                   SourceLocation ExternLoc,
2932
                                   SourceLocation TemplateLoc,
2933
                                   SourceLocation &DeclEnd,
2934
                                   ParsedAttributes &AccessAttrs,
2935
                                   AccessSpecifier AS = AS_none);
2936
2937
  //===--------------------------------------------------------------------===//
2938
  // Modules
2939
  DeclGroupPtrTy ParseModuleDecl();
2940
  Decl *ParseModuleImport(SourceLocation AtLoc);
2941
  bool parseMisplacedModuleImport();
2942
19.3M
  bool tryParseMisplacedModuleImport() {
2943
19.3M
    tok::TokenKind Kind = Tok.getKind();
2944
19.3M
    if (Kind == tok::annot_module_begin || 
Kind == tok::annot_module_end19.3M
||
2945
19.3M
        
Kind == tok::annot_module_include19.3M
)
2946
21
      return parseMisplacedModuleImport();
2947
19.3M
    return false;
2948
19.3M
  }
2949
2950
  bool ParseModuleName(
2951
      SourceLocation UseLoc,
2952
      SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
2953
      bool IsImport);
2954
2955
  //===--------------------------------------------------------------------===//
2956
  // C++11/G++: Type Traits [Type-Traits.html in the GCC manual]
2957
  ExprResult ParseTypeTrait();
2958
2959
  //===--------------------------------------------------------------------===//
2960
  // Embarcadero: Arary and Expression Traits
2961
  ExprResult ParseArrayTypeTrait();
2962
  ExprResult ParseExpressionTrait();
2963
2964
  //===--------------------------------------------------------------------===//
2965
  // Preprocessor code-completion pass-through
2966
  void CodeCompleteDirective(bool InConditional) override;
2967
  void CodeCompleteInConditionalExclusion() override;
2968
  void CodeCompleteMacroName(bool IsDefinition) override;
2969
  void CodeCompletePreprocessorExpression() override;
2970
  void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo,
2971
                                 unsigned ArgumentIndex) override;
2972
  void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) override;
2973
  void CodeCompleteNaturalLanguage() override;
2974
};
2975
2976
}  // end namespace clang
2977
2978
#endif