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();
604 bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS,
606 bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
609 enum AnnotatedNameKind {
610 /// Annotation has failed and emitted an error.
612 /// The identifier is a tentatively-declared name.
614 /// The identifier is a template name. FIXME: Add an annotation for that.
616 /// The identifier can't be resolved.
618 /// Annotation was successful.
622 TryAnnotateName(bool IsAddressOfOperand,
623 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
625 /// Push a tok::annot_cxxscope token onto the token stream.
626 void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
628 /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
629 /// replacing them with the non-context-sensitive keywords. This returns
630 /// true if the token was replaced.
631 bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
632 const char *&PrevSpec, unsigned &DiagID,
634 if (!getLangOpts().AltiVec && !getLangOpts().ZVector)
637 if (Tok.getIdentifierInfo() != Ident_vector &&
638 Tok.getIdentifierInfo() != Ident_bool &&
639 (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel))
642 return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
645 /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
646 /// identifier token, replacing it with the non-context-sensitive __vector.
647 /// This returns true if the token was replaced.
648 bool TryAltiVecVectorToken() {
649 if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) ||
650 Tok.getIdentifierInfo() != Ident_vector) return false;
651 return TryAltiVecVectorTokenOutOfLine();
654 bool TryAltiVecVectorTokenOutOfLine();
655 bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
656 const char *&PrevSpec, unsigned &DiagID,
659 /// Returns true if the current token is the identifier 'instancetype'.
661 /// Should only be used in Objective-C language modes.
662 bool isObjCInstancetype() {
663 assert(getLangOpts().ObjC1);
664 if (Tok.isAnnotation())
666 if (!Ident_instancetype)
667 Ident_instancetype = PP.getIdentifierInfo("instancetype");
668 return Tok.getIdentifierInfo() == Ident_instancetype;
671 /// TryKeywordIdentFallback - For compatibility with system headers using
672 /// keywords as identifiers, attempt to convert the current token to an
673 /// identifier and optionally disable the keyword for the remainder of the
674 /// translation unit. This returns false if the token was not replaced,
675 /// otherwise emits a diagnostic and returns true.
676 bool TryKeywordIdentFallback(bool DisableKeyword);
678 /// \brief Get the TemplateIdAnnotation from the token.
679 TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
681 /// TentativeParsingAction - An object that is used as a kind of "tentative
682 /// parsing transaction". It gets instantiated to mark the token position and
683 /// after the token consumption is done, Commit() or Revert() is called to
684 /// either "commit the consumed tokens" or revert to the previously marked
685 /// token position. Example:
687 /// TentativeParsingAction TPA(*this);
692 class TentativeParsingAction {
695 size_t PrevTentativelyDeclaredIdentifierCount;
696 unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
700 explicit TentativeParsingAction(Parser& p) : P(p) {
702 PrevTentativelyDeclaredIdentifierCount =
703 P.TentativelyDeclaredIdentifiers.size();
704 PrevParenCount = P.ParenCount;
705 PrevBracketCount = P.BracketCount;
706 PrevBraceCount = P.BraceCount;
707 P.PP.EnableBacktrackAtThisPos();
711 assert(isActive && "Parsing action was finished!");
712 P.TentativelyDeclaredIdentifiers.resize(
713 PrevTentativelyDeclaredIdentifierCount);
714 P.PP.CommitBacktrackedTokens();
718 assert(isActive && "Parsing action was finished!");
721 P.TentativelyDeclaredIdentifiers.resize(
722 PrevTentativelyDeclaredIdentifierCount);
723 P.ParenCount = PrevParenCount;
724 P.BracketCount = PrevBracketCount;
725 P.BraceCount = PrevBraceCount;
728 ~TentativeParsingAction() {
729 assert(!isActive && "Forgot to call Commit or Revert!");
732 /// A TentativeParsingAction that automatically reverts in its destructor.
733 /// Useful for disambiguation parses that will always be reverted.
734 class RevertingTentativeParsingAction
735 : private Parser::TentativeParsingAction {
737 RevertingTentativeParsingAction(Parser &P)
738 : Parser::TentativeParsingAction(P) {}
739 ~RevertingTentativeParsingAction() { Revert(); }
742 class UnannotatedTentativeParsingAction;
744 /// ObjCDeclContextSwitch - An object used to switch context from
745 /// an objective-c decl context to its enclosing decl context and
747 class ObjCDeclContextSwitch {
750 SaveAndRestore<bool> WithinObjCContainer;
752 explicit ObjCDeclContextSwitch(Parser &p)
753 : P(p), DC(p.getObjCDeclContext()),
754 WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) {
756 P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC));
758 ~ObjCDeclContextSwitch() {
760 P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC));
764 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
765 /// input. If so, it is consumed and false is returned.
767 /// If a trivial punctuator misspelling is encountered, a FixIt error
768 /// diagnostic is issued and false is returned after recovery.
770 /// If the input is malformed, this emits the specified diagnostic and true is
772 bool ExpectAndConsume(tok::TokenKind ExpectedTok,
773 unsigned Diag = diag::err_expected,
774 StringRef DiagMsg = "");
776 /// \brief The parser expects a semicolon and, if present, will consume it.
778 /// If the next token is not a semicolon, this emits the specified diagnostic,
779 /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
780 /// to the semicolon, consumes that extra token.
781 bool ExpectAndConsumeSemi(unsigned DiagID);
783 /// \brief The kind of extra semi diagnostic to emit.
787 InstanceVariableList = 2,
788 AfterMemberFunctionDefinition = 3
791 /// \brief Consume any extra semi-colons until the end of the line.
792 void ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST = TST_unspecified);
795 //===--------------------------------------------------------------------===//
796 // Scope manipulation
798 /// ParseScope - Introduces a new scope for parsing. The kind of
799 /// scope is determined by ScopeFlags. Objects of this type should
800 /// be created on the stack to coincide with the position where the
801 /// parser enters the new scope, and this object's constructor will
802 /// create that new scope. Similarly, once the object is destroyed
803 /// the parser will exit the scope.
806 ParseScope(const ParseScope &) = delete;
807 void operator=(const ParseScope &) = delete;
810 // ParseScope - Construct a new object to manage a scope in the
811 // parser Self where the new Scope is created with the flags
812 // ScopeFlags, but only when we aren't about to enter a compound statement.
813 ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true,
814 bool BeforeCompoundStmt = false)
816 if (EnteredScope && !BeforeCompoundStmt)
817 Self->EnterScope(ScopeFlags);
819 if (BeforeCompoundStmt)
820 Self->incrementMSManglingNumber();
822 this->Self = nullptr;
826 // Exit - Exit the scope associated with this object now, rather
827 // than waiting until the object is destroyed.
840 /// EnterScope - Start a new scope.
841 void EnterScope(unsigned ScopeFlags);
843 /// ExitScope - Pop a scope off the scope stack.
847 /// \brief RAII object used to modify the scope flags for the current scope.
848 class ParseScopeFlags {
851 ParseScopeFlags(const ParseScopeFlags &) = delete;
852 void operator=(const ParseScopeFlags &) = delete;
855 ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
859 //===--------------------------------------------------------------------===//
860 // Diagnostic Emission and Error recovery.
863 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
864 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
865 DiagnosticBuilder Diag(unsigned DiagID) {
866 return Diag(Tok, DiagID);
870 void SuggestParentheses(SourceLocation Loc, unsigned DK,
871 SourceRange ParenRange);
872 void CheckNestedObjCContexts(SourceLocation AtLoc);
876 /// \brief Control flags for SkipUntil functions.
877 enum SkipUntilFlags {
878 StopAtSemi = 1 << 0, ///< Stop skipping at semicolon
879 /// \brief Stop skipping at specified token, but don't skip the token itself
880 StopBeforeMatch = 1 << 1,
881 StopAtCodeCompletion = 1 << 2 ///< Stop at code completion
884 friend constexpr SkipUntilFlags operator|(SkipUntilFlags L,
886 return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) |
887 static_cast<unsigned>(R));
890 /// SkipUntil - Read tokens until we get to the specified token, then consume
891 /// it (unless StopBeforeMatch is specified). Because we cannot guarantee
892 /// that the token will ever occur, this skips to the next token, or to some
893 /// likely good stopping point. If Flags has StopAtSemi flag, skipping will
894 /// stop at a ';' character.
896 /// If SkipUntil finds the specified token, it returns true, otherwise it
898 bool SkipUntil(tok::TokenKind T,
899 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
900 return SkipUntil(llvm::makeArrayRef(T), Flags);
902 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2,
903 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
904 tok::TokenKind TokArray[] = {T1, T2};
905 return SkipUntil(TokArray, Flags);
907 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3,
908 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
909 tok::TokenKind TokArray[] = {T1, T2, T3};
910 return SkipUntil(TokArray, Flags);
912 bool SkipUntil(ArrayRef<tok::TokenKind> Toks,
913 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0));
915 /// SkipMalformedDecl - Read tokens until we get to some likely good stopping
916 /// point for skipping past a simple-declaration.
917 void SkipMalformedDecl();
920 //===--------------------------------------------------------------------===//
921 // Lexing and parsing of C++ inline methods.
925 /// [class.mem]p1: "... the class is regarded as complete within
926 /// - function bodies
927 /// - default arguments
928 /// - exception-specifications (TODO: C++0x)
929 /// - and brace-or-equal-initializers for non-static data members
930 /// (including such things in nested classes)."
931 /// LateParsedDeclarations build the tree of those elements so they can
932 /// be parsed after parsing the top-level class.
933 class LateParsedDeclaration {
935 virtual ~LateParsedDeclaration();
937 virtual void ParseLexedMethodDeclarations();
938 virtual void ParseLexedMemberInitializers();
939 virtual void ParseLexedMethodDefs();
940 virtual void ParseLexedAttributes();
943 /// Inner node of the LateParsedDeclaration tree that parses
944 /// all its members recursively.
945 class LateParsedClass : public LateParsedDeclaration {
947 LateParsedClass(Parser *P, ParsingClass *C);
948 ~LateParsedClass() override;
950 void ParseLexedMethodDeclarations() override;
951 void ParseLexedMemberInitializers() override;
952 void ParseLexedMethodDefs() override;
953 void ParseLexedAttributes() override;
960 /// Contains the lexed tokens of an attribute with arguments that
961 /// may reference member variables and so need to be parsed at the
962 /// end of the class declaration after parsing all other member
963 /// member declarations.
964 /// FIXME: Perhaps we should change the name of LateParsedDeclaration to
965 /// LateParsedTokens.
966 struct LateParsedAttribute : public LateParsedDeclaration {
969 IdentifierInfo &AttrName;
970 SourceLocation AttrNameLoc;
971 SmallVector<Decl*, 2> Decls;
973 explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
975 : Self(P), AttrName(Name), AttrNameLoc(Loc) {}
977 void ParseLexedAttributes() override;
979 void addDecl(Decl *D) { Decls.push_back(D); }
982 // A list of late-parsed attributes. Used by ParseGNUAttributes.
983 class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> {
985 LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { }
987 bool parseSoon() { return ParseSoon; }
990 bool ParseSoon; // Are we planning to parse these shortly after creation?
993 /// Contains the lexed tokens of a member function definition
994 /// which needs to be parsed at the end of the class declaration
995 /// after parsing all other member declarations.
996 struct LexedMethod : public LateParsedDeclaration {
1001 /// \brief Whether this member function had an associated template
1002 /// scope. When true, D is a template declaration.
1003 /// otherwise, it is a member function declaration.
1006 explicit LexedMethod(Parser* P, Decl *MD)
1007 : Self(P), D(MD), TemplateScope(false) {}
1009 void ParseLexedMethodDefs() override;
1012 /// LateParsedDefaultArgument - Keeps track of a parameter that may
1013 /// have a default argument that cannot be parsed yet because it
1014 /// occurs within a member function declaration inside the class
1015 /// (C++ [class.mem]p2).
1016 struct LateParsedDefaultArgument {
1017 explicit LateParsedDefaultArgument(Decl *P,
1018 std::unique_ptr<CachedTokens> Toks = nullptr)
1019 : Param(P), Toks(std::move(Toks)) { }
1021 /// Param - The parameter declaration for this parameter.
1024 /// Toks - The sequence of tokens that comprises the default
1025 /// argument expression, not including the '=' or the terminating
1026 /// ')' or ','. This will be NULL for parameters that have no
1027 /// default argument.
1028 std::unique_ptr<CachedTokens> Toks;
1031 /// LateParsedMethodDeclaration - A method declaration inside a class that
1032 /// contains at least one entity whose parsing needs to be delayed
1033 /// until the class itself is completely-defined, such as a default
1034 /// argument (C++ [class.mem]p2).
1035 struct LateParsedMethodDeclaration : public LateParsedDeclaration {
1036 explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
1037 : Self(P), Method(M), TemplateScope(false),
1038 ExceptionSpecTokens(nullptr) {}
1040 void ParseLexedMethodDeclarations() override;
1044 /// Method - The method declaration.
1047 /// \brief Whether this member function had an associated template
1048 /// scope. When true, D is a template declaration.
1049 /// othewise, it is a member function declaration.
1052 /// DefaultArgs - Contains the parameters of the function and
1053 /// their default arguments. At least one of the parameters will
1054 /// have a default argument, but all of the parameters of the
1055 /// method will be stored so that they can be reintroduced into
1056 /// scope at the appropriate times.
1057 SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
1059 /// \brief The set of tokens that make up an exception-specification that
1060 /// has not yet been parsed.
1061 CachedTokens *ExceptionSpecTokens;
1064 /// LateParsedMemberInitializer - An initializer for a non-static class data
1065 /// member whose parsing must to be delayed until the class is completely
1066 /// defined (C++11 [class.mem]p2).
1067 struct LateParsedMemberInitializer : public LateParsedDeclaration {
1068 LateParsedMemberInitializer(Parser *P, Decl *FD)
1069 : Self(P), Field(FD) { }
1071 void ParseLexedMemberInitializers() override;
1075 /// Field - The field declaration.
1078 /// CachedTokens - The sequence of tokens that comprises the initializer,
1079 /// including any leading '='.
1083 /// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
1084 /// C++ class, its method declarations that contain parts that won't be
1085 /// parsed until after the definition is completed (C++ [class.mem]p2),
1086 /// the method declarations and possibly attached inline definitions
1087 /// will be stored here with the tokens that will be parsed to create those
1089 typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer;
1091 /// \brief Representation of a class that has been parsed, including
1092 /// any member function declarations or definitions that need to be
1093 /// parsed after the corresponding top-level class is complete.
1094 struct ParsingClass {
1095 ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface)
1096 : TopLevelClass(TopLevelClass), TemplateScope(false),
1097 IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) { }
1099 /// \brief Whether this is a "top-level" class, meaning that it is
1100 /// not nested within another class.
1101 bool TopLevelClass : 1;
1103 /// \brief Whether this class had an associated template
1104 /// scope. When true, TagOrTemplate is a template declaration;
1105 /// othewise, it is a tag declaration.
1106 bool TemplateScope : 1;
1108 /// \brief Whether this class is an __interface.
1109 bool IsInterface : 1;
1111 /// \brief The class or class template whose definition we are parsing.
1112 Decl *TagOrTemplate;
1114 /// LateParsedDeclarations - Method declarations, inline definitions and
1115 /// nested classes that contain pieces whose parsing will be delayed until
1116 /// the top-level class is fully defined.
1117 LateParsedDeclarationsContainer LateParsedDeclarations;
1120 /// \brief The stack of classes that is currently being
1121 /// parsed. Nested and local classes will be pushed onto this stack
1122 /// when they are parsed, and removed afterward.
1123 std::stack<ParsingClass *> ClassStack;
1125 ParsingClass &getCurrentClass() {
1126 assert(!ClassStack.empty() && "No lexed method stacks!");
1127 return *ClassStack.top();
1130 /// \brief RAII object used to manage the parsing of a class definition.
1131 class ParsingClassDefinition {
1134 Sema::ParsingClassState State;
1137 ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass,
1139 : P(P), Popped(false),
1140 State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
1143 /// \brief Pop this class of the stack.
1145 assert(!Popped && "Nested class has already been popped");
1147 P.PopParsingClass(State);
1150 ~ParsingClassDefinition() {
1152 P.PopParsingClass(State);
1156 /// \brief Contains information about any template-specific
1157 /// information that has been parsed prior to parsing declaration
1159 struct ParsedTemplateInfo {
1160 ParsedTemplateInfo()
1161 : Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { }
1163 ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
1164 bool isSpecialization,
1165 bool lastParameterListWasEmpty = false)
1166 : Kind(isSpecialization? ExplicitSpecialization : Template),
1167 TemplateParams(TemplateParams),
1168 LastParameterListWasEmpty(lastParameterListWasEmpty) { }
1170 explicit ParsedTemplateInfo(SourceLocation ExternLoc,
1171 SourceLocation TemplateLoc)
1172 : Kind(ExplicitInstantiation), TemplateParams(nullptr),
1173 ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
1174 LastParameterListWasEmpty(false){ }
1176 /// \brief The kind of template we are parsing.
1178 /// \brief We are not parsing a template at all.
1180 /// \brief We are parsing a template declaration.
1182 /// \brief We are parsing an explicit specialization.
1183 ExplicitSpecialization,
1184 /// \brief We are parsing an explicit instantiation.
1185 ExplicitInstantiation
1188 /// \brief The template parameter lists, for template declarations
1189 /// and explicit specializations.
1190 TemplateParameterLists *TemplateParams;
1192 /// \brief The location of the 'extern' keyword, if any, for an explicit
1194 SourceLocation ExternLoc;
1196 /// \brief The location of the 'template' keyword, for an explicit
1198 SourceLocation TemplateLoc;
1200 /// \brief Whether the last template parameter list was empty.
1201 bool LastParameterListWasEmpty;
1203 SourceRange getSourceRange() const LLVM_READONLY;
1206 void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
1207 void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
1209 static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
1210 static void LateTemplateParserCleanupCallback(void *P);
1212 Sema::ParsingClassState
1213 PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface);
1214 void DeallocateParsedClasses(ParsingClass *Class);
1215 void PopParsingClass(Sema::ParsingClassState);
1217 enum CachedInitKind {
1218 CIK_DefaultArgument,
1219 CIK_DefaultInitializer
1222 NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS,
1223 AttributeList *AccessAttrs,
1224 ParsingDeclarator &D,
1225 const ParsedTemplateInfo &TemplateInfo,
1226 const VirtSpecifiers& VS,
1227 SourceLocation PureSpecLoc);
1228 void ParseCXXNonStaticMemberInitializer(Decl *VarD);
1229 void ParseLexedAttributes(ParsingClass &Class);
1230 void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1231 bool EnterScope, bool OnDefinition);
1232 void ParseLexedAttribute(LateParsedAttribute &LA,
1233 bool EnterScope, bool OnDefinition);
1234 void ParseLexedMethodDeclarations(ParsingClass &Class);
1235 void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
1236 void ParseLexedMethodDefs(ParsingClass &Class);
1237 void ParseLexedMethodDef(LexedMethod &LM);
1238 void ParseLexedMemberInitializers(ParsingClass &Class);
1239 void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
1240 void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod);
1241 bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
1242 bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK);
1243 bool ConsumeAndStoreConditional(CachedTokens &Toks);
1244 bool ConsumeAndStoreUntil(tok::TokenKind T1,
1246 bool StopAtSemi = true,
1247 bool ConsumeFinalToken = true) {
1248 return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
1250 bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
1252 bool StopAtSemi = true,
1253 bool ConsumeFinalToken = true);
1255 //===--------------------------------------------------------------------===//
1256 // C99 6.9: External Definitions.
1257 struct ParsedAttributesWithRange : ParsedAttributes {
1258 ParsedAttributesWithRange(AttributeFactory &factory)
1259 : ParsedAttributes(factory) {}
1262 ParsedAttributes::clear();
1263 Range = SourceRange();
1269 DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
1270 ParsingDeclSpec *DS = nullptr);
1271 bool isDeclarationAfterDeclarator();
1272 bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
1273 DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(
1274 ParsedAttributesWithRange &attrs,
1275 ParsingDeclSpec *DS = nullptr,
1276 AccessSpecifier AS = AS_none);
1277 DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
1278 ParsingDeclSpec &DS,
1279 AccessSpecifier AS);
1281 void SkipFunctionBody();
1282 Decl *ParseFunctionDefinition(ParsingDeclarator &D,
1283 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1284 LateParsedAttrList *LateParsedAttrs = nullptr);
1285 void ParseKNRParamDeclarations(Declarator &D);
1286 // EndLoc, if non-NULL, is filled with the location of the last token of
1288 ExprResult ParseSimpleAsm(SourceLocation *EndLoc = nullptr);
1289 ExprResult ParseAsmStringLiteral();
1291 // Objective-C External Declarations
1292 void MaybeSkipAttributes(tok::ObjCKeywordKind Kind);
1293 DeclGroupPtrTy ParseObjCAtDirectives();
1294 DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
1295 Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
1296 ParsedAttributes &prefixAttrs);
1297 class ObjCTypeParamListScope;
1298 ObjCTypeParamList *parseObjCTypeParamList();
1299 ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs(
1300 ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
1301 SmallVectorImpl<IdentifierLocPair> &protocolIdents,
1302 SourceLocation &rAngleLoc, bool mayBeProtocolList = true);
1304 void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
1305 BalancedDelimiterTracker &T,
1306 SmallVectorImpl<Decl *> &AllIvarDecls,
1307 bool RBraceMissing);
1308 void ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1309 tok::ObjCKeywordKind visibility,
1310 SourceLocation atLoc);
1311 bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P,
1312 SmallVectorImpl<SourceLocation> &PLocs,
1313 bool WarnOnDeclarations,
1314 bool ForObjCContainer,
1315 SourceLocation &LAngleLoc,
1316 SourceLocation &EndProtoLoc,
1317 bool consumeLastToken);
1319 /// Parse the first angle-bracket-delimited clause for an
1320 /// Objective-C object or object pointer type, which may be either
1321 /// type arguments or protocol qualifiers.
1322 void parseObjCTypeArgsOrProtocolQualifiers(
1323 ParsedType baseType,
1324 SourceLocation &typeArgsLAngleLoc,
1325 SmallVectorImpl<ParsedType> &typeArgs,
1326 SourceLocation &typeArgsRAngleLoc,
1327 SourceLocation &protocolLAngleLoc,
1328 SmallVectorImpl<Decl *> &protocols,
1329 SmallVectorImpl<SourceLocation> &protocolLocs,
1330 SourceLocation &protocolRAngleLoc,
1331 bool consumeLastToken,
1332 bool warnOnIncompleteProtocols);
1334 /// Parse either Objective-C type arguments or protocol qualifiers; if the
1335 /// former, also parse protocol qualifiers afterward.
1336 void parseObjCTypeArgsAndProtocolQualifiers(
1337 ParsedType baseType,
1338 SourceLocation &typeArgsLAngleLoc,
1339 SmallVectorImpl<ParsedType> &typeArgs,
1340 SourceLocation &typeArgsRAngleLoc,
1341 SourceLocation &protocolLAngleLoc,
1342 SmallVectorImpl<Decl *> &protocols,
1343 SmallVectorImpl<SourceLocation> &protocolLocs,
1344 SourceLocation &protocolRAngleLoc,
1345 bool consumeLastToken);
1347 /// Parse a protocol qualifier type such as '<NSCopying>', which is
1348 /// an anachronistic way of writing 'id<NSCopying>'.
1349 TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc);
1351 /// Parse Objective-C type arguments and protocol qualifiers, extending the
1352 /// current type with the parsed result.
1353 TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc,
1355 bool consumeLastToken,
1356 SourceLocation &endLoc);
1358 void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
1360 DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
1361 ParsedAttributes &prefixAttrs);
1363 struct ObjCImplParsingDataRAII {
1367 typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer;
1368 LateParsedObjCMethodContainer LateParsedObjCMethods;
1370 ObjCImplParsingDataRAII(Parser &parser, Decl *D)
1371 : P(parser), Dcl(D), HasCFunction(false) {
1372 P.CurParsedObjCImpl = this;
1375 ~ObjCImplParsingDataRAII();
1377 void finish(SourceRange AtEnd);
1378 bool isFinished() const { return Finished; }
1383 ObjCImplParsingDataRAII *CurParsedObjCImpl;
1384 void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl);
1386 DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc);
1387 DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
1388 Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
1389 Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
1390 Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
1392 IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
1393 // Definitions for Objective-c context sensitive keywords recognition.
1395 objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
1396 objc_nonnull, objc_nullable, objc_null_unspecified,
1399 IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
1401 bool isTokIdentifier_in() const;
1403 ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, Declarator::TheContext Ctx,
1404 ParsedAttributes *ParamAttrs);
1405 void ParseObjCMethodRequirement();
1406 Decl *ParseObjCMethodPrototype(
1407 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1408 bool MethodDefinition = true);
1409 Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
1410 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1411 bool MethodDefinition=true);
1412 void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
1414 Decl *ParseObjCMethodDefinition();
1417 //===--------------------------------------------------------------------===//
1418 // C99 6.5: Expressions.
1420 /// TypeCastState - State whether an expression is or may be a type cast.
1421 enum TypeCastState {
1427 ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast);
1428 ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast);
1429 ExprResult ParseConstraintExpression();
1430 // Expr that doesn't include commas.
1431 ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast);
1433 ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1434 unsigned &NumLineToksConsumed,
1436 bool IsUnevaluated);
1439 ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
1441 ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
1443 ExprResult ParseRHSOfBinaryExpression(ExprResult LHS,
1444 prec::Level MinPrec);
1445 ExprResult ParseCastExpression(bool isUnaryExpression,
1446 bool isAddressOfOperand,
1448 TypeCastState isTypeCast);
1449 ExprResult ParseCastExpression(bool isUnaryExpression,
1450 bool isAddressOfOperand = false,
1451 TypeCastState isTypeCast = NotTypeCast);
1453 /// Returns true if the next token cannot start an expression.
1454 bool isNotExpressionStart();
1456 /// Returns true if the next token would start a postfix-expression
1458 bool isPostfixExpressionSuffixStart() {
1459 tok::TokenKind K = Tok.getKind();
1460 return (K == tok::l_square || K == tok::l_paren ||
1461 K == tok::period || K == tok::arrow ||
1462 K == tok::plusplus || K == tok::minusminus);
1465 ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
1466 ExprResult ParseUnaryExprOrTypeTraitExpression();
1467 ExprResult ParseBuiltinPrimaryExpression();
1469 ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1472 SourceRange &CastRange);
1474 typedef SmallVector<Expr*, 20> ExprListTy;
1475 typedef SmallVector<SourceLocation, 20> CommaLocsTy;
1477 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1478 bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
1479 SmallVectorImpl<SourceLocation> &CommaLocs,
1480 std::function<void()> Completer = nullptr);
1482 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
1483 /// used for misc language extensions.
1484 bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
1485 SmallVectorImpl<SourceLocation> &CommaLocs);
1488 /// ParenParseOption - Control what ParseParenExpression will parse.
1489 enum ParenParseOption {
1490 SimpleExpr, // Only parse '(' expression ')'
1491 CompoundStmt, // Also allow '(' compound-statement ')'
1492 CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
1493 CastExpr // Also allow '(' type-name ')' <anything>
1495 ExprResult ParseParenExpression(ParenParseOption &ExprType,
1496 bool stopIfCastExpr,
1499 SourceLocation &RParenLoc);
1501 ExprResult ParseCXXAmbiguousParenExpression(
1502 ParenParseOption &ExprType, ParsedType &CastTy,
1503 BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt);
1504 ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
1505 SourceLocation LParenLoc,
1506 SourceLocation RParenLoc);
1508 ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
1510 ExprResult ParseGenericSelectionExpression();
1512 ExprResult ParseObjCBoolLiteral();
1514 ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T);
1516 //===--------------------------------------------------------------------===//
1518 ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
1519 Token &Replacement);
1520 ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
1522 bool areTokensAdjacent(const Token &A, const Token &B);
1524 void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
1525 bool EnteringContext, IdentifierInfo &II,
1528 bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
1529 ParsedType ObjectType,
1530 bool EnteringContext,
1531 bool *MayBePseudoDestructor = nullptr,
1532 bool IsTypename = false,
1533 IdentifierInfo **LastII = nullptr);
1535 //===--------------------------------------------------------------------===//
1536 // C++0x 5.1.2: Lambda expressions
1538 // [...] () -> type {...}
1539 ExprResult ParseLambdaExpression();
1540 ExprResult TryParseLambdaExpression();
1541 Optional<unsigned> ParseLambdaIntroducer(LambdaIntroducer &Intro,
1542 bool *SkippedInits = nullptr);
1543 bool TryParseLambdaIntroducer(LambdaIntroducer &Intro);
1544 ExprResult ParseLambdaExpressionAfterIntroducer(
1545 LambdaIntroducer &Intro);
1547 //===--------------------------------------------------------------------===//
1548 // C++ 5.2p1: C++ Casts
1549 ExprResult ParseCXXCasts();
1551 //===--------------------------------------------------------------------===//
1552 // C++ 5.2p1: C++ Type Identification
1553 ExprResult ParseCXXTypeid();
1555 //===--------------------------------------------------------------------===//
1556 // C++ : Microsoft __uuidof Expression
1557 ExprResult ParseCXXUuidof();
1559 //===--------------------------------------------------------------------===//
1560 // C++ 5.2.4: C++ Pseudo-Destructor Expressions
1561 ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1562 tok::TokenKind OpKind,
1564 ParsedType ObjectType);
1566 //===--------------------------------------------------------------------===//
1567 // C++ 9.3.2: C++ 'this' pointer
1568 ExprResult ParseCXXThis();
1570 //===--------------------------------------------------------------------===//
1571 // C++ 15: C++ Throw Expression
1572 ExprResult ParseThrowExpression();
1574 ExceptionSpecificationType tryParseExceptionSpecification(
1576 SourceRange &SpecificationRange,
1577 SmallVectorImpl<ParsedType> &DynamicExceptions,
1578 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
1579 ExprResult &NoexceptExpr,
1580 CachedTokens *&ExceptionSpecTokens);
1582 // EndLoc is filled with the location of the last token of the specification.
1583 ExceptionSpecificationType ParseDynamicExceptionSpecification(
1584 SourceRange &SpecificationRange,
1585 SmallVectorImpl<ParsedType> &Exceptions,
1586 SmallVectorImpl<SourceRange> &Ranges);
1588 //===--------------------------------------------------------------------===//
1589 // C++0x 8: Function declaration trailing-return-type
1590 TypeResult ParseTrailingReturnType(SourceRange &Range);
1592 //===--------------------------------------------------------------------===//
1593 // C++ 2.13.5: C++ Boolean Literals
1594 ExprResult ParseCXXBoolLiteral();
1596 //===--------------------------------------------------------------------===//
1597 // C++ 5.2.3: Explicit type conversion (functional notation)
1598 ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
1600 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1601 /// This should only be called when the current token is known to be part of
1602 /// simple-type-specifier.
1603 void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
1605 bool ParseCXXTypeSpecifierSeq(DeclSpec &DS);
1607 //===--------------------------------------------------------------------===//
1608 // C++ 5.3.4 and 5.3.5: C++ new and delete
1609 bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs,
1611 void ParseDirectNewDeclarator(Declarator &D);
1612 ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
1613 ExprResult ParseCXXDeleteExpression(bool UseGlobal,
1614 SourceLocation Start);
1616 //===--------------------------------------------------------------------===//
1617 // C++ if/switch/while condition expression.
1618 Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt,
1620 Sema::ConditionKind CK);
1622 //===--------------------------------------------------------------------===//
1625 ExprResult ParseCoyieldExpression();
1627 //===--------------------------------------------------------------------===//
1628 // C99 6.7.8: Initialization.
1630 /// ParseInitializer
1631 /// initializer: [C99 6.7.8]
1632 /// assignment-expression
1634 ExprResult ParseInitializer() {
1635 if (Tok.isNot(tok::l_brace))
1636 return ParseAssignmentExpression();
1637 return ParseBraceInitializer();
1639 bool MayBeDesignationStart();
1640 ExprResult ParseBraceInitializer();
1641 ExprResult ParseInitializerWithPotentialDesignator();
1643 //===--------------------------------------------------------------------===//
1644 // clang Expressions
1646 ExprResult ParseBlockLiteralExpression(); // ^{...}
1648 //===--------------------------------------------------------------------===//
1649 // Objective-C Expressions
1650 ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
1651 ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
1652 ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
1653 ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
1654 ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
1655 ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
1656 ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
1657 ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
1658 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
1659 ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
1660 ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
1661 bool isSimpleObjCMessageExpression();
1662 ExprResult ParseObjCMessageExpression();
1663 ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
1664 SourceLocation SuperLoc,
1665 ParsedType ReceiverType,
1666 Expr *ReceiverExpr);
1667 ExprResult ParseAssignmentExprWithObjCMessageExprStart(
1668 SourceLocation LBracloc, SourceLocation SuperLoc,
1669 ParsedType ReceiverType, Expr *ReceiverExpr);
1670 bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
1672 //===--------------------------------------------------------------------===//
1673 // C99 6.8: Statements and Blocks.
1675 /// A SmallVector of statements, with stack size 32 (as that is the only one
1677 typedef SmallVector<Stmt*, 32> StmtVector;
1678 /// A SmallVector of expressions, with stack size 12 (the maximum used.)
1679 typedef SmallVector<Expr*, 12> ExprVector;
1680 /// A SmallVector of types.
1681 typedef SmallVector<ParsedType, 12> TypeVector;
1683 StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
1684 bool AllowOpenMPStandalone = false);
1685 enum AllowedContsructsKind {
1686 /// \brief Allow any declarations, statements, OpenMP directives.
1688 /// \brief Allow only statements and non-standalone OpenMP directives.
1689 ACK_StatementsOpenMPNonStandalone,
1690 /// \brief Allow statements and all executable OpenMP directives
1691 ACK_StatementsOpenMPAnyExecutable
1694 ParseStatementOrDeclaration(StmtVector &Stmts, AllowedContsructsKind Allowed,
1695 SourceLocation *TrailingElseLoc = nullptr);
1696 StmtResult ParseStatementOrDeclarationAfterAttributes(
1698 AllowedContsructsKind Allowed,
1699 SourceLocation *TrailingElseLoc,
1700 ParsedAttributesWithRange &Attrs);
1701 StmtResult ParseExprStatement();
1702 StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs);
1703 StmtResult ParseCaseStatement(bool MissingCase = false,
1704 ExprResult Expr = ExprResult());
1705 StmtResult ParseDefaultStatement();
1706 StmtResult ParseCompoundStatement(bool isStmtExpr = false);
1707 StmtResult ParseCompoundStatement(bool isStmtExpr,
1708 unsigned ScopeFlags);
1709 void ParseCompoundStatementLeadingPragmas();
1710 StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
1711 bool ParseParenExprOrCondition(StmtResult *InitStmt,
1712 Sema::ConditionResult &CondResult,
1714 Sema::ConditionKind CK);
1715 StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
1716 StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
1717 StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
1718 StmtResult ParseDoStatement();
1719 StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
1720 StmtResult ParseGotoStatement();
1721 StmtResult ParseContinueStatement();
1722 StmtResult ParseBreakStatement();
1723 StmtResult ParseReturnStatement();
1724 StmtResult ParseAsmStatement(bool &msAsm);
1725 StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
1726 StmtResult ParsePragmaLoopHint(StmtVector &Stmts,
1727 AllowedContsructsKind Allowed,
1728 SourceLocation *TrailingElseLoc,
1729 ParsedAttributesWithRange &Attrs);
1731 /// \brief Describes the behavior that should be taken for an __if_exists
1733 enum IfExistsBehavior {
1734 /// \brief Parse the block; this code is always used.
1736 /// \brief Skip the block entirely; this code is never used.
1738 /// \brief Parse the block as a dependent block, which may be used in
1739 /// some template instantiations but not others.
1743 /// \brief Describes the condition of a Microsoft __if_exists or
1744 /// __if_not_exists block.
1745 struct IfExistsCondition {
1746 /// \brief The location of the initial keyword.
1747 SourceLocation KeywordLoc;
1748 /// \brief Whether this is an __if_exists block (rather than an
1749 /// __if_not_exists block).
1752 /// \brief Nested-name-specifier preceding the name.
1755 /// \brief The name we're looking for.
1758 /// \brief The behavior of this __if_exists or __if_not_exists block
1760 IfExistsBehavior Behavior;
1763 bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
1764 void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
1765 void ParseMicrosoftIfExistsExternalDeclaration();
1766 void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
1767 AccessSpecifier& CurAS);
1768 bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
1770 bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
1771 SmallVectorImpl<Expr *> &Constraints,
1772 SmallVectorImpl<Expr *> &Exprs);
1774 //===--------------------------------------------------------------------===//
1775 // C++ 6: Statements and Blocks
1777 StmtResult ParseCXXTryBlock();
1778 StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
1779 StmtResult ParseCXXCatchBlock(bool FnCatch = false);
1781 //===--------------------------------------------------------------------===//
1782 // MS: SEH Statements and Blocks
1784 StmtResult ParseSEHTryBlock();
1785 StmtResult ParseSEHExceptBlock(SourceLocation Loc);
1786 StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
1787 StmtResult ParseSEHLeaveStatement();
1789 //===--------------------------------------------------------------------===//
1790 // Objective-C Statements
1792 StmtResult ParseObjCAtStatement(SourceLocation atLoc);
1793 StmtResult ParseObjCTryStmt(SourceLocation atLoc);
1794 StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
1795 StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
1796 StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
1799 //===--------------------------------------------------------------------===//
1800 // C99 6.7: Declarations.
1802 /// A context for parsing declaration specifiers. TODO: flesh this
1803 /// out, there are other significant restrictions on specifiers than
1804 /// would be best implemented in the parser.
1805 enum DeclSpecContext {
1806 DSC_normal, // normal context
1807 DSC_class, // class context, enables 'friend'
1808 DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
1809 DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
1810 DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration
1811 DSC_top_level, // top-level/namespace declaration context
1812 DSC_template_type_arg, // template type argument context
1813 DSC_objc_method_result, // ObjC method result context, enables 'instancetype'
1814 DSC_condition // condition declaration context
1817 /// Is this a context in which we are parsing just a type-specifier (or
1818 /// trailing-type-specifier)?
1819 static bool isTypeSpecifier(DeclSpecContext DSC) {
1824 case DSC_objc_method_result:
1828 case DSC_template_type_arg:
1829 case DSC_type_specifier:
1831 case DSC_alias_declaration:
1834 llvm_unreachable("Missing DeclSpecContext case");
1837 /// Information on a C++0x for-range-initializer found while parsing a
1838 /// declaration which turns out to be a for-range-declaration.
1839 struct ForRangeInit {
1840 SourceLocation ColonLoc;
1841 ExprResult RangeExpr;
1843 bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
1846 DeclGroupPtrTy ParseDeclaration(unsigned Context, SourceLocation &DeclEnd,
1847 ParsedAttributesWithRange &attrs);
1848 DeclGroupPtrTy ParseSimpleDeclaration(unsigned Context,
1849 SourceLocation &DeclEnd,
1850 ParsedAttributesWithRange &attrs,
1852 ForRangeInit *FRI = nullptr);
1853 bool MightBeDeclarator(unsigned Context);
1854 DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, unsigned Context,
1855 SourceLocation *DeclEnd = nullptr,
1856 ForRangeInit *FRI = nullptr);
1857 Decl *ParseDeclarationAfterDeclarator(Declarator &D,
1858 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
1859 bool ParseAsmAttributesAfterDeclarator(Declarator &D);
1860 Decl *ParseDeclarationAfterDeclaratorAndAttributes(
1862 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1863 ForRangeInit *FRI = nullptr);
1864 Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
1865 Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
1867 /// \brief When in code-completion, skip parsing of the function/method body
1868 /// unless the body contains the code-completion point.
1870 /// \returns true if the function body was skipped.
1871 bool trySkippingFunctionBody();
1873 bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
1874 const ParsedTemplateInfo &TemplateInfo,
1875 AccessSpecifier AS, DeclSpecContext DSC,
1876 ParsedAttributesWithRange &Attrs);
1877 DeclSpecContext getDeclSpecContextFromDeclaratorContext(unsigned Context);
1878 void ParseDeclarationSpecifiers(DeclSpec &DS,
1879 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1880 AccessSpecifier AS = AS_none,
1881 DeclSpecContext DSC = DSC_normal,
1882 LateParsedAttrList *LateAttrs = nullptr);
1883 bool DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
1884 DeclSpecContext DSContext,
1885 LateParsedAttrList *LateAttrs = nullptr);
1887 void ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS = AS_none,
1888 DeclSpecContext DSC = DSC_normal);
1890 void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
1891 Declarator::TheContext Context);
1893 void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
1894 const ParsedTemplateInfo &TemplateInfo,
1895 AccessSpecifier AS, DeclSpecContext DSC);
1896 void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
1897 void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType,
1900 void ParseStructDeclaration(
1901 ParsingDeclSpec &DS,
1902 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback);
1904 bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
1905 bool isTypeSpecifierQualifier();
1907 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
1908 /// is definitely a type-specifier. Return false if it isn't part of a type
1909 /// specifier or if we're not sure.
1910 bool isKnownToBeTypeSpecifier(const Token &Tok) const;
1912 /// \brief Return true if we know that we are definitely looking at a
1913 /// decl-specifier, and isn't part of an expression such as a function-style
1914 /// cast. Return false if it's no a decl-specifier, or we're not sure.
1915 bool isKnownToBeDeclarationSpecifier() {
1916 if (getLangOpts().CPlusPlus)
1917 return isCXXDeclarationSpecifier() == TPResult::True;
1918 return isDeclarationSpecifier(true);
1921 /// isDeclarationStatement - Disambiguates between a declaration or an
1922 /// expression statement, when parsing function bodies.
1923 /// Returns true for declaration, false for expression.
1924 bool isDeclarationStatement() {
1925 if (getLangOpts().CPlusPlus)
1926 return isCXXDeclarationStatement();
1927 return isDeclarationSpecifier(true);
1930 /// isForInitDeclaration - Disambiguates between a declaration or an
1931 /// expression in the context of the C 'clause-1' or the C++
1932 // 'for-init-statement' part of a 'for' statement.
1933 /// Returns true for declaration, false for expression.
1934 bool isForInitDeclaration() {
1935 if (getLangOpts().CPlusPlus)
1936 return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
1937 return isDeclarationSpecifier(true);
1940 /// \brief Determine whether this is a C++1z for-range-identifier.
1941 bool isForRangeIdentifier();
1943 /// \brief Determine whether we are currently at the start of an Objective-C
1944 /// class message that appears to be missing the open bracket '['.
1945 bool isStartOfObjCClassMessageMissingOpenBracket();
1947 /// \brief Starting with a scope specifier, identifier, or
1948 /// template-id that refers to the current class, determine whether
1949 /// this is a constructor declarator.
1950 bool isConstructorDeclarator(bool Unqualified);
1952 /// \brief Specifies the context in which type-id/expression
1953 /// disambiguation will occur.
1954 enum TentativeCXXTypeIdContext {
1957 TypeIdAsTemplateArgument
1961 /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
1962 /// whether the parens contain an expression or a type-id.
1963 /// Returns true for a type-id and false for an expression.
1964 bool isTypeIdInParens(bool &isAmbiguous) {
1965 if (getLangOpts().CPlusPlus)
1966 return isCXXTypeId(TypeIdInParens, isAmbiguous);
1967 isAmbiguous = false;
1968 return isTypeSpecifierQualifier();
1970 bool isTypeIdInParens() {
1972 return isTypeIdInParens(isAmbiguous);
1975 /// \brief Checks if the current tokens form type-id or expression.
1976 /// It is similar to isTypeIdInParens but does not suppose that type-id
1977 /// is in parenthesis.
1978 bool isTypeIdUnambiguously() {
1980 if (getLangOpts().CPlusPlus)
1981 return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous);
1982 return isTypeSpecifierQualifier();
1985 /// isCXXDeclarationStatement - C++-specialized function that disambiguates
1986 /// between a declaration or an expression statement, when parsing function
1987 /// bodies. Returns true for declaration, false for expression.
1988 bool isCXXDeclarationStatement();
1990 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
1991 /// between a simple-declaration or an expression-statement.
1992 /// If during the disambiguation process a parsing error is encountered,
1993 /// the function returns true to let the declaration parsing code handle it.
1994 /// Returns false if the statement is disambiguated as expression.
1995 bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
1997 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
1998 /// a constructor-style initializer, when parsing declaration statements.
1999 /// Returns true for function declarator and false for constructor-style
2000 /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
2001 /// might be a constructor-style initializer.
2002 /// If during the disambiguation process a parsing error is encountered,
2003 /// the function returns true to let the declaration parsing code handle it.
2004 bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr);
2006 struct ConditionDeclarationOrInitStatementState;
2007 enum class ConditionOrInitStatement {
2008 Expression, ///< Disambiguated as an expression (either kind).
2009 ConditionDecl, ///< Disambiguated as the declaration form of condition.
2010 InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement.
2011 Error ///< Can't be any of the above!
2013 /// \brief Disambiguates between the different kinds of things that can happen
2014 /// after 'if (' or 'switch ('. This could be one of two different kinds of
2015 /// declaration (depending on whether there is a ';' later) or an expression.
2016 ConditionOrInitStatement
2017 isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt);
2019 bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
2020 bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
2022 return isCXXTypeId(Context, isAmbiguous);
2025 /// TPResult - Used as the result value for functions whose purpose is to
2026 /// disambiguate C++ constructs by "tentatively parsing" them.
2027 enum class TPResult {
2028 True, False, Ambiguous, Error
2031 /// \brief Based only on the given token kind, determine whether we know that
2032 /// we're at the start of an expression or a type-specifier-seq (which may
2033 /// be an expression, in C++).
2035 /// This routine does not attempt to resolve any of the trick cases, e.g.,
2036 /// those involving lookup of identifiers.
2038 /// \returns \c TPR_true if this token starts an expression, \c TPR_false if
2039 /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot
2041 TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind);
2043 /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a
2044 /// declaration specifier, TPResult::False if it is not,
2045 /// TPResult::Ambiguous if it could be either a decl-specifier or a
2046 /// function-style cast, and TPResult::Error if a parsing error was
2047 /// encountered. If it could be a braced C++11 function-style cast, returns
2048 /// BracedCastResult.
2049 /// Doesn't consume tokens.
2051 isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False,
2052 bool *HasMissingTypename = nullptr);
2054 /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
2055 /// \c TPResult::Ambiguous, determine whether the decl-specifier would be
2056 /// a type-specifier other than a cv-qualifier.
2057 bool isCXXDeclarationSpecifierAType();
2059 /// \brief Determine whether an identifier has been tentatively declared as a
2060 /// non-type. Such tentative declarations should not be found to name a type
2061 /// during a tentative parse, but also should not be annotated as a non-type.
2062 bool isTentativelyDeclared(IdentifierInfo *II);
2064 // "Tentative parsing" functions, used for disambiguation. If a parsing error
2065 // is encountered they will return TPResult::Error.
2066 // Returning TPResult::True/False indicates that the ambiguity was
2067 // resolved and tentative parsing may stop. TPResult::Ambiguous indicates
2068 // that more tentative parsing is necessary for disambiguation.
2069 // They all consume tokens, so backtracking should be used after calling them.
2071 TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
2072 TPResult TryParseTypeofSpecifier();
2073 TPResult TryParseProtocolQualifiers();
2074 TPResult TryParsePtrOperatorSeq();
2075 TPResult TryParseOperatorId();
2076 TPResult TryParseInitDeclaratorList();
2077 TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier=true);
2079 TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr,
2080 bool VersusTemplateArg = false);
2081 TPResult TryParseFunctionDeclarator();
2082 TPResult TryParseBracketDeclarator();
2083 TPResult TryConsumeDeclarationSpecifier();
2086 TypeResult ParseTypeName(SourceRange *Range = nullptr,
2087 Declarator::TheContext Context
2088 = Declarator::TypeNameContext,
2089 AccessSpecifier AS = AS_none,
2090 Decl **OwnedType = nullptr,
2091 ParsedAttributes *Attrs = nullptr);
2094 void ParseBlockId(SourceLocation CaretLoc);
2096 // Check for the start of a C++11 attribute-specifier-seq in a context where
2097 // an attribute is not allowed.
2098 bool CheckProhibitedCXX11Attribute() {
2099 assert(Tok.is(tok::l_square));
2100 if (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))
2102 return DiagnoseProhibitedCXX11Attribute();
2104 bool DiagnoseProhibitedCXX11Attribute();
2105 void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2106 SourceLocation CorrectLocation) {
2107 if (!getLangOpts().CPlusPlus11)
2109 if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
2110 Tok.isNot(tok::kw_alignas))
2112 DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
2114 void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2115 SourceLocation CorrectLocation);
2117 void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
2118 DeclSpec &DS, Sema::TagUseKind TUK);
2120 void ProhibitAttributes(ParsedAttributesWithRange &attrs) {
2121 if (!attrs.Range.isValid()) return;
2122 DiagnoseProhibitedAttributes(attrs);
2125 void DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs);
2127 // Forbid C++11 attributes that appear on certain syntactic
2128 // locations which standard permits but we don't supported yet,
2129 // for example, attributes appertain to decl specifiers.
2130 void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
2133 /// \brief Skip C++11 attributes and return the end location of the last one.
2134 /// \returns SourceLocation() if there are no attributes.
2135 SourceLocation SkipCXX11Attributes();
2137 /// \brief Diagnose and skip C++11 attributes that appear in syntactic
2138 /// locations where attributes are not allowed.
2139 void DiagnoseAndSkipCXX11Attributes();
2141 /// \brief Parses syntax-generic attribute arguments for attributes which are
2142 /// known to the implementation, and adds them to the given ParsedAttributes
2143 /// list with the given attribute syntax. Returns the number of arguments
2144 /// parsed for the attribute.
2146 ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2147 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2148 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2149 AttributeList::Syntax Syntax);
2151 void MaybeParseGNUAttributes(Declarator &D,
2152 LateParsedAttrList *LateAttrs = nullptr) {
2153 if (Tok.is(tok::kw___attribute)) {
2154 ParsedAttributes attrs(AttrFactory);
2155 SourceLocation endLoc;
2156 ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D);
2157 D.takeAttributes(attrs, endLoc);
2160 void MaybeParseGNUAttributes(ParsedAttributes &attrs,
2161 SourceLocation *endLoc = nullptr,
2162 LateParsedAttrList *LateAttrs = nullptr) {
2163 if (Tok.is(tok::kw___attribute))
2164 ParseGNUAttributes(attrs, endLoc, LateAttrs);
2166 void ParseGNUAttributes(ParsedAttributes &attrs,
2167 SourceLocation *endLoc = nullptr,
2168 LateParsedAttrList *LateAttrs = nullptr,
2169 Declarator *D = nullptr);
2170 void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
2171 SourceLocation AttrNameLoc,
2172 ParsedAttributes &Attrs,
2173 SourceLocation *EndLoc,
2174 IdentifierInfo *ScopeName,
2175 SourceLocation ScopeLoc,
2176 AttributeList::Syntax Syntax,
2178 IdentifierLoc *ParseIdentifierLoc();
2180 void MaybeParseCXX11Attributes(Declarator &D) {
2181 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
2182 ParsedAttributesWithRange attrs(AttrFactory);
2183 SourceLocation endLoc;
2184 ParseCXX11Attributes(attrs, &endLoc);
2185 D.takeAttributes(attrs, endLoc);
2188 void MaybeParseCXX11Attributes(ParsedAttributes &attrs,
2189 SourceLocation *endLoc = nullptr) {
2190 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
2191 ParsedAttributesWithRange attrsWithRange(AttrFactory);
2192 ParseCXX11Attributes(attrsWithRange, endLoc);
2193 attrs.takeAllFrom(attrsWithRange);
2196 void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2197 SourceLocation *endLoc = nullptr,
2198 bool OuterMightBeMessageSend = false) {
2199 if (getLangOpts().CPlusPlus11 &&
2200 isCXX11AttributeSpecifier(false, OuterMightBeMessageSend))
2201 ParseCXX11Attributes(attrs, endLoc);
2204 void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
2205 SourceLocation *EndLoc = nullptr);
2206 void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2207 SourceLocation *EndLoc = nullptr);
2208 /// \brief Parses a C++-style attribute argument list. Returns true if this
2209 /// results in adding an attribute to the ParsedAttributes list.
2210 bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
2211 SourceLocation AttrNameLoc,
2212 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2213 IdentifierInfo *ScopeName,
2214 SourceLocation ScopeLoc);
2216 IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc);
2218 void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
2219 SourceLocation *endLoc = nullptr) {
2220 if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
2221 ParseMicrosoftAttributes(attrs, endLoc);
2223 void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs);
2224 void ParseMicrosoftAttributes(ParsedAttributes &attrs,
2225 SourceLocation *endLoc = nullptr);
2226 void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2227 SourceLocation *End = nullptr) {
2228 const auto &LO = getLangOpts();
2229 if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec))
2230 ParseMicrosoftDeclSpecs(Attrs, End);
2232 void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2233 SourceLocation *End = nullptr);
2234 bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
2235 SourceLocation AttrNameLoc,
2236 ParsedAttributes &Attrs);
2237 void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
2238 void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2239 SourceLocation SkipExtendedMicrosoftTypeAttributes();
2240 void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
2241 void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
2242 void ParseOpenCLKernelAttributes(ParsedAttributes &attrs);
2243 void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
2244 /// \brief Parses opencl_unroll_hint attribute if language is OpenCL v2.0
2246 /// \return false if error happens.
2247 bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
2248 if (getLangOpts().OpenCL)
2249 return ParseOpenCLUnrollHintAttribute(Attrs);
2252 /// \brief Parses opencl_unroll_hint attribute.
2253 /// \return false if error happens.
2254 bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs);
2255 void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
2257 VersionTuple ParseVersionTuple(SourceRange &Range);
2258 void ParseAvailabilityAttribute(IdentifierInfo &Availability,
2259 SourceLocation AvailabilityLoc,
2260 ParsedAttributes &attrs,
2261 SourceLocation *endLoc,
2262 IdentifierInfo *ScopeName,
2263 SourceLocation ScopeLoc,
2264 AttributeList::Syntax Syntax);
2266 Optional<AvailabilitySpec> ParseAvailabilitySpec();
2267 ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc);
2269 void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
2270 SourceLocation ObjCBridgeRelatedLoc,
2271 ParsedAttributes &attrs,
2272 SourceLocation *endLoc,
2273 IdentifierInfo *ScopeName,
2274 SourceLocation ScopeLoc,
2275 AttributeList::Syntax Syntax);
2277 void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
2278 SourceLocation AttrNameLoc,
2279 ParsedAttributes &Attrs,
2280 SourceLocation *EndLoc,
2281 IdentifierInfo *ScopeName,
2282 SourceLocation ScopeLoc,
2283 AttributeList::Syntax Syntax);
2285 void ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
2286 SourceLocation AttrNameLoc,
2287 ParsedAttributes &Attrs,
2288 SourceLocation *EndLoc,
2289 IdentifierInfo *ScopeName,
2290 SourceLocation ScopeLoc,
2291 AttributeList::Syntax Syntax);
2293 void ParseTypeofSpecifier(DeclSpec &DS);
2294 SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
2295 void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
2296 SourceLocation StartLoc,
2297 SourceLocation EndLoc);
2298 void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
2299 void ParseAtomicSpecifier(DeclSpec &DS);
2301 ExprResult ParseAlignArgument(SourceLocation Start,
2302 SourceLocation &EllipsisLoc);
2303 void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2304 SourceLocation *endLoc = nullptr);
2306 VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
2307 VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
2308 return isCXX11VirtSpecifier(Tok);
2310 void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface,
2311 SourceLocation FriendLoc);
2313 bool isCXX11FinalKeyword() const;
2315 /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
2316 /// enter a new C++ declarator scope and exit it when the function is
2318 class DeclaratorScopeObj {
2324 DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
2325 : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
2327 void EnterDeclaratorScope() {
2328 assert(!EnteredScope && "Already entered the scope!");
2329 assert(SS.isSet() && "C++ scope was not set!");
2331 CreatedScope = true;
2332 P.EnterScope(0); // Not a decl scope.
2334 if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
2335 EnteredScope = true;
2338 ~DeclaratorScopeObj() {
2340 assert(SS.isSet() && "C++ scope was cleared ?");
2341 P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
2348 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
2349 void ParseDeclarator(Declarator &D);
2350 /// A function that parses a variant of direct-declarator.
2351 typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
2352 void ParseDeclaratorInternal(Declarator &D,
2353 DirectDeclParseFunction DirectDeclParser);
2355 enum AttrRequirements {
2356 AR_NoAttributesParsed = 0, ///< No attributes are diagnosed.
2357 AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes.
2358 AR_GNUAttributesParsed = 1 << 1,
2359 AR_CXX11AttributesParsed = 1 << 2,
2360 AR_DeclspecAttributesParsed = 1 << 3,
2361 AR_AllAttributesParsed = AR_GNUAttributesParsed |
2362 AR_CXX11AttributesParsed |
2363 AR_DeclspecAttributesParsed,
2364 AR_VendorAttributesParsed = AR_GNUAttributesParsed |
2365 AR_DeclspecAttributesParsed
2368 void ParseTypeQualifierListOpt(DeclSpec &DS,
2369 unsigned AttrReqs = AR_AllAttributesParsed,
2370 bool AtomicAllowed = true,
2371 bool IdentifierRequired = false);
2372 void ParseDirectDeclarator(Declarator &D);
2373 void ParseDecompositionDeclarator(Declarator &D);
2374 void ParseParenDeclarator(Declarator &D);
2375 void ParseFunctionDeclarator(Declarator &D,
2376 ParsedAttributes &attrs,
2377 BalancedDelimiterTracker &Tracker,
2379 bool RequiresArg = false);
2380 bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
2381 SourceLocation &RefQualifierLoc);
2382 bool isFunctionDeclaratorIdentifierList();
2383 void ParseFunctionDeclaratorIdentifierList(
2385 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
2386 void ParseParameterDeclarationClause(
2388 ParsedAttributes &attrs,
2389 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
2390 SourceLocation &EllipsisLoc);
2391 void ParseBracketDeclarator(Declarator &D);
2392 void ParseMisplacedBracketDeclarator(Declarator &D);
2394 //===--------------------------------------------------------------------===//
2395 // C++ 7: Declarations [dcl.dcl]
2397 /// The kind of attribute specifier we have found.
2398 enum CXX11AttributeKind {
2399 /// This is not an attribute specifier.
2400 CAK_NotAttributeSpecifier,
2401 /// This should be treated as an attribute-specifier.
2402 CAK_AttributeSpecifier,
2403 /// The next tokens are '[[', but this is not an attribute-specifier. This
2404 /// is ill-formed by C++11 [dcl.attr.grammar]p6.
2405 CAK_InvalidAttributeSpecifier
2408 isCXX11AttributeSpecifier(bool Disambiguate = false,
2409 bool OuterMightBeMessageSend = false);
2411 void DiagnoseUnexpectedNamespace(NamedDecl *Context);
2413 DeclGroupPtrTy ParseNamespace(unsigned Context, SourceLocation &DeclEnd,
2414 SourceLocation InlineLoc = SourceLocation());
2415 void ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc,
2416 std::vector<IdentifierInfo*>& Ident,
2417 std::vector<SourceLocation>& NamespaceLoc,
2418 unsigned int index, SourceLocation& InlineLoc,
2419 ParsedAttributes& attrs,
2420 BalancedDelimiterTracker &Tracker);
2421 Decl *ParseLinkage(ParsingDeclSpec &DS, unsigned Context);
2422 Decl *ParseExportDeclaration();
2423 DeclGroupPtrTy ParseUsingDirectiveOrDeclaration(
2424 unsigned Context, const ParsedTemplateInfo &TemplateInfo,
2425 SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs);
2426 Decl *ParseUsingDirective(unsigned Context,
2427 SourceLocation UsingLoc,
2428 SourceLocation &DeclEnd,
2429 ParsedAttributes &attrs);
2431 struct UsingDeclarator {
2432 SourceLocation TypenameLoc;
2434 SourceLocation TemplateKWLoc;
2436 SourceLocation EllipsisLoc;
2439 TypenameLoc = TemplateKWLoc = EllipsisLoc = SourceLocation();
2445 bool ParseUsingDeclarator(unsigned Context, UsingDeclarator &D);
2446 DeclGroupPtrTy ParseUsingDeclaration(unsigned Context,
2447 const ParsedTemplateInfo &TemplateInfo,
2448 SourceLocation UsingLoc,
2449 SourceLocation &DeclEnd,
2450 AccessSpecifier AS = AS_none);
2451 Decl *ParseAliasDeclarationAfterDeclarator(
2452 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
2453 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
2454 ParsedAttributes &Attrs, Decl **OwnedType = nullptr);
2456 Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
2457 Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
2458 SourceLocation AliasLoc, IdentifierInfo *Alias,
2459 SourceLocation &DeclEnd);
2461 //===--------------------------------------------------------------------===//
2462 // C++ 9: classes [class] and C structs/unions.
2463 bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
2464 void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
2465 DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo,
2466 AccessSpecifier AS, bool EnteringContext,
2467 DeclSpecContext DSC,
2468 ParsedAttributesWithRange &Attributes);
2469 void SkipCXXMemberSpecification(SourceLocation StartLoc,
2470 SourceLocation AttrFixitLoc,
2473 void ParseCXXMemberSpecification(SourceLocation StartLoc,
2474 SourceLocation AttrFixitLoc,
2475 ParsedAttributesWithRange &Attrs,
2478 ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2479 SourceLocation &EqualLoc);
2480 bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
2482 ExprResult &BitfieldSize,
2483 LateParsedAttrList &LateAttrs);
2484 void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D,
2485 VirtSpecifiers &VS);
2486 DeclGroupPtrTy ParseCXXClassMemberDeclaration(
2487 AccessSpecifier AS, AttributeList *Attr,
2488 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2489 ParsingDeclRAIIObject *DiagsFromTParams = nullptr);
2490 DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas(
2491 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
2492 DeclSpec::TST TagType, Decl *Tag);
2493 void ParseConstructorInitializer(Decl *ConstructorDecl);
2494 MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
2495 void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2498 //===--------------------------------------------------------------------===//
2499 // C++ 10: Derived classes [class.derived]
2500 TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
2501 SourceLocation &EndLocation);
2502 void ParseBaseClause(Decl *ClassDecl);
2503 BaseResult ParseBaseSpecifier(Decl *ClassDecl);
2504 AccessSpecifier getAccessSpecifierIfPresent() const;
2506 bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
2507 SourceLocation TemplateKWLoc,
2508 IdentifierInfo *Name,
2509 SourceLocation NameLoc,
2510 bool EnteringContext,
2511 ParsedType ObjectType,
2513 bool AssumeTemplateId);
2514 bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2515 ParsedType ObjectType,
2516 UnqualifiedId &Result);
2518 //===--------------------------------------------------------------------===//
2519 // OpenMP: Directives and clauses.
2520 /// Parse clauses for '#pragma omp declare simd'.
2521 DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr,
2523 SourceLocation Loc);
2524 /// \brief Parses declarative OpenMP directives.
2525 DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl(
2526 AccessSpecifier &AS, ParsedAttributesWithRange &Attrs,
2527 DeclSpec::TST TagType = DeclSpec::TST_unspecified,
2528 Decl *TagDecl = nullptr);
2529 /// \brief Parse 'omp declare reduction' construct.
2530 DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS);
2532 /// \brief Parses simple list of variables.
2534 /// \param Kind Kind of the directive.
2535 /// \param Callback Callback function to be called for the list elements.
2536 /// \param AllowScopeSpecifier true, if the variables can have fully
2537 /// qualified names.
2539 bool ParseOpenMPSimpleVarList(
2540 OpenMPDirectiveKind Kind,
2541 const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
2543 bool AllowScopeSpecifier);
2544 /// \brief Parses declarative or executable directive.
2546 /// \param Allowed ACK_Any, if any directives are allowed,
2547 /// ACK_StatementsOpenMPAnyExecutable - if any executable directives are
2548 /// allowed, ACK_StatementsOpenMPNonStandalone - if only non-standalone
2549 /// executable directives are allowed.
2552 ParseOpenMPDeclarativeOrExecutableDirective(AllowedContsructsKind Allowed);
2553 /// \brief Parses clause of kind \a CKind for directive of a kind \a Kind.
2555 /// \param DKind Kind of current directive.
2556 /// \param CKind Kind of current clause.
2557 /// \param FirstClause true, if this is the first clause of a kind \a CKind
2558 /// in current directive.
2560 OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
2561 OpenMPClauseKind CKind, bool FirstClause);
2562 /// \brief Parses clause with a single expression of a kind \a Kind.
2564 /// \param Kind Kind of current clause.
2566 OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind);
2567 /// \brief Parses simple clause of a kind \a Kind.
2569 /// \param Kind Kind of current clause.
2571 OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind);
2572 /// \brief Parses clause with a single expression and an additional argument
2573 /// of a kind \a Kind.
2575 /// \param Kind Kind of current clause.
2577 OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind);
2578 /// \brief Parses clause without any additional arguments.
2580 /// \param Kind Kind of current clause.
2582 OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind);
2583 /// \brief Parses clause with the list of variables of a kind \a Kind.
2585 /// \param Kind Kind of current clause.
2587 OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
2588 OpenMPClauseKind Kind);
2591 /// Parses simple expression in parens for single-expression clauses of OpenMP
2593 /// \param RLoc Returned location of right paren.
2594 ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc);
2596 /// Data used for parsing list of variables in OpenMP clauses.
2597 struct OpenMPVarListDataTy {
2598 Expr *TailExpr = nullptr;
2599 SourceLocation ColonLoc;
2600 CXXScopeSpec ReductionIdScopeSpec;
2601 DeclarationNameInfo ReductionId;
2602 OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown;
2603 OpenMPLinearClauseKind LinKind = OMPC_LINEAR_val;
2604 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
2605 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
2606 bool IsMapTypeImplicit = false;
2607 SourceLocation DepLinMapLoc;
2610 /// Parses clauses with list.
2611 bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind,
2612 SmallVectorImpl<Expr *> &Vars,
2613 OpenMPVarListDataTy &Data);
2614 bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2615 bool AllowDestructorName,
2616 bool AllowConstructorName,
2617 ParsedType ObjectType,
2618 SourceLocation& TemplateKWLoc,
2619 UnqualifiedId &Result);
2622 //===--------------------------------------------------------------------===//
2623 // C++ 14: Templates [temp]
2625 // C++ 14.1: Template Parameters [temp.param]
2626 Decl *ParseDeclarationStartingWithTemplate(unsigned Context,
2627 SourceLocation &DeclEnd,
2628 AccessSpecifier AS = AS_none,
2629 AttributeList *AccessAttrs = nullptr);
2630 Decl *ParseTemplateDeclarationOrSpecialization(unsigned Context,
2631 SourceLocation &DeclEnd,
2633 AttributeList *AccessAttrs);
2634 Decl *ParseSingleDeclarationAfterTemplate(
2636 const ParsedTemplateInfo &TemplateInfo,
2637 ParsingDeclRAIIObject &DiagsFromParams,
2638 SourceLocation &DeclEnd,
2639 AccessSpecifier AS=AS_none,
2640 AttributeList *AccessAttrs = nullptr);
2641 bool ParseTemplateParameters(unsigned Depth,
2642 SmallVectorImpl<Decl*> &TemplateParams,
2643 SourceLocation &LAngleLoc,
2644 SourceLocation &RAngleLoc);
2645 bool ParseTemplateParameterList(unsigned Depth,
2646 SmallVectorImpl<Decl*> &TemplateParams);
2647 bool isStartOfTemplateTypeParameter();
2648 Decl *ParseTemplateParameter(unsigned Depth, unsigned Position);
2649 Decl *ParseTypeParameter(unsigned Depth, unsigned Position);
2650 Decl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
2651 Decl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
2652 void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
2653 SourceLocation CorrectLoc,
2654 bool AlreadyHasEllipsis,
2655 bool IdentifierHasName);
2656 void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
2658 // C++ 14.3: Template arguments [temp.arg]
2659 typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
2661 bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
2662 bool ConsumeLastToken,
2663 bool ObjCGenericList);
2664 bool ParseTemplateIdAfterTemplateName(TemplateTy Template,
2665 SourceLocation TemplateNameLoc,
2666 const CXXScopeSpec &SS,
2667 bool ConsumeLastToken,
2668 SourceLocation &LAngleLoc,
2669 TemplateArgList &TemplateArgs,
2670 SourceLocation &RAngleLoc);
2672 bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
2674 SourceLocation TemplateKWLoc,
2675 UnqualifiedId &TemplateName,
2676 bool AllowTypeAnnotation = true);
2677 void AnnotateTemplateIdTokenAsType();
2678 bool IsTemplateArgumentList(unsigned Skip = 0);
2679 bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
2680 ParsedTemplateArgument ParseTemplateTemplateArgument();
2681 ParsedTemplateArgument ParseTemplateArgument();
2682 Decl *ParseExplicitInstantiation(unsigned Context,
2683 SourceLocation ExternLoc,
2684 SourceLocation TemplateLoc,
2685 SourceLocation &DeclEnd,
2686 AccessSpecifier AS = AS_none);
2688 //===--------------------------------------------------------------------===//
2690 DeclGroupPtrTy ParseModuleDecl();
2691 DeclGroupPtrTy ParseModuleImport(SourceLocation AtLoc);
2692 bool parseMisplacedModuleImport();
2693 bool tryParseMisplacedModuleImport() {
2694 tok::TokenKind Kind = Tok.getKind();
2695 if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end ||
2696 Kind == tok::annot_module_include)
2697 return parseMisplacedModuleImport();
2701 bool ParseModuleName(
2702 SourceLocation UseLoc,
2703 SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
2706 //===--------------------------------------------------------------------===//
2707 // C++11/G++: Type Traits [Type-Traits.html in the GCC manual]
2708 ExprResult ParseTypeTrait();
2710 //===--------------------------------------------------------------------===//
2711 // Embarcadero: Arary and Expression Traits
2712 ExprResult ParseArrayTypeTrait();
2713 ExprResult ParseExpressionTrait();
2715 //===--------------------------------------------------------------------===//
2716 // Preprocessor code-completion pass-through
2717 void CodeCompleteDirective(bool InConditional) override;
2718 void CodeCompleteInConditionalExclusion() override;
2719 void CodeCompleteMacroName(bool IsDefinition) override;
2720 void CodeCompletePreprocessorExpression() override;
2721 void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo,
2722 unsigned ArgumentIndex) override;
2723 void CodeCompleteNaturalLanguage() override;
2726 } // end namespace clang