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