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/Specifiers.h"
18 #include "clang/Lex/Preprocessor.h"
19 #include "clang/Lex/CodeCompletionHandler.h"
20 #include "clang/Sema/Sema.h"
21 #include "clang/Sema/DeclSpec.h"
22 #include "llvm/ADT/OwningPtr.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/PrettyStackTrace.h"
32 class DiagnosticBuilder;
34 class PragmaUnusedHandler;
35 class ColonProtectionRAIIObject;
36 class InMessageExpressionRAIIObject;
37 class PoisonSEHIdentifiersRAIIObject;
40 /// PrettyStackTraceParserEntry - If a crash happens while the parser is active,
41 /// an entry is printed for it.
42 class PrettyStackTraceParserEntry : public llvm::PrettyStackTraceEntry {
45 PrettyStackTraceParserEntry(const Parser &p) : P(p) {}
46 virtual void print(raw_ostream &OS) const;
49 /// PrecedenceLevels - These are precedences for the binary/ternary
50 /// operators in the C99 grammar. These have been named to relate
51 /// with the C99 grammar productions. Low precedences numbers bind
52 /// more weakly than high numbers.
55 Unknown = 0, // Not binary operator.
57 Assignment = 2, // =, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |=
64 Equality = 9, // ==, !=
65 Relational = 10, // >=, <=, >, <
67 Additive = 12, // -, +
68 Multiplicative = 13, // *, /, %
69 PointerToMember = 14 // .*, ->*
73 /// Parser - This implements a parser for the C family of languages. After
74 /// parsing units of the grammar, productions are invoked to handle whatever has
77 class Parser : public CodeCompletionHandler {
78 friend class PragmaUnusedHandler;
79 friend class ColonProtectionRAIIObject;
80 friend class InMessageExpressionRAIIObject;
81 friend class PoisonSEHIdentifiersRAIIObject;
82 friend class ParenBraceBracketBalancer;
86 /// Tok - The current token we are peeking ahead. All parsing methods assume
87 /// that this is valid.
90 // PrevTokLocation - The location of the token we previously
91 // consumed. This token is used for diagnostics where we expected to
92 // see a token following another token (e.g., the ';' at the end of
94 SourceLocation PrevTokLocation;
96 unsigned short ParenCount, BracketCount, BraceCount;
98 /// Actions - These are the callbacks we invoke as we parse various constructs
102 DiagnosticsEngine &Diags;
104 /// ScopeCache - Cache scopes to reduce malloc traffic.
105 enum { ScopeCacheSize = 16 };
106 unsigned NumCachedScopes;
107 Scope *ScopeCache[ScopeCacheSize];
109 /// Identifiers used for SEH handling in Borland. These are only
110 /// allowed in particular circumstances
112 IdentifierInfo *Ident__exception_code,
113 *Ident___exception_code,
114 *Ident_GetExceptionCode;
115 // __except filter expression
116 IdentifierInfo *Ident__exception_info,
117 *Ident___exception_info,
118 *Ident_GetExceptionInfo;
120 IdentifierInfo *Ident__abnormal_termination,
121 *Ident___abnormal_termination,
122 *Ident_AbnormalTermination;
124 /// Contextual keywords for Microsoft extensions.
125 IdentifierInfo *Ident__except;
127 /// Ident_super - IdentifierInfo for "super", to support fast
129 IdentifierInfo *Ident_super;
130 /// Ident_vector and Ident_pixel - cached IdentifierInfo's for
131 /// "vector" and "pixel" fast comparison. Only present if
133 IdentifierInfo *Ident_vector;
134 IdentifierInfo *Ident_pixel;
136 /// Objective-C contextual keywords.
137 mutable IdentifierInfo *Ident_instancetype;
139 /// \brief Identifier for "introduced".
140 IdentifierInfo *Ident_introduced;
142 /// \brief Identifier for "deprecated".
143 IdentifierInfo *Ident_deprecated;
145 /// \brief Identifier for "obsoleted".
146 IdentifierInfo *Ident_obsoleted;
148 /// \brief Identifier for "unavailable".
149 IdentifierInfo *Ident_unavailable;
151 /// \brief Identifier for "message".
152 IdentifierInfo *Ident_message;
154 /// C++0x contextual keywords.
155 mutable IdentifierInfo *Ident_final;
156 mutable IdentifierInfo *Ident_override;
158 OwningPtr<PragmaHandler> AlignHandler;
159 OwningPtr<PragmaHandler> GCCVisibilityHandler;
160 OwningPtr<PragmaHandler> OptionsHandler;
161 OwningPtr<PragmaHandler> PackHandler;
162 OwningPtr<PragmaHandler> MSStructHandler;
163 OwningPtr<PragmaHandler> UnusedHandler;
164 OwningPtr<PragmaHandler> WeakHandler;
165 OwningPtr<PragmaHandler> RedefineExtnameHandler;
166 OwningPtr<PragmaHandler> FPContractHandler;
167 OwningPtr<PragmaHandler> OpenCLExtensionHandler;
169 /// Whether the '>' token acts as an operator or not. This will be
170 /// true except when we are parsing an expression within a C++
171 /// template argument list, where the '>' closes the template
173 bool GreaterThanIsOperator;
175 /// ColonIsSacred - When this is false, we aggressively try to recover from
176 /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not
177 /// safe in case statements and a few other things. This is managed by the
178 /// ColonProtectionRAIIObject RAII object.
181 /// \brief When true, we are directly inside an Objective-C messsage
184 /// This is managed by the \c InMessageExpressionRAIIObject class, and
185 /// should not be set directly.
186 bool InMessageExpression;
188 /// The "depth" of the template parameters currently being parsed.
189 unsigned TemplateParameterDepth;
191 /// Factory object for creating AttributeList objects.
192 AttributeFactory AttrFactory;
194 /// \brief Gathers and cleans up TemplateIdAnnotations when parsing of a
195 /// top-level declaration is finished.
196 SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
198 IdentifierInfo *getSEHExceptKeyword();
200 bool SkipFunctionBodies;
203 Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
206 const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
207 const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
208 Preprocessor &getPreprocessor() const { return PP; }
209 Sema &getActions() const { return Actions; }
211 const Token &getCurToken() const { return Tok; }
212 Scope *getCurScope() const { return Actions.getCurScope(); }
214 Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); }
216 // Type forwarding. All of these are statically 'void*', but they may all be
217 // different actual classes based on the actions in place.
218 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
219 typedef OpaquePtr<TemplateName> TemplateTy;
221 typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists;
223 typedef clang::ExprResult ExprResult;
224 typedef clang::StmtResult StmtResult;
225 typedef clang::BaseResult BaseResult;
226 typedef clang::MemInitResult MemInitResult;
227 typedef clang::TypeResult TypeResult;
229 typedef Expr *ExprArg;
230 typedef ASTMultiPtr<Stmt*> MultiStmtArg;
231 typedef Sema::FullExprArg FullExprArg;
233 /// Adorns a ExprResult with Actions to make it an ExprResult
234 ExprResult Owned(ExprResult res) {
235 return ExprResult(res);
237 /// Adorns a StmtResult with Actions to make it an StmtResult
238 StmtResult Owned(StmtResult res) {
239 return StmtResult(res);
242 ExprResult ExprError() { return ExprResult(true); }
243 StmtResult StmtError() { return StmtResult(true); }
245 ExprResult ExprError(const DiagnosticBuilder &) { return ExprError(); }
246 StmtResult StmtError(const DiagnosticBuilder &) { return StmtError(); }
248 ExprResult ExprEmpty() { return ExprResult(false); }
252 /// ParseTranslationUnit - All in one method that initializes parses, and
253 /// shuts down the parser.
254 void ParseTranslationUnit();
256 /// Initialize - Warm up the parser.
260 /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if
261 /// the EOF was encountered.
262 bool ParseTopLevelDecl(DeclGroupPtrTy &Result);
265 //===--------------------------------------------------------------------===//
266 // Low-Level token peeking and consumption methods.
269 /// isTokenParen - Return true if the cur token is '(' or ')'.
270 bool isTokenParen() const {
271 return Tok.getKind() == tok::l_paren || Tok.getKind() == tok::r_paren;
273 /// isTokenBracket - Return true if the cur token is '[' or ']'.
274 bool isTokenBracket() const {
275 return Tok.getKind() == tok::l_square || Tok.getKind() == tok::r_square;
277 /// isTokenBrace - Return true if the cur token is '{' or '}'.
278 bool isTokenBrace() const {
279 return Tok.getKind() == tok::l_brace || Tok.getKind() == tok::r_brace;
282 /// isTokenStringLiteral - True if this token is a string-literal.
284 bool isTokenStringLiteral() const {
285 return Tok.getKind() == tok::string_literal ||
286 Tok.getKind() == tok::wide_string_literal ||
287 Tok.getKind() == tok::utf8_string_literal ||
288 Tok.getKind() == tok::utf16_string_literal ||
289 Tok.getKind() == tok::utf32_string_literal;
292 /// \brief Returns true if the current token is '=' or is a type of '='.
293 /// For typos, give a fixit to '='
294 bool isTokenEqualOrEqualTypo();
296 /// ConsumeToken - Consume the current 'peek token' and lex the next one.
297 /// This does not work with all kinds of tokens: strings and specific other
298 /// tokens must be consumed with custom methods below. This returns the
299 /// location of the consumed token.
300 SourceLocation ConsumeToken() {
301 assert(!isTokenStringLiteral() && !isTokenParen() && !isTokenBracket() &&
303 "Should consume special tokens with Consume*Token");
305 if (Tok.is(tok::code_completion))
306 return handleUnexpectedCodeCompletionToken();
308 PrevTokLocation = Tok.getLocation();
310 return PrevTokLocation;
313 /// ConsumeAnyToken - Dispatch to the right Consume* method based on the
314 /// current token type. This should only be used in cases where the type of
315 /// the token really isn't known, e.g. in error recovery.
316 SourceLocation ConsumeAnyToken() {
318 return ConsumeParen();
319 else if (isTokenBracket())
320 return ConsumeBracket();
321 else if (isTokenBrace())
322 return ConsumeBrace();
323 else if (isTokenStringLiteral())
324 return ConsumeStringToken();
326 return ConsumeToken();
329 /// ConsumeParen - This consume method keeps the paren count up-to-date.
331 SourceLocation ConsumeParen() {
332 assert(isTokenParen() && "wrong consume method");
333 if (Tok.getKind() == tok::l_paren)
336 --ParenCount; // Don't let unbalanced )'s drive the count negative.
337 PrevTokLocation = Tok.getLocation();
339 return PrevTokLocation;
342 /// ConsumeBracket - This consume method keeps the bracket count up-to-date.
344 SourceLocation ConsumeBracket() {
345 assert(isTokenBracket() && "wrong consume method");
346 if (Tok.getKind() == tok::l_square)
348 else if (BracketCount)
349 --BracketCount; // Don't let unbalanced ]'s drive the count negative.
351 PrevTokLocation = Tok.getLocation();
353 return PrevTokLocation;
356 /// ConsumeBrace - This consume method keeps the brace count up-to-date.
358 SourceLocation ConsumeBrace() {
359 assert(isTokenBrace() && "wrong consume method");
360 if (Tok.getKind() == tok::l_brace)
363 --BraceCount; // Don't let unbalanced }'s drive the count negative.
365 PrevTokLocation = Tok.getLocation();
367 return PrevTokLocation;
370 /// ConsumeStringToken - Consume the current 'peek token', lexing a new one
371 /// and returning the token kind. This method is specific to strings, as it
372 /// handles string literal concatenation, as per C99 5.1.1.2, translation
374 SourceLocation ConsumeStringToken() {
375 assert(isTokenStringLiteral() &&
376 "Should only consume string literals with this method");
377 PrevTokLocation = Tok.getLocation();
379 return PrevTokLocation;
382 /// \brief Consume the current code-completion token.
384 /// This routine should be called to consume the code-completion token once
385 /// a code-completion action has already been invoked.
386 SourceLocation ConsumeCodeCompletionToken() {
387 assert(Tok.is(tok::code_completion));
388 PrevTokLocation = Tok.getLocation();
390 return PrevTokLocation;
393 ///\ brief When we are consuming a code-completion token without having
394 /// matched specific position in the grammar, provide code-completion results
395 /// based on context.
397 /// \returns the source location of the code-completion token.
398 SourceLocation handleUnexpectedCodeCompletionToken();
400 /// \brief Abruptly cut off parsing; mainly used when we have reached the
401 /// code-completion point.
402 void cutOffParsing() {
403 PP.setCodeCompletionReached();
404 // Cut off parsing by acting as if we reached the end-of-file.
405 Tok.setKind(tok::eof);
408 /// \brief Handle the annotation token produced for #pragma unused(...)
409 void HandlePragmaUnused();
411 /// \brief Handle the annotation token produced for
412 /// #pragma GCC visibility...
413 void HandlePragmaVisibility();
415 /// \brief Handle the annotation token produced for
417 void HandlePragmaPack();
419 /// GetLookAheadToken - This peeks ahead N tokens and returns that token
420 /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1)
421 /// returns the token after Tok, etc.
423 /// Note that this differs from the Preprocessor's LookAhead method, because
424 /// the Parser always has one token lexed that the preprocessor doesn't.
426 const Token &GetLookAheadToken(unsigned N) {
427 if (N == 0 || Tok.is(tok::eof)) return Tok;
428 return PP.LookAhead(N-1);
431 /// NextToken - This peeks ahead one token and returns it without
433 const Token &NextToken() {
434 return PP.LookAhead(0);
437 /// \brief RAII class that helps handle the parsing of an open/close delimiter
438 /// pair, such as braces { ... } or parentheses ( ... ).
439 class BalancedDelimiterTracker {
441 tok::TokenKind Kind, Close;
442 SourceLocation (Parser::*Consumer)();
443 SourceLocation LOpen, LClose;
445 unsigned short &getDepth() {
447 case tok::l_brace: return P.BraceCount;
448 case tok::l_square: return P.BracketCount;
449 case tok::l_paren: return P.ParenCount;
450 default: llvm_unreachable("Wrong token kind");
454 enum { MaxDepth = 512 };
456 bool diagnoseOverflow();
457 bool diagnoseMissingClose();
460 BalancedDelimiterTracker(Parser& p, tok::TokenKind k) : P(p), Kind(k) {
462 default: llvm_unreachable("Unexpected balanced token");
464 Close = tok::r_brace;
465 Consumer = &Parser::ConsumeBrace;
468 Close = tok::r_paren;
469 Consumer = &Parser::ConsumeParen;
473 Close = tok::r_square;
474 Consumer = &Parser::ConsumeBracket;
479 SourceLocation getOpenLocation() const { return LOpen; }
480 SourceLocation getCloseLocation() const { return LClose; }
481 SourceRange getRange() const { return SourceRange(LOpen, LClose); }
487 if (getDepth() < MaxDepth) {
488 LOpen = (P.*Consumer)();
492 return diagnoseOverflow();
495 bool expectAndConsume(unsigned DiagID,
496 const char *Msg = "",
497 tok::TokenKind SkipToTok = tok::unknown);
498 bool consumeClose() {
499 if (P.Tok.is(Close)) {
500 LClose = (P.*Consumer)();
504 return diagnoseMissingClose();
509 /// getTypeAnnotation - Read a parsed type out of an annotation token.
510 static ParsedType getTypeAnnotation(Token &Tok) {
511 return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
514 static void setTypeAnnotation(Token &Tok, ParsedType T) {
515 Tok.setAnnotationValue(T.getAsOpaquePtr());
518 /// \brief Read an already-translated primary expression out of an annotation
520 static ExprResult getExprAnnotation(Token &Tok) {
521 if (Tok.getAnnotationValue())
522 return ExprResult((Expr *)Tok.getAnnotationValue());
524 return ExprResult(true);
527 /// \brief Set the primary expression corresponding to the given annotation
529 static void setExprAnnotation(Token &Tok, ExprResult ER) {
531 Tok.setAnnotationValue(0);
533 Tok.setAnnotationValue(ER.get());
536 // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to
537 // find a type name by attempting typo correction.
538 bool TryAnnotateTypeOrScopeToken(bool EnteringContext = false,
539 bool NeedType = false);
540 bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
542 /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
543 /// replacing them with the non-context-sensitive keywords. This returns
544 /// true if the token was replaced.
545 bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
546 const char *&PrevSpec, unsigned &DiagID,
548 if (!getLangOpts().AltiVec ||
549 (Tok.getIdentifierInfo() != Ident_vector &&
550 Tok.getIdentifierInfo() != Ident_pixel))
553 return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
556 /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
557 /// identifier token, replacing it with the non-context-sensitive __vector.
558 /// This returns true if the token was replaced.
559 bool TryAltiVecVectorToken() {
560 if (!getLangOpts().AltiVec ||
561 Tok.getIdentifierInfo() != Ident_vector) return false;
562 return TryAltiVecVectorTokenOutOfLine();
565 bool TryAltiVecVectorTokenOutOfLine();
566 bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
567 const char *&PrevSpec, unsigned &DiagID,
570 /// \brief Get the TemplateIdAnnotation from the token.
571 TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
573 /// TentativeParsingAction - An object that is used as a kind of "tentative
574 /// parsing transaction". It gets instantiated to mark the token position and
575 /// after the token consumption is done, Commit() or Revert() is called to
576 /// either "commit the consumed tokens" or revert to the previously marked
577 /// token position. Example:
579 /// TentativeParsingAction TPA(*this);
584 class TentativeParsingAction {
590 explicit TentativeParsingAction(Parser& p) : P(p) {
592 P.PP.EnableBacktrackAtThisPos();
596 assert(isActive && "Parsing action was finished!");
597 P.PP.CommitBacktrackedTokens();
601 assert(isActive && "Parsing action was finished!");
606 ~TentativeParsingAction() {
607 assert(!isActive && "Forgot to call Commit or Revert!");
611 /// ObjCDeclContextSwitch - An object used to switch context from
612 /// an objective-c decl context to its enclosing decl context and
614 class ObjCDeclContextSwitch {
618 explicit ObjCDeclContextSwitch(Parser &p) : P(p),
619 DC(p.getObjCDeclContext()) {
621 P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC));
623 ~ObjCDeclContextSwitch() {
625 P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC));
629 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
630 /// input. If so, it is consumed and false is returned.
632 /// If the input is malformed, this emits the specified diagnostic. Next, if
633 /// SkipToTok is specified, it calls SkipUntil(SkipToTok). Finally, true is
635 bool ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned Diag,
636 const char *DiagMsg = "",
637 tok::TokenKind SkipToTok = tok::unknown);
639 /// \brief The parser expects a semicolon and, if present, will consume it.
641 /// If the next token is not a semicolon, this emits the specified diagnostic,
642 /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
643 /// to the semicolon, consumes that extra token.
644 bool ExpectAndConsumeSemi(unsigned DiagID);
646 //===--------------------------------------------------------------------===//
647 // Scope manipulation
649 /// ParseScope - Introduces a new scope for parsing. The kind of
650 /// scope is determined by ScopeFlags. Objects of this type should
651 /// be created on the stack to coincide with the position where the
652 /// parser enters the new scope, and this object's constructor will
653 /// create that new scope. Similarly, once the object is destroyed
654 /// the parser will exit the scope.
657 ParseScope(const ParseScope&); // do not implement
658 ParseScope& operator=(const ParseScope&); // do not implement
661 // ParseScope - Construct a new object to manage a scope in the
662 // parser Self where the new Scope is created with the flags
663 // ScopeFlags, but only when ManageScope is true (the default). If
664 // ManageScope is false, this object does nothing.
665 ParseScope(Parser *Self, unsigned ScopeFlags, bool ManageScope = true)
668 Self->EnterScope(ScopeFlags);
673 // Exit - Exit the scope associated with this object now, rather
674 // than waiting until the object is destroyed.
687 /// EnterScope - Start a new scope.
688 void EnterScope(unsigned ScopeFlags);
690 /// ExitScope - Pop a scope off the scope stack.
693 /// \brief RAII object used to modify the scope flags for the current scope.
694 class ParseScopeFlags {
697 ParseScopeFlags(const ParseScopeFlags &); // do not implement
698 void operator=(const ParseScopeFlags &); // do not implement
701 ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
705 //===--------------------------------------------------------------------===//
706 // Diagnostic Emission and Error recovery.
709 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
710 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
713 void SuggestParentheses(SourceLocation Loc, unsigned DK,
714 SourceRange ParenRange);
715 void CheckNestedObjCContexts(SourceLocation AtLoc);
717 /// SkipUntil - Read tokens until we get to the specified token, then consume
718 /// it (unless DontConsume is true). Because we cannot guarantee that the
719 /// token will ever occur, this skips to the next token, or to some likely
720 /// good stopping point. If StopAtSemi is true, skipping will stop at a ';'
723 /// If SkipUntil finds the specified token, it returns true, otherwise it
725 bool SkipUntil(tok::TokenKind T, bool StopAtSemi = true,
726 bool DontConsume = false, bool StopAtCodeCompletion = false) {
727 return SkipUntil(llvm::makeArrayRef(T), StopAtSemi, DontConsume,
728 StopAtCodeCompletion);
730 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, bool StopAtSemi = true,
731 bool DontConsume = false, bool StopAtCodeCompletion = false) {
732 tok::TokenKind TokArray[] = {T1, T2};
733 return SkipUntil(TokArray, StopAtSemi, DontConsume,StopAtCodeCompletion);
735 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3,
736 bool StopAtSemi = true, bool DontConsume = false,
737 bool StopAtCodeCompletion = false) {
738 tok::TokenKind TokArray[] = {T1, T2, T3};
739 return SkipUntil(TokArray, StopAtSemi, DontConsume,StopAtCodeCompletion);
741 bool SkipUntil(ArrayRef<tok::TokenKind> Toks, bool StopAtSemi = true,
742 bool DontConsume = false, bool StopAtCodeCompletion = false);
744 /// SkipMalformedDecl - Read tokens until we get to some likely good stopping
745 /// point for skipping past a simple-declaration.
746 void SkipMalformedDecl();
748 //===--------------------------------------------------------------------===//
749 // Lexing and parsing of C++ inline methods.
753 /// [class.mem]p1: "... the class is regarded as complete within
754 /// - function bodies
755 /// - default arguments
756 /// - exception-specifications (TODO: C++0x)
757 /// - and brace-or-equal-initializers for non-static data members
758 /// (including such things in nested classes)."
759 /// LateParsedDeclarations build the tree of those elements so they can
760 /// be parsed after parsing the top-level class.
761 class LateParsedDeclaration {
763 virtual ~LateParsedDeclaration();
765 virtual void ParseLexedMethodDeclarations();
766 virtual void ParseLexedMemberInitializers();
767 virtual void ParseLexedMethodDefs();
768 virtual void ParseLexedAttributes();
771 /// Inner node of the LateParsedDeclaration tree that parses
772 /// all its members recursively.
773 class LateParsedClass : public LateParsedDeclaration {
775 LateParsedClass(Parser *P, ParsingClass *C);
776 virtual ~LateParsedClass();
778 virtual void ParseLexedMethodDeclarations();
779 virtual void ParseLexedMemberInitializers();
780 virtual void ParseLexedMethodDefs();
781 virtual void ParseLexedAttributes();
788 /// Contains the lexed tokens of an attribute with arguments that
789 /// may reference member variables and so need to be parsed at the
790 /// end of the class declaration after parsing all other member
791 /// member declarations.
792 /// FIXME: Perhaps we should change the name of LateParsedDeclaration to
793 /// LateParsedTokens.
794 struct LateParsedAttribute : public LateParsedDeclaration {
797 IdentifierInfo &AttrName;
798 SourceLocation AttrNameLoc;
799 SmallVector<Decl*, 2> Decls;
801 explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
803 : Self(P), AttrName(Name), AttrNameLoc(Loc) {}
805 virtual void ParseLexedAttributes();
807 void addDecl(Decl *D) { Decls.push_back(D); }
810 /// A list of late parsed attributes. Used by ParseGNUAttributes.
811 typedef llvm::SmallVector<LateParsedAttribute*, 2> LateParsedAttrList;
814 /// Contains the lexed tokens of a member function definition
815 /// which needs to be parsed at the end of the class declaration
816 /// after parsing all other member declarations.
817 struct LexedMethod : public LateParsedDeclaration {
822 /// \brief Whether this member function had an associated template
823 /// scope. When true, D is a template declaration.
824 /// othewise, it is a member function declaration.
827 explicit LexedMethod(Parser* P, Decl *MD)
828 : Self(P), D(MD), TemplateScope(false) {}
830 virtual void ParseLexedMethodDefs();
833 /// LateParsedDefaultArgument - Keeps track of a parameter that may
834 /// have a default argument that cannot be parsed yet because it
835 /// occurs within a member function declaration inside the class
836 /// (C++ [class.mem]p2).
837 struct LateParsedDefaultArgument {
838 explicit LateParsedDefaultArgument(Decl *P,
839 CachedTokens *Toks = 0)
840 : Param(P), Toks(Toks) { }
842 /// Param - The parameter declaration for this parameter.
845 /// Toks - The sequence of tokens that comprises the default
846 /// argument expression, not including the '=' or the terminating
847 /// ')' or ','. This will be NULL for parameters that have no
848 /// default argument.
852 /// LateParsedMethodDeclaration - A method declaration inside a class that
853 /// contains at least one entity whose parsing needs to be delayed
854 /// until the class itself is completely-defined, such as a default
855 /// argument (C++ [class.mem]p2).
856 struct LateParsedMethodDeclaration : public LateParsedDeclaration {
857 explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
858 : Self(P), Method(M), TemplateScope(false), ExceptionSpecTokens(0) { }
860 virtual void ParseLexedMethodDeclarations();
864 /// Method - The method declaration.
867 /// \brief Whether this member function had an associated template
868 /// scope. When true, D is a template declaration.
869 /// othewise, it is a member function declaration.
872 /// DefaultArgs - Contains the parameters of the function and
873 /// their default arguments. At least one of the parameters will
874 /// have a default argument, but all of the parameters of the
875 /// method will be stored so that they can be reintroduced into
876 /// scope at the appropriate times.
877 SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
879 /// \brief The set of tokens that make up an exception-specification that
880 /// has not yet been parsed.
881 CachedTokens *ExceptionSpecTokens;
884 /// LateParsedMemberInitializer - An initializer for a non-static class data
885 /// member whose parsing must to be delayed until the class is completely
886 /// defined (C++11 [class.mem]p2).
887 struct LateParsedMemberInitializer : public LateParsedDeclaration {
888 LateParsedMemberInitializer(Parser *P, Decl *FD)
889 : Self(P), Field(FD) { }
891 virtual void ParseLexedMemberInitializers();
895 /// Field - The field declaration.
898 /// CachedTokens - The sequence of tokens that comprises the initializer,
899 /// including any leading '='.
903 /// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
904 /// C++ class, its method declarations that contain parts that won't be
905 /// parsed until after the definition is completed (C++ [class.mem]p2),
906 /// the method declarations and possibly attached inline definitions
907 /// will be stored here with the tokens that will be parsed to create those
909 typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer;
911 /// \brief Representation of a class that has been parsed, including
912 /// any member function declarations or definitions that need to be
913 /// parsed after the corresponding top-level class is complete.
914 struct ParsingClass {
915 ParsingClass(Decl *TagOrTemplate, bool TopLevelClass)
916 : TopLevelClass(TopLevelClass), TemplateScope(false),
917 TagOrTemplate(TagOrTemplate) { }
919 /// \brief Whether this is a "top-level" class, meaning that it is
920 /// not nested within another class.
921 bool TopLevelClass : 1;
923 /// \brief Whether this class had an associated template
924 /// scope. When true, TagOrTemplate is a template declaration;
925 /// othewise, it is a tag declaration.
926 bool TemplateScope : 1;
928 /// \brief The class or class template whose definition we are parsing.
931 /// LateParsedDeclarations - Method declarations, inline definitions and
932 /// nested classes that contain pieces whose parsing will be delayed until
933 /// the top-level class is fully defined.
934 LateParsedDeclarationsContainer LateParsedDeclarations;
937 /// \brief The stack of classes that is currently being
938 /// parsed. Nested and local classes will be pushed onto this stack
939 /// when they are parsed, and removed afterward.
940 std::stack<ParsingClass *> ClassStack;
942 ParsingClass &getCurrentClass() {
943 assert(!ClassStack.empty() && "No lexed method stacks!");
944 return *ClassStack.top();
947 /// \brief RAII object used to inform the actions that we're
948 /// currently parsing a declaration. This is active when parsing a
949 /// variable's initializer, but not when parsing the body of a
950 /// class or function definition.
951 class ParsingDeclRAIIObject {
953 Sema::ParsingDeclState State;
957 ParsingDeclRAIIObject(Parser &P) : Actions(P.Actions) {
961 ParsingDeclRAIIObject(Parser &P, ParsingDeclRAIIObject *Other)
962 : Actions(P.Actions) {
963 if (Other) steal(*Other);
967 /// Creates a RAII object which steals the state from a different
968 /// object instead of pushing.
969 ParsingDeclRAIIObject(ParsingDeclRAIIObject &Other)
970 : Actions(Other.Actions) {
974 ~ParsingDeclRAIIObject() {
978 /// Resets the RAII object for a new declaration.
984 /// Signals that the context was completed without an appropriate
985 /// declaration being parsed.
990 void complete(Decl *D) {
991 assert(!Popped && "ParsingDeclaration has already been popped!");
996 void steal(ParsingDeclRAIIObject &Other) {
998 Popped = Other.Popped;
1003 State = Actions.PushParsingDeclaration();
1009 Actions.PopParsingDeclaration(State, D);
1015 /// A class for parsing a DeclSpec.
1016 class ParsingDeclSpec : public DeclSpec {
1017 ParsingDeclRAIIObject ParsingRAII;
1020 ParsingDeclSpec(Parser &P) : DeclSpec(P.AttrFactory), ParsingRAII(P) {}
1021 ParsingDeclSpec(Parser &P, ParsingDeclRAIIObject *RAII)
1022 : DeclSpec(P.AttrFactory), ParsingRAII(P, RAII) {}
1024 void complete(Decl *D) {
1025 ParsingRAII.complete(D);
1029 ParsingRAII.abort();
1033 /// A class for parsing a declarator.
1034 class ParsingDeclarator : public Declarator {
1035 ParsingDeclRAIIObject ParsingRAII;
1038 ParsingDeclarator(Parser &P, const ParsingDeclSpec &DS, TheContext C)
1039 : Declarator(DS, C), ParsingRAII(P) {
1042 const ParsingDeclSpec &getDeclSpec() const {
1043 return static_cast<const ParsingDeclSpec&>(Declarator::getDeclSpec());
1046 ParsingDeclSpec &getMutableDeclSpec() const {
1047 return const_cast<ParsingDeclSpec&>(getDeclSpec());
1051 Declarator::clear();
1052 ParsingRAII.reset();
1055 void complete(Decl *D) {
1056 ParsingRAII.complete(D);
1060 /// \brief RAII object used to
1061 class ParsingClassDefinition {
1064 Sema::ParsingClassState State;
1067 ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass)
1068 : P(P), Popped(false),
1069 State(P.PushParsingClass(TagOrTemplate, TopLevelClass)) {
1072 /// \brief Pop this class of the stack.
1074 assert(!Popped && "Nested class has already been popped");
1076 P.PopParsingClass(State);
1079 ~ParsingClassDefinition() {
1081 P.PopParsingClass(State);
1085 /// \brief Contains information about any template-specific
1086 /// information that has been parsed prior to parsing declaration
1088 struct ParsedTemplateInfo {
1089 ParsedTemplateInfo()
1090 : Kind(NonTemplate), TemplateParams(0), TemplateLoc() { }
1092 ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
1093 bool isSpecialization,
1094 bool lastParameterListWasEmpty = false)
1095 : Kind(isSpecialization? ExplicitSpecialization : Template),
1096 TemplateParams(TemplateParams),
1097 LastParameterListWasEmpty(lastParameterListWasEmpty) { }
1099 explicit ParsedTemplateInfo(SourceLocation ExternLoc,
1100 SourceLocation TemplateLoc)
1101 : Kind(ExplicitInstantiation), TemplateParams(0),
1102 ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
1103 LastParameterListWasEmpty(false){ }
1105 /// \brief The kind of template we are parsing.
1107 /// \brief We are not parsing a template at all.
1109 /// \brief We are parsing a template declaration.
1111 /// \brief We are parsing an explicit specialization.
1112 ExplicitSpecialization,
1113 /// \brief We are parsing an explicit instantiation.
1114 ExplicitInstantiation
1117 /// \brief The template parameter lists, for template declarations
1118 /// and explicit specializations.
1119 TemplateParameterLists *TemplateParams;
1121 /// \brief The location of the 'extern' keyword, if any, for an explicit
1123 SourceLocation ExternLoc;
1125 /// \brief The location of the 'template' keyword, for an explicit
1127 SourceLocation TemplateLoc;
1129 /// \brief Whether the last template parameter list was empty.
1130 bool LastParameterListWasEmpty;
1132 SourceRange getSourceRange() const LLVM_READONLY;
1135 /// \brief Contains a late templated function.
1136 /// Will be parsed at the end of the translation unit.
1137 struct LateParsedTemplatedFunction {
1138 explicit LateParsedTemplatedFunction(Decl *MD)
1143 /// \brief The template function declaration to be late parsed.
1147 void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
1148 void ParseLateTemplatedFuncDef(LateParsedTemplatedFunction &LMT);
1149 typedef llvm::DenseMap<const FunctionDecl*, LateParsedTemplatedFunction*>
1150 LateParsedTemplateMapT;
1151 LateParsedTemplateMapT LateParsedTemplateMap;
1153 static void LateTemplateParserCallback(void *P, const FunctionDecl *FD);
1154 void LateTemplateParser(const FunctionDecl *FD);
1156 Sema::ParsingClassState
1157 PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass);
1158 void DeallocateParsedClasses(ParsingClass *Class);
1159 void PopParsingClass(Sema::ParsingClassState);
1161 Decl *ParseCXXInlineMethodDef(AccessSpecifier AS, AttributeList *AccessAttrs,
1162 ParsingDeclarator &D,
1163 const ParsedTemplateInfo &TemplateInfo,
1164 const VirtSpecifiers& VS,
1165 FunctionDefinitionKind DefinitionKind,
1167 void ParseCXXNonStaticMemberInitializer(Decl *VarD);
1168 void ParseLexedAttributes(ParsingClass &Class);
1169 void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1170 bool EnterScope, bool OnDefinition);
1171 void ParseLexedAttribute(LateParsedAttribute &LA,
1172 bool EnterScope, bool OnDefinition);
1173 void ParseLexedMethodDeclarations(ParsingClass &Class);
1174 void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
1175 void ParseLexedMethodDefs(ParsingClass &Class);
1176 void ParseLexedMethodDef(LexedMethod &LM);
1177 void ParseLexedMemberInitializers(ParsingClass &Class);
1178 void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
1179 Decl *ParseLexedObjCMethodDefs(LexedMethod &LM);
1180 bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
1181 bool ConsumeAndStoreUntil(tok::TokenKind T1,
1183 bool StopAtSemi = true,
1184 bool ConsumeFinalToken = true) {
1185 return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
1187 bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
1189 bool StopAtSemi = true,
1190 bool ConsumeFinalToken = true);
1192 //===--------------------------------------------------------------------===//
1193 // C99 6.9: External Definitions.
1194 struct ParsedAttributesWithRange : ParsedAttributes {
1195 ParsedAttributesWithRange(AttributeFactory &factory)
1196 : ParsedAttributes(factory) {}
1201 DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
1202 ParsingDeclSpec *DS = 0);
1203 bool isDeclarationAfterDeclarator();
1204 bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
1205 DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(ParsedAttributes &attrs,
1206 AccessSpecifier AS = AS_none);
1207 DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(ParsingDeclSpec &DS,
1208 AccessSpecifier AS = AS_none);
1210 Decl *ParseFunctionDefinition(ParsingDeclarator &D,
1211 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1212 LateParsedAttrList *LateParsedAttrs = 0);
1213 void ParseKNRParamDeclarations(Declarator &D);
1214 // EndLoc, if non-NULL, is filled with the location of the last token of
1216 ExprResult ParseSimpleAsm(SourceLocation *EndLoc = 0);
1217 ExprResult ParseAsmStringLiteral();
1219 // Objective-C External Declarations
1220 DeclGroupPtrTy ParseObjCAtDirectives();
1221 DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
1222 Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
1223 ParsedAttributes &prefixAttrs);
1224 void ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1225 tok::ObjCKeywordKind visibility,
1226 SourceLocation atLoc);
1227 bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P,
1228 SmallVectorImpl<SourceLocation> &PLocs,
1229 bool WarnOnDeclarations,
1230 SourceLocation &LAngleLoc,
1231 SourceLocation &EndProtoLoc);
1232 bool ParseObjCProtocolQualifiers(DeclSpec &DS);
1233 void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
1235 DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
1236 ParsedAttributes &prefixAttrs);
1238 struct ObjCImplParsingDataRAII {
1241 typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer;
1242 LateParsedObjCMethodContainer LateParsedObjCMethods;
1244 ObjCImplParsingDataRAII(Parser &parser, Decl *D)
1245 : P(parser), Dcl(D) {
1246 P.CurParsedObjCImpl = this;
1249 ~ObjCImplParsingDataRAII();
1251 void finish(SourceRange AtEnd);
1252 bool isFinished() const { return Finished; }
1257 ObjCImplParsingDataRAII *CurParsedObjCImpl;
1259 DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc);
1260 DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
1261 Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
1262 Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
1263 Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
1265 IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
1266 // Definitions for Objective-c context sensitive keywords recognition.
1268 objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
1271 IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
1273 bool isTokIdentifier_in() const;
1275 ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, Declarator::TheContext Ctx,
1276 ParsedAttributes *ParamAttrs);
1277 void ParseObjCMethodRequirement();
1278 Decl *ParseObjCMethodPrototype(
1279 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1280 bool MethodDefinition = true);
1281 Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
1282 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1283 bool MethodDefinition=true);
1284 void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
1286 Decl *ParseObjCMethodDefinition();
1288 //===--------------------------------------------------------------------===//
1289 // C99 6.5: Expressions.
1291 /// TypeCastState - State whether an expression is or may be a type cast.
1292 enum TypeCastState {
1298 ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast);
1299 ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast);
1300 // Expr that doesn't include commas.
1301 ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast);
1303 ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
1305 ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
1307 ExprResult ParseRHSOfBinaryExpression(ExprResult LHS,
1308 prec::Level MinPrec);
1309 ExprResult ParseCastExpression(bool isUnaryExpression,
1310 bool isAddressOfOperand,
1312 TypeCastState isTypeCast);
1313 ExprResult ParseCastExpression(bool isUnaryExpression,
1314 bool isAddressOfOperand = false,
1315 TypeCastState isTypeCast = NotTypeCast);
1317 /// Returns true if the next token would start a postfix-expression
1319 bool isPostfixExpressionSuffixStart() {
1320 tok::TokenKind K = Tok.getKind();
1321 return (K == tok::l_square || K == tok::l_paren ||
1322 K == tok::period || K == tok::arrow ||
1323 K == tok::plusplus || K == tok::minusminus);
1326 ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
1327 ExprResult ParseUnaryExprOrTypeTraitExpression();
1328 ExprResult ParseBuiltinPrimaryExpression();
1330 ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1333 SourceRange &CastRange);
1335 typedef SmallVector<Expr*, 20> ExprListTy;
1336 typedef SmallVector<SourceLocation, 20> CommaLocsTy;
1338 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1339 bool ParseExpressionList(SmallVectorImpl<Expr*> &Exprs,
1340 SmallVectorImpl<SourceLocation> &CommaLocs,
1341 void (Sema::*Completer)(Scope *S,
1343 llvm::ArrayRef<Expr *> Args) = 0,
1346 /// ParenParseOption - Control what ParseParenExpression will parse.
1347 enum ParenParseOption {
1348 SimpleExpr, // Only parse '(' expression ')'
1349 CompoundStmt, // Also allow '(' compound-statement ')'
1350 CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
1351 CastExpr // Also allow '(' type-name ')' <anything>
1353 ExprResult ParseParenExpression(ParenParseOption &ExprType,
1354 bool stopIfCastExpr,
1357 SourceLocation &RParenLoc);
1359 ExprResult ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
1361 BalancedDelimiterTracker &Tracker);
1362 ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
1363 SourceLocation LParenLoc,
1364 SourceLocation RParenLoc);
1366 ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
1368 ExprResult ParseGenericSelectionExpression();
1370 ExprResult ParseObjCBoolLiteral();
1372 //===--------------------------------------------------------------------===//
1374 ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
1376 void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
1377 bool EnteringContext, IdentifierInfo &II,
1380 bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
1381 ParsedType ObjectType,
1382 bool EnteringContext,
1383 bool *MayBePseudoDestructor = 0,
1384 bool IsTypename = false);
1386 //===--------------------------------------------------------------------===//
1387 // C++0x 5.1.2: Lambda expressions
1389 // [...] () -> type {...}
1390 ExprResult ParseLambdaExpression();
1391 ExprResult TryParseLambdaExpression();
1392 llvm::Optional<unsigned> ParseLambdaIntroducer(LambdaIntroducer &Intro);
1393 bool TryParseLambdaIntroducer(LambdaIntroducer &Intro);
1394 ExprResult ParseLambdaExpressionAfterIntroducer(
1395 LambdaIntroducer &Intro);
1397 //===--------------------------------------------------------------------===//
1398 // C++ 5.2p1: C++ Casts
1399 ExprResult ParseCXXCasts();
1401 //===--------------------------------------------------------------------===//
1402 // C++ 5.2p1: C++ Type Identification
1403 ExprResult ParseCXXTypeid();
1405 //===--------------------------------------------------------------------===//
1406 // C++ : Microsoft __uuidof Expression
1407 ExprResult ParseCXXUuidof();
1409 //===--------------------------------------------------------------------===//
1410 // C++ 5.2.4: C++ Pseudo-Destructor Expressions
1411 ExprResult ParseCXXPseudoDestructor(ExprArg Base, SourceLocation OpLoc,
1412 tok::TokenKind OpKind,
1414 ParsedType ObjectType);
1416 //===--------------------------------------------------------------------===//
1417 // C++ 9.3.2: C++ 'this' pointer
1418 ExprResult ParseCXXThis();
1420 //===--------------------------------------------------------------------===//
1421 // C++ 15: C++ Throw Expression
1422 ExprResult ParseThrowExpression();
1424 ExceptionSpecificationType tryParseExceptionSpecification(
1426 SourceRange &SpecificationRange,
1427 SmallVectorImpl<ParsedType> &DynamicExceptions,
1428 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
1429 ExprResult &NoexceptExpr,
1430 CachedTokens *&ExceptionSpecTokens);
1432 // EndLoc is filled with the location of the last token of the specification.
1433 ExceptionSpecificationType ParseDynamicExceptionSpecification(
1434 SourceRange &SpecificationRange,
1435 SmallVectorImpl<ParsedType> &Exceptions,
1436 SmallVectorImpl<SourceRange> &Ranges);
1438 //===--------------------------------------------------------------------===//
1439 // C++0x 8: Function declaration trailing-return-type
1440 TypeResult ParseTrailingReturnType(SourceRange &Range);
1442 //===--------------------------------------------------------------------===//
1443 // C++ 2.13.5: C++ Boolean Literals
1444 ExprResult ParseCXXBoolLiteral();
1446 //===--------------------------------------------------------------------===//
1447 // C++ 5.2.3: Explicit type conversion (functional notation)
1448 ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
1450 bool isCXXSimpleTypeSpecifier() const;
1452 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1453 /// This should only be called when the current token is known to be part of
1454 /// simple-type-specifier.
1455 void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
1457 bool ParseCXXTypeSpecifierSeq(DeclSpec &DS);
1459 //===--------------------------------------------------------------------===//
1460 // C++ 5.3.4 and 5.3.5: C++ new and delete
1461 bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs,
1463 void ParseDirectNewDeclarator(Declarator &D);
1464 ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
1465 ExprResult ParseCXXDeleteExpression(bool UseGlobal,
1466 SourceLocation Start);
1468 //===--------------------------------------------------------------------===//
1469 // C++ if/switch/while condition expression.
1470 bool ParseCXXCondition(ExprResult &ExprResult, Decl *&DeclResult,
1471 SourceLocation Loc, bool ConvertToBoolean);
1473 //===--------------------------------------------------------------------===//
1476 //===--------------------------------------------------------------------===//
1477 // C99 6.7.8: Initialization.
1479 /// ParseInitializer
1480 /// initializer: [C99 6.7.8]
1481 /// assignment-expression
1483 ExprResult ParseInitializer() {
1484 if (Tok.isNot(tok::l_brace))
1485 return ParseAssignmentExpression();
1486 return ParseBraceInitializer();
1488 bool MayBeDesignationStart();
1489 ExprResult ParseBraceInitializer();
1490 ExprResult ParseInitializerWithPotentialDesignator();
1492 //===--------------------------------------------------------------------===//
1493 // clang Expressions
1495 ExprResult ParseBlockLiteralExpression(); // ^{...}
1497 //===--------------------------------------------------------------------===//
1498 // Objective-C Expressions
1499 ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
1500 ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
1501 ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
1502 ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
1503 ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
1504 ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
1505 ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
1506 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
1507 ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
1508 ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
1509 bool isSimpleObjCMessageExpression();
1510 ExprResult ParseObjCMessageExpression();
1511 ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
1512 SourceLocation SuperLoc,
1513 ParsedType ReceiverType,
1514 ExprArg ReceiverExpr);
1515 ExprResult ParseAssignmentExprWithObjCMessageExprStart(
1516 SourceLocation LBracloc, SourceLocation SuperLoc,
1517 ParsedType ReceiverType, ExprArg ReceiverExpr);
1518 bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
1520 //===--------------------------------------------------------------------===//
1521 // C99 6.8: Statements and Blocks.
1523 StmtResult ParseStatement(SourceLocation *TrailingElseLoc = 0) {
1524 StmtVector Stmts(Actions);
1525 return ParseStatementOrDeclaration(Stmts, true, TrailingElseLoc);
1527 StmtResult ParseStatementOrDeclaration(StmtVector &Stmts,
1529 SourceLocation *TrailingElseLoc = 0);
1530 StmtResult ParseStatementOrDeclarationAfterAttributes(
1533 SourceLocation *TrailingElseLoc,
1534 ParsedAttributesWithRange &Attrs);
1535 StmtResult ParseExprStatement();
1536 StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs);
1537 StmtResult ParseCaseStatement(bool MissingCase = false,
1538 ExprResult Expr = ExprResult());
1539 StmtResult ParseDefaultStatement();
1540 StmtResult ParseCompoundStatement(bool isStmtExpr = false);
1541 StmtResult ParseCompoundStatement(bool isStmtExpr,
1542 unsigned ScopeFlags);
1543 StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
1544 bool ParseParenExprOrCondition(ExprResult &ExprResult,
1547 bool ConvertToBoolean);
1548 StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
1549 StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
1550 StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
1551 StmtResult ParseDoStatement();
1552 StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
1553 StmtResult ParseGotoStatement();
1554 StmtResult ParseContinueStatement();
1555 StmtResult ParseBreakStatement();
1556 StmtResult ParseReturnStatement();
1557 StmtResult ParseAsmStatement(bool &msAsm);
1558 StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
1560 /// \brief Describes the behavior that should be taken for an __if_exists
1562 enum IfExistsBehavior {
1563 /// \brief Parse the block; this code is always used.
1565 /// \brief Skip the block entirely; this code is never used.
1567 /// \brief Parse the block as a dependent block, which may be used in
1568 /// some template instantiations but not others.
1572 /// \brief Describes the condition of a Microsoft __if_exists or
1573 /// __if_not_exists block.
1574 struct IfExistsCondition {
1575 /// \brief The location of the initial keyword.
1576 SourceLocation KeywordLoc;
1577 /// \brief Whether this is an __if_exists block (rather than an
1578 /// __if_not_exists block).
1581 /// \brief Nested-name-specifier preceding the name.
1584 /// \brief The name we're looking for.
1587 /// \brief The behavior of this __if_exists or __if_not_exists block
1589 IfExistsBehavior Behavior;
1592 bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
1593 void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
1594 void ParseMicrosoftIfExistsExternalDeclaration();
1595 void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
1596 AccessSpecifier& CurAS);
1597 bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
1599 bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
1600 SmallVectorImpl<Expr *> &Constraints,
1601 SmallVectorImpl<Expr *> &Exprs);
1603 //===--------------------------------------------------------------------===//
1604 // C++ 6: Statements and Blocks
1606 StmtResult ParseCXXTryBlock();
1607 StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc);
1608 StmtResult ParseCXXCatchBlock();
1610 //===--------------------------------------------------------------------===//
1611 // MS: SEH Statements and Blocks
1613 StmtResult ParseSEHTryBlock();
1614 StmtResult ParseSEHTryBlockCommon(SourceLocation Loc);
1615 StmtResult ParseSEHExceptBlock(SourceLocation Loc);
1616 StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
1618 //===--------------------------------------------------------------------===//
1619 // Objective-C Statements
1621 StmtResult ParseObjCAtStatement(SourceLocation atLoc);
1622 StmtResult ParseObjCTryStmt(SourceLocation atLoc);
1623 StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
1624 StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
1625 StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
1628 //===--------------------------------------------------------------------===//
1629 // C99 6.7: Declarations.
1631 /// A context for parsing declaration specifiers. TODO: flesh this
1632 /// out, there are other significant restrictions on specifiers than
1633 /// would be best implemented in the parser.
1634 enum DeclSpecContext {
1635 DSC_normal, // normal context
1636 DSC_class, // class context, enables 'friend'
1637 DSC_type_specifier, // C++ type-specifier-seq
1638 DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
1639 DSC_top_level // top-level/namespace declaration context
1642 /// Information on a C++0x for-range-initializer found while parsing a
1643 /// declaration which turns out to be a for-range-declaration.
1644 struct ForRangeInit {
1645 SourceLocation ColonLoc;
1646 ExprResult RangeExpr;
1648 bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
1651 DeclGroupPtrTy ParseDeclaration(StmtVector &Stmts,
1652 unsigned Context, SourceLocation &DeclEnd,
1653 ParsedAttributesWithRange &attrs);
1654 DeclGroupPtrTy ParseSimpleDeclaration(StmtVector &Stmts,
1656 SourceLocation &DeclEnd,
1657 ParsedAttributes &attrs,
1659 ForRangeInit *FRI = 0);
1660 bool MightBeDeclarator(unsigned Context);
1661 DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, unsigned Context,
1662 bool AllowFunctionDefinitions,
1663 SourceLocation *DeclEnd = 0,
1664 ForRangeInit *FRI = 0);
1665 Decl *ParseDeclarationAfterDeclarator(Declarator &D,
1666 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
1667 bool ParseAsmAttributesAfterDeclarator(Declarator &D);
1668 Decl *ParseDeclarationAfterDeclaratorAndAttributes(Declarator &D,
1669 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
1670 Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
1671 Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
1673 /// \brief When in code-completion, skip parsing of the function/method body
1674 /// unless the body contains the code-completion point.
1676 /// \returns true if the function body was skipped.
1677 bool trySkippingFunctionBody();
1679 bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
1680 const ParsedTemplateInfo &TemplateInfo,
1681 AccessSpecifier AS, DeclSpecContext DSC);
1682 DeclSpecContext getDeclSpecContextFromDeclaratorContext(unsigned Context);
1683 void ParseDeclarationSpecifiers(DeclSpec &DS,
1684 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1685 AccessSpecifier AS = AS_none,
1686 DeclSpecContext DSC = DSC_normal,
1687 LateParsedAttrList *LateAttrs = 0);
1689 void ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS = AS_none,
1690 DeclSpecContext DSC = DSC_normal);
1692 void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
1693 Declarator::TheContext Context);
1695 void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
1696 const ParsedTemplateInfo &TemplateInfo,
1697 AccessSpecifier AS, DeclSpecContext DSC);
1698 void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
1699 void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType,
1702 struct FieldCallback {
1703 virtual Decl *invoke(FieldDeclarator &Field) = 0;
1704 virtual ~FieldCallback() {}
1707 virtual void _anchor();
1709 struct ObjCPropertyCallback;
1711 void ParseStructDeclaration(DeclSpec &DS, FieldCallback &Callback);
1713 bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
1714 bool isTypeSpecifierQualifier();
1715 bool isTypeQualifier() const;
1717 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
1718 /// is definitely a type-specifier. Return false if it isn't part of a type
1719 /// specifier or if we're not sure.
1720 bool isKnownToBeTypeSpecifier(const Token &Tok) const;
1722 /// isDeclarationStatement - Disambiguates between a declaration or an
1723 /// expression statement, when parsing function bodies.
1724 /// Returns true for declaration, false for expression.
1725 bool isDeclarationStatement() {
1726 if (getLangOpts().CPlusPlus)
1727 return isCXXDeclarationStatement();
1728 return isDeclarationSpecifier(true);
1731 /// isForInitDeclaration - Disambiguates between a declaration or an
1732 /// expression in the context of the C 'clause-1' or the C++
1733 // 'for-init-statement' part of a 'for' statement.
1734 /// Returns true for declaration, false for expression.
1735 bool isForInitDeclaration() {
1736 if (getLangOpts().CPlusPlus)
1737 return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
1738 return isDeclarationSpecifier(true);
1741 /// \brief Determine whether we are currently at the start of an Objective-C
1742 /// class message that appears to be missing the open bracket '['.
1743 bool isStartOfObjCClassMessageMissingOpenBracket();
1745 /// \brief Starting with a scope specifier, identifier, or
1746 /// template-id that refers to the current class, determine whether
1747 /// this is a constructor declarator.
1748 bool isConstructorDeclarator();
1750 /// \brief Specifies the context in which type-id/expression
1751 /// disambiguation will occur.
1752 enum TentativeCXXTypeIdContext {
1754 TypeIdAsTemplateArgument
1758 /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
1759 /// whether the parens contain an expression or a type-id.
1760 /// Returns true for a type-id and false for an expression.
1761 bool isTypeIdInParens(bool &isAmbiguous) {
1762 if (getLangOpts().CPlusPlus)
1763 return isCXXTypeId(TypeIdInParens, isAmbiguous);
1764 isAmbiguous = false;
1765 return isTypeSpecifierQualifier();
1767 bool isTypeIdInParens() {
1769 return isTypeIdInParens(isAmbiguous);
1772 /// isCXXDeclarationStatement - C++-specialized function that disambiguates
1773 /// between a declaration or an expression statement, when parsing function
1774 /// bodies. Returns true for declaration, false for expression.
1775 bool isCXXDeclarationStatement();
1777 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
1778 /// between a simple-declaration or an expression-statement.
1779 /// If during the disambiguation process a parsing error is encountered,
1780 /// the function returns true to let the declaration parsing code handle it.
1781 /// Returns false if the statement is disambiguated as expression.
1782 bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
1784 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
1785 /// a constructor-style initializer, when parsing declaration statements.
1786 /// Returns true for function declarator and false for constructor-style
1787 /// initializer. If 'warnIfAmbiguous' is true a warning will be emitted to
1788 /// indicate that the parens were disambiguated as function declarator.
1789 /// If during the disambiguation process a parsing error is encountered,
1790 /// the function returns true to let the declaration parsing code handle it.
1791 bool isCXXFunctionDeclarator(bool warnIfAmbiguous);
1793 /// isCXXConditionDeclaration - Disambiguates between a declaration or an
1794 /// expression for a condition of a if/switch/while/for statement.
1795 /// If during the disambiguation process a parsing error is encountered,
1796 /// the function returns true to let the declaration parsing code handle it.
1797 bool isCXXConditionDeclaration();
1799 bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
1800 bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
1802 return isCXXTypeId(Context, isAmbiguous);
1805 /// TPResult - Used as the result value for functions whose purpose is to
1806 /// disambiguate C++ constructs by "tentatively parsing" them.
1807 /// This is a class instead of a simple enum because the implicit enum-to-bool
1808 /// conversions may cause subtle bugs.
1817 TPResult(Result result) : Res(result) {}
1819 static TPResult True() { return TPR_true; }
1820 static TPResult False() { return TPR_false; }
1821 static TPResult Ambiguous() { return TPR_ambiguous; }
1822 static TPResult Error() { return TPR_error; }
1824 bool operator==(const TPResult &RHS) const { return Res == RHS.Res; }
1825 bool operator!=(const TPResult &RHS) const { return Res != RHS.Res; }
1828 /// \brief Based only on the given token kind, determine whether we know that
1829 /// we're at the start of an expression or a type-specifier-seq (which may
1830 /// be an expression, in C++).
1832 /// This routine does not attempt to resolve any of the trick cases, e.g.,
1833 /// those involving lookup of identifiers.
1835 /// \returns \c TPR_true if this token starts an expression, \c TPR_false if
1836 /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot
1838 TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind);
1840 /// isCXXDeclarationSpecifier - Returns TPResult::True() if it is a
1841 /// declaration specifier, TPResult::False() if it is not,
1842 /// TPResult::Ambiguous() if it could be either a decl-specifier or a
1843 /// function-style cast, and TPResult::Error() if a parsing error was
1844 /// encountered. If it could be a braced C++11 function-style cast, returns
1845 /// BracedCastResult.
1846 /// Doesn't consume tokens.
1848 isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False());
1850 // "Tentative parsing" functions, used for disambiguation. If a parsing error
1851 // is encountered they will return TPResult::Error().
1852 // Returning TPResult::True()/False() indicates that the ambiguity was
1853 // resolved and tentative parsing may stop. TPResult::Ambiguous() indicates
1854 // that more tentative parsing is necessary for disambiguation.
1855 // They all consume tokens, so backtracking should be used after calling them.
1857 TPResult TryParseDeclarationSpecifier();
1858 TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
1859 TPResult TryParseTypeofSpecifier();
1860 TPResult TryParseProtocolQualifiers();
1861 TPResult TryParseInitDeclaratorList();
1862 TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier=true);
1863 TPResult TryParseParameterDeclarationClause();
1864 TPResult TryParseFunctionDeclarator();
1865 TPResult TryParseBracketDeclarator();
1867 TypeResult ParseTypeName(SourceRange *Range = 0,
1868 Declarator::TheContext Context
1869 = Declarator::TypeNameContext,
1870 AccessSpecifier AS = AS_none,
1871 Decl **OwnedType = 0);
1872 void ParseBlockId();
1874 // Check for the start of a C++11 attribute-specifier-seq in a context where
1875 // an attribute is not allowed.
1876 bool CheckProhibitedCXX11Attribute() {
1877 assert(Tok.is(tok::l_square));
1878 if (!getLangOpts().CPlusPlus0x || NextToken().isNot(tok::l_square))
1880 return DiagnoseProhibitedCXX11Attribute();
1882 bool DiagnoseProhibitedCXX11Attribute();
1884 void ProhibitAttributes(ParsedAttributesWithRange &attrs) {
1885 if (!attrs.Range.isValid()) return;
1886 DiagnoseProhibitedAttributes(attrs);
1889 void DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs);
1891 void MaybeParseGNUAttributes(Declarator &D,
1892 LateParsedAttrList *LateAttrs = 0) {
1893 if (Tok.is(tok::kw___attribute)) {
1894 ParsedAttributes attrs(AttrFactory);
1895 SourceLocation endLoc;
1896 ParseGNUAttributes(attrs, &endLoc, LateAttrs);
1897 D.takeAttributes(attrs, endLoc);
1900 void MaybeParseGNUAttributes(ParsedAttributes &attrs,
1901 SourceLocation *endLoc = 0,
1902 LateParsedAttrList *LateAttrs = 0) {
1903 if (Tok.is(tok::kw___attribute))
1904 ParseGNUAttributes(attrs, endLoc, LateAttrs);
1906 void ParseGNUAttributes(ParsedAttributes &attrs,
1907 SourceLocation *endLoc = 0,
1908 LateParsedAttrList *LateAttrs = 0);
1909 void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
1910 SourceLocation AttrNameLoc,
1911 ParsedAttributes &Attrs,
1912 SourceLocation *EndLoc);
1914 void MaybeParseCXX0XAttributes(Declarator &D) {
1915 if (getLangOpts().CPlusPlus0x && isCXX11AttributeSpecifier()) {
1916 ParsedAttributesWithRange attrs(AttrFactory);
1917 SourceLocation endLoc;
1918 ParseCXX11Attributes(attrs, &endLoc);
1919 D.takeAttributes(attrs, endLoc);
1922 void MaybeParseCXX0XAttributes(ParsedAttributes &attrs,
1923 SourceLocation *endLoc = 0) {
1924 if (getLangOpts().CPlusPlus0x && isCXX11AttributeSpecifier()) {
1925 ParsedAttributesWithRange attrsWithRange(AttrFactory);
1926 ParseCXX11Attributes(attrsWithRange, endLoc);
1927 attrs.takeAllFrom(attrsWithRange);
1930 void MaybeParseCXX0XAttributes(ParsedAttributesWithRange &attrs,
1931 SourceLocation *endLoc = 0,
1932 bool OuterMightBeMessageSend = false) {
1933 if (getLangOpts().CPlusPlus0x &&
1934 isCXX11AttributeSpecifier(false, OuterMightBeMessageSend))
1935 ParseCXX11Attributes(attrs, endLoc);
1938 void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
1939 SourceLocation *EndLoc = 0);
1940 void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
1941 SourceLocation *EndLoc = 0);
1942 IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc);
1944 void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
1945 SourceLocation *endLoc = 0) {
1946 if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
1947 ParseMicrosoftAttributes(attrs, endLoc);
1949 void ParseMicrosoftAttributes(ParsedAttributes &attrs,
1950 SourceLocation *endLoc = 0);
1951 void ParseMicrosoftDeclSpec(ParsedAttributes &attrs);
1952 void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
1953 void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
1954 void ParseOpenCLAttributes(ParsedAttributes &attrs);
1955 void ParseOpenCLQualifiers(DeclSpec &DS);
1957 VersionTuple ParseVersionTuple(SourceRange &Range);
1958 void ParseAvailabilityAttribute(IdentifierInfo &Availability,
1959 SourceLocation AvailabilityLoc,
1960 ParsedAttributes &attrs,
1961 SourceLocation *endLoc);
1963 bool IsThreadSafetyAttribute(llvm::StringRef AttrName);
1964 void ParseThreadSafetyAttribute(IdentifierInfo &AttrName,
1965 SourceLocation AttrNameLoc,
1966 ParsedAttributes &Attrs,
1967 SourceLocation *EndLoc);
1970 void ParseTypeofSpecifier(DeclSpec &DS);
1971 SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
1972 void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
1973 SourceLocation StartLoc,
1974 SourceLocation EndLoc);
1975 void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
1976 void ParseAtomicSpecifier(DeclSpec &DS);
1978 ExprResult ParseAlignArgument(SourceLocation Start,
1979 SourceLocation &EllipsisLoc);
1980 void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
1981 SourceLocation *endLoc = 0);
1983 VirtSpecifiers::Specifier isCXX0XVirtSpecifier(const Token &Tok) const;
1984 VirtSpecifiers::Specifier isCXX0XVirtSpecifier() const {
1985 return isCXX0XVirtSpecifier(Tok);
1987 void ParseOptionalCXX0XVirtSpecifierSeq(VirtSpecifiers &VS);
1989 bool isCXX0XFinalKeyword() const;
1991 /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
1992 /// enter a new C++ declarator scope and exit it when the function is
1994 class DeclaratorScopeObj {
2000 DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
2001 : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
2003 void EnterDeclaratorScope() {
2004 assert(!EnteredScope && "Already entered the scope!");
2005 assert(SS.isSet() && "C++ scope was not set!");
2007 CreatedScope = true;
2008 P.EnterScope(0); // Not a decl scope.
2010 if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
2011 EnteredScope = true;
2014 ~DeclaratorScopeObj() {
2016 assert(SS.isSet() && "C++ scope was cleared ?");
2017 P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
2024 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
2025 void ParseDeclarator(Declarator &D);
2026 /// A function that parses a variant of direct-declarator.
2027 typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
2028 void ParseDeclaratorInternal(Declarator &D,
2029 DirectDeclParseFunction DirectDeclParser);
2031 void ParseTypeQualifierListOpt(DeclSpec &DS, bool GNUAttributesAllowed = true,
2032 bool CXX0XAttributesAllowed = true);
2033 void ParseDirectDeclarator(Declarator &D);
2034 void ParseParenDeclarator(Declarator &D);
2035 void ParseFunctionDeclarator(Declarator &D,
2036 ParsedAttributes &attrs,
2037 BalancedDelimiterTracker &Tracker,
2038 bool RequiresArg = false);
2039 bool isFunctionDeclaratorIdentifierList();
2040 void ParseFunctionDeclaratorIdentifierList(
2042 SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo);
2043 void ParseParameterDeclarationClause(
2045 ParsedAttributes &attrs,
2046 SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo,
2047 SourceLocation &EllipsisLoc);
2048 void ParseBracketDeclarator(Declarator &D);
2050 //===--------------------------------------------------------------------===//
2051 // C++ 7: Declarations [dcl.dcl]
2053 /// The kind of attribute specifier we have found.
2054 enum CXX11AttributeKind {
2055 /// This is not an attribute specifier.
2056 CAK_NotAttributeSpecifier,
2057 /// This should be treated as an attribute-specifier.
2058 CAK_AttributeSpecifier,
2059 /// The next tokens are '[[', but this is not an attribute-specifier. This
2060 /// is ill-formed by C++11 [dcl.attr.grammar]p6.
2061 CAK_InvalidAttributeSpecifier
2064 isCXX11AttributeSpecifier(bool Disambiguate = false,
2065 bool OuterMightBeMessageSend = false);
2067 Decl *ParseNamespace(unsigned Context, SourceLocation &DeclEnd,
2068 SourceLocation InlineLoc = SourceLocation());
2069 void ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc,
2070 std::vector<IdentifierInfo*>& Ident,
2071 std::vector<SourceLocation>& NamespaceLoc,
2072 unsigned int index, SourceLocation& InlineLoc,
2073 ParsedAttributes& attrs,
2074 BalancedDelimiterTracker &Tracker);
2075 Decl *ParseLinkage(ParsingDeclSpec &DS, unsigned Context);
2076 Decl *ParseUsingDirectiveOrDeclaration(unsigned Context,
2077 const ParsedTemplateInfo &TemplateInfo,
2078 SourceLocation &DeclEnd,
2079 ParsedAttributesWithRange &attrs,
2080 Decl **OwnedType = 0);
2081 Decl *ParseUsingDirective(unsigned Context,
2082 SourceLocation UsingLoc,
2083 SourceLocation &DeclEnd,
2084 ParsedAttributes &attrs);
2085 Decl *ParseUsingDeclaration(unsigned Context,
2086 const ParsedTemplateInfo &TemplateInfo,
2087 SourceLocation UsingLoc,
2088 SourceLocation &DeclEnd,
2089 AccessSpecifier AS = AS_none,
2090 Decl **OwnedType = 0);
2091 Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
2092 Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
2093 SourceLocation AliasLoc, IdentifierInfo *Alias,
2094 SourceLocation &DeclEnd);
2096 //===--------------------------------------------------------------------===//
2097 // C++ 9: classes [class] and C structs/unions.
2098 void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
2099 DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo,
2100 AccessSpecifier AS, bool EnteringContext,
2101 DeclSpecContext DSC);
2102 void ParseCXXMemberSpecification(SourceLocation StartLoc, unsigned TagType,
2104 ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2105 SourceLocation &EqualLoc);
2106 void ParseCXXClassMemberDeclaration(AccessSpecifier AS, AttributeList *Attr,
2107 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2108 ParsingDeclRAIIObject *DiagsFromTParams = 0);
2109 void ParseConstructorInitializer(Decl *ConstructorDecl);
2110 MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
2111 void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2114 //===--------------------------------------------------------------------===//
2115 // C++ 10: Derived classes [class.derived]
2116 TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
2117 SourceLocation &EndLocation);
2118 void ParseBaseClause(Decl *ClassDecl);
2119 BaseResult ParseBaseSpecifier(Decl *ClassDecl);
2120 AccessSpecifier getAccessSpecifierIfPresent() const;
2122 bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
2123 SourceLocation TemplateKWLoc,
2124 IdentifierInfo *Name,
2125 SourceLocation NameLoc,
2126 bool EnteringContext,
2127 ParsedType ObjectType,
2129 bool AssumeTemplateId);
2130 bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2131 ParsedType ObjectType,
2132 UnqualifiedId &Result);
2133 bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2134 bool AllowDestructorName,
2135 bool AllowConstructorName,
2136 ParsedType ObjectType,
2137 SourceLocation& TemplateKWLoc,
2138 UnqualifiedId &Result);
2140 //===--------------------------------------------------------------------===//
2141 // C++ 14: Templates [temp]
2143 // C++ 14.1: Template Parameters [temp.param]
2144 Decl *ParseDeclarationStartingWithTemplate(unsigned Context,
2145 SourceLocation &DeclEnd,
2146 AccessSpecifier AS = AS_none,
2147 AttributeList *AccessAttrs = 0);
2148 Decl *ParseTemplateDeclarationOrSpecialization(unsigned Context,
2149 SourceLocation &DeclEnd,
2151 AttributeList *AccessAttrs);
2152 Decl *ParseSingleDeclarationAfterTemplate(
2154 const ParsedTemplateInfo &TemplateInfo,
2155 ParsingDeclRAIIObject &DiagsFromParams,
2156 SourceLocation &DeclEnd,
2157 AccessSpecifier AS=AS_none,
2158 AttributeList *AccessAttrs = 0);
2159 bool ParseTemplateParameters(unsigned Depth,
2160 SmallVectorImpl<Decl*> &TemplateParams,
2161 SourceLocation &LAngleLoc,
2162 SourceLocation &RAngleLoc);
2163 bool ParseTemplateParameterList(unsigned Depth,
2164 SmallVectorImpl<Decl*> &TemplateParams);
2165 bool isStartOfTemplateTypeParameter();
2166 Decl *ParseTemplateParameter(unsigned Depth, unsigned Position);
2167 Decl *ParseTypeParameter(unsigned Depth, unsigned Position);
2168 Decl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
2169 Decl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
2170 // C++ 14.3: Template arguments [temp.arg]
2171 typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
2173 bool ParseTemplateIdAfterTemplateName(TemplateTy Template,
2174 SourceLocation TemplateNameLoc,
2175 const CXXScopeSpec &SS,
2176 bool ConsumeLastToken,
2177 SourceLocation &LAngleLoc,
2178 TemplateArgList &TemplateArgs,
2179 SourceLocation &RAngleLoc);
2181 bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
2183 SourceLocation TemplateKWLoc,
2184 UnqualifiedId &TemplateName,
2185 bool AllowTypeAnnotation = true);
2186 void AnnotateTemplateIdTokenAsType();
2187 bool IsTemplateArgumentList(unsigned Skip = 0);
2188 bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
2189 ParsedTemplateArgument ParseTemplateTemplateArgument();
2190 ParsedTemplateArgument ParseTemplateArgument();
2191 Decl *ParseExplicitInstantiation(unsigned Context,
2192 SourceLocation ExternLoc,
2193 SourceLocation TemplateLoc,
2194 SourceLocation &DeclEnd,
2195 AccessSpecifier AS = AS_none);
2197 //===--------------------------------------------------------------------===//
2199 DeclGroupPtrTy ParseModuleImport(SourceLocation AtLoc);
2201 //===--------------------------------------------------------------------===//
2202 // GNU G++: Type Traits [Type-Traits.html in the GCC manual]
2203 ExprResult ParseUnaryTypeTrait();
2204 ExprResult ParseBinaryTypeTrait();
2205 ExprResult ParseTypeTrait();
2207 //===--------------------------------------------------------------------===//
2208 // Embarcadero: Arary and Expression Traits
2209 ExprResult ParseArrayTypeTrait();
2210 ExprResult ParseExpressionTrait();
2212 //===--------------------------------------------------------------------===//
2213 // Preprocessor code-completion pass-through
2214 virtual void CodeCompleteDirective(bool InConditional);
2215 virtual void CodeCompleteInConditionalExclusion();
2216 virtual void CodeCompleteMacroName(bool IsDefinition);
2217 virtual void CodeCompletePreprocessorExpression();
2218 virtual void CodeCompleteMacroArgument(IdentifierInfo *Macro,
2219 MacroInfo *MacroInfo,
2220 unsigned ArgumentIndex);
2221 virtual void CodeCompleteNaturalLanguage();
2224 } // end namespace clang