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