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