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, Declarator::TheContext 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 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) {
1877 case DSC_template_param:
1880 case DSC_objc_method_result:
1884 case DSC_template_type_arg:
1885 case DSC_type_specifier:
1887 case 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) {
1898 case DSC_template_param:
1902 case DSC_type_specifier:
1905 case DSC_objc_method_result:
1906 case DSC_template_type_arg:
1908 case 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(unsigned Context, SourceLocation &DeclEnd,
1924 ParsedAttributesWithRange &attrs);
1925 DeclGroupPtrTy ParseSimpleDeclaration(unsigned Context,
1926 SourceLocation &DeclEnd,
1927 ParsedAttributesWithRange &attrs,
1929 ForRangeInit *FRI = nullptr);
1930 bool MightBeDeclarator(unsigned Context);
1931 DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, unsigned Context,
1932 SourceLocation *DeclEnd = nullptr,
1933 ForRangeInit *FRI = nullptr);
1934 Decl *ParseDeclarationAfterDeclarator(Declarator &D,
1935 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
1936 bool ParseAsmAttributesAfterDeclarator(Declarator &D);
1937 Decl *ParseDeclarationAfterDeclaratorAndAttributes(
1939 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1940 ForRangeInit *FRI = nullptr);
1941 Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
1942 Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
1944 /// \brief When in code-completion, skip parsing of the function/method body
1945 /// unless the body contains the code-completion point.
1947 /// \returns true if the function body was skipped.
1948 bool trySkippingFunctionBody();
1950 bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
1951 const ParsedTemplateInfo &TemplateInfo,
1952 AccessSpecifier AS, DeclSpecContext DSC,
1953 ParsedAttributesWithRange &Attrs);
1954 DeclSpecContext getDeclSpecContextFromDeclaratorContext(unsigned Context);
1955 void ParseDeclarationSpecifiers(DeclSpec &DS,
1956 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1957 AccessSpecifier AS = AS_none,
1958 DeclSpecContext DSC = DSC_normal,
1959 LateParsedAttrList *LateAttrs = nullptr);
1960 bool DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
1961 DeclSpecContext DSContext,
1962 LateParsedAttrList *LateAttrs = nullptr);
1964 void ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS = AS_none,
1965 DeclSpecContext DSC = DSC_normal);
1967 void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
1968 Declarator::TheContext Context);
1970 void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
1971 const ParsedTemplateInfo &TemplateInfo,
1972 AccessSpecifier AS, DeclSpecContext DSC);
1973 void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
1974 void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType,
1977 void ParseStructDeclaration(
1978 ParsingDeclSpec &DS,
1979 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback);
1981 bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
1982 bool isTypeSpecifierQualifier();
1984 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
1985 /// is definitely a type-specifier. Return false if it isn't part of a type
1986 /// specifier or if we're not sure.
1987 bool isKnownToBeTypeSpecifier(const Token &Tok) const;
1989 /// \brief Return true if we know that we are definitely looking at a
1990 /// decl-specifier, and isn't part of an expression such as a function-style
1991 /// cast. Return false if it's no a decl-specifier, or we're not sure.
1992 bool isKnownToBeDeclarationSpecifier() {
1993 if (getLangOpts().CPlusPlus)
1994 return isCXXDeclarationSpecifier() == TPResult::True;
1995 return isDeclarationSpecifier(true);
1998 /// isDeclarationStatement - Disambiguates between a declaration or an
1999 /// expression statement, when parsing function bodies.
2000 /// Returns true for declaration, false for expression.
2001 bool isDeclarationStatement() {
2002 if (getLangOpts().CPlusPlus)
2003 return isCXXDeclarationStatement();
2004 return isDeclarationSpecifier(true);
2007 /// isForInitDeclaration - Disambiguates between a declaration or an
2008 /// expression in the context of the C 'clause-1' or the C++
2009 // 'for-init-statement' part of a 'for' statement.
2010 /// Returns true for declaration, false for expression.
2011 bool isForInitDeclaration() {
2012 if (getLangOpts().CPlusPlus)
2013 return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
2014 return isDeclarationSpecifier(true);
2017 /// \brief Determine whether this is a C++1z for-range-identifier.
2018 bool isForRangeIdentifier();
2020 /// \brief Determine whether we are currently at the start of an Objective-C
2021 /// class message that appears to be missing the open bracket '['.
2022 bool isStartOfObjCClassMessageMissingOpenBracket();
2024 /// \brief Starting with a scope specifier, identifier, or
2025 /// template-id that refers to the current class, determine whether
2026 /// this is a constructor declarator.
2027 bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false);
2029 /// \brief Specifies the context in which type-id/expression
2030 /// disambiguation will occur.
2031 enum TentativeCXXTypeIdContext {
2034 TypeIdAsTemplateArgument
2038 /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
2039 /// whether the parens contain an expression or a type-id.
2040 /// Returns true for a type-id and false for an expression.
2041 bool isTypeIdInParens(bool &isAmbiguous) {
2042 if (getLangOpts().CPlusPlus)
2043 return isCXXTypeId(TypeIdInParens, isAmbiguous);
2044 isAmbiguous = false;
2045 return isTypeSpecifierQualifier();
2047 bool isTypeIdInParens() {
2049 return isTypeIdInParens(isAmbiguous);
2052 /// \brief Checks if the current tokens form type-id or expression.
2053 /// It is similar to isTypeIdInParens but does not suppose that type-id
2054 /// is in parenthesis.
2055 bool isTypeIdUnambiguously() {
2057 if (getLangOpts().CPlusPlus)
2058 return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous);
2059 return isTypeSpecifierQualifier();
2062 /// isCXXDeclarationStatement - C++-specialized function that disambiguates
2063 /// between a declaration or an expression statement, when parsing function
2064 /// bodies. Returns true for declaration, false for expression.
2065 bool isCXXDeclarationStatement();
2067 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
2068 /// between a simple-declaration or an expression-statement.
2069 /// If during the disambiguation process a parsing error is encountered,
2070 /// the function returns true to let the declaration parsing code handle it.
2071 /// Returns false if the statement is disambiguated as expression.
2072 bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
2074 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
2075 /// a constructor-style initializer, when parsing declaration statements.
2076 /// Returns true for function declarator and false for constructor-style
2077 /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
2078 /// might be a constructor-style initializer.
2079 /// If during the disambiguation process a parsing error is encountered,
2080 /// the function returns true to let the declaration parsing code handle it.
2081 bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr);
2083 struct ConditionDeclarationOrInitStatementState;
2084 enum class ConditionOrInitStatement {
2085 Expression, ///< Disambiguated as an expression (either kind).
2086 ConditionDecl, ///< Disambiguated as the declaration form of condition.
2087 InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement.
2088 Error ///< Can't be any of the above!
2090 /// \brief Disambiguates between the different kinds of things that can happen
2091 /// after 'if (' or 'switch ('. This could be one of two different kinds of
2092 /// declaration (depending on whether there is a ';' later) or an expression.
2093 ConditionOrInitStatement
2094 isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt);
2096 bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
2097 bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
2099 return isCXXTypeId(Context, isAmbiguous);
2102 /// TPResult - Used as the result value for functions whose purpose is to
2103 /// disambiguate C++ constructs by "tentatively parsing" them.
2104 enum class TPResult {
2105 True, False, Ambiguous, Error
2108 /// \brief Based only on the given token kind, determine whether we know that
2109 /// we're at the start of an expression or a type-specifier-seq (which may
2110 /// be an expression, in C++).
2112 /// This routine does not attempt to resolve any of the trick cases, e.g.,
2113 /// those involving lookup of identifiers.
2115 /// \returns \c TPR_true if this token starts an expression, \c TPR_false if
2116 /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot
2118 TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind);
2120 /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a
2121 /// declaration specifier, TPResult::False if it is not,
2122 /// TPResult::Ambiguous if it could be either a decl-specifier or a
2123 /// function-style cast, and TPResult::Error if a parsing error was
2124 /// encountered. If it could be a braced C++11 function-style cast, returns
2125 /// BracedCastResult.
2126 /// Doesn't consume tokens.
2128 isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False,
2129 bool *HasMissingTypename = nullptr);
2131 /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
2132 /// \c TPResult::Ambiguous, determine whether the decl-specifier would be
2133 /// a type-specifier other than a cv-qualifier.
2134 bool isCXXDeclarationSpecifierAType();
2136 /// \brief Determine whether an identifier has been tentatively declared as a
2137 /// non-type. Such tentative declarations should not be found to name a type
2138 /// during a tentative parse, but also should not be annotated as a non-type.
2139 bool isTentativelyDeclared(IdentifierInfo *II);
2141 // "Tentative parsing" functions, used for disambiguation. If a parsing error
2142 // is encountered they will return TPResult::Error.
2143 // Returning TPResult::True/False indicates that the ambiguity was
2144 // resolved and tentative parsing may stop. TPResult::Ambiguous indicates
2145 // that more tentative parsing is necessary for disambiguation.
2146 // They all consume tokens, so backtracking should be used after calling them.
2148 TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
2149 TPResult TryParseTypeofSpecifier();
2150 TPResult TryParseProtocolQualifiers();
2151 TPResult TryParsePtrOperatorSeq();
2152 TPResult TryParseOperatorId();
2153 TPResult TryParseInitDeclaratorList();
2154 TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier=true);
2156 TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr,
2157 bool VersusTemplateArg = false);
2158 TPResult TryParseFunctionDeclarator();
2159 TPResult TryParseBracketDeclarator();
2160 TPResult TryConsumeDeclarationSpecifier();
2163 TypeResult ParseTypeName(SourceRange *Range = nullptr,
2164 Declarator::TheContext Context
2165 = Declarator::TypeNameContext,
2166 AccessSpecifier AS = AS_none,
2167 Decl **OwnedType = nullptr,
2168 ParsedAttributes *Attrs = nullptr);
2171 void ParseBlockId(SourceLocation CaretLoc);
2173 /// Are [[]] attributes enabled?
2174 bool standardAttributesAllowed() const {
2175 const LangOptions &LO = getLangOpts();
2176 return LO.DoubleSquareBracketAttributes;
2179 // Check for the start of an attribute-specifier-seq in a context where an
2180 // attribute is not allowed.
2181 bool CheckProhibitedCXX11Attribute() {
2182 assert(Tok.is(tok::l_square));
2183 if (!standardAttributesAllowed() || NextToken().isNot(tok::l_square))
2185 return DiagnoseProhibitedCXX11Attribute();
2188 bool DiagnoseProhibitedCXX11Attribute();
2189 void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2190 SourceLocation CorrectLocation) {
2191 if (!standardAttributesAllowed())
2193 if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
2194 Tok.isNot(tok::kw_alignas))
2196 DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
2198 void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2199 SourceLocation CorrectLocation);
2201 void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
2202 DeclSpec &DS, Sema::TagUseKind TUK);
2204 void ProhibitAttributes(ParsedAttributesWithRange &attrs) {
2205 if (!attrs.Range.isValid()) return;
2206 DiagnoseProhibitedAttributes(attrs);
2209 void DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs);
2211 // Forbid C++11 and C2x attributes that appear on certain syntactic locations
2212 // which standard permits but we don't supported yet, for example, attributes
2213 // appertain to decl specifiers.
2214 void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
2217 /// \brief Skip C++11 and C2x attributes and return the end location of the
2219 /// \returns SourceLocation() if there are no attributes.
2220 SourceLocation SkipCXX11Attributes();
2222 /// \brief Diagnose and skip C++11 and C2x attributes that appear in syntactic
2223 /// locations where attributes are not allowed.
2224 void DiagnoseAndSkipCXX11Attributes();
2226 /// \brief Parses syntax-generic attribute arguments for attributes which are
2227 /// known to the implementation, and adds them to the given ParsedAttributes
2228 /// list with the given attribute syntax. Returns the number of arguments
2229 /// parsed for the attribute.
2231 ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2232 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2233 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2234 AttributeList::Syntax Syntax);
2236 void MaybeParseGNUAttributes(Declarator &D,
2237 LateParsedAttrList *LateAttrs = nullptr) {
2238 if (Tok.is(tok::kw___attribute)) {
2239 ParsedAttributes attrs(AttrFactory);
2240 SourceLocation endLoc;
2241 ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D);
2242 D.takeAttributes(attrs, endLoc);
2245 void MaybeParseGNUAttributes(ParsedAttributes &attrs,
2246 SourceLocation *endLoc = nullptr,
2247 LateParsedAttrList *LateAttrs = nullptr) {
2248 if (Tok.is(tok::kw___attribute))
2249 ParseGNUAttributes(attrs, endLoc, LateAttrs);
2251 void ParseGNUAttributes(ParsedAttributes &attrs,
2252 SourceLocation *endLoc = nullptr,
2253 LateParsedAttrList *LateAttrs = nullptr,
2254 Declarator *D = nullptr);
2255 void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
2256 SourceLocation AttrNameLoc,
2257 ParsedAttributes &Attrs,
2258 SourceLocation *EndLoc,
2259 IdentifierInfo *ScopeName,
2260 SourceLocation ScopeLoc,
2261 AttributeList::Syntax Syntax,
2263 IdentifierLoc *ParseIdentifierLoc();
2266 ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2267 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2268 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2269 AttributeList::Syntax Syntax);
2271 void MaybeParseCXX11Attributes(Declarator &D) {
2272 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
2273 ParsedAttributesWithRange attrs(AttrFactory);
2274 SourceLocation endLoc;
2275 ParseCXX11Attributes(attrs, &endLoc);
2276 D.takeAttributes(attrs, endLoc);
2279 void MaybeParseCXX11Attributes(ParsedAttributes &attrs,
2280 SourceLocation *endLoc = nullptr) {
2281 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
2282 ParsedAttributesWithRange attrsWithRange(AttrFactory);
2283 ParseCXX11Attributes(attrsWithRange, endLoc);
2284 attrs.takeAllFrom(attrsWithRange);
2287 void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2288 SourceLocation *endLoc = nullptr,
2289 bool OuterMightBeMessageSend = false) {
2290 if (standardAttributesAllowed() &&
2291 isCXX11AttributeSpecifier(false, OuterMightBeMessageSend))
2292 ParseCXX11Attributes(attrs, endLoc);
2295 void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
2296 SourceLocation *EndLoc = nullptr);
2297 void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2298 SourceLocation *EndLoc = nullptr);
2299 /// \brief Parses a C++11 (or C2x)-style attribute argument list. Returns true
2300 /// if this results in adding an attribute to the ParsedAttributes list.
2301 bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
2302 SourceLocation AttrNameLoc,
2303 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2304 IdentifierInfo *ScopeName,
2305 SourceLocation ScopeLoc);
2307 IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc);
2309 void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
2310 SourceLocation *endLoc = nullptr) {
2311 if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
2312 ParseMicrosoftAttributes(attrs, endLoc);
2314 void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs);
2315 void ParseMicrosoftAttributes(ParsedAttributes &attrs,
2316 SourceLocation *endLoc = nullptr);
2317 void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2318 SourceLocation *End = nullptr) {
2319 const auto &LO = getLangOpts();
2320 if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec))
2321 ParseMicrosoftDeclSpecs(Attrs, End);
2323 void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2324 SourceLocation *End = nullptr);
2325 bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
2326 SourceLocation AttrNameLoc,
2327 ParsedAttributes &Attrs);
2328 void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
2329 void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2330 SourceLocation SkipExtendedMicrosoftTypeAttributes();
2331 void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
2332 void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
2333 void ParseOpenCLKernelAttributes(ParsedAttributes &attrs);
2334 void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
2335 /// \brief Parses opencl_unroll_hint attribute if language is OpenCL v2.0
2337 /// \return false if error happens.
2338 bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
2339 if (getLangOpts().OpenCL)
2340 return ParseOpenCLUnrollHintAttribute(Attrs);
2343 /// \brief Parses opencl_unroll_hint attribute.
2344 /// \return false if error happens.
2345 bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs);
2346 void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
2348 VersionTuple ParseVersionTuple(SourceRange &Range);
2349 void ParseAvailabilityAttribute(IdentifierInfo &Availability,
2350 SourceLocation AvailabilityLoc,
2351 ParsedAttributes &attrs,
2352 SourceLocation *endLoc,
2353 IdentifierInfo *ScopeName,
2354 SourceLocation ScopeLoc,
2355 AttributeList::Syntax Syntax);
2357 Optional<AvailabilitySpec> ParseAvailabilitySpec();
2358 ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc);
2360 void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol,
2362 ParsedAttributes &Attrs,
2363 SourceLocation *EndLoc,
2364 IdentifierInfo *ScopeName,
2365 SourceLocation ScopeLoc,
2366 AttributeList::Syntax Syntax);
2368 void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
2369 SourceLocation ObjCBridgeRelatedLoc,
2370 ParsedAttributes &attrs,
2371 SourceLocation *endLoc,
2372 IdentifierInfo *ScopeName,
2373 SourceLocation ScopeLoc,
2374 AttributeList::Syntax Syntax);
2376 void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
2377 SourceLocation AttrNameLoc,
2378 ParsedAttributes &Attrs,
2379 SourceLocation *EndLoc,
2380 IdentifierInfo *ScopeName,
2381 SourceLocation ScopeLoc,
2382 AttributeList::Syntax Syntax);
2384 void ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
2385 SourceLocation AttrNameLoc,
2386 ParsedAttributes &Attrs,
2387 SourceLocation *EndLoc,
2388 IdentifierInfo *ScopeName,
2389 SourceLocation ScopeLoc,
2390 AttributeList::Syntax Syntax);
2392 void ParseTypeofSpecifier(DeclSpec &DS);
2393 SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
2394 void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
2395 SourceLocation StartLoc,
2396 SourceLocation EndLoc);
2397 void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
2398 void ParseAtomicSpecifier(DeclSpec &DS);
2400 ExprResult ParseAlignArgument(SourceLocation Start,
2401 SourceLocation &EllipsisLoc);
2402 void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2403 SourceLocation *endLoc = nullptr);
2405 VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
2406 VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
2407 return isCXX11VirtSpecifier(Tok);
2409 void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface,
2410 SourceLocation FriendLoc);
2412 bool isCXX11FinalKeyword() const;
2414 /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
2415 /// enter a new C++ declarator scope and exit it when the function is
2417 class DeclaratorScopeObj {
2423 DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
2424 : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
2426 void EnterDeclaratorScope() {
2427 assert(!EnteredScope && "Already entered the scope!");
2428 assert(SS.isSet() && "C++ scope was not set!");
2430 CreatedScope = true;
2431 P.EnterScope(0); // Not a decl scope.
2433 if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
2434 EnteredScope = true;
2437 ~DeclaratorScopeObj() {
2439 assert(SS.isSet() && "C++ scope was cleared ?");
2440 P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
2447 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
2448 void ParseDeclarator(Declarator &D);
2449 /// A function that parses a variant of direct-declarator.
2450 typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
2451 void ParseDeclaratorInternal(Declarator &D,
2452 DirectDeclParseFunction DirectDeclParser);
2454 enum AttrRequirements {
2455 AR_NoAttributesParsed = 0, ///< No attributes are diagnosed.
2456 AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes.
2457 AR_GNUAttributesParsed = 1 << 1,
2458 AR_CXX11AttributesParsed = 1 << 2,
2459 AR_DeclspecAttributesParsed = 1 << 3,
2460 AR_AllAttributesParsed = AR_GNUAttributesParsed |
2461 AR_CXX11AttributesParsed |
2462 AR_DeclspecAttributesParsed,
2463 AR_VendorAttributesParsed = AR_GNUAttributesParsed |
2464 AR_DeclspecAttributesParsed
2467 void ParseTypeQualifierListOpt(
2468 DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed,
2469 bool AtomicAllowed = true, bool IdentifierRequired = false,
2470 Optional<llvm::function_ref<void()>> CodeCompletionHandler = None);
2471 void ParseDirectDeclarator(Declarator &D);
2472 void ParseDecompositionDeclarator(Declarator &D);
2473 void ParseParenDeclarator(Declarator &D);
2474 void ParseFunctionDeclarator(Declarator &D,
2475 ParsedAttributes &attrs,
2476 BalancedDelimiterTracker &Tracker,
2478 bool RequiresArg = false);
2479 bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
2480 SourceLocation &RefQualifierLoc);
2481 bool isFunctionDeclaratorIdentifierList();
2482 void ParseFunctionDeclaratorIdentifierList(
2484 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
2485 void ParseParameterDeclarationClause(
2487 ParsedAttributes &attrs,
2488 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
2489 SourceLocation &EllipsisLoc);
2490 void ParseBracketDeclarator(Declarator &D);
2491 void ParseMisplacedBracketDeclarator(Declarator &D);
2493 //===--------------------------------------------------------------------===//
2494 // C++ 7: Declarations [dcl.dcl]
2496 /// The kind of attribute specifier we have found.
2497 enum CXX11AttributeKind {
2498 /// This is not an attribute specifier.
2499 CAK_NotAttributeSpecifier,
2500 /// This should be treated as an attribute-specifier.
2501 CAK_AttributeSpecifier,
2502 /// The next tokens are '[[', but this is not an attribute-specifier. This
2503 /// is ill-formed by C++11 [dcl.attr.grammar]p6.
2504 CAK_InvalidAttributeSpecifier
2507 isCXX11AttributeSpecifier(bool Disambiguate = false,
2508 bool OuterMightBeMessageSend = false);
2510 void DiagnoseUnexpectedNamespace(NamedDecl *Context);
2512 DeclGroupPtrTy ParseNamespace(unsigned Context, SourceLocation &DeclEnd,
2513 SourceLocation InlineLoc = SourceLocation());
2514 void ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc,
2515 std::vector<IdentifierInfo*>& Ident,
2516 std::vector<SourceLocation>& NamespaceLoc,
2517 unsigned int index, SourceLocation& InlineLoc,
2518 ParsedAttributes& attrs,
2519 BalancedDelimiterTracker &Tracker);
2520 Decl *ParseLinkage(ParsingDeclSpec &DS, unsigned Context);
2521 Decl *ParseExportDeclaration();
2522 DeclGroupPtrTy ParseUsingDirectiveOrDeclaration(
2523 unsigned Context, const ParsedTemplateInfo &TemplateInfo,
2524 SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs);
2525 Decl *ParseUsingDirective(unsigned Context,
2526 SourceLocation UsingLoc,
2527 SourceLocation &DeclEnd,
2528 ParsedAttributes &attrs);
2530 struct UsingDeclarator {
2531 SourceLocation TypenameLoc;
2533 SourceLocation TemplateKWLoc;
2535 SourceLocation EllipsisLoc;
2538 TypenameLoc = TemplateKWLoc = EllipsisLoc = SourceLocation();
2544 bool ParseUsingDeclarator(unsigned Context, UsingDeclarator &D);
2545 DeclGroupPtrTy ParseUsingDeclaration(unsigned Context,
2546 const ParsedTemplateInfo &TemplateInfo,
2547 SourceLocation UsingLoc,
2548 SourceLocation &DeclEnd,
2549 AccessSpecifier AS = AS_none);
2550 Decl *ParseAliasDeclarationAfterDeclarator(
2551 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
2552 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
2553 ParsedAttributes &Attrs, Decl **OwnedType = nullptr);
2555 Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
2556 Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
2557 SourceLocation AliasLoc, IdentifierInfo *Alias,
2558 SourceLocation &DeclEnd);
2560 //===--------------------------------------------------------------------===//
2561 // C++ 9: classes [class] and C structs/unions.
2562 bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
2563 void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
2564 DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo,
2565 AccessSpecifier AS, bool EnteringContext,
2566 DeclSpecContext DSC,
2567 ParsedAttributesWithRange &Attributes);
2568 void SkipCXXMemberSpecification(SourceLocation StartLoc,
2569 SourceLocation AttrFixitLoc,
2572 void ParseCXXMemberSpecification(SourceLocation StartLoc,
2573 SourceLocation AttrFixitLoc,
2574 ParsedAttributesWithRange &Attrs,
2577 ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2578 SourceLocation &EqualLoc);
2579 bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
2581 ExprResult &BitfieldSize,
2582 LateParsedAttrList &LateAttrs);
2583 void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D,
2584 VirtSpecifiers &VS);
2585 DeclGroupPtrTy ParseCXXClassMemberDeclaration(
2586 AccessSpecifier AS, AttributeList *Attr,
2587 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2588 ParsingDeclRAIIObject *DiagsFromTParams = nullptr);
2589 DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas(
2590 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
2591 DeclSpec::TST TagType, Decl *Tag);
2592 void ParseConstructorInitializer(Decl *ConstructorDecl);
2593 MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
2594 void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2597 //===--------------------------------------------------------------------===//
2598 // C++ 10: Derived classes [class.derived]
2599 TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
2600 SourceLocation &EndLocation);
2601 void ParseBaseClause(Decl *ClassDecl);
2602 BaseResult ParseBaseSpecifier(Decl *ClassDecl);
2603 AccessSpecifier getAccessSpecifierIfPresent() const;
2605 bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
2606 SourceLocation TemplateKWLoc,
2607 IdentifierInfo *Name,
2608 SourceLocation NameLoc,
2609 bool EnteringContext,
2610 ParsedType ObjectType,
2612 bool AssumeTemplateId);
2613 bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2614 ParsedType ObjectType,
2615 UnqualifiedId &Result);
2617 //===--------------------------------------------------------------------===//
2618 // OpenMP: Directives and clauses.
2619 /// Parse clauses for '#pragma omp declare simd'.
2620 DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr,
2622 SourceLocation Loc);
2623 /// \brief Parses declarative OpenMP directives.
2624 DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl(
2625 AccessSpecifier &AS, ParsedAttributesWithRange &Attrs,
2626 DeclSpec::TST TagType = DeclSpec::TST_unspecified,
2627 Decl *TagDecl = nullptr);
2628 /// \brief Parse 'omp declare reduction' construct.
2629 DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS);
2630 /// Parses initializer for provided omp_priv declaration inside the reduction
2632 void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm);
2634 /// \brief Parses simple list of variables.
2636 /// \param Kind Kind of the directive.
2637 /// \param Callback Callback function to be called for the list elements.
2638 /// \param AllowScopeSpecifier true, if the variables can have fully
2639 /// qualified names.
2641 bool ParseOpenMPSimpleVarList(
2642 OpenMPDirectiveKind Kind,
2643 const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
2645 bool AllowScopeSpecifier);
2646 /// \brief Parses declarative or executable directive.
2648 /// \param Allowed ACK_Any, if any directives are allowed,
2649 /// ACK_StatementsOpenMPAnyExecutable - if any executable directives are
2650 /// allowed, ACK_StatementsOpenMPNonStandalone - if only non-standalone
2651 /// executable directives are allowed.
2654 ParseOpenMPDeclarativeOrExecutableDirective(AllowedConstructsKind Allowed);
2655 /// \brief Parses clause of kind \a CKind for directive of a kind \a Kind.
2657 /// \param DKind Kind of current directive.
2658 /// \param CKind Kind of current clause.
2659 /// \param FirstClause true, if this is the first clause of a kind \a CKind
2660 /// in current directive.
2662 OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
2663 OpenMPClauseKind CKind, bool FirstClause);
2664 /// \brief Parses clause with a single expression of a kind \a Kind.
2666 /// \param Kind Kind of current clause.
2668 OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind);
2669 /// \brief Parses simple clause of a kind \a Kind.
2671 /// \param Kind Kind of current clause.
2673 OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind);
2674 /// \brief Parses clause with a single expression and an additional argument
2675 /// of a kind \a Kind.
2677 /// \param Kind Kind of current clause.
2679 OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind);
2680 /// \brief Parses clause without any additional arguments.
2682 /// \param Kind Kind of current clause.
2684 OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind);
2685 /// \brief Parses clause with the list of variables of a kind \a Kind.
2687 /// \param Kind Kind of current clause.
2689 OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
2690 OpenMPClauseKind Kind);
2693 /// Parses simple expression in parens for single-expression clauses of OpenMP
2695 /// \param RLoc Returned location of right paren.
2696 ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc);
2698 /// Data used for parsing list of variables in OpenMP clauses.
2699 struct OpenMPVarListDataTy {
2700 Expr *TailExpr = nullptr;
2701 SourceLocation ColonLoc;
2702 CXXScopeSpec ReductionIdScopeSpec;
2703 DeclarationNameInfo ReductionId;
2704 OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown;
2705 OpenMPLinearClauseKind LinKind = OMPC_LINEAR_val;
2706 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
2707 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
2708 bool IsMapTypeImplicit = false;
2709 SourceLocation DepLinMapLoc;
2712 /// Parses clauses with list.
2713 bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind,
2714 SmallVectorImpl<Expr *> &Vars,
2715 OpenMPVarListDataTy &Data);
2716 bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2717 bool AllowDestructorName,
2718 bool AllowConstructorName,
2719 bool AllowDeductionGuide,
2720 ParsedType ObjectType,
2721 SourceLocation& TemplateKWLoc,
2722 UnqualifiedId &Result);
2725 //===--------------------------------------------------------------------===//
2726 // C++ 14: Templates [temp]
2728 // C++ 14.1: Template Parameters [temp.param]
2729 Decl *ParseDeclarationStartingWithTemplate(unsigned Context,
2730 SourceLocation &DeclEnd,
2731 AccessSpecifier AS = AS_none,
2732 AttributeList *AccessAttrs = nullptr);
2733 Decl *ParseTemplateDeclarationOrSpecialization(unsigned Context,
2734 SourceLocation &DeclEnd,
2736 AttributeList *AccessAttrs);
2737 Decl *ParseSingleDeclarationAfterTemplate(
2739 const ParsedTemplateInfo &TemplateInfo,
2740 ParsingDeclRAIIObject &DiagsFromParams,
2741 SourceLocation &DeclEnd,
2742 AccessSpecifier AS=AS_none,
2743 AttributeList *AccessAttrs = nullptr);
2744 bool ParseTemplateParameters(unsigned Depth,
2745 SmallVectorImpl<NamedDecl *> &TemplateParams,
2746 SourceLocation &LAngleLoc,
2747 SourceLocation &RAngleLoc);
2748 bool ParseTemplateParameterList(unsigned Depth,
2749 SmallVectorImpl<NamedDecl*> &TemplateParams);
2750 bool isStartOfTemplateTypeParameter();
2751 Decl *ParseTemplateParameter(unsigned Depth, unsigned Position);
2752 Decl *ParseTypeParameter(unsigned Depth, unsigned Position);
2753 Decl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
2754 Decl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
2755 void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
2756 SourceLocation CorrectLoc,
2757 bool AlreadyHasEllipsis,
2758 bool IdentifierHasName);
2759 void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
2761 // C++ 14.3: Template arguments [temp.arg]
2762 typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
2764 bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
2765 bool ConsumeLastToken,
2766 bool ObjCGenericList);
2767 bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
2768 SourceLocation &LAngleLoc,
2769 TemplateArgList &TemplateArgs,
2770 SourceLocation &RAngleLoc);
2772 bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
2774 SourceLocation TemplateKWLoc,
2775 UnqualifiedId &TemplateName,
2776 bool AllowTypeAnnotation = true);
2777 void AnnotateTemplateIdTokenAsType(bool IsClassName = false);
2778 bool IsTemplateArgumentList(unsigned Skip = 0);
2779 bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
2780 ParsedTemplateArgument ParseTemplateTemplateArgument();
2781 ParsedTemplateArgument ParseTemplateArgument();
2782 Decl *ParseExplicitInstantiation(unsigned Context,
2783 SourceLocation ExternLoc,
2784 SourceLocation TemplateLoc,
2785 SourceLocation &DeclEnd,
2786 AccessSpecifier AS = AS_none);
2788 //===--------------------------------------------------------------------===//
2790 DeclGroupPtrTy ParseModuleDecl();
2791 Decl *ParseModuleImport(SourceLocation AtLoc);
2792 bool parseMisplacedModuleImport();
2793 bool tryParseMisplacedModuleImport() {
2794 tok::TokenKind Kind = Tok.getKind();
2795 if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end ||
2796 Kind == tok::annot_module_include)
2797 return parseMisplacedModuleImport();
2801 bool ParseModuleName(
2802 SourceLocation UseLoc,
2803 SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
2806 //===--------------------------------------------------------------------===//
2807 // C++11/G++: Type Traits [Type-Traits.html in the GCC manual]
2808 ExprResult ParseTypeTrait();
2810 //===--------------------------------------------------------------------===//
2811 // Embarcadero: Arary and Expression Traits
2812 ExprResult ParseArrayTypeTrait();
2813 ExprResult ParseExpressionTrait();
2815 //===--------------------------------------------------------------------===//
2816 // Preprocessor code-completion pass-through
2817 void CodeCompleteDirective(bool InConditional) override;
2818 void CodeCompleteInConditionalExclusion() override;
2819 void CodeCompleteMacroName(bool IsDefinition) override;
2820 void CodeCompletePreprocessorExpression() override;
2821 void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo,
2822 unsigned ArgumentIndex) override;
2823 void CodeCompleteNaturalLanguage() override;
2826 } // end namespace clang