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 bool SkipFunctionBodies;
258 /// The location of the expression statement that is being parsed right now.
259 /// Used to determine if an expression that is being parsed is a statement or
260 /// just a regular sub-expression.
261 SourceLocation ExprStatementTokLoc;
264 Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
267 const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
268 const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
269 Preprocessor &getPreprocessor() const { return PP; }
270 Sema &getActions() const { return Actions; }
271 AttributeFactory &getAttrFactory() { return AttrFactory; }
273 const Token &getCurToken() const { return Tok; }
274 Scope *getCurScope() const { return Actions.getCurScope(); }
275 void incrementMSManglingNumber() const {
276 return Actions.incrementMSManglingNumber();
279 Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); }
281 // Type forwarding. All of these are statically 'void*', but they may all be
282 // different actual classes based on the actions in place.
283 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
284 typedef OpaquePtr<TemplateName> TemplateTy;
286 typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists;
288 typedef Sema::FullExprArg FullExprArg;
292 /// Initialize - Warm up the parser.
296 /// Parse the first top-level declaration in a translation unit.
297 bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result);
299 /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if
300 /// the EOF was encountered.
301 bool ParseTopLevelDecl(DeclGroupPtrTy &Result);
302 bool ParseTopLevelDecl() {
303 DeclGroupPtrTy Result;
304 return ParseTopLevelDecl(Result);
307 /// ConsumeToken - Consume the current 'peek token' and lex the next one.
308 /// This does not work with special tokens: string literals, code completion,
309 /// annotation tokens and balanced tokens must be handled using the specific
311 /// Returns the location of the consumed token.
312 SourceLocation ConsumeToken() {
313 assert(!isTokenSpecial() &&
314 "Should consume special tokens with Consume*Token");
315 PrevTokLocation = Tok.getLocation();
317 return PrevTokLocation;
320 bool TryConsumeToken(tok::TokenKind Expected) {
321 if (Tok.isNot(Expected))
323 assert(!isTokenSpecial() &&
324 "Should consume special tokens with Consume*Token");
325 PrevTokLocation = Tok.getLocation();
330 bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) {
331 if (!TryConsumeToken(Expected))
333 Loc = PrevTokLocation;
337 SourceLocation getEndOfPreviousToken() {
338 return PP.getLocForEndOfToken(PrevTokLocation);
341 /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds
342 /// to the given nullability kind.
343 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) {
344 return Actions.getNullabilityKeyword(nullability);
348 //===--------------------------------------------------------------------===//
349 // Low-Level token peeking and consumption methods.
352 /// isTokenParen - Return true if the cur token is '(' or ')'.
353 bool isTokenParen() const {
354 return Tok.getKind() == tok::l_paren || Tok.getKind() == tok::r_paren;
356 /// isTokenBracket - Return true if the cur token is '[' or ']'.
357 bool isTokenBracket() const {
358 return Tok.getKind() == tok::l_square || Tok.getKind() == tok::r_square;
360 /// isTokenBrace - Return true if the cur token is '{' or '}'.
361 bool isTokenBrace() const {
362 return Tok.getKind() == tok::l_brace || Tok.getKind() == tok::r_brace;
364 /// isTokenStringLiteral - True if this token is a string-literal.
365 bool isTokenStringLiteral() const {
366 return tok::isStringLiteral(Tok.getKind());
368 /// isTokenSpecial - True if this token requires special consumption methods.
369 bool isTokenSpecial() const {
370 return isTokenStringLiteral() || isTokenParen() || isTokenBracket() ||
371 isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation();
374 /// \brief Returns true if the current token is '=' or is a type of '='.
375 /// For typos, give a fixit to '='
376 bool isTokenEqualOrEqualTypo();
378 /// \brief Return the current token to the token stream and make the given
379 /// token the current token.
380 void UnconsumeToken(Token &Consumed) {
382 PP.EnterToken(Consumed);
387 /// ConsumeAnyToken - Dispatch to the right Consume* method based on the
388 /// current token type. This should only be used in cases where the type of
389 /// the token really isn't known, e.g. in error recovery.
390 SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) {
392 return ConsumeParen();
393 if (isTokenBracket())
394 return ConsumeBracket();
396 return ConsumeBrace();
397 if (isTokenStringLiteral())
398 return ConsumeStringToken();
399 if (Tok.is(tok::code_completion))
400 return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken()
401 : handleUnexpectedCodeCompletionToken();
402 if (Tok.isAnnotation())
403 return ConsumeAnnotationToken();
404 return ConsumeToken();
407 SourceLocation ConsumeAnnotationToken() {
408 assert(Tok.isAnnotation() && "wrong consume method");
409 SourceLocation Loc = Tok.getLocation();
410 PrevTokLocation = Tok.getAnnotationEndLoc();
415 /// ConsumeParen - This consume method keeps the paren count up-to-date.
417 SourceLocation ConsumeParen() {
418 assert(isTokenParen() && "wrong consume method");
419 if (Tok.getKind() == tok::l_paren)
422 --ParenCount; // Don't let unbalanced )'s drive the count negative.
423 PrevTokLocation = Tok.getLocation();
425 return PrevTokLocation;
428 /// ConsumeBracket - This consume method keeps the bracket count up-to-date.
430 SourceLocation ConsumeBracket() {
431 assert(isTokenBracket() && "wrong consume method");
432 if (Tok.getKind() == tok::l_square)
434 else if (BracketCount)
435 --BracketCount; // Don't let unbalanced ]'s drive the count negative.
437 PrevTokLocation = Tok.getLocation();
439 return PrevTokLocation;
442 /// ConsumeBrace - This consume method keeps the brace count up-to-date.
444 SourceLocation ConsumeBrace() {
445 assert(isTokenBrace() && "wrong consume method");
446 if (Tok.getKind() == tok::l_brace)
449 --BraceCount; // Don't let unbalanced }'s drive the count negative.
451 PrevTokLocation = Tok.getLocation();
453 return PrevTokLocation;
456 /// ConsumeStringToken - Consume the current 'peek token', lexing a new one
457 /// and returning the token kind. This method is specific to strings, as it
458 /// handles string literal concatenation, as per C99 5.1.1.2, translation
460 SourceLocation ConsumeStringToken() {
461 assert(isTokenStringLiteral() &&
462 "Should only consume string literals with this method");
463 PrevTokLocation = Tok.getLocation();
465 return PrevTokLocation;
468 /// \brief Consume the current code-completion token.
470 /// This routine can be called to consume the code-completion token and
471 /// continue processing in special cases where \c cutOffParsing() isn't
472 /// desired, such as token caching or completion with lookahead.
473 SourceLocation ConsumeCodeCompletionToken() {
474 assert(Tok.is(tok::code_completion));
475 PrevTokLocation = Tok.getLocation();
477 return PrevTokLocation;
480 ///\ brief When we are consuming a code-completion token without having
481 /// matched specific position in the grammar, provide code-completion results
482 /// based on context.
484 /// \returns the source location of the code-completion token.
485 SourceLocation handleUnexpectedCodeCompletionToken();
487 /// \brief Abruptly cut off parsing; mainly used when we have reached the
488 /// code-completion point.
489 void cutOffParsing() {
490 if (PP.isCodeCompletionEnabled())
491 PP.setCodeCompletionReached();
492 // Cut off parsing by acting as if we reached the end-of-file.
493 Tok.setKind(tok::eof);
496 /// \brief Determine if we're at the end of the file or at a transition
499 tok::TokenKind Kind = Tok.getKind();
500 return Kind == tok::eof || Kind == tok::annot_module_begin ||
501 Kind == tok::annot_module_end || Kind == tok::annot_module_include;
504 /// \brief Initialize all pragma handlers.
505 void initializePragmaHandlers();
507 /// \brief Destroy and reset all pragma handlers.
508 void resetPragmaHandlers();
510 /// \brief Handle the annotation token produced for #pragma unused(...)
511 void HandlePragmaUnused();
513 /// \brief Handle the annotation token produced for
514 /// #pragma GCC visibility...
515 void HandlePragmaVisibility();
517 /// \brief Handle the annotation token produced for
519 void HandlePragmaPack();
521 /// \brief Handle the annotation token produced for
522 /// #pragma ms_struct...
523 void HandlePragmaMSStruct();
525 /// \brief Handle the annotation token produced for
526 /// #pragma comment...
527 void HandlePragmaMSComment();
529 void HandlePragmaMSPointersToMembers();
531 void HandlePragmaMSVtorDisp();
533 void HandlePragmaMSPragma();
534 bool HandlePragmaMSSection(StringRef PragmaName,
535 SourceLocation PragmaLocation);
536 bool HandlePragmaMSSegment(StringRef PragmaName,
537 SourceLocation PragmaLocation);
538 bool HandlePragmaMSInitSeg(StringRef PragmaName,
539 SourceLocation PragmaLocation);
541 /// \brief Handle the annotation token produced for
543 void HandlePragmaAlign();
545 /// \brief Handle the annotation token produced for
546 /// #pragma clang __debug dump...
547 void HandlePragmaDump();
549 /// \brief Handle the annotation token produced for
550 /// #pragma weak id...
551 void HandlePragmaWeak();
553 /// \brief Handle the annotation token produced for
554 /// #pragma weak id = id...
555 void HandlePragmaWeakAlias();
557 /// \brief Handle the annotation token produced for
558 /// #pragma redefine_extname...
559 void HandlePragmaRedefineExtname();
561 /// \brief Handle the annotation token produced for
562 /// #pragma STDC FP_CONTRACT...
563 void HandlePragmaFPContract();
565 /// \brief Handle the annotation token produced for
566 /// #pragma clang fp ...
567 void HandlePragmaFP();
569 /// \brief Handle the annotation token produced for
570 /// #pragma OPENCL EXTENSION...
571 void HandlePragmaOpenCLExtension();
573 /// \brief Handle the annotation token produced for
574 /// #pragma clang __debug captured
575 StmtResult HandlePragmaCaptured();
577 /// \brief Handle the annotation token produced for
578 /// #pragma clang loop and #pragma unroll.
579 bool HandlePragmaLoopHint(LoopHint &Hint);
581 bool ParsePragmaAttributeSubjectMatchRuleSet(
582 attr::ParsedSubjectMatchRuleSet &SubjectMatchRules,
583 SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc);
585 void HandlePragmaAttribute();
587 /// GetLookAheadToken - This peeks ahead N tokens and returns that token
588 /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1)
589 /// returns the token after Tok, etc.
591 /// Note that this differs from the Preprocessor's LookAhead method, because
592 /// the Parser always has one token lexed that the preprocessor doesn't.
594 const Token &GetLookAheadToken(unsigned N) {
595 if (N == 0 || Tok.is(tok::eof)) return Tok;
596 return PP.LookAhead(N-1);
600 /// NextToken - This peeks ahead one token and returns it without
602 const Token &NextToken() {
603 return PP.LookAhead(0);
606 /// getTypeAnnotation - Read a parsed type out of an annotation token.
607 static ParsedType getTypeAnnotation(const Token &Tok) {
608 return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
612 static void setTypeAnnotation(Token &Tok, ParsedType T) {
613 Tok.setAnnotationValue(T.getAsOpaquePtr());
616 /// \brief Read an already-translated primary expression out of an annotation
618 static ExprResult getExprAnnotation(const Token &Tok) {
619 return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue());
622 /// \brief Set the primary expression corresponding to the given annotation
624 static void setExprAnnotation(Token &Tok, ExprResult ER) {
625 Tok.setAnnotationValue(ER.getAsOpaquePointer());
629 // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to
630 // find a type name by attempting typo correction.
631 bool TryAnnotateTypeOrScopeToken();
632 bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS,
634 bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
637 enum AnnotatedNameKind {
638 /// Annotation has failed and emitted an error.
640 /// The identifier is a tentatively-declared name.
642 /// The identifier is a template name. FIXME: Add an annotation for that.
644 /// The identifier can't be resolved.
646 /// Annotation was successful.
650 TryAnnotateName(bool IsAddressOfOperand,
651 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
653 /// Push a tok::annot_cxxscope token onto the token stream.
654 void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
656 /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
657 /// replacing them with the non-context-sensitive keywords. This returns
658 /// true if the token was replaced.
659 bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
660 const char *&PrevSpec, unsigned &DiagID,
662 if (!getLangOpts().AltiVec && !getLangOpts().ZVector)
665 if (Tok.getIdentifierInfo() != Ident_vector &&
666 Tok.getIdentifierInfo() != Ident_bool &&
667 (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel))
670 return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
673 /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
674 /// identifier token, replacing it with the non-context-sensitive __vector.
675 /// This returns true if the token was replaced.
676 bool TryAltiVecVectorToken() {
677 if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) ||
678 Tok.getIdentifierInfo() != Ident_vector) return false;
679 return TryAltiVecVectorTokenOutOfLine();
682 bool TryAltiVecVectorTokenOutOfLine();
683 bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
684 const char *&PrevSpec, unsigned &DiagID,
687 /// Returns true if the current token is the identifier 'instancetype'.
689 /// Should only be used in Objective-C language modes.
690 bool isObjCInstancetype() {
691 assert(getLangOpts().ObjC1);
692 if (Tok.isAnnotation())
694 if (!Ident_instancetype)
695 Ident_instancetype = PP.getIdentifierInfo("instancetype");
696 return Tok.getIdentifierInfo() == Ident_instancetype;
699 /// TryKeywordIdentFallback - For compatibility with system headers using
700 /// keywords as identifiers, attempt to convert the current token to an
701 /// identifier and optionally disable the keyword for the remainder of the
702 /// translation unit. This returns false if the token was not replaced,
703 /// otherwise emits a diagnostic and returns true.
704 bool TryKeywordIdentFallback(bool DisableKeyword);
706 /// \brief Get the TemplateIdAnnotation from the token.
707 TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
709 /// TentativeParsingAction - An object that is used as a kind of "tentative
710 /// parsing transaction". It gets instantiated to mark the token position and
711 /// after the token consumption is done, Commit() or Revert() is called to
712 /// either "commit the consumed tokens" or revert to the previously marked
713 /// token position. Example:
715 /// TentativeParsingAction TPA(*this);
720 class TentativeParsingAction {
723 size_t PrevTentativelyDeclaredIdentifierCount;
724 unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
728 explicit TentativeParsingAction(Parser& p) : P(p) {
730 PrevTentativelyDeclaredIdentifierCount =
731 P.TentativelyDeclaredIdentifiers.size();
732 PrevParenCount = P.ParenCount;
733 PrevBracketCount = P.BracketCount;
734 PrevBraceCount = P.BraceCount;
735 P.PP.EnableBacktrackAtThisPos();
739 assert(isActive && "Parsing action was finished!");
740 P.TentativelyDeclaredIdentifiers.resize(
741 PrevTentativelyDeclaredIdentifierCount);
742 P.PP.CommitBacktrackedTokens();
746 assert(isActive && "Parsing action was finished!");
749 P.TentativelyDeclaredIdentifiers.resize(
750 PrevTentativelyDeclaredIdentifierCount);
751 P.ParenCount = PrevParenCount;
752 P.BracketCount = PrevBracketCount;
753 P.BraceCount = PrevBraceCount;
756 ~TentativeParsingAction() {
757 assert(!isActive && "Forgot to call Commit or Revert!");
760 /// A TentativeParsingAction that automatically reverts in its destructor.
761 /// Useful for disambiguation parses that will always be reverted.
762 class RevertingTentativeParsingAction
763 : private Parser::TentativeParsingAction {
765 RevertingTentativeParsingAction(Parser &P)
766 : Parser::TentativeParsingAction(P) {}
767 ~RevertingTentativeParsingAction() { Revert(); }
770 class UnannotatedTentativeParsingAction;
772 /// ObjCDeclContextSwitch - An object used to switch context from
773 /// an objective-c decl context to its enclosing decl context and
775 class ObjCDeclContextSwitch {
778 SaveAndRestore<bool> WithinObjCContainer;
780 explicit ObjCDeclContextSwitch(Parser &p)
781 : P(p), DC(p.getObjCDeclContext()),
782 WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) {
784 P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC));
786 ~ObjCDeclContextSwitch() {
788 P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC));
792 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
793 /// input. If so, it is consumed and false is returned.
795 /// If a trivial punctuator misspelling is encountered, a FixIt error
796 /// diagnostic is issued and false is returned after recovery.
798 /// If the input is malformed, this emits the specified diagnostic and true is
800 bool ExpectAndConsume(tok::TokenKind ExpectedTok,
801 unsigned Diag = diag::err_expected,
802 StringRef DiagMsg = "");
804 /// \brief The parser expects a semicolon and, if present, will consume it.
806 /// If the next token is not a semicolon, this emits the specified diagnostic,
807 /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
808 /// to the semicolon, consumes that extra token.
809 bool ExpectAndConsumeSemi(unsigned DiagID);
811 /// \brief The kind of extra semi diagnostic to emit.
815 InstanceVariableList = 2,
816 AfterMemberFunctionDefinition = 3
819 /// \brief Consume any extra semi-colons until the end of the line.
820 void ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST = TST_unspecified);
822 /// Return false if the next token is an identifier. An 'expected identifier'
823 /// error is emitted otherwise.
825 /// The parser tries to recover from the error by checking if the next token
826 /// is a C++ keyword when parsing Objective-C++. Return false if the recovery
828 bool expectIdentifier();
831 //===--------------------------------------------------------------------===//
832 // Scope manipulation
834 /// ParseScope - Introduces a new scope for parsing. The kind of
835 /// scope is determined by ScopeFlags. Objects of this type should
836 /// be created on the stack to coincide with the position where the
837 /// parser enters the new scope, and this object's constructor will
838 /// create that new scope. Similarly, once the object is destroyed
839 /// the parser will exit the scope.
842 ParseScope(const ParseScope &) = delete;
843 void operator=(const ParseScope &) = delete;
846 // ParseScope - Construct a new object to manage a scope in the
847 // parser Self where the new Scope is created with the flags
848 // ScopeFlags, but only when we aren't about to enter a compound statement.
849 ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true,
850 bool BeforeCompoundStmt = false)
852 if (EnteredScope && !BeforeCompoundStmt)
853 Self->EnterScope(ScopeFlags);
855 if (BeforeCompoundStmt)
856 Self->incrementMSManglingNumber();
858 this->Self = nullptr;
862 // Exit - Exit the scope associated with this object now, rather
863 // than waiting until the object is destroyed.
876 /// EnterScope - Start a new scope.
877 void EnterScope(unsigned ScopeFlags);
879 /// ExitScope - Pop a scope off the scope stack.
883 /// \brief RAII object used to modify the scope flags for the current scope.
884 class ParseScopeFlags {
887 ParseScopeFlags(const ParseScopeFlags &) = delete;
888 void operator=(const ParseScopeFlags &) = delete;
891 ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
895 //===--------------------------------------------------------------------===//
896 // Diagnostic Emission and Error recovery.
899 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
900 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
901 DiagnosticBuilder Diag(unsigned DiagID) {
902 return Diag(Tok, DiagID);
906 void SuggestParentheses(SourceLocation Loc, unsigned DK,
907 SourceRange ParenRange);
908 void CheckNestedObjCContexts(SourceLocation AtLoc);
912 /// \brief Control flags for SkipUntil functions.
913 enum SkipUntilFlags {
914 StopAtSemi = 1 << 0, ///< Stop skipping at semicolon
915 /// \brief Stop skipping at specified token, but don't skip the token itself
916 StopBeforeMatch = 1 << 1,
917 StopAtCodeCompletion = 1 << 2 ///< Stop at code completion
920 friend constexpr SkipUntilFlags operator|(SkipUntilFlags L,
922 return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) |
923 static_cast<unsigned>(R));
926 /// SkipUntil - Read tokens until we get to the specified token, then consume
927 /// it (unless StopBeforeMatch is specified). Because we cannot guarantee
928 /// that the token will ever occur, this skips to the next token, or to some
929 /// likely good stopping point. If Flags has StopAtSemi flag, skipping will
930 /// stop at a ';' character.
932 /// If SkipUntil finds the specified token, it returns true, otherwise it
934 bool SkipUntil(tok::TokenKind T,
935 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
936 return SkipUntil(llvm::makeArrayRef(T), Flags);
938 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2,
939 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
940 tok::TokenKind TokArray[] = {T1, T2};
941 return SkipUntil(TokArray, Flags);
943 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3,
944 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
945 tok::TokenKind TokArray[] = {T1, T2, T3};
946 return SkipUntil(TokArray, Flags);
948 bool SkipUntil(ArrayRef<tok::TokenKind> Toks,
949 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0));
951 /// SkipMalformedDecl - Read tokens until we get to some likely good stopping
952 /// point for skipping past a simple-declaration.
953 void SkipMalformedDecl();
956 //===--------------------------------------------------------------------===//
957 // Lexing and parsing of C++ inline methods.
961 /// [class.mem]p1: "... the class is regarded as complete within
962 /// - function bodies
963 /// - default arguments
964 /// - exception-specifications (TODO: C++0x)
965 /// - and brace-or-equal-initializers for non-static data members
966 /// (including such things in nested classes)."
967 /// LateParsedDeclarations build the tree of those elements so they can
968 /// be parsed after parsing the top-level class.
969 class LateParsedDeclaration {
971 virtual ~LateParsedDeclaration();
973 virtual void ParseLexedMethodDeclarations();
974 virtual void ParseLexedMemberInitializers();
975 virtual void ParseLexedMethodDefs();
976 virtual void ParseLexedAttributes();
979 /// Inner node of the LateParsedDeclaration tree that parses
980 /// all its members recursively.
981 class LateParsedClass : public LateParsedDeclaration {
983 LateParsedClass(Parser *P, ParsingClass *C);
984 ~LateParsedClass() override;
986 void ParseLexedMethodDeclarations() override;
987 void ParseLexedMemberInitializers() override;
988 void ParseLexedMethodDefs() override;
989 void ParseLexedAttributes() override;
996 /// Contains the lexed tokens of an attribute with arguments that
997 /// may reference member variables and so need to be parsed at the
998 /// end of the class declaration after parsing all other member
999 /// member declarations.
1000 /// FIXME: Perhaps we should change the name of LateParsedDeclaration to
1001 /// LateParsedTokens.
1002 struct LateParsedAttribute : public LateParsedDeclaration {
1005 IdentifierInfo &AttrName;
1006 SourceLocation AttrNameLoc;
1007 SmallVector<Decl*, 2> Decls;
1009 explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
1011 : Self(P), AttrName(Name), AttrNameLoc(Loc) {}
1013 void ParseLexedAttributes() override;
1015 void addDecl(Decl *D) { Decls.push_back(D); }
1018 // A list of late-parsed attributes. Used by ParseGNUAttributes.
1019 class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> {
1021 LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { }
1023 bool parseSoon() { return ParseSoon; }
1026 bool ParseSoon; // Are we planning to parse these shortly after creation?
1029 /// Contains the lexed tokens of a member function definition
1030 /// which needs to be parsed at the end of the class declaration
1031 /// after parsing all other member declarations.
1032 struct LexedMethod : public LateParsedDeclaration {
1037 /// \brief Whether this member function had an associated template
1038 /// scope. When true, D is a template declaration.
1039 /// otherwise, it is a member function declaration.
1042 explicit LexedMethod(Parser* P, Decl *MD)
1043 : Self(P), D(MD), TemplateScope(false) {}
1045 void ParseLexedMethodDefs() override;
1048 /// LateParsedDefaultArgument - Keeps track of a parameter that may
1049 /// have a default argument that cannot be parsed yet because it
1050 /// occurs within a member function declaration inside the class
1051 /// (C++ [class.mem]p2).
1052 struct LateParsedDefaultArgument {
1053 explicit LateParsedDefaultArgument(Decl *P,
1054 std::unique_ptr<CachedTokens> Toks = nullptr)
1055 : Param(P), Toks(std::move(Toks)) { }
1057 /// Param - The parameter declaration for this parameter.
1060 /// Toks - The sequence of tokens that comprises the default
1061 /// argument expression, not including the '=' or the terminating
1062 /// ')' or ','. This will be NULL for parameters that have no
1063 /// default argument.
1064 std::unique_ptr<CachedTokens> Toks;
1067 /// LateParsedMethodDeclaration - A method declaration inside a class that
1068 /// contains at least one entity whose parsing needs to be delayed
1069 /// until the class itself is completely-defined, such as a default
1070 /// argument (C++ [class.mem]p2).
1071 struct LateParsedMethodDeclaration : public LateParsedDeclaration {
1072 explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
1073 : Self(P), Method(M), TemplateScope(false),
1074 ExceptionSpecTokens(nullptr) {}
1076 void ParseLexedMethodDeclarations() override;
1080 /// Method - The method declaration.
1083 /// \brief Whether this member function had an associated template
1084 /// scope. When true, D is a template declaration.
1085 /// othewise, it is a member function declaration.
1088 /// DefaultArgs - Contains the parameters of the function and
1089 /// their default arguments. At least one of the parameters will
1090 /// have a default argument, but all of the parameters of the
1091 /// method will be stored so that they can be reintroduced into
1092 /// scope at the appropriate times.
1093 SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
1095 /// \brief The set of tokens that make up an exception-specification that
1096 /// has not yet been parsed.
1097 CachedTokens *ExceptionSpecTokens;
1100 /// LateParsedMemberInitializer - An initializer for a non-static class data
1101 /// member whose parsing must to be delayed until the class is completely
1102 /// defined (C++11 [class.mem]p2).
1103 struct LateParsedMemberInitializer : public LateParsedDeclaration {
1104 LateParsedMemberInitializer(Parser *P, Decl *FD)
1105 : Self(P), Field(FD) { }
1107 void ParseLexedMemberInitializers() override;
1111 /// Field - The field declaration.
1114 /// CachedTokens - The sequence of tokens that comprises the initializer,
1115 /// including any leading '='.
1119 /// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
1120 /// C++ class, its method declarations that contain parts that won't be
1121 /// parsed until after the definition is completed (C++ [class.mem]p2),
1122 /// the method declarations and possibly attached inline definitions
1123 /// will be stored here with the tokens that will be parsed to create those
1125 typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer;
1127 /// \brief Representation of a class that has been parsed, including
1128 /// any member function declarations or definitions that need to be
1129 /// parsed after the corresponding top-level class is complete.
1130 struct ParsingClass {
1131 ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface)
1132 : TopLevelClass(TopLevelClass), TemplateScope(false),
1133 IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) { }
1135 /// \brief Whether this is a "top-level" class, meaning that it is
1136 /// not nested within another class.
1137 bool TopLevelClass : 1;
1139 /// \brief Whether this class had an associated template
1140 /// scope. When true, TagOrTemplate is a template declaration;
1141 /// othewise, it is a tag declaration.
1142 bool TemplateScope : 1;
1144 /// \brief Whether this class is an __interface.
1145 bool IsInterface : 1;
1147 /// \brief The class or class template whose definition we are parsing.
1148 Decl *TagOrTemplate;
1150 /// LateParsedDeclarations - Method declarations, inline definitions and
1151 /// nested classes that contain pieces whose parsing will be delayed until
1152 /// the top-level class is fully defined.
1153 LateParsedDeclarationsContainer LateParsedDeclarations;
1156 /// \brief The stack of classes that is currently being
1157 /// parsed. Nested and local classes will be pushed onto this stack
1158 /// when they are parsed, and removed afterward.
1159 std::stack<ParsingClass *> ClassStack;
1161 ParsingClass &getCurrentClass() {
1162 assert(!ClassStack.empty() && "No lexed method stacks!");
1163 return *ClassStack.top();
1166 /// \brief RAII object used to manage the parsing of a class definition.
1167 class ParsingClassDefinition {
1170 Sema::ParsingClassState State;
1173 ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass,
1175 : P(P), Popped(false),
1176 State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
1179 /// \brief Pop this class of the stack.
1181 assert(!Popped && "Nested class has already been popped");
1183 P.PopParsingClass(State);
1186 ~ParsingClassDefinition() {
1188 P.PopParsingClass(State);
1192 /// \brief Contains information about any template-specific
1193 /// information that has been parsed prior to parsing declaration
1195 struct ParsedTemplateInfo {
1196 ParsedTemplateInfo()
1197 : Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { }
1199 ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
1200 bool isSpecialization,
1201 bool lastParameterListWasEmpty = false)
1202 : Kind(isSpecialization? ExplicitSpecialization : Template),
1203 TemplateParams(TemplateParams),
1204 LastParameterListWasEmpty(lastParameterListWasEmpty) { }
1206 explicit ParsedTemplateInfo(SourceLocation ExternLoc,
1207 SourceLocation TemplateLoc)
1208 : Kind(ExplicitInstantiation), TemplateParams(nullptr),
1209 ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
1210 LastParameterListWasEmpty(false){ }
1212 /// \brief The kind of template we are parsing.
1214 /// \brief We are not parsing a template at all.
1216 /// \brief We are parsing a template declaration.
1218 /// \brief We are parsing an explicit specialization.
1219 ExplicitSpecialization,
1220 /// \brief We are parsing an explicit instantiation.
1221 ExplicitInstantiation
1224 /// \brief The template parameter lists, for template declarations
1225 /// and explicit specializations.
1226 TemplateParameterLists *TemplateParams;
1228 /// \brief The location of the 'extern' keyword, if any, for an explicit
1230 SourceLocation ExternLoc;
1232 /// \brief The location of the 'template' keyword, for an explicit
1234 SourceLocation TemplateLoc;
1236 /// \brief Whether the last template parameter list was empty.
1237 bool LastParameterListWasEmpty;
1239 SourceRange getSourceRange() const LLVM_READONLY;
1242 void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
1243 void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
1245 static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
1246 static void LateTemplateParserCleanupCallback(void *P);
1248 Sema::ParsingClassState
1249 PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface);
1250 void DeallocateParsedClasses(ParsingClass *Class);
1251 void PopParsingClass(Sema::ParsingClassState);
1253 enum CachedInitKind {
1254 CIK_DefaultArgument,
1255 CIK_DefaultInitializer
1258 NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS,
1259 AttributeList *AccessAttrs,
1260 ParsingDeclarator &D,
1261 const ParsedTemplateInfo &TemplateInfo,
1262 const VirtSpecifiers& VS,
1263 SourceLocation PureSpecLoc);
1264 void ParseCXXNonStaticMemberInitializer(Decl *VarD);
1265 void ParseLexedAttributes(ParsingClass &Class);
1266 void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1267 bool EnterScope, bool OnDefinition);
1268 void ParseLexedAttribute(LateParsedAttribute &LA,
1269 bool EnterScope, bool OnDefinition);
1270 void ParseLexedMethodDeclarations(ParsingClass &Class);
1271 void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
1272 void ParseLexedMethodDefs(ParsingClass &Class);
1273 void ParseLexedMethodDef(LexedMethod &LM);
1274 void ParseLexedMemberInitializers(ParsingClass &Class);
1275 void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
1276 void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod);
1277 bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
1278 bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK);
1279 bool ConsumeAndStoreConditional(CachedTokens &Toks);
1280 bool ConsumeAndStoreUntil(tok::TokenKind T1,
1282 bool StopAtSemi = true,
1283 bool ConsumeFinalToken = true) {
1284 return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
1286 bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
1288 bool StopAtSemi = true,
1289 bool ConsumeFinalToken = true);
1291 //===--------------------------------------------------------------------===//
1292 // C99 6.9: External Definitions.
1293 struct ParsedAttributesWithRange : ParsedAttributes {
1294 ParsedAttributesWithRange(AttributeFactory &factory)
1295 : ParsedAttributes(factory) {}
1298 ParsedAttributes::clear();
1299 Range = SourceRange();
1305 DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
1306 ParsingDeclSpec *DS = nullptr);
1307 bool isDeclarationAfterDeclarator();
1308 bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
1309 DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(
1310 ParsedAttributesWithRange &attrs,
1311 ParsingDeclSpec *DS = nullptr,
1312 AccessSpecifier AS = AS_none);
1313 DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
1314 ParsingDeclSpec &DS,
1315 AccessSpecifier AS);
1317 void SkipFunctionBody();
1318 Decl *ParseFunctionDefinition(ParsingDeclarator &D,
1319 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1320 LateParsedAttrList *LateParsedAttrs = nullptr);
1321 void ParseKNRParamDeclarations(Declarator &D);
1322 // EndLoc, if non-NULL, is filled with the location of the last token of
1324 ExprResult ParseSimpleAsm(SourceLocation *EndLoc = nullptr);
1325 ExprResult ParseAsmStringLiteral();
1327 // Objective-C External Declarations
1328 void MaybeSkipAttributes(tok::ObjCKeywordKind Kind);
1329 DeclGroupPtrTy ParseObjCAtDirectives();
1330 DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
1331 Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
1332 ParsedAttributes &prefixAttrs);
1333 class ObjCTypeParamListScope;
1334 ObjCTypeParamList *parseObjCTypeParamList();
1335 ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs(
1336 ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
1337 SmallVectorImpl<IdentifierLocPair> &protocolIdents,
1338 SourceLocation &rAngleLoc, bool mayBeProtocolList = true);
1340 void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
1341 BalancedDelimiterTracker &T,
1342 SmallVectorImpl<Decl *> &AllIvarDecls,
1343 bool RBraceMissing);
1344 void ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1345 tok::ObjCKeywordKind visibility,
1346 SourceLocation atLoc);
1347 bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P,
1348 SmallVectorImpl<SourceLocation> &PLocs,
1349 bool WarnOnDeclarations,
1350 bool ForObjCContainer,
1351 SourceLocation &LAngleLoc,
1352 SourceLocation &EndProtoLoc,
1353 bool consumeLastToken);
1355 /// Parse the first angle-bracket-delimited clause for an
1356 /// Objective-C object or object pointer type, which may be either
1357 /// type arguments or protocol qualifiers.
1358 void parseObjCTypeArgsOrProtocolQualifiers(
1359 ParsedType baseType,
1360 SourceLocation &typeArgsLAngleLoc,
1361 SmallVectorImpl<ParsedType> &typeArgs,
1362 SourceLocation &typeArgsRAngleLoc,
1363 SourceLocation &protocolLAngleLoc,
1364 SmallVectorImpl<Decl *> &protocols,
1365 SmallVectorImpl<SourceLocation> &protocolLocs,
1366 SourceLocation &protocolRAngleLoc,
1367 bool consumeLastToken,
1368 bool warnOnIncompleteProtocols);
1370 /// Parse either Objective-C type arguments or protocol qualifiers; if the
1371 /// former, also parse protocol qualifiers afterward.
1372 void parseObjCTypeArgsAndProtocolQualifiers(
1373 ParsedType baseType,
1374 SourceLocation &typeArgsLAngleLoc,
1375 SmallVectorImpl<ParsedType> &typeArgs,
1376 SourceLocation &typeArgsRAngleLoc,
1377 SourceLocation &protocolLAngleLoc,
1378 SmallVectorImpl<Decl *> &protocols,
1379 SmallVectorImpl<SourceLocation> &protocolLocs,
1380 SourceLocation &protocolRAngleLoc,
1381 bool consumeLastToken);
1383 /// Parse a protocol qualifier type such as '<NSCopying>', which is
1384 /// an anachronistic way of writing 'id<NSCopying>'.
1385 TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc);
1387 /// Parse Objective-C type arguments and protocol qualifiers, extending the
1388 /// current type with the parsed result.
1389 TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc,
1391 bool consumeLastToken,
1392 SourceLocation &endLoc);
1394 void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
1396 DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
1397 ParsedAttributes &prefixAttrs);
1399 struct ObjCImplParsingDataRAII {
1403 typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer;
1404 LateParsedObjCMethodContainer LateParsedObjCMethods;
1406 ObjCImplParsingDataRAII(Parser &parser, Decl *D)
1407 : P(parser), Dcl(D), HasCFunction(false) {
1408 P.CurParsedObjCImpl = this;
1411 ~ObjCImplParsingDataRAII();
1413 void finish(SourceRange AtEnd);
1414 bool isFinished() const { return Finished; }
1419 ObjCImplParsingDataRAII *CurParsedObjCImpl;
1420 void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl);
1422 DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc);
1423 DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
1424 Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
1425 Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
1426 Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
1428 IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
1429 // Definitions for Objective-c context sensitive keywords recognition.
1431 objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
1432 objc_nonnull, objc_nullable, objc_null_unspecified,
1435 IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
1437 bool isTokIdentifier_in() const;
1439 ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, Declarator::TheContext Ctx,
1440 ParsedAttributes *ParamAttrs);
1441 void ParseObjCMethodRequirement();
1442 Decl *ParseObjCMethodPrototype(
1443 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1444 bool MethodDefinition = true);
1445 Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
1446 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1447 bool MethodDefinition=true);
1448 void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
1450 Decl *ParseObjCMethodDefinition();
1453 //===--------------------------------------------------------------------===//
1454 // C99 6.5: Expressions.
1456 /// TypeCastState - State whether an expression is or may be a type cast.
1457 enum TypeCastState {
1463 ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast);
1464 ExprResult ParseConstantExpressionInExprEvalContext(
1465 TypeCastState isTypeCast = NotTypeCast);
1466 ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast);
1467 ExprResult ParseConstraintExpression();
1468 // Expr that doesn't include commas.
1469 ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast);
1471 ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1472 unsigned &NumLineToksConsumed,
1474 bool IsUnevaluated);
1477 ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
1479 ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
1481 ExprResult ParseRHSOfBinaryExpression(ExprResult LHS,
1482 prec::Level MinPrec);
1483 ExprResult ParseCastExpression(bool isUnaryExpression,
1484 bool isAddressOfOperand,
1486 TypeCastState isTypeCast,
1487 bool isVectorLiteral = false);
1488 ExprResult ParseCastExpression(bool isUnaryExpression,
1489 bool isAddressOfOperand = false,
1490 TypeCastState isTypeCast = NotTypeCast,
1491 bool isVectorLiteral = false);
1493 /// Returns true if the next token cannot start an expression.
1494 bool isNotExpressionStart();
1496 /// Returns true if the next token would start a postfix-expression
1498 bool isPostfixExpressionSuffixStart() {
1499 tok::TokenKind K = Tok.getKind();
1500 return (K == tok::l_square || K == tok::l_paren ||
1501 K == tok::period || K == tok::arrow ||
1502 K == tok::plusplus || K == tok::minusminus);
1505 bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less);
1507 ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
1508 ExprResult ParseUnaryExprOrTypeTraitExpression();
1509 ExprResult ParseBuiltinPrimaryExpression();
1511 ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1514 SourceRange &CastRange);
1516 typedef SmallVector<Expr*, 20> ExprListTy;
1517 typedef SmallVector<SourceLocation, 20> CommaLocsTy;
1519 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1520 bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
1521 SmallVectorImpl<SourceLocation> &CommaLocs,
1522 std::function<void()> Completer = nullptr);
1524 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
1525 /// used for misc language extensions.
1526 bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
1527 SmallVectorImpl<SourceLocation> &CommaLocs);
1530 /// ParenParseOption - Control what ParseParenExpression will parse.
1531 enum ParenParseOption {
1532 SimpleExpr, // Only parse '(' expression ')'
1533 CompoundStmt, // Also allow '(' compound-statement ')'
1534 CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
1535 CastExpr // Also allow '(' type-name ')' <anything>
1537 ExprResult ParseParenExpression(ParenParseOption &ExprType,
1538 bool stopIfCastExpr,
1541 SourceLocation &RParenLoc);
1543 ExprResult ParseCXXAmbiguousParenExpression(
1544 ParenParseOption &ExprType, ParsedType &CastTy,
1545 BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt);
1546 ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
1547 SourceLocation LParenLoc,
1548 SourceLocation RParenLoc);
1550 ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
1552 ExprResult ParseGenericSelectionExpression();
1554 ExprResult ParseObjCBoolLiteral();
1556 ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T);
1558 //===--------------------------------------------------------------------===//
1560 ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
1561 Token &Replacement);
1562 ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
1564 bool areTokensAdjacent(const Token &A, const Token &B);
1566 void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
1567 bool EnteringContext, IdentifierInfo &II,
1570 bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
1571 ParsedType ObjectType,
1572 bool EnteringContext,
1573 bool *MayBePseudoDestructor = nullptr,
1574 bool IsTypename = false,
1575 IdentifierInfo **LastII = nullptr,
1576 bool OnlyNamespace = false);
1578 //===--------------------------------------------------------------------===//
1579 // C++0x 5.1.2: Lambda expressions
1581 // [...] () -> type {...}
1582 ExprResult ParseLambdaExpression();
1583 ExprResult TryParseLambdaExpression();
1584 Optional<unsigned> ParseLambdaIntroducer(LambdaIntroducer &Intro,
1585 bool *SkippedInits = nullptr);
1586 bool TryParseLambdaIntroducer(LambdaIntroducer &Intro);
1587 ExprResult ParseLambdaExpressionAfterIntroducer(
1588 LambdaIntroducer &Intro);
1590 //===--------------------------------------------------------------------===//
1591 // C++ 5.2p1: C++ Casts
1592 ExprResult ParseCXXCasts();
1594 //===--------------------------------------------------------------------===//
1595 // C++ 5.2p1: C++ Type Identification
1596 ExprResult ParseCXXTypeid();
1598 //===--------------------------------------------------------------------===//
1599 // C++ : Microsoft __uuidof Expression
1600 ExprResult ParseCXXUuidof();
1602 //===--------------------------------------------------------------------===//
1603 // C++ 5.2.4: C++ Pseudo-Destructor Expressions
1604 ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1605 tok::TokenKind OpKind,
1607 ParsedType ObjectType);
1609 //===--------------------------------------------------------------------===//
1610 // C++ 9.3.2: C++ 'this' pointer
1611 ExprResult ParseCXXThis();
1613 //===--------------------------------------------------------------------===//
1614 // C++ 15: C++ Throw Expression
1615 ExprResult ParseThrowExpression();
1617 ExceptionSpecificationType tryParseExceptionSpecification(
1619 SourceRange &SpecificationRange,
1620 SmallVectorImpl<ParsedType> &DynamicExceptions,
1621 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
1622 ExprResult &NoexceptExpr,
1623 CachedTokens *&ExceptionSpecTokens);
1625 // EndLoc is filled with the location of the last token of the specification.
1626 ExceptionSpecificationType ParseDynamicExceptionSpecification(
1627 SourceRange &SpecificationRange,
1628 SmallVectorImpl<ParsedType> &Exceptions,
1629 SmallVectorImpl<SourceRange> &Ranges);
1631 //===--------------------------------------------------------------------===//
1632 // C++0x 8: Function declaration trailing-return-type
1633 TypeResult ParseTrailingReturnType(SourceRange &Range);
1635 //===--------------------------------------------------------------------===//
1636 // C++ 2.13.5: C++ Boolean Literals
1637 ExprResult ParseCXXBoolLiteral();
1639 //===--------------------------------------------------------------------===//
1640 // C++ 5.2.3: Explicit type conversion (functional notation)
1641 ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
1643 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1644 /// This should only be called when the current token is known to be part of
1645 /// simple-type-specifier.
1646 void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
1648 bool ParseCXXTypeSpecifierSeq(DeclSpec &DS);
1650 //===--------------------------------------------------------------------===//
1651 // C++ 5.3.4 and 5.3.5: C++ new and delete
1652 bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs,
1654 void ParseDirectNewDeclarator(Declarator &D);
1655 ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
1656 ExprResult ParseCXXDeleteExpression(bool UseGlobal,
1657 SourceLocation Start);
1659 //===--------------------------------------------------------------------===//
1660 // C++ if/switch/while condition expression.
1661 Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt,
1663 Sema::ConditionKind CK);
1665 //===--------------------------------------------------------------------===//
1668 ExprResult ParseCoyieldExpression();
1670 //===--------------------------------------------------------------------===//
1671 // C99 6.7.8: Initialization.
1673 /// ParseInitializer
1674 /// initializer: [C99 6.7.8]
1675 /// assignment-expression
1677 ExprResult ParseInitializer() {
1678 if (Tok.isNot(tok::l_brace))
1679 return ParseAssignmentExpression();
1680 return ParseBraceInitializer();
1682 bool MayBeDesignationStart();
1683 ExprResult ParseBraceInitializer();
1684 ExprResult ParseInitializerWithPotentialDesignator();
1686 //===--------------------------------------------------------------------===//
1687 // clang Expressions
1689 ExprResult ParseBlockLiteralExpression(); // ^{...}
1691 //===--------------------------------------------------------------------===//
1692 // Objective-C Expressions
1693 ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
1694 ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
1695 ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
1696 ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
1697 ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
1698 ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
1699 ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
1700 ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
1701 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
1702 ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
1703 ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
1704 bool isSimpleObjCMessageExpression();
1705 ExprResult ParseObjCMessageExpression();
1706 ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
1707 SourceLocation SuperLoc,
1708 ParsedType ReceiverType,
1709 Expr *ReceiverExpr);
1710 ExprResult ParseAssignmentExprWithObjCMessageExprStart(
1711 SourceLocation LBracloc, SourceLocation SuperLoc,
1712 ParsedType ReceiverType, Expr *ReceiverExpr);
1713 bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
1715 //===--------------------------------------------------------------------===//
1716 // C99 6.8: Statements and Blocks.
1718 /// A SmallVector of statements, with stack size 32 (as that is the only one
1720 typedef SmallVector<Stmt*, 32> StmtVector;
1721 /// A SmallVector of expressions, with stack size 12 (the maximum used.)
1722 typedef SmallVector<Expr*, 12> ExprVector;
1723 /// A SmallVector of types.
1724 typedef SmallVector<ParsedType, 12> TypeVector;
1726 StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
1727 bool AllowOpenMPStandalone = false);
1728 enum AllowedConstructsKind {
1729 /// \brief Allow any declarations, statements, OpenMP directives.
1731 /// \brief Allow only statements and non-standalone OpenMP directives.
1732 ACK_StatementsOpenMPNonStandalone,
1733 /// \brief Allow statements and all executable OpenMP directives
1734 ACK_StatementsOpenMPAnyExecutable
1737 ParseStatementOrDeclaration(StmtVector &Stmts, AllowedConstructsKind Allowed,
1738 SourceLocation *TrailingElseLoc = nullptr);
1739 StmtResult ParseStatementOrDeclarationAfterAttributes(
1741 AllowedConstructsKind Allowed,
1742 SourceLocation *TrailingElseLoc,
1743 ParsedAttributesWithRange &Attrs);
1744 StmtResult ParseExprStatement();
1745 StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs);
1746 StmtResult ParseCaseStatement(bool MissingCase = false,
1747 ExprResult Expr = ExprResult());
1748 StmtResult ParseDefaultStatement();
1749 StmtResult ParseCompoundStatement(bool isStmtExpr = false);
1750 StmtResult ParseCompoundStatement(bool isStmtExpr,
1751 unsigned ScopeFlags);
1752 void ParseCompoundStatementLeadingPragmas();
1753 StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
1754 bool ParseParenExprOrCondition(StmtResult *InitStmt,
1755 Sema::ConditionResult &CondResult,
1757 Sema::ConditionKind CK);
1758 StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
1759 StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
1760 StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
1761 StmtResult ParseDoStatement();
1762 StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
1763 StmtResult ParseGotoStatement();
1764 StmtResult ParseContinueStatement();
1765 StmtResult ParseBreakStatement();
1766 StmtResult ParseReturnStatement();
1767 StmtResult ParseAsmStatement(bool &msAsm);
1768 StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
1769 StmtResult ParsePragmaLoopHint(StmtVector &Stmts,
1770 AllowedConstructsKind Allowed,
1771 SourceLocation *TrailingElseLoc,
1772 ParsedAttributesWithRange &Attrs);
1774 /// \brief Describes the behavior that should be taken for an __if_exists
1776 enum IfExistsBehavior {
1777 /// \brief Parse the block; this code is always used.
1779 /// \brief Skip the block entirely; this code is never used.
1781 /// \brief Parse the block as a dependent block, which may be used in
1782 /// some template instantiations but not others.
1786 /// \brief Describes the condition of a Microsoft __if_exists or
1787 /// __if_not_exists block.
1788 struct IfExistsCondition {
1789 /// \brief The location of the initial keyword.
1790 SourceLocation KeywordLoc;
1791 /// \brief Whether this is an __if_exists block (rather than an
1792 /// __if_not_exists block).
1795 /// \brief Nested-name-specifier preceding the name.
1798 /// \brief The name we're looking for.
1801 /// \brief The behavior of this __if_exists or __if_not_exists block
1803 IfExistsBehavior Behavior;
1806 bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
1807 void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
1808 void ParseMicrosoftIfExistsExternalDeclaration();
1809 void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
1810 AccessSpecifier& CurAS);
1811 bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
1813 bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
1814 SmallVectorImpl<Expr *> &Constraints,
1815 SmallVectorImpl<Expr *> &Exprs);
1817 //===--------------------------------------------------------------------===//
1818 // C++ 6: Statements and Blocks
1820 StmtResult ParseCXXTryBlock();
1821 StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
1822 StmtResult ParseCXXCatchBlock(bool FnCatch = false);
1824 //===--------------------------------------------------------------------===//
1825 // MS: SEH Statements and Blocks
1827 StmtResult ParseSEHTryBlock();
1828 StmtResult ParseSEHExceptBlock(SourceLocation Loc);
1829 StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
1830 StmtResult ParseSEHLeaveStatement();
1832 //===--------------------------------------------------------------------===//
1833 // Objective-C Statements
1835 StmtResult ParseObjCAtStatement(SourceLocation atLoc);
1836 StmtResult ParseObjCTryStmt(SourceLocation atLoc);
1837 StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
1838 StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
1839 StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
1842 //===--------------------------------------------------------------------===//
1843 // C99 6.7: Declarations.
1845 /// A context for parsing declaration specifiers. TODO: flesh this
1846 /// out, there are other significant restrictions on specifiers than
1847 /// would be best implemented in the parser.
1848 enum DeclSpecContext {
1849 DSC_normal, // normal context
1850 DSC_class, // class context, enables 'friend'
1851 DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
1852 DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
1853 DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration
1854 DSC_top_level, // top-level/namespace declaration context
1855 DSC_template_param, // template parameter context
1856 DSC_template_type_arg, // template type argument context
1857 DSC_objc_method_result, // ObjC method result context, enables 'instancetype'
1858 DSC_condition // condition declaration context
1861 /// Is this a context in which we are parsing just a type-specifier (or
1862 /// trailing-type-specifier)?
1863 static bool isTypeSpecifier(DeclSpecContext DSC) {
1866 case DSC_template_param:
1869 case DSC_objc_method_result:
1873 case DSC_template_type_arg:
1874 case DSC_type_specifier:
1876 case DSC_alias_declaration:
1879 llvm_unreachable("Missing DeclSpecContext case");
1882 /// Is this a context in which we can perform class template argument
1884 static bool isClassTemplateDeductionContext(DeclSpecContext DSC) {
1887 case DSC_template_param:
1891 case DSC_type_specifier:
1894 case DSC_objc_method_result:
1895 case DSC_template_type_arg:
1897 case DSC_alias_declaration:
1900 llvm_unreachable("Missing DeclSpecContext case");
1903 /// Information on a C++0x for-range-initializer found while parsing a
1904 /// declaration which turns out to be a for-range-declaration.
1905 struct ForRangeInit {
1906 SourceLocation ColonLoc;
1907 ExprResult RangeExpr;
1909 bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
1912 DeclGroupPtrTy ParseDeclaration(unsigned Context, SourceLocation &DeclEnd,
1913 ParsedAttributesWithRange &attrs);
1914 DeclGroupPtrTy ParseSimpleDeclaration(unsigned Context,
1915 SourceLocation &DeclEnd,
1916 ParsedAttributesWithRange &attrs,
1918 ForRangeInit *FRI = nullptr);
1919 bool MightBeDeclarator(unsigned Context);
1920 DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, unsigned Context,
1921 SourceLocation *DeclEnd = nullptr,
1922 ForRangeInit *FRI = nullptr);
1923 Decl *ParseDeclarationAfterDeclarator(Declarator &D,
1924 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
1925 bool ParseAsmAttributesAfterDeclarator(Declarator &D);
1926 Decl *ParseDeclarationAfterDeclaratorAndAttributes(
1928 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1929 ForRangeInit *FRI = nullptr);
1930 Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
1931 Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
1933 /// \brief When in code-completion, skip parsing of the function/method body
1934 /// unless the body contains the code-completion point.
1936 /// \returns true if the function body was skipped.
1937 bool trySkippingFunctionBody();
1939 bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
1940 const ParsedTemplateInfo &TemplateInfo,
1941 AccessSpecifier AS, DeclSpecContext DSC,
1942 ParsedAttributesWithRange &Attrs);
1943 DeclSpecContext getDeclSpecContextFromDeclaratorContext(unsigned Context);
1944 void ParseDeclarationSpecifiers(DeclSpec &DS,
1945 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1946 AccessSpecifier AS = AS_none,
1947 DeclSpecContext DSC = DSC_normal,
1948 LateParsedAttrList *LateAttrs = nullptr);
1949 bool DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
1950 DeclSpecContext DSContext,
1951 LateParsedAttrList *LateAttrs = nullptr);
1953 void ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS = AS_none,
1954 DeclSpecContext DSC = DSC_normal);
1956 void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
1957 Declarator::TheContext Context);
1959 void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
1960 const ParsedTemplateInfo &TemplateInfo,
1961 AccessSpecifier AS, DeclSpecContext DSC);
1962 void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
1963 void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType,
1966 void ParseStructDeclaration(
1967 ParsingDeclSpec &DS,
1968 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback);
1970 bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
1971 bool isTypeSpecifierQualifier();
1973 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
1974 /// is definitely a type-specifier. Return false if it isn't part of a type
1975 /// specifier or if we're not sure.
1976 bool isKnownToBeTypeSpecifier(const Token &Tok) const;
1978 /// \brief Return true if we know that we are definitely looking at a
1979 /// decl-specifier, and isn't part of an expression such as a function-style
1980 /// cast. Return false if it's no a decl-specifier, or we're not sure.
1981 bool isKnownToBeDeclarationSpecifier() {
1982 if (getLangOpts().CPlusPlus)
1983 return isCXXDeclarationSpecifier() == TPResult::True;
1984 return isDeclarationSpecifier(true);
1987 /// isDeclarationStatement - Disambiguates between a declaration or an
1988 /// expression statement, when parsing function bodies.
1989 /// Returns true for declaration, false for expression.
1990 bool isDeclarationStatement() {
1991 if (getLangOpts().CPlusPlus)
1992 return isCXXDeclarationStatement();
1993 return isDeclarationSpecifier(true);
1996 /// isForInitDeclaration - Disambiguates between a declaration or an
1997 /// expression in the context of the C 'clause-1' or the C++
1998 // 'for-init-statement' part of a 'for' statement.
1999 /// Returns true for declaration, false for expression.
2000 bool isForInitDeclaration() {
2001 if (getLangOpts().CPlusPlus)
2002 return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
2003 return isDeclarationSpecifier(true);
2006 /// \brief Determine whether this is a C++1z for-range-identifier.
2007 bool isForRangeIdentifier();
2009 /// \brief Determine whether we are currently at the start of an Objective-C
2010 /// class message that appears to be missing the open bracket '['.
2011 bool isStartOfObjCClassMessageMissingOpenBracket();
2013 /// \brief Starting with a scope specifier, identifier, or
2014 /// template-id that refers to the current class, determine whether
2015 /// this is a constructor declarator.
2016 bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false);
2018 /// \brief Specifies the context in which type-id/expression
2019 /// disambiguation will occur.
2020 enum TentativeCXXTypeIdContext {
2023 TypeIdAsTemplateArgument
2027 /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
2028 /// whether the parens contain an expression or a type-id.
2029 /// Returns true for a type-id and false for an expression.
2030 bool isTypeIdInParens(bool &isAmbiguous) {
2031 if (getLangOpts().CPlusPlus)
2032 return isCXXTypeId(TypeIdInParens, isAmbiguous);
2033 isAmbiguous = false;
2034 return isTypeSpecifierQualifier();
2036 bool isTypeIdInParens() {
2038 return isTypeIdInParens(isAmbiguous);
2041 /// \brief Checks if the current tokens form type-id or expression.
2042 /// It is similar to isTypeIdInParens but does not suppose that type-id
2043 /// is in parenthesis.
2044 bool isTypeIdUnambiguously() {
2046 if (getLangOpts().CPlusPlus)
2047 return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous);
2048 return isTypeSpecifierQualifier();
2051 /// isCXXDeclarationStatement - C++-specialized function that disambiguates
2052 /// between a declaration or an expression statement, when parsing function
2053 /// bodies. Returns true for declaration, false for expression.
2054 bool isCXXDeclarationStatement();
2056 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
2057 /// between a simple-declaration or an expression-statement.
2058 /// If during the disambiguation process a parsing error is encountered,
2059 /// the function returns true to let the declaration parsing code handle it.
2060 /// Returns false if the statement is disambiguated as expression.
2061 bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
2063 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
2064 /// a constructor-style initializer, when parsing declaration statements.
2065 /// Returns true for function declarator and false for constructor-style
2066 /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
2067 /// might be a constructor-style initializer.
2068 /// If during the disambiguation process a parsing error is encountered,
2069 /// the function returns true to let the declaration parsing code handle it.
2070 bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr);
2072 struct ConditionDeclarationOrInitStatementState;
2073 enum class ConditionOrInitStatement {
2074 Expression, ///< Disambiguated as an expression (either kind).
2075 ConditionDecl, ///< Disambiguated as the declaration form of condition.
2076 InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement.
2077 Error ///< Can't be any of the above!
2079 /// \brief Disambiguates between the different kinds of things that can happen
2080 /// after 'if (' or 'switch ('. This could be one of two different kinds of
2081 /// declaration (depending on whether there is a ';' later) or an expression.
2082 ConditionOrInitStatement
2083 isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt);
2085 bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
2086 bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
2088 return isCXXTypeId(Context, isAmbiguous);
2091 /// TPResult - Used as the result value for functions whose purpose is to
2092 /// disambiguate C++ constructs by "tentatively parsing" them.
2093 enum class TPResult {
2094 True, False, Ambiguous, Error
2097 /// \brief Based only on the given token kind, determine whether we know that
2098 /// we're at the start of an expression or a type-specifier-seq (which may
2099 /// be an expression, in C++).
2101 /// This routine does not attempt to resolve any of the trick cases, e.g.,
2102 /// those involving lookup of identifiers.
2104 /// \returns \c TPR_true if this token starts an expression, \c TPR_false if
2105 /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot
2107 TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind);
2109 /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a
2110 /// declaration specifier, TPResult::False if it is not,
2111 /// TPResult::Ambiguous if it could be either a decl-specifier or a
2112 /// function-style cast, and TPResult::Error if a parsing error was
2113 /// encountered. If it could be a braced C++11 function-style cast, returns
2114 /// BracedCastResult.
2115 /// Doesn't consume tokens.
2117 isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False,
2118 bool *HasMissingTypename = nullptr);
2120 /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
2121 /// \c TPResult::Ambiguous, determine whether the decl-specifier would be
2122 /// a type-specifier other than a cv-qualifier.
2123 bool isCXXDeclarationSpecifierAType();
2125 /// \brief Determine whether an identifier has been tentatively declared as a
2126 /// non-type. Such tentative declarations should not be found to name a type
2127 /// during a tentative parse, but also should not be annotated as a non-type.
2128 bool isTentativelyDeclared(IdentifierInfo *II);
2130 // "Tentative parsing" functions, used for disambiguation. If a parsing error
2131 // is encountered they will return TPResult::Error.
2132 // Returning TPResult::True/False indicates that the ambiguity was
2133 // resolved and tentative parsing may stop. TPResult::Ambiguous indicates
2134 // that more tentative parsing is necessary for disambiguation.
2135 // They all consume tokens, so backtracking should be used after calling them.
2137 TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
2138 TPResult TryParseTypeofSpecifier();
2139 TPResult TryParseProtocolQualifiers();
2140 TPResult TryParsePtrOperatorSeq();
2141 TPResult TryParseOperatorId();
2142 TPResult TryParseInitDeclaratorList();
2143 TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier=true);
2145 TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr,
2146 bool VersusTemplateArg = false);
2147 TPResult TryParseFunctionDeclarator();
2148 TPResult TryParseBracketDeclarator();
2149 TPResult TryConsumeDeclarationSpecifier();
2152 TypeResult ParseTypeName(SourceRange *Range = nullptr,
2153 Declarator::TheContext Context
2154 = Declarator::TypeNameContext,
2155 AccessSpecifier AS = AS_none,
2156 Decl **OwnedType = nullptr,
2157 ParsedAttributes *Attrs = nullptr);
2160 void ParseBlockId(SourceLocation CaretLoc);
2162 // Check for the start of a C++11 attribute-specifier-seq in a context where
2163 // an attribute is not allowed.
2164 bool CheckProhibitedCXX11Attribute() {
2165 assert(Tok.is(tok::l_square));
2166 if (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))
2168 return DiagnoseProhibitedCXX11Attribute();
2170 bool DiagnoseProhibitedCXX11Attribute();
2171 void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2172 SourceLocation CorrectLocation) {
2173 if (!getLangOpts().CPlusPlus11)
2175 if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
2176 Tok.isNot(tok::kw_alignas))
2178 DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
2180 void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2181 SourceLocation CorrectLocation);
2183 void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
2184 DeclSpec &DS, Sema::TagUseKind TUK);
2186 void ProhibitAttributes(ParsedAttributesWithRange &attrs) {
2187 if (!attrs.Range.isValid()) return;
2188 DiagnoseProhibitedAttributes(attrs);
2191 void DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs);
2193 // Forbid C++11 attributes that appear on certain syntactic
2194 // locations which standard permits but we don't supported yet,
2195 // for example, attributes appertain to decl specifiers.
2196 void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
2199 /// \brief Skip C++11 attributes and return the end location of the last one.
2200 /// \returns SourceLocation() if there are no attributes.
2201 SourceLocation SkipCXX11Attributes();
2203 /// \brief Diagnose and skip C++11 attributes that appear in syntactic
2204 /// locations where attributes are not allowed.
2205 void DiagnoseAndSkipCXX11Attributes();
2207 /// \brief Parses syntax-generic attribute arguments for attributes which are
2208 /// known to the implementation, and adds them to the given ParsedAttributes
2209 /// list with the given attribute syntax. Returns the number of arguments
2210 /// parsed for the attribute.
2212 ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2213 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2214 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2215 AttributeList::Syntax Syntax);
2217 void MaybeParseGNUAttributes(Declarator &D,
2218 LateParsedAttrList *LateAttrs = nullptr) {
2219 if (Tok.is(tok::kw___attribute)) {
2220 ParsedAttributes attrs(AttrFactory);
2221 SourceLocation endLoc;
2222 ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D);
2223 D.takeAttributes(attrs, endLoc);
2226 void MaybeParseGNUAttributes(ParsedAttributes &attrs,
2227 SourceLocation *endLoc = nullptr,
2228 LateParsedAttrList *LateAttrs = nullptr) {
2229 if (Tok.is(tok::kw___attribute))
2230 ParseGNUAttributes(attrs, endLoc, LateAttrs);
2232 void ParseGNUAttributes(ParsedAttributes &attrs,
2233 SourceLocation *endLoc = nullptr,
2234 LateParsedAttrList *LateAttrs = nullptr,
2235 Declarator *D = nullptr);
2236 void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
2237 SourceLocation AttrNameLoc,
2238 ParsedAttributes &Attrs,
2239 SourceLocation *EndLoc,
2240 IdentifierInfo *ScopeName,
2241 SourceLocation ScopeLoc,
2242 AttributeList::Syntax Syntax,
2244 IdentifierLoc *ParseIdentifierLoc();
2247 ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2248 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2249 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2250 AttributeList::Syntax Syntax);
2252 void MaybeParseCXX11Attributes(Declarator &D) {
2253 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
2254 ParsedAttributesWithRange attrs(AttrFactory);
2255 SourceLocation endLoc;
2256 ParseCXX11Attributes(attrs, &endLoc);
2257 D.takeAttributes(attrs, endLoc);
2260 void MaybeParseCXX11Attributes(ParsedAttributes &attrs,
2261 SourceLocation *endLoc = nullptr) {
2262 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
2263 ParsedAttributesWithRange attrsWithRange(AttrFactory);
2264 ParseCXX11Attributes(attrsWithRange, endLoc);
2265 attrs.takeAllFrom(attrsWithRange);
2268 void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2269 SourceLocation *endLoc = nullptr,
2270 bool OuterMightBeMessageSend = false) {
2271 if (getLangOpts().CPlusPlus11 &&
2272 isCXX11AttributeSpecifier(false, OuterMightBeMessageSend))
2273 ParseCXX11Attributes(attrs, endLoc);
2276 void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
2277 SourceLocation *EndLoc = nullptr);
2278 void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2279 SourceLocation *EndLoc = nullptr);
2280 /// \brief Parses a C++-style attribute argument list. Returns true if this
2281 /// results in adding an attribute to the ParsedAttributes list.
2282 bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
2283 SourceLocation AttrNameLoc,
2284 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2285 IdentifierInfo *ScopeName,
2286 SourceLocation ScopeLoc);
2288 IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc);
2290 void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
2291 SourceLocation *endLoc = nullptr) {
2292 if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
2293 ParseMicrosoftAttributes(attrs, endLoc);
2295 void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs);
2296 void ParseMicrosoftAttributes(ParsedAttributes &attrs,
2297 SourceLocation *endLoc = nullptr);
2298 void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2299 SourceLocation *End = nullptr) {
2300 const auto &LO = getLangOpts();
2301 if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec))
2302 ParseMicrosoftDeclSpecs(Attrs, End);
2304 void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2305 SourceLocation *End = nullptr);
2306 bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
2307 SourceLocation AttrNameLoc,
2308 ParsedAttributes &Attrs);
2309 void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
2310 void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2311 SourceLocation SkipExtendedMicrosoftTypeAttributes();
2312 void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
2313 void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
2314 void ParseOpenCLKernelAttributes(ParsedAttributes &attrs);
2315 void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
2316 /// \brief Parses opencl_unroll_hint attribute if language is OpenCL v2.0
2318 /// \return false if error happens.
2319 bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
2320 if (getLangOpts().OpenCL)
2321 return ParseOpenCLUnrollHintAttribute(Attrs);
2324 /// \brief Parses opencl_unroll_hint attribute.
2325 /// \return false if error happens.
2326 bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs);
2327 void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
2329 VersionTuple ParseVersionTuple(SourceRange &Range);
2330 void ParseAvailabilityAttribute(IdentifierInfo &Availability,
2331 SourceLocation AvailabilityLoc,
2332 ParsedAttributes &attrs,
2333 SourceLocation *endLoc,
2334 IdentifierInfo *ScopeName,
2335 SourceLocation ScopeLoc,
2336 AttributeList::Syntax Syntax);
2338 Optional<AvailabilitySpec> ParseAvailabilitySpec();
2339 ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc);
2341 void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol,
2343 ParsedAttributes &Attrs,
2344 SourceLocation *EndLoc,
2345 IdentifierInfo *ScopeName,
2346 SourceLocation ScopeLoc,
2347 AttributeList::Syntax Syntax);
2349 void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
2350 SourceLocation ObjCBridgeRelatedLoc,
2351 ParsedAttributes &attrs,
2352 SourceLocation *endLoc,
2353 IdentifierInfo *ScopeName,
2354 SourceLocation ScopeLoc,
2355 AttributeList::Syntax Syntax);
2357 void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
2358 SourceLocation AttrNameLoc,
2359 ParsedAttributes &Attrs,
2360 SourceLocation *EndLoc,
2361 IdentifierInfo *ScopeName,
2362 SourceLocation ScopeLoc,
2363 AttributeList::Syntax Syntax);
2365 void ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
2366 SourceLocation AttrNameLoc,
2367 ParsedAttributes &Attrs,
2368 SourceLocation *EndLoc,
2369 IdentifierInfo *ScopeName,
2370 SourceLocation ScopeLoc,
2371 AttributeList::Syntax Syntax);
2373 void ParseTypeofSpecifier(DeclSpec &DS);
2374 SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
2375 void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
2376 SourceLocation StartLoc,
2377 SourceLocation EndLoc);
2378 void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
2379 void ParseAtomicSpecifier(DeclSpec &DS);
2381 ExprResult ParseAlignArgument(SourceLocation Start,
2382 SourceLocation &EllipsisLoc);
2383 void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2384 SourceLocation *endLoc = nullptr);
2386 VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
2387 VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
2388 return isCXX11VirtSpecifier(Tok);
2390 void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface,
2391 SourceLocation FriendLoc);
2393 bool isCXX11FinalKeyword() const;
2395 /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
2396 /// enter a new C++ declarator scope and exit it when the function is
2398 class DeclaratorScopeObj {
2404 DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
2405 : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
2407 void EnterDeclaratorScope() {
2408 assert(!EnteredScope && "Already entered the scope!");
2409 assert(SS.isSet() && "C++ scope was not set!");
2411 CreatedScope = true;
2412 P.EnterScope(0); // Not a decl scope.
2414 if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
2415 EnteredScope = true;
2418 ~DeclaratorScopeObj() {
2420 assert(SS.isSet() && "C++ scope was cleared ?");
2421 P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
2428 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
2429 void ParseDeclarator(Declarator &D);
2430 /// A function that parses a variant of direct-declarator.
2431 typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
2432 void ParseDeclaratorInternal(Declarator &D,
2433 DirectDeclParseFunction DirectDeclParser);
2435 enum AttrRequirements {
2436 AR_NoAttributesParsed = 0, ///< No attributes are diagnosed.
2437 AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes.
2438 AR_GNUAttributesParsed = 1 << 1,
2439 AR_CXX11AttributesParsed = 1 << 2,
2440 AR_DeclspecAttributesParsed = 1 << 3,
2441 AR_AllAttributesParsed = AR_GNUAttributesParsed |
2442 AR_CXX11AttributesParsed |
2443 AR_DeclspecAttributesParsed,
2444 AR_VendorAttributesParsed = AR_GNUAttributesParsed |
2445 AR_DeclspecAttributesParsed
2448 void ParseTypeQualifierListOpt(
2449 DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed,
2450 bool AtomicAllowed = true, bool IdentifierRequired = false,
2451 Optional<llvm::function_ref<void()>> CodeCompletionHandler = None);
2452 void ParseDirectDeclarator(Declarator &D);
2453 void ParseDecompositionDeclarator(Declarator &D);
2454 void ParseParenDeclarator(Declarator &D);
2455 void ParseFunctionDeclarator(Declarator &D,
2456 ParsedAttributes &attrs,
2457 BalancedDelimiterTracker &Tracker,
2459 bool RequiresArg = false);
2460 bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
2461 SourceLocation &RefQualifierLoc);
2462 bool isFunctionDeclaratorIdentifierList();
2463 void ParseFunctionDeclaratorIdentifierList(
2465 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
2466 void ParseParameterDeclarationClause(
2468 ParsedAttributes &attrs,
2469 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
2470 SourceLocation &EllipsisLoc);
2471 void ParseBracketDeclarator(Declarator &D);
2472 void ParseMisplacedBracketDeclarator(Declarator &D);
2474 //===--------------------------------------------------------------------===//
2475 // C++ 7: Declarations [dcl.dcl]
2477 /// The kind of attribute specifier we have found.
2478 enum CXX11AttributeKind {
2479 /// This is not an attribute specifier.
2480 CAK_NotAttributeSpecifier,
2481 /// This should be treated as an attribute-specifier.
2482 CAK_AttributeSpecifier,
2483 /// The next tokens are '[[', but this is not an attribute-specifier. This
2484 /// is ill-formed by C++11 [dcl.attr.grammar]p6.
2485 CAK_InvalidAttributeSpecifier
2488 isCXX11AttributeSpecifier(bool Disambiguate = false,
2489 bool OuterMightBeMessageSend = false);
2491 void DiagnoseUnexpectedNamespace(NamedDecl *Context);
2493 DeclGroupPtrTy ParseNamespace(unsigned Context, SourceLocation &DeclEnd,
2494 SourceLocation InlineLoc = SourceLocation());
2495 void ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc,
2496 std::vector<IdentifierInfo*>& Ident,
2497 std::vector<SourceLocation>& NamespaceLoc,
2498 unsigned int index, SourceLocation& InlineLoc,
2499 ParsedAttributes& attrs,
2500 BalancedDelimiterTracker &Tracker);
2501 Decl *ParseLinkage(ParsingDeclSpec &DS, unsigned Context);
2502 Decl *ParseExportDeclaration();
2503 DeclGroupPtrTy ParseUsingDirectiveOrDeclaration(
2504 unsigned Context, const ParsedTemplateInfo &TemplateInfo,
2505 SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs);
2506 Decl *ParseUsingDirective(unsigned Context,
2507 SourceLocation UsingLoc,
2508 SourceLocation &DeclEnd,
2509 ParsedAttributes &attrs);
2511 struct UsingDeclarator {
2512 SourceLocation TypenameLoc;
2514 SourceLocation TemplateKWLoc;
2516 SourceLocation EllipsisLoc;
2519 TypenameLoc = TemplateKWLoc = EllipsisLoc = SourceLocation();
2525 bool ParseUsingDeclarator(unsigned Context, UsingDeclarator &D);
2526 DeclGroupPtrTy ParseUsingDeclaration(unsigned Context,
2527 const ParsedTemplateInfo &TemplateInfo,
2528 SourceLocation UsingLoc,
2529 SourceLocation &DeclEnd,
2530 AccessSpecifier AS = AS_none);
2531 Decl *ParseAliasDeclarationAfterDeclarator(
2532 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
2533 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
2534 ParsedAttributes &Attrs, Decl **OwnedType = nullptr);
2536 Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
2537 Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
2538 SourceLocation AliasLoc, IdentifierInfo *Alias,
2539 SourceLocation &DeclEnd);
2541 //===--------------------------------------------------------------------===//
2542 // C++ 9: classes [class] and C structs/unions.
2543 bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
2544 void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
2545 DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo,
2546 AccessSpecifier AS, bool EnteringContext,
2547 DeclSpecContext DSC,
2548 ParsedAttributesWithRange &Attributes);
2549 void SkipCXXMemberSpecification(SourceLocation StartLoc,
2550 SourceLocation AttrFixitLoc,
2553 void ParseCXXMemberSpecification(SourceLocation StartLoc,
2554 SourceLocation AttrFixitLoc,
2555 ParsedAttributesWithRange &Attrs,
2558 ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2559 SourceLocation &EqualLoc);
2560 bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
2562 ExprResult &BitfieldSize,
2563 LateParsedAttrList &LateAttrs);
2564 void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D,
2565 VirtSpecifiers &VS);
2566 DeclGroupPtrTy ParseCXXClassMemberDeclaration(
2567 AccessSpecifier AS, AttributeList *Attr,
2568 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2569 ParsingDeclRAIIObject *DiagsFromTParams = nullptr);
2570 DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas(
2571 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
2572 DeclSpec::TST TagType, Decl *Tag);
2573 void ParseConstructorInitializer(Decl *ConstructorDecl);
2574 MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
2575 void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2578 //===--------------------------------------------------------------------===//
2579 // C++ 10: Derived classes [class.derived]
2580 TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
2581 SourceLocation &EndLocation);
2582 void ParseBaseClause(Decl *ClassDecl);
2583 BaseResult ParseBaseSpecifier(Decl *ClassDecl);
2584 AccessSpecifier getAccessSpecifierIfPresent() const;
2586 bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
2587 SourceLocation TemplateKWLoc,
2588 IdentifierInfo *Name,
2589 SourceLocation NameLoc,
2590 bool EnteringContext,
2591 ParsedType ObjectType,
2593 bool AssumeTemplateId);
2594 bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2595 ParsedType ObjectType,
2596 UnqualifiedId &Result);
2598 //===--------------------------------------------------------------------===//
2599 // OpenMP: Directives and clauses.
2600 /// Parse clauses for '#pragma omp declare simd'.
2601 DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr,
2603 SourceLocation Loc);
2604 /// \brief Parses declarative OpenMP directives.
2605 DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl(
2606 AccessSpecifier &AS, ParsedAttributesWithRange &Attrs,
2607 DeclSpec::TST TagType = DeclSpec::TST_unspecified,
2608 Decl *TagDecl = nullptr);
2609 /// \brief Parse 'omp declare reduction' construct.
2610 DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS);
2612 /// \brief Parses simple list of variables.
2614 /// \param Kind Kind of the directive.
2615 /// \param Callback Callback function to be called for the list elements.
2616 /// \param AllowScopeSpecifier true, if the variables can have fully
2617 /// qualified names.
2619 bool ParseOpenMPSimpleVarList(
2620 OpenMPDirectiveKind Kind,
2621 const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
2623 bool AllowScopeSpecifier);
2624 /// \brief Parses declarative or executable directive.
2626 /// \param Allowed ACK_Any, if any directives are allowed,
2627 /// ACK_StatementsOpenMPAnyExecutable - if any executable directives are
2628 /// allowed, ACK_StatementsOpenMPNonStandalone - if only non-standalone
2629 /// executable directives are allowed.
2632 ParseOpenMPDeclarativeOrExecutableDirective(AllowedConstructsKind Allowed);
2633 /// \brief Parses clause of kind \a CKind for directive of a kind \a Kind.
2635 /// \param DKind Kind of current directive.
2636 /// \param CKind Kind of current clause.
2637 /// \param FirstClause true, if this is the first clause of a kind \a CKind
2638 /// in current directive.
2640 OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
2641 OpenMPClauseKind CKind, bool FirstClause);
2642 /// \brief Parses clause with a single expression of a kind \a Kind.
2644 /// \param Kind Kind of current clause.
2646 OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind);
2647 /// \brief Parses simple clause of a kind \a Kind.
2649 /// \param Kind Kind of current clause.
2651 OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind);
2652 /// \brief Parses clause with a single expression and an additional argument
2653 /// of a kind \a Kind.
2655 /// \param Kind Kind of current clause.
2657 OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind);
2658 /// \brief Parses clause without any additional arguments.
2660 /// \param Kind Kind of current clause.
2662 OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind);
2663 /// \brief Parses clause with the list of variables of a kind \a Kind.
2665 /// \param Kind Kind of current clause.
2667 OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
2668 OpenMPClauseKind Kind);
2671 /// Parses simple expression in parens for single-expression clauses of OpenMP
2673 /// \param RLoc Returned location of right paren.
2674 ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc);
2676 /// Data used for parsing list of variables in OpenMP clauses.
2677 struct OpenMPVarListDataTy {
2678 Expr *TailExpr = nullptr;
2679 SourceLocation ColonLoc;
2680 CXXScopeSpec ReductionIdScopeSpec;
2681 DeclarationNameInfo ReductionId;
2682 OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown;
2683 OpenMPLinearClauseKind LinKind = OMPC_LINEAR_val;
2684 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
2685 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
2686 bool IsMapTypeImplicit = false;
2687 SourceLocation DepLinMapLoc;
2690 /// Parses clauses with list.
2691 bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind,
2692 SmallVectorImpl<Expr *> &Vars,
2693 OpenMPVarListDataTy &Data);
2694 bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2695 bool AllowDestructorName,
2696 bool AllowConstructorName,
2697 bool AllowDeductionGuide,
2698 ParsedType ObjectType,
2699 SourceLocation& TemplateKWLoc,
2700 UnqualifiedId &Result);
2703 //===--------------------------------------------------------------------===//
2704 // C++ 14: Templates [temp]
2706 // C++ 14.1: Template Parameters [temp.param]
2707 Decl *ParseDeclarationStartingWithTemplate(unsigned Context,
2708 SourceLocation &DeclEnd,
2709 AccessSpecifier AS = AS_none,
2710 AttributeList *AccessAttrs = nullptr);
2711 Decl *ParseTemplateDeclarationOrSpecialization(unsigned Context,
2712 SourceLocation &DeclEnd,
2714 AttributeList *AccessAttrs);
2715 Decl *ParseSingleDeclarationAfterTemplate(
2717 const ParsedTemplateInfo &TemplateInfo,
2718 ParsingDeclRAIIObject &DiagsFromParams,
2719 SourceLocation &DeclEnd,
2720 AccessSpecifier AS=AS_none,
2721 AttributeList *AccessAttrs = nullptr);
2722 bool ParseTemplateParameters(unsigned Depth,
2723 SmallVectorImpl<Decl*> &TemplateParams,
2724 SourceLocation &LAngleLoc,
2725 SourceLocation &RAngleLoc);
2726 bool ParseTemplateParameterList(unsigned Depth,
2727 SmallVectorImpl<Decl*> &TemplateParams);
2728 bool isStartOfTemplateTypeParameter();
2729 Decl *ParseTemplateParameter(unsigned Depth, unsigned Position);
2730 Decl *ParseTypeParameter(unsigned Depth, unsigned Position);
2731 Decl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
2732 Decl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
2733 void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
2734 SourceLocation CorrectLoc,
2735 bool AlreadyHasEllipsis,
2736 bool IdentifierHasName);
2737 void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
2739 // C++ 14.3: Template arguments [temp.arg]
2740 typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
2742 bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
2743 bool ConsumeLastToken,
2744 bool ObjCGenericList);
2745 bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
2746 SourceLocation &LAngleLoc,
2747 TemplateArgList &TemplateArgs,
2748 SourceLocation &RAngleLoc);
2750 bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
2752 SourceLocation TemplateKWLoc,
2753 UnqualifiedId &TemplateName,
2754 bool AllowTypeAnnotation = true);
2755 void AnnotateTemplateIdTokenAsType(bool IsClassName = false);
2756 bool IsTemplateArgumentList(unsigned Skip = 0);
2757 bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
2758 ParsedTemplateArgument ParseTemplateTemplateArgument();
2759 ParsedTemplateArgument ParseTemplateArgument();
2760 Decl *ParseExplicitInstantiation(unsigned Context,
2761 SourceLocation ExternLoc,
2762 SourceLocation TemplateLoc,
2763 SourceLocation &DeclEnd,
2764 AccessSpecifier AS = AS_none);
2766 //===--------------------------------------------------------------------===//
2768 DeclGroupPtrTy ParseModuleDecl();
2769 DeclGroupPtrTy ParseModuleImport(SourceLocation AtLoc);
2770 bool parseMisplacedModuleImport();
2771 bool tryParseMisplacedModuleImport() {
2772 tok::TokenKind Kind = Tok.getKind();
2773 if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end ||
2774 Kind == tok::annot_module_include)
2775 return parseMisplacedModuleImport();
2779 bool ParseModuleName(
2780 SourceLocation UseLoc,
2781 SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
2784 //===--------------------------------------------------------------------===//
2785 // C++11/G++: Type Traits [Type-Traits.html in the GCC manual]
2786 ExprResult ParseTypeTrait();
2788 //===--------------------------------------------------------------------===//
2789 // Embarcadero: Arary and Expression Traits
2790 ExprResult ParseArrayTypeTrait();
2791 ExprResult ParseExpressionTrait();
2793 //===--------------------------------------------------------------------===//
2794 // Preprocessor code-completion pass-through
2795 void CodeCompleteDirective(bool InConditional) override;
2796 void CodeCompleteInConditionalExclusion() override;
2797 void CodeCompleteMacroName(bool IsDefinition) override;
2798 void CodeCompletePreprocessorExpression() override;
2799 void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo,
2800 unsigned ArgumentIndex) override;
2801 void CodeCompleteNaturalLanguage() override;
2804 } // end namespace clang