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/Basic/OpenMPKinds.h"
18 #include "clang/Basic/OperatorPrecedence.h"
19 #include "clang/Basic/Specifiers.h"
20 #include "clang/Lex/CodeCompletionHandler.h"
21 #include "clang/Lex/Preprocessor.h"
22 #include "clang/Sema/DeclSpec.h"
23 #include "clang/Sema/Sema.h"
24 #include "llvm/ADT/OwningPtr.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/PrettyStackTrace.h"
28 #include "llvm/Support/SaveAndRestore.h"
34 class BalancedDelimiterTracker;
35 class CorrectionCandidateCallback;
37 class DiagnosticBuilder;
39 class ParsingDeclRAIIObject;
40 class ParsingDeclSpec;
41 class ParsingDeclarator;
42 class ParsingFieldDeclarator;
43 class PragmaUnusedHandler;
44 class ColonProtectionRAIIObject;
45 class InMessageExpressionRAIIObject;
46 class PoisonSEHIdentifiersRAIIObject;
50 /// Parser - This implements a parser for the C family of languages. After
51 /// parsing units of the grammar, productions are invoked to handle whatever has
54 class Parser : public CodeCompletionHandler {
55 friend class PragmaUnusedHandler;
56 friend class ColonProtectionRAIIObject;
57 friend class InMessageExpressionRAIIObject;
58 friend class PoisonSEHIdentifiersRAIIObject;
59 friend class ObjCDeclContextSwitch;
60 friend class ParenBraceBracketBalancer;
61 friend class BalancedDelimiterTracker;
65 /// Tok - The current token we are peeking ahead. All parsing methods assume
66 /// that this is valid.
69 // PrevTokLocation - The location of the token we previously
70 // consumed. This token is used for diagnostics where we expected to
71 // see a token following another token (e.g., the ';' at the end of
73 SourceLocation PrevTokLocation;
75 unsigned short ParenCount, BracketCount, BraceCount;
77 /// Actions - These are the callbacks we invoke as we parse various constructs
81 DiagnosticsEngine &Diags;
83 /// ScopeCache - Cache scopes to reduce malloc traffic.
84 enum { ScopeCacheSize = 16 };
85 unsigned NumCachedScopes;
86 Scope *ScopeCache[ScopeCacheSize];
88 /// Identifiers used for SEH handling in Borland. These are only
89 /// allowed in particular circumstances
91 IdentifierInfo *Ident__exception_code,
92 *Ident___exception_code,
93 *Ident_GetExceptionCode;
94 // __except filter expression
95 IdentifierInfo *Ident__exception_info,
96 *Ident___exception_info,
97 *Ident_GetExceptionInfo;
99 IdentifierInfo *Ident__abnormal_termination,
100 *Ident___abnormal_termination,
101 *Ident_AbnormalTermination;
103 /// Contextual keywords for Microsoft extensions.
104 IdentifierInfo *Ident__except;
105 mutable IdentifierInfo *Ident_sealed;
107 /// Ident_super - IdentifierInfo for "super", to support fast
109 IdentifierInfo *Ident_super;
110 /// Ident_vector, Ident_pixel, Ident_bool - cached IdentifierInfo's
111 /// for "vector", "pixel", and "bool" fast comparison. Only present
112 /// if AltiVec enabled.
113 IdentifierInfo *Ident_vector;
114 IdentifierInfo *Ident_pixel;
115 IdentifierInfo *Ident_bool;
117 /// Objective-C contextual keywords.
118 mutable IdentifierInfo *Ident_instancetype;
120 /// \brief Identifier for "introduced".
121 IdentifierInfo *Ident_introduced;
123 /// \brief Identifier for "deprecated".
124 IdentifierInfo *Ident_deprecated;
126 /// \brief Identifier for "obsoleted".
127 IdentifierInfo *Ident_obsoleted;
129 /// \brief Identifier for "unavailable".
130 IdentifierInfo *Ident_unavailable;
132 /// \brief Identifier for "message".
133 IdentifierInfo *Ident_message;
135 /// C++0x contextual keywords.
136 mutable IdentifierInfo *Ident_final;
137 mutable IdentifierInfo *Ident_override;
139 // C++ type trait keywords that have can be reverted to identifiers and
140 // still used as type traits.
141 llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertableTypeTraits;
143 OwningPtr<PragmaHandler> AlignHandler;
144 OwningPtr<PragmaHandler> GCCVisibilityHandler;
145 OwningPtr<PragmaHandler> OptionsHandler;
146 OwningPtr<PragmaHandler> PackHandler;
147 OwningPtr<PragmaHandler> MSStructHandler;
148 OwningPtr<PragmaHandler> UnusedHandler;
149 OwningPtr<PragmaHandler> WeakHandler;
150 OwningPtr<PragmaHandler> RedefineExtnameHandler;
151 OwningPtr<PragmaHandler> FPContractHandler;
152 OwningPtr<PragmaHandler> OpenCLExtensionHandler;
153 OwningPtr<CommentHandler> CommentSemaHandler;
154 OwningPtr<PragmaHandler> OpenMPHandler;
155 OwningPtr<PragmaHandler> MSCommentHandler;
156 OwningPtr<PragmaHandler> MSDetectMismatchHandler;
158 /// Whether the '>' token acts as an operator or not. This will be
159 /// true except when we are parsing an expression within a C++
160 /// template argument list, where the '>' closes the template
162 bool GreaterThanIsOperator;
164 /// ColonIsSacred - When this is false, we aggressively try to recover from
165 /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not
166 /// safe in case statements and a few other things. This is managed by the
167 /// ColonProtectionRAIIObject RAII object.
170 /// \brief When true, we are directly inside an Objective-C messsage
173 /// This is managed by the \c InMessageExpressionRAIIObject class, and
174 /// should not be set directly.
175 bool InMessageExpression;
177 /// The "depth" of the template parameters currently being parsed.
178 unsigned TemplateParameterDepth;
180 /// \brief RAII class that manages the template parameter depth.
181 class TemplateParameterDepthRAII {
183 unsigned AddedLevels;
185 explicit TemplateParameterDepthRAII(unsigned &Depth)
186 : Depth(Depth), AddedLevels(0) {}
188 ~TemplateParameterDepthRAII() {
189 Depth -= AddedLevels;
196 unsigned getDepth() const { return Depth; }
199 /// Factory object for creating AttributeList objects.
200 AttributeFactory AttrFactory;
202 /// \brief Gathers and cleans up TemplateIdAnnotations when parsing of a
203 /// top-level declaration is finished.
204 SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
206 /// \brief Identifiers which have been declared within a tentative parse.
207 SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers;
209 IdentifierInfo *getSEHExceptKeyword();
211 /// True if we are within an Objective-C container while parsing C-like decls.
213 /// This is necessary because Sema thinks we have left the container
214 /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will
216 bool ParsingInObjCContainer;
218 bool SkipFunctionBodies;
221 Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
224 const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
225 const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
226 Preprocessor &getPreprocessor() const { return PP; }
227 Sema &getActions() const { return Actions; }
228 AttributeFactory &getAttrFactory() { return AttrFactory; }
230 const Token &getCurToken() const { return Tok; }
231 Scope *getCurScope() const { return Actions.getCurScope(); }
233 Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); }
235 // Type forwarding. All of these are statically 'void*', but they may all be
236 // different actual classes based on the actions in place.
237 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
238 typedef OpaquePtr<TemplateName> TemplateTy;
240 typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists;
242 typedef clang::ExprResult ExprResult;
243 typedef clang::StmtResult StmtResult;
244 typedef clang::BaseResult BaseResult;
245 typedef clang::MemInitResult MemInitResult;
246 typedef clang::TypeResult TypeResult;
248 typedef Expr *ExprArg;
249 typedef llvm::MutableArrayRef<Stmt*> MultiStmtArg;
250 typedef Sema::FullExprArg FullExprArg;
252 ExprResult ExprError() { return ExprResult(true); }
253 StmtResult StmtError() { return StmtResult(true); }
255 ExprResult ExprError(const DiagnosticBuilder &) { return ExprError(); }
256 StmtResult StmtError(const DiagnosticBuilder &) { return StmtError(); }
258 ExprResult ExprEmpty() { return ExprResult(false); }
262 /// Initialize - Warm up the parser.
266 /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if
267 /// the EOF was encountered.
268 bool ParseTopLevelDecl(DeclGroupPtrTy &Result);
270 /// ConsumeToken - Consume the current 'peek token' and lex the next one.
271 /// This does not work with all kinds of tokens: strings and specific other
272 /// tokens must be consumed with custom methods below. This returns the
273 /// location of the consumed token.
274 SourceLocation ConsumeToken(bool ConsumeCodeCompletionTok = false) {
275 assert(!isTokenStringLiteral() && !isTokenParen() && !isTokenBracket() &&
277 "Should consume special tokens with Consume*Token");
279 if (!ConsumeCodeCompletionTok && Tok.is(tok::code_completion))
280 return handleUnexpectedCodeCompletionToken();
282 PrevTokLocation = Tok.getLocation();
284 return PrevTokLocation;
288 //===--------------------------------------------------------------------===//
289 // Low-Level token peeking and consumption methods.
292 /// isTokenParen - Return true if the cur token is '(' or ')'.
293 bool isTokenParen() const {
294 return Tok.getKind() == tok::l_paren || Tok.getKind() == tok::r_paren;
296 /// isTokenBracket - Return true if the cur token is '[' or ']'.
297 bool isTokenBracket() const {
298 return Tok.getKind() == tok::l_square || Tok.getKind() == tok::r_square;
300 /// isTokenBrace - Return true if the cur token is '{' or '}'.
301 bool isTokenBrace() const {
302 return Tok.getKind() == tok::l_brace || Tok.getKind() == tok::r_brace;
305 /// isTokenStringLiteral - True if this token is a string-literal.
307 bool isTokenStringLiteral() const {
308 return tok::isStringLiteral(Tok.getKind());
311 /// \brief Returns true if the current token is '=' or is a type of '='.
312 /// For typos, give a fixit to '='
313 bool isTokenEqualOrEqualTypo();
315 /// ConsumeAnyToken - Dispatch to the right Consume* method based on the
316 /// current token type. This should only be used in cases where the type of
317 /// the token really isn't known, e.g. in error recovery.
318 SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) {
320 return ConsumeParen();
321 else if (isTokenBracket())
322 return ConsumeBracket();
323 else if (isTokenBrace())
324 return ConsumeBrace();
325 else if (isTokenStringLiteral())
326 return ConsumeStringToken();
328 return ConsumeToken(ConsumeCodeCompletionTok);
331 /// ConsumeParen - This consume method keeps the paren count up-to-date.
333 SourceLocation ConsumeParen() {
334 assert(isTokenParen() && "wrong consume method");
335 if (Tok.getKind() == tok::l_paren)
338 --ParenCount; // Don't let unbalanced )'s drive the count negative.
339 PrevTokLocation = Tok.getLocation();
341 return PrevTokLocation;
344 /// ConsumeBracket - This consume method keeps the bracket count up-to-date.
346 SourceLocation ConsumeBracket() {
347 assert(isTokenBracket() && "wrong consume method");
348 if (Tok.getKind() == tok::l_square)
350 else if (BracketCount)
351 --BracketCount; // Don't let unbalanced ]'s drive the count negative.
353 PrevTokLocation = Tok.getLocation();
355 return PrevTokLocation;
358 /// ConsumeBrace - This consume method keeps the brace count up-to-date.
360 SourceLocation ConsumeBrace() {
361 assert(isTokenBrace() && "wrong consume method");
362 if (Tok.getKind() == tok::l_brace)
365 --BraceCount; // Don't let unbalanced }'s drive the count negative.
367 PrevTokLocation = Tok.getLocation();
369 return PrevTokLocation;
372 /// ConsumeStringToken - Consume the current 'peek token', lexing a new one
373 /// and returning the token kind. This method is specific to strings, as it
374 /// handles string literal concatenation, as per C99 5.1.1.2, translation
376 SourceLocation ConsumeStringToken() {
377 assert(isTokenStringLiteral() &&
378 "Should only consume string literals with this method");
379 PrevTokLocation = Tok.getLocation();
381 return PrevTokLocation;
384 /// \brief Consume the current code-completion token.
386 /// This routine should be called to consume the code-completion token once
387 /// a code-completion action has already been invoked.
388 SourceLocation ConsumeCodeCompletionToken() {
389 assert(Tok.is(tok::code_completion));
390 PrevTokLocation = Tok.getLocation();
392 return PrevTokLocation;
395 ///\ brief When we are consuming a code-completion token without having
396 /// matched specific position in the grammar, provide code-completion results
397 /// based on context.
399 /// \returns the source location of the code-completion token.
400 SourceLocation handleUnexpectedCodeCompletionToken();
402 /// \brief Abruptly cut off parsing; mainly used when we have reached the
403 /// code-completion point.
404 void cutOffParsing() {
405 if (PP.isCodeCompletionEnabled())
406 PP.setCodeCompletionReached();
407 // Cut off parsing by acting as if we reached the end-of-file.
408 Tok.setKind(tok::eof);
411 /// \brief Handle the annotation token produced for #pragma unused(...)
412 void HandlePragmaUnused();
414 /// \brief Handle the annotation token produced for
415 /// #pragma GCC visibility...
416 void HandlePragmaVisibility();
418 /// \brief Handle the annotation token produced for
420 void HandlePragmaPack();
422 /// \brief Handle the annotation token produced for
423 /// #pragma ms_struct...
424 void HandlePragmaMSStruct();
426 /// \brief Handle the annotation token produced for
427 /// #pragma comment...
428 void HandlePragmaMSComment();
430 /// \brief Handle the annotation token produced for
432 void HandlePragmaAlign();
434 /// \brief Handle the annotation token produced for
435 /// #pragma weak id...
436 void HandlePragmaWeak();
438 /// \brief Handle the annotation token produced for
439 /// #pragma weak id = id...
440 void HandlePragmaWeakAlias();
442 /// \brief Handle the annotation token produced for
443 /// #pragma redefine_extname...
444 void HandlePragmaRedefineExtname();
446 /// \brief Handle the annotation token produced for
447 /// #pragma STDC FP_CONTRACT...
448 void HandlePragmaFPContract();
450 /// \brief Handle the annotation token produced for
451 /// #pragma OPENCL EXTENSION...
452 void HandlePragmaOpenCLExtension();
454 /// \brief Handle the annotation token produced for
455 /// #pragma clang __debug captured
456 StmtResult HandlePragmaCaptured();
458 /// GetLookAheadToken - This peeks ahead N tokens and returns that token
459 /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1)
460 /// returns the token after Tok, etc.
462 /// Note that this differs from the Preprocessor's LookAhead method, because
463 /// the Parser always has one token lexed that the preprocessor doesn't.
465 const Token &GetLookAheadToken(unsigned N) {
466 if (N == 0 || Tok.is(tok::eof)) return Tok;
467 return PP.LookAhead(N-1);
471 /// NextToken - This peeks ahead one token and returns it without
473 const Token &NextToken() {
474 return PP.LookAhead(0);
477 /// getTypeAnnotation - Read a parsed type out of an annotation token.
478 static ParsedType getTypeAnnotation(Token &Tok) {
479 return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
483 static void setTypeAnnotation(Token &Tok, ParsedType T) {
484 Tok.setAnnotationValue(T.getAsOpaquePtr());
487 /// \brief Read an already-translated primary expression out of an annotation
489 static ExprResult getExprAnnotation(Token &Tok) {
490 return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue());
493 /// \brief Set the primary expression corresponding to the given annotation
495 static void setExprAnnotation(Token &Tok, ExprResult ER) {
496 Tok.setAnnotationValue(ER.getAsOpaquePointer());
500 // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to
501 // find a type name by attempting typo correction.
502 bool TryAnnotateTypeOrScopeToken(bool EnteringContext = false,
503 bool NeedType = false);
504 bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext,
508 bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
511 enum AnnotatedNameKind {
512 /// Annotation has failed and emitted an error.
514 /// The identifier is a tentatively-declared name.
516 /// The identifier is a template name. FIXME: Add an annotation for that.
518 /// The identifier can't be resolved.
520 /// Annotation was successful.
523 AnnotatedNameKind TryAnnotateName(bool IsAddressOfOperand,
524 CorrectionCandidateCallback *CCC = 0);
526 /// Push a tok::annot_cxxscope token onto the token stream.
527 void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
529 /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
530 /// replacing them with the non-context-sensitive keywords. This returns
531 /// true if the token was replaced.
532 bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
533 const char *&PrevSpec, unsigned &DiagID,
535 if (!getLangOpts().AltiVec ||
536 (Tok.getIdentifierInfo() != Ident_vector &&
537 Tok.getIdentifierInfo() != Ident_pixel &&
538 Tok.getIdentifierInfo() != Ident_bool))
541 return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
544 /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
545 /// identifier token, replacing it with the non-context-sensitive __vector.
546 /// This returns true if the token was replaced.
547 bool TryAltiVecVectorToken() {
548 if (!getLangOpts().AltiVec ||
549 Tok.getIdentifierInfo() != Ident_vector) return false;
550 return TryAltiVecVectorTokenOutOfLine();
553 bool TryAltiVecVectorTokenOutOfLine();
554 bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
555 const char *&PrevSpec, unsigned &DiagID,
558 /// TryKeywordIdentFallback - For compatibility with system headers using
559 /// keywords as identifiers, attempt to convert the current token to an
560 /// identifier and optionally disable the keyword for the remainder of the
561 /// translation unit. This returns false if the token was not replaced,
562 /// otherwise emits a diagnostic and returns true.
563 bool TryKeywordIdentFallback(bool DisableKeyword);
565 /// \brief Get the TemplateIdAnnotation from the token.
566 TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
568 /// TentativeParsingAction - An object that is used as a kind of "tentative
569 /// parsing transaction". It gets instantiated to mark the token position and
570 /// after the token consumption is done, Commit() or Revert() is called to
571 /// either "commit the consumed tokens" or revert to the previously marked
572 /// token position. Example:
574 /// TentativeParsingAction TPA(*this);
579 class TentativeParsingAction {
582 size_t PrevTentativelyDeclaredIdentifierCount;
583 unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
587 explicit TentativeParsingAction(Parser& p) : P(p) {
589 PrevTentativelyDeclaredIdentifierCount =
590 P.TentativelyDeclaredIdentifiers.size();
591 PrevParenCount = P.ParenCount;
592 PrevBracketCount = P.BracketCount;
593 PrevBraceCount = P.BraceCount;
594 P.PP.EnableBacktrackAtThisPos();
598 assert(isActive && "Parsing action was finished!");
599 P.TentativelyDeclaredIdentifiers.resize(
600 PrevTentativelyDeclaredIdentifierCount);
601 P.PP.CommitBacktrackedTokens();
605 assert(isActive && "Parsing action was finished!");
608 P.TentativelyDeclaredIdentifiers.resize(
609 PrevTentativelyDeclaredIdentifierCount);
610 P.ParenCount = PrevParenCount;
611 P.BracketCount = PrevBracketCount;
612 P.BraceCount = PrevBraceCount;
615 ~TentativeParsingAction() {
616 assert(!isActive && "Forgot to call Commit or Revert!");
619 class UnannotatedTentativeParsingAction;
621 /// ObjCDeclContextSwitch - An object used to switch context from
622 /// an objective-c decl context to its enclosing decl context and
624 class ObjCDeclContextSwitch {
627 SaveAndRestore<bool> WithinObjCContainer;
629 explicit ObjCDeclContextSwitch(Parser &p)
630 : P(p), DC(p.getObjCDeclContext()),
631 WithinObjCContainer(P.ParsingInObjCContainer, DC != 0) {
633 P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC));
635 ~ObjCDeclContextSwitch() {
637 P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC));
641 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
642 /// input. If so, it is consumed and false is returned.
644 /// If the input is malformed, this emits the specified diagnostic. Next, if
645 /// SkipToTok is specified, it calls SkipUntil(SkipToTok). Finally, true is
647 bool ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned Diag,
648 const char *DiagMsg = "",
649 tok::TokenKind SkipToTok = tok::unknown);
651 /// \brief The parser expects a semicolon and, if present, will consume it.
653 /// If the next token is not a semicolon, this emits the specified diagnostic,
654 /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
655 /// to the semicolon, consumes that extra token.
656 bool ExpectAndConsumeSemi(unsigned DiagID);
658 /// \brief The kind of extra semi diagnostic to emit.
662 InstanceVariableList = 2,
663 AfterMemberFunctionDefinition = 3
666 /// \brief Consume any extra semi-colons until the end of the line.
667 void ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST = TST_unspecified);
670 //===--------------------------------------------------------------------===//
671 // Scope manipulation
673 /// ParseScope - Introduces a new scope for parsing. The kind of
674 /// scope is determined by ScopeFlags. Objects of this type should
675 /// be created on the stack to coincide with the position where the
676 /// parser enters the new scope, and this object's constructor will
677 /// create that new scope. Similarly, once the object is destroyed
678 /// the parser will exit the scope.
681 ParseScope(const ParseScope &) LLVM_DELETED_FUNCTION;
682 void operator=(const ParseScope &) LLVM_DELETED_FUNCTION;
685 // ParseScope - Construct a new object to manage a scope in the
686 // parser Self where the new Scope is created with the flags
687 // ScopeFlags, but only when ManageScope is true (the default). If
688 // ManageScope is false, this object does nothing.
689 ParseScope(Parser *Self, unsigned ScopeFlags, bool ManageScope = true)
692 Self->EnterScope(ScopeFlags);
697 // Exit - Exit the scope associated with this object now, rather
698 // than waiting until the object is destroyed.
711 /// EnterScope - Start a new scope.
712 void EnterScope(unsigned ScopeFlags);
714 /// ExitScope - Pop a scope off the scope stack.
718 /// \brief RAII object used to modify the scope flags for the current scope.
719 class ParseScopeFlags {
722 ParseScopeFlags(const ParseScopeFlags &) LLVM_DELETED_FUNCTION;
723 void operator=(const ParseScopeFlags &) LLVM_DELETED_FUNCTION;
726 ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
730 //===--------------------------------------------------------------------===//
731 // Diagnostic Emission and Error recovery.
734 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
735 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
736 DiagnosticBuilder Diag(unsigned DiagID) {
737 return Diag(Tok, DiagID);
741 void SuggestParentheses(SourceLocation Loc, unsigned DK,
742 SourceRange ParenRange);
743 void CheckNestedObjCContexts(SourceLocation AtLoc);
747 /// \brief Control flags for SkipUntil functions.
748 enum SkipUntilFlags {
749 StopAtSemi = 1 << 0, ///< Stop skipping at semicolon
750 /// \brief Stop skipping at specified token, but don't skip the token itself
751 StopBeforeMatch = 1 << 1,
752 StopAtCodeCompletion = 1 << 2 ///< Stop at code completion
755 friend LLVM_CONSTEXPR SkipUntilFlags operator|(SkipUntilFlags L,
757 return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) |
758 static_cast<unsigned>(R));
761 /// SkipUntil - Read tokens until we get to the specified token, then consume
762 /// it (unless StopBeforeMatch is specified). Because we cannot guarantee
763 /// that the token will ever occur, this skips to the next token, or to some
764 /// likely good stopping point. If Flags has StopAtSemi flag, skipping will
765 /// stop at a ';' character.
767 /// If SkipUntil finds the specified token, it returns true, otherwise it
769 bool SkipUntil(tok::TokenKind T,
770 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
771 return SkipUntil(llvm::makeArrayRef(T), Flags);
773 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2,
774 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
775 tok::TokenKind TokArray[] = {T1, T2};
776 return SkipUntil(TokArray, Flags);
778 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3,
779 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
780 tok::TokenKind TokArray[] = {T1, T2, T3};
781 return SkipUntil(TokArray, Flags);
783 bool SkipUntil(ArrayRef<tok::TokenKind> Toks,
784 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0));
786 /// SkipMalformedDecl - Read tokens until we get to some likely good stopping
787 /// point for skipping past a simple-declaration.
788 void SkipMalformedDecl();
791 //===--------------------------------------------------------------------===//
792 // Lexing and parsing of C++ inline methods.
796 /// [class.mem]p1: "... the class is regarded as complete within
797 /// - function bodies
798 /// - default arguments
799 /// - exception-specifications (TODO: C++0x)
800 /// - and brace-or-equal-initializers for non-static data members
801 /// (including such things in nested classes)."
802 /// LateParsedDeclarations build the tree of those elements so they can
803 /// be parsed after parsing the top-level class.
804 class LateParsedDeclaration {
806 virtual ~LateParsedDeclaration();
808 virtual void ParseLexedMethodDeclarations();
809 virtual void ParseLexedMemberInitializers();
810 virtual void ParseLexedMethodDefs();
811 virtual void ParseLexedAttributes();
814 /// Inner node of the LateParsedDeclaration tree that parses
815 /// all its members recursively.
816 class LateParsedClass : public LateParsedDeclaration {
818 LateParsedClass(Parser *P, ParsingClass *C);
819 virtual ~LateParsedClass();
821 virtual void ParseLexedMethodDeclarations();
822 virtual void ParseLexedMemberInitializers();
823 virtual void ParseLexedMethodDefs();
824 virtual void ParseLexedAttributes();
831 /// Contains the lexed tokens of an attribute with arguments that
832 /// may reference member variables and so need to be parsed at the
833 /// end of the class declaration after parsing all other member
834 /// member declarations.
835 /// FIXME: Perhaps we should change the name of LateParsedDeclaration to
836 /// LateParsedTokens.
837 struct LateParsedAttribute : public LateParsedDeclaration {
840 IdentifierInfo &AttrName;
841 SourceLocation AttrNameLoc;
842 SmallVector<Decl*, 2> Decls;
844 explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
846 : Self(P), AttrName(Name), AttrNameLoc(Loc) {}
848 virtual void ParseLexedAttributes();
850 void addDecl(Decl *D) { Decls.push_back(D); }
853 // A list of late-parsed attributes. Used by ParseGNUAttributes.
854 class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> {
856 LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { }
858 bool parseSoon() { return ParseSoon; }
861 bool ParseSoon; // Are we planning to parse these shortly after creation?
864 /// Contains the lexed tokens of a member function definition
865 /// which needs to be parsed at the end of the class declaration
866 /// after parsing all other member declarations.
867 struct LexedMethod : public LateParsedDeclaration {
872 /// \brief Whether this member function had an associated template
873 /// scope. When true, D is a template declaration.
874 /// otherwise, it is a member function declaration.
877 explicit LexedMethod(Parser* P, Decl *MD)
878 : Self(P), D(MD), TemplateScope(false) {}
880 virtual void ParseLexedMethodDefs();
883 /// LateParsedDefaultArgument - Keeps track of a parameter that may
884 /// have a default argument that cannot be parsed yet because it
885 /// occurs within a member function declaration inside the class
886 /// (C++ [class.mem]p2).
887 struct LateParsedDefaultArgument {
888 explicit LateParsedDefaultArgument(Decl *P,
889 CachedTokens *Toks = 0)
890 : Param(P), Toks(Toks) { }
892 /// Param - The parameter declaration for this parameter.
895 /// Toks - The sequence of tokens that comprises the default
896 /// argument expression, not including the '=' or the terminating
897 /// ')' or ','. This will be NULL for parameters that have no
898 /// default argument.
902 /// LateParsedMethodDeclaration - A method declaration inside a class that
903 /// contains at least one entity whose parsing needs to be delayed
904 /// until the class itself is completely-defined, such as a default
905 /// argument (C++ [class.mem]p2).
906 struct LateParsedMethodDeclaration : public LateParsedDeclaration {
907 explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
908 : Self(P), Method(M), TemplateScope(false), ExceptionSpecTokens(0) { }
910 virtual void ParseLexedMethodDeclarations();
914 /// Method - The method declaration.
917 /// \brief Whether this member function had an associated template
918 /// scope. When true, D is a template declaration.
919 /// othewise, it is a member function declaration.
922 /// DefaultArgs - Contains the parameters of the function and
923 /// their default arguments. At least one of the parameters will
924 /// have a default argument, but all of the parameters of the
925 /// method will be stored so that they can be reintroduced into
926 /// scope at the appropriate times.
927 SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
929 /// \brief The set of tokens that make up an exception-specification that
930 /// has not yet been parsed.
931 CachedTokens *ExceptionSpecTokens;
934 /// LateParsedMemberInitializer - An initializer for a non-static class data
935 /// member whose parsing must to be delayed until the class is completely
936 /// defined (C++11 [class.mem]p2).
937 struct LateParsedMemberInitializer : public LateParsedDeclaration {
938 LateParsedMemberInitializer(Parser *P, Decl *FD)
939 : Self(P), Field(FD) { }
941 virtual void ParseLexedMemberInitializers();
945 /// Field - The field declaration.
948 /// CachedTokens - The sequence of tokens that comprises the initializer,
949 /// including any leading '='.
953 /// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
954 /// C++ class, its method declarations that contain parts that won't be
955 /// parsed until after the definition is completed (C++ [class.mem]p2),
956 /// the method declarations and possibly attached inline definitions
957 /// will be stored here with the tokens that will be parsed to create those
959 typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer;
961 /// \brief Representation of a class that has been parsed, including
962 /// any member function declarations or definitions that need to be
963 /// parsed after the corresponding top-level class is complete.
964 struct ParsingClass {
965 ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface)
966 : TopLevelClass(TopLevelClass), TemplateScope(false),
967 IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) { }
969 /// \brief Whether this is a "top-level" class, meaning that it is
970 /// not nested within another class.
971 bool TopLevelClass : 1;
973 /// \brief Whether this class had an associated template
974 /// scope. When true, TagOrTemplate is a template declaration;
975 /// othewise, it is a tag declaration.
976 bool TemplateScope : 1;
978 /// \brief Whether this class is an __interface.
979 bool IsInterface : 1;
981 /// \brief The class or class template whose definition we are parsing.
984 /// LateParsedDeclarations - Method declarations, inline definitions and
985 /// nested classes that contain pieces whose parsing will be delayed until
986 /// the top-level class is fully defined.
987 LateParsedDeclarationsContainer LateParsedDeclarations;
990 /// \brief The stack of classes that is currently being
991 /// parsed. Nested and local classes will be pushed onto this stack
992 /// when they are parsed, and removed afterward.
993 std::stack<ParsingClass *> ClassStack;
995 ParsingClass &getCurrentClass() {
996 assert(!ClassStack.empty() && "No lexed method stacks!");
997 return *ClassStack.top();
1000 /// \brief RAII object used to manage the parsing of a class definition.
1001 class ParsingClassDefinition {
1004 Sema::ParsingClassState State;
1007 ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass,
1009 : P(P), Popped(false),
1010 State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
1013 /// \brief Pop this class of the stack.
1015 assert(!Popped && "Nested class has already been popped");
1017 P.PopParsingClass(State);
1020 ~ParsingClassDefinition() {
1022 P.PopParsingClass(State);
1026 /// \brief Contains information about any template-specific
1027 /// information that has been parsed prior to parsing declaration
1029 struct ParsedTemplateInfo {
1030 ParsedTemplateInfo()
1031 : Kind(NonTemplate), TemplateParams(0), TemplateLoc() { }
1033 ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
1034 bool isSpecialization,
1035 bool lastParameterListWasEmpty = false)
1036 : Kind(isSpecialization? ExplicitSpecialization : Template),
1037 TemplateParams(TemplateParams),
1038 LastParameterListWasEmpty(lastParameterListWasEmpty) { }
1040 explicit ParsedTemplateInfo(SourceLocation ExternLoc,
1041 SourceLocation TemplateLoc)
1042 : Kind(ExplicitInstantiation), TemplateParams(0),
1043 ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
1044 LastParameterListWasEmpty(false){ }
1046 /// \brief The kind of template we are parsing.
1048 /// \brief We are not parsing a template at all.
1050 /// \brief We are parsing a template declaration.
1052 /// \brief We are parsing an explicit specialization.
1053 ExplicitSpecialization,
1054 /// \brief We are parsing an explicit instantiation.
1055 ExplicitInstantiation
1058 /// \brief The template parameter lists, for template declarations
1059 /// and explicit specializations.
1060 TemplateParameterLists *TemplateParams;
1062 /// \brief The location of the 'extern' keyword, if any, for an explicit
1064 SourceLocation ExternLoc;
1066 /// \brief The location of the 'template' keyword, for an explicit
1068 SourceLocation TemplateLoc;
1070 /// \brief Whether the last template parameter list was empty.
1071 bool LastParameterListWasEmpty;
1073 SourceRange getSourceRange() const LLVM_READONLY;
1076 void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
1077 void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
1079 static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
1081 Sema::ParsingClassState
1082 PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface);
1083 void DeallocateParsedClasses(ParsingClass *Class);
1084 void PopParsingClass(Sema::ParsingClassState);
1086 enum CachedInitKind {
1087 CIK_DefaultArgument,
1088 CIK_DefaultInitializer
1091 NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS,
1092 AttributeList *AccessAttrs,
1093 ParsingDeclarator &D,
1094 const ParsedTemplateInfo &TemplateInfo,
1095 const VirtSpecifiers& VS,
1096 FunctionDefinitionKind DefinitionKind,
1098 void ParseCXXNonStaticMemberInitializer(Decl *VarD);
1099 void ParseLexedAttributes(ParsingClass &Class);
1100 void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1101 bool EnterScope, bool OnDefinition);
1102 void ParseLexedAttribute(LateParsedAttribute &LA,
1103 bool EnterScope, bool OnDefinition);
1104 void ParseLexedMethodDeclarations(ParsingClass &Class);
1105 void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
1106 void ParseLexedMethodDefs(ParsingClass &Class);
1107 void ParseLexedMethodDef(LexedMethod &LM);
1108 void ParseLexedMemberInitializers(ParsingClass &Class);
1109 void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
1110 void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod);
1111 bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
1112 bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK);
1113 bool ConsumeAndStoreConditional(CachedTokens &Toks);
1114 bool ConsumeAndStoreUntil(tok::TokenKind T1,
1116 bool StopAtSemi = true,
1117 bool ConsumeFinalToken = true) {
1118 return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
1120 bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
1122 bool StopAtSemi = true,
1123 bool ConsumeFinalToken = true);
1125 //===--------------------------------------------------------------------===//
1126 // C99 6.9: External Definitions.
1127 struct ParsedAttributesWithRange : ParsedAttributes {
1128 ParsedAttributesWithRange(AttributeFactory &factory)
1129 : ParsedAttributes(factory) {}
1134 DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
1135 ParsingDeclSpec *DS = 0);
1136 bool isDeclarationAfterDeclarator();
1137 bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
1138 DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(
1139 ParsedAttributesWithRange &attrs,
1140 ParsingDeclSpec *DS = 0,
1141 AccessSpecifier AS = AS_none);
1142 DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
1143 ParsingDeclSpec &DS,
1144 AccessSpecifier AS);
1146 Decl *ParseFunctionDefinition(ParsingDeclarator &D,
1147 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1148 LateParsedAttrList *LateParsedAttrs = 0);
1149 void ParseKNRParamDeclarations(Declarator &D);
1150 // EndLoc, if non-NULL, is filled with the location of the last token of
1152 ExprResult ParseSimpleAsm(SourceLocation *EndLoc = 0);
1153 ExprResult ParseAsmStringLiteral();
1155 // Objective-C External Declarations
1156 void MaybeSkipAttributes(tok::ObjCKeywordKind Kind);
1157 DeclGroupPtrTy ParseObjCAtDirectives();
1158 DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
1159 Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
1160 ParsedAttributes &prefixAttrs);
1161 void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
1162 BalancedDelimiterTracker &T,
1163 SmallVectorImpl<Decl *> &AllIvarDecls,
1164 bool RBraceMissing);
1165 void ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1166 tok::ObjCKeywordKind visibility,
1167 SourceLocation atLoc);
1168 bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P,
1169 SmallVectorImpl<SourceLocation> &PLocs,
1170 bool WarnOnDeclarations,
1171 SourceLocation &LAngleLoc,
1172 SourceLocation &EndProtoLoc);
1173 bool ParseObjCProtocolQualifiers(DeclSpec &DS);
1174 void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
1176 DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
1177 ParsedAttributes &prefixAttrs);
1179 struct ObjCImplParsingDataRAII {
1183 typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer;
1184 LateParsedObjCMethodContainer LateParsedObjCMethods;
1186 ObjCImplParsingDataRAII(Parser &parser, Decl *D)
1187 : P(parser), Dcl(D), HasCFunction(false) {
1188 P.CurParsedObjCImpl = this;
1191 ~ObjCImplParsingDataRAII();
1193 void finish(SourceRange AtEnd);
1194 bool isFinished() const { return Finished; }
1199 ObjCImplParsingDataRAII *CurParsedObjCImpl;
1200 void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl);
1202 DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc);
1203 DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
1204 Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
1205 Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
1206 Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
1208 IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
1209 // Definitions for Objective-c context sensitive keywords recognition.
1211 objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
1214 IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
1216 bool isTokIdentifier_in() const;
1218 ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, Declarator::TheContext Ctx,
1219 ParsedAttributes *ParamAttrs);
1220 void ParseObjCMethodRequirement();
1221 Decl *ParseObjCMethodPrototype(
1222 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1223 bool MethodDefinition = true);
1224 Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
1225 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1226 bool MethodDefinition=true);
1227 void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
1229 Decl *ParseObjCMethodDefinition();
1232 //===--------------------------------------------------------------------===//
1233 // C99 6.5: Expressions.
1235 /// TypeCastState - State whether an expression is or may be a type cast.
1236 enum TypeCastState {
1242 ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast);
1243 ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast);
1244 // Expr that doesn't include commas.
1245 ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast);
1247 ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1248 unsigned &NumLineToksConsumed,
1250 bool IsUnevaluated);
1253 ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
1255 ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
1257 ExprResult ParseRHSOfBinaryExpression(ExprResult LHS,
1258 prec::Level MinPrec);
1259 ExprResult ParseCastExpression(bool isUnaryExpression,
1260 bool isAddressOfOperand,
1262 TypeCastState isTypeCast);
1263 ExprResult ParseCastExpression(bool isUnaryExpression,
1264 bool isAddressOfOperand = false,
1265 TypeCastState isTypeCast = NotTypeCast);
1267 /// Returns true if the next token cannot start an expression.
1268 bool isNotExpressionStart();
1270 /// Returns true if the next token would start a postfix-expression
1272 bool isPostfixExpressionSuffixStart() {
1273 tok::TokenKind K = Tok.getKind();
1274 return (K == tok::l_square || K == tok::l_paren ||
1275 K == tok::period || K == tok::arrow ||
1276 K == tok::plusplus || K == tok::minusminus);
1279 ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
1280 ExprResult ParseUnaryExprOrTypeTraitExpression();
1281 ExprResult ParseBuiltinPrimaryExpression();
1283 ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1286 SourceRange &CastRange);
1288 typedef SmallVector<Expr*, 20> ExprListTy;
1289 typedef SmallVector<SourceLocation, 20> CommaLocsTy;
1291 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1292 bool ParseExpressionList(SmallVectorImpl<Expr*> &Exprs,
1293 SmallVectorImpl<SourceLocation> &CommaLocs,
1294 void (Sema::*Completer)(Scope *S,
1296 ArrayRef<Expr *> Args) = 0,
1299 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
1300 /// used for misc language extensions.
1301 bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
1302 SmallVectorImpl<SourceLocation> &CommaLocs);
1305 /// ParenParseOption - Control what ParseParenExpression will parse.
1306 enum ParenParseOption {
1307 SimpleExpr, // Only parse '(' expression ')'
1308 CompoundStmt, // Also allow '(' compound-statement ')'
1309 CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
1310 CastExpr // Also allow '(' type-name ')' <anything>
1312 ExprResult ParseParenExpression(ParenParseOption &ExprType,
1313 bool stopIfCastExpr,
1316 SourceLocation &RParenLoc);
1318 ExprResult ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
1320 BalancedDelimiterTracker &Tracker);
1321 ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
1322 SourceLocation LParenLoc,
1323 SourceLocation RParenLoc);
1325 ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
1327 ExprResult ParseGenericSelectionExpression();
1329 ExprResult ParseObjCBoolLiteral();
1331 //===--------------------------------------------------------------------===//
1333 ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
1335 bool areTokensAdjacent(const Token &A, const Token &B);
1337 void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
1338 bool EnteringContext, IdentifierInfo &II,
1341 bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
1342 ParsedType ObjectType,
1343 bool EnteringContext,
1344 bool *MayBePseudoDestructor = 0,
1345 bool IsTypename = false,
1346 IdentifierInfo **LastII = 0);
1348 void CheckForLParenAfterColonColon();
1350 //===--------------------------------------------------------------------===//
1351 // C++0x 5.1.2: Lambda expressions
1353 // [...] () -> type {...}
1354 ExprResult ParseLambdaExpression();
1355 ExprResult TryParseLambdaExpression();
1356 Optional<unsigned> ParseLambdaIntroducer(LambdaIntroducer &Intro,
1357 bool *SkippedInits = 0);
1358 bool TryParseLambdaIntroducer(LambdaIntroducer &Intro);
1359 ExprResult ParseLambdaExpressionAfterIntroducer(
1360 LambdaIntroducer &Intro);
1362 //===--------------------------------------------------------------------===//
1363 // C++ 5.2p1: C++ Casts
1364 ExprResult ParseCXXCasts();
1366 //===--------------------------------------------------------------------===//
1367 // C++ 5.2p1: C++ Type Identification
1368 ExprResult ParseCXXTypeid();
1370 //===--------------------------------------------------------------------===//
1371 // C++ : Microsoft __uuidof Expression
1372 ExprResult ParseCXXUuidof();
1374 //===--------------------------------------------------------------------===//
1375 // C++ 5.2.4: C++ Pseudo-Destructor Expressions
1376 ExprResult ParseCXXPseudoDestructor(ExprArg Base, SourceLocation OpLoc,
1377 tok::TokenKind OpKind,
1379 ParsedType ObjectType);
1381 //===--------------------------------------------------------------------===//
1382 // C++ 9.3.2: C++ 'this' pointer
1383 ExprResult ParseCXXThis();
1385 //===--------------------------------------------------------------------===//
1386 // C++ 15: C++ Throw Expression
1387 ExprResult ParseThrowExpression();
1389 ExceptionSpecificationType tryParseExceptionSpecification(
1390 SourceRange &SpecificationRange,
1391 SmallVectorImpl<ParsedType> &DynamicExceptions,
1392 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
1393 ExprResult &NoexceptExpr);
1395 // EndLoc is filled with the location of the last token of the specification.
1396 ExceptionSpecificationType ParseDynamicExceptionSpecification(
1397 SourceRange &SpecificationRange,
1398 SmallVectorImpl<ParsedType> &Exceptions,
1399 SmallVectorImpl<SourceRange> &Ranges);
1401 //===--------------------------------------------------------------------===//
1402 // C++0x 8: Function declaration trailing-return-type
1403 TypeResult ParseTrailingReturnType(SourceRange &Range);
1405 //===--------------------------------------------------------------------===//
1406 // C++ 2.13.5: C++ Boolean Literals
1407 ExprResult ParseCXXBoolLiteral();
1409 //===--------------------------------------------------------------------===//
1410 // C++ 5.2.3: Explicit type conversion (functional notation)
1411 ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
1413 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1414 /// This should only be called when the current token is known to be part of
1415 /// simple-type-specifier.
1416 void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
1418 bool ParseCXXTypeSpecifierSeq(DeclSpec &DS);
1420 //===--------------------------------------------------------------------===//
1421 // C++ 5.3.4 and 5.3.5: C++ new and delete
1422 bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs,
1424 void ParseDirectNewDeclarator(Declarator &D);
1425 ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
1426 ExprResult ParseCXXDeleteExpression(bool UseGlobal,
1427 SourceLocation Start);
1429 //===--------------------------------------------------------------------===//
1430 // C++ if/switch/while condition expression.
1431 bool ParseCXXCondition(ExprResult &ExprResult, Decl *&DeclResult,
1432 SourceLocation Loc, bool ConvertToBoolean);
1434 //===--------------------------------------------------------------------===//
1437 //===--------------------------------------------------------------------===//
1438 // C99 6.7.8: Initialization.
1440 /// ParseInitializer
1441 /// initializer: [C99 6.7.8]
1442 /// assignment-expression
1444 ExprResult ParseInitializer() {
1445 if (Tok.isNot(tok::l_brace))
1446 return ParseAssignmentExpression();
1447 return ParseBraceInitializer();
1449 bool MayBeDesignationStart();
1450 ExprResult ParseBraceInitializer();
1451 ExprResult ParseInitializerWithPotentialDesignator();
1453 //===--------------------------------------------------------------------===//
1454 // clang Expressions
1456 ExprResult ParseBlockLiteralExpression(); // ^{...}
1458 //===--------------------------------------------------------------------===//
1459 // Objective-C Expressions
1460 ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
1461 ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
1462 ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
1463 ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
1464 ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
1465 ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
1466 ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
1467 ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
1468 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
1469 ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
1470 ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
1471 bool isSimpleObjCMessageExpression();
1472 ExprResult ParseObjCMessageExpression();
1473 ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
1474 SourceLocation SuperLoc,
1475 ParsedType ReceiverType,
1476 ExprArg ReceiverExpr);
1477 ExprResult ParseAssignmentExprWithObjCMessageExprStart(
1478 SourceLocation LBracloc, SourceLocation SuperLoc,
1479 ParsedType ReceiverType, ExprArg ReceiverExpr);
1480 bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
1482 //===--------------------------------------------------------------------===//
1483 // C99 6.8: Statements and Blocks.
1485 /// A SmallVector of statements, with stack size 32 (as that is the only one
1487 typedef SmallVector<Stmt*, 32> StmtVector;
1488 /// A SmallVector of expressions, with stack size 12 (the maximum used.)
1489 typedef SmallVector<Expr*, 12> ExprVector;
1490 /// A SmallVector of types.
1491 typedef SmallVector<ParsedType, 12> TypeVector;
1493 StmtResult ParseStatement(SourceLocation *TrailingElseLoc = 0);
1494 StmtResult ParseStatementOrDeclaration(StmtVector &Stmts,
1496 SourceLocation *TrailingElseLoc = 0);
1497 StmtResult ParseStatementOrDeclarationAfterAttributes(
1500 SourceLocation *TrailingElseLoc,
1501 ParsedAttributesWithRange &Attrs);
1502 StmtResult ParseExprStatement();
1503 StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs);
1504 StmtResult ParseCaseStatement(bool MissingCase = false,
1505 ExprResult Expr = ExprResult());
1506 StmtResult ParseDefaultStatement();
1507 StmtResult ParseCompoundStatement(bool isStmtExpr = false);
1508 StmtResult ParseCompoundStatement(bool isStmtExpr,
1509 unsigned ScopeFlags);
1510 void ParseCompoundStatementLeadingPragmas();
1511 StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
1512 bool ParseParenExprOrCondition(ExprResult &ExprResult,
1515 bool ConvertToBoolean);
1516 StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
1517 StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
1518 StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
1519 StmtResult ParseDoStatement();
1520 StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
1521 StmtResult ParseGotoStatement();
1522 StmtResult ParseContinueStatement();
1523 StmtResult ParseBreakStatement();
1524 StmtResult ParseReturnStatement();
1525 StmtResult ParseAsmStatement(bool &msAsm);
1526 StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
1528 /// \brief Describes the behavior that should be taken for an __if_exists
1530 enum IfExistsBehavior {
1531 /// \brief Parse the block; this code is always used.
1533 /// \brief Skip the block entirely; this code is never used.
1535 /// \brief Parse the block as a dependent block, which may be used in
1536 /// some template instantiations but not others.
1540 /// \brief Describes the condition of a Microsoft __if_exists or
1541 /// __if_not_exists block.
1542 struct IfExistsCondition {
1543 /// \brief The location of the initial keyword.
1544 SourceLocation KeywordLoc;
1545 /// \brief Whether this is an __if_exists block (rather than an
1546 /// __if_not_exists block).
1549 /// \brief Nested-name-specifier preceding the name.
1552 /// \brief The name we're looking for.
1555 /// \brief The behavior of this __if_exists or __if_not_exists block
1557 IfExistsBehavior Behavior;
1560 bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
1561 void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
1562 void ParseMicrosoftIfExistsExternalDeclaration();
1563 void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
1564 AccessSpecifier& CurAS);
1565 bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
1567 bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
1568 SmallVectorImpl<Expr *> &Constraints,
1569 SmallVectorImpl<Expr *> &Exprs);
1571 //===--------------------------------------------------------------------===//
1572 // C++ 6: Statements and Blocks
1574 StmtResult ParseCXXTryBlock();
1575 StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
1576 StmtResult ParseCXXCatchBlock(bool FnCatch = false);
1578 //===--------------------------------------------------------------------===//
1579 // MS: SEH Statements and Blocks
1581 StmtResult ParseSEHTryBlock();
1582 StmtResult ParseSEHTryBlockCommon(SourceLocation Loc);
1583 StmtResult ParseSEHExceptBlock(SourceLocation Loc);
1584 StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
1586 //===--------------------------------------------------------------------===//
1587 // Objective-C Statements
1589 StmtResult ParseObjCAtStatement(SourceLocation atLoc);
1590 StmtResult ParseObjCTryStmt(SourceLocation atLoc);
1591 StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
1592 StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
1593 StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
1596 //===--------------------------------------------------------------------===//
1597 // C99 6.7: Declarations.
1599 /// A context for parsing declaration specifiers. TODO: flesh this
1600 /// out, there are other significant restrictions on specifiers than
1601 /// would be best implemented in the parser.
1602 enum DeclSpecContext {
1603 DSC_normal, // normal context
1604 DSC_class, // class context, enables 'friend'
1605 DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
1606 DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
1607 DSC_top_level // top-level/namespace declaration context
1610 /// Information on a C++0x for-range-initializer found while parsing a
1611 /// declaration which turns out to be a for-range-declaration.
1612 struct ForRangeInit {
1613 SourceLocation ColonLoc;
1614 ExprResult RangeExpr;
1616 bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
1619 DeclGroupPtrTy ParseDeclaration(StmtVector &Stmts,
1620 unsigned Context, SourceLocation &DeclEnd,
1621 ParsedAttributesWithRange &attrs);
1622 DeclGroupPtrTy ParseSimpleDeclaration(StmtVector &Stmts,
1624 SourceLocation &DeclEnd,
1625 ParsedAttributesWithRange &attrs,
1627 ForRangeInit *FRI = 0);
1628 bool MightBeDeclarator(unsigned Context);
1629 DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, unsigned Context,
1630 bool AllowFunctionDefinitions,
1631 SourceLocation *DeclEnd = 0,
1632 ForRangeInit *FRI = 0);
1633 Decl *ParseDeclarationAfterDeclarator(Declarator &D,
1634 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
1635 bool ParseAsmAttributesAfterDeclarator(Declarator &D);
1636 Decl *ParseDeclarationAfterDeclaratorAndAttributes(Declarator &D,
1637 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
1638 Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
1639 Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
1641 /// \brief When in code-completion, skip parsing of the function/method body
1642 /// unless the body contains the code-completion point.
1644 /// \returns true if the function body was skipped.
1645 bool trySkippingFunctionBody();
1647 bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
1648 const ParsedTemplateInfo &TemplateInfo,
1649 AccessSpecifier AS, DeclSpecContext DSC,
1650 ParsedAttributesWithRange &Attrs);
1651 DeclSpecContext getDeclSpecContextFromDeclaratorContext(unsigned Context);
1652 void ParseDeclarationSpecifiers(DeclSpec &DS,
1653 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1654 AccessSpecifier AS = AS_none,
1655 DeclSpecContext DSC = DSC_normal,
1656 LateParsedAttrList *LateAttrs = 0);
1657 bool DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
1658 DeclSpecContext DSContext,
1659 LateParsedAttrList *LateAttrs = 0);
1661 void ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS = AS_none,
1662 DeclSpecContext DSC = DSC_normal);
1664 void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
1665 Declarator::TheContext Context);
1667 void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
1668 const ParsedTemplateInfo &TemplateInfo,
1669 AccessSpecifier AS, DeclSpecContext DSC);
1670 void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
1671 void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType,
1674 struct FieldCallback {
1675 virtual void invoke(ParsingFieldDeclarator &Field) = 0;
1676 virtual ~FieldCallback() {}
1679 virtual void _anchor();
1681 struct ObjCPropertyCallback;
1683 void ParseStructDeclaration(ParsingDeclSpec &DS, FieldCallback &Callback);
1685 bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
1686 bool isTypeSpecifierQualifier();
1687 bool isTypeQualifier() const;
1689 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
1690 /// is definitely a type-specifier. Return false if it isn't part of a type
1691 /// specifier or if we're not sure.
1692 bool isKnownToBeTypeSpecifier(const Token &Tok) const;
1694 /// \brief Return true if we know that we are definitely looking at a
1695 /// decl-specifier, and isn't part of an expression such as a function-style
1696 /// cast. Return false if it's no a decl-specifier, or we're not sure.
1697 bool isKnownToBeDeclarationSpecifier() {
1698 if (getLangOpts().CPlusPlus)
1699 return isCXXDeclarationSpecifier() == TPResult::True();
1700 return isDeclarationSpecifier(true);
1703 /// isDeclarationStatement - Disambiguates between a declaration or an
1704 /// expression statement, when parsing function bodies.
1705 /// Returns true for declaration, false for expression.
1706 bool isDeclarationStatement() {
1707 if (getLangOpts().CPlusPlus)
1708 return isCXXDeclarationStatement();
1709 return isDeclarationSpecifier(true);
1712 /// isForInitDeclaration - Disambiguates between a declaration or an
1713 /// expression in the context of the C 'clause-1' or the C++
1714 // 'for-init-statement' part of a 'for' statement.
1715 /// Returns true for declaration, false for expression.
1716 bool isForInitDeclaration() {
1717 if (getLangOpts().CPlusPlus)
1718 return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
1719 return isDeclarationSpecifier(true);
1722 /// \brief Determine whether we are currently at the start of an Objective-C
1723 /// class message that appears to be missing the open bracket '['.
1724 bool isStartOfObjCClassMessageMissingOpenBracket();
1726 /// \brief Starting with a scope specifier, identifier, or
1727 /// template-id that refers to the current class, determine whether
1728 /// this is a constructor declarator.
1729 bool isConstructorDeclarator();
1731 /// \brief Specifies the context in which type-id/expression
1732 /// disambiguation will occur.
1733 enum TentativeCXXTypeIdContext {
1735 TypeIdAsTemplateArgument
1739 /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
1740 /// whether the parens contain an expression or a type-id.
1741 /// Returns true for a type-id and false for an expression.
1742 bool isTypeIdInParens(bool &isAmbiguous) {
1743 if (getLangOpts().CPlusPlus)
1744 return isCXXTypeId(TypeIdInParens, isAmbiguous);
1745 isAmbiguous = false;
1746 return isTypeSpecifierQualifier();
1748 bool isTypeIdInParens() {
1750 return isTypeIdInParens(isAmbiguous);
1753 /// isCXXDeclarationStatement - C++-specialized function that disambiguates
1754 /// between a declaration or an expression statement, when parsing function
1755 /// bodies. Returns true for declaration, false for expression.
1756 bool isCXXDeclarationStatement();
1758 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
1759 /// between a simple-declaration or an expression-statement.
1760 /// If during the disambiguation process a parsing error is encountered,
1761 /// the function returns true to let the declaration parsing code handle it.
1762 /// Returns false if the statement is disambiguated as expression.
1763 bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
1765 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
1766 /// a constructor-style initializer, when parsing declaration statements.
1767 /// Returns true for function declarator and false for constructor-style
1768 /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
1769 /// might be a constructor-style initializer.
1770 /// If during the disambiguation process a parsing error is encountered,
1771 /// the function returns true to let the declaration parsing code handle it.
1772 bool isCXXFunctionDeclarator(bool *IsAmbiguous = 0);
1774 /// isCXXConditionDeclaration - Disambiguates between a declaration or an
1775 /// expression for a condition of a if/switch/while/for statement.
1776 /// If during the disambiguation process a parsing error is encountered,
1777 /// the function returns true to let the declaration parsing code handle it.
1778 bool isCXXConditionDeclaration();
1780 bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
1781 bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
1783 return isCXXTypeId(Context, isAmbiguous);
1786 /// TPResult - Used as the result value for functions whose purpose is to
1787 /// disambiguate C++ constructs by "tentatively parsing" them.
1788 /// This is a class instead of a simple enum because the implicit enum-to-bool
1789 /// conversions may cause subtle bugs.
1798 TPResult(Result result) : Res(result) {}
1800 static TPResult True() { return TPR_true; }
1801 static TPResult False() { return TPR_false; }
1802 static TPResult Ambiguous() { return TPR_ambiguous; }
1803 static TPResult Error() { return TPR_error; }
1805 bool operator==(const TPResult &RHS) const { return Res == RHS.Res; }
1806 bool operator!=(const TPResult &RHS) const { return Res != RHS.Res; }
1809 /// \brief Based only on the given token kind, determine whether we know that
1810 /// we're at the start of an expression or a type-specifier-seq (which may
1811 /// be an expression, in C++).
1813 /// This routine does not attempt to resolve any of the trick cases, e.g.,
1814 /// those involving lookup of identifiers.
1816 /// \returns \c TPR_true if this token starts an expression, \c TPR_false if
1817 /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot
1819 TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind);
1821 /// isCXXDeclarationSpecifier - Returns TPResult::True() if it is a
1822 /// declaration specifier, TPResult::False() if it is not,
1823 /// TPResult::Ambiguous() if it could be either a decl-specifier or a
1824 /// function-style cast, and TPResult::Error() if a parsing error was
1825 /// encountered. If it could be a braced C++11 function-style cast, returns
1826 /// BracedCastResult.
1827 /// Doesn't consume tokens.
1829 isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False(),
1830 bool *HasMissingTypename = 0);
1832 /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
1833 /// \c TPResult::Ambiguous, determine whether the decl-specifier would be
1834 /// a type-specifier other than a cv-qualifier.
1835 bool isCXXDeclarationSpecifierAType();
1837 /// \brief Determine whether an identifier has been tentatively declared as a
1838 /// non-type. Such tentative declarations should not be found to name a type
1839 /// during a tentative parse, but also should not be annotated as a non-type.
1840 bool isTentativelyDeclared(IdentifierInfo *II);
1842 // "Tentative parsing" functions, used for disambiguation. If a parsing error
1843 // is encountered they will return TPResult::Error().
1844 // Returning TPResult::True()/False() indicates that the ambiguity was
1845 // resolved and tentative parsing may stop. TPResult::Ambiguous() indicates
1846 // that more tentative parsing is necessary for disambiguation.
1847 // They all consume tokens, so backtracking should be used after calling them.
1849 TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
1850 TPResult TryParseTypeofSpecifier();
1851 TPResult TryParseProtocolQualifiers();
1852 TPResult TryParsePtrOperatorSeq();
1853 TPResult TryParseOperatorId();
1854 TPResult TryParseInitDeclaratorList();
1855 TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier=true);
1856 TPResult TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = 0,
1857 bool VersusTemplateArg = false);
1858 TPResult TryParseFunctionDeclarator();
1859 TPResult TryParseBracketDeclarator();
1860 TPResult TryConsumeDeclarationSpecifier();
1863 TypeResult ParseTypeName(SourceRange *Range = 0,
1864 Declarator::TheContext Context
1865 = Declarator::TypeNameContext,
1866 AccessSpecifier AS = AS_none,
1867 Decl **OwnedType = 0,
1868 ParsedAttributes *Attrs = 0);
1871 void ParseBlockId(SourceLocation CaretLoc);
1873 // Check for the start of a C++11 attribute-specifier-seq in a context where
1874 // an attribute is not allowed.
1875 bool CheckProhibitedCXX11Attribute() {
1876 assert(Tok.is(tok::l_square));
1877 if (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))
1879 return DiagnoseProhibitedCXX11Attribute();
1881 bool DiagnoseProhibitedCXX11Attribute();
1882 void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1883 SourceLocation CorrectLocation) {
1884 if (!getLangOpts().CPlusPlus11)
1886 if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
1887 Tok.isNot(tok::kw_alignas))
1889 DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
1891 void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1892 SourceLocation CorrectLocation);
1894 void ProhibitAttributes(ParsedAttributesWithRange &attrs) {
1895 if (!attrs.Range.isValid()) return;
1896 DiagnoseProhibitedAttributes(attrs);
1899 void DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs);
1901 // Forbid C++11 attributes that appear on certain syntactic
1902 // locations which standard permits but we don't supported yet,
1903 // for example, attributes appertain to decl specifiers.
1904 void ProhibitCXX11Attributes(ParsedAttributesWithRange &attrs);
1906 /// \brief Diagnose and skip C++11 attributes that appear in syntactic
1907 /// locations where attributes are not allowed.
1908 void DiagnoseAndSkipCXX11Attributes();
1910 void MaybeParseGNUAttributes(Declarator &D,
1911 LateParsedAttrList *LateAttrs = 0) {
1912 if (Tok.is(tok::kw___attribute)) {
1913 ParsedAttributes attrs(AttrFactory);
1914 SourceLocation endLoc;
1915 ParseGNUAttributes(attrs, &endLoc, LateAttrs);
1916 D.takeAttributes(attrs, endLoc);
1919 void MaybeParseGNUAttributes(ParsedAttributes &attrs,
1920 SourceLocation *endLoc = 0,
1921 LateParsedAttrList *LateAttrs = 0) {
1922 if (Tok.is(tok::kw___attribute))
1923 ParseGNUAttributes(attrs, endLoc, LateAttrs);
1925 void ParseGNUAttributes(ParsedAttributes &attrs,
1926 SourceLocation *endLoc = 0,
1927 LateParsedAttrList *LateAttrs = 0);
1928 void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
1929 SourceLocation AttrNameLoc,
1930 ParsedAttributes &Attrs,
1931 SourceLocation *EndLoc,
1932 IdentifierInfo *ScopeName,
1933 SourceLocation ScopeLoc,
1934 AttributeList::Syntax Syntax);
1935 IdentifierLoc *ParseIdentifierLoc();
1937 void MaybeParseCXX11Attributes(Declarator &D) {
1938 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
1939 ParsedAttributesWithRange attrs(AttrFactory);
1940 SourceLocation endLoc;
1941 ParseCXX11Attributes(attrs, &endLoc);
1942 D.takeAttributes(attrs, endLoc);
1945 void MaybeParseCXX11Attributes(ParsedAttributes &attrs,
1946 SourceLocation *endLoc = 0) {
1947 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
1948 ParsedAttributesWithRange attrsWithRange(AttrFactory);
1949 ParseCXX11Attributes(attrsWithRange, endLoc);
1950 attrs.takeAllFrom(attrsWithRange);
1953 void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs,
1954 SourceLocation *endLoc = 0,
1955 bool OuterMightBeMessageSend = false) {
1956 if (getLangOpts().CPlusPlus11 &&
1957 isCXX11AttributeSpecifier(false, OuterMightBeMessageSend))
1958 ParseCXX11Attributes(attrs, endLoc);
1961 void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
1962 SourceLocation *EndLoc = 0);
1963 void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
1964 SourceLocation *EndLoc = 0);
1966 IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc);
1968 void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
1969 SourceLocation *endLoc = 0) {
1970 if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
1971 ParseMicrosoftAttributes(attrs, endLoc);
1973 void ParseMicrosoftAttributes(ParsedAttributes &attrs,
1974 SourceLocation *endLoc = 0);
1975 void ParseMicrosoftDeclSpec(ParsedAttributes &Attrs);
1976 bool IsSimpleMicrosoftDeclSpec(IdentifierInfo *Ident);
1977 void ParseComplexMicrosoftDeclSpec(IdentifierInfo *Ident,
1979 ParsedAttributes &Attrs);
1980 void ParseMicrosoftDeclSpecWithSingleArg(IdentifierInfo *AttrName,
1981 SourceLocation AttrNameLoc,
1982 ParsedAttributes &Attrs);
1983 void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
1984 void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
1985 void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
1986 void ParseOpenCLAttributes(ParsedAttributes &attrs);
1987 void ParseOpenCLQualifiers(DeclSpec &DS);
1989 VersionTuple ParseVersionTuple(SourceRange &Range);
1990 void ParseAvailabilityAttribute(IdentifierInfo &Availability,
1991 SourceLocation AvailabilityLoc,
1992 ParsedAttributes &attrs,
1993 SourceLocation *endLoc);
1995 bool IsThreadSafetyAttribute(StringRef AttrName);
1996 void ParseThreadSafetyAttribute(IdentifierInfo &AttrName,
1997 SourceLocation AttrNameLoc,
1998 ParsedAttributes &Attrs,
1999 SourceLocation *EndLoc);
2001 void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
2002 SourceLocation AttrNameLoc,
2003 ParsedAttributes &Attrs,
2004 SourceLocation *EndLoc);
2006 void ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
2007 SourceLocation AttrNameLoc,
2008 ParsedAttributes &Attrs,
2009 SourceLocation *EndLoc);
2011 void ParseTypeofSpecifier(DeclSpec &DS);
2012 SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
2013 void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
2014 SourceLocation StartLoc,
2015 SourceLocation EndLoc);
2016 void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
2017 void ParseAtomicSpecifier(DeclSpec &DS);
2019 ExprResult ParseAlignArgument(SourceLocation Start,
2020 SourceLocation &EllipsisLoc);
2021 void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2022 SourceLocation *endLoc = 0);
2024 VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
2025 VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
2026 return isCXX11VirtSpecifier(Tok);
2028 void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface);
2030 bool isCXX11FinalKeyword() const;
2032 /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
2033 /// enter a new C++ declarator scope and exit it when the function is
2035 class DeclaratorScopeObj {
2041 DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
2042 : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
2044 void EnterDeclaratorScope() {
2045 assert(!EnteredScope && "Already entered the scope!");
2046 assert(SS.isSet() && "C++ scope was not set!");
2048 CreatedScope = true;
2049 P.EnterScope(0); // Not a decl scope.
2051 if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
2052 EnteredScope = true;
2055 ~DeclaratorScopeObj() {
2057 assert(SS.isSet() && "C++ scope was cleared ?");
2058 P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
2065 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
2066 void ParseDeclarator(Declarator &D);
2067 /// A function that parses a variant of direct-declarator.
2068 typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
2069 void ParseDeclaratorInternal(Declarator &D,
2070 DirectDeclParseFunction DirectDeclParser);
2072 void ParseTypeQualifierListOpt(DeclSpec &DS, bool GNUAttributesAllowed = true,
2073 bool CXX11AttributesAllowed = true,
2074 bool AtomicAllowed = true,
2075 bool IdentifierRequired = false);
2076 void ParseDirectDeclarator(Declarator &D);
2077 void ParseParenDeclarator(Declarator &D);
2078 void ParseFunctionDeclarator(Declarator &D,
2079 ParsedAttributes &attrs,
2080 BalancedDelimiterTracker &Tracker,
2082 bool RequiresArg = false);
2083 bool isFunctionDeclaratorIdentifierList();
2084 void ParseFunctionDeclaratorIdentifierList(
2086 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
2087 void ParseParameterDeclarationClause(
2089 ParsedAttributes &attrs,
2090 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
2091 SourceLocation &EllipsisLoc);
2092 void ParseBracketDeclarator(Declarator &D);
2094 //===--------------------------------------------------------------------===//
2095 // C++ 7: Declarations [dcl.dcl]
2097 /// The kind of attribute specifier we have found.
2098 enum CXX11AttributeKind {
2099 /// This is not an attribute specifier.
2100 CAK_NotAttributeSpecifier,
2101 /// This should be treated as an attribute-specifier.
2102 CAK_AttributeSpecifier,
2103 /// The next tokens are '[[', but this is not an attribute-specifier. This
2104 /// is ill-formed by C++11 [dcl.attr.grammar]p6.
2105 CAK_InvalidAttributeSpecifier
2108 isCXX11AttributeSpecifier(bool Disambiguate = false,
2109 bool OuterMightBeMessageSend = false);
2111 void DiagnoseUnexpectedNamespace(NamedDecl *Context);
2113 Decl *ParseNamespace(unsigned Context, SourceLocation &DeclEnd,
2114 SourceLocation InlineLoc = SourceLocation());
2115 void ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc,
2116 std::vector<IdentifierInfo*>& Ident,
2117 std::vector<SourceLocation>& NamespaceLoc,
2118 unsigned int index, SourceLocation& InlineLoc,
2119 ParsedAttributes& attrs,
2120 BalancedDelimiterTracker &Tracker);
2121 Decl *ParseLinkage(ParsingDeclSpec &DS, unsigned Context);
2122 Decl *ParseUsingDirectiveOrDeclaration(unsigned Context,
2123 const ParsedTemplateInfo &TemplateInfo,
2124 SourceLocation &DeclEnd,
2125 ParsedAttributesWithRange &attrs,
2126 Decl **OwnedType = 0);
2127 Decl *ParseUsingDirective(unsigned Context,
2128 SourceLocation UsingLoc,
2129 SourceLocation &DeclEnd,
2130 ParsedAttributes &attrs);
2131 Decl *ParseUsingDeclaration(unsigned Context,
2132 const ParsedTemplateInfo &TemplateInfo,
2133 SourceLocation UsingLoc,
2134 SourceLocation &DeclEnd,
2135 AccessSpecifier AS = AS_none,
2136 Decl **OwnedType = 0);
2137 Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
2138 Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
2139 SourceLocation AliasLoc, IdentifierInfo *Alias,
2140 SourceLocation &DeclEnd);
2142 //===--------------------------------------------------------------------===//
2143 // C++ 9: classes [class] and C structs/unions.
2144 bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
2145 void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
2146 DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo,
2147 AccessSpecifier AS, bool EnteringContext,
2148 DeclSpecContext DSC,
2149 ParsedAttributesWithRange &Attributes);
2150 void ParseCXXMemberSpecification(SourceLocation StartLoc,
2151 SourceLocation AttrFixitLoc,
2152 ParsedAttributesWithRange &Attrs,
2155 ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2156 SourceLocation &EqualLoc);
2157 void ParseCXXClassMemberDeclaration(AccessSpecifier AS, AttributeList *Attr,
2158 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2159 ParsingDeclRAIIObject *DiagsFromTParams = 0);
2160 void ParseConstructorInitializer(Decl *ConstructorDecl);
2161 MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
2162 void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2165 //===--------------------------------------------------------------------===//
2166 // C++ 10: Derived classes [class.derived]
2167 TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
2168 SourceLocation &EndLocation);
2169 void ParseBaseClause(Decl *ClassDecl);
2170 BaseResult ParseBaseSpecifier(Decl *ClassDecl);
2171 AccessSpecifier getAccessSpecifierIfPresent() const;
2173 bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
2174 SourceLocation TemplateKWLoc,
2175 IdentifierInfo *Name,
2176 SourceLocation NameLoc,
2177 bool EnteringContext,
2178 ParsedType ObjectType,
2180 bool AssumeTemplateId);
2181 bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2182 ParsedType ObjectType,
2183 UnqualifiedId &Result);
2185 //===--------------------------------------------------------------------===//
2186 // OpenMP: Directives and clauses.
2187 /// \brief Parses declarative OpenMP directives.
2188 DeclGroupPtrTy ParseOpenMPDeclarativeDirective();
2189 /// \brief Parses simple list of variables.
2191 /// \param Kind Kind of the directive.
2192 /// \param [out] VarList List of referenced variables.
2193 /// \param AllowScopeSpecifier true, if the variables can have fully
2194 /// qualified names.
2196 bool ParseOpenMPSimpleVarList(OpenMPDirectiveKind Kind,
2197 SmallVectorImpl<Expr *> &VarList,
2198 bool AllowScopeSpecifier);
2199 /// \brief Parses declarative or executable directive.
2200 StmtResult ParseOpenMPDeclarativeOrExecutableDirective();
2201 /// \brief Parses clause of kind \a CKind for directive of a kind \a Kind.
2203 /// \param DKind Kind of current directive.
2204 /// \param CKind Kind of current clause.
2205 /// \param FirstClause true, if this is the first clause of a kind \a CKind
2206 /// in current directive.
2208 OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
2209 OpenMPClauseKind CKind, bool FirstClause);
2210 /// \brief Parses clause with a single expression of a kind \a Kind.
2212 /// \param Kind Kind of current clause.
2214 OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind);
2215 /// \brief Parses simple clause of a kind \a Kind.
2217 /// \param Kind Kind of current clause.
2219 OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind);
2220 /// \brief Parses clause with the list of variables of a kind \a Kind.
2222 /// \param Kind Kind of current clause.
2224 OMPClause *ParseOpenMPVarListClause(OpenMPClauseKind Kind);
2226 bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2227 bool AllowDestructorName,
2228 bool AllowConstructorName,
2229 ParsedType ObjectType,
2230 SourceLocation& TemplateKWLoc,
2231 UnqualifiedId &Result);
2234 //===--------------------------------------------------------------------===//
2235 // C++ 14: Templates [temp]
2237 // C++ 14.1: Template Parameters [temp.param]
2238 Decl *ParseDeclarationStartingWithTemplate(unsigned Context,
2239 SourceLocation &DeclEnd,
2240 AccessSpecifier AS = AS_none,
2241 AttributeList *AccessAttrs = 0);
2242 Decl *ParseTemplateDeclarationOrSpecialization(unsigned Context,
2243 SourceLocation &DeclEnd,
2245 AttributeList *AccessAttrs);
2246 Decl *ParseSingleDeclarationAfterTemplate(
2248 const ParsedTemplateInfo &TemplateInfo,
2249 ParsingDeclRAIIObject &DiagsFromParams,
2250 SourceLocation &DeclEnd,
2251 AccessSpecifier AS=AS_none,
2252 AttributeList *AccessAttrs = 0);
2253 bool ParseTemplateParameters(unsigned Depth,
2254 SmallVectorImpl<Decl*> &TemplateParams,
2255 SourceLocation &LAngleLoc,
2256 SourceLocation &RAngleLoc);
2257 bool ParseTemplateParameterList(unsigned Depth,
2258 SmallVectorImpl<Decl*> &TemplateParams);
2259 bool isStartOfTemplateTypeParameter();
2260 Decl *ParseTemplateParameter(unsigned Depth, unsigned Position);
2261 Decl *ParseTypeParameter(unsigned Depth, unsigned Position);
2262 Decl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
2263 Decl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
2264 // C++ 14.3: Template arguments [temp.arg]
2265 typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
2267 bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
2268 bool ConsumeLastToken);
2269 bool ParseTemplateIdAfterTemplateName(TemplateTy Template,
2270 SourceLocation TemplateNameLoc,
2271 const CXXScopeSpec &SS,
2272 bool ConsumeLastToken,
2273 SourceLocation &LAngleLoc,
2274 TemplateArgList &TemplateArgs,
2275 SourceLocation &RAngleLoc);
2277 bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
2279 SourceLocation TemplateKWLoc,
2280 UnqualifiedId &TemplateName,
2281 bool AllowTypeAnnotation = true);
2282 void AnnotateTemplateIdTokenAsType();
2283 bool IsTemplateArgumentList(unsigned Skip = 0);
2284 bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
2285 ParsedTemplateArgument ParseTemplateTemplateArgument();
2286 ParsedTemplateArgument ParseTemplateArgument();
2287 Decl *ParseExplicitInstantiation(unsigned Context,
2288 SourceLocation ExternLoc,
2289 SourceLocation TemplateLoc,
2290 SourceLocation &DeclEnd,
2291 AccessSpecifier AS = AS_none);
2293 //===--------------------------------------------------------------------===//
2295 DeclGroupPtrTy ParseModuleImport(SourceLocation AtLoc);
2297 //===--------------------------------------------------------------------===//
2298 // GNU G++: Type Traits [Type-Traits.html in the GCC manual]
2299 ExprResult ParseUnaryTypeTrait();
2300 ExprResult ParseBinaryTypeTrait();
2301 ExprResult ParseTypeTrait();
2303 //===--------------------------------------------------------------------===//
2304 // Embarcadero: Arary and Expression Traits
2305 ExprResult ParseArrayTypeTrait();
2306 ExprResult ParseExpressionTrait();
2308 //===--------------------------------------------------------------------===//
2309 // Preprocessor code-completion pass-through
2310 virtual void CodeCompleteDirective(bool InConditional);
2311 virtual void CodeCompleteInConditionalExclusion();
2312 virtual void CodeCompleteMacroName(bool IsDefinition);
2313 virtual void CodeCompletePreprocessorExpression();
2314 virtual void CodeCompleteMacroArgument(IdentifierInfo *Macro,
2315 MacroInfo *MacroInfo,
2316 unsigned ArgumentIndex);
2317 virtual void CodeCompleteNaturalLanguage();
2320 } // end namespace clang