1 //===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the Parser interface.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_PARSE_PARSER_H
15 #define LLVM_CLANG_PARSE_PARSER_H
17 #include "clang/AST/Availability.h"
18 #include "clang/Basic/OpenMPKinds.h"
19 #include "clang/Basic/OperatorPrecedence.h"
20 #include "clang/Basic/Specifiers.h"
21 #include "clang/Lex/CodeCompletionHandler.h"
22 #include "clang/Lex/Preprocessor.h"
23 #include "clang/Sema/DeclSpec.h"
24 #include "clang/Sema/LoopHint.h"
25 #include "clang/Sema/Sema.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/Support/PrettyStackTrace.h"
29 #include "llvm/Support/SaveAndRestore.h"
36 class BalancedDelimiterTracker;
37 class CorrectionCandidateCallback;
39 class DiagnosticBuilder;
41 class ParsingDeclRAIIObject;
42 class ParsingDeclSpec;
43 class ParsingDeclarator;
44 class ParsingFieldDeclarator;
45 class ColonProtectionRAIIObject;
46 class InMessageExpressionRAIIObject;
47 class PoisonSEHIdentifiersRAIIObject;
50 class ObjCTypeParamList;
51 class ObjCTypeParameter;
53 /// Parser - This implements a parser for the C family of languages. After
54 /// parsing units of the grammar, productions are invoked to handle whatever has
57 class Parser : public CodeCompletionHandler {
58 friend class ColonProtectionRAIIObject;
59 friend class InMessageExpressionRAIIObject;
60 friend class PoisonSEHIdentifiersRAIIObject;
61 friend class ObjCDeclContextSwitch;
62 friend class ParenBraceBracketBalancer;
63 friend class BalancedDelimiterTracker;
67 /// Tok - The current token we are peeking ahead. All parsing methods assume
68 /// that this is valid.
71 // PrevTokLocation - The location of the token we previously
72 // consumed. This token is used for diagnostics where we expected to
73 // see a token following another token (e.g., the ';' at the end of
75 SourceLocation PrevTokLocation;
77 unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0;
78 unsigned short MisplacedModuleBeginCount = 0;
80 /// Actions - These are the callbacks we invoke as we parse various constructs
84 DiagnosticsEngine &Diags;
86 /// ScopeCache - Cache scopes to reduce malloc traffic.
87 enum { ScopeCacheSize = 16 };
88 unsigned NumCachedScopes;
89 Scope *ScopeCache[ScopeCacheSize];
91 /// Identifiers used for SEH handling in Borland. These are only
92 /// allowed in particular circumstances
94 IdentifierInfo *Ident__exception_code,
95 *Ident___exception_code,
96 *Ident_GetExceptionCode;
97 // __except filter expression
98 IdentifierInfo *Ident__exception_info,
99 *Ident___exception_info,
100 *Ident_GetExceptionInfo;
102 IdentifierInfo *Ident__abnormal_termination,
103 *Ident___abnormal_termination,
104 *Ident_AbnormalTermination;
106 /// Contextual keywords for Microsoft extensions.
107 IdentifierInfo *Ident__except;
108 mutable IdentifierInfo *Ident_sealed;
110 /// Ident_super - IdentifierInfo for "super", to support fast
112 IdentifierInfo *Ident_super;
113 /// Ident_vector, Ident_bool - cached IdentifierInfos for "vector" and
114 /// "bool" fast comparison. Only present if AltiVec or ZVector are enabled.
115 IdentifierInfo *Ident_vector;
116 IdentifierInfo *Ident_bool;
117 /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison.
118 /// Only present if AltiVec enabled.
119 IdentifierInfo *Ident_pixel;
121 /// Objective-C contextual keywords.
122 mutable IdentifierInfo *Ident_instancetype;
124 /// \brief Identifier for "introduced".
125 IdentifierInfo *Ident_introduced;
127 /// \brief Identifier for "deprecated".
128 IdentifierInfo *Ident_deprecated;
130 /// \brief Identifier for "obsoleted".
131 IdentifierInfo *Ident_obsoleted;
133 /// \brief Identifier for "unavailable".
134 IdentifierInfo *Ident_unavailable;
136 /// \brief Identifier for "message".
137 IdentifierInfo *Ident_message;
139 /// \brief Identifier for "strict".
140 IdentifierInfo *Ident_strict;
142 /// \brief Identifier for "replacement".
143 IdentifierInfo *Ident_replacement;
145 /// Identifiers used by the 'external_source_symbol' attribute.
146 IdentifierInfo *Ident_language, *Ident_defined_in,
147 *Ident_generated_declaration;
149 /// C++0x contextual keywords.
150 mutable IdentifierInfo *Ident_final;
151 mutable IdentifierInfo *Ident_GNU_final;
152 mutable IdentifierInfo *Ident_override;
154 // C++ type trait keywords that can be reverted to identifiers and still be
155 // used as type traits.
156 llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits;
158 std::unique_ptr<PragmaHandler> AlignHandler;
159 std::unique_ptr<PragmaHandler> GCCVisibilityHandler;
160 std::unique_ptr<PragmaHandler> OptionsHandler;
161 std::unique_ptr<PragmaHandler> PackHandler;
162 std::unique_ptr<PragmaHandler> MSStructHandler;
163 std::unique_ptr<PragmaHandler> UnusedHandler;
164 std::unique_ptr<PragmaHandler> WeakHandler;
165 std::unique_ptr<PragmaHandler> RedefineExtnameHandler;
166 std::unique_ptr<PragmaHandler> FPContractHandler;
167 std::unique_ptr<PragmaHandler> OpenCLExtensionHandler;
168 std::unique_ptr<PragmaHandler> OpenMPHandler;
169 std::unique_ptr<PragmaHandler> PCSectionHandler;
170 std::unique_ptr<PragmaHandler> MSCommentHandler;
171 std::unique_ptr<PragmaHandler> MSDetectMismatchHandler;
172 std::unique_ptr<PragmaHandler> MSPointersToMembers;
173 std::unique_ptr<PragmaHandler> MSVtorDisp;
174 std::unique_ptr<PragmaHandler> MSInitSeg;
175 std::unique_ptr<PragmaHandler> MSDataSeg;
176 std::unique_ptr<PragmaHandler> MSBSSSeg;
177 std::unique_ptr<PragmaHandler> MSConstSeg;
178 std::unique_ptr<PragmaHandler> MSCodeSeg;
179 std::unique_ptr<PragmaHandler> MSSection;
180 std::unique_ptr<PragmaHandler> MSRuntimeChecks;
181 std::unique_ptr<PragmaHandler> MSIntrinsic;
182 std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler;
183 std::unique_ptr<PragmaHandler> OptimizeHandler;
184 std::unique_ptr<PragmaHandler> LoopHintHandler;
185 std::unique_ptr<PragmaHandler> UnrollHintHandler;
186 std::unique_ptr<PragmaHandler> NoUnrollHintHandler;
187 std::unique_ptr<PragmaHandler> FPHandler;
188 std::unique_ptr<PragmaHandler> AttributePragmaHandler;
190 std::unique_ptr<CommentHandler> CommentSemaHandler;
192 /// Whether the '>' token acts as an operator or not. This will be
193 /// true except when we are parsing an expression within a C++
194 /// template argument list, where the '>' closes the template
196 bool GreaterThanIsOperator;
198 /// ColonIsSacred - When this is false, we aggressively try to recover from
199 /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not
200 /// safe in case statements and a few other things. This is managed by the
201 /// ColonProtectionRAIIObject RAII object.
204 /// \brief When true, we are directly inside an Objective-C message
207 /// This is managed by the \c InMessageExpressionRAIIObject class, and
208 /// should not be set directly.
209 bool InMessageExpression;
211 /// The "depth" of the template parameters currently being parsed.
212 unsigned TemplateParameterDepth;
214 /// \brief RAII class that manages the template parameter depth.
215 class TemplateParameterDepthRAII {
217 unsigned AddedLevels;
219 explicit TemplateParameterDepthRAII(unsigned &Depth)
220 : Depth(Depth), AddedLevels(0) {}
222 ~TemplateParameterDepthRAII() {
223 Depth -= AddedLevels;
230 void addDepth(unsigned D) {
234 unsigned getDepth() const { return Depth; }
237 /// Factory object for creating AttributeList objects.
238 AttributeFactory AttrFactory;
240 /// \brief Gathers and cleans up TemplateIdAnnotations when parsing of a
241 /// top-level declaration is finished.
242 SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
244 /// \brief Identifiers which have been declared within a tentative parse.
245 SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers;
247 IdentifierInfo *getSEHExceptKeyword();
249 /// True if we are within an Objective-C container while parsing C-like decls.
251 /// This is necessary because Sema thinks we have left the container
252 /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will
254 bool ParsingInObjCContainer;
256 /// Whether to skip parsing of function bodies.
258 /// This option can be used, for example, to speed up searches for
259 /// declarations/definitions when indexing.
260 bool SkipFunctionBodies;
262 /// The location of the expression statement that is being parsed right now.
263 /// Used to determine if an expression that is being parsed is a statement or
264 /// just a regular sub-expression.
265 SourceLocation ExprStatementTokLoc;
268 Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
271 const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
272 const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
273 Preprocessor &getPreprocessor() const { return PP; }
274 Sema &getActions() const { return Actions; }
275 AttributeFactory &getAttrFactory() { return AttrFactory; }
277 const Token &getCurToken() const { return Tok; }
278 Scope *getCurScope() const { return Actions.getCurScope(); }
279 void incrementMSManglingNumber() const {
280 return Actions.incrementMSManglingNumber();
283 Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); }
285 // Type forwarding. All of these are statically 'void*', but they may all be
286 // different actual classes based on the actions in place.
287 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
288 typedef OpaquePtr<TemplateName> TemplateTy;
290 typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists;
292 typedef Sema::FullExprArg FullExprArg;
296 /// Initialize - Warm up the parser.
300 /// Parse the first top-level declaration in a translation unit.
301 bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result);
303 /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if
304 /// the EOF was encountered.
305 bool ParseTopLevelDecl(DeclGroupPtrTy &Result);
306 bool ParseTopLevelDecl() {
307 DeclGroupPtrTy Result;
308 return ParseTopLevelDecl(Result);
311 /// ConsumeToken - Consume the current 'peek token' and lex the next one.
312 /// This does not work with special tokens: string literals, code completion,
313 /// annotation tokens and balanced tokens must be handled using the specific
315 /// Returns the location of the consumed token.
316 SourceLocation ConsumeToken() {
317 assert(!isTokenSpecial() &&
318 "Should consume special tokens with Consume*Token");
319 PrevTokLocation = Tok.getLocation();
321 return PrevTokLocation;
324 bool TryConsumeToken(tok::TokenKind Expected) {
325 if (Tok.isNot(Expected))
327 assert(!isTokenSpecial() &&
328 "Should consume special tokens with Consume*Token");
329 PrevTokLocation = Tok.getLocation();
334 bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) {
335 if (!TryConsumeToken(Expected))
337 Loc = PrevTokLocation;
341 /// ConsumeAnyToken - Dispatch to the right Consume* method based on the
342 /// current token type. This should only be used in cases where the type of
343 /// the token really isn't known, e.g. in error recovery.
344 SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) {
346 return ConsumeParen();
347 if (isTokenBracket())
348 return ConsumeBracket();
350 return ConsumeBrace();
351 if (isTokenStringLiteral())
352 return ConsumeStringToken();
353 if (Tok.is(tok::code_completion))
354 return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken()
355 : handleUnexpectedCodeCompletionToken();
356 if (Tok.isAnnotation())
357 return ConsumeAnnotationToken();
358 return ConsumeToken();
362 SourceLocation getEndOfPreviousToken() {
363 return PP.getLocForEndOfToken(PrevTokLocation);
366 /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds
367 /// to the given nullability kind.
368 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) {
369 return Actions.getNullabilityKeyword(nullability);
373 //===--------------------------------------------------------------------===//
374 // Low-Level token peeking and consumption methods.
377 /// isTokenParen - Return true if the cur token is '(' or ')'.
378 bool isTokenParen() const {
379 return Tok.getKind() == tok::l_paren || Tok.getKind() == tok::r_paren;
381 /// isTokenBracket - Return true if the cur token is '[' or ']'.
382 bool isTokenBracket() const {
383 return Tok.getKind() == tok::l_square || Tok.getKind() == tok::r_square;
385 /// isTokenBrace - Return true if the cur token is '{' or '}'.
386 bool isTokenBrace() const {
387 return Tok.getKind() == tok::l_brace || Tok.getKind() == tok::r_brace;
389 /// isTokenStringLiteral - True if this token is a string-literal.
390 bool isTokenStringLiteral() const {
391 return tok::isStringLiteral(Tok.getKind());
393 /// isTokenSpecial - True if this token requires special consumption methods.
394 bool isTokenSpecial() const {
395 return isTokenStringLiteral() || isTokenParen() || isTokenBracket() ||
396 isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation();
399 /// \brief Returns true if the current token is '=' or is a type of '='.
400 /// For typos, give a fixit to '='
401 bool isTokenEqualOrEqualTypo();
403 /// \brief Return the current token to the token stream and make the given
404 /// token the current token.
405 void UnconsumeToken(Token &Consumed) {
407 PP.EnterToken(Consumed);
412 SourceLocation ConsumeAnnotationToken() {
413 assert(Tok.isAnnotation() && "wrong consume method");
414 SourceLocation Loc = Tok.getLocation();
415 PrevTokLocation = Tok.getAnnotationEndLoc();
420 /// ConsumeParen - This consume method keeps the paren count up-to-date.
422 SourceLocation ConsumeParen() {
423 assert(isTokenParen() && "wrong consume method");
424 if (Tok.getKind() == tok::l_paren)
427 --ParenCount; // Don't let unbalanced )'s drive the count negative.
428 PrevTokLocation = Tok.getLocation();
430 return PrevTokLocation;
433 /// ConsumeBracket - This consume method keeps the bracket count up-to-date.
435 SourceLocation ConsumeBracket() {
436 assert(isTokenBracket() && "wrong consume method");
437 if (Tok.getKind() == tok::l_square)
439 else if (BracketCount)
440 --BracketCount; // Don't let unbalanced ]'s drive the count negative.
442 PrevTokLocation = Tok.getLocation();
444 return PrevTokLocation;
447 /// ConsumeBrace - This consume method keeps the brace count up-to-date.
449 SourceLocation ConsumeBrace() {
450 assert(isTokenBrace() && "wrong consume method");
451 if (Tok.getKind() == tok::l_brace)
454 --BraceCount; // Don't let unbalanced }'s drive the count negative.
456 PrevTokLocation = Tok.getLocation();
458 return PrevTokLocation;
461 /// ConsumeStringToken - Consume the current 'peek token', lexing a new one
462 /// and returning the token kind. This method is specific to strings, as it
463 /// handles string literal concatenation, as per C99 5.1.1.2, translation
465 SourceLocation ConsumeStringToken() {
466 assert(isTokenStringLiteral() &&
467 "Should only consume string literals with this method");
468 PrevTokLocation = Tok.getLocation();
470 return PrevTokLocation;
473 /// \brief Consume the current code-completion token.
475 /// This routine can be called to consume the code-completion token and
476 /// continue processing in special cases where \c cutOffParsing() isn't
477 /// desired, such as token caching or completion with lookahead.
478 SourceLocation ConsumeCodeCompletionToken() {
479 assert(Tok.is(tok::code_completion));
480 PrevTokLocation = Tok.getLocation();
482 return PrevTokLocation;
485 ///\ brief When we are consuming a code-completion token without having
486 /// matched specific position in the grammar, provide code-completion results
487 /// based on context.
489 /// \returns the source location of the code-completion token.
490 SourceLocation handleUnexpectedCodeCompletionToken();
492 /// \brief Abruptly cut off parsing; mainly used when we have reached the
493 /// code-completion point.
494 void cutOffParsing() {
495 if (PP.isCodeCompletionEnabled())
496 PP.setCodeCompletionReached();
497 // Cut off parsing by acting as if we reached the end-of-file.
498 Tok.setKind(tok::eof);
501 /// \brief Determine if we're at the end of the file or at a transition
504 tok::TokenKind Kind = Tok.getKind();
505 return Kind == tok::eof || Kind == tok::annot_module_begin ||
506 Kind == tok::annot_module_end || Kind == tok::annot_module_include;
509 /// \brief Checks if the \p Level is valid for use in a fold expression.
510 bool isFoldOperator(prec::Level Level) const;
512 /// \brief Checks if the \p Kind is a valid operator for fold expressions.
513 bool isFoldOperator(tok::TokenKind Kind) const;
515 /// \brief Initialize all pragma handlers.
516 void initializePragmaHandlers();
518 /// \brief Destroy and reset all pragma handlers.
519 void resetPragmaHandlers();
521 /// \brief Handle the annotation token produced for #pragma unused(...)
522 void HandlePragmaUnused();
524 /// \brief Handle the annotation token produced for
525 /// #pragma GCC visibility...
526 void HandlePragmaVisibility();
528 /// \brief Handle the annotation token produced for
530 void HandlePragmaPack();
532 /// \brief Handle the annotation token produced for
533 /// #pragma ms_struct...
534 void HandlePragmaMSStruct();
536 /// \brief Handle the annotation token produced for
537 /// #pragma comment...
538 void HandlePragmaMSComment();
540 void HandlePragmaMSPointersToMembers();
542 void HandlePragmaMSVtorDisp();
544 void HandlePragmaMSPragma();
545 bool HandlePragmaMSSection(StringRef PragmaName,
546 SourceLocation PragmaLocation);
547 bool HandlePragmaMSSegment(StringRef PragmaName,
548 SourceLocation PragmaLocation);
549 bool HandlePragmaMSInitSeg(StringRef PragmaName,
550 SourceLocation PragmaLocation);
552 /// \brief Handle the annotation token produced for
554 void HandlePragmaAlign();
556 /// \brief Handle the annotation token produced for
557 /// #pragma clang __debug dump...
558 void HandlePragmaDump();
560 /// \brief Handle the annotation token produced for
561 /// #pragma weak id...
562 void HandlePragmaWeak();
564 /// \brief Handle the annotation token produced for
565 /// #pragma weak id = id...
566 void HandlePragmaWeakAlias();
568 /// \brief Handle the annotation token produced for
569 /// #pragma redefine_extname...
570 void HandlePragmaRedefineExtname();
572 /// \brief Handle the annotation token produced for
573 /// #pragma STDC FP_CONTRACT...
574 void HandlePragmaFPContract();
576 /// \brief Handle the annotation token produced for
577 /// #pragma clang fp ...
578 void HandlePragmaFP();
580 /// \brief Handle the annotation token produced for
581 /// #pragma OPENCL EXTENSION...
582 void HandlePragmaOpenCLExtension();
584 /// \brief Handle the annotation token produced for
585 /// #pragma clang __debug captured
586 StmtResult HandlePragmaCaptured();
588 /// \brief Handle the annotation token produced for
589 /// #pragma clang loop and #pragma unroll.
590 bool HandlePragmaLoopHint(LoopHint &Hint);
592 bool ParsePragmaAttributeSubjectMatchRuleSet(
593 attr::ParsedSubjectMatchRuleSet &SubjectMatchRules,
594 SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc);
596 void HandlePragmaAttribute();
598 /// GetLookAheadToken - This peeks ahead N tokens and returns that token
599 /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1)
600 /// returns the token after Tok, etc.
602 /// Note that this differs from the Preprocessor's LookAhead method, because
603 /// the Parser always has one token lexed that the preprocessor doesn't.
605 const Token &GetLookAheadToken(unsigned N) {
606 if (N == 0 || Tok.is(tok::eof)) return Tok;
607 return PP.LookAhead(N-1);
611 /// NextToken - This peeks ahead one token and returns it without
613 const Token &NextToken() {
614 return PP.LookAhead(0);
617 /// getTypeAnnotation - Read a parsed type out of an annotation token.
618 static ParsedType getTypeAnnotation(const Token &Tok) {
619 return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
623 static void setTypeAnnotation(Token &Tok, ParsedType T) {
624 Tok.setAnnotationValue(T.getAsOpaquePtr());
627 /// \brief Read an already-translated primary expression out of an annotation
629 static ExprResult getExprAnnotation(const Token &Tok) {
630 return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue());
633 /// \brief Set the primary expression corresponding to the given annotation
635 static void setExprAnnotation(Token &Tok, ExprResult ER) {
636 Tok.setAnnotationValue(ER.getAsOpaquePointer());
640 // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to
641 // find a type name by attempting typo correction.
642 bool TryAnnotateTypeOrScopeToken();
643 bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS,
645 bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
648 enum AnnotatedNameKind {
649 /// Annotation has failed and emitted an error.
651 /// The identifier is a tentatively-declared name.
653 /// The identifier is a template name. FIXME: Add an annotation for that.
655 /// The identifier can't be resolved.
657 /// Annotation was successful.
661 TryAnnotateName(bool IsAddressOfOperand,
662 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
664 /// Push a tok::annot_cxxscope token onto the token stream.
665 void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
667 /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
668 /// replacing them with the non-context-sensitive keywords. This returns
669 /// true if the token was replaced.
670 bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
671 const char *&PrevSpec, unsigned &DiagID,
673 if (!getLangOpts().AltiVec && !getLangOpts().ZVector)
676 if (Tok.getIdentifierInfo() != Ident_vector &&
677 Tok.getIdentifierInfo() != Ident_bool &&
678 (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel))
681 return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
684 /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
685 /// identifier token, replacing it with the non-context-sensitive __vector.
686 /// This returns true if the token was replaced.
687 bool TryAltiVecVectorToken() {
688 if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) ||
689 Tok.getIdentifierInfo() != Ident_vector) return false;
690 return TryAltiVecVectorTokenOutOfLine();
693 bool TryAltiVecVectorTokenOutOfLine();
694 bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
695 const char *&PrevSpec, unsigned &DiagID,
698 /// Returns true if the current token is the identifier 'instancetype'.
700 /// Should only be used in Objective-C language modes.
701 bool isObjCInstancetype() {
702 assert(getLangOpts().ObjC1);
703 if (Tok.isAnnotation())
705 if (!Ident_instancetype)
706 Ident_instancetype = PP.getIdentifierInfo("instancetype");
707 return Tok.getIdentifierInfo() == Ident_instancetype;
710 /// TryKeywordIdentFallback - For compatibility with system headers using
711 /// keywords as identifiers, attempt to convert the current token to an
712 /// identifier and optionally disable the keyword for the remainder of the
713 /// translation unit. This returns false if the token was not replaced,
714 /// otherwise emits a diagnostic and returns true.
715 bool TryKeywordIdentFallback(bool DisableKeyword);
717 /// \brief Get the TemplateIdAnnotation from the token.
718 TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
720 /// TentativeParsingAction - An object that is used as a kind of "tentative
721 /// parsing transaction". It gets instantiated to mark the token position and
722 /// after the token consumption is done, Commit() or Revert() is called to
723 /// either "commit the consumed tokens" or revert to the previously marked
724 /// token position. Example:
726 /// TentativeParsingAction TPA(*this);
731 class TentativeParsingAction {
734 size_t PrevTentativelyDeclaredIdentifierCount;
735 unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
739 explicit TentativeParsingAction(Parser& p) : P(p) {
741 PrevTentativelyDeclaredIdentifierCount =
742 P.TentativelyDeclaredIdentifiers.size();
743 PrevParenCount = P.ParenCount;
744 PrevBracketCount = P.BracketCount;
745 PrevBraceCount = P.BraceCount;
746 P.PP.EnableBacktrackAtThisPos();
750 assert(isActive && "Parsing action was finished!");
751 P.TentativelyDeclaredIdentifiers.resize(
752 PrevTentativelyDeclaredIdentifierCount);
753 P.PP.CommitBacktrackedTokens();
757 assert(isActive && "Parsing action was finished!");
760 P.TentativelyDeclaredIdentifiers.resize(
761 PrevTentativelyDeclaredIdentifierCount);
762 P.ParenCount = PrevParenCount;
763 P.BracketCount = PrevBracketCount;
764 P.BraceCount = PrevBraceCount;
767 ~TentativeParsingAction() {
768 assert(!isActive && "Forgot to call Commit or Revert!");
771 /// A TentativeParsingAction that automatically reverts in its destructor.
772 /// Useful for disambiguation parses that will always be reverted.
773 class RevertingTentativeParsingAction
774 : private Parser::TentativeParsingAction {
776 RevertingTentativeParsingAction(Parser &P)
777 : Parser::TentativeParsingAction(P) {}
778 ~RevertingTentativeParsingAction() { Revert(); }
781 class UnannotatedTentativeParsingAction;
783 /// ObjCDeclContextSwitch - An object used to switch context from
784 /// an objective-c decl context to its enclosing decl context and
786 class ObjCDeclContextSwitch {
789 SaveAndRestore<bool> WithinObjCContainer;
791 explicit ObjCDeclContextSwitch(Parser &p)
792 : P(p), DC(p.getObjCDeclContext()),
793 WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) {
795 P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC));
797 ~ObjCDeclContextSwitch() {
799 P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC));
803 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
804 /// input. If so, it is consumed and false is returned.
806 /// If a trivial punctuator misspelling is encountered, a FixIt error
807 /// diagnostic is issued and false is returned after recovery.
809 /// If the input is malformed, this emits the specified diagnostic and true is
811 bool ExpectAndConsume(tok::TokenKind ExpectedTok,
812 unsigned Diag = diag::err_expected,
813 StringRef DiagMsg = "");
815 /// \brief The parser expects a semicolon and, if present, will consume it.
817 /// If the next token is not a semicolon, this emits the specified diagnostic,
818 /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
819 /// to the semicolon, consumes that extra token.
820 bool ExpectAndConsumeSemi(unsigned DiagID);
822 /// \brief The kind of extra semi diagnostic to emit.
826 InstanceVariableList = 2,
827 AfterMemberFunctionDefinition = 3
830 /// \brief Consume any extra semi-colons until the end of the line.
831 void ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST = TST_unspecified);
833 /// Return false if the next token is an identifier. An 'expected identifier'
834 /// error is emitted otherwise.
836 /// The parser tries to recover from the error by checking if the next token
837 /// is a C++ keyword when parsing Objective-C++. Return false if the recovery
839 bool expectIdentifier();
842 //===--------------------------------------------------------------------===//
843 // Scope manipulation
845 /// ParseScope - Introduces a new scope for parsing. The kind of
846 /// scope is determined by ScopeFlags. Objects of this type should
847 /// be created on the stack to coincide with the position where the
848 /// parser enters the new scope, and this object's constructor will
849 /// create that new scope. Similarly, once the object is destroyed
850 /// the parser will exit the scope.
853 ParseScope(const ParseScope &) = delete;
854 void operator=(const ParseScope &) = delete;
857 // ParseScope - Construct a new object to manage a scope in the
858 // parser Self where the new Scope is created with the flags
859 // ScopeFlags, but only when we aren't about to enter a compound statement.
860 ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true,
861 bool BeforeCompoundStmt = false)
863 if (EnteredScope && !BeforeCompoundStmt)
864 Self->EnterScope(ScopeFlags);
866 if (BeforeCompoundStmt)
867 Self->incrementMSManglingNumber();
869 this->Self = nullptr;
873 // Exit - Exit the scope associated with this object now, rather
874 // than waiting until the object is destroyed.
887 /// EnterScope - Start a new scope.
888 void EnterScope(unsigned ScopeFlags);
890 /// ExitScope - Pop a scope off the scope stack.
894 /// \brief RAII object used to modify the scope flags for the current scope.
895 class ParseScopeFlags {
898 ParseScopeFlags(const ParseScopeFlags &) = delete;
899 void operator=(const ParseScopeFlags &) = delete;
902 ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
906 //===--------------------------------------------------------------------===//
907 // Diagnostic Emission and Error recovery.
910 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
911 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
912 DiagnosticBuilder Diag(unsigned DiagID) {
913 return Diag(Tok, DiagID);
917 void SuggestParentheses(SourceLocation Loc, unsigned DK,
918 SourceRange ParenRange);
919 void CheckNestedObjCContexts(SourceLocation AtLoc);
923 /// \brief Control flags for SkipUntil functions.
924 enum SkipUntilFlags {
925 StopAtSemi = 1 << 0, ///< Stop skipping at semicolon
926 /// \brief Stop skipping at specified token, but don't skip the token itself
927 StopBeforeMatch = 1 << 1,
928 StopAtCodeCompletion = 1 << 2 ///< Stop at code completion
931 friend constexpr SkipUntilFlags operator|(SkipUntilFlags L,
933 return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) |
934 static_cast<unsigned>(R));
937 /// SkipUntil - Read tokens until we get to the specified token, then consume
938 /// it (unless StopBeforeMatch is specified). Because we cannot guarantee
939 /// that the token will ever occur, this skips to the next token, or to some
940 /// likely good stopping point. If Flags has StopAtSemi flag, skipping will
941 /// stop at a ';' character.
943 /// If SkipUntil finds the specified token, it returns true, otherwise it
945 bool SkipUntil(tok::TokenKind T,
946 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
947 return SkipUntil(llvm::makeArrayRef(T), Flags);
949 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2,
950 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
951 tok::TokenKind TokArray[] = {T1, T2};
952 return SkipUntil(TokArray, Flags);
954 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3,
955 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
956 tok::TokenKind TokArray[] = {T1, T2, T3};
957 return SkipUntil(TokArray, Flags);
959 bool SkipUntil(ArrayRef<tok::TokenKind> Toks,
960 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0));
962 /// SkipMalformedDecl - Read tokens until we get to some likely good stopping
963 /// point for skipping past a simple-declaration.
964 void SkipMalformedDecl();
967 //===--------------------------------------------------------------------===//
968 // Lexing and parsing of C++ inline methods.
972 /// [class.mem]p1: "... the class is regarded as complete within
973 /// - function bodies
974 /// - default arguments
975 /// - exception-specifications (TODO: C++0x)
976 /// - and brace-or-equal-initializers for non-static data members
977 /// (including such things in nested classes)."
978 /// LateParsedDeclarations build the tree of those elements so they can
979 /// be parsed after parsing the top-level class.
980 class LateParsedDeclaration {
982 virtual ~LateParsedDeclaration();
984 virtual void ParseLexedMethodDeclarations();
985 virtual void ParseLexedMemberInitializers();
986 virtual void ParseLexedMethodDefs();
987 virtual void ParseLexedAttributes();
990 /// Inner node of the LateParsedDeclaration tree that parses
991 /// all its members recursively.
992 class LateParsedClass : public LateParsedDeclaration {
994 LateParsedClass(Parser *P, ParsingClass *C);
995 ~LateParsedClass() override;
997 void ParseLexedMethodDeclarations() override;
998 void ParseLexedMemberInitializers() override;
999 void ParseLexedMethodDefs() override;
1000 void ParseLexedAttributes() override;
1004 ParsingClass *Class;
1007 /// Contains the lexed tokens of an attribute with arguments that
1008 /// may reference member variables and so need to be parsed at the
1009 /// end of the class declaration after parsing all other member
1010 /// member declarations.
1011 /// FIXME: Perhaps we should change the name of LateParsedDeclaration to
1012 /// LateParsedTokens.
1013 struct LateParsedAttribute : public LateParsedDeclaration {
1016 IdentifierInfo &AttrName;
1017 SourceLocation AttrNameLoc;
1018 SmallVector<Decl*, 2> Decls;
1020 explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
1022 : Self(P), AttrName(Name), AttrNameLoc(Loc) {}
1024 void ParseLexedAttributes() override;
1026 void addDecl(Decl *D) { Decls.push_back(D); }
1029 // A list of late-parsed attributes. Used by ParseGNUAttributes.
1030 class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> {
1032 LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { }
1034 bool parseSoon() { return ParseSoon; }
1037 bool ParseSoon; // Are we planning to parse these shortly after creation?
1040 /// Contains the lexed tokens of a member function definition
1041 /// which needs to be parsed at the end of the class declaration
1042 /// after parsing all other member declarations.
1043 struct LexedMethod : public LateParsedDeclaration {
1048 /// \brief Whether this member function had an associated template
1049 /// scope. When true, D is a template declaration.
1050 /// otherwise, it is a member function declaration.
1053 explicit LexedMethod(Parser* P, Decl *MD)
1054 : Self(P), D(MD), TemplateScope(false) {}
1056 void ParseLexedMethodDefs() override;
1059 /// LateParsedDefaultArgument - Keeps track of a parameter that may
1060 /// have a default argument that cannot be parsed yet because it
1061 /// occurs within a member function declaration inside the class
1062 /// (C++ [class.mem]p2).
1063 struct LateParsedDefaultArgument {
1064 explicit LateParsedDefaultArgument(Decl *P,
1065 std::unique_ptr<CachedTokens> Toks = nullptr)
1066 : Param(P), Toks(std::move(Toks)) { }
1068 /// Param - The parameter declaration for this parameter.
1071 /// Toks - The sequence of tokens that comprises the default
1072 /// argument expression, not including the '=' or the terminating
1073 /// ')' or ','. This will be NULL for parameters that have no
1074 /// default argument.
1075 std::unique_ptr<CachedTokens> Toks;
1078 /// LateParsedMethodDeclaration - A method declaration inside a class that
1079 /// contains at least one entity whose parsing needs to be delayed
1080 /// until the class itself is completely-defined, such as a default
1081 /// argument (C++ [class.mem]p2).
1082 struct LateParsedMethodDeclaration : public LateParsedDeclaration {
1083 explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
1084 : Self(P), Method(M), TemplateScope(false),
1085 ExceptionSpecTokens(nullptr) {}
1087 void ParseLexedMethodDeclarations() override;
1091 /// Method - The method declaration.
1094 /// \brief Whether this member function had an associated template
1095 /// scope. When true, D is a template declaration.
1096 /// othewise, it is a member function declaration.
1099 /// DefaultArgs - Contains the parameters of the function and
1100 /// their default arguments. At least one of the parameters will
1101 /// have a default argument, but all of the parameters of the
1102 /// method will be stored so that they can be reintroduced into
1103 /// scope at the appropriate times.
1104 SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
1106 /// \brief The set of tokens that make up an exception-specification that
1107 /// has not yet been parsed.
1108 CachedTokens *ExceptionSpecTokens;
1111 /// LateParsedMemberInitializer - An initializer for a non-static class data
1112 /// member whose parsing must to be delayed until the class is completely
1113 /// defined (C++11 [class.mem]p2).
1114 struct LateParsedMemberInitializer : public LateParsedDeclaration {
1115 LateParsedMemberInitializer(Parser *P, Decl *FD)
1116 : Self(P), Field(FD) { }
1118 void ParseLexedMemberInitializers() override;
1122 /// Field - The field declaration.
1125 /// CachedTokens - The sequence of tokens that comprises the initializer,
1126 /// including any leading '='.
1130 /// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
1131 /// C++ class, its method declarations that contain parts that won't be
1132 /// parsed until after the definition is completed (C++ [class.mem]p2),
1133 /// the method declarations and possibly attached inline definitions
1134 /// will be stored here with the tokens that will be parsed to create those
1136 typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer;
1138 /// \brief Representation of a class that has been parsed, including
1139 /// any member function declarations or definitions that need to be
1140 /// parsed after the corresponding top-level class is complete.
1141 struct ParsingClass {
1142 ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface)
1143 : TopLevelClass(TopLevelClass), TemplateScope(false),
1144 IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) { }
1146 /// \brief Whether this is a "top-level" class, meaning that it is
1147 /// not nested within another class.
1148 bool TopLevelClass : 1;
1150 /// \brief Whether this class had an associated template
1151 /// scope. When true, TagOrTemplate is a template declaration;
1152 /// othewise, it is a tag declaration.
1153 bool TemplateScope : 1;
1155 /// \brief Whether this class is an __interface.
1156 bool IsInterface : 1;
1158 /// \brief The class or class template whose definition we are parsing.
1159 Decl *TagOrTemplate;
1161 /// LateParsedDeclarations - Method declarations, inline definitions and
1162 /// nested classes that contain pieces whose parsing will be delayed until
1163 /// the top-level class is fully defined.
1164 LateParsedDeclarationsContainer LateParsedDeclarations;
1167 /// \brief The stack of classes that is currently being
1168 /// parsed. Nested and local classes will be pushed onto this stack
1169 /// when they are parsed, and removed afterward.
1170 std::stack<ParsingClass *> ClassStack;
1172 ParsingClass &getCurrentClass() {
1173 assert(!ClassStack.empty() && "No lexed method stacks!");
1174 return *ClassStack.top();
1177 /// \brief RAII object used to manage the parsing of a class definition.
1178 class ParsingClassDefinition {
1181 Sema::ParsingClassState State;
1184 ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass,
1186 : P(P), Popped(false),
1187 State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
1190 /// \brief Pop this class of the stack.
1192 assert(!Popped && "Nested class has already been popped");
1194 P.PopParsingClass(State);
1197 ~ParsingClassDefinition() {
1199 P.PopParsingClass(State);
1203 /// \brief Contains information about any template-specific
1204 /// information that has been parsed prior to parsing declaration
1206 struct ParsedTemplateInfo {
1207 ParsedTemplateInfo()
1208 : Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { }
1210 ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
1211 bool isSpecialization,
1212 bool lastParameterListWasEmpty = false)
1213 : Kind(isSpecialization? ExplicitSpecialization : Template),
1214 TemplateParams(TemplateParams),
1215 LastParameterListWasEmpty(lastParameterListWasEmpty) { }
1217 explicit ParsedTemplateInfo(SourceLocation ExternLoc,
1218 SourceLocation TemplateLoc)
1219 : Kind(ExplicitInstantiation), TemplateParams(nullptr),
1220 ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
1221 LastParameterListWasEmpty(false){ }
1223 /// \brief The kind of template we are parsing.
1225 /// \brief We are not parsing a template at all.
1227 /// \brief We are parsing a template declaration.
1229 /// \brief We are parsing an explicit specialization.
1230 ExplicitSpecialization,
1231 /// \brief We are parsing an explicit instantiation.
1232 ExplicitInstantiation
1235 /// \brief The template parameter lists, for template declarations
1236 /// and explicit specializations.
1237 TemplateParameterLists *TemplateParams;
1239 /// \brief The location of the 'extern' keyword, if any, for an explicit
1241 SourceLocation ExternLoc;
1243 /// \brief The location of the 'template' keyword, for an explicit
1245 SourceLocation TemplateLoc;
1247 /// \brief Whether the last template parameter list was empty.
1248 bool LastParameterListWasEmpty;
1250 SourceRange getSourceRange() const LLVM_READONLY;
1253 void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
1254 void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
1256 static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
1257 static void LateTemplateParserCleanupCallback(void *P);
1259 Sema::ParsingClassState
1260 PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface);
1261 void DeallocateParsedClasses(ParsingClass *Class);
1262 void PopParsingClass(Sema::ParsingClassState);
1264 enum CachedInitKind {
1265 CIK_DefaultArgument,
1266 CIK_DefaultInitializer
1269 NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS,
1270 AttributeList *AccessAttrs,
1271 ParsingDeclarator &D,
1272 const ParsedTemplateInfo &TemplateInfo,
1273 const VirtSpecifiers& VS,
1274 SourceLocation PureSpecLoc);
1275 void ParseCXXNonStaticMemberInitializer(Decl *VarD);
1276 void ParseLexedAttributes(ParsingClass &Class);
1277 void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1278 bool EnterScope, bool OnDefinition);
1279 void ParseLexedAttribute(LateParsedAttribute &LA,
1280 bool EnterScope, bool OnDefinition);
1281 void ParseLexedMethodDeclarations(ParsingClass &Class);
1282 void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
1283 void ParseLexedMethodDefs(ParsingClass &Class);
1284 void ParseLexedMethodDef(LexedMethod &LM);
1285 void ParseLexedMemberInitializers(ParsingClass &Class);
1286 void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
1287 void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod);
1288 bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
1289 bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK);
1290 bool ConsumeAndStoreConditional(CachedTokens &Toks);
1291 bool ConsumeAndStoreUntil(tok::TokenKind T1,
1293 bool StopAtSemi = true,
1294 bool ConsumeFinalToken = true) {
1295 return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
1297 bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
1299 bool StopAtSemi = true,
1300 bool ConsumeFinalToken = true);
1302 //===--------------------------------------------------------------------===//
1303 // C99 6.9: External Definitions.
1304 struct ParsedAttributesWithRange : ParsedAttributes {
1305 ParsedAttributesWithRange(AttributeFactory &factory)
1306 : ParsedAttributes(factory) {}
1309 ParsedAttributes::clear();
1310 Range = SourceRange();
1316 DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
1317 ParsingDeclSpec *DS = nullptr);
1318 bool isDeclarationAfterDeclarator();
1319 bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
1320 DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(
1321 ParsedAttributesWithRange &attrs,
1322 ParsingDeclSpec *DS = nullptr,
1323 AccessSpecifier AS = AS_none);
1324 DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
1325 ParsingDeclSpec &DS,
1326 AccessSpecifier AS);
1328 void SkipFunctionBody();
1329 Decl *ParseFunctionDefinition(ParsingDeclarator &D,
1330 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1331 LateParsedAttrList *LateParsedAttrs = nullptr);
1332 void ParseKNRParamDeclarations(Declarator &D);
1333 // EndLoc, if non-NULL, is filled with the location of the last token of
1335 ExprResult ParseSimpleAsm(SourceLocation *EndLoc = nullptr);
1336 ExprResult ParseAsmStringLiteral();
1338 // Objective-C External Declarations
1339 void MaybeSkipAttributes(tok::ObjCKeywordKind Kind);
1340 DeclGroupPtrTy ParseObjCAtDirectives();
1341 DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
1342 Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
1343 ParsedAttributes &prefixAttrs);
1344 class ObjCTypeParamListScope;
1345 ObjCTypeParamList *parseObjCTypeParamList();
1346 ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs(
1347 ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
1348 SmallVectorImpl<IdentifierLocPair> &protocolIdents,
1349 SourceLocation &rAngleLoc, bool mayBeProtocolList = true);
1351 void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
1352 BalancedDelimiterTracker &T,
1353 SmallVectorImpl<Decl *> &AllIvarDecls,
1354 bool RBraceMissing);
1355 void ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1356 tok::ObjCKeywordKind visibility,
1357 SourceLocation atLoc);
1358 bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P,
1359 SmallVectorImpl<SourceLocation> &PLocs,
1360 bool WarnOnDeclarations,
1361 bool ForObjCContainer,
1362 SourceLocation &LAngleLoc,
1363 SourceLocation &EndProtoLoc,
1364 bool consumeLastToken);
1366 /// Parse the first angle-bracket-delimited clause for an
1367 /// Objective-C object or object pointer type, which may be either
1368 /// type arguments or protocol qualifiers.
1369 void parseObjCTypeArgsOrProtocolQualifiers(
1370 ParsedType baseType,
1371 SourceLocation &typeArgsLAngleLoc,
1372 SmallVectorImpl<ParsedType> &typeArgs,
1373 SourceLocation &typeArgsRAngleLoc,
1374 SourceLocation &protocolLAngleLoc,
1375 SmallVectorImpl<Decl *> &protocols,
1376 SmallVectorImpl<SourceLocation> &protocolLocs,
1377 SourceLocation &protocolRAngleLoc,
1378 bool consumeLastToken,
1379 bool warnOnIncompleteProtocols);
1381 /// Parse either Objective-C type arguments or protocol qualifiers; if the
1382 /// former, also parse protocol qualifiers afterward.
1383 void parseObjCTypeArgsAndProtocolQualifiers(
1384 ParsedType baseType,
1385 SourceLocation &typeArgsLAngleLoc,
1386 SmallVectorImpl<ParsedType> &typeArgs,
1387 SourceLocation &typeArgsRAngleLoc,
1388 SourceLocation &protocolLAngleLoc,
1389 SmallVectorImpl<Decl *> &protocols,
1390 SmallVectorImpl<SourceLocation> &protocolLocs,
1391 SourceLocation &protocolRAngleLoc,
1392 bool consumeLastToken);
1394 /// Parse a protocol qualifier type such as '<NSCopying>', which is
1395 /// an anachronistic way of writing 'id<NSCopying>'.
1396 TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc);
1398 /// Parse Objective-C type arguments and protocol qualifiers, extending the
1399 /// current type with the parsed result.
1400 TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc,
1402 bool consumeLastToken,
1403 SourceLocation &endLoc);
1405 void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
1407 DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
1408 ParsedAttributes &prefixAttrs);
1410 struct ObjCImplParsingDataRAII {
1414 typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer;
1415 LateParsedObjCMethodContainer LateParsedObjCMethods;
1417 ObjCImplParsingDataRAII(Parser &parser, Decl *D)
1418 : P(parser), Dcl(D), HasCFunction(false) {
1419 P.CurParsedObjCImpl = this;
1422 ~ObjCImplParsingDataRAII();
1424 void finish(SourceRange AtEnd);
1425 bool isFinished() const { return Finished; }
1430 ObjCImplParsingDataRAII *CurParsedObjCImpl;
1431 void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl);
1433 DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc);
1434 DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
1435 Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
1436 Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
1437 Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
1439 IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
1440 // Definitions for Objective-c context sensitive keywords recognition.
1442 objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
1443 objc_nonnull, objc_nullable, objc_null_unspecified,
1446 IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
1448 bool isTokIdentifier_in() const;
1450 ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx,
1451 ParsedAttributes *ParamAttrs);
1452 void ParseObjCMethodRequirement();
1453 Decl *ParseObjCMethodPrototype(
1454 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1455 bool MethodDefinition = true);
1456 Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
1457 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1458 bool MethodDefinition=true);
1459 void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
1461 Decl *ParseObjCMethodDefinition();
1464 //===--------------------------------------------------------------------===//
1465 // C99 6.5: Expressions.
1467 /// TypeCastState - State whether an expression is or may be a type cast.
1468 enum TypeCastState {
1474 ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast);
1475 ExprResult ParseConstantExpressionInExprEvalContext(
1476 TypeCastState isTypeCast = NotTypeCast);
1477 ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast);
1478 ExprResult ParseConstraintExpression();
1479 // Expr that doesn't include commas.
1480 ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast);
1482 ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1483 unsigned &NumLineToksConsumed,
1484 bool IsUnevaluated);
1487 ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
1489 ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
1491 ExprResult ParseRHSOfBinaryExpression(ExprResult LHS,
1492 prec::Level MinPrec);
1493 ExprResult ParseCastExpression(bool isUnaryExpression,
1494 bool isAddressOfOperand,
1496 TypeCastState isTypeCast,
1497 bool isVectorLiteral = false);
1498 ExprResult ParseCastExpression(bool isUnaryExpression,
1499 bool isAddressOfOperand = false,
1500 TypeCastState isTypeCast = NotTypeCast,
1501 bool isVectorLiteral = false);
1503 /// Returns true if the next token cannot start an expression.
1504 bool isNotExpressionStart();
1506 /// Returns true if the next token would start a postfix-expression
1508 bool isPostfixExpressionSuffixStart() {
1509 tok::TokenKind K = Tok.getKind();
1510 return (K == tok::l_square || K == tok::l_paren ||
1511 K == tok::period || K == tok::arrow ||
1512 K == tok::plusplus || K == tok::minusminus);
1515 bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less);
1517 ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
1518 ExprResult ParseUnaryExprOrTypeTraitExpression();
1519 ExprResult ParseBuiltinPrimaryExpression();
1521 ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1524 SourceRange &CastRange);
1526 typedef SmallVector<Expr*, 20> ExprListTy;
1527 typedef SmallVector<SourceLocation, 20> CommaLocsTy;
1529 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1530 bool ParseExpressionList(
1531 SmallVectorImpl<Expr *> &Exprs,
1532 SmallVectorImpl<SourceLocation> &CommaLocs,
1533 llvm::function_ref<void()> Completer = llvm::function_ref<void()>());
1535 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
1536 /// used for misc language extensions.
1537 bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
1538 SmallVectorImpl<SourceLocation> &CommaLocs);
1541 /// ParenParseOption - Control what ParseParenExpression will parse.
1542 enum ParenParseOption {
1543 SimpleExpr, // Only parse '(' expression ')'
1544 CompoundStmt, // Also allow '(' compound-statement ')'
1545 CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
1546 CastExpr // Also allow '(' type-name ')' <anything>
1548 ExprResult ParseParenExpression(ParenParseOption &ExprType,
1549 bool stopIfCastExpr,
1552 SourceLocation &RParenLoc);
1554 ExprResult ParseCXXAmbiguousParenExpression(
1555 ParenParseOption &ExprType, ParsedType &CastTy,
1556 BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt);
1557 ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
1558 SourceLocation LParenLoc,
1559 SourceLocation RParenLoc);
1561 ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
1563 ExprResult ParseGenericSelectionExpression();
1565 ExprResult ParseObjCBoolLiteral();
1567 ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T);
1569 //===--------------------------------------------------------------------===//
1571 ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
1572 Token &Replacement);
1573 ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
1575 bool areTokensAdjacent(const Token &A, const Token &B);
1577 void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
1578 bool EnteringContext, IdentifierInfo &II,
1581 bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
1582 ParsedType ObjectType,
1583 bool EnteringContext,
1584 bool *MayBePseudoDestructor = nullptr,
1585 bool IsTypename = false,
1586 IdentifierInfo **LastII = nullptr,
1587 bool OnlyNamespace = false);
1589 //===--------------------------------------------------------------------===//
1590 // C++0x 5.1.2: Lambda expressions
1592 // [...] () -> type {...}
1593 ExprResult ParseLambdaExpression();
1594 ExprResult TryParseLambdaExpression();
1595 Optional<unsigned> ParseLambdaIntroducer(LambdaIntroducer &Intro,
1596 bool *SkippedInits = nullptr);
1597 bool TryParseLambdaIntroducer(LambdaIntroducer &Intro);
1598 ExprResult ParseLambdaExpressionAfterIntroducer(
1599 LambdaIntroducer &Intro);
1601 //===--------------------------------------------------------------------===//
1602 // C++ 5.2p1: C++ Casts
1603 ExprResult ParseCXXCasts();
1605 //===--------------------------------------------------------------------===//
1606 // C++ 5.2p1: C++ Type Identification
1607 ExprResult ParseCXXTypeid();
1609 //===--------------------------------------------------------------------===//
1610 // C++ : Microsoft __uuidof Expression
1611 ExprResult ParseCXXUuidof();
1613 //===--------------------------------------------------------------------===//
1614 // C++ 5.2.4: C++ Pseudo-Destructor Expressions
1615 ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1616 tok::TokenKind OpKind,
1618 ParsedType ObjectType);
1620 //===--------------------------------------------------------------------===//
1621 // C++ 9.3.2: C++ 'this' pointer
1622 ExprResult ParseCXXThis();
1624 //===--------------------------------------------------------------------===//
1625 // C++ 15: C++ Throw Expression
1626 ExprResult ParseThrowExpression();
1628 ExceptionSpecificationType tryParseExceptionSpecification(
1630 SourceRange &SpecificationRange,
1631 SmallVectorImpl<ParsedType> &DynamicExceptions,
1632 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
1633 ExprResult &NoexceptExpr,
1634 CachedTokens *&ExceptionSpecTokens);
1636 // EndLoc is filled with the location of the last token of the specification.
1637 ExceptionSpecificationType ParseDynamicExceptionSpecification(
1638 SourceRange &SpecificationRange,
1639 SmallVectorImpl<ParsedType> &Exceptions,
1640 SmallVectorImpl<SourceRange> &Ranges);
1642 //===--------------------------------------------------------------------===//
1643 // C++0x 8: Function declaration trailing-return-type
1644 TypeResult ParseTrailingReturnType(SourceRange &Range);
1646 //===--------------------------------------------------------------------===//
1647 // C++ 2.13.5: C++ Boolean Literals
1648 ExprResult ParseCXXBoolLiteral();
1650 //===--------------------------------------------------------------------===//
1651 // C++ 5.2.3: Explicit type conversion (functional notation)
1652 ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
1654 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1655 /// This should only be called when the current token is known to be part of
1656 /// simple-type-specifier.
1657 void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
1659 bool ParseCXXTypeSpecifierSeq(DeclSpec &DS);
1661 //===--------------------------------------------------------------------===//
1662 // C++ 5.3.4 and 5.3.5: C++ new and delete
1663 bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs,
1665 void ParseDirectNewDeclarator(Declarator &D);
1666 ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
1667 ExprResult ParseCXXDeleteExpression(bool UseGlobal,
1668 SourceLocation Start);
1670 //===--------------------------------------------------------------------===//
1671 // C++ if/switch/while condition expression.
1672 Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt,
1674 Sema::ConditionKind CK);
1676 //===--------------------------------------------------------------------===//
1679 ExprResult ParseCoyieldExpression();
1681 //===--------------------------------------------------------------------===//
1682 // C99 6.7.8: Initialization.
1684 /// ParseInitializer
1685 /// initializer: [C99 6.7.8]
1686 /// assignment-expression
1688 ExprResult ParseInitializer() {
1689 if (Tok.isNot(tok::l_brace))
1690 return ParseAssignmentExpression();
1691 return ParseBraceInitializer();
1693 bool MayBeDesignationStart();
1694 ExprResult ParseBraceInitializer();
1695 ExprResult ParseInitializerWithPotentialDesignator();
1697 //===--------------------------------------------------------------------===//
1698 // clang Expressions
1700 ExprResult ParseBlockLiteralExpression(); // ^{...}
1702 //===--------------------------------------------------------------------===//
1703 // Objective-C Expressions
1704 ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
1705 ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
1706 ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
1707 ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
1708 ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
1709 ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
1710 ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
1711 ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
1712 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
1713 ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
1714 ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
1715 bool isSimpleObjCMessageExpression();
1716 ExprResult ParseObjCMessageExpression();
1717 ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
1718 SourceLocation SuperLoc,
1719 ParsedType ReceiverType,
1720 Expr *ReceiverExpr);
1721 ExprResult ParseAssignmentExprWithObjCMessageExprStart(
1722 SourceLocation LBracloc, SourceLocation SuperLoc,
1723 ParsedType ReceiverType, Expr *ReceiverExpr);
1724 bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
1726 //===--------------------------------------------------------------------===//
1727 // C99 6.8: Statements and Blocks.
1729 /// A SmallVector of statements, with stack size 32 (as that is the only one
1731 typedef SmallVector<Stmt*, 32> StmtVector;
1732 /// A SmallVector of expressions, with stack size 12 (the maximum used.)
1733 typedef SmallVector<Expr*, 12> ExprVector;
1734 /// A SmallVector of types.
1735 typedef SmallVector<ParsedType, 12> TypeVector;
1737 StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
1738 bool AllowOpenMPStandalone = false);
1739 enum AllowedConstructsKind {
1740 /// \brief Allow any declarations, statements, OpenMP directives.
1742 /// \brief Allow only statements and non-standalone OpenMP directives.
1743 ACK_StatementsOpenMPNonStandalone,
1744 /// \brief Allow statements and all executable OpenMP directives
1745 ACK_StatementsOpenMPAnyExecutable
1748 ParseStatementOrDeclaration(StmtVector &Stmts, AllowedConstructsKind Allowed,
1749 SourceLocation *TrailingElseLoc = nullptr);
1750 StmtResult ParseStatementOrDeclarationAfterAttributes(
1752 AllowedConstructsKind Allowed,
1753 SourceLocation *TrailingElseLoc,
1754 ParsedAttributesWithRange &Attrs);
1755 StmtResult ParseExprStatement();
1756 StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs);
1757 StmtResult ParseCaseStatement(bool MissingCase = false,
1758 ExprResult Expr = ExprResult());
1759 StmtResult ParseDefaultStatement();
1760 StmtResult ParseCompoundStatement(bool isStmtExpr = false);
1761 StmtResult ParseCompoundStatement(bool isStmtExpr,
1762 unsigned ScopeFlags);
1763 void ParseCompoundStatementLeadingPragmas();
1764 StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
1765 bool ParseParenExprOrCondition(StmtResult *InitStmt,
1766 Sema::ConditionResult &CondResult,
1768 Sema::ConditionKind CK);
1769 StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
1770 StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
1771 StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
1772 StmtResult ParseDoStatement();
1773 StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
1774 StmtResult ParseGotoStatement();
1775 StmtResult ParseContinueStatement();
1776 StmtResult ParseBreakStatement();
1777 StmtResult ParseReturnStatement();
1778 StmtResult ParseAsmStatement(bool &msAsm);
1779 StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
1780 StmtResult ParsePragmaLoopHint(StmtVector &Stmts,
1781 AllowedConstructsKind Allowed,
1782 SourceLocation *TrailingElseLoc,
1783 ParsedAttributesWithRange &Attrs);
1785 /// \brief Describes the behavior that should be taken for an __if_exists
1787 enum IfExistsBehavior {
1788 /// \brief Parse the block; this code is always used.
1790 /// \brief Skip the block entirely; this code is never used.
1792 /// \brief Parse the block as a dependent block, which may be used in
1793 /// some template instantiations but not others.
1797 /// \brief Describes the condition of a Microsoft __if_exists or
1798 /// __if_not_exists block.
1799 struct IfExistsCondition {
1800 /// \brief The location of the initial keyword.
1801 SourceLocation KeywordLoc;
1802 /// \brief Whether this is an __if_exists block (rather than an
1803 /// __if_not_exists block).
1806 /// \brief Nested-name-specifier preceding the name.
1809 /// \brief The name we're looking for.
1812 /// \brief The behavior of this __if_exists or __if_not_exists block
1814 IfExistsBehavior Behavior;
1817 bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
1818 void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
1819 void ParseMicrosoftIfExistsExternalDeclaration();
1820 void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
1821 AccessSpecifier& CurAS);
1822 bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
1824 bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
1825 SmallVectorImpl<Expr *> &Constraints,
1826 SmallVectorImpl<Expr *> &Exprs);
1828 //===--------------------------------------------------------------------===//
1829 // C++ 6: Statements and Blocks
1831 StmtResult ParseCXXTryBlock();
1832 StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
1833 StmtResult ParseCXXCatchBlock(bool FnCatch = false);
1835 //===--------------------------------------------------------------------===//
1836 // MS: SEH Statements and Blocks
1838 StmtResult ParseSEHTryBlock();
1839 StmtResult ParseSEHExceptBlock(SourceLocation Loc);
1840 StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
1841 StmtResult ParseSEHLeaveStatement();
1843 //===--------------------------------------------------------------------===//
1844 // Objective-C Statements
1846 StmtResult ParseObjCAtStatement(SourceLocation atLoc);
1847 StmtResult ParseObjCTryStmt(SourceLocation atLoc);
1848 StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
1849 StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
1850 StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
1853 //===--------------------------------------------------------------------===//
1854 // C99 6.7: Declarations.
1856 /// A context for parsing declaration specifiers. TODO: flesh this
1857 /// out, there are other significant restrictions on specifiers than
1858 /// would be best implemented in the parser.
1859 enum class DeclSpecContext {
1860 DSC_normal, // normal context
1861 DSC_class, // class context, enables 'friend'
1862 DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
1863 DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
1864 DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration
1865 DSC_top_level, // top-level/namespace declaration context
1866 DSC_template_param, // template parameter context
1867 DSC_template_type_arg, // template type argument context
1868 DSC_objc_method_result, // ObjC method result context, enables 'instancetype'
1869 DSC_condition // condition declaration context
1872 /// Is this a context in which we are parsing just a type-specifier (or
1873 /// trailing-type-specifier)?
1874 static bool isTypeSpecifier(DeclSpecContext DSC) {
1876 case DeclSpecContext::DSC_normal:
1877 case DeclSpecContext::DSC_template_param:
1878 case DeclSpecContext::DSC_class:
1879 case DeclSpecContext::DSC_top_level:
1880 case DeclSpecContext::DSC_objc_method_result:
1881 case DeclSpecContext::DSC_condition:
1884 case DeclSpecContext::DSC_template_type_arg:
1885 case DeclSpecContext::DSC_type_specifier:
1886 case DeclSpecContext::DSC_trailing:
1887 case DeclSpecContext::DSC_alias_declaration:
1890 llvm_unreachable("Missing DeclSpecContext case");
1893 /// Is this a context in which we can perform class template argument
1895 static bool isClassTemplateDeductionContext(DeclSpecContext DSC) {
1897 case DeclSpecContext::DSC_normal:
1898 case DeclSpecContext::DSC_template_param:
1899 case DeclSpecContext::DSC_class:
1900 case DeclSpecContext::DSC_top_level:
1901 case DeclSpecContext::DSC_condition:
1902 case DeclSpecContext::DSC_type_specifier:
1905 case DeclSpecContext::DSC_objc_method_result:
1906 case DeclSpecContext::DSC_template_type_arg:
1907 case DeclSpecContext::DSC_trailing:
1908 case DeclSpecContext::DSC_alias_declaration:
1911 llvm_unreachable("Missing DeclSpecContext case");
1914 /// Information on a C++0x for-range-initializer found while parsing a
1915 /// declaration which turns out to be a for-range-declaration.
1916 struct ForRangeInit {
1917 SourceLocation ColonLoc;
1918 ExprResult RangeExpr;
1920 bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
1923 DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context,
1924 SourceLocation &DeclEnd,
1925 ParsedAttributesWithRange &attrs);
1926 DeclGroupPtrTy ParseSimpleDeclaration(DeclaratorContext Context,
1927 SourceLocation &DeclEnd,
1928 ParsedAttributesWithRange &attrs,
1930 ForRangeInit *FRI = nullptr);
1931 bool MightBeDeclarator(DeclaratorContext Context);
1932 DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context,
1933 SourceLocation *DeclEnd = nullptr,
1934 ForRangeInit *FRI = nullptr);
1935 Decl *ParseDeclarationAfterDeclarator(Declarator &D,
1936 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
1937 bool ParseAsmAttributesAfterDeclarator(Declarator &D);
1938 Decl *ParseDeclarationAfterDeclaratorAndAttributes(
1940 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1941 ForRangeInit *FRI = nullptr);
1942 Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
1943 Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
1945 /// \brief When in code-completion, skip parsing of the function/method body
1946 /// unless the body contains the code-completion point.
1948 /// \returns true if the function body was skipped.
1949 bool trySkippingFunctionBody();
1951 bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
1952 const ParsedTemplateInfo &TemplateInfo,
1953 AccessSpecifier AS, DeclSpecContext DSC,
1954 ParsedAttributesWithRange &Attrs);
1956 getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context);
1957 void ParseDeclarationSpecifiers(
1959 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1960 AccessSpecifier AS = AS_none,
1961 DeclSpecContext DSC = DeclSpecContext::DSC_normal,
1962 LateParsedAttrList *LateAttrs = nullptr);
1963 bool DiagnoseMissingSemiAfterTagDefinition(
1964 DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext,
1965 LateParsedAttrList *LateAttrs = nullptr);
1967 void ParseSpecifierQualifierList(
1968 DeclSpec &DS, AccessSpecifier AS = AS_none,
1969 DeclSpecContext DSC = DeclSpecContext::DSC_normal);
1971 void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
1972 DeclaratorContext Context);
1974 void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
1975 const ParsedTemplateInfo &TemplateInfo,
1976 AccessSpecifier AS, DeclSpecContext DSC);
1977 void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
1978 void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType,
1981 void ParseStructDeclaration(
1982 ParsingDeclSpec &DS,
1983 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback);
1985 bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
1986 bool isTypeSpecifierQualifier();
1988 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
1989 /// is definitely a type-specifier. Return false if it isn't part of a type
1990 /// specifier or if we're not sure.
1991 bool isKnownToBeTypeSpecifier(const Token &Tok) const;
1993 /// \brief Return true if we know that we are definitely looking at a
1994 /// decl-specifier, and isn't part of an expression such as a function-style
1995 /// cast. Return false if it's no a decl-specifier, or we're not sure.
1996 bool isKnownToBeDeclarationSpecifier() {
1997 if (getLangOpts().CPlusPlus)
1998 return isCXXDeclarationSpecifier() == TPResult::True;
1999 return isDeclarationSpecifier(true);
2002 /// isDeclarationStatement - Disambiguates between a declaration or an
2003 /// expression statement, when parsing function bodies.
2004 /// Returns true for declaration, false for expression.
2005 bool isDeclarationStatement() {
2006 if (getLangOpts().CPlusPlus)
2007 return isCXXDeclarationStatement();
2008 return isDeclarationSpecifier(true);
2011 /// isForInitDeclaration - Disambiguates between a declaration or an
2012 /// expression in the context of the C 'clause-1' or the C++
2013 // 'for-init-statement' part of a 'for' statement.
2014 /// Returns true for declaration, false for expression.
2015 bool isForInitDeclaration() {
2016 if (getLangOpts().CPlusPlus)
2017 return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
2018 return isDeclarationSpecifier(true);
2021 /// \brief Determine whether this is a C++1z for-range-identifier.
2022 bool isForRangeIdentifier();
2024 /// \brief Determine whether we are currently at the start of an Objective-C
2025 /// class message that appears to be missing the open bracket '['.
2026 bool isStartOfObjCClassMessageMissingOpenBracket();
2028 /// \brief Starting with a scope specifier, identifier, or
2029 /// template-id that refers to the current class, determine whether
2030 /// this is a constructor declarator.
2031 bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false);
2033 /// \brief Specifies the context in which type-id/expression
2034 /// disambiguation will occur.
2035 enum TentativeCXXTypeIdContext {
2038 TypeIdAsTemplateArgument
2042 /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
2043 /// whether the parens contain an expression or a type-id.
2044 /// Returns true for a type-id and false for an expression.
2045 bool isTypeIdInParens(bool &isAmbiguous) {
2046 if (getLangOpts().CPlusPlus)
2047 return isCXXTypeId(TypeIdInParens, isAmbiguous);
2048 isAmbiguous = false;
2049 return isTypeSpecifierQualifier();
2051 bool isTypeIdInParens() {
2053 return isTypeIdInParens(isAmbiguous);
2056 /// \brief Checks if the current tokens form type-id or expression.
2057 /// It is similar to isTypeIdInParens but does not suppose that type-id
2058 /// is in parenthesis.
2059 bool isTypeIdUnambiguously() {
2061 if (getLangOpts().CPlusPlus)
2062 return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous);
2063 return isTypeSpecifierQualifier();
2066 /// isCXXDeclarationStatement - C++-specialized function that disambiguates
2067 /// between a declaration or an expression statement, when parsing function
2068 /// bodies. Returns true for declaration, false for expression.
2069 bool isCXXDeclarationStatement();
2071 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
2072 /// between a simple-declaration or an expression-statement.
2073 /// If during the disambiguation process a parsing error is encountered,
2074 /// the function returns true to let the declaration parsing code handle it.
2075 /// Returns false if the statement is disambiguated as expression.
2076 bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
2078 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
2079 /// a constructor-style initializer, when parsing declaration statements.
2080 /// Returns true for function declarator and false for constructor-style
2081 /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
2082 /// might be a constructor-style initializer.
2083 /// If during the disambiguation process a parsing error is encountered,
2084 /// the function returns true to let the declaration parsing code handle it.
2085 bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr);
2087 struct ConditionDeclarationOrInitStatementState;
2088 enum class ConditionOrInitStatement {
2089 Expression, ///< Disambiguated as an expression (either kind).
2090 ConditionDecl, ///< Disambiguated as the declaration form of condition.
2091 InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement.
2092 Error ///< Can't be any of the above!
2094 /// \brief Disambiguates between the different kinds of things that can happen
2095 /// after 'if (' or 'switch ('. This could be one of two different kinds of
2096 /// declaration (depending on whether there is a ';' later) or an expression.
2097 ConditionOrInitStatement
2098 isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt);
2100 bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
2101 bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
2103 return isCXXTypeId(Context, isAmbiguous);
2106 /// TPResult - Used as the result value for functions whose purpose is to
2107 /// disambiguate C++ constructs by "tentatively parsing" them.
2108 enum class TPResult {
2109 True, False, Ambiguous, Error
2112 /// \brief Based only on the given token kind, determine whether we know that
2113 /// we're at the start of an expression or a type-specifier-seq (which may
2114 /// be an expression, in C++).
2116 /// This routine does not attempt to resolve any of the trick cases, e.g.,
2117 /// those involving lookup of identifiers.
2119 /// \returns \c TPR_true if this token starts an expression, \c TPR_false if
2120 /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot
2122 TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind);
2124 /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a
2125 /// declaration specifier, TPResult::False if it is not,
2126 /// TPResult::Ambiguous if it could be either a decl-specifier or a
2127 /// function-style cast, and TPResult::Error if a parsing error was
2128 /// encountered. If it could be a braced C++11 function-style cast, returns
2129 /// BracedCastResult.
2130 /// Doesn't consume tokens.
2132 isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False,
2133 bool *HasMissingTypename = nullptr);
2135 /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
2136 /// \c TPResult::Ambiguous, determine whether the decl-specifier would be
2137 /// a type-specifier other than a cv-qualifier.
2138 bool isCXXDeclarationSpecifierAType();
2140 /// \brief Determine whether an identifier has been tentatively declared as a
2141 /// non-type. Such tentative declarations should not be found to name a type
2142 /// during a tentative parse, but also should not be annotated as a non-type.
2143 bool isTentativelyDeclared(IdentifierInfo *II);
2145 // "Tentative parsing" functions, used for disambiguation. If a parsing error
2146 // is encountered they will return TPResult::Error.
2147 // Returning TPResult::True/False indicates that the ambiguity was
2148 // resolved and tentative parsing may stop. TPResult::Ambiguous indicates
2149 // that more tentative parsing is necessary for disambiguation.
2150 // They all consume tokens, so backtracking should be used after calling them.
2152 TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
2153 TPResult TryParseTypeofSpecifier();
2154 TPResult TryParseProtocolQualifiers();
2155 TPResult TryParsePtrOperatorSeq();
2156 TPResult TryParseOperatorId();
2157 TPResult TryParseInitDeclaratorList();
2158 TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier=true);
2160 TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr,
2161 bool VersusTemplateArg = false);
2162 TPResult TryParseFunctionDeclarator();
2163 TPResult TryParseBracketDeclarator();
2164 TPResult TryConsumeDeclarationSpecifier();
2167 TypeResult ParseTypeName(SourceRange *Range = nullptr,
2168 DeclaratorContext Context
2169 = DeclaratorContext::TypeNameContext,
2170 AccessSpecifier AS = AS_none,
2171 Decl **OwnedType = nullptr,
2172 ParsedAttributes *Attrs = nullptr);
2175 void ParseBlockId(SourceLocation CaretLoc);
2177 /// Are [[]] attributes enabled?
2178 bool standardAttributesAllowed() const {
2179 const LangOptions &LO = getLangOpts();
2180 return LO.DoubleSquareBracketAttributes;
2183 // Check for the start of an attribute-specifier-seq in a context where an
2184 // attribute is not allowed.
2185 bool CheckProhibitedCXX11Attribute() {
2186 assert(Tok.is(tok::l_square));
2187 if (!standardAttributesAllowed() || NextToken().isNot(tok::l_square))
2189 return DiagnoseProhibitedCXX11Attribute();
2192 bool DiagnoseProhibitedCXX11Attribute();
2193 void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2194 SourceLocation CorrectLocation) {
2195 if (!standardAttributesAllowed())
2197 if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
2198 Tok.isNot(tok::kw_alignas))
2200 DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
2202 void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2203 SourceLocation CorrectLocation);
2205 void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
2206 DeclSpec &DS, Sema::TagUseKind TUK);
2208 // FixItLoc = possible correct location for the attributes
2209 void ProhibitAttributes(ParsedAttributesWithRange &attrs,
2210 SourceLocation FixItLoc = SourceLocation()) {
2211 if (!attrs.Range.isValid()) return;
2212 DiagnoseProhibitedAttributes(attrs, FixItLoc);
2215 void DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs,
2216 SourceLocation FixItLoc);
2218 // Forbid C++11 and C2x attributes that appear on certain syntactic locations
2219 // which standard permits but we don't supported yet, for example, attributes
2220 // appertain to decl specifiers.
2221 void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
2224 /// \brief Skip C++11 and C2x attributes and return the end location of the
2226 /// \returns SourceLocation() if there are no attributes.
2227 SourceLocation SkipCXX11Attributes();
2229 /// \brief Diagnose and skip C++11 and C2x attributes that appear in syntactic
2230 /// locations where attributes are not allowed.
2231 void DiagnoseAndSkipCXX11Attributes();
2233 /// \brief Parses syntax-generic attribute arguments for attributes which are
2234 /// known to the implementation, and adds them to the given ParsedAttributes
2235 /// list with the given attribute syntax. Returns the number of arguments
2236 /// parsed for the attribute.
2238 ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2239 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2240 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2241 AttributeList::Syntax Syntax);
2243 void MaybeParseGNUAttributes(Declarator &D,
2244 LateParsedAttrList *LateAttrs = nullptr) {
2245 if (Tok.is(tok::kw___attribute)) {
2246 ParsedAttributes attrs(AttrFactory);
2247 SourceLocation endLoc;
2248 ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D);
2249 D.takeAttributes(attrs, endLoc);
2252 void MaybeParseGNUAttributes(ParsedAttributes &attrs,
2253 SourceLocation *endLoc = nullptr,
2254 LateParsedAttrList *LateAttrs = nullptr) {
2255 if (Tok.is(tok::kw___attribute))
2256 ParseGNUAttributes(attrs, endLoc, LateAttrs);
2258 void ParseGNUAttributes(ParsedAttributes &attrs,
2259 SourceLocation *endLoc = nullptr,
2260 LateParsedAttrList *LateAttrs = nullptr,
2261 Declarator *D = nullptr);
2262 void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
2263 SourceLocation AttrNameLoc,
2264 ParsedAttributes &Attrs,
2265 SourceLocation *EndLoc,
2266 IdentifierInfo *ScopeName,
2267 SourceLocation ScopeLoc,
2268 AttributeList::Syntax Syntax,
2270 IdentifierLoc *ParseIdentifierLoc();
2273 ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2274 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2275 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2276 AttributeList::Syntax Syntax);
2278 void MaybeParseCXX11Attributes(Declarator &D) {
2279 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
2280 ParsedAttributesWithRange attrs(AttrFactory);
2281 SourceLocation endLoc;
2282 ParseCXX11Attributes(attrs, &endLoc);
2283 D.takeAttributes(attrs, endLoc);
2286 void MaybeParseCXX11Attributes(ParsedAttributes &attrs,
2287 SourceLocation *endLoc = nullptr) {
2288 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
2289 ParsedAttributesWithRange attrsWithRange(AttrFactory);
2290 ParseCXX11Attributes(attrsWithRange, endLoc);
2291 attrs.takeAllFrom(attrsWithRange);
2294 void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2295 SourceLocation *endLoc = nullptr,
2296 bool OuterMightBeMessageSend = false) {
2297 if (standardAttributesAllowed() &&
2298 isCXX11AttributeSpecifier(false, OuterMightBeMessageSend))
2299 ParseCXX11Attributes(attrs, endLoc);
2302 void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
2303 SourceLocation *EndLoc = nullptr);
2304 void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2305 SourceLocation *EndLoc = nullptr);
2306 /// \brief Parses a C++11 (or C2x)-style attribute argument list. Returns true
2307 /// if this results in adding an attribute to the ParsedAttributes list.
2308 bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
2309 SourceLocation AttrNameLoc,
2310 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2311 IdentifierInfo *ScopeName,
2312 SourceLocation ScopeLoc);
2314 IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc);
2316 void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
2317 SourceLocation *endLoc = nullptr) {
2318 if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
2319 ParseMicrosoftAttributes(attrs, endLoc);
2321 void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs);
2322 void ParseMicrosoftAttributes(ParsedAttributes &attrs,
2323 SourceLocation *endLoc = nullptr);
2324 void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2325 SourceLocation *End = nullptr) {
2326 const auto &LO = getLangOpts();
2327 if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec))
2328 ParseMicrosoftDeclSpecs(Attrs, End);
2330 void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2331 SourceLocation *End = nullptr);
2332 bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
2333 SourceLocation AttrNameLoc,
2334 ParsedAttributes &Attrs);
2335 void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
2336 void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2337 SourceLocation SkipExtendedMicrosoftTypeAttributes();
2338 void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
2339 void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
2340 void ParseOpenCLKernelAttributes(ParsedAttributes &attrs);
2341 void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
2342 /// \brief Parses opencl_unroll_hint attribute if language is OpenCL v2.0
2344 /// \return false if error happens.
2345 bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
2346 if (getLangOpts().OpenCL)
2347 return ParseOpenCLUnrollHintAttribute(Attrs);
2350 /// \brief Parses opencl_unroll_hint attribute.
2351 /// \return false if error happens.
2352 bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs);
2353 void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
2355 VersionTuple ParseVersionTuple(SourceRange &Range);
2356 void ParseAvailabilityAttribute(IdentifierInfo &Availability,
2357 SourceLocation AvailabilityLoc,
2358 ParsedAttributes &attrs,
2359 SourceLocation *endLoc,
2360 IdentifierInfo *ScopeName,
2361 SourceLocation ScopeLoc,
2362 AttributeList::Syntax Syntax);
2364 Optional<AvailabilitySpec> ParseAvailabilitySpec();
2365 ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc);
2367 void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol,
2369 ParsedAttributes &Attrs,
2370 SourceLocation *EndLoc,
2371 IdentifierInfo *ScopeName,
2372 SourceLocation ScopeLoc,
2373 AttributeList::Syntax Syntax);
2375 void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
2376 SourceLocation ObjCBridgeRelatedLoc,
2377 ParsedAttributes &attrs,
2378 SourceLocation *endLoc,
2379 IdentifierInfo *ScopeName,
2380 SourceLocation ScopeLoc,
2381 AttributeList::Syntax Syntax);
2383 void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
2384 SourceLocation AttrNameLoc,
2385 ParsedAttributes &Attrs,
2386 SourceLocation *EndLoc,
2387 IdentifierInfo *ScopeName,
2388 SourceLocation ScopeLoc,
2389 AttributeList::Syntax Syntax);
2391 void ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
2392 SourceLocation AttrNameLoc,
2393 ParsedAttributes &Attrs,
2394 SourceLocation *EndLoc,
2395 IdentifierInfo *ScopeName,
2396 SourceLocation ScopeLoc,
2397 AttributeList::Syntax Syntax);
2399 void ParseTypeofSpecifier(DeclSpec &DS);
2400 SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
2401 void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
2402 SourceLocation StartLoc,
2403 SourceLocation EndLoc);
2404 void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
2405 void ParseAtomicSpecifier(DeclSpec &DS);
2407 ExprResult ParseAlignArgument(SourceLocation Start,
2408 SourceLocation &EllipsisLoc);
2409 void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2410 SourceLocation *endLoc = nullptr);
2412 VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
2413 VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
2414 return isCXX11VirtSpecifier(Tok);
2416 void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface,
2417 SourceLocation FriendLoc);
2419 bool isCXX11FinalKeyword() const;
2421 /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
2422 /// enter a new C++ declarator scope and exit it when the function is
2424 class DeclaratorScopeObj {
2430 DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
2431 : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
2433 void EnterDeclaratorScope() {
2434 assert(!EnteredScope && "Already entered the scope!");
2435 assert(SS.isSet() && "C++ scope was not set!");
2437 CreatedScope = true;
2438 P.EnterScope(0); // Not a decl scope.
2440 if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
2441 EnteredScope = true;
2444 ~DeclaratorScopeObj() {
2446 assert(SS.isSet() && "C++ scope was cleared ?");
2447 P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
2454 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
2455 void ParseDeclarator(Declarator &D);
2456 /// A function that parses a variant of direct-declarator.
2457 typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
2458 void ParseDeclaratorInternal(Declarator &D,
2459 DirectDeclParseFunction DirectDeclParser);
2461 enum AttrRequirements {
2462 AR_NoAttributesParsed = 0, ///< No attributes are diagnosed.
2463 AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes.
2464 AR_GNUAttributesParsed = 1 << 1,
2465 AR_CXX11AttributesParsed = 1 << 2,
2466 AR_DeclspecAttributesParsed = 1 << 3,
2467 AR_AllAttributesParsed = AR_GNUAttributesParsed |
2468 AR_CXX11AttributesParsed |
2469 AR_DeclspecAttributesParsed,
2470 AR_VendorAttributesParsed = AR_GNUAttributesParsed |
2471 AR_DeclspecAttributesParsed
2474 void ParseTypeQualifierListOpt(
2475 DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed,
2476 bool AtomicAllowed = true, bool IdentifierRequired = false,
2477 Optional<llvm::function_ref<void()>> CodeCompletionHandler = None);
2478 void ParseDirectDeclarator(Declarator &D);
2479 void ParseDecompositionDeclarator(Declarator &D);
2480 void ParseParenDeclarator(Declarator &D);
2481 void ParseFunctionDeclarator(Declarator &D,
2482 ParsedAttributes &attrs,
2483 BalancedDelimiterTracker &Tracker,
2485 bool RequiresArg = false);
2486 bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
2487 SourceLocation &RefQualifierLoc);
2488 bool isFunctionDeclaratorIdentifierList();
2489 void ParseFunctionDeclaratorIdentifierList(
2491 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
2492 void ParseParameterDeclarationClause(
2494 ParsedAttributes &attrs,
2495 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
2496 SourceLocation &EllipsisLoc);
2497 void ParseBracketDeclarator(Declarator &D);
2498 void ParseMisplacedBracketDeclarator(Declarator &D);
2500 //===--------------------------------------------------------------------===//
2501 // C++ 7: Declarations [dcl.dcl]
2503 /// The kind of attribute specifier we have found.
2504 enum CXX11AttributeKind {
2505 /// This is not an attribute specifier.
2506 CAK_NotAttributeSpecifier,
2507 /// This should be treated as an attribute-specifier.
2508 CAK_AttributeSpecifier,
2509 /// The next tokens are '[[', but this is not an attribute-specifier. This
2510 /// is ill-formed by C++11 [dcl.attr.grammar]p6.
2511 CAK_InvalidAttributeSpecifier
2514 isCXX11AttributeSpecifier(bool Disambiguate = false,
2515 bool OuterMightBeMessageSend = false);
2517 void DiagnoseUnexpectedNamespace(NamedDecl *Context);
2519 DeclGroupPtrTy ParseNamespace(DeclaratorContext Context,
2520 SourceLocation &DeclEnd,
2521 SourceLocation InlineLoc = SourceLocation());
2522 void ParseInnerNamespace(std::vector<SourceLocation> &IdentLoc,
2523 std::vector<IdentifierInfo *> &Ident,
2524 std::vector<SourceLocation> &NamespaceLoc,
2525 unsigned int index, SourceLocation &InlineLoc,
2526 ParsedAttributes &attrs,
2527 BalancedDelimiterTracker &Tracker);
2528 Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context);
2529 Decl *ParseExportDeclaration();
2530 DeclGroupPtrTy ParseUsingDirectiveOrDeclaration(
2531 DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
2532 SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs);
2533 Decl *ParseUsingDirective(DeclaratorContext Context,
2534 SourceLocation UsingLoc,
2535 SourceLocation &DeclEnd,
2536 ParsedAttributes &attrs);
2538 struct UsingDeclarator {
2539 SourceLocation TypenameLoc;
2541 SourceLocation TemplateKWLoc;
2543 SourceLocation EllipsisLoc;
2546 TypenameLoc = TemplateKWLoc = EllipsisLoc = SourceLocation();
2552 bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D);
2553 DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context,
2554 const ParsedTemplateInfo &TemplateInfo,
2555 SourceLocation UsingLoc,
2556 SourceLocation &DeclEnd,
2557 AccessSpecifier AS = AS_none);
2558 Decl *ParseAliasDeclarationAfterDeclarator(
2559 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
2560 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
2561 ParsedAttributes &Attrs, Decl **OwnedType = nullptr);
2563 Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
2564 Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
2565 SourceLocation AliasLoc, IdentifierInfo *Alias,
2566 SourceLocation &DeclEnd);
2568 //===--------------------------------------------------------------------===//
2569 // C++ 9: classes [class] and C structs/unions.
2570 bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
2571 void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
2572 DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo,
2573 AccessSpecifier AS, bool EnteringContext,
2574 DeclSpecContext DSC,
2575 ParsedAttributesWithRange &Attributes);
2576 void SkipCXXMemberSpecification(SourceLocation StartLoc,
2577 SourceLocation AttrFixitLoc,
2580 void ParseCXXMemberSpecification(SourceLocation StartLoc,
2581 SourceLocation AttrFixitLoc,
2582 ParsedAttributesWithRange &Attrs,
2585 ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2586 SourceLocation &EqualLoc);
2587 bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
2589 ExprResult &BitfieldSize,
2590 LateParsedAttrList &LateAttrs);
2591 void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D,
2592 VirtSpecifiers &VS);
2593 DeclGroupPtrTy ParseCXXClassMemberDeclaration(
2594 AccessSpecifier AS, AttributeList *Attr,
2595 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2596 ParsingDeclRAIIObject *DiagsFromTParams = nullptr);
2597 DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas(
2598 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
2599 DeclSpec::TST TagType, Decl *Tag);
2600 void ParseConstructorInitializer(Decl *ConstructorDecl);
2601 MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
2602 void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2605 //===--------------------------------------------------------------------===//
2606 // C++ 10: Derived classes [class.derived]
2607 TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
2608 SourceLocation &EndLocation);
2609 void ParseBaseClause(Decl *ClassDecl);
2610 BaseResult ParseBaseSpecifier(Decl *ClassDecl);
2611 AccessSpecifier getAccessSpecifierIfPresent() const;
2613 bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
2614 SourceLocation TemplateKWLoc,
2615 IdentifierInfo *Name,
2616 SourceLocation NameLoc,
2617 bool EnteringContext,
2618 ParsedType ObjectType,
2620 bool AssumeTemplateId);
2621 bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2622 ParsedType ObjectType,
2623 UnqualifiedId &Result);
2625 //===--------------------------------------------------------------------===//
2626 // OpenMP: Directives and clauses.
2627 /// Parse clauses for '#pragma omp declare simd'.
2628 DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr,
2630 SourceLocation Loc);
2631 /// \brief Parses declarative OpenMP directives.
2632 DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl(
2633 AccessSpecifier &AS, ParsedAttributesWithRange &Attrs,
2634 DeclSpec::TST TagType = DeclSpec::TST_unspecified,
2635 Decl *TagDecl = nullptr);
2636 /// \brief Parse 'omp declare reduction' construct.
2637 DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS);
2638 /// Parses initializer for provided omp_priv declaration inside the reduction
2640 void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm);
2642 /// \brief Parses simple list of variables.
2644 /// \param Kind Kind of the directive.
2645 /// \param Callback Callback function to be called for the list elements.
2646 /// \param AllowScopeSpecifier true, if the variables can have fully
2647 /// qualified names.
2649 bool ParseOpenMPSimpleVarList(
2650 OpenMPDirectiveKind Kind,
2651 const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
2653 bool AllowScopeSpecifier);
2654 /// \brief Parses declarative or executable directive.
2656 /// \param Allowed ACK_Any, if any directives are allowed,
2657 /// ACK_StatementsOpenMPAnyExecutable - if any executable directives are
2658 /// allowed, ACK_StatementsOpenMPNonStandalone - if only non-standalone
2659 /// executable directives are allowed.
2662 ParseOpenMPDeclarativeOrExecutableDirective(AllowedConstructsKind Allowed);
2663 /// \brief Parses clause of kind \a CKind for directive of a kind \a Kind.
2665 /// \param DKind Kind of current directive.
2666 /// \param CKind Kind of current clause.
2667 /// \param FirstClause true, if this is the first clause of a kind \a CKind
2668 /// in current directive.
2670 OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
2671 OpenMPClauseKind CKind, bool FirstClause);
2672 /// \brief Parses clause with a single expression of a kind \a Kind.
2674 /// \param Kind Kind of current clause.
2676 OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind);
2677 /// \brief Parses simple clause of a kind \a Kind.
2679 /// \param Kind Kind of current clause.
2681 OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind);
2682 /// \brief Parses clause with a single expression and an additional argument
2683 /// of a kind \a Kind.
2685 /// \param Kind Kind of current clause.
2687 OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind);
2688 /// \brief Parses clause without any additional arguments.
2690 /// \param Kind Kind of current clause.
2692 OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind);
2693 /// \brief Parses clause with the list of variables of a kind \a Kind.
2695 /// \param Kind Kind of current clause.
2697 OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
2698 OpenMPClauseKind Kind);
2701 /// Parses simple expression in parens for single-expression clauses of OpenMP
2703 /// \param RLoc Returned location of right paren.
2704 ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc);
2706 /// Data used for parsing list of variables in OpenMP clauses.
2707 struct OpenMPVarListDataTy {
2708 Expr *TailExpr = nullptr;
2709 SourceLocation ColonLoc;
2710 CXXScopeSpec ReductionIdScopeSpec;
2711 DeclarationNameInfo ReductionId;
2712 OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown;
2713 OpenMPLinearClauseKind LinKind = OMPC_LINEAR_val;
2714 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
2715 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
2716 bool IsMapTypeImplicit = false;
2717 SourceLocation DepLinMapLoc;
2720 /// Parses clauses with list.
2721 bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind,
2722 SmallVectorImpl<Expr *> &Vars,
2723 OpenMPVarListDataTy &Data);
2724 bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2725 bool AllowDestructorName,
2726 bool AllowConstructorName,
2727 bool AllowDeductionGuide,
2728 ParsedType ObjectType,
2729 SourceLocation& TemplateKWLoc,
2730 UnqualifiedId &Result);
2733 //===--------------------------------------------------------------------===//
2734 // C++ 14: Templates [temp]
2736 // C++ 14.1: Template Parameters [temp.param]
2737 Decl *ParseDeclarationStartingWithTemplate(DeclaratorContext Context,
2738 SourceLocation &DeclEnd,
2739 AccessSpecifier AS = AS_none,
2740 AttributeList *AccessAttrs = nullptr);
2741 Decl *ParseTemplateDeclarationOrSpecialization(DeclaratorContext Context,
2742 SourceLocation &DeclEnd,
2744 AttributeList *AccessAttrs);
2745 Decl *ParseSingleDeclarationAfterTemplate(
2746 DeclaratorContext Context,
2747 const ParsedTemplateInfo &TemplateInfo,
2748 ParsingDeclRAIIObject &DiagsFromParams,
2749 SourceLocation &DeclEnd,
2750 AccessSpecifier AS=AS_none,
2751 AttributeList *AccessAttrs = nullptr);
2752 bool ParseTemplateParameters(unsigned Depth,
2753 SmallVectorImpl<NamedDecl *> &TemplateParams,
2754 SourceLocation &LAngleLoc,
2755 SourceLocation &RAngleLoc);
2756 bool ParseTemplateParameterList(unsigned Depth,
2757 SmallVectorImpl<NamedDecl*> &TemplateParams);
2758 bool isStartOfTemplateTypeParameter();
2759 NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position);
2760 NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position);
2761 NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
2762 NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
2763 void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
2764 SourceLocation CorrectLoc,
2765 bool AlreadyHasEllipsis,
2766 bool IdentifierHasName);
2767 void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
2769 // C++ 14.3: Template arguments [temp.arg]
2770 typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
2772 bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
2773 bool ConsumeLastToken,
2774 bool ObjCGenericList);
2775 bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
2776 SourceLocation &LAngleLoc,
2777 TemplateArgList &TemplateArgs,
2778 SourceLocation &RAngleLoc);
2780 bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
2782 SourceLocation TemplateKWLoc,
2783 UnqualifiedId &TemplateName,
2784 bool AllowTypeAnnotation = true);
2785 void AnnotateTemplateIdTokenAsType(bool IsClassName = false);
2786 bool IsTemplateArgumentList(unsigned Skip = 0);
2787 bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
2788 ParsedTemplateArgument ParseTemplateTemplateArgument();
2789 ParsedTemplateArgument ParseTemplateArgument();
2790 Decl *ParseExplicitInstantiation(DeclaratorContext Context,
2791 SourceLocation ExternLoc,
2792 SourceLocation TemplateLoc,
2793 SourceLocation &DeclEnd,
2794 AccessSpecifier AS = AS_none);
2796 //===--------------------------------------------------------------------===//
2798 DeclGroupPtrTy ParseModuleDecl();
2799 Decl *ParseModuleImport(SourceLocation AtLoc);
2800 bool parseMisplacedModuleImport();
2801 bool tryParseMisplacedModuleImport() {
2802 tok::TokenKind Kind = Tok.getKind();
2803 if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end ||
2804 Kind == tok::annot_module_include)
2805 return parseMisplacedModuleImport();
2809 bool ParseModuleName(
2810 SourceLocation UseLoc,
2811 SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
2814 //===--------------------------------------------------------------------===//
2815 // C++11/G++: Type Traits [Type-Traits.html in the GCC manual]
2816 ExprResult ParseTypeTrait();
2818 //===--------------------------------------------------------------------===//
2819 // Embarcadero: Arary and Expression Traits
2820 ExprResult ParseArrayTypeTrait();
2821 ExprResult ParseExpressionTrait();
2823 //===--------------------------------------------------------------------===//
2824 // Preprocessor code-completion pass-through
2825 void CodeCompleteDirective(bool InConditional) override;
2826 void CodeCompleteInConditionalExclusion() override;
2827 void CodeCompleteMacroName(bool IsDefinition) override;
2828 void CodeCompletePreprocessorExpression() override;
2829 void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo,
2830 unsigned ArgumentIndex) override;
2831 void CodeCompleteNaturalLanguage() override;
2834 } // end namespace clang