1 //===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the Parser interface.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_PARSE_PARSER_H
15 #define LLVM_CLANG_PARSE_PARSER_H
17 #include "clang/Basic/OpenMPKinds.h"
18 #include "clang/Basic/OperatorPrecedence.h"
19 #include "clang/Basic/Specifiers.h"
20 #include "clang/Lex/CodeCompletionHandler.h"
21 #include "clang/Lex/Preprocessor.h"
22 #include "clang/Sema/DeclSpec.h"
23 #include "clang/Sema/LoopHint.h"
24 #include "clang/Sema/Sema.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/PrettyStackTrace.h"
28 #include "llvm/Support/SaveAndRestore.h"
35 class BalancedDelimiterTracker;
36 class CorrectionCandidateCallback;
38 class DiagnosticBuilder;
40 class ParsingDeclRAIIObject;
41 class ParsingDeclSpec;
42 class ParsingDeclarator;
43 class ParsingFieldDeclarator;
44 class ColonProtectionRAIIObject;
45 class InMessageExpressionRAIIObject;
46 class PoisonSEHIdentifiersRAIIObject;
49 class ObjCTypeParamList;
50 class ObjCTypeParameter;
52 /// Parser - This implements a parser for the C family of languages. After
53 /// parsing units of the grammar, productions are invoked to handle whatever has
56 class Parser : public CodeCompletionHandler {
57 friend class ColonProtectionRAIIObject;
58 friend class InMessageExpressionRAIIObject;
59 friend class PoisonSEHIdentifiersRAIIObject;
60 friend class ObjCDeclContextSwitch;
61 friend class ParenBraceBracketBalancer;
62 friend class BalancedDelimiterTracker;
66 /// Tok - The current token we are peeking ahead. All parsing methods assume
67 /// that this is valid.
70 // PrevTokLocation - The location of the token we previously
71 // consumed. This token is used for diagnostics where we expected to
72 // see a token following another token (e.g., the ';' at the end of
74 SourceLocation PrevTokLocation;
76 unsigned short ParenCount, BracketCount, BraceCount;
78 /// Actions - These are the callbacks we invoke as we parse various constructs
82 DiagnosticsEngine &Diags;
84 /// ScopeCache - Cache scopes to reduce malloc traffic.
85 enum { ScopeCacheSize = 16 };
86 unsigned NumCachedScopes;
87 Scope *ScopeCache[ScopeCacheSize];
89 /// Identifiers used for SEH handling in Borland. These are only
90 /// allowed in particular circumstances
92 IdentifierInfo *Ident__exception_code,
93 *Ident___exception_code,
94 *Ident_GetExceptionCode;
95 // __except filter expression
96 IdentifierInfo *Ident__exception_info,
97 *Ident___exception_info,
98 *Ident_GetExceptionInfo;
100 IdentifierInfo *Ident__abnormal_termination,
101 *Ident___abnormal_termination,
102 *Ident_AbnormalTermination;
104 /// Contextual keywords for Microsoft extensions.
105 IdentifierInfo *Ident__except;
106 mutable IdentifierInfo *Ident_sealed;
108 /// Ident_super - IdentifierInfo for "super", to support fast
110 IdentifierInfo *Ident_super;
111 /// Ident_vector, Ident_bool - cached IdentifierInfos for "vector" and
112 /// "bool" fast comparison. Only present if AltiVec or ZVector are enabled.
113 IdentifierInfo *Ident_vector;
114 IdentifierInfo *Ident_bool;
115 /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison.
116 /// Only present if AltiVec enabled.
117 IdentifierInfo *Ident_pixel;
119 /// Objective-C contextual keywords.
120 mutable IdentifierInfo *Ident_instancetype;
122 /// \brief Identifier for "introduced".
123 IdentifierInfo *Ident_introduced;
125 /// \brief Identifier for "deprecated".
126 IdentifierInfo *Ident_deprecated;
128 /// \brief Identifier for "obsoleted".
129 IdentifierInfo *Ident_obsoleted;
131 /// \brief Identifier for "unavailable".
132 IdentifierInfo *Ident_unavailable;
134 /// \brief Identifier for "message".
135 IdentifierInfo *Ident_message;
137 /// C++0x contextual keywords.
138 mutable IdentifierInfo *Ident_final;
139 mutable IdentifierInfo *Ident_override;
141 // C++ type trait keywords that can be reverted to identifiers and still be
142 // used as type traits.
143 llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits;
145 std::unique_ptr<PragmaHandler> AlignHandler;
146 std::unique_ptr<PragmaHandler> GCCVisibilityHandler;
147 std::unique_ptr<PragmaHandler> OptionsHandler;
148 std::unique_ptr<PragmaHandler> PackHandler;
149 std::unique_ptr<PragmaHandler> MSStructHandler;
150 std::unique_ptr<PragmaHandler> UnusedHandler;
151 std::unique_ptr<PragmaHandler> WeakHandler;
152 std::unique_ptr<PragmaHandler> RedefineExtnameHandler;
153 std::unique_ptr<PragmaHandler> FPContractHandler;
154 std::unique_ptr<PragmaHandler> OpenCLExtensionHandler;
155 std::unique_ptr<PragmaHandler> OpenMPHandler;
156 std::unique_ptr<PragmaHandler> MSCommentHandler;
157 std::unique_ptr<PragmaHandler> MSDetectMismatchHandler;
158 std::unique_ptr<PragmaHandler> MSPointersToMembers;
159 std::unique_ptr<PragmaHandler> MSVtorDisp;
160 std::unique_ptr<PragmaHandler> MSInitSeg;
161 std::unique_ptr<PragmaHandler> MSDataSeg;
162 std::unique_ptr<PragmaHandler> MSBSSSeg;
163 std::unique_ptr<PragmaHandler> MSConstSeg;
164 std::unique_ptr<PragmaHandler> MSCodeSeg;
165 std::unique_ptr<PragmaHandler> MSSection;
166 std::unique_ptr<PragmaHandler> MSRuntimeChecks;
167 std::unique_ptr<PragmaHandler> OptimizeHandler;
168 std::unique_ptr<PragmaHandler> LoopHintHandler;
169 std::unique_ptr<PragmaHandler> UnrollHintHandler;
170 std::unique_ptr<PragmaHandler> NoUnrollHintHandler;
172 std::unique_ptr<CommentHandler> CommentSemaHandler;
174 /// Whether the '>' token acts as an operator or not. This will be
175 /// true except when we are parsing an expression within a C++
176 /// template argument list, where the '>' closes the template
178 bool GreaterThanIsOperator;
180 /// ColonIsSacred - When this is false, we aggressively try to recover from
181 /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not
182 /// safe in case statements and a few other things. This is managed by the
183 /// ColonProtectionRAIIObject RAII object.
186 /// \brief When true, we are directly inside an Objective-C message
189 /// This is managed by the \c InMessageExpressionRAIIObject class, and
190 /// should not be set directly.
191 bool InMessageExpression;
193 /// The "depth" of the template parameters currently being parsed.
194 unsigned TemplateParameterDepth;
196 /// \brief RAII class that manages the template parameter depth.
197 class TemplateParameterDepthRAII {
199 unsigned AddedLevels;
201 explicit TemplateParameterDepthRAII(unsigned &Depth)
202 : Depth(Depth), AddedLevels(0) {}
204 ~TemplateParameterDepthRAII() {
205 Depth -= AddedLevels;
212 void addDepth(unsigned D) {
216 unsigned getDepth() const { return Depth; }
219 /// Factory object for creating AttributeList objects.
220 AttributeFactory AttrFactory;
222 /// \brief Gathers and cleans up TemplateIdAnnotations when parsing of a
223 /// top-level declaration is finished.
224 SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
226 /// \brief Identifiers which have been declared within a tentative parse.
227 SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers;
229 IdentifierInfo *getSEHExceptKeyword();
231 /// True if we are within an Objective-C container while parsing C-like decls.
233 /// This is necessary because Sema thinks we have left the container
234 /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will
236 bool ParsingInObjCContainer;
238 bool SkipFunctionBodies;
241 Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
244 const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
245 const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
246 Preprocessor &getPreprocessor() const { return PP; }
247 Sema &getActions() const { return Actions; }
248 AttributeFactory &getAttrFactory() { return AttrFactory; }
250 const Token &getCurToken() const { return Tok; }
251 Scope *getCurScope() const { return Actions.getCurScope(); }
252 void incrementMSManglingNumber() const {
253 return Actions.incrementMSManglingNumber();
256 Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); }
258 // Type forwarding. All of these are statically 'void*', but they may all be
259 // different actual classes based on the actions in place.
260 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
261 typedef OpaquePtr<TemplateName> TemplateTy;
263 typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists;
265 typedef Sema::FullExprArg FullExprArg;
269 /// Initialize - Warm up the parser.
273 /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if
274 /// the EOF was encountered.
275 bool ParseTopLevelDecl(DeclGroupPtrTy &Result);
276 bool ParseTopLevelDecl() {
277 DeclGroupPtrTy Result;
278 return ParseTopLevelDecl(Result);
281 /// ConsumeToken - Consume the current 'peek token' and lex the next one.
282 /// This does not work with special tokens: string literals, code completion
283 /// and balanced tokens must be handled using the specific consume methods.
284 /// Returns the location of the consumed token.
285 SourceLocation ConsumeToken() {
286 assert(!isTokenSpecial() &&
287 "Should consume special tokens with Consume*Token");
288 PrevTokLocation = Tok.getLocation();
290 return PrevTokLocation;
293 bool TryConsumeToken(tok::TokenKind Expected) {
294 if (Tok.isNot(Expected))
296 assert(!isTokenSpecial() &&
297 "Should consume special tokens with Consume*Token");
298 PrevTokLocation = Tok.getLocation();
303 bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) {
304 if (!TryConsumeToken(Expected))
306 Loc = PrevTokLocation;
310 /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds
311 /// to the given nullability kind.
312 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) {
313 return Actions.getNullabilityKeyword(nullability);
317 //===--------------------------------------------------------------------===//
318 // Low-Level token peeking and consumption methods.
321 /// isTokenParen - Return true if the cur token is '(' or ')'.
322 bool isTokenParen() const {
323 return Tok.getKind() == tok::l_paren || Tok.getKind() == tok::r_paren;
325 /// isTokenBracket - Return true if the cur token is '[' or ']'.
326 bool isTokenBracket() const {
327 return Tok.getKind() == tok::l_square || Tok.getKind() == tok::r_square;
329 /// isTokenBrace - Return true if the cur token is '{' or '}'.
330 bool isTokenBrace() const {
331 return Tok.getKind() == tok::l_brace || Tok.getKind() == tok::r_brace;
333 /// isTokenStringLiteral - True if this token is a string-literal.
334 bool isTokenStringLiteral() const {
335 return tok::isStringLiteral(Tok.getKind());
337 /// isTokenSpecial - True if this token requires special consumption methods.
338 bool isTokenSpecial() const {
339 return isTokenStringLiteral() || isTokenParen() || isTokenBracket() ||
340 isTokenBrace() || Tok.is(tok::code_completion);
343 /// \brief Returns true if the current token is '=' or is a type of '='.
344 /// For typos, give a fixit to '='
345 bool isTokenEqualOrEqualTypo();
347 /// \brief Return the current token to the token stream and make the given
348 /// token the current token.
349 void UnconsumeToken(Token &Consumed) {
351 PP.EnterToken(Consumed);
356 /// ConsumeAnyToken - Dispatch to the right Consume* method based on the
357 /// current token type. This should only be used in cases where the type of
358 /// the token really isn't known, e.g. in error recovery.
359 SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) {
361 return ConsumeParen();
362 if (isTokenBracket())
363 return ConsumeBracket();
365 return ConsumeBrace();
366 if (isTokenStringLiteral())
367 return ConsumeStringToken();
368 if (Tok.is(tok::code_completion))
369 return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken()
370 : handleUnexpectedCodeCompletionToken();
371 return ConsumeToken();
374 /// ConsumeParen - This consume method keeps the paren count up-to-date.
376 SourceLocation ConsumeParen() {
377 assert(isTokenParen() && "wrong consume method");
378 if (Tok.getKind() == tok::l_paren)
381 --ParenCount; // Don't let unbalanced )'s drive the count negative.
382 PrevTokLocation = Tok.getLocation();
384 return PrevTokLocation;
387 /// ConsumeBracket - This consume method keeps the bracket count up-to-date.
389 SourceLocation ConsumeBracket() {
390 assert(isTokenBracket() && "wrong consume method");
391 if (Tok.getKind() == tok::l_square)
393 else if (BracketCount)
394 --BracketCount; // Don't let unbalanced ]'s drive the count negative.
396 PrevTokLocation = Tok.getLocation();
398 return PrevTokLocation;
401 /// ConsumeBrace - This consume method keeps the brace count up-to-date.
403 SourceLocation ConsumeBrace() {
404 assert(isTokenBrace() && "wrong consume method");
405 if (Tok.getKind() == tok::l_brace)
408 --BraceCount; // Don't let unbalanced }'s drive the count negative.
410 PrevTokLocation = Tok.getLocation();
412 return PrevTokLocation;
415 /// ConsumeStringToken - Consume the current 'peek token', lexing a new one
416 /// and returning the token kind. This method is specific to strings, as it
417 /// handles string literal concatenation, as per C99 5.1.1.2, translation
419 SourceLocation ConsumeStringToken() {
420 assert(isTokenStringLiteral() &&
421 "Should only consume string literals with this method");
422 PrevTokLocation = Tok.getLocation();
424 return PrevTokLocation;
427 /// \brief Consume the current code-completion token.
429 /// This routine can be called to consume the code-completion token and
430 /// continue processing in special cases where \c cutOffParsing() isn't
431 /// desired, such as token caching or completion with lookahead.
432 SourceLocation ConsumeCodeCompletionToken() {
433 assert(Tok.is(tok::code_completion));
434 PrevTokLocation = Tok.getLocation();
436 return PrevTokLocation;
439 ///\ brief When we are consuming a code-completion token without having
440 /// matched specific position in the grammar, provide code-completion results
441 /// based on context.
443 /// \returns the source location of the code-completion token.
444 SourceLocation handleUnexpectedCodeCompletionToken();
446 /// \brief Abruptly cut off parsing; mainly used when we have reached the
447 /// code-completion point.
448 void cutOffParsing() {
449 if (PP.isCodeCompletionEnabled())
450 PP.setCodeCompletionReached();
451 // Cut off parsing by acting as if we reached the end-of-file.
452 Tok.setKind(tok::eof);
455 /// \brief Determine if we're at the end of the file or at a transition
458 tok::TokenKind Kind = Tok.getKind();
459 return Kind == tok::eof || Kind == tok::annot_module_begin ||
460 Kind == tok::annot_module_end || Kind == tok::annot_module_include;
463 /// \brief Initialize all pragma handlers.
464 void initializePragmaHandlers();
466 /// \brief Destroy and reset all pragma handlers.
467 void resetPragmaHandlers();
469 /// \brief Handle the annotation token produced for #pragma unused(...)
470 void HandlePragmaUnused();
472 /// \brief Handle the annotation token produced for
473 /// #pragma GCC visibility...
474 void HandlePragmaVisibility();
476 /// \brief Handle the annotation token produced for
478 void HandlePragmaPack();
480 /// \brief Handle the annotation token produced for
481 /// #pragma ms_struct...
482 void HandlePragmaMSStruct();
484 /// \brief Handle the annotation token produced for
485 /// #pragma comment...
486 void HandlePragmaMSComment();
488 void HandlePragmaMSPointersToMembers();
490 void HandlePragmaMSVtorDisp();
492 void HandlePragmaMSPragma();
493 bool HandlePragmaMSSection(StringRef PragmaName,
494 SourceLocation PragmaLocation);
495 bool HandlePragmaMSSegment(StringRef PragmaName,
496 SourceLocation PragmaLocation);
497 bool HandlePragmaMSInitSeg(StringRef PragmaName,
498 SourceLocation PragmaLocation);
500 /// \brief Handle the annotation token produced for
502 void HandlePragmaAlign();
504 /// \brief Handle the annotation token produced for
505 /// #pragma clang __debug dump...
506 void HandlePragmaDump();
508 /// \brief Handle the annotation token produced for
509 /// #pragma weak id...
510 void HandlePragmaWeak();
512 /// \brief Handle the annotation token produced for
513 /// #pragma weak id = id...
514 void HandlePragmaWeakAlias();
516 /// \brief Handle the annotation token produced for
517 /// #pragma redefine_extname...
518 void HandlePragmaRedefineExtname();
520 /// \brief Handle the annotation token produced for
521 /// #pragma STDC FP_CONTRACT...
522 void HandlePragmaFPContract();
524 /// \brief Handle the annotation token produced for
525 /// #pragma OPENCL EXTENSION...
526 void HandlePragmaOpenCLExtension();
528 /// \brief Handle the annotation token produced for
529 /// #pragma clang __debug captured
530 StmtResult HandlePragmaCaptured();
532 /// \brief Handle the annotation token produced for
533 /// #pragma clang loop and #pragma unroll.
534 bool HandlePragmaLoopHint(LoopHint &Hint);
536 /// GetLookAheadToken - This peeks ahead N tokens and returns that token
537 /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1)
538 /// returns the token after Tok, etc.
540 /// Note that this differs from the Preprocessor's LookAhead method, because
541 /// the Parser always has one token lexed that the preprocessor doesn't.
543 const Token &GetLookAheadToken(unsigned N) {
544 if (N == 0 || Tok.is(tok::eof)) return Tok;
545 return PP.LookAhead(N-1);
549 /// NextToken - This peeks ahead one token and returns it without
551 const Token &NextToken() {
552 return PP.LookAhead(0);
555 /// getTypeAnnotation - Read a parsed type out of an annotation token.
556 static ParsedType getTypeAnnotation(Token &Tok) {
557 return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
561 static void setTypeAnnotation(Token &Tok, ParsedType T) {
562 Tok.setAnnotationValue(T.getAsOpaquePtr());
565 /// \brief Read an already-translated primary expression out of an annotation
567 static ExprResult getExprAnnotation(Token &Tok) {
568 return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue());
571 /// \brief Set the primary expression corresponding to the given annotation
573 static void setExprAnnotation(Token &Tok, ExprResult ER) {
574 Tok.setAnnotationValue(ER.getAsOpaquePointer());
578 // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to
579 // find a type name by attempting typo correction.
580 bool TryAnnotateTypeOrScopeToken(bool EnteringContext = false,
581 bool NeedType = false);
582 bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext,
586 bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
589 enum AnnotatedNameKind {
590 /// Annotation has failed and emitted an error.
592 /// The identifier is a tentatively-declared name.
594 /// The identifier is a template name. FIXME: Add an annotation for that.
596 /// The identifier can't be resolved.
598 /// Annotation was successful.
602 TryAnnotateName(bool IsAddressOfOperand,
603 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
605 /// Push a tok::annot_cxxscope token onto the token stream.
606 void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
608 /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
609 /// replacing them with the non-context-sensitive keywords. This returns
610 /// true if the token was replaced.
611 bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
612 const char *&PrevSpec, unsigned &DiagID,
614 if (!getLangOpts().AltiVec && !getLangOpts().ZVector)
617 if (Tok.getIdentifierInfo() != Ident_vector &&
618 Tok.getIdentifierInfo() != Ident_bool &&
619 (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel))
622 return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
625 /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
626 /// identifier token, replacing it with the non-context-sensitive __vector.
627 /// This returns true if the token was replaced.
628 bool TryAltiVecVectorToken() {
629 if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) ||
630 Tok.getIdentifierInfo() != Ident_vector) return false;
631 return TryAltiVecVectorTokenOutOfLine();
634 bool TryAltiVecVectorTokenOutOfLine();
635 bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
636 const char *&PrevSpec, unsigned &DiagID,
639 /// Returns true if the current token is the identifier 'instancetype'.
641 /// Should only be used in Objective-C language modes.
642 bool isObjCInstancetype() {
643 assert(getLangOpts().ObjC1);
644 if (!Ident_instancetype)
645 Ident_instancetype = PP.getIdentifierInfo("instancetype");
646 return Tok.getIdentifierInfo() == Ident_instancetype;
649 /// TryKeywordIdentFallback - For compatibility with system headers using
650 /// keywords as identifiers, attempt to convert the current token to an
651 /// identifier and optionally disable the keyword for the remainder of the
652 /// translation unit. This returns false if the token was not replaced,
653 /// otherwise emits a diagnostic and returns true.
654 bool TryKeywordIdentFallback(bool DisableKeyword);
656 /// \brief Get the TemplateIdAnnotation from the token.
657 TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
659 /// TentativeParsingAction - An object that is used as a kind of "tentative
660 /// parsing transaction". It gets instantiated to mark the token position and
661 /// after the token consumption is done, Commit() or Revert() is called to
662 /// either "commit the consumed tokens" or revert to the previously marked
663 /// token position. Example:
665 /// TentativeParsingAction TPA(*this);
670 class TentativeParsingAction {
673 size_t PrevTentativelyDeclaredIdentifierCount;
674 unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
678 explicit TentativeParsingAction(Parser& p) : P(p) {
680 PrevTentativelyDeclaredIdentifierCount =
681 P.TentativelyDeclaredIdentifiers.size();
682 PrevParenCount = P.ParenCount;
683 PrevBracketCount = P.BracketCount;
684 PrevBraceCount = P.BraceCount;
685 P.PP.EnableBacktrackAtThisPos();
689 assert(isActive && "Parsing action was finished!");
690 P.TentativelyDeclaredIdentifiers.resize(
691 PrevTentativelyDeclaredIdentifierCount);
692 P.PP.CommitBacktrackedTokens();
696 assert(isActive && "Parsing action was finished!");
699 P.TentativelyDeclaredIdentifiers.resize(
700 PrevTentativelyDeclaredIdentifierCount);
701 P.ParenCount = PrevParenCount;
702 P.BracketCount = PrevBracketCount;
703 P.BraceCount = PrevBraceCount;
706 ~TentativeParsingAction() {
707 assert(!isActive && "Forgot to call Commit or Revert!");
710 class UnannotatedTentativeParsingAction;
712 /// ObjCDeclContextSwitch - An object used to switch context from
713 /// an objective-c decl context to its enclosing decl context and
715 class ObjCDeclContextSwitch {
718 SaveAndRestore<bool> WithinObjCContainer;
720 explicit ObjCDeclContextSwitch(Parser &p)
721 : P(p), DC(p.getObjCDeclContext()),
722 WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) {
724 P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC));
726 ~ObjCDeclContextSwitch() {
728 P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC));
732 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
733 /// input. If so, it is consumed and false is returned.
735 /// If a trivial punctuator misspelling is encountered, a FixIt error
736 /// diagnostic is issued and false is returned after recovery.
738 /// If the input is malformed, this emits the specified diagnostic and true is
740 bool ExpectAndConsume(tok::TokenKind ExpectedTok,
741 unsigned Diag = diag::err_expected,
742 StringRef DiagMsg = "");
744 /// \brief The parser expects a semicolon and, if present, will consume it.
746 /// If the next token is not a semicolon, this emits the specified diagnostic,
747 /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
748 /// to the semicolon, consumes that extra token.
749 bool ExpectAndConsumeSemi(unsigned DiagID);
751 /// \brief The kind of extra semi diagnostic to emit.
755 InstanceVariableList = 2,
756 AfterMemberFunctionDefinition = 3
759 /// \brief Consume any extra semi-colons until the end of the line.
760 void ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST = TST_unspecified);
763 //===--------------------------------------------------------------------===//
764 // Scope manipulation
766 /// ParseScope - Introduces a new scope for parsing. The kind of
767 /// scope is determined by ScopeFlags. Objects of this type should
768 /// be created on the stack to coincide with the position where the
769 /// parser enters the new scope, and this object's constructor will
770 /// create that new scope. Similarly, once the object is destroyed
771 /// the parser will exit the scope.
774 ParseScope(const ParseScope &) = delete;
775 void operator=(const ParseScope &) = delete;
778 // ParseScope - Construct a new object to manage a scope in the
779 // parser Self where the new Scope is created with the flags
780 // ScopeFlags, but only when we aren't about to enter a compound statement.
781 ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true,
782 bool BeforeCompoundStmt = false)
784 if (EnteredScope && !BeforeCompoundStmt)
785 Self->EnterScope(ScopeFlags);
787 if (BeforeCompoundStmt)
788 Self->incrementMSManglingNumber();
790 this->Self = nullptr;
794 // Exit - Exit the scope associated with this object now, rather
795 // than waiting until the object is destroyed.
808 /// EnterScope - Start a new scope.
809 void EnterScope(unsigned ScopeFlags);
811 /// ExitScope - Pop a scope off the scope stack.
815 /// \brief RAII object used to modify the scope flags for the current scope.
816 class ParseScopeFlags {
819 ParseScopeFlags(const ParseScopeFlags &) = delete;
820 void operator=(const ParseScopeFlags &) = delete;
823 ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
827 //===--------------------------------------------------------------------===//
828 // Diagnostic Emission and Error recovery.
831 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
832 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
833 DiagnosticBuilder Diag(unsigned DiagID) {
834 return Diag(Tok, DiagID);
838 void SuggestParentheses(SourceLocation Loc, unsigned DK,
839 SourceRange ParenRange);
840 void CheckNestedObjCContexts(SourceLocation AtLoc);
844 /// \brief Control flags for SkipUntil functions.
845 enum SkipUntilFlags {
846 StopAtSemi = 1 << 0, ///< Stop skipping at semicolon
847 /// \brief Stop skipping at specified token, but don't skip the token itself
848 StopBeforeMatch = 1 << 1,
849 StopAtCodeCompletion = 1 << 2 ///< Stop at code completion
852 friend LLVM_CONSTEXPR SkipUntilFlags operator|(SkipUntilFlags L,
854 return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) |
855 static_cast<unsigned>(R));
858 /// SkipUntil - Read tokens until we get to the specified token, then consume
859 /// it (unless StopBeforeMatch is specified). Because we cannot guarantee
860 /// that the token will ever occur, this skips to the next token, or to some
861 /// likely good stopping point. If Flags has StopAtSemi flag, skipping will
862 /// stop at a ';' character.
864 /// If SkipUntil finds the specified token, it returns true, otherwise it
866 bool SkipUntil(tok::TokenKind T,
867 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
868 return SkipUntil(llvm::makeArrayRef(T), Flags);
870 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2,
871 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
872 tok::TokenKind TokArray[] = {T1, T2};
873 return SkipUntil(TokArray, Flags);
875 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3,
876 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
877 tok::TokenKind TokArray[] = {T1, T2, T3};
878 return SkipUntil(TokArray, Flags);
880 bool SkipUntil(ArrayRef<tok::TokenKind> Toks,
881 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0));
883 /// SkipMalformedDecl - Read tokens until we get to some likely good stopping
884 /// point for skipping past a simple-declaration.
885 void SkipMalformedDecl();
888 //===--------------------------------------------------------------------===//
889 // Lexing and parsing of C++ inline methods.
893 /// [class.mem]p1: "... the class is regarded as complete within
894 /// - function bodies
895 /// - default arguments
896 /// - exception-specifications (TODO: C++0x)
897 /// - and brace-or-equal-initializers for non-static data members
898 /// (including such things in nested classes)."
899 /// LateParsedDeclarations build the tree of those elements so they can
900 /// be parsed after parsing the top-level class.
901 class LateParsedDeclaration {
903 virtual ~LateParsedDeclaration();
905 virtual void ParseLexedMethodDeclarations();
906 virtual void ParseLexedMemberInitializers();
907 virtual void ParseLexedMethodDefs();
908 virtual void ParseLexedAttributes();
911 /// Inner node of the LateParsedDeclaration tree that parses
912 /// all its members recursively.
913 class LateParsedClass : public LateParsedDeclaration {
915 LateParsedClass(Parser *P, ParsingClass *C);
916 ~LateParsedClass() override;
918 void ParseLexedMethodDeclarations() override;
919 void ParseLexedMemberInitializers() override;
920 void ParseLexedMethodDefs() override;
921 void ParseLexedAttributes() override;
928 /// Contains the lexed tokens of an attribute with arguments that
929 /// may reference member variables and so need to be parsed at the
930 /// end of the class declaration after parsing all other member
931 /// member declarations.
932 /// FIXME: Perhaps we should change the name of LateParsedDeclaration to
933 /// LateParsedTokens.
934 struct LateParsedAttribute : public LateParsedDeclaration {
937 IdentifierInfo &AttrName;
938 SourceLocation AttrNameLoc;
939 SmallVector<Decl*, 2> Decls;
941 explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
943 : Self(P), AttrName(Name), AttrNameLoc(Loc) {}
945 void ParseLexedAttributes() override;
947 void addDecl(Decl *D) { Decls.push_back(D); }
950 // A list of late-parsed attributes. Used by ParseGNUAttributes.
951 class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> {
953 LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { }
955 bool parseSoon() { return ParseSoon; }
958 bool ParseSoon; // Are we planning to parse these shortly after creation?
961 /// Contains the lexed tokens of a member function definition
962 /// which needs to be parsed at the end of the class declaration
963 /// after parsing all other member declarations.
964 struct LexedMethod : public LateParsedDeclaration {
969 /// \brief Whether this member function had an associated template
970 /// scope. When true, D is a template declaration.
971 /// otherwise, it is a member function declaration.
974 explicit LexedMethod(Parser* P, Decl *MD)
975 : Self(P), D(MD), TemplateScope(false) {}
977 void ParseLexedMethodDefs() override;
980 /// LateParsedDefaultArgument - Keeps track of a parameter that may
981 /// have a default argument that cannot be parsed yet because it
982 /// occurs within a member function declaration inside the class
983 /// (C++ [class.mem]p2).
984 struct LateParsedDefaultArgument {
985 explicit LateParsedDefaultArgument(Decl *P,
986 CachedTokens *Toks = nullptr)
987 : Param(P), Toks(Toks) { }
989 /// Param - The parameter declaration for this parameter.
992 /// Toks - The sequence of tokens that comprises the default
993 /// argument expression, not including the '=' or the terminating
994 /// ')' or ','. This will be NULL for parameters that have no
995 /// default argument.
999 /// LateParsedMethodDeclaration - A method declaration inside a class that
1000 /// contains at least one entity whose parsing needs to be delayed
1001 /// until the class itself is completely-defined, such as a default
1002 /// argument (C++ [class.mem]p2).
1003 struct LateParsedMethodDeclaration : public LateParsedDeclaration {
1004 explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
1005 : Self(P), Method(M), TemplateScope(false),
1006 ExceptionSpecTokens(nullptr) {}
1008 void ParseLexedMethodDeclarations() override;
1012 /// Method - The method declaration.
1015 /// \brief Whether this member function had an associated template
1016 /// scope. When true, D is a template declaration.
1017 /// othewise, it is a member function declaration.
1020 /// DefaultArgs - Contains the parameters of the function and
1021 /// their default arguments. At least one of the parameters will
1022 /// have a default argument, but all of the parameters of the
1023 /// method will be stored so that they can be reintroduced into
1024 /// scope at the appropriate times.
1025 SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
1027 /// \brief The set of tokens that make up an exception-specification that
1028 /// has not yet been parsed.
1029 CachedTokens *ExceptionSpecTokens;
1032 /// LateParsedMemberInitializer - An initializer for a non-static class data
1033 /// member whose parsing must to be delayed until the class is completely
1034 /// defined (C++11 [class.mem]p2).
1035 struct LateParsedMemberInitializer : public LateParsedDeclaration {
1036 LateParsedMemberInitializer(Parser *P, Decl *FD)
1037 : Self(P), Field(FD) { }
1039 void ParseLexedMemberInitializers() override;
1043 /// Field - The field declaration.
1046 /// CachedTokens - The sequence of tokens that comprises the initializer,
1047 /// including any leading '='.
1051 /// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
1052 /// C++ class, its method declarations that contain parts that won't be
1053 /// parsed until after the definition is completed (C++ [class.mem]p2),
1054 /// the method declarations and possibly attached inline definitions
1055 /// will be stored here with the tokens that will be parsed to create those
1057 typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer;
1059 /// \brief Representation of a class that has been parsed, including
1060 /// any member function declarations or definitions that need to be
1061 /// parsed after the corresponding top-level class is complete.
1062 struct ParsingClass {
1063 ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface)
1064 : TopLevelClass(TopLevelClass), TemplateScope(false),
1065 IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) { }
1067 /// \brief Whether this is a "top-level" class, meaning that it is
1068 /// not nested within another class.
1069 bool TopLevelClass : 1;
1071 /// \brief Whether this class had an associated template
1072 /// scope. When true, TagOrTemplate is a template declaration;
1073 /// othewise, it is a tag declaration.
1074 bool TemplateScope : 1;
1076 /// \brief Whether this class is an __interface.
1077 bool IsInterface : 1;
1079 /// \brief The class or class template whose definition we are parsing.
1080 Decl *TagOrTemplate;
1082 /// LateParsedDeclarations - Method declarations, inline definitions and
1083 /// nested classes that contain pieces whose parsing will be delayed until
1084 /// the top-level class is fully defined.
1085 LateParsedDeclarationsContainer LateParsedDeclarations;
1088 /// \brief The stack of classes that is currently being
1089 /// parsed. Nested and local classes will be pushed onto this stack
1090 /// when they are parsed, and removed afterward.
1091 std::stack<ParsingClass *> ClassStack;
1093 ParsingClass &getCurrentClass() {
1094 assert(!ClassStack.empty() && "No lexed method stacks!");
1095 return *ClassStack.top();
1098 /// \brief RAII object used to manage the parsing of a class definition.
1099 class ParsingClassDefinition {
1102 Sema::ParsingClassState State;
1105 ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass,
1107 : P(P), Popped(false),
1108 State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
1111 /// \brief Pop this class of the stack.
1113 assert(!Popped && "Nested class has already been popped");
1115 P.PopParsingClass(State);
1118 ~ParsingClassDefinition() {
1120 P.PopParsingClass(State);
1124 /// \brief Contains information about any template-specific
1125 /// information that has been parsed prior to parsing declaration
1127 struct ParsedTemplateInfo {
1128 ParsedTemplateInfo()
1129 : Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { }
1131 ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
1132 bool isSpecialization,
1133 bool lastParameterListWasEmpty = false)
1134 : Kind(isSpecialization? ExplicitSpecialization : Template),
1135 TemplateParams(TemplateParams),
1136 LastParameterListWasEmpty(lastParameterListWasEmpty) { }
1138 explicit ParsedTemplateInfo(SourceLocation ExternLoc,
1139 SourceLocation TemplateLoc)
1140 : Kind(ExplicitInstantiation), TemplateParams(nullptr),
1141 ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
1142 LastParameterListWasEmpty(false){ }
1144 /// \brief The kind of template we are parsing.
1146 /// \brief We are not parsing a template at all.
1148 /// \brief We are parsing a template declaration.
1150 /// \brief We are parsing an explicit specialization.
1151 ExplicitSpecialization,
1152 /// \brief We are parsing an explicit instantiation.
1153 ExplicitInstantiation
1156 /// \brief The template parameter lists, for template declarations
1157 /// and explicit specializations.
1158 TemplateParameterLists *TemplateParams;
1160 /// \brief The location of the 'extern' keyword, if any, for an explicit
1162 SourceLocation ExternLoc;
1164 /// \brief The location of the 'template' keyword, for an explicit
1166 SourceLocation TemplateLoc;
1168 /// \brief Whether the last template parameter list was empty.
1169 bool LastParameterListWasEmpty;
1171 SourceRange getSourceRange() const LLVM_READONLY;
1174 void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
1175 void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
1177 static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
1178 static void LateTemplateParserCleanupCallback(void *P);
1180 Sema::ParsingClassState
1181 PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface);
1182 void DeallocateParsedClasses(ParsingClass *Class);
1183 void PopParsingClass(Sema::ParsingClassState);
1185 enum CachedInitKind {
1186 CIK_DefaultArgument,
1187 CIK_DefaultInitializer
1190 NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS,
1191 AttributeList *AccessAttrs,
1192 ParsingDeclarator &D,
1193 const ParsedTemplateInfo &TemplateInfo,
1194 const VirtSpecifiers& VS,
1195 SourceLocation PureSpecLoc);
1196 void ParseCXXNonStaticMemberInitializer(Decl *VarD);
1197 void ParseLexedAttributes(ParsingClass &Class);
1198 void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1199 bool EnterScope, bool OnDefinition);
1200 void ParseLexedAttribute(LateParsedAttribute &LA,
1201 bool EnterScope, bool OnDefinition);
1202 void ParseLexedMethodDeclarations(ParsingClass &Class);
1203 void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
1204 void ParseLexedMethodDefs(ParsingClass &Class);
1205 void ParseLexedMethodDef(LexedMethod &LM);
1206 void ParseLexedMemberInitializers(ParsingClass &Class);
1207 void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
1208 void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod);
1209 bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
1210 bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK);
1211 bool ConsumeAndStoreConditional(CachedTokens &Toks);
1212 bool ConsumeAndStoreUntil(tok::TokenKind T1,
1214 bool StopAtSemi = true,
1215 bool ConsumeFinalToken = true) {
1216 return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
1218 bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
1220 bool StopAtSemi = true,
1221 bool ConsumeFinalToken = true);
1223 //===--------------------------------------------------------------------===//
1224 // C99 6.9: External Definitions.
1225 struct ParsedAttributesWithRange : ParsedAttributes {
1226 ParsedAttributesWithRange(AttributeFactory &factory)
1227 : ParsedAttributes(factory) {}
1232 DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
1233 ParsingDeclSpec *DS = nullptr);
1234 bool isDeclarationAfterDeclarator();
1235 bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
1236 DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(
1237 ParsedAttributesWithRange &attrs,
1238 ParsingDeclSpec *DS = nullptr,
1239 AccessSpecifier AS = AS_none);
1240 DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
1241 ParsingDeclSpec &DS,
1242 AccessSpecifier AS);
1244 void SkipFunctionBody();
1245 Decl *ParseFunctionDefinition(ParsingDeclarator &D,
1246 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1247 LateParsedAttrList *LateParsedAttrs = nullptr);
1248 void ParseKNRParamDeclarations(Declarator &D);
1249 // EndLoc, if non-NULL, is filled with the location of the last token of
1251 ExprResult ParseSimpleAsm(SourceLocation *EndLoc = nullptr);
1252 ExprResult ParseAsmStringLiteral();
1254 // Objective-C External Declarations
1255 void MaybeSkipAttributes(tok::ObjCKeywordKind Kind);
1256 DeclGroupPtrTy ParseObjCAtDirectives();
1257 DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
1258 Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
1259 ParsedAttributes &prefixAttrs);
1260 class ObjCTypeParamListScope;
1261 ObjCTypeParamList *parseObjCTypeParamList();
1262 ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs(
1263 ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
1264 SmallVectorImpl<IdentifierLocPair> &protocolIdents,
1265 SourceLocation &rAngleLoc, bool mayBeProtocolList = true);
1267 void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
1268 BalancedDelimiterTracker &T,
1269 SmallVectorImpl<Decl *> &AllIvarDecls,
1270 bool RBraceMissing);
1271 void ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1272 tok::ObjCKeywordKind visibility,
1273 SourceLocation atLoc);
1274 bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P,
1275 SmallVectorImpl<SourceLocation> &PLocs,
1276 bool WarnOnDeclarations,
1277 bool ForObjCContainer,
1278 SourceLocation &LAngleLoc,
1279 SourceLocation &EndProtoLoc,
1280 bool consumeLastToken);
1282 /// Parse the first angle-bracket-delimited clause for an
1283 /// Objective-C object or object pointer type, which may be either
1284 /// type arguments or protocol qualifiers.
1285 void parseObjCTypeArgsOrProtocolQualifiers(
1286 ParsedType baseType,
1287 SourceLocation &typeArgsLAngleLoc,
1288 SmallVectorImpl<ParsedType> &typeArgs,
1289 SourceLocation &typeArgsRAngleLoc,
1290 SourceLocation &protocolLAngleLoc,
1291 SmallVectorImpl<Decl *> &protocols,
1292 SmallVectorImpl<SourceLocation> &protocolLocs,
1293 SourceLocation &protocolRAngleLoc,
1294 bool consumeLastToken,
1295 bool warnOnIncompleteProtocols);
1297 /// Parse either Objective-C type arguments or protocol qualifiers; if the
1298 /// former, also parse protocol qualifiers afterward.
1299 void parseObjCTypeArgsAndProtocolQualifiers(
1300 ParsedType baseType,
1301 SourceLocation &typeArgsLAngleLoc,
1302 SmallVectorImpl<ParsedType> &typeArgs,
1303 SourceLocation &typeArgsRAngleLoc,
1304 SourceLocation &protocolLAngleLoc,
1305 SmallVectorImpl<Decl *> &protocols,
1306 SmallVectorImpl<SourceLocation> &protocolLocs,
1307 SourceLocation &protocolRAngleLoc,
1308 bool consumeLastToken);
1310 /// Parse a protocol qualifier type such as '<NSCopying>', which is
1311 /// an anachronistic way of writing 'id<NSCopying>'.
1312 TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc);
1314 /// Parse Objective-C type arguments and protocol qualifiers, extending the
1315 /// current type with the parsed result.
1316 TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc,
1318 bool consumeLastToken,
1319 SourceLocation &endLoc);
1321 void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
1323 DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
1324 ParsedAttributes &prefixAttrs);
1326 struct ObjCImplParsingDataRAII {
1330 typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer;
1331 LateParsedObjCMethodContainer LateParsedObjCMethods;
1333 ObjCImplParsingDataRAII(Parser &parser, Decl *D)
1334 : P(parser), Dcl(D), HasCFunction(false) {
1335 P.CurParsedObjCImpl = this;
1338 ~ObjCImplParsingDataRAII();
1340 void finish(SourceRange AtEnd);
1341 bool isFinished() const { return Finished; }
1346 ObjCImplParsingDataRAII *CurParsedObjCImpl;
1347 void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl);
1349 DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc);
1350 DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
1351 Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
1352 Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
1353 Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
1355 IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
1356 // Definitions for Objective-c context sensitive keywords recognition.
1358 objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
1359 objc_nonnull, objc_nullable, objc_null_unspecified,
1362 IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
1364 bool isTokIdentifier_in() const;
1366 ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, Declarator::TheContext Ctx,
1367 ParsedAttributes *ParamAttrs);
1368 void ParseObjCMethodRequirement();
1369 Decl *ParseObjCMethodPrototype(
1370 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1371 bool MethodDefinition = true);
1372 Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
1373 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1374 bool MethodDefinition=true);
1375 void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
1377 Decl *ParseObjCMethodDefinition();
1380 //===--------------------------------------------------------------------===//
1381 // C99 6.5: Expressions.
1383 /// TypeCastState - State whether an expression is or may be a type cast.
1384 enum TypeCastState {
1390 ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast);
1391 ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast);
1392 ExprResult ParseConstraintExpression();
1393 // Expr that doesn't include commas.
1394 ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast);
1396 ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1397 unsigned &NumLineToksConsumed,
1399 bool IsUnevaluated);
1402 ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
1404 ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
1406 ExprResult ParseRHSOfBinaryExpression(ExprResult LHS,
1407 prec::Level MinPrec);
1408 ExprResult ParseCastExpression(bool isUnaryExpression,
1409 bool isAddressOfOperand,
1411 TypeCastState isTypeCast);
1412 ExprResult ParseCastExpression(bool isUnaryExpression,
1413 bool isAddressOfOperand = false,
1414 TypeCastState isTypeCast = NotTypeCast);
1416 /// Returns true if the next token cannot start an expression.
1417 bool isNotExpressionStart();
1419 /// Returns true if the next token would start a postfix-expression
1421 bool isPostfixExpressionSuffixStart() {
1422 tok::TokenKind K = Tok.getKind();
1423 return (K == tok::l_square || K == tok::l_paren ||
1424 K == tok::period || K == tok::arrow ||
1425 K == tok::plusplus || K == tok::minusminus);
1428 ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
1429 ExprResult ParseUnaryExprOrTypeTraitExpression();
1430 ExprResult ParseBuiltinPrimaryExpression();
1432 ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1435 SourceRange &CastRange);
1437 typedef SmallVector<Expr*, 20> ExprListTy;
1438 typedef SmallVector<SourceLocation, 20> CommaLocsTy;
1440 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1441 bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
1442 SmallVectorImpl<SourceLocation> &CommaLocs,
1443 std::function<void()> Completer = nullptr);
1445 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
1446 /// used for misc language extensions.
1447 bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
1448 SmallVectorImpl<SourceLocation> &CommaLocs);
1451 /// ParenParseOption - Control what ParseParenExpression will parse.
1452 enum ParenParseOption {
1453 SimpleExpr, // Only parse '(' expression ')'
1454 CompoundStmt, // Also allow '(' compound-statement ')'
1455 CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
1456 CastExpr // Also allow '(' type-name ')' <anything>
1458 ExprResult ParseParenExpression(ParenParseOption &ExprType,
1459 bool stopIfCastExpr,
1462 SourceLocation &RParenLoc);
1464 ExprResult ParseCXXAmbiguousParenExpression(
1465 ParenParseOption &ExprType, ParsedType &CastTy,
1466 BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt);
1467 ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
1468 SourceLocation LParenLoc,
1469 SourceLocation RParenLoc);
1471 ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
1473 ExprResult ParseGenericSelectionExpression();
1475 ExprResult ParseObjCBoolLiteral();
1477 ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T);
1479 //===--------------------------------------------------------------------===//
1481 ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
1482 Token &Replacement);
1483 ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
1485 bool areTokensAdjacent(const Token &A, const Token &B);
1487 void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
1488 bool EnteringContext, IdentifierInfo &II,
1491 bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
1492 ParsedType ObjectType,
1493 bool EnteringContext,
1494 bool *MayBePseudoDestructor = nullptr,
1495 bool IsTypename = false,
1496 IdentifierInfo **LastII = nullptr);
1498 void CheckForLParenAfterColonColon();
1500 //===--------------------------------------------------------------------===//
1501 // C++0x 5.1.2: Lambda expressions
1503 // [...] () -> type {...}
1504 ExprResult ParseLambdaExpression();
1505 ExprResult TryParseLambdaExpression();
1506 Optional<unsigned> ParseLambdaIntroducer(LambdaIntroducer &Intro,
1507 bool *SkippedInits = nullptr);
1508 bool TryParseLambdaIntroducer(LambdaIntroducer &Intro);
1509 ExprResult ParseLambdaExpressionAfterIntroducer(
1510 LambdaIntroducer &Intro);
1512 //===--------------------------------------------------------------------===//
1513 // C++ 5.2p1: C++ Casts
1514 ExprResult ParseCXXCasts();
1516 //===--------------------------------------------------------------------===//
1517 // C++ 5.2p1: C++ Type Identification
1518 ExprResult ParseCXXTypeid();
1520 //===--------------------------------------------------------------------===//
1521 // C++ : Microsoft __uuidof Expression
1522 ExprResult ParseCXXUuidof();
1524 //===--------------------------------------------------------------------===//
1525 // C++ 5.2.4: C++ Pseudo-Destructor Expressions
1526 ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1527 tok::TokenKind OpKind,
1529 ParsedType ObjectType);
1531 //===--------------------------------------------------------------------===//
1532 // C++ 9.3.2: C++ 'this' pointer
1533 ExprResult ParseCXXThis();
1535 //===--------------------------------------------------------------------===//
1536 // C++ 15: C++ Throw Expression
1537 ExprResult ParseThrowExpression();
1539 ExceptionSpecificationType tryParseExceptionSpecification(
1541 SourceRange &SpecificationRange,
1542 SmallVectorImpl<ParsedType> &DynamicExceptions,
1543 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
1544 ExprResult &NoexceptExpr,
1545 CachedTokens *&ExceptionSpecTokens);
1547 // EndLoc is filled with the location of the last token of the specification.
1548 ExceptionSpecificationType ParseDynamicExceptionSpecification(
1549 SourceRange &SpecificationRange,
1550 SmallVectorImpl<ParsedType> &Exceptions,
1551 SmallVectorImpl<SourceRange> &Ranges);
1553 //===--------------------------------------------------------------------===//
1554 // C++0x 8: Function declaration trailing-return-type
1555 TypeResult ParseTrailingReturnType(SourceRange &Range);
1557 //===--------------------------------------------------------------------===//
1558 // C++ 2.13.5: C++ Boolean Literals
1559 ExprResult ParseCXXBoolLiteral();
1561 //===--------------------------------------------------------------------===//
1562 // C++ 5.2.3: Explicit type conversion (functional notation)
1563 ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
1565 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1566 /// This should only be called when the current token is known to be part of
1567 /// simple-type-specifier.
1568 void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
1570 bool ParseCXXTypeSpecifierSeq(DeclSpec &DS);
1572 //===--------------------------------------------------------------------===//
1573 // C++ 5.3.4 and 5.3.5: C++ new and delete
1574 bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs,
1576 void ParseDirectNewDeclarator(Declarator &D);
1577 ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
1578 ExprResult ParseCXXDeleteExpression(bool UseGlobal,
1579 SourceLocation Start);
1581 //===--------------------------------------------------------------------===//
1582 // C++ if/switch/while condition expression.
1583 bool ParseCXXCondition(ExprResult &ExprResult, Decl *&DeclResult,
1584 SourceLocation Loc, bool ConvertToBoolean);
1586 //===--------------------------------------------------------------------===//
1589 ExprResult ParseCoyieldExpression();
1591 //===--------------------------------------------------------------------===//
1592 // C99 6.7.8: Initialization.
1594 /// ParseInitializer
1595 /// initializer: [C99 6.7.8]
1596 /// assignment-expression
1598 ExprResult ParseInitializer() {
1599 if (Tok.isNot(tok::l_brace))
1600 return ParseAssignmentExpression();
1601 return ParseBraceInitializer();
1603 bool MayBeDesignationStart();
1604 ExprResult ParseBraceInitializer();
1605 ExprResult ParseInitializerWithPotentialDesignator();
1607 //===--------------------------------------------------------------------===//
1608 // clang Expressions
1610 ExprResult ParseBlockLiteralExpression(); // ^{...}
1612 //===--------------------------------------------------------------------===//
1613 // Objective-C Expressions
1614 ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
1615 ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
1616 ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
1617 ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
1618 ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
1619 ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
1620 ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
1621 ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
1622 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
1623 ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
1624 ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
1625 bool isSimpleObjCMessageExpression();
1626 ExprResult ParseObjCMessageExpression();
1627 ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
1628 SourceLocation SuperLoc,
1629 ParsedType ReceiverType,
1630 Expr *ReceiverExpr);
1631 ExprResult ParseAssignmentExprWithObjCMessageExprStart(
1632 SourceLocation LBracloc, SourceLocation SuperLoc,
1633 ParsedType ReceiverType, Expr *ReceiverExpr);
1634 bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
1636 //===--------------------------------------------------------------------===//
1637 // C99 6.8: Statements and Blocks.
1639 /// A SmallVector of statements, with stack size 32 (as that is the only one
1641 typedef SmallVector<Stmt*, 32> StmtVector;
1642 /// A SmallVector of expressions, with stack size 12 (the maximum used.)
1643 typedef SmallVector<Expr*, 12> ExprVector;
1644 /// A SmallVector of types.
1645 typedef SmallVector<ParsedType, 12> TypeVector;
1647 StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
1648 bool AllowOpenMPStandalone = false);
1649 enum AllowedContsructsKind {
1650 /// \brief Allow any declarations, statements, OpenMP directives.
1652 /// \brief Allow only statements and non-standalone OpenMP directives.
1653 ACK_StatementsOpenMPNonStandalone,
1654 /// \brief Allow statements and all executable OpenMP directives
1655 ACK_StatementsOpenMPAnyExecutable
1658 ParseStatementOrDeclaration(StmtVector &Stmts, AllowedContsructsKind Allowed,
1659 SourceLocation *TrailingElseLoc = nullptr);
1660 StmtResult ParseStatementOrDeclarationAfterAttributes(
1662 AllowedContsructsKind Allowed,
1663 SourceLocation *TrailingElseLoc,
1664 ParsedAttributesWithRange &Attrs);
1665 StmtResult ParseExprStatement();
1666 StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs);
1667 StmtResult ParseCaseStatement(bool MissingCase = false,
1668 ExprResult Expr = ExprResult());
1669 StmtResult ParseDefaultStatement();
1670 StmtResult ParseCompoundStatement(bool isStmtExpr = false);
1671 StmtResult ParseCompoundStatement(bool isStmtExpr,
1672 unsigned ScopeFlags);
1673 void ParseCompoundStatementLeadingPragmas();
1674 StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
1675 bool ParseParenExprOrCondition(ExprResult &ExprResult,
1678 bool ConvertToBoolean);
1679 StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
1680 StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
1681 StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
1682 StmtResult ParseDoStatement();
1683 StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
1684 StmtResult ParseGotoStatement();
1685 StmtResult ParseContinueStatement();
1686 StmtResult ParseBreakStatement();
1687 StmtResult ParseReturnStatement();
1688 StmtResult ParseAsmStatement(bool &msAsm);
1689 StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
1690 StmtResult ParsePragmaLoopHint(StmtVector &Stmts,
1691 AllowedContsructsKind Allowed,
1692 SourceLocation *TrailingElseLoc,
1693 ParsedAttributesWithRange &Attrs);
1695 /// \brief Describes the behavior that should be taken for an __if_exists
1697 enum IfExistsBehavior {
1698 /// \brief Parse the block; this code is always used.
1700 /// \brief Skip the block entirely; this code is never used.
1702 /// \brief Parse the block as a dependent block, which may be used in
1703 /// some template instantiations but not others.
1707 /// \brief Describes the condition of a Microsoft __if_exists or
1708 /// __if_not_exists block.
1709 struct IfExistsCondition {
1710 /// \brief The location of the initial keyword.
1711 SourceLocation KeywordLoc;
1712 /// \brief Whether this is an __if_exists block (rather than an
1713 /// __if_not_exists block).
1716 /// \brief Nested-name-specifier preceding the name.
1719 /// \brief The name we're looking for.
1722 /// \brief The behavior of this __if_exists or __if_not_exists block
1724 IfExistsBehavior Behavior;
1727 bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
1728 void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
1729 void ParseMicrosoftIfExistsExternalDeclaration();
1730 void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
1731 AccessSpecifier& CurAS);
1732 bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
1734 bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
1735 SmallVectorImpl<Expr *> &Constraints,
1736 SmallVectorImpl<Expr *> &Exprs);
1738 //===--------------------------------------------------------------------===//
1739 // C++ 6: Statements and Blocks
1741 StmtResult ParseCXXTryBlock();
1742 StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
1743 StmtResult ParseCXXCatchBlock(bool FnCatch = false);
1745 //===--------------------------------------------------------------------===//
1746 // MS: SEH Statements and Blocks
1748 StmtResult ParseSEHTryBlock();
1749 StmtResult ParseSEHExceptBlock(SourceLocation Loc);
1750 StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
1751 StmtResult ParseSEHLeaveStatement();
1753 //===--------------------------------------------------------------------===//
1754 // Objective-C Statements
1756 StmtResult ParseObjCAtStatement(SourceLocation atLoc);
1757 StmtResult ParseObjCTryStmt(SourceLocation atLoc);
1758 StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
1759 StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
1760 StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
1763 //===--------------------------------------------------------------------===//
1764 // C99 6.7: Declarations.
1766 /// A context for parsing declaration specifiers. TODO: flesh this
1767 /// out, there are other significant restrictions on specifiers than
1768 /// would be best implemented in the parser.
1769 enum DeclSpecContext {
1770 DSC_normal, // normal context
1771 DSC_class, // class context, enables 'friend'
1772 DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
1773 DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
1774 DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration
1775 DSC_top_level, // top-level/namespace declaration context
1776 DSC_template_type_arg, // template type argument context
1777 DSC_objc_method_result, // ObjC method result context, enables 'instancetype'
1778 DSC_condition // condition declaration context
1781 /// Is this a context in which we are parsing just a type-specifier (or
1782 /// trailing-type-specifier)?
1783 static bool isTypeSpecifier(DeclSpecContext DSC) {
1788 case DSC_objc_method_result:
1792 case DSC_template_type_arg:
1793 case DSC_type_specifier:
1795 case DSC_alias_declaration:
1798 llvm_unreachable("Missing DeclSpecContext case");
1801 /// Information on a C++0x for-range-initializer found while parsing a
1802 /// declaration which turns out to be a for-range-declaration.
1803 struct ForRangeInit {
1804 SourceLocation ColonLoc;
1805 ExprResult RangeExpr;
1807 bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
1810 DeclGroupPtrTy ParseDeclaration(unsigned Context, SourceLocation &DeclEnd,
1811 ParsedAttributesWithRange &attrs);
1812 DeclGroupPtrTy ParseSimpleDeclaration(unsigned Context,
1813 SourceLocation &DeclEnd,
1814 ParsedAttributesWithRange &attrs,
1816 ForRangeInit *FRI = nullptr);
1817 bool MightBeDeclarator(unsigned Context);
1818 DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, unsigned Context,
1819 SourceLocation *DeclEnd = nullptr,
1820 ForRangeInit *FRI = nullptr);
1821 Decl *ParseDeclarationAfterDeclarator(Declarator &D,
1822 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
1823 bool ParseAsmAttributesAfterDeclarator(Declarator &D);
1824 Decl *ParseDeclarationAfterDeclaratorAndAttributes(
1826 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1827 ForRangeInit *FRI = nullptr);
1828 Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
1829 Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
1831 /// \brief When in code-completion, skip parsing of the function/method body
1832 /// unless the body contains the code-completion point.
1834 /// \returns true if the function body was skipped.
1835 bool trySkippingFunctionBody();
1837 bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
1838 const ParsedTemplateInfo &TemplateInfo,
1839 AccessSpecifier AS, DeclSpecContext DSC,
1840 ParsedAttributesWithRange &Attrs);
1841 DeclSpecContext getDeclSpecContextFromDeclaratorContext(unsigned Context);
1842 void ParseDeclarationSpecifiers(DeclSpec &DS,
1843 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1844 AccessSpecifier AS = AS_none,
1845 DeclSpecContext DSC = DSC_normal,
1846 LateParsedAttrList *LateAttrs = nullptr);
1847 bool DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
1848 DeclSpecContext DSContext,
1849 LateParsedAttrList *LateAttrs = nullptr);
1851 void ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS = AS_none,
1852 DeclSpecContext DSC = DSC_normal);
1854 void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
1855 Declarator::TheContext Context);
1857 void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
1858 const ParsedTemplateInfo &TemplateInfo,
1859 AccessSpecifier AS, DeclSpecContext DSC);
1860 void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
1861 void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType,
1864 void ParseStructDeclaration(
1865 ParsingDeclSpec &DS,
1866 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback);
1868 bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
1869 bool isTypeSpecifierQualifier();
1870 bool isTypeQualifier() const;
1872 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
1873 /// is definitely a type-specifier. Return false if it isn't part of a type
1874 /// specifier or if we're not sure.
1875 bool isKnownToBeTypeSpecifier(const Token &Tok) const;
1877 /// \brief Return true if we know that we are definitely looking at a
1878 /// decl-specifier, and isn't part of an expression such as a function-style
1879 /// cast. Return false if it's no a decl-specifier, or we're not sure.
1880 bool isKnownToBeDeclarationSpecifier() {
1881 if (getLangOpts().CPlusPlus)
1882 return isCXXDeclarationSpecifier() == TPResult::True;
1883 return isDeclarationSpecifier(true);
1886 /// isDeclarationStatement - Disambiguates between a declaration or an
1887 /// expression statement, when parsing function bodies.
1888 /// Returns true for declaration, false for expression.
1889 bool isDeclarationStatement() {
1890 if (getLangOpts().CPlusPlus)
1891 return isCXXDeclarationStatement();
1892 return isDeclarationSpecifier(true);
1895 /// isForInitDeclaration - Disambiguates between a declaration or an
1896 /// expression in the context of the C 'clause-1' or the C++
1897 // 'for-init-statement' part of a 'for' statement.
1898 /// Returns true for declaration, false for expression.
1899 bool isForInitDeclaration() {
1900 if (getLangOpts().CPlusPlus)
1901 return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
1902 return isDeclarationSpecifier(true);
1905 /// \brief Determine whether this is a C++1z for-range-identifier.
1906 bool isForRangeIdentifier();
1908 /// \brief Determine whether we are currently at the start of an Objective-C
1909 /// class message that appears to be missing the open bracket '['.
1910 bool isStartOfObjCClassMessageMissingOpenBracket();
1912 /// \brief Starting with a scope specifier, identifier, or
1913 /// template-id that refers to the current class, determine whether
1914 /// this is a constructor declarator.
1915 bool isConstructorDeclarator(bool Unqualified);
1917 /// \brief Specifies the context in which type-id/expression
1918 /// disambiguation will occur.
1919 enum TentativeCXXTypeIdContext {
1922 TypeIdAsTemplateArgument
1926 /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
1927 /// whether the parens contain an expression or a type-id.
1928 /// Returns true for a type-id and false for an expression.
1929 bool isTypeIdInParens(bool &isAmbiguous) {
1930 if (getLangOpts().CPlusPlus)
1931 return isCXXTypeId(TypeIdInParens, isAmbiguous);
1932 isAmbiguous = false;
1933 return isTypeSpecifierQualifier();
1935 bool isTypeIdInParens() {
1937 return isTypeIdInParens(isAmbiguous);
1940 /// \brief Checks if the current tokens form type-id or expression.
1941 /// It is similar to isTypeIdInParens but does not suppose that type-id
1942 /// is in parenthesis.
1943 bool isTypeIdUnambiguously() {
1945 if (getLangOpts().CPlusPlus)
1946 return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous);
1947 return isTypeSpecifierQualifier();
1950 /// isCXXDeclarationStatement - C++-specialized function that disambiguates
1951 /// between a declaration or an expression statement, when parsing function
1952 /// bodies. Returns true for declaration, false for expression.
1953 bool isCXXDeclarationStatement();
1955 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
1956 /// between a simple-declaration or an expression-statement.
1957 /// If during the disambiguation process a parsing error is encountered,
1958 /// the function returns true to let the declaration parsing code handle it.
1959 /// Returns false if the statement is disambiguated as expression.
1960 bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
1962 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
1963 /// a constructor-style initializer, when parsing declaration statements.
1964 /// Returns true for function declarator and false for constructor-style
1965 /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
1966 /// might be a constructor-style initializer.
1967 /// If during the disambiguation process a parsing error is encountered,
1968 /// the function returns true to let the declaration parsing code handle it.
1969 bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr);
1971 /// isCXXConditionDeclaration - Disambiguates between a declaration or an
1972 /// expression for a condition of a if/switch/while/for statement.
1973 /// If during the disambiguation process a parsing error is encountered,
1974 /// the function returns true to let the declaration parsing code handle it.
1975 bool isCXXConditionDeclaration();
1977 bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
1978 bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
1980 return isCXXTypeId(Context, isAmbiguous);
1983 /// TPResult - Used as the result value for functions whose purpose is to
1984 /// disambiguate C++ constructs by "tentatively parsing" them.
1985 enum class TPResult {
1986 True, False, Ambiguous, Error
1989 /// \brief Based only on the given token kind, determine whether we know that
1990 /// we're at the start of an expression or a type-specifier-seq (which may
1991 /// be an expression, in C++).
1993 /// This routine does not attempt to resolve any of the trick cases, e.g.,
1994 /// those involving lookup of identifiers.
1996 /// \returns \c TPR_true if this token starts an expression, \c TPR_false if
1997 /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot
1999 TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind);
2001 /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a
2002 /// declaration specifier, TPResult::False if it is not,
2003 /// TPResult::Ambiguous if it could be either a decl-specifier or a
2004 /// function-style cast, and TPResult::Error if a parsing error was
2005 /// encountered. If it could be a braced C++11 function-style cast, returns
2006 /// BracedCastResult.
2007 /// Doesn't consume tokens.
2009 isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False,
2010 bool *HasMissingTypename = nullptr);
2012 /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
2013 /// \c TPResult::Ambiguous, determine whether the decl-specifier would be
2014 /// a type-specifier other than a cv-qualifier.
2015 bool isCXXDeclarationSpecifierAType();
2017 /// \brief Determine whether an identifier has been tentatively declared as a
2018 /// non-type. Such tentative declarations should not be found to name a type
2019 /// during a tentative parse, but also should not be annotated as a non-type.
2020 bool isTentativelyDeclared(IdentifierInfo *II);
2022 // "Tentative parsing" functions, used for disambiguation. If a parsing error
2023 // is encountered they will return TPResult::Error.
2024 // Returning TPResult::True/False indicates that the ambiguity was
2025 // resolved and tentative parsing may stop. TPResult::Ambiguous indicates
2026 // that more tentative parsing is necessary for disambiguation.
2027 // They all consume tokens, so backtracking should be used after calling them.
2029 TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
2030 TPResult TryParseTypeofSpecifier();
2031 TPResult TryParseProtocolQualifiers();
2032 TPResult TryParsePtrOperatorSeq();
2033 TPResult TryParseOperatorId();
2034 TPResult TryParseInitDeclaratorList();
2035 TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier=true);
2037 TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr,
2038 bool VersusTemplateArg = false);
2039 TPResult TryParseFunctionDeclarator();
2040 TPResult TryParseBracketDeclarator();
2041 TPResult TryConsumeDeclarationSpecifier();
2044 TypeResult ParseTypeName(SourceRange *Range = nullptr,
2045 Declarator::TheContext Context
2046 = Declarator::TypeNameContext,
2047 AccessSpecifier AS = AS_none,
2048 Decl **OwnedType = nullptr,
2049 ParsedAttributes *Attrs = nullptr);
2052 void ParseBlockId(SourceLocation CaretLoc);
2054 // Check for the start of a C++11 attribute-specifier-seq in a context where
2055 // an attribute is not allowed.
2056 bool CheckProhibitedCXX11Attribute() {
2057 assert(Tok.is(tok::l_square));
2058 if (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))
2060 return DiagnoseProhibitedCXX11Attribute();
2062 bool DiagnoseProhibitedCXX11Attribute();
2063 void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2064 SourceLocation CorrectLocation) {
2065 if (!getLangOpts().CPlusPlus11)
2067 if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
2068 Tok.isNot(tok::kw_alignas))
2070 DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
2072 void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2073 SourceLocation CorrectLocation);
2075 void handleDeclspecAlignBeforeClassKey(ParsedAttributesWithRange &Attrs,
2076 DeclSpec &DS, Sema::TagUseKind TUK);
2078 void ProhibitAttributes(ParsedAttributesWithRange &attrs) {
2079 if (!attrs.Range.isValid()) return;
2080 DiagnoseProhibitedAttributes(attrs);
2083 void DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs);
2085 // Forbid C++11 attributes that appear on certain syntactic
2086 // locations which standard permits but we don't supported yet,
2087 // for example, attributes appertain to decl specifiers.
2088 void ProhibitCXX11Attributes(ParsedAttributesWithRange &attrs);
2090 /// \brief Skip C++11 attributes and return the end location of the last one.
2091 /// \returns SourceLocation() if there are no attributes.
2092 SourceLocation SkipCXX11Attributes();
2094 /// \brief Diagnose and skip C++11 attributes that appear in syntactic
2095 /// locations where attributes are not allowed.
2096 void DiagnoseAndSkipCXX11Attributes();
2098 /// \brief Parses syntax-generic attribute arguments for attributes which are
2099 /// known to the implementation, and adds them to the given ParsedAttributes
2100 /// list with the given attribute syntax. Returns the number of arguments
2101 /// parsed for the attribute.
2103 ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2104 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2105 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2106 AttributeList::Syntax Syntax);
2108 void MaybeParseGNUAttributes(Declarator &D,
2109 LateParsedAttrList *LateAttrs = nullptr) {
2110 if (Tok.is(tok::kw___attribute)) {
2111 ParsedAttributes attrs(AttrFactory);
2112 SourceLocation endLoc;
2113 ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D);
2114 D.takeAttributes(attrs, endLoc);
2117 void MaybeParseGNUAttributes(ParsedAttributes &attrs,
2118 SourceLocation *endLoc = nullptr,
2119 LateParsedAttrList *LateAttrs = nullptr) {
2120 if (Tok.is(tok::kw___attribute))
2121 ParseGNUAttributes(attrs, endLoc, LateAttrs);
2123 void ParseGNUAttributes(ParsedAttributes &attrs,
2124 SourceLocation *endLoc = nullptr,
2125 LateParsedAttrList *LateAttrs = nullptr,
2126 Declarator *D = nullptr);
2127 void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
2128 SourceLocation AttrNameLoc,
2129 ParsedAttributes &Attrs,
2130 SourceLocation *EndLoc,
2131 IdentifierInfo *ScopeName,
2132 SourceLocation ScopeLoc,
2133 AttributeList::Syntax Syntax,
2135 IdentifierLoc *ParseIdentifierLoc();
2137 void MaybeParseCXX11Attributes(Declarator &D) {
2138 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
2139 ParsedAttributesWithRange attrs(AttrFactory);
2140 SourceLocation endLoc;
2141 ParseCXX11Attributes(attrs, &endLoc);
2142 D.takeAttributes(attrs, endLoc);
2145 void MaybeParseCXX11Attributes(ParsedAttributes &attrs,
2146 SourceLocation *endLoc = nullptr) {
2147 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
2148 ParsedAttributesWithRange attrsWithRange(AttrFactory);
2149 ParseCXX11Attributes(attrsWithRange, endLoc);
2150 attrs.takeAllFrom(attrsWithRange);
2153 void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2154 SourceLocation *endLoc = nullptr,
2155 bool OuterMightBeMessageSend = false) {
2156 if (getLangOpts().CPlusPlus11 &&
2157 isCXX11AttributeSpecifier(false, OuterMightBeMessageSend))
2158 ParseCXX11Attributes(attrs, endLoc);
2161 void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
2162 SourceLocation *EndLoc = nullptr);
2163 void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2164 SourceLocation *EndLoc = nullptr);
2165 /// \brief Parses a C++-style attribute argument list. Returns true if this
2166 /// results in adding an attribute to the ParsedAttributes list.
2167 bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
2168 SourceLocation AttrNameLoc,
2169 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2170 IdentifierInfo *ScopeName,
2171 SourceLocation ScopeLoc);
2173 IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc);
2175 void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
2176 SourceLocation *endLoc = nullptr) {
2177 if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
2178 ParseMicrosoftAttributes(attrs, endLoc);
2180 void ParseMicrosoftAttributes(ParsedAttributes &attrs,
2181 SourceLocation *endLoc = nullptr);
2182 void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2183 SourceLocation *End = nullptr) {
2184 const auto &LO = getLangOpts();
2185 if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec))
2186 ParseMicrosoftDeclSpecs(Attrs, End);
2188 void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2189 SourceLocation *End = nullptr);
2190 bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
2191 SourceLocation AttrNameLoc,
2192 ParsedAttributes &Attrs);
2193 void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
2194 void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2195 SourceLocation SkipExtendedMicrosoftTypeAttributes();
2196 void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
2197 void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
2198 void ParseOpenCLAttributes(ParsedAttributes &attrs);
2199 void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
2200 void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
2202 VersionTuple ParseVersionTuple(SourceRange &Range);
2203 void ParseAvailabilityAttribute(IdentifierInfo &Availability,
2204 SourceLocation AvailabilityLoc,
2205 ParsedAttributes &attrs,
2206 SourceLocation *endLoc,
2207 IdentifierInfo *ScopeName,
2208 SourceLocation ScopeLoc,
2209 AttributeList::Syntax Syntax);
2211 void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
2212 SourceLocation ObjCBridgeRelatedLoc,
2213 ParsedAttributes &attrs,
2214 SourceLocation *endLoc,
2215 IdentifierInfo *ScopeName,
2216 SourceLocation ScopeLoc,
2217 AttributeList::Syntax Syntax);
2219 void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
2220 SourceLocation AttrNameLoc,
2221 ParsedAttributes &Attrs,
2222 SourceLocation *EndLoc,
2223 IdentifierInfo *ScopeName,
2224 SourceLocation ScopeLoc,
2225 AttributeList::Syntax Syntax);
2227 void ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
2228 SourceLocation AttrNameLoc,
2229 ParsedAttributes &Attrs,
2230 SourceLocation *EndLoc,
2231 IdentifierInfo *ScopeName,
2232 SourceLocation ScopeLoc,
2233 AttributeList::Syntax Syntax);
2235 void ParseTypeofSpecifier(DeclSpec &DS);
2236 SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
2237 void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
2238 SourceLocation StartLoc,
2239 SourceLocation EndLoc);
2240 void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
2241 void ParseAtomicSpecifier(DeclSpec &DS);
2243 ExprResult ParseAlignArgument(SourceLocation Start,
2244 SourceLocation &EllipsisLoc);
2245 void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2246 SourceLocation *endLoc = nullptr);
2248 VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
2249 VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
2250 return isCXX11VirtSpecifier(Tok);
2252 void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface,
2253 SourceLocation FriendLoc);
2255 bool isCXX11FinalKeyword() const;
2257 /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
2258 /// enter a new C++ declarator scope and exit it when the function is
2260 class DeclaratorScopeObj {
2266 DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
2267 : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
2269 void EnterDeclaratorScope() {
2270 assert(!EnteredScope && "Already entered the scope!");
2271 assert(SS.isSet() && "C++ scope was not set!");
2273 CreatedScope = true;
2274 P.EnterScope(0); // Not a decl scope.
2276 if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
2277 EnteredScope = true;
2280 ~DeclaratorScopeObj() {
2282 assert(SS.isSet() && "C++ scope was cleared ?");
2283 P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
2290 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
2291 void ParseDeclarator(Declarator &D);
2292 /// A function that parses a variant of direct-declarator.
2293 typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
2294 void ParseDeclaratorInternal(Declarator &D,
2295 DirectDeclParseFunction DirectDeclParser);
2297 enum AttrRequirements {
2298 AR_NoAttributesParsed = 0, ///< No attributes are diagnosed.
2299 AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes.
2300 AR_GNUAttributesParsed = 1 << 1,
2301 AR_CXX11AttributesParsed = 1 << 2,
2302 AR_DeclspecAttributesParsed = 1 << 3,
2303 AR_AllAttributesParsed = AR_GNUAttributesParsed |
2304 AR_CXX11AttributesParsed |
2305 AR_DeclspecAttributesParsed,
2306 AR_VendorAttributesParsed = AR_GNUAttributesParsed |
2307 AR_DeclspecAttributesParsed
2310 void ParseTypeQualifierListOpt(DeclSpec &DS,
2311 unsigned AttrReqs = AR_AllAttributesParsed,
2312 bool AtomicAllowed = true,
2313 bool IdentifierRequired = false);
2314 void ParseDirectDeclarator(Declarator &D);
2315 void ParseParenDeclarator(Declarator &D);
2316 void ParseFunctionDeclarator(Declarator &D,
2317 ParsedAttributes &attrs,
2318 BalancedDelimiterTracker &Tracker,
2320 bool RequiresArg = false);
2321 bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
2322 SourceLocation &RefQualifierLoc);
2323 bool isFunctionDeclaratorIdentifierList();
2324 void ParseFunctionDeclaratorIdentifierList(
2326 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
2327 void ParseParameterDeclarationClause(
2329 ParsedAttributes &attrs,
2330 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
2331 SourceLocation &EllipsisLoc);
2332 void ParseBracketDeclarator(Declarator &D);
2333 void ParseMisplacedBracketDeclarator(Declarator &D);
2335 //===--------------------------------------------------------------------===//
2336 // C++ 7: Declarations [dcl.dcl]
2338 /// The kind of attribute specifier we have found.
2339 enum CXX11AttributeKind {
2340 /// This is not an attribute specifier.
2341 CAK_NotAttributeSpecifier,
2342 /// This should be treated as an attribute-specifier.
2343 CAK_AttributeSpecifier,
2344 /// The next tokens are '[[', but this is not an attribute-specifier. This
2345 /// is ill-formed by C++11 [dcl.attr.grammar]p6.
2346 CAK_InvalidAttributeSpecifier
2349 isCXX11AttributeSpecifier(bool Disambiguate = false,
2350 bool OuterMightBeMessageSend = false);
2352 void DiagnoseUnexpectedNamespace(NamedDecl *Context);
2354 DeclGroupPtrTy ParseNamespace(unsigned Context, SourceLocation &DeclEnd,
2355 SourceLocation InlineLoc = SourceLocation());
2356 void ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc,
2357 std::vector<IdentifierInfo*>& Ident,
2358 std::vector<SourceLocation>& NamespaceLoc,
2359 unsigned int index, SourceLocation& InlineLoc,
2360 ParsedAttributes& attrs,
2361 BalancedDelimiterTracker &Tracker);
2362 Decl *ParseLinkage(ParsingDeclSpec &DS, unsigned Context);
2363 Decl *ParseUsingDirectiveOrDeclaration(unsigned Context,
2364 const ParsedTemplateInfo &TemplateInfo,
2365 SourceLocation &DeclEnd,
2366 ParsedAttributesWithRange &attrs,
2367 Decl **OwnedType = nullptr);
2368 Decl *ParseUsingDirective(unsigned Context,
2369 SourceLocation UsingLoc,
2370 SourceLocation &DeclEnd,
2371 ParsedAttributes &attrs);
2372 Decl *ParseUsingDeclaration(unsigned Context,
2373 const ParsedTemplateInfo &TemplateInfo,
2374 SourceLocation UsingLoc,
2375 SourceLocation &DeclEnd,
2376 AccessSpecifier AS = AS_none,
2377 Decl **OwnedType = nullptr);
2378 Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
2379 Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
2380 SourceLocation AliasLoc, IdentifierInfo *Alias,
2381 SourceLocation &DeclEnd);
2383 //===--------------------------------------------------------------------===//
2384 // C++ 9: classes [class] and C structs/unions.
2385 bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
2386 void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
2387 DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo,
2388 AccessSpecifier AS, bool EnteringContext,
2389 DeclSpecContext DSC,
2390 ParsedAttributesWithRange &Attributes);
2391 void SkipCXXMemberSpecification(SourceLocation StartLoc,
2392 SourceLocation AttrFixitLoc,
2395 void ParseCXXMemberSpecification(SourceLocation StartLoc,
2396 SourceLocation AttrFixitLoc,
2397 ParsedAttributesWithRange &Attrs,
2400 ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2401 SourceLocation &EqualLoc);
2402 bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
2404 ExprResult &BitfieldSize,
2405 LateParsedAttrList &LateAttrs);
2406 void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D,
2407 VirtSpecifiers &VS);
2408 DeclGroupPtrTy ParseCXXClassMemberDeclaration(
2409 AccessSpecifier AS, AttributeList *Attr,
2410 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2411 ParsingDeclRAIIObject *DiagsFromTParams = nullptr);
2412 DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas(
2413 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
2414 DeclSpec::TST TagType, Decl *TagDecl);
2415 void ParseConstructorInitializer(Decl *ConstructorDecl);
2416 MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
2417 void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2420 //===--------------------------------------------------------------------===//
2421 // C++ 10: Derived classes [class.derived]
2422 TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
2423 SourceLocation &EndLocation);
2424 void ParseBaseClause(Decl *ClassDecl);
2425 BaseResult ParseBaseSpecifier(Decl *ClassDecl);
2426 AccessSpecifier getAccessSpecifierIfPresent() const;
2428 bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
2429 SourceLocation TemplateKWLoc,
2430 IdentifierInfo *Name,
2431 SourceLocation NameLoc,
2432 bool EnteringContext,
2433 ParsedType ObjectType,
2435 bool AssumeTemplateId);
2436 bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2437 ParsedType ObjectType,
2438 UnqualifiedId &Result);
2440 //===--------------------------------------------------------------------===//
2441 // OpenMP: Directives and clauses.
2442 /// \brief Parses declarative OpenMP directives.
2443 DeclGroupPtrTy ParseOpenMPDeclarativeDirective();
2444 /// \brief Parses simple list of variables.
2446 /// \param Kind Kind of the directive.
2447 /// \param [out] VarList List of referenced variables.
2448 /// \param AllowScopeSpecifier true, if the variables can have fully
2449 /// qualified names.
2451 bool ParseOpenMPSimpleVarList(OpenMPDirectiveKind Kind,
2452 SmallVectorImpl<Expr *> &VarList,
2453 bool AllowScopeSpecifier);
2454 /// \brief Parses declarative or executable directive.
2456 /// \param Allowed ACK_Any, if any directives are allowed,
2457 /// ACK_StatementsOpenMPAnyExecutable - if any executable directives are
2458 /// allowed, ACK_StatementsOpenMPNonStandalone - if only non-standalone
2459 /// executable directives are allowed.
2462 ParseOpenMPDeclarativeOrExecutableDirective(AllowedContsructsKind Allowed);
2463 /// \brief Parses clause of kind \a CKind for directive of a kind \a Kind.
2465 /// \param DKind Kind of current directive.
2466 /// \param CKind Kind of current clause.
2467 /// \param FirstClause true, if this is the first clause of a kind \a CKind
2468 /// in current directive.
2470 OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
2471 OpenMPClauseKind CKind, bool FirstClause);
2472 /// \brief Parses clause with a single expression of a kind \a Kind.
2474 /// \param Kind Kind of current clause.
2476 OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind);
2477 /// \brief Parses simple clause of a kind \a Kind.
2479 /// \param Kind Kind of current clause.
2481 OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind);
2482 /// \brief Parses clause with a single expression and an additional argument
2483 /// of a kind \a Kind.
2485 /// \param Kind Kind of current clause.
2487 OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind);
2488 /// \brief Parses clause without any additional arguments.
2490 /// \param Kind Kind of current clause.
2492 OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind);
2493 /// \brief Parses clause with the list of variables of a kind \a Kind.
2495 /// \param Kind Kind of current clause.
2497 OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
2498 OpenMPClauseKind Kind);
2501 bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2502 bool AllowDestructorName,
2503 bool AllowConstructorName,
2504 ParsedType ObjectType,
2505 SourceLocation& TemplateKWLoc,
2506 UnqualifiedId &Result);
2509 //===--------------------------------------------------------------------===//
2510 // C++ 14: Templates [temp]
2512 // C++ 14.1: Template Parameters [temp.param]
2513 Decl *ParseDeclarationStartingWithTemplate(unsigned Context,
2514 SourceLocation &DeclEnd,
2515 AccessSpecifier AS = AS_none,
2516 AttributeList *AccessAttrs = nullptr);
2517 Decl *ParseTemplateDeclarationOrSpecialization(unsigned Context,
2518 SourceLocation &DeclEnd,
2520 AttributeList *AccessAttrs);
2521 Decl *ParseSingleDeclarationAfterTemplate(
2523 const ParsedTemplateInfo &TemplateInfo,
2524 ParsingDeclRAIIObject &DiagsFromParams,
2525 SourceLocation &DeclEnd,
2526 AccessSpecifier AS=AS_none,
2527 AttributeList *AccessAttrs = nullptr);
2528 bool ParseTemplateParameters(unsigned Depth,
2529 SmallVectorImpl<Decl*> &TemplateParams,
2530 SourceLocation &LAngleLoc,
2531 SourceLocation &RAngleLoc);
2532 bool ParseTemplateParameterList(unsigned Depth,
2533 SmallVectorImpl<Decl*> &TemplateParams);
2534 bool isStartOfTemplateTypeParameter();
2535 Decl *ParseTemplateParameter(unsigned Depth, unsigned Position);
2536 Decl *ParseTypeParameter(unsigned Depth, unsigned Position);
2537 Decl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
2538 Decl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
2539 void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
2540 SourceLocation CorrectLoc,
2541 bool AlreadyHasEllipsis,
2542 bool IdentifierHasName);
2543 void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
2545 // C++ 14.3: Template arguments [temp.arg]
2546 typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
2548 bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
2549 bool ConsumeLastToken,
2550 bool ObjCGenericList);
2551 bool ParseTemplateIdAfterTemplateName(TemplateTy Template,
2552 SourceLocation TemplateNameLoc,
2553 const CXXScopeSpec &SS,
2554 bool ConsumeLastToken,
2555 SourceLocation &LAngleLoc,
2556 TemplateArgList &TemplateArgs,
2557 SourceLocation &RAngleLoc);
2559 bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
2561 SourceLocation TemplateKWLoc,
2562 UnqualifiedId &TemplateName,
2563 bool AllowTypeAnnotation = true);
2564 void AnnotateTemplateIdTokenAsType();
2565 bool IsTemplateArgumentList(unsigned Skip = 0);
2566 bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
2567 ParsedTemplateArgument ParseTemplateTemplateArgument();
2568 ParsedTemplateArgument ParseTemplateArgument();
2569 Decl *ParseExplicitInstantiation(unsigned Context,
2570 SourceLocation ExternLoc,
2571 SourceLocation TemplateLoc,
2572 SourceLocation &DeclEnd,
2573 AccessSpecifier AS = AS_none);
2575 //===--------------------------------------------------------------------===//
2577 DeclGroupPtrTy ParseModuleImport(SourceLocation AtLoc);
2578 bool parseMisplacedModuleImport();
2579 bool tryParseMisplacedModuleImport() {
2580 tok::TokenKind Kind = Tok.getKind();
2581 if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end ||
2582 Kind == tok::annot_module_include)
2583 return parseMisplacedModuleImport();
2587 //===--------------------------------------------------------------------===//
2588 // C++11/G++: Type Traits [Type-Traits.html in the GCC manual]
2589 ExprResult ParseTypeTrait();
2591 //===--------------------------------------------------------------------===//
2592 // Embarcadero: Arary and Expression Traits
2593 ExprResult ParseArrayTypeTrait();
2594 ExprResult ParseExpressionTrait();
2596 //===--------------------------------------------------------------------===//
2597 // Preprocessor code-completion pass-through
2598 void CodeCompleteDirective(bool InConditional) override;
2599 void CodeCompleteInConditionalExclusion() override;
2600 void CodeCompleteMacroName(bool IsDefinition) override;
2601 void CodeCompletePreprocessorExpression() override;
2602 void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo,
2603 unsigned ArgumentIndex) override;
2604 void CodeCompleteNaturalLanguage() override;
2607 } // end namespace clang