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