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