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/OpenMPClause.h"
18 #include "clang/AST/Availability.h"
19 #include "clang/Basic/BitmaskEnum.h"
20 #include "clang/Basic/OpenMPKinds.h"
21 #include "clang/Basic/OperatorPrecedence.h"
22 #include "clang/Basic/Specifiers.h"
23 #include "clang/Lex/CodeCompletionHandler.h"
24 #include "clang/Lex/Preprocessor.h"
25 #include "clang/Sema/DeclSpec.h"
26 #include "clang/Sema/Sema.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Support/PrettyStackTrace.h"
30 #include "llvm/Support/SaveAndRestore.h"
37 class BalancedDelimiterTracker;
38 class CorrectionCandidateCallback;
40 class DiagnosticBuilder;
43 class ParsingDeclRAIIObject;
44 class ParsingDeclSpec;
45 class ParsingDeclarator;
46 class ParsingFieldDeclarator;
47 class ColonProtectionRAIIObject;
48 class InMessageExpressionRAIIObject;
49 class PoisonSEHIdentifiersRAIIObject;
51 class ObjCTypeParamList;
52 class ObjCTypeParameter;
54 /// Parser - This implements a parser for the C family of languages. After
55 /// parsing units of the grammar, productions are invoked to handle whatever has
58 class Parser : public CodeCompletionHandler {
59 friend class ColonProtectionRAIIObject;
60 friend class InMessageExpressionRAIIObject;
61 friend class PoisonSEHIdentifiersRAIIObject;
62 friend class ObjCDeclContextSwitch;
63 friend class ParenBraceBracketBalancer;
64 friend class BalancedDelimiterTracker;
68 /// Tok - The current token we are peeking ahead. All parsing methods assume
69 /// that this is valid.
72 // PrevTokLocation - The location of the token we previously
73 // consumed. This token is used for diagnostics where we expected to
74 // see a token following another token (e.g., the ';' at the end of
76 SourceLocation PrevTokLocation;
78 unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0;
79 unsigned short MisplacedModuleBeginCount = 0;
81 /// Actions - These are the callbacks we invoke as we parse various constructs
85 DiagnosticsEngine &Diags;
87 /// ScopeCache - Cache scopes to reduce malloc traffic.
88 enum { ScopeCacheSize = 16 };
89 unsigned NumCachedScopes;
90 Scope *ScopeCache[ScopeCacheSize];
92 /// Identifiers used for SEH handling in Borland. These are only
93 /// allowed in particular circumstances
95 IdentifierInfo *Ident__exception_code,
96 *Ident___exception_code,
97 *Ident_GetExceptionCode;
98 // __except filter expression
99 IdentifierInfo *Ident__exception_info,
100 *Ident___exception_info,
101 *Ident_GetExceptionInfo;
103 IdentifierInfo *Ident__abnormal_termination,
104 *Ident___abnormal_termination,
105 *Ident_AbnormalTermination;
107 /// Contextual keywords for Microsoft extensions.
108 IdentifierInfo *Ident__except;
109 mutable IdentifierInfo *Ident_sealed;
111 /// Ident_super - IdentifierInfo for "super", to support fast
113 IdentifierInfo *Ident_super;
114 /// Ident_vector, Ident_bool - cached IdentifierInfos for "vector" and
115 /// "bool" fast comparison. Only present if AltiVec or ZVector are enabled.
116 IdentifierInfo *Ident_vector;
117 IdentifierInfo *Ident_bool;
118 /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison.
119 /// Only present if AltiVec enabled.
120 IdentifierInfo *Ident_pixel;
122 /// Objective-C contextual keywords.
123 IdentifierInfo *Ident_instancetype;
125 /// Identifier for "introduced".
126 IdentifierInfo *Ident_introduced;
128 /// Identifier for "deprecated".
129 IdentifierInfo *Ident_deprecated;
131 /// Identifier for "obsoleted".
132 IdentifierInfo *Ident_obsoleted;
134 /// Identifier for "unavailable".
135 IdentifierInfo *Ident_unavailable;
137 /// Identifier for "message".
138 IdentifierInfo *Ident_message;
140 /// Identifier for "strict".
141 IdentifierInfo *Ident_strict;
143 /// Identifier for "replacement".
144 IdentifierInfo *Ident_replacement;
146 /// Identifiers used by the 'external_source_symbol' attribute.
147 IdentifierInfo *Ident_language, *Ident_defined_in,
148 *Ident_generated_declaration;
150 /// C++0x contextual keywords.
151 mutable IdentifierInfo *Ident_final;
152 mutable IdentifierInfo *Ident_GNU_final;
153 mutable IdentifierInfo *Ident_override;
155 // C++ type trait keywords that can be reverted to identifiers and still be
156 // used as type traits.
157 llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits;
159 std::unique_ptr<PragmaHandler> AlignHandler;
160 std::unique_ptr<PragmaHandler> GCCVisibilityHandler;
161 std::unique_ptr<PragmaHandler> OptionsHandler;
162 std::unique_ptr<PragmaHandler> PackHandler;
163 std::unique_ptr<PragmaHandler> MSStructHandler;
164 std::unique_ptr<PragmaHandler> UnusedHandler;
165 std::unique_ptr<PragmaHandler> WeakHandler;
166 std::unique_ptr<PragmaHandler> RedefineExtnameHandler;
167 std::unique_ptr<PragmaHandler> FPContractHandler;
168 std::unique_ptr<PragmaHandler> OpenCLExtensionHandler;
169 std::unique_ptr<PragmaHandler> OpenMPHandler;
170 std::unique_ptr<PragmaHandler> PCSectionHandler;
171 std::unique_ptr<PragmaHandler> MSCommentHandler;
172 std::unique_ptr<PragmaHandler> MSDetectMismatchHandler;
173 std::unique_ptr<PragmaHandler> MSPointersToMembers;
174 std::unique_ptr<PragmaHandler> MSVtorDisp;
175 std::unique_ptr<PragmaHandler> MSInitSeg;
176 std::unique_ptr<PragmaHandler> MSDataSeg;
177 std::unique_ptr<PragmaHandler> MSBSSSeg;
178 std::unique_ptr<PragmaHandler> MSConstSeg;
179 std::unique_ptr<PragmaHandler> MSCodeSeg;
180 std::unique_ptr<PragmaHandler> MSSection;
181 std::unique_ptr<PragmaHandler> MSRuntimeChecks;
182 std::unique_ptr<PragmaHandler> MSIntrinsic;
183 std::unique_ptr<PragmaHandler> MSOptimize;
184 std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler;
185 std::unique_ptr<PragmaHandler> OptimizeHandler;
186 std::unique_ptr<PragmaHandler> LoopHintHandler;
187 std::unique_ptr<PragmaHandler> UnrollHintHandler;
188 std::unique_ptr<PragmaHandler> NoUnrollHintHandler;
189 std::unique_ptr<PragmaHandler> UnrollAndJamHintHandler;
190 std::unique_ptr<PragmaHandler> NoUnrollAndJamHintHandler;
191 std::unique_ptr<PragmaHandler> FPHandler;
192 std::unique_ptr<PragmaHandler> STDCFENVHandler;
193 std::unique_ptr<PragmaHandler> STDCCXLIMITHandler;
194 std::unique_ptr<PragmaHandler> STDCUnknownHandler;
195 std::unique_ptr<PragmaHandler> AttributePragmaHandler;
197 std::unique_ptr<CommentHandler> CommentSemaHandler;
199 /// Whether the '>' token acts as an operator or not. This will be
200 /// true except when we are parsing an expression within a C++
201 /// template argument list, where the '>' closes the template
203 bool GreaterThanIsOperator;
205 /// ColonIsSacred - When this is false, we aggressively try to recover from
206 /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not
207 /// safe in case statements and a few other things. This is managed by the
208 /// ColonProtectionRAIIObject RAII object.
211 /// When true, we are directly inside an Objective-C message
214 /// This is managed by the \c InMessageExpressionRAIIObject class, and
215 /// should not be set directly.
216 bool InMessageExpression;
218 /// Gets set to true after calling ProduceSignatureHelp, it is for a
219 /// workaround to make sure ProduceSignatureHelp is only called at the deepest
221 bool CalledSignatureHelp = false;
223 /// The "depth" of the template parameters currently being parsed.
224 unsigned TemplateParameterDepth;
226 /// RAII class that manages the template parameter depth.
227 class TemplateParameterDepthRAII {
229 unsigned AddedLevels;
231 explicit TemplateParameterDepthRAII(unsigned &Depth)
232 : Depth(Depth), AddedLevels(0) {}
234 ~TemplateParameterDepthRAII() {
235 Depth -= AddedLevels;
242 void addDepth(unsigned D) {
246 unsigned getDepth() const { return Depth; }
249 /// Factory object for creating ParsedAttr objects.
250 AttributeFactory AttrFactory;
252 /// Gathers and cleans up TemplateIdAnnotations when parsing of a
253 /// top-level declaration is finished.
254 SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
256 /// Identifiers which have been declared within a tentative parse.
257 SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers;
259 /// Tracker for '<' tokens that might have been intended to be treated as an
260 /// angle bracket instead of a less-than comparison.
262 /// This happens when the user intends to form a template-id, but typoes the
263 /// template-name or forgets a 'template' keyword for a dependent template
266 /// We track these locations from the point where we see a '<' with a
267 /// name-like expression on its left until we see a '>' or '>>' that might
269 struct AngleBracketTracker {
270 /// Flags used to rank candidate template names when there is more than one
272 enum Priority : unsigned short {
273 /// A non-dependent name that is a potential typo for a template name.
275 /// A dependent name that might instantiate to a template-name.
278 /// A space appears before the '<' token.
279 SpaceBeforeLess = 0x0,
280 /// No space before the '<' token
281 NoSpaceBeforeLess = 0x1,
283 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue*/ DependentName)
288 SourceLocation LessLoc;
289 AngleBracketTracker::Priority Priority;
290 unsigned short ParenCount, BracketCount, BraceCount;
292 bool isActive(Parser &P) const {
293 return P.ParenCount == ParenCount && P.BracketCount == BracketCount &&
294 P.BraceCount == BraceCount;
297 bool isActiveOrNested(Parser &P) const {
298 return isActive(P) || P.ParenCount > ParenCount ||
299 P.BracketCount > BracketCount || P.BraceCount > BraceCount;
303 SmallVector<Loc, 8> Locs;
305 /// Add an expression that might have been intended to be a template name.
306 /// In the case of ambiguity, we arbitrarily select the innermost such
307 /// expression, for example in 'foo < bar < baz', 'bar' is the current
308 /// candidate. No attempt is made to track that 'foo' is also a candidate
309 /// for the case where we see a second suspicious '>' token.
310 void add(Parser &P, Expr *TemplateName, SourceLocation LessLoc,
312 if (!Locs.empty() && Locs.back().isActive(P)) {
313 if (Locs.back().Priority <= Prio) {
314 Locs.back().TemplateName = TemplateName;
315 Locs.back().LessLoc = LessLoc;
316 Locs.back().Priority = Prio;
319 Locs.push_back({TemplateName, LessLoc, Prio,
320 P.ParenCount, P.BracketCount, P.BraceCount});
324 /// Mark the current potential missing template location as having been
325 /// handled (this happens if we pass a "corresponding" '>' or '>>' token
326 /// or leave a bracket scope).
327 void clear(Parser &P) {
328 while (!Locs.empty() && Locs.back().isActiveOrNested(P))
332 /// Get the current enclosing expression that might hve been intended to be
334 Loc *getCurrent(Parser &P) {
335 if (!Locs.empty() && Locs.back().isActive(P))
341 AngleBracketTracker AngleBrackets;
343 IdentifierInfo *getSEHExceptKeyword();
345 /// True if we are within an Objective-C container while parsing C-like decls.
347 /// This is necessary because Sema thinks we have left the container
348 /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will
350 bool ParsingInObjCContainer;
352 /// Whether to skip parsing of function bodies.
354 /// This option can be used, for example, to speed up searches for
355 /// declarations/definitions when indexing.
356 bool SkipFunctionBodies;
358 /// The location of the expression statement that is being parsed right now.
359 /// Used to determine if an expression that is being parsed is a statement or
360 /// just a regular sub-expression.
361 SourceLocation ExprStatementTokLoc;
364 Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
367 const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
368 const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
369 Preprocessor &getPreprocessor() const { return PP; }
370 Sema &getActions() const { return Actions; }
371 AttributeFactory &getAttrFactory() { return AttrFactory; }
373 const Token &getCurToken() const { return Tok; }
374 Scope *getCurScope() const { return Actions.getCurScope(); }
375 void incrementMSManglingNumber() const {
376 return Actions.incrementMSManglingNumber();
379 Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); }
381 // Type forwarding. All of these are statically 'void*', but they may all be
382 // different actual classes based on the actions in place.
383 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
384 typedef OpaquePtr<TemplateName> TemplateTy;
386 typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists;
388 typedef Sema::FullExprArg FullExprArg;
392 /// Initialize - Warm up the parser.
396 /// Parse the first top-level declaration in a translation unit.
397 bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result);
399 /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if
400 /// the EOF was encountered.
401 bool ParseTopLevelDecl(DeclGroupPtrTy &Result);
402 bool ParseTopLevelDecl() {
403 DeclGroupPtrTy Result;
404 return ParseTopLevelDecl(Result);
407 /// ConsumeToken - Consume the current 'peek token' and lex the next one.
408 /// This does not work with special tokens: string literals, code completion,
409 /// annotation tokens and balanced tokens must be handled using the specific
411 /// Returns the location of the consumed token.
412 SourceLocation ConsumeToken() {
413 assert(!isTokenSpecial() &&
414 "Should consume special tokens with Consume*Token");
415 PrevTokLocation = Tok.getLocation();
417 return PrevTokLocation;
420 bool TryConsumeToken(tok::TokenKind Expected) {
421 if (Tok.isNot(Expected))
423 assert(!isTokenSpecial() &&
424 "Should consume special tokens with Consume*Token");
425 PrevTokLocation = Tok.getLocation();
430 bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) {
431 if (!TryConsumeToken(Expected))
433 Loc = PrevTokLocation;
437 /// ConsumeAnyToken - Dispatch to the right Consume* method based on the
438 /// current token type. This should only be used in cases where the type of
439 /// the token really isn't known, e.g. in error recovery.
440 SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) {
442 return ConsumeParen();
443 if (isTokenBracket())
444 return ConsumeBracket();
446 return ConsumeBrace();
447 if (isTokenStringLiteral())
448 return ConsumeStringToken();
449 if (Tok.is(tok::code_completion))
450 return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken()
451 : handleUnexpectedCodeCompletionToken();
452 if (Tok.isAnnotation())
453 return ConsumeAnnotationToken();
454 return ConsumeToken();
458 SourceLocation getEndOfPreviousToken() {
459 return PP.getLocForEndOfToken(PrevTokLocation);
462 /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds
463 /// to the given nullability kind.
464 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) {
465 return Actions.getNullabilityKeyword(nullability);
469 //===--------------------------------------------------------------------===//
470 // Low-Level token peeking and consumption methods.
473 /// isTokenParen - Return true if the cur token is '(' or ')'.
474 bool isTokenParen() const {
475 return Tok.isOneOf(tok::l_paren, tok::r_paren);
477 /// isTokenBracket - Return true if the cur token is '[' or ']'.
478 bool isTokenBracket() const {
479 return Tok.isOneOf(tok::l_square, tok::r_square);
481 /// isTokenBrace - Return true if the cur token is '{' or '}'.
482 bool isTokenBrace() const {
483 return Tok.isOneOf(tok::l_brace, tok::r_brace);
485 /// isTokenStringLiteral - True if this token is a string-literal.
486 bool isTokenStringLiteral() const {
487 return tok::isStringLiteral(Tok.getKind());
489 /// isTokenSpecial - True if this token requires special consumption methods.
490 bool isTokenSpecial() const {
491 return isTokenStringLiteral() || isTokenParen() || isTokenBracket() ||
492 isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation();
495 /// Returns true if the current token is '=' or is a type of '='.
496 /// For typos, give a fixit to '='
497 bool isTokenEqualOrEqualTypo();
499 /// Return the current token to the token stream and make the given
500 /// token the current token.
501 void UnconsumeToken(Token &Consumed) {
503 PP.EnterToken(Consumed);
508 SourceLocation ConsumeAnnotationToken() {
509 assert(Tok.isAnnotation() && "wrong consume method");
510 SourceLocation Loc = Tok.getLocation();
511 PrevTokLocation = Tok.getAnnotationEndLoc();
516 /// ConsumeParen - This consume method keeps the paren count up-to-date.
518 SourceLocation ConsumeParen() {
519 assert(isTokenParen() && "wrong consume method");
520 if (Tok.getKind() == tok::l_paren)
522 else if (ParenCount) {
523 AngleBrackets.clear(*this);
524 --ParenCount; // Don't let unbalanced )'s drive the count negative.
526 PrevTokLocation = Tok.getLocation();
528 return PrevTokLocation;
531 /// ConsumeBracket - This consume method keeps the bracket count up-to-date.
533 SourceLocation ConsumeBracket() {
534 assert(isTokenBracket() && "wrong consume method");
535 if (Tok.getKind() == tok::l_square)
537 else if (BracketCount) {
538 AngleBrackets.clear(*this);
539 --BracketCount; // Don't let unbalanced ]'s drive the count negative.
542 PrevTokLocation = Tok.getLocation();
544 return PrevTokLocation;
547 /// ConsumeBrace - This consume method keeps the brace count up-to-date.
549 SourceLocation ConsumeBrace() {
550 assert(isTokenBrace() && "wrong consume method");
551 if (Tok.getKind() == tok::l_brace)
553 else if (BraceCount) {
554 AngleBrackets.clear(*this);
555 --BraceCount; // Don't let unbalanced }'s drive the count negative.
558 PrevTokLocation = Tok.getLocation();
560 return PrevTokLocation;
563 /// ConsumeStringToken - Consume the current 'peek token', lexing a new one
564 /// and returning the token kind. This method is specific to strings, as it
565 /// handles string literal concatenation, as per C99 5.1.1.2, translation
567 SourceLocation ConsumeStringToken() {
568 assert(isTokenStringLiteral() &&
569 "Should only consume string literals with this method");
570 PrevTokLocation = Tok.getLocation();
572 return PrevTokLocation;
575 /// Consume the current code-completion token.
577 /// This routine can be called to consume the code-completion token and
578 /// continue processing in special cases where \c cutOffParsing() isn't
579 /// desired, such as token caching or completion with lookahead.
580 SourceLocation ConsumeCodeCompletionToken() {
581 assert(Tok.is(tok::code_completion));
582 PrevTokLocation = Tok.getLocation();
584 return PrevTokLocation;
587 ///\ brief When we are consuming a code-completion token without having
588 /// matched specific position in the grammar, provide code-completion results
589 /// based on context.
591 /// \returns the source location of the code-completion token.
592 SourceLocation handleUnexpectedCodeCompletionToken();
594 /// Abruptly cut off parsing; mainly used when we have reached the
595 /// code-completion point.
596 void cutOffParsing() {
597 if (PP.isCodeCompletionEnabled())
598 PP.setCodeCompletionReached();
599 // Cut off parsing by acting as if we reached the end-of-file.
600 Tok.setKind(tok::eof);
603 /// Determine if we're at the end of the file or at a transition
606 tok::TokenKind Kind = Tok.getKind();
607 return Kind == tok::eof || Kind == tok::annot_module_begin ||
608 Kind == tok::annot_module_end || Kind == tok::annot_module_include;
611 /// Checks if the \p Level is valid for use in a fold expression.
612 bool isFoldOperator(prec::Level Level) const;
614 /// Checks if the \p Kind is a valid operator for fold expressions.
615 bool isFoldOperator(tok::TokenKind Kind) const;
617 /// Initialize all pragma handlers.
618 void initializePragmaHandlers();
620 /// Destroy and reset all pragma handlers.
621 void resetPragmaHandlers();
623 /// Handle the annotation token produced for #pragma unused(...)
624 void HandlePragmaUnused();
626 /// Handle the annotation token produced for
627 /// #pragma GCC visibility...
628 void HandlePragmaVisibility();
630 /// Handle the annotation token produced for
632 void HandlePragmaPack();
634 /// Handle the annotation token produced for
635 /// #pragma ms_struct...
636 void HandlePragmaMSStruct();
638 /// Handle the annotation token produced for
639 /// #pragma comment...
640 void HandlePragmaMSComment();
642 void HandlePragmaMSPointersToMembers();
644 void HandlePragmaMSVtorDisp();
646 void HandlePragmaMSPragma();
647 bool HandlePragmaMSSection(StringRef PragmaName,
648 SourceLocation PragmaLocation);
649 bool HandlePragmaMSSegment(StringRef PragmaName,
650 SourceLocation PragmaLocation);
651 bool HandlePragmaMSInitSeg(StringRef PragmaName,
652 SourceLocation PragmaLocation);
654 /// Handle the annotation token produced for
656 void HandlePragmaAlign();
658 /// Handle the annotation token produced for
659 /// #pragma clang __debug dump...
660 void HandlePragmaDump();
662 /// Handle the annotation token produced for
663 /// #pragma weak id...
664 void HandlePragmaWeak();
666 /// Handle the annotation token produced for
667 /// #pragma weak id = id...
668 void HandlePragmaWeakAlias();
670 /// Handle the annotation token produced for
671 /// #pragma redefine_extname...
672 void HandlePragmaRedefineExtname();
674 /// Handle the annotation token produced for
675 /// #pragma STDC FP_CONTRACT...
676 void HandlePragmaFPContract();
678 /// Handle the annotation token produced for
679 /// #pragma STDC FENV_ACCESS...
680 void HandlePragmaFEnvAccess();
682 /// \brief Handle the annotation token produced for
683 /// #pragma clang fp ...
684 void HandlePragmaFP();
686 /// Handle the annotation token produced for
687 /// #pragma OPENCL EXTENSION...
688 void HandlePragmaOpenCLExtension();
690 /// Handle the annotation token produced for
691 /// #pragma clang __debug captured
692 StmtResult HandlePragmaCaptured();
694 /// Handle the annotation token produced for
695 /// #pragma clang loop and #pragma unroll.
696 bool HandlePragmaLoopHint(LoopHint &Hint);
698 bool ParsePragmaAttributeSubjectMatchRuleSet(
699 attr::ParsedSubjectMatchRuleSet &SubjectMatchRules,
700 SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc);
702 void HandlePragmaAttribute();
704 /// GetLookAheadToken - This peeks ahead N tokens and returns that token
705 /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1)
706 /// returns the token after Tok, etc.
708 /// Note that this differs from the Preprocessor's LookAhead method, because
709 /// the Parser always has one token lexed that the preprocessor doesn't.
711 const Token &GetLookAheadToken(unsigned N) {
712 if (N == 0 || Tok.is(tok::eof)) return Tok;
713 return PP.LookAhead(N-1);
717 /// NextToken - This peeks ahead one token and returns it without
719 const Token &NextToken() {
720 return PP.LookAhead(0);
723 /// getTypeAnnotation - Read a parsed type out of an annotation token.
724 static ParsedType getTypeAnnotation(const Token &Tok) {
725 return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
729 static void setTypeAnnotation(Token &Tok, ParsedType T) {
730 Tok.setAnnotationValue(T.getAsOpaquePtr());
733 /// Read an already-translated primary expression out of an annotation
735 static ExprResult getExprAnnotation(const Token &Tok) {
736 return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue());
739 /// Set the primary expression corresponding to the given annotation
741 static void setExprAnnotation(Token &Tok, ExprResult ER) {
742 Tok.setAnnotationValue(ER.getAsOpaquePointer());
746 // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to
747 // find a type name by attempting typo correction.
748 bool TryAnnotateTypeOrScopeToken();
749 bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS,
751 bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
754 enum AnnotatedNameKind {
755 /// Annotation has failed and emitted an error.
757 /// The identifier is a tentatively-declared name.
759 /// The identifier is a template name. FIXME: Add an annotation for that.
761 /// The identifier can't be resolved.
763 /// Annotation was successful.
767 TryAnnotateName(bool IsAddressOfOperand,
768 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
770 /// Push a tok::annot_cxxscope token onto the token stream.
771 void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
773 /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
774 /// replacing them with the non-context-sensitive keywords. This returns
775 /// true if the token was replaced.
776 bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
777 const char *&PrevSpec, unsigned &DiagID,
779 if (!getLangOpts().AltiVec && !getLangOpts().ZVector)
782 if (Tok.getIdentifierInfo() != Ident_vector &&
783 Tok.getIdentifierInfo() != Ident_bool &&
784 (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel))
787 return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
790 /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
791 /// identifier token, replacing it with the non-context-sensitive __vector.
792 /// This returns true if the token was replaced.
793 bool TryAltiVecVectorToken() {
794 if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) ||
795 Tok.getIdentifierInfo() != Ident_vector) return false;
796 return TryAltiVecVectorTokenOutOfLine();
799 bool TryAltiVecVectorTokenOutOfLine();
800 bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
801 const char *&PrevSpec, unsigned &DiagID,
804 /// Returns true if the current token is the identifier 'instancetype'.
806 /// Should only be used in Objective-C language modes.
807 bool isObjCInstancetype() {
808 assert(getLangOpts().ObjC);
809 if (Tok.isAnnotation())
811 if (!Ident_instancetype)
812 Ident_instancetype = PP.getIdentifierInfo("instancetype");
813 return Tok.getIdentifierInfo() == Ident_instancetype;
816 /// TryKeywordIdentFallback - For compatibility with system headers using
817 /// keywords as identifiers, attempt to convert the current token to an
818 /// identifier and optionally disable the keyword for the remainder of the
819 /// translation unit. This returns false if the token was not replaced,
820 /// otherwise emits a diagnostic and returns true.
821 bool TryKeywordIdentFallback(bool DisableKeyword);
823 /// Get the TemplateIdAnnotation from the token.
824 TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
826 /// TentativeParsingAction - An object that is used as a kind of "tentative
827 /// parsing transaction". It gets instantiated to mark the token position and
828 /// after the token consumption is done, Commit() or Revert() is called to
829 /// either "commit the consumed tokens" or revert to the previously marked
830 /// token position. Example:
832 /// TentativeParsingAction TPA(*this);
837 class TentativeParsingAction {
840 size_t PrevTentativelyDeclaredIdentifierCount;
841 unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
845 explicit TentativeParsingAction(Parser& p) : P(p) {
847 PrevTentativelyDeclaredIdentifierCount =
848 P.TentativelyDeclaredIdentifiers.size();
849 PrevParenCount = P.ParenCount;
850 PrevBracketCount = P.BracketCount;
851 PrevBraceCount = P.BraceCount;
852 P.PP.EnableBacktrackAtThisPos();
856 assert(isActive && "Parsing action was finished!");
857 P.TentativelyDeclaredIdentifiers.resize(
858 PrevTentativelyDeclaredIdentifierCount);
859 P.PP.CommitBacktrackedTokens();
863 assert(isActive && "Parsing action was finished!");
866 P.TentativelyDeclaredIdentifiers.resize(
867 PrevTentativelyDeclaredIdentifierCount);
868 P.ParenCount = PrevParenCount;
869 P.BracketCount = PrevBracketCount;
870 P.BraceCount = PrevBraceCount;
873 ~TentativeParsingAction() {
874 assert(!isActive && "Forgot to call Commit or Revert!");
877 /// A TentativeParsingAction that automatically reverts in its destructor.
878 /// Useful for disambiguation parses that will always be reverted.
879 class RevertingTentativeParsingAction
880 : private Parser::TentativeParsingAction {
882 RevertingTentativeParsingAction(Parser &P)
883 : Parser::TentativeParsingAction(P) {}
884 ~RevertingTentativeParsingAction() { Revert(); }
887 class UnannotatedTentativeParsingAction;
889 /// ObjCDeclContextSwitch - An object used to switch context from
890 /// an objective-c decl context to its enclosing decl context and
892 class ObjCDeclContextSwitch {
895 SaveAndRestore<bool> WithinObjCContainer;
897 explicit ObjCDeclContextSwitch(Parser &p)
898 : P(p), DC(p.getObjCDeclContext()),
899 WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) {
901 P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC));
903 ~ObjCDeclContextSwitch() {
905 P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC));
909 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
910 /// input. If so, it is consumed and false is returned.
912 /// If a trivial punctuator misspelling is encountered, a FixIt error
913 /// diagnostic is issued and false is returned after recovery.
915 /// If the input is malformed, this emits the specified diagnostic and true is
917 bool ExpectAndConsume(tok::TokenKind ExpectedTok,
918 unsigned Diag = diag::err_expected,
919 StringRef DiagMsg = "");
921 /// The parser expects a semicolon and, if present, will consume it.
923 /// If the next token is not a semicolon, this emits the specified diagnostic,
924 /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
925 /// to the semicolon, consumes that extra token.
926 bool ExpectAndConsumeSemi(unsigned DiagID);
928 /// The kind of extra semi diagnostic to emit.
932 InstanceVariableList = 2,
933 AfterMemberFunctionDefinition = 3
936 /// Consume any extra semi-colons until the end of the line.
937 void ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST = TST_unspecified);
939 /// Return false if the next token is an identifier. An 'expected identifier'
940 /// error is emitted otherwise.
942 /// The parser tries to recover from the error by checking if the next token
943 /// is a C++ keyword when parsing Objective-C++. Return false if the recovery
945 bool expectIdentifier();
948 //===--------------------------------------------------------------------===//
949 // Scope manipulation
951 /// ParseScope - Introduces a new scope for parsing. The kind of
952 /// scope is determined by ScopeFlags. Objects of this type should
953 /// be created on the stack to coincide with the position where the
954 /// parser enters the new scope, and this object's constructor will
955 /// create that new scope. Similarly, once the object is destroyed
956 /// the parser will exit the scope.
959 ParseScope(const ParseScope &) = delete;
960 void operator=(const ParseScope &) = delete;
963 // ParseScope - Construct a new object to manage a scope in the
964 // parser Self where the new Scope is created with the flags
965 // ScopeFlags, but only when we aren't about to enter a compound statement.
966 ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true,
967 bool BeforeCompoundStmt = false)
969 if (EnteredScope && !BeforeCompoundStmt)
970 Self->EnterScope(ScopeFlags);
972 if (BeforeCompoundStmt)
973 Self->incrementMSManglingNumber();
975 this->Self = nullptr;
979 // Exit - Exit the scope associated with this object now, rather
980 // than waiting until the object is destroyed.
993 /// EnterScope - Start a new scope.
994 void EnterScope(unsigned ScopeFlags);
996 /// ExitScope - Pop a scope off the scope stack.
1000 /// RAII object used to modify the scope flags for the current scope.
1001 class ParseScopeFlags {
1004 ParseScopeFlags(const ParseScopeFlags &) = delete;
1005 void operator=(const ParseScopeFlags &) = delete;
1008 ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
1012 //===--------------------------------------------------------------------===//
1013 // Diagnostic Emission and Error recovery.
1016 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
1017 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
1018 DiagnosticBuilder Diag(unsigned DiagID) {
1019 return Diag(Tok, DiagID);
1023 void SuggestParentheses(SourceLocation Loc, unsigned DK,
1024 SourceRange ParenRange);
1025 void CheckNestedObjCContexts(SourceLocation AtLoc);
1029 /// Control flags for SkipUntil functions.
1030 enum SkipUntilFlags {
1031 StopAtSemi = 1 << 0, ///< Stop skipping at semicolon
1032 /// Stop skipping at specified token, but don't skip the token itself
1033 StopBeforeMatch = 1 << 1,
1034 StopAtCodeCompletion = 1 << 2 ///< Stop at code completion
1037 friend constexpr SkipUntilFlags operator|(SkipUntilFlags L,
1039 return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) |
1040 static_cast<unsigned>(R));
1043 /// SkipUntil - Read tokens until we get to the specified token, then consume
1044 /// it (unless StopBeforeMatch is specified). Because we cannot guarantee
1045 /// that the token will ever occur, this skips to the next token, or to some
1046 /// likely good stopping point. If Flags has StopAtSemi flag, skipping will
1047 /// stop at a ';' character.
1049 /// If SkipUntil finds the specified token, it returns true, otherwise it
1051 bool SkipUntil(tok::TokenKind T,
1052 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
1053 return SkipUntil(llvm::makeArrayRef(T), Flags);
1055 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2,
1056 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
1057 tok::TokenKind TokArray[] = {T1, T2};
1058 return SkipUntil(TokArray, Flags);
1060 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3,
1061 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
1062 tok::TokenKind TokArray[] = {T1, T2, T3};
1063 return SkipUntil(TokArray, Flags);
1065 bool SkipUntil(ArrayRef<tok::TokenKind> Toks,
1066 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0));
1068 /// SkipMalformedDecl - Read tokens until we get to some likely good stopping
1069 /// point for skipping past a simple-declaration.
1070 void SkipMalformedDecl();
1073 //===--------------------------------------------------------------------===//
1074 // Lexing and parsing of C++ inline methods.
1076 struct ParsingClass;
1078 /// [class.mem]p1: "... the class is regarded as complete within
1079 /// - function bodies
1080 /// - default arguments
1081 /// - exception-specifications (TODO: C++0x)
1082 /// - and brace-or-equal-initializers for non-static data members
1083 /// (including such things in nested classes)."
1084 /// LateParsedDeclarations build the tree of those elements so they can
1085 /// be parsed after parsing the top-level class.
1086 class LateParsedDeclaration {
1088 virtual ~LateParsedDeclaration();
1090 virtual void ParseLexedMethodDeclarations();
1091 virtual void ParseLexedMemberInitializers();
1092 virtual void ParseLexedMethodDefs();
1093 virtual void ParseLexedAttributes();
1096 /// Inner node of the LateParsedDeclaration tree that parses
1097 /// all its members recursively.
1098 class LateParsedClass : public LateParsedDeclaration {
1100 LateParsedClass(Parser *P, ParsingClass *C);
1101 ~LateParsedClass() override;
1103 void ParseLexedMethodDeclarations() override;
1104 void ParseLexedMemberInitializers() override;
1105 void ParseLexedMethodDefs() override;
1106 void ParseLexedAttributes() override;
1110 ParsingClass *Class;
1113 /// Contains the lexed tokens of an attribute with arguments that
1114 /// may reference member variables and so need to be parsed at the
1115 /// end of the class declaration after parsing all other member
1116 /// member declarations.
1117 /// FIXME: Perhaps we should change the name of LateParsedDeclaration to
1118 /// LateParsedTokens.
1119 struct LateParsedAttribute : public LateParsedDeclaration {
1122 IdentifierInfo &AttrName;
1123 SourceLocation AttrNameLoc;
1124 SmallVector<Decl*, 2> Decls;
1126 explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
1128 : Self(P), AttrName(Name), AttrNameLoc(Loc) {}
1130 void ParseLexedAttributes() override;
1132 void addDecl(Decl *D) { Decls.push_back(D); }
1135 // A list of late-parsed attributes. Used by ParseGNUAttributes.
1136 class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> {
1138 LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { }
1140 bool parseSoon() { return ParseSoon; }
1143 bool ParseSoon; // Are we planning to parse these shortly after creation?
1146 /// Contains the lexed tokens of a member function definition
1147 /// which needs to be parsed at the end of the class declaration
1148 /// after parsing all other member declarations.
1149 struct LexedMethod : public LateParsedDeclaration {
1154 /// Whether this member function had an associated template
1155 /// scope. When true, D is a template declaration.
1156 /// otherwise, it is a member function declaration.
1159 explicit LexedMethod(Parser* P, Decl *MD)
1160 : Self(P), D(MD), TemplateScope(false) {}
1162 void ParseLexedMethodDefs() override;
1165 /// LateParsedDefaultArgument - Keeps track of a parameter that may
1166 /// have a default argument that cannot be parsed yet because it
1167 /// occurs within a member function declaration inside the class
1168 /// (C++ [class.mem]p2).
1169 struct LateParsedDefaultArgument {
1170 explicit LateParsedDefaultArgument(Decl *P,
1171 std::unique_ptr<CachedTokens> Toks = nullptr)
1172 : Param(P), Toks(std::move(Toks)) { }
1174 /// Param - The parameter declaration for this parameter.
1177 /// Toks - The sequence of tokens that comprises the default
1178 /// argument expression, not including the '=' or the terminating
1179 /// ')' or ','. This will be NULL for parameters that have no
1180 /// default argument.
1181 std::unique_ptr<CachedTokens> Toks;
1184 /// LateParsedMethodDeclaration - A method declaration inside a class that
1185 /// contains at least one entity whose parsing needs to be delayed
1186 /// until the class itself is completely-defined, such as a default
1187 /// argument (C++ [class.mem]p2).
1188 struct LateParsedMethodDeclaration : public LateParsedDeclaration {
1189 explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
1190 : Self(P), Method(M), TemplateScope(false),
1191 ExceptionSpecTokens(nullptr) {}
1193 void ParseLexedMethodDeclarations() override;
1197 /// Method - The method declaration.
1200 /// Whether this member function had an associated template
1201 /// scope. When true, D is a template declaration.
1202 /// otherwise, it is a member function declaration.
1205 /// DefaultArgs - Contains the parameters of the function and
1206 /// their default arguments. At least one of the parameters will
1207 /// have a default argument, but all of the parameters of the
1208 /// method will be stored so that they can be reintroduced into
1209 /// scope at the appropriate times.
1210 SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
1212 /// The set of tokens that make up an exception-specification that
1213 /// has not yet been parsed.
1214 CachedTokens *ExceptionSpecTokens;
1217 /// LateParsedMemberInitializer - An initializer for a non-static class data
1218 /// member whose parsing must to be delayed until the class is completely
1219 /// defined (C++11 [class.mem]p2).
1220 struct LateParsedMemberInitializer : public LateParsedDeclaration {
1221 LateParsedMemberInitializer(Parser *P, Decl *FD)
1222 : Self(P), Field(FD) { }
1224 void ParseLexedMemberInitializers() override;
1228 /// Field - The field declaration.
1231 /// CachedTokens - The sequence of tokens that comprises the initializer,
1232 /// including any leading '='.
1236 /// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
1237 /// C++ class, its method declarations that contain parts that won't be
1238 /// parsed until after the definition is completed (C++ [class.mem]p2),
1239 /// the method declarations and possibly attached inline definitions
1240 /// will be stored here with the tokens that will be parsed to create those
1242 typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer;
1244 /// Representation of a class that has been parsed, including
1245 /// any member function declarations or definitions that need to be
1246 /// parsed after the corresponding top-level class is complete.
1247 struct ParsingClass {
1248 ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface)
1249 : TopLevelClass(TopLevelClass), TemplateScope(false),
1250 IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) { }
1252 /// Whether this is a "top-level" class, meaning that it is
1253 /// not nested within another class.
1254 bool TopLevelClass : 1;
1256 /// Whether this class had an associated template
1257 /// scope. When true, TagOrTemplate is a template declaration;
1258 /// otherwise, it is a tag declaration.
1259 bool TemplateScope : 1;
1261 /// Whether this class is an __interface.
1262 bool IsInterface : 1;
1264 /// The class or class template whose definition we are parsing.
1265 Decl *TagOrTemplate;
1267 /// LateParsedDeclarations - Method declarations, inline definitions and
1268 /// nested classes that contain pieces whose parsing will be delayed until
1269 /// the top-level class is fully defined.
1270 LateParsedDeclarationsContainer LateParsedDeclarations;
1273 /// The stack of classes that is currently being
1274 /// parsed. Nested and local classes will be pushed onto this stack
1275 /// when they are parsed, and removed afterward.
1276 std::stack<ParsingClass *> ClassStack;
1278 ParsingClass &getCurrentClass() {
1279 assert(!ClassStack.empty() && "No lexed method stacks!");
1280 return *ClassStack.top();
1283 /// RAII object used to manage the parsing of a class definition.
1284 class ParsingClassDefinition {
1287 Sema::ParsingClassState State;
1290 ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass,
1292 : P(P), Popped(false),
1293 State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
1296 /// Pop this class of the stack.
1298 assert(!Popped && "Nested class has already been popped");
1300 P.PopParsingClass(State);
1303 ~ParsingClassDefinition() {
1305 P.PopParsingClass(State);
1309 /// Contains information about any template-specific
1310 /// information that has been parsed prior to parsing declaration
1312 struct ParsedTemplateInfo {
1313 ParsedTemplateInfo()
1314 : Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { }
1316 ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
1317 bool isSpecialization,
1318 bool lastParameterListWasEmpty = false)
1319 : Kind(isSpecialization? ExplicitSpecialization : Template),
1320 TemplateParams(TemplateParams),
1321 LastParameterListWasEmpty(lastParameterListWasEmpty) { }
1323 explicit ParsedTemplateInfo(SourceLocation ExternLoc,
1324 SourceLocation TemplateLoc)
1325 : Kind(ExplicitInstantiation), TemplateParams(nullptr),
1326 ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
1327 LastParameterListWasEmpty(false){ }
1329 /// The kind of template we are parsing.
1331 /// We are not parsing a template at all.
1333 /// We are parsing a template declaration.
1335 /// We are parsing an explicit specialization.
1336 ExplicitSpecialization,
1337 /// We are parsing an explicit instantiation.
1338 ExplicitInstantiation
1341 /// The template parameter lists, for template declarations
1342 /// and explicit specializations.
1343 TemplateParameterLists *TemplateParams;
1345 /// The location of the 'extern' keyword, if any, for an explicit
1347 SourceLocation ExternLoc;
1349 /// The location of the 'template' keyword, for an explicit
1351 SourceLocation TemplateLoc;
1353 /// Whether the last template parameter list was empty.
1354 bool LastParameterListWasEmpty;
1356 SourceRange getSourceRange() const LLVM_READONLY;
1359 void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
1360 void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
1362 static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
1363 static void LateTemplateParserCleanupCallback(void *P);
1365 Sema::ParsingClassState
1366 PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface);
1367 void DeallocateParsedClasses(ParsingClass *Class);
1368 void PopParsingClass(Sema::ParsingClassState);
1370 enum CachedInitKind {
1371 CIK_DefaultArgument,
1372 CIK_DefaultInitializer
1375 NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS,
1376 ParsedAttributes &AccessAttrs,
1377 ParsingDeclarator &D,
1378 const ParsedTemplateInfo &TemplateInfo,
1379 const VirtSpecifiers &VS,
1380 SourceLocation PureSpecLoc);
1381 void ParseCXXNonStaticMemberInitializer(Decl *VarD);
1382 void ParseLexedAttributes(ParsingClass &Class);
1383 void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1384 bool EnterScope, bool OnDefinition);
1385 void ParseLexedAttribute(LateParsedAttribute &LA,
1386 bool EnterScope, bool OnDefinition);
1387 void ParseLexedMethodDeclarations(ParsingClass &Class);
1388 void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
1389 void ParseLexedMethodDefs(ParsingClass &Class);
1390 void ParseLexedMethodDef(LexedMethod &LM);
1391 void ParseLexedMemberInitializers(ParsingClass &Class);
1392 void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
1393 void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod);
1394 bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
1395 bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK);
1396 bool ConsumeAndStoreConditional(CachedTokens &Toks);
1397 bool ConsumeAndStoreUntil(tok::TokenKind T1,
1399 bool StopAtSemi = true,
1400 bool ConsumeFinalToken = true) {
1401 return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
1403 bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
1405 bool StopAtSemi = true,
1406 bool ConsumeFinalToken = true);
1408 //===--------------------------------------------------------------------===//
1409 // C99 6.9: External Definitions.
1410 struct ParsedAttributesWithRange : ParsedAttributes {
1411 ParsedAttributesWithRange(AttributeFactory &factory)
1412 : ParsedAttributes(factory) {}
1415 ParsedAttributes::clear();
1416 Range = SourceRange();
1421 struct ParsedAttributesViewWithRange : ParsedAttributesView {
1422 ParsedAttributesViewWithRange() : ParsedAttributesView() {}
1423 void clearListOnly() {
1424 ParsedAttributesView::clearListOnly();
1425 Range = SourceRange();
1431 DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
1432 ParsingDeclSpec *DS = nullptr);
1433 bool isDeclarationAfterDeclarator();
1434 bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
1435 DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(
1436 ParsedAttributesWithRange &attrs,
1437 ParsingDeclSpec *DS = nullptr,
1438 AccessSpecifier AS = AS_none);
1439 DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
1440 ParsingDeclSpec &DS,
1441 AccessSpecifier AS);
1443 void SkipFunctionBody();
1444 Decl *ParseFunctionDefinition(ParsingDeclarator &D,
1445 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1446 LateParsedAttrList *LateParsedAttrs = nullptr);
1447 void ParseKNRParamDeclarations(Declarator &D);
1448 // EndLoc, if non-NULL, is filled with the location of the last token of
1450 ExprResult ParseSimpleAsm(SourceLocation *EndLoc = nullptr);
1451 ExprResult ParseAsmStringLiteral();
1453 // Objective-C External Declarations
1454 void MaybeSkipAttributes(tok::ObjCKeywordKind Kind);
1455 DeclGroupPtrTy ParseObjCAtDirectives(ParsedAttributesWithRange &Attrs);
1456 DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
1457 Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
1458 ParsedAttributes &prefixAttrs);
1459 class ObjCTypeParamListScope;
1460 ObjCTypeParamList *parseObjCTypeParamList();
1461 ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs(
1462 ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
1463 SmallVectorImpl<IdentifierLocPair> &protocolIdents,
1464 SourceLocation &rAngleLoc, bool mayBeProtocolList = true);
1466 void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
1467 BalancedDelimiterTracker &T,
1468 SmallVectorImpl<Decl *> &AllIvarDecls,
1469 bool RBraceMissing);
1470 void ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1471 tok::ObjCKeywordKind visibility,
1472 SourceLocation atLoc);
1473 bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P,
1474 SmallVectorImpl<SourceLocation> &PLocs,
1475 bool WarnOnDeclarations,
1476 bool ForObjCContainer,
1477 SourceLocation &LAngleLoc,
1478 SourceLocation &EndProtoLoc,
1479 bool consumeLastToken);
1481 /// Parse the first angle-bracket-delimited clause for an
1482 /// Objective-C object or object pointer type, which may be either
1483 /// type arguments or protocol qualifiers.
1484 void parseObjCTypeArgsOrProtocolQualifiers(
1485 ParsedType baseType,
1486 SourceLocation &typeArgsLAngleLoc,
1487 SmallVectorImpl<ParsedType> &typeArgs,
1488 SourceLocation &typeArgsRAngleLoc,
1489 SourceLocation &protocolLAngleLoc,
1490 SmallVectorImpl<Decl *> &protocols,
1491 SmallVectorImpl<SourceLocation> &protocolLocs,
1492 SourceLocation &protocolRAngleLoc,
1493 bool consumeLastToken,
1494 bool warnOnIncompleteProtocols);
1496 /// Parse either Objective-C type arguments or protocol qualifiers; if the
1497 /// former, also parse protocol qualifiers afterward.
1498 void parseObjCTypeArgsAndProtocolQualifiers(
1499 ParsedType baseType,
1500 SourceLocation &typeArgsLAngleLoc,
1501 SmallVectorImpl<ParsedType> &typeArgs,
1502 SourceLocation &typeArgsRAngleLoc,
1503 SourceLocation &protocolLAngleLoc,
1504 SmallVectorImpl<Decl *> &protocols,
1505 SmallVectorImpl<SourceLocation> &protocolLocs,
1506 SourceLocation &protocolRAngleLoc,
1507 bool consumeLastToken);
1509 /// Parse a protocol qualifier type such as '<NSCopying>', which is
1510 /// an anachronistic way of writing 'id<NSCopying>'.
1511 TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc);
1513 /// Parse Objective-C type arguments and protocol qualifiers, extending the
1514 /// current type with the parsed result.
1515 TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc,
1517 bool consumeLastToken,
1518 SourceLocation &endLoc);
1520 void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
1522 DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
1523 ParsedAttributes &prefixAttrs);
1525 struct ObjCImplParsingDataRAII {
1529 typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer;
1530 LateParsedObjCMethodContainer LateParsedObjCMethods;
1532 ObjCImplParsingDataRAII(Parser &parser, Decl *D)
1533 : P(parser), Dcl(D), HasCFunction(false) {
1534 P.CurParsedObjCImpl = this;
1537 ~ObjCImplParsingDataRAII();
1539 void finish(SourceRange AtEnd);
1540 bool isFinished() const { return Finished; }
1545 ObjCImplParsingDataRAII *CurParsedObjCImpl;
1546 void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl);
1548 DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc);
1549 DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
1550 Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
1551 Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
1552 Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
1554 IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
1555 // Definitions for Objective-c context sensitive keywords recognition.
1557 objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
1558 objc_nonnull, objc_nullable, objc_null_unspecified,
1561 IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
1563 bool isTokIdentifier_in() const;
1565 ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx,
1566 ParsedAttributes *ParamAttrs);
1567 void ParseObjCMethodRequirement();
1568 Decl *ParseObjCMethodPrototype(
1569 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1570 bool MethodDefinition = true);
1571 Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
1572 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1573 bool MethodDefinition=true);
1574 void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
1576 Decl *ParseObjCMethodDefinition();
1579 //===--------------------------------------------------------------------===//
1580 // C99 6.5: Expressions.
1582 /// TypeCastState - State whether an expression is or may be a type cast.
1583 enum TypeCastState {
1589 ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast);
1590 ExprResult ParseConstantExpressionInExprEvalContext(
1591 TypeCastState isTypeCast = NotTypeCast);
1592 ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast);
1593 ExprResult ParseCaseExpression(SourceLocation CaseLoc);
1594 ExprResult ParseConstraintExpression();
1595 // Expr that doesn't include commas.
1596 ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast);
1598 ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1599 unsigned &NumLineToksConsumed,
1600 bool IsUnevaluated);
1603 ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
1605 ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
1607 ExprResult ParseRHSOfBinaryExpression(ExprResult LHS,
1608 prec::Level MinPrec);
1609 ExprResult ParseCastExpression(bool isUnaryExpression,
1610 bool isAddressOfOperand,
1612 TypeCastState isTypeCast,
1613 bool isVectorLiteral = false);
1614 ExprResult ParseCastExpression(bool isUnaryExpression,
1615 bool isAddressOfOperand = false,
1616 TypeCastState isTypeCast = NotTypeCast,
1617 bool isVectorLiteral = false);
1619 /// Returns true if the next token cannot start an expression.
1620 bool isNotExpressionStart();
1622 /// Returns true if the next token would start a postfix-expression
1624 bool isPostfixExpressionSuffixStart() {
1625 tok::TokenKind K = Tok.getKind();
1626 return (K == tok::l_square || K == tok::l_paren ||
1627 K == tok::period || K == tok::arrow ||
1628 K == tok::plusplus || K == tok::minusminus);
1631 bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less);
1632 void checkPotentialAngleBracket(ExprResult &PotentialTemplateName);
1633 bool checkPotentialAngleBracketDelimiter(const AngleBracketTracker::Loc &,
1634 const Token &OpToken);
1635 bool checkPotentialAngleBracketDelimiter(const Token &OpToken) {
1636 if (auto *Info = AngleBrackets.getCurrent(*this))
1637 return checkPotentialAngleBracketDelimiter(*Info, OpToken);
1641 ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
1642 ExprResult ParseUnaryExprOrTypeTraitExpression();
1643 ExprResult ParseBuiltinPrimaryExpression();
1645 ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1648 SourceRange &CastRange);
1650 typedef SmallVector<Expr*, 20> ExprListTy;
1651 typedef SmallVector<SourceLocation, 20> CommaLocsTy;
1653 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1654 bool ParseExpressionList(
1655 SmallVectorImpl<Expr *> &Exprs,
1656 SmallVectorImpl<SourceLocation> &CommaLocs,
1657 llvm::function_ref<void()> Completer = llvm::function_ref<void()>());
1659 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
1660 /// used for misc language extensions.
1661 bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
1662 SmallVectorImpl<SourceLocation> &CommaLocs);
1665 /// ParenParseOption - Control what ParseParenExpression will parse.
1666 enum ParenParseOption {
1667 SimpleExpr, // Only parse '(' expression ')'
1668 FoldExpr, // Also allow fold-expression <anything>
1669 CompoundStmt, // Also allow '(' compound-statement ')'
1670 CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
1671 CastExpr // Also allow '(' type-name ')' <anything>
1673 ExprResult ParseParenExpression(ParenParseOption &ExprType,
1674 bool stopIfCastExpr,
1677 SourceLocation &RParenLoc);
1679 ExprResult ParseCXXAmbiguousParenExpression(
1680 ParenParseOption &ExprType, ParsedType &CastTy,
1681 BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt);
1682 ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
1683 SourceLocation LParenLoc,
1684 SourceLocation RParenLoc);
1686 ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
1688 ExprResult ParseGenericSelectionExpression();
1690 ExprResult ParseObjCBoolLiteral();
1692 ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T);
1694 //===--------------------------------------------------------------------===//
1696 ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
1697 Token &Replacement);
1698 ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
1700 bool areTokensAdjacent(const Token &A, const Token &B);
1702 void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
1703 bool EnteringContext, IdentifierInfo &II,
1706 bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
1707 ParsedType ObjectType,
1708 bool EnteringContext,
1709 bool *MayBePseudoDestructor = nullptr,
1710 bool IsTypename = false,
1711 IdentifierInfo **LastII = nullptr,
1712 bool OnlyNamespace = false);
1714 //===--------------------------------------------------------------------===//
1715 // C++0x 5.1.2: Lambda expressions
1717 // [...] () -> type {...}
1718 ExprResult ParseLambdaExpression();
1719 ExprResult TryParseLambdaExpression();
1720 Optional<unsigned> ParseLambdaIntroducer(LambdaIntroducer &Intro,
1721 bool *SkippedInits = nullptr);
1722 bool TryParseLambdaIntroducer(LambdaIntroducer &Intro);
1723 ExprResult ParseLambdaExpressionAfterIntroducer(
1724 LambdaIntroducer &Intro);
1726 //===--------------------------------------------------------------------===//
1727 // C++ 5.2p1: C++ Casts
1728 ExprResult ParseCXXCasts();
1730 //===--------------------------------------------------------------------===//
1731 // C++ 5.2p1: C++ Type Identification
1732 ExprResult ParseCXXTypeid();
1734 //===--------------------------------------------------------------------===//
1735 // C++ : Microsoft __uuidof Expression
1736 ExprResult ParseCXXUuidof();
1738 //===--------------------------------------------------------------------===//
1739 // C++ 5.2.4: C++ Pseudo-Destructor Expressions
1740 ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1741 tok::TokenKind OpKind,
1743 ParsedType ObjectType);
1745 //===--------------------------------------------------------------------===//
1746 // C++ 9.3.2: C++ 'this' pointer
1747 ExprResult ParseCXXThis();
1749 //===--------------------------------------------------------------------===//
1750 // C++ 15: C++ Throw Expression
1751 ExprResult ParseThrowExpression();
1753 ExceptionSpecificationType tryParseExceptionSpecification(
1755 SourceRange &SpecificationRange,
1756 SmallVectorImpl<ParsedType> &DynamicExceptions,
1757 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
1758 ExprResult &NoexceptExpr,
1759 CachedTokens *&ExceptionSpecTokens);
1761 // EndLoc is filled with the location of the last token of the specification.
1762 ExceptionSpecificationType ParseDynamicExceptionSpecification(
1763 SourceRange &SpecificationRange,
1764 SmallVectorImpl<ParsedType> &Exceptions,
1765 SmallVectorImpl<SourceRange> &Ranges);
1767 //===--------------------------------------------------------------------===//
1768 // C++0x 8: Function declaration trailing-return-type
1769 TypeResult ParseTrailingReturnType(SourceRange &Range,
1770 bool MayBeFollowedByDirectInit);
1772 //===--------------------------------------------------------------------===//
1773 // C++ 2.13.5: C++ Boolean Literals
1774 ExprResult ParseCXXBoolLiteral();
1776 //===--------------------------------------------------------------------===//
1777 // C++ 5.2.3: Explicit type conversion (functional notation)
1778 ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
1780 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1781 /// This should only be called when the current token is known to be part of
1782 /// simple-type-specifier.
1783 void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
1785 bool ParseCXXTypeSpecifierSeq(DeclSpec &DS);
1787 //===--------------------------------------------------------------------===//
1788 // C++ 5.3.4 and 5.3.5: C++ new and delete
1789 bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs,
1791 void ParseDirectNewDeclarator(Declarator &D);
1792 ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
1793 ExprResult ParseCXXDeleteExpression(bool UseGlobal,
1794 SourceLocation Start);
1796 //===--------------------------------------------------------------------===//
1797 // C++ if/switch/while/for condition expression.
1798 struct ForRangeInfo;
1799 Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt,
1801 Sema::ConditionKind CK,
1802 ForRangeInfo *FRI = nullptr);
1804 //===--------------------------------------------------------------------===//
1807 ExprResult ParseCoyieldExpression();
1809 //===--------------------------------------------------------------------===//
1810 // C99 6.7.8: Initialization.
1812 /// ParseInitializer
1813 /// initializer: [C99 6.7.8]
1814 /// assignment-expression
1816 ExprResult ParseInitializer() {
1817 if (Tok.isNot(tok::l_brace))
1818 return ParseAssignmentExpression();
1819 return ParseBraceInitializer();
1821 bool MayBeDesignationStart();
1822 ExprResult ParseBraceInitializer();
1823 ExprResult ParseInitializerWithPotentialDesignator();
1825 //===--------------------------------------------------------------------===//
1826 // clang Expressions
1828 ExprResult ParseBlockLiteralExpression(); // ^{...}
1830 //===--------------------------------------------------------------------===//
1831 // Objective-C Expressions
1832 ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
1833 ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
1834 ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
1835 ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
1836 ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
1837 ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
1838 ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
1839 ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
1840 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
1841 ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
1842 ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
1843 bool isSimpleObjCMessageExpression();
1844 ExprResult ParseObjCMessageExpression();
1845 ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
1846 SourceLocation SuperLoc,
1847 ParsedType ReceiverType,
1848 Expr *ReceiverExpr);
1849 ExprResult ParseAssignmentExprWithObjCMessageExprStart(
1850 SourceLocation LBracloc, SourceLocation SuperLoc,
1851 ParsedType ReceiverType, Expr *ReceiverExpr);
1852 bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
1854 //===--------------------------------------------------------------------===//
1855 // C99 6.8: Statements and Blocks.
1857 /// A SmallVector of statements, with stack size 32 (as that is the only one
1859 typedef SmallVector<Stmt*, 32> StmtVector;
1860 /// A SmallVector of expressions, with stack size 12 (the maximum used.)
1861 typedef SmallVector<Expr*, 12> ExprVector;
1862 /// A SmallVector of types.
1863 typedef SmallVector<ParsedType, 12> TypeVector;
1865 StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
1866 bool AllowOpenMPStandalone = false);
1867 enum AllowedConstructsKind {
1868 /// Allow any declarations, statements, OpenMP directives.
1870 /// Allow only statements and non-standalone OpenMP directives.
1871 ACK_StatementsOpenMPNonStandalone,
1872 /// Allow statements and all executable OpenMP directives
1873 ACK_StatementsOpenMPAnyExecutable
1876 ParseStatementOrDeclaration(StmtVector &Stmts, AllowedConstructsKind Allowed,
1877 SourceLocation *TrailingElseLoc = nullptr);
1878 StmtResult ParseStatementOrDeclarationAfterAttributes(
1880 AllowedConstructsKind Allowed,
1881 SourceLocation *TrailingElseLoc,
1882 ParsedAttributesWithRange &Attrs);
1883 StmtResult ParseExprStatement();
1884 StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs);
1885 StmtResult ParseCaseStatement(bool MissingCase = false,
1886 ExprResult Expr = ExprResult());
1887 StmtResult ParseDefaultStatement();
1888 StmtResult ParseCompoundStatement(bool isStmtExpr = false);
1889 StmtResult ParseCompoundStatement(bool isStmtExpr,
1890 unsigned ScopeFlags);
1891 void ParseCompoundStatementLeadingPragmas();
1892 bool ConsumeNullStmt(StmtVector &Stmts);
1893 StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
1894 bool ParseParenExprOrCondition(StmtResult *InitStmt,
1895 Sema::ConditionResult &CondResult,
1897 Sema::ConditionKind CK);
1898 StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
1899 StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
1900 StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
1901 StmtResult ParseDoStatement();
1902 StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
1903 StmtResult ParseGotoStatement();
1904 StmtResult ParseContinueStatement();
1905 StmtResult ParseBreakStatement();
1906 StmtResult ParseReturnStatement();
1907 StmtResult ParseAsmStatement(bool &msAsm);
1908 StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
1909 StmtResult ParsePragmaLoopHint(StmtVector &Stmts,
1910 AllowedConstructsKind Allowed,
1911 SourceLocation *TrailingElseLoc,
1912 ParsedAttributesWithRange &Attrs);
1914 /// Describes the behavior that should be taken for an __if_exists
1916 enum IfExistsBehavior {
1917 /// Parse the block; this code is always used.
1919 /// Skip the block entirely; this code is never used.
1921 /// Parse the block as a dependent block, which may be used in
1922 /// some template instantiations but not others.
1926 /// Describes the condition of a Microsoft __if_exists or
1927 /// __if_not_exists block.
1928 struct IfExistsCondition {
1929 /// The location of the initial keyword.
1930 SourceLocation KeywordLoc;
1931 /// Whether this is an __if_exists block (rather than an
1932 /// __if_not_exists block).
1935 /// Nested-name-specifier preceding the name.
1938 /// The name we're looking for.
1941 /// The behavior of this __if_exists or __if_not_exists block
1943 IfExistsBehavior Behavior;
1946 bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
1947 void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
1948 void ParseMicrosoftIfExistsExternalDeclaration();
1949 void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
1950 ParsedAttributes &AccessAttrs,
1951 AccessSpecifier &CurAS);
1952 bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
1954 bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
1955 SmallVectorImpl<Expr *> &Constraints,
1956 SmallVectorImpl<Expr *> &Exprs);
1958 //===--------------------------------------------------------------------===//
1959 // C++ 6: Statements and Blocks
1961 StmtResult ParseCXXTryBlock();
1962 StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
1963 StmtResult ParseCXXCatchBlock(bool FnCatch = false);
1965 //===--------------------------------------------------------------------===//
1966 // MS: SEH Statements and Blocks
1968 StmtResult ParseSEHTryBlock();
1969 StmtResult ParseSEHExceptBlock(SourceLocation Loc);
1970 StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
1971 StmtResult ParseSEHLeaveStatement();
1973 //===--------------------------------------------------------------------===//
1974 // Objective-C Statements
1976 StmtResult ParseObjCAtStatement(SourceLocation atLoc);
1977 StmtResult ParseObjCTryStmt(SourceLocation atLoc);
1978 StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
1979 StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
1980 StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
1983 //===--------------------------------------------------------------------===//
1984 // C99 6.7: Declarations.
1986 /// A context for parsing declaration specifiers. TODO: flesh this
1987 /// out, there are other significant restrictions on specifiers than
1988 /// would be best implemented in the parser.
1989 enum class DeclSpecContext {
1990 DSC_normal, // normal context
1991 DSC_class, // class context, enables 'friend'
1992 DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
1993 DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
1994 DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration
1995 DSC_top_level, // top-level/namespace declaration context
1996 DSC_template_param, // template parameter context
1997 DSC_template_type_arg, // template type argument context
1998 DSC_objc_method_result, // ObjC method result context, enables 'instancetype'
1999 DSC_condition // condition declaration context
2002 /// Is this a context in which we are parsing just a type-specifier (or
2003 /// trailing-type-specifier)?
2004 static bool isTypeSpecifier(DeclSpecContext DSC) {
2006 case DeclSpecContext::DSC_normal:
2007 case DeclSpecContext::DSC_template_param:
2008 case DeclSpecContext::DSC_class:
2009 case DeclSpecContext::DSC_top_level:
2010 case DeclSpecContext::DSC_objc_method_result:
2011 case DeclSpecContext::DSC_condition:
2014 case DeclSpecContext::DSC_template_type_arg:
2015 case DeclSpecContext::DSC_type_specifier:
2016 case DeclSpecContext::DSC_trailing:
2017 case DeclSpecContext::DSC_alias_declaration:
2020 llvm_unreachable("Missing DeclSpecContext case");
2023 /// Is this a context in which we can perform class template argument
2025 static bool isClassTemplateDeductionContext(DeclSpecContext DSC) {
2027 case DeclSpecContext::DSC_normal:
2028 case DeclSpecContext::DSC_template_param:
2029 case DeclSpecContext::DSC_class:
2030 case DeclSpecContext::DSC_top_level:
2031 case DeclSpecContext::DSC_condition:
2032 case DeclSpecContext::DSC_type_specifier:
2035 case DeclSpecContext::DSC_objc_method_result:
2036 case DeclSpecContext::DSC_template_type_arg:
2037 case DeclSpecContext::DSC_trailing:
2038 case DeclSpecContext::DSC_alias_declaration:
2041 llvm_unreachable("Missing DeclSpecContext case");
2044 /// Information on a C++0x for-range-initializer found while parsing a
2045 /// declaration which turns out to be a for-range-declaration.
2046 struct ForRangeInit {
2047 SourceLocation ColonLoc;
2048 ExprResult RangeExpr;
2050 bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
2052 struct ForRangeInfo : ForRangeInit {
2056 DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context,
2057 SourceLocation &DeclEnd,
2058 ParsedAttributesWithRange &attrs);
2059 DeclGroupPtrTy ParseSimpleDeclaration(DeclaratorContext Context,
2060 SourceLocation &DeclEnd,
2061 ParsedAttributesWithRange &attrs,
2063 ForRangeInit *FRI = nullptr);
2064 bool MightBeDeclarator(DeclaratorContext Context);
2065 DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context,
2066 SourceLocation *DeclEnd = nullptr,
2067 ForRangeInit *FRI = nullptr);
2068 Decl *ParseDeclarationAfterDeclarator(Declarator &D,
2069 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
2070 bool ParseAsmAttributesAfterDeclarator(Declarator &D);
2071 Decl *ParseDeclarationAfterDeclaratorAndAttributes(
2073 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2074 ForRangeInit *FRI = nullptr);
2075 Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
2076 Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
2078 /// When in code-completion, skip parsing of the function/method body
2079 /// unless the body contains the code-completion point.
2081 /// \returns true if the function body was skipped.
2082 bool trySkippingFunctionBody();
2084 bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2085 const ParsedTemplateInfo &TemplateInfo,
2086 AccessSpecifier AS, DeclSpecContext DSC,
2087 ParsedAttributesWithRange &Attrs);
2089 getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context);
2090 void ParseDeclarationSpecifiers(
2092 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2093 AccessSpecifier AS = AS_none,
2094 DeclSpecContext DSC = DeclSpecContext::DSC_normal,
2095 LateParsedAttrList *LateAttrs = nullptr);
2096 bool DiagnoseMissingSemiAfterTagDefinition(
2097 DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext,
2098 LateParsedAttrList *LateAttrs = nullptr);
2100 void ParseSpecifierQualifierList(
2101 DeclSpec &DS, AccessSpecifier AS = AS_none,
2102 DeclSpecContext DSC = DeclSpecContext::DSC_normal);
2104 void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
2105 DeclaratorContext Context);
2107 void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
2108 const ParsedTemplateInfo &TemplateInfo,
2109 AccessSpecifier AS, DeclSpecContext DSC);
2110 void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
2111 void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType,
2114 void ParseStructDeclaration(
2115 ParsingDeclSpec &DS,
2116 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback);
2118 bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
2119 bool isTypeSpecifierQualifier();
2121 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
2122 /// is definitely a type-specifier. Return false if it isn't part of a type
2123 /// specifier or if we're not sure.
2124 bool isKnownToBeTypeSpecifier(const Token &Tok) const;
2126 /// Return true if we know that we are definitely looking at a
2127 /// decl-specifier, and isn't part of an expression such as a function-style
2128 /// cast. Return false if it's no a decl-specifier, or we're not sure.
2129 bool isKnownToBeDeclarationSpecifier() {
2130 if (getLangOpts().CPlusPlus)
2131 return isCXXDeclarationSpecifier() == TPResult::True;
2132 return isDeclarationSpecifier(true);
2135 /// isDeclarationStatement - Disambiguates between a declaration or an
2136 /// expression statement, when parsing function bodies.
2137 /// Returns true for declaration, false for expression.
2138 bool isDeclarationStatement() {
2139 if (getLangOpts().CPlusPlus)
2140 return isCXXDeclarationStatement();
2141 return isDeclarationSpecifier(true);
2144 /// isForInitDeclaration - Disambiguates between a declaration or an
2145 /// expression in the context of the C 'clause-1' or the C++
2146 // 'for-init-statement' part of a 'for' statement.
2147 /// Returns true for declaration, false for expression.
2148 bool isForInitDeclaration() {
2149 if (getLangOpts().OpenMP)
2150 Actions.startOpenMPLoop();
2151 if (getLangOpts().CPlusPlus)
2152 return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
2153 return isDeclarationSpecifier(true);
2156 /// Determine whether this is a C++1z for-range-identifier.
2157 bool isForRangeIdentifier();
2159 /// Determine whether we are currently at the start of an Objective-C
2160 /// class message that appears to be missing the open bracket '['.
2161 bool isStartOfObjCClassMessageMissingOpenBracket();
2163 /// Starting with a scope specifier, identifier, or
2164 /// template-id that refers to the current class, determine whether
2165 /// this is a constructor declarator.
2166 bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false);
2168 /// Specifies the context in which type-id/expression
2169 /// disambiguation will occur.
2170 enum TentativeCXXTypeIdContext {
2173 TypeIdAsTemplateArgument
2177 /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
2178 /// whether the parens contain an expression or a type-id.
2179 /// Returns true for a type-id and false for an expression.
2180 bool isTypeIdInParens(bool &isAmbiguous) {
2181 if (getLangOpts().CPlusPlus)
2182 return isCXXTypeId(TypeIdInParens, isAmbiguous);
2183 isAmbiguous = false;
2184 return isTypeSpecifierQualifier();
2186 bool isTypeIdInParens() {
2188 return isTypeIdInParens(isAmbiguous);
2191 /// Checks if the current tokens form type-id or expression.
2192 /// It is similar to isTypeIdInParens but does not suppose that type-id
2193 /// is in parenthesis.
2194 bool isTypeIdUnambiguously() {
2196 if (getLangOpts().CPlusPlus)
2197 return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous);
2198 return isTypeSpecifierQualifier();
2201 /// isCXXDeclarationStatement - C++-specialized function that disambiguates
2202 /// between a declaration or an expression statement, when parsing function
2203 /// bodies. Returns true for declaration, false for expression.
2204 bool isCXXDeclarationStatement();
2206 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
2207 /// between a simple-declaration or an expression-statement.
2208 /// If during the disambiguation process a parsing error is encountered,
2209 /// the function returns true to let the declaration parsing code handle it.
2210 /// Returns false if the statement is disambiguated as expression.
2211 bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
2213 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
2214 /// a constructor-style initializer, when parsing declaration statements.
2215 /// Returns true for function declarator and false for constructor-style
2216 /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
2217 /// might be a constructor-style initializer.
2218 /// If during the disambiguation process a parsing error is encountered,
2219 /// the function returns true to let the declaration parsing code handle it.
2220 bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr);
2222 struct ConditionDeclarationOrInitStatementState;
2223 enum class ConditionOrInitStatement {
2224 Expression, ///< Disambiguated as an expression (either kind).
2225 ConditionDecl, ///< Disambiguated as the declaration form of condition.
2226 InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement.
2227 ForRangeDecl, ///< Disambiguated as a for-range declaration.
2228 Error ///< Can't be any of the above!
2230 /// Disambiguates between the different kinds of things that can happen
2231 /// after 'if (' or 'switch ('. This could be one of two different kinds of
2232 /// declaration (depending on whether there is a ';' later) or an expression.
2233 ConditionOrInitStatement
2234 isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt,
2235 bool CanBeForRangeDecl);
2237 bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
2238 bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
2240 return isCXXTypeId(Context, isAmbiguous);
2243 /// TPResult - Used as the result value for functions whose purpose is to
2244 /// disambiguate C++ constructs by "tentatively parsing" them.
2245 enum class TPResult {
2246 True, False, Ambiguous, Error
2249 /// Based only on the given token kind, determine whether we know that
2250 /// we're at the start of an expression or a type-specifier-seq (which may
2251 /// be an expression, in C++).
2253 /// This routine does not attempt to resolve any of the trick cases, e.g.,
2254 /// those involving lookup of identifiers.
2256 /// \returns \c TPR_true if this token starts an expression, \c TPR_false if
2257 /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot
2259 TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind);
2261 /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a
2262 /// declaration specifier, TPResult::False if it is not,
2263 /// TPResult::Ambiguous if it could be either a decl-specifier or a
2264 /// function-style cast, and TPResult::Error if a parsing error was
2265 /// encountered. If it could be a braced C++11 function-style cast, returns
2266 /// BracedCastResult.
2267 /// Doesn't consume tokens.
2269 isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False,
2270 bool *HasMissingTypename = nullptr);
2272 /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
2273 /// \c TPResult::Ambiguous, determine whether the decl-specifier would be
2274 /// a type-specifier other than a cv-qualifier.
2275 bool isCXXDeclarationSpecifierAType();
2277 /// Determine whether an identifier has been tentatively declared as a
2278 /// non-type. Such tentative declarations should not be found to name a type
2279 /// during a tentative parse, but also should not be annotated as a non-type.
2280 bool isTentativelyDeclared(IdentifierInfo *II);
2282 // "Tentative parsing" functions, used for disambiguation. If a parsing error
2283 // is encountered they will return TPResult::Error.
2284 // Returning TPResult::True/False indicates that the ambiguity was
2285 // resolved and tentative parsing may stop. TPResult::Ambiguous indicates
2286 // that more tentative parsing is necessary for disambiguation.
2287 // They all consume tokens, so backtracking should be used after calling them.
2289 TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
2290 TPResult TryParseTypeofSpecifier();
2291 TPResult TryParseProtocolQualifiers();
2292 TPResult TryParsePtrOperatorSeq();
2293 TPResult TryParseOperatorId();
2294 TPResult TryParseInitDeclaratorList();
2295 TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true,
2296 bool mayHaveDirectInit = false);
2298 TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr,
2299 bool VersusTemplateArg = false);
2300 TPResult TryParseFunctionDeclarator();
2301 TPResult TryParseBracketDeclarator();
2302 TPResult TryConsumeDeclarationSpecifier();
2305 TypeResult ParseTypeName(SourceRange *Range = nullptr,
2306 DeclaratorContext Context
2307 = DeclaratorContext::TypeNameContext,
2308 AccessSpecifier AS = AS_none,
2309 Decl **OwnedType = nullptr,
2310 ParsedAttributes *Attrs = nullptr);
2313 void ParseBlockId(SourceLocation CaretLoc);
2315 /// Are [[]] attributes enabled?
2316 bool standardAttributesAllowed() const {
2317 const LangOptions &LO = getLangOpts();
2318 return LO.DoubleSquareBracketAttributes;
2321 // Check for the start of an attribute-specifier-seq in a context where an
2322 // attribute is not allowed.
2323 bool CheckProhibitedCXX11Attribute() {
2324 assert(Tok.is(tok::l_square));
2325 if (!standardAttributesAllowed() || NextToken().isNot(tok::l_square))
2327 return DiagnoseProhibitedCXX11Attribute();
2330 bool DiagnoseProhibitedCXX11Attribute();
2331 void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2332 SourceLocation CorrectLocation) {
2333 if (!standardAttributesAllowed())
2335 if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
2336 Tok.isNot(tok::kw_alignas))
2338 DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
2340 void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2341 SourceLocation CorrectLocation);
2343 void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
2344 DeclSpec &DS, Sema::TagUseKind TUK);
2346 // FixItLoc = possible correct location for the attributes
2347 void ProhibitAttributes(ParsedAttributesWithRange &Attrs,
2348 SourceLocation FixItLoc = SourceLocation()) {
2349 if (Attrs.Range.isInvalid())
2351 DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc);
2355 void ProhibitAttributes(ParsedAttributesViewWithRange &Attrs,
2356 SourceLocation FixItLoc = SourceLocation()) {
2357 if (Attrs.Range.isInvalid())
2359 DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc);
2360 Attrs.clearListOnly();
2362 void DiagnoseProhibitedAttributes(const SourceRange &Range,
2363 SourceLocation FixItLoc);
2365 // Forbid C++11 and C2x attributes that appear on certain syntactic locations
2366 // which standard permits but we don't supported yet, for example, attributes
2367 // appertain to decl specifiers.
2368 void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
2371 /// Skip C++11 and C2x attributes and return the end location of the
2373 /// \returns SourceLocation() if there are no attributes.
2374 SourceLocation SkipCXX11Attributes();
2376 /// Diagnose and skip C++11 and C2x attributes that appear in syntactic
2377 /// locations where attributes are not allowed.
2378 void DiagnoseAndSkipCXX11Attributes();
2380 /// Parses syntax-generic attribute arguments for attributes which are
2381 /// known to the implementation, and adds them to the given ParsedAttributes
2382 /// list with the given attribute syntax. Returns the number of arguments
2383 /// parsed for the attribute.
2385 ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2386 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2387 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2388 ParsedAttr::Syntax Syntax);
2390 void MaybeParseGNUAttributes(Declarator &D,
2391 LateParsedAttrList *LateAttrs = nullptr) {
2392 if (Tok.is(tok::kw___attribute)) {
2393 ParsedAttributes attrs(AttrFactory);
2394 SourceLocation endLoc;
2395 ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D);
2396 D.takeAttributes(attrs, endLoc);
2399 void MaybeParseGNUAttributes(ParsedAttributes &attrs,
2400 SourceLocation *endLoc = nullptr,
2401 LateParsedAttrList *LateAttrs = nullptr) {
2402 if (Tok.is(tok::kw___attribute))
2403 ParseGNUAttributes(attrs, endLoc, LateAttrs);
2405 void ParseGNUAttributes(ParsedAttributes &attrs,
2406 SourceLocation *endLoc = nullptr,
2407 LateParsedAttrList *LateAttrs = nullptr,
2408 Declarator *D = nullptr);
2409 void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
2410 SourceLocation AttrNameLoc,
2411 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2412 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2413 ParsedAttr::Syntax Syntax, Declarator *D);
2414 IdentifierLoc *ParseIdentifierLoc();
2417 ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2418 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2419 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2420 ParsedAttr::Syntax Syntax);
2422 void MaybeParseCXX11Attributes(Declarator &D) {
2423 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
2424 ParsedAttributesWithRange attrs(AttrFactory);
2425 SourceLocation endLoc;
2426 ParseCXX11Attributes(attrs, &endLoc);
2427 D.takeAttributes(attrs, endLoc);
2430 void MaybeParseCXX11Attributes(ParsedAttributes &attrs,
2431 SourceLocation *endLoc = nullptr) {
2432 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
2433 ParsedAttributesWithRange attrsWithRange(AttrFactory);
2434 ParseCXX11Attributes(attrsWithRange, endLoc);
2435 attrs.takeAllFrom(attrsWithRange);
2438 void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2439 SourceLocation *endLoc = nullptr,
2440 bool OuterMightBeMessageSend = false) {
2441 if (standardAttributesAllowed() &&
2442 isCXX11AttributeSpecifier(false, OuterMightBeMessageSend))
2443 ParseCXX11Attributes(attrs, endLoc);
2446 void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
2447 SourceLocation *EndLoc = nullptr);
2448 void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2449 SourceLocation *EndLoc = nullptr);
2450 /// Parses a C++11 (or C2x)-style attribute argument list. Returns true
2451 /// if this results in adding an attribute to the ParsedAttributes list.
2452 bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
2453 SourceLocation AttrNameLoc,
2454 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2455 IdentifierInfo *ScopeName,
2456 SourceLocation ScopeLoc);
2458 IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc);
2460 void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
2461 SourceLocation *endLoc = nullptr) {
2462 if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
2463 ParseMicrosoftAttributes(attrs, endLoc);
2465 void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs);
2466 void ParseMicrosoftAttributes(ParsedAttributes &attrs,
2467 SourceLocation *endLoc = nullptr);
2468 void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2469 SourceLocation *End = nullptr) {
2470 const auto &LO = getLangOpts();
2471 if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec))
2472 ParseMicrosoftDeclSpecs(Attrs, End);
2474 void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2475 SourceLocation *End = nullptr);
2476 bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
2477 SourceLocation AttrNameLoc,
2478 ParsedAttributes &Attrs);
2479 void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
2480 void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2481 SourceLocation SkipExtendedMicrosoftTypeAttributes();
2482 void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
2483 void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
2484 void ParseOpenCLKernelAttributes(ParsedAttributes &attrs);
2485 void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
2486 /// Parses opencl_unroll_hint attribute if language is OpenCL v2.0
2488 /// \return false if error happens.
2489 bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
2490 if (getLangOpts().OpenCL)
2491 return ParseOpenCLUnrollHintAttribute(Attrs);
2494 /// Parses opencl_unroll_hint attribute.
2495 /// \return false if error happens.
2496 bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs);
2497 void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
2499 VersionTuple ParseVersionTuple(SourceRange &Range);
2500 void ParseAvailabilityAttribute(IdentifierInfo &Availability,
2501 SourceLocation AvailabilityLoc,
2502 ParsedAttributes &attrs,
2503 SourceLocation *endLoc,
2504 IdentifierInfo *ScopeName,
2505 SourceLocation ScopeLoc,
2506 ParsedAttr::Syntax Syntax);
2508 Optional<AvailabilitySpec> ParseAvailabilitySpec();
2509 ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc);
2511 void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol,
2513 ParsedAttributes &Attrs,
2514 SourceLocation *EndLoc,
2515 IdentifierInfo *ScopeName,
2516 SourceLocation ScopeLoc,
2517 ParsedAttr::Syntax Syntax);
2519 void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
2520 SourceLocation ObjCBridgeRelatedLoc,
2521 ParsedAttributes &attrs,
2522 SourceLocation *endLoc,
2523 IdentifierInfo *ScopeName,
2524 SourceLocation ScopeLoc,
2525 ParsedAttr::Syntax Syntax);
2527 void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
2528 SourceLocation AttrNameLoc,
2529 ParsedAttributes &Attrs,
2530 SourceLocation *EndLoc,
2531 IdentifierInfo *ScopeName,
2532 SourceLocation ScopeLoc,
2533 ParsedAttr::Syntax Syntax);
2536 ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
2537 SourceLocation AttrNameLoc, ParsedAttributes &Attrs,
2538 SourceLocation *EndLoc, IdentifierInfo *ScopeName,
2539 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax);
2541 void ParseTypeofSpecifier(DeclSpec &DS);
2542 SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
2543 void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
2544 SourceLocation StartLoc,
2545 SourceLocation EndLoc);
2546 void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
2547 void ParseAtomicSpecifier(DeclSpec &DS);
2549 ExprResult ParseAlignArgument(SourceLocation Start,
2550 SourceLocation &EllipsisLoc);
2551 void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2552 SourceLocation *endLoc = nullptr);
2554 VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
2555 VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
2556 return isCXX11VirtSpecifier(Tok);
2558 void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface,
2559 SourceLocation FriendLoc);
2561 bool isCXX11FinalKeyword() const;
2563 /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
2564 /// enter a new C++ declarator scope and exit it when the function is
2566 class DeclaratorScopeObj {
2572 DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
2573 : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
2575 void EnterDeclaratorScope() {
2576 assert(!EnteredScope && "Already entered the scope!");
2577 assert(SS.isSet() && "C++ scope was not set!");
2579 CreatedScope = true;
2580 P.EnterScope(0); // Not a decl scope.
2582 if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
2583 EnteredScope = true;
2586 ~DeclaratorScopeObj() {
2588 assert(SS.isSet() && "C++ scope was cleared ?");
2589 P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
2596 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
2597 void ParseDeclarator(Declarator &D);
2598 /// A function that parses a variant of direct-declarator.
2599 typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
2600 void ParseDeclaratorInternal(Declarator &D,
2601 DirectDeclParseFunction DirectDeclParser);
2603 enum AttrRequirements {
2604 AR_NoAttributesParsed = 0, ///< No attributes are diagnosed.
2605 AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes.
2606 AR_GNUAttributesParsed = 1 << 1,
2607 AR_CXX11AttributesParsed = 1 << 2,
2608 AR_DeclspecAttributesParsed = 1 << 3,
2609 AR_AllAttributesParsed = AR_GNUAttributesParsed |
2610 AR_CXX11AttributesParsed |
2611 AR_DeclspecAttributesParsed,
2612 AR_VendorAttributesParsed = AR_GNUAttributesParsed |
2613 AR_DeclspecAttributesParsed
2616 void ParseTypeQualifierListOpt(
2617 DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed,
2618 bool AtomicAllowed = true, bool IdentifierRequired = false,
2619 Optional<llvm::function_ref<void()>> CodeCompletionHandler = None);
2620 void ParseDirectDeclarator(Declarator &D);
2621 void ParseDecompositionDeclarator(Declarator &D);
2622 void ParseParenDeclarator(Declarator &D);
2623 void ParseFunctionDeclarator(Declarator &D,
2624 ParsedAttributes &attrs,
2625 BalancedDelimiterTracker &Tracker,
2627 bool RequiresArg = false);
2628 bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
2629 SourceLocation &RefQualifierLoc);
2630 bool isFunctionDeclaratorIdentifierList();
2631 void ParseFunctionDeclaratorIdentifierList(
2633 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
2634 void ParseParameterDeclarationClause(
2636 ParsedAttributes &attrs,
2637 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
2638 SourceLocation &EllipsisLoc);
2639 void ParseBracketDeclarator(Declarator &D);
2640 void ParseMisplacedBracketDeclarator(Declarator &D);
2642 //===--------------------------------------------------------------------===//
2643 // C++ 7: Declarations [dcl.dcl]
2645 /// The kind of attribute specifier we have found.
2646 enum CXX11AttributeKind {
2647 /// This is not an attribute specifier.
2648 CAK_NotAttributeSpecifier,
2649 /// This should be treated as an attribute-specifier.
2650 CAK_AttributeSpecifier,
2651 /// The next tokens are '[[', but this is not an attribute-specifier. This
2652 /// is ill-formed by C++11 [dcl.attr.grammar]p6.
2653 CAK_InvalidAttributeSpecifier
2656 isCXX11AttributeSpecifier(bool Disambiguate = false,
2657 bool OuterMightBeMessageSend = false);
2659 void DiagnoseUnexpectedNamespace(NamedDecl *Context);
2661 DeclGroupPtrTy ParseNamespace(DeclaratorContext Context,
2662 SourceLocation &DeclEnd,
2663 SourceLocation InlineLoc = SourceLocation());
2665 struct InnerNamespaceInfo {
2666 SourceLocation NamespaceLoc;
2667 SourceLocation InlineLoc;
2668 SourceLocation IdentLoc;
2669 IdentifierInfo *Ident;
2671 using InnerNamespaceInfoList = llvm::SmallVector<InnerNamespaceInfo, 4>;
2673 void ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs,
2674 unsigned int index, SourceLocation &InlineLoc,
2675 ParsedAttributes &attrs,
2676 BalancedDelimiterTracker &Tracker);
2677 Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context);
2678 Decl *ParseExportDeclaration();
2679 DeclGroupPtrTy ParseUsingDirectiveOrDeclaration(
2680 DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
2681 SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs);
2682 Decl *ParseUsingDirective(DeclaratorContext Context,
2683 SourceLocation UsingLoc,
2684 SourceLocation &DeclEnd,
2685 ParsedAttributes &attrs);
2687 struct UsingDeclarator {
2688 SourceLocation TypenameLoc;
2691 SourceLocation EllipsisLoc;
2694 TypenameLoc = EllipsisLoc = SourceLocation();
2700 bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D);
2701 DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context,
2702 const ParsedTemplateInfo &TemplateInfo,
2703 SourceLocation UsingLoc,
2704 SourceLocation &DeclEnd,
2705 AccessSpecifier AS = AS_none);
2706 Decl *ParseAliasDeclarationAfterDeclarator(
2707 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
2708 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
2709 ParsedAttributes &Attrs, Decl **OwnedType = nullptr);
2711 Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
2712 Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
2713 SourceLocation AliasLoc, IdentifierInfo *Alias,
2714 SourceLocation &DeclEnd);
2716 //===--------------------------------------------------------------------===//
2717 // C++ 9: classes [class] and C structs/unions.
2718 bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
2719 void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
2720 DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo,
2721 AccessSpecifier AS, bool EnteringContext,
2722 DeclSpecContext DSC,
2723 ParsedAttributesWithRange &Attributes);
2724 void SkipCXXMemberSpecification(SourceLocation StartLoc,
2725 SourceLocation AttrFixitLoc,
2728 void ParseCXXMemberSpecification(SourceLocation StartLoc,
2729 SourceLocation AttrFixitLoc,
2730 ParsedAttributesWithRange &Attrs,
2733 ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2734 SourceLocation &EqualLoc);
2735 bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
2737 ExprResult &BitfieldSize,
2738 LateParsedAttrList &LateAttrs);
2739 void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D,
2740 VirtSpecifiers &VS);
2741 DeclGroupPtrTy ParseCXXClassMemberDeclaration(
2742 AccessSpecifier AS, ParsedAttributes &Attr,
2743 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2744 ParsingDeclRAIIObject *DiagsFromTParams = nullptr);
2745 DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas(
2746 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
2747 DeclSpec::TST TagType, Decl *Tag);
2748 void ParseConstructorInitializer(Decl *ConstructorDecl);
2749 MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
2750 void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2753 //===--------------------------------------------------------------------===//
2754 // C++ 10: Derived classes [class.derived]
2755 TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
2756 SourceLocation &EndLocation);
2757 void ParseBaseClause(Decl *ClassDecl);
2758 BaseResult ParseBaseSpecifier(Decl *ClassDecl);
2759 AccessSpecifier getAccessSpecifierIfPresent() const;
2761 bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
2762 SourceLocation TemplateKWLoc,
2763 IdentifierInfo *Name,
2764 SourceLocation NameLoc,
2765 bool EnteringContext,
2766 ParsedType ObjectType,
2768 bool AssumeTemplateId);
2769 bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2770 ParsedType ObjectType,
2771 UnqualifiedId &Result);
2773 //===--------------------------------------------------------------------===//
2774 // OpenMP: Directives and clauses.
2775 /// Parse clauses for '#pragma omp declare simd'.
2776 DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr,
2778 SourceLocation Loc);
2779 /// Parse clauses for '#pragma omp declare target'.
2780 DeclGroupPtrTy ParseOMPDeclareTargetClauses();
2781 /// Parse '#pragma omp end declare target'.
2782 void ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind DKind,
2783 SourceLocation Loc);
2784 /// Parses declarative OpenMP directives.
2785 DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl(
2786 AccessSpecifier &AS, ParsedAttributesWithRange &Attrs,
2787 DeclSpec::TST TagType = DeclSpec::TST_unspecified,
2788 Decl *TagDecl = nullptr);
2789 /// Parse 'omp declare reduction' construct.
2790 DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS);
2791 /// Parses initializer for provided omp_priv declaration inside the reduction
2793 void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm);
2795 /// Parses simple list of variables.
2797 /// \param Kind Kind of the directive.
2798 /// \param Callback Callback function to be called for the list elements.
2799 /// \param AllowScopeSpecifier true, if the variables can have fully
2800 /// qualified names.
2802 bool ParseOpenMPSimpleVarList(
2803 OpenMPDirectiveKind Kind,
2804 const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
2806 bool AllowScopeSpecifier);
2807 /// Parses declarative or executable directive.
2809 /// \param Allowed ACK_Any, if any directives are allowed,
2810 /// ACK_StatementsOpenMPAnyExecutable - if any executable directives are
2811 /// allowed, ACK_StatementsOpenMPNonStandalone - if only non-standalone
2812 /// executable directives are allowed.
2815 ParseOpenMPDeclarativeOrExecutableDirective(AllowedConstructsKind Allowed);
2816 /// Parses clause of kind \a CKind for directive of a kind \a Kind.
2818 /// \param DKind Kind of current directive.
2819 /// \param CKind Kind of current clause.
2820 /// \param FirstClause true, if this is the first clause of a kind \a CKind
2821 /// in current directive.
2823 OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
2824 OpenMPClauseKind CKind, bool FirstClause);
2825 /// Parses clause with a single expression of a kind \a Kind.
2827 /// \param Kind Kind of current clause.
2828 /// \param ParseOnly true to skip the clause's semantic actions and return
2831 OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind,
2833 /// Parses simple clause of a kind \a Kind.
2835 /// \param Kind Kind of current clause.
2836 /// \param ParseOnly true to skip the clause's semantic actions and return
2839 OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly);
2840 /// Parses clause with a single expression and an additional argument
2841 /// of a kind \a Kind.
2843 /// \param Kind Kind of current clause.
2844 /// \param ParseOnly true to skip the clause's semantic actions and return
2847 OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind,
2849 /// Parses clause without any additional arguments.
2851 /// \param Kind Kind of current clause.
2852 /// \param ParseOnly true to skip the clause's semantic actions and return
2855 OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false);
2856 /// Parses clause with the list of variables of a kind \a Kind.
2858 /// \param Kind Kind of current clause.
2859 /// \param ParseOnly true to skip the clause's semantic actions and return
2862 OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
2863 OpenMPClauseKind Kind, bool ParseOnly);
2866 /// Parses simple expression in parens for single-expression clauses of OpenMP
2868 /// \param RLoc Returned location of right paren.
2869 ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc);
2871 /// Data used for parsing list of variables in OpenMP clauses.
2872 struct OpenMPVarListDataTy {
2873 Expr *TailExpr = nullptr;
2874 SourceLocation ColonLoc;
2875 SourceLocation RLoc;
2876 CXXScopeSpec ReductionIdScopeSpec;
2877 DeclarationNameInfo ReductionId;
2878 OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown;
2879 OpenMPLinearClauseKind LinKind = OMPC_LINEAR_val;
2880 SmallVector<OpenMPMapModifierKind, OMPMapClause::NumberOfModifiers>
2882 SmallVector<SourceLocation, OMPMapClause::NumberOfModifiers>
2883 MapTypeModifiersLoc;
2884 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
2885 bool IsMapTypeImplicit = false;
2886 SourceLocation DepLinMapLoc;
2889 /// Parses clauses with list.
2890 bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind,
2891 SmallVectorImpl<Expr *> &Vars,
2892 OpenMPVarListDataTy &Data);
2893 bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2894 bool AllowDestructorName,
2895 bool AllowConstructorName,
2896 bool AllowDeductionGuide,
2897 ParsedType ObjectType,
2898 SourceLocation *TemplateKWLoc,
2899 UnqualifiedId &Result);
2902 //===--------------------------------------------------------------------===//
2903 // C++ 14: Templates [temp]
2905 // C++ 14.1: Template Parameters [temp.param]
2906 Decl *ParseDeclarationStartingWithTemplate(DeclaratorContext Context,
2907 SourceLocation &DeclEnd,
2908 ParsedAttributes &AccessAttrs,
2909 AccessSpecifier AS = AS_none);
2910 Decl *ParseTemplateDeclarationOrSpecialization(DeclaratorContext Context,
2911 SourceLocation &DeclEnd,
2912 ParsedAttributes &AccessAttrs,
2913 AccessSpecifier AS);
2914 Decl *ParseSingleDeclarationAfterTemplate(
2915 DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
2916 ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd,
2917 ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none);
2918 bool ParseTemplateParameters(unsigned Depth,
2919 SmallVectorImpl<NamedDecl *> &TemplateParams,
2920 SourceLocation &LAngleLoc,
2921 SourceLocation &RAngleLoc);
2922 bool ParseTemplateParameterList(unsigned Depth,
2923 SmallVectorImpl<NamedDecl*> &TemplateParams);
2924 bool isStartOfTemplateTypeParameter();
2925 NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position);
2926 NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position);
2927 NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
2928 NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
2929 void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
2930 SourceLocation CorrectLoc,
2931 bool AlreadyHasEllipsis,
2932 bool IdentifierHasName);
2933 void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
2935 // C++ 14.3: Template arguments [temp.arg]
2936 typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
2938 bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
2939 bool ConsumeLastToken,
2940 bool ObjCGenericList);
2941 bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
2942 SourceLocation &LAngleLoc,
2943 TemplateArgList &TemplateArgs,
2944 SourceLocation &RAngleLoc);
2946 bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
2948 SourceLocation TemplateKWLoc,
2949 UnqualifiedId &TemplateName,
2950 bool AllowTypeAnnotation = true);
2951 void AnnotateTemplateIdTokenAsType(bool IsClassName = false);
2952 bool IsTemplateArgumentList(unsigned Skip = 0);
2953 bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
2954 ParsedTemplateArgument ParseTemplateTemplateArgument();
2955 ParsedTemplateArgument ParseTemplateArgument();
2956 Decl *ParseExplicitInstantiation(DeclaratorContext Context,
2957 SourceLocation ExternLoc,
2958 SourceLocation TemplateLoc,
2959 SourceLocation &DeclEnd,
2960 ParsedAttributes &AccessAttrs,
2961 AccessSpecifier AS = AS_none);
2963 //===--------------------------------------------------------------------===//
2965 DeclGroupPtrTy ParseModuleDecl();
2966 Decl *ParseModuleImport(SourceLocation AtLoc);
2967 bool parseMisplacedModuleImport();
2968 bool tryParseMisplacedModuleImport() {
2969 tok::TokenKind Kind = Tok.getKind();
2970 if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end ||
2971 Kind == tok::annot_module_include)
2972 return parseMisplacedModuleImport();
2976 bool ParseModuleName(
2977 SourceLocation UseLoc,
2978 SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
2981 //===--------------------------------------------------------------------===//
2982 // C++11/G++: Type Traits [Type-Traits.html in the GCC manual]
2983 ExprResult ParseTypeTrait();
2985 //===--------------------------------------------------------------------===//
2986 // Embarcadero: Arary and Expression Traits
2987 ExprResult ParseArrayTypeTrait();
2988 ExprResult ParseExpressionTrait();
2990 //===--------------------------------------------------------------------===//
2991 // Preprocessor code-completion pass-through
2992 void CodeCompleteDirective(bool InConditional) override;
2993 void CodeCompleteInConditionalExclusion() override;
2994 void CodeCompleteMacroName(bool IsDefinition) override;
2995 void CodeCompletePreprocessorExpression() override;
2996 void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo,
2997 unsigned ArgumentIndex) override;
2998 void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) override;
2999 void CodeCompleteNaturalLanguage() override;
3002 } // end namespace clang