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"
26 #include "llvm/Support/SaveAndRestore.h"
32 class BalancedDelimiterTracker;
33 class CorrectionCandidateCallback;
35 class DiagnosticBuilder;
37 class ParsingDeclRAIIObject;
38 class ParsingDeclSpec;
39 class ParsingDeclarator;
40 class ParsingFieldDeclarator;
41 class PragmaUnusedHandler;
42 class ColonProtectionRAIIObject;
43 class InMessageExpressionRAIIObject;
44 class PoisonSEHIdentifiersRAIIObject;
47 /// PrettyStackTraceParserEntry - If a crash happens while the parser is active,
48 /// an entry is printed for it.
49 class PrettyStackTraceParserEntry : public llvm::PrettyStackTraceEntry {
52 PrettyStackTraceParserEntry(const Parser &p) : P(p) {}
53 virtual void print(raw_ostream &OS) const;
56 /// PrecedenceLevels - These are precedences for the binary/ternary
57 /// operators in the C99 grammar. These have been named to relate
58 /// with the C99 grammar productions. Low precedences numbers bind
59 /// more weakly than high numbers.
62 Unknown = 0, // Not binary operator.
64 Assignment = 2, // =, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |=
71 Equality = 9, // ==, !=
72 Relational = 10, // >=, <=, >, <
74 Additive = 12, // -, +
75 Multiplicative = 13, // *, /, %
76 PointerToMember = 14 // .*, ->*
80 /// Parser - This implements a parser for the C family of languages. After
81 /// parsing units of the grammar, productions are invoked to handle whatever has
84 class Parser : public CodeCompletionHandler {
85 friend class PragmaUnusedHandler;
86 friend class ColonProtectionRAIIObject;
87 friend class InMessageExpressionRAIIObject;
88 friend class PoisonSEHIdentifiersRAIIObject;
89 friend class ObjCDeclContextSwitch;
90 friend class ParenBraceBracketBalancer;
91 friend class BalancedDelimiterTracker;
95 /// Tok - The current token we are peeking ahead. All parsing methods assume
96 /// that this is valid.
99 // PrevTokLocation - The location of the token we previously
100 // consumed. This token is used for diagnostics where we expected to
101 // see a token following another token (e.g., the ';' at the end of
103 SourceLocation PrevTokLocation;
105 unsigned short ParenCount, BracketCount, BraceCount;
107 /// Actions - These are the callbacks we invoke as we parse various constructs
111 DiagnosticsEngine &Diags;
113 /// ScopeCache - Cache scopes to reduce malloc traffic.
114 enum { ScopeCacheSize = 16 };
115 unsigned NumCachedScopes;
116 Scope *ScopeCache[ScopeCacheSize];
118 /// Identifiers used for SEH handling in Borland. These are only
119 /// allowed in particular circumstances
121 IdentifierInfo *Ident__exception_code,
122 *Ident___exception_code,
123 *Ident_GetExceptionCode;
124 // __except filter expression
125 IdentifierInfo *Ident__exception_info,
126 *Ident___exception_info,
127 *Ident_GetExceptionInfo;
129 IdentifierInfo *Ident__abnormal_termination,
130 *Ident___abnormal_termination,
131 *Ident_AbnormalTermination;
133 /// Contextual keywords for Microsoft extensions.
134 IdentifierInfo *Ident__except;
136 /// Ident_super - IdentifierInfo for "super", to support fast
138 IdentifierInfo *Ident_super;
139 /// Ident_vector and Ident_pixel - cached IdentifierInfo's for
140 /// "vector" and "pixel" fast comparison. Only present if
142 IdentifierInfo *Ident_vector;
143 IdentifierInfo *Ident_pixel;
145 /// Objective-C contextual keywords.
146 mutable IdentifierInfo *Ident_instancetype;
148 /// \brief Identifier for "introduced".
149 IdentifierInfo *Ident_introduced;
151 /// \brief Identifier for "deprecated".
152 IdentifierInfo *Ident_deprecated;
154 /// \brief Identifier for "obsoleted".
155 IdentifierInfo *Ident_obsoleted;
157 /// \brief Identifier for "unavailable".
158 IdentifierInfo *Ident_unavailable;
160 /// \brief Identifier for "message".
161 IdentifierInfo *Ident_message;
163 /// C++0x contextual keywords.
164 mutable IdentifierInfo *Ident_final;
165 mutable IdentifierInfo *Ident_override;
167 // C++ type trait keywords that have can be reverted to identifiers and
168 // still used as type traits.
169 llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertableTypeTraits;
171 OwningPtr<PragmaHandler> AlignHandler;
172 OwningPtr<PragmaHandler> GCCVisibilityHandler;
173 OwningPtr<PragmaHandler> OptionsHandler;
174 OwningPtr<PragmaHandler> PackHandler;
175 OwningPtr<PragmaHandler> MSStructHandler;
176 OwningPtr<PragmaHandler> UnusedHandler;
177 OwningPtr<PragmaHandler> WeakHandler;
178 OwningPtr<PragmaHandler> RedefineExtnameHandler;
179 OwningPtr<PragmaHandler> FPContractHandler;
180 OwningPtr<PragmaHandler> OpenCLExtensionHandler;
181 OwningPtr<CommentHandler> CommentSemaHandler;
183 /// Whether the '>' token acts as an operator or not. This will be
184 /// true except when we are parsing an expression within a C++
185 /// template argument list, where the '>' closes the template
187 bool GreaterThanIsOperator;
189 /// ColonIsSacred - When this is false, we aggressively try to recover from
190 /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not
191 /// safe in case statements and a few other things. This is managed by the
192 /// ColonProtectionRAIIObject RAII object.
195 /// \brief When true, we are directly inside an Objective-C messsage
198 /// This is managed by the \c InMessageExpressionRAIIObject class, and
199 /// should not be set directly.
200 bool InMessageExpression;
202 /// The "depth" of the template parameters currently being parsed.
203 unsigned TemplateParameterDepth;
205 /// Factory object for creating AttributeList objects.
206 AttributeFactory AttrFactory;
208 /// \brief Gathers and cleans up TemplateIdAnnotations when parsing of a
209 /// top-level declaration is finished.
210 SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
212 /// \brief Identifiers which have been declared within a tentative parse.
213 SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers;
215 IdentifierInfo *getSEHExceptKeyword();
217 /// True if we are within an Objective-C container while parsing C-like decls.
219 /// This is necessary because Sema thinks we have left the container
220 /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will
222 bool ParsingInObjCContainer;
224 bool SkipFunctionBodies;
227 Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
230 const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
231 const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
232 Preprocessor &getPreprocessor() const { return PP; }
233 Sema &getActions() const { return Actions; }
234 AttributeFactory &getAttrFactory() { return AttrFactory; }
236 const Token &getCurToken() const { return Tok; }
237 Scope *getCurScope() const { return Actions.getCurScope(); }
239 Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); }
241 // Type forwarding. All of these are statically 'void*', but they may all be
242 // different actual classes based on the actions in place.
243 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
244 typedef OpaquePtr<TemplateName> TemplateTy;
246 typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists;
248 typedef clang::ExprResult ExprResult;
249 typedef clang::StmtResult StmtResult;
250 typedef clang::BaseResult BaseResult;
251 typedef clang::MemInitResult MemInitResult;
252 typedef clang::TypeResult TypeResult;
254 typedef Expr *ExprArg;
255 typedef llvm::MutableArrayRef<Stmt*> MultiStmtArg;
256 typedef Sema::FullExprArg FullExprArg;
258 /// Adorns a ExprResult with Actions to make it an ExprResult
259 ExprResult Owned(ExprResult res) {
260 return ExprResult(res);
262 /// Adorns a StmtResult with Actions to make it an StmtResult
263 StmtResult Owned(StmtResult res) {
264 return StmtResult(res);
267 ExprResult ExprError() { return ExprResult(true); }
268 StmtResult StmtError() { return StmtResult(true); }
270 ExprResult ExprError(const DiagnosticBuilder &) { return ExprError(); }
271 StmtResult StmtError(const DiagnosticBuilder &) { return StmtError(); }
273 ExprResult ExprEmpty() { return ExprResult(false); }
277 /// ParseTranslationUnit - All in one method that initializes parses, and
278 /// shuts down the parser.
279 void ParseTranslationUnit();
281 /// Initialize - Warm up the parser.
285 /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if
286 /// the EOF was encountered.
287 bool ParseTopLevelDecl(DeclGroupPtrTy &Result);
289 /// ConsumeToken - Consume the current 'peek token' and lex the next one.
290 /// This does not work with all kinds of tokens: strings and specific other
291 /// tokens must be consumed with custom methods below. This returns the
292 /// location of the consumed token.
293 SourceLocation ConsumeToken() {
294 assert(!isTokenStringLiteral() && !isTokenParen() && !isTokenBracket() &&
296 "Should consume special tokens with Consume*Token");
298 if (Tok.is(tok::code_completion))
299 return handleUnexpectedCodeCompletionToken();
301 PrevTokLocation = Tok.getLocation();
303 return PrevTokLocation;
307 //===--------------------------------------------------------------------===//
308 // Low-Level token peeking and consumption methods.
311 /// isTokenParen - Return true if the cur token is '(' or ')'.
312 bool isTokenParen() const {
313 return Tok.getKind() == tok::l_paren || Tok.getKind() == tok::r_paren;
315 /// isTokenBracket - Return true if the cur token is '[' or ']'.
316 bool isTokenBracket() const {
317 return Tok.getKind() == tok::l_square || Tok.getKind() == tok::r_square;
319 /// isTokenBrace - Return true if the cur token is '{' or '}'.
320 bool isTokenBrace() const {
321 return Tok.getKind() == tok::l_brace || Tok.getKind() == tok::r_brace;
324 /// isTokenStringLiteral - True if this token is a string-literal.
326 bool isTokenStringLiteral() const {
327 return Tok.getKind() == tok::string_literal ||
328 Tok.getKind() == tok::wide_string_literal ||
329 Tok.getKind() == tok::utf8_string_literal ||
330 Tok.getKind() == tok::utf16_string_literal ||
331 Tok.getKind() == tok::utf32_string_literal;
334 /// \brief Returns true if the current token is '=' or is a type of '='.
335 /// For typos, give a fixit to '='
336 bool isTokenEqualOrEqualTypo();
338 /// ConsumeAnyToken - Dispatch to the right Consume* method based on the
339 /// current token type. This should only be used in cases where the type of
340 /// the token really isn't known, e.g. in error recovery.
341 SourceLocation ConsumeAnyToken() {
343 return ConsumeParen();
344 else if (isTokenBracket())
345 return ConsumeBracket();
346 else if (isTokenBrace())
347 return ConsumeBrace();
348 else if (isTokenStringLiteral())
349 return ConsumeStringToken();
351 return ConsumeToken();
354 /// ConsumeParen - This consume method keeps the paren count up-to-date.
356 SourceLocation ConsumeParen() {
357 assert(isTokenParen() && "wrong consume method");
358 if (Tok.getKind() == tok::l_paren)
361 --ParenCount; // Don't let unbalanced )'s drive the count negative.
362 PrevTokLocation = Tok.getLocation();
364 return PrevTokLocation;
367 /// ConsumeBracket - This consume method keeps the bracket count up-to-date.
369 SourceLocation ConsumeBracket() {
370 assert(isTokenBracket() && "wrong consume method");
371 if (Tok.getKind() == tok::l_square)
373 else if (BracketCount)
374 --BracketCount; // Don't let unbalanced ]'s drive the count negative.
376 PrevTokLocation = Tok.getLocation();
378 return PrevTokLocation;
381 /// ConsumeBrace - This consume method keeps the brace count up-to-date.
383 SourceLocation ConsumeBrace() {
384 assert(isTokenBrace() && "wrong consume method");
385 if (Tok.getKind() == tok::l_brace)
388 --BraceCount; // Don't let unbalanced }'s drive the count negative.
390 PrevTokLocation = Tok.getLocation();
392 return PrevTokLocation;
395 /// ConsumeStringToken - Consume the current 'peek token', lexing a new one
396 /// and returning the token kind. This method is specific to strings, as it
397 /// handles string literal concatenation, as per C99 5.1.1.2, translation
399 SourceLocation ConsumeStringToken() {
400 assert(isTokenStringLiteral() &&
401 "Should only consume string literals with this method");
402 PrevTokLocation = Tok.getLocation();
404 return PrevTokLocation;
407 /// \brief Consume the current code-completion token.
409 /// This routine should be called to consume the code-completion token once
410 /// a code-completion action has already been invoked.
411 SourceLocation ConsumeCodeCompletionToken() {
412 assert(Tok.is(tok::code_completion));
413 PrevTokLocation = Tok.getLocation();
415 return PrevTokLocation;
418 ///\ brief When we are consuming a code-completion token without having
419 /// matched specific position in the grammar, provide code-completion results
420 /// based on context.
422 /// \returns the source location of the code-completion token.
423 SourceLocation handleUnexpectedCodeCompletionToken();
425 /// \brief Abruptly cut off parsing; mainly used when we have reached the
426 /// code-completion point.
427 void cutOffParsing() {
428 PP.setCodeCompletionReached();
429 // Cut off parsing by acting as if we reached the end-of-file.
430 Tok.setKind(tok::eof);
433 /// \brief Handle the annotation token produced for #pragma unused(...)
434 void HandlePragmaUnused();
436 /// \brief Handle the annotation token produced for
437 /// #pragma GCC visibility...
438 void HandlePragmaVisibility();
440 /// \brief Handle the annotation token produced for
442 void HandlePragmaPack();
444 /// \brief Handle the annotation token produced for
445 /// #pragma ms_struct...
446 void HandlePragmaMSStruct();
448 /// \brief Handle the annotation token produced for
450 void HandlePragmaAlign();
452 /// \brief Handle the annotation token produced for
453 /// #pragma weak id...
454 void HandlePragmaWeak();
456 /// \brief Handle the annotation token produced for
457 /// #pragma weak id = id...
458 void HandlePragmaWeakAlias();
460 /// \brief Handle the annotation token produced for
461 /// #pragma redefine_extname...
462 void HandlePragmaRedefineExtname();
464 /// \brief Handle the annotation token produced for
465 /// #pragma STDC FP_CONTRACT...
466 void HandlePragmaFPContract();
468 /// \brief Handle the annotation token produced for
469 /// #pragma OPENCL EXTENSION...
470 void HandlePragmaOpenCLExtension();
472 /// GetLookAheadToken - This peeks ahead N tokens and returns that token
473 /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1)
474 /// returns the token after Tok, etc.
476 /// Note that this differs from the Preprocessor's LookAhead method, because
477 /// the Parser always has one token lexed that the preprocessor doesn't.
479 const Token &GetLookAheadToken(unsigned N) {
480 if (N == 0 || Tok.is(tok::eof)) return Tok;
481 return PP.LookAhead(N-1);
485 /// NextToken - This peeks ahead one token and returns it without
487 const Token &NextToken() {
488 return PP.LookAhead(0);
491 /// getTypeAnnotation - Read a parsed type out of an annotation token.
492 static ParsedType getTypeAnnotation(Token &Tok) {
493 return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
497 static void setTypeAnnotation(Token &Tok, ParsedType T) {
498 Tok.setAnnotationValue(T.getAsOpaquePtr());
501 /// \brief Read an already-translated primary expression out of an annotation
503 static ExprResult getExprAnnotation(Token &Tok) {
504 if (Tok.getAnnotationValue())
505 return ExprResult((Expr *)Tok.getAnnotationValue());
507 return ExprResult(true);
510 /// \brief Set the primary expression corresponding to the given annotation
512 static void setExprAnnotation(Token &Tok, ExprResult ER) {
514 Tok.setAnnotationValue(0);
516 Tok.setAnnotationValue(ER.get());
520 // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to
521 // find a type name by attempting typo correction.
522 bool TryAnnotateTypeOrScopeToken(bool EnteringContext = false,
523 bool NeedType = false);
524 bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext,
528 bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
531 enum AnnotatedNameKind {
532 /// Annotation has failed and emitted an error.
534 /// The identifier is a tentatively-declared name.
536 /// The identifier is a template name. FIXME: Add an annotation for that.
538 /// The identifier can't be resolved.
540 /// Annotation was successful.
543 AnnotatedNameKind TryAnnotateName(bool IsAddressOfOperand,
544 CorrectionCandidateCallback *CCC = 0);
546 /// Push a tok::annot_cxxscope token onto the token stream.
547 void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
549 /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
550 /// replacing them with the non-context-sensitive keywords. This returns
551 /// true if the token was replaced.
552 bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
553 const char *&PrevSpec, unsigned &DiagID,
555 if (!getLangOpts().AltiVec ||
556 (Tok.getIdentifierInfo() != Ident_vector &&
557 Tok.getIdentifierInfo() != Ident_pixel))
560 return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
563 /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
564 /// identifier token, replacing it with the non-context-sensitive __vector.
565 /// This returns true if the token was replaced.
566 bool TryAltiVecVectorToken() {
567 if (!getLangOpts().AltiVec ||
568 Tok.getIdentifierInfo() != Ident_vector) return false;
569 return TryAltiVecVectorTokenOutOfLine();
572 bool TryAltiVecVectorTokenOutOfLine();
573 bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
574 const char *&PrevSpec, unsigned &DiagID,
577 /// \brief Get the TemplateIdAnnotation from the token.
578 TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
580 /// TentativeParsingAction - An object that is used as a kind of "tentative
581 /// parsing transaction". It gets instantiated to mark the token position and
582 /// after the token consumption is done, Commit() or Revert() is called to
583 /// either "commit the consumed tokens" or revert to the previously marked
584 /// token position. Example:
586 /// TentativeParsingAction TPA(*this);
591 class TentativeParsingAction {
594 size_t PrevTentativelyDeclaredIdentifierCount;
595 unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
599 explicit TentativeParsingAction(Parser& p) : P(p) {
601 PrevTentativelyDeclaredIdentifierCount =
602 P.TentativelyDeclaredIdentifiers.size();
603 PrevParenCount = P.ParenCount;
604 PrevBracketCount = P.BracketCount;
605 PrevBraceCount = P.BraceCount;
606 P.PP.EnableBacktrackAtThisPos();
610 assert(isActive && "Parsing action was finished!");
611 P.TentativelyDeclaredIdentifiers.resize(
612 PrevTentativelyDeclaredIdentifierCount);
613 P.PP.CommitBacktrackedTokens();
617 assert(isActive && "Parsing action was finished!");
620 P.TentativelyDeclaredIdentifiers.resize(
621 PrevTentativelyDeclaredIdentifierCount);
622 P.ParenCount = PrevParenCount;
623 P.BracketCount = PrevBracketCount;
624 P.BraceCount = PrevBraceCount;
627 ~TentativeParsingAction() {
628 assert(!isActive && "Forgot to call Commit or Revert!");
632 /// ObjCDeclContextSwitch - An object used to switch context from
633 /// an objective-c decl context to its enclosing decl context and
635 class ObjCDeclContextSwitch {
638 SaveAndRestore<bool> WithinObjCContainer;
640 explicit ObjCDeclContextSwitch(Parser &p)
641 : P(p), DC(p.getObjCDeclContext()),
642 WithinObjCContainer(P.ParsingInObjCContainer, DC != 0) {
644 P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC));
646 ~ObjCDeclContextSwitch() {
648 P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC));
652 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
653 /// input. If so, it is consumed and false is returned.
655 /// If the input is malformed, this emits the specified diagnostic. Next, if
656 /// SkipToTok is specified, it calls SkipUntil(SkipToTok). Finally, true is
658 bool ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned Diag,
659 const char *DiagMsg = "",
660 tok::TokenKind SkipToTok = tok::unknown);
662 /// \brief The parser expects a semicolon and, if present, will consume it.
664 /// If the next token is not a semicolon, this emits the specified diagnostic,
665 /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
666 /// to the semicolon, consumes that extra token.
667 bool ExpectAndConsumeSemi(unsigned DiagID);
669 /// \brief The kind of extra semi diagnostic to emit.
673 InstanceVariableList = 2,
674 AfterMemberFunctionDefinition = 3
677 /// \brief Consume any extra semi-colons until the end of the line.
678 void ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST = TST_unspecified);
681 //===--------------------------------------------------------------------===//
682 // Scope manipulation
684 /// ParseScope - Introduces a new scope for parsing. The kind of
685 /// scope is determined by ScopeFlags. Objects of this type should
686 /// be created on the stack to coincide with the position where the
687 /// parser enters the new scope, and this object's constructor will
688 /// create that new scope. Similarly, once the object is destroyed
689 /// the parser will exit the scope.
692 ParseScope(const ParseScope &) LLVM_DELETED_FUNCTION;
693 void operator=(const ParseScope &) LLVM_DELETED_FUNCTION;
696 // ParseScope - Construct a new object to manage a scope in the
697 // parser Self where the new Scope is created with the flags
698 // ScopeFlags, but only when ManageScope is true (the default). If
699 // ManageScope is false, this object does nothing.
700 ParseScope(Parser *Self, unsigned ScopeFlags, bool ManageScope = true)
703 Self->EnterScope(ScopeFlags);
708 // Exit - Exit the scope associated with this object now, rather
709 // than waiting until the object is destroyed.
722 /// EnterScope - Start a new scope.
723 void EnterScope(unsigned ScopeFlags);
725 /// ExitScope - Pop a scope off the scope stack.
729 /// \brief RAII object used to modify the scope flags for the current scope.
730 class ParseScopeFlags {
733 ParseScopeFlags(const ParseScopeFlags &) LLVM_DELETED_FUNCTION;
734 void operator=(const ParseScopeFlags &) LLVM_DELETED_FUNCTION;
737 ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
741 //===--------------------------------------------------------------------===//
742 // Diagnostic Emission and Error recovery.
745 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
746 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
747 DiagnosticBuilder Diag(unsigned DiagID) {
748 return Diag(Tok, DiagID);
752 void SuggestParentheses(SourceLocation Loc, unsigned DK,
753 SourceRange ParenRange);
754 void CheckNestedObjCContexts(SourceLocation AtLoc);
757 /// SkipUntil - Read tokens until we get to the specified token, then consume
758 /// it (unless DontConsume is true). Because we cannot guarantee that the
759 /// token will ever occur, this skips to the next token, or to some likely
760 /// good stopping point. If StopAtSemi is true, skipping will stop at a ';'
763 /// If SkipUntil finds the specified token, it returns true, otherwise it
765 bool SkipUntil(tok::TokenKind T, bool StopAtSemi = true,
766 bool DontConsume = false, bool StopAtCodeCompletion = false) {
767 return SkipUntil(llvm::makeArrayRef(T), StopAtSemi, DontConsume,
768 StopAtCodeCompletion);
770 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, bool StopAtSemi = true,
771 bool DontConsume = false, bool StopAtCodeCompletion = false) {
772 tok::TokenKind TokArray[] = {T1, T2};
773 return SkipUntil(TokArray, StopAtSemi, DontConsume,StopAtCodeCompletion);
775 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3,
776 bool StopAtSemi = true, bool DontConsume = false,
777 bool StopAtCodeCompletion = false) {
778 tok::TokenKind TokArray[] = {T1, T2, T3};
779 return SkipUntil(TokArray, StopAtSemi, DontConsume,StopAtCodeCompletion);
781 bool SkipUntil(ArrayRef<tok::TokenKind> Toks, bool StopAtSemi = true,
782 bool DontConsume = false, bool StopAtCodeCompletion = false);
784 /// SkipMalformedDecl - Read tokens until we get to some likely good stopping
785 /// point for skipping past a simple-declaration.
786 void SkipMalformedDecl();
789 //===--------------------------------------------------------------------===//
790 // Lexing and parsing of C++ inline methods.
794 /// [class.mem]p1: "... the class is regarded as complete within
795 /// - function bodies
796 /// - default arguments
797 /// - exception-specifications (TODO: C++0x)
798 /// - and brace-or-equal-initializers for non-static data members
799 /// (including such things in nested classes)."
800 /// LateParsedDeclarations build the tree of those elements so they can
801 /// be parsed after parsing the top-level class.
802 class LateParsedDeclaration {
804 virtual ~LateParsedDeclaration();
806 virtual void ParseLexedMethodDeclarations();
807 virtual void ParseLexedMemberInitializers();
808 virtual void ParseLexedMethodDefs();
809 virtual void ParseLexedAttributes();
812 /// Inner node of the LateParsedDeclaration tree that parses
813 /// all its members recursively.
814 class LateParsedClass : public LateParsedDeclaration {
816 LateParsedClass(Parser *P, ParsingClass *C);
817 virtual ~LateParsedClass();
819 virtual void ParseLexedMethodDeclarations();
820 virtual void ParseLexedMemberInitializers();
821 virtual void ParseLexedMethodDefs();
822 virtual void ParseLexedAttributes();
829 /// Contains the lexed tokens of an attribute with arguments that
830 /// may reference member variables and so need to be parsed at the
831 /// end of the class declaration after parsing all other member
832 /// member declarations.
833 /// FIXME: Perhaps we should change the name of LateParsedDeclaration to
834 /// LateParsedTokens.
835 struct LateParsedAttribute : public LateParsedDeclaration {
838 IdentifierInfo &AttrName;
839 SourceLocation AttrNameLoc;
840 SmallVector<Decl*, 2> Decls;
842 explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
844 : Self(P), AttrName(Name), AttrNameLoc(Loc) {}
846 virtual void ParseLexedAttributes();
848 void addDecl(Decl *D) { Decls.push_back(D); }
851 // A list of late-parsed attributes. Used by ParseGNUAttributes.
852 class LateParsedAttrList: public llvm::SmallVector<LateParsedAttribute*, 2> {
854 LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { }
856 bool parseSoon() { return ParseSoon; }
859 bool ParseSoon; // Are we planning to parse these shortly after creation?
862 /// Contains the lexed tokens of a member function definition
863 /// which needs to be parsed at the end of the class declaration
864 /// after parsing all other member declarations.
865 struct LexedMethod : public LateParsedDeclaration {
870 /// \brief Whether this member function had an associated template
871 /// scope. When true, D is a template declaration.
872 /// othewise, it is a member function declaration.
875 explicit LexedMethod(Parser* P, Decl *MD)
876 : Self(P), D(MD), TemplateScope(false) {}
878 virtual void ParseLexedMethodDefs();
881 /// LateParsedDefaultArgument - Keeps track of a parameter that may
882 /// have a default argument that cannot be parsed yet because it
883 /// occurs within a member function declaration inside the class
884 /// (C++ [class.mem]p2).
885 struct LateParsedDefaultArgument {
886 explicit LateParsedDefaultArgument(Decl *P,
887 CachedTokens *Toks = 0)
888 : Param(P), Toks(Toks) { }
890 /// Param - The parameter declaration for this parameter.
893 /// Toks - The sequence of tokens that comprises the default
894 /// argument expression, not including the '=' or the terminating
895 /// ')' or ','. This will be NULL for parameters that have no
896 /// default argument.
900 /// LateParsedMethodDeclaration - A method declaration inside a class that
901 /// contains at least one entity whose parsing needs to be delayed
902 /// until the class itself is completely-defined, such as a default
903 /// argument (C++ [class.mem]p2).
904 struct LateParsedMethodDeclaration : public LateParsedDeclaration {
905 explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
906 : Self(P), Method(M), TemplateScope(false), ExceptionSpecTokens(0) { }
908 virtual void ParseLexedMethodDeclarations();
912 /// Method - The method declaration.
915 /// \brief Whether this member function had an associated template
916 /// scope. When true, D is a template declaration.
917 /// othewise, it is a member function declaration.
920 /// DefaultArgs - Contains the parameters of the function and
921 /// their default arguments. At least one of the parameters will
922 /// have a default argument, but all of the parameters of the
923 /// method will be stored so that they can be reintroduced into
924 /// scope at the appropriate times.
925 SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
927 /// \brief The set of tokens that make up an exception-specification that
928 /// has not yet been parsed.
929 CachedTokens *ExceptionSpecTokens;
932 /// LateParsedMemberInitializer - An initializer for a non-static class data
933 /// member whose parsing must to be delayed until the class is completely
934 /// defined (C++11 [class.mem]p2).
935 struct LateParsedMemberInitializer : public LateParsedDeclaration {
936 LateParsedMemberInitializer(Parser *P, Decl *FD)
937 : Self(P), Field(FD) { }
939 virtual void ParseLexedMemberInitializers();
943 /// Field - The field declaration.
946 /// CachedTokens - The sequence of tokens that comprises the initializer,
947 /// including any leading '='.
951 /// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
952 /// C++ class, its method declarations that contain parts that won't be
953 /// parsed until after the definition is completed (C++ [class.mem]p2),
954 /// the method declarations and possibly attached inline definitions
955 /// will be stored here with the tokens that will be parsed to create those
957 typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer;
959 /// \brief Representation of a class that has been parsed, including
960 /// any member function declarations or definitions that need to be
961 /// parsed after the corresponding top-level class is complete.
962 struct ParsingClass {
963 ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface)
964 : TopLevelClass(TopLevelClass), TemplateScope(false),
965 IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) { }
967 /// \brief Whether this is a "top-level" class, meaning that it is
968 /// not nested within another class.
969 bool TopLevelClass : 1;
971 /// \brief Whether this class had an associated template
972 /// scope. When true, TagOrTemplate is a template declaration;
973 /// othewise, it is a tag declaration.
974 bool TemplateScope : 1;
976 /// \brief Whether this class is an __interface.
977 bool IsInterface : 1;
979 /// \brief The class or class template whose definition we are parsing.
982 /// LateParsedDeclarations - Method declarations, inline definitions and
983 /// nested classes that contain pieces whose parsing will be delayed until
984 /// the top-level class is fully defined.
985 LateParsedDeclarationsContainer LateParsedDeclarations;
988 /// \brief The stack of classes that is currently being
989 /// parsed. Nested and local classes will be pushed onto this stack
990 /// when they are parsed, and removed afterward.
991 std::stack<ParsingClass *> ClassStack;
993 ParsingClass &getCurrentClass() {
994 assert(!ClassStack.empty() && "No lexed method stacks!");
995 return *ClassStack.top();
998 /// \brief RAII object used to manage the parsing of a class definition.
999 class ParsingClassDefinition {
1002 Sema::ParsingClassState State;
1005 ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass,
1007 : P(P), Popped(false),
1008 State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
1011 /// \brief Pop this class of the stack.
1013 assert(!Popped && "Nested class has already been popped");
1015 P.PopParsingClass(State);
1018 ~ParsingClassDefinition() {
1020 P.PopParsingClass(State);
1024 /// \brief Contains information about any template-specific
1025 /// information that has been parsed prior to parsing declaration
1027 struct ParsedTemplateInfo {
1028 ParsedTemplateInfo()
1029 : Kind(NonTemplate), TemplateParams(0), TemplateLoc() { }
1031 ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
1032 bool isSpecialization,
1033 bool lastParameterListWasEmpty = false)
1034 : Kind(isSpecialization? ExplicitSpecialization : Template),
1035 TemplateParams(TemplateParams),
1036 LastParameterListWasEmpty(lastParameterListWasEmpty) { }
1038 explicit ParsedTemplateInfo(SourceLocation ExternLoc,
1039 SourceLocation TemplateLoc)
1040 : Kind(ExplicitInstantiation), TemplateParams(0),
1041 ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
1042 LastParameterListWasEmpty(false){ }
1044 /// \brief The kind of template we are parsing.
1046 /// \brief We are not parsing a template at all.
1048 /// \brief We are parsing a template declaration.
1050 /// \brief We are parsing an explicit specialization.
1051 ExplicitSpecialization,
1052 /// \brief We are parsing an explicit instantiation.
1053 ExplicitInstantiation
1056 /// \brief The template parameter lists, for template declarations
1057 /// and explicit specializations.
1058 TemplateParameterLists *TemplateParams;
1060 /// \brief The location of the 'extern' keyword, if any, for an explicit
1062 SourceLocation ExternLoc;
1064 /// \brief The location of the 'template' keyword, for an explicit
1066 SourceLocation TemplateLoc;
1068 /// \brief Whether the last template parameter list was empty.
1069 bool LastParameterListWasEmpty;
1071 SourceRange getSourceRange() const LLVM_READONLY;
1074 /// \brief Contains a late templated function.
1075 /// Will be parsed at the end of the translation unit.
1076 struct LateParsedTemplatedFunction {
1077 explicit LateParsedTemplatedFunction(Decl *MD)
1082 /// \brief The template function declaration to be late parsed.
1086 void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
1087 void ParseLateTemplatedFuncDef(LateParsedTemplatedFunction &LMT);
1088 typedef llvm::DenseMap<const FunctionDecl*, LateParsedTemplatedFunction*>
1089 LateParsedTemplateMapT;
1090 LateParsedTemplateMapT LateParsedTemplateMap;
1092 static void LateTemplateParserCallback(void *P, const FunctionDecl *FD);
1093 void LateTemplateParser(const FunctionDecl *FD);
1095 Sema::ParsingClassState
1096 PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface);
1097 void DeallocateParsedClasses(ParsingClass *Class);
1098 void PopParsingClass(Sema::ParsingClassState);
1100 Decl *ParseCXXInlineMethodDef(AccessSpecifier AS, AttributeList *AccessAttrs,
1101 ParsingDeclarator &D,
1102 const ParsedTemplateInfo &TemplateInfo,
1103 const VirtSpecifiers& VS,
1104 FunctionDefinitionKind DefinitionKind,
1106 void ParseCXXNonStaticMemberInitializer(Decl *VarD);
1107 void ParseLexedAttributes(ParsingClass &Class);
1108 void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1109 bool EnterScope, bool OnDefinition);
1110 void ParseLexedAttribute(LateParsedAttribute &LA,
1111 bool EnterScope, bool OnDefinition);
1112 void ParseLexedMethodDeclarations(ParsingClass &Class);
1113 void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
1114 void ParseLexedMethodDefs(ParsingClass &Class);
1115 void ParseLexedMethodDef(LexedMethod &LM);
1116 void ParseLexedMemberInitializers(ParsingClass &Class);
1117 void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
1118 void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod);
1119 bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
1120 bool ConsumeAndStoreUntil(tok::TokenKind T1,
1122 bool StopAtSemi = true,
1123 bool ConsumeFinalToken = true) {
1124 return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
1126 bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
1128 bool StopAtSemi = true,
1129 bool ConsumeFinalToken = true);
1131 //===--------------------------------------------------------------------===//
1132 // C99 6.9: External Definitions.
1133 struct ParsedAttributesWithRange : ParsedAttributes {
1134 ParsedAttributesWithRange(AttributeFactory &factory)
1135 : ParsedAttributes(factory) {}
1140 DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
1141 ParsingDeclSpec *DS = 0);
1142 bool isDeclarationAfterDeclarator();
1143 bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
1144 DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(
1145 ParsedAttributesWithRange &attrs,
1146 ParsingDeclSpec *DS = 0,
1147 AccessSpecifier AS = AS_none);
1148 DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
1149 ParsingDeclSpec &DS,
1150 AccessSpecifier AS);
1152 Decl *ParseFunctionDefinition(ParsingDeclarator &D,
1153 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1154 LateParsedAttrList *LateParsedAttrs = 0);
1155 void ParseKNRParamDeclarations(Declarator &D);
1156 // EndLoc, if non-NULL, is filled with the location of the last token of
1158 ExprResult ParseSimpleAsm(SourceLocation *EndLoc = 0);
1159 ExprResult ParseAsmStringLiteral();
1161 // Objective-C External Declarations
1162 DeclGroupPtrTy ParseObjCAtDirectives();
1163 DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
1164 Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
1165 ParsedAttributes &prefixAttrs);
1166 void ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1167 tok::ObjCKeywordKind visibility,
1168 SourceLocation atLoc);
1169 bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P,
1170 SmallVectorImpl<SourceLocation> &PLocs,
1171 bool WarnOnDeclarations,
1172 SourceLocation &LAngleLoc,
1173 SourceLocation &EndProtoLoc);
1174 bool ParseObjCProtocolQualifiers(DeclSpec &DS);
1175 void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
1177 DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
1178 ParsedAttributes &prefixAttrs);
1180 struct ObjCImplParsingDataRAII {
1184 typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer;
1185 LateParsedObjCMethodContainer LateParsedObjCMethods;
1187 ObjCImplParsingDataRAII(Parser &parser, Decl *D)
1188 : P(parser), Dcl(D), HasCFunction(false) {
1189 P.CurParsedObjCImpl = this;
1192 ~ObjCImplParsingDataRAII();
1194 void finish(SourceRange AtEnd);
1195 bool isFinished() const { return Finished; }
1200 ObjCImplParsingDataRAII *CurParsedObjCImpl;
1201 void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl);
1203 DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc);
1204 DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
1205 Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
1206 Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
1207 Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
1209 IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
1210 // Definitions for Objective-c context sensitive keywords recognition.
1212 objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
1215 IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
1217 bool isTokIdentifier_in() const;
1219 ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, Declarator::TheContext Ctx,
1220 ParsedAttributes *ParamAttrs);
1221 void ParseObjCMethodRequirement();
1222 Decl *ParseObjCMethodPrototype(
1223 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1224 bool MethodDefinition = true);
1225 Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
1226 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1227 bool MethodDefinition=true);
1228 void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
1230 Decl *ParseObjCMethodDefinition();
1233 //===--------------------------------------------------------------------===//
1234 // C99 6.5: Expressions.
1236 /// TypeCastState - State whether an expression is or may be a type cast.
1237 enum TypeCastState {
1243 ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast);
1244 ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast);
1245 // Expr that doesn't include commas.
1246 ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast);
1249 ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
1251 ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
1253 ExprResult ParseRHSOfBinaryExpression(ExprResult LHS,
1254 prec::Level MinPrec);
1255 ExprResult ParseCastExpression(bool isUnaryExpression,
1256 bool isAddressOfOperand,
1258 TypeCastState isTypeCast);
1259 ExprResult ParseCastExpression(bool isUnaryExpression,
1260 bool isAddressOfOperand = false,
1261 TypeCastState isTypeCast = NotTypeCast);
1263 /// Returns true if the next token cannot start an expression.
1264 bool isNotExpressionStart();
1266 /// Returns true if the next token would start a postfix-expression
1268 bool isPostfixExpressionSuffixStart() {
1269 tok::TokenKind K = Tok.getKind();
1270 return (K == tok::l_square || K == tok::l_paren ||
1271 K == tok::period || K == tok::arrow ||
1272 K == tok::plusplus || K == tok::minusminus);
1275 ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
1276 ExprResult ParseUnaryExprOrTypeTraitExpression();
1277 ExprResult ParseBuiltinPrimaryExpression();
1279 ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1282 SourceRange &CastRange);
1284 typedef SmallVector<Expr*, 20> ExprListTy;
1285 typedef SmallVector<SourceLocation, 20> CommaLocsTy;
1287 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1288 bool ParseExpressionList(SmallVectorImpl<Expr*> &Exprs,
1289 SmallVectorImpl<SourceLocation> &CommaLocs,
1290 void (Sema::*Completer)(Scope *S,
1292 llvm::ArrayRef<Expr *> Args) = 0,
1295 /// ParenParseOption - Control what ParseParenExpression will parse.
1296 enum ParenParseOption {
1297 SimpleExpr, // Only parse '(' expression ')'
1298 CompoundStmt, // Also allow '(' compound-statement ')'
1299 CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
1300 CastExpr // Also allow '(' type-name ')' <anything>
1302 ExprResult ParseParenExpression(ParenParseOption &ExprType,
1303 bool stopIfCastExpr,
1306 SourceLocation &RParenLoc);
1308 ExprResult ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
1310 BalancedDelimiterTracker &Tracker);
1311 ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
1312 SourceLocation LParenLoc,
1313 SourceLocation RParenLoc);
1315 ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
1317 ExprResult ParseGenericSelectionExpression();
1319 ExprResult ParseObjCBoolLiteral();
1321 //===--------------------------------------------------------------------===//
1323 ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
1325 bool areTokensAdjacent(const Token &A, const Token &B);
1327 void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
1328 bool EnteringContext, IdentifierInfo &II,
1331 bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
1332 ParsedType ObjectType,
1333 bool EnteringContext,
1334 bool *MayBePseudoDestructor = 0,
1335 bool IsTypename = false);
1337 void CheckForLParenAfterColonColon();
1339 //===--------------------------------------------------------------------===//
1340 // C++0x 5.1.2: Lambda expressions
1342 // [...] () -> type {...}
1343 ExprResult ParseLambdaExpression();
1344 ExprResult TryParseLambdaExpression();
1345 llvm::Optional<unsigned> ParseLambdaIntroducer(LambdaIntroducer &Intro);
1346 bool TryParseLambdaIntroducer(LambdaIntroducer &Intro);
1347 ExprResult ParseLambdaExpressionAfterIntroducer(
1348 LambdaIntroducer &Intro);
1350 //===--------------------------------------------------------------------===//
1351 // C++ 5.2p1: C++ Casts
1352 ExprResult ParseCXXCasts();
1354 //===--------------------------------------------------------------------===//
1355 // C++ 5.2p1: C++ Type Identification
1356 ExprResult ParseCXXTypeid();
1358 //===--------------------------------------------------------------------===//
1359 // C++ : Microsoft __uuidof Expression
1360 ExprResult ParseCXXUuidof();
1362 //===--------------------------------------------------------------------===//
1363 // C++ 5.2.4: C++ Pseudo-Destructor Expressions
1364 ExprResult ParseCXXPseudoDestructor(ExprArg Base, SourceLocation OpLoc,
1365 tok::TokenKind OpKind,
1367 ParsedType ObjectType);
1369 //===--------------------------------------------------------------------===//
1370 // C++ 9.3.2: C++ 'this' pointer
1371 ExprResult ParseCXXThis();
1373 //===--------------------------------------------------------------------===//
1374 // C++ 15: C++ Throw Expression
1375 ExprResult ParseThrowExpression();
1377 ExceptionSpecificationType tryParseExceptionSpecification(
1378 SourceRange &SpecificationRange,
1379 SmallVectorImpl<ParsedType> &DynamicExceptions,
1380 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
1381 ExprResult &NoexceptExpr);
1383 // EndLoc is filled with the location of the last token of the specification.
1384 ExceptionSpecificationType ParseDynamicExceptionSpecification(
1385 SourceRange &SpecificationRange,
1386 SmallVectorImpl<ParsedType> &Exceptions,
1387 SmallVectorImpl<SourceRange> &Ranges);
1389 //===--------------------------------------------------------------------===//
1390 // C++0x 8: Function declaration trailing-return-type
1391 TypeResult ParseTrailingReturnType(SourceRange &Range);
1393 //===--------------------------------------------------------------------===//
1394 // C++ 2.13.5: C++ Boolean Literals
1395 ExprResult ParseCXXBoolLiteral();
1397 //===--------------------------------------------------------------------===//
1398 // C++ 5.2.3: Explicit type conversion (functional notation)
1399 ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
1401 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1402 /// This should only be called when the current token is known to be part of
1403 /// simple-type-specifier.
1404 void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
1406 bool ParseCXXTypeSpecifierSeq(DeclSpec &DS);
1408 //===--------------------------------------------------------------------===//
1409 // C++ 5.3.4 and 5.3.5: C++ new and delete
1410 bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs,
1412 void ParseDirectNewDeclarator(Declarator &D);
1413 ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
1414 ExprResult ParseCXXDeleteExpression(bool UseGlobal,
1415 SourceLocation Start);
1417 //===--------------------------------------------------------------------===//
1418 // C++ if/switch/while condition expression.
1419 bool ParseCXXCondition(ExprResult &ExprResult, Decl *&DeclResult,
1420 SourceLocation Loc, bool ConvertToBoolean);
1422 //===--------------------------------------------------------------------===//
1425 //===--------------------------------------------------------------------===//
1426 // C99 6.7.8: Initialization.
1428 /// ParseInitializer
1429 /// initializer: [C99 6.7.8]
1430 /// assignment-expression
1432 ExprResult ParseInitializer() {
1433 if (Tok.isNot(tok::l_brace))
1434 return ParseAssignmentExpression();
1435 return ParseBraceInitializer();
1437 bool MayBeDesignationStart();
1438 ExprResult ParseBraceInitializer();
1439 ExprResult ParseInitializerWithPotentialDesignator();
1441 //===--------------------------------------------------------------------===//
1442 // clang Expressions
1444 ExprResult ParseBlockLiteralExpression(); // ^{...}
1446 //===--------------------------------------------------------------------===//
1447 // Objective-C Expressions
1448 ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
1449 ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
1450 ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
1451 ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
1452 ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
1453 ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
1454 ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
1455 ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
1456 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
1457 ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
1458 ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
1459 bool isSimpleObjCMessageExpression();
1460 ExprResult ParseObjCMessageExpression();
1461 ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
1462 SourceLocation SuperLoc,
1463 ParsedType ReceiverType,
1464 ExprArg ReceiverExpr);
1465 ExprResult ParseAssignmentExprWithObjCMessageExprStart(
1466 SourceLocation LBracloc, SourceLocation SuperLoc,
1467 ParsedType ReceiverType, ExprArg ReceiverExpr);
1468 bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
1470 //===--------------------------------------------------------------------===//
1471 // C99 6.8: Statements and Blocks.
1473 /// A SmallVector of statements, with stack size 32 (as that is the only one
1475 typedef SmallVector<Stmt*, 32> StmtVector;
1476 /// A SmallVector of expressions, with stack size 12 (the maximum used.)
1477 typedef SmallVector<Expr*, 12> ExprVector;
1478 /// A SmallVector of types.
1479 typedef SmallVector<ParsedType, 12> TypeVector;
1481 StmtResult ParseStatement(SourceLocation *TrailingElseLoc = 0) {
1483 return ParseStatementOrDeclaration(Stmts, true, TrailingElseLoc);
1485 StmtResult ParseStatementOrDeclaration(StmtVector &Stmts,
1487 SourceLocation *TrailingElseLoc = 0);
1488 StmtResult ParseStatementOrDeclarationAfterAttributes(
1491 SourceLocation *TrailingElseLoc,
1492 ParsedAttributesWithRange &Attrs);
1493 StmtResult ParseExprStatement();
1494 StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs);
1495 StmtResult ParseCaseStatement(bool MissingCase = false,
1496 ExprResult Expr = ExprResult());
1497 StmtResult ParseDefaultStatement();
1498 StmtResult ParseCompoundStatement(bool isStmtExpr = false);
1499 StmtResult ParseCompoundStatement(bool isStmtExpr,
1500 unsigned ScopeFlags);
1501 void ParseCompoundStatementLeadingPragmas();
1502 StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
1503 bool ParseParenExprOrCondition(ExprResult &ExprResult,
1506 bool ConvertToBoolean);
1507 StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
1508 StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
1509 StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
1510 StmtResult ParseDoStatement();
1511 StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
1512 StmtResult ParseGotoStatement();
1513 StmtResult ParseContinueStatement();
1514 StmtResult ParseBreakStatement();
1515 StmtResult ParseReturnStatement();
1516 StmtResult ParseAsmStatement(bool &msAsm);
1517 StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
1519 /// \brief Describes the behavior that should be taken for an __if_exists
1521 enum IfExistsBehavior {
1522 /// \brief Parse the block; this code is always used.
1524 /// \brief Skip the block entirely; this code is never used.
1526 /// \brief Parse the block as a dependent block, which may be used in
1527 /// some template instantiations but not others.
1531 /// \brief Describes the condition of a Microsoft __if_exists or
1532 /// __if_not_exists block.
1533 struct IfExistsCondition {
1534 /// \brief The location of the initial keyword.
1535 SourceLocation KeywordLoc;
1536 /// \brief Whether this is an __if_exists block (rather than an
1537 /// __if_not_exists block).
1540 /// \brief Nested-name-specifier preceding the name.
1543 /// \brief The name we're looking for.
1546 /// \brief The behavior of this __if_exists or __if_not_exists block
1548 IfExistsBehavior Behavior;
1551 bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
1552 void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
1553 void ParseMicrosoftIfExistsExternalDeclaration();
1554 void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
1555 AccessSpecifier& CurAS);
1556 bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
1558 bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
1559 SmallVectorImpl<Expr *> &Constraints,
1560 SmallVectorImpl<Expr *> &Exprs);
1562 //===--------------------------------------------------------------------===//
1563 // C++ 6: Statements and Blocks
1565 StmtResult ParseCXXTryBlock();
1566 StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
1567 StmtResult ParseCXXCatchBlock(bool FnCatch = false);
1569 //===--------------------------------------------------------------------===//
1570 // MS: SEH Statements and Blocks
1572 StmtResult ParseSEHTryBlock();
1573 StmtResult ParseSEHTryBlockCommon(SourceLocation Loc);
1574 StmtResult ParseSEHExceptBlock(SourceLocation Loc);
1575 StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
1577 //===--------------------------------------------------------------------===//
1578 // Objective-C Statements
1580 StmtResult ParseObjCAtStatement(SourceLocation atLoc);
1581 StmtResult ParseObjCTryStmt(SourceLocation atLoc);
1582 StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
1583 StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
1584 StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
1587 //===--------------------------------------------------------------------===//
1588 // C99 6.7: Declarations.
1590 /// A context for parsing declaration specifiers. TODO: flesh this
1591 /// out, there are other significant restrictions on specifiers than
1592 /// would be best implemented in the parser.
1593 enum DeclSpecContext {
1594 DSC_normal, // normal context
1595 DSC_class, // class context, enables 'friend'
1596 DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
1597 DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
1598 DSC_top_level // top-level/namespace declaration context
1601 /// Information on a C++0x for-range-initializer found while parsing a
1602 /// declaration which turns out to be a for-range-declaration.
1603 struct ForRangeInit {
1604 SourceLocation ColonLoc;
1605 ExprResult RangeExpr;
1607 bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
1610 DeclGroupPtrTy ParseDeclaration(StmtVector &Stmts,
1611 unsigned Context, SourceLocation &DeclEnd,
1612 ParsedAttributesWithRange &attrs);
1613 DeclGroupPtrTy ParseSimpleDeclaration(StmtVector &Stmts,
1615 SourceLocation &DeclEnd,
1616 ParsedAttributesWithRange &attrs,
1618 ForRangeInit *FRI = 0);
1619 bool MightBeDeclarator(unsigned Context);
1620 DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, unsigned Context,
1621 bool AllowFunctionDefinitions,
1622 SourceLocation *DeclEnd = 0,
1623 ForRangeInit *FRI = 0);
1624 Decl *ParseDeclarationAfterDeclarator(Declarator &D,
1625 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
1626 bool ParseAsmAttributesAfterDeclarator(Declarator &D);
1627 Decl *ParseDeclarationAfterDeclaratorAndAttributes(Declarator &D,
1628 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
1629 Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
1630 Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
1632 /// \brief When in code-completion, skip parsing of the function/method body
1633 /// unless the body contains the code-completion point.
1635 /// \returns true if the function body was skipped.
1636 bool trySkippingFunctionBody();
1638 bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
1639 const ParsedTemplateInfo &TemplateInfo,
1640 AccessSpecifier AS, DeclSpecContext DSC);
1641 DeclSpecContext getDeclSpecContextFromDeclaratorContext(unsigned Context);
1642 void ParseDeclarationSpecifiers(DeclSpec &DS,
1643 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1644 AccessSpecifier AS = AS_none,
1645 DeclSpecContext DSC = DSC_normal,
1646 LateParsedAttrList *LateAttrs = 0);
1648 void ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS = AS_none,
1649 DeclSpecContext DSC = DSC_normal);
1651 void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
1652 Declarator::TheContext Context);
1654 void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
1655 const ParsedTemplateInfo &TemplateInfo,
1656 AccessSpecifier AS, DeclSpecContext DSC);
1657 void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
1658 void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType,
1661 struct FieldCallback {
1662 virtual void invoke(ParsingFieldDeclarator &Field) = 0;
1663 virtual ~FieldCallback() {}
1666 virtual void _anchor();
1668 struct ObjCPropertyCallback;
1670 void ParseStructDeclaration(ParsingDeclSpec &DS, FieldCallback &Callback);
1672 bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
1673 bool isTypeSpecifierQualifier();
1674 bool isTypeQualifier() const;
1676 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
1677 /// is definitely a type-specifier. Return false if it isn't part of a type
1678 /// specifier or if we're not sure.
1679 bool isKnownToBeTypeSpecifier(const Token &Tok) const;
1681 /// \brief Return true if we know that we are definitely looking at a
1682 /// decl-specifier, and isn't part of an expression such as a function-style
1683 /// cast. Return false if it's no a decl-specifier, or we're not sure.
1684 bool isKnownToBeDeclarationSpecifier() {
1685 if (getLangOpts().CPlusPlus)
1686 return isCXXDeclarationSpecifier() == TPResult::True();
1687 return isDeclarationSpecifier(true);
1690 /// isDeclarationStatement - Disambiguates between a declaration or an
1691 /// expression statement, when parsing function bodies.
1692 /// Returns true for declaration, false for expression.
1693 bool isDeclarationStatement() {
1694 if (getLangOpts().CPlusPlus)
1695 return isCXXDeclarationStatement();
1696 return isDeclarationSpecifier(true);
1699 /// isForInitDeclaration - Disambiguates between a declaration or an
1700 /// expression in the context of the C 'clause-1' or the C++
1701 // 'for-init-statement' part of a 'for' statement.
1702 /// Returns true for declaration, false for expression.
1703 bool isForInitDeclaration() {
1704 if (getLangOpts().CPlusPlus)
1705 return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
1706 return isDeclarationSpecifier(true);
1709 /// \brief Determine whether we are currently at the start of an Objective-C
1710 /// class message that appears to be missing the open bracket '['.
1711 bool isStartOfObjCClassMessageMissingOpenBracket();
1713 /// \brief Starting with a scope specifier, identifier, or
1714 /// template-id that refers to the current class, determine whether
1715 /// this is a constructor declarator.
1716 bool isConstructorDeclarator();
1718 /// \brief Specifies the context in which type-id/expression
1719 /// disambiguation will occur.
1720 enum TentativeCXXTypeIdContext {
1722 TypeIdAsTemplateArgument
1726 /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
1727 /// whether the parens contain an expression or a type-id.
1728 /// Returns true for a type-id and false for an expression.
1729 bool isTypeIdInParens(bool &isAmbiguous) {
1730 if (getLangOpts().CPlusPlus)
1731 return isCXXTypeId(TypeIdInParens, isAmbiguous);
1732 isAmbiguous = false;
1733 return isTypeSpecifierQualifier();
1735 bool isTypeIdInParens() {
1737 return isTypeIdInParens(isAmbiguous);
1740 /// isCXXDeclarationStatement - C++-specialized function that disambiguates
1741 /// between a declaration or an expression statement, when parsing function
1742 /// bodies. Returns true for declaration, false for expression.
1743 bool isCXXDeclarationStatement();
1745 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
1746 /// between a simple-declaration or an expression-statement.
1747 /// If during the disambiguation process a parsing error is encountered,
1748 /// the function returns true to let the declaration parsing code handle it.
1749 /// Returns false if the statement is disambiguated as expression.
1750 bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
1752 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
1753 /// a constructor-style initializer, when parsing declaration statements.
1754 /// Returns true for function declarator and false for constructor-style
1755 /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
1756 /// might be a constructor-style initializer.
1757 /// If during the disambiguation process a parsing error is encountered,
1758 /// the function returns true to let the declaration parsing code handle it.
1759 bool isCXXFunctionDeclarator(bool *IsAmbiguous = 0);
1761 /// isCXXConditionDeclaration - Disambiguates between a declaration or an
1762 /// expression for a condition of a if/switch/while/for statement.
1763 /// If during the disambiguation process a parsing error is encountered,
1764 /// the function returns true to let the declaration parsing code handle it.
1765 bool isCXXConditionDeclaration();
1767 bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
1768 bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
1770 return isCXXTypeId(Context, isAmbiguous);
1773 /// TPResult - Used as the result value for functions whose purpose is to
1774 /// disambiguate C++ constructs by "tentatively parsing" them.
1775 /// This is a class instead of a simple enum because the implicit enum-to-bool
1776 /// conversions may cause subtle bugs.
1785 TPResult(Result result) : Res(result) {}
1787 static TPResult True() { return TPR_true; }
1788 static TPResult False() { return TPR_false; }
1789 static TPResult Ambiguous() { return TPR_ambiguous; }
1790 static TPResult Error() { return TPR_error; }
1792 bool operator==(const TPResult &RHS) const { return Res == RHS.Res; }
1793 bool operator!=(const TPResult &RHS) const { return Res != RHS.Res; }
1796 /// \brief Based only on the given token kind, determine whether we know that
1797 /// we're at the start of an expression or a type-specifier-seq (which may
1798 /// be an expression, in C++).
1800 /// This routine does not attempt to resolve any of the trick cases, e.g.,
1801 /// those involving lookup of identifiers.
1803 /// \returns \c TPR_true if this token starts an expression, \c TPR_false if
1804 /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot
1806 TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind);
1808 /// isCXXDeclarationSpecifier - Returns TPResult::True() if it is a
1809 /// declaration specifier, TPResult::False() if it is not,
1810 /// TPResult::Ambiguous() if it could be either a decl-specifier or a
1811 /// function-style cast, and TPResult::Error() if a parsing error was
1812 /// encountered. If it could be a braced C++11 function-style cast, returns
1813 /// BracedCastResult.
1814 /// Doesn't consume tokens.
1816 isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False(),
1817 bool *HasMissingTypename = 0);
1819 /// \brief Determine whether an identifier has been tentatively declared as a
1820 /// non-type. Such tentative declarations should not be found to name a type
1821 /// during a tentative parse, but also should not be annotated as a non-type.
1822 bool isTentativelyDeclared(IdentifierInfo *II);
1824 // "Tentative parsing" functions, used for disambiguation. If a parsing error
1825 // is encountered they will return TPResult::Error().
1826 // Returning TPResult::True()/False() indicates that the ambiguity was
1827 // resolved and tentative parsing may stop. TPResult::Ambiguous() indicates
1828 // that more tentative parsing is necessary for disambiguation.
1829 // They all consume tokens, so backtracking should be used after calling them.
1831 TPResult TryParseDeclarationSpecifier(bool *HasMissingTypename = 0);
1832 TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
1833 TPResult TryParseTypeofSpecifier();
1834 TPResult TryParseProtocolQualifiers();
1835 TPResult TryParseInitDeclaratorList();
1836 TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier=true);
1837 TPResult TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = 0);
1838 TPResult TryParseFunctionDeclarator();
1839 TPResult TryParseBracketDeclarator();
1842 TypeResult ParseTypeName(SourceRange *Range = 0,
1843 Declarator::TheContext Context
1844 = Declarator::TypeNameContext,
1845 AccessSpecifier AS = AS_none,
1846 Decl **OwnedType = 0);
1849 void ParseBlockId(SourceLocation CaretLoc);
1851 // Check for the start of a C++11 attribute-specifier-seq in a context where
1852 // an attribute is not allowed.
1853 bool CheckProhibitedCXX11Attribute() {
1854 assert(Tok.is(tok::l_square));
1855 if (!getLangOpts().CPlusPlus0x || NextToken().isNot(tok::l_square))
1857 return DiagnoseProhibitedCXX11Attribute();
1859 bool DiagnoseProhibitedCXX11Attribute();
1861 void ProhibitAttributes(ParsedAttributesWithRange &attrs) {
1862 if (!attrs.Range.isValid()) return;
1863 DiagnoseProhibitedAttributes(attrs);
1866 void DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs);
1868 // Forbid C++11 attributes that appear on certain syntactic
1869 // locations which standard permits but we don't supported yet,
1870 // for example, attributes appertain to decl specifiers.
1871 void ProhibitCXX11Attributes(ParsedAttributesWithRange &attrs);
1873 void MaybeParseGNUAttributes(Declarator &D,
1874 LateParsedAttrList *LateAttrs = 0) {
1875 if (Tok.is(tok::kw___attribute)) {
1876 ParsedAttributes attrs(AttrFactory);
1877 SourceLocation endLoc;
1878 ParseGNUAttributes(attrs, &endLoc, LateAttrs);
1879 D.takeAttributes(attrs, endLoc);
1882 void MaybeParseGNUAttributes(ParsedAttributes &attrs,
1883 SourceLocation *endLoc = 0,
1884 LateParsedAttrList *LateAttrs = 0) {
1885 if (Tok.is(tok::kw___attribute))
1886 ParseGNUAttributes(attrs, endLoc, LateAttrs);
1888 void ParseGNUAttributes(ParsedAttributes &attrs,
1889 SourceLocation *endLoc = 0,
1890 LateParsedAttrList *LateAttrs = 0);
1891 void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
1892 SourceLocation AttrNameLoc,
1893 ParsedAttributes &Attrs,
1894 SourceLocation *EndLoc,
1895 IdentifierInfo *ScopeName,
1896 SourceLocation ScopeLoc,
1897 AttributeList::Syntax Syntax);
1899 void MaybeParseCXX0XAttributes(Declarator &D) {
1900 if (getLangOpts().CPlusPlus0x && isCXX11AttributeSpecifier()) {
1901 ParsedAttributesWithRange attrs(AttrFactory);
1902 SourceLocation endLoc;
1903 ParseCXX11Attributes(attrs, &endLoc);
1904 D.takeAttributes(attrs, endLoc);
1907 void MaybeParseCXX0XAttributes(ParsedAttributes &attrs,
1908 SourceLocation *endLoc = 0) {
1909 if (getLangOpts().CPlusPlus0x && isCXX11AttributeSpecifier()) {
1910 ParsedAttributesWithRange attrsWithRange(AttrFactory);
1911 ParseCXX11Attributes(attrsWithRange, endLoc);
1912 attrs.takeAllFrom(attrsWithRange);
1915 void MaybeParseCXX0XAttributes(ParsedAttributesWithRange &attrs,
1916 SourceLocation *endLoc = 0,
1917 bool OuterMightBeMessageSend = false) {
1918 if (getLangOpts().CPlusPlus0x &&
1919 isCXX11AttributeSpecifier(false, OuterMightBeMessageSend))
1920 ParseCXX11Attributes(attrs, endLoc);
1923 void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
1924 SourceLocation *EndLoc = 0);
1925 void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
1926 SourceLocation *EndLoc = 0);
1928 IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc);
1930 void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
1931 SourceLocation *endLoc = 0) {
1932 if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
1933 ParseMicrosoftAttributes(attrs, endLoc);
1935 void ParseMicrosoftAttributes(ParsedAttributes &attrs,
1936 SourceLocation *endLoc = 0);
1937 void ParseMicrosoftDeclSpec(ParsedAttributes &Attrs);
1938 bool IsSimpleMicrosoftDeclSpec(IdentifierInfo *Ident);
1939 void ParseComplexMicrosoftDeclSpec(IdentifierInfo *Ident,
1941 ParsedAttributes &Attrs);
1942 void ParseMicrosoftDeclSpecWithSingleArg(IdentifierInfo *AttrName,
1943 SourceLocation AttrNameLoc,
1944 ParsedAttributes &Attrs);
1945 void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
1946 void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
1947 void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
1948 void ParseOpenCLAttributes(ParsedAttributes &attrs);
1949 void ParseOpenCLQualifiers(DeclSpec &DS);
1951 VersionTuple ParseVersionTuple(SourceRange &Range);
1952 void ParseAvailabilityAttribute(IdentifierInfo &Availability,
1953 SourceLocation AvailabilityLoc,
1954 ParsedAttributes &attrs,
1955 SourceLocation *endLoc);
1957 bool IsThreadSafetyAttribute(llvm::StringRef AttrName);
1958 void ParseThreadSafetyAttribute(IdentifierInfo &AttrName,
1959 SourceLocation AttrNameLoc,
1960 ParsedAttributes &Attrs,
1961 SourceLocation *EndLoc);
1963 void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1964 SourceLocation AttrNameLoc,
1965 ParsedAttributes &Attrs,
1966 SourceLocation *EndLoc);
1968 void ParseTypeofSpecifier(DeclSpec &DS);
1969 SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
1970 void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
1971 SourceLocation StartLoc,
1972 SourceLocation EndLoc);
1973 void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
1974 void ParseAtomicSpecifier(DeclSpec &DS);
1976 ExprResult ParseAlignArgument(SourceLocation Start,
1977 SourceLocation &EllipsisLoc);
1978 void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
1979 SourceLocation *endLoc = 0);
1981 VirtSpecifiers::Specifier isCXX0XVirtSpecifier(const Token &Tok) const;
1982 VirtSpecifiers::Specifier isCXX0XVirtSpecifier() const {
1983 return isCXX0XVirtSpecifier(Tok);
1985 void ParseOptionalCXX0XVirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface);
1987 bool isCXX0XFinalKeyword() const;
1989 /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
1990 /// enter a new C++ declarator scope and exit it when the function is
1992 class DeclaratorScopeObj {
1998 DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
1999 : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
2001 void EnterDeclaratorScope() {
2002 assert(!EnteredScope && "Already entered the scope!");
2003 assert(SS.isSet() && "C++ scope was not set!");
2005 CreatedScope = true;
2006 P.EnterScope(0); // Not a decl scope.
2008 if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
2009 EnteredScope = true;
2012 ~DeclaratorScopeObj() {
2014 assert(SS.isSet() && "C++ scope was cleared ?");
2015 P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
2022 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
2023 void ParseDeclarator(Declarator &D);
2024 /// A function that parses a variant of direct-declarator.
2025 typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
2026 void ParseDeclaratorInternal(Declarator &D,
2027 DirectDeclParseFunction DirectDeclParser);
2029 void ParseTypeQualifierListOpt(DeclSpec &DS, bool GNUAttributesAllowed = true,
2030 bool CXX0XAttributesAllowed = true);
2031 void ParseDirectDeclarator(Declarator &D);
2032 void ParseParenDeclarator(Declarator &D);
2033 void ParseFunctionDeclarator(Declarator &D,
2034 ParsedAttributes &attrs,
2035 BalancedDelimiterTracker &Tracker,
2037 bool RequiresArg = false);
2038 bool isFunctionDeclaratorIdentifierList();
2039 void ParseFunctionDeclaratorIdentifierList(
2041 SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo);
2042 void ParseParameterDeclarationClause(
2044 ParsedAttributes &attrs,
2045 SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo,
2046 SourceLocation &EllipsisLoc);
2047 void ParseBracketDeclarator(Declarator &D);
2049 //===--------------------------------------------------------------------===//
2050 // C++ 7: Declarations [dcl.dcl]
2052 /// The kind of attribute specifier we have found.
2053 enum CXX11AttributeKind {
2054 /// This is not an attribute specifier.
2055 CAK_NotAttributeSpecifier,
2056 /// This should be treated as an attribute-specifier.
2057 CAK_AttributeSpecifier,
2058 /// The next tokens are '[[', but this is not an attribute-specifier. This
2059 /// is ill-formed by C++11 [dcl.attr.grammar]p6.
2060 CAK_InvalidAttributeSpecifier
2063 isCXX11AttributeSpecifier(bool Disambiguate = false,
2064 bool OuterMightBeMessageSend = false);
2066 Decl *ParseNamespace(unsigned Context, SourceLocation &DeclEnd,
2067 SourceLocation InlineLoc = SourceLocation());
2068 void ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc,
2069 std::vector<IdentifierInfo*>& Ident,
2070 std::vector<SourceLocation>& NamespaceLoc,
2071 unsigned int index, SourceLocation& InlineLoc,
2072 ParsedAttributes& attrs,
2073 BalancedDelimiterTracker &Tracker);
2074 Decl *ParseLinkage(ParsingDeclSpec &DS, unsigned Context);
2075 Decl *ParseUsingDirectiveOrDeclaration(unsigned Context,
2076 const ParsedTemplateInfo &TemplateInfo,
2077 SourceLocation &DeclEnd,
2078 ParsedAttributesWithRange &attrs,
2079 Decl **OwnedType = 0);
2080 Decl *ParseUsingDirective(unsigned Context,
2081 SourceLocation UsingLoc,
2082 SourceLocation &DeclEnd,
2083 ParsedAttributes &attrs);
2084 Decl *ParseUsingDeclaration(unsigned Context,
2085 const ParsedTemplateInfo &TemplateInfo,
2086 SourceLocation UsingLoc,
2087 SourceLocation &DeclEnd,
2088 AccessSpecifier AS = AS_none,
2089 Decl **OwnedType = 0);
2090 Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
2091 Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
2092 SourceLocation AliasLoc, IdentifierInfo *Alias,
2093 SourceLocation &DeclEnd);
2095 //===--------------------------------------------------------------------===//
2096 // C++ 9: classes [class] and C structs/unions.
2097 bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
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);
2135 bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2136 bool AllowDestructorName,
2137 bool AllowConstructorName,
2138 ParsedType ObjectType,
2139 SourceLocation& TemplateKWLoc,
2140 UnqualifiedId &Result);
2143 //===--------------------------------------------------------------------===//
2144 // C++ 14: Templates [temp]
2146 // C++ 14.1: Template Parameters [temp.param]
2147 Decl *ParseDeclarationStartingWithTemplate(unsigned Context,
2148 SourceLocation &DeclEnd,
2149 AccessSpecifier AS = AS_none,
2150 AttributeList *AccessAttrs = 0);
2151 Decl *ParseTemplateDeclarationOrSpecialization(unsigned Context,
2152 SourceLocation &DeclEnd,
2154 AttributeList *AccessAttrs);
2155 Decl *ParseSingleDeclarationAfterTemplate(
2157 const ParsedTemplateInfo &TemplateInfo,
2158 ParsingDeclRAIIObject &DiagsFromParams,
2159 SourceLocation &DeclEnd,
2160 AccessSpecifier AS=AS_none,
2161 AttributeList *AccessAttrs = 0);
2162 bool ParseTemplateParameters(unsigned Depth,
2163 SmallVectorImpl<Decl*> &TemplateParams,
2164 SourceLocation &LAngleLoc,
2165 SourceLocation &RAngleLoc);
2166 bool ParseTemplateParameterList(unsigned Depth,
2167 SmallVectorImpl<Decl*> &TemplateParams);
2168 bool isStartOfTemplateTypeParameter();
2169 Decl *ParseTemplateParameter(unsigned Depth, unsigned Position);
2170 Decl *ParseTypeParameter(unsigned Depth, unsigned Position);
2171 Decl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
2172 Decl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
2173 // C++ 14.3: Template arguments [temp.arg]
2174 typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
2176 bool ParseTemplateIdAfterTemplateName(TemplateTy Template,
2177 SourceLocation TemplateNameLoc,
2178 const CXXScopeSpec &SS,
2179 bool ConsumeLastToken,
2180 SourceLocation &LAngleLoc,
2181 TemplateArgList &TemplateArgs,
2182 SourceLocation &RAngleLoc);
2184 bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
2186 SourceLocation TemplateKWLoc,
2187 UnqualifiedId &TemplateName,
2188 bool AllowTypeAnnotation = true);
2189 void AnnotateTemplateIdTokenAsType();
2190 bool IsTemplateArgumentList(unsigned Skip = 0);
2191 bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
2192 ParsedTemplateArgument ParseTemplateTemplateArgument();
2193 ParsedTemplateArgument ParseTemplateArgument();
2194 Decl *ParseExplicitInstantiation(unsigned Context,
2195 SourceLocation ExternLoc,
2196 SourceLocation TemplateLoc,
2197 SourceLocation &DeclEnd,
2198 AccessSpecifier AS = AS_none);
2200 //===--------------------------------------------------------------------===//
2202 DeclGroupPtrTy ParseModuleImport(SourceLocation AtLoc);
2204 //===--------------------------------------------------------------------===//
2205 // GNU G++: Type Traits [Type-Traits.html in the GCC manual]
2206 ExprResult ParseUnaryTypeTrait();
2207 ExprResult ParseBinaryTypeTrait();
2208 ExprResult ParseTypeTrait();
2210 //===--------------------------------------------------------------------===//
2211 // Embarcadero: Arary and Expression Traits
2212 ExprResult ParseArrayTypeTrait();
2213 ExprResult ParseExpressionTrait();
2215 //===--------------------------------------------------------------------===//
2216 // Preprocessor code-completion pass-through
2217 virtual void CodeCompleteDirective(bool InConditional);
2218 virtual void CodeCompleteInConditionalExclusion();
2219 virtual void CodeCompleteMacroName(bool IsDefinition);
2220 virtual void CodeCompletePreprocessorExpression();
2221 virtual void CodeCompleteMacroArgument(IdentifierInfo *Macro,
2222 MacroInfo *MacroInfo,
2223 unsigned ArgumentIndex);
2224 virtual void CodeCompleteNaturalLanguage();
2227 } // end namespace clang