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