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