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 CompoundStmt, // Also allow '(' compound-statement ')'
1657 CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
1658 CastExpr // Also allow '(' type-name ')' <anything>
1660 ExprResult ParseParenExpression(ParenParseOption &ExprType,
1661 bool stopIfCastExpr,
1664 SourceLocation &RParenLoc);
1666 ExprResult ParseCXXAmbiguousParenExpression(
1667 ParenParseOption &ExprType, ParsedType &CastTy,
1668 BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt);
1669 ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
1670 SourceLocation LParenLoc,
1671 SourceLocation RParenLoc);
1673 ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
1675 ExprResult ParseGenericSelectionExpression();
1677 ExprResult ParseObjCBoolLiteral();
1679 ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T);
1681 //===--------------------------------------------------------------------===//
1683 ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
1684 Token &Replacement);
1685 ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
1687 bool areTokensAdjacent(const Token &A, const Token &B);
1689 void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
1690 bool EnteringContext, IdentifierInfo &II,
1693 bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
1694 ParsedType ObjectType,
1695 bool EnteringContext,
1696 bool *MayBePseudoDestructor = nullptr,
1697 bool IsTypename = false,
1698 IdentifierInfo **LastII = nullptr,
1699 bool OnlyNamespace = false);
1701 //===--------------------------------------------------------------------===//
1702 // C++0x 5.1.2: Lambda expressions
1704 // [...] () -> type {...}
1705 ExprResult ParseLambdaExpression();
1706 ExprResult TryParseLambdaExpression();
1707 Optional<unsigned> ParseLambdaIntroducer(LambdaIntroducer &Intro,
1708 bool *SkippedInits = nullptr);
1709 bool TryParseLambdaIntroducer(LambdaIntroducer &Intro);
1710 ExprResult ParseLambdaExpressionAfterIntroducer(
1711 LambdaIntroducer &Intro);
1713 //===--------------------------------------------------------------------===//
1714 // C++ 5.2p1: C++ Casts
1715 ExprResult ParseCXXCasts();
1717 //===--------------------------------------------------------------------===//
1718 // C++ 5.2p1: C++ Type Identification
1719 ExprResult ParseCXXTypeid();
1721 //===--------------------------------------------------------------------===//
1722 // C++ : Microsoft __uuidof Expression
1723 ExprResult ParseCXXUuidof();
1725 //===--------------------------------------------------------------------===//
1726 // C++ 5.2.4: C++ Pseudo-Destructor Expressions
1727 ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1728 tok::TokenKind OpKind,
1730 ParsedType ObjectType);
1732 //===--------------------------------------------------------------------===//
1733 // C++ 9.3.2: C++ 'this' pointer
1734 ExprResult ParseCXXThis();
1736 //===--------------------------------------------------------------------===//
1737 // C++ 15: C++ Throw Expression
1738 ExprResult ParseThrowExpression();
1740 ExceptionSpecificationType tryParseExceptionSpecification(
1742 SourceRange &SpecificationRange,
1743 SmallVectorImpl<ParsedType> &DynamicExceptions,
1744 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
1745 ExprResult &NoexceptExpr,
1746 CachedTokens *&ExceptionSpecTokens);
1748 // EndLoc is filled with the location of the last token of the specification.
1749 ExceptionSpecificationType ParseDynamicExceptionSpecification(
1750 SourceRange &SpecificationRange,
1751 SmallVectorImpl<ParsedType> &Exceptions,
1752 SmallVectorImpl<SourceRange> &Ranges);
1754 //===--------------------------------------------------------------------===//
1755 // C++0x 8: Function declaration trailing-return-type
1756 TypeResult ParseTrailingReturnType(SourceRange &Range,
1757 bool MayBeFollowedByDirectInit);
1759 //===--------------------------------------------------------------------===//
1760 // C++ 2.13.5: C++ Boolean Literals
1761 ExprResult ParseCXXBoolLiteral();
1763 //===--------------------------------------------------------------------===//
1764 // C++ 5.2.3: Explicit type conversion (functional notation)
1765 ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
1767 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1768 /// This should only be called when the current token is known to be part of
1769 /// simple-type-specifier.
1770 void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
1772 bool ParseCXXTypeSpecifierSeq(DeclSpec &DS);
1774 //===--------------------------------------------------------------------===//
1775 // C++ 5.3.4 and 5.3.5: C++ new and delete
1776 bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs,
1778 void ParseDirectNewDeclarator(Declarator &D);
1779 ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
1780 ExprResult ParseCXXDeleteExpression(bool UseGlobal,
1781 SourceLocation Start);
1783 //===--------------------------------------------------------------------===//
1784 // C++ if/switch/while condition expression.
1785 Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt,
1787 Sema::ConditionKind CK);
1789 //===--------------------------------------------------------------------===//
1792 ExprResult ParseCoyieldExpression();
1794 //===--------------------------------------------------------------------===//
1795 // C99 6.7.8: Initialization.
1797 /// ParseInitializer
1798 /// initializer: [C99 6.7.8]
1799 /// assignment-expression
1801 ExprResult ParseInitializer() {
1802 if (Tok.isNot(tok::l_brace))
1803 return ParseAssignmentExpression();
1804 return ParseBraceInitializer();
1806 bool MayBeDesignationStart();
1807 ExprResult ParseBraceInitializer();
1808 ExprResult ParseInitializerWithPotentialDesignator();
1810 //===--------------------------------------------------------------------===//
1811 // clang Expressions
1813 ExprResult ParseBlockLiteralExpression(); // ^{...}
1815 //===--------------------------------------------------------------------===//
1816 // Objective-C Expressions
1817 ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
1818 ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
1819 ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
1820 ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
1821 ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
1822 ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
1823 ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
1824 ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
1825 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
1826 ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
1827 ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
1828 bool isSimpleObjCMessageExpression();
1829 ExprResult ParseObjCMessageExpression();
1830 ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
1831 SourceLocation SuperLoc,
1832 ParsedType ReceiverType,
1833 Expr *ReceiverExpr);
1834 ExprResult ParseAssignmentExprWithObjCMessageExprStart(
1835 SourceLocation LBracloc, SourceLocation SuperLoc,
1836 ParsedType ReceiverType, Expr *ReceiverExpr);
1837 bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
1839 //===--------------------------------------------------------------------===//
1840 // C99 6.8: Statements and Blocks.
1842 /// A SmallVector of statements, with stack size 32 (as that is the only one
1844 typedef SmallVector<Stmt*, 32> StmtVector;
1845 /// A SmallVector of expressions, with stack size 12 (the maximum used.)
1846 typedef SmallVector<Expr*, 12> ExprVector;
1847 /// A SmallVector of types.
1848 typedef SmallVector<ParsedType, 12> TypeVector;
1850 StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
1851 bool AllowOpenMPStandalone = false);
1852 enum AllowedConstructsKind {
1853 /// Allow any declarations, statements, OpenMP directives.
1855 /// Allow only statements and non-standalone OpenMP directives.
1856 ACK_StatementsOpenMPNonStandalone,
1857 /// Allow statements and all executable OpenMP directives
1858 ACK_StatementsOpenMPAnyExecutable
1861 ParseStatementOrDeclaration(StmtVector &Stmts, AllowedConstructsKind Allowed,
1862 SourceLocation *TrailingElseLoc = nullptr);
1863 StmtResult ParseStatementOrDeclarationAfterAttributes(
1865 AllowedConstructsKind Allowed,
1866 SourceLocation *TrailingElseLoc,
1867 ParsedAttributesWithRange &Attrs);
1868 StmtResult ParseExprStatement();
1869 StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs);
1870 StmtResult ParseCaseStatement(bool MissingCase = false,
1871 ExprResult Expr = ExprResult());
1872 StmtResult ParseDefaultStatement();
1873 StmtResult ParseCompoundStatement(bool isStmtExpr = false);
1874 StmtResult ParseCompoundStatement(bool isStmtExpr,
1875 unsigned ScopeFlags);
1876 void ParseCompoundStatementLeadingPragmas();
1877 StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
1878 bool ParseParenExprOrCondition(StmtResult *InitStmt,
1879 Sema::ConditionResult &CondResult,
1881 Sema::ConditionKind CK);
1882 StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
1883 StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
1884 StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
1885 StmtResult ParseDoStatement();
1886 StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
1887 StmtResult ParseGotoStatement();
1888 StmtResult ParseContinueStatement();
1889 StmtResult ParseBreakStatement();
1890 StmtResult ParseReturnStatement();
1891 StmtResult ParseAsmStatement(bool &msAsm);
1892 StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
1893 StmtResult ParsePragmaLoopHint(StmtVector &Stmts,
1894 AllowedConstructsKind Allowed,
1895 SourceLocation *TrailingElseLoc,
1896 ParsedAttributesWithRange &Attrs);
1898 /// Describes the behavior that should be taken for an __if_exists
1900 enum IfExistsBehavior {
1901 /// Parse the block; this code is always used.
1903 /// Skip the block entirely; this code is never used.
1905 /// Parse the block as a dependent block, which may be used in
1906 /// some template instantiations but not others.
1910 /// Describes the condition of a Microsoft __if_exists or
1911 /// __if_not_exists block.
1912 struct IfExistsCondition {
1913 /// The location of the initial keyword.
1914 SourceLocation KeywordLoc;
1915 /// Whether this is an __if_exists block (rather than an
1916 /// __if_not_exists block).
1919 /// Nested-name-specifier preceding the name.
1922 /// The name we're looking for.
1925 /// The behavior of this __if_exists or __if_not_exists block
1927 IfExistsBehavior Behavior;
1930 bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
1931 void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
1932 void ParseMicrosoftIfExistsExternalDeclaration();
1933 void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
1934 ParsedAttributes &AccessAttrs,
1935 AccessSpecifier &CurAS);
1936 bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
1938 bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
1939 SmallVectorImpl<Expr *> &Constraints,
1940 SmallVectorImpl<Expr *> &Exprs);
1942 //===--------------------------------------------------------------------===//
1943 // C++ 6: Statements and Blocks
1945 StmtResult ParseCXXTryBlock();
1946 StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
1947 StmtResult ParseCXXCatchBlock(bool FnCatch = false);
1949 //===--------------------------------------------------------------------===//
1950 // MS: SEH Statements and Blocks
1952 StmtResult ParseSEHTryBlock();
1953 StmtResult ParseSEHExceptBlock(SourceLocation Loc);
1954 StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
1955 StmtResult ParseSEHLeaveStatement();
1957 //===--------------------------------------------------------------------===//
1958 // Objective-C Statements
1960 StmtResult ParseObjCAtStatement(SourceLocation atLoc);
1961 StmtResult ParseObjCTryStmt(SourceLocation atLoc);
1962 StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
1963 StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
1964 StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
1967 //===--------------------------------------------------------------------===//
1968 // C99 6.7: Declarations.
1970 /// A context for parsing declaration specifiers. TODO: flesh this
1971 /// out, there are other significant restrictions on specifiers than
1972 /// would be best implemented in the parser.
1973 enum class DeclSpecContext {
1974 DSC_normal, // normal context
1975 DSC_class, // class context, enables 'friend'
1976 DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
1977 DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
1978 DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration
1979 DSC_top_level, // top-level/namespace declaration context
1980 DSC_template_param, // template parameter context
1981 DSC_template_type_arg, // template type argument context
1982 DSC_objc_method_result, // ObjC method result context, enables 'instancetype'
1983 DSC_condition // condition declaration context
1986 /// Is this a context in which we are parsing just a type-specifier (or
1987 /// trailing-type-specifier)?
1988 static bool isTypeSpecifier(DeclSpecContext DSC) {
1990 case DeclSpecContext::DSC_normal:
1991 case DeclSpecContext::DSC_template_param:
1992 case DeclSpecContext::DSC_class:
1993 case DeclSpecContext::DSC_top_level:
1994 case DeclSpecContext::DSC_objc_method_result:
1995 case DeclSpecContext::DSC_condition:
1998 case DeclSpecContext::DSC_template_type_arg:
1999 case DeclSpecContext::DSC_type_specifier:
2000 case DeclSpecContext::DSC_trailing:
2001 case DeclSpecContext::DSC_alias_declaration:
2004 llvm_unreachable("Missing DeclSpecContext case");
2007 /// Is this a context in which we can perform class template argument
2009 static bool isClassTemplateDeductionContext(DeclSpecContext DSC) {
2011 case DeclSpecContext::DSC_normal:
2012 case DeclSpecContext::DSC_template_param:
2013 case DeclSpecContext::DSC_class:
2014 case DeclSpecContext::DSC_top_level:
2015 case DeclSpecContext::DSC_condition:
2016 case DeclSpecContext::DSC_type_specifier:
2019 case DeclSpecContext::DSC_objc_method_result:
2020 case DeclSpecContext::DSC_template_type_arg:
2021 case DeclSpecContext::DSC_trailing:
2022 case DeclSpecContext::DSC_alias_declaration:
2025 llvm_unreachable("Missing DeclSpecContext case");
2028 /// Information on a C++0x for-range-initializer found while parsing a
2029 /// declaration which turns out to be a for-range-declaration.
2030 struct ForRangeInit {
2031 SourceLocation ColonLoc;
2032 ExprResult RangeExpr;
2034 bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
2037 DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context,
2038 SourceLocation &DeclEnd,
2039 ParsedAttributesWithRange &attrs);
2040 DeclGroupPtrTy ParseSimpleDeclaration(DeclaratorContext Context,
2041 SourceLocation &DeclEnd,
2042 ParsedAttributesWithRange &attrs,
2044 ForRangeInit *FRI = nullptr);
2045 bool MightBeDeclarator(DeclaratorContext Context);
2046 DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context,
2047 SourceLocation *DeclEnd = nullptr,
2048 ForRangeInit *FRI = nullptr);
2049 Decl *ParseDeclarationAfterDeclarator(Declarator &D,
2050 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
2051 bool ParseAsmAttributesAfterDeclarator(Declarator &D);
2052 Decl *ParseDeclarationAfterDeclaratorAndAttributes(
2054 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2055 ForRangeInit *FRI = nullptr);
2056 Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
2057 Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
2059 /// When in code-completion, skip parsing of the function/method body
2060 /// unless the body contains the code-completion point.
2062 /// \returns true if the function body was skipped.
2063 bool trySkippingFunctionBody();
2065 bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2066 const ParsedTemplateInfo &TemplateInfo,
2067 AccessSpecifier AS, DeclSpecContext DSC,
2068 ParsedAttributesWithRange &Attrs);
2070 getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context);
2071 void ParseDeclarationSpecifiers(
2073 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2074 AccessSpecifier AS = AS_none,
2075 DeclSpecContext DSC = DeclSpecContext::DSC_normal,
2076 LateParsedAttrList *LateAttrs = nullptr);
2077 bool DiagnoseMissingSemiAfterTagDefinition(
2078 DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext,
2079 LateParsedAttrList *LateAttrs = nullptr);
2081 void ParseSpecifierQualifierList(
2082 DeclSpec &DS, AccessSpecifier AS = AS_none,
2083 DeclSpecContext DSC = DeclSpecContext::DSC_normal);
2085 void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
2086 DeclaratorContext Context);
2088 void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
2089 const ParsedTemplateInfo &TemplateInfo,
2090 AccessSpecifier AS, DeclSpecContext DSC);
2091 void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
2092 void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType,
2095 void ParseStructDeclaration(
2096 ParsingDeclSpec &DS,
2097 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback);
2099 bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
2100 bool isTypeSpecifierQualifier();
2102 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
2103 /// is definitely a type-specifier. Return false if it isn't part of a type
2104 /// specifier or if we're not sure.
2105 bool isKnownToBeTypeSpecifier(const Token &Tok) const;
2107 /// Return true if we know that we are definitely looking at a
2108 /// decl-specifier, and isn't part of an expression such as a function-style
2109 /// cast. Return false if it's no a decl-specifier, or we're not sure.
2110 bool isKnownToBeDeclarationSpecifier() {
2111 if (getLangOpts().CPlusPlus)
2112 return isCXXDeclarationSpecifier() == TPResult::True;
2113 return isDeclarationSpecifier(true);
2116 /// isDeclarationStatement - Disambiguates between a declaration or an
2117 /// expression statement, when parsing function bodies.
2118 /// Returns true for declaration, false for expression.
2119 bool isDeclarationStatement() {
2120 if (getLangOpts().CPlusPlus)
2121 return isCXXDeclarationStatement();
2122 return isDeclarationSpecifier(true);
2125 /// isForInitDeclaration - Disambiguates between a declaration or an
2126 /// expression in the context of the C 'clause-1' or the C++
2127 // 'for-init-statement' part of a 'for' statement.
2128 /// Returns true for declaration, false for expression.
2129 bool isForInitDeclaration() {
2130 if (getLangOpts().CPlusPlus)
2131 return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
2132 return isDeclarationSpecifier(true);
2135 /// Determine whether this is a C++1z for-range-identifier.
2136 bool isForRangeIdentifier();
2138 /// Determine whether we are currently at the start of an Objective-C
2139 /// class message that appears to be missing the open bracket '['.
2140 bool isStartOfObjCClassMessageMissingOpenBracket();
2142 /// Starting with a scope specifier, identifier, or
2143 /// template-id that refers to the current class, determine whether
2144 /// this is a constructor declarator.
2145 bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false);
2147 /// Specifies the context in which type-id/expression
2148 /// disambiguation will occur.
2149 enum TentativeCXXTypeIdContext {
2152 TypeIdAsTemplateArgument
2156 /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
2157 /// whether the parens contain an expression or a type-id.
2158 /// Returns true for a type-id and false for an expression.
2159 bool isTypeIdInParens(bool &isAmbiguous) {
2160 if (getLangOpts().CPlusPlus)
2161 return isCXXTypeId(TypeIdInParens, isAmbiguous);
2162 isAmbiguous = false;
2163 return isTypeSpecifierQualifier();
2165 bool isTypeIdInParens() {
2167 return isTypeIdInParens(isAmbiguous);
2170 /// Checks if the current tokens form type-id or expression.
2171 /// It is similar to isTypeIdInParens but does not suppose that type-id
2172 /// is in parenthesis.
2173 bool isTypeIdUnambiguously() {
2175 if (getLangOpts().CPlusPlus)
2176 return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous);
2177 return isTypeSpecifierQualifier();
2180 /// isCXXDeclarationStatement - C++-specialized function that disambiguates
2181 /// between a declaration or an expression statement, when parsing function
2182 /// bodies. Returns true for declaration, false for expression.
2183 bool isCXXDeclarationStatement();
2185 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
2186 /// between a simple-declaration or an expression-statement.
2187 /// If during the disambiguation process a parsing error is encountered,
2188 /// the function returns true to let the declaration parsing code handle it.
2189 /// Returns false if the statement is disambiguated as expression.
2190 bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
2192 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
2193 /// a constructor-style initializer, when parsing declaration statements.
2194 /// Returns true for function declarator and false for constructor-style
2195 /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
2196 /// might be a constructor-style initializer.
2197 /// If during the disambiguation process a parsing error is encountered,
2198 /// the function returns true to let the declaration parsing code handle it.
2199 bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr);
2201 struct ConditionDeclarationOrInitStatementState;
2202 enum class ConditionOrInitStatement {
2203 Expression, ///< Disambiguated as an expression (either kind).
2204 ConditionDecl, ///< Disambiguated as the declaration form of condition.
2205 InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement.
2206 Error ///< Can't be any of the above!
2208 /// Disambiguates between the different kinds of things that can happen
2209 /// after 'if (' or 'switch ('. This could be one of two different kinds of
2210 /// declaration (depending on whether there is a ';' later) or an expression.
2211 ConditionOrInitStatement
2212 isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt);
2214 bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
2215 bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
2217 return isCXXTypeId(Context, isAmbiguous);
2220 /// TPResult - Used as the result value for functions whose purpose is to
2221 /// disambiguate C++ constructs by "tentatively parsing" them.
2222 enum class TPResult {
2223 True, False, Ambiguous, Error
2226 /// Based only on the given token kind, determine whether we know that
2227 /// we're at the start of an expression or a type-specifier-seq (which may
2228 /// be an expression, in C++).
2230 /// This routine does not attempt to resolve any of the trick cases, e.g.,
2231 /// those involving lookup of identifiers.
2233 /// \returns \c TPR_true if this token starts an expression, \c TPR_false if
2234 /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot
2236 TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind);
2238 /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a
2239 /// declaration specifier, TPResult::False if it is not,
2240 /// TPResult::Ambiguous if it could be either a decl-specifier or a
2241 /// function-style cast, and TPResult::Error if a parsing error was
2242 /// encountered. If it could be a braced C++11 function-style cast, returns
2243 /// BracedCastResult.
2244 /// Doesn't consume tokens.
2246 isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False,
2247 bool *HasMissingTypename = nullptr);
2249 /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
2250 /// \c TPResult::Ambiguous, determine whether the decl-specifier would be
2251 /// a type-specifier other than a cv-qualifier.
2252 bool isCXXDeclarationSpecifierAType();
2254 /// Determine whether an identifier has been tentatively declared as a
2255 /// non-type. Such tentative declarations should not be found to name a type
2256 /// during a tentative parse, but also should not be annotated as a non-type.
2257 bool isTentativelyDeclared(IdentifierInfo *II);
2259 // "Tentative parsing" functions, used for disambiguation. If a parsing error
2260 // is encountered they will return TPResult::Error.
2261 // Returning TPResult::True/False indicates that the ambiguity was
2262 // resolved and tentative parsing may stop. TPResult::Ambiguous indicates
2263 // that more tentative parsing is necessary for disambiguation.
2264 // They all consume tokens, so backtracking should be used after calling them.
2266 TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
2267 TPResult TryParseTypeofSpecifier();
2268 TPResult TryParseProtocolQualifiers();
2269 TPResult TryParsePtrOperatorSeq();
2270 TPResult TryParseOperatorId();
2271 TPResult TryParseInitDeclaratorList();
2272 TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true,
2273 bool mayHaveDirectInit = false);
2275 TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr,
2276 bool VersusTemplateArg = false);
2277 TPResult TryParseFunctionDeclarator();
2278 TPResult TryParseBracketDeclarator();
2279 TPResult TryConsumeDeclarationSpecifier();
2282 TypeResult ParseTypeName(SourceRange *Range = nullptr,
2283 DeclaratorContext Context
2284 = DeclaratorContext::TypeNameContext,
2285 AccessSpecifier AS = AS_none,
2286 Decl **OwnedType = nullptr,
2287 ParsedAttributes *Attrs = nullptr);
2290 void ParseBlockId(SourceLocation CaretLoc);
2292 /// Are [[]] attributes enabled?
2293 bool standardAttributesAllowed() const {
2294 const LangOptions &LO = getLangOpts();
2295 return LO.DoubleSquareBracketAttributes;
2298 // Check for the start of an attribute-specifier-seq in a context where an
2299 // attribute is not allowed.
2300 bool CheckProhibitedCXX11Attribute() {
2301 assert(Tok.is(tok::l_square));
2302 if (!standardAttributesAllowed() || NextToken().isNot(tok::l_square))
2304 return DiagnoseProhibitedCXX11Attribute();
2307 bool DiagnoseProhibitedCXX11Attribute();
2308 void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2309 SourceLocation CorrectLocation) {
2310 if (!standardAttributesAllowed())
2312 if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
2313 Tok.isNot(tok::kw_alignas))
2315 DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
2317 void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2318 SourceLocation CorrectLocation);
2320 void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
2321 DeclSpec &DS, Sema::TagUseKind TUK);
2323 // FixItLoc = possible correct location for the attributes
2324 void ProhibitAttributes(ParsedAttributesWithRange &Attrs,
2325 SourceLocation FixItLoc = SourceLocation()) {
2326 if (Attrs.Range.isInvalid())
2328 DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc);
2332 void ProhibitAttributes(ParsedAttributesViewWithRange &Attrs,
2333 SourceLocation FixItLoc = SourceLocation()) {
2334 if (Attrs.Range.isInvalid())
2336 DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc);
2337 Attrs.clearListOnly();
2339 void DiagnoseProhibitedAttributes(const SourceRange &Range,
2340 SourceLocation FixItLoc);
2342 // Forbid C++11 and C2x attributes that appear on certain syntactic locations
2343 // which standard permits but we don't supported yet, for example, attributes
2344 // appertain to decl specifiers.
2345 void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
2348 /// Skip C++11 and C2x attributes and return the end location of the
2350 /// \returns SourceLocation() if there are no attributes.
2351 SourceLocation SkipCXX11Attributes();
2353 /// Diagnose and skip C++11 and C2x attributes that appear in syntactic
2354 /// locations where attributes are not allowed.
2355 void DiagnoseAndSkipCXX11Attributes();
2357 /// Parses syntax-generic attribute arguments for attributes which are
2358 /// known to the implementation, and adds them to the given ParsedAttributes
2359 /// list with the given attribute syntax. Returns the number of arguments
2360 /// parsed for the attribute.
2362 ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2363 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2364 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2365 ParsedAttr::Syntax Syntax);
2367 void MaybeParseGNUAttributes(Declarator &D,
2368 LateParsedAttrList *LateAttrs = nullptr) {
2369 if (Tok.is(tok::kw___attribute)) {
2370 ParsedAttributes attrs(AttrFactory);
2371 SourceLocation endLoc;
2372 ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D);
2373 D.takeAttributes(attrs, endLoc);
2376 void MaybeParseGNUAttributes(ParsedAttributes &attrs,
2377 SourceLocation *endLoc = nullptr,
2378 LateParsedAttrList *LateAttrs = nullptr) {
2379 if (Tok.is(tok::kw___attribute))
2380 ParseGNUAttributes(attrs, endLoc, LateAttrs);
2382 void ParseGNUAttributes(ParsedAttributes &attrs,
2383 SourceLocation *endLoc = nullptr,
2384 LateParsedAttrList *LateAttrs = nullptr,
2385 Declarator *D = nullptr);
2386 void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
2387 SourceLocation AttrNameLoc,
2388 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2389 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2390 ParsedAttr::Syntax Syntax, Declarator *D);
2391 IdentifierLoc *ParseIdentifierLoc();
2394 ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2395 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2396 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2397 ParsedAttr::Syntax Syntax);
2399 void MaybeParseCXX11Attributes(Declarator &D) {
2400 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
2401 ParsedAttributesWithRange attrs(AttrFactory);
2402 SourceLocation endLoc;
2403 ParseCXX11Attributes(attrs, &endLoc);
2404 D.takeAttributes(attrs, endLoc);
2407 void MaybeParseCXX11Attributes(ParsedAttributes &attrs,
2408 SourceLocation *endLoc = nullptr) {
2409 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
2410 ParsedAttributesWithRange attrsWithRange(AttrFactory);
2411 ParseCXX11Attributes(attrsWithRange, endLoc);
2412 attrs.takeAllFrom(attrsWithRange);
2415 void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2416 SourceLocation *endLoc = nullptr,
2417 bool OuterMightBeMessageSend = false) {
2418 if (standardAttributesAllowed() &&
2419 isCXX11AttributeSpecifier(false, OuterMightBeMessageSend))
2420 ParseCXX11Attributes(attrs, endLoc);
2423 void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
2424 SourceLocation *EndLoc = nullptr);
2425 void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2426 SourceLocation *EndLoc = nullptr);
2427 /// Parses a C++11 (or C2x)-style attribute argument list. Returns true
2428 /// if this results in adding an attribute to the ParsedAttributes list.
2429 bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
2430 SourceLocation AttrNameLoc,
2431 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2432 IdentifierInfo *ScopeName,
2433 SourceLocation ScopeLoc);
2435 IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc);
2437 void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
2438 SourceLocation *endLoc = nullptr) {
2439 if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
2440 ParseMicrosoftAttributes(attrs, endLoc);
2442 void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs);
2443 void ParseMicrosoftAttributes(ParsedAttributes &attrs,
2444 SourceLocation *endLoc = nullptr);
2445 void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2446 SourceLocation *End = nullptr) {
2447 const auto &LO = getLangOpts();
2448 if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec))
2449 ParseMicrosoftDeclSpecs(Attrs, End);
2451 void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2452 SourceLocation *End = nullptr);
2453 bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
2454 SourceLocation AttrNameLoc,
2455 ParsedAttributes &Attrs);
2456 void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
2457 void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2458 SourceLocation SkipExtendedMicrosoftTypeAttributes();
2459 void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
2460 void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
2461 void ParseOpenCLKernelAttributes(ParsedAttributes &attrs);
2462 void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
2463 /// Parses opencl_unroll_hint attribute if language is OpenCL v2.0
2465 /// \return false if error happens.
2466 bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
2467 if (getLangOpts().OpenCL)
2468 return ParseOpenCLUnrollHintAttribute(Attrs);
2471 /// Parses opencl_unroll_hint attribute.
2472 /// \return false if error happens.
2473 bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs);
2474 void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
2476 VersionTuple ParseVersionTuple(SourceRange &Range);
2477 void ParseAvailabilityAttribute(IdentifierInfo &Availability,
2478 SourceLocation AvailabilityLoc,
2479 ParsedAttributes &attrs,
2480 SourceLocation *endLoc,
2481 IdentifierInfo *ScopeName,
2482 SourceLocation ScopeLoc,
2483 ParsedAttr::Syntax Syntax);
2485 Optional<AvailabilitySpec> ParseAvailabilitySpec();
2486 ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc);
2488 void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol,
2490 ParsedAttributes &Attrs,
2491 SourceLocation *EndLoc,
2492 IdentifierInfo *ScopeName,
2493 SourceLocation ScopeLoc,
2494 ParsedAttr::Syntax Syntax);
2496 void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
2497 SourceLocation ObjCBridgeRelatedLoc,
2498 ParsedAttributes &attrs,
2499 SourceLocation *endLoc,
2500 IdentifierInfo *ScopeName,
2501 SourceLocation ScopeLoc,
2502 ParsedAttr::Syntax Syntax);
2504 void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
2505 SourceLocation AttrNameLoc,
2506 ParsedAttributes &Attrs,
2507 SourceLocation *EndLoc,
2508 IdentifierInfo *ScopeName,
2509 SourceLocation ScopeLoc,
2510 ParsedAttr::Syntax Syntax);
2513 ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
2514 SourceLocation AttrNameLoc, ParsedAttributes &Attrs,
2515 SourceLocation *EndLoc, IdentifierInfo *ScopeName,
2516 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax);
2518 void ParseTypeofSpecifier(DeclSpec &DS);
2519 SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
2520 void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
2521 SourceLocation StartLoc,
2522 SourceLocation EndLoc);
2523 void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
2524 void ParseAtomicSpecifier(DeclSpec &DS);
2526 ExprResult ParseAlignArgument(SourceLocation Start,
2527 SourceLocation &EllipsisLoc);
2528 void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2529 SourceLocation *endLoc = nullptr);
2531 VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
2532 VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
2533 return isCXX11VirtSpecifier(Tok);
2535 void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface,
2536 SourceLocation FriendLoc);
2538 bool isCXX11FinalKeyword() const;
2540 /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
2541 /// enter a new C++ declarator scope and exit it when the function is
2543 class DeclaratorScopeObj {
2549 DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
2550 : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
2552 void EnterDeclaratorScope() {
2553 assert(!EnteredScope && "Already entered the scope!");
2554 assert(SS.isSet() && "C++ scope was not set!");
2556 CreatedScope = true;
2557 P.EnterScope(0); // Not a decl scope.
2559 if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
2560 EnteredScope = true;
2563 ~DeclaratorScopeObj() {
2565 assert(SS.isSet() && "C++ scope was cleared ?");
2566 P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
2573 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
2574 void ParseDeclarator(Declarator &D);
2575 /// A function that parses a variant of direct-declarator.
2576 typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
2577 void ParseDeclaratorInternal(Declarator &D,
2578 DirectDeclParseFunction DirectDeclParser);
2580 enum AttrRequirements {
2581 AR_NoAttributesParsed = 0, ///< No attributes are diagnosed.
2582 AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes.
2583 AR_GNUAttributesParsed = 1 << 1,
2584 AR_CXX11AttributesParsed = 1 << 2,
2585 AR_DeclspecAttributesParsed = 1 << 3,
2586 AR_AllAttributesParsed = AR_GNUAttributesParsed |
2587 AR_CXX11AttributesParsed |
2588 AR_DeclspecAttributesParsed,
2589 AR_VendorAttributesParsed = AR_GNUAttributesParsed |
2590 AR_DeclspecAttributesParsed
2593 void ParseTypeQualifierListOpt(
2594 DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed,
2595 bool AtomicAllowed = true, bool IdentifierRequired = false,
2596 Optional<llvm::function_ref<void()>> CodeCompletionHandler = None);
2597 void ParseDirectDeclarator(Declarator &D);
2598 void ParseDecompositionDeclarator(Declarator &D);
2599 void ParseParenDeclarator(Declarator &D);
2600 void ParseFunctionDeclarator(Declarator &D,
2601 ParsedAttributes &attrs,
2602 BalancedDelimiterTracker &Tracker,
2604 bool RequiresArg = false);
2605 bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
2606 SourceLocation &RefQualifierLoc);
2607 bool isFunctionDeclaratorIdentifierList();
2608 void ParseFunctionDeclaratorIdentifierList(
2610 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
2611 void ParseParameterDeclarationClause(
2613 ParsedAttributes &attrs,
2614 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
2615 SourceLocation &EllipsisLoc);
2616 void ParseBracketDeclarator(Declarator &D);
2617 void ParseMisplacedBracketDeclarator(Declarator &D);
2619 //===--------------------------------------------------------------------===//
2620 // C++ 7: Declarations [dcl.dcl]
2622 /// The kind of attribute specifier we have found.
2623 enum CXX11AttributeKind {
2624 /// This is not an attribute specifier.
2625 CAK_NotAttributeSpecifier,
2626 /// This should be treated as an attribute-specifier.
2627 CAK_AttributeSpecifier,
2628 /// The next tokens are '[[', but this is not an attribute-specifier. This
2629 /// is ill-formed by C++11 [dcl.attr.grammar]p6.
2630 CAK_InvalidAttributeSpecifier
2633 isCXX11AttributeSpecifier(bool Disambiguate = false,
2634 bool OuterMightBeMessageSend = false);
2636 void DiagnoseUnexpectedNamespace(NamedDecl *Context);
2638 DeclGroupPtrTy ParseNamespace(DeclaratorContext Context,
2639 SourceLocation &DeclEnd,
2640 SourceLocation InlineLoc = SourceLocation());
2641 void ParseInnerNamespace(std::vector<SourceLocation> &IdentLoc,
2642 std::vector<IdentifierInfo *> &Ident,
2643 std::vector<SourceLocation> &NamespaceLoc,
2644 unsigned int index, SourceLocation &InlineLoc,
2645 ParsedAttributes &attrs,
2646 BalancedDelimiterTracker &Tracker);
2647 Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context);
2648 Decl *ParseExportDeclaration();
2649 DeclGroupPtrTy ParseUsingDirectiveOrDeclaration(
2650 DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
2651 SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs);
2652 Decl *ParseUsingDirective(DeclaratorContext Context,
2653 SourceLocation UsingLoc,
2654 SourceLocation &DeclEnd,
2655 ParsedAttributes &attrs);
2657 struct UsingDeclarator {
2658 SourceLocation TypenameLoc;
2661 SourceLocation EllipsisLoc;
2664 TypenameLoc = EllipsisLoc = SourceLocation();
2670 bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D);
2671 DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context,
2672 const ParsedTemplateInfo &TemplateInfo,
2673 SourceLocation UsingLoc,
2674 SourceLocation &DeclEnd,
2675 AccessSpecifier AS = AS_none);
2676 Decl *ParseAliasDeclarationAfterDeclarator(
2677 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
2678 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
2679 ParsedAttributes &Attrs, Decl **OwnedType = nullptr);
2681 Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
2682 Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
2683 SourceLocation AliasLoc, IdentifierInfo *Alias,
2684 SourceLocation &DeclEnd);
2686 //===--------------------------------------------------------------------===//
2687 // C++ 9: classes [class] and C structs/unions.
2688 bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
2689 void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
2690 DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo,
2691 AccessSpecifier AS, bool EnteringContext,
2692 DeclSpecContext DSC,
2693 ParsedAttributesWithRange &Attributes);
2694 void SkipCXXMemberSpecification(SourceLocation StartLoc,
2695 SourceLocation AttrFixitLoc,
2698 void ParseCXXMemberSpecification(SourceLocation StartLoc,
2699 SourceLocation AttrFixitLoc,
2700 ParsedAttributesWithRange &Attrs,
2703 ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2704 SourceLocation &EqualLoc);
2705 bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
2707 ExprResult &BitfieldSize,
2708 LateParsedAttrList &LateAttrs);
2709 void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D,
2710 VirtSpecifiers &VS);
2711 DeclGroupPtrTy ParseCXXClassMemberDeclaration(
2712 AccessSpecifier AS, ParsedAttributes &Attr,
2713 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2714 ParsingDeclRAIIObject *DiagsFromTParams = nullptr);
2715 DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas(
2716 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
2717 DeclSpec::TST TagType, Decl *Tag);
2718 void ParseConstructorInitializer(Decl *ConstructorDecl);
2719 MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
2720 void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2723 //===--------------------------------------------------------------------===//
2724 // C++ 10: Derived classes [class.derived]
2725 TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
2726 SourceLocation &EndLocation);
2727 void ParseBaseClause(Decl *ClassDecl);
2728 BaseResult ParseBaseSpecifier(Decl *ClassDecl);
2729 AccessSpecifier getAccessSpecifierIfPresent() const;
2731 bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
2732 SourceLocation TemplateKWLoc,
2733 IdentifierInfo *Name,
2734 SourceLocation NameLoc,
2735 bool EnteringContext,
2736 ParsedType ObjectType,
2738 bool AssumeTemplateId);
2739 bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2740 ParsedType ObjectType,
2741 UnqualifiedId &Result);
2743 //===--------------------------------------------------------------------===//
2744 // OpenMP: Directives and clauses.
2745 /// Parse clauses for '#pragma omp declare simd'.
2746 DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr,
2748 SourceLocation Loc);
2749 /// Parses declarative OpenMP directives.
2750 DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl(
2751 AccessSpecifier &AS, ParsedAttributesWithRange &Attrs,
2752 DeclSpec::TST TagType = DeclSpec::TST_unspecified,
2753 Decl *TagDecl = nullptr);
2754 /// Parse 'omp declare reduction' construct.
2755 DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS);
2756 /// Parses initializer for provided omp_priv declaration inside the reduction
2758 void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm);
2760 /// Parses simple list of variables.
2762 /// \param Kind Kind of the directive.
2763 /// \param Callback Callback function to be called for the list elements.
2764 /// \param AllowScopeSpecifier true, if the variables can have fully
2765 /// qualified names.
2767 bool ParseOpenMPSimpleVarList(
2768 OpenMPDirectiveKind Kind,
2769 const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
2771 bool AllowScopeSpecifier);
2772 /// Parses declarative or executable directive.
2774 /// \param Allowed ACK_Any, if any directives are allowed,
2775 /// ACK_StatementsOpenMPAnyExecutable - if any executable directives are
2776 /// allowed, ACK_StatementsOpenMPNonStandalone - if only non-standalone
2777 /// executable directives are allowed.
2780 ParseOpenMPDeclarativeOrExecutableDirective(AllowedConstructsKind Allowed);
2781 /// Parses clause of kind \a CKind for directive of a kind \a Kind.
2783 /// \param DKind Kind of current directive.
2784 /// \param CKind Kind of current clause.
2785 /// \param FirstClause true, if this is the first clause of a kind \a CKind
2786 /// in current directive.
2788 OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
2789 OpenMPClauseKind CKind, bool FirstClause);
2790 /// Parses clause with a single expression of a kind \a Kind.
2792 /// \param Kind Kind of current clause.
2793 /// \param ParseOnly true to skip the clause's semantic actions and return
2796 OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind,
2798 /// Parses simple clause of a kind \a Kind.
2800 /// \param Kind Kind of current clause.
2801 /// \param ParseOnly true to skip the clause's semantic actions and return
2804 OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly);
2805 /// Parses clause with a single expression and an additional argument
2806 /// of a kind \a Kind.
2808 /// \param Kind Kind of current clause.
2809 /// \param ParseOnly true to skip the clause's semantic actions and return
2812 OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind,
2814 /// Parses clause without any additional arguments.
2816 /// \param Kind Kind of current clause.
2817 /// \param ParseOnly true to skip the clause's semantic actions and return
2820 OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false);
2821 /// Parses clause with the list of variables of a kind \a Kind.
2823 /// \param Kind Kind of current clause.
2824 /// \param ParseOnly true to skip the clause's semantic actions and return
2827 OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
2828 OpenMPClauseKind Kind, bool ParseOnly);
2831 /// Parses simple expression in parens for single-expression clauses of OpenMP
2833 /// \param RLoc Returned location of right paren.
2834 ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc);
2836 /// Data used for parsing list of variables in OpenMP clauses.
2837 struct OpenMPVarListDataTy {
2838 Expr *TailExpr = nullptr;
2839 SourceLocation ColonLoc;
2840 SourceLocation RLoc;
2841 CXXScopeSpec ReductionIdScopeSpec;
2842 DeclarationNameInfo ReductionId;
2843 OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown;
2844 OpenMPLinearClauseKind LinKind = OMPC_LINEAR_val;
2845 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
2846 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
2847 bool IsMapTypeImplicit = false;
2848 SourceLocation DepLinMapLoc;
2851 /// Parses clauses with list.
2852 bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind,
2853 SmallVectorImpl<Expr *> &Vars,
2854 OpenMPVarListDataTy &Data);
2855 bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2856 bool AllowDestructorName,
2857 bool AllowConstructorName,
2858 bool AllowDeductionGuide,
2859 ParsedType ObjectType,
2860 SourceLocation *TemplateKWLoc,
2861 UnqualifiedId &Result);
2864 //===--------------------------------------------------------------------===//
2865 // C++ 14: Templates [temp]
2867 // C++ 14.1: Template Parameters [temp.param]
2868 Decl *ParseDeclarationStartingWithTemplate(DeclaratorContext Context,
2869 SourceLocation &DeclEnd,
2870 ParsedAttributes &AccessAttrs,
2871 AccessSpecifier AS = AS_none);
2872 Decl *ParseTemplateDeclarationOrSpecialization(DeclaratorContext Context,
2873 SourceLocation &DeclEnd,
2874 ParsedAttributes &AccessAttrs,
2875 AccessSpecifier AS);
2876 Decl *ParseSingleDeclarationAfterTemplate(
2877 DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
2878 ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd,
2879 ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none);
2880 bool ParseTemplateParameters(unsigned Depth,
2881 SmallVectorImpl<NamedDecl *> &TemplateParams,
2882 SourceLocation &LAngleLoc,
2883 SourceLocation &RAngleLoc);
2884 bool ParseTemplateParameterList(unsigned Depth,
2885 SmallVectorImpl<NamedDecl*> &TemplateParams);
2886 bool isStartOfTemplateTypeParameter();
2887 NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position);
2888 NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position);
2889 NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
2890 NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
2891 void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
2892 SourceLocation CorrectLoc,
2893 bool AlreadyHasEllipsis,
2894 bool IdentifierHasName);
2895 void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
2897 // C++ 14.3: Template arguments [temp.arg]
2898 typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
2900 bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
2901 bool ConsumeLastToken,
2902 bool ObjCGenericList);
2903 bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
2904 SourceLocation &LAngleLoc,
2905 TemplateArgList &TemplateArgs,
2906 SourceLocation &RAngleLoc);
2908 bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
2910 SourceLocation TemplateKWLoc,
2911 UnqualifiedId &TemplateName,
2912 bool AllowTypeAnnotation = true);
2913 void AnnotateTemplateIdTokenAsType(bool IsClassName = false);
2914 bool IsTemplateArgumentList(unsigned Skip = 0);
2915 bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
2916 ParsedTemplateArgument ParseTemplateTemplateArgument();
2917 ParsedTemplateArgument ParseTemplateArgument();
2918 Decl *ParseExplicitInstantiation(DeclaratorContext Context,
2919 SourceLocation ExternLoc,
2920 SourceLocation TemplateLoc,
2921 SourceLocation &DeclEnd,
2922 ParsedAttributes &AccessAttrs,
2923 AccessSpecifier AS = AS_none);
2925 //===--------------------------------------------------------------------===//
2927 DeclGroupPtrTy ParseModuleDecl();
2928 Decl *ParseModuleImport(SourceLocation AtLoc);
2929 bool parseMisplacedModuleImport();
2930 bool tryParseMisplacedModuleImport() {
2931 tok::TokenKind Kind = Tok.getKind();
2932 if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end ||
2933 Kind == tok::annot_module_include)
2934 return parseMisplacedModuleImport();
2938 bool ParseModuleName(
2939 SourceLocation UseLoc,
2940 SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
2943 //===--------------------------------------------------------------------===//
2944 // C++11/G++: Type Traits [Type-Traits.html in the GCC manual]
2945 ExprResult ParseTypeTrait();
2947 //===--------------------------------------------------------------------===//
2948 // Embarcadero: Arary and Expression Traits
2949 ExprResult ParseArrayTypeTrait();
2950 ExprResult ParseExpressionTrait();
2952 //===--------------------------------------------------------------------===//
2953 // Preprocessor code-completion pass-through
2954 void CodeCompleteDirective(bool InConditional) override;
2955 void CodeCompleteInConditionalExclusion() override;
2956 void CodeCompleteMacroName(bool IsDefinition) override;
2957 void CodeCompletePreprocessorExpression() override;
2958 void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo,
2959 unsigned ArgumentIndex) override;
2960 void CodeCompleteNaturalLanguage() override;
2963 } // end namespace clang