clang  9.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, unsigned TST = 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  //===--------------------------------------------------------------------===//
1784  // C++ 5.2p1: C++ Type Identification
1785  ExprResult ParseCXXTypeid();
1786 
1787  //===--------------------------------------------------------------------===//
1788  // C++ : Microsoft __uuidof Expression
1789  ExprResult ParseCXXUuidof();
1790 
1791  //===--------------------------------------------------------------------===//
1792  // C++ 5.2.4: C++ Pseudo-Destructor Expressions
1793  ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1794  tok::TokenKind OpKind,
1795  CXXScopeSpec &SS,
1796  ParsedType ObjectType);
1797 
1798  //===--------------------------------------------------------------------===//
1799  // C++ 9.3.2: C++ 'this' pointer
1800  ExprResult ParseCXXThis();
1801 
1802  //===--------------------------------------------------------------------===//
1803  // C++ 15: C++ Throw Expression
1804  ExprResult ParseThrowExpression();
1805 
1806  ExceptionSpecificationType tryParseExceptionSpecification(
1807  bool Delayed,
1808  SourceRange &SpecificationRange,
1809  SmallVectorImpl<ParsedType> &DynamicExceptions,
1810  SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
1811  ExprResult &NoexceptExpr,
1812  CachedTokens *&ExceptionSpecTokens);
1813 
1814  // EndLoc is filled with the location of the last token of the specification.
1815  ExceptionSpecificationType ParseDynamicExceptionSpecification(
1816  SourceRange &SpecificationRange,
1817  SmallVectorImpl<ParsedType> &Exceptions,
1819 
1820  //===--------------------------------------------------------------------===//
1821  // C++0x 8: Function declaration trailing-return-type
1822  TypeResult ParseTrailingReturnType(SourceRange &Range,
1823  bool MayBeFollowedByDirectInit);
1824 
1825  //===--------------------------------------------------------------------===//
1826  // C++ 2.13.5: C++ Boolean Literals
1827  ExprResult ParseCXXBoolLiteral();
1828 
1829  //===--------------------------------------------------------------------===//
1830  // C++ 5.2.3: Explicit type conversion (functional notation)
1831  ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
1832 
1833  /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1834  /// This should only be called when the current token is known to be part of
1835  /// simple-type-specifier.
1836  void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
1837 
1838  bool ParseCXXTypeSpecifierSeq(DeclSpec &DS);
1839 
1840  //===--------------------------------------------------------------------===//
1841  // C++ 5.3.4 and 5.3.5: C++ new and delete
1842  bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs,
1843  Declarator &D);
1844  void ParseDirectNewDeclarator(Declarator &D);
1845  ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
1846  ExprResult ParseCXXDeleteExpression(bool UseGlobal,
1847  SourceLocation Start);
1848 
1849  //===--------------------------------------------------------------------===//
1850  // C++ if/switch/while/for condition expression.
1851  struct ForRangeInfo;
1852  Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt,
1853  SourceLocation Loc,
1855  ForRangeInfo *FRI = nullptr);
1856 
1857  //===--------------------------------------------------------------------===//
1858  // C++ Coroutines
1859 
1860  ExprResult ParseCoyieldExpression();
1861 
1862  //===--------------------------------------------------------------------===//
1863  // C99 6.7.8: Initialization.
1864 
1865  /// ParseInitializer
1866  /// initializer: [C99 6.7.8]
1867  /// assignment-expression
1868  /// '{' ...
1869  ExprResult ParseInitializer() {
1870  if (Tok.isNot(tok::l_brace))
1871  return ParseAssignmentExpression();
1872  return ParseBraceInitializer();
1873  }
1874  bool MayBeDesignationStart();
1875  ExprResult ParseBraceInitializer();
1876  ExprResult ParseInitializerWithPotentialDesignator();
1877 
1878  //===--------------------------------------------------------------------===//
1879  // clang Expressions
1880 
1881  ExprResult ParseBlockLiteralExpression(); // ^{...}
1882 
1883  //===--------------------------------------------------------------------===//
1884  // Objective-C Expressions
1885  ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
1886  ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
1887  ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
1888  ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
1889  ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
1890  ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
1891  ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
1892  ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
1893  ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
1894  ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
1895  ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
1896  bool isSimpleObjCMessageExpression();
1897  ExprResult ParseObjCMessageExpression();
1898  ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
1899  SourceLocation SuperLoc,
1900  ParsedType ReceiverType,
1901  Expr *ReceiverExpr);
1902  ExprResult ParseAssignmentExprWithObjCMessageExprStart(
1903  SourceLocation LBracloc, SourceLocation SuperLoc,
1904  ParsedType ReceiverType, Expr *ReceiverExpr);
1905  bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
1906 
1907  //===--------------------------------------------------------------------===//
1908  // C99 6.8: Statements and Blocks.
1909 
1910  /// A SmallVector of statements, with stack size 32 (as that is the only one
1911  /// used.)
1913  /// A SmallVector of expressions, with stack size 12 (the maximum used.)
1915  /// A SmallVector of types.
1917 
1918  StmtResult
1919  ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
1920  ParsedStmtContext StmtCtx = ParsedStmtContext::SubStmt);
1921  StmtResult ParseStatementOrDeclaration(
1922  StmtVector &Stmts, ParsedStmtContext StmtCtx,
1923  SourceLocation *TrailingElseLoc = nullptr);
1924  StmtResult ParseStatementOrDeclarationAfterAttributes(
1925  StmtVector &Stmts,
1926  ParsedStmtContext StmtCtx,
1927  SourceLocation *TrailingElseLoc,
1928  ParsedAttributesWithRange &Attrs);
1929  StmtResult ParseExprStatement(ParsedStmtContext StmtCtx);
1930  StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs,
1931  ParsedStmtContext StmtCtx);
1932  StmtResult ParseCaseStatement(ParsedStmtContext StmtCtx,
1933  bool MissingCase = false,
1934  ExprResult Expr = ExprResult());
1935  StmtResult ParseDefaultStatement(ParsedStmtContext StmtCtx);
1936  StmtResult ParseCompoundStatement(bool isStmtExpr = false);
1937  StmtResult ParseCompoundStatement(bool isStmtExpr,
1938  unsigned ScopeFlags);
1939  void ParseCompoundStatementLeadingPragmas();
1940  bool ConsumeNullStmt(StmtVector &Stmts);
1941  StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
1942  bool ParseParenExprOrCondition(StmtResult *InitStmt,
1943  Sema::ConditionResult &CondResult,
1944  SourceLocation Loc,
1945  Sema::ConditionKind CK);
1946  StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
1947  StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
1948  StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
1949  StmtResult ParseDoStatement();
1950  StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
1951  StmtResult ParseGotoStatement();
1952  StmtResult ParseContinueStatement();
1953  StmtResult ParseBreakStatement();
1954  StmtResult ParseReturnStatement();
1955  StmtResult ParseAsmStatement(bool &msAsm);
1956  StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
1957  StmtResult ParsePragmaLoopHint(StmtVector &Stmts,
1958  ParsedStmtContext StmtCtx,
1959  SourceLocation *TrailingElseLoc,
1960  ParsedAttributesWithRange &Attrs);
1961 
1962  /// Describes the behavior that should be taken for an __if_exists
1963  /// block.
1964  enum IfExistsBehavior {
1965  /// Parse the block; this code is always used.
1966  IEB_Parse,
1967  /// Skip the block entirely; this code is never used.
1968  IEB_Skip,
1969  /// Parse the block as a dependent block, which may be used in
1970  /// some template instantiations but not others.
1971  IEB_Dependent
1972  };
1973 
1974  /// Describes the condition of a Microsoft __if_exists or
1975  /// __if_not_exists block.
1976  struct IfExistsCondition {
1977  /// The location of the initial keyword.
1978  SourceLocation KeywordLoc;
1979  /// Whether this is an __if_exists block (rather than an
1980  /// __if_not_exists block).
1981  bool IsIfExists;
1982 
1983  /// Nested-name-specifier preceding the name.
1984  CXXScopeSpec SS;
1985 
1986  /// The name we're looking for.
1987  UnqualifiedId Name;
1988 
1989  /// The behavior of this __if_exists or __if_not_exists block
1990  /// should.
1991  IfExistsBehavior Behavior;
1992  };
1993 
1994  bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
1995  void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
1996  void ParseMicrosoftIfExistsExternalDeclaration();
1997  void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
1998  ParsedAttributes &AccessAttrs,
1999  AccessSpecifier &CurAS);
2000  bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
2001  bool &InitExprsOk);
2002  bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
2003  SmallVectorImpl<Expr *> &Constraints,
2004  SmallVectorImpl<Expr *> &Exprs);
2005 
2006  //===--------------------------------------------------------------------===//
2007  // C++ 6: Statements and Blocks
2008 
2009  StmtResult ParseCXXTryBlock();
2010  StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
2011  StmtResult ParseCXXCatchBlock(bool FnCatch = false);
2012 
2013  //===--------------------------------------------------------------------===//
2014  // MS: SEH Statements and Blocks
2015 
2016  StmtResult ParseSEHTryBlock();
2017  StmtResult ParseSEHExceptBlock(SourceLocation Loc);
2018  StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
2019  StmtResult ParseSEHLeaveStatement();
2020 
2021  //===--------------------------------------------------------------------===//
2022  // Objective-C Statements
2023 
2024  StmtResult ParseObjCAtStatement(SourceLocation atLoc,
2025  ParsedStmtContext StmtCtx);
2026  StmtResult ParseObjCTryStmt(SourceLocation atLoc);
2027  StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
2028  StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
2029  StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
2030 
2031 
2032  //===--------------------------------------------------------------------===//
2033  // C99 6.7: Declarations.
2034 
2035  /// A context for parsing declaration specifiers. TODO: flesh this
2036  /// out, there are other significant restrictions on specifiers than
2037  /// would be best implemented in the parser.
2038  enum class DeclSpecContext {
2039  DSC_normal, // normal context
2040  DSC_class, // class context, enables 'friend'
2041  DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
2042  DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
2043  DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration
2044  DSC_top_level, // top-level/namespace declaration context
2045  DSC_template_param, // template parameter context
2046  DSC_template_type_arg, // template type argument context
2047  DSC_objc_method_result, // ObjC method result context, enables 'instancetype'
2048  DSC_condition // condition declaration context
2049  };
2050 
2051  /// Is this a context in which we are parsing just a type-specifier (or
2052  /// trailing-type-specifier)?
2053  static bool isTypeSpecifier(DeclSpecContext DSC) {
2054  switch (DSC) {
2055  case DeclSpecContext::DSC_normal:
2056  case DeclSpecContext::DSC_template_param:
2057  case DeclSpecContext::DSC_class:
2058  case DeclSpecContext::DSC_top_level:
2059  case DeclSpecContext::DSC_objc_method_result:
2060  case DeclSpecContext::DSC_condition:
2061  return false;
2062 
2063  case DeclSpecContext::DSC_template_type_arg:
2064  case DeclSpecContext::DSC_type_specifier:
2065  case DeclSpecContext::DSC_trailing:
2066  case DeclSpecContext::DSC_alias_declaration:
2067  return true;
2068  }
2069  llvm_unreachable("Missing DeclSpecContext case");
2070  }
2071 
2072  /// Is this a context in which we can perform class template argument
2073  /// deduction?
2074  static bool isClassTemplateDeductionContext(DeclSpecContext DSC) {
2075  switch (DSC) {
2076  case DeclSpecContext::DSC_normal:
2077  case DeclSpecContext::DSC_template_param:
2078  case DeclSpecContext::DSC_class:
2079  case DeclSpecContext::DSC_top_level:
2080  case DeclSpecContext::DSC_condition:
2081  case DeclSpecContext::DSC_type_specifier:
2082  return true;
2083 
2084  case DeclSpecContext::DSC_objc_method_result:
2085  case DeclSpecContext::DSC_template_type_arg:
2086  case DeclSpecContext::DSC_trailing:
2087  case DeclSpecContext::DSC_alias_declaration:
2088  return false;
2089  }
2090  llvm_unreachable("Missing DeclSpecContext case");
2091  }
2092 
2093  /// Information on a C++0x for-range-initializer found while parsing a
2094  /// declaration which turns out to be a for-range-declaration.
2095  struct ForRangeInit {
2097  ExprResult RangeExpr;
2098 
2099  bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
2100  };
2101  struct ForRangeInfo : ForRangeInit {
2102  StmtResult LoopVar;
2103  };
2104 
2105  DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context,
2106  SourceLocation &DeclEnd,
2107  ParsedAttributesWithRange &attrs);
2108  DeclGroupPtrTy ParseSimpleDeclaration(DeclaratorContext Context,
2109  SourceLocation &DeclEnd,
2110  ParsedAttributesWithRange &attrs,
2111  bool RequireSemi,
2112  ForRangeInit *FRI = nullptr);
2113  bool MightBeDeclarator(DeclaratorContext Context);
2114  DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context,
2115  SourceLocation *DeclEnd = nullptr,
2116  ForRangeInit *FRI = nullptr);
2117  Decl *ParseDeclarationAfterDeclarator(Declarator &D,
2118  const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
2119  bool ParseAsmAttributesAfterDeclarator(Declarator &D);
2120  Decl *ParseDeclarationAfterDeclaratorAndAttributes(
2121  Declarator &D,
2122  const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2123  ForRangeInit *FRI = nullptr);
2124  Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
2125  Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
2126 
2127  /// When in code-completion, skip parsing of the function/method body
2128  /// unless the body contains the code-completion point.
2129  ///
2130  /// \returns true if the function body was skipped.
2131  bool trySkippingFunctionBody();
2132 
2133  bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2134  const ParsedTemplateInfo &TemplateInfo,
2135  AccessSpecifier AS, DeclSpecContext DSC,
2136  ParsedAttributesWithRange &Attrs);
2137  DeclSpecContext
2138  getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context);
2139  void ParseDeclarationSpecifiers(
2140  DeclSpec &DS,
2141  const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2142  AccessSpecifier AS = AS_none,
2143  DeclSpecContext DSC = DeclSpecContext::DSC_normal,
2144  LateParsedAttrList *LateAttrs = nullptr);
2145  bool DiagnoseMissingSemiAfterTagDefinition(
2146  DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext,
2147  LateParsedAttrList *LateAttrs = nullptr);
2148 
2149  void ParseSpecifierQualifierList(
2150  DeclSpec &DS, AccessSpecifier AS = AS_none,
2151  DeclSpecContext DSC = DeclSpecContext::DSC_normal);
2152 
2153  void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
2154  DeclaratorContext Context);
2155 
2156  void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
2157  const ParsedTemplateInfo &TemplateInfo,
2158  AccessSpecifier AS, DeclSpecContext DSC);
2159  void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
2160  void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType,
2161  Decl *TagDecl);
2162 
2163  void ParseStructDeclaration(
2164  ParsingDeclSpec &DS,
2165  llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback);
2166 
2167  bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
2168  bool isTypeSpecifierQualifier();
2169 
2170  /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
2171  /// is definitely a type-specifier. Return false if it isn't part of a type
2172  /// specifier or if we're not sure.
2173  bool isKnownToBeTypeSpecifier(const Token &Tok) const;
2174 
2175  /// Return true if we know that we are definitely looking at a
2176  /// decl-specifier, and isn't part of an expression such as a function-style
2177  /// cast. Return false if it's no a decl-specifier, or we're not sure.
2178  bool isKnownToBeDeclarationSpecifier() {
2179  if (getLangOpts().CPlusPlus)
2180  return isCXXDeclarationSpecifier() == TPResult::True;
2181  return isDeclarationSpecifier(true);
2182  }
2183 
2184  /// isDeclarationStatement - Disambiguates between a declaration or an
2185  /// expression statement, when parsing function bodies.
2186  /// Returns true for declaration, false for expression.
2187  bool isDeclarationStatement() {
2188  if (getLangOpts().CPlusPlus)
2189  return isCXXDeclarationStatement();
2190  return isDeclarationSpecifier(true);
2191  }
2192 
2193  /// isForInitDeclaration - Disambiguates between a declaration or an
2194  /// expression in the context of the C 'clause-1' or the C++
2195  // 'for-init-statement' part of a 'for' statement.
2196  /// Returns true for declaration, false for expression.
2197  bool isForInitDeclaration() {
2198  if (getLangOpts().OpenMP)
2199  Actions.startOpenMPLoop();
2200  if (getLangOpts().CPlusPlus)
2201  return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
2202  return isDeclarationSpecifier(true);
2203  }
2204 
2205  /// Determine whether this is a C++1z for-range-identifier.
2206  bool isForRangeIdentifier();
2207 
2208  /// Determine whether we are currently at the start of an Objective-C
2209  /// class message that appears to be missing the open bracket '['.
2210  bool isStartOfObjCClassMessageMissingOpenBracket();
2211 
2212  /// Starting with a scope specifier, identifier, or
2213  /// template-id that refers to the current class, determine whether
2214  /// this is a constructor declarator.
2215  bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false);
2216 
2217  /// Specifies the context in which type-id/expression
2218  /// disambiguation will occur.
2219  enum TentativeCXXTypeIdContext {
2220  TypeIdInParens,
2221  TypeIdUnambiguous,
2222  TypeIdAsTemplateArgument
2223  };
2224 
2225 
2226  /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
2227  /// whether the parens contain an expression or a type-id.
2228  /// Returns true for a type-id and false for an expression.
2229  bool isTypeIdInParens(bool &isAmbiguous) {
2230  if (getLangOpts().CPlusPlus)
2231  return isCXXTypeId(TypeIdInParens, isAmbiguous);
2232  isAmbiguous = false;
2233  return isTypeSpecifierQualifier();
2234  }
2235  bool isTypeIdInParens() {
2236  bool isAmbiguous;
2237  return isTypeIdInParens(isAmbiguous);
2238  }
2239 
2240  /// Checks if the current tokens form type-id or expression.
2241  /// It is similar to isTypeIdInParens but does not suppose that type-id
2242  /// is in parenthesis.
2243  bool isTypeIdUnambiguously() {
2244  bool IsAmbiguous;
2245  if (getLangOpts().CPlusPlus)
2246  return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous);
2247  return isTypeSpecifierQualifier();
2248  }
2249 
2250  /// isCXXDeclarationStatement - C++-specialized function that disambiguates
2251  /// between a declaration or an expression statement, when parsing function
2252  /// bodies. Returns true for declaration, false for expression.
2253  bool isCXXDeclarationStatement();
2254 
2255  /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
2256  /// between a simple-declaration or an expression-statement.
2257  /// If during the disambiguation process a parsing error is encountered,
2258  /// the function returns true to let the declaration parsing code handle it.
2259  /// Returns false if the statement is disambiguated as expression.
2260  bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
2261 
2262  /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
2263  /// a constructor-style initializer, when parsing declaration statements.
2264  /// Returns true for function declarator and false for constructor-style
2265  /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
2266  /// might be a constructor-style initializer.
2267  /// If during the disambiguation process a parsing error is encountered,
2268  /// the function returns true to let the declaration parsing code handle it.
2269  bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr);
2270 
2272  enum class ConditionOrInitStatement {
2273  Expression, ///< Disambiguated as an expression (either kind).
2274  ConditionDecl, ///< Disambiguated as the declaration form of condition.
2275  InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement.
2276  ForRangeDecl, ///< Disambiguated as a for-range declaration.
2277  Error ///< Can't be any of the above!
2278  };
2279  /// Disambiguates between the different kinds of things that can happen
2280  /// after 'if (' or 'switch ('. This could be one of two different kinds of
2281  /// declaration (depending on whether there is a ';' later) or an expression.
2282  ConditionOrInitStatement
2283  isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt,
2284  bool CanBeForRangeDecl);
2285 
2286  bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
2287  bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
2288  bool isAmbiguous;
2289  return isCXXTypeId(Context, isAmbiguous);
2290  }
2291 
2292  /// TPResult - Used as the result value for functions whose purpose is to
2293  /// disambiguate C++ constructs by "tentatively parsing" them.
2294  enum class TPResult {
2295  True, False, Ambiguous, Error
2296  };
2297 
2298  /// Based only on the given token kind, determine whether we know that
2299  /// we're at the start of an expression or a type-specifier-seq (which may
2300  /// be an expression, in C++).
2301  ///
2302  /// This routine does not attempt to resolve any of the trick cases, e.g.,
2303  /// those involving lookup of identifiers.
2304  ///
2305  /// \returns \c TPR_true if this token starts an expression, \c TPR_false if
2306  /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot
2307  /// tell.
2308  TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind);
2309 
2310  /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a
2311  /// declaration specifier, TPResult::False if it is not,
2312  /// TPResult::Ambiguous if it could be either a decl-specifier or a
2313  /// function-style cast, and TPResult::Error if a parsing error was
2314  /// encountered. If it could be a braced C++11 function-style cast, returns
2315  /// BracedCastResult.
2316  /// Doesn't consume tokens.
2317  TPResult
2318  isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False,
2319  bool *InvalidAsDeclSpec = nullptr);
2320 
2321  /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
2322  /// \c TPResult::Ambiguous, determine whether the decl-specifier would be
2323  /// a type-specifier other than a cv-qualifier.
2324  bool isCXXDeclarationSpecifierAType();
2325 
2326  /// Determine whether the current token sequence might be
2327  /// '<' template-argument-list '>'
2328  /// rather than a less-than expression.
2329  TPResult isTemplateArgumentList(unsigned TokensToSkip);
2330 
2331  /// Determine whether an identifier has been tentatively declared as a
2332  /// non-type. Such tentative declarations should not be found to name a type
2333  /// during a tentative parse, but also should not be annotated as a non-type.
2334  bool isTentativelyDeclared(IdentifierInfo *II);
2335 
2336  // "Tentative parsing" functions, used for disambiguation. If a parsing error
2337  // is encountered they will return TPResult::Error.
2338  // Returning TPResult::True/False indicates that the ambiguity was
2339  // resolved and tentative parsing may stop. TPResult::Ambiguous indicates
2340  // that more tentative parsing is necessary for disambiguation.
2341  // They all consume tokens, so backtracking should be used after calling them.
2342 
2343  TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
2344  TPResult TryParseTypeofSpecifier();
2345  TPResult TryParseProtocolQualifiers();
2346  TPResult TryParsePtrOperatorSeq();
2347  TPResult TryParseOperatorId();
2348  TPResult TryParseInitDeclaratorList();
2349  TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true,
2350  bool mayHaveDirectInit = false);
2351  TPResult
2352  TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr,
2353  bool VersusTemplateArg = false);
2354  TPResult TryParseFunctionDeclarator();
2355  TPResult TryParseBracketDeclarator();
2356  TPResult TryConsumeDeclarationSpecifier();
2357 
2358 public:
2359  TypeResult ParseTypeName(SourceRange *Range = nullptr,
2360  DeclaratorContext Context
2362  AccessSpecifier AS = AS_none,
2363  Decl **OwnedType = nullptr,
2364  ParsedAttributes *Attrs = nullptr);
2365 
2366 private:
2367  void ParseBlockId(SourceLocation CaretLoc);
2368 
2369  /// Are [[]] attributes enabled?
2370  bool standardAttributesAllowed() const {
2371  const LangOptions &LO = getLangOpts();
2372  return LO.DoubleSquareBracketAttributes;
2373  }
2374 
2375  // Check for the start of an attribute-specifier-seq in a context where an
2376  // attribute is not allowed.
2377  bool CheckProhibitedCXX11Attribute() {
2378  assert(Tok.is(tok::l_square));
2379  if (!standardAttributesAllowed() || NextToken().isNot(tok::l_square))
2380  return false;
2381  return DiagnoseProhibitedCXX11Attribute();
2382  }
2383 
2384  bool DiagnoseProhibitedCXX11Attribute();
2385  void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2386  SourceLocation CorrectLocation) {
2387  if (!standardAttributesAllowed())
2388  return;
2389  if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
2390  Tok.isNot(tok::kw_alignas))
2391  return;
2392  DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
2393  }
2394  void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2395  SourceLocation CorrectLocation);
2396 
2397  void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
2398  DeclSpec &DS, Sema::TagUseKind TUK);
2399 
2400  // FixItLoc = possible correct location for the attributes
2401  void ProhibitAttributes(ParsedAttributesWithRange &Attrs,
2402  SourceLocation FixItLoc = SourceLocation()) {
2403  if (Attrs.Range.isInvalid())
2404  return;
2405  DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc);
2406  Attrs.clear();
2407  }
2408 
2409  void ProhibitAttributes(ParsedAttributesViewWithRange &Attrs,
2410  SourceLocation FixItLoc = SourceLocation()) {
2411  if (Attrs.Range.isInvalid())
2412  return;
2413  DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc);
2414  Attrs.clearListOnly();
2415  }
2416  void DiagnoseProhibitedAttributes(const SourceRange &Range,
2417  SourceLocation FixItLoc);
2418 
2419  // Forbid C++11 and C2x attributes that appear on certain syntactic locations
2420  // which standard permits but we don't supported yet, for example, attributes
2421  // appertain to decl specifiers.
2422  void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
2423  unsigned DiagID);
2424 
2425  /// Skip C++11 and C2x attributes and return the end location of the
2426  /// last one.
2427  /// \returns SourceLocation() if there are no attributes.
2428  SourceLocation SkipCXX11Attributes();
2429 
2430  /// Diagnose and skip C++11 and C2x attributes that appear in syntactic
2431  /// locations where attributes are not allowed.
2432  void DiagnoseAndSkipCXX11Attributes();
2433 
2434  /// Parses syntax-generic attribute arguments for attributes which are
2435  /// known to the implementation, and adds them to the given ParsedAttributes
2436  /// list with the given attribute syntax. Returns the number of arguments
2437  /// parsed for the attribute.
2438  unsigned
2439  ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2440  ParsedAttributes &Attrs, SourceLocation *EndLoc,
2441  IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2442  ParsedAttr::Syntax Syntax);
2443 
2444  void MaybeParseGNUAttributes(Declarator &D,
2445  LateParsedAttrList *LateAttrs = nullptr) {
2446  if (Tok.is(tok::kw___attribute)) {
2447  ParsedAttributes attrs(AttrFactory);
2448  SourceLocation endLoc;
2449  ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D);
2450  D.takeAttributes(attrs, endLoc);
2451  }
2452  }
2453  void MaybeParseGNUAttributes(ParsedAttributes &attrs,
2454  SourceLocation *endLoc = nullptr,
2455  LateParsedAttrList *LateAttrs = nullptr) {
2456  if (Tok.is(tok::kw___attribute))
2457  ParseGNUAttributes(attrs, endLoc, LateAttrs);
2458  }
2459  void ParseGNUAttributes(ParsedAttributes &attrs,
2460  SourceLocation *endLoc = nullptr,
2461  LateParsedAttrList *LateAttrs = nullptr,
2462  Declarator *D = nullptr);
2463  void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
2464  SourceLocation AttrNameLoc,
2465  ParsedAttributes &Attrs, SourceLocation *EndLoc,
2466  IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2467  ParsedAttr::Syntax Syntax, Declarator *D);
2468  IdentifierLoc *ParseIdentifierLoc();
2469 
2470  unsigned
2471  ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2472  ParsedAttributes &Attrs, SourceLocation *EndLoc,
2473  IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2474  ParsedAttr::Syntax Syntax);
2475 
2476  void MaybeParseCXX11Attributes(Declarator &D) {
2477  if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
2478  ParsedAttributesWithRange attrs(AttrFactory);
2479  SourceLocation endLoc;
2480  ParseCXX11Attributes(attrs, &endLoc);
2481  D.takeAttributes(attrs, endLoc);
2482  }
2483  }
2484  void MaybeParseCXX11Attributes(ParsedAttributes &attrs,
2485  SourceLocation *endLoc = nullptr) {
2486  if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
2487  ParsedAttributesWithRange attrsWithRange(AttrFactory);
2488  ParseCXX11Attributes(attrsWithRange, endLoc);
2489  attrs.takeAllFrom(attrsWithRange);
2490  }
2491  }
2492  void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2493  SourceLocation *endLoc = nullptr,
2494  bool OuterMightBeMessageSend = false) {
2495  if (standardAttributesAllowed() &&
2496  isCXX11AttributeSpecifier(false, OuterMightBeMessageSend))
2497  ParseCXX11Attributes(attrs, endLoc);
2498  }
2499 
2500  void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
2501  SourceLocation *EndLoc = nullptr);
2502  void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2503  SourceLocation *EndLoc = nullptr);
2504  /// Parses a C++11 (or C2x)-style attribute argument list. Returns true
2505  /// if this results in adding an attribute to the ParsedAttributes list.
2506  bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
2507  SourceLocation AttrNameLoc,
2508  ParsedAttributes &Attrs, SourceLocation *EndLoc,
2509  IdentifierInfo *ScopeName,
2510  SourceLocation ScopeLoc);
2511 
2512  IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc);
2513 
2514  void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
2515  SourceLocation *endLoc = nullptr) {
2516  if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
2517  ParseMicrosoftAttributes(attrs, endLoc);
2518  }
2519  void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs);
2520  void ParseMicrosoftAttributes(ParsedAttributes &attrs,
2521  SourceLocation *endLoc = nullptr);
2522  void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2523  SourceLocation *End = nullptr) {
2524  const auto &LO = getLangOpts();
2525  if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec))
2526  ParseMicrosoftDeclSpecs(Attrs, End);
2527  }
2528  void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2529  SourceLocation *End = nullptr);
2530  bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
2531  SourceLocation AttrNameLoc,
2532  ParsedAttributes &Attrs);
2533  void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
2534  void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2535  SourceLocation SkipExtendedMicrosoftTypeAttributes();
2536  void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
2537  void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
2538  void ParseOpenCLKernelAttributes(ParsedAttributes &attrs);
2539  void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
2540  /// Parses opencl_unroll_hint attribute if language is OpenCL v2.0
2541  /// or higher.
2542  /// \return false if error happens.
2543  bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
2544  if (getLangOpts().OpenCL)
2545  return ParseOpenCLUnrollHintAttribute(Attrs);
2546  return true;
2547  }
2548  /// Parses opencl_unroll_hint attribute.
2549  /// \return false if error happens.
2550  bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs);
2551  void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
2552 
2553  VersionTuple ParseVersionTuple(SourceRange &Range);
2554  void ParseAvailabilityAttribute(IdentifierInfo &Availability,
2555  SourceLocation AvailabilityLoc,
2556  ParsedAttributes &attrs,
2557  SourceLocation *endLoc,
2558  IdentifierInfo *ScopeName,
2559  SourceLocation ScopeLoc,
2560  ParsedAttr::Syntax Syntax);
2561 
2562  Optional<AvailabilitySpec> ParseAvailabilitySpec();
2563  ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc);
2564 
2565  void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol,
2566  SourceLocation Loc,
2567  ParsedAttributes &Attrs,
2568  SourceLocation *EndLoc,
2569  IdentifierInfo *ScopeName,
2570  SourceLocation ScopeLoc,
2571  ParsedAttr::Syntax Syntax);
2572 
2573  void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
2574  SourceLocation ObjCBridgeRelatedLoc,
2575  ParsedAttributes &attrs,
2576  SourceLocation *endLoc,
2577  IdentifierInfo *ScopeName,
2578  SourceLocation ScopeLoc,
2579  ParsedAttr::Syntax Syntax);
2580 
2581  void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
2582  SourceLocation AttrNameLoc,
2583  ParsedAttributes &Attrs,
2584  SourceLocation *EndLoc,
2585  IdentifierInfo *ScopeName,
2586  SourceLocation ScopeLoc,
2587  ParsedAttr::Syntax Syntax);
2588 
2589  void
2590  ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
2591  SourceLocation AttrNameLoc, ParsedAttributes &Attrs,
2592  SourceLocation *EndLoc, IdentifierInfo *ScopeName,
2593  SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax);
2594 
2595  void ParseTypeofSpecifier(DeclSpec &DS);
2596  SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
2597  void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
2598  SourceLocation StartLoc,
2599  SourceLocation EndLoc);
2600  void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
2601  void ParseAtomicSpecifier(DeclSpec &DS);
2602 
2603  ExprResult ParseAlignArgument(SourceLocation Start,
2604  SourceLocation &EllipsisLoc);
2605  void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2606  SourceLocation *endLoc = nullptr);
2607 
2608  VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
2609  VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
2610  return isCXX11VirtSpecifier(Tok);
2611  }
2612  void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface,
2613  SourceLocation FriendLoc);
2614 
2615  bool isCXX11FinalKeyword() const;
2616 
2617  /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
2618  /// enter a new C++ declarator scope and exit it when the function is
2619  /// finished.
2620  class DeclaratorScopeObj {
2621  Parser &P;
2622  CXXScopeSpec &SS;
2623  bool EnteredScope;
2624  bool CreatedScope;
2625  public:
2626  DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
2627  : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
2628 
2629  void EnterDeclaratorScope() {
2630  assert(!EnteredScope && "Already entered the scope!");
2631  assert(SS.isSet() && "C++ scope was not set!");
2632 
2633  CreatedScope = true;
2634  P.EnterScope(0); // Not a decl scope.
2635 
2636  if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
2637  EnteredScope = true;
2638  }
2639 
2640  ~DeclaratorScopeObj() {
2641  if (EnteredScope) {
2642  assert(SS.isSet() && "C++ scope was cleared ?");
2643  P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
2644  }
2645  if (CreatedScope)
2646  P.ExitScope();
2647  }
2648  };
2649 
2650  /// ParseDeclarator - Parse and verify a newly-initialized declarator.
2651  void ParseDeclarator(Declarator &D);
2652  /// A function that parses a variant of direct-declarator.
2653  typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
2654  void ParseDeclaratorInternal(Declarator &D,
2655  DirectDeclParseFunction DirectDeclParser);
2656 
2657  enum AttrRequirements {
2658  AR_NoAttributesParsed = 0, ///< No attributes are diagnosed.
2659  AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes.
2660  AR_GNUAttributesParsed = 1 << 1,
2661  AR_CXX11AttributesParsed = 1 << 2,
2662  AR_DeclspecAttributesParsed = 1 << 3,
2663  AR_AllAttributesParsed = AR_GNUAttributesParsed |
2664  AR_CXX11AttributesParsed |
2665  AR_DeclspecAttributesParsed,
2666  AR_VendorAttributesParsed = AR_GNUAttributesParsed |
2667  AR_DeclspecAttributesParsed
2668  };
2669 
2670  void ParseTypeQualifierListOpt(
2671  DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed,
2672  bool AtomicAllowed = true, bool IdentifierRequired = false,
2673  Optional<llvm::function_ref<void()>> CodeCompletionHandler = None);
2674  void ParseDirectDeclarator(Declarator &D);
2675  void ParseDecompositionDeclarator(Declarator &D);
2676  void ParseParenDeclarator(Declarator &D);
2677  void ParseFunctionDeclarator(Declarator &D,
2678  ParsedAttributes &attrs,
2679  BalancedDelimiterTracker &Tracker,
2680  bool IsAmbiguous,
2681  bool RequiresArg = false);
2682  bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
2683  SourceLocation &RefQualifierLoc);
2684  bool isFunctionDeclaratorIdentifierList();
2685  void ParseFunctionDeclaratorIdentifierList(
2686  Declarator &D,
2688  void ParseParameterDeclarationClause(
2689  Declarator &D,
2690  ParsedAttributes &attrs,
2692  SourceLocation &EllipsisLoc);
2693  void ParseBracketDeclarator(Declarator &D);
2694  void ParseMisplacedBracketDeclarator(Declarator &D);
2695 
2696  //===--------------------------------------------------------------------===//
2697  // C++ 7: Declarations [dcl.dcl]
2698 
2699  /// The kind of attribute specifier we have found.
2700  enum CXX11AttributeKind {
2701  /// This is not an attribute specifier.
2702  CAK_NotAttributeSpecifier,
2703  /// This should be treated as an attribute-specifier.
2704  CAK_AttributeSpecifier,
2705  /// The next tokens are '[[', but this is not an attribute-specifier. This
2706  /// is ill-formed by C++11 [dcl.attr.grammar]p6.
2707  CAK_InvalidAttributeSpecifier
2708  };
2709  CXX11AttributeKind
2710  isCXX11AttributeSpecifier(bool Disambiguate = false,
2711  bool OuterMightBeMessageSend = false);
2712 
2713  void DiagnoseUnexpectedNamespace(NamedDecl *Context);
2714 
2715  DeclGroupPtrTy ParseNamespace(DeclaratorContext Context,
2716  SourceLocation &DeclEnd,
2717  SourceLocation InlineLoc = SourceLocation());
2718 
2719  struct InnerNamespaceInfo {
2720  SourceLocation NamespaceLoc;
2721  SourceLocation InlineLoc;
2722  SourceLocation IdentLoc;
2723  IdentifierInfo *Ident;
2724  };
2726 
2727  void ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs,
2728  unsigned int index, SourceLocation &InlineLoc,
2729  ParsedAttributes &attrs,
2730  BalancedDelimiterTracker &Tracker);
2731  Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context);
2732  Decl *ParseExportDeclaration();
2733  DeclGroupPtrTy ParseUsingDirectiveOrDeclaration(
2734  DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
2735  SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs);
2736  Decl *ParseUsingDirective(DeclaratorContext Context,
2737  SourceLocation UsingLoc,
2738  SourceLocation &DeclEnd,
2739  ParsedAttributes &attrs);
2740 
2741  struct UsingDeclarator {
2742  SourceLocation TypenameLoc;
2743  CXXScopeSpec SS;
2744  UnqualifiedId Name;
2745  SourceLocation EllipsisLoc;
2746 
2747  void clear() {
2748  TypenameLoc = EllipsisLoc = SourceLocation();
2749  SS.clear();
2750  Name.clear();
2751  }
2752  };
2753 
2754  bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D);
2755  DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context,
2756  const ParsedTemplateInfo &TemplateInfo,
2757  SourceLocation UsingLoc,
2758  SourceLocation &DeclEnd,
2759  AccessSpecifier AS = AS_none);
2760  Decl *ParseAliasDeclarationAfterDeclarator(
2761  const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
2762  UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
2763  ParsedAttributes &Attrs, Decl **OwnedType = nullptr);
2764 
2765  Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
2766  Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
2767  SourceLocation AliasLoc, IdentifierInfo *Alias,
2768  SourceLocation &DeclEnd);
2769 
2770  //===--------------------------------------------------------------------===//
2771  // C++ 9: classes [class] and C structs/unions.
2772  bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
2773  void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
2774  DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo,
2775  AccessSpecifier AS, bool EnteringContext,
2776  DeclSpecContext DSC,
2777  ParsedAttributesWithRange &Attributes);
2778  void SkipCXXMemberSpecification(SourceLocation StartLoc,
2779  SourceLocation AttrFixitLoc,
2780  unsigned TagType,
2781  Decl *TagDecl);
2782  void ParseCXXMemberSpecification(SourceLocation StartLoc,
2783  SourceLocation AttrFixitLoc,
2784  ParsedAttributesWithRange &Attrs,
2785  unsigned TagType,
2786  Decl *TagDecl);
2787  ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2788  SourceLocation &EqualLoc);
2789  bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
2790  VirtSpecifiers &VS,
2791  ExprResult &BitfieldSize,
2792  LateParsedAttrList &LateAttrs);
2793  void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D,
2794  VirtSpecifiers &VS);
2795  DeclGroupPtrTy ParseCXXClassMemberDeclaration(
2797  const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2798  ParsingDeclRAIIObject *DiagsFromTParams = nullptr);
2799  DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas(
2800  AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
2801  DeclSpec::TST TagType, Decl *Tag);
2802  void ParseConstructorInitializer(Decl *ConstructorDecl);
2803  MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
2804  void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2805  Decl *ThisDecl);
2806 
2807  //===--------------------------------------------------------------------===//
2808  // C++ 10: Derived classes [class.derived]
2809  TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
2810  SourceLocation &EndLocation);
2811  void ParseBaseClause(Decl *ClassDecl);
2812  BaseResult ParseBaseSpecifier(Decl *ClassDecl);
2813  AccessSpecifier getAccessSpecifierIfPresent() const;
2814 
2815  bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
2816  SourceLocation TemplateKWLoc,
2817  IdentifierInfo *Name,
2818  SourceLocation NameLoc,
2819  bool EnteringContext,
2820  ParsedType ObjectType,
2821  UnqualifiedId &Id,
2822  bool AssumeTemplateId);
2823  bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2824  ParsedType ObjectType,
2826 
2827  //===--------------------------------------------------------------------===//
2828  // OpenMP: Directives and clauses.
2829  /// Parse clauses for '#pragma omp declare simd'.
2830  DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr,
2831  CachedTokens &Toks,
2832  SourceLocation Loc);
2833  /// Parse clauses for '#pragma omp declare target'.
2834  DeclGroupPtrTy ParseOMPDeclareTargetClauses();
2835  /// Parse '#pragma omp end declare target'.
2836  void ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind DKind,
2837  SourceLocation Loc);
2838  /// Parses declarative OpenMP directives.
2839  DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl(
2840  AccessSpecifier &AS, ParsedAttributesWithRange &Attrs,
2842  Decl *TagDecl = nullptr);
2843  /// Parse 'omp declare reduction' construct.
2844  DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS);
2845  /// Parses initializer for provided omp_priv declaration inside the reduction
2846  /// initializer.
2847  void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm);
2848 
2849  /// Parses 'omp declare mapper' directive.
2850  DeclGroupPtrTy ParseOpenMPDeclareMapperDirective(AccessSpecifier AS);
2851  /// Parses variable declaration in 'omp declare mapper' directive.
2852  TypeResult parseOpenMPDeclareMapperVarDecl(SourceRange &Range,
2853  DeclarationName &Name,
2854  AccessSpecifier AS = AS_none);
2855 
2856  /// Parses simple list of variables.
2857  ///
2858  /// \param Kind Kind of the directive.
2859  /// \param Callback Callback function to be called for the list elements.
2860  /// \param AllowScopeSpecifier true, if the variables can have fully
2861  /// qualified names.
2862  ///
2863  bool ParseOpenMPSimpleVarList(
2864  OpenMPDirectiveKind Kind,
2865  const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
2866  Callback,
2867  bool AllowScopeSpecifier);
2868  /// Parses declarative or executable directive.
2869  ///
2870  /// \param StmtCtx The context in which we're parsing the directive.
2871  StmtResult
2872  ParseOpenMPDeclarativeOrExecutableDirective(ParsedStmtContext StmtCtx);
2873  /// Parses clause of kind \a CKind for directive of a kind \a Kind.
2874  ///
2875  /// \param DKind Kind of current directive.
2876  /// \param CKind Kind of current clause.
2877  /// \param FirstClause true, if this is the first clause of a kind \a CKind
2878  /// in current directive.
2879  ///
2880  OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
2881  OpenMPClauseKind CKind, bool FirstClause);
2882  /// Parses clause with a single expression of a kind \a Kind.
2883  ///
2884  /// \param Kind Kind of current clause.
2885  /// \param ParseOnly true to skip the clause's semantic actions and return
2886  /// nullptr.
2887  ///
2888  OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind,
2889  bool ParseOnly);
2890  /// Parses simple clause 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 *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly);
2897  /// Parses clause with a single expression and an additional argument
2898  /// 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 *ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind,
2905  bool ParseOnly);
2906  /// Parses clause without any additional arguments.
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 *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false);
2913  /// Parses clause with the list of variables of a kind \a Kind.
2914  ///
2915  /// \param Kind Kind of current clause.
2916  /// \param ParseOnly true to skip the clause's semantic actions and return
2917  /// nullptr.
2918  ///
2919  OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
2920  OpenMPClauseKind Kind, bool ParseOnly);
2921 
2922 public:
2923  /// Parses simple expression in parens for single-expression clauses of OpenMP
2924  /// constructs.
2925  /// \param RLoc Returned location of right paren.
2926  ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc);
2927 
2928  /// Data used for parsing list of variables in OpenMP clauses.
2930  Expr *TailExpr = nullptr;
2936  OpenMPLinearClauseKind LinKind = OMPC_LINEAR_val;
2942  bool IsMapTypeImplicit = false;
2944  };
2945 
2946  /// Parses clauses with list.
2949  OpenMPVarListDataTy &Data);
2950  bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2951  bool AllowDestructorName,
2952  bool AllowConstructorName,
2953  bool AllowDeductionGuide,
2954  ParsedType ObjectType,
2955  SourceLocation *TemplateKWLoc,
2957  /// Parses the mapper modifier in map, to, and from clauses.
2959  /// Parses map-type-modifiers in map clause.
2960  /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list)
2961  /// where, map-type-modifier ::= always | close | mapper(mapper-identifier)
2963 
2964 private:
2965  //===--------------------------------------------------------------------===//
2966  // C++ 14: Templates [temp]
2967 
2968  // C++ 14.1: Template Parameters [temp.param]
2969  Decl *ParseDeclarationStartingWithTemplate(DeclaratorContext Context,
2970  SourceLocation &DeclEnd,
2971  ParsedAttributes &AccessAttrs,
2972  AccessSpecifier AS = AS_none);
2973  Decl *ParseTemplateDeclarationOrSpecialization(DeclaratorContext Context,
2974  SourceLocation &DeclEnd,
2975  ParsedAttributes &AccessAttrs,
2976  AccessSpecifier AS);
2977  Decl *ParseSingleDeclarationAfterTemplate(
2978  DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
2979  ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd,
2980  ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none);
2981  bool ParseTemplateParameters(unsigned Depth,
2982  SmallVectorImpl<NamedDecl *> &TemplateParams,
2983  SourceLocation &LAngleLoc,
2984  SourceLocation &RAngleLoc);
2985  bool ParseTemplateParameterList(unsigned Depth,
2986  SmallVectorImpl<NamedDecl*> &TemplateParams);
2987  bool isStartOfTemplateTypeParameter();
2988  NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position);
2989  NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position);
2990  NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
2991  NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
2992  void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
2993  SourceLocation CorrectLoc,
2994  bool AlreadyHasEllipsis,
2995  bool IdentifierHasName);
2996  void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
2997  Declarator &D);
2998  // C++ 14.3: Template arguments [temp.arg]
3000 
3001  bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
3002  bool ConsumeLastToken,
3003  bool ObjCGenericList);
3004  bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
3005  SourceLocation &LAngleLoc,
3006  TemplateArgList &TemplateArgs,
3007  SourceLocation &RAngleLoc);
3008 
3009  bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
3010  CXXScopeSpec &SS,
3011  SourceLocation TemplateKWLoc,
3013  bool AllowTypeAnnotation = true);
3014  void AnnotateTemplateIdTokenAsType(bool IsClassName = false);
3015  bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
3016  ParsedTemplateArgument ParseTemplateTemplateArgument();
3017  ParsedTemplateArgument ParseTemplateArgument();
3018  Decl *ParseExplicitInstantiation(DeclaratorContext Context,
3019  SourceLocation ExternLoc,
3020  SourceLocation TemplateLoc,
3021  SourceLocation &DeclEnd,
3022  ParsedAttributes &AccessAttrs,
3023  AccessSpecifier AS = AS_none);
3024 
3025  //===--------------------------------------------------------------------===//
3026  // Modules
3027  DeclGroupPtrTy ParseModuleDecl(bool IsFirstDecl);
3028  Decl *ParseModuleImport(SourceLocation AtLoc);
3029  bool parseMisplacedModuleImport();
3030  bool tryParseMisplacedModuleImport() {
3031  tok::TokenKind Kind = Tok.getKind();
3032  if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end ||
3033  Kind == tok::annot_module_include)
3034  return parseMisplacedModuleImport();
3035  return false;
3036  }
3037 
3038  bool ParseModuleName(
3039  SourceLocation UseLoc,
3040  SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
3041  bool IsImport);
3042 
3043  //===--------------------------------------------------------------------===//
3044  // C++11/G++: Type Traits [Type-Traits.html in the GCC manual]
3045  ExprResult ParseTypeTrait();
3046 
3047  //===--------------------------------------------------------------------===//
3048  // Embarcadero: Arary and Expression Traits
3049  ExprResult ParseArrayTypeTrait();
3050  ExprResult ParseExpressionTrait();
3051 
3052  //===--------------------------------------------------------------------===//
3053  // Preprocessor code-completion pass-through
3054  void CodeCompleteDirective(bool InConditional) override;
3055  void CodeCompleteInConditionalExclusion() override;
3056  void CodeCompleteMacroName(bool IsDefinition) override;
3057  void CodeCompletePreprocessorExpression() override;
3058  void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo,
3059  unsigned ArgumentIndex) override;
3060  void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) override;
3061  void CodeCompleteNaturalLanguage() override;
3062 };
3063 
3064 } // end namespace clang
3065 
3066 #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:314
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:2934
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:88
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:2938
StringRef P
bool TryAnnotateCXXScopeToken(bool EnteringContext=false)
TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only annotates C++ scope specifiers and ...
Definition: Parser.cpp:1978
virtual void clear()
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:112
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
void setCodeCompletionReached()
Note that we hit the code-completion point.
__m128i_u * p
Definition: emmintrin.h:2134
void ActOnObjCReenterContainerContext(DeclContext *DC)
Definition: SemaDecl.cpp:15235
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:59
void ActOnObjCTemporaryExitContainerContext(DeclContext *DC)
Invoked when we must temporarily exit the objective-c container scope for parsing/looking-up C constr...
Definition: SemaDecl.cpp:15229
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:83
const TargetInfo & getTargetInfo() const
Definition: Preprocessor.h:904
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:903
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:17143
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:148
void incrementMSManglingNumber() const
Definition: Sema.h:11065
void takeAllFrom(ParsedAttributes &attrs)
Definition: ParsedAttr.h:913
bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, SkipUntilFlags Flags=static_cast< SkipUntilFlags >(0))
Definition: Parser.h:1093
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:3054
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:1044
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1290
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:11063
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:1897
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:2940
Wraps an identifier and optional source location for the identifier.
Definition: ParsedAttr.h:94
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:75
bool TryAnnotateTypeOrScopeToken()
TryAnnotateTypeOrScopeToken - If the current token position is on a typename (possibly qualified in C...
Definition: Parser.cpp:1749
DiagnosticBuilder Diag(unsigned DiagID)
Definition: Parser.h:1056
bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, SmallVectorImpl< Expr *> &Vars, OpenMPVarListDataTy &Data)
Parses clauses with list.
Syntax
The style used to specify an attribute.
Definition: ParsedAttr.h:139
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3090
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 ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc)
Parses simple expression in parens for single-expression clauses of OpenMP constructs.
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:2929
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:2933
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:629
OpenMPMapClauseKind
OpenMP mapping kind for &#39;map&#39; clause.
Definition: OpenMPKinds.h:91
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:3505
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:1864
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:11243
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:906
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:43
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:124
Stop skipping at specified token, but don&#39;t skip the token itself.
Definition: Parser.h:1071