Coverage Report

Created: 2020-02-25 14:32

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