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> MSCommentHandler;
170 std::unique_ptr<PragmaHandler> MSDetectMismatchHandler;
171 std::unique_ptr<PragmaHandler> MSPointersToMembers;
172 std::unique_ptr<PragmaHandler> MSVtorDisp;
173 std::unique_ptr<PragmaHandler> MSInitSeg;
174 std::unique_ptr<PragmaHandler> MSDataSeg;
175 std::unique_ptr<PragmaHandler> MSBSSSeg;
176 std::unique_ptr<PragmaHandler> MSConstSeg;
177 std::unique_ptr<PragmaHandler> MSCodeSeg;
178 std::unique_ptr<PragmaHandler> MSSection;
179 std::unique_ptr<PragmaHandler> MSRuntimeChecks;
180 std::unique_ptr<PragmaHandler> MSIntrinsic;
181 std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler;
182 std::unique_ptr<PragmaHandler> OptimizeHandler;
183 std::unique_ptr<PragmaHandler> LoopHintHandler;
184 std::unique_ptr<PragmaHandler> UnrollHintHandler;
185 std::unique_ptr<PragmaHandler> NoUnrollHintHandler;
186 std::unique_ptr<PragmaHandler> FPHandler;
187 std::unique_ptr<PragmaHandler> AttributePragmaHandler;
189 std::unique_ptr<CommentHandler> CommentSemaHandler;
191 /// Whether the '>' token acts as an operator or not. This will be
192 /// true except when we are parsing an expression within a C++
193 /// template argument list, where the '>' closes the template
195 bool GreaterThanIsOperator;
197 /// ColonIsSacred - When this is false, we aggressively try to recover from
198 /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not
199 /// safe in case statements and a few other things. This is managed by the
200 /// ColonProtectionRAIIObject RAII object.
203 /// \brief When true, we are directly inside an Objective-C message
206 /// This is managed by the \c InMessageExpressionRAIIObject class, and
207 /// should not be set directly.
208 bool InMessageExpression;
210 /// The "depth" of the template parameters currently being parsed.
211 unsigned TemplateParameterDepth;
213 /// \brief RAII class that manages the template parameter depth.
214 class TemplateParameterDepthRAII {
216 unsigned AddedLevels;
218 explicit TemplateParameterDepthRAII(unsigned &Depth)
219 : Depth(Depth), AddedLevels(0) {}
221 ~TemplateParameterDepthRAII() {
222 Depth -= AddedLevels;
229 void addDepth(unsigned D) {
233 unsigned getDepth() const { return Depth; }
236 /// Factory object for creating AttributeList objects.
237 AttributeFactory AttrFactory;
239 /// \brief Gathers and cleans up TemplateIdAnnotations when parsing of a
240 /// top-level declaration is finished.
241 SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
243 /// \brief Identifiers which have been declared within a tentative parse.
244 SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers;
246 IdentifierInfo *getSEHExceptKeyword();
248 /// True if we are within an Objective-C container while parsing C-like decls.
250 /// This is necessary because Sema thinks we have left the container
251 /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will
253 bool ParsingInObjCContainer;
255 bool SkipFunctionBodies;
257 /// The location of the expression statement that is being parsed right now.
258 /// Used to determine if an expression that is being parsed is a statement or
259 /// just a regular sub-expression.
260 SourceLocation ExprStatementTokLoc;
263 Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
266 const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
267 const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
268 Preprocessor &getPreprocessor() const { return PP; }
269 Sema &getActions() const { return Actions; }
270 AttributeFactory &getAttrFactory() { return AttrFactory; }
272 const Token &getCurToken() const { return Tok; }
273 Scope *getCurScope() const { return Actions.getCurScope(); }
274 void incrementMSManglingNumber() const {
275 return Actions.incrementMSManglingNumber();
278 Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); }
280 // Type forwarding. All of these are statically 'void*', but they may all be
281 // different actual classes based on the actions in place.
282 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
283 typedef OpaquePtr<TemplateName> TemplateTy;
285 typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists;
287 typedef Sema::FullExprArg FullExprArg;
291 /// Initialize - Warm up the parser.
295 /// Parse the first top-level declaration in a translation unit.
296 bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result);
298 /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if
299 /// the EOF was encountered.
300 bool ParseTopLevelDecl(DeclGroupPtrTy &Result);
301 bool ParseTopLevelDecl() {
302 DeclGroupPtrTy Result;
303 return ParseTopLevelDecl(Result);
306 /// ConsumeToken - Consume the current 'peek token' and lex the next one.
307 /// This does not work with special tokens: string literals, code completion,
308 /// annotation tokens and balanced tokens must be handled using the specific
310 /// Returns the location of the consumed token.
311 SourceLocation ConsumeToken() {
312 assert(!isTokenSpecial() &&
313 "Should consume special tokens with Consume*Token");
314 PrevTokLocation = Tok.getLocation();
316 return PrevTokLocation;
319 bool TryConsumeToken(tok::TokenKind Expected) {
320 if (Tok.isNot(Expected))
322 assert(!isTokenSpecial() &&
323 "Should consume special tokens with Consume*Token");
324 PrevTokLocation = Tok.getLocation();
329 bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) {
330 if (!TryConsumeToken(Expected))
332 Loc = PrevTokLocation;
336 SourceLocation getEndOfPreviousToken() {
337 return PP.getLocForEndOfToken(PrevTokLocation);
340 /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds
341 /// to the given nullability kind.
342 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) {
343 return Actions.getNullabilityKeyword(nullability);
347 //===--------------------------------------------------------------------===//
348 // Low-Level token peeking and consumption methods.
351 /// isTokenParen - Return true if the cur token is '(' or ')'.
352 bool isTokenParen() const {
353 return Tok.getKind() == tok::l_paren || Tok.getKind() == tok::r_paren;
355 /// isTokenBracket - Return true if the cur token is '[' or ']'.
356 bool isTokenBracket() const {
357 return Tok.getKind() == tok::l_square || Tok.getKind() == tok::r_square;
359 /// isTokenBrace - Return true if the cur token is '{' or '}'.
360 bool isTokenBrace() const {
361 return Tok.getKind() == tok::l_brace || Tok.getKind() == tok::r_brace;
363 /// isTokenStringLiteral - True if this token is a string-literal.
364 bool isTokenStringLiteral() const {
365 return tok::isStringLiteral(Tok.getKind());
367 /// isTokenSpecial - True if this token requires special consumption methods.
368 bool isTokenSpecial() const {
369 return isTokenStringLiteral() || isTokenParen() || isTokenBracket() ||
370 isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation();
373 /// \brief Returns true if the current token is '=' or is a type of '='.
374 /// For typos, give a fixit to '='
375 bool isTokenEqualOrEqualTypo();
377 /// \brief Return the current token to the token stream and make the given
378 /// token the current token.
379 void UnconsumeToken(Token &Consumed) {
381 PP.EnterToken(Consumed);
386 /// ConsumeAnyToken - Dispatch to the right Consume* method based on the
387 /// current token type. This should only be used in cases where the type of
388 /// the token really isn't known, e.g. in error recovery.
389 SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) {
391 return ConsumeParen();
392 if (isTokenBracket())
393 return ConsumeBracket();
395 return ConsumeBrace();
396 if (isTokenStringLiteral())
397 return ConsumeStringToken();
398 if (Tok.is(tok::code_completion))
399 return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken()
400 : handleUnexpectedCodeCompletionToken();
401 if (Tok.isAnnotation())
402 return ConsumeAnnotationToken();
403 return ConsumeToken();
406 SourceLocation ConsumeAnnotationToken() {
407 assert(Tok.isAnnotation() && "wrong consume method");
408 SourceLocation Loc = Tok.getLocation();
409 PrevTokLocation = Tok.getAnnotationEndLoc();
414 /// ConsumeParen - This consume method keeps the paren count up-to-date.
416 SourceLocation ConsumeParen() {
417 assert(isTokenParen() && "wrong consume method");
418 if (Tok.getKind() == tok::l_paren)
421 --ParenCount; // Don't let unbalanced )'s drive the count negative.
422 PrevTokLocation = Tok.getLocation();
424 return PrevTokLocation;
427 /// ConsumeBracket - This consume method keeps the bracket count up-to-date.
429 SourceLocation ConsumeBracket() {
430 assert(isTokenBracket() && "wrong consume method");
431 if (Tok.getKind() == tok::l_square)
433 else if (BracketCount)
434 --BracketCount; // Don't let unbalanced ]'s drive the count negative.
436 PrevTokLocation = Tok.getLocation();
438 return PrevTokLocation;
441 /// ConsumeBrace - This consume method keeps the brace count up-to-date.
443 SourceLocation ConsumeBrace() {
444 assert(isTokenBrace() && "wrong consume method");
445 if (Tok.getKind() == tok::l_brace)
448 --BraceCount; // Don't let unbalanced }'s drive the count negative.
450 PrevTokLocation = Tok.getLocation();
452 return PrevTokLocation;
455 /// ConsumeStringToken - Consume the current 'peek token', lexing a new one
456 /// and returning the token kind. This method is specific to strings, as it
457 /// handles string literal concatenation, as per C99 5.1.1.2, translation
459 SourceLocation ConsumeStringToken() {
460 assert(isTokenStringLiteral() &&
461 "Should only consume string literals with this method");
462 PrevTokLocation = Tok.getLocation();
464 return PrevTokLocation;
467 /// \brief Consume the current code-completion token.
469 /// This routine can be called to consume the code-completion token and
470 /// continue processing in special cases where \c cutOffParsing() isn't
471 /// desired, such as token caching or completion with lookahead.
472 SourceLocation ConsumeCodeCompletionToken() {
473 assert(Tok.is(tok::code_completion));
474 PrevTokLocation = Tok.getLocation();
476 return PrevTokLocation;
479 ///\ brief When we are consuming a code-completion token without having
480 /// matched specific position in the grammar, provide code-completion results
481 /// based on context.
483 /// \returns the source location of the code-completion token.
484 SourceLocation handleUnexpectedCodeCompletionToken();
486 /// \brief Abruptly cut off parsing; mainly used when we have reached the
487 /// code-completion point.
488 void cutOffParsing() {
489 if (PP.isCodeCompletionEnabled())
490 PP.setCodeCompletionReached();
491 // Cut off parsing by acting as if we reached the end-of-file.
492 Tok.setKind(tok::eof);
495 /// \brief Determine if we're at the end of the file or at a transition
498 tok::TokenKind Kind = Tok.getKind();
499 return Kind == tok::eof || Kind == tok::annot_module_begin ||
500 Kind == tok::annot_module_end || Kind == tok::annot_module_include;
503 /// \brief Initialize all pragma handlers.
504 void initializePragmaHandlers();
506 /// \brief Destroy and reset all pragma handlers.
507 void resetPragmaHandlers();
509 /// \brief Handle the annotation token produced for #pragma unused(...)
510 void HandlePragmaUnused();
512 /// \brief Handle the annotation token produced for
513 /// #pragma GCC visibility...
514 void HandlePragmaVisibility();
516 /// \brief Handle the annotation token produced for
518 void HandlePragmaPack();
520 /// \brief Handle the annotation token produced for
521 /// #pragma ms_struct...
522 void HandlePragmaMSStruct();
524 /// \brief Handle the annotation token produced for
525 /// #pragma comment...
526 void HandlePragmaMSComment();
528 void HandlePragmaMSPointersToMembers();
530 void HandlePragmaMSVtorDisp();
532 void HandlePragmaMSPragma();
533 bool HandlePragmaMSSection(StringRef PragmaName,
534 SourceLocation PragmaLocation);
535 bool HandlePragmaMSSegment(StringRef PragmaName,
536 SourceLocation PragmaLocation);
537 bool HandlePragmaMSInitSeg(StringRef PragmaName,
538 SourceLocation PragmaLocation);
540 /// \brief Handle the annotation token produced for
542 void HandlePragmaAlign();
544 /// \brief Handle the annotation token produced for
545 /// #pragma clang __debug dump...
546 void HandlePragmaDump();
548 /// \brief Handle the annotation token produced for
549 /// #pragma weak id...
550 void HandlePragmaWeak();
552 /// \brief Handle the annotation token produced for
553 /// #pragma weak id = id...
554 void HandlePragmaWeakAlias();
556 /// \brief Handle the annotation token produced for
557 /// #pragma redefine_extname...
558 void HandlePragmaRedefineExtname();
560 /// \brief Handle the annotation token produced for
561 /// #pragma STDC FP_CONTRACT...
562 void HandlePragmaFPContract();
564 /// \brief Handle the annotation token produced for
565 /// #pragma clang fp ...
566 void HandlePragmaFP();
568 /// \brief Handle the annotation token produced for
569 /// #pragma OPENCL EXTENSION...
570 void HandlePragmaOpenCLExtension();
572 /// \brief Handle the annotation token produced for
573 /// #pragma clang __debug captured
574 StmtResult HandlePragmaCaptured();
576 /// \brief Handle the annotation token produced for
577 /// #pragma clang loop and #pragma unroll.
578 bool HandlePragmaLoopHint(LoopHint &Hint);
580 bool ParsePragmaAttributeSubjectMatchRuleSet(
581 attr::ParsedSubjectMatchRuleSet &SubjectMatchRules,
582 SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc);
584 void HandlePragmaAttribute();
586 /// GetLookAheadToken - This peeks ahead N tokens and returns that token
587 /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1)
588 /// returns the token after Tok, etc.
590 /// Note that this differs from the Preprocessor's LookAhead method, because
591 /// the Parser always has one token lexed that the preprocessor doesn't.
593 const Token &GetLookAheadToken(unsigned N) {
594 if (N == 0 || Tok.is(tok::eof)) return Tok;
595 return PP.LookAhead(N-1);
599 /// NextToken - This peeks ahead one token and returns it without
601 const Token &NextToken() {
602 return PP.LookAhead(0);
605 /// getTypeAnnotation - Read a parsed type out of an annotation token.
606 static ParsedType getTypeAnnotation(Token &Tok) {
607 return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
611 static void setTypeAnnotation(Token &Tok, ParsedType T) {
612 Tok.setAnnotationValue(T.getAsOpaquePtr());
615 /// \brief Read an already-translated primary expression out of an annotation
617 static ExprResult getExprAnnotation(Token &Tok) {
618 return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue());
621 /// \brief Set the primary expression corresponding to the given annotation
623 static void setExprAnnotation(Token &Tok, ExprResult ER) {
624 Tok.setAnnotationValue(ER.getAsOpaquePointer());
628 // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to
629 // find a type name by attempting typo correction.
630 bool TryAnnotateTypeOrScopeToken();
631 bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS,
633 bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
636 enum AnnotatedNameKind {
637 /// Annotation has failed and emitted an error.
639 /// The identifier is a tentatively-declared name.
641 /// The identifier is a template name. FIXME: Add an annotation for that.
643 /// The identifier can't be resolved.
645 /// Annotation was successful.
649 TryAnnotateName(bool IsAddressOfOperand,
650 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
652 /// Push a tok::annot_cxxscope token onto the token stream.
653 void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
655 /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
656 /// replacing them with the non-context-sensitive keywords. This returns
657 /// true if the token was replaced.
658 bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
659 const char *&PrevSpec, unsigned &DiagID,
661 if (!getLangOpts().AltiVec && !getLangOpts().ZVector)
664 if (Tok.getIdentifierInfo() != Ident_vector &&
665 Tok.getIdentifierInfo() != Ident_bool &&
666 (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel))
669 return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
672 /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
673 /// identifier token, replacing it with the non-context-sensitive __vector.
674 /// This returns true if the token was replaced.
675 bool TryAltiVecVectorToken() {
676 if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) ||
677 Tok.getIdentifierInfo() != Ident_vector) return false;
678 return TryAltiVecVectorTokenOutOfLine();
681 bool TryAltiVecVectorTokenOutOfLine();
682 bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
683 const char *&PrevSpec, unsigned &DiagID,
686 /// Returns true if the current token is the identifier 'instancetype'.
688 /// Should only be used in Objective-C language modes.
689 bool isObjCInstancetype() {
690 assert(getLangOpts().ObjC1);
691 if (Tok.isAnnotation())
693 if (!Ident_instancetype)
694 Ident_instancetype = PP.getIdentifierInfo("instancetype");
695 return Tok.getIdentifierInfo() == Ident_instancetype;
698 /// TryKeywordIdentFallback - For compatibility with system headers using
699 /// keywords as identifiers, attempt to convert the current token to an
700 /// identifier and optionally disable the keyword for the remainder of the
701 /// translation unit. This returns false if the token was not replaced,
702 /// otherwise emits a diagnostic and returns true.
703 bool TryKeywordIdentFallback(bool DisableKeyword);
705 /// \brief Get the TemplateIdAnnotation from the token.
706 TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
708 /// TentativeParsingAction - An object that is used as a kind of "tentative
709 /// parsing transaction". It gets instantiated to mark the token position and
710 /// after the token consumption is done, Commit() or Revert() is called to
711 /// either "commit the consumed tokens" or revert to the previously marked
712 /// token position. Example:
714 /// TentativeParsingAction TPA(*this);
719 class TentativeParsingAction {
722 size_t PrevTentativelyDeclaredIdentifierCount;
723 unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
727 explicit TentativeParsingAction(Parser& p) : P(p) {
729 PrevTentativelyDeclaredIdentifierCount =
730 P.TentativelyDeclaredIdentifiers.size();
731 PrevParenCount = P.ParenCount;
732 PrevBracketCount = P.BracketCount;
733 PrevBraceCount = P.BraceCount;
734 P.PP.EnableBacktrackAtThisPos();
738 assert(isActive && "Parsing action was finished!");
739 P.TentativelyDeclaredIdentifiers.resize(
740 PrevTentativelyDeclaredIdentifierCount);
741 P.PP.CommitBacktrackedTokens();
745 assert(isActive && "Parsing action was finished!");
748 P.TentativelyDeclaredIdentifiers.resize(
749 PrevTentativelyDeclaredIdentifierCount);
750 P.ParenCount = PrevParenCount;
751 P.BracketCount = PrevBracketCount;
752 P.BraceCount = PrevBraceCount;
755 ~TentativeParsingAction() {
756 assert(!isActive && "Forgot to call Commit or Revert!");
759 /// A TentativeParsingAction that automatically reverts in its destructor.
760 /// Useful for disambiguation parses that will always be reverted.
761 class RevertingTentativeParsingAction
762 : private Parser::TentativeParsingAction {
764 RevertingTentativeParsingAction(Parser &P)
765 : Parser::TentativeParsingAction(P) {}
766 ~RevertingTentativeParsingAction() { Revert(); }
769 class UnannotatedTentativeParsingAction;
771 /// ObjCDeclContextSwitch - An object used to switch context from
772 /// an objective-c decl context to its enclosing decl context and
774 class ObjCDeclContextSwitch {
777 SaveAndRestore<bool> WithinObjCContainer;
779 explicit ObjCDeclContextSwitch(Parser &p)
780 : P(p), DC(p.getObjCDeclContext()),
781 WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) {
783 P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC));
785 ~ObjCDeclContextSwitch() {
787 P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC));
791 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
792 /// input. If so, it is consumed and false is returned.
794 /// If a trivial punctuator misspelling is encountered, a FixIt error
795 /// diagnostic is issued and false is returned after recovery.
797 /// If the input is malformed, this emits the specified diagnostic and true is
799 bool ExpectAndConsume(tok::TokenKind ExpectedTok,
800 unsigned Diag = diag::err_expected,
801 StringRef DiagMsg = "");
803 /// \brief The parser expects a semicolon and, if present, will consume it.
805 /// If the next token is not a semicolon, this emits the specified diagnostic,
806 /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
807 /// to the semicolon, consumes that extra token.
808 bool ExpectAndConsumeSemi(unsigned DiagID);
810 /// \brief The kind of extra semi diagnostic to emit.
814 InstanceVariableList = 2,
815 AfterMemberFunctionDefinition = 3
818 /// \brief Consume any extra semi-colons until the end of the line.
819 void ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST = TST_unspecified);
821 /// Return false if the next token is an identifier. An 'expected identifier'
822 /// error is emitted otherwise.
824 /// The parser tries to recover from the error by checking if the next token
825 /// is a C++ keyword when parsing Objective-C++. Return false if the recovery
827 bool expectIdentifier();
830 //===--------------------------------------------------------------------===//
831 // Scope manipulation
833 /// ParseScope - Introduces a new scope for parsing. The kind of
834 /// scope is determined by ScopeFlags. Objects of this type should
835 /// be created on the stack to coincide with the position where the
836 /// parser enters the new scope, and this object's constructor will
837 /// create that new scope. Similarly, once the object is destroyed
838 /// the parser will exit the scope.
841 ParseScope(const ParseScope &) = delete;
842 void operator=(const ParseScope &) = delete;
845 // ParseScope - Construct a new object to manage a scope in the
846 // parser Self where the new Scope is created with the flags
847 // ScopeFlags, but only when we aren't about to enter a compound statement.
848 ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true,
849 bool BeforeCompoundStmt = false)
851 if (EnteredScope && !BeforeCompoundStmt)
852 Self->EnterScope(ScopeFlags);
854 if (BeforeCompoundStmt)
855 Self->incrementMSManglingNumber();
857 this->Self = nullptr;
861 // Exit - Exit the scope associated with this object now, rather
862 // than waiting until the object is destroyed.
875 /// EnterScope - Start a new scope.
876 void EnterScope(unsigned ScopeFlags);
878 /// ExitScope - Pop a scope off the scope stack.
882 /// \brief RAII object used to modify the scope flags for the current scope.
883 class ParseScopeFlags {
886 ParseScopeFlags(const ParseScopeFlags &) = delete;
887 void operator=(const ParseScopeFlags &) = delete;
890 ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
894 //===--------------------------------------------------------------------===//
895 // Diagnostic Emission and Error recovery.
898 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
899 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
900 DiagnosticBuilder Diag(unsigned DiagID) {
901 return Diag(Tok, DiagID);
905 void SuggestParentheses(SourceLocation Loc, unsigned DK,
906 SourceRange ParenRange);
907 void CheckNestedObjCContexts(SourceLocation AtLoc);
911 /// \brief Control flags for SkipUntil functions.
912 enum SkipUntilFlags {
913 StopAtSemi = 1 << 0, ///< Stop skipping at semicolon
914 /// \brief Stop skipping at specified token, but don't skip the token itself
915 StopBeforeMatch = 1 << 1,
916 StopAtCodeCompletion = 1 << 2 ///< Stop at code completion
919 friend constexpr SkipUntilFlags operator|(SkipUntilFlags L,
921 return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) |
922 static_cast<unsigned>(R));
925 /// SkipUntil - Read tokens until we get to the specified token, then consume
926 /// it (unless StopBeforeMatch is specified). Because we cannot guarantee
927 /// that the token will ever occur, this skips to the next token, or to some
928 /// likely good stopping point. If Flags has StopAtSemi flag, skipping will
929 /// stop at a ';' character.
931 /// If SkipUntil finds the specified token, it returns true, otherwise it
933 bool SkipUntil(tok::TokenKind T,
934 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
935 return SkipUntil(llvm::makeArrayRef(T), Flags);
937 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2,
938 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
939 tok::TokenKind TokArray[] = {T1, T2};
940 return SkipUntil(TokArray, Flags);
942 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3,
943 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
944 tok::TokenKind TokArray[] = {T1, T2, T3};
945 return SkipUntil(TokArray, Flags);
947 bool SkipUntil(ArrayRef<tok::TokenKind> Toks,
948 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0));
950 /// SkipMalformedDecl - Read tokens until we get to some likely good stopping
951 /// point for skipping past a simple-declaration.
952 void SkipMalformedDecl();
955 //===--------------------------------------------------------------------===//
956 // Lexing and parsing of C++ inline methods.
960 /// [class.mem]p1: "... the class is regarded as complete within
961 /// - function bodies
962 /// - default arguments
963 /// - exception-specifications (TODO: C++0x)
964 /// - and brace-or-equal-initializers for non-static data members
965 /// (including such things in nested classes)."
966 /// LateParsedDeclarations build the tree of those elements so they can
967 /// be parsed after parsing the top-level class.
968 class LateParsedDeclaration {
970 virtual ~LateParsedDeclaration();
972 virtual void ParseLexedMethodDeclarations();
973 virtual void ParseLexedMemberInitializers();
974 virtual void ParseLexedMethodDefs();
975 virtual void ParseLexedAttributes();
978 /// Inner node of the LateParsedDeclaration tree that parses
979 /// all its members recursively.
980 class LateParsedClass : public LateParsedDeclaration {
982 LateParsedClass(Parser *P, ParsingClass *C);
983 ~LateParsedClass() override;
985 void ParseLexedMethodDeclarations() override;
986 void ParseLexedMemberInitializers() override;
987 void ParseLexedMethodDefs() override;
988 void ParseLexedAttributes() override;
995 /// Contains the lexed tokens of an attribute with arguments that
996 /// may reference member variables and so need to be parsed at the
997 /// end of the class declaration after parsing all other member
998 /// member declarations.
999 /// FIXME: Perhaps we should change the name of LateParsedDeclaration to
1000 /// LateParsedTokens.
1001 struct LateParsedAttribute : public LateParsedDeclaration {
1004 IdentifierInfo &AttrName;
1005 SourceLocation AttrNameLoc;
1006 SmallVector<Decl*, 2> Decls;
1008 explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
1010 : Self(P), AttrName(Name), AttrNameLoc(Loc) {}
1012 void ParseLexedAttributes() override;
1014 void addDecl(Decl *D) { Decls.push_back(D); }
1017 // A list of late-parsed attributes. Used by ParseGNUAttributes.
1018 class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> {
1020 LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { }
1022 bool parseSoon() { return ParseSoon; }
1025 bool ParseSoon; // Are we planning to parse these shortly after creation?
1028 /// Contains the lexed tokens of a member function definition
1029 /// which needs to be parsed at the end of the class declaration
1030 /// after parsing all other member declarations.
1031 struct LexedMethod : public LateParsedDeclaration {
1036 /// \brief Whether this member function had an associated template
1037 /// scope. When true, D is a template declaration.
1038 /// otherwise, it is a member function declaration.
1041 explicit LexedMethod(Parser* P, Decl *MD)
1042 : Self(P), D(MD), TemplateScope(false) {}
1044 void ParseLexedMethodDefs() override;
1047 /// LateParsedDefaultArgument - Keeps track of a parameter that may
1048 /// have a default argument that cannot be parsed yet because it
1049 /// occurs within a member function declaration inside the class
1050 /// (C++ [class.mem]p2).
1051 struct LateParsedDefaultArgument {
1052 explicit LateParsedDefaultArgument(Decl *P,
1053 std::unique_ptr<CachedTokens> Toks = nullptr)
1054 : Param(P), Toks(std::move(Toks)) { }
1056 /// Param - The parameter declaration for this parameter.
1059 /// Toks - The sequence of tokens that comprises the default
1060 /// argument expression, not including the '=' or the terminating
1061 /// ')' or ','. This will be NULL for parameters that have no
1062 /// default argument.
1063 std::unique_ptr<CachedTokens> Toks;
1066 /// LateParsedMethodDeclaration - A method declaration inside a class that
1067 /// contains at least one entity whose parsing needs to be delayed
1068 /// until the class itself is completely-defined, such as a default
1069 /// argument (C++ [class.mem]p2).
1070 struct LateParsedMethodDeclaration : public LateParsedDeclaration {
1071 explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
1072 : Self(P), Method(M), TemplateScope(false),
1073 ExceptionSpecTokens(nullptr) {}
1075 void ParseLexedMethodDeclarations() override;
1079 /// Method - The method declaration.
1082 /// \brief Whether this member function had an associated template
1083 /// scope. When true, D is a template declaration.
1084 /// othewise, it is a member function declaration.
1087 /// DefaultArgs - Contains the parameters of the function and
1088 /// their default arguments. At least one of the parameters will
1089 /// have a default argument, but all of the parameters of the
1090 /// method will be stored so that they can be reintroduced into
1091 /// scope at the appropriate times.
1092 SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
1094 /// \brief The set of tokens that make up an exception-specification that
1095 /// has not yet been parsed.
1096 CachedTokens *ExceptionSpecTokens;
1099 /// LateParsedMemberInitializer - An initializer for a non-static class data
1100 /// member whose parsing must to be delayed until the class is completely
1101 /// defined (C++11 [class.mem]p2).
1102 struct LateParsedMemberInitializer : public LateParsedDeclaration {
1103 LateParsedMemberInitializer(Parser *P, Decl *FD)
1104 : Self(P), Field(FD) { }
1106 void ParseLexedMemberInitializers() override;
1110 /// Field - The field declaration.
1113 /// CachedTokens - The sequence of tokens that comprises the initializer,
1114 /// including any leading '='.
1118 /// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
1119 /// C++ class, its method declarations that contain parts that won't be
1120 /// parsed until after the definition is completed (C++ [class.mem]p2),
1121 /// the method declarations and possibly attached inline definitions
1122 /// will be stored here with the tokens that will be parsed to create those
1124 typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer;
1126 /// \brief Representation of a class that has been parsed, including
1127 /// any member function declarations or definitions that need to be
1128 /// parsed after the corresponding top-level class is complete.
1129 struct ParsingClass {
1130 ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface)
1131 : TopLevelClass(TopLevelClass), TemplateScope(false),
1132 IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) { }
1134 /// \brief Whether this is a "top-level" class, meaning that it is
1135 /// not nested within another class.
1136 bool TopLevelClass : 1;
1138 /// \brief Whether this class had an associated template
1139 /// scope. When true, TagOrTemplate is a template declaration;
1140 /// othewise, it is a tag declaration.
1141 bool TemplateScope : 1;
1143 /// \brief Whether this class is an __interface.
1144 bool IsInterface : 1;
1146 /// \brief The class or class template whose definition we are parsing.
1147 Decl *TagOrTemplate;
1149 /// LateParsedDeclarations - Method declarations, inline definitions and
1150 /// nested classes that contain pieces whose parsing will be delayed until
1151 /// the top-level class is fully defined.
1152 LateParsedDeclarationsContainer LateParsedDeclarations;
1155 /// \brief The stack of classes that is currently being
1156 /// parsed. Nested and local classes will be pushed onto this stack
1157 /// when they are parsed, and removed afterward.
1158 std::stack<ParsingClass *> ClassStack;
1160 ParsingClass &getCurrentClass() {
1161 assert(!ClassStack.empty() && "No lexed method stacks!");
1162 return *ClassStack.top();
1165 /// \brief RAII object used to manage the parsing of a class definition.
1166 class ParsingClassDefinition {
1169 Sema::ParsingClassState State;
1172 ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass,
1174 : P(P), Popped(false),
1175 State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
1178 /// \brief Pop this class of the stack.
1180 assert(!Popped && "Nested class has already been popped");
1182 P.PopParsingClass(State);
1185 ~ParsingClassDefinition() {
1187 P.PopParsingClass(State);
1191 /// \brief Contains information about any template-specific
1192 /// information that has been parsed prior to parsing declaration
1194 struct ParsedTemplateInfo {
1195 ParsedTemplateInfo()
1196 : Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { }
1198 ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
1199 bool isSpecialization,
1200 bool lastParameterListWasEmpty = false)
1201 : Kind(isSpecialization? ExplicitSpecialization : Template),
1202 TemplateParams(TemplateParams),
1203 LastParameterListWasEmpty(lastParameterListWasEmpty) { }
1205 explicit ParsedTemplateInfo(SourceLocation ExternLoc,
1206 SourceLocation TemplateLoc)
1207 : Kind(ExplicitInstantiation), TemplateParams(nullptr),
1208 ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
1209 LastParameterListWasEmpty(false){ }
1211 /// \brief The kind of template we are parsing.
1213 /// \brief We are not parsing a template at all.
1215 /// \brief We are parsing a template declaration.
1217 /// \brief We are parsing an explicit specialization.
1218 ExplicitSpecialization,
1219 /// \brief We are parsing an explicit instantiation.
1220 ExplicitInstantiation
1223 /// \brief The template parameter lists, for template declarations
1224 /// and explicit specializations.
1225 TemplateParameterLists *TemplateParams;
1227 /// \brief The location of the 'extern' keyword, if any, for an explicit
1229 SourceLocation ExternLoc;
1231 /// \brief The location of the 'template' keyword, for an explicit
1233 SourceLocation TemplateLoc;
1235 /// \brief Whether the last template parameter list was empty.
1236 bool LastParameterListWasEmpty;
1238 SourceRange getSourceRange() const LLVM_READONLY;
1241 void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
1242 void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
1244 static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
1245 static void LateTemplateParserCleanupCallback(void *P);
1247 Sema::ParsingClassState
1248 PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface);
1249 void DeallocateParsedClasses(ParsingClass *Class);
1250 void PopParsingClass(Sema::ParsingClassState);
1252 enum CachedInitKind {
1253 CIK_DefaultArgument,
1254 CIK_DefaultInitializer
1257 NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS,
1258 AttributeList *AccessAttrs,
1259 ParsingDeclarator &D,
1260 const ParsedTemplateInfo &TemplateInfo,
1261 const VirtSpecifiers& VS,
1262 SourceLocation PureSpecLoc);
1263 void ParseCXXNonStaticMemberInitializer(Decl *VarD);
1264 void ParseLexedAttributes(ParsingClass &Class);
1265 void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1266 bool EnterScope, bool OnDefinition);
1267 void ParseLexedAttribute(LateParsedAttribute &LA,
1268 bool EnterScope, bool OnDefinition);
1269 void ParseLexedMethodDeclarations(ParsingClass &Class);
1270 void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
1271 void ParseLexedMethodDefs(ParsingClass &Class);
1272 void ParseLexedMethodDef(LexedMethod &LM);
1273 void ParseLexedMemberInitializers(ParsingClass &Class);
1274 void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
1275 void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod);
1276 bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
1277 bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK);
1278 bool ConsumeAndStoreConditional(CachedTokens &Toks);
1279 bool ConsumeAndStoreUntil(tok::TokenKind T1,
1281 bool StopAtSemi = true,
1282 bool ConsumeFinalToken = true) {
1283 return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
1285 bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
1287 bool StopAtSemi = true,
1288 bool ConsumeFinalToken = true);
1290 //===--------------------------------------------------------------------===//
1291 // C99 6.9: External Definitions.
1292 struct ParsedAttributesWithRange : ParsedAttributes {
1293 ParsedAttributesWithRange(AttributeFactory &factory)
1294 : ParsedAttributes(factory) {}
1297 ParsedAttributes::clear();
1298 Range = SourceRange();
1304 DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
1305 ParsingDeclSpec *DS = nullptr);
1306 bool isDeclarationAfterDeclarator();
1307 bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
1308 DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(
1309 ParsedAttributesWithRange &attrs,
1310 ParsingDeclSpec *DS = nullptr,
1311 AccessSpecifier AS = AS_none);
1312 DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
1313 ParsingDeclSpec &DS,
1314 AccessSpecifier AS);
1316 void SkipFunctionBody();
1317 Decl *ParseFunctionDefinition(ParsingDeclarator &D,
1318 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1319 LateParsedAttrList *LateParsedAttrs = nullptr);
1320 void ParseKNRParamDeclarations(Declarator &D);
1321 // EndLoc, if non-NULL, is filled with the location of the last token of
1323 ExprResult ParseSimpleAsm(SourceLocation *EndLoc = nullptr);
1324 ExprResult ParseAsmStringLiteral();
1326 // Objective-C External Declarations
1327 void MaybeSkipAttributes(tok::ObjCKeywordKind Kind);
1328 DeclGroupPtrTy ParseObjCAtDirectives();
1329 DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
1330 Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
1331 ParsedAttributes &prefixAttrs);
1332 class ObjCTypeParamListScope;
1333 ObjCTypeParamList *parseObjCTypeParamList();
1334 ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs(
1335 ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
1336 SmallVectorImpl<IdentifierLocPair> &protocolIdents,
1337 SourceLocation &rAngleLoc, bool mayBeProtocolList = true);
1339 void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
1340 BalancedDelimiterTracker &T,
1341 SmallVectorImpl<Decl *> &AllIvarDecls,
1342 bool RBraceMissing);
1343 void ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1344 tok::ObjCKeywordKind visibility,
1345 SourceLocation atLoc);
1346 bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P,
1347 SmallVectorImpl<SourceLocation> &PLocs,
1348 bool WarnOnDeclarations,
1349 bool ForObjCContainer,
1350 SourceLocation &LAngleLoc,
1351 SourceLocation &EndProtoLoc,
1352 bool consumeLastToken);
1354 /// Parse the first angle-bracket-delimited clause for an
1355 /// Objective-C object or object pointer type, which may be either
1356 /// type arguments or protocol qualifiers.
1357 void parseObjCTypeArgsOrProtocolQualifiers(
1358 ParsedType baseType,
1359 SourceLocation &typeArgsLAngleLoc,
1360 SmallVectorImpl<ParsedType> &typeArgs,
1361 SourceLocation &typeArgsRAngleLoc,
1362 SourceLocation &protocolLAngleLoc,
1363 SmallVectorImpl<Decl *> &protocols,
1364 SmallVectorImpl<SourceLocation> &protocolLocs,
1365 SourceLocation &protocolRAngleLoc,
1366 bool consumeLastToken,
1367 bool warnOnIncompleteProtocols);
1369 /// Parse either Objective-C type arguments or protocol qualifiers; if the
1370 /// former, also parse protocol qualifiers afterward.
1371 void parseObjCTypeArgsAndProtocolQualifiers(
1372 ParsedType baseType,
1373 SourceLocation &typeArgsLAngleLoc,
1374 SmallVectorImpl<ParsedType> &typeArgs,
1375 SourceLocation &typeArgsRAngleLoc,
1376 SourceLocation &protocolLAngleLoc,
1377 SmallVectorImpl<Decl *> &protocols,
1378 SmallVectorImpl<SourceLocation> &protocolLocs,
1379 SourceLocation &protocolRAngleLoc,
1380 bool consumeLastToken);
1382 /// Parse a protocol qualifier type such as '<NSCopying>', which is
1383 /// an anachronistic way of writing 'id<NSCopying>'.
1384 TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc);
1386 /// Parse Objective-C type arguments and protocol qualifiers, extending the
1387 /// current type with the parsed result.
1388 TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc,
1390 bool consumeLastToken,
1391 SourceLocation &endLoc);
1393 void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
1395 DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
1396 ParsedAttributes &prefixAttrs);
1398 struct ObjCImplParsingDataRAII {
1402 typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer;
1403 LateParsedObjCMethodContainer LateParsedObjCMethods;
1405 ObjCImplParsingDataRAII(Parser &parser, Decl *D)
1406 : P(parser), Dcl(D), HasCFunction(false) {
1407 P.CurParsedObjCImpl = this;
1410 ~ObjCImplParsingDataRAII();
1412 void finish(SourceRange AtEnd);
1413 bool isFinished() const { return Finished; }
1418 ObjCImplParsingDataRAII *CurParsedObjCImpl;
1419 void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl);
1421 DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc);
1422 DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
1423 Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
1424 Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
1425 Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
1427 IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
1428 // Definitions for Objective-c context sensitive keywords recognition.
1430 objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
1431 objc_nonnull, objc_nullable, objc_null_unspecified,
1434 IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
1436 bool isTokIdentifier_in() const;
1438 ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, Declarator::TheContext Ctx,
1439 ParsedAttributes *ParamAttrs);
1440 void ParseObjCMethodRequirement();
1441 Decl *ParseObjCMethodPrototype(
1442 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1443 bool MethodDefinition = true);
1444 Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
1445 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1446 bool MethodDefinition=true);
1447 void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
1449 Decl *ParseObjCMethodDefinition();
1452 //===--------------------------------------------------------------------===//
1453 // C99 6.5: Expressions.
1455 /// TypeCastState - State whether an expression is or may be a type cast.
1456 enum TypeCastState {
1462 ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast);
1463 ExprResult ParseConstantExpressionInExprEvalContext(TypeCastState isTypeCast);
1464 ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast);
1465 ExprResult ParseConstraintExpression();
1466 // Expr that doesn't include commas.
1467 ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast);
1469 ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1470 unsigned &NumLineToksConsumed,
1472 bool IsUnevaluated);
1475 ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
1477 ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
1479 ExprResult ParseRHSOfBinaryExpression(ExprResult LHS,
1480 prec::Level MinPrec);
1481 ExprResult ParseCastExpression(bool isUnaryExpression,
1482 bool isAddressOfOperand,
1484 TypeCastState isTypeCast,
1485 bool isVectorLiteral = false);
1486 ExprResult ParseCastExpression(bool isUnaryExpression,
1487 bool isAddressOfOperand = false,
1488 TypeCastState isTypeCast = NotTypeCast,
1489 bool isVectorLiteral = false);
1491 /// Returns true if the next token cannot start an expression.
1492 bool isNotExpressionStart();
1494 /// Returns true if the next token would start a postfix-expression
1496 bool isPostfixExpressionSuffixStart() {
1497 tok::TokenKind K = Tok.getKind();
1498 return (K == tok::l_square || K == tok::l_paren ||
1499 K == tok::period || K == tok::arrow ||
1500 K == tok::plusplus || K == tok::minusminus);
1503 bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less);
1505 ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
1506 ExprResult ParseUnaryExprOrTypeTraitExpression();
1507 ExprResult ParseBuiltinPrimaryExpression();
1509 ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1512 SourceRange &CastRange);
1514 typedef SmallVector<Expr*, 20> ExprListTy;
1515 typedef SmallVector<SourceLocation, 20> CommaLocsTy;
1517 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1518 bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
1519 SmallVectorImpl<SourceLocation> &CommaLocs,
1520 std::function<void()> Completer = nullptr);
1522 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
1523 /// used for misc language extensions.
1524 bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
1525 SmallVectorImpl<SourceLocation> &CommaLocs);
1528 /// ParenParseOption - Control what ParseParenExpression will parse.
1529 enum ParenParseOption {
1530 SimpleExpr, // Only parse '(' expression ')'
1531 CompoundStmt, // Also allow '(' compound-statement ')'
1532 CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
1533 CastExpr // Also allow '(' type-name ')' <anything>
1535 ExprResult ParseParenExpression(ParenParseOption &ExprType,
1536 bool stopIfCastExpr,
1539 SourceLocation &RParenLoc);
1541 ExprResult ParseCXXAmbiguousParenExpression(
1542 ParenParseOption &ExprType, ParsedType &CastTy,
1543 BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt);
1544 ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
1545 SourceLocation LParenLoc,
1546 SourceLocation RParenLoc);
1548 ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
1550 ExprResult ParseGenericSelectionExpression();
1552 ExprResult ParseObjCBoolLiteral();
1554 ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T);
1556 //===--------------------------------------------------------------------===//
1558 ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
1559 Token &Replacement);
1560 ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
1562 bool areTokensAdjacent(const Token &A, const Token &B);
1564 void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
1565 bool EnteringContext, IdentifierInfo &II,
1568 bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
1569 ParsedType ObjectType,
1570 bool EnteringContext,
1571 bool *MayBePseudoDestructor = nullptr,
1572 bool IsTypename = false,
1573 IdentifierInfo **LastII = nullptr,
1574 bool OnlyNamespace = false);
1576 //===--------------------------------------------------------------------===//
1577 // C++0x 5.1.2: Lambda expressions
1579 // [...] () -> type {...}
1580 ExprResult ParseLambdaExpression();
1581 ExprResult TryParseLambdaExpression();
1582 Optional<unsigned> ParseLambdaIntroducer(LambdaIntroducer &Intro,
1583 bool *SkippedInits = nullptr);
1584 bool TryParseLambdaIntroducer(LambdaIntroducer &Intro);
1585 ExprResult ParseLambdaExpressionAfterIntroducer(
1586 LambdaIntroducer &Intro);
1588 //===--------------------------------------------------------------------===//
1589 // C++ 5.2p1: C++ Casts
1590 ExprResult ParseCXXCasts();
1592 //===--------------------------------------------------------------------===//
1593 // C++ 5.2p1: C++ Type Identification
1594 ExprResult ParseCXXTypeid();
1596 //===--------------------------------------------------------------------===//
1597 // C++ : Microsoft __uuidof Expression
1598 ExprResult ParseCXXUuidof();
1600 //===--------------------------------------------------------------------===//
1601 // C++ 5.2.4: C++ Pseudo-Destructor Expressions
1602 ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1603 tok::TokenKind OpKind,
1605 ParsedType ObjectType);
1607 //===--------------------------------------------------------------------===//
1608 // C++ 9.3.2: C++ 'this' pointer
1609 ExprResult ParseCXXThis();
1611 //===--------------------------------------------------------------------===//
1612 // C++ 15: C++ Throw Expression
1613 ExprResult ParseThrowExpression();
1615 ExceptionSpecificationType tryParseExceptionSpecification(
1617 SourceRange &SpecificationRange,
1618 SmallVectorImpl<ParsedType> &DynamicExceptions,
1619 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
1620 ExprResult &NoexceptExpr,
1621 CachedTokens *&ExceptionSpecTokens);
1623 // EndLoc is filled with the location of the last token of the specification.
1624 ExceptionSpecificationType ParseDynamicExceptionSpecification(
1625 SourceRange &SpecificationRange,
1626 SmallVectorImpl<ParsedType> &Exceptions,
1627 SmallVectorImpl<SourceRange> &Ranges);
1629 //===--------------------------------------------------------------------===//
1630 // C++0x 8: Function declaration trailing-return-type
1631 TypeResult ParseTrailingReturnType(SourceRange &Range);
1633 //===--------------------------------------------------------------------===//
1634 // C++ 2.13.5: C++ Boolean Literals
1635 ExprResult ParseCXXBoolLiteral();
1637 //===--------------------------------------------------------------------===//
1638 // C++ 5.2.3: Explicit type conversion (functional notation)
1639 ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
1641 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1642 /// This should only be called when the current token is known to be part of
1643 /// simple-type-specifier.
1644 void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
1646 bool ParseCXXTypeSpecifierSeq(DeclSpec &DS);
1648 //===--------------------------------------------------------------------===//
1649 // C++ 5.3.4 and 5.3.5: C++ new and delete
1650 bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs,
1652 void ParseDirectNewDeclarator(Declarator &D);
1653 ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
1654 ExprResult ParseCXXDeleteExpression(bool UseGlobal,
1655 SourceLocation Start);
1657 //===--------------------------------------------------------------------===//
1658 // C++ if/switch/while condition expression.
1659 Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt,
1661 Sema::ConditionKind CK);
1663 //===--------------------------------------------------------------------===//
1666 ExprResult ParseCoyieldExpression();
1668 //===--------------------------------------------------------------------===//
1669 // C99 6.7.8: Initialization.
1671 /// ParseInitializer
1672 /// initializer: [C99 6.7.8]
1673 /// assignment-expression
1675 ExprResult ParseInitializer() {
1676 if (Tok.isNot(tok::l_brace))
1677 return ParseAssignmentExpression();
1678 return ParseBraceInitializer();
1680 bool MayBeDesignationStart();
1681 ExprResult ParseBraceInitializer();
1682 ExprResult ParseInitializerWithPotentialDesignator();
1684 //===--------------------------------------------------------------------===//
1685 // clang Expressions
1687 ExprResult ParseBlockLiteralExpression(); // ^{...}
1689 //===--------------------------------------------------------------------===//
1690 // Objective-C Expressions
1691 ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
1692 ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
1693 ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
1694 ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
1695 ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
1696 ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
1697 ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
1698 ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
1699 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
1700 ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
1701 ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
1702 bool isSimpleObjCMessageExpression();
1703 ExprResult ParseObjCMessageExpression();
1704 ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
1705 SourceLocation SuperLoc,
1706 ParsedType ReceiverType,
1707 Expr *ReceiverExpr);
1708 ExprResult ParseAssignmentExprWithObjCMessageExprStart(
1709 SourceLocation LBracloc, SourceLocation SuperLoc,
1710 ParsedType ReceiverType, Expr *ReceiverExpr);
1711 bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
1713 //===--------------------------------------------------------------------===//
1714 // C99 6.8: Statements and Blocks.
1716 /// A SmallVector of statements, with stack size 32 (as that is the only one
1718 typedef SmallVector<Stmt*, 32> StmtVector;
1719 /// A SmallVector of expressions, with stack size 12 (the maximum used.)
1720 typedef SmallVector<Expr*, 12> ExprVector;
1721 /// A SmallVector of types.
1722 typedef SmallVector<ParsedType, 12> TypeVector;
1724 StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
1725 bool AllowOpenMPStandalone = false);
1726 enum AllowedConstructsKind {
1727 /// \brief Allow any declarations, statements, OpenMP directives.
1729 /// \brief Allow only statements and non-standalone OpenMP directives.
1730 ACK_StatementsOpenMPNonStandalone,
1731 /// \brief Allow statements and all executable OpenMP directives
1732 ACK_StatementsOpenMPAnyExecutable
1735 ParseStatementOrDeclaration(StmtVector &Stmts, AllowedConstructsKind Allowed,
1736 SourceLocation *TrailingElseLoc = nullptr);
1737 StmtResult ParseStatementOrDeclarationAfterAttributes(
1739 AllowedConstructsKind Allowed,
1740 SourceLocation *TrailingElseLoc,
1741 ParsedAttributesWithRange &Attrs);
1742 StmtResult ParseExprStatement();
1743 StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs);
1744 StmtResult ParseCaseStatement(bool MissingCase = false,
1745 ExprResult Expr = ExprResult());
1746 StmtResult ParseDefaultStatement();
1747 StmtResult ParseCompoundStatement(bool isStmtExpr = false);
1748 StmtResult ParseCompoundStatement(bool isStmtExpr,
1749 unsigned ScopeFlags);
1750 void ParseCompoundStatementLeadingPragmas();
1751 StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
1752 bool ParseParenExprOrCondition(StmtResult *InitStmt,
1753 Sema::ConditionResult &CondResult,
1755 Sema::ConditionKind CK);
1756 StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
1757 StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
1758 StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
1759 StmtResult ParseDoStatement();
1760 StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
1761 StmtResult ParseGotoStatement();
1762 StmtResult ParseContinueStatement();
1763 StmtResult ParseBreakStatement();
1764 StmtResult ParseReturnStatement();
1765 StmtResult ParseAsmStatement(bool &msAsm);
1766 StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
1767 StmtResult ParsePragmaLoopHint(StmtVector &Stmts,
1768 AllowedConstructsKind Allowed,
1769 SourceLocation *TrailingElseLoc,
1770 ParsedAttributesWithRange &Attrs);
1772 /// \brief Describes the behavior that should be taken for an __if_exists
1774 enum IfExistsBehavior {
1775 /// \brief Parse the block; this code is always used.
1777 /// \brief Skip the block entirely; this code is never used.
1779 /// \brief Parse the block as a dependent block, which may be used in
1780 /// some template instantiations but not others.
1784 /// \brief Describes the condition of a Microsoft __if_exists or
1785 /// __if_not_exists block.
1786 struct IfExistsCondition {
1787 /// \brief The location of the initial keyword.
1788 SourceLocation KeywordLoc;
1789 /// \brief Whether this is an __if_exists block (rather than an
1790 /// __if_not_exists block).
1793 /// \brief Nested-name-specifier preceding the name.
1796 /// \brief The name we're looking for.
1799 /// \brief The behavior of this __if_exists or __if_not_exists block
1801 IfExistsBehavior Behavior;
1804 bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
1805 void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
1806 void ParseMicrosoftIfExistsExternalDeclaration();
1807 void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
1808 AccessSpecifier& CurAS);
1809 bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
1811 bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
1812 SmallVectorImpl<Expr *> &Constraints,
1813 SmallVectorImpl<Expr *> &Exprs);
1815 //===--------------------------------------------------------------------===//
1816 // C++ 6: Statements and Blocks
1818 StmtResult ParseCXXTryBlock();
1819 StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
1820 StmtResult ParseCXXCatchBlock(bool FnCatch = false);
1822 //===--------------------------------------------------------------------===//
1823 // MS: SEH Statements and Blocks
1825 StmtResult ParseSEHTryBlock();
1826 StmtResult ParseSEHExceptBlock(SourceLocation Loc);
1827 StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
1828 StmtResult ParseSEHLeaveStatement();
1830 //===--------------------------------------------------------------------===//
1831 // Objective-C Statements
1833 StmtResult ParseObjCAtStatement(SourceLocation atLoc);
1834 StmtResult ParseObjCTryStmt(SourceLocation atLoc);
1835 StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
1836 StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
1837 StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
1840 //===--------------------------------------------------------------------===//
1841 // C99 6.7: Declarations.
1843 /// A context for parsing declaration specifiers. TODO: flesh this
1844 /// out, there are other significant restrictions on specifiers than
1845 /// would be best implemented in the parser.
1846 enum DeclSpecContext {
1847 DSC_normal, // normal context
1848 DSC_class, // class context, enables 'friend'
1849 DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
1850 DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
1851 DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration
1852 DSC_top_level, // top-level/namespace declaration context
1853 DSC_template_type_arg, // template type argument context
1854 DSC_objc_method_result, // ObjC method result context, enables 'instancetype'
1855 DSC_condition // condition declaration context
1858 /// Is this a context in which we are parsing just a type-specifier (or
1859 /// trailing-type-specifier)?
1860 static bool isTypeSpecifier(DeclSpecContext DSC) {
1865 case DSC_objc_method_result:
1869 case DSC_template_type_arg:
1870 case DSC_type_specifier:
1872 case DSC_alias_declaration:
1875 llvm_unreachable("Missing DeclSpecContext case");
1878 /// Is this a context in which we can perform class template argument
1880 static bool isClassTemplateDeductionContext(DeclSpecContext DSC) {
1886 case DSC_type_specifier:
1889 case DSC_objc_method_result:
1890 case DSC_template_type_arg:
1892 case DSC_alias_declaration:
1895 llvm_unreachable("Missing DeclSpecContext case");
1898 /// Information on a C++0x for-range-initializer found while parsing a
1899 /// declaration which turns out to be a for-range-declaration.
1900 struct ForRangeInit {
1901 SourceLocation ColonLoc;
1902 ExprResult RangeExpr;
1904 bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
1907 DeclGroupPtrTy ParseDeclaration(unsigned Context, SourceLocation &DeclEnd,
1908 ParsedAttributesWithRange &attrs);
1909 DeclGroupPtrTy ParseSimpleDeclaration(unsigned Context,
1910 SourceLocation &DeclEnd,
1911 ParsedAttributesWithRange &attrs,
1913 ForRangeInit *FRI = nullptr);
1914 bool MightBeDeclarator(unsigned Context);
1915 DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, unsigned Context,
1916 SourceLocation *DeclEnd = nullptr,
1917 ForRangeInit *FRI = nullptr);
1918 Decl *ParseDeclarationAfterDeclarator(Declarator &D,
1919 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
1920 bool ParseAsmAttributesAfterDeclarator(Declarator &D);
1921 Decl *ParseDeclarationAfterDeclaratorAndAttributes(
1923 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1924 ForRangeInit *FRI = nullptr);
1925 Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
1926 Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
1928 /// \brief When in code-completion, skip parsing of the function/method body
1929 /// unless the body contains the code-completion point.
1931 /// \returns true if the function body was skipped.
1932 bool trySkippingFunctionBody();
1934 bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
1935 const ParsedTemplateInfo &TemplateInfo,
1936 AccessSpecifier AS, DeclSpecContext DSC,
1937 ParsedAttributesWithRange &Attrs);
1938 DeclSpecContext getDeclSpecContextFromDeclaratorContext(unsigned Context);
1939 void ParseDeclarationSpecifiers(DeclSpec &DS,
1940 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1941 AccessSpecifier AS = AS_none,
1942 DeclSpecContext DSC = DSC_normal,
1943 LateParsedAttrList *LateAttrs = nullptr);
1944 bool DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
1945 DeclSpecContext DSContext,
1946 LateParsedAttrList *LateAttrs = nullptr);
1948 void ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS = AS_none,
1949 DeclSpecContext DSC = DSC_normal);
1951 void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
1952 Declarator::TheContext Context);
1954 void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
1955 const ParsedTemplateInfo &TemplateInfo,
1956 AccessSpecifier AS, DeclSpecContext DSC);
1957 void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
1958 void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType,
1961 void ParseStructDeclaration(
1962 ParsingDeclSpec &DS,
1963 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback);
1965 bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
1966 bool isTypeSpecifierQualifier();
1968 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
1969 /// is definitely a type-specifier. Return false if it isn't part of a type
1970 /// specifier or if we're not sure.
1971 bool isKnownToBeTypeSpecifier(const Token &Tok) const;
1973 /// \brief Return true if we know that we are definitely looking at a
1974 /// decl-specifier, and isn't part of an expression such as a function-style
1975 /// cast. Return false if it's no a decl-specifier, or we're not sure.
1976 bool isKnownToBeDeclarationSpecifier() {
1977 if (getLangOpts().CPlusPlus)
1978 return isCXXDeclarationSpecifier() == TPResult::True;
1979 return isDeclarationSpecifier(true);
1982 /// isDeclarationStatement - Disambiguates between a declaration or an
1983 /// expression statement, when parsing function bodies.
1984 /// Returns true for declaration, false for expression.
1985 bool isDeclarationStatement() {
1986 if (getLangOpts().CPlusPlus)
1987 return isCXXDeclarationStatement();
1988 return isDeclarationSpecifier(true);
1991 /// isForInitDeclaration - Disambiguates between a declaration or an
1992 /// expression in the context of the C 'clause-1' or the C++
1993 // 'for-init-statement' part of a 'for' statement.
1994 /// Returns true for declaration, false for expression.
1995 bool isForInitDeclaration() {
1996 if (getLangOpts().CPlusPlus)
1997 return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
1998 return isDeclarationSpecifier(true);
2001 /// \brief Determine whether this is a C++1z for-range-identifier.
2002 bool isForRangeIdentifier();
2004 /// \brief Determine whether we are currently at the start of an Objective-C
2005 /// class message that appears to be missing the open bracket '['.
2006 bool isStartOfObjCClassMessageMissingOpenBracket();
2008 /// \brief Starting with a scope specifier, identifier, or
2009 /// template-id that refers to the current class, determine whether
2010 /// this is a constructor declarator.
2011 bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false);
2013 /// \brief Specifies the context in which type-id/expression
2014 /// disambiguation will occur.
2015 enum TentativeCXXTypeIdContext {
2018 TypeIdAsTemplateArgument
2022 /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
2023 /// whether the parens contain an expression or a type-id.
2024 /// Returns true for a type-id and false for an expression.
2025 bool isTypeIdInParens(bool &isAmbiguous) {
2026 if (getLangOpts().CPlusPlus)
2027 return isCXXTypeId(TypeIdInParens, isAmbiguous);
2028 isAmbiguous = false;
2029 return isTypeSpecifierQualifier();
2031 bool isTypeIdInParens() {
2033 return isTypeIdInParens(isAmbiguous);
2036 /// \brief Checks if the current tokens form type-id or expression.
2037 /// It is similar to isTypeIdInParens but does not suppose that type-id
2038 /// is in parenthesis.
2039 bool isTypeIdUnambiguously() {
2041 if (getLangOpts().CPlusPlus)
2042 return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous);
2043 return isTypeSpecifierQualifier();
2046 /// isCXXDeclarationStatement - C++-specialized function that disambiguates
2047 /// between a declaration or an expression statement, when parsing function
2048 /// bodies. Returns true for declaration, false for expression.
2049 bool isCXXDeclarationStatement();
2051 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
2052 /// between a simple-declaration or an expression-statement.
2053 /// If during the disambiguation process a parsing error is encountered,
2054 /// the function returns true to let the declaration parsing code handle it.
2055 /// Returns false if the statement is disambiguated as expression.
2056 bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
2058 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
2059 /// a constructor-style initializer, when parsing declaration statements.
2060 /// Returns true for function declarator and false for constructor-style
2061 /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
2062 /// might be a constructor-style initializer.
2063 /// If during the disambiguation process a parsing error is encountered,
2064 /// the function returns true to let the declaration parsing code handle it.
2065 bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr);
2067 struct ConditionDeclarationOrInitStatementState;
2068 enum class ConditionOrInitStatement {
2069 Expression, ///< Disambiguated as an expression (either kind).
2070 ConditionDecl, ///< Disambiguated as the declaration form of condition.
2071 InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement.
2072 Error ///< Can't be any of the above!
2074 /// \brief Disambiguates between the different kinds of things that can happen
2075 /// after 'if (' or 'switch ('. This could be one of two different kinds of
2076 /// declaration (depending on whether there is a ';' later) or an expression.
2077 ConditionOrInitStatement
2078 isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt);
2080 bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
2081 bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
2083 return isCXXTypeId(Context, isAmbiguous);
2086 /// TPResult - Used as the result value for functions whose purpose is to
2087 /// disambiguate C++ constructs by "tentatively parsing" them.
2088 enum class TPResult {
2089 True, False, Ambiguous, Error
2092 /// \brief Based only on the given token kind, determine whether we know that
2093 /// we're at the start of an expression or a type-specifier-seq (which may
2094 /// be an expression, in C++).
2096 /// This routine does not attempt to resolve any of the trick cases, e.g.,
2097 /// those involving lookup of identifiers.
2099 /// \returns \c TPR_true if this token starts an expression, \c TPR_false if
2100 /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot
2102 TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind);
2104 /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a
2105 /// declaration specifier, TPResult::False if it is not,
2106 /// TPResult::Ambiguous if it could be either a decl-specifier or a
2107 /// function-style cast, and TPResult::Error if a parsing error was
2108 /// encountered. If it could be a braced C++11 function-style cast, returns
2109 /// BracedCastResult.
2110 /// Doesn't consume tokens.
2112 isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False,
2113 bool *HasMissingTypename = nullptr);
2115 /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
2116 /// \c TPResult::Ambiguous, determine whether the decl-specifier would be
2117 /// a type-specifier other than a cv-qualifier.
2118 bool isCXXDeclarationSpecifierAType();
2120 /// \brief Determine whether an identifier has been tentatively declared as a
2121 /// non-type. Such tentative declarations should not be found to name a type
2122 /// during a tentative parse, but also should not be annotated as a non-type.
2123 bool isTentativelyDeclared(IdentifierInfo *II);
2125 // "Tentative parsing" functions, used for disambiguation. If a parsing error
2126 // is encountered they will return TPResult::Error.
2127 // Returning TPResult::True/False indicates that the ambiguity was
2128 // resolved and tentative parsing may stop. TPResult::Ambiguous indicates
2129 // that more tentative parsing is necessary for disambiguation.
2130 // They all consume tokens, so backtracking should be used after calling them.
2132 TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
2133 TPResult TryParseTypeofSpecifier();
2134 TPResult TryParseProtocolQualifiers();
2135 TPResult TryParsePtrOperatorSeq();
2136 TPResult TryParseOperatorId();
2137 TPResult TryParseInitDeclaratorList();
2138 TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier=true);
2140 TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr,
2141 bool VersusTemplateArg = false);
2142 TPResult TryParseFunctionDeclarator();
2143 TPResult TryParseBracketDeclarator();
2144 TPResult TryConsumeDeclarationSpecifier();
2147 TypeResult ParseTypeName(SourceRange *Range = nullptr,
2148 Declarator::TheContext Context
2149 = Declarator::TypeNameContext,
2150 AccessSpecifier AS = AS_none,
2151 Decl **OwnedType = nullptr,
2152 ParsedAttributes *Attrs = nullptr);
2155 void ParseBlockId(SourceLocation CaretLoc);
2157 // Check for the start of a C++11 attribute-specifier-seq in a context where
2158 // an attribute is not allowed.
2159 bool CheckProhibitedCXX11Attribute() {
2160 assert(Tok.is(tok::l_square));
2161 if (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))
2163 return DiagnoseProhibitedCXX11Attribute();
2165 bool DiagnoseProhibitedCXX11Attribute();
2166 void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2167 SourceLocation CorrectLocation) {
2168 if (!getLangOpts().CPlusPlus11)
2170 if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
2171 Tok.isNot(tok::kw_alignas))
2173 DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
2175 void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2176 SourceLocation CorrectLocation);
2178 void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
2179 DeclSpec &DS, Sema::TagUseKind TUK);
2181 void ProhibitAttributes(ParsedAttributesWithRange &attrs) {
2182 if (!attrs.Range.isValid()) return;
2183 DiagnoseProhibitedAttributes(attrs);
2186 void DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs);
2188 // Forbid C++11 attributes that appear on certain syntactic
2189 // locations which standard permits but we don't supported yet,
2190 // for example, attributes appertain to decl specifiers.
2191 void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
2194 /// \brief Skip C++11 attributes and return the end location of the last one.
2195 /// \returns SourceLocation() if there are no attributes.
2196 SourceLocation SkipCXX11Attributes();
2198 /// \brief Diagnose and skip C++11 attributes that appear in syntactic
2199 /// locations where attributes are not allowed.
2200 void DiagnoseAndSkipCXX11Attributes();
2202 /// \brief Parses syntax-generic attribute arguments for attributes which are
2203 /// known to the implementation, and adds them to the given ParsedAttributes
2204 /// list with the given attribute syntax. Returns the number of arguments
2205 /// parsed for the attribute.
2207 ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2208 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2209 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2210 AttributeList::Syntax Syntax);
2212 void MaybeParseGNUAttributes(Declarator &D,
2213 LateParsedAttrList *LateAttrs = nullptr) {
2214 if (Tok.is(tok::kw___attribute)) {
2215 ParsedAttributes attrs(AttrFactory);
2216 SourceLocation endLoc;
2217 ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D);
2218 D.takeAttributes(attrs, endLoc);
2221 void MaybeParseGNUAttributes(ParsedAttributes &attrs,
2222 SourceLocation *endLoc = nullptr,
2223 LateParsedAttrList *LateAttrs = nullptr) {
2224 if (Tok.is(tok::kw___attribute))
2225 ParseGNUAttributes(attrs, endLoc, LateAttrs);
2227 void ParseGNUAttributes(ParsedAttributes &attrs,
2228 SourceLocation *endLoc = nullptr,
2229 LateParsedAttrList *LateAttrs = nullptr,
2230 Declarator *D = nullptr);
2231 void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
2232 SourceLocation AttrNameLoc,
2233 ParsedAttributes &Attrs,
2234 SourceLocation *EndLoc,
2235 IdentifierInfo *ScopeName,
2236 SourceLocation ScopeLoc,
2237 AttributeList::Syntax Syntax,
2239 IdentifierLoc *ParseIdentifierLoc();
2242 ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2243 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2244 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2245 AttributeList::Syntax Syntax);
2247 void MaybeParseCXX11Attributes(Declarator &D) {
2248 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
2249 ParsedAttributesWithRange attrs(AttrFactory);
2250 SourceLocation endLoc;
2251 ParseCXX11Attributes(attrs, &endLoc);
2252 D.takeAttributes(attrs, endLoc);
2255 void MaybeParseCXX11Attributes(ParsedAttributes &attrs,
2256 SourceLocation *endLoc = nullptr) {
2257 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
2258 ParsedAttributesWithRange attrsWithRange(AttrFactory);
2259 ParseCXX11Attributes(attrsWithRange, endLoc);
2260 attrs.takeAllFrom(attrsWithRange);
2263 void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2264 SourceLocation *endLoc = nullptr,
2265 bool OuterMightBeMessageSend = false) {
2266 if (getLangOpts().CPlusPlus11 &&
2267 isCXX11AttributeSpecifier(false, OuterMightBeMessageSend))
2268 ParseCXX11Attributes(attrs, endLoc);
2271 void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
2272 SourceLocation *EndLoc = nullptr);
2273 void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2274 SourceLocation *EndLoc = nullptr);
2275 /// \brief Parses a C++-style attribute argument list. Returns true if this
2276 /// results in adding an attribute to the ParsedAttributes list.
2277 bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
2278 SourceLocation AttrNameLoc,
2279 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2280 IdentifierInfo *ScopeName,
2281 SourceLocation ScopeLoc);
2283 IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc);
2285 void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
2286 SourceLocation *endLoc = nullptr) {
2287 if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
2288 ParseMicrosoftAttributes(attrs, endLoc);
2290 void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs);
2291 void ParseMicrosoftAttributes(ParsedAttributes &attrs,
2292 SourceLocation *endLoc = nullptr);
2293 void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2294 SourceLocation *End = nullptr) {
2295 const auto &LO = getLangOpts();
2296 if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec))
2297 ParseMicrosoftDeclSpecs(Attrs, End);
2299 void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2300 SourceLocation *End = nullptr);
2301 bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
2302 SourceLocation AttrNameLoc,
2303 ParsedAttributes &Attrs);
2304 void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
2305 void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2306 SourceLocation SkipExtendedMicrosoftTypeAttributes();
2307 void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
2308 void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
2309 void ParseOpenCLKernelAttributes(ParsedAttributes &attrs);
2310 void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
2311 /// \brief Parses opencl_unroll_hint attribute if language is OpenCL v2.0
2313 /// \return false if error happens.
2314 bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
2315 if (getLangOpts().OpenCL)
2316 return ParseOpenCLUnrollHintAttribute(Attrs);
2319 /// \brief Parses opencl_unroll_hint attribute.
2320 /// \return false if error happens.
2321 bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs);
2322 void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
2324 VersionTuple ParseVersionTuple(SourceRange &Range);
2325 void ParseAvailabilityAttribute(IdentifierInfo &Availability,
2326 SourceLocation AvailabilityLoc,
2327 ParsedAttributes &attrs,
2328 SourceLocation *endLoc,
2329 IdentifierInfo *ScopeName,
2330 SourceLocation ScopeLoc,
2331 AttributeList::Syntax Syntax);
2333 Optional<AvailabilitySpec> ParseAvailabilitySpec();
2334 ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc);
2336 void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol,
2338 ParsedAttributes &Attrs,
2339 SourceLocation *EndLoc,
2340 IdentifierInfo *ScopeName,
2341 SourceLocation ScopeLoc,
2342 AttributeList::Syntax Syntax);
2344 void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
2345 SourceLocation ObjCBridgeRelatedLoc,
2346 ParsedAttributes &attrs,
2347 SourceLocation *endLoc,
2348 IdentifierInfo *ScopeName,
2349 SourceLocation ScopeLoc,
2350 AttributeList::Syntax Syntax);
2352 void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
2353 SourceLocation AttrNameLoc,
2354 ParsedAttributes &Attrs,
2355 SourceLocation *EndLoc,
2356 IdentifierInfo *ScopeName,
2357 SourceLocation ScopeLoc,
2358 AttributeList::Syntax Syntax);
2360 void ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
2361 SourceLocation AttrNameLoc,
2362 ParsedAttributes &Attrs,
2363 SourceLocation *EndLoc,
2364 IdentifierInfo *ScopeName,
2365 SourceLocation ScopeLoc,
2366 AttributeList::Syntax Syntax);
2368 void ParseTypeofSpecifier(DeclSpec &DS);
2369 SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
2370 void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
2371 SourceLocation StartLoc,
2372 SourceLocation EndLoc);
2373 void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
2374 void ParseAtomicSpecifier(DeclSpec &DS);
2376 ExprResult ParseAlignArgument(SourceLocation Start,
2377 SourceLocation &EllipsisLoc);
2378 void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2379 SourceLocation *endLoc = nullptr);
2381 VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
2382 VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
2383 return isCXX11VirtSpecifier(Tok);
2385 void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface,
2386 SourceLocation FriendLoc);
2388 bool isCXX11FinalKeyword() const;
2390 /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
2391 /// enter a new C++ declarator scope and exit it when the function is
2393 class DeclaratorScopeObj {
2399 DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
2400 : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
2402 void EnterDeclaratorScope() {
2403 assert(!EnteredScope && "Already entered the scope!");
2404 assert(SS.isSet() && "C++ scope was not set!");
2406 CreatedScope = true;
2407 P.EnterScope(0); // Not a decl scope.
2409 if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
2410 EnteredScope = true;
2413 ~DeclaratorScopeObj() {
2415 assert(SS.isSet() && "C++ scope was cleared ?");
2416 P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
2423 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
2424 void ParseDeclarator(Declarator &D);
2425 /// A function that parses a variant of direct-declarator.
2426 typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
2427 void ParseDeclaratorInternal(Declarator &D,
2428 DirectDeclParseFunction DirectDeclParser);
2430 enum AttrRequirements {
2431 AR_NoAttributesParsed = 0, ///< No attributes are diagnosed.
2432 AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes.
2433 AR_GNUAttributesParsed = 1 << 1,
2434 AR_CXX11AttributesParsed = 1 << 2,
2435 AR_DeclspecAttributesParsed = 1 << 3,
2436 AR_AllAttributesParsed = AR_GNUAttributesParsed |
2437 AR_CXX11AttributesParsed |
2438 AR_DeclspecAttributesParsed,
2439 AR_VendorAttributesParsed = AR_GNUAttributesParsed |
2440 AR_DeclspecAttributesParsed
2443 void ParseTypeQualifierListOpt(
2444 DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed,
2445 bool AtomicAllowed = true, bool IdentifierRequired = false,
2446 Optional<llvm::function_ref<void()>> CodeCompletionHandler = None);
2447 void ParseDirectDeclarator(Declarator &D);
2448 void ParseDecompositionDeclarator(Declarator &D);
2449 void ParseParenDeclarator(Declarator &D);
2450 void ParseFunctionDeclarator(Declarator &D,
2451 ParsedAttributes &attrs,
2452 BalancedDelimiterTracker &Tracker,
2454 bool RequiresArg = false);
2455 bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
2456 SourceLocation &RefQualifierLoc);
2457 bool isFunctionDeclaratorIdentifierList();
2458 void ParseFunctionDeclaratorIdentifierList(
2460 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
2461 void ParseParameterDeclarationClause(
2463 ParsedAttributes &attrs,
2464 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
2465 SourceLocation &EllipsisLoc);
2466 void ParseBracketDeclarator(Declarator &D);
2467 void ParseMisplacedBracketDeclarator(Declarator &D);
2469 //===--------------------------------------------------------------------===//
2470 // C++ 7: Declarations [dcl.dcl]
2472 /// The kind of attribute specifier we have found.
2473 enum CXX11AttributeKind {
2474 /// This is not an attribute specifier.
2475 CAK_NotAttributeSpecifier,
2476 /// This should be treated as an attribute-specifier.
2477 CAK_AttributeSpecifier,
2478 /// The next tokens are '[[', but this is not an attribute-specifier. This
2479 /// is ill-formed by C++11 [dcl.attr.grammar]p6.
2480 CAK_InvalidAttributeSpecifier
2483 isCXX11AttributeSpecifier(bool Disambiguate = false,
2484 bool OuterMightBeMessageSend = false);
2486 void DiagnoseUnexpectedNamespace(NamedDecl *Context);
2488 DeclGroupPtrTy ParseNamespace(unsigned Context, SourceLocation &DeclEnd,
2489 SourceLocation InlineLoc = SourceLocation());
2490 void ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc,
2491 std::vector<IdentifierInfo*>& Ident,
2492 std::vector<SourceLocation>& NamespaceLoc,
2493 unsigned int index, SourceLocation& InlineLoc,
2494 ParsedAttributes& attrs,
2495 BalancedDelimiterTracker &Tracker);
2496 Decl *ParseLinkage(ParsingDeclSpec &DS, unsigned Context);
2497 Decl *ParseExportDeclaration();
2498 DeclGroupPtrTy ParseUsingDirectiveOrDeclaration(
2499 unsigned Context, const ParsedTemplateInfo &TemplateInfo,
2500 SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs);
2501 Decl *ParseUsingDirective(unsigned Context,
2502 SourceLocation UsingLoc,
2503 SourceLocation &DeclEnd,
2504 ParsedAttributes &attrs);
2506 struct UsingDeclarator {
2507 SourceLocation TypenameLoc;
2509 SourceLocation TemplateKWLoc;
2511 SourceLocation EllipsisLoc;
2514 TypenameLoc = TemplateKWLoc = EllipsisLoc = SourceLocation();
2520 bool ParseUsingDeclarator(unsigned Context, UsingDeclarator &D);
2521 DeclGroupPtrTy ParseUsingDeclaration(unsigned Context,
2522 const ParsedTemplateInfo &TemplateInfo,
2523 SourceLocation UsingLoc,
2524 SourceLocation &DeclEnd,
2525 AccessSpecifier AS = AS_none);
2526 Decl *ParseAliasDeclarationAfterDeclarator(
2527 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
2528 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
2529 ParsedAttributes &Attrs, Decl **OwnedType = nullptr);
2531 Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
2532 Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
2533 SourceLocation AliasLoc, IdentifierInfo *Alias,
2534 SourceLocation &DeclEnd);
2536 //===--------------------------------------------------------------------===//
2537 // C++ 9: classes [class] and C structs/unions.
2538 bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
2539 void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
2540 DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo,
2541 AccessSpecifier AS, bool EnteringContext,
2542 DeclSpecContext DSC,
2543 ParsedAttributesWithRange &Attributes);
2544 void SkipCXXMemberSpecification(SourceLocation StartLoc,
2545 SourceLocation AttrFixitLoc,
2548 void ParseCXXMemberSpecification(SourceLocation StartLoc,
2549 SourceLocation AttrFixitLoc,
2550 ParsedAttributesWithRange &Attrs,
2553 ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2554 SourceLocation &EqualLoc);
2555 bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
2557 ExprResult &BitfieldSize,
2558 LateParsedAttrList &LateAttrs);
2559 void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D,
2560 VirtSpecifiers &VS);
2561 DeclGroupPtrTy ParseCXXClassMemberDeclaration(
2562 AccessSpecifier AS, AttributeList *Attr,
2563 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2564 ParsingDeclRAIIObject *DiagsFromTParams = nullptr);
2565 DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas(
2566 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
2567 DeclSpec::TST TagType, Decl *Tag);
2568 void ParseConstructorInitializer(Decl *ConstructorDecl);
2569 MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
2570 void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2573 //===--------------------------------------------------------------------===//
2574 // C++ 10: Derived classes [class.derived]
2575 TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
2576 SourceLocation &EndLocation);
2577 void ParseBaseClause(Decl *ClassDecl);
2578 BaseResult ParseBaseSpecifier(Decl *ClassDecl);
2579 AccessSpecifier getAccessSpecifierIfPresent() const;
2581 bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
2582 SourceLocation TemplateKWLoc,
2583 IdentifierInfo *Name,
2584 SourceLocation NameLoc,
2585 bool EnteringContext,
2586 ParsedType ObjectType,
2588 bool AssumeTemplateId);
2589 bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2590 ParsedType ObjectType,
2591 UnqualifiedId &Result);
2593 //===--------------------------------------------------------------------===//
2594 // OpenMP: Directives and clauses.
2595 /// Parse clauses for '#pragma omp declare simd'.
2596 DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr,
2598 SourceLocation Loc);
2599 /// \brief Parses declarative OpenMP directives.
2600 DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl(
2601 AccessSpecifier &AS, ParsedAttributesWithRange &Attrs,
2602 DeclSpec::TST TagType = DeclSpec::TST_unspecified,
2603 Decl *TagDecl = nullptr);
2604 /// \brief Parse 'omp declare reduction' construct.
2605 DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS);
2607 /// \brief Parses simple list of variables.
2609 /// \param Kind Kind of the directive.
2610 /// \param Callback Callback function to be called for the list elements.
2611 /// \param AllowScopeSpecifier true, if the variables can have fully
2612 /// qualified names.
2614 bool ParseOpenMPSimpleVarList(
2615 OpenMPDirectiveKind Kind,
2616 const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
2618 bool AllowScopeSpecifier);
2619 /// \brief Parses declarative or executable directive.
2621 /// \param Allowed ACK_Any, if any directives are allowed,
2622 /// ACK_StatementsOpenMPAnyExecutable - if any executable directives are
2623 /// allowed, ACK_StatementsOpenMPNonStandalone - if only non-standalone
2624 /// executable directives are allowed.
2627 ParseOpenMPDeclarativeOrExecutableDirective(AllowedConstructsKind Allowed);
2628 /// \brief Parses clause of kind \a CKind for directive of a kind \a Kind.
2630 /// \param DKind Kind of current directive.
2631 /// \param CKind Kind of current clause.
2632 /// \param FirstClause true, if this is the first clause of a kind \a CKind
2633 /// in current directive.
2635 OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
2636 OpenMPClauseKind CKind, bool FirstClause);
2637 /// \brief Parses clause with a single expression of a kind \a Kind.
2639 /// \param Kind Kind of current clause.
2641 OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind);
2642 /// \brief Parses simple clause of a kind \a Kind.
2644 /// \param Kind Kind of current clause.
2646 OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind);
2647 /// \brief Parses clause with a single expression and an additional argument
2648 /// of a kind \a Kind.
2650 /// \param Kind Kind of current clause.
2652 OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind);
2653 /// \brief Parses clause without any additional arguments.
2655 /// \param Kind Kind of current clause.
2657 OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind);
2658 /// \brief Parses clause with the list of variables of a kind \a Kind.
2660 /// \param Kind Kind of current clause.
2662 OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
2663 OpenMPClauseKind Kind);
2666 /// Parses simple expression in parens for single-expression clauses of OpenMP
2668 /// \param RLoc Returned location of right paren.
2669 ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc);
2671 /// Data used for parsing list of variables in OpenMP clauses.
2672 struct OpenMPVarListDataTy {
2673 Expr *TailExpr = nullptr;
2674 SourceLocation ColonLoc;
2675 CXXScopeSpec ReductionIdScopeSpec;
2676 DeclarationNameInfo ReductionId;
2677 OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown;
2678 OpenMPLinearClauseKind LinKind = OMPC_LINEAR_val;
2679 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
2680 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
2681 bool IsMapTypeImplicit = false;
2682 SourceLocation DepLinMapLoc;
2685 /// Parses clauses with list.
2686 bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind,
2687 SmallVectorImpl<Expr *> &Vars,
2688 OpenMPVarListDataTy &Data);
2689 bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2690 bool AllowDestructorName,
2691 bool AllowConstructorName,
2692 bool AllowDeductionGuide,
2693 ParsedType ObjectType,
2694 SourceLocation& TemplateKWLoc,
2695 UnqualifiedId &Result);
2698 //===--------------------------------------------------------------------===//
2699 // C++ 14: Templates [temp]
2701 // C++ 14.1: Template Parameters [temp.param]
2702 Decl *ParseDeclarationStartingWithTemplate(unsigned Context,
2703 SourceLocation &DeclEnd,
2704 AccessSpecifier AS = AS_none,
2705 AttributeList *AccessAttrs = nullptr);
2706 Decl *ParseTemplateDeclarationOrSpecialization(unsigned Context,
2707 SourceLocation &DeclEnd,
2709 AttributeList *AccessAttrs);
2710 Decl *ParseSingleDeclarationAfterTemplate(
2712 const ParsedTemplateInfo &TemplateInfo,
2713 ParsingDeclRAIIObject &DiagsFromParams,
2714 SourceLocation &DeclEnd,
2715 AccessSpecifier AS=AS_none,
2716 AttributeList *AccessAttrs = nullptr);
2717 bool ParseTemplateParameters(unsigned Depth,
2718 SmallVectorImpl<Decl*> &TemplateParams,
2719 SourceLocation &LAngleLoc,
2720 SourceLocation &RAngleLoc);
2721 bool ParseTemplateParameterList(unsigned Depth,
2722 SmallVectorImpl<Decl*> &TemplateParams);
2723 bool isStartOfTemplateTypeParameter();
2724 Decl *ParseTemplateParameter(unsigned Depth, unsigned Position);
2725 Decl *ParseTypeParameter(unsigned Depth, unsigned Position);
2726 Decl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
2727 Decl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
2728 void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
2729 SourceLocation CorrectLoc,
2730 bool AlreadyHasEllipsis,
2731 bool IdentifierHasName);
2732 void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
2734 // C++ 14.3: Template arguments [temp.arg]
2735 typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
2737 bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
2738 bool ConsumeLastToken,
2739 bool ObjCGenericList);
2740 bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
2741 SourceLocation &LAngleLoc,
2742 TemplateArgList &TemplateArgs,
2743 SourceLocation &RAngleLoc);
2745 bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
2747 SourceLocation TemplateKWLoc,
2748 UnqualifiedId &TemplateName,
2749 bool AllowTypeAnnotation = true);
2750 void AnnotateTemplateIdTokenAsType(bool IsClassName = false);
2751 bool IsTemplateArgumentList(unsigned Skip = 0);
2752 bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
2753 ParsedTemplateArgument ParseTemplateTemplateArgument();
2754 ParsedTemplateArgument ParseTemplateArgument();
2755 Decl *ParseExplicitInstantiation(unsigned Context,
2756 SourceLocation ExternLoc,
2757 SourceLocation TemplateLoc,
2758 SourceLocation &DeclEnd,
2759 AccessSpecifier AS = AS_none);
2761 //===--------------------------------------------------------------------===//
2763 DeclGroupPtrTy ParseModuleDecl();
2764 DeclGroupPtrTy ParseModuleImport(SourceLocation AtLoc);
2765 bool parseMisplacedModuleImport();
2766 bool tryParseMisplacedModuleImport() {
2767 tok::TokenKind Kind = Tok.getKind();
2768 if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end ||
2769 Kind == tok::annot_module_include)
2770 return parseMisplacedModuleImport();
2774 bool ParseModuleName(
2775 SourceLocation UseLoc,
2776 SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
2779 //===--------------------------------------------------------------------===//
2780 // C++11/G++: Type Traits [Type-Traits.html in the GCC manual]
2781 ExprResult ParseTypeTrait();
2783 //===--------------------------------------------------------------------===//
2784 // Embarcadero: Arary and Expression Traits
2785 ExprResult ParseArrayTypeTrait();
2786 ExprResult ParseExpressionTrait();
2788 //===--------------------------------------------------------------------===//
2789 // Preprocessor code-completion pass-through
2790 void CodeCompleteDirective(bool InConditional) override;
2791 void CodeCompleteInConditionalExclusion() override;
2792 void CodeCompleteMacroName(bool IsDefinition) override;
2793 void CodeCompletePreprocessorExpression() override;
2794 void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo,
2795 unsigned ArgumentIndex) override;
2796 void CodeCompleteNaturalLanguage() override;
2799 } // end namespace clang