1 //===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the Parser interface.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_PARSE_PARSER_H
15 #define LLVM_CLANG_PARSE_PARSER_H
17 #include "clang/AST/Availability.h"
18 #include "clang/Basic/OpenMPKinds.h"
19 #include "clang/Basic/OperatorPrecedence.h"
20 #include "clang/Basic/Specifiers.h"
21 #include "clang/Lex/CodeCompletionHandler.h"
22 #include "clang/Lex/Preprocessor.h"
23 #include "clang/Sema/DeclSpec.h"
24 #include "clang/Sema/LoopHint.h"
25 #include "clang/Sema/Sema.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/Support/PrettyStackTrace.h"
29 #include "llvm/Support/SaveAndRestore.h"
36 class BalancedDelimiterTracker;
37 class CorrectionCandidateCallback;
39 class DiagnosticBuilder;
41 class ParsingDeclRAIIObject;
42 class ParsingDeclSpec;
43 class ParsingDeclarator;
44 class ParsingFieldDeclarator;
45 class ColonProtectionRAIIObject;
46 class InMessageExpressionRAIIObject;
47 class PoisonSEHIdentifiersRAIIObject;
50 class ObjCTypeParamList;
51 class ObjCTypeParameter;
53 /// Parser - This implements a parser for the C family of languages. After
54 /// parsing units of the grammar, productions are invoked to handle whatever has
57 class Parser : public CodeCompletionHandler {
58 friend class ColonProtectionRAIIObject;
59 friend class InMessageExpressionRAIIObject;
60 friend class PoisonSEHIdentifiersRAIIObject;
61 friend class ObjCDeclContextSwitch;
62 friend class ParenBraceBracketBalancer;
63 friend class BalancedDelimiterTracker;
67 /// Tok - The current token we are peeking ahead. All parsing methods assume
68 /// that this is valid.
71 // PrevTokLocation - The location of the token we previously
72 // consumed. This token is used for diagnostics where we expected to
73 // see a token following another token (e.g., the ';' at the end of
75 SourceLocation PrevTokLocation;
77 unsigned short ParenCount, BracketCount, BraceCount;
79 /// Actions - These are the callbacks we invoke as we parse various constructs
83 DiagnosticsEngine &Diags;
85 /// ScopeCache - Cache scopes to reduce malloc traffic.
86 enum { ScopeCacheSize = 16 };
87 unsigned NumCachedScopes;
88 Scope *ScopeCache[ScopeCacheSize];
90 /// Identifiers used for SEH handling in Borland. These are only
91 /// allowed in particular circumstances
93 IdentifierInfo *Ident__exception_code,
94 *Ident___exception_code,
95 *Ident_GetExceptionCode;
96 // __except filter expression
97 IdentifierInfo *Ident__exception_info,
98 *Ident___exception_info,
99 *Ident_GetExceptionInfo;
101 IdentifierInfo *Ident__abnormal_termination,
102 *Ident___abnormal_termination,
103 *Ident_AbnormalTermination;
105 /// Contextual keywords for Microsoft extensions.
106 IdentifierInfo *Ident__except;
107 mutable IdentifierInfo *Ident_sealed;
109 /// Ident_super - IdentifierInfo for "super", to support fast
111 IdentifierInfo *Ident_super;
112 /// Ident_vector, Ident_bool - cached IdentifierInfos for "vector" and
113 /// "bool" fast comparison. Only present if AltiVec or ZVector are enabled.
114 IdentifierInfo *Ident_vector;
115 IdentifierInfo *Ident_bool;
116 /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison.
117 /// Only present if AltiVec enabled.
118 IdentifierInfo *Ident_pixel;
120 /// Objective-C contextual keywords.
121 mutable IdentifierInfo *Ident_instancetype;
123 /// \brief Identifier for "introduced".
124 IdentifierInfo *Ident_introduced;
126 /// \brief Identifier for "deprecated".
127 IdentifierInfo *Ident_deprecated;
129 /// \brief Identifier for "obsoleted".
130 IdentifierInfo *Ident_obsoleted;
132 /// \brief Identifier for "unavailable".
133 IdentifierInfo *Ident_unavailable;
135 /// \brief Identifier for "message".
136 IdentifierInfo *Ident_message;
138 /// \brief Identifier for "strict".
139 IdentifierInfo *Ident_strict;
141 /// \brief Identifier for "replacement".
142 IdentifierInfo *Ident_replacement;
144 /// C++0x contextual keywords.
145 mutable IdentifierInfo *Ident_final;
146 mutable IdentifierInfo *Ident_override;
148 // C++ type trait keywords that can be reverted to identifiers and still be
149 // used as type traits.
150 llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits;
152 std::unique_ptr<PragmaHandler> AlignHandler;
153 std::unique_ptr<PragmaHandler> GCCVisibilityHandler;
154 std::unique_ptr<PragmaHandler> OptionsHandler;
155 std::unique_ptr<PragmaHandler> PackHandler;
156 std::unique_ptr<PragmaHandler> MSStructHandler;
157 std::unique_ptr<PragmaHandler> UnusedHandler;
158 std::unique_ptr<PragmaHandler> WeakHandler;
159 std::unique_ptr<PragmaHandler> RedefineExtnameHandler;
160 std::unique_ptr<PragmaHandler> FPContractHandler;
161 std::unique_ptr<PragmaHandler> OpenCLExtensionHandler;
162 std::unique_ptr<PragmaHandler> OpenMPHandler;
163 std::unique_ptr<PragmaHandler> MSCommentHandler;
164 std::unique_ptr<PragmaHandler> MSDetectMismatchHandler;
165 std::unique_ptr<PragmaHandler> MSPointersToMembers;
166 std::unique_ptr<PragmaHandler> MSVtorDisp;
167 std::unique_ptr<PragmaHandler> MSInitSeg;
168 std::unique_ptr<PragmaHandler> MSDataSeg;
169 std::unique_ptr<PragmaHandler> MSBSSSeg;
170 std::unique_ptr<PragmaHandler> MSConstSeg;
171 std::unique_ptr<PragmaHandler> MSCodeSeg;
172 std::unique_ptr<PragmaHandler> MSSection;
173 std::unique_ptr<PragmaHandler> MSRuntimeChecks;
174 std::unique_ptr<PragmaHandler> OptimizeHandler;
175 std::unique_ptr<PragmaHandler> LoopHintHandler;
176 std::unique_ptr<PragmaHandler> UnrollHintHandler;
177 std::unique_ptr<PragmaHandler> NoUnrollHintHandler;
179 std::unique_ptr<CommentHandler> CommentSemaHandler;
181 /// Whether the '>' token acts as an operator or not. This will be
182 /// true except when we are parsing an expression within a C++
183 /// template argument list, where the '>' closes the template
185 bool GreaterThanIsOperator;
187 /// ColonIsSacred - When this is false, we aggressively try to recover from
188 /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not
189 /// safe in case statements and a few other things. This is managed by the
190 /// ColonProtectionRAIIObject RAII object.
193 /// \brief When true, we are directly inside an Objective-C message
196 /// This is managed by the \c InMessageExpressionRAIIObject class, and
197 /// should not be set directly.
198 bool InMessageExpression;
200 /// The "depth" of the template parameters currently being parsed.
201 unsigned TemplateParameterDepth;
203 /// \brief RAII class that manages the template parameter depth.
204 class TemplateParameterDepthRAII {
206 unsigned AddedLevels;
208 explicit TemplateParameterDepthRAII(unsigned &Depth)
209 : Depth(Depth), AddedLevels(0) {}
211 ~TemplateParameterDepthRAII() {
212 Depth -= AddedLevels;
219 void addDepth(unsigned D) {
223 unsigned getDepth() const { return Depth; }
226 /// Factory object for creating AttributeList objects.
227 AttributeFactory AttrFactory;
229 /// \brief Gathers and cleans up TemplateIdAnnotations when parsing of a
230 /// top-level declaration is finished.
231 SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
233 /// \brief Identifiers which have been declared within a tentative parse.
234 SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers;
236 IdentifierInfo *getSEHExceptKeyword();
238 /// True if we are within an Objective-C container while parsing C-like decls.
240 /// This is necessary because Sema thinks we have left the container
241 /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will
243 bool ParsingInObjCContainer;
245 bool SkipFunctionBodies;
248 Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
251 const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
252 const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
253 Preprocessor &getPreprocessor() const { return PP; }
254 Sema &getActions() const { return Actions; }
255 AttributeFactory &getAttrFactory() { return AttrFactory; }
257 const Token &getCurToken() const { return Tok; }
258 Scope *getCurScope() const { return Actions.getCurScope(); }
259 void incrementMSManglingNumber() const {
260 return Actions.incrementMSManglingNumber();
263 Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); }
265 // Type forwarding. All of these are statically 'void*', but they may all be
266 // different actual classes based on the actions in place.
267 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
268 typedef OpaquePtr<TemplateName> TemplateTy;
270 typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists;
272 typedef Sema::FullExprArg FullExprArg;
276 /// Initialize - Warm up the parser.
280 /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if
281 /// the EOF was encountered.
282 bool ParseTopLevelDecl(DeclGroupPtrTy &Result);
283 bool ParseTopLevelDecl() {
284 DeclGroupPtrTy Result;
285 return ParseTopLevelDecl(Result);
288 /// ConsumeToken - Consume the current 'peek token' and lex the next one.
289 /// This does not work with special tokens: string literals, code completion
290 /// and balanced tokens must be handled using the specific consume methods.
291 /// Returns the location of the consumed token.
292 SourceLocation ConsumeToken() {
293 assert(!isTokenSpecial() &&
294 "Should consume special tokens with Consume*Token");
295 PrevTokLocation = Tok.getLocation();
297 return PrevTokLocation;
300 bool TryConsumeToken(tok::TokenKind Expected) {
301 if (Tok.isNot(Expected))
303 assert(!isTokenSpecial() &&
304 "Should consume special tokens with Consume*Token");
305 PrevTokLocation = Tok.getLocation();
310 bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) {
311 if (!TryConsumeToken(Expected))
313 Loc = PrevTokLocation;
317 /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds
318 /// to the given nullability kind.
319 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) {
320 return Actions.getNullabilityKeyword(nullability);
324 //===--------------------------------------------------------------------===//
325 // Low-Level token peeking and consumption methods.
328 /// isTokenParen - Return true if the cur token is '(' or ')'.
329 bool isTokenParen() const {
330 return Tok.getKind() == tok::l_paren || Tok.getKind() == tok::r_paren;
332 /// isTokenBracket - Return true if the cur token is '[' or ']'.
333 bool isTokenBracket() const {
334 return Tok.getKind() == tok::l_square || Tok.getKind() == tok::r_square;
336 /// isTokenBrace - Return true if the cur token is '{' or '}'.
337 bool isTokenBrace() const {
338 return Tok.getKind() == tok::l_brace || Tok.getKind() == tok::r_brace;
340 /// isTokenStringLiteral - True if this token is a string-literal.
341 bool isTokenStringLiteral() const {
342 return tok::isStringLiteral(Tok.getKind());
344 /// isTokenSpecial - True if this token requires special consumption methods.
345 bool isTokenSpecial() const {
346 return isTokenStringLiteral() || isTokenParen() || isTokenBracket() ||
347 isTokenBrace() || Tok.is(tok::code_completion);
350 /// \brief Returns true if the current token is '=' or is a type of '='.
351 /// For typos, give a fixit to '='
352 bool isTokenEqualOrEqualTypo();
354 /// \brief Return the current token to the token stream and make the given
355 /// token the current token.
356 void UnconsumeToken(Token &Consumed) {
358 PP.EnterToken(Consumed);
363 /// ConsumeAnyToken - Dispatch to the right Consume* method based on the
364 /// current token type. This should only be used in cases where the type of
365 /// the token really isn't known, e.g. in error recovery.
366 SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) {
368 return ConsumeParen();
369 if (isTokenBracket())
370 return ConsumeBracket();
372 return ConsumeBrace();
373 if (isTokenStringLiteral())
374 return ConsumeStringToken();
375 if (Tok.is(tok::code_completion))
376 return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken()
377 : handleUnexpectedCodeCompletionToken();
378 return ConsumeToken();
381 /// ConsumeParen - This consume method keeps the paren count up-to-date.
383 SourceLocation ConsumeParen() {
384 assert(isTokenParen() && "wrong consume method");
385 if (Tok.getKind() == tok::l_paren)
388 --ParenCount; // Don't let unbalanced )'s drive the count negative.
389 PrevTokLocation = Tok.getLocation();
391 return PrevTokLocation;
394 /// ConsumeBracket - This consume method keeps the bracket count up-to-date.
396 SourceLocation ConsumeBracket() {
397 assert(isTokenBracket() && "wrong consume method");
398 if (Tok.getKind() == tok::l_square)
400 else if (BracketCount)
401 --BracketCount; // Don't let unbalanced ]'s drive the count negative.
403 PrevTokLocation = Tok.getLocation();
405 return PrevTokLocation;
408 /// ConsumeBrace - This consume method keeps the brace count up-to-date.
410 SourceLocation ConsumeBrace() {
411 assert(isTokenBrace() && "wrong consume method");
412 if (Tok.getKind() == tok::l_brace)
415 --BraceCount; // Don't let unbalanced }'s drive the count negative.
417 PrevTokLocation = Tok.getLocation();
419 return PrevTokLocation;
422 /// ConsumeStringToken - Consume the current 'peek token', lexing a new one
423 /// and returning the token kind. This method is specific to strings, as it
424 /// handles string literal concatenation, as per C99 5.1.1.2, translation
426 SourceLocation ConsumeStringToken() {
427 assert(isTokenStringLiteral() &&
428 "Should only consume string literals with this method");
429 PrevTokLocation = Tok.getLocation();
431 return PrevTokLocation;
434 /// \brief Consume the current code-completion token.
436 /// This routine can be called to consume the code-completion token and
437 /// continue processing in special cases where \c cutOffParsing() isn't
438 /// desired, such as token caching or completion with lookahead.
439 SourceLocation ConsumeCodeCompletionToken() {
440 assert(Tok.is(tok::code_completion));
441 PrevTokLocation = Tok.getLocation();
443 return PrevTokLocation;
446 ///\ brief When we are consuming a code-completion token without having
447 /// matched specific position in the grammar, provide code-completion results
448 /// based on context.
450 /// \returns the source location of the code-completion token.
451 SourceLocation handleUnexpectedCodeCompletionToken();
453 /// \brief Abruptly cut off parsing; mainly used when we have reached the
454 /// code-completion point.
455 void cutOffParsing() {
456 if (PP.isCodeCompletionEnabled())
457 PP.setCodeCompletionReached();
458 // Cut off parsing by acting as if we reached the end-of-file.
459 Tok.setKind(tok::eof);
462 /// \brief Determine if we're at the end of the file or at a transition
465 tok::TokenKind Kind = Tok.getKind();
466 return Kind == tok::eof || Kind == tok::annot_module_begin ||
467 Kind == tok::annot_module_end || Kind == tok::annot_module_include;
470 /// \brief Initialize all pragma handlers.
471 void initializePragmaHandlers();
473 /// \brief Destroy and reset all pragma handlers.
474 void resetPragmaHandlers();
476 /// \brief Handle the annotation token produced for #pragma unused(...)
477 void HandlePragmaUnused();
479 /// \brief Handle the annotation token produced for
480 /// #pragma GCC visibility...
481 void HandlePragmaVisibility();
483 /// \brief Handle the annotation token produced for
485 void HandlePragmaPack();
487 /// \brief Handle the annotation token produced for
488 /// #pragma ms_struct...
489 void HandlePragmaMSStruct();
491 /// \brief Handle the annotation token produced for
492 /// #pragma comment...
493 void HandlePragmaMSComment();
495 void HandlePragmaMSPointersToMembers();
497 void HandlePragmaMSVtorDisp();
499 void HandlePragmaMSPragma();
500 bool HandlePragmaMSSection(StringRef PragmaName,
501 SourceLocation PragmaLocation);
502 bool HandlePragmaMSSegment(StringRef PragmaName,
503 SourceLocation PragmaLocation);
504 bool HandlePragmaMSInitSeg(StringRef PragmaName,
505 SourceLocation PragmaLocation);
507 /// \brief Handle the annotation token produced for
509 void HandlePragmaAlign();
511 /// \brief Handle the annotation token produced for
512 /// #pragma clang __debug dump...
513 void HandlePragmaDump();
515 /// \brief Handle the annotation token produced for
516 /// #pragma weak id...
517 void HandlePragmaWeak();
519 /// \brief Handle the annotation token produced for
520 /// #pragma weak id = id...
521 void HandlePragmaWeakAlias();
523 /// \brief Handle the annotation token produced for
524 /// #pragma redefine_extname...
525 void HandlePragmaRedefineExtname();
527 /// \brief Handle the annotation token produced for
528 /// #pragma STDC FP_CONTRACT...
529 void HandlePragmaFPContract();
531 /// \brief Handle the annotation token produced for
532 /// #pragma OPENCL EXTENSION...
533 void HandlePragmaOpenCLExtension();
535 /// \brief Handle the annotation token produced for
536 /// #pragma clang __debug captured
537 StmtResult HandlePragmaCaptured();
539 /// \brief Handle the annotation token produced for
540 /// #pragma clang loop and #pragma unroll.
541 bool HandlePragmaLoopHint(LoopHint &Hint);
543 /// GetLookAheadToken - This peeks ahead N tokens and returns that token
544 /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1)
545 /// returns the token after Tok, etc.
547 /// Note that this differs from the Preprocessor's LookAhead method, because
548 /// the Parser always has one token lexed that the preprocessor doesn't.
550 const Token &GetLookAheadToken(unsigned N) {
551 if (N == 0 || Tok.is(tok::eof)) return Tok;
552 return PP.LookAhead(N-1);
556 /// NextToken - This peeks ahead one token and returns it without
558 const Token &NextToken() {
559 return PP.LookAhead(0);
562 /// getTypeAnnotation - Read a parsed type out of an annotation token.
563 static ParsedType getTypeAnnotation(Token &Tok) {
564 return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
568 static void setTypeAnnotation(Token &Tok, ParsedType T) {
569 Tok.setAnnotationValue(T.getAsOpaquePtr());
572 /// \brief Read an already-translated primary expression out of an annotation
574 static ExprResult getExprAnnotation(Token &Tok) {
575 return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue());
578 /// \brief Set the primary expression corresponding to the given annotation
580 static void setExprAnnotation(Token &Tok, ExprResult ER) {
581 Tok.setAnnotationValue(ER.getAsOpaquePointer());
585 // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to
586 // find a type name by attempting typo correction.
587 bool TryAnnotateTypeOrScopeToken(bool EnteringContext = false,
588 bool NeedType = false);
589 bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext,
593 bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
596 enum AnnotatedNameKind {
597 /// Annotation has failed and emitted an error.
599 /// The identifier is a tentatively-declared name.
601 /// The identifier is a template name. FIXME: Add an annotation for that.
603 /// The identifier can't be resolved.
605 /// Annotation was successful.
609 TryAnnotateName(bool IsAddressOfOperand,
610 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
612 /// Push a tok::annot_cxxscope token onto the token stream.
613 void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
615 /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
616 /// replacing them with the non-context-sensitive keywords. This returns
617 /// true if the token was replaced.
618 bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
619 const char *&PrevSpec, unsigned &DiagID,
621 if (!getLangOpts().AltiVec && !getLangOpts().ZVector)
624 if (Tok.getIdentifierInfo() != Ident_vector &&
625 Tok.getIdentifierInfo() != Ident_bool &&
626 (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel))
629 return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
632 /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
633 /// identifier token, replacing it with the non-context-sensitive __vector.
634 /// This returns true if the token was replaced.
635 bool TryAltiVecVectorToken() {
636 if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) ||
637 Tok.getIdentifierInfo() != Ident_vector) return false;
638 return TryAltiVecVectorTokenOutOfLine();
641 bool TryAltiVecVectorTokenOutOfLine();
642 bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
643 const char *&PrevSpec, unsigned &DiagID,
646 /// Returns true if the current token is the identifier 'instancetype'.
648 /// Should only be used in Objective-C language modes.
649 bool isObjCInstancetype() {
650 assert(getLangOpts().ObjC1);
651 if (Tok.isAnnotation())
653 if (!Ident_instancetype)
654 Ident_instancetype = PP.getIdentifierInfo("instancetype");
655 return Tok.getIdentifierInfo() == Ident_instancetype;
658 /// TryKeywordIdentFallback - For compatibility with system headers using
659 /// keywords as identifiers, attempt to convert the current token to an
660 /// identifier and optionally disable the keyword for the remainder of the
661 /// translation unit. This returns false if the token was not replaced,
662 /// otherwise emits a diagnostic and returns true.
663 bool TryKeywordIdentFallback(bool DisableKeyword);
665 /// \brief Get the TemplateIdAnnotation from the token.
666 TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
668 /// TentativeParsingAction - An object that is used as a kind of "tentative
669 /// parsing transaction". It gets instantiated to mark the token position and
670 /// after the token consumption is done, Commit() or Revert() is called to
671 /// either "commit the consumed tokens" or revert to the previously marked
672 /// token position. Example:
674 /// TentativeParsingAction TPA(*this);
679 class TentativeParsingAction {
682 size_t PrevTentativelyDeclaredIdentifierCount;
683 unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
687 explicit TentativeParsingAction(Parser& p) : P(p) {
689 PrevTentativelyDeclaredIdentifierCount =
690 P.TentativelyDeclaredIdentifiers.size();
691 PrevParenCount = P.ParenCount;
692 PrevBracketCount = P.BracketCount;
693 PrevBraceCount = P.BraceCount;
694 P.PP.EnableBacktrackAtThisPos();
698 assert(isActive && "Parsing action was finished!");
699 P.TentativelyDeclaredIdentifiers.resize(
700 PrevTentativelyDeclaredIdentifierCount);
701 P.PP.CommitBacktrackedTokens();
705 assert(isActive && "Parsing action was finished!");
708 P.TentativelyDeclaredIdentifiers.resize(
709 PrevTentativelyDeclaredIdentifierCount);
710 P.ParenCount = PrevParenCount;
711 P.BracketCount = PrevBracketCount;
712 P.BraceCount = PrevBraceCount;
715 ~TentativeParsingAction() {
716 assert(!isActive && "Forgot to call Commit or Revert!");
719 /// A TentativeParsingAction that automatically reverts in its destructor.
720 /// Useful for disambiguation parses that will always be reverted.
721 class RevertingTentativeParsingAction
722 : private Parser::TentativeParsingAction {
724 RevertingTentativeParsingAction(Parser &P)
725 : Parser::TentativeParsingAction(P) {}
726 ~RevertingTentativeParsingAction() { Revert(); }
729 class UnannotatedTentativeParsingAction;
731 /// ObjCDeclContextSwitch - An object used to switch context from
732 /// an objective-c decl context to its enclosing decl context and
734 class ObjCDeclContextSwitch {
737 SaveAndRestore<bool> WithinObjCContainer;
739 explicit ObjCDeclContextSwitch(Parser &p)
740 : P(p), DC(p.getObjCDeclContext()),
741 WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) {
743 P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC));
745 ~ObjCDeclContextSwitch() {
747 P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC));
751 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
752 /// input. If so, it is consumed and false is returned.
754 /// If a trivial punctuator misspelling is encountered, a FixIt error
755 /// diagnostic is issued and false is returned after recovery.
757 /// If the input is malformed, this emits the specified diagnostic and true is
759 bool ExpectAndConsume(tok::TokenKind ExpectedTok,
760 unsigned Diag = diag::err_expected,
761 StringRef DiagMsg = "");
763 /// \brief The parser expects a semicolon and, if present, will consume it.
765 /// If the next token is not a semicolon, this emits the specified diagnostic,
766 /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
767 /// to the semicolon, consumes that extra token.
768 bool ExpectAndConsumeSemi(unsigned DiagID);
770 /// \brief The kind of extra semi diagnostic to emit.
774 InstanceVariableList = 2,
775 AfterMemberFunctionDefinition = 3
778 /// \brief Consume any extra semi-colons until the end of the line.
779 void ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST = TST_unspecified);
782 //===--------------------------------------------------------------------===//
783 // Scope manipulation
785 /// ParseScope - Introduces a new scope for parsing. The kind of
786 /// scope is determined by ScopeFlags. Objects of this type should
787 /// be created on the stack to coincide with the position where the
788 /// parser enters the new scope, and this object's constructor will
789 /// create that new scope. Similarly, once the object is destroyed
790 /// the parser will exit the scope.
793 ParseScope(const ParseScope &) = delete;
794 void operator=(const ParseScope &) = delete;
797 // ParseScope - Construct a new object to manage a scope in the
798 // parser Self where the new Scope is created with the flags
799 // ScopeFlags, but only when we aren't about to enter a compound statement.
800 ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true,
801 bool BeforeCompoundStmt = false)
803 if (EnteredScope && !BeforeCompoundStmt)
804 Self->EnterScope(ScopeFlags);
806 if (BeforeCompoundStmt)
807 Self->incrementMSManglingNumber();
809 this->Self = nullptr;
813 // Exit - Exit the scope associated with this object now, rather
814 // than waiting until the object is destroyed.
827 /// EnterScope - Start a new scope.
828 void EnterScope(unsigned ScopeFlags);
830 /// ExitScope - Pop a scope off the scope stack.
834 /// \brief RAII object used to modify the scope flags for the current scope.
835 class ParseScopeFlags {
838 ParseScopeFlags(const ParseScopeFlags &) = delete;
839 void operator=(const ParseScopeFlags &) = delete;
842 ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
846 //===--------------------------------------------------------------------===//
847 // Diagnostic Emission and Error recovery.
850 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
851 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
852 DiagnosticBuilder Diag(unsigned DiagID) {
853 return Diag(Tok, DiagID);
857 void SuggestParentheses(SourceLocation Loc, unsigned DK,
858 SourceRange ParenRange);
859 void CheckNestedObjCContexts(SourceLocation AtLoc);
863 /// \brief Control flags for SkipUntil functions.
864 enum SkipUntilFlags {
865 StopAtSemi = 1 << 0, ///< Stop skipping at semicolon
866 /// \brief Stop skipping at specified token, but don't skip the token itself
867 StopBeforeMatch = 1 << 1,
868 StopAtCodeCompletion = 1 << 2 ///< Stop at code completion
871 friend LLVM_CONSTEXPR SkipUntilFlags operator|(SkipUntilFlags L,
873 return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) |
874 static_cast<unsigned>(R));
877 /// SkipUntil - Read tokens until we get to the specified token, then consume
878 /// it (unless StopBeforeMatch is specified). Because we cannot guarantee
879 /// that the token will ever occur, this skips to the next token, or to some
880 /// likely good stopping point. If Flags has StopAtSemi flag, skipping will
881 /// stop at a ';' character.
883 /// If SkipUntil finds the specified token, it returns true, otherwise it
885 bool SkipUntil(tok::TokenKind T,
886 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
887 return SkipUntil(llvm::makeArrayRef(T), Flags);
889 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2,
890 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
891 tok::TokenKind TokArray[] = {T1, T2};
892 return SkipUntil(TokArray, Flags);
894 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3,
895 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
896 tok::TokenKind TokArray[] = {T1, T2, T3};
897 return SkipUntil(TokArray, Flags);
899 bool SkipUntil(ArrayRef<tok::TokenKind> Toks,
900 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0));
902 /// SkipMalformedDecl - Read tokens until we get to some likely good stopping
903 /// point for skipping past a simple-declaration.
904 void SkipMalformedDecl();
907 //===--------------------------------------------------------------------===//
908 // Lexing and parsing of C++ inline methods.
912 /// [class.mem]p1: "... the class is regarded as complete within
913 /// - function bodies
914 /// - default arguments
915 /// - exception-specifications (TODO: C++0x)
916 /// - and brace-or-equal-initializers for non-static data members
917 /// (including such things in nested classes)."
918 /// LateParsedDeclarations build the tree of those elements so they can
919 /// be parsed after parsing the top-level class.
920 class LateParsedDeclaration {
922 virtual ~LateParsedDeclaration();
924 virtual void ParseLexedMethodDeclarations();
925 virtual void ParseLexedMemberInitializers();
926 virtual void ParseLexedMethodDefs();
927 virtual void ParseLexedAttributes();
930 /// Inner node of the LateParsedDeclaration tree that parses
931 /// all its members recursively.
932 class LateParsedClass : public LateParsedDeclaration {
934 LateParsedClass(Parser *P, ParsingClass *C);
935 ~LateParsedClass() override;
937 void ParseLexedMethodDeclarations() override;
938 void ParseLexedMemberInitializers() override;
939 void ParseLexedMethodDefs() override;
940 void ParseLexedAttributes() override;
947 /// Contains the lexed tokens of an attribute with arguments that
948 /// may reference member variables and so need to be parsed at the
949 /// end of the class declaration after parsing all other member
950 /// member declarations.
951 /// FIXME: Perhaps we should change the name of LateParsedDeclaration to
952 /// LateParsedTokens.
953 struct LateParsedAttribute : public LateParsedDeclaration {
956 IdentifierInfo &AttrName;
957 SourceLocation AttrNameLoc;
958 SmallVector<Decl*, 2> Decls;
960 explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
962 : Self(P), AttrName(Name), AttrNameLoc(Loc) {}
964 void ParseLexedAttributes() override;
966 void addDecl(Decl *D) { Decls.push_back(D); }
969 // A list of late-parsed attributes. Used by ParseGNUAttributes.
970 class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> {
972 LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { }
974 bool parseSoon() { return ParseSoon; }
977 bool ParseSoon; // Are we planning to parse these shortly after creation?
980 /// Contains the lexed tokens of a member function definition
981 /// which needs to be parsed at the end of the class declaration
982 /// after parsing all other member declarations.
983 struct LexedMethod : public LateParsedDeclaration {
988 /// \brief Whether this member function had an associated template
989 /// scope. When true, D is a template declaration.
990 /// otherwise, it is a member function declaration.
993 explicit LexedMethod(Parser* P, Decl *MD)
994 : Self(P), D(MD), TemplateScope(false) {}
996 void ParseLexedMethodDefs() override;
999 /// LateParsedDefaultArgument - Keeps track of a parameter that may
1000 /// have a default argument that cannot be parsed yet because it
1001 /// occurs within a member function declaration inside the class
1002 /// (C++ [class.mem]p2).
1003 struct LateParsedDefaultArgument {
1004 explicit LateParsedDefaultArgument(Decl *P,
1005 CachedTokens *Toks = nullptr)
1006 : Param(P), Toks(Toks) { }
1008 /// Param - The parameter declaration for this parameter.
1011 /// Toks - The sequence of tokens that comprises the default
1012 /// argument expression, not including the '=' or the terminating
1013 /// ')' or ','. This will be NULL for parameters that have no
1014 /// default argument.
1018 /// LateParsedMethodDeclaration - A method declaration inside a class that
1019 /// contains at least one entity whose parsing needs to be delayed
1020 /// until the class itself is completely-defined, such as a default
1021 /// argument (C++ [class.mem]p2).
1022 struct LateParsedMethodDeclaration : public LateParsedDeclaration {
1023 explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
1024 : Self(P), Method(M), TemplateScope(false),
1025 ExceptionSpecTokens(nullptr) {}
1027 void ParseLexedMethodDeclarations() override;
1031 /// Method - The method declaration.
1034 /// \brief Whether this member function had an associated template
1035 /// scope. When true, D is a template declaration.
1036 /// othewise, it is a member function declaration.
1039 /// DefaultArgs - Contains the parameters of the function and
1040 /// their default arguments. At least one of the parameters will
1041 /// have a default argument, but all of the parameters of the
1042 /// method will be stored so that they can be reintroduced into
1043 /// scope at the appropriate times.
1044 SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
1046 /// \brief The set of tokens that make up an exception-specification that
1047 /// has not yet been parsed.
1048 CachedTokens *ExceptionSpecTokens;
1051 /// LateParsedMemberInitializer - An initializer for a non-static class data
1052 /// member whose parsing must to be delayed until the class is completely
1053 /// defined (C++11 [class.mem]p2).
1054 struct LateParsedMemberInitializer : public LateParsedDeclaration {
1055 LateParsedMemberInitializer(Parser *P, Decl *FD)
1056 : Self(P), Field(FD) { }
1058 void ParseLexedMemberInitializers() override;
1062 /// Field - The field declaration.
1065 /// CachedTokens - The sequence of tokens that comprises the initializer,
1066 /// including any leading '='.
1070 /// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
1071 /// C++ class, its method declarations that contain parts that won't be
1072 /// parsed until after the definition is completed (C++ [class.mem]p2),
1073 /// the method declarations and possibly attached inline definitions
1074 /// will be stored here with the tokens that will be parsed to create those
1076 typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer;
1078 /// \brief Representation of a class that has been parsed, including
1079 /// any member function declarations or definitions that need to be
1080 /// parsed after the corresponding top-level class is complete.
1081 struct ParsingClass {
1082 ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface)
1083 : TopLevelClass(TopLevelClass), TemplateScope(false),
1084 IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) { }
1086 /// \brief Whether this is a "top-level" class, meaning that it is
1087 /// not nested within another class.
1088 bool TopLevelClass : 1;
1090 /// \brief Whether this class had an associated template
1091 /// scope. When true, TagOrTemplate is a template declaration;
1092 /// othewise, it is a tag declaration.
1093 bool TemplateScope : 1;
1095 /// \brief Whether this class is an __interface.
1096 bool IsInterface : 1;
1098 /// \brief The class or class template whose definition we are parsing.
1099 Decl *TagOrTemplate;
1101 /// LateParsedDeclarations - Method declarations, inline definitions and
1102 /// nested classes that contain pieces whose parsing will be delayed until
1103 /// the top-level class is fully defined.
1104 LateParsedDeclarationsContainer LateParsedDeclarations;
1107 /// \brief The stack of classes that is currently being
1108 /// parsed. Nested and local classes will be pushed onto this stack
1109 /// when they are parsed, and removed afterward.
1110 std::stack<ParsingClass *> ClassStack;
1112 ParsingClass &getCurrentClass() {
1113 assert(!ClassStack.empty() && "No lexed method stacks!");
1114 return *ClassStack.top();
1117 /// \brief RAII object used to manage the parsing of a class definition.
1118 class ParsingClassDefinition {
1121 Sema::ParsingClassState State;
1124 ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass,
1126 : P(P), Popped(false),
1127 State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
1130 /// \brief Pop this class of the stack.
1132 assert(!Popped && "Nested class has already been popped");
1134 P.PopParsingClass(State);
1137 ~ParsingClassDefinition() {
1139 P.PopParsingClass(State);
1143 /// \brief Contains information about any template-specific
1144 /// information that has been parsed prior to parsing declaration
1146 struct ParsedTemplateInfo {
1147 ParsedTemplateInfo()
1148 : Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { }
1150 ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
1151 bool isSpecialization,
1152 bool lastParameterListWasEmpty = false)
1153 : Kind(isSpecialization? ExplicitSpecialization : Template),
1154 TemplateParams(TemplateParams),
1155 LastParameterListWasEmpty(lastParameterListWasEmpty) { }
1157 explicit ParsedTemplateInfo(SourceLocation ExternLoc,
1158 SourceLocation TemplateLoc)
1159 : Kind(ExplicitInstantiation), TemplateParams(nullptr),
1160 ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
1161 LastParameterListWasEmpty(false){ }
1163 /// \brief The kind of template we are parsing.
1165 /// \brief We are not parsing a template at all.
1167 /// \brief We are parsing a template declaration.
1169 /// \brief We are parsing an explicit specialization.
1170 ExplicitSpecialization,
1171 /// \brief We are parsing an explicit instantiation.
1172 ExplicitInstantiation
1175 /// \brief The template parameter lists, for template declarations
1176 /// and explicit specializations.
1177 TemplateParameterLists *TemplateParams;
1179 /// \brief The location of the 'extern' keyword, if any, for an explicit
1181 SourceLocation ExternLoc;
1183 /// \brief The location of the 'template' keyword, for an explicit
1185 SourceLocation TemplateLoc;
1187 /// \brief Whether the last template parameter list was empty.
1188 bool LastParameterListWasEmpty;
1190 SourceRange getSourceRange() const LLVM_READONLY;
1193 void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
1194 void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
1196 static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
1197 static void LateTemplateParserCleanupCallback(void *P);
1199 Sema::ParsingClassState
1200 PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface);
1201 void DeallocateParsedClasses(ParsingClass *Class);
1202 void PopParsingClass(Sema::ParsingClassState);
1204 enum CachedInitKind {
1205 CIK_DefaultArgument,
1206 CIK_DefaultInitializer
1209 NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS,
1210 AttributeList *AccessAttrs,
1211 ParsingDeclarator &D,
1212 const ParsedTemplateInfo &TemplateInfo,
1213 const VirtSpecifiers& VS,
1214 SourceLocation PureSpecLoc);
1215 void ParseCXXNonStaticMemberInitializer(Decl *VarD);
1216 void ParseLexedAttributes(ParsingClass &Class);
1217 void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1218 bool EnterScope, bool OnDefinition);
1219 void ParseLexedAttribute(LateParsedAttribute &LA,
1220 bool EnterScope, bool OnDefinition);
1221 void ParseLexedMethodDeclarations(ParsingClass &Class);
1222 void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
1223 void ParseLexedMethodDefs(ParsingClass &Class);
1224 void ParseLexedMethodDef(LexedMethod &LM);
1225 void ParseLexedMemberInitializers(ParsingClass &Class);
1226 void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
1227 void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod);
1228 bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
1229 bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK);
1230 bool ConsumeAndStoreConditional(CachedTokens &Toks);
1231 bool ConsumeAndStoreUntil(tok::TokenKind T1,
1233 bool StopAtSemi = true,
1234 bool ConsumeFinalToken = true) {
1235 return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
1237 bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
1239 bool StopAtSemi = true,
1240 bool ConsumeFinalToken = true);
1242 //===--------------------------------------------------------------------===//
1243 // C99 6.9: External Definitions.
1244 struct ParsedAttributesWithRange : ParsedAttributes {
1245 ParsedAttributesWithRange(AttributeFactory &factory)
1246 : ParsedAttributes(factory) {}
1251 DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
1252 ParsingDeclSpec *DS = nullptr);
1253 bool isDeclarationAfterDeclarator();
1254 bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
1255 DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(
1256 ParsedAttributesWithRange &attrs,
1257 ParsingDeclSpec *DS = nullptr,
1258 AccessSpecifier AS = AS_none);
1259 DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
1260 ParsingDeclSpec &DS,
1261 AccessSpecifier AS);
1263 void SkipFunctionBody();
1264 Decl *ParseFunctionDefinition(ParsingDeclarator &D,
1265 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1266 LateParsedAttrList *LateParsedAttrs = nullptr);
1267 void ParseKNRParamDeclarations(Declarator &D);
1268 // EndLoc, if non-NULL, is filled with the location of the last token of
1270 ExprResult ParseSimpleAsm(SourceLocation *EndLoc = nullptr);
1271 ExprResult ParseAsmStringLiteral();
1273 // Objective-C External Declarations
1274 void MaybeSkipAttributes(tok::ObjCKeywordKind Kind);
1275 DeclGroupPtrTy ParseObjCAtDirectives();
1276 DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
1277 Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
1278 ParsedAttributes &prefixAttrs);
1279 class ObjCTypeParamListScope;
1280 ObjCTypeParamList *parseObjCTypeParamList();
1281 ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs(
1282 ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
1283 SmallVectorImpl<IdentifierLocPair> &protocolIdents,
1284 SourceLocation &rAngleLoc, bool mayBeProtocolList = true);
1286 void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
1287 BalancedDelimiterTracker &T,
1288 SmallVectorImpl<Decl *> &AllIvarDecls,
1289 bool RBraceMissing);
1290 void ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1291 tok::ObjCKeywordKind visibility,
1292 SourceLocation atLoc);
1293 bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P,
1294 SmallVectorImpl<SourceLocation> &PLocs,
1295 bool WarnOnDeclarations,
1296 bool ForObjCContainer,
1297 SourceLocation &LAngleLoc,
1298 SourceLocation &EndProtoLoc,
1299 bool consumeLastToken);
1301 /// Parse the first angle-bracket-delimited clause for an
1302 /// Objective-C object or object pointer type, which may be either
1303 /// type arguments or protocol qualifiers.
1304 void parseObjCTypeArgsOrProtocolQualifiers(
1305 ParsedType baseType,
1306 SourceLocation &typeArgsLAngleLoc,
1307 SmallVectorImpl<ParsedType> &typeArgs,
1308 SourceLocation &typeArgsRAngleLoc,
1309 SourceLocation &protocolLAngleLoc,
1310 SmallVectorImpl<Decl *> &protocols,
1311 SmallVectorImpl<SourceLocation> &protocolLocs,
1312 SourceLocation &protocolRAngleLoc,
1313 bool consumeLastToken,
1314 bool warnOnIncompleteProtocols);
1316 /// Parse either Objective-C type arguments or protocol qualifiers; if the
1317 /// former, also parse protocol qualifiers afterward.
1318 void parseObjCTypeArgsAndProtocolQualifiers(
1319 ParsedType baseType,
1320 SourceLocation &typeArgsLAngleLoc,
1321 SmallVectorImpl<ParsedType> &typeArgs,
1322 SourceLocation &typeArgsRAngleLoc,
1323 SourceLocation &protocolLAngleLoc,
1324 SmallVectorImpl<Decl *> &protocols,
1325 SmallVectorImpl<SourceLocation> &protocolLocs,
1326 SourceLocation &protocolRAngleLoc,
1327 bool consumeLastToken);
1329 /// Parse a protocol qualifier type such as '<NSCopying>', which is
1330 /// an anachronistic way of writing 'id<NSCopying>'.
1331 TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc);
1333 /// Parse Objective-C type arguments and protocol qualifiers, extending the
1334 /// current type with the parsed result.
1335 TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc,
1337 bool consumeLastToken,
1338 SourceLocation &endLoc);
1340 void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
1342 DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
1343 ParsedAttributes &prefixAttrs);
1345 struct ObjCImplParsingDataRAII {
1349 typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer;
1350 LateParsedObjCMethodContainer LateParsedObjCMethods;
1352 ObjCImplParsingDataRAII(Parser &parser, Decl *D)
1353 : P(parser), Dcl(D), HasCFunction(false) {
1354 P.CurParsedObjCImpl = this;
1357 ~ObjCImplParsingDataRAII();
1359 void finish(SourceRange AtEnd);
1360 bool isFinished() const { return Finished; }
1365 ObjCImplParsingDataRAII *CurParsedObjCImpl;
1366 void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl);
1368 DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc);
1369 DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
1370 Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
1371 Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
1372 Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
1374 IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
1375 // Definitions for Objective-c context sensitive keywords recognition.
1377 objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
1378 objc_nonnull, objc_nullable, objc_null_unspecified,
1381 IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
1383 bool isTokIdentifier_in() const;
1385 ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, Declarator::TheContext Ctx,
1386 ParsedAttributes *ParamAttrs);
1387 void ParseObjCMethodRequirement();
1388 Decl *ParseObjCMethodPrototype(
1389 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1390 bool MethodDefinition = true);
1391 Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
1392 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1393 bool MethodDefinition=true);
1394 void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
1396 Decl *ParseObjCMethodDefinition();
1399 //===--------------------------------------------------------------------===//
1400 // C99 6.5: Expressions.
1402 /// TypeCastState - State whether an expression is or may be a type cast.
1403 enum TypeCastState {
1409 ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast);
1410 ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast);
1411 ExprResult ParseConstraintExpression();
1412 // Expr that doesn't include commas.
1413 ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast);
1415 ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1416 unsigned &NumLineToksConsumed,
1418 bool IsUnevaluated);
1421 ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
1423 ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
1425 ExprResult ParseRHSOfBinaryExpression(ExprResult LHS,
1426 prec::Level MinPrec);
1427 ExprResult ParseCastExpression(bool isUnaryExpression,
1428 bool isAddressOfOperand,
1430 TypeCastState isTypeCast);
1431 ExprResult ParseCastExpression(bool isUnaryExpression,
1432 bool isAddressOfOperand = false,
1433 TypeCastState isTypeCast = NotTypeCast);
1435 /// Returns true if the next token cannot start an expression.
1436 bool isNotExpressionStart();
1438 /// Returns true if the next token would start a postfix-expression
1440 bool isPostfixExpressionSuffixStart() {
1441 tok::TokenKind K = Tok.getKind();
1442 return (K == tok::l_square || K == tok::l_paren ||
1443 K == tok::period || K == tok::arrow ||
1444 K == tok::plusplus || K == tok::minusminus);
1447 ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
1448 ExprResult ParseUnaryExprOrTypeTraitExpression();
1449 ExprResult ParseBuiltinPrimaryExpression();
1451 ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1454 SourceRange &CastRange);
1456 typedef SmallVector<Expr*, 20> ExprListTy;
1457 typedef SmallVector<SourceLocation, 20> CommaLocsTy;
1459 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1460 bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
1461 SmallVectorImpl<SourceLocation> &CommaLocs,
1462 std::function<void()> Completer = nullptr);
1464 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
1465 /// used for misc language extensions.
1466 bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
1467 SmallVectorImpl<SourceLocation> &CommaLocs);
1470 /// ParenParseOption - Control what ParseParenExpression will parse.
1471 enum ParenParseOption {
1472 SimpleExpr, // Only parse '(' expression ')'
1473 CompoundStmt, // Also allow '(' compound-statement ')'
1474 CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
1475 CastExpr // Also allow '(' type-name ')' <anything>
1477 ExprResult ParseParenExpression(ParenParseOption &ExprType,
1478 bool stopIfCastExpr,
1481 SourceLocation &RParenLoc);
1483 ExprResult ParseCXXAmbiguousParenExpression(
1484 ParenParseOption &ExprType, ParsedType &CastTy,
1485 BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt);
1486 ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
1487 SourceLocation LParenLoc,
1488 SourceLocation RParenLoc);
1490 ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
1492 ExprResult ParseGenericSelectionExpression();
1494 ExprResult ParseObjCBoolLiteral();
1496 ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T);
1498 //===--------------------------------------------------------------------===//
1500 ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
1501 Token &Replacement);
1502 ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
1504 bool areTokensAdjacent(const Token &A, const Token &B);
1506 void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
1507 bool EnteringContext, IdentifierInfo &II,
1510 bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
1511 ParsedType ObjectType,
1512 bool EnteringContext,
1513 bool *MayBePseudoDestructor = nullptr,
1514 bool IsTypename = false,
1515 IdentifierInfo **LastII = nullptr);
1517 void CheckForLParenAfterColonColon();
1519 //===--------------------------------------------------------------------===//
1520 // C++0x 5.1.2: Lambda expressions
1522 // [...] () -> type {...}
1523 ExprResult ParseLambdaExpression();
1524 ExprResult TryParseLambdaExpression();
1525 Optional<unsigned> ParseLambdaIntroducer(LambdaIntroducer &Intro,
1526 bool *SkippedInits = nullptr);
1527 bool TryParseLambdaIntroducer(LambdaIntroducer &Intro);
1528 ExprResult ParseLambdaExpressionAfterIntroducer(
1529 LambdaIntroducer &Intro);
1531 //===--------------------------------------------------------------------===//
1532 // C++ 5.2p1: C++ Casts
1533 ExprResult ParseCXXCasts();
1535 //===--------------------------------------------------------------------===//
1536 // C++ 5.2p1: C++ Type Identification
1537 ExprResult ParseCXXTypeid();
1539 //===--------------------------------------------------------------------===//
1540 // C++ : Microsoft __uuidof Expression
1541 ExprResult ParseCXXUuidof();
1543 //===--------------------------------------------------------------------===//
1544 // C++ 5.2.4: C++ Pseudo-Destructor Expressions
1545 ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1546 tok::TokenKind OpKind,
1548 ParsedType ObjectType);
1550 //===--------------------------------------------------------------------===//
1551 // C++ 9.3.2: C++ 'this' pointer
1552 ExprResult ParseCXXThis();
1554 //===--------------------------------------------------------------------===//
1555 // C++ 15: C++ Throw Expression
1556 ExprResult ParseThrowExpression();
1558 ExceptionSpecificationType tryParseExceptionSpecification(
1560 SourceRange &SpecificationRange,
1561 SmallVectorImpl<ParsedType> &DynamicExceptions,
1562 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
1563 ExprResult &NoexceptExpr,
1564 CachedTokens *&ExceptionSpecTokens);
1566 // EndLoc is filled with the location of the last token of the specification.
1567 ExceptionSpecificationType ParseDynamicExceptionSpecification(
1568 SourceRange &SpecificationRange,
1569 SmallVectorImpl<ParsedType> &Exceptions,
1570 SmallVectorImpl<SourceRange> &Ranges);
1572 //===--------------------------------------------------------------------===//
1573 // C++0x 8: Function declaration trailing-return-type
1574 TypeResult ParseTrailingReturnType(SourceRange &Range);
1576 //===--------------------------------------------------------------------===//
1577 // C++ 2.13.5: C++ Boolean Literals
1578 ExprResult ParseCXXBoolLiteral();
1580 //===--------------------------------------------------------------------===//
1581 // C++ 5.2.3: Explicit type conversion (functional notation)
1582 ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
1584 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1585 /// This should only be called when the current token is known to be part of
1586 /// simple-type-specifier.
1587 void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
1589 bool ParseCXXTypeSpecifierSeq(DeclSpec &DS);
1591 //===--------------------------------------------------------------------===//
1592 // C++ 5.3.4 and 5.3.5: C++ new and delete
1593 bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs,
1595 void ParseDirectNewDeclarator(Declarator &D);
1596 ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
1597 ExprResult ParseCXXDeleteExpression(bool UseGlobal,
1598 SourceLocation Start);
1600 //===--------------------------------------------------------------------===//
1601 // C++ if/switch/while condition expression.
1602 Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt,
1604 Sema::ConditionKind CK);
1606 //===--------------------------------------------------------------------===//
1609 ExprResult ParseCoyieldExpression();
1611 //===--------------------------------------------------------------------===//
1612 // C99 6.7.8: Initialization.
1614 /// ParseInitializer
1615 /// initializer: [C99 6.7.8]
1616 /// assignment-expression
1618 ExprResult ParseInitializer() {
1619 if (Tok.isNot(tok::l_brace))
1620 return ParseAssignmentExpression();
1621 return ParseBraceInitializer();
1623 bool MayBeDesignationStart();
1624 ExprResult ParseBraceInitializer();
1625 ExprResult ParseInitializerWithPotentialDesignator();
1627 //===--------------------------------------------------------------------===//
1628 // clang Expressions
1630 ExprResult ParseBlockLiteralExpression(); // ^{...}
1632 //===--------------------------------------------------------------------===//
1633 // Objective-C Expressions
1634 ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
1635 ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
1636 ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
1637 ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
1638 ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
1639 ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
1640 ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
1641 ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
1642 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
1643 ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
1644 ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
1645 bool isSimpleObjCMessageExpression();
1646 ExprResult ParseObjCMessageExpression();
1647 ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
1648 SourceLocation SuperLoc,
1649 ParsedType ReceiverType,
1650 Expr *ReceiverExpr);
1651 ExprResult ParseAssignmentExprWithObjCMessageExprStart(
1652 SourceLocation LBracloc, SourceLocation SuperLoc,
1653 ParsedType ReceiverType, Expr *ReceiverExpr);
1654 bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
1656 //===--------------------------------------------------------------------===//
1657 // C99 6.8: Statements and Blocks.
1659 /// A SmallVector of statements, with stack size 32 (as that is the only one
1661 typedef SmallVector<Stmt*, 32> StmtVector;
1662 /// A SmallVector of expressions, with stack size 12 (the maximum used.)
1663 typedef SmallVector<Expr*, 12> ExprVector;
1664 /// A SmallVector of types.
1665 typedef SmallVector<ParsedType, 12> TypeVector;
1667 StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
1668 bool AllowOpenMPStandalone = false);
1669 enum AllowedContsructsKind {
1670 /// \brief Allow any declarations, statements, OpenMP directives.
1672 /// \brief Allow only statements and non-standalone OpenMP directives.
1673 ACK_StatementsOpenMPNonStandalone,
1674 /// \brief Allow statements and all executable OpenMP directives
1675 ACK_StatementsOpenMPAnyExecutable
1678 ParseStatementOrDeclaration(StmtVector &Stmts, AllowedContsructsKind Allowed,
1679 SourceLocation *TrailingElseLoc = nullptr);
1680 StmtResult ParseStatementOrDeclarationAfterAttributes(
1682 AllowedContsructsKind Allowed,
1683 SourceLocation *TrailingElseLoc,
1684 ParsedAttributesWithRange &Attrs);
1685 StmtResult ParseExprStatement();
1686 StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs);
1687 StmtResult ParseCaseStatement(bool MissingCase = false,
1688 ExprResult Expr = ExprResult());
1689 StmtResult ParseDefaultStatement();
1690 StmtResult ParseCompoundStatement(bool isStmtExpr = false);
1691 StmtResult ParseCompoundStatement(bool isStmtExpr,
1692 unsigned ScopeFlags);
1693 void ParseCompoundStatementLeadingPragmas();
1694 StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
1695 bool ParseParenExprOrCondition(StmtResult *InitStmt,
1696 Sema::ConditionResult &CondResult,
1698 Sema::ConditionKind CK);
1699 StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
1700 StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
1701 StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
1702 StmtResult ParseDoStatement();
1703 StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
1704 StmtResult ParseGotoStatement();
1705 StmtResult ParseContinueStatement();
1706 StmtResult ParseBreakStatement();
1707 StmtResult ParseReturnStatement();
1708 StmtResult ParseAsmStatement(bool &msAsm);
1709 StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
1710 StmtResult ParsePragmaLoopHint(StmtVector &Stmts,
1711 AllowedContsructsKind Allowed,
1712 SourceLocation *TrailingElseLoc,
1713 ParsedAttributesWithRange &Attrs);
1715 /// \brief Describes the behavior that should be taken for an __if_exists
1717 enum IfExistsBehavior {
1718 /// \brief Parse the block; this code is always used.
1720 /// \brief Skip the block entirely; this code is never used.
1722 /// \brief Parse the block as a dependent block, which may be used in
1723 /// some template instantiations but not others.
1727 /// \brief Describes the condition of a Microsoft __if_exists or
1728 /// __if_not_exists block.
1729 struct IfExistsCondition {
1730 /// \brief The location of the initial keyword.
1731 SourceLocation KeywordLoc;
1732 /// \brief Whether this is an __if_exists block (rather than an
1733 /// __if_not_exists block).
1736 /// \brief Nested-name-specifier preceding the name.
1739 /// \brief The name we're looking for.
1742 /// \brief The behavior of this __if_exists or __if_not_exists block
1744 IfExistsBehavior Behavior;
1747 bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
1748 void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
1749 void ParseMicrosoftIfExistsExternalDeclaration();
1750 void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
1751 AccessSpecifier& CurAS);
1752 bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
1754 bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
1755 SmallVectorImpl<Expr *> &Constraints,
1756 SmallVectorImpl<Expr *> &Exprs);
1758 //===--------------------------------------------------------------------===//
1759 // C++ 6: Statements and Blocks
1761 StmtResult ParseCXXTryBlock();
1762 StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
1763 StmtResult ParseCXXCatchBlock(bool FnCatch = false);
1765 //===--------------------------------------------------------------------===//
1766 // MS: SEH Statements and Blocks
1768 StmtResult ParseSEHTryBlock();
1769 StmtResult ParseSEHExceptBlock(SourceLocation Loc);
1770 StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
1771 StmtResult ParseSEHLeaveStatement();
1773 //===--------------------------------------------------------------------===//
1774 // Objective-C Statements
1776 StmtResult ParseObjCAtStatement(SourceLocation atLoc);
1777 StmtResult ParseObjCTryStmt(SourceLocation atLoc);
1778 StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
1779 StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
1780 StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
1783 //===--------------------------------------------------------------------===//
1784 // C99 6.7: Declarations.
1786 /// A context for parsing declaration specifiers. TODO: flesh this
1787 /// out, there are other significant restrictions on specifiers than
1788 /// would be best implemented in the parser.
1789 enum DeclSpecContext {
1790 DSC_normal, // normal context
1791 DSC_class, // class context, enables 'friend'
1792 DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
1793 DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
1794 DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration
1795 DSC_top_level, // top-level/namespace declaration context
1796 DSC_template_type_arg, // template type argument context
1797 DSC_objc_method_result, // ObjC method result context, enables 'instancetype'
1798 DSC_condition // condition declaration context
1801 /// Is this a context in which we are parsing just a type-specifier (or
1802 /// trailing-type-specifier)?
1803 static bool isTypeSpecifier(DeclSpecContext DSC) {
1808 case DSC_objc_method_result:
1812 case DSC_template_type_arg:
1813 case DSC_type_specifier:
1815 case DSC_alias_declaration:
1818 llvm_unreachable("Missing DeclSpecContext case");
1821 /// Information on a C++0x for-range-initializer found while parsing a
1822 /// declaration which turns out to be a for-range-declaration.
1823 struct ForRangeInit {
1824 SourceLocation ColonLoc;
1825 ExprResult RangeExpr;
1827 bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
1830 DeclGroupPtrTy ParseDeclaration(unsigned Context, SourceLocation &DeclEnd,
1831 ParsedAttributesWithRange &attrs);
1832 DeclGroupPtrTy ParseSimpleDeclaration(unsigned Context,
1833 SourceLocation &DeclEnd,
1834 ParsedAttributesWithRange &attrs,
1836 ForRangeInit *FRI = nullptr);
1837 bool MightBeDeclarator(unsigned Context);
1838 DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, unsigned Context,
1839 SourceLocation *DeclEnd = nullptr,
1840 ForRangeInit *FRI = nullptr);
1841 Decl *ParseDeclarationAfterDeclarator(Declarator &D,
1842 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
1843 bool ParseAsmAttributesAfterDeclarator(Declarator &D);
1844 Decl *ParseDeclarationAfterDeclaratorAndAttributes(
1846 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1847 ForRangeInit *FRI = nullptr);
1848 Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
1849 Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
1851 /// \brief When in code-completion, skip parsing of the function/method body
1852 /// unless the body contains the code-completion point.
1854 /// \returns true if the function body was skipped.
1855 bool trySkippingFunctionBody();
1857 bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
1858 const ParsedTemplateInfo &TemplateInfo,
1859 AccessSpecifier AS, DeclSpecContext DSC,
1860 ParsedAttributesWithRange &Attrs);
1861 DeclSpecContext getDeclSpecContextFromDeclaratorContext(unsigned Context);
1862 void ParseDeclarationSpecifiers(DeclSpec &DS,
1863 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1864 AccessSpecifier AS = AS_none,
1865 DeclSpecContext DSC = DSC_normal,
1866 LateParsedAttrList *LateAttrs = nullptr);
1867 bool DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
1868 DeclSpecContext DSContext,
1869 LateParsedAttrList *LateAttrs = nullptr);
1871 void ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS = AS_none,
1872 DeclSpecContext DSC = DSC_normal);
1874 void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
1875 Declarator::TheContext Context);
1877 void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
1878 const ParsedTemplateInfo &TemplateInfo,
1879 AccessSpecifier AS, DeclSpecContext DSC);
1880 void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
1881 void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType,
1884 void ParseStructDeclaration(
1885 ParsingDeclSpec &DS,
1886 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback);
1888 bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
1889 bool isTypeSpecifierQualifier();
1891 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
1892 /// is definitely a type-specifier. Return false if it isn't part of a type
1893 /// specifier or if we're not sure.
1894 bool isKnownToBeTypeSpecifier(const Token &Tok) const;
1896 /// \brief Return true if we know that we are definitely looking at a
1897 /// decl-specifier, and isn't part of an expression such as a function-style
1898 /// cast. Return false if it's no a decl-specifier, or we're not sure.
1899 bool isKnownToBeDeclarationSpecifier() {
1900 if (getLangOpts().CPlusPlus)
1901 return isCXXDeclarationSpecifier() == TPResult::True;
1902 return isDeclarationSpecifier(true);
1905 /// isDeclarationStatement - Disambiguates between a declaration or an
1906 /// expression statement, when parsing function bodies.
1907 /// Returns true for declaration, false for expression.
1908 bool isDeclarationStatement() {
1909 if (getLangOpts().CPlusPlus)
1910 return isCXXDeclarationStatement();
1911 return isDeclarationSpecifier(true);
1914 /// isForInitDeclaration - Disambiguates between a declaration or an
1915 /// expression in the context of the C 'clause-1' or the C++
1916 // 'for-init-statement' part of a 'for' statement.
1917 /// Returns true for declaration, false for expression.
1918 bool isForInitDeclaration() {
1919 if (getLangOpts().CPlusPlus)
1920 return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
1921 return isDeclarationSpecifier(true);
1924 /// \brief Determine whether this is a C++1z for-range-identifier.
1925 bool isForRangeIdentifier();
1927 /// \brief Determine whether we are currently at the start of an Objective-C
1928 /// class message that appears to be missing the open bracket '['.
1929 bool isStartOfObjCClassMessageMissingOpenBracket();
1931 /// \brief Starting with a scope specifier, identifier, or
1932 /// template-id that refers to the current class, determine whether
1933 /// this is a constructor declarator.
1934 bool isConstructorDeclarator(bool Unqualified);
1936 /// \brief Specifies the context in which type-id/expression
1937 /// disambiguation will occur.
1938 enum TentativeCXXTypeIdContext {
1941 TypeIdAsTemplateArgument
1945 /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
1946 /// whether the parens contain an expression or a type-id.
1947 /// Returns true for a type-id and false for an expression.
1948 bool isTypeIdInParens(bool &isAmbiguous) {
1949 if (getLangOpts().CPlusPlus)
1950 return isCXXTypeId(TypeIdInParens, isAmbiguous);
1951 isAmbiguous = false;
1952 return isTypeSpecifierQualifier();
1954 bool isTypeIdInParens() {
1956 return isTypeIdInParens(isAmbiguous);
1959 /// \brief Checks if the current tokens form type-id or expression.
1960 /// It is similar to isTypeIdInParens but does not suppose that type-id
1961 /// is in parenthesis.
1962 bool isTypeIdUnambiguously() {
1964 if (getLangOpts().CPlusPlus)
1965 return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous);
1966 return isTypeSpecifierQualifier();
1969 /// isCXXDeclarationStatement - C++-specialized function that disambiguates
1970 /// between a declaration or an expression statement, when parsing function
1971 /// bodies. Returns true for declaration, false for expression.
1972 bool isCXXDeclarationStatement();
1974 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
1975 /// between a simple-declaration or an expression-statement.
1976 /// If during the disambiguation process a parsing error is encountered,
1977 /// the function returns true to let the declaration parsing code handle it.
1978 /// Returns false if the statement is disambiguated as expression.
1979 bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
1981 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
1982 /// a constructor-style initializer, when parsing declaration statements.
1983 /// Returns true for function declarator and false for constructor-style
1984 /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
1985 /// might be a constructor-style initializer.
1986 /// If during the disambiguation process a parsing error is encountered,
1987 /// the function returns true to let the declaration parsing code handle it.
1988 bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr);
1990 struct ConditionDeclarationOrInitStatementState;
1991 enum class ConditionOrInitStatement {
1992 Expression, ///< Disambiguated as an expression (either kind).
1993 ConditionDecl, ///< Disambiguated as the declaration form of condition.
1994 InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement.
1995 Error ///< Can't be any of the above!
1997 /// \brief Disambiguates between the different kinds of things that can happen
1998 /// after 'if (' or 'switch ('. This could be one of two different kinds of
1999 /// declaration (depending on whether there is a ';' later) or an expression.
2000 ConditionOrInitStatement
2001 isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt);
2003 bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
2004 bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
2006 return isCXXTypeId(Context, isAmbiguous);
2009 /// TPResult - Used as the result value for functions whose purpose is to
2010 /// disambiguate C++ constructs by "tentatively parsing" them.
2011 enum class TPResult {
2012 True, False, Ambiguous, Error
2015 /// \brief Based only on the given token kind, determine whether we know that
2016 /// we're at the start of an expression or a type-specifier-seq (which may
2017 /// be an expression, in C++).
2019 /// This routine does not attempt to resolve any of the trick cases, e.g.,
2020 /// those involving lookup of identifiers.
2022 /// \returns \c TPR_true if this token starts an expression, \c TPR_false if
2023 /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot
2025 TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind);
2027 /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a
2028 /// declaration specifier, TPResult::False if it is not,
2029 /// TPResult::Ambiguous if it could be either a decl-specifier or a
2030 /// function-style cast, and TPResult::Error if a parsing error was
2031 /// encountered. If it could be a braced C++11 function-style cast, returns
2032 /// BracedCastResult.
2033 /// Doesn't consume tokens.
2035 isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False,
2036 bool *HasMissingTypename = nullptr);
2038 /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
2039 /// \c TPResult::Ambiguous, determine whether the decl-specifier would be
2040 /// a type-specifier other than a cv-qualifier.
2041 bool isCXXDeclarationSpecifierAType();
2043 /// \brief Determine whether an identifier has been tentatively declared as a
2044 /// non-type. Such tentative declarations should not be found to name a type
2045 /// during a tentative parse, but also should not be annotated as a non-type.
2046 bool isTentativelyDeclared(IdentifierInfo *II);
2048 // "Tentative parsing" functions, used for disambiguation. If a parsing error
2049 // is encountered they will return TPResult::Error.
2050 // Returning TPResult::True/False indicates that the ambiguity was
2051 // resolved and tentative parsing may stop. TPResult::Ambiguous indicates
2052 // that more tentative parsing is necessary for disambiguation.
2053 // They all consume tokens, so backtracking should be used after calling them.
2055 TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
2056 TPResult TryParseTypeofSpecifier();
2057 TPResult TryParseProtocolQualifiers();
2058 TPResult TryParsePtrOperatorSeq();
2059 TPResult TryParseOperatorId();
2060 TPResult TryParseInitDeclaratorList();
2061 TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier=true);
2063 TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr,
2064 bool VersusTemplateArg = false);
2065 TPResult TryParseFunctionDeclarator();
2066 TPResult TryParseBracketDeclarator();
2067 TPResult TryConsumeDeclarationSpecifier();
2070 TypeResult ParseTypeName(SourceRange *Range = nullptr,
2071 Declarator::TheContext Context
2072 = Declarator::TypeNameContext,
2073 AccessSpecifier AS = AS_none,
2074 Decl **OwnedType = nullptr,
2075 ParsedAttributes *Attrs = nullptr);
2078 void ParseBlockId(SourceLocation CaretLoc);
2080 // Check for the start of a C++11 attribute-specifier-seq in a context where
2081 // an attribute is not allowed.
2082 bool CheckProhibitedCXX11Attribute() {
2083 assert(Tok.is(tok::l_square));
2084 if (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))
2086 return DiagnoseProhibitedCXX11Attribute();
2088 bool DiagnoseProhibitedCXX11Attribute();
2089 void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2090 SourceLocation CorrectLocation) {
2091 if (!getLangOpts().CPlusPlus11)
2093 if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
2094 Tok.isNot(tok::kw_alignas))
2096 DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
2098 void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2099 SourceLocation CorrectLocation);
2101 void handleDeclspecAlignBeforeClassKey(ParsedAttributesWithRange &Attrs,
2102 DeclSpec &DS, Sema::TagUseKind TUK);
2104 void ProhibitAttributes(ParsedAttributesWithRange &attrs) {
2105 if (!attrs.Range.isValid()) return;
2106 DiagnoseProhibitedAttributes(attrs);
2109 void DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs);
2111 // Forbid C++11 attributes that appear on certain syntactic
2112 // locations which standard permits but we don't supported yet,
2113 // for example, attributes appertain to decl specifiers.
2114 void ProhibitCXX11Attributes(ParsedAttributesWithRange &attrs);
2116 /// \brief Skip C++11 attributes and return the end location of the last one.
2117 /// \returns SourceLocation() if there are no attributes.
2118 SourceLocation SkipCXX11Attributes();
2120 /// \brief Diagnose and skip C++11 attributes that appear in syntactic
2121 /// locations where attributes are not allowed.
2122 void DiagnoseAndSkipCXX11Attributes();
2124 /// \brief Parses syntax-generic attribute arguments for attributes which are
2125 /// known to the implementation, and adds them to the given ParsedAttributes
2126 /// list with the given attribute syntax. Returns the number of arguments
2127 /// parsed for the attribute.
2129 ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2130 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2131 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2132 AttributeList::Syntax Syntax);
2134 void MaybeParseGNUAttributes(Declarator &D,
2135 LateParsedAttrList *LateAttrs = nullptr) {
2136 if (Tok.is(tok::kw___attribute)) {
2137 ParsedAttributes attrs(AttrFactory);
2138 SourceLocation endLoc;
2139 ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D);
2140 D.takeAttributes(attrs, endLoc);
2143 void MaybeParseGNUAttributes(ParsedAttributes &attrs,
2144 SourceLocation *endLoc = nullptr,
2145 LateParsedAttrList *LateAttrs = nullptr) {
2146 if (Tok.is(tok::kw___attribute))
2147 ParseGNUAttributes(attrs, endLoc, LateAttrs);
2149 void ParseGNUAttributes(ParsedAttributes &attrs,
2150 SourceLocation *endLoc = nullptr,
2151 LateParsedAttrList *LateAttrs = nullptr,
2152 Declarator *D = nullptr);
2153 void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
2154 SourceLocation AttrNameLoc,
2155 ParsedAttributes &Attrs,
2156 SourceLocation *EndLoc,
2157 IdentifierInfo *ScopeName,
2158 SourceLocation ScopeLoc,
2159 AttributeList::Syntax Syntax,
2161 IdentifierLoc *ParseIdentifierLoc();
2163 void MaybeParseCXX11Attributes(Declarator &D) {
2164 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
2165 ParsedAttributesWithRange attrs(AttrFactory);
2166 SourceLocation endLoc;
2167 ParseCXX11Attributes(attrs, &endLoc);
2168 D.takeAttributes(attrs, endLoc);
2171 void MaybeParseCXX11Attributes(ParsedAttributes &attrs,
2172 SourceLocation *endLoc = nullptr) {
2173 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
2174 ParsedAttributesWithRange attrsWithRange(AttrFactory);
2175 ParseCXX11Attributes(attrsWithRange, endLoc);
2176 attrs.takeAllFrom(attrsWithRange);
2179 void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2180 SourceLocation *endLoc = nullptr,
2181 bool OuterMightBeMessageSend = false) {
2182 if (getLangOpts().CPlusPlus11 &&
2183 isCXX11AttributeSpecifier(false, OuterMightBeMessageSend))
2184 ParseCXX11Attributes(attrs, endLoc);
2187 void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
2188 SourceLocation *EndLoc = nullptr);
2189 void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2190 SourceLocation *EndLoc = nullptr);
2191 /// \brief Parses a C++-style attribute argument list. Returns true if this
2192 /// results in adding an attribute to the ParsedAttributes list.
2193 bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
2194 SourceLocation AttrNameLoc,
2195 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2196 IdentifierInfo *ScopeName,
2197 SourceLocation ScopeLoc);
2199 IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc);
2201 void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
2202 SourceLocation *endLoc = nullptr) {
2203 if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
2204 ParseMicrosoftAttributes(attrs, endLoc);
2206 void ParseMicrosoftAttributes(ParsedAttributes &attrs,
2207 SourceLocation *endLoc = nullptr);
2208 void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2209 SourceLocation *End = nullptr) {
2210 const auto &LO = getLangOpts();
2211 if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec))
2212 ParseMicrosoftDeclSpecs(Attrs, End);
2214 void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2215 SourceLocation *End = nullptr);
2216 bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
2217 SourceLocation AttrNameLoc,
2218 ParsedAttributes &Attrs);
2219 void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
2220 void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2221 SourceLocation SkipExtendedMicrosoftTypeAttributes();
2222 void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
2223 void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
2224 void ParseOpenCLKernelAttributes(ParsedAttributes &attrs);
2225 void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
2226 /// \brief Parses opencl_unroll_hint attribute if language is OpenCL v2.0
2228 /// \return false if error happens.
2229 bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
2230 if (getLangOpts().OpenCL)
2231 return ParseOpenCLUnrollHintAttribute(Attrs);
2234 /// \brief Parses opencl_unroll_hint attribute.
2235 /// \return false if error happens.
2236 bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs);
2237 void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
2239 VersionTuple ParseVersionTuple(SourceRange &Range);
2240 void ParseAvailabilityAttribute(IdentifierInfo &Availability,
2241 SourceLocation AvailabilityLoc,
2242 ParsedAttributes &attrs,
2243 SourceLocation *endLoc,
2244 IdentifierInfo *ScopeName,
2245 SourceLocation ScopeLoc,
2246 AttributeList::Syntax Syntax);
2248 Optional<AvailabilitySpec> ParseAvailabilitySpec();
2249 ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc);
2251 void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
2252 SourceLocation ObjCBridgeRelatedLoc,
2253 ParsedAttributes &attrs,
2254 SourceLocation *endLoc,
2255 IdentifierInfo *ScopeName,
2256 SourceLocation ScopeLoc,
2257 AttributeList::Syntax Syntax);
2259 void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
2260 SourceLocation AttrNameLoc,
2261 ParsedAttributes &Attrs,
2262 SourceLocation *EndLoc,
2263 IdentifierInfo *ScopeName,
2264 SourceLocation ScopeLoc,
2265 AttributeList::Syntax Syntax);
2267 void ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
2268 SourceLocation AttrNameLoc,
2269 ParsedAttributes &Attrs,
2270 SourceLocation *EndLoc,
2271 IdentifierInfo *ScopeName,
2272 SourceLocation ScopeLoc,
2273 AttributeList::Syntax Syntax);
2275 void ParseTypeofSpecifier(DeclSpec &DS);
2276 SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
2277 void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
2278 SourceLocation StartLoc,
2279 SourceLocation EndLoc);
2280 void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
2281 void ParseAtomicSpecifier(DeclSpec &DS);
2283 ExprResult ParseAlignArgument(SourceLocation Start,
2284 SourceLocation &EllipsisLoc);
2285 void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2286 SourceLocation *endLoc = nullptr);
2288 VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
2289 VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
2290 return isCXX11VirtSpecifier(Tok);
2292 void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface,
2293 SourceLocation FriendLoc);
2295 bool isCXX11FinalKeyword() const;
2297 /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
2298 /// enter a new C++ declarator scope and exit it when the function is
2300 class DeclaratorScopeObj {
2306 DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
2307 : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
2309 void EnterDeclaratorScope() {
2310 assert(!EnteredScope && "Already entered the scope!");
2311 assert(SS.isSet() && "C++ scope was not set!");
2313 CreatedScope = true;
2314 P.EnterScope(0); // Not a decl scope.
2316 if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
2317 EnteredScope = true;
2320 ~DeclaratorScopeObj() {
2322 assert(SS.isSet() && "C++ scope was cleared ?");
2323 P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
2330 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
2331 void ParseDeclarator(Declarator &D);
2332 /// A function that parses a variant of direct-declarator.
2333 typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
2334 void ParseDeclaratorInternal(Declarator &D,
2335 DirectDeclParseFunction DirectDeclParser);
2337 enum AttrRequirements {
2338 AR_NoAttributesParsed = 0, ///< No attributes are diagnosed.
2339 AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes.
2340 AR_GNUAttributesParsed = 1 << 1,
2341 AR_CXX11AttributesParsed = 1 << 2,
2342 AR_DeclspecAttributesParsed = 1 << 3,
2343 AR_AllAttributesParsed = AR_GNUAttributesParsed |
2344 AR_CXX11AttributesParsed |
2345 AR_DeclspecAttributesParsed,
2346 AR_VendorAttributesParsed = AR_GNUAttributesParsed |
2347 AR_DeclspecAttributesParsed
2350 void ParseTypeQualifierListOpt(DeclSpec &DS,
2351 unsigned AttrReqs = AR_AllAttributesParsed,
2352 bool AtomicAllowed = true,
2353 bool IdentifierRequired = false);
2354 void ParseDirectDeclarator(Declarator &D);
2355 void ParseParenDeclarator(Declarator &D);
2356 void ParseFunctionDeclarator(Declarator &D,
2357 ParsedAttributes &attrs,
2358 BalancedDelimiterTracker &Tracker,
2360 bool RequiresArg = false);
2361 bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
2362 SourceLocation &RefQualifierLoc);
2363 bool isFunctionDeclaratorIdentifierList();
2364 void ParseFunctionDeclaratorIdentifierList(
2366 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
2367 void ParseParameterDeclarationClause(
2369 ParsedAttributes &attrs,
2370 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
2371 SourceLocation &EllipsisLoc);
2372 void ParseBracketDeclarator(Declarator &D);
2373 void ParseMisplacedBracketDeclarator(Declarator &D);
2375 //===--------------------------------------------------------------------===//
2376 // C++ 7: Declarations [dcl.dcl]
2378 /// The kind of attribute specifier we have found.
2379 enum CXX11AttributeKind {
2380 /// This is not an attribute specifier.
2381 CAK_NotAttributeSpecifier,
2382 /// This should be treated as an attribute-specifier.
2383 CAK_AttributeSpecifier,
2384 /// The next tokens are '[[', but this is not an attribute-specifier. This
2385 /// is ill-formed by C++11 [dcl.attr.grammar]p6.
2386 CAK_InvalidAttributeSpecifier
2389 isCXX11AttributeSpecifier(bool Disambiguate = false,
2390 bool OuterMightBeMessageSend = false);
2392 void DiagnoseUnexpectedNamespace(NamedDecl *Context);
2394 DeclGroupPtrTy ParseNamespace(unsigned Context, SourceLocation &DeclEnd,
2395 SourceLocation InlineLoc = SourceLocation());
2396 void ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc,
2397 std::vector<IdentifierInfo*>& Ident,
2398 std::vector<SourceLocation>& NamespaceLoc,
2399 unsigned int index, SourceLocation& InlineLoc,
2400 ParsedAttributes& attrs,
2401 BalancedDelimiterTracker &Tracker);
2402 Decl *ParseLinkage(ParsingDeclSpec &DS, unsigned Context);
2403 Decl *ParseUsingDirectiveOrDeclaration(unsigned Context,
2404 const ParsedTemplateInfo &TemplateInfo,
2405 SourceLocation &DeclEnd,
2406 ParsedAttributesWithRange &attrs,
2407 Decl **OwnedType = nullptr);
2408 Decl *ParseUsingDirective(unsigned Context,
2409 SourceLocation UsingLoc,
2410 SourceLocation &DeclEnd,
2411 ParsedAttributes &attrs);
2412 Decl *ParseUsingDeclaration(unsigned Context,
2413 const ParsedTemplateInfo &TemplateInfo,
2414 SourceLocation UsingLoc,
2415 SourceLocation &DeclEnd,
2416 AccessSpecifier AS = AS_none,
2417 Decl **OwnedType = nullptr);
2418 Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
2419 Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
2420 SourceLocation AliasLoc, IdentifierInfo *Alias,
2421 SourceLocation &DeclEnd);
2423 //===--------------------------------------------------------------------===//
2424 // C++ 9: classes [class] and C structs/unions.
2425 bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
2426 void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
2427 DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo,
2428 AccessSpecifier AS, bool EnteringContext,
2429 DeclSpecContext DSC,
2430 ParsedAttributesWithRange &Attributes);
2431 void SkipCXXMemberSpecification(SourceLocation StartLoc,
2432 SourceLocation AttrFixitLoc,
2435 void ParseCXXMemberSpecification(SourceLocation StartLoc,
2436 SourceLocation AttrFixitLoc,
2437 ParsedAttributesWithRange &Attrs,
2440 ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2441 SourceLocation &EqualLoc);
2442 bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
2444 ExprResult &BitfieldSize,
2445 LateParsedAttrList &LateAttrs);
2446 void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D,
2447 VirtSpecifiers &VS);
2448 DeclGroupPtrTy ParseCXXClassMemberDeclaration(
2449 AccessSpecifier AS, AttributeList *Attr,
2450 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2451 ParsingDeclRAIIObject *DiagsFromTParams = nullptr);
2452 DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas(
2453 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
2454 DeclSpec::TST TagType, Decl *Tag);
2455 void ParseConstructorInitializer(Decl *ConstructorDecl);
2456 MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
2457 void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2460 //===--------------------------------------------------------------------===//
2461 // C++ 10: Derived classes [class.derived]
2462 TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
2463 SourceLocation &EndLocation);
2464 void ParseBaseClause(Decl *ClassDecl);
2465 BaseResult ParseBaseSpecifier(Decl *ClassDecl);
2466 AccessSpecifier getAccessSpecifierIfPresent() const;
2468 bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
2469 SourceLocation TemplateKWLoc,
2470 IdentifierInfo *Name,
2471 SourceLocation NameLoc,
2472 bool EnteringContext,
2473 ParsedType ObjectType,
2475 bool AssumeTemplateId);
2476 bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2477 ParsedType ObjectType,
2478 UnqualifiedId &Result);
2480 //===--------------------------------------------------------------------===//
2481 // OpenMP: Directives and clauses.
2482 /// Parse clauses for '#pragma omp declare simd'.
2483 DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr,
2485 SourceLocation Loc);
2486 /// \brief Parses declarative OpenMP directives.
2487 DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl(
2488 AccessSpecifier &AS, ParsedAttributesWithRange &Attrs,
2489 DeclSpec::TST TagType = DeclSpec::TST_unspecified,
2490 Decl *TagDecl = nullptr);
2491 /// \brief Parse 'omp declare reduction' construct.
2492 DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS);
2494 /// \brief Parses simple list of variables.
2496 /// \param Kind Kind of the directive.
2497 /// \param Callback Callback function to be called for the list elements.
2498 /// \param AllowScopeSpecifier true, if the variables can have fully
2499 /// qualified names.
2501 bool ParseOpenMPSimpleVarList(
2502 OpenMPDirectiveKind Kind,
2503 const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
2505 bool AllowScopeSpecifier);
2506 /// \brief Parses declarative or executable directive.
2508 /// \param Allowed ACK_Any, if any directives are allowed,
2509 /// ACK_StatementsOpenMPAnyExecutable - if any executable directives are
2510 /// allowed, ACK_StatementsOpenMPNonStandalone - if only non-standalone
2511 /// executable directives are allowed.
2514 ParseOpenMPDeclarativeOrExecutableDirective(AllowedContsructsKind Allowed);
2515 /// \brief Parses clause of kind \a CKind for directive of a kind \a Kind.
2517 /// \param DKind Kind of current directive.
2518 /// \param CKind Kind of current clause.
2519 /// \param FirstClause true, if this is the first clause of a kind \a CKind
2520 /// in current directive.
2522 OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
2523 OpenMPClauseKind CKind, bool FirstClause);
2524 /// \brief Parses clause with a single expression of a kind \a Kind.
2526 /// \param Kind Kind of current clause.
2528 OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind);
2529 /// \brief Parses simple clause of a kind \a Kind.
2531 /// \param Kind Kind of current clause.
2533 OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind);
2534 /// \brief Parses clause with a single expression and an additional argument
2535 /// of a kind \a Kind.
2537 /// \param Kind Kind of current clause.
2539 OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind);
2540 /// \brief Parses clause without any additional arguments.
2542 /// \param Kind Kind of current clause.
2544 OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind);
2545 /// \brief Parses clause with the list of variables of a kind \a Kind.
2547 /// \param Kind Kind of current clause.
2549 OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
2550 OpenMPClauseKind Kind);
2553 /// Parses simple expression in parens for single-expression clauses of OpenMP
2555 /// \param RLoc Returned location of right paren.
2556 ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc);
2558 /// Data used for parsing list of variables in OpenMP clauses.
2559 struct OpenMPVarListDataTy {
2560 Expr *TailExpr = nullptr;
2561 SourceLocation ColonLoc;
2562 CXXScopeSpec ReductionIdScopeSpec;
2563 DeclarationNameInfo ReductionId;
2564 OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown;
2565 OpenMPLinearClauseKind LinKind = OMPC_LINEAR_val;
2566 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
2567 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
2568 bool IsMapTypeImplicit = false;
2569 SourceLocation DepLinMapLoc;
2572 /// Parses clauses with list.
2573 bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind,
2574 SmallVectorImpl<Expr *> &Vars,
2575 OpenMPVarListDataTy &Data);
2576 bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2577 bool AllowDestructorName,
2578 bool AllowConstructorName,
2579 ParsedType ObjectType,
2580 SourceLocation& TemplateKWLoc,
2581 UnqualifiedId &Result);
2584 //===--------------------------------------------------------------------===//
2585 // C++ 14: Templates [temp]
2587 // C++ 14.1: Template Parameters [temp.param]
2588 Decl *ParseDeclarationStartingWithTemplate(unsigned Context,
2589 SourceLocation &DeclEnd,
2590 AccessSpecifier AS = AS_none,
2591 AttributeList *AccessAttrs = nullptr);
2592 Decl *ParseTemplateDeclarationOrSpecialization(unsigned Context,
2593 SourceLocation &DeclEnd,
2595 AttributeList *AccessAttrs);
2596 Decl *ParseSingleDeclarationAfterTemplate(
2598 const ParsedTemplateInfo &TemplateInfo,
2599 ParsingDeclRAIIObject &DiagsFromParams,
2600 SourceLocation &DeclEnd,
2601 AccessSpecifier AS=AS_none,
2602 AttributeList *AccessAttrs = nullptr);
2603 bool ParseTemplateParameters(unsigned Depth,
2604 SmallVectorImpl<Decl*> &TemplateParams,
2605 SourceLocation &LAngleLoc,
2606 SourceLocation &RAngleLoc);
2607 bool ParseTemplateParameterList(unsigned Depth,
2608 SmallVectorImpl<Decl*> &TemplateParams);
2609 bool isStartOfTemplateTypeParameter();
2610 Decl *ParseTemplateParameter(unsigned Depth, unsigned Position);
2611 Decl *ParseTypeParameter(unsigned Depth, unsigned Position);
2612 Decl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
2613 Decl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
2614 void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
2615 SourceLocation CorrectLoc,
2616 bool AlreadyHasEllipsis,
2617 bool IdentifierHasName);
2618 void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
2620 // C++ 14.3: Template arguments [temp.arg]
2621 typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
2623 bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
2624 bool ConsumeLastToken,
2625 bool ObjCGenericList);
2626 bool ParseTemplateIdAfterTemplateName(TemplateTy Template,
2627 SourceLocation TemplateNameLoc,
2628 const CXXScopeSpec &SS,
2629 bool ConsumeLastToken,
2630 SourceLocation &LAngleLoc,
2631 TemplateArgList &TemplateArgs,
2632 SourceLocation &RAngleLoc);
2634 bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
2636 SourceLocation TemplateKWLoc,
2637 UnqualifiedId &TemplateName,
2638 bool AllowTypeAnnotation = true);
2639 void AnnotateTemplateIdTokenAsType();
2640 bool IsTemplateArgumentList(unsigned Skip = 0);
2641 bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
2642 ParsedTemplateArgument ParseTemplateTemplateArgument();
2643 ParsedTemplateArgument ParseTemplateArgument();
2644 Decl *ParseExplicitInstantiation(unsigned Context,
2645 SourceLocation ExternLoc,
2646 SourceLocation TemplateLoc,
2647 SourceLocation &DeclEnd,
2648 AccessSpecifier AS = AS_none);
2650 //===--------------------------------------------------------------------===//
2652 DeclGroupPtrTy ParseModuleImport(SourceLocation AtLoc);
2653 bool parseMisplacedModuleImport();
2654 bool tryParseMisplacedModuleImport() {
2655 tok::TokenKind Kind = Tok.getKind();
2656 if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end ||
2657 Kind == tok::annot_module_include)
2658 return parseMisplacedModuleImport();
2662 //===--------------------------------------------------------------------===//
2663 // C++11/G++: Type Traits [Type-Traits.html in the GCC manual]
2664 ExprResult ParseTypeTrait();
2666 //===--------------------------------------------------------------------===//
2667 // Embarcadero: Arary and Expression Traits
2668 ExprResult ParseArrayTypeTrait();
2669 ExprResult ParseExpressionTrait();
2671 //===--------------------------------------------------------------------===//
2672 // Preprocessor code-completion pass-through
2673 void CodeCompleteDirective(bool InConditional) override;
2674 void CodeCompleteInConditionalExclusion() override;
2675 void CodeCompleteMacroName(bool IsDefinition) override;
2676 void CodeCompletePreprocessorExpression() override;
2677 void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo,
2678 unsigned ArgumentIndex) override;
2679 void CodeCompleteNaturalLanguage() override;
2682 } // end namespace clang