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