1 //===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the Parser interface.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_PARSE_PARSER_H
15 #define LLVM_CLANG_PARSE_PARSER_H
17 #include "clang/AST/Availability.h"
18 #include "clang/Basic/OpenMPKinds.h"
19 #include "clang/Basic/OperatorPrecedence.h"
20 #include "clang/Basic/Specifiers.h"
21 #include "clang/Lex/CodeCompletionHandler.h"
22 #include "clang/Lex/Preprocessor.h"
23 #include "clang/Sema/DeclSpec.h"
24 #include "clang/Sema/LoopHint.h"
25 #include "clang/Sema/Sema.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/Support/PrettyStackTrace.h"
29 #include "llvm/Support/SaveAndRestore.h"
36 class BalancedDelimiterTracker;
37 class CorrectionCandidateCallback;
39 class DiagnosticBuilder;
41 class ParsingDeclRAIIObject;
42 class ParsingDeclSpec;
43 class ParsingDeclarator;
44 class ParsingFieldDeclarator;
45 class ColonProtectionRAIIObject;
46 class InMessageExpressionRAIIObject;
47 class PoisonSEHIdentifiersRAIIObject;
50 class ObjCTypeParamList;
51 class ObjCTypeParameter;
53 /// Parser - This implements a parser for the C family of languages. After
54 /// parsing units of the grammar, productions are invoked to handle whatever has
57 class Parser : public CodeCompletionHandler {
58 friend class ColonProtectionRAIIObject;
59 friend class InMessageExpressionRAIIObject;
60 friend class PoisonSEHIdentifiersRAIIObject;
61 friend class ObjCDeclContextSwitch;
62 friend class ParenBraceBracketBalancer;
63 friend class BalancedDelimiterTracker;
67 /// Tok - The current token we are peeking ahead. All parsing methods assume
68 /// that this is valid.
71 // PrevTokLocation - The location of the token we previously
72 // consumed. This token is used for diagnostics where we expected to
73 // see a token following another token (e.g., the ';' at the end of
75 SourceLocation PrevTokLocation;
77 unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0;
78 unsigned short MisplacedModuleBeginCount = 0;
80 /// Actions - These are the callbacks we invoke as we parse various constructs
84 DiagnosticsEngine &Diags;
86 /// ScopeCache - Cache scopes to reduce malloc traffic.
87 enum { ScopeCacheSize = 16 };
88 unsigned NumCachedScopes;
89 Scope *ScopeCache[ScopeCacheSize];
91 /// Identifiers used for SEH handling in Borland. These are only
92 /// allowed in particular circumstances
94 IdentifierInfo *Ident__exception_code,
95 *Ident___exception_code,
96 *Ident_GetExceptionCode;
97 // __except filter expression
98 IdentifierInfo *Ident__exception_info,
99 *Ident___exception_info,
100 *Ident_GetExceptionInfo;
102 IdentifierInfo *Ident__abnormal_termination,
103 *Ident___abnormal_termination,
104 *Ident_AbnormalTermination;
106 /// Contextual keywords for Microsoft extensions.
107 IdentifierInfo *Ident__except;
108 mutable IdentifierInfo *Ident_sealed;
110 /// Ident_super - IdentifierInfo for "super", to support fast
112 IdentifierInfo *Ident_super;
113 /// Ident_vector, Ident_bool - cached IdentifierInfos for "vector" and
114 /// "bool" fast comparison. Only present if AltiVec or ZVector are enabled.
115 IdentifierInfo *Ident_vector;
116 IdentifierInfo *Ident_bool;
117 /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison.
118 /// Only present if AltiVec enabled.
119 IdentifierInfo *Ident_pixel;
121 /// Objective-C contextual keywords.
122 mutable IdentifierInfo *Ident_instancetype;
124 /// \brief Identifier for "introduced".
125 IdentifierInfo *Ident_introduced;
127 /// \brief Identifier for "deprecated".
128 IdentifierInfo *Ident_deprecated;
130 /// \brief Identifier for "obsoleted".
131 IdentifierInfo *Ident_obsoleted;
133 /// \brief Identifier for "unavailable".
134 IdentifierInfo *Ident_unavailable;
136 /// \brief Identifier for "message".
137 IdentifierInfo *Ident_message;
139 /// \brief Identifier for "strict".
140 IdentifierInfo *Ident_strict;
142 /// \brief Identifier for "replacement".
143 IdentifierInfo *Ident_replacement;
145 /// C++0x contextual keywords.
146 mutable IdentifierInfo *Ident_final;
147 mutable IdentifierInfo *Ident_GNU_final;
148 mutable IdentifierInfo *Ident_override;
150 // C++ type trait keywords that can be reverted to identifiers and still be
151 // used as type traits.
152 llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits;
154 std::unique_ptr<PragmaHandler> AlignHandler;
155 std::unique_ptr<PragmaHandler> GCCVisibilityHandler;
156 std::unique_ptr<PragmaHandler> OptionsHandler;
157 std::unique_ptr<PragmaHandler> PackHandler;
158 std::unique_ptr<PragmaHandler> MSStructHandler;
159 std::unique_ptr<PragmaHandler> UnusedHandler;
160 std::unique_ptr<PragmaHandler> WeakHandler;
161 std::unique_ptr<PragmaHandler> RedefineExtnameHandler;
162 std::unique_ptr<PragmaHandler> FPContractHandler;
163 std::unique_ptr<PragmaHandler> OpenCLExtensionHandler;
164 std::unique_ptr<PragmaHandler> OpenMPHandler;
165 std::unique_ptr<PragmaHandler> MSCommentHandler;
166 std::unique_ptr<PragmaHandler> MSDetectMismatchHandler;
167 std::unique_ptr<PragmaHandler> MSPointersToMembers;
168 std::unique_ptr<PragmaHandler> MSVtorDisp;
169 std::unique_ptr<PragmaHandler> MSInitSeg;
170 std::unique_ptr<PragmaHandler> MSDataSeg;
171 std::unique_ptr<PragmaHandler> MSBSSSeg;
172 std::unique_ptr<PragmaHandler> MSConstSeg;
173 std::unique_ptr<PragmaHandler> MSCodeSeg;
174 std::unique_ptr<PragmaHandler> MSSection;
175 std::unique_ptr<PragmaHandler> MSRuntimeChecks;
176 std::unique_ptr<PragmaHandler> MSIntrinsic;
177 std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler;
178 std::unique_ptr<PragmaHandler> OptimizeHandler;
179 std::unique_ptr<PragmaHandler> LoopHintHandler;
180 std::unique_ptr<PragmaHandler> UnrollHintHandler;
181 std::unique_ptr<PragmaHandler> NoUnrollHintHandler;
183 std::unique_ptr<CommentHandler> CommentSemaHandler;
185 /// Whether the '>' token acts as an operator or not. This will be
186 /// true except when we are parsing an expression within a C++
187 /// template argument list, where the '>' closes the template
189 bool GreaterThanIsOperator;
191 /// ColonIsSacred - When this is false, we aggressively try to recover from
192 /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not
193 /// safe in case statements and a few other things. This is managed by the
194 /// ColonProtectionRAIIObject RAII object.
197 /// \brief When true, we are directly inside an Objective-C message
200 /// This is managed by the \c InMessageExpressionRAIIObject class, and
201 /// should not be set directly.
202 bool InMessageExpression;
204 /// The "depth" of the template parameters currently being parsed.
205 unsigned TemplateParameterDepth;
207 /// \brief RAII class that manages the template parameter depth.
208 class TemplateParameterDepthRAII {
210 unsigned AddedLevels;
212 explicit TemplateParameterDepthRAII(unsigned &Depth)
213 : Depth(Depth), AddedLevels(0) {}
215 ~TemplateParameterDepthRAII() {
216 Depth -= AddedLevels;
223 void addDepth(unsigned D) {
227 unsigned getDepth() const { return Depth; }
230 /// Factory object for creating AttributeList objects.
231 AttributeFactory AttrFactory;
233 /// \brief Gathers and cleans up TemplateIdAnnotations when parsing of a
234 /// top-level declaration is finished.
235 SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
237 /// \brief Identifiers which have been declared within a tentative parse.
238 SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers;
240 IdentifierInfo *getSEHExceptKeyword();
242 /// True if we are within an Objective-C container while parsing C-like decls.
244 /// This is necessary because Sema thinks we have left the container
245 /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will
247 bool ParsingInObjCContainer;
249 bool SkipFunctionBodies;
251 /// The location of the expression statement that is being parsed right now.
252 /// Used to determine if an expression that is being parsed is a statement or
253 /// just a regular sub-expression.
254 SourceLocation ExprStatementTokLoc;
257 Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
260 const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
261 const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
262 Preprocessor &getPreprocessor() const { return PP; }
263 Sema &getActions() const { return Actions; }
264 AttributeFactory &getAttrFactory() { return AttrFactory; }
266 const Token &getCurToken() const { return Tok; }
267 Scope *getCurScope() const { return Actions.getCurScope(); }
268 void incrementMSManglingNumber() const {
269 return Actions.incrementMSManglingNumber();
272 Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); }
274 // Type forwarding. All of these are statically 'void*', but they may all be
275 // different actual classes based on the actions in place.
276 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
277 typedef OpaquePtr<TemplateName> TemplateTy;
279 typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists;
281 typedef Sema::FullExprArg FullExprArg;
285 /// Initialize - Warm up the parser.
289 /// Parse the first top-level declaration in a translation unit.
290 bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result);
292 /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if
293 /// the EOF was encountered.
294 bool ParseTopLevelDecl(DeclGroupPtrTy &Result);
295 bool ParseTopLevelDecl() {
296 DeclGroupPtrTy Result;
297 return ParseTopLevelDecl(Result);
300 /// ConsumeToken - Consume the current 'peek token' and lex the next one.
301 /// This does not work with special tokens: string literals, code completion
302 /// and balanced tokens must be handled using the specific consume methods.
303 /// Returns the location of the consumed token.
304 SourceLocation ConsumeToken() {
305 assert(!isTokenSpecial() &&
306 "Should consume special tokens with Consume*Token");
307 PrevTokLocation = Tok.getLocation();
309 return PrevTokLocation;
312 bool TryConsumeToken(tok::TokenKind Expected) {
313 if (Tok.isNot(Expected))
315 assert(!isTokenSpecial() &&
316 "Should consume special tokens with Consume*Token");
317 PrevTokLocation = Tok.getLocation();
322 bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) {
323 if (!TryConsumeToken(Expected))
325 Loc = PrevTokLocation;
329 SourceLocation getEndOfPreviousToken() {
330 return PP.getLocForEndOfToken(PrevTokLocation);
333 /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds
334 /// to the given nullability kind.
335 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) {
336 return Actions.getNullabilityKeyword(nullability);
340 //===--------------------------------------------------------------------===//
341 // Low-Level token peeking and consumption methods.
344 /// isTokenParen - Return true if the cur token is '(' or ')'.
345 bool isTokenParen() const {
346 return Tok.getKind() == tok::l_paren || Tok.getKind() == tok::r_paren;
348 /// isTokenBracket - Return true if the cur token is '[' or ']'.
349 bool isTokenBracket() const {
350 return Tok.getKind() == tok::l_square || Tok.getKind() == tok::r_square;
352 /// isTokenBrace - Return true if the cur token is '{' or '}'.
353 bool isTokenBrace() const {
354 return Tok.getKind() == tok::l_brace || Tok.getKind() == tok::r_brace;
356 /// isTokenStringLiteral - True if this token is a string-literal.
357 bool isTokenStringLiteral() const {
358 return tok::isStringLiteral(Tok.getKind());
360 /// isTokenSpecial - True if this token requires special consumption methods.
361 bool isTokenSpecial() const {
362 return isTokenStringLiteral() || isTokenParen() || isTokenBracket() ||
363 isTokenBrace() || Tok.is(tok::code_completion);
366 /// \brief Returns true if the current token is '=' or is a type of '='.
367 /// For typos, give a fixit to '='
368 bool isTokenEqualOrEqualTypo();
370 /// \brief Return the current token to the token stream and make the given
371 /// token the current token.
372 void UnconsumeToken(Token &Consumed) {
374 PP.EnterToken(Consumed);
379 /// ConsumeAnyToken - Dispatch to the right Consume* method based on the
380 /// current token type. This should only be used in cases where the type of
381 /// the token really isn't known, e.g. in error recovery.
382 SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) {
384 return ConsumeParen();
385 if (isTokenBracket())
386 return ConsumeBracket();
388 return ConsumeBrace();
389 if (isTokenStringLiteral())
390 return ConsumeStringToken();
391 if (Tok.is(tok::code_completion))
392 return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken()
393 : handleUnexpectedCodeCompletionToken();
394 return ConsumeToken();
397 /// ConsumeParen - This consume method keeps the paren count up-to-date.
399 SourceLocation ConsumeParen() {
400 assert(isTokenParen() && "wrong consume method");
401 if (Tok.getKind() == tok::l_paren)
404 --ParenCount; // Don't let unbalanced )'s drive the count negative.
405 PrevTokLocation = Tok.getLocation();
407 return PrevTokLocation;
410 /// ConsumeBracket - This consume method keeps the bracket count up-to-date.
412 SourceLocation ConsumeBracket() {
413 assert(isTokenBracket() && "wrong consume method");
414 if (Tok.getKind() == tok::l_square)
416 else if (BracketCount)
417 --BracketCount; // Don't let unbalanced ]'s drive the count negative.
419 PrevTokLocation = Tok.getLocation();
421 return PrevTokLocation;
424 /// ConsumeBrace - This consume method keeps the brace count up-to-date.
426 SourceLocation ConsumeBrace() {
427 assert(isTokenBrace() && "wrong consume method");
428 if (Tok.getKind() == tok::l_brace)
431 --BraceCount; // Don't let unbalanced }'s drive the count negative.
433 PrevTokLocation = Tok.getLocation();
435 return PrevTokLocation;
438 /// ConsumeStringToken - Consume the current 'peek token', lexing a new one
439 /// and returning the token kind. This method is specific to strings, as it
440 /// handles string literal concatenation, as per C99 5.1.1.2, translation
442 SourceLocation ConsumeStringToken() {
443 assert(isTokenStringLiteral() &&
444 "Should only consume string literals with this method");
445 PrevTokLocation = Tok.getLocation();
447 return PrevTokLocation;
450 /// \brief Consume the current code-completion token.
452 /// This routine can be called to consume the code-completion token and
453 /// continue processing in special cases where \c cutOffParsing() isn't
454 /// desired, such as token caching or completion with lookahead.
455 SourceLocation ConsumeCodeCompletionToken() {
456 assert(Tok.is(tok::code_completion));
457 PrevTokLocation = Tok.getLocation();
459 return PrevTokLocation;
462 ///\ brief When we are consuming a code-completion token without having
463 /// matched specific position in the grammar, provide code-completion results
464 /// based on context.
466 /// \returns the source location of the code-completion token.
467 SourceLocation handleUnexpectedCodeCompletionToken();
469 /// \brief Abruptly cut off parsing; mainly used when we have reached the
470 /// code-completion point.
471 void cutOffParsing() {
472 if (PP.isCodeCompletionEnabled())
473 PP.setCodeCompletionReached();
474 // Cut off parsing by acting as if we reached the end-of-file.
475 Tok.setKind(tok::eof);
478 /// \brief Determine if we're at the end of the file or at a transition
481 tok::TokenKind Kind = Tok.getKind();
482 return Kind == tok::eof || Kind == tok::annot_module_begin ||
483 Kind == tok::annot_module_end || Kind == tok::annot_module_include;
486 /// \brief Initialize all pragma handlers.
487 void initializePragmaHandlers();
489 /// \brief Destroy and reset all pragma handlers.
490 void resetPragmaHandlers();
492 /// \brief Handle the annotation token produced for #pragma unused(...)
493 void HandlePragmaUnused();
495 /// \brief Handle the annotation token produced for
496 /// #pragma GCC visibility...
497 void HandlePragmaVisibility();
499 /// \brief Handle the annotation token produced for
501 void HandlePragmaPack();
503 /// \brief Handle the annotation token produced for
504 /// #pragma ms_struct...
505 void HandlePragmaMSStruct();
507 /// \brief Handle the annotation token produced for
508 /// #pragma comment...
509 void HandlePragmaMSComment();
511 void HandlePragmaMSPointersToMembers();
513 void HandlePragmaMSVtorDisp();
515 void HandlePragmaMSPragma();
516 bool HandlePragmaMSSection(StringRef PragmaName,
517 SourceLocation PragmaLocation);
518 bool HandlePragmaMSSegment(StringRef PragmaName,
519 SourceLocation PragmaLocation);
520 bool HandlePragmaMSInitSeg(StringRef PragmaName,
521 SourceLocation PragmaLocation);
523 /// \brief Handle the annotation token produced for
525 void HandlePragmaAlign();
527 /// \brief Handle the annotation token produced for
528 /// #pragma clang __debug dump...
529 void HandlePragmaDump();
531 /// \brief Handle the annotation token produced for
532 /// #pragma weak id...
533 void HandlePragmaWeak();
535 /// \brief Handle the annotation token produced for
536 /// #pragma weak id = id...
537 void HandlePragmaWeakAlias();
539 /// \brief Handle the annotation token produced for
540 /// #pragma redefine_extname...
541 void HandlePragmaRedefineExtname();
543 /// \brief Handle the annotation token produced for
544 /// #pragma STDC FP_CONTRACT...
545 void HandlePragmaFPContract();
547 /// \brief Handle the annotation token produced for
548 /// #pragma OPENCL EXTENSION...
549 void HandlePragmaOpenCLExtension();
551 /// \brief Handle the annotation token produced for
552 /// #pragma clang __debug captured
553 StmtResult HandlePragmaCaptured();
555 /// \brief Handle the annotation token produced for
556 /// #pragma clang loop and #pragma unroll.
557 bool HandlePragmaLoopHint(LoopHint &Hint);
559 /// GetLookAheadToken - This peeks ahead N tokens and returns that token
560 /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1)
561 /// returns the token after Tok, etc.
563 /// Note that this differs from the Preprocessor's LookAhead method, because
564 /// the Parser always has one token lexed that the preprocessor doesn't.
566 const Token &GetLookAheadToken(unsigned N) {
567 if (N == 0 || Tok.is(tok::eof)) return Tok;
568 return PP.LookAhead(N-1);
572 /// NextToken - This peeks ahead one token and returns it without
574 const Token &NextToken() {
575 return PP.LookAhead(0);
578 /// getTypeAnnotation - Read a parsed type out of an annotation token.
579 static ParsedType getTypeAnnotation(Token &Tok) {
580 return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
584 static void setTypeAnnotation(Token &Tok, ParsedType T) {
585 Tok.setAnnotationValue(T.getAsOpaquePtr());
588 /// \brief Read an already-translated primary expression out of an annotation
590 static ExprResult getExprAnnotation(Token &Tok) {
591 return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue());
594 /// \brief Set the primary expression corresponding to the given annotation
596 static void setExprAnnotation(Token &Tok, ExprResult ER) {
597 Tok.setAnnotationValue(ER.getAsOpaquePointer());
601 // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to
602 // find a type name by attempting typo correction.
603 bool TryAnnotateTypeOrScopeToken(bool EnteringContext = false,
604 bool NeedType = false);
605 bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext,
609 bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
612 enum AnnotatedNameKind {
613 /// Annotation has failed and emitted an error.
615 /// The identifier is a tentatively-declared name.
617 /// The identifier is a template name. FIXME: Add an annotation for that.
619 /// The identifier can't be resolved.
621 /// Annotation was successful.
625 TryAnnotateName(bool IsAddressOfOperand,
626 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
628 /// Push a tok::annot_cxxscope token onto the token stream.
629 void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
631 /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
632 /// replacing them with the non-context-sensitive keywords. This returns
633 /// true if the token was replaced.
634 bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
635 const char *&PrevSpec, unsigned &DiagID,
637 if (!getLangOpts().AltiVec && !getLangOpts().ZVector)
640 if (Tok.getIdentifierInfo() != Ident_vector &&
641 Tok.getIdentifierInfo() != Ident_bool &&
642 (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel))
645 return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
648 /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
649 /// identifier token, replacing it with the non-context-sensitive __vector.
650 /// This returns true if the token was replaced.
651 bool TryAltiVecVectorToken() {
652 if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) ||
653 Tok.getIdentifierInfo() != Ident_vector) return false;
654 return TryAltiVecVectorTokenOutOfLine();
657 bool TryAltiVecVectorTokenOutOfLine();
658 bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
659 const char *&PrevSpec, unsigned &DiagID,
662 /// Returns true if the current token is the identifier 'instancetype'.
664 /// Should only be used in Objective-C language modes.
665 bool isObjCInstancetype() {
666 assert(getLangOpts().ObjC1);
667 if (Tok.isAnnotation())
669 if (!Ident_instancetype)
670 Ident_instancetype = PP.getIdentifierInfo("instancetype");
671 return Tok.getIdentifierInfo() == Ident_instancetype;
674 /// TryKeywordIdentFallback - For compatibility with system headers using
675 /// keywords as identifiers, attempt to convert the current token to an
676 /// identifier and optionally disable the keyword for the remainder of the
677 /// translation unit. This returns false if the token was not replaced,
678 /// otherwise emits a diagnostic and returns true.
679 bool TryKeywordIdentFallback(bool DisableKeyword);
681 /// \brief Get the TemplateIdAnnotation from the token.
682 TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
684 /// TentativeParsingAction - An object that is used as a kind of "tentative
685 /// parsing transaction". It gets instantiated to mark the token position and
686 /// after the token consumption is done, Commit() or Revert() is called to
687 /// either "commit the consumed tokens" or revert to the previously marked
688 /// token position. Example:
690 /// TentativeParsingAction TPA(*this);
695 class TentativeParsingAction {
698 size_t PrevTentativelyDeclaredIdentifierCount;
699 unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
703 explicit TentativeParsingAction(Parser& p) : P(p) {
705 PrevTentativelyDeclaredIdentifierCount =
706 P.TentativelyDeclaredIdentifiers.size();
707 PrevParenCount = P.ParenCount;
708 PrevBracketCount = P.BracketCount;
709 PrevBraceCount = P.BraceCount;
710 P.PP.EnableBacktrackAtThisPos();
714 assert(isActive && "Parsing action was finished!");
715 P.TentativelyDeclaredIdentifiers.resize(
716 PrevTentativelyDeclaredIdentifierCount);
717 P.PP.CommitBacktrackedTokens();
721 assert(isActive && "Parsing action was finished!");
724 P.TentativelyDeclaredIdentifiers.resize(
725 PrevTentativelyDeclaredIdentifierCount);
726 P.ParenCount = PrevParenCount;
727 P.BracketCount = PrevBracketCount;
728 P.BraceCount = PrevBraceCount;
731 ~TentativeParsingAction() {
732 assert(!isActive && "Forgot to call Commit or Revert!");
735 /// A TentativeParsingAction that automatically reverts in its destructor.
736 /// Useful for disambiguation parses that will always be reverted.
737 class RevertingTentativeParsingAction
738 : private Parser::TentativeParsingAction {
740 RevertingTentativeParsingAction(Parser &P)
741 : Parser::TentativeParsingAction(P) {}
742 ~RevertingTentativeParsingAction() { Revert(); }
745 class UnannotatedTentativeParsingAction;
747 /// ObjCDeclContextSwitch - An object used to switch context from
748 /// an objective-c decl context to its enclosing decl context and
750 class ObjCDeclContextSwitch {
753 SaveAndRestore<bool> WithinObjCContainer;
755 explicit ObjCDeclContextSwitch(Parser &p)
756 : P(p), DC(p.getObjCDeclContext()),
757 WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) {
759 P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC));
761 ~ObjCDeclContextSwitch() {
763 P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC));
767 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
768 /// input. If so, it is consumed and false is returned.
770 /// If a trivial punctuator misspelling is encountered, a FixIt error
771 /// diagnostic is issued and false is returned after recovery.
773 /// If the input is malformed, this emits the specified diagnostic and true is
775 bool ExpectAndConsume(tok::TokenKind ExpectedTok,
776 unsigned Diag = diag::err_expected,
777 StringRef DiagMsg = "");
779 /// \brief The parser expects a semicolon and, if present, will consume it.
781 /// If the next token is not a semicolon, this emits the specified diagnostic,
782 /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
783 /// to the semicolon, consumes that extra token.
784 bool ExpectAndConsumeSemi(unsigned DiagID);
786 /// \brief The kind of extra semi diagnostic to emit.
790 InstanceVariableList = 2,
791 AfterMemberFunctionDefinition = 3
794 /// \brief Consume any extra semi-colons until the end of the line.
795 void ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST = TST_unspecified);
798 //===--------------------------------------------------------------------===//
799 // Scope manipulation
801 /// ParseScope - Introduces a new scope for parsing. The kind of
802 /// scope is determined by ScopeFlags. Objects of this type should
803 /// be created on the stack to coincide with the position where the
804 /// parser enters the new scope, and this object's constructor will
805 /// create that new scope. Similarly, once the object is destroyed
806 /// the parser will exit the scope.
809 ParseScope(const ParseScope &) = delete;
810 void operator=(const ParseScope &) = delete;
813 // ParseScope - Construct a new object to manage a scope in the
814 // parser Self where the new Scope is created with the flags
815 // ScopeFlags, but only when we aren't about to enter a compound statement.
816 ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true,
817 bool BeforeCompoundStmt = false)
819 if (EnteredScope && !BeforeCompoundStmt)
820 Self->EnterScope(ScopeFlags);
822 if (BeforeCompoundStmt)
823 Self->incrementMSManglingNumber();
825 this->Self = nullptr;
829 // Exit - Exit the scope associated with this object now, rather
830 // than waiting until the object is destroyed.
843 /// EnterScope - Start a new scope.
844 void EnterScope(unsigned ScopeFlags);
846 /// ExitScope - Pop a scope off the scope stack.
850 /// \brief RAII object used to modify the scope flags for the current scope.
851 class ParseScopeFlags {
854 ParseScopeFlags(const ParseScopeFlags &) = delete;
855 void operator=(const ParseScopeFlags &) = delete;
858 ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
862 //===--------------------------------------------------------------------===//
863 // Diagnostic Emission and Error recovery.
866 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
867 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
868 DiagnosticBuilder Diag(unsigned DiagID) {
869 return Diag(Tok, DiagID);
873 void SuggestParentheses(SourceLocation Loc, unsigned DK,
874 SourceRange ParenRange);
875 void CheckNestedObjCContexts(SourceLocation AtLoc);
879 /// \brief Control flags for SkipUntil functions.
880 enum SkipUntilFlags {
881 StopAtSemi = 1 << 0, ///< Stop skipping at semicolon
882 /// \brief Stop skipping at specified token, but don't skip the token itself
883 StopBeforeMatch = 1 << 1,
884 StopAtCodeCompletion = 1 << 2 ///< Stop at code completion
887 friend constexpr SkipUntilFlags operator|(SkipUntilFlags L,
889 return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) |
890 static_cast<unsigned>(R));
893 /// SkipUntil - Read tokens until we get to the specified token, then consume
894 /// it (unless StopBeforeMatch is specified). Because we cannot guarantee
895 /// that the token will ever occur, this skips to the next token, or to some
896 /// likely good stopping point. If Flags has StopAtSemi flag, skipping will
897 /// stop at a ';' character.
899 /// If SkipUntil finds the specified token, it returns true, otherwise it
901 bool SkipUntil(tok::TokenKind T,
902 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
903 return SkipUntil(llvm::makeArrayRef(T), Flags);
905 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2,
906 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
907 tok::TokenKind TokArray[] = {T1, T2};
908 return SkipUntil(TokArray, Flags);
910 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3,
911 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
912 tok::TokenKind TokArray[] = {T1, T2, T3};
913 return SkipUntil(TokArray, Flags);
915 bool SkipUntil(ArrayRef<tok::TokenKind> Toks,
916 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0));
918 /// SkipMalformedDecl - Read tokens until we get to some likely good stopping
919 /// point for skipping past a simple-declaration.
920 void SkipMalformedDecl();
923 //===--------------------------------------------------------------------===//
924 // Lexing and parsing of C++ inline methods.
928 /// [class.mem]p1: "... the class is regarded as complete within
929 /// - function bodies
930 /// - default arguments
931 /// - exception-specifications (TODO: C++0x)
932 /// - and brace-or-equal-initializers for non-static data members
933 /// (including such things in nested classes)."
934 /// LateParsedDeclarations build the tree of those elements so they can
935 /// be parsed after parsing the top-level class.
936 class LateParsedDeclaration {
938 virtual ~LateParsedDeclaration();
940 virtual void ParseLexedMethodDeclarations();
941 virtual void ParseLexedMemberInitializers();
942 virtual void ParseLexedMethodDefs();
943 virtual void ParseLexedAttributes();
946 /// Inner node of the LateParsedDeclaration tree that parses
947 /// all its members recursively.
948 class LateParsedClass : public LateParsedDeclaration {
950 LateParsedClass(Parser *P, ParsingClass *C);
951 ~LateParsedClass() override;
953 void ParseLexedMethodDeclarations() override;
954 void ParseLexedMemberInitializers() override;
955 void ParseLexedMethodDefs() override;
956 void ParseLexedAttributes() override;
963 /// Contains the lexed tokens of an attribute with arguments that
964 /// may reference member variables and so need to be parsed at the
965 /// end of the class declaration after parsing all other member
966 /// member declarations.
967 /// FIXME: Perhaps we should change the name of LateParsedDeclaration to
968 /// LateParsedTokens.
969 struct LateParsedAttribute : public LateParsedDeclaration {
972 IdentifierInfo &AttrName;
973 SourceLocation AttrNameLoc;
974 SmallVector<Decl*, 2> Decls;
976 explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
978 : Self(P), AttrName(Name), AttrNameLoc(Loc) {}
980 void ParseLexedAttributes() override;
982 void addDecl(Decl *D) { Decls.push_back(D); }
985 // A list of late-parsed attributes. Used by ParseGNUAttributes.
986 class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> {
988 LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { }
990 bool parseSoon() { return ParseSoon; }
993 bool ParseSoon; // Are we planning to parse these shortly after creation?
996 /// Contains the lexed tokens of a member function definition
997 /// which needs to be parsed at the end of the class declaration
998 /// after parsing all other member declarations.
999 struct LexedMethod : public LateParsedDeclaration {
1004 /// \brief Whether this member function had an associated template
1005 /// scope. When true, D is a template declaration.
1006 /// otherwise, it is a member function declaration.
1009 explicit LexedMethod(Parser* P, Decl *MD)
1010 : Self(P), D(MD), TemplateScope(false) {}
1012 void ParseLexedMethodDefs() override;
1015 /// LateParsedDefaultArgument - Keeps track of a parameter that may
1016 /// have a default argument that cannot be parsed yet because it
1017 /// occurs within a member function declaration inside the class
1018 /// (C++ [class.mem]p2).
1019 struct LateParsedDefaultArgument {
1020 explicit LateParsedDefaultArgument(Decl *P,
1021 std::unique_ptr<CachedTokens> Toks = nullptr)
1022 : Param(P), Toks(std::move(Toks)) { }
1024 /// Param - The parameter declaration for this parameter.
1027 /// Toks - The sequence of tokens that comprises the default
1028 /// argument expression, not including the '=' or the terminating
1029 /// ')' or ','. This will be NULL for parameters that have no
1030 /// default argument.
1031 std::unique_ptr<CachedTokens> Toks;
1034 /// LateParsedMethodDeclaration - A method declaration inside a class that
1035 /// contains at least one entity whose parsing needs to be delayed
1036 /// until the class itself is completely-defined, such as a default
1037 /// argument (C++ [class.mem]p2).
1038 struct LateParsedMethodDeclaration : public LateParsedDeclaration {
1039 explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
1040 : Self(P), Method(M), TemplateScope(false),
1041 ExceptionSpecTokens(nullptr) {}
1043 void ParseLexedMethodDeclarations() override;
1047 /// Method - The method declaration.
1050 /// \brief Whether this member function had an associated template
1051 /// scope. When true, D is a template declaration.
1052 /// othewise, it is a member function declaration.
1055 /// DefaultArgs - Contains the parameters of the function and
1056 /// their default arguments. At least one of the parameters will
1057 /// have a default argument, but all of the parameters of the
1058 /// method will be stored so that they can be reintroduced into
1059 /// scope at the appropriate times.
1060 SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
1062 /// \brief The set of tokens that make up an exception-specification that
1063 /// has not yet been parsed.
1064 CachedTokens *ExceptionSpecTokens;
1067 /// LateParsedMemberInitializer - An initializer for a non-static class data
1068 /// member whose parsing must to be delayed until the class is completely
1069 /// defined (C++11 [class.mem]p2).
1070 struct LateParsedMemberInitializer : public LateParsedDeclaration {
1071 LateParsedMemberInitializer(Parser *P, Decl *FD)
1072 : Self(P), Field(FD) { }
1074 void ParseLexedMemberInitializers() override;
1078 /// Field - The field declaration.
1081 /// CachedTokens - The sequence of tokens that comprises the initializer,
1082 /// including any leading '='.
1086 /// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
1087 /// C++ class, its method declarations that contain parts that won't be
1088 /// parsed until after the definition is completed (C++ [class.mem]p2),
1089 /// the method declarations and possibly attached inline definitions
1090 /// will be stored here with the tokens that will be parsed to create those
1092 typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer;
1094 /// \brief Representation of a class that has been parsed, including
1095 /// any member function declarations or definitions that need to be
1096 /// parsed after the corresponding top-level class is complete.
1097 struct ParsingClass {
1098 ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface)
1099 : TopLevelClass(TopLevelClass), TemplateScope(false),
1100 IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) { }
1102 /// \brief Whether this is a "top-level" class, meaning that it is
1103 /// not nested within another class.
1104 bool TopLevelClass : 1;
1106 /// \brief Whether this class had an associated template
1107 /// scope. When true, TagOrTemplate is a template declaration;
1108 /// othewise, it is a tag declaration.
1109 bool TemplateScope : 1;
1111 /// \brief Whether this class is an __interface.
1112 bool IsInterface : 1;
1114 /// \brief The class or class template whose definition we are parsing.
1115 Decl *TagOrTemplate;
1117 /// LateParsedDeclarations - Method declarations, inline definitions and
1118 /// nested classes that contain pieces whose parsing will be delayed until
1119 /// the top-level class is fully defined.
1120 LateParsedDeclarationsContainer LateParsedDeclarations;
1123 /// \brief The stack of classes that is currently being
1124 /// parsed. Nested and local classes will be pushed onto this stack
1125 /// when they are parsed, and removed afterward.
1126 std::stack<ParsingClass *> ClassStack;
1128 ParsingClass &getCurrentClass() {
1129 assert(!ClassStack.empty() && "No lexed method stacks!");
1130 return *ClassStack.top();
1133 /// \brief RAII object used to manage the parsing of a class definition.
1134 class ParsingClassDefinition {
1137 Sema::ParsingClassState State;
1140 ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass,
1142 : P(P), Popped(false),
1143 State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
1146 /// \brief Pop this class of the stack.
1148 assert(!Popped && "Nested class has already been popped");
1150 P.PopParsingClass(State);
1153 ~ParsingClassDefinition() {
1155 P.PopParsingClass(State);
1159 /// \brief Contains information about any template-specific
1160 /// information that has been parsed prior to parsing declaration
1162 struct ParsedTemplateInfo {
1163 ParsedTemplateInfo()
1164 : Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { }
1166 ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
1167 bool isSpecialization,
1168 bool lastParameterListWasEmpty = false)
1169 : Kind(isSpecialization? ExplicitSpecialization : Template),
1170 TemplateParams(TemplateParams),
1171 LastParameterListWasEmpty(lastParameterListWasEmpty) { }
1173 explicit ParsedTemplateInfo(SourceLocation ExternLoc,
1174 SourceLocation TemplateLoc)
1175 : Kind(ExplicitInstantiation), TemplateParams(nullptr),
1176 ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
1177 LastParameterListWasEmpty(false){ }
1179 /// \brief The kind of template we are parsing.
1181 /// \brief We are not parsing a template at all.
1183 /// \brief We are parsing a template declaration.
1185 /// \brief We are parsing an explicit specialization.
1186 ExplicitSpecialization,
1187 /// \brief We are parsing an explicit instantiation.
1188 ExplicitInstantiation
1191 /// \brief The template parameter lists, for template declarations
1192 /// and explicit specializations.
1193 TemplateParameterLists *TemplateParams;
1195 /// \brief The location of the 'extern' keyword, if any, for an explicit
1197 SourceLocation ExternLoc;
1199 /// \brief The location of the 'template' keyword, for an explicit
1201 SourceLocation TemplateLoc;
1203 /// \brief Whether the last template parameter list was empty.
1204 bool LastParameterListWasEmpty;
1206 SourceRange getSourceRange() const LLVM_READONLY;
1209 void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
1210 void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
1212 static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
1213 static void LateTemplateParserCleanupCallback(void *P);
1215 Sema::ParsingClassState
1216 PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface);
1217 void DeallocateParsedClasses(ParsingClass *Class);
1218 void PopParsingClass(Sema::ParsingClassState);
1220 enum CachedInitKind {
1221 CIK_DefaultArgument,
1222 CIK_DefaultInitializer
1225 NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS,
1226 AttributeList *AccessAttrs,
1227 ParsingDeclarator &D,
1228 const ParsedTemplateInfo &TemplateInfo,
1229 const VirtSpecifiers& VS,
1230 SourceLocation PureSpecLoc);
1231 void ParseCXXNonStaticMemberInitializer(Decl *VarD);
1232 void ParseLexedAttributes(ParsingClass &Class);
1233 void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1234 bool EnterScope, bool OnDefinition);
1235 void ParseLexedAttribute(LateParsedAttribute &LA,
1236 bool EnterScope, bool OnDefinition);
1237 void ParseLexedMethodDeclarations(ParsingClass &Class);
1238 void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
1239 void ParseLexedMethodDefs(ParsingClass &Class);
1240 void ParseLexedMethodDef(LexedMethod &LM);
1241 void ParseLexedMemberInitializers(ParsingClass &Class);
1242 void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
1243 void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod);
1244 bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
1245 bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK);
1246 bool ConsumeAndStoreConditional(CachedTokens &Toks);
1247 bool ConsumeAndStoreUntil(tok::TokenKind T1,
1249 bool StopAtSemi = true,
1250 bool ConsumeFinalToken = true) {
1251 return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
1253 bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
1255 bool StopAtSemi = true,
1256 bool ConsumeFinalToken = true);
1258 //===--------------------------------------------------------------------===//
1259 // C99 6.9: External Definitions.
1260 struct ParsedAttributesWithRange : ParsedAttributes {
1261 ParsedAttributesWithRange(AttributeFactory &factory)
1262 : ParsedAttributes(factory) {}
1265 ParsedAttributes::clear();
1266 Range = SourceRange();
1272 DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
1273 ParsingDeclSpec *DS = nullptr);
1274 bool isDeclarationAfterDeclarator();
1275 bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
1276 DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(
1277 ParsedAttributesWithRange &attrs,
1278 ParsingDeclSpec *DS = nullptr,
1279 AccessSpecifier AS = AS_none);
1280 DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
1281 ParsingDeclSpec &DS,
1282 AccessSpecifier AS);
1284 void SkipFunctionBody();
1285 Decl *ParseFunctionDefinition(ParsingDeclarator &D,
1286 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1287 LateParsedAttrList *LateParsedAttrs = nullptr);
1288 void ParseKNRParamDeclarations(Declarator &D);
1289 // EndLoc, if non-NULL, is filled with the location of the last token of
1291 ExprResult ParseSimpleAsm(SourceLocation *EndLoc = nullptr);
1292 ExprResult ParseAsmStringLiteral();
1294 // Objective-C External Declarations
1295 void MaybeSkipAttributes(tok::ObjCKeywordKind Kind);
1296 DeclGroupPtrTy ParseObjCAtDirectives();
1297 DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
1298 Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
1299 ParsedAttributes &prefixAttrs);
1300 class ObjCTypeParamListScope;
1301 ObjCTypeParamList *parseObjCTypeParamList();
1302 ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs(
1303 ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
1304 SmallVectorImpl<IdentifierLocPair> &protocolIdents,
1305 SourceLocation &rAngleLoc, bool mayBeProtocolList = true);
1307 void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
1308 BalancedDelimiterTracker &T,
1309 SmallVectorImpl<Decl *> &AllIvarDecls,
1310 bool RBraceMissing);
1311 void ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1312 tok::ObjCKeywordKind visibility,
1313 SourceLocation atLoc);
1314 bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P,
1315 SmallVectorImpl<SourceLocation> &PLocs,
1316 bool WarnOnDeclarations,
1317 bool ForObjCContainer,
1318 SourceLocation &LAngleLoc,
1319 SourceLocation &EndProtoLoc,
1320 bool consumeLastToken);
1322 /// Parse the first angle-bracket-delimited clause for an
1323 /// Objective-C object or object pointer type, which may be either
1324 /// type arguments or protocol qualifiers.
1325 void parseObjCTypeArgsOrProtocolQualifiers(
1326 ParsedType baseType,
1327 SourceLocation &typeArgsLAngleLoc,
1328 SmallVectorImpl<ParsedType> &typeArgs,
1329 SourceLocation &typeArgsRAngleLoc,
1330 SourceLocation &protocolLAngleLoc,
1331 SmallVectorImpl<Decl *> &protocols,
1332 SmallVectorImpl<SourceLocation> &protocolLocs,
1333 SourceLocation &protocolRAngleLoc,
1334 bool consumeLastToken,
1335 bool warnOnIncompleteProtocols);
1337 /// Parse either Objective-C type arguments or protocol qualifiers; if the
1338 /// former, also parse protocol qualifiers afterward.
1339 void parseObjCTypeArgsAndProtocolQualifiers(
1340 ParsedType baseType,
1341 SourceLocation &typeArgsLAngleLoc,
1342 SmallVectorImpl<ParsedType> &typeArgs,
1343 SourceLocation &typeArgsRAngleLoc,
1344 SourceLocation &protocolLAngleLoc,
1345 SmallVectorImpl<Decl *> &protocols,
1346 SmallVectorImpl<SourceLocation> &protocolLocs,
1347 SourceLocation &protocolRAngleLoc,
1348 bool consumeLastToken);
1350 /// Parse a protocol qualifier type such as '<NSCopying>', which is
1351 /// an anachronistic way of writing 'id<NSCopying>'.
1352 TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc);
1354 /// Parse Objective-C type arguments and protocol qualifiers, extending the
1355 /// current type with the parsed result.
1356 TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc,
1358 bool consumeLastToken,
1359 SourceLocation &endLoc);
1361 void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
1363 DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
1364 ParsedAttributes &prefixAttrs);
1366 struct ObjCImplParsingDataRAII {
1370 typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer;
1371 LateParsedObjCMethodContainer LateParsedObjCMethods;
1373 ObjCImplParsingDataRAII(Parser &parser, Decl *D)
1374 : P(parser), Dcl(D), HasCFunction(false) {
1375 P.CurParsedObjCImpl = this;
1378 ~ObjCImplParsingDataRAII();
1380 void finish(SourceRange AtEnd);
1381 bool isFinished() const { return Finished; }
1386 ObjCImplParsingDataRAII *CurParsedObjCImpl;
1387 void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl);
1389 DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc);
1390 DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
1391 Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
1392 Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
1393 Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
1395 IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
1396 // Definitions for Objective-c context sensitive keywords recognition.
1398 objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
1399 objc_nonnull, objc_nullable, objc_null_unspecified,
1402 IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
1404 bool isTokIdentifier_in() const;
1406 ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, Declarator::TheContext Ctx,
1407 ParsedAttributes *ParamAttrs);
1408 void ParseObjCMethodRequirement();
1409 Decl *ParseObjCMethodPrototype(
1410 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1411 bool MethodDefinition = true);
1412 Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
1413 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1414 bool MethodDefinition=true);
1415 void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
1417 Decl *ParseObjCMethodDefinition();
1420 //===--------------------------------------------------------------------===//
1421 // C99 6.5: Expressions.
1423 /// TypeCastState - State whether an expression is or may be a type cast.
1424 enum TypeCastState {
1430 ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast);
1431 ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast);
1432 ExprResult ParseConstraintExpression();
1433 // Expr that doesn't include commas.
1434 ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast);
1436 ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1437 unsigned &NumLineToksConsumed,
1439 bool IsUnevaluated);
1442 ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
1444 ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
1446 ExprResult ParseRHSOfBinaryExpression(ExprResult LHS,
1447 prec::Level MinPrec);
1448 ExprResult ParseCastExpression(bool isUnaryExpression,
1449 bool isAddressOfOperand,
1451 TypeCastState isTypeCast);
1452 ExprResult ParseCastExpression(bool isUnaryExpression,
1453 bool isAddressOfOperand = false,
1454 TypeCastState isTypeCast = NotTypeCast);
1456 /// Returns true if the next token cannot start an expression.
1457 bool isNotExpressionStart();
1459 /// Returns true if the next token would start a postfix-expression
1461 bool isPostfixExpressionSuffixStart() {
1462 tok::TokenKind K = Tok.getKind();
1463 return (K == tok::l_square || K == tok::l_paren ||
1464 K == tok::period || K == tok::arrow ||
1465 K == tok::plusplus || K == tok::minusminus);
1468 ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
1469 ExprResult ParseUnaryExprOrTypeTraitExpression();
1470 ExprResult ParseBuiltinPrimaryExpression();
1472 ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1475 SourceRange &CastRange);
1477 typedef SmallVector<Expr*, 20> ExprListTy;
1478 typedef SmallVector<SourceLocation, 20> CommaLocsTy;
1480 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1481 bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
1482 SmallVectorImpl<SourceLocation> &CommaLocs,
1483 std::function<void()> Completer = nullptr);
1485 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
1486 /// used for misc language extensions.
1487 bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
1488 SmallVectorImpl<SourceLocation> &CommaLocs);
1491 /// ParenParseOption - Control what ParseParenExpression will parse.
1492 enum ParenParseOption {
1493 SimpleExpr, // Only parse '(' expression ')'
1494 CompoundStmt, // Also allow '(' compound-statement ')'
1495 CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
1496 CastExpr // Also allow '(' type-name ')' <anything>
1498 ExprResult ParseParenExpression(ParenParseOption &ExprType,
1499 bool stopIfCastExpr,
1502 SourceLocation &RParenLoc);
1504 ExprResult ParseCXXAmbiguousParenExpression(
1505 ParenParseOption &ExprType, ParsedType &CastTy,
1506 BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt);
1507 ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
1508 SourceLocation LParenLoc,
1509 SourceLocation RParenLoc);
1511 ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
1513 ExprResult ParseGenericSelectionExpression();
1515 ExprResult ParseObjCBoolLiteral();
1517 ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T);
1519 //===--------------------------------------------------------------------===//
1521 ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
1522 Token &Replacement);
1523 ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
1525 bool areTokensAdjacent(const Token &A, const Token &B);
1527 void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
1528 bool EnteringContext, IdentifierInfo &II,
1531 bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
1532 ParsedType ObjectType,
1533 bool EnteringContext,
1534 bool *MayBePseudoDestructor = nullptr,
1535 bool IsTypename = false,
1536 IdentifierInfo **LastII = nullptr);
1538 //===--------------------------------------------------------------------===//
1539 // C++0x 5.1.2: Lambda expressions
1541 // [...] () -> type {...}
1542 ExprResult ParseLambdaExpression();
1543 ExprResult TryParseLambdaExpression();
1544 Optional<unsigned> ParseLambdaIntroducer(LambdaIntroducer &Intro,
1545 bool *SkippedInits = nullptr);
1546 bool TryParseLambdaIntroducer(LambdaIntroducer &Intro);
1547 ExprResult ParseLambdaExpressionAfterIntroducer(
1548 LambdaIntroducer &Intro);
1550 //===--------------------------------------------------------------------===//
1551 // C++ 5.2p1: C++ Casts
1552 ExprResult ParseCXXCasts();
1554 //===--------------------------------------------------------------------===//
1555 // C++ 5.2p1: C++ Type Identification
1556 ExprResult ParseCXXTypeid();
1558 //===--------------------------------------------------------------------===//
1559 // C++ : Microsoft __uuidof Expression
1560 ExprResult ParseCXXUuidof();
1562 //===--------------------------------------------------------------------===//
1563 // C++ 5.2.4: C++ Pseudo-Destructor Expressions
1564 ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1565 tok::TokenKind OpKind,
1567 ParsedType ObjectType);
1569 //===--------------------------------------------------------------------===//
1570 // C++ 9.3.2: C++ 'this' pointer
1571 ExprResult ParseCXXThis();
1573 //===--------------------------------------------------------------------===//
1574 // C++ 15: C++ Throw Expression
1575 ExprResult ParseThrowExpression();
1577 ExceptionSpecificationType tryParseExceptionSpecification(
1579 SourceRange &SpecificationRange,
1580 SmallVectorImpl<ParsedType> &DynamicExceptions,
1581 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
1582 ExprResult &NoexceptExpr,
1583 CachedTokens *&ExceptionSpecTokens);
1585 // EndLoc is filled with the location of the last token of the specification.
1586 ExceptionSpecificationType ParseDynamicExceptionSpecification(
1587 SourceRange &SpecificationRange,
1588 SmallVectorImpl<ParsedType> &Exceptions,
1589 SmallVectorImpl<SourceRange> &Ranges);
1591 //===--------------------------------------------------------------------===//
1592 // C++0x 8: Function declaration trailing-return-type
1593 TypeResult ParseTrailingReturnType(SourceRange &Range);
1595 //===--------------------------------------------------------------------===//
1596 // C++ 2.13.5: C++ Boolean Literals
1597 ExprResult ParseCXXBoolLiteral();
1599 //===--------------------------------------------------------------------===//
1600 // C++ 5.2.3: Explicit type conversion (functional notation)
1601 ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
1603 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1604 /// This should only be called when the current token is known to be part of
1605 /// simple-type-specifier.
1606 void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
1608 bool ParseCXXTypeSpecifierSeq(DeclSpec &DS);
1610 //===--------------------------------------------------------------------===//
1611 // C++ 5.3.4 and 5.3.5: C++ new and delete
1612 bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs,
1614 void ParseDirectNewDeclarator(Declarator &D);
1615 ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
1616 ExprResult ParseCXXDeleteExpression(bool UseGlobal,
1617 SourceLocation Start);
1619 //===--------------------------------------------------------------------===//
1620 // C++ if/switch/while condition expression.
1621 Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt,
1623 Sema::ConditionKind CK);
1625 //===--------------------------------------------------------------------===//
1628 ExprResult ParseCoyieldExpression();
1630 //===--------------------------------------------------------------------===//
1631 // C99 6.7.8: Initialization.
1633 /// ParseInitializer
1634 /// initializer: [C99 6.7.8]
1635 /// assignment-expression
1637 ExprResult ParseInitializer() {
1638 if (Tok.isNot(tok::l_brace))
1639 return ParseAssignmentExpression();
1640 return ParseBraceInitializer();
1642 bool MayBeDesignationStart();
1643 ExprResult ParseBraceInitializer();
1644 ExprResult ParseInitializerWithPotentialDesignator();
1646 //===--------------------------------------------------------------------===//
1647 // clang Expressions
1649 ExprResult ParseBlockLiteralExpression(); // ^{...}
1651 //===--------------------------------------------------------------------===//
1652 // Objective-C Expressions
1653 ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
1654 ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
1655 ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
1656 ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
1657 ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
1658 ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
1659 ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
1660 ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
1661 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
1662 ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
1663 ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
1664 bool isSimpleObjCMessageExpression();
1665 ExprResult ParseObjCMessageExpression();
1666 ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
1667 SourceLocation SuperLoc,
1668 ParsedType ReceiverType,
1669 Expr *ReceiverExpr);
1670 ExprResult ParseAssignmentExprWithObjCMessageExprStart(
1671 SourceLocation LBracloc, SourceLocation SuperLoc,
1672 ParsedType ReceiverType, Expr *ReceiverExpr);
1673 bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
1675 //===--------------------------------------------------------------------===//
1676 // C99 6.8: Statements and Blocks.
1678 /// A SmallVector of statements, with stack size 32 (as that is the only one
1680 typedef SmallVector<Stmt*, 32> StmtVector;
1681 /// A SmallVector of expressions, with stack size 12 (the maximum used.)
1682 typedef SmallVector<Expr*, 12> ExprVector;
1683 /// A SmallVector of types.
1684 typedef SmallVector<ParsedType, 12> TypeVector;
1686 StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
1687 bool AllowOpenMPStandalone = false);
1688 enum AllowedContsructsKind {
1689 /// \brief Allow any declarations, statements, OpenMP directives.
1691 /// \brief Allow only statements and non-standalone OpenMP directives.
1692 ACK_StatementsOpenMPNonStandalone,
1693 /// \brief Allow statements and all executable OpenMP directives
1694 ACK_StatementsOpenMPAnyExecutable
1697 ParseStatementOrDeclaration(StmtVector &Stmts, AllowedContsructsKind Allowed,
1698 SourceLocation *TrailingElseLoc = nullptr);
1699 StmtResult ParseStatementOrDeclarationAfterAttributes(
1701 AllowedContsructsKind Allowed,
1702 SourceLocation *TrailingElseLoc,
1703 ParsedAttributesWithRange &Attrs);
1704 StmtResult ParseExprStatement();
1705 StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs);
1706 StmtResult ParseCaseStatement(bool MissingCase = false,
1707 ExprResult Expr = ExprResult());
1708 StmtResult ParseDefaultStatement();
1709 StmtResult ParseCompoundStatement(bool isStmtExpr = false);
1710 StmtResult ParseCompoundStatement(bool isStmtExpr,
1711 unsigned ScopeFlags);
1712 void ParseCompoundStatementLeadingPragmas();
1713 StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
1714 bool ParseParenExprOrCondition(StmtResult *InitStmt,
1715 Sema::ConditionResult &CondResult,
1717 Sema::ConditionKind CK);
1718 StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
1719 StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
1720 StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
1721 StmtResult ParseDoStatement();
1722 StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
1723 StmtResult ParseGotoStatement();
1724 StmtResult ParseContinueStatement();
1725 StmtResult ParseBreakStatement();
1726 StmtResult ParseReturnStatement();
1727 StmtResult ParseAsmStatement(bool &msAsm);
1728 StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
1729 StmtResult ParsePragmaLoopHint(StmtVector &Stmts,
1730 AllowedContsructsKind Allowed,
1731 SourceLocation *TrailingElseLoc,
1732 ParsedAttributesWithRange &Attrs);
1734 /// \brief Describes the behavior that should be taken for an __if_exists
1736 enum IfExistsBehavior {
1737 /// \brief Parse the block; this code is always used.
1739 /// \brief Skip the block entirely; this code is never used.
1741 /// \brief Parse the block as a dependent block, which may be used in
1742 /// some template instantiations but not others.
1746 /// \brief Describes the condition of a Microsoft __if_exists or
1747 /// __if_not_exists block.
1748 struct IfExistsCondition {
1749 /// \brief The location of the initial keyword.
1750 SourceLocation KeywordLoc;
1751 /// \brief Whether this is an __if_exists block (rather than an
1752 /// __if_not_exists block).
1755 /// \brief Nested-name-specifier preceding the name.
1758 /// \brief The name we're looking for.
1761 /// \brief The behavior of this __if_exists or __if_not_exists block
1763 IfExistsBehavior Behavior;
1766 bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
1767 void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
1768 void ParseMicrosoftIfExistsExternalDeclaration();
1769 void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
1770 AccessSpecifier& CurAS);
1771 bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
1773 bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
1774 SmallVectorImpl<Expr *> &Constraints,
1775 SmallVectorImpl<Expr *> &Exprs);
1777 //===--------------------------------------------------------------------===//
1778 // C++ 6: Statements and Blocks
1780 StmtResult ParseCXXTryBlock();
1781 StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
1782 StmtResult ParseCXXCatchBlock(bool FnCatch = false);
1784 //===--------------------------------------------------------------------===//
1785 // MS: SEH Statements and Blocks
1787 StmtResult ParseSEHTryBlock();
1788 StmtResult ParseSEHExceptBlock(SourceLocation Loc);
1789 StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
1790 StmtResult ParseSEHLeaveStatement();
1792 //===--------------------------------------------------------------------===//
1793 // Objective-C Statements
1795 StmtResult ParseObjCAtStatement(SourceLocation atLoc);
1796 StmtResult ParseObjCTryStmt(SourceLocation atLoc);
1797 StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
1798 StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
1799 StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
1802 //===--------------------------------------------------------------------===//
1803 // C99 6.7: Declarations.
1805 /// A context for parsing declaration specifiers. TODO: flesh this
1806 /// out, there are other significant restrictions on specifiers than
1807 /// would be best implemented in the parser.
1808 enum DeclSpecContext {
1809 DSC_normal, // normal context
1810 DSC_class, // class context, enables 'friend'
1811 DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
1812 DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
1813 DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration
1814 DSC_top_level, // top-level/namespace declaration context
1815 DSC_template_type_arg, // template type argument context
1816 DSC_objc_method_result, // ObjC method result context, enables 'instancetype'
1817 DSC_condition // condition declaration context
1820 /// Is this a context in which we are parsing just a type-specifier (or
1821 /// trailing-type-specifier)?
1822 static bool isTypeSpecifier(DeclSpecContext DSC) {
1827 case DSC_objc_method_result:
1831 case DSC_template_type_arg:
1832 case DSC_type_specifier:
1834 case DSC_alias_declaration:
1837 llvm_unreachable("Missing DeclSpecContext case");
1840 /// Information on a C++0x for-range-initializer found while parsing a
1841 /// declaration which turns out to be a for-range-declaration.
1842 struct ForRangeInit {
1843 SourceLocation ColonLoc;
1844 ExprResult RangeExpr;
1846 bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
1849 DeclGroupPtrTy ParseDeclaration(unsigned Context, SourceLocation &DeclEnd,
1850 ParsedAttributesWithRange &attrs);
1851 DeclGroupPtrTy ParseSimpleDeclaration(unsigned Context,
1852 SourceLocation &DeclEnd,
1853 ParsedAttributesWithRange &attrs,
1855 ForRangeInit *FRI = nullptr);
1856 bool MightBeDeclarator(unsigned Context);
1857 DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, unsigned Context,
1858 SourceLocation *DeclEnd = nullptr,
1859 ForRangeInit *FRI = nullptr);
1860 Decl *ParseDeclarationAfterDeclarator(Declarator &D,
1861 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
1862 bool ParseAsmAttributesAfterDeclarator(Declarator &D);
1863 Decl *ParseDeclarationAfterDeclaratorAndAttributes(
1865 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1866 ForRangeInit *FRI = nullptr);
1867 Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
1868 Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
1870 /// \brief When in code-completion, skip parsing of the function/method body
1871 /// unless the body contains the code-completion point.
1873 /// \returns true if the function body was skipped.
1874 bool trySkippingFunctionBody();
1876 bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
1877 const ParsedTemplateInfo &TemplateInfo,
1878 AccessSpecifier AS, DeclSpecContext DSC,
1879 ParsedAttributesWithRange &Attrs);
1880 DeclSpecContext getDeclSpecContextFromDeclaratorContext(unsigned Context);
1881 void ParseDeclarationSpecifiers(DeclSpec &DS,
1882 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1883 AccessSpecifier AS = AS_none,
1884 DeclSpecContext DSC = DSC_normal,
1885 LateParsedAttrList *LateAttrs = nullptr);
1886 bool DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
1887 DeclSpecContext DSContext,
1888 LateParsedAttrList *LateAttrs = nullptr);
1890 void ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS = AS_none,
1891 DeclSpecContext DSC = DSC_normal);
1893 void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
1894 Declarator::TheContext Context);
1896 void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
1897 const ParsedTemplateInfo &TemplateInfo,
1898 AccessSpecifier AS, DeclSpecContext DSC);
1899 void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
1900 void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType,
1903 void ParseStructDeclaration(
1904 ParsingDeclSpec &DS,
1905 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback);
1907 bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
1908 bool isTypeSpecifierQualifier();
1910 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
1911 /// is definitely a type-specifier. Return false if it isn't part of a type
1912 /// specifier or if we're not sure.
1913 bool isKnownToBeTypeSpecifier(const Token &Tok) const;
1915 /// \brief Return true if we know that we are definitely looking at a
1916 /// decl-specifier, and isn't part of an expression such as a function-style
1917 /// cast. Return false if it's no a decl-specifier, or we're not sure.
1918 bool isKnownToBeDeclarationSpecifier() {
1919 if (getLangOpts().CPlusPlus)
1920 return isCXXDeclarationSpecifier() == TPResult::True;
1921 return isDeclarationSpecifier(true);
1924 /// isDeclarationStatement - Disambiguates between a declaration or an
1925 /// expression statement, when parsing function bodies.
1926 /// Returns true for declaration, false for expression.
1927 bool isDeclarationStatement() {
1928 if (getLangOpts().CPlusPlus)
1929 return isCXXDeclarationStatement();
1930 return isDeclarationSpecifier(true);
1933 /// isForInitDeclaration - Disambiguates between a declaration or an
1934 /// expression in the context of the C 'clause-1' or the C++
1935 // 'for-init-statement' part of a 'for' statement.
1936 /// Returns true for declaration, false for expression.
1937 bool isForInitDeclaration() {
1938 if (getLangOpts().CPlusPlus)
1939 return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
1940 return isDeclarationSpecifier(true);
1943 /// \brief Determine whether this is a C++1z for-range-identifier.
1944 bool isForRangeIdentifier();
1946 /// \brief Determine whether we are currently at the start of an Objective-C
1947 /// class message that appears to be missing the open bracket '['.
1948 bool isStartOfObjCClassMessageMissingOpenBracket();
1950 /// \brief Starting with a scope specifier, identifier, or
1951 /// template-id that refers to the current class, determine whether
1952 /// this is a constructor declarator.
1953 bool isConstructorDeclarator(bool Unqualified);
1955 /// \brief Specifies the context in which type-id/expression
1956 /// disambiguation will occur.
1957 enum TentativeCXXTypeIdContext {
1960 TypeIdAsTemplateArgument
1964 /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
1965 /// whether the parens contain an expression or a type-id.
1966 /// Returns true for a type-id and false for an expression.
1967 bool isTypeIdInParens(bool &isAmbiguous) {
1968 if (getLangOpts().CPlusPlus)
1969 return isCXXTypeId(TypeIdInParens, isAmbiguous);
1970 isAmbiguous = false;
1971 return isTypeSpecifierQualifier();
1973 bool isTypeIdInParens() {
1975 return isTypeIdInParens(isAmbiguous);
1978 /// \brief Checks if the current tokens form type-id or expression.
1979 /// It is similar to isTypeIdInParens but does not suppose that type-id
1980 /// is in parenthesis.
1981 bool isTypeIdUnambiguously() {
1983 if (getLangOpts().CPlusPlus)
1984 return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous);
1985 return isTypeSpecifierQualifier();
1988 /// isCXXDeclarationStatement - C++-specialized function that disambiguates
1989 /// between a declaration or an expression statement, when parsing function
1990 /// bodies. Returns true for declaration, false for expression.
1991 bool isCXXDeclarationStatement();
1993 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
1994 /// between a simple-declaration or an expression-statement.
1995 /// If during the disambiguation process a parsing error is encountered,
1996 /// the function returns true to let the declaration parsing code handle it.
1997 /// Returns false if the statement is disambiguated as expression.
1998 bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
2000 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
2001 /// a constructor-style initializer, when parsing declaration statements.
2002 /// Returns true for function declarator and false for constructor-style
2003 /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
2004 /// might be a constructor-style initializer.
2005 /// If during the disambiguation process a parsing error is encountered,
2006 /// the function returns true to let the declaration parsing code handle it.
2007 bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr);
2009 struct ConditionDeclarationOrInitStatementState;
2010 enum class ConditionOrInitStatement {
2011 Expression, ///< Disambiguated as an expression (either kind).
2012 ConditionDecl, ///< Disambiguated as the declaration form of condition.
2013 InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement.
2014 Error ///< Can't be any of the above!
2016 /// \brief Disambiguates between the different kinds of things that can happen
2017 /// after 'if (' or 'switch ('. This could be one of two different kinds of
2018 /// declaration (depending on whether there is a ';' later) or an expression.
2019 ConditionOrInitStatement
2020 isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt);
2022 bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
2023 bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
2025 return isCXXTypeId(Context, isAmbiguous);
2028 /// TPResult - Used as the result value for functions whose purpose is to
2029 /// disambiguate C++ constructs by "tentatively parsing" them.
2030 enum class TPResult {
2031 True, False, Ambiguous, Error
2034 /// \brief Based only on the given token kind, determine whether we know that
2035 /// we're at the start of an expression or a type-specifier-seq (which may
2036 /// be an expression, in C++).
2038 /// This routine does not attempt to resolve any of the trick cases, e.g.,
2039 /// those involving lookup of identifiers.
2041 /// \returns \c TPR_true if this token starts an expression, \c TPR_false if
2042 /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot
2044 TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind);
2046 /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a
2047 /// declaration specifier, TPResult::False if it is not,
2048 /// TPResult::Ambiguous if it could be either a decl-specifier or a
2049 /// function-style cast, and TPResult::Error if a parsing error was
2050 /// encountered. If it could be a braced C++11 function-style cast, returns
2051 /// BracedCastResult.
2052 /// Doesn't consume tokens.
2054 isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False,
2055 bool *HasMissingTypename = nullptr);
2057 /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
2058 /// \c TPResult::Ambiguous, determine whether the decl-specifier would be
2059 /// a type-specifier other than a cv-qualifier.
2060 bool isCXXDeclarationSpecifierAType();
2062 /// \brief Determine whether an identifier has been tentatively declared as a
2063 /// non-type. Such tentative declarations should not be found to name a type
2064 /// during a tentative parse, but also should not be annotated as a non-type.
2065 bool isTentativelyDeclared(IdentifierInfo *II);
2067 // "Tentative parsing" functions, used for disambiguation. If a parsing error
2068 // is encountered they will return TPResult::Error.
2069 // Returning TPResult::True/False indicates that the ambiguity was
2070 // resolved and tentative parsing may stop. TPResult::Ambiguous indicates
2071 // that more tentative parsing is necessary for disambiguation.
2072 // They all consume tokens, so backtracking should be used after calling them.
2074 TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
2075 TPResult TryParseTypeofSpecifier();
2076 TPResult TryParseProtocolQualifiers();
2077 TPResult TryParsePtrOperatorSeq();
2078 TPResult TryParseOperatorId();
2079 TPResult TryParseInitDeclaratorList();
2080 TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier=true);
2082 TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr,
2083 bool VersusTemplateArg = false);
2084 TPResult TryParseFunctionDeclarator();
2085 TPResult TryParseBracketDeclarator();
2086 TPResult TryConsumeDeclarationSpecifier();
2089 TypeResult ParseTypeName(SourceRange *Range = nullptr,
2090 Declarator::TheContext Context
2091 = Declarator::TypeNameContext,
2092 AccessSpecifier AS = AS_none,
2093 Decl **OwnedType = nullptr,
2094 ParsedAttributes *Attrs = nullptr);
2097 void ParseBlockId(SourceLocation CaretLoc);
2099 // Check for the start of a C++11 attribute-specifier-seq in a context where
2100 // an attribute is not allowed.
2101 bool CheckProhibitedCXX11Attribute() {
2102 assert(Tok.is(tok::l_square));
2103 if (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))
2105 return DiagnoseProhibitedCXX11Attribute();
2107 bool DiagnoseProhibitedCXX11Attribute();
2108 void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2109 SourceLocation CorrectLocation) {
2110 if (!getLangOpts().CPlusPlus11)
2112 if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
2113 Tok.isNot(tok::kw_alignas))
2115 DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
2117 void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2118 SourceLocation CorrectLocation);
2120 void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
2121 DeclSpec &DS, Sema::TagUseKind TUK);
2123 void ProhibitAttributes(ParsedAttributesWithRange &attrs) {
2124 if (!attrs.Range.isValid()) return;
2125 DiagnoseProhibitedAttributes(attrs);
2128 void DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs);
2130 // Forbid C++11 attributes that appear on certain syntactic
2131 // locations which standard permits but we don't supported yet,
2132 // for example, attributes appertain to decl specifiers.
2133 void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
2136 /// \brief Skip C++11 attributes and return the end location of the last one.
2137 /// \returns SourceLocation() if there are no attributes.
2138 SourceLocation SkipCXX11Attributes();
2140 /// \brief Diagnose and skip C++11 attributes that appear in syntactic
2141 /// locations where attributes are not allowed.
2142 void DiagnoseAndSkipCXX11Attributes();
2144 /// \brief Parses syntax-generic attribute arguments for attributes which are
2145 /// known to the implementation, and adds them to the given ParsedAttributes
2146 /// list with the given attribute syntax. Returns the number of arguments
2147 /// parsed for the attribute.
2149 ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2150 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2151 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2152 AttributeList::Syntax Syntax);
2154 void MaybeParseGNUAttributes(Declarator &D,
2155 LateParsedAttrList *LateAttrs = nullptr) {
2156 if (Tok.is(tok::kw___attribute)) {
2157 ParsedAttributes attrs(AttrFactory);
2158 SourceLocation endLoc;
2159 ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D);
2160 D.takeAttributes(attrs, endLoc);
2163 void MaybeParseGNUAttributes(ParsedAttributes &attrs,
2164 SourceLocation *endLoc = nullptr,
2165 LateParsedAttrList *LateAttrs = nullptr) {
2166 if (Tok.is(tok::kw___attribute))
2167 ParseGNUAttributes(attrs, endLoc, LateAttrs);
2169 void ParseGNUAttributes(ParsedAttributes &attrs,
2170 SourceLocation *endLoc = nullptr,
2171 LateParsedAttrList *LateAttrs = nullptr,
2172 Declarator *D = nullptr);
2173 void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
2174 SourceLocation AttrNameLoc,
2175 ParsedAttributes &Attrs,
2176 SourceLocation *EndLoc,
2177 IdentifierInfo *ScopeName,
2178 SourceLocation ScopeLoc,
2179 AttributeList::Syntax Syntax,
2181 IdentifierLoc *ParseIdentifierLoc();
2183 void MaybeParseCXX11Attributes(Declarator &D) {
2184 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
2185 ParsedAttributesWithRange attrs(AttrFactory);
2186 SourceLocation endLoc;
2187 ParseCXX11Attributes(attrs, &endLoc);
2188 D.takeAttributes(attrs, endLoc);
2191 void MaybeParseCXX11Attributes(ParsedAttributes &attrs,
2192 SourceLocation *endLoc = nullptr) {
2193 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
2194 ParsedAttributesWithRange attrsWithRange(AttrFactory);
2195 ParseCXX11Attributes(attrsWithRange, endLoc);
2196 attrs.takeAllFrom(attrsWithRange);
2199 void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2200 SourceLocation *endLoc = nullptr,
2201 bool OuterMightBeMessageSend = false) {
2202 if (getLangOpts().CPlusPlus11 &&
2203 isCXX11AttributeSpecifier(false, OuterMightBeMessageSend))
2204 ParseCXX11Attributes(attrs, endLoc);
2207 void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
2208 SourceLocation *EndLoc = nullptr);
2209 void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2210 SourceLocation *EndLoc = nullptr);
2211 /// \brief Parses a C++-style attribute argument list. Returns true if this
2212 /// results in adding an attribute to the ParsedAttributes list.
2213 bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
2214 SourceLocation AttrNameLoc,
2215 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2216 IdentifierInfo *ScopeName,
2217 SourceLocation ScopeLoc);
2219 IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc);
2221 void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
2222 SourceLocation *endLoc = nullptr) {
2223 if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
2224 ParseMicrosoftAttributes(attrs, endLoc);
2226 void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs);
2227 void ParseMicrosoftAttributes(ParsedAttributes &attrs,
2228 SourceLocation *endLoc = nullptr);
2229 void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2230 SourceLocation *End = nullptr) {
2231 const auto &LO = getLangOpts();
2232 if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec))
2233 ParseMicrosoftDeclSpecs(Attrs, End);
2235 void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2236 SourceLocation *End = nullptr);
2237 bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
2238 SourceLocation AttrNameLoc,
2239 ParsedAttributes &Attrs);
2240 void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
2241 void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2242 SourceLocation SkipExtendedMicrosoftTypeAttributes();
2243 void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
2244 void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
2245 void ParseOpenCLKernelAttributes(ParsedAttributes &attrs);
2246 void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
2247 /// \brief Parses opencl_unroll_hint attribute if language is OpenCL v2.0
2249 /// \return false if error happens.
2250 bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
2251 if (getLangOpts().OpenCL)
2252 return ParseOpenCLUnrollHintAttribute(Attrs);
2255 /// \brief Parses opencl_unroll_hint attribute.
2256 /// \return false if error happens.
2257 bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs);
2258 void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
2260 VersionTuple ParseVersionTuple(SourceRange &Range);
2261 void ParseAvailabilityAttribute(IdentifierInfo &Availability,
2262 SourceLocation AvailabilityLoc,
2263 ParsedAttributes &attrs,
2264 SourceLocation *endLoc,
2265 IdentifierInfo *ScopeName,
2266 SourceLocation ScopeLoc,
2267 AttributeList::Syntax Syntax);
2269 Optional<AvailabilitySpec> ParseAvailabilitySpec();
2270 ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc);
2272 void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
2273 SourceLocation ObjCBridgeRelatedLoc,
2274 ParsedAttributes &attrs,
2275 SourceLocation *endLoc,
2276 IdentifierInfo *ScopeName,
2277 SourceLocation ScopeLoc,
2278 AttributeList::Syntax Syntax);
2280 void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
2281 SourceLocation AttrNameLoc,
2282 ParsedAttributes &Attrs,
2283 SourceLocation *EndLoc,
2284 IdentifierInfo *ScopeName,
2285 SourceLocation ScopeLoc,
2286 AttributeList::Syntax Syntax);
2288 void ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
2289 SourceLocation AttrNameLoc,
2290 ParsedAttributes &Attrs,
2291 SourceLocation *EndLoc,
2292 IdentifierInfo *ScopeName,
2293 SourceLocation ScopeLoc,
2294 AttributeList::Syntax Syntax);
2296 void ParseTypeofSpecifier(DeclSpec &DS);
2297 SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
2298 void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
2299 SourceLocation StartLoc,
2300 SourceLocation EndLoc);
2301 void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
2302 void ParseAtomicSpecifier(DeclSpec &DS);
2304 ExprResult ParseAlignArgument(SourceLocation Start,
2305 SourceLocation &EllipsisLoc);
2306 void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2307 SourceLocation *endLoc = nullptr);
2309 VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
2310 VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
2311 return isCXX11VirtSpecifier(Tok);
2313 void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface,
2314 SourceLocation FriendLoc);
2316 bool isCXX11FinalKeyword() const;
2318 /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
2319 /// enter a new C++ declarator scope and exit it when the function is
2321 class DeclaratorScopeObj {
2327 DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
2328 : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
2330 void EnterDeclaratorScope() {
2331 assert(!EnteredScope && "Already entered the scope!");
2332 assert(SS.isSet() && "C++ scope was not set!");
2334 CreatedScope = true;
2335 P.EnterScope(0); // Not a decl scope.
2337 if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
2338 EnteredScope = true;
2341 ~DeclaratorScopeObj() {
2343 assert(SS.isSet() && "C++ scope was cleared ?");
2344 P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
2351 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
2352 void ParseDeclarator(Declarator &D);
2353 /// A function that parses a variant of direct-declarator.
2354 typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
2355 void ParseDeclaratorInternal(Declarator &D,
2356 DirectDeclParseFunction DirectDeclParser);
2358 enum AttrRequirements {
2359 AR_NoAttributesParsed = 0, ///< No attributes are diagnosed.
2360 AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes.
2361 AR_GNUAttributesParsed = 1 << 1,
2362 AR_CXX11AttributesParsed = 1 << 2,
2363 AR_DeclspecAttributesParsed = 1 << 3,
2364 AR_AllAttributesParsed = AR_GNUAttributesParsed |
2365 AR_CXX11AttributesParsed |
2366 AR_DeclspecAttributesParsed,
2367 AR_VendorAttributesParsed = AR_GNUAttributesParsed |
2368 AR_DeclspecAttributesParsed
2371 void ParseTypeQualifierListOpt(DeclSpec &DS,
2372 unsigned AttrReqs = AR_AllAttributesParsed,
2373 bool AtomicAllowed = true,
2374 bool IdentifierRequired = false);
2375 void ParseDirectDeclarator(Declarator &D);
2376 void ParseDecompositionDeclarator(Declarator &D);
2377 void ParseParenDeclarator(Declarator &D);
2378 void ParseFunctionDeclarator(Declarator &D,
2379 ParsedAttributes &attrs,
2380 BalancedDelimiterTracker &Tracker,
2382 bool RequiresArg = false);
2383 bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
2384 SourceLocation &RefQualifierLoc);
2385 bool isFunctionDeclaratorIdentifierList();
2386 void ParseFunctionDeclaratorIdentifierList(
2388 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
2389 void ParseParameterDeclarationClause(
2391 ParsedAttributes &attrs,
2392 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
2393 SourceLocation &EllipsisLoc);
2394 void ParseBracketDeclarator(Declarator &D);
2395 void ParseMisplacedBracketDeclarator(Declarator &D);
2397 //===--------------------------------------------------------------------===//
2398 // C++ 7: Declarations [dcl.dcl]
2400 /// The kind of attribute specifier we have found.
2401 enum CXX11AttributeKind {
2402 /// This is not an attribute specifier.
2403 CAK_NotAttributeSpecifier,
2404 /// This should be treated as an attribute-specifier.
2405 CAK_AttributeSpecifier,
2406 /// The next tokens are '[[', but this is not an attribute-specifier. This
2407 /// is ill-formed by C++11 [dcl.attr.grammar]p6.
2408 CAK_InvalidAttributeSpecifier
2411 isCXX11AttributeSpecifier(bool Disambiguate = false,
2412 bool OuterMightBeMessageSend = false);
2414 void DiagnoseUnexpectedNamespace(NamedDecl *Context);
2416 DeclGroupPtrTy ParseNamespace(unsigned Context, SourceLocation &DeclEnd,
2417 SourceLocation InlineLoc = SourceLocation());
2418 void ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc,
2419 std::vector<IdentifierInfo*>& Ident,
2420 std::vector<SourceLocation>& NamespaceLoc,
2421 unsigned int index, SourceLocation& InlineLoc,
2422 ParsedAttributes& attrs,
2423 BalancedDelimiterTracker &Tracker);
2424 Decl *ParseLinkage(ParsingDeclSpec &DS, unsigned Context);
2425 Decl *ParseExportDeclaration();
2426 DeclGroupPtrTy ParseUsingDirectiveOrDeclaration(
2427 unsigned Context, const ParsedTemplateInfo &TemplateInfo,
2428 SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs);
2429 Decl *ParseUsingDirective(unsigned Context,
2430 SourceLocation UsingLoc,
2431 SourceLocation &DeclEnd,
2432 ParsedAttributes &attrs);
2434 struct UsingDeclarator {
2435 SourceLocation TypenameLoc;
2437 SourceLocation TemplateKWLoc;
2439 SourceLocation EllipsisLoc;
2442 TypenameLoc = TemplateKWLoc = EllipsisLoc = SourceLocation();
2448 bool ParseUsingDeclarator(unsigned Context, UsingDeclarator &D);
2449 DeclGroupPtrTy ParseUsingDeclaration(unsigned Context,
2450 const ParsedTemplateInfo &TemplateInfo,
2451 SourceLocation UsingLoc,
2452 SourceLocation &DeclEnd,
2453 AccessSpecifier AS = AS_none);
2454 Decl *ParseAliasDeclarationAfterDeclarator(
2455 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
2456 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
2457 ParsedAttributes &Attrs, Decl **OwnedType = nullptr);
2459 Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
2460 Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
2461 SourceLocation AliasLoc, IdentifierInfo *Alias,
2462 SourceLocation &DeclEnd);
2464 //===--------------------------------------------------------------------===//
2465 // C++ 9: classes [class] and C structs/unions.
2466 bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
2467 void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
2468 DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo,
2469 AccessSpecifier AS, bool EnteringContext,
2470 DeclSpecContext DSC,
2471 ParsedAttributesWithRange &Attributes);
2472 void SkipCXXMemberSpecification(SourceLocation StartLoc,
2473 SourceLocation AttrFixitLoc,
2476 void ParseCXXMemberSpecification(SourceLocation StartLoc,
2477 SourceLocation AttrFixitLoc,
2478 ParsedAttributesWithRange &Attrs,
2481 ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2482 SourceLocation &EqualLoc);
2483 bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
2485 ExprResult &BitfieldSize,
2486 LateParsedAttrList &LateAttrs);
2487 void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D,
2488 VirtSpecifiers &VS);
2489 DeclGroupPtrTy ParseCXXClassMemberDeclaration(
2490 AccessSpecifier AS, AttributeList *Attr,
2491 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2492 ParsingDeclRAIIObject *DiagsFromTParams = nullptr);
2493 DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas(
2494 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
2495 DeclSpec::TST TagType, Decl *Tag);
2496 void ParseConstructorInitializer(Decl *ConstructorDecl);
2497 MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
2498 void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2501 //===--------------------------------------------------------------------===//
2502 // C++ 10: Derived classes [class.derived]
2503 TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
2504 SourceLocation &EndLocation);
2505 void ParseBaseClause(Decl *ClassDecl);
2506 BaseResult ParseBaseSpecifier(Decl *ClassDecl);
2507 AccessSpecifier getAccessSpecifierIfPresent() const;
2509 bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
2510 SourceLocation TemplateKWLoc,
2511 IdentifierInfo *Name,
2512 SourceLocation NameLoc,
2513 bool EnteringContext,
2514 ParsedType ObjectType,
2516 bool AssumeTemplateId);
2517 bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2518 ParsedType ObjectType,
2519 UnqualifiedId &Result);
2521 //===--------------------------------------------------------------------===//
2522 // OpenMP: Directives and clauses.
2523 /// Parse clauses for '#pragma omp declare simd'.
2524 DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr,
2526 SourceLocation Loc);
2527 /// \brief Parses declarative OpenMP directives.
2528 DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl(
2529 AccessSpecifier &AS, ParsedAttributesWithRange &Attrs,
2530 DeclSpec::TST TagType = DeclSpec::TST_unspecified,
2531 Decl *TagDecl = nullptr);
2532 /// \brief Parse 'omp declare reduction' construct.
2533 DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS);
2535 /// \brief Parses simple list of variables.
2537 /// \param Kind Kind of the directive.
2538 /// \param Callback Callback function to be called for the list elements.
2539 /// \param AllowScopeSpecifier true, if the variables can have fully
2540 /// qualified names.
2542 bool ParseOpenMPSimpleVarList(
2543 OpenMPDirectiveKind Kind,
2544 const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
2546 bool AllowScopeSpecifier);
2547 /// \brief Parses declarative or executable directive.
2549 /// \param Allowed ACK_Any, if any directives are allowed,
2550 /// ACK_StatementsOpenMPAnyExecutable - if any executable directives are
2551 /// allowed, ACK_StatementsOpenMPNonStandalone - if only non-standalone
2552 /// executable directives are allowed.
2555 ParseOpenMPDeclarativeOrExecutableDirective(AllowedContsructsKind Allowed);
2556 /// \brief Parses clause of kind \a CKind for directive of a kind \a Kind.
2558 /// \param DKind Kind of current directive.
2559 /// \param CKind Kind of current clause.
2560 /// \param FirstClause true, if this is the first clause of a kind \a CKind
2561 /// in current directive.
2563 OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
2564 OpenMPClauseKind CKind, bool FirstClause);
2565 /// \brief Parses clause with a single expression of a kind \a Kind.
2567 /// \param Kind Kind of current clause.
2569 OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind);
2570 /// \brief Parses simple clause of a kind \a Kind.
2572 /// \param Kind Kind of current clause.
2574 OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind);
2575 /// \brief Parses clause with a single expression and an additional argument
2576 /// of a kind \a Kind.
2578 /// \param Kind Kind of current clause.
2580 OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind);
2581 /// \brief Parses clause without any additional arguments.
2583 /// \param Kind Kind of current clause.
2585 OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind);
2586 /// \brief Parses clause with the list of variables of a kind \a Kind.
2588 /// \param Kind Kind of current clause.
2590 OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
2591 OpenMPClauseKind Kind);
2594 /// Parses simple expression in parens for single-expression clauses of OpenMP
2596 /// \param RLoc Returned location of right paren.
2597 ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc);
2599 /// Data used for parsing list of variables in OpenMP clauses.
2600 struct OpenMPVarListDataTy {
2601 Expr *TailExpr = nullptr;
2602 SourceLocation ColonLoc;
2603 CXXScopeSpec ReductionIdScopeSpec;
2604 DeclarationNameInfo ReductionId;
2605 OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown;
2606 OpenMPLinearClauseKind LinKind = OMPC_LINEAR_val;
2607 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
2608 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
2609 bool IsMapTypeImplicit = false;
2610 SourceLocation DepLinMapLoc;
2613 /// Parses clauses with list.
2614 bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind,
2615 SmallVectorImpl<Expr *> &Vars,
2616 OpenMPVarListDataTy &Data);
2617 bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2618 bool AllowDestructorName,
2619 bool AllowConstructorName,
2620 ParsedType ObjectType,
2621 SourceLocation& TemplateKWLoc,
2622 UnqualifiedId &Result);
2625 //===--------------------------------------------------------------------===//
2626 // C++ 14: Templates [temp]
2628 // C++ 14.1: Template Parameters [temp.param]
2629 Decl *ParseDeclarationStartingWithTemplate(unsigned Context,
2630 SourceLocation &DeclEnd,
2631 AccessSpecifier AS = AS_none,
2632 AttributeList *AccessAttrs = nullptr);
2633 Decl *ParseTemplateDeclarationOrSpecialization(unsigned Context,
2634 SourceLocation &DeclEnd,
2636 AttributeList *AccessAttrs);
2637 Decl *ParseSingleDeclarationAfterTemplate(
2639 const ParsedTemplateInfo &TemplateInfo,
2640 ParsingDeclRAIIObject &DiagsFromParams,
2641 SourceLocation &DeclEnd,
2642 AccessSpecifier AS=AS_none,
2643 AttributeList *AccessAttrs = nullptr);
2644 bool ParseTemplateParameters(unsigned Depth,
2645 SmallVectorImpl<Decl*> &TemplateParams,
2646 SourceLocation &LAngleLoc,
2647 SourceLocation &RAngleLoc);
2648 bool ParseTemplateParameterList(unsigned Depth,
2649 SmallVectorImpl<Decl*> &TemplateParams);
2650 bool isStartOfTemplateTypeParameter();
2651 Decl *ParseTemplateParameter(unsigned Depth, unsigned Position);
2652 Decl *ParseTypeParameter(unsigned Depth, unsigned Position);
2653 Decl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
2654 Decl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
2655 void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
2656 SourceLocation CorrectLoc,
2657 bool AlreadyHasEllipsis,
2658 bool IdentifierHasName);
2659 void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
2661 // C++ 14.3: Template arguments [temp.arg]
2662 typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
2664 bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
2665 bool ConsumeLastToken,
2666 bool ObjCGenericList);
2667 bool ParseTemplateIdAfterTemplateName(TemplateTy Template,
2668 SourceLocation TemplateNameLoc,
2669 const CXXScopeSpec &SS,
2670 bool ConsumeLastToken,
2671 SourceLocation &LAngleLoc,
2672 TemplateArgList &TemplateArgs,
2673 SourceLocation &RAngleLoc);
2675 bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
2677 SourceLocation TemplateKWLoc,
2678 UnqualifiedId &TemplateName,
2679 bool AllowTypeAnnotation = true);
2680 void AnnotateTemplateIdTokenAsType();
2681 bool IsTemplateArgumentList(unsigned Skip = 0);
2682 bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
2683 ParsedTemplateArgument ParseTemplateTemplateArgument();
2684 ParsedTemplateArgument ParseTemplateArgument();
2685 Decl *ParseExplicitInstantiation(unsigned Context,
2686 SourceLocation ExternLoc,
2687 SourceLocation TemplateLoc,
2688 SourceLocation &DeclEnd,
2689 AccessSpecifier AS = AS_none);
2691 //===--------------------------------------------------------------------===//
2693 DeclGroupPtrTy ParseModuleDecl();
2694 DeclGroupPtrTy ParseModuleImport(SourceLocation AtLoc);
2695 bool parseMisplacedModuleImport();
2696 bool tryParseMisplacedModuleImport() {
2697 tok::TokenKind Kind = Tok.getKind();
2698 if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end ||
2699 Kind == tok::annot_module_include)
2700 return parseMisplacedModuleImport();
2704 bool ParseModuleName(
2705 SourceLocation UseLoc,
2706 SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
2709 //===--------------------------------------------------------------------===//
2710 // C++11/G++: Type Traits [Type-Traits.html in the GCC manual]
2711 ExprResult ParseTypeTrait();
2713 //===--------------------------------------------------------------------===//
2714 // Embarcadero: Arary and Expression Traits
2715 ExprResult ParseArrayTypeTrait();
2716 ExprResult ParseExpressionTrait();
2718 //===--------------------------------------------------------------------===//
2719 // Preprocessor code-completion pass-through
2720 void CodeCompleteDirective(bool InConditional) override;
2721 void CodeCompleteInConditionalExclusion() override;
2722 void CodeCompleteMacroName(bool IsDefinition) override;
2723 void CodeCompletePreprocessorExpression() override;
2724 void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo,
2725 unsigned ArgumentIndex) override;
2726 void CodeCompleteNaturalLanguage() override;
2729 } // end namespace clang