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/BitmaskEnum.h"
19 #include "clang/Basic/OpenMPKinds.h"
20 #include "clang/Basic/OperatorPrecedence.h"
21 #include "clang/Basic/Specifiers.h"
22 #include "clang/Lex/CodeCompletionHandler.h"
23 #include "clang/Lex/Preprocessor.h"
24 #include "clang/Sema/DeclSpec.h"
25 #include "clang/Sema/LoopHint.h"
26 #include "clang/Sema/Sema.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Support/PrettyStackTrace.h"
30 #include "llvm/Support/SaveAndRestore.h"
37 class BalancedDelimiterTracker;
38 class CorrectionCandidateCallback;
40 class DiagnosticBuilder;
42 class ParsingDeclRAIIObject;
43 class ParsingDeclSpec;
44 class ParsingDeclarator;
45 class ParsingFieldDeclarator;
46 class ColonProtectionRAIIObject;
47 class InMessageExpressionRAIIObject;
48 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 /// Identifier for "introduced".
125 IdentifierInfo *Ident_introduced;
127 /// Identifier for "deprecated".
128 IdentifierInfo *Ident_deprecated;
130 /// Identifier for "obsoleted".
131 IdentifierInfo *Ident_obsoleted;
133 /// Identifier for "unavailable".
134 IdentifierInfo *Ident_unavailable;
136 /// Identifier for "message".
137 IdentifierInfo *Ident_message;
139 /// Identifier for "strict".
140 IdentifierInfo *Ident_strict;
142 /// Identifier for "replacement".
143 IdentifierInfo *Ident_replacement;
145 /// Identifiers used by the 'external_source_symbol' attribute.
146 IdentifierInfo *Ident_language, *Ident_defined_in,
147 *Ident_generated_declaration;
149 /// C++0x contextual keywords.
150 mutable IdentifierInfo *Ident_final;
151 mutable IdentifierInfo *Ident_GNU_final;
152 mutable IdentifierInfo *Ident_override;
154 // C++ type trait keywords that can be reverted to identifiers and still be
155 // used as type traits.
156 llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits;
158 std::unique_ptr<PragmaHandler> AlignHandler;
159 std::unique_ptr<PragmaHandler> GCCVisibilityHandler;
160 std::unique_ptr<PragmaHandler> OptionsHandler;
161 std::unique_ptr<PragmaHandler> PackHandler;
162 std::unique_ptr<PragmaHandler> MSStructHandler;
163 std::unique_ptr<PragmaHandler> UnusedHandler;
164 std::unique_ptr<PragmaHandler> WeakHandler;
165 std::unique_ptr<PragmaHandler> RedefineExtnameHandler;
166 std::unique_ptr<PragmaHandler> FPContractHandler;
167 std::unique_ptr<PragmaHandler> OpenCLExtensionHandler;
168 std::unique_ptr<PragmaHandler> OpenMPHandler;
169 std::unique_ptr<PragmaHandler> PCSectionHandler;
170 std::unique_ptr<PragmaHandler> MSCommentHandler;
171 std::unique_ptr<PragmaHandler> MSDetectMismatchHandler;
172 std::unique_ptr<PragmaHandler> MSPointersToMembers;
173 std::unique_ptr<PragmaHandler> MSVtorDisp;
174 std::unique_ptr<PragmaHandler> MSInitSeg;
175 std::unique_ptr<PragmaHandler> MSDataSeg;
176 std::unique_ptr<PragmaHandler> MSBSSSeg;
177 std::unique_ptr<PragmaHandler> MSConstSeg;
178 std::unique_ptr<PragmaHandler> MSCodeSeg;
179 std::unique_ptr<PragmaHandler> MSSection;
180 std::unique_ptr<PragmaHandler> MSRuntimeChecks;
181 std::unique_ptr<PragmaHandler> MSIntrinsic;
182 std::unique_ptr<PragmaHandler> MSOptimize;
183 std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler;
184 std::unique_ptr<PragmaHandler> OptimizeHandler;
185 std::unique_ptr<PragmaHandler> LoopHintHandler;
186 std::unique_ptr<PragmaHandler> UnrollHintHandler;
187 std::unique_ptr<PragmaHandler> NoUnrollHintHandler;
188 std::unique_ptr<PragmaHandler> FPHandler;
189 std::unique_ptr<PragmaHandler> STDCFENVHandler;
190 std::unique_ptr<PragmaHandler> STDCCXLIMITHandler;
191 std::unique_ptr<PragmaHandler> STDCUnknownHandler;
192 std::unique_ptr<PragmaHandler> AttributePragmaHandler;
194 std::unique_ptr<CommentHandler> CommentSemaHandler;
196 /// Whether the '>' token acts as an operator or not. This will be
197 /// true except when we are parsing an expression within a C++
198 /// template argument list, where the '>' closes the template
200 bool GreaterThanIsOperator;
202 /// ColonIsSacred - When this is false, we aggressively try to recover from
203 /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not
204 /// safe in case statements and a few other things. This is managed by the
205 /// ColonProtectionRAIIObject RAII object.
208 /// When true, we are directly inside an Objective-C message
211 /// This is managed by the \c InMessageExpressionRAIIObject class, and
212 /// should not be set directly.
213 bool InMessageExpression;
215 /// The "depth" of the template parameters currently being parsed.
216 unsigned TemplateParameterDepth;
218 /// RAII class that manages the template parameter depth.
219 class TemplateParameterDepthRAII {
221 unsigned AddedLevels;
223 explicit TemplateParameterDepthRAII(unsigned &Depth)
224 : Depth(Depth), AddedLevels(0) {}
226 ~TemplateParameterDepthRAII() {
227 Depth -= AddedLevels;
234 void addDepth(unsigned D) {
238 unsigned getDepth() const { return Depth; }
241 /// Factory object for creating ParsedAttr objects.
242 AttributeFactory AttrFactory;
244 /// Gathers and cleans up TemplateIdAnnotations when parsing of a
245 /// top-level declaration is finished.
246 SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
248 /// Identifiers which have been declared within a tentative parse.
249 SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers;
251 /// Tracker for '<' tokens that might have been intended to be treated as an
252 /// angle bracket instead of a less-than comparison.
254 /// This happens when the user intends to form a template-id, but typoes the
255 /// template-name or forgets a 'template' keyword for a dependent template
258 /// We track these locations from the point where we see a '<' with a
259 /// name-like expression on its left until we see a '>' or '>>' that might
261 struct AngleBracketTracker {
262 /// Flags used to rank candidate template names when there is more than one
264 enum Priority : unsigned short {
265 /// A non-dependent name that is a potential typo for a template name.
267 /// A dependent name that might instantiate to a template-name.
270 /// A space appears before the '<' token.
271 SpaceBeforeLess = 0x0,
272 /// No space before the '<' token
273 NoSpaceBeforeLess = 0x1,
275 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue*/ DependentName)
280 SourceLocation LessLoc;
281 AngleBracketTracker::Priority Priority;
282 unsigned short ParenCount, BracketCount, BraceCount;
284 bool isActive(Parser &P) const {
285 return P.ParenCount == ParenCount && P.BracketCount == BracketCount &&
286 P.BraceCount == BraceCount;
289 bool isActiveOrNested(Parser &P) const {
290 return isActive(P) || P.ParenCount > ParenCount ||
291 P.BracketCount > BracketCount || P.BraceCount > BraceCount;
295 SmallVector<Loc, 8> Locs;
297 /// Add an expression that might have been intended to be a template name.
298 /// In the case of ambiguity, we arbitrarily select the innermost such
299 /// expression, for example in 'foo < bar < baz', 'bar' is the current
300 /// candidate. No attempt is made to track that 'foo' is also a candidate
301 /// for the case where we see a second suspicious '>' token.
302 void add(Parser &P, Expr *TemplateName, SourceLocation LessLoc,
304 if (!Locs.empty() && Locs.back().isActive(P)) {
305 if (Locs.back().Priority <= Prio) {
306 Locs.back().TemplateName = TemplateName;
307 Locs.back().LessLoc = LessLoc;
308 Locs.back().Priority = Prio;
311 Locs.push_back({TemplateName, LessLoc, Prio,
312 P.ParenCount, P.BracketCount, P.BraceCount});
316 /// Mark the current potential missing template location as having been
317 /// handled (this happens if we pass a "corresponding" '>' or '>>' token
318 /// or leave a bracket scope).
319 void clear(Parser &P) {
320 while (!Locs.empty() && Locs.back().isActiveOrNested(P))
324 /// Get the current enclosing expression that might hve been intended to be
326 Loc *getCurrent(Parser &P) {
327 if (!Locs.empty() && Locs.back().isActive(P))
333 AngleBracketTracker AngleBrackets;
335 IdentifierInfo *getSEHExceptKeyword();
337 /// True if we are within an Objective-C container while parsing C-like decls.
339 /// This is necessary because Sema thinks we have left the container
340 /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will
342 bool ParsingInObjCContainer;
344 /// Whether to skip parsing of function bodies.
346 /// This option can be used, for example, to speed up searches for
347 /// declarations/definitions when indexing.
348 bool SkipFunctionBodies;
350 /// The location of the expression statement that is being parsed right now.
351 /// Used to determine if an expression that is being parsed is a statement or
352 /// just a regular sub-expression.
353 SourceLocation ExprStatementTokLoc;
356 Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
359 const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
360 const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
361 Preprocessor &getPreprocessor() const { return PP; }
362 Sema &getActions() const { return Actions; }
363 AttributeFactory &getAttrFactory() { return AttrFactory; }
365 const Token &getCurToken() const { return Tok; }
366 Scope *getCurScope() const { return Actions.getCurScope(); }
367 void incrementMSManglingNumber() const {
368 return Actions.incrementMSManglingNumber();
371 Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); }
373 // Type forwarding. All of these are statically 'void*', but they may all be
374 // different actual classes based on the actions in place.
375 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
376 typedef OpaquePtr<TemplateName> TemplateTy;
378 typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists;
380 typedef Sema::FullExprArg FullExprArg;
384 /// Initialize - Warm up the parser.
388 /// Parse the first top-level declaration in a translation unit.
389 bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result);
391 /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if
392 /// the EOF was encountered.
393 bool ParseTopLevelDecl(DeclGroupPtrTy &Result);
394 bool ParseTopLevelDecl() {
395 DeclGroupPtrTy Result;
396 return ParseTopLevelDecl(Result);
399 /// ConsumeToken - Consume the current 'peek token' and lex the next one.
400 /// This does not work with special tokens: string literals, code completion,
401 /// annotation tokens and balanced tokens must be handled using the specific
403 /// Returns the location of the consumed token.
404 SourceLocation ConsumeToken() {
405 assert(!isTokenSpecial() &&
406 "Should consume special tokens with Consume*Token");
407 PrevTokLocation = Tok.getLocation();
409 return PrevTokLocation;
412 bool TryConsumeToken(tok::TokenKind Expected) {
413 if (Tok.isNot(Expected))
415 assert(!isTokenSpecial() &&
416 "Should consume special tokens with Consume*Token");
417 PrevTokLocation = Tok.getLocation();
422 bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) {
423 if (!TryConsumeToken(Expected))
425 Loc = PrevTokLocation;
429 /// ConsumeAnyToken - Dispatch to the right Consume* method based on the
430 /// current token type. This should only be used in cases where the type of
431 /// the token really isn't known, e.g. in error recovery.
432 SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) {
434 return ConsumeParen();
435 if (isTokenBracket())
436 return ConsumeBracket();
438 return ConsumeBrace();
439 if (isTokenStringLiteral())
440 return ConsumeStringToken();
441 if (Tok.is(tok::code_completion))
442 return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken()
443 : handleUnexpectedCodeCompletionToken();
444 if (Tok.isAnnotation())
445 return ConsumeAnnotationToken();
446 return ConsumeToken();
450 SourceLocation getEndOfPreviousToken() {
451 return PP.getLocForEndOfToken(PrevTokLocation);
454 /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds
455 /// to the given nullability kind.
456 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) {
457 return Actions.getNullabilityKeyword(nullability);
461 //===--------------------------------------------------------------------===//
462 // Low-Level token peeking and consumption methods.
465 /// isTokenParen - Return true if the cur token is '(' or ')'.
466 bool isTokenParen() const {
467 return Tok.isOneOf(tok::l_paren, tok::r_paren);
469 /// isTokenBracket - Return true if the cur token is '[' or ']'.
470 bool isTokenBracket() const {
471 return Tok.isOneOf(tok::l_square, tok::r_square);
473 /// isTokenBrace - Return true if the cur token is '{' or '}'.
474 bool isTokenBrace() const {
475 return Tok.isOneOf(tok::l_brace, tok::r_brace);
477 /// isTokenStringLiteral - True if this token is a string-literal.
478 bool isTokenStringLiteral() const {
479 return tok::isStringLiteral(Tok.getKind());
481 /// isTokenSpecial - True if this token requires special consumption methods.
482 bool isTokenSpecial() const {
483 return isTokenStringLiteral() || isTokenParen() || isTokenBracket() ||
484 isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation();
487 /// Returns true if the current token is '=' or is a type of '='.
488 /// For typos, give a fixit to '='
489 bool isTokenEqualOrEqualTypo();
491 /// Return the current token to the token stream and make the given
492 /// token the current token.
493 void UnconsumeToken(Token &Consumed) {
495 PP.EnterToken(Consumed);
500 SourceLocation ConsumeAnnotationToken() {
501 assert(Tok.isAnnotation() && "wrong consume method");
502 SourceLocation Loc = Tok.getLocation();
503 PrevTokLocation = Tok.getAnnotationEndLoc();
508 /// ConsumeParen - This consume method keeps the paren count up-to-date.
510 SourceLocation ConsumeParen() {
511 assert(isTokenParen() && "wrong consume method");
512 if (Tok.getKind() == tok::l_paren)
514 else if (ParenCount) {
515 AngleBrackets.clear(*this);
516 --ParenCount; // Don't let unbalanced )'s drive the count negative.
518 PrevTokLocation = Tok.getLocation();
520 return PrevTokLocation;
523 /// ConsumeBracket - This consume method keeps the bracket count up-to-date.
525 SourceLocation ConsumeBracket() {
526 assert(isTokenBracket() && "wrong consume method");
527 if (Tok.getKind() == tok::l_square)
529 else if (BracketCount) {
530 AngleBrackets.clear(*this);
531 --BracketCount; // Don't let unbalanced ]'s drive the count negative.
534 PrevTokLocation = Tok.getLocation();
536 return PrevTokLocation;
539 /// ConsumeBrace - This consume method keeps the brace count up-to-date.
541 SourceLocation ConsumeBrace() {
542 assert(isTokenBrace() && "wrong consume method");
543 if (Tok.getKind() == tok::l_brace)
545 else if (BraceCount) {
546 AngleBrackets.clear(*this);
547 --BraceCount; // Don't let unbalanced }'s drive the count negative.
550 PrevTokLocation = Tok.getLocation();
552 return PrevTokLocation;
555 /// ConsumeStringToken - Consume the current 'peek token', lexing a new one
556 /// and returning the token kind. This method is specific to strings, as it
557 /// handles string literal concatenation, as per C99 5.1.1.2, translation
559 SourceLocation ConsumeStringToken() {
560 assert(isTokenStringLiteral() &&
561 "Should only consume string literals with this method");
562 PrevTokLocation = Tok.getLocation();
564 return PrevTokLocation;
567 /// Consume the current code-completion token.
569 /// This routine can be called to consume the code-completion token and
570 /// continue processing in special cases where \c cutOffParsing() isn't
571 /// desired, such as token caching or completion with lookahead.
572 SourceLocation ConsumeCodeCompletionToken() {
573 assert(Tok.is(tok::code_completion));
574 PrevTokLocation = Tok.getLocation();
576 return PrevTokLocation;
579 ///\ brief When we are consuming a code-completion token without having
580 /// matched specific position in the grammar, provide code-completion results
581 /// based on context.
583 /// \returns the source location of the code-completion token.
584 SourceLocation handleUnexpectedCodeCompletionToken();
586 /// Abruptly cut off parsing; mainly used when we have reached the
587 /// code-completion point.
588 void cutOffParsing() {
589 if (PP.isCodeCompletionEnabled())
590 PP.setCodeCompletionReached();
591 // Cut off parsing by acting as if we reached the end-of-file.
592 Tok.setKind(tok::eof);
595 /// Determine if we're at the end of the file or at a transition
598 tok::TokenKind Kind = Tok.getKind();
599 return Kind == tok::eof || Kind == tok::annot_module_begin ||
600 Kind == tok::annot_module_end || Kind == tok::annot_module_include;
603 /// Checks if the \p Level is valid for use in a fold expression.
604 bool isFoldOperator(prec::Level Level) const;
606 /// Checks if the \p Kind is a valid operator for fold expressions.
607 bool isFoldOperator(tok::TokenKind Kind) const;
609 /// Initialize all pragma handlers.
610 void initializePragmaHandlers();
612 /// Destroy and reset all pragma handlers.
613 void resetPragmaHandlers();
615 /// Handle the annotation token produced for #pragma unused(...)
616 void HandlePragmaUnused();
618 /// Handle the annotation token produced for
619 /// #pragma GCC visibility...
620 void HandlePragmaVisibility();
622 /// Handle the annotation token produced for
624 void HandlePragmaPack();
626 /// Handle the annotation token produced for
627 /// #pragma ms_struct...
628 void HandlePragmaMSStruct();
630 /// Handle the annotation token produced for
631 /// #pragma comment...
632 void HandlePragmaMSComment();
634 void HandlePragmaMSPointersToMembers();
636 void HandlePragmaMSVtorDisp();
638 void HandlePragmaMSPragma();
639 bool HandlePragmaMSSection(StringRef PragmaName,
640 SourceLocation PragmaLocation);
641 bool HandlePragmaMSSegment(StringRef PragmaName,
642 SourceLocation PragmaLocation);
643 bool HandlePragmaMSInitSeg(StringRef PragmaName,
644 SourceLocation PragmaLocation);
646 /// Handle the annotation token produced for
648 void HandlePragmaAlign();
650 /// Handle the annotation token produced for
651 /// #pragma clang __debug dump...
652 void HandlePragmaDump();
654 /// Handle the annotation token produced for
655 /// #pragma weak id...
656 void HandlePragmaWeak();
658 /// Handle the annotation token produced for
659 /// #pragma weak id = id...
660 void HandlePragmaWeakAlias();
662 /// Handle the annotation token produced for
663 /// #pragma redefine_extname...
664 void HandlePragmaRedefineExtname();
666 /// Handle the annotation token produced for
667 /// #pragma STDC FP_CONTRACT...
668 void HandlePragmaFPContract();
670 /// Handle the annotation token produced for
671 /// #pragma clang fp ...
672 void HandlePragmaFP();
674 /// Handle the annotation token produced for
675 /// #pragma OPENCL EXTENSION...
676 void HandlePragmaOpenCLExtension();
678 /// Handle the annotation token produced for
679 /// #pragma clang __debug captured
680 StmtResult HandlePragmaCaptured();
682 /// Handle the annotation token produced for
683 /// #pragma clang loop and #pragma unroll.
684 bool HandlePragmaLoopHint(LoopHint &Hint);
686 bool ParsePragmaAttributeSubjectMatchRuleSet(
687 attr::ParsedSubjectMatchRuleSet &SubjectMatchRules,
688 SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc);
690 void HandlePragmaAttribute();
692 /// GetLookAheadToken - This peeks ahead N tokens and returns that token
693 /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1)
694 /// returns the token after Tok, etc.
696 /// Note that this differs from the Preprocessor's LookAhead method, because
697 /// the Parser always has one token lexed that the preprocessor doesn't.
699 const Token &GetLookAheadToken(unsigned N) {
700 if (N == 0 || Tok.is(tok::eof)) return Tok;
701 return PP.LookAhead(N-1);
705 /// NextToken - This peeks ahead one token and returns it without
707 const Token &NextToken() {
708 return PP.LookAhead(0);
711 /// getTypeAnnotation - Read a parsed type out of an annotation token.
712 static ParsedType getTypeAnnotation(const Token &Tok) {
713 return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
717 static void setTypeAnnotation(Token &Tok, ParsedType T) {
718 Tok.setAnnotationValue(T.getAsOpaquePtr());
721 /// Read an already-translated primary expression out of an annotation
723 static ExprResult getExprAnnotation(const Token &Tok) {
724 return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue());
727 /// Set the primary expression corresponding to the given annotation
729 static void setExprAnnotation(Token &Tok, ExprResult ER) {
730 Tok.setAnnotationValue(ER.getAsOpaquePointer());
734 // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to
735 // find a type name by attempting typo correction.
736 bool TryAnnotateTypeOrScopeToken();
737 bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS,
739 bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
742 enum AnnotatedNameKind {
743 /// Annotation has failed and emitted an error.
745 /// The identifier is a tentatively-declared name.
747 /// The identifier is a template name. FIXME: Add an annotation for that.
749 /// The identifier can't be resolved.
751 /// Annotation was successful.
755 TryAnnotateName(bool IsAddressOfOperand,
756 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
758 /// Push a tok::annot_cxxscope token onto the token stream.
759 void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
761 /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
762 /// replacing them with the non-context-sensitive keywords. This returns
763 /// true if the token was replaced.
764 bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
765 const char *&PrevSpec, unsigned &DiagID,
767 if (!getLangOpts().AltiVec && !getLangOpts().ZVector)
770 if (Tok.getIdentifierInfo() != Ident_vector &&
771 Tok.getIdentifierInfo() != Ident_bool &&
772 (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel))
775 return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
778 /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
779 /// identifier token, replacing it with the non-context-sensitive __vector.
780 /// This returns true if the token was replaced.
781 bool TryAltiVecVectorToken() {
782 if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) ||
783 Tok.getIdentifierInfo() != Ident_vector) return false;
784 return TryAltiVecVectorTokenOutOfLine();
787 bool TryAltiVecVectorTokenOutOfLine();
788 bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
789 const char *&PrevSpec, unsigned &DiagID,
792 /// Returns true if the current token is the identifier 'instancetype'.
794 /// Should only be used in Objective-C language modes.
795 bool isObjCInstancetype() {
796 assert(getLangOpts().ObjC1);
797 if (Tok.isAnnotation())
799 if (!Ident_instancetype)
800 Ident_instancetype = PP.getIdentifierInfo("instancetype");
801 return Tok.getIdentifierInfo() == Ident_instancetype;
804 /// TryKeywordIdentFallback - For compatibility with system headers using
805 /// keywords as identifiers, attempt to convert the current token to an
806 /// identifier and optionally disable the keyword for the remainder of the
807 /// translation unit. This returns false if the token was not replaced,
808 /// otherwise emits a diagnostic and returns true.
809 bool TryKeywordIdentFallback(bool DisableKeyword);
811 /// Get the TemplateIdAnnotation from the token.
812 TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
814 /// TentativeParsingAction - An object that is used as a kind of "tentative
815 /// parsing transaction". It gets instantiated to mark the token position and
816 /// after the token consumption is done, Commit() or Revert() is called to
817 /// either "commit the consumed tokens" or revert to the previously marked
818 /// token position. Example:
820 /// TentativeParsingAction TPA(*this);
825 class TentativeParsingAction {
828 size_t PrevTentativelyDeclaredIdentifierCount;
829 unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
833 explicit TentativeParsingAction(Parser& p) : P(p) {
835 PrevTentativelyDeclaredIdentifierCount =
836 P.TentativelyDeclaredIdentifiers.size();
837 PrevParenCount = P.ParenCount;
838 PrevBracketCount = P.BracketCount;
839 PrevBraceCount = P.BraceCount;
840 P.PP.EnableBacktrackAtThisPos();
844 assert(isActive && "Parsing action was finished!");
845 P.TentativelyDeclaredIdentifiers.resize(
846 PrevTentativelyDeclaredIdentifierCount);
847 P.PP.CommitBacktrackedTokens();
851 assert(isActive && "Parsing action was finished!");
854 P.TentativelyDeclaredIdentifiers.resize(
855 PrevTentativelyDeclaredIdentifierCount);
856 P.ParenCount = PrevParenCount;
857 P.BracketCount = PrevBracketCount;
858 P.BraceCount = PrevBraceCount;
861 ~TentativeParsingAction() {
862 assert(!isActive && "Forgot to call Commit or Revert!");
865 /// A TentativeParsingAction that automatically reverts in its destructor.
866 /// Useful for disambiguation parses that will always be reverted.
867 class RevertingTentativeParsingAction
868 : private Parser::TentativeParsingAction {
870 RevertingTentativeParsingAction(Parser &P)
871 : Parser::TentativeParsingAction(P) {}
872 ~RevertingTentativeParsingAction() { Revert(); }
875 class UnannotatedTentativeParsingAction;
877 /// ObjCDeclContextSwitch - An object used to switch context from
878 /// an objective-c decl context to its enclosing decl context and
880 class ObjCDeclContextSwitch {
883 SaveAndRestore<bool> WithinObjCContainer;
885 explicit ObjCDeclContextSwitch(Parser &p)
886 : P(p), DC(p.getObjCDeclContext()),
887 WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) {
889 P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC));
891 ~ObjCDeclContextSwitch() {
893 P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC));
897 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
898 /// input. If so, it is consumed and false is returned.
900 /// If a trivial punctuator misspelling is encountered, a FixIt error
901 /// diagnostic is issued and false is returned after recovery.
903 /// If the input is malformed, this emits the specified diagnostic and true is
905 bool ExpectAndConsume(tok::TokenKind ExpectedTok,
906 unsigned Diag = diag::err_expected,
907 StringRef DiagMsg = "");
909 /// The parser expects a semicolon and, if present, will consume it.
911 /// If the next token is not a semicolon, this emits the specified diagnostic,
912 /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
913 /// to the semicolon, consumes that extra token.
914 bool ExpectAndConsumeSemi(unsigned DiagID);
916 /// The kind of extra semi diagnostic to emit.
920 InstanceVariableList = 2,
921 AfterMemberFunctionDefinition = 3
924 /// Consume any extra semi-colons until the end of the line.
925 void ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST = TST_unspecified);
927 /// Return false if the next token is an identifier. An 'expected identifier'
928 /// error is emitted otherwise.
930 /// The parser tries to recover from the error by checking if the next token
931 /// is a C++ keyword when parsing Objective-C++. Return false if the recovery
933 bool expectIdentifier();
936 //===--------------------------------------------------------------------===//
937 // Scope manipulation
939 /// ParseScope - Introduces a new scope for parsing. The kind of
940 /// scope is determined by ScopeFlags. Objects of this type should
941 /// be created on the stack to coincide with the position where the
942 /// parser enters the new scope, and this object's constructor will
943 /// create that new scope. Similarly, once the object is destroyed
944 /// the parser will exit the scope.
947 ParseScope(const ParseScope &) = delete;
948 void operator=(const ParseScope &) = delete;
951 // ParseScope - Construct a new object to manage a scope in the
952 // parser Self where the new Scope is created with the flags
953 // ScopeFlags, but only when we aren't about to enter a compound statement.
954 ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true,
955 bool BeforeCompoundStmt = false)
957 if (EnteredScope && !BeforeCompoundStmt)
958 Self->EnterScope(ScopeFlags);
960 if (BeforeCompoundStmt)
961 Self->incrementMSManglingNumber();
963 this->Self = nullptr;
967 // Exit - Exit the scope associated with this object now, rather
968 // than waiting until the object is destroyed.
981 /// EnterScope - Start a new scope.
982 void EnterScope(unsigned ScopeFlags);
984 /// ExitScope - Pop a scope off the scope stack.
988 /// RAII object used to modify the scope flags for the current scope.
989 class ParseScopeFlags {
992 ParseScopeFlags(const ParseScopeFlags &) = delete;
993 void operator=(const ParseScopeFlags &) = delete;
996 ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
1000 //===--------------------------------------------------------------------===//
1001 // Diagnostic Emission and Error recovery.
1004 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
1005 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
1006 DiagnosticBuilder Diag(unsigned DiagID) {
1007 return Diag(Tok, DiagID);
1011 void SuggestParentheses(SourceLocation Loc, unsigned DK,
1012 SourceRange ParenRange);
1013 void CheckNestedObjCContexts(SourceLocation AtLoc);
1017 /// Control flags for SkipUntil functions.
1018 enum SkipUntilFlags {
1019 StopAtSemi = 1 << 0, ///< Stop skipping at semicolon
1020 /// Stop skipping at specified token, but don't skip the token itself
1021 StopBeforeMatch = 1 << 1,
1022 StopAtCodeCompletion = 1 << 2 ///< Stop at code completion
1025 friend constexpr SkipUntilFlags operator|(SkipUntilFlags L,
1027 return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) |
1028 static_cast<unsigned>(R));
1031 /// SkipUntil - Read tokens until we get to the specified token, then consume
1032 /// it (unless StopBeforeMatch is specified). Because we cannot guarantee
1033 /// that the token will ever occur, this skips to the next token, or to some
1034 /// likely good stopping point. If Flags has StopAtSemi flag, skipping will
1035 /// stop at a ';' character.
1037 /// If SkipUntil finds the specified token, it returns true, otherwise it
1039 bool SkipUntil(tok::TokenKind T,
1040 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
1041 return SkipUntil(llvm::makeArrayRef(T), Flags);
1043 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2,
1044 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
1045 tok::TokenKind TokArray[] = {T1, T2};
1046 return SkipUntil(TokArray, Flags);
1048 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3,
1049 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
1050 tok::TokenKind TokArray[] = {T1, T2, T3};
1051 return SkipUntil(TokArray, Flags);
1053 bool SkipUntil(ArrayRef<tok::TokenKind> Toks,
1054 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0));
1056 /// SkipMalformedDecl - Read tokens until we get to some likely good stopping
1057 /// point for skipping past a simple-declaration.
1058 void SkipMalformedDecl();
1061 //===--------------------------------------------------------------------===//
1062 // Lexing and parsing of C++ inline methods.
1064 struct ParsingClass;
1066 /// [class.mem]p1: "... the class is regarded as complete within
1067 /// - function bodies
1068 /// - default arguments
1069 /// - exception-specifications (TODO: C++0x)
1070 /// - and brace-or-equal-initializers for non-static data members
1071 /// (including such things in nested classes)."
1072 /// LateParsedDeclarations build the tree of those elements so they can
1073 /// be parsed after parsing the top-level class.
1074 class LateParsedDeclaration {
1076 virtual ~LateParsedDeclaration();
1078 virtual void ParseLexedMethodDeclarations();
1079 virtual void ParseLexedMemberInitializers();
1080 virtual void ParseLexedMethodDefs();
1081 virtual void ParseLexedAttributes();
1084 /// Inner node of the LateParsedDeclaration tree that parses
1085 /// all its members recursively.
1086 class LateParsedClass : public LateParsedDeclaration {
1088 LateParsedClass(Parser *P, ParsingClass *C);
1089 ~LateParsedClass() override;
1091 void ParseLexedMethodDeclarations() override;
1092 void ParseLexedMemberInitializers() override;
1093 void ParseLexedMethodDefs() override;
1094 void ParseLexedAttributes() override;
1098 ParsingClass *Class;
1101 /// Contains the lexed tokens of an attribute with arguments that
1102 /// may reference member variables and so need to be parsed at the
1103 /// end of the class declaration after parsing all other member
1104 /// member declarations.
1105 /// FIXME: Perhaps we should change the name of LateParsedDeclaration to
1106 /// LateParsedTokens.
1107 struct LateParsedAttribute : public LateParsedDeclaration {
1110 IdentifierInfo &AttrName;
1111 SourceLocation AttrNameLoc;
1112 SmallVector<Decl*, 2> Decls;
1114 explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
1116 : Self(P), AttrName(Name), AttrNameLoc(Loc) {}
1118 void ParseLexedAttributes() override;
1120 void addDecl(Decl *D) { Decls.push_back(D); }
1123 // A list of late-parsed attributes. Used by ParseGNUAttributes.
1124 class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> {
1126 LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { }
1128 bool parseSoon() { return ParseSoon; }
1131 bool ParseSoon; // Are we planning to parse these shortly after creation?
1134 /// Contains the lexed tokens of a member function definition
1135 /// which needs to be parsed at the end of the class declaration
1136 /// after parsing all other member declarations.
1137 struct LexedMethod : public LateParsedDeclaration {
1142 /// Whether this member function had an associated template
1143 /// scope. When true, D is a template declaration.
1144 /// otherwise, it is a member function declaration.
1147 explicit LexedMethod(Parser* P, Decl *MD)
1148 : Self(P), D(MD), TemplateScope(false) {}
1150 void ParseLexedMethodDefs() override;
1153 /// LateParsedDefaultArgument - Keeps track of a parameter that may
1154 /// have a default argument that cannot be parsed yet because it
1155 /// occurs within a member function declaration inside the class
1156 /// (C++ [class.mem]p2).
1157 struct LateParsedDefaultArgument {
1158 explicit LateParsedDefaultArgument(Decl *P,
1159 std::unique_ptr<CachedTokens> Toks = nullptr)
1160 : Param(P), Toks(std::move(Toks)) { }
1162 /// Param - The parameter declaration for this parameter.
1165 /// Toks - The sequence of tokens that comprises the default
1166 /// argument expression, not including the '=' or the terminating
1167 /// ')' or ','. This will be NULL for parameters that have no
1168 /// default argument.
1169 std::unique_ptr<CachedTokens> Toks;
1172 /// LateParsedMethodDeclaration - A method declaration inside a class that
1173 /// contains at least one entity whose parsing needs to be delayed
1174 /// until the class itself is completely-defined, such as a default
1175 /// argument (C++ [class.mem]p2).
1176 struct LateParsedMethodDeclaration : public LateParsedDeclaration {
1177 explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
1178 : Self(P), Method(M), TemplateScope(false),
1179 ExceptionSpecTokens(nullptr) {}
1181 void ParseLexedMethodDeclarations() override;
1185 /// Method - The method declaration.
1188 /// Whether this member function had an associated template
1189 /// scope. When true, D is a template declaration.
1190 /// otherwise, it is a member function declaration.
1193 /// DefaultArgs - Contains the parameters of the function and
1194 /// their default arguments. At least one of the parameters will
1195 /// have a default argument, but all of the parameters of the
1196 /// method will be stored so that they can be reintroduced into
1197 /// scope at the appropriate times.
1198 SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
1200 /// The set of tokens that make up an exception-specification that
1201 /// has not yet been parsed.
1202 CachedTokens *ExceptionSpecTokens;
1205 /// LateParsedMemberInitializer - An initializer for a non-static class data
1206 /// member whose parsing must to be delayed until the class is completely
1207 /// defined (C++11 [class.mem]p2).
1208 struct LateParsedMemberInitializer : public LateParsedDeclaration {
1209 LateParsedMemberInitializer(Parser *P, Decl *FD)
1210 : Self(P), Field(FD) { }
1212 void ParseLexedMemberInitializers() override;
1216 /// Field - The field declaration.
1219 /// CachedTokens - The sequence of tokens that comprises the initializer,
1220 /// including any leading '='.
1224 /// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
1225 /// C++ class, its method declarations that contain parts that won't be
1226 /// parsed until after the definition is completed (C++ [class.mem]p2),
1227 /// the method declarations and possibly attached inline definitions
1228 /// will be stored here with the tokens that will be parsed to create those
1230 typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer;
1232 /// Representation of a class that has been parsed, including
1233 /// any member function declarations or definitions that need to be
1234 /// parsed after the corresponding top-level class is complete.
1235 struct ParsingClass {
1236 ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface)
1237 : TopLevelClass(TopLevelClass), TemplateScope(false),
1238 IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) { }
1240 /// Whether this is a "top-level" class, meaning that it is
1241 /// not nested within another class.
1242 bool TopLevelClass : 1;
1244 /// Whether this class had an associated template
1245 /// scope. When true, TagOrTemplate is a template declaration;
1246 /// otherwise, it is a tag declaration.
1247 bool TemplateScope : 1;
1249 /// Whether this class is an __interface.
1250 bool IsInterface : 1;
1252 /// The class or class template whose definition we are parsing.
1253 Decl *TagOrTemplate;
1255 /// LateParsedDeclarations - Method declarations, inline definitions and
1256 /// nested classes that contain pieces whose parsing will be delayed until
1257 /// the top-level class is fully defined.
1258 LateParsedDeclarationsContainer LateParsedDeclarations;
1261 /// The stack of classes that is currently being
1262 /// parsed. Nested and local classes will be pushed onto this stack
1263 /// when they are parsed, and removed afterward.
1264 std::stack<ParsingClass *> ClassStack;
1266 ParsingClass &getCurrentClass() {
1267 assert(!ClassStack.empty() && "No lexed method stacks!");
1268 return *ClassStack.top();
1271 /// RAII object used to manage the parsing of a class definition.
1272 class ParsingClassDefinition {
1275 Sema::ParsingClassState State;
1278 ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass,
1280 : P(P), Popped(false),
1281 State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
1284 /// Pop this class of the stack.
1286 assert(!Popped && "Nested class has already been popped");
1288 P.PopParsingClass(State);
1291 ~ParsingClassDefinition() {
1293 P.PopParsingClass(State);
1297 /// Contains information about any template-specific
1298 /// information that has been parsed prior to parsing declaration
1300 struct ParsedTemplateInfo {
1301 ParsedTemplateInfo()
1302 : Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { }
1304 ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
1305 bool isSpecialization,
1306 bool lastParameterListWasEmpty = false)
1307 : Kind(isSpecialization? ExplicitSpecialization : Template),
1308 TemplateParams(TemplateParams),
1309 LastParameterListWasEmpty(lastParameterListWasEmpty) { }
1311 explicit ParsedTemplateInfo(SourceLocation ExternLoc,
1312 SourceLocation TemplateLoc)
1313 : Kind(ExplicitInstantiation), TemplateParams(nullptr),
1314 ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
1315 LastParameterListWasEmpty(false){ }
1317 /// The kind of template we are parsing.
1319 /// We are not parsing a template at all.
1321 /// We are parsing a template declaration.
1323 /// We are parsing an explicit specialization.
1324 ExplicitSpecialization,
1325 /// We are parsing an explicit instantiation.
1326 ExplicitInstantiation
1329 /// The template parameter lists, for template declarations
1330 /// and explicit specializations.
1331 TemplateParameterLists *TemplateParams;
1333 /// The location of the 'extern' keyword, if any, for an explicit
1335 SourceLocation ExternLoc;
1337 /// The location of the 'template' keyword, for an explicit
1339 SourceLocation TemplateLoc;
1341 /// Whether the last template parameter list was empty.
1342 bool LastParameterListWasEmpty;
1344 SourceRange getSourceRange() const LLVM_READONLY;
1347 void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
1348 void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
1350 static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
1351 static void LateTemplateParserCleanupCallback(void *P);
1353 Sema::ParsingClassState
1354 PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface);
1355 void DeallocateParsedClasses(ParsingClass *Class);
1356 void PopParsingClass(Sema::ParsingClassState);
1358 enum CachedInitKind {
1359 CIK_DefaultArgument,
1360 CIK_DefaultInitializer
1363 NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS,
1364 ParsedAttributes &AccessAttrs,
1365 ParsingDeclarator &D,
1366 const ParsedTemplateInfo &TemplateInfo,
1367 const VirtSpecifiers &VS,
1368 SourceLocation PureSpecLoc);
1369 void ParseCXXNonStaticMemberInitializer(Decl *VarD);
1370 void ParseLexedAttributes(ParsingClass &Class);
1371 void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1372 bool EnterScope, bool OnDefinition);
1373 void ParseLexedAttribute(LateParsedAttribute &LA,
1374 bool EnterScope, bool OnDefinition);
1375 void ParseLexedMethodDeclarations(ParsingClass &Class);
1376 void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
1377 void ParseLexedMethodDefs(ParsingClass &Class);
1378 void ParseLexedMethodDef(LexedMethod &LM);
1379 void ParseLexedMemberInitializers(ParsingClass &Class);
1380 void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
1381 void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod);
1382 bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
1383 bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK);
1384 bool ConsumeAndStoreConditional(CachedTokens &Toks);
1385 bool ConsumeAndStoreUntil(tok::TokenKind T1,
1387 bool StopAtSemi = true,
1388 bool ConsumeFinalToken = true) {
1389 return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
1391 bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
1393 bool StopAtSemi = true,
1394 bool ConsumeFinalToken = true);
1396 //===--------------------------------------------------------------------===//
1397 // C99 6.9: External Definitions.
1398 struct ParsedAttributesWithRange : ParsedAttributes {
1399 ParsedAttributesWithRange(AttributeFactory &factory)
1400 : ParsedAttributes(factory) {}
1403 ParsedAttributes::clear();
1404 Range = SourceRange();
1409 struct ParsedAttributesViewWithRange : ParsedAttributesView {
1410 ParsedAttributesViewWithRange() : ParsedAttributesView() {}
1411 void clearListOnly() {
1412 ParsedAttributesView::clearListOnly();
1413 Range = SourceRange();
1419 DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
1420 ParsingDeclSpec *DS = nullptr);
1421 bool isDeclarationAfterDeclarator();
1422 bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
1423 DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(
1424 ParsedAttributesWithRange &attrs,
1425 ParsingDeclSpec *DS = nullptr,
1426 AccessSpecifier AS = AS_none);
1427 DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
1428 ParsingDeclSpec &DS,
1429 AccessSpecifier AS);
1431 void SkipFunctionBody();
1432 Decl *ParseFunctionDefinition(ParsingDeclarator &D,
1433 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1434 LateParsedAttrList *LateParsedAttrs = nullptr);
1435 void ParseKNRParamDeclarations(Declarator &D);
1436 // EndLoc, if non-NULL, is filled with the location of the last token of
1438 ExprResult ParseSimpleAsm(SourceLocation *EndLoc = nullptr);
1439 ExprResult ParseAsmStringLiteral();
1441 // Objective-C External Declarations
1442 void MaybeSkipAttributes(tok::ObjCKeywordKind Kind);
1443 DeclGroupPtrTy ParseObjCAtDirectives(ParsedAttributesWithRange &Attrs);
1444 DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
1445 Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
1446 ParsedAttributes &prefixAttrs);
1447 class ObjCTypeParamListScope;
1448 ObjCTypeParamList *parseObjCTypeParamList();
1449 ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs(
1450 ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
1451 SmallVectorImpl<IdentifierLocPair> &protocolIdents,
1452 SourceLocation &rAngleLoc, bool mayBeProtocolList = true);
1454 void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
1455 BalancedDelimiterTracker &T,
1456 SmallVectorImpl<Decl *> &AllIvarDecls,
1457 bool RBraceMissing);
1458 void ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1459 tok::ObjCKeywordKind visibility,
1460 SourceLocation atLoc);
1461 bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P,
1462 SmallVectorImpl<SourceLocation> &PLocs,
1463 bool WarnOnDeclarations,
1464 bool ForObjCContainer,
1465 SourceLocation &LAngleLoc,
1466 SourceLocation &EndProtoLoc,
1467 bool consumeLastToken);
1469 /// Parse the first angle-bracket-delimited clause for an
1470 /// Objective-C object or object pointer type, which may be either
1471 /// type arguments or protocol qualifiers.
1472 void parseObjCTypeArgsOrProtocolQualifiers(
1473 ParsedType baseType,
1474 SourceLocation &typeArgsLAngleLoc,
1475 SmallVectorImpl<ParsedType> &typeArgs,
1476 SourceLocation &typeArgsRAngleLoc,
1477 SourceLocation &protocolLAngleLoc,
1478 SmallVectorImpl<Decl *> &protocols,
1479 SmallVectorImpl<SourceLocation> &protocolLocs,
1480 SourceLocation &protocolRAngleLoc,
1481 bool consumeLastToken,
1482 bool warnOnIncompleteProtocols);
1484 /// Parse either Objective-C type arguments or protocol qualifiers; if the
1485 /// former, also parse protocol qualifiers afterward.
1486 void parseObjCTypeArgsAndProtocolQualifiers(
1487 ParsedType baseType,
1488 SourceLocation &typeArgsLAngleLoc,
1489 SmallVectorImpl<ParsedType> &typeArgs,
1490 SourceLocation &typeArgsRAngleLoc,
1491 SourceLocation &protocolLAngleLoc,
1492 SmallVectorImpl<Decl *> &protocols,
1493 SmallVectorImpl<SourceLocation> &protocolLocs,
1494 SourceLocation &protocolRAngleLoc,
1495 bool consumeLastToken);
1497 /// Parse a protocol qualifier type such as '<NSCopying>', which is
1498 /// an anachronistic way of writing 'id<NSCopying>'.
1499 TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc);
1501 /// Parse Objective-C type arguments and protocol qualifiers, extending the
1502 /// current type with the parsed result.
1503 TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc,
1505 bool consumeLastToken,
1506 SourceLocation &endLoc);
1508 void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
1510 DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
1511 ParsedAttributes &prefixAttrs);
1513 struct ObjCImplParsingDataRAII {
1517 typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer;
1518 LateParsedObjCMethodContainer LateParsedObjCMethods;
1520 ObjCImplParsingDataRAII(Parser &parser, Decl *D)
1521 : P(parser), Dcl(D), HasCFunction(false) {
1522 P.CurParsedObjCImpl = this;
1525 ~ObjCImplParsingDataRAII();
1527 void finish(SourceRange AtEnd);
1528 bool isFinished() const { return Finished; }
1533 ObjCImplParsingDataRAII *CurParsedObjCImpl;
1534 void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl);
1536 DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc);
1537 DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
1538 Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
1539 Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
1540 Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
1542 IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
1543 // Definitions for Objective-c context sensitive keywords recognition.
1545 objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
1546 objc_nonnull, objc_nullable, objc_null_unspecified,
1549 IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
1551 bool isTokIdentifier_in() const;
1553 ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx,
1554 ParsedAttributes *ParamAttrs);
1555 void ParseObjCMethodRequirement();
1556 Decl *ParseObjCMethodPrototype(
1557 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1558 bool MethodDefinition = true);
1559 Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
1560 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1561 bool MethodDefinition=true);
1562 void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
1564 Decl *ParseObjCMethodDefinition();
1567 //===--------------------------------------------------------------------===//
1568 // C99 6.5: Expressions.
1570 /// TypeCastState - State whether an expression is or may be a type cast.
1571 enum TypeCastState {
1577 ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast);
1578 ExprResult ParseConstantExpressionInExprEvalContext(
1579 TypeCastState isTypeCast = NotTypeCast);
1580 ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast);
1581 ExprResult ParseCaseExpression(SourceLocation CaseLoc);
1582 ExprResult ParseConstraintExpression();
1583 // Expr that doesn't include commas.
1584 ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast);
1586 ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1587 unsigned &NumLineToksConsumed,
1588 bool IsUnevaluated);
1591 ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
1593 ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
1595 ExprResult ParseRHSOfBinaryExpression(ExprResult LHS,
1596 prec::Level MinPrec);
1597 ExprResult ParseCastExpression(bool isUnaryExpression,
1598 bool isAddressOfOperand,
1600 TypeCastState isTypeCast,
1601 bool isVectorLiteral = false);
1602 ExprResult ParseCastExpression(bool isUnaryExpression,
1603 bool isAddressOfOperand = false,
1604 TypeCastState isTypeCast = NotTypeCast,
1605 bool isVectorLiteral = false);
1607 /// Returns true if the next token cannot start an expression.
1608 bool isNotExpressionStart();
1610 /// Returns true if the next token would start a postfix-expression
1612 bool isPostfixExpressionSuffixStart() {
1613 tok::TokenKind K = Tok.getKind();
1614 return (K == tok::l_square || K == tok::l_paren ||
1615 K == tok::period || K == tok::arrow ||
1616 K == tok::plusplus || K == tok::minusminus);
1619 bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less);
1620 void checkPotentialAngleBracket(ExprResult &PotentialTemplateName);
1621 bool checkPotentialAngleBracketDelimiter(const AngleBracketTracker::Loc &,
1622 const Token &OpToken);
1623 bool checkPotentialAngleBracketDelimiter(const Token &OpToken) {
1624 if (auto *Info = AngleBrackets.getCurrent(*this))
1625 return checkPotentialAngleBracketDelimiter(*Info, OpToken);
1629 ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
1630 ExprResult ParseUnaryExprOrTypeTraitExpression();
1631 ExprResult ParseBuiltinPrimaryExpression();
1633 ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1636 SourceRange &CastRange);
1638 typedef SmallVector<Expr*, 20> ExprListTy;
1639 typedef SmallVector<SourceLocation, 20> CommaLocsTy;
1641 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1642 bool ParseExpressionList(
1643 SmallVectorImpl<Expr *> &Exprs,
1644 SmallVectorImpl<SourceLocation> &CommaLocs,
1645 llvm::function_ref<void()> Completer = llvm::function_ref<void()>());
1647 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
1648 /// used for misc language extensions.
1649 bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
1650 SmallVectorImpl<SourceLocation> &CommaLocs);
1653 /// ParenParseOption - Control what ParseParenExpression will parse.
1654 enum ParenParseOption {
1655 SimpleExpr, // Only parse '(' expression ')'
1656 FoldExpr, // Also allow fold-expression <anything>
1657 CompoundStmt, // Also allow '(' compound-statement ')'
1658 CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
1659 CastExpr // Also allow '(' type-name ')' <anything>
1661 ExprResult ParseParenExpression(ParenParseOption &ExprType,
1662 bool stopIfCastExpr,
1665 SourceLocation &RParenLoc);
1667 ExprResult ParseCXXAmbiguousParenExpression(
1668 ParenParseOption &ExprType, ParsedType &CastTy,
1669 BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt);
1670 ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
1671 SourceLocation LParenLoc,
1672 SourceLocation RParenLoc);
1674 ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
1676 ExprResult ParseGenericSelectionExpression();
1678 ExprResult ParseObjCBoolLiteral();
1680 ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T);
1682 //===--------------------------------------------------------------------===//
1684 ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
1685 Token &Replacement);
1686 ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
1688 bool areTokensAdjacent(const Token &A, const Token &B);
1690 void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
1691 bool EnteringContext, IdentifierInfo &II,
1694 bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
1695 ParsedType ObjectType,
1696 bool EnteringContext,
1697 bool *MayBePseudoDestructor = nullptr,
1698 bool IsTypename = false,
1699 IdentifierInfo **LastII = nullptr,
1700 bool OnlyNamespace = false);
1702 //===--------------------------------------------------------------------===//
1703 // C++0x 5.1.2: Lambda expressions
1705 // [...] () -> type {...}
1706 ExprResult ParseLambdaExpression();
1707 ExprResult TryParseLambdaExpression();
1708 Optional<unsigned> ParseLambdaIntroducer(LambdaIntroducer &Intro,
1709 bool *SkippedInits = nullptr);
1710 bool TryParseLambdaIntroducer(LambdaIntroducer &Intro);
1711 ExprResult ParseLambdaExpressionAfterIntroducer(
1712 LambdaIntroducer &Intro);
1714 //===--------------------------------------------------------------------===//
1715 // C++ 5.2p1: C++ Casts
1716 ExprResult ParseCXXCasts();
1718 //===--------------------------------------------------------------------===//
1719 // C++ 5.2p1: C++ Type Identification
1720 ExprResult ParseCXXTypeid();
1722 //===--------------------------------------------------------------------===//
1723 // C++ : Microsoft __uuidof Expression
1724 ExprResult ParseCXXUuidof();
1726 //===--------------------------------------------------------------------===//
1727 // C++ 5.2.4: C++ Pseudo-Destructor Expressions
1728 ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1729 tok::TokenKind OpKind,
1731 ParsedType ObjectType);
1733 //===--------------------------------------------------------------------===//
1734 // C++ 9.3.2: C++ 'this' pointer
1735 ExprResult ParseCXXThis();
1737 //===--------------------------------------------------------------------===//
1738 // C++ 15: C++ Throw Expression
1739 ExprResult ParseThrowExpression();
1741 ExceptionSpecificationType tryParseExceptionSpecification(
1743 SourceRange &SpecificationRange,
1744 SmallVectorImpl<ParsedType> &DynamicExceptions,
1745 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
1746 ExprResult &NoexceptExpr,
1747 CachedTokens *&ExceptionSpecTokens);
1749 // EndLoc is filled with the location of the last token of the specification.
1750 ExceptionSpecificationType ParseDynamicExceptionSpecification(
1751 SourceRange &SpecificationRange,
1752 SmallVectorImpl<ParsedType> &Exceptions,
1753 SmallVectorImpl<SourceRange> &Ranges);
1755 //===--------------------------------------------------------------------===//
1756 // C++0x 8: Function declaration trailing-return-type
1757 TypeResult ParseTrailingReturnType(SourceRange &Range,
1758 bool MayBeFollowedByDirectInit);
1760 //===--------------------------------------------------------------------===//
1761 // C++ 2.13.5: C++ Boolean Literals
1762 ExprResult ParseCXXBoolLiteral();
1764 //===--------------------------------------------------------------------===//
1765 // C++ 5.2.3: Explicit type conversion (functional notation)
1766 ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
1768 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1769 /// This should only be called when the current token is known to be part of
1770 /// simple-type-specifier.
1771 void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
1773 bool ParseCXXTypeSpecifierSeq(DeclSpec &DS);
1775 //===--------------------------------------------------------------------===//
1776 // C++ 5.3.4 and 5.3.5: C++ new and delete
1777 bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs,
1779 void ParseDirectNewDeclarator(Declarator &D);
1780 ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
1781 ExprResult ParseCXXDeleteExpression(bool UseGlobal,
1782 SourceLocation Start);
1784 //===--------------------------------------------------------------------===//
1785 // C++ if/switch/while condition expression.
1786 Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt,
1788 Sema::ConditionKind CK);
1790 //===--------------------------------------------------------------------===//
1793 ExprResult ParseCoyieldExpression();
1795 //===--------------------------------------------------------------------===//
1796 // C99 6.7.8: Initialization.
1798 /// ParseInitializer
1799 /// initializer: [C99 6.7.8]
1800 /// assignment-expression
1802 ExprResult ParseInitializer() {
1803 if (Tok.isNot(tok::l_brace))
1804 return ParseAssignmentExpression();
1805 return ParseBraceInitializer();
1807 bool MayBeDesignationStart();
1808 ExprResult ParseBraceInitializer();
1809 ExprResult ParseInitializerWithPotentialDesignator();
1811 //===--------------------------------------------------------------------===//
1812 // clang Expressions
1814 ExprResult ParseBlockLiteralExpression(); // ^{...}
1816 //===--------------------------------------------------------------------===//
1817 // Objective-C Expressions
1818 ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
1819 ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
1820 ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
1821 ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
1822 ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
1823 ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
1824 ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
1825 ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
1826 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
1827 ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
1828 ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
1829 bool isSimpleObjCMessageExpression();
1830 ExprResult ParseObjCMessageExpression();
1831 ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
1832 SourceLocation SuperLoc,
1833 ParsedType ReceiverType,
1834 Expr *ReceiverExpr);
1835 ExprResult ParseAssignmentExprWithObjCMessageExprStart(
1836 SourceLocation LBracloc, SourceLocation SuperLoc,
1837 ParsedType ReceiverType, Expr *ReceiverExpr);
1838 bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
1840 //===--------------------------------------------------------------------===//
1841 // C99 6.8: Statements and Blocks.
1843 /// A SmallVector of statements, with stack size 32 (as that is the only one
1845 typedef SmallVector<Stmt*, 32> StmtVector;
1846 /// A SmallVector of expressions, with stack size 12 (the maximum used.)
1847 typedef SmallVector<Expr*, 12> ExprVector;
1848 /// A SmallVector of types.
1849 typedef SmallVector<ParsedType, 12> TypeVector;
1851 StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
1852 bool AllowOpenMPStandalone = false);
1853 enum AllowedConstructsKind {
1854 /// Allow any declarations, statements, OpenMP directives.
1856 /// Allow only statements and non-standalone OpenMP directives.
1857 ACK_StatementsOpenMPNonStandalone,
1858 /// Allow statements and all executable OpenMP directives
1859 ACK_StatementsOpenMPAnyExecutable
1862 ParseStatementOrDeclaration(StmtVector &Stmts, AllowedConstructsKind Allowed,
1863 SourceLocation *TrailingElseLoc = nullptr);
1864 StmtResult ParseStatementOrDeclarationAfterAttributes(
1866 AllowedConstructsKind Allowed,
1867 SourceLocation *TrailingElseLoc,
1868 ParsedAttributesWithRange &Attrs);
1869 StmtResult ParseExprStatement();
1870 StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs);
1871 StmtResult ParseCaseStatement(bool MissingCase = false,
1872 ExprResult Expr = ExprResult());
1873 StmtResult ParseDefaultStatement();
1874 StmtResult ParseCompoundStatement(bool isStmtExpr = false);
1875 StmtResult ParseCompoundStatement(bool isStmtExpr,
1876 unsigned ScopeFlags);
1877 void ParseCompoundStatementLeadingPragmas();
1878 StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
1879 bool ParseParenExprOrCondition(StmtResult *InitStmt,
1880 Sema::ConditionResult &CondResult,
1882 Sema::ConditionKind CK);
1883 StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
1884 StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
1885 StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
1886 StmtResult ParseDoStatement();
1887 StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
1888 StmtResult ParseGotoStatement();
1889 StmtResult ParseContinueStatement();
1890 StmtResult ParseBreakStatement();
1891 StmtResult ParseReturnStatement();
1892 StmtResult ParseAsmStatement(bool &msAsm);
1893 StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
1894 StmtResult ParsePragmaLoopHint(StmtVector &Stmts,
1895 AllowedConstructsKind Allowed,
1896 SourceLocation *TrailingElseLoc,
1897 ParsedAttributesWithRange &Attrs);
1899 /// Describes the behavior that should be taken for an __if_exists
1901 enum IfExistsBehavior {
1902 /// Parse the block; this code is always used.
1904 /// Skip the block entirely; this code is never used.
1906 /// Parse the block as a dependent block, which may be used in
1907 /// some template instantiations but not others.
1911 /// Describes the condition of a Microsoft __if_exists or
1912 /// __if_not_exists block.
1913 struct IfExistsCondition {
1914 /// The location of the initial keyword.
1915 SourceLocation KeywordLoc;
1916 /// Whether this is an __if_exists block (rather than an
1917 /// __if_not_exists block).
1920 /// Nested-name-specifier preceding the name.
1923 /// The name we're looking for.
1926 /// The behavior of this __if_exists or __if_not_exists block
1928 IfExistsBehavior Behavior;
1931 bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
1932 void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
1933 void ParseMicrosoftIfExistsExternalDeclaration();
1934 void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
1935 ParsedAttributes &AccessAttrs,
1936 AccessSpecifier &CurAS);
1937 bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
1939 bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
1940 SmallVectorImpl<Expr *> &Constraints,
1941 SmallVectorImpl<Expr *> &Exprs);
1943 //===--------------------------------------------------------------------===//
1944 // C++ 6: Statements and Blocks
1946 StmtResult ParseCXXTryBlock();
1947 StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
1948 StmtResult ParseCXXCatchBlock(bool FnCatch = false);
1950 //===--------------------------------------------------------------------===//
1951 // MS: SEH Statements and Blocks
1953 StmtResult ParseSEHTryBlock();
1954 StmtResult ParseSEHExceptBlock(SourceLocation Loc);
1955 StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
1956 StmtResult ParseSEHLeaveStatement();
1958 //===--------------------------------------------------------------------===//
1959 // Objective-C Statements
1961 StmtResult ParseObjCAtStatement(SourceLocation atLoc);
1962 StmtResult ParseObjCTryStmt(SourceLocation atLoc);
1963 StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
1964 StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
1965 StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
1968 //===--------------------------------------------------------------------===//
1969 // C99 6.7: Declarations.
1971 /// A context for parsing declaration specifiers. TODO: flesh this
1972 /// out, there are other significant restrictions on specifiers than
1973 /// would be best implemented in the parser.
1974 enum class DeclSpecContext {
1975 DSC_normal, // normal context
1976 DSC_class, // class context, enables 'friend'
1977 DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
1978 DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
1979 DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration
1980 DSC_top_level, // top-level/namespace declaration context
1981 DSC_template_param, // template parameter context
1982 DSC_template_type_arg, // template type argument context
1983 DSC_objc_method_result, // ObjC method result context, enables 'instancetype'
1984 DSC_condition // condition declaration context
1987 /// Is this a context in which we are parsing just a type-specifier (or
1988 /// trailing-type-specifier)?
1989 static bool isTypeSpecifier(DeclSpecContext DSC) {
1991 case DeclSpecContext::DSC_normal:
1992 case DeclSpecContext::DSC_template_param:
1993 case DeclSpecContext::DSC_class:
1994 case DeclSpecContext::DSC_top_level:
1995 case DeclSpecContext::DSC_objc_method_result:
1996 case DeclSpecContext::DSC_condition:
1999 case DeclSpecContext::DSC_template_type_arg:
2000 case DeclSpecContext::DSC_type_specifier:
2001 case DeclSpecContext::DSC_trailing:
2002 case DeclSpecContext::DSC_alias_declaration:
2005 llvm_unreachable("Missing DeclSpecContext case");
2008 /// Is this a context in which we can perform class template argument
2010 static bool isClassTemplateDeductionContext(DeclSpecContext DSC) {
2012 case DeclSpecContext::DSC_normal:
2013 case DeclSpecContext::DSC_template_param:
2014 case DeclSpecContext::DSC_class:
2015 case DeclSpecContext::DSC_top_level:
2016 case DeclSpecContext::DSC_condition:
2017 case DeclSpecContext::DSC_type_specifier:
2020 case DeclSpecContext::DSC_objc_method_result:
2021 case DeclSpecContext::DSC_template_type_arg:
2022 case DeclSpecContext::DSC_trailing:
2023 case DeclSpecContext::DSC_alias_declaration:
2026 llvm_unreachable("Missing DeclSpecContext case");
2029 /// Information on a C++0x for-range-initializer found while parsing a
2030 /// declaration which turns out to be a for-range-declaration.
2031 struct ForRangeInit {
2032 SourceLocation ColonLoc;
2033 ExprResult RangeExpr;
2035 bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
2038 DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context,
2039 SourceLocation &DeclEnd,
2040 ParsedAttributesWithRange &attrs);
2041 DeclGroupPtrTy ParseSimpleDeclaration(DeclaratorContext Context,
2042 SourceLocation &DeclEnd,
2043 ParsedAttributesWithRange &attrs,
2045 ForRangeInit *FRI = nullptr);
2046 bool MightBeDeclarator(DeclaratorContext Context);
2047 DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context,
2048 SourceLocation *DeclEnd = nullptr,
2049 ForRangeInit *FRI = nullptr);
2050 Decl *ParseDeclarationAfterDeclarator(Declarator &D,
2051 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
2052 bool ParseAsmAttributesAfterDeclarator(Declarator &D);
2053 Decl *ParseDeclarationAfterDeclaratorAndAttributes(
2055 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2056 ForRangeInit *FRI = nullptr);
2057 Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
2058 Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
2060 /// When in code-completion, skip parsing of the function/method body
2061 /// unless the body contains the code-completion point.
2063 /// \returns true if the function body was skipped.
2064 bool trySkippingFunctionBody();
2066 bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2067 const ParsedTemplateInfo &TemplateInfo,
2068 AccessSpecifier AS, DeclSpecContext DSC,
2069 ParsedAttributesWithRange &Attrs);
2071 getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context);
2072 void ParseDeclarationSpecifiers(
2074 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2075 AccessSpecifier AS = AS_none,
2076 DeclSpecContext DSC = DeclSpecContext::DSC_normal,
2077 LateParsedAttrList *LateAttrs = nullptr);
2078 bool DiagnoseMissingSemiAfterTagDefinition(
2079 DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext,
2080 LateParsedAttrList *LateAttrs = nullptr);
2082 void ParseSpecifierQualifierList(
2083 DeclSpec &DS, AccessSpecifier AS = AS_none,
2084 DeclSpecContext DSC = DeclSpecContext::DSC_normal);
2086 void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
2087 DeclaratorContext Context);
2089 void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
2090 const ParsedTemplateInfo &TemplateInfo,
2091 AccessSpecifier AS, DeclSpecContext DSC);
2092 void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
2093 void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType,
2096 void ParseStructDeclaration(
2097 ParsingDeclSpec &DS,
2098 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback);
2100 bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
2101 bool isTypeSpecifierQualifier();
2103 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
2104 /// is definitely a type-specifier. Return false if it isn't part of a type
2105 /// specifier or if we're not sure.
2106 bool isKnownToBeTypeSpecifier(const Token &Tok) const;
2108 /// Return true if we know that we are definitely looking at a
2109 /// decl-specifier, and isn't part of an expression such as a function-style
2110 /// cast. Return false if it's no a decl-specifier, or we're not sure.
2111 bool isKnownToBeDeclarationSpecifier() {
2112 if (getLangOpts().CPlusPlus)
2113 return isCXXDeclarationSpecifier() == TPResult::True;
2114 return isDeclarationSpecifier(true);
2117 /// isDeclarationStatement - Disambiguates between a declaration or an
2118 /// expression statement, when parsing function bodies.
2119 /// Returns true for declaration, false for expression.
2120 bool isDeclarationStatement() {
2121 if (getLangOpts().CPlusPlus)
2122 return isCXXDeclarationStatement();
2123 return isDeclarationSpecifier(true);
2126 /// isForInitDeclaration - Disambiguates between a declaration or an
2127 /// expression in the context of the C 'clause-1' or the C++
2128 // 'for-init-statement' part of a 'for' statement.
2129 /// Returns true for declaration, false for expression.
2130 bool isForInitDeclaration() {
2131 if (getLangOpts().CPlusPlus)
2132 return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
2133 return isDeclarationSpecifier(true);
2136 /// Determine whether this is a C++1z for-range-identifier.
2137 bool isForRangeIdentifier();
2139 /// Determine whether we are currently at the start of an Objective-C
2140 /// class message that appears to be missing the open bracket '['.
2141 bool isStartOfObjCClassMessageMissingOpenBracket();
2143 /// Starting with a scope specifier, identifier, or
2144 /// template-id that refers to the current class, determine whether
2145 /// this is a constructor declarator.
2146 bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false);
2148 /// Specifies the context in which type-id/expression
2149 /// disambiguation will occur.
2150 enum TentativeCXXTypeIdContext {
2153 TypeIdAsTemplateArgument
2157 /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
2158 /// whether the parens contain an expression or a type-id.
2159 /// Returns true for a type-id and false for an expression.
2160 bool isTypeIdInParens(bool &isAmbiguous) {
2161 if (getLangOpts().CPlusPlus)
2162 return isCXXTypeId(TypeIdInParens, isAmbiguous);
2163 isAmbiguous = false;
2164 return isTypeSpecifierQualifier();
2166 bool isTypeIdInParens() {
2168 return isTypeIdInParens(isAmbiguous);
2171 /// Checks if the current tokens form type-id or expression.
2172 /// It is similar to isTypeIdInParens but does not suppose that type-id
2173 /// is in parenthesis.
2174 bool isTypeIdUnambiguously() {
2176 if (getLangOpts().CPlusPlus)
2177 return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous);
2178 return isTypeSpecifierQualifier();
2181 /// isCXXDeclarationStatement - C++-specialized function that disambiguates
2182 /// between a declaration or an expression statement, when parsing function
2183 /// bodies. Returns true for declaration, false for expression.
2184 bool isCXXDeclarationStatement();
2186 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
2187 /// between a simple-declaration or an expression-statement.
2188 /// If during the disambiguation process a parsing error is encountered,
2189 /// the function returns true to let the declaration parsing code handle it.
2190 /// Returns false if the statement is disambiguated as expression.
2191 bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
2193 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
2194 /// a constructor-style initializer, when parsing declaration statements.
2195 /// Returns true for function declarator and false for constructor-style
2196 /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
2197 /// might be a constructor-style initializer.
2198 /// If during the disambiguation process a parsing error is encountered,
2199 /// the function returns true to let the declaration parsing code handle it.
2200 bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr);
2202 struct ConditionDeclarationOrInitStatementState;
2203 enum class ConditionOrInitStatement {
2204 Expression, ///< Disambiguated as an expression (either kind).
2205 ConditionDecl, ///< Disambiguated as the declaration form of condition.
2206 InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement.
2207 Error ///< Can't be any of the above!
2209 /// Disambiguates between the different kinds of things that can happen
2210 /// after 'if (' or 'switch ('. This could be one of two different kinds of
2211 /// declaration (depending on whether there is a ';' later) or an expression.
2212 ConditionOrInitStatement
2213 isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt);
2215 bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
2216 bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
2218 return isCXXTypeId(Context, isAmbiguous);
2221 /// TPResult - Used as the result value for functions whose purpose is to
2222 /// disambiguate C++ constructs by "tentatively parsing" them.
2223 enum class TPResult {
2224 True, False, Ambiguous, Error
2227 /// Based only on the given token kind, determine whether we know that
2228 /// we're at the start of an expression or a type-specifier-seq (which may
2229 /// be an expression, in C++).
2231 /// This routine does not attempt to resolve any of the trick cases, e.g.,
2232 /// those involving lookup of identifiers.
2234 /// \returns \c TPR_true if this token starts an expression, \c TPR_false if
2235 /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot
2237 TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind);
2239 /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a
2240 /// declaration specifier, TPResult::False if it is not,
2241 /// TPResult::Ambiguous if it could be either a decl-specifier or a
2242 /// function-style cast, and TPResult::Error if a parsing error was
2243 /// encountered. If it could be a braced C++11 function-style cast, returns
2244 /// BracedCastResult.
2245 /// Doesn't consume tokens.
2247 isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False,
2248 bool *HasMissingTypename = nullptr);
2250 /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
2251 /// \c TPResult::Ambiguous, determine whether the decl-specifier would be
2252 /// a type-specifier other than a cv-qualifier.
2253 bool isCXXDeclarationSpecifierAType();
2255 /// Determine whether an identifier has been tentatively declared as a
2256 /// non-type. Such tentative declarations should not be found to name a type
2257 /// during a tentative parse, but also should not be annotated as a non-type.
2258 bool isTentativelyDeclared(IdentifierInfo *II);
2260 // "Tentative parsing" functions, used for disambiguation. If a parsing error
2261 // is encountered they will return TPResult::Error.
2262 // Returning TPResult::True/False indicates that the ambiguity was
2263 // resolved and tentative parsing may stop. TPResult::Ambiguous indicates
2264 // that more tentative parsing is necessary for disambiguation.
2265 // They all consume tokens, so backtracking should be used after calling them.
2267 TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
2268 TPResult TryParseTypeofSpecifier();
2269 TPResult TryParseProtocolQualifiers();
2270 TPResult TryParsePtrOperatorSeq();
2271 TPResult TryParseOperatorId();
2272 TPResult TryParseInitDeclaratorList();
2273 TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true,
2274 bool mayHaveDirectInit = false);
2276 TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr,
2277 bool VersusTemplateArg = false);
2278 TPResult TryParseFunctionDeclarator();
2279 TPResult TryParseBracketDeclarator();
2280 TPResult TryConsumeDeclarationSpecifier();
2283 TypeResult ParseTypeName(SourceRange *Range = nullptr,
2284 DeclaratorContext Context
2285 = DeclaratorContext::TypeNameContext,
2286 AccessSpecifier AS = AS_none,
2287 Decl **OwnedType = nullptr,
2288 ParsedAttributes *Attrs = nullptr);
2291 void ParseBlockId(SourceLocation CaretLoc);
2293 /// Are [[]] attributes enabled?
2294 bool standardAttributesAllowed() const {
2295 const LangOptions &LO = getLangOpts();
2296 return LO.DoubleSquareBracketAttributes;
2299 // Check for the start of an attribute-specifier-seq in a context where an
2300 // attribute is not allowed.
2301 bool CheckProhibitedCXX11Attribute() {
2302 assert(Tok.is(tok::l_square));
2303 if (!standardAttributesAllowed() || NextToken().isNot(tok::l_square))
2305 return DiagnoseProhibitedCXX11Attribute();
2308 bool DiagnoseProhibitedCXX11Attribute();
2309 void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2310 SourceLocation CorrectLocation) {
2311 if (!standardAttributesAllowed())
2313 if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
2314 Tok.isNot(tok::kw_alignas))
2316 DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
2318 void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2319 SourceLocation CorrectLocation);
2321 void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
2322 DeclSpec &DS, Sema::TagUseKind TUK);
2324 // FixItLoc = possible correct location for the attributes
2325 void ProhibitAttributes(ParsedAttributesWithRange &Attrs,
2326 SourceLocation FixItLoc = SourceLocation()) {
2327 if (Attrs.Range.isInvalid())
2329 DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc);
2333 void ProhibitAttributes(ParsedAttributesViewWithRange &Attrs,
2334 SourceLocation FixItLoc = SourceLocation()) {
2335 if (Attrs.Range.isInvalid())
2337 DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc);
2338 Attrs.clearListOnly();
2340 void DiagnoseProhibitedAttributes(const SourceRange &Range,
2341 SourceLocation FixItLoc);
2343 // Forbid C++11 and C2x attributes that appear on certain syntactic locations
2344 // which standard permits but we don't supported yet, for example, attributes
2345 // appertain to decl specifiers.
2346 void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
2349 /// Skip C++11 and C2x attributes and return the end location of the
2351 /// \returns SourceLocation() if there are no attributes.
2352 SourceLocation SkipCXX11Attributes();
2354 /// Diagnose and skip C++11 and C2x attributes that appear in syntactic
2355 /// locations where attributes are not allowed.
2356 void DiagnoseAndSkipCXX11Attributes();
2358 /// Parses syntax-generic attribute arguments for attributes which are
2359 /// known to the implementation, and adds them to the given ParsedAttributes
2360 /// list with the given attribute syntax. Returns the number of arguments
2361 /// parsed for the attribute.
2363 ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2364 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2365 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2366 ParsedAttr::Syntax Syntax);
2368 void MaybeParseGNUAttributes(Declarator &D,
2369 LateParsedAttrList *LateAttrs = nullptr) {
2370 if (Tok.is(tok::kw___attribute)) {
2371 ParsedAttributes attrs(AttrFactory);
2372 SourceLocation endLoc;
2373 ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D);
2374 D.takeAttributes(attrs, endLoc);
2377 void MaybeParseGNUAttributes(ParsedAttributes &attrs,
2378 SourceLocation *endLoc = nullptr,
2379 LateParsedAttrList *LateAttrs = nullptr) {
2380 if (Tok.is(tok::kw___attribute))
2381 ParseGNUAttributes(attrs, endLoc, LateAttrs);
2383 void ParseGNUAttributes(ParsedAttributes &attrs,
2384 SourceLocation *endLoc = nullptr,
2385 LateParsedAttrList *LateAttrs = nullptr,
2386 Declarator *D = nullptr);
2387 void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
2388 SourceLocation AttrNameLoc,
2389 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2390 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2391 ParsedAttr::Syntax Syntax, Declarator *D);
2392 IdentifierLoc *ParseIdentifierLoc();
2395 ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2396 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2397 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2398 ParsedAttr::Syntax Syntax);
2400 void MaybeParseCXX11Attributes(Declarator &D) {
2401 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
2402 ParsedAttributesWithRange attrs(AttrFactory);
2403 SourceLocation endLoc;
2404 ParseCXX11Attributes(attrs, &endLoc);
2405 D.takeAttributes(attrs, endLoc);
2408 void MaybeParseCXX11Attributes(ParsedAttributes &attrs,
2409 SourceLocation *endLoc = nullptr) {
2410 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
2411 ParsedAttributesWithRange attrsWithRange(AttrFactory);
2412 ParseCXX11Attributes(attrsWithRange, endLoc);
2413 attrs.takeAllFrom(attrsWithRange);
2416 void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2417 SourceLocation *endLoc = nullptr,
2418 bool OuterMightBeMessageSend = false) {
2419 if (standardAttributesAllowed() &&
2420 isCXX11AttributeSpecifier(false, OuterMightBeMessageSend))
2421 ParseCXX11Attributes(attrs, endLoc);
2424 void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
2425 SourceLocation *EndLoc = nullptr);
2426 void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2427 SourceLocation *EndLoc = nullptr);
2428 /// Parses a C++11 (or C2x)-style attribute argument list. Returns true
2429 /// if this results in adding an attribute to the ParsedAttributes list.
2430 bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
2431 SourceLocation AttrNameLoc,
2432 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2433 IdentifierInfo *ScopeName,
2434 SourceLocation ScopeLoc);
2436 IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc);
2438 void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
2439 SourceLocation *endLoc = nullptr) {
2440 if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
2441 ParseMicrosoftAttributes(attrs, endLoc);
2443 void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs);
2444 void ParseMicrosoftAttributes(ParsedAttributes &attrs,
2445 SourceLocation *endLoc = nullptr);
2446 void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2447 SourceLocation *End = nullptr) {
2448 const auto &LO = getLangOpts();
2449 if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec))
2450 ParseMicrosoftDeclSpecs(Attrs, End);
2452 void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2453 SourceLocation *End = nullptr);
2454 bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
2455 SourceLocation AttrNameLoc,
2456 ParsedAttributes &Attrs);
2457 void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
2458 void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2459 SourceLocation SkipExtendedMicrosoftTypeAttributes();
2460 void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
2461 void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
2462 void ParseOpenCLKernelAttributes(ParsedAttributes &attrs);
2463 void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
2464 /// Parses opencl_unroll_hint attribute if language is OpenCL v2.0
2466 /// \return false if error happens.
2467 bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
2468 if (getLangOpts().OpenCL)
2469 return ParseOpenCLUnrollHintAttribute(Attrs);
2472 /// Parses opencl_unroll_hint attribute.
2473 /// \return false if error happens.
2474 bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs);
2475 void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
2477 VersionTuple ParseVersionTuple(SourceRange &Range);
2478 void ParseAvailabilityAttribute(IdentifierInfo &Availability,
2479 SourceLocation AvailabilityLoc,
2480 ParsedAttributes &attrs,
2481 SourceLocation *endLoc,
2482 IdentifierInfo *ScopeName,
2483 SourceLocation ScopeLoc,
2484 ParsedAttr::Syntax Syntax);
2486 Optional<AvailabilitySpec> ParseAvailabilitySpec();
2487 ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc);
2489 void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol,
2491 ParsedAttributes &Attrs,
2492 SourceLocation *EndLoc,
2493 IdentifierInfo *ScopeName,
2494 SourceLocation ScopeLoc,
2495 ParsedAttr::Syntax Syntax);
2497 void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
2498 SourceLocation ObjCBridgeRelatedLoc,
2499 ParsedAttributes &attrs,
2500 SourceLocation *endLoc,
2501 IdentifierInfo *ScopeName,
2502 SourceLocation ScopeLoc,
2503 ParsedAttr::Syntax Syntax);
2505 void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
2506 SourceLocation AttrNameLoc,
2507 ParsedAttributes &Attrs,
2508 SourceLocation *EndLoc,
2509 IdentifierInfo *ScopeName,
2510 SourceLocation ScopeLoc,
2511 ParsedAttr::Syntax Syntax);
2514 ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
2515 SourceLocation AttrNameLoc, ParsedAttributes &Attrs,
2516 SourceLocation *EndLoc, IdentifierInfo *ScopeName,
2517 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax);
2519 void ParseTypeofSpecifier(DeclSpec &DS);
2520 SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
2521 void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
2522 SourceLocation StartLoc,
2523 SourceLocation EndLoc);
2524 void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
2525 void ParseAtomicSpecifier(DeclSpec &DS);
2527 ExprResult ParseAlignArgument(SourceLocation Start,
2528 SourceLocation &EllipsisLoc);
2529 void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2530 SourceLocation *endLoc = nullptr);
2532 VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
2533 VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
2534 return isCXX11VirtSpecifier(Tok);
2536 void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface,
2537 SourceLocation FriendLoc);
2539 bool isCXX11FinalKeyword() const;
2541 /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
2542 /// enter a new C++ declarator scope and exit it when the function is
2544 class DeclaratorScopeObj {
2550 DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
2551 : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
2553 void EnterDeclaratorScope() {
2554 assert(!EnteredScope && "Already entered the scope!");
2555 assert(SS.isSet() && "C++ scope was not set!");
2557 CreatedScope = true;
2558 P.EnterScope(0); // Not a decl scope.
2560 if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
2561 EnteredScope = true;
2564 ~DeclaratorScopeObj() {
2566 assert(SS.isSet() && "C++ scope was cleared ?");
2567 P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
2574 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
2575 void ParseDeclarator(Declarator &D);
2576 /// A function that parses a variant of direct-declarator.
2577 typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
2578 void ParseDeclaratorInternal(Declarator &D,
2579 DirectDeclParseFunction DirectDeclParser);
2581 enum AttrRequirements {
2582 AR_NoAttributesParsed = 0, ///< No attributes are diagnosed.
2583 AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes.
2584 AR_GNUAttributesParsed = 1 << 1,
2585 AR_CXX11AttributesParsed = 1 << 2,
2586 AR_DeclspecAttributesParsed = 1 << 3,
2587 AR_AllAttributesParsed = AR_GNUAttributesParsed |
2588 AR_CXX11AttributesParsed |
2589 AR_DeclspecAttributesParsed,
2590 AR_VendorAttributesParsed = AR_GNUAttributesParsed |
2591 AR_DeclspecAttributesParsed
2594 void ParseTypeQualifierListOpt(
2595 DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed,
2596 bool AtomicAllowed = true, bool IdentifierRequired = false,
2597 Optional<llvm::function_ref<void()>> CodeCompletionHandler = None);
2598 void ParseDirectDeclarator(Declarator &D);
2599 void ParseDecompositionDeclarator(Declarator &D);
2600 void ParseParenDeclarator(Declarator &D);
2601 void ParseFunctionDeclarator(Declarator &D,
2602 ParsedAttributes &attrs,
2603 BalancedDelimiterTracker &Tracker,
2605 bool RequiresArg = false);
2606 bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
2607 SourceLocation &RefQualifierLoc);
2608 bool isFunctionDeclaratorIdentifierList();
2609 void ParseFunctionDeclaratorIdentifierList(
2611 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
2612 void ParseParameterDeclarationClause(
2614 ParsedAttributes &attrs,
2615 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
2616 SourceLocation &EllipsisLoc);
2617 void ParseBracketDeclarator(Declarator &D);
2618 void ParseMisplacedBracketDeclarator(Declarator &D);
2620 //===--------------------------------------------------------------------===//
2621 // C++ 7: Declarations [dcl.dcl]
2623 /// The kind of attribute specifier we have found.
2624 enum CXX11AttributeKind {
2625 /// This is not an attribute specifier.
2626 CAK_NotAttributeSpecifier,
2627 /// This should be treated as an attribute-specifier.
2628 CAK_AttributeSpecifier,
2629 /// The next tokens are '[[', but this is not an attribute-specifier. This
2630 /// is ill-formed by C++11 [dcl.attr.grammar]p6.
2631 CAK_InvalidAttributeSpecifier
2634 isCXX11AttributeSpecifier(bool Disambiguate = false,
2635 bool OuterMightBeMessageSend = false);
2637 void DiagnoseUnexpectedNamespace(NamedDecl *Context);
2639 DeclGroupPtrTy ParseNamespace(DeclaratorContext Context,
2640 SourceLocation &DeclEnd,
2641 SourceLocation InlineLoc = SourceLocation());
2642 void ParseInnerNamespace(std::vector<SourceLocation> &IdentLoc,
2643 std::vector<IdentifierInfo *> &Ident,
2644 std::vector<SourceLocation> &NamespaceLoc,
2645 unsigned int index, SourceLocation &InlineLoc,
2646 ParsedAttributes &attrs,
2647 BalancedDelimiterTracker &Tracker);
2648 Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context);
2649 Decl *ParseExportDeclaration();
2650 DeclGroupPtrTy ParseUsingDirectiveOrDeclaration(
2651 DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
2652 SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs);
2653 Decl *ParseUsingDirective(DeclaratorContext Context,
2654 SourceLocation UsingLoc,
2655 SourceLocation &DeclEnd,
2656 ParsedAttributes &attrs);
2658 struct UsingDeclarator {
2659 SourceLocation TypenameLoc;
2662 SourceLocation EllipsisLoc;
2665 TypenameLoc = EllipsisLoc = SourceLocation();
2671 bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D);
2672 DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context,
2673 const ParsedTemplateInfo &TemplateInfo,
2674 SourceLocation UsingLoc,
2675 SourceLocation &DeclEnd,
2676 AccessSpecifier AS = AS_none);
2677 Decl *ParseAliasDeclarationAfterDeclarator(
2678 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
2679 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
2680 ParsedAttributes &Attrs, Decl **OwnedType = nullptr);
2682 Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
2683 Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
2684 SourceLocation AliasLoc, IdentifierInfo *Alias,
2685 SourceLocation &DeclEnd);
2687 //===--------------------------------------------------------------------===//
2688 // C++ 9: classes [class] and C structs/unions.
2689 bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
2690 void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
2691 DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo,
2692 AccessSpecifier AS, bool EnteringContext,
2693 DeclSpecContext DSC,
2694 ParsedAttributesWithRange &Attributes);
2695 void SkipCXXMemberSpecification(SourceLocation StartLoc,
2696 SourceLocation AttrFixitLoc,
2699 void ParseCXXMemberSpecification(SourceLocation StartLoc,
2700 SourceLocation AttrFixitLoc,
2701 ParsedAttributesWithRange &Attrs,
2704 ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2705 SourceLocation &EqualLoc);
2706 bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
2708 ExprResult &BitfieldSize,
2709 LateParsedAttrList &LateAttrs);
2710 void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D,
2711 VirtSpecifiers &VS);
2712 DeclGroupPtrTy ParseCXXClassMemberDeclaration(
2713 AccessSpecifier AS, ParsedAttributes &Attr,
2714 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2715 ParsingDeclRAIIObject *DiagsFromTParams = nullptr);
2716 DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas(
2717 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
2718 DeclSpec::TST TagType, Decl *Tag);
2719 void ParseConstructorInitializer(Decl *ConstructorDecl);
2720 MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
2721 void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2724 //===--------------------------------------------------------------------===//
2725 // C++ 10: Derived classes [class.derived]
2726 TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
2727 SourceLocation &EndLocation);
2728 void ParseBaseClause(Decl *ClassDecl);
2729 BaseResult ParseBaseSpecifier(Decl *ClassDecl);
2730 AccessSpecifier getAccessSpecifierIfPresent() const;
2732 bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
2733 SourceLocation TemplateKWLoc,
2734 IdentifierInfo *Name,
2735 SourceLocation NameLoc,
2736 bool EnteringContext,
2737 ParsedType ObjectType,
2739 bool AssumeTemplateId);
2740 bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2741 ParsedType ObjectType,
2742 UnqualifiedId &Result);
2744 //===--------------------------------------------------------------------===//
2745 // OpenMP: Directives and clauses.
2746 /// Parse clauses for '#pragma omp declare simd'.
2747 DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr,
2749 SourceLocation Loc);
2750 /// Parses declarative OpenMP directives.
2751 DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl(
2752 AccessSpecifier &AS, ParsedAttributesWithRange &Attrs,
2753 DeclSpec::TST TagType = DeclSpec::TST_unspecified,
2754 Decl *TagDecl = nullptr);
2755 /// Parse 'omp declare reduction' construct.
2756 DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS);
2757 /// Parses initializer for provided omp_priv declaration inside the reduction
2759 void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm);
2761 /// Parses simple list of variables.
2763 /// \param Kind Kind of the directive.
2764 /// \param Callback Callback function to be called for the list elements.
2765 /// \param AllowScopeSpecifier true, if the variables can have fully
2766 /// qualified names.
2768 bool ParseOpenMPSimpleVarList(
2769 OpenMPDirectiveKind Kind,
2770 const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
2772 bool AllowScopeSpecifier);
2773 /// Parses declarative or executable directive.
2775 /// \param Allowed ACK_Any, if any directives are allowed,
2776 /// ACK_StatementsOpenMPAnyExecutable - if any executable directives are
2777 /// allowed, ACK_StatementsOpenMPNonStandalone - if only non-standalone
2778 /// executable directives are allowed.
2781 ParseOpenMPDeclarativeOrExecutableDirective(AllowedConstructsKind Allowed);
2782 /// Parses clause of kind \a CKind for directive of a kind \a Kind.
2784 /// \param DKind Kind of current directive.
2785 /// \param CKind Kind of current clause.
2786 /// \param FirstClause true, if this is the first clause of a kind \a CKind
2787 /// in current directive.
2789 OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
2790 OpenMPClauseKind CKind, bool FirstClause);
2791 /// Parses clause with a single expression of a kind \a Kind.
2793 /// \param Kind Kind of current clause.
2794 /// \param ParseOnly true to skip the clause's semantic actions and return
2797 OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind,
2799 /// Parses simple clause of a kind \a Kind.
2801 /// \param Kind Kind of current clause.
2802 /// \param ParseOnly true to skip the clause's semantic actions and return
2805 OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly);
2806 /// Parses clause with a single expression and an additional argument
2807 /// of a kind \a Kind.
2809 /// \param Kind Kind of current clause.
2810 /// \param ParseOnly true to skip the clause's semantic actions and return
2813 OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind,
2815 /// Parses clause without any additional arguments.
2817 /// \param Kind Kind of current clause.
2818 /// \param ParseOnly true to skip the clause's semantic actions and return
2821 OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false);
2822 /// Parses clause with the list of variables of a kind \a Kind.
2824 /// \param Kind Kind of current clause.
2825 /// \param ParseOnly true to skip the clause's semantic actions and return
2828 OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
2829 OpenMPClauseKind Kind, bool ParseOnly);
2832 /// Parses simple expression in parens for single-expression clauses of OpenMP
2834 /// \param RLoc Returned location of right paren.
2835 ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc);
2837 /// Data used for parsing list of variables in OpenMP clauses.
2838 struct OpenMPVarListDataTy {
2839 Expr *TailExpr = nullptr;
2840 SourceLocation ColonLoc;
2841 SourceLocation RLoc;
2842 CXXScopeSpec ReductionIdScopeSpec;
2843 DeclarationNameInfo ReductionId;
2844 OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown;
2845 OpenMPLinearClauseKind LinKind = OMPC_LINEAR_val;
2846 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
2847 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
2848 bool IsMapTypeImplicit = false;
2849 SourceLocation DepLinMapLoc;
2852 /// Parses clauses with list.
2853 bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind,
2854 SmallVectorImpl<Expr *> &Vars,
2855 OpenMPVarListDataTy &Data);
2856 bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2857 bool AllowDestructorName,
2858 bool AllowConstructorName,
2859 bool AllowDeductionGuide,
2860 ParsedType ObjectType,
2861 SourceLocation *TemplateKWLoc,
2862 UnqualifiedId &Result);
2865 //===--------------------------------------------------------------------===//
2866 // C++ 14: Templates [temp]
2868 // C++ 14.1: Template Parameters [temp.param]
2869 Decl *ParseDeclarationStartingWithTemplate(DeclaratorContext Context,
2870 SourceLocation &DeclEnd,
2871 ParsedAttributes &AccessAttrs,
2872 AccessSpecifier AS = AS_none);
2873 Decl *ParseTemplateDeclarationOrSpecialization(DeclaratorContext Context,
2874 SourceLocation &DeclEnd,
2875 ParsedAttributes &AccessAttrs,
2876 AccessSpecifier AS);
2877 Decl *ParseSingleDeclarationAfterTemplate(
2878 DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
2879 ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd,
2880 ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none);
2881 bool ParseTemplateParameters(unsigned Depth,
2882 SmallVectorImpl<NamedDecl *> &TemplateParams,
2883 SourceLocation &LAngleLoc,
2884 SourceLocation &RAngleLoc);
2885 bool ParseTemplateParameterList(unsigned Depth,
2886 SmallVectorImpl<NamedDecl*> &TemplateParams);
2887 bool isStartOfTemplateTypeParameter();
2888 NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position);
2889 NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position);
2890 NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
2891 NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
2892 void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
2893 SourceLocation CorrectLoc,
2894 bool AlreadyHasEllipsis,
2895 bool IdentifierHasName);
2896 void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
2898 // C++ 14.3: Template arguments [temp.arg]
2899 typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
2901 bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
2902 bool ConsumeLastToken,
2903 bool ObjCGenericList);
2904 bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
2905 SourceLocation &LAngleLoc,
2906 TemplateArgList &TemplateArgs,
2907 SourceLocation &RAngleLoc);
2909 bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
2911 SourceLocation TemplateKWLoc,
2912 UnqualifiedId &TemplateName,
2913 bool AllowTypeAnnotation = true);
2914 void AnnotateTemplateIdTokenAsType(bool IsClassName = false);
2915 bool IsTemplateArgumentList(unsigned Skip = 0);
2916 bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
2917 ParsedTemplateArgument ParseTemplateTemplateArgument();
2918 ParsedTemplateArgument ParseTemplateArgument();
2919 Decl *ParseExplicitInstantiation(DeclaratorContext Context,
2920 SourceLocation ExternLoc,
2921 SourceLocation TemplateLoc,
2922 SourceLocation &DeclEnd,
2923 ParsedAttributes &AccessAttrs,
2924 AccessSpecifier AS = AS_none);
2926 //===--------------------------------------------------------------------===//
2928 DeclGroupPtrTy ParseModuleDecl();
2929 Decl *ParseModuleImport(SourceLocation AtLoc);
2930 bool parseMisplacedModuleImport();
2931 bool tryParseMisplacedModuleImport() {
2932 tok::TokenKind Kind = Tok.getKind();
2933 if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end ||
2934 Kind == tok::annot_module_include)
2935 return parseMisplacedModuleImport();
2939 bool ParseModuleName(
2940 SourceLocation UseLoc,
2941 SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
2944 //===--------------------------------------------------------------------===//
2945 // C++11/G++: Type Traits [Type-Traits.html in the GCC manual]
2946 ExprResult ParseTypeTrait();
2948 //===--------------------------------------------------------------------===//
2949 // Embarcadero: Arary and Expression Traits
2950 ExprResult ParseArrayTypeTrait();
2951 ExprResult ParseExpressionTrait();
2953 //===--------------------------------------------------------------------===//
2954 // Preprocessor code-completion pass-through
2955 void CodeCompleteDirective(bool InConditional) override;
2956 void CodeCompleteInConditionalExclusion() override;
2957 void CodeCompleteMacroName(bool IsDefinition) override;
2958 void CodeCompletePreprocessorExpression() override;
2959 void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo,
2960 unsigned ArgumentIndex) override;
2961 void CodeCompleteNaturalLanguage() override;
2964 } // end namespace clang