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;
188 std::unique_ptr<CommentHandler> CommentSemaHandler;
190 /// Whether the '>' token acts as an operator or not. This will be
191 /// true except when we are parsing an expression within a C++
192 /// template argument list, where the '>' closes the template
194 bool GreaterThanIsOperator;
196 /// ColonIsSacred - When this is false, we aggressively try to recover from
197 /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not
198 /// safe in case statements and a few other things. This is managed by the
199 /// ColonProtectionRAIIObject RAII object.
202 /// \brief When true, we are directly inside an Objective-C message
205 /// This is managed by the \c InMessageExpressionRAIIObject class, and
206 /// should not be set directly.
207 bool InMessageExpression;
209 /// The "depth" of the template parameters currently being parsed.
210 unsigned TemplateParameterDepth;
212 /// \brief RAII class that manages the template parameter depth.
213 class TemplateParameterDepthRAII {
215 unsigned AddedLevels;
217 explicit TemplateParameterDepthRAII(unsigned &Depth)
218 : Depth(Depth), AddedLevels(0) {}
220 ~TemplateParameterDepthRAII() {
221 Depth -= AddedLevels;
228 void addDepth(unsigned D) {
232 unsigned getDepth() const { return Depth; }
235 /// Factory object for creating AttributeList objects.
236 AttributeFactory AttrFactory;
238 /// \brief Gathers and cleans up TemplateIdAnnotations when parsing of a
239 /// top-level declaration is finished.
240 SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
242 /// \brief Identifiers which have been declared within a tentative parse.
243 SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers;
245 IdentifierInfo *getSEHExceptKeyword();
247 /// True if we are within an Objective-C container while parsing C-like decls.
249 /// This is necessary because Sema thinks we have left the container
250 /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will
252 bool ParsingInObjCContainer;
254 bool SkipFunctionBodies;
256 /// The location of the expression statement that is being parsed right now.
257 /// Used to determine if an expression that is being parsed is a statement or
258 /// just a regular sub-expression.
259 SourceLocation ExprStatementTokLoc;
262 Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
265 const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
266 const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
267 Preprocessor &getPreprocessor() const { return PP; }
268 Sema &getActions() const { return Actions; }
269 AttributeFactory &getAttrFactory() { return AttrFactory; }
271 const Token &getCurToken() const { return Tok; }
272 Scope *getCurScope() const { return Actions.getCurScope(); }
273 void incrementMSManglingNumber() const {
274 return Actions.incrementMSManglingNumber();
277 Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); }
279 // Type forwarding. All of these are statically 'void*', but they may all be
280 // different actual classes based on the actions in place.
281 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
282 typedef OpaquePtr<TemplateName> TemplateTy;
284 typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists;
286 typedef Sema::FullExprArg FullExprArg;
290 /// Initialize - Warm up the parser.
294 /// Parse the first top-level declaration in a translation unit.
295 bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result);
297 /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if
298 /// the EOF was encountered.
299 bool ParseTopLevelDecl(DeclGroupPtrTy &Result);
300 bool ParseTopLevelDecl() {
301 DeclGroupPtrTy Result;
302 return ParseTopLevelDecl(Result);
305 /// ConsumeToken - Consume the current 'peek token' and lex the next one.
306 /// This does not work with special tokens: string literals, code completion
307 /// and balanced tokens must be handled using the specific consume methods.
308 /// Returns the location of the consumed token.
309 SourceLocation ConsumeToken() {
310 assert(!isTokenSpecial() &&
311 "Should consume special tokens with Consume*Token");
312 PrevTokLocation = Tok.getLocation();
314 return PrevTokLocation;
317 bool TryConsumeToken(tok::TokenKind Expected) {
318 if (Tok.isNot(Expected))
320 assert(!isTokenSpecial() &&
321 "Should consume special tokens with Consume*Token");
322 PrevTokLocation = Tok.getLocation();
327 bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) {
328 if (!TryConsumeToken(Expected))
330 Loc = PrevTokLocation;
334 SourceLocation getEndOfPreviousToken() {
335 return PP.getLocForEndOfToken(PrevTokLocation);
338 /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds
339 /// to the given nullability kind.
340 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) {
341 return Actions.getNullabilityKeyword(nullability);
345 //===--------------------------------------------------------------------===//
346 // Low-Level token peeking and consumption methods.
349 /// isTokenParen - Return true if the cur token is '(' or ')'.
350 bool isTokenParen() const {
351 return Tok.getKind() == tok::l_paren || Tok.getKind() == tok::r_paren;
353 /// isTokenBracket - Return true if the cur token is '[' or ']'.
354 bool isTokenBracket() const {
355 return Tok.getKind() == tok::l_square || Tok.getKind() == tok::r_square;
357 /// isTokenBrace - Return true if the cur token is '{' or '}'.
358 bool isTokenBrace() const {
359 return Tok.getKind() == tok::l_brace || Tok.getKind() == tok::r_brace;
361 /// isTokenStringLiteral - True if this token is a string-literal.
362 bool isTokenStringLiteral() const {
363 return tok::isStringLiteral(Tok.getKind());
365 /// isTokenSpecial - True if this token requires special consumption methods.
366 bool isTokenSpecial() const {
367 return isTokenStringLiteral() || isTokenParen() || isTokenBracket() ||
368 isTokenBrace() || Tok.is(tok::code_completion);
371 /// \brief Returns true if the current token is '=' or is a type of '='.
372 /// For typos, give a fixit to '='
373 bool isTokenEqualOrEqualTypo();
375 /// \brief Return the current token to the token stream and make the given
376 /// token the current token.
377 void UnconsumeToken(Token &Consumed) {
379 PP.EnterToken(Consumed);
384 /// ConsumeAnyToken - Dispatch to the right Consume* method based on the
385 /// current token type. This should only be used in cases where the type of
386 /// the token really isn't known, e.g. in error recovery.
387 SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) {
389 return ConsumeParen();
390 if (isTokenBracket())
391 return ConsumeBracket();
393 return ConsumeBrace();
394 if (isTokenStringLiteral())
395 return ConsumeStringToken();
396 if (Tok.is(tok::code_completion))
397 return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken()
398 : handleUnexpectedCodeCompletionToken();
399 return ConsumeToken();
402 /// ConsumeParen - This consume method keeps the paren count up-to-date.
404 SourceLocation ConsumeParen() {
405 assert(isTokenParen() && "wrong consume method");
406 if (Tok.getKind() == tok::l_paren)
409 --ParenCount; // Don't let unbalanced )'s drive the count negative.
410 PrevTokLocation = Tok.getLocation();
412 return PrevTokLocation;
415 /// ConsumeBracket - This consume method keeps the bracket count up-to-date.
417 SourceLocation ConsumeBracket() {
418 assert(isTokenBracket() && "wrong consume method");
419 if (Tok.getKind() == tok::l_square)
421 else if (BracketCount)
422 --BracketCount; // Don't let unbalanced ]'s drive the count negative.
424 PrevTokLocation = Tok.getLocation();
426 return PrevTokLocation;
429 /// ConsumeBrace - This consume method keeps the brace count up-to-date.
431 SourceLocation ConsumeBrace() {
432 assert(isTokenBrace() && "wrong consume method");
433 if (Tok.getKind() == tok::l_brace)
436 --BraceCount; // Don't let unbalanced }'s drive the count negative.
438 PrevTokLocation = Tok.getLocation();
440 return PrevTokLocation;
443 /// ConsumeStringToken - Consume the current 'peek token', lexing a new one
444 /// and returning the token kind. This method is specific to strings, as it
445 /// handles string literal concatenation, as per C99 5.1.1.2, translation
447 SourceLocation ConsumeStringToken() {
448 assert(isTokenStringLiteral() &&
449 "Should only consume string literals with this method");
450 PrevTokLocation = Tok.getLocation();
452 return PrevTokLocation;
455 /// \brief Consume the current code-completion token.
457 /// This routine can be called to consume the code-completion token and
458 /// continue processing in special cases where \c cutOffParsing() isn't
459 /// desired, such as token caching or completion with lookahead.
460 SourceLocation ConsumeCodeCompletionToken() {
461 assert(Tok.is(tok::code_completion));
462 PrevTokLocation = Tok.getLocation();
464 return PrevTokLocation;
467 ///\ brief When we are consuming a code-completion token without having
468 /// matched specific position in the grammar, provide code-completion results
469 /// based on context.
471 /// \returns the source location of the code-completion token.
472 SourceLocation handleUnexpectedCodeCompletionToken();
474 /// \brief Abruptly cut off parsing; mainly used when we have reached the
475 /// code-completion point.
476 void cutOffParsing() {
477 if (PP.isCodeCompletionEnabled())
478 PP.setCodeCompletionReached();
479 // Cut off parsing by acting as if we reached the end-of-file.
480 Tok.setKind(tok::eof);
483 /// \brief Determine if we're at the end of the file or at a transition
486 tok::TokenKind Kind = Tok.getKind();
487 return Kind == tok::eof || Kind == tok::annot_module_begin ||
488 Kind == tok::annot_module_end || Kind == tok::annot_module_include;
491 /// \brief Initialize all pragma handlers.
492 void initializePragmaHandlers();
494 /// \brief Destroy and reset all pragma handlers.
495 void resetPragmaHandlers();
497 /// \brief Handle the annotation token produced for #pragma unused(...)
498 void HandlePragmaUnused();
500 /// \brief Handle the annotation token produced for
501 /// #pragma GCC visibility...
502 void HandlePragmaVisibility();
504 /// \brief Handle the annotation token produced for
506 void HandlePragmaPack();
508 /// \brief Handle the annotation token produced for
509 /// #pragma ms_struct...
510 void HandlePragmaMSStruct();
512 /// \brief Handle the annotation token produced for
513 /// #pragma comment...
514 void HandlePragmaMSComment();
516 void HandlePragmaMSPointersToMembers();
518 void HandlePragmaMSVtorDisp();
520 void HandlePragmaMSPragma();
521 bool HandlePragmaMSSection(StringRef PragmaName,
522 SourceLocation PragmaLocation);
523 bool HandlePragmaMSSegment(StringRef PragmaName,
524 SourceLocation PragmaLocation);
525 bool HandlePragmaMSInitSeg(StringRef PragmaName,
526 SourceLocation PragmaLocation);
528 /// \brief Handle the annotation token produced for
530 void HandlePragmaAlign();
532 /// \brief Handle the annotation token produced for
533 /// #pragma clang __debug dump...
534 void HandlePragmaDump();
536 /// \brief Handle the annotation token produced for
537 /// #pragma weak id...
538 void HandlePragmaWeak();
540 /// \brief Handle the annotation token produced for
541 /// #pragma weak id = id...
542 void HandlePragmaWeakAlias();
544 /// \brief Handle the annotation token produced for
545 /// #pragma redefine_extname...
546 void HandlePragmaRedefineExtname();
548 /// \brief Handle the annotation token produced for
549 /// #pragma STDC FP_CONTRACT...
550 void HandlePragmaFPContract();
552 /// \brief Handle the annotation token produced for
553 /// #pragma clang fp ...
554 void HandlePragmaFP();
556 /// \brief Handle the annotation token produced for
557 /// #pragma OPENCL EXTENSION...
558 void HandlePragmaOpenCLExtension();
560 /// \brief Handle the annotation token produced for
561 /// #pragma clang __debug captured
562 StmtResult HandlePragmaCaptured();
564 /// \brief Handle the annotation token produced for
565 /// #pragma clang loop and #pragma unroll.
566 bool HandlePragmaLoopHint(LoopHint &Hint);
568 /// GetLookAheadToken - This peeks ahead N tokens and returns that token
569 /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1)
570 /// returns the token after Tok, etc.
572 /// Note that this differs from the Preprocessor's LookAhead method, because
573 /// the Parser always has one token lexed that the preprocessor doesn't.
575 const Token &GetLookAheadToken(unsigned N) {
576 if (N == 0 || Tok.is(tok::eof)) return Tok;
577 return PP.LookAhead(N-1);
581 /// NextToken - This peeks ahead one token and returns it without
583 const Token &NextToken() {
584 return PP.LookAhead(0);
587 /// getTypeAnnotation - Read a parsed type out of an annotation token.
588 static ParsedType getTypeAnnotation(Token &Tok) {
589 return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
593 static void setTypeAnnotation(Token &Tok, ParsedType T) {
594 Tok.setAnnotationValue(T.getAsOpaquePtr());
597 /// \brief Read an already-translated primary expression out of an annotation
599 static ExprResult getExprAnnotation(Token &Tok) {
600 return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue());
603 /// \brief Set the primary expression corresponding to the given annotation
605 static void setExprAnnotation(Token &Tok, ExprResult ER) {
606 Tok.setAnnotationValue(ER.getAsOpaquePointer());
610 // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to
611 // find a type name by attempting typo correction.
612 bool TryAnnotateTypeOrScopeToken();
613 bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS,
615 bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
618 enum AnnotatedNameKind {
619 /// Annotation has failed and emitted an error.
621 /// The identifier is a tentatively-declared name.
623 /// The identifier is a template name. FIXME: Add an annotation for that.
625 /// The identifier can't be resolved.
627 /// Annotation was successful.
631 TryAnnotateName(bool IsAddressOfOperand,
632 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
634 /// Push a tok::annot_cxxscope token onto the token stream.
635 void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
637 /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
638 /// replacing them with the non-context-sensitive keywords. This returns
639 /// true if the token was replaced.
640 bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
641 const char *&PrevSpec, unsigned &DiagID,
643 if (!getLangOpts().AltiVec && !getLangOpts().ZVector)
646 if (Tok.getIdentifierInfo() != Ident_vector &&
647 Tok.getIdentifierInfo() != Ident_bool &&
648 (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel))
651 return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
654 /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
655 /// identifier token, replacing it with the non-context-sensitive __vector.
656 /// This returns true if the token was replaced.
657 bool TryAltiVecVectorToken() {
658 if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) ||
659 Tok.getIdentifierInfo() != Ident_vector) return false;
660 return TryAltiVecVectorTokenOutOfLine();
663 bool TryAltiVecVectorTokenOutOfLine();
664 bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
665 const char *&PrevSpec, unsigned &DiagID,
668 /// Returns true if the current token is the identifier 'instancetype'.
670 /// Should only be used in Objective-C language modes.
671 bool isObjCInstancetype() {
672 assert(getLangOpts().ObjC1);
673 if (Tok.isAnnotation())
675 if (!Ident_instancetype)
676 Ident_instancetype = PP.getIdentifierInfo("instancetype");
677 return Tok.getIdentifierInfo() == Ident_instancetype;
680 /// TryKeywordIdentFallback - For compatibility with system headers using
681 /// keywords as identifiers, attempt to convert the current token to an
682 /// identifier and optionally disable the keyword for the remainder of the
683 /// translation unit. This returns false if the token was not replaced,
684 /// otherwise emits a diagnostic and returns true.
685 bool TryKeywordIdentFallback(bool DisableKeyword);
687 /// \brief Get the TemplateIdAnnotation from the token.
688 TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
690 /// TentativeParsingAction - An object that is used as a kind of "tentative
691 /// parsing transaction". It gets instantiated to mark the token position and
692 /// after the token consumption is done, Commit() or Revert() is called to
693 /// either "commit the consumed tokens" or revert to the previously marked
694 /// token position. Example:
696 /// TentativeParsingAction TPA(*this);
701 class TentativeParsingAction {
704 size_t PrevTentativelyDeclaredIdentifierCount;
705 unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
709 explicit TentativeParsingAction(Parser& p) : P(p) {
711 PrevTentativelyDeclaredIdentifierCount =
712 P.TentativelyDeclaredIdentifiers.size();
713 PrevParenCount = P.ParenCount;
714 PrevBracketCount = P.BracketCount;
715 PrevBraceCount = P.BraceCount;
716 P.PP.EnableBacktrackAtThisPos();
720 assert(isActive && "Parsing action was finished!");
721 P.TentativelyDeclaredIdentifiers.resize(
722 PrevTentativelyDeclaredIdentifierCount);
723 P.PP.CommitBacktrackedTokens();
727 assert(isActive && "Parsing action was finished!");
730 P.TentativelyDeclaredIdentifiers.resize(
731 PrevTentativelyDeclaredIdentifierCount);
732 P.ParenCount = PrevParenCount;
733 P.BracketCount = PrevBracketCount;
734 P.BraceCount = PrevBraceCount;
737 ~TentativeParsingAction() {
738 assert(!isActive && "Forgot to call Commit or Revert!");
741 /// A TentativeParsingAction that automatically reverts in its destructor.
742 /// Useful for disambiguation parses that will always be reverted.
743 class RevertingTentativeParsingAction
744 : private Parser::TentativeParsingAction {
746 RevertingTentativeParsingAction(Parser &P)
747 : Parser::TentativeParsingAction(P) {}
748 ~RevertingTentativeParsingAction() { Revert(); }
751 class UnannotatedTentativeParsingAction;
753 /// ObjCDeclContextSwitch - An object used to switch context from
754 /// an objective-c decl context to its enclosing decl context and
756 class ObjCDeclContextSwitch {
759 SaveAndRestore<bool> WithinObjCContainer;
761 explicit ObjCDeclContextSwitch(Parser &p)
762 : P(p), DC(p.getObjCDeclContext()),
763 WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) {
765 P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC));
767 ~ObjCDeclContextSwitch() {
769 P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC));
773 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
774 /// input. If so, it is consumed and false is returned.
776 /// If a trivial punctuator misspelling is encountered, a FixIt error
777 /// diagnostic is issued and false is returned after recovery.
779 /// If the input is malformed, this emits the specified diagnostic and true is
781 bool ExpectAndConsume(tok::TokenKind ExpectedTok,
782 unsigned Diag = diag::err_expected,
783 StringRef DiagMsg = "");
785 /// \brief The parser expects a semicolon and, if present, will consume it.
787 /// If the next token is not a semicolon, this emits the specified diagnostic,
788 /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
789 /// to the semicolon, consumes that extra token.
790 bool ExpectAndConsumeSemi(unsigned DiagID);
792 /// \brief The kind of extra semi diagnostic to emit.
796 InstanceVariableList = 2,
797 AfterMemberFunctionDefinition = 3
800 /// \brief Consume any extra semi-colons until the end of the line.
801 void ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST = TST_unspecified);
803 /// Return false if the next token is an identifier. An 'expected identifier'
804 /// error is emitted otherwise.
806 /// The parser tries to recover from the error by checking if the next token
807 /// is a C++ keyword when parsing Objective-C++. Return false if the recovery
809 bool expectIdentifier();
812 //===--------------------------------------------------------------------===//
813 // Scope manipulation
815 /// ParseScope - Introduces a new scope for parsing. The kind of
816 /// scope is determined by ScopeFlags. Objects of this type should
817 /// be created on the stack to coincide with the position where the
818 /// parser enters the new scope, and this object's constructor will
819 /// create that new scope. Similarly, once the object is destroyed
820 /// the parser will exit the scope.
823 ParseScope(const ParseScope &) = delete;
824 void operator=(const ParseScope &) = delete;
827 // ParseScope - Construct a new object to manage a scope in the
828 // parser Self where the new Scope is created with the flags
829 // ScopeFlags, but only when we aren't about to enter a compound statement.
830 ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true,
831 bool BeforeCompoundStmt = false)
833 if (EnteredScope && !BeforeCompoundStmt)
834 Self->EnterScope(ScopeFlags);
836 if (BeforeCompoundStmt)
837 Self->incrementMSManglingNumber();
839 this->Self = nullptr;
843 // Exit - Exit the scope associated with this object now, rather
844 // than waiting until the object is destroyed.
857 /// EnterScope - Start a new scope.
858 void EnterScope(unsigned ScopeFlags);
860 /// ExitScope - Pop a scope off the scope stack.
864 /// \brief RAII object used to modify the scope flags for the current scope.
865 class ParseScopeFlags {
868 ParseScopeFlags(const ParseScopeFlags &) = delete;
869 void operator=(const ParseScopeFlags &) = delete;
872 ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
876 //===--------------------------------------------------------------------===//
877 // Diagnostic Emission and Error recovery.
880 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
881 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
882 DiagnosticBuilder Diag(unsigned DiagID) {
883 return Diag(Tok, DiagID);
887 void SuggestParentheses(SourceLocation Loc, unsigned DK,
888 SourceRange ParenRange);
889 void CheckNestedObjCContexts(SourceLocation AtLoc);
893 /// \brief Control flags for SkipUntil functions.
894 enum SkipUntilFlags {
895 StopAtSemi = 1 << 0, ///< Stop skipping at semicolon
896 /// \brief Stop skipping at specified token, but don't skip the token itself
897 StopBeforeMatch = 1 << 1,
898 StopAtCodeCompletion = 1 << 2 ///< Stop at code completion
901 friend constexpr SkipUntilFlags operator|(SkipUntilFlags L,
903 return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) |
904 static_cast<unsigned>(R));
907 /// SkipUntil - Read tokens until we get to the specified token, then consume
908 /// it (unless StopBeforeMatch is specified). Because we cannot guarantee
909 /// that the token will ever occur, this skips to the next token, or to some
910 /// likely good stopping point. If Flags has StopAtSemi flag, skipping will
911 /// stop at a ';' character.
913 /// If SkipUntil finds the specified token, it returns true, otherwise it
915 bool SkipUntil(tok::TokenKind T,
916 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
917 return SkipUntil(llvm::makeArrayRef(T), Flags);
919 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2,
920 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
921 tok::TokenKind TokArray[] = {T1, T2};
922 return SkipUntil(TokArray, Flags);
924 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3,
925 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
926 tok::TokenKind TokArray[] = {T1, T2, T3};
927 return SkipUntil(TokArray, Flags);
929 bool SkipUntil(ArrayRef<tok::TokenKind> Toks,
930 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0));
932 /// SkipMalformedDecl - Read tokens until we get to some likely good stopping
933 /// point for skipping past a simple-declaration.
934 void SkipMalformedDecl();
937 //===--------------------------------------------------------------------===//
938 // Lexing and parsing of C++ inline methods.
942 /// [class.mem]p1: "... the class is regarded as complete within
943 /// - function bodies
944 /// - default arguments
945 /// - exception-specifications (TODO: C++0x)
946 /// - and brace-or-equal-initializers for non-static data members
947 /// (including such things in nested classes)."
948 /// LateParsedDeclarations build the tree of those elements so they can
949 /// be parsed after parsing the top-level class.
950 class LateParsedDeclaration {
952 virtual ~LateParsedDeclaration();
954 virtual void ParseLexedMethodDeclarations();
955 virtual void ParseLexedMemberInitializers();
956 virtual void ParseLexedMethodDefs();
957 virtual void ParseLexedAttributes();
960 /// Inner node of the LateParsedDeclaration tree that parses
961 /// all its members recursively.
962 class LateParsedClass : public LateParsedDeclaration {
964 LateParsedClass(Parser *P, ParsingClass *C);
965 ~LateParsedClass() override;
967 void ParseLexedMethodDeclarations() override;
968 void ParseLexedMemberInitializers() override;
969 void ParseLexedMethodDefs() override;
970 void ParseLexedAttributes() override;
977 /// Contains the lexed tokens of an attribute with arguments that
978 /// may reference member variables and so need to be parsed at the
979 /// end of the class declaration after parsing all other member
980 /// member declarations.
981 /// FIXME: Perhaps we should change the name of LateParsedDeclaration to
982 /// LateParsedTokens.
983 struct LateParsedAttribute : public LateParsedDeclaration {
986 IdentifierInfo &AttrName;
987 SourceLocation AttrNameLoc;
988 SmallVector<Decl*, 2> Decls;
990 explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
992 : Self(P), AttrName(Name), AttrNameLoc(Loc) {}
994 void ParseLexedAttributes() override;
996 void addDecl(Decl *D) { Decls.push_back(D); }
999 // A list of late-parsed attributes. Used by ParseGNUAttributes.
1000 class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> {
1002 LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { }
1004 bool parseSoon() { return ParseSoon; }
1007 bool ParseSoon; // Are we planning to parse these shortly after creation?
1010 /// Contains the lexed tokens of a member function definition
1011 /// which needs to be parsed at the end of the class declaration
1012 /// after parsing all other member declarations.
1013 struct LexedMethod : public LateParsedDeclaration {
1018 /// \brief Whether this member function had an associated template
1019 /// scope. When true, D is a template declaration.
1020 /// otherwise, it is a member function declaration.
1023 explicit LexedMethod(Parser* P, Decl *MD)
1024 : Self(P), D(MD), TemplateScope(false) {}
1026 void ParseLexedMethodDefs() override;
1029 /// LateParsedDefaultArgument - Keeps track of a parameter that may
1030 /// have a default argument that cannot be parsed yet because it
1031 /// occurs within a member function declaration inside the class
1032 /// (C++ [class.mem]p2).
1033 struct LateParsedDefaultArgument {
1034 explicit LateParsedDefaultArgument(Decl *P,
1035 std::unique_ptr<CachedTokens> Toks = nullptr)
1036 : Param(P), Toks(std::move(Toks)) { }
1038 /// Param - The parameter declaration for this parameter.
1041 /// Toks - The sequence of tokens that comprises the default
1042 /// argument expression, not including the '=' or the terminating
1043 /// ')' or ','. This will be NULL for parameters that have no
1044 /// default argument.
1045 std::unique_ptr<CachedTokens> Toks;
1048 /// LateParsedMethodDeclaration - A method declaration inside a class that
1049 /// contains at least one entity whose parsing needs to be delayed
1050 /// until the class itself is completely-defined, such as a default
1051 /// argument (C++ [class.mem]p2).
1052 struct LateParsedMethodDeclaration : public LateParsedDeclaration {
1053 explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
1054 : Self(P), Method(M), TemplateScope(false),
1055 ExceptionSpecTokens(nullptr) {}
1057 void ParseLexedMethodDeclarations() override;
1061 /// Method - The method declaration.
1064 /// \brief Whether this member function had an associated template
1065 /// scope. When true, D is a template declaration.
1066 /// othewise, it is a member function declaration.
1069 /// DefaultArgs - Contains the parameters of the function and
1070 /// their default arguments. At least one of the parameters will
1071 /// have a default argument, but all of the parameters of the
1072 /// method will be stored so that they can be reintroduced into
1073 /// scope at the appropriate times.
1074 SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
1076 /// \brief The set of tokens that make up an exception-specification that
1077 /// has not yet been parsed.
1078 CachedTokens *ExceptionSpecTokens;
1081 /// LateParsedMemberInitializer - An initializer for a non-static class data
1082 /// member whose parsing must to be delayed until the class is completely
1083 /// defined (C++11 [class.mem]p2).
1084 struct LateParsedMemberInitializer : public LateParsedDeclaration {
1085 LateParsedMemberInitializer(Parser *P, Decl *FD)
1086 : Self(P), Field(FD) { }
1088 void ParseLexedMemberInitializers() override;
1092 /// Field - The field declaration.
1095 /// CachedTokens - The sequence of tokens that comprises the initializer,
1096 /// including any leading '='.
1100 /// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
1101 /// C++ class, its method declarations that contain parts that won't be
1102 /// parsed until after the definition is completed (C++ [class.mem]p2),
1103 /// the method declarations and possibly attached inline definitions
1104 /// will be stored here with the tokens that will be parsed to create those
1106 typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer;
1108 /// \brief Representation of a class that has been parsed, including
1109 /// any member function declarations or definitions that need to be
1110 /// parsed after the corresponding top-level class is complete.
1111 struct ParsingClass {
1112 ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface)
1113 : TopLevelClass(TopLevelClass), TemplateScope(false),
1114 IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) { }
1116 /// \brief Whether this is a "top-level" class, meaning that it is
1117 /// not nested within another class.
1118 bool TopLevelClass : 1;
1120 /// \brief Whether this class had an associated template
1121 /// scope. When true, TagOrTemplate is a template declaration;
1122 /// othewise, it is a tag declaration.
1123 bool TemplateScope : 1;
1125 /// \brief Whether this class is an __interface.
1126 bool IsInterface : 1;
1128 /// \brief The class or class template whose definition we are parsing.
1129 Decl *TagOrTemplate;
1131 /// LateParsedDeclarations - Method declarations, inline definitions and
1132 /// nested classes that contain pieces whose parsing will be delayed until
1133 /// the top-level class is fully defined.
1134 LateParsedDeclarationsContainer LateParsedDeclarations;
1137 /// \brief The stack of classes that is currently being
1138 /// parsed. Nested and local classes will be pushed onto this stack
1139 /// when they are parsed, and removed afterward.
1140 std::stack<ParsingClass *> ClassStack;
1142 ParsingClass &getCurrentClass() {
1143 assert(!ClassStack.empty() && "No lexed method stacks!");
1144 return *ClassStack.top();
1147 /// \brief RAII object used to manage the parsing of a class definition.
1148 class ParsingClassDefinition {
1151 Sema::ParsingClassState State;
1154 ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass,
1156 : P(P), Popped(false),
1157 State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
1160 /// \brief Pop this class of the stack.
1162 assert(!Popped && "Nested class has already been popped");
1164 P.PopParsingClass(State);
1167 ~ParsingClassDefinition() {
1169 P.PopParsingClass(State);
1173 /// \brief Contains information about any template-specific
1174 /// information that has been parsed prior to parsing declaration
1176 struct ParsedTemplateInfo {
1177 ParsedTemplateInfo()
1178 : Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { }
1180 ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
1181 bool isSpecialization,
1182 bool lastParameterListWasEmpty = false)
1183 : Kind(isSpecialization? ExplicitSpecialization : Template),
1184 TemplateParams(TemplateParams),
1185 LastParameterListWasEmpty(lastParameterListWasEmpty) { }
1187 explicit ParsedTemplateInfo(SourceLocation ExternLoc,
1188 SourceLocation TemplateLoc)
1189 : Kind(ExplicitInstantiation), TemplateParams(nullptr),
1190 ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
1191 LastParameterListWasEmpty(false){ }
1193 /// \brief The kind of template we are parsing.
1195 /// \brief We are not parsing a template at all.
1197 /// \brief We are parsing a template declaration.
1199 /// \brief We are parsing an explicit specialization.
1200 ExplicitSpecialization,
1201 /// \brief We are parsing an explicit instantiation.
1202 ExplicitInstantiation
1205 /// \brief The template parameter lists, for template declarations
1206 /// and explicit specializations.
1207 TemplateParameterLists *TemplateParams;
1209 /// \brief The location of the 'extern' keyword, if any, for an explicit
1211 SourceLocation ExternLoc;
1213 /// \brief The location of the 'template' keyword, for an explicit
1215 SourceLocation TemplateLoc;
1217 /// \brief Whether the last template parameter list was empty.
1218 bool LastParameterListWasEmpty;
1220 SourceRange getSourceRange() const LLVM_READONLY;
1223 void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
1224 void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
1226 static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
1227 static void LateTemplateParserCleanupCallback(void *P);
1229 Sema::ParsingClassState
1230 PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface);
1231 void DeallocateParsedClasses(ParsingClass *Class);
1232 void PopParsingClass(Sema::ParsingClassState);
1234 enum CachedInitKind {
1235 CIK_DefaultArgument,
1236 CIK_DefaultInitializer
1239 NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS,
1240 AttributeList *AccessAttrs,
1241 ParsingDeclarator &D,
1242 const ParsedTemplateInfo &TemplateInfo,
1243 const VirtSpecifiers& VS,
1244 SourceLocation PureSpecLoc);
1245 void ParseCXXNonStaticMemberInitializer(Decl *VarD);
1246 void ParseLexedAttributes(ParsingClass &Class);
1247 void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1248 bool EnterScope, bool OnDefinition);
1249 void ParseLexedAttribute(LateParsedAttribute &LA,
1250 bool EnterScope, bool OnDefinition);
1251 void ParseLexedMethodDeclarations(ParsingClass &Class);
1252 void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
1253 void ParseLexedMethodDefs(ParsingClass &Class);
1254 void ParseLexedMethodDef(LexedMethod &LM);
1255 void ParseLexedMemberInitializers(ParsingClass &Class);
1256 void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
1257 void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod);
1258 bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
1259 bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK);
1260 bool ConsumeAndStoreConditional(CachedTokens &Toks);
1261 bool ConsumeAndStoreUntil(tok::TokenKind T1,
1263 bool StopAtSemi = true,
1264 bool ConsumeFinalToken = true) {
1265 return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
1267 bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
1269 bool StopAtSemi = true,
1270 bool ConsumeFinalToken = true);
1272 //===--------------------------------------------------------------------===//
1273 // C99 6.9: External Definitions.
1274 struct ParsedAttributesWithRange : ParsedAttributes {
1275 ParsedAttributesWithRange(AttributeFactory &factory)
1276 : ParsedAttributes(factory) {}
1279 ParsedAttributes::clear();
1280 Range = SourceRange();
1286 DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
1287 ParsingDeclSpec *DS = nullptr);
1288 bool isDeclarationAfterDeclarator();
1289 bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
1290 DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(
1291 ParsedAttributesWithRange &attrs,
1292 ParsingDeclSpec *DS = nullptr,
1293 AccessSpecifier AS = AS_none);
1294 DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
1295 ParsingDeclSpec &DS,
1296 AccessSpecifier AS);
1298 void SkipFunctionBody();
1299 Decl *ParseFunctionDefinition(ParsingDeclarator &D,
1300 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1301 LateParsedAttrList *LateParsedAttrs = nullptr);
1302 void ParseKNRParamDeclarations(Declarator &D);
1303 // EndLoc, if non-NULL, is filled with the location of the last token of
1305 ExprResult ParseSimpleAsm(SourceLocation *EndLoc = nullptr);
1306 ExprResult ParseAsmStringLiteral();
1308 // Objective-C External Declarations
1309 void MaybeSkipAttributes(tok::ObjCKeywordKind Kind);
1310 DeclGroupPtrTy ParseObjCAtDirectives();
1311 DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
1312 Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
1313 ParsedAttributes &prefixAttrs);
1314 class ObjCTypeParamListScope;
1315 ObjCTypeParamList *parseObjCTypeParamList();
1316 ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs(
1317 ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
1318 SmallVectorImpl<IdentifierLocPair> &protocolIdents,
1319 SourceLocation &rAngleLoc, bool mayBeProtocolList = true);
1321 void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
1322 BalancedDelimiterTracker &T,
1323 SmallVectorImpl<Decl *> &AllIvarDecls,
1324 bool RBraceMissing);
1325 void ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1326 tok::ObjCKeywordKind visibility,
1327 SourceLocation atLoc);
1328 bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P,
1329 SmallVectorImpl<SourceLocation> &PLocs,
1330 bool WarnOnDeclarations,
1331 bool ForObjCContainer,
1332 SourceLocation &LAngleLoc,
1333 SourceLocation &EndProtoLoc,
1334 bool consumeLastToken);
1336 /// Parse the first angle-bracket-delimited clause for an
1337 /// Objective-C object or object pointer type, which may be either
1338 /// type arguments or protocol qualifiers.
1339 void parseObjCTypeArgsOrProtocolQualifiers(
1340 ParsedType baseType,
1341 SourceLocation &typeArgsLAngleLoc,
1342 SmallVectorImpl<ParsedType> &typeArgs,
1343 SourceLocation &typeArgsRAngleLoc,
1344 SourceLocation &protocolLAngleLoc,
1345 SmallVectorImpl<Decl *> &protocols,
1346 SmallVectorImpl<SourceLocation> &protocolLocs,
1347 SourceLocation &protocolRAngleLoc,
1348 bool consumeLastToken,
1349 bool warnOnIncompleteProtocols);
1351 /// Parse either Objective-C type arguments or protocol qualifiers; if the
1352 /// former, also parse protocol qualifiers afterward.
1353 void parseObjCTypeArgsAndProtocolQualifiers(
1354 ParsedType baseType,
1355 SourceLocation &typeArgsLAngleLoc,
1356 SmallVectorImpl<ParsedType> &typeArgs,
1357 SourceLocation &typeArgsRAngleLoc,
1358 SourceLocation &protocolLAngleLoc,
1359 SmallVectorImpl<Decl *> &protocols,
1360 SmallVectorImpl<SourceLocation> &protocolLocs,
1361 SourceLocation &protocolRAngleLoc,
1362 bool consumeLastToken);
1364 /// Parse a protocol qualifier type such as '<NSCopying>', which is
1365 /// an anachronistic way of writing 'id<NSCopying>'.
1366 TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc);
1368 /// Parse Objective-C type arguments and protocol qualifiers, extending the
1369 /// current type with the parsed result.
1370 TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc,
1372 bool consumeLastToken,
1373 SourceLocation &endLoc);
1375 void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
1377 DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
1378 ParsedAttributes &prefixAttrs);
1380 struct ObjCImplParsingDataRAII {
1384 typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer;
1385 LateParsedObjCMethodContainer LateParsedObjCMethods;
1387 ObjCImplParsingDataRAII(Parser &parser, Decl *D)
1388 : P(parser), Dcl(D), HasCFunction(false) {
1389 P.CurParsedObjCImpl = this;
1392 ~ObjCImplParsingDataRAII();
1394 void finish(SourceRange AtEnd);
1395 bool isFinished() const { return Finished; }
1400 ObjCImplParsingDataRAII *CurParsedObjCImpl;
1401 void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl);
1403 DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc);
1404 DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
1405 Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
1406 Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
1407 Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
1409 IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
1410 // Definitions for Objective-c context sensitive keywords recognition.
1412 objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
1413 objc_nonnull, objc_nullable, objc_null_unspecified,
1416 IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
1418 bool isTokIdentifier_in() const;
1420 ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, Declarator::TheContext Ctx,
1421 ParsedAttributes *ParamAttrs);
1422 void ParseObjCMethodRequirement();
1423 Decl *ParseObjCMethodPrototype(
1424 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1425 bool MethodDefinition = true);
1426 Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
1427 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1428 bool MethodDefinition=true);
1429 void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
1431 Decl *ParseObjCMethodDefinition();
1434 //===--------------------------------------------------------------------===//
1435 // C99 6.5: Expressions.
1437 /// TypeCastState - State whether an expression is or may be a type cast.
1438 enum TypeCastState {
1444 ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast);
1445 ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast);
1446 ExprResult ParseConstraintExpression();
1447 // Expr that doesn't include commas.
1448 ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast);
1450 ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1451 unsigned &NumLineToksConsumed,
1453 bool IsUnevaluated);
1456 ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
1458 ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
1460 ExprResult ParseRHSOfBinaryExpression(ExprResult LHS,
1461 prec::Level MinPrec);
1462 ExprResult ParseCastExpression(bool isUnaryExpression,
1463 bool isAddressOfOperand,
1465 TypeCastState isTypeCast,
1466 bool isVectorLiteral = false);
1467 ExprResult ParseCastExpression(bool isUnaryExpression,
1468 bool isAddressOfOperand = false,
1469 TypeCastState isTypeCast = NotTypeCast,
1470 bool isVectorLiteral = false);
1472 /// Returns true if the next token cannot start an expression.
1473 bool isNotExpressionStart();
1475 /// Returns true if the next token would start a postfix-expression
1477 bool isPostfixExpressionSuffixStart() {
1478 tok::TokenKind K = Tok.getKind();
1479 return (K == tok::l_square || K == tok::l_paren ||
1480 K == tok::period || K == tok::arrow ||
1481 K == tok::plusplus || K == tok::minusminus);
1484 ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
1485 ExprResult ParseUnaryExprOrTypeTraitExpression();
1486 ExprResult ParseBuiltinPrimaryExpression();
1488 ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1491 SourceRange &CastRange);
1493 typedef SmallVector<Expr*, 20> ExprListTy;
1494 typedef SmallVector<SourceLocation, 20> CommaLocsTy;
1496 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1497 bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
1498 SmallVectorImpl<SourceLocation> &CommaLocs,
1499 std::function<void()> Completer = nullptr);
1501 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
1502 /// used for misc language extensions.
1503 bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
1504 SmallVectorImpl<SourceLocation> &CommaLocs);
1507 /// ParenParseOption - Control what ParseParenExpression will parse.
1508 enum ParenParseOption {
1509 SimpleExpr, // Only parse '(' expression ')'
1510 CompoundStmt, // Also allow '(' compound-statement ')'
1511 CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
1512 CastExpr // Also allow '(' type-name ')' <anything>
1514 ExprResult ParseParenExpression(ParenParseOption &ExprType,
1515 bool stopIfCastExpr,
1518 SourceLocation &RParenLoc);
1520 ExprResult ParseCXXAmbiguousParenExpression(
1521 ParenParseOption &ExprType, ParsedType &CastTy,
1522 BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt);
1523 ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
1524 SourceLocation LParenLoc,
1525 SourceLocation RParenLoc);
1527 ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
1529 ExprResult ParseGenericSelectionExpression();
1531 ExprResult ParseObjCBoolLiteral();
1533 ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T);
1535 //===--------------------------------------------------------------------===//
1537 ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
1538 Token &Replacement);
1539 ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
1541 bool areTokensAdjacent(const Token &A, const Token &B);
1543 void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
1544 bool EnteringContext, IdentifierInfo &II,
1547 bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
1548 ParsedType ObjectType,
1549 bool EnteringContext,
1550 bool *MayBePseudoDestructor = nullptr,
1551 bool IsTypename = false,
1552 IdentifierInfo **LastII = nullptr,
1553 bool OnlyNamespace = false);
1555 //===--------------------------------------------------------------------===//
1556 // C++0x 5.1.2: Lambda expressions
1558 // [...] () -> type {...}
1559 ExprResult ParseLambdaExpression();
1560 ExprResult TryParseLambdaExpression();
1561 Optional<unsigned> ParseLambdaIntroducer(LambdaIntroducer &Intro,
1562 bool *SkippedInits = nullptr);
1563 bool TryParseLambdaIntroducer(LambdaIntroducer &Intro);
1564 ExprResult ParseLambdaExpressionAfterIntroducer(
1565 LambdaIntroducer &Intro);
1567 //===--------------------------------------------------------------------===//
1568 // C++ 5.2p1: C++ Casts
1569 ExprResult ParseCXXCasts();
1571 //===--------------------------------------------------------------------===//
1572 // C++ 5.2p1: C++ Type Identification
1573 ExprResult ParseCXXTypeid();
1575 //===--------------------------------------------------------------------===//
1576 // C++ : Microsoft __uuidof Expression
1577 ExprResult ParseCXXUuidof();
1579 //===--------------------------------------------------------------------===//
1580 // C++ 5.2.4: C++ Pseudo-Destructor Expressions
1581 ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1582 tok::TokenKind OpKind,
1584 ParsedType ObjectType);
1586 //===--------------------------------------------------------------------===//
1587 // C++ 9.3.2: C++ 'this' pointer
1588 ExprResult ParseCXXThis();
1590 //===--------------------------------------------------------------------===//
1591 // C++ 15: C++ Throw Expression
1592 ExprResult ParseThrowExpression();
1594 ExceptionSpecificationType tryParseExceptionSpecification(
1596 SourceRange &SpecificationRange,
1597 SmallVectorImpl<ParsedType> &DynamicExceptions,
1598 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
1599 ExprResult &NoexceptExpr,
1600 CachedTokens *&ExceptionSpecTokens);
1602 // EndLoc is filled with the location of the last token of the specification.
1603 ExceptionSpecificationType ParseDynamicExceptionSpecification(
1604 SourceRange &SpecificationRange,
1605 SmallVectorImpl<ParsedType> &Exceptions,
1606 SmallVectorImpl<SourceRange> &Ranges);
1608 //===--------------------------------------------------------------------===//
1609 // C++0x 8: Function declaration trailing-return-type
1610 TypeResult ParseTrailingReturnType(SourceRange &Range);
1612 //===--------------------------------------------------------------------===//
1613 // C++ 2.13.5: C++ Boolean Literals
1614 ExprResult ParseCXXBoolLiteral();
1616 //===--------------------------------------------------------------------===//
1617 // C++ 5.2.3: Explicit type conversion (functional notation)
1618 ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
1620 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1621 /// This should only be called when the current token is known to be part of
1622 /// simple-type-specifier.
1623 void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
1625 bool ParseCXXTypeSpecifierSeq(DeclSpec &DS);
1627 //===--------------------------------------------------------------------===//
1628 // C++ 5.3.4 and 5.3.5: C++ new and delete
1629 bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs,
1631 void ParseDirectNewDeclarator(Declarator &D);
1632 ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
1633 ExprResult ParseCXXDeleteExpression(bool UseGlobal,
1634 SourceLocation Start);
1636 //===--------------------------------------------------------------------===//
1637 // C++ if/switch/while condition expression.
1638 Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt,
1640 Sema::ConditionKind CK);
1642 //===--------------------------------------------------------------------===//
1645 ExprResult ParseCoyieldExpression();
1647 //===--------------------------------------------------------------------===//
1648 // C99 6.7.8: Initialization.
1650 /// ParseInitializer
1651 /// initializer: [C99 6.7.8]
1652 /// assignment-expression
1654 ExprResult ParseInitializer() {
1655 if (Tok.isNot(tok::l_brace))
1656 return ParseAssignmentExpression();
1657 return ParseBraceInitializer();
1659 bool MayBeDesignationStart();
1660 ExprResult ParseBraceInitializer();
1661 ExprResult ParseInitializerWithPotentialDesignator();
1663 //===--------------------------------------------------------------------===//
1664 // clang Expressions
1666 ExprResult ParseBlockLiteralExpression(); // ^{...}
1668 //===--------------------------------------------------------------------===//
1669 // Objective-C Expressions
1670 ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
1671 ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
1672 ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
1673 ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
1674 ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
1675 ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
1676 ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
1677 ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
1678 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
1679 ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
1680 ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
1681 bool isSimpleObjCMessageExpression();
1682 ExprResult ParseObjCMessageExpression();
1683 ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
1684 SourceLocation SuperLoc,
1685 ParsedType ReceiverType,
1686 Expr *ReceiverExpr);
1687 ExprResult ParseAssignmentExprWithObjCMessageExprStart(
1688 SourceLocation LBracloc, SourceLocation SuperLoc,
1689 ParsedType ReceiverType, Expr *ReceiverExpr);
1690 bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
1692 //===--------------------------------------------------------------------===//
1693 // C99 6.8: Statements and Blocks.
1695 /// A SmallVector of statements, with stack size 32 (as that is the only one
1697 typedef SmallVector<Stmt*, 32> StmtVector;
1698 /// A SmallVector of expressions, with stack size 12 (the maximum used.)
1699 typedef SmallVector<Expr*, 12> ExprVector;
1700 /// A SmallVector of types.
1701 typedef SmallVector<ParsedType, 12> TypeVector;
1703 StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
1704 bool AllowOpenMPStandalone = false);
1705 enum AllowedConstructsKind {
1706 /// \brief Allow any declarations, statements, OpenMP directives.
1708 /// \brief Allow only statements and non-standalone OpenMP directives.
1709 ACK_StatementsOpenMPNonStandalone,
1710 /// \brief Allow statements and all executable OpenMP directives
1711 ACK_StatementsOpenMPAnyExecutable
1714 ParseStatementOrDeclaration(StmtVector &Stmts, AllowedConstructsKind Allowed,
1715 SourceLocation *TrailingElseLoc = nullptr);
1716 StmtResult ParseStatementOrDeclarationAfterAttributes(
1718 AllowedConstructsKind Allowed,
1719 SourceLocation *TrailingElseLoc,
1720 ParsedAttributesWithRange &Attrs);
1721 StmtResult ParseExprStatement();
1722 StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs);
1723 StmtResult ParseCaseStatement(bool MissingCase = false,
1724 ExprResult Expr = ExprResult());
1725 StmtResult ParseDefaultStatement();
1726 StmtResult ParseCompoundStatement(bool isStmtExpr = false);
1727 StmtResult ParseCompoundStatement(bool isStmtExpr,
1728 unsigned ScopeFlags);
1729 void ParseCompoundStatementLeadingPragmas();
1730 StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
1731 bool ParseParenExprOrCondition(StmtResult *InitStmt,
1732 Sema::ConditionResult &CondResult,
1734 Sema::ConditionKind CK);
1735 StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
1736 StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
1737 StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
1738 StmtResult ParseDoStatement();
1739 StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
1740 StmtResult ParseGotoStatement();
1741 StmtResult ParseContinueStatement();
1742 StmtResult ParseBreakStatement();
1743 StmtResult ParseReturnStatement();
1744 StmtResult ParseAsmStatement(bool &msAsm);
1745 StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
1746 StmtResult ParsePragmaLoopHint(StmtVector &Stmts,
1747 AllowedConstructsKind Allowed,
1748 SourceLocation *TrailingElseLoc,
1749 ParsedAttributesWithRange &Attrs);
1751 /// \brief Describes the behavior that should be taken for an __if_exists
1753 enum IfExistsBehavior {
1754 /// \brief Parse the block; this code is always used.
1756 /// \brief Skip the block entirely; this code is never used.
1758 /// \brief Parse the block as a dependent block, which may be used in
1759 /// some template instantiations but not others.
1763 /// \brief Describes the condition of a Microsoft __if_exists or
1764 /// __if_not_exists block.
1765 struct IfExistsCondition {
1766 /// \brief The location of the initial keyword.
1767 SourceLocation KeywordLoc;
1768 /// \brief Whether this is an __if_exists block (rather than an
1769 /// __if_not_exists block).
1772 /// \brief Nested-name-specifier preceding the name.
1775 /// \brief The name we're looking for.
1778 /// \brief The behavior of this __if_exists or __if_not_exists block
1780 IfExistsBehavior Behavior;
1783 bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
1784 void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
1785 void ParseMicrosoftIfExistsExternalDeclaration();
1786 void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
1787 AccessSpecifier& CurAS);
1788 bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
1790 bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
1791 SmallVectorImpl<Expr *> &Constraints,
1792 SmallVectorImpl<Expr *> &Exprs);
1794 //===--------------------------------------------------------------------===//
1795 // C++ 6: Statements and Blocks
1797 StmtResult ParseCXXTryBlock();
1798 StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
1799 StmtResult ParseCXXCatchBlock(bool FnCatch = false);
1801 //===--------------------------------------------------------------------===//
1802 // MS: SEH Statements and Blocks
1804 StmtResult ParseSEHTryBlock();
1805 StmtResult ParseSEHExceptBlock(SourceLocation Loc);
1806 StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
1807 StmtResult ParseSEHLeaveStatement();
1809 //===--------------------------------------------------------------------===//
1810 // Objective-C Statements
1812 StmtResult ParseObjCAtStatement(SourceLocation atLoc);
1813 StmtResult ParseObjCTryStmt(SourceLocation atLoc);
1814 StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
1815 StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
1816 StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
1819 //===--------------------------------------------------------------------===//
1820 // C99 6.7: Declarations.
1822 /// A context for parsing declaration specifiers. TODO: flesh this
1823 /// out, there are other significant restrictions on specifiers than
1824 /// would be best implemented in the parser.
1825 enum DeclSpecContext {
1826 DSC_normal, // normal context
1827 DSC_class, // class context, enables 'friend'
1828 DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
1829 DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
1830 DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration
1831 DSC_top_level, // top-level/namespace declaration context
1832 DSC_template_type_arg, // template type argument context
1833 DSC_objc_method_result, // ObjC method result context, enables 'instancetype'
1834 DSC_condition // condition declaration context
1837 /// Is this a context in which we are parsing just a type-specifier (or
1838 /// trailing-type-specifier)?
1839 static bool isTypeSpecifier(DeclSpecContext DSC) {
1844 case DSC_objc_method_result:
1848 case DSC_template_type_arg:
1849 case DSC_type_specifier:
1851 case DSC_alias_declaration:
1854 llvm_unreachable("Missing DeclSpecContext case");
1857 /// Is this a context in which we can perform class template argument
1859 static bool isClassTemplateDeductionContext(DeclSpecContext DSC) {
1865 case DSC_type_specifier:
1868 case DSC_objc_method_result:
1869 case DSC_template_type_arg:
1871 case DSC_alias_declaration:
1874 llvm_unreachable("Missing DeclSpecContext case");
1877 /// Information on a C++0x for-range-initializer found while parsing a
1878 /// declaration which turns out to be a for-range-declaration.
1879 struct ForRangeInit {
1880 SourceLocation ColonLoc;
1881 ExprResult RangeExpr;
1883 bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
1886 DeclGroupPtrTy ParseDeclaration(unsigned Context, SourceLocation &DeclEnd,
1887 ParsedAttributesWithRange &attrs);
1888 DeclGroupPtrTy ParseSimpleDeclaration(unsigned Context,
1889 SourceLocation &DeclEnd,
1890 ParsedAttributesWithRange &attrs,
1892 ForRangeInit *FRI = nullptr);
1893 bool MightBeDeclarator(unsigned Context);
1894 DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, unsigned Context,
1895 SourceLocation *DeclEnd = nullptr,
1896 ForRangeInit *FRI = nullptr);
1897 Decl *ParseDeclarationAfterDeclarator(Declarator &D,
1898 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
1899 bool ParseAsmAttributesAfterDeclarator(Declarator &D);
1900 Decl *ParseDeclarationAfterDeclaratorAndAttributes(
1902 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1903 ForRangeInit *FRI = nullptr);
1904 Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
1905 Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
1907 /// \brief When in code-completion, skip parsing of the function/method body
1908 /// unless the body contains the code-completion point.
1910 /// \returns true if the function body was skipped.
1911 bool trySkippingFunctionBody();
1913 bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
1914 const ParsedTemplateInfo &TemplateInfo,
1915 AccessSpecifier AS, DeclSpecContext DSC,
1916 ParsedAttributesWithRange &Attrs);
1917 DeclSpecContext getDeclSpecContextFromDeclaratorContext(unsigned Context);
1918 void ParseDeclarationSpecifiers(DeclSpec &DS,
1919 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1920 AccessSpecifier AS = AS_none,
1921 DeclSpecContext DSC = DSC_normal,
1922 LateParsedAttrList *LateAttrs = nullptr);
1923 bool DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
1924 DeclSpecContext DSContext,
1925 LateParsedAttrList *LateAttrs = nullptr);
1927 void ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS = AS_none,
1928 DeclSpecContext DSC = DSC_normal);
1930 void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
1931 Declarator::TheContext Context);
1933 void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
1934 const ParsedTemplateInfo &TemplateInfo,
1935 AccessSpecifier AS, DeclSpecContext DSC);
1936 void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
1937 void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType,
1940 void ParseStructDeclaration(
1941 ParsingDeclSpec &DS,
1942 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback);
1944 bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
1945 bool isTypeSpecifierQualifier();
1947 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
1948 /// is definitely a type-specifier. Return false if it isn't part of a type
1949 /// specifier or if we're not sure.
1950 bool isKnownToBeTypeSpecifier(const Token &Tok) const;
1952 /// \brief Return true if we know that we are definitely looking at a
1953 /// decl-specifier, and isn't part of an expression such as a function-style
1954 /// cast. Return false if it's no a decl-specifier, or we're not sure.
1955 bool isKnownToBeDeclarationSpecifier() {
1956 if (getLangOpts().CPlusPlus)
1957 return isCXXDeclarationSpecifier() == TPResult::True;
1958 return isDeclarationSpecifier(true);
1961 /// isDeclarationStatement - Disambiguates between a declaration or an
1962 /// expression statement, when parsing function bodies.
1963 /// Returns true for declaration, false for expression.
1964 bool isDeclarationStatement() {
1965 if (getLangOpts().CPlusPlus)
1966 return isCXXDeclarationStatement();
1967 return isDeclarationSpecifier(true);
1970 /// isForInitDeclaration - Disambiguates between a declaration or an
1971 /// expression in the context of the C 'clause-1' or the C++
1972 // 'for-init-statement' part of a 'for' statement.
1973 /// Returns true for declaration, false for expression.
1974 bool isForInitDeclaration() {
1975 if (getLangOpts().CPlusPlus)
1976 return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
1977 return isDeclarationSpecifier(true);
1980 /// \brief Determine whether this is a C++1z for-range-identifier.
1981 bool isForRangeIdentifier();
1983 /// \brief Determine whether we are currently at the start of an Objective-C
1984 /// class message that appears to be missing the open bracket '['.
1985 bool isStartOfObjCClassMessageMissingOpenBracket();
1987 /// \brief Starting with a scope specifier, identifier, or
1988 /// template-id that refers to the current class, determine whether
1989 /// this is a constructor declarator.
1990 bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false);
1992 /// \brief Specifies the context in which type-id/expression
1993 /// disambiguation will occur.
1994 enum TentativeCXXTypeIdContext {
1997 TypeIdAsTemplateArgument
2001 /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
2002 /// whether the parens contain an expression or a type-id.
2003 /// Returns true for a type-id and false for an expression.
2004 bool isTypeIdInParens(bool &isAmbiguous) {
2005 if (getLangOpts().CPlusPlus)
2006 return isCXXTypeId(TypeIdInParens, isAmbiguous);
2007 isAmbiguous = false;
2008 return isTypeSpecifierQualifier();
2010 bool isTypeIdInParens() {
2012 return isTypeIdInParens(isAmbiguous);
2015 /// \brief Checks if the current tokens form type-id or expression.
2016 /// It is similar to isTypeIdInParens but does not suppose that type-id
2017 /// is in parenthesis.
2018 bool isTypeIdUnambiguously() {
2020 if (getLangOpts().CPlusPlus)
2021 return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous);
2022 return isTypeSpecifierQualifier();
2025 /// isCXXDeclarationStatement - C++-specialized function that disambiguates
2026 /// between a declaration or an expression statement, when parsing function
2027 /// bodies. Returns true for declaration, false for expression.
2028 bool isCXXDeclarationStatement();
2030 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
2031 /// between a simple-declaration or an expression-statement.
2032 /// If during the disambiguation process a parsing error is encountered,
2033 /// the function returns true to let the declaration parsing code handle it.
2034 /// Returns false if the statement is disambiguated as expression.
2035 bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
2037 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
2038 /// a constructor-style initializer, when parsing declaration statements.
2039 /// Returns true for function declarator and false for constructor-style
2040 /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
2041 /// might be a constructor-style initializer.
2042 /// If during the disambiguation process a parsing error is encountered,
2043 /// the function returns true to let the declaration parsing code handle it.
2044 bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr);
2046 struct ConditionDeclarationOrInitStatementState;
2047 enum class ConditionOrInitStatement {
2048 Expression, ///< Disambiguated as an expression (either kind).
2049 ConditionDecl, ///< Disambiguated as the declaration form of condition.
2050 InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement.
2051 Error ///< Can't be any of the above!
2053 /// \brief Disambiguates between the different kinds of things that can happen
2054 /// after 'if (' or 'switch ('. This could be one of two different kinds of
2055 /// declaration (depending on whether there is a ';' later) or an expression.
2056 ConditionOrInitStatement
2057 isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt);
2059 bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
2060 bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
2062 return isCXXTypeId(Context, isAmbiguous);
2065 /// TPResult - Used as the result value for functions whose purpose is to
2066 /// disambiguate C++ constructs by "tentatively parsing" them.
2067 enum class TPResult {
2068 True, False, Ambiguous, Error
2071 /// \brief Based only on the given token kind, determine whether we know that
2072 /// we're at the start of an expression or a type-specifier-seq (which may
2073 /// be an expression, in C++).
2075 /// This routine does not attempt to resolve any of the trick cases, e.g.,
2076 /// those involving lookup of identifiers.
2078 /// \returns \c TPR_true if this token starts an expression, \c TPR_false if
2079 /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot
2081 TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind);
2083 /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a
2084 /// declaration specifier, TPResult::False if it is not,
2085 /// TPResult::Ambiguous if it could be either a decl-specifier or a
2086 /// function-style cast, and TPResult::Error if a parsing error was
2087 /// encountered. If it could be a braced C++11 function-style cast, returns
2088 /// BracedCastResult.
2089 /// Doesn't consume tokens.
2091 isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False,
2092 bool *HasMissingTypename = nullptr);
2094 /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
2095 /// \c TPResult::Ambiguous, determine whether the decl-specifier would be
2096 /// a type-specifier other than a cv-qualifier.
2097 bool isCXXDeclarationSpecifierAType();
2099 /// \brief Determine whether an identifier has been tentatively declared as a
2100 /// non-type. Such tentative declarations should not be found to name a type
2101 /// during a tentative parse, but also should not be annotated as a non-type.
2102 bool isTentativelyDeclared(IdentifierInfo *II);
2104 // "Tentative parsing" functions, used for disambiguation. If a parsing error
2105 // is encountered they will return TPResult::Error.
2106 // Returning TPResult::True/False indicates that the ambiguity was
2107 // resolved and tentative parsing may stop. TPResult::Ambiguous indicates
2108 // that more tentative parsing is necessary for disambiguation.
2109 // They all consume tokens, so backtracking should be used after calling them.
2111 TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
2112 TPResult TryParseTypeofSpecifier();
2113 TPResult TryParseProtocolQualifiers();
2114 TPResult TryParsePtrOperatorSeq();
2115 TPResult TryParseOperatorId();
2116 TPResult TryParseInitDeclaratorList();
2117 TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier=true);
2119 TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr,
2120 bool VersusTemplateArg = false);
2121 TPResult TryParseFunctionDeclarator();
2122 TPResult TryParseBracketDeclarator();
2123 TPResult TryConsumeDeclarationSpecifier();
2126 TypeResult ParseTypeName(SourceRange *Range = nullptr,
2127 Declarator::TheContext Context
2128 = Declarator::TypeNameContext,
2129 AccessSpecifier AS = AS_none,
2130 Decl **OwnedType = nullptr,
2131 ParsedAttributes *Attrs = nullptr);
2134 void ParseBlockId(SourceLocation CaretLoc);
2136 // Check for the start of a C++11 attribute-specifier-seq in a context where
2137 // an attribute is not allowed.
2138 bool CheckProhibitedCXX11Attribute() {
2139 assert(Tok.is(tok::l_square));
2140 if (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))
2142 return DiagnoseProhibitedCXX11Attribute();
2144 bool DiagnoseProhibitedCXX11Attribute();
2145 void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2146 SourceLocation CorrectLocation) {
2147 if (!getLangOpts().CPlusPlus11)
2149 if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
2150 Tok.isNot(tok::kw_alignas))
2152 DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
2154 void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2155 SourceLocation CorrectLocation);
2157 void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
2158 DeclSpec &DS, Sema::TagUseKind TUK);
2160 void ProhibitAttributes(ParsedAttributesWithRange &attrs) {
2161 if (!attrs.Range.isValid()) return;
2162 DiagnoseProhibitedAttributes(attrs);
2165 void DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs);
2167 // Forbid C++11 attributes that appear on certain syntactic
2168 // locations which standard permits but we don't supported yet,
2169 // for example, attributes appertain to decl specifiers.
2170 void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
2173 /// \brief Skip C++11 attributes and return the end location of the last one.
2174 /// \returns SourceLocation() if there are no attributes.
2175 SourceLocation SkipCXX11Attributes();
2177 /// \brief Diagnose and skip C++11 attributes that appear in syntactic
2178 /// locations where attributes are not allowed.
2179 void DiagnoseAndSkipCXX11Attributes();
2181 /// \brief Parses syntax-generic attribute arguments for attributes which are
2182 /// known to the implementation, and adds them to the given ParsedAttributes
2183 /// list with the given attribute syntax. Returns the number of arguments
2184 /// parsed for the attribute.
2186 ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2187 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2188 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2189 AttributeList::Syntax Syntax);
2191 void MaybeParseGNUAttributes(Declarator &D,
2192 LateParsedAttrList *LateAttrs = nullptr) {
2193 if (Tok.is(tok::kw___attribute)) {
2194 ParsedAttributes attrs(AttrFactory);
2195 SourceLocation endLoc;
2196 ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D);
2197 D.takeAttributes(attrs, endLoc);
2200 void MaybeParseGNUAttributes(ParsedAttributes &attrs,
2201 SourceLocation *endLoc = nullptr,
2202 LateParsedAttrList *LateAttrs = nullptr) {
2203 if (Tok.is(tok::kw___attribute))
2204 ParseGNUAttributes(attrs, endLoc, LateAttrs);
2206 void ParseGNUAttributes(ParsedAttributes &attrs,
2207 SourceLocation *endLoc = nullptr,
2208 LateParsedAttrList *LateAttrs = nullptr,
2209 Declarator *D = nullptr);
2210 void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
2211 SourceLocation AttrNameLoc,
2212 ParsedAttributes &Attrs,
2213 SourceLocation *EndLoc,
2214 IdentifierInfo *ScopeName,
2215 SourceLocation ScopeLoc,
2216 AttributeList::Syntax Syntax,
2218 IdentifierLoc *ParseIdentifierLoc();
2221 ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2222 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2223 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2224 AttributeList::Syntax Syntax);
2226 void MaybeParseCXX11Attributes(Declarator &D) {
2227 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
2228 ParsedAttributesWithRange attrs(AttrFactory);
2229 SourceLocation endLoc;
2230 ParseCXX11Attributes(attrs, &endLoc);
2231 D.takeAttributes(attrs, endLoc);
2234 void MaybeParseCXX11Attributes(ParsedAttributes &attrs,
2235 SourceLocation *endLoc = nullptr) {
2236 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
2237 ParsedAttributesWithRange attrsWithRange(AttrFactory);
2238 ParseCXX11Attributes(attrsWithRange, endLoc);
2239 attrs.takeAllFrom(attrsWithRange);
2242 void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2243 SourceLocation *endLoc = nullptr,
2244 bool OuterMightBeMessageSend = false) {
2245 if (getLangOpts().CPlusPlus11 &&
2246 isCXX11AttributeSpecifier(false, OuterMightBeMessageSend))
2247 ParseCXX11Attributes(attrs, endLoc);
2250 void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
2251 SourceLocation *EndLoc = nullptr);
2252 void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2253 SourceLocation *EndLoc = nullptr);
2254 /// \brief Parses a C++-style attribute argument list. Returns true if this
2255 /// results in adding an attribute to the ParsedAttributes list.
2256 bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
2257 SourceLocation AttrNameLoc,
2258 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2259 IdentifierInfo *ScopeName,
2260 SourceLocation ScopeLoc);
2262 IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc);
2264 void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
2265 SourceLocation *endLoc = nullptr) {
2266 if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
2267 ParseMicrosoftAttributes(attrs, endLoc);
2269 void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs);
2270 void ParseMicrosoftAttributes(ParsedAttributes &attrs,
2271 SourceLocation *endLoc = nullptr);
2272 void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2273 SourceLocation *End = nullptr) {
2274 const auto &LO = getLangOpts();
2275 if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec))
2276 ParseMicrosoftDeclSpecs(Attrs, End);
2278 void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2279 SourceLocation *End = nullptr);
2280 bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
2281 SourceLocation AttrNameLoc,
2282 ParsedAttributes &Attrs);
2283 void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
2284 void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2285 SourceLocation SkipExtendedMicrosoftTypeAttributes();
2286 void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
2287 void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
2288 void ParseOpenCLKernelAttributes(ParsedAttributes &attrs);
2289 void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
2290 /// \brief Parses opencl_unroll_hint attribute if language is OpenCL v2.0
2292 /// \return false if error happens.
2293 bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
2294 if (getLangOpts().OpenCL)
2295 return ParseOpenCLUnrollHintAttribute(Attrs);
2298 /// \brief Parses opencl_unroll_hint attribute.
2299 /// \return false if error happens.
2300 bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs);
2301 void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
2303 VersionTuple ParseVersionTuple(SourceRange &Range);
2304 void ParseAvailabilityAttribute(IdentifierInfo &Availability,
2305 SourceLocation AvailabilityLoc,
2306 ParsedAttributes &attrs,
2307 SourceLocation *endLoc,
2308 IdentifierInfo *ScopeName,
2309 SourceLocation ScopeLoc,
2310 AttributeList::Syntax Syntax);
2312 Optional<AvailabilitySpec> ParseAvailabilitySpec();
2313 ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc);
2315 void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol,
2317 ParsedAttributes &Attrs,
2318 SourceLocation *EndLoc,
2319 IdentifierInfo *ScopeName,
2320 SourceLocation ScopeLoc,
2321 AttributeList::Syntax Syntax);
2323 void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
2324 SourceLocation ObjCBridgeRelatedLoc,
2325 ParsedAttributes &attrs,
2326 SourceLocation *endLoc,
2327 IdentifierInfo *ScopeName,
2328 SourceLocation ScopeLoc,
2329 AttributeList::Syntax Syntax);
2331 void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
2332 SourceLocation AttrNameLoc,
2333 ParsedAttributes &Attrs,
2334 SourceLocation *EndLoc,
2335 IdentifierInfo *ScopeName,
2336 SourceLocation ScopeLoc,
2337 AttributeList::Syntax Syntax);
2339 void ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
2340 SourceLocation AttrNameLoc,
2341 ParsedAttributes &Attrs,
2342 SourceLocation *EndLoc,
2343 IdentifierInfo *ScopeName,
2344 SourceLocation ScopeLoc,
2345 AttributeList::Syntax Syntax);
2347 void ParseTypeofSpecifier(DeclSpec &DS);
2348 SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
2349 void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
2350 SourceLocation StartLoc,
2351 SourceLocation EndLoc);
2352 void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
2353 void ParseAtomicSpecifier(DeclSpec &DS);
2355 ExprResult ParseAlignArgument(SourceLocation Start,
2356 SourceLocation &EllipsisLoc);
2357 void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2358 SourceLocation *endLoc = nullptr);
2360 VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
2361 VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
2362 return isCXX11VirtSpecifier(Tok);
2364 void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface,
2365 SourceLocation FriendLoc);
2367 bool isCXX11FinalKeyword() const;
2369 /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
2370 /// enter a new C++ declarator scope and exit it when the function is
2372 class DeclaratorScopeObj {
2378 DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
2379 : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
2381 void EnterDeclaratorScope() {
2382 assert(!EnteredScope && "Already entered the scope!");
2383 assert(SS.isSet() && "C++ scope was not set!");
2385 CreatedScope = true;
2386 P.EnterScope(0); // Not a decl scope.
2388 if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
2389 EnteredScope = true;
2392 ~DeclaratorScopeObj() {
2394 assert(SS.isSet() && "C++ scope was cleared ?");
2395 P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
2402 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
2403 void ParseDeclarator(Declarator &D);
2404 /// A function that parses a variant of direct-declarator.
2405 typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
2406 void ParseDeclaratorInternal(Declarator &D,
2407 DirectDeclParseFunction DirectDeclParser);
2409 enum AttrRequirements {
2410 AR_NoAttributesParsed = 0, ///< No attributes are diagnosed.
2411 AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes.
2412 AR_GNUAttributesParsed = 1 << 1,
2413 AR_CXX11AttributesParsed = 1 << 2,
2414 AR_DeclspecAttributesParsed = 1 << 3,
2415 AR_AllAttributesParsed = AR_GNUAttributesParsed |
2416 AR_CXX11AttributesParsed |
2417 AR_DeclspecAttributesParsed,
2418 AR_VendorAttributesParsed = AR_GNUAttributesParsed |
2419 AR_DeclspecAttributesParsed
2422 void ParseTypeQualifierListOpt(
2423 DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed,
2424 bool AtomicAllowed = true, bool IdentifierRequired = false,
2425 Optional<llvm::function_ref<void()>> CodeCompletionHandler = None);
2426 void ParseDirectDeclarator(Declarator &D);
2427 void ParseDecompositionDeclarator(Declarator &D);
2428 void ParseParenDeclarator(Declarator &D);
2429 void ParseFunctionDeclarator(Declarator &D,
2430 ParsedAttributes &attrs,
2431 BalancedDelimiterTracker &Tracker,
2433 bool RequiresArg = false);
2434 bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
2435 SourceLocation &RefQualifierLoc);
2436 bool isFunctionDeclaratorIdentifierList();
2437 void ParseFunctionDeclaratorIdentifierList(
2439 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
2440 void ParseParameterDeclarationClause(
2442 ParsedAttributes &attrs,
2443 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
2444 SourceLocation &EllipsisLoc);
2445 void ParseBracketDeclarator(Declarator &D);
2446 void ParseMisplacedBracketDeclarator(Declarator &D);
2448 //===--------------------------------------------------------------------===//
2449 // C++ 7: Declarations [dcl.dcl]
2451 /// The kind of attribute specifier we have found.
2452 enum CXX11AttributeKind {
2453 /// This is not an attribute specifier.
2454 CAK_NotAttributeSpecifier,
2455 /// This should be treated as an attribute-specifier.
2456 CAK_AttributeSpecifier,
2457 /// The next tokens are '[[', but this is not an attribute-specifier. This
2458 /// is ill-formed by C++11 [dcl.attr.grammar]p6.
2459 CAK_InvalidAttributeSpecifier
2462 isCXX11AttributeSpecifier(bool Disambiguate = false,
2463 bool OuterMightBeMessageSend = false);
2465 void DiagnoseUnexpectedNamespace(NamedDecl *Context);
2467 DeclGroupPtrTy ParseNamespace(unsigned Context, SourceLocation &DeclEnd,
2468 SourceLocation InlineLoc = SourceLocation());
2469 void ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc,
2470 std::vector<IdentifierInfo*>& Ident,
2471 std::vector<SourceLocation>& NamespaceLoc,
2472 unsigned int index, SourceLocation& InlineLoc,
2473 ParsedAttributes& attrs,
2474 BalancedDelimiterTracker &Tracker);
2475 Decl *ParseLinkage(ParsingDeclSpec &DS, unsigned Context);
2476 Decl *ParseExportDeclaration();
2477 DeclGroupPtrTy ParseUsingDirectiveOrDeclaration(
2478 unsigned Context, const ParsedTemplateInfo &TemplateInfo,
2479 SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs);
2480 Decl *ParseUsingDirective(unsigned Context,
2481 SourceLocation UsingLoc,
2482 SourceLocation &DeclEnd,
2483 ParsedAttributes &attrs);
2485 struct UsingDeclarator {
2486 SourceLocation TypenameLoc;
2488 SourceLocation TemplateKWLoc;
2490 SourceLocation EllipsisLoc;
2493 TypenameLoc = TemplateKWLoc = EllipsisLoc = SourceLocation();
2499 bool ParseUsingDeclarator(unsigned Context, UsingDeclarator &D);
2500 DeclGroupPtrTy ParseUsingDeclaration(unsigned Context,
2501 const ParsedTemplateInfo &TemplateInfo,
2502 SourceLocation UsingLoc,
2503 SourceLocation &DeclEnd,
2504 AccessSpecifier AS = AS_none);
2505 Decl *ParseAliasDeclarationAfterDeclarator(
2506 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
2507 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
2508 ParsedAttributes &Attrs, Decl **OwnedType = nullptr);
2510 Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
2511 Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
2512 SourceLocation AliasLoc, IdentifierInfo *Alias,
2513 SourceLocation &DeclEnd);
2515 //===--------------------------------------------------------------------===//
2516 // C++ 9: classes [class] and C structs/unions.
2517 bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
2518 void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
2519 DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo,
2520 AccessSpecifier AS, bool EnteringContext,
2521 DeclSpecContext DSC,
2522 ParsedAttributesWithRange &Attributes);
2523 void SkipCXXMemberSpecification(SourceLocation StartLoc,
2524 SourceLocation AttrFixitLoc,
2527 void ParseCXXMemberSpecification(SourceLocation StartLoc,
2528 SourceLocation AttrFixitLoc,
2529 ParsedAttributesWithRange &Attrs,
2532 ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2533 SourceLocation &EqualLoc);
2534 bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
2536 ExprResult &BitfieldSize,
2537 LateParsedAttrList &LateAttrs);
2538 void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D,
2539 VirtSpecifiers &VS);
2540 DeclGroupPtrTy ParseCXXClassMemberDeclaration(
2541 AccessSpecifier AS, AttributeList *Attr,
2542 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2543 ParsingDeclRAIIObject *DiagsFromTParams = nullptr);
2544 DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas(
2545 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
2546 DeclSpec::TST TagType, Decl *Tag);
2547 void ParseConstructorInitializer(Decl *ConstructorDecl);
2548 MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
2549 void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2552 //===--------------------------------------------------------------------===//
2553 // C++ 10: Derived classes [class.derived]
2554 TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
2555 SourceLocation &EndLocation);
2556 void ParseBaseClause(Decl *ClassDecl);
2557 BaseResult ParseBaseSpecifier(Decl *ClassDecl);
2558 AccessSpecifier getAccessSpecifierIfPresent() const;
2560 bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
2561 SourceLocation TemplateKWLoc,
2562 IdentifierInfo *Name,
2563 SourceLocation NameLoc,
2564 bool EnteringContext,
2565 ParsedType ObjectType,
2567 bool AssumeTemplateId);
2568 bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2569 ParsedType ObjectType,
2570 UnqualifiedId &Result);
2572 //===--------------------------------------------------------------------===//
2573 // OpenMP: Directives and clauses.
2574 /// Parse clauses for '#pragma omp declare simd'.
2575 DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr,
2577 SourceLocation Loc);
2578 /// \brief Parses declarative OpenMP directives.
2579 DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl(
2580 AccessSpecifier &AS, ParsedAttributesWithRange &Attrs,
2581 DeclSpec::TST TagType = DeclSpec::TST_unspecified,
2582 Decl *TagDecl = nullptr);
2583 /// \brief Parse 'omp declare reduction' construct.
2584 DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS);
2586 /// \brief Parses simple list of variables.
2588 /// \param Kind Kind of the directive.
2589 /// \param Callback Callback function to be called for the list elements.
2590 /// \param AllowScopeSpecifier true, if the variables can have fully
2591 /// qualified names.
2593 bool ParseOpenMPSimpleVarList(
2594 OpenMPDirectiveKind Kind,
2595 const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
2597 bool AllowScopeSpecifier);
2598 /// \brief Parses declarative or executable directive.
2600 /// \param Allowed ACK_Any, if any directives are allowed,
2601 /// ACK_StatementsOpenMPAnyExecutable - if any executable directives are
2602 /// allowed, ACK_StatementsOpenMPNonStandalone - if only non-standalone
2603 /// executable directives are allowed.
2606 ParseOpenMPDeclarativeOrExecutableDirective(AllowedConstructsKind Allowed);
2607 /// \brief Parses clause of kind \a CKind for directive of a kind \a Kind.
2609 /// \param DKind Kind of current directive.
2610 /// \param CKind Kind of current clause.
2611 /// \param FirstClause true, if this is the first clause of a kind \a CKind
2612 /// in current directive.
2614 OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
2615 OpenMPClauseKind CKind, bool FirstClause);
2616 /// \brief Parses clause with a single expression of a kind \a Kind.
2618 /// \param Kind Kind of current clause.
2620 OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind);
2621 /// \brief Parses simple clause of a kind \a Kind.
2623 /// \param Kind Kind of current clause.
2625 OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind);
2626 /// \brief Parses clause with a single expression and an additional argument
2627 /// of a kind \a Kind.
2629 /// \param Kind Kind of current clause.
2631 OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind);
2632 /// \brief Parses clause without any additional arguments.
2634 /// \param Kind Kind of current clause.
2636 OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind);
2637 /// \brief Parses clause with the list of variables of a kind \a Kind.
2639 /// \param Kind Kind of current clause.
2641 OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
2642 OpenMPClauseKind Kind);
2645 /// Parses simple expression in parens for single-expression clauses of OpenMP
2647 /// \param RLoc Returned location of right paren.
2648 ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc);
2650 /// Data used for parsing list of variables in OpenMP clauses.
2651 struct OpenMPVarListDataTy {
2652 Expr *TailExpr = nullptr;
2653 SourceLocation ColonLoc;
2654 CXXScopeSpec ReductionIdScopeSpec;
2655 DeclarationNameInfo ReductionId;
2656 OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown;
2657 OpenMPLinearClauseKind LinKind = OMPC_LINEAR_val;
2658 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
2659 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
2660 bool IsMapTypeImplicit = false;
2661 SourceLocation DepLinMapLoc;
2664 /// Parses clauses with list.
2665 bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind,
2666 SmallVectorImpl<Expr *> &Vars,
2667 OpenMPVarListDataTy &Data);
2668 bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2669 bool AllowDestructorName,
2670 bool AllowConstructorName,
2671 bool AllowDeductionGuide,
2672 ParsedType ObjectType,
2673 SourceLocation& TemplateKWLoc,
2674 UnqualifiedId &Result);
2677 //===--------------------------------------------------------------------===//
2678 // C++ 14: Templates [temp]
2680 // C++ 14.1: Template Parameters [temp.param]
2681 Decl *ParseDeclarationStartingWithTemplate(unsigned Context,
2682 SourceLocation &DeclEnd,
2683 AccessSpecifier AS = AS_none,
2684 AttributeList *AccessAttrs = nullptr);
2685 Decl *ParseTemplateDeclarationOrSpecialization(unsigned Context,
2686 SourceLocation &DeclEnd,
2688 AttributeList *AccessAttrs);
2689 Decl *ParseSingleDeclarationAfterTemplate(
2691 const ParsedTemplateInfo &TemplateInfo,
2692 ParsingDeclRAIIObject &DiagsFromParams,
2693 SourceLocation &DeclEnd,
2694 AccessSpecifier AS=AS_none,
2695 AttributeList *AccessAttrs = nullptr);
2696 bool ParseTemplateParameters(unsigned Depth,
2697 SmallVectorImpl<Decl*> &TemplateParams,
2698 SourceLocation &LAngleLoc,
2699 SourceLocation &RAngleLoc);
2700 bool ParseTemplateParameterList(unsigned Depth,
2701 SmallVectorImpl<Decl*> &TemplateParams);
2702 bool isStartOfTemplateTypeParameter();
2703 Decl *ParseTemplateParameter(unsigned Depth, unsigned Position);
2704 Decl *ParseTypeParameter(unsigned Depth, unsigned Position);
2705 Decl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
2706 Decl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
2707 void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
2708 SourceLocation CorrectLoc,
2709 bool AlreadyHasEllipsis,
2710 bool IdentifierHasName);
2711 void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
2713 // C++ 14.3: Template arguments [temp.arg]
2714 typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
2716 bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
2717 bool ConsumeLastToken,
2718 bool ObjCGenericList);
2719 bool ParseTemplateIdAfterTemplateName(TemplateTy Template,
2720 SourceLocation TemplateNameLoc,
2721 const CXXScopeSpec &SS,
2722 bool ConsumeLastToken,
2723 SourceLocation &LAngleLoc,
2724 TemplateArgList &TemplateArgs,
2725 SourceLocation &RAngleLoc);
2727 bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
2729 SourceLocation TemplateKWLoc,
2730 UnqualifiedId &TemplateName,
2731 bool AllowTypeAnnotation = true);
2732 void AnnotateTemplateIdTokenAsType(bool IsClassName = false);
2733 bool IsTemplateArgumentList(unsigned Skip = 0);
2734 bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
2735 ParsedTemplateArgument ParseTemplateTemplateArgument();
2736 ParsedTemplateArgument ParseTemplateArgument();
2737 Decl *ParseExplicitInstantiation(unsigned Context,
2738 SourceLocation ExternLoc,
2739 SourceLocation TemplateLoc,
2740 SourceLocation &DeclEnd,
2741 AccessSpecifier AS = AS_none);
2743 //===--------------------------------------------------------------------===//
2745 DeclGroupPtrTy ParseModuleDecl();
2746 DeclGroupPtrTy ParseModuleImport(SourceLocation AtLoc);
2747 bool parseMisplacedModuleImport();
2748 bool tryParseMisplacedModuleImport() {
2749 tok::TokenKind Kind = Tok.getKind();
2750 if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end ||
2751 Kind == tok::annot_module_include)
2752 return parseMisplacedModuleImport();
2756 bool ParseModuleName(
2757 SourceLocation UseLoc,
2758 SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
2761 //===--------------------------------------------------------------------===//
2762 // C++11/G++: Type Traits [Type-Traits.html in the GCC manual]
2763 ExprResult ParseTypeTrait();
2765 //===--------------------------------------------------------------------===//
2766 // Embarcadero: Arary and Expression Traits
2767 ExprResult ParseArrayTypeTrait();
2768 ExprResult ParseExpressionTrait();
2770 //===--------------------------------------------------------------------===//
2771 // Preprocessor code-completion pass-through
2772 void CodeCompleteDirective(bool InConditional) override;
2773 void CodeCompleteInConditionalExclusion() override;
2774 void CodeCompleteMacroName(bool IsDefinition) override;
2775 void CodeCompletePreprocessorExpression() override;
2776 void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo,
2777 unsigned ArgumentIndex) override;
2778 void CodeCompleteNaturalLanguage() override;
2781 } // end namespace clang