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