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