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