clang 23.0.0git
ParseCXXInlineMethods.cpp
Go to the documentation of this file.
1//===--- ParseCXXInlineMethods.cpp - C++ class inline methods parsing------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements parsing for C++ class inline methods.
10//
11//===----------------------------------------------------------------------===//
12
15#include "clang/Parse/Parser.h"
17#include "clang/Sema/DeclSpec.h"
19#include "clang/Sema/Scope.h"
20#include "llvm/ADT/ScopeExit.h"
21
22using namespace clang;
23
24StringLiteral *Parser::ParseCXXDeletedFunctionMessage() {
25 if (!Tok.is(tok::l_paren))
26 return nullptr;
27 StringLiteral *Message = nullptr;
28 BalancedDelimiterTracker BT{*this, tok::l_paren};
29 BT.consumeOpen();
30
31 if (isTokenStringLiteral()) {
33 if (Res.isUsable()) {
34 Message = Res.getAs<StringLiteral>();
35 Diag(Message->getBeginLoc(), getLangOpts().CPlusPlus26
36 ? diag::warn_cxx23_delete_with_message
37 : diag::ext_delete_with_message)
38 << Message->getSourceRange();
39 }
40 } else {
41 Diag(Tok.getLocation(), diag::err_expected_string_literal)
42 << /*Source='in'*/ 0 << "'delete'";
43 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
44 }
45
46 BT.consumeClose();
47 return Message;
48}
49
50void Parser::SkipDeletedFunctionBody() {
51 if (!Tok.is(tok::l_paren))
52 return;
53
54 BalancedDelimiterTracker BT{*this, tok::l_paren};
55 BT.consumeOpen();
56
57 // Just skip to the end of the current declaration.
58 SkipUntil(tok::r_paren, tok::comma, StopAtSemi | StopBeforeMatch);
59 if (Tok.is(tok::r_paren))
60 BT.consumeClose();
61}
62
63NamedDecl *Parser::ParseCXXInlineMethodDef(
64 AccessSpecifier AS, const ParsedAttributesView &AccessAttrs,
65 ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo,
66 const VirtSpecifiers &VS, SourceLocation PureSpecLoc) {
67 assert(D.isFunctionDeclarator() && "This isn't a function declarator!");
68 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try, tok::equal) &&
69 "Current token not a '{', ':', '=', or 'try'!");
70
71 MultiTemplateParamsArg TemplateParams(
72 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data()
73 : nullptr,
74 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0);
75
76 NamedDecl *FnD;
78 FnD = Actions.ActOnFriendFunctionDecl(getCurScope(), D,
79 TemplateParams);
80 else {
81 FnD = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, D,
82 TemplateParams, nullptr,
83 VS, ICIS_NoInit);
84 if (FnD) {
85 Actions.ProcessDeclAttributeList(getCurScope(), FnD, AccessAttrs);
86 if (PureSpecLoc.isValid())
87 Actions.ActOnPureSpecifier(FnD, PureSpecLoc);
88 }
89 }
90
91 if (FnD)
92 HandleMemberFunctionDeclDelays(D, FnD);
93
94 D.complete(FnD);
95
96 if (TryConsumeToken(tok::equal)) {
97 if (!FnD) {
98 SkipUntil(tok::semi);
99 return nullptr;
100 }
101
102 bool Delete = false;
103 SourceLocation KWLoc;
104 SourceLocation KWEndLoc = Tok.getEndLoc().getLocWithOffset(-1);
105 if (TryConsumeToken(tok::kw_delete, KWLoc)) {
107 ? diag::warn_cxx98_compat_defaulted_deleted_function
108 : diag::ext_defaulted_deleted_function)
109 << 1 /* deleted */;
110 StringLiteral *Message = ParseCXXDeletedFunctionMessage();
111 Actions.SetDeclDeleted(FnD, KWLoc, Message);
112 Delete = true;
113 if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
114 DeclAsFunction->setRangeEnd(KWEndLoc);
115 }
116 } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
118 ? diag::warn_cxx98_compat_defaulted_deleted_function
119 : diag::ext_defaulted_deleted_function)
120 << 0 /* defaulted */;
121 Actions.SetDeclDefaulted(FnD, KWLoc);
122 if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
123 DeclAsFunction->setRangeEnd(KWEndLoc);
124 }
125 } else {
126 llvm_unreachable("function definition after = not 'delete' or 'default'");
127 }
128
129 if (Tok.is(tok::comma)) {
130 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
131 << Delete;
132 SkipUntil(tok::semi);
133 } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
134 Delete ? "delete" : "default") &&
135 !isLikelyAtStartOfNewDeclaration()) {
136 SkipUntil(tok::semi);
137 }
138
139 return FnD;
140 }
141
142 if (SkipFunctionBodies && (!FnD || Actions.canSkipFunctionBody(FnD)) &&
143 trySkippingFunctionBody()) {
144 Actions.ActOnSkippedFunctionBody(FnD);
145 return FnD;
146 }
147
148 // In delayed template parsing mode, if we are within a class template
149 // or if we are about to parse function member template then consume
150 // the tokens and store them for parsing at the end of the translation unit.
151 if (getLangOpts().DelayedTemplateParsing &&
154 !(FnD && FnD->getAsFunction() &&
156 ((Actions.CurContext->isDependentContext() ||
157 (TemplateInfo.Kind != ParsedTemplateKind::NonTemplate &&
158 TemplateInfo.Kind != ParsedTemplateKind::ExplicitSpecialization)) &&
159 !Actions.IsInsideALocalClassWithinATemplateFunction())) {
160
161 CachedTokens Toks;
162 LexTemplateFunctionForLateParsing(Toks);
163
164 if (FnD) {
165 FunctionDecl *FD = FnD->getAsFunction();
166 Actions.CheckForFunctionRedefinition(FD);
167 Actions.MarkAsLateParsedTemplate(FD, FnD, Toks);
168 }
169
170 return FnD;
171 }
172
173 // Consume the tokens and store them for later parsing.
174
175 LexedMethod* LM = new LexedMethod(this, FnD);
176 getCurrentClass().LateParsedDeclarations.push_back(LM);
177 CachedTokens &Toks = LM->Toks;
178
179 tok::TokenKind kind = Tok.getKind();
180 // Consume everything up to (and including) the left brace of the
181 // function body.
182 if (ConsumeAndStoreFunctionPrologue(Toks)) {
183 // We didn't find the left-brace we expected after the
184 // constructor initializer.
185
186 // If we're code-completing and the completion point was in the broken
187 // initializer, we want to parse it even though that will fail.
188 if (PP.isCodeCompletionEnabled() &&
189 llvm::any_of(Toks, [](const Token &Tok) {
190 return Tok.is(tok::code_completion);
191 })) {
192 // If we gave up at the completion point, the initializer list was
193 // likely truncated, so don't eat more tokens. We'll hit some extra
194 // errors, but they should be ignored in code completion.
195 return FnD;
196 }
197
198 // We already printed an error, and it's likely impossible to recover,
199 // so don't try to parse this method later.
200 // Skip over the rest of the decl and back to somewhere that looks
201 // reasonable.
203 delete getCurrentClass().LateParsedDeclarations.back();
204 getCurrentClass().LateParsedDeclarations.pop_back();
205 return FnD;
206 } else {
207 // Consume everything up to (and including) the matching right brace.
208 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
209 }
210
211 // If we're in a function-try-block, we need to store all the catch blocks.
212 if (kind == tok::kw_try) {
213 while (Tok.is(tok::kw_catch)) {
214 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
215 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
216 }
217 }
218
219 if (FnD) {
220 FunctionDecl *FD = FnD->getAsFunction();
221 // Track that this function will eventually have a body; Sema needs
222 // to know this.
223 Actions.CheckForFunctionRedefinition(FD);
224 FD->setWillHaveBody(true);
225 } else {
226 // If semantic analysis could not build a function declaration,
227 // just throw away the late-parsed declaration.
228 delete getCurrentClass().LateParsedDeclarations.back();
229 getCurrentClass().LateParsedDeclarations.pop_back();
230 }
231
232 return FnD;
233}
234
235void Parser::ParseCXXNonStaticMemberInitializer(Decl *VarD) {
236 assert(Tok.isOneOf(tok::l_brace, tok::equal) &&
237 "Current token not a '{' or '='!");
238
239 LateParsedMemberInitializer *MI =
240 new LateParsedMemberInitializer(this, VarD);
241 getCurrentClass().LateParsedDeclarations.push_back(MI);
242 CachedTokens &Toks = MI->Toks;
243
244 tok::TokenKind kind = Tok.getKind();
245 if (kind == tok::equal) {
246 Toks.push_back(Tok);
247 ConsumeToken();
248 }
249
250 if (kind == tok::l_brace) {
251 // Begin by storing the '{' token.
252 Toks.push_back(Tok);
253 ConsumeBrace();
254
255 // Consume everything up to (and including) the matching right brace.
256 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/true);
257 } else {
258 // Consume everything up to (but excluding) the comma or semicolon.
259 ConsumeAndStoreInitializer(Toks, CachedInitKind::DefaultInitializer);
260 }
261
262 // Store an artificial EOF token to ensure that we don't run off the end of
263 // the initializer when we come to parse it.
264 Token Eof;
265 Eof.startToken();
266 Eof.setKind(tok::eof);
267 Eof.setLocation(Tok.getLocation());
268 Eof.setEofData(VarD);
269 Toks.push_back(Eof);
270}
271
272Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
273void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
274void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {}
275void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
276void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
277void Parser::LateParsedDeclaration::ParseLexedPragmas() {}
278
279Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C)
280 : Self(P), Class(C) {}
281
282Parser::LateParsedClass::~LateParsedClass() {
283 Self->DeallocateParsedClasses(Class);
284}
285
286void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
287 Self->ParseLexedMethodDeclarations(*Class);
288}
289
290void Parser::LateParsedClass::ParseLexedMemberInitializers() {
291 Self->ParseLexedMemberInitializers(*Class);
292}
293
294void Parser::LateParsedClass::ParseLexedMethodDefs() {
295 Self->ParseLexedMethodDefs(*Class);
296}
297
298void Parser::LateParsedClass::ParseLexedAttributes() {
299 Self->ParseLexedAttributes(*Class);
300}
301
302void Parser::LateParsedClass::ParseLexedPragmas() {
303 Self->ParseLexedPragmas(*Class);
304}
305
306void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
307 Self->ParseLexedMethodDeclaration(*this);
308}
309
310void Parser::LexedMethod::ParseLexedMethodDefs() {
311 Self->ParseLexedMethodDef(*this);
312}
313
314void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() {
315 Self->ParseLexedMemberInitializer(*this);
316}
317
318void Parser::LateParsedAttribute::ParseLexedAttributes() {
319 Self->ParseLexedAttribute(*this, true, false);
320}
321
322void Parser::LateParsedPragma::ParseLexedPragmas() {
323 Self->ParseLexedPragma(*this);
324}
325
329 TemplateParameterDepthRAII CurTemplateDepthTracker;
330
331 ReenterTemplateScopeRAII(Parser &P, Decl *MaybeTemplated, bool Enter = true)
332 : P(P), Scopes(P), CurTemplateDepthTracker(P.TemplateParameterDepth) {
333 if (Enter) {
335 P.ReenterTemplateScopes(Scopes, MaybeTemplated));
336 }
337 }
338};
339
341 ParsingClass &Class;
342
344 : ReenterTemplateScopeRAII(P, Class.TagOrTemplate,
345 /*Enter=*/!Class.TopLevelClass),
346 Class(Class) {
347 // If this is the top-level class, we're still within its scope.
348 if (Class.TopLevelClass)
349 return;
350
351 // Re-enter the class scope itself.
353 P.Actions.ActOnStartDelayedMemberDeclarations(P.getCurScope(),
354 Class.TagOrTemplate);
355 }
357 if (Class.TopLevelClass)
358 return;
359
360 P.Actions.ActOnFinishDelayedMemberDeclarations(P.getCurScope(),
361 Class.TagOrTemplate);
362 }
363};
364
365void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
366 ReenterClassScopeRAII InClassScope(*this, Class);
367
368 for (LateParsedDeclaration *LateD : Class.LateParsedDeclarations)
369 LateD->ParseLexedMethodDeclarations();
370}
371
372void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
373 // If this is a member template, introduce the template parameter scope.
374 ReenterTemplateScopeRAII InFunctionTemplateScope(*this, LM.Method);
375
376 // Start the delayed C++ method declaration
378
379 // Introduce the parameters into scope and parse their default
380 // arguments.
381 InFunctionTemplateScope.Scopes.Enter(Scope::FunctionPrototypeScope |
384 for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
385 auto Param = cast<ParmVarDecl>(LM.DefaultArgs[I].Param);
386 // Introduce the parameter into scope.
387 bool HasUnparsed = Param->hasUnparsedDefaultArg();
389 std::unique_ptr<CachedTokens> Toks = std::move(LM.DefaultArgs[I].Toks);
390 if (Toks) {
391 ParenBraceBracketBalancer BalancerRAIIObj(*this);
392
393 // Mark the end of the default argument so that we know when to stop when
394 // we parse it later on.
395 Token LastDefaultArgToken = Toks->back();
396 Token DefArgEnd;
397 DefArgEnd.startToken();
398 DefArgEnd.setKind(tok::eof);
399 DefArgEnd.setLocation(LastDefaultArgToken.getEndLoc());
400 DefArgEnd.setEofData(Param);
401 Toks->push_back(DefArgEnd);
402
403 // Parse the default argument from its saved token stream.
404 Toks->push_back(Tok); // So that the current token doesn't get lost
405 PP.EnterTokenStream(*Toks, true, /*IsReinject*/ true);
406
407 // Consume the previously-pushed token.
409
410 // Consume the '='.
411 assert(Tok.is(tok::equal) && "Default argument not starting with '='");
412 SourceLocation EqualLoc = ConsumeToken();
413
414 // The argument isn't actually potentially evaluated unless it is
415 // used.
417 Actions,
419
420 ExprResult DefArgResult;
421 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
422 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
423 DefArgResult = ParseBraceInitializer();
424 } else
425 DefArgResult = ParseAssignmentExpression();
426 if (DefArgResult.isInvalid()) {
427 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc,
428 /*DefaultArg=*/nullptr);
429 } else {
430 if (Tok.isNot(tok::eof) || Tok.getEofData() != Param) {
431 // The last two tokens are the terminator and the saved value of
432 // Tok; the last token in the default argument is the one before
433 // those.
434 assert(Toks->size() >= 3 && "expected a token in default arg");
435 Diag(Tok.getLocation(), diag::err_default_arg_unparsed)
436 << SourceRange(Tok.getLocation(),
437 (*Toks)[Toks->size() - 3].getLocation());
438 }
439 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
440 DefArgResult.get());
441 }
442
443 // There could be leftover tokens (e.g. because of an error).
444 // Skip through until we reach the 'end of default argument' token.
445 while (Tok.isNot(tok::eof))
447
448 if (Tok.is(tok::eof) && Tok.getEofData() == Param)
450 } else if (HasUnparsed) {
451 assert(Param->hasInheritedDefaultArg());
452 FunctionDecl *Old;
453 if (const auto *FunTmpl = dyn_cast<FunctionTemplateDecl>(LM.Method))
454 Old =
455 cast<FunctionDecl>(FunTmpl->getTemplatedDecl())->getPreviousDecl();
456 else
457 Old = cast<FunctionDecl>(LM.Method)->getPreviousDecl();
458 if (Old) {
459 ParmVarDecl *OldParam = Old->getParamDecl(I);
460 assert(!OldParam->hasUnparsedDefaultArg());
461 if (OldParam->hasUninstantiatedDefaultArg())
462 Param->setUninstantiatedDefaultArg(
463 OldParam->getUninstantiatedDefaultArg());
464 else
465 Param->setDefaultArg(OldParam->getInit());
466 }
467 }
468 }
469
470 // Parse a delayed exception-specification, if there is one.
471 if (CachedTokens *Toks = LM.ExceptionSpecTokens) {
472 ParenBraceBracketBalancer BalancerRAIIObj(*this);
473
474 // Add the 'stop' token.
475 Token LastExceptionSpecToken = Toks->back();
476 Token ExceptionSpecEnd;
477 ExceptionSpecEnd.startToken();
478 ExceptionSpecEnd.setKind(tok::eof);
479 ExceptionSpecEnd.setLocation(LastExceptionSpecToken.getEndLoc());
480 ExceptionSpecEnd.setEofData(LM.Method);
481 Toks->push_back(ExceptionSpecEnd);
482
483 // Parse the default argument from its saved token stream.
484 Toks->push_back(Tok); // So that the current token doesn't get lost
485 PP.EnterTokenStream(*Toks, true, /*IsReinject*/true);
486
487 // Consume the previously-pushed token.
489
490 // C++11 [expr.prim.general]p3:
491 // If a declaration declares a member function or member function
492 // template of a class X, the expression this is a prvalue of type
493 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
494 // and the end of the function-definition, member-declarator, or
495 // declarator.
496 CXXMethodDecl *Method;
497 FunctionDecl *FunctionToPush;
498 if (FunctionTemplateDecl *FunTmpl
499 = dyn_cast<FunctionTemplateDecl>(LM.Method))
500 FunctionToPush = FunTmpl->getTemplatedDecl();
501 else
502 FunctionToPush = cast<FunctionDecl>(LM.Method);
503 Method = dyn_cast<CXXMethodDecl>(FunctionToPush);
504
505 // Push a function scope so that tryCaptureVariable() can properly visit
506 // function scopes involving function parameters that are referenced inside
507 // the noexcept specifier e.g. through a lambda expression.
508 // Example:
509 // struct X {
510 // void ICE(int val) noexcept(noexcept([val]{}));
511 // };
512 // Setup the CurScope to match the function DeclContext - we have such
513 // assumption in IsInFnTryBlockHandler().
514 ParseScope FnScope(this, Scope::FnScope);
515 Sema::ContextRAII FnContext(Actions, FunctionToPush,
516 /*NewThisContext=*/false);
517 Sema::FunctionScopeRAII PopFnContext(Actions);
518 Actions.PushFunctionScope();
519
520 Sema::CXXThisScopeRAII ThisScope(
521 Actions, Method ? Method->getParent() : nullptr,
522 Method ? Method->getMethodQualifiers() : Qualifiers{},
524
525 // Parse the exception-specification.
526 SourceRange SpecificationRange;
527 SmallVector<ParsedType, 4> DynamicExceptions;
528 SmallVector<SourceRange, 4> DynamicExceptionRanges;
529 ExprResult NoexceptExpr;
530 CachedTokens *ExceptionSpecTokens;
531
533 = tryParseExceptionSpecification(/*Delayed=*/false, SpecificationRange,
534 DynamicExceptions,
535 DynamicExceptionRanges, NoexceptExpr,
536 ExceptionSpecTokens);
537
538 if (Tok.isNot(tok::eof) || Tok.getEofData() != LM.Method)
539 Diag(Tok.getLocation(), diag::err_except_spec_unparsed);
540
541 // Attach the exception-specification to the method.
542 Actions.actOnDelayedExceptionSpecification(LM.Method, EST,
543 SpecificationRange,
544 DynamicExceptions,
545 DynamicExceptionRanges,
546 NoexceptExpr.isUsable()?
547 NoexceptExpr.get() : nullptr);
548
549 // There could be leftover tokens (e.g. because of an error).
550 // Skip through until we reach the original token position.
551 while (Tok.isNot(tok::eof))
553
554 // Clean up the remaining EOF token.
555 if (Tok.is(tok::eof) && Tok.getEofData() == LM.Method)
557
558 delete Toks;
559 LM.ExceptionSpecTokens = nullptr;
560 }
561
562 InFunctionTemplateScope.Scopes.Exit();
563
564 // Finish the delayed C++ method declaration.
565 Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
566}
567
568void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
569 ReenterClassScopeRAII InClassScope(*this, Class);
570
571 for (LateParsedDeclaration *D : Class.LateParsedDeclarations)
572 D->ParseLexedMethodDefs();
573}
574
575void Parser::ParseLexedMethodDef(LexedMethod &LM) {
576 // If this is a member template, introduce the template parameter scope.
577 ReenterTemplateScopeRAII InFunctionTemplateScope(*this, LM.D);
578
579 ParenBraceBracketBalancer BalancerRAIIObj(*this);
580
581 assert(!LM.Toks.empty() && "Empty body!");
582 Token LastBodyToken = LM.Toks.back();
583 Token BodyEnd;
584 BodyEnd.startToken();
585 BodyEnd.setKind(tok::eof);
586 BodyEnd.setLocation(LastBodyToken.getEndLoc());
587 BodyEnd.setEofData(LM.D);
588 LM.Toks.push_back(BodyEnd);
589 // Append the current token at the end of the new token stream so that it
590 // doesn't get lost.
591 LM.Toks.push_back(Tok);
592 PP.EnterTokenStream(LM.Toks, true, /*IsReinject*/true);
593
594 // Consume the previously pushed token.
595 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
596 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)
597 && "Inline method not starting with '{', ':' or 'try'");
598
599 // Parse the method body. Function body parsing code is similar enough
600 // to be re-used for method bodies as well.
603 Sema::FPFeaturesStateRAII SaveFPFeatures(Actions);
604
605 Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
606
607 llvm::scope_exit _([&]() {
608 while (Tok.isNot(tok::eof))
610
611 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
613
614 if (auto *FD = dyn_cast_or_null<FunctionDecl>(LM.D))
615 if (isa<CXXMethodDecl>(FD) ||
617 Actions.ActOnFinishInlineFunctionDef(FD);
618 });
619
620 if (Tok.is(tok::kw_try)) {
621 ParseFunctionTryBlock(LM.D, FnScope);
622 return;
623 }
624 if (Tok.is(tok::colon)) {
625 ParseConstructorInitializer(LM.D);
626
627 // Error recovery.
628 if (!Tok.is(tok::l_brace)) {
629 FnScope.Exit();
630 Actions.ActOnFinishFunctionBody(LM.D, nullptr);
631 return;
632 }
633 } else
634 Actions.ActOnDefaultCtorInitializers(LM.D);
635
636 assert((Actions.getDiagnostics().hasErrorOccurred() ||
638 cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
639 < TemplateParameterDepth) &&
640 "TemplateParameterDepth should be greater than the depth of "
641 "current template being instantiated!");
642
643 ParseFunctionStatementBody(LM.D, FnScope);
644}
645
646void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
647 ReenterClassScopeRAII InClassScope(*this, Class);
648
649 if (!Class.LateParsedDeclarations.empty()) {
650 // C++11 [expr.prim.general]p4:
651 // Otherwise, if a member-declarator declares a non-static data member
652 // (9.2) of a class X, the expression this is a prvalue of type "pointer
653 // to X" within the optional brace-or-equal-initializer. It shall not
654 // appear elsewhere in the member-declarator.
655 // FIXME: This should be done in ParseLexedMemberInitializer, not here.
656 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
657 Qualifiers());
658
659 for (LateParsedDeclaration *D : Class.LateParsedDeclarations)
660 D->ParseLexedMemberInitializers();
661 }
662
663 Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
664}
665
666void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
667 if (!MI.Field || MI.Field->isInvalidDecl())
668 return;
669
670 ParenBraceBracketBalancer BalancerRAIIObj(*this);
671
672 // Append the current token at the end of the new token stream so that it
673 // doesn't get lost.
674 MI.Toks.push_back(Tok);
675 PP.EnterTokenStream(MI.Toks, true, /*IsReinject*/true);
676
677 // Consume the previously pushed token.
678 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
679
680 SourceLocation EqualLoc;
681
682 Actions.ActOnStartCXXInClassMemberInitializer();
683
684 // The initializer isn't actually potentially evaluated unless it is
685 // used.
686 EnterExpressionEvaluationContext Eval(
688
689 ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
690 EqualLoc);
691
692 Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc, Init);
693
694 // The next token should be our artificial terminating EOF token.
695 if (Tok.isNot(tok::eof)) {
696 if (!Init.isInvalid()) {
697 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
698 if (!EndLoc.isValid())
699 EndLoc = Tok.getLocation();
700 // No fixit; we can't recover as if there were a semicolon here.
701 Diag(EndLoc, diag::err_expected_semi_decl_list);
702 }
703
704 // Consume tokens until we hit the artificial EOF.
705 while (Tok.isNot(tok::eof))
707 }
708 // Make sure this is *our* artificial EOF token.
709 if (Tok.getEofData() == MI.Field)
711}
712
713void Parser::ParseLexedAttributes(ParsingClass &Class) {
714 ReenterClassScopeRAII InClassScope(*this, Class);
715
716 for (LateParsedDeclaration *LateD : Class.LateParsedDeclarations)
717 LateD->ParseLexedAttributes();
718}
719
720void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
721 bool EnterScope, bool OnDefinition) {
722 assert(LAs.parseSoon() &&
723 "Attribute list should be marked for immediate parsing.");
724 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
725 if (D)
726 LAs[i]->addDecl(D);
727 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
728 delete LAs[i];
729 }
730 LAs.clear();
731}
732
733void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
734 bool EnterScope, bool OnDefinition) {
735 // Create a fake EOF so that attribute parsing won't go off the end of the
736 // attribute.
737 Token AttrEnd;
738 AttrEnd.startToken();
739 AttrEnd.setKind(tok::eof);
740 AttrEnd.setLocation(Tok.getLocation());
741 AttrEnd.setEofData(LA.Toks.data());
742 LA.Toks.push_back(AttrEnd);
743
744 // Append the current token at the end of the new token stream so that it
745 // doesn't get lost.
746 LA.Toks.push_back(Tok);
747 PP.EnterTokenStream(LA.Toks, true, /*IsReinject=*/true);
748 // Consume the previously pushed token.
749 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
750
751 ParsedAttributes Attrs(AttrFactory);
752
753 if (LA.Decls.size() > 0) {
754 Decl *D = LA.Decls[0];
755 NamedDecl *ND = dyn_cast<NamedDecl>(D);
756 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
757
758 // Allow 'this' within late-parsed attributes.
759 Sema::CXXThisScopeRAII ThisScope(Actions, RD, Qualifiers(),
760 ND && ND->isCXXInstanceMember());
761
762 if (LA.Decls.size() == 1) {
763 // If the Decl is templatized, add template parameters to scope.
764 ReenterTemplateScopeRAII InDeclScope(*this, D, EnterScope);
765
766 // If the Decl is on a function, add function parameters to the scope.
767 bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
768 if (HasFunScope) {
769 InDeclScope.Scopes.Enter(Scope::FnScope | Scope::DeclScope |
771 Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
772 }
773
774 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, nullptr,
775 nullptr, SourceLocation(), ParsedAttr::Form::GNU(),
776 nullptr);
777
778 if (HasFunScope)
779 Actions.ActOnExitFunctionContext();
780 } else {
781 // If there are multiple decls, then the decl cannot be within the
782 // function scope.
783 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, nullptr,
784 nullptr, SourceLocation(), ParsedAttr::Form::GNU(),
785 nullptr);
786 }
787 } else {
788 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
789 }
790
791 if (OnDefinition && !Attrs.empty() && !Attrs.begin()->isCXX11Attribute() &&
792 Attrs.begin()->isKnownToGCC())
793 Diag(Tok, diag::warn_attribute_on_function_definition)
794 << &LA.AttrName;
795
796 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
797 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
798
799 // Due to a parsing error, we either went over the cached tokens or
800 // there are still cached tokens left, so we skip the leftover tokens.
801 while (Tok.isNot(tok::eof))
803
804 if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
806}
807
808void Parser::ParseLexedPragmas(ParsingClass &Class) {
809 ReenterClassScopeRAII InClassScope(*this, Class);
810
811 for (LateParsedDeclaration *D : Class.LateParsedDeclarations)
812 D->ParseLexedPragmas();
813}
814
815void Parser::ParseLexedPragma(LateParsedPragma &LP) {
816 PP.EnterToken(Tok, /*IsReinject=*/true);
817 PP.EnterTokenStream(LP.toks(), /*DisableMacroExpansion=*/true,
818 /*IsReinject=*/true);
819
820 // Consume the previously pushed token.
821 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
822 assert(Tok.isAnnotation() && "Expected annotation token.");
823 switch (Tok.getKind()) {
824 case tok::annot_attr_openmp:
825 case tok::annot_pragma_openmp: {
826 AccessSpecifier AS = LP.getAccessSpecifier();
827 ParsedAttributes Attrs(AttrFactory);
828 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
829 break;
830 }
831 default:
832 llvm_unreachable("Unexpected token.");
833 }
834}
835
836bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
837 CachedTokens &Toks,
838 bool StopAtSemi, bool ConsumeFinalToken) {
839 // We always want this function to consume at least one token if the first
840 // token isn't T and if not at EOF.
841 bool isFirstTokenConsumed = true;
842 while (true) {
843 // If we found one of the tokens, stop and return true.
844 if (Tok.is(T1) || Tok.is(T2)) {
845 if (ConsumeFinalToken) {
846 Toks.push_back(Tok);
848 }
849 return true;
850 }
851
852 switch (Tok.getKind()) {
853 case tok::eof:
854 case tok::annot_module_begin:
855 case tok::annot_module_end:
856 case tok::annot_module_include:
857 case tok::annot_repl_input_end:
858 // Ran out of tokens.
859 return false;
860
861 case tok::l_paren:
862 // Recursively consume properly-nested parens.
863 Toks.push_back(Tok);
864 ConsumeParen();
865 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
866 break;
867 case tok::l_square:
868 // Recursively consume properly-nested square brackets.
869 Toks.push_back(Tok);
870 ConsumeBracket();
871 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
872 break;
873 case tok::l_brace:
874 // Recursively consume properly-nested braces.
875 Toks.push_back(Tok);
876 ConsumeBrace();
877 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
878 break;
879
880 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
881 // Since the user wasn't looking for this token (if they were, it would
882 // already be handled), this isn't balanced. If there is a LHS token at a
883 // higher level, we will assume that this matches the unbalanced token
884 // and return it. Otherwise, this is a spurious RHS token, which we skip.
885 case tok::r_paren:
886 if (ParenCount && !isFirstTokenConsumed)
887 return false; // Matches something.
888 Toks.push_back(Tok);
889 ConsumeParen();
890 break;
891 case tok::r_square:
892 if (BracketCount && !isFirstTokenConsumed)
893 return false; // Matches something.
894 Toks.push_back(Tok);
895 ConsumeBracket();
896 break;
897 case tok::r_brace:
898 if (BraceCount && !isFirstTokenConsumed)
899 return false; // Matches something.
900 Toks.push_back(Tok);
901 ConsumeBrace();
902 break;
903
904 case tok::semi:
905 if (StopAtSemi)
906 return false;
907 [[fallthrough]];
908 default:
909 // consume this token.
910 Toks.push_back(Tok);
911 ConsumeAnyToken(/*ConsumeCodeCompletionTok*/true);
912 break;
913 }
914 isFirstTokenConsumed = false;
915 }
916}
917
918bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
919 if (Tok.is(tok::kw_try)) {
920 Toks.push_back(Tok);
921 ConsumeToken();
922 }
923
924 if (Tok.isNot(tok::colon)) {
925 // Easy case, just a function body.
926
927 // Grab any remaining garbage to be diagnosed later. We stop when we reach a
928 // brace: an opening one is the function body, while a closing one probably
929 // means we've reached the end of the class.
930 ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
931 /*StopAtSemi=*/true,
932 /*ConsumeFinalToken=*/false);
933 if (Tok.isNot(tok::l_brace))
934 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
935
936 Toks.push_back(Tok);
937 ConsumeBrace();
938 return false;
939 }
940
941 Toks.push_back(Tok);
942 ConsumeToken();
943
944 // We can't reliably skip over a mem-initializer-id, because it could be
945 // a template-id involving not-yet-declared names. Given:
946 //
947 // S ( ) : a < b < c > ( e )
948 //
949 // 'e' might be an initializer or part of a template argument, depending
950 // on whether 'b' is a template.
951
952 // Track whether we might be inside a template argument. We can give
953 // significantly better diagnostics if we know that we're not.
954 bool MightBeTemplateArgument = false;
955
956 while (true) {
957 // Skip over the mem-initializer-id, if possible.
958 if (Tok.is(tok::kw_decltype)) {
959 Toks.push_back(Tok);
960 SourceLocation OpenLoc = ConsumeToken();
961 if (Tok.isNot(tok::l_paren))
962 return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
963 << "decltype";
964 Toks.push_back(Tok);
965 ConsumeParen();
966 if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
967 Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
968 Diag(OpenLoc, diag::note_matching) << tok::l_paren;
969 return true;
970 }
971 }
972 do {
973 // Walk over a component of a nested-name-specifier.
974 if (Tok.is(tok::coloncolon)) {
975 Toks.push_back(Tok);
976 ConsumeToken();
977
978 if (Tok.is(tok::kw_template)) {
979 Toks.push_back(Tok);
980 ConsumeToken();
981 }
982 }
983
984 if (Tok.is(tok::identifier)) {
985 Toks.push_back(Tok);
986 ConsumeToken();
987 } else {
988 break;
989 }
990 // Pack indexing
991 if (Tok.is(tok::ellipsis) && NextToken().is(tok::l_square)) {
992 Toks.push_back(Tok);
993 SourceLocation OpenLoc = ConsumeToken();
994 Toks.push_back(Tok);
995 ConsumeBracket();
996 if (!ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/true)) {
997 Diag(Tok.getLocation(), diag::err_expected) << tok::r_square;
998 Diag(OpenLoc, diag::note_matching) << tok::l_square;
999 return true;
1000 }
1001 }
1002
1003 } while (Tok.is(tok::coloncolon));
1004
1005 if (Tok.is(tok::code_completion)) {
1006 Toks.push_back(Tok);
1007 ConsumeCodeCompletionToken();
1008 if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype)) {
1009 // Could be the start of another member initializer (the ',' has not
1010 // been written yet)
1011 continue;
1012 }
1013 }
1014
1015 if (Tok.is(tok::comma)) {
1016 // The initialization is missing, we'll diagnose it later.
1017 Toks.push_back(Tok);
1018 ConsumeToken();
1019 continue;
1020 }
1021 if (Tok.is(tok::less))
1022 MightBeTemplateArgument = true;
1023
1024 if (MightBeTemplateArgument) {
1025 // We may be inside a template argument list. Grab up to the start of the
1026 // next parenthesized initializer or braced-init-list. This *might* be the
1027 // initializer, or it might be a subexpression in the template argument
1028 // list.
1029 // FIXME: Count angle brackets, and clear MightBeTemplateArgument
1030 // if all angles are closed.
1031 if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
1032 /*StopAtSemi=*/true,
1033 /*ConsumeFinalToken=*/false)) {
1034 // We're not just missing the initializer, we're also missing the
1035 // function body!
1036 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
1037 }
1038 } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
1039 // We found something weird in a mem-initializer-id.
1041 return Diag(Tok.getLocation(), diag::err_expected_either)
1042 << tok::l_paren << tok::l_brace;
1043 else
1044 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
1045 }
1046
1047 tok::TokenKind kind = Tok.getKind();
1048 Toks.push_back(Tok);
1049 bool IsLParen = (kind == tok::l_paren);
1050 SourceLocation OpenLoc = Tok.getLocation();
1051
1052 if (IsLParen) {
1053 ConsumeParen();
1054 } else {
1055 assert(kind == tok::l_brace && "Must be left paren or brace here.");
1056 ConsumeBrace();
1057 // In C++03, this has to be the start of the function body, which
1058 // means the initializer is malformed; we'll diagnose it later.
1059 if (!getLangOpts().CPlusPlus11)
1060 return false;
1061
1062 const Token &PreviousToken = Toks[Toks.size() - 2];
1063 if (!MightBeTemplateArgument &&
1064 !PreviousToken.isOneOf(tok::identifier, tok::greater,
1065 tok::greatergreater)) {
1066 // If the opening brace is not preceded by one of these tokens, we are
1067 // missing the mem-initializer-id. In order to recover better, we need
1068 // to use heuristics to determine if this '{' is most likely the
1069 // beginning of a brace-init-list or the function body.
1070 // Check the token after the corresponding '}'.
1071 TentativeParsingAction PA(*this);
1072 if (SkipUntil(tok::r_brace) &&
1073 !Tok.isOneOf(tok::comma, tok::ellipsis, tok::l_brace)) {
1074 // Consider there was a malformed initializer and this is the start
1075 // of the function body. We'll diagnose it later.
1076 PA.Revert();
1077 return false;
1078 }
1079 PA.Revert();
1080 }
1081 }
1082
1083 // Grab the initializer (or the subexpression of the template argument).
1084 // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
1085 // if we might be inside the braces of a lambda-expression.
1086 tok::TokenKind CloseKind = IsLParen ? tok::r_paren : tok::r_brace;
1087 if (!ConsumeAndStoreUntil(CloseKind, Toks, /*StopAtSemi=*/true)) {
1088 Diag(Tok, diag::err_expected) << CloseKind;
1089 Diag(OpenLoc, diag::note_matching) << kind;
1090 return true;
1091 }
1092
1093 // Grab pack ellipsis, if present.
1094 if (Tok.is(tok::ellipsis)) {
1095 Toks.push_back(Tok);
1096 ConsumeToken();
1097 }
1098
1099 // If we know we just consumed a mem-initializer, we must have ',' or '{'
1100 // next.
1101 if (Tok.is(tok::comma)) {
1102 Toks.push_back(Tok);
1103 ConsumeToken();
1104 } else if (Tok.is(tok::l_brace)) {
1105 // This is the function body if the ')' or '}' is immediately followed by
1106 // a '{'. That cannot happen within a template argument, apart from the
1107 // case where a template argument contains a compound literal:
1108 //
1109 // S ( ) : a < b < c > ( d ) { }
1110 // // End of declaration, or still inside the template argument?
1111 //
1112 // ... and the case where the template argument contains a lambda:
1113 //
1114 // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
1115 // ( ) > ( ) { }
1116 //
1117 // FIXME: Disambiguate these cases. Note that the latter case is probably
1118 // going to be made ill-formed by core issue 1607.
1119 Toks.push_back(Tok);
1120 ConsumeBrace();
1121 return false;
1122 } else if (!MightBeTemplateArgument) {
1123 return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
1124 << tok::comma;
1125 }
1126 }
1127}
1128
1129bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
1130 // Consume '?'.
1131 assert(Tok.is(tok::question));
1132 Toks.push_back(Tok);
1133 ConsumeToken();
1134
1135 while (Tok.isNot(tok::colon)) {
1136 if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks,
1137 /*StopAtSemi=*/true,
1138 /*ConsumeFinalToken=*/false))
1139 return false;
1140
1141 // If we found a nested conditional, consume it.
1142 if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
1143 return false;
1144 }
1145
1146 // Consume ':'.
1147 Toks.push_back(Tok);
1148 ConsumeToken();
1149 return true;
1150}
1151
1152bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
1153 CachedInitKind CIK) {
1154 // We always want this function to consume at least one token if not at EOF.
1155 bool IsFirstToken = true;
1156
1157 // Number of possible unclosed <s we've seen so far. These might be templates,
1158 // and might not, but if there were none of them (or we know for sure that
1159 // we're within a template), we can avoid a tentative parse.
1160 unsigned AngleCount = 0;
1161 unsigned KnownTemplateCount = 0;
1162
1163 while (true) {
1164 switch (Tok.getKind()) {
1165 case tok::ellipsis:
1166 // We found an elipsis at the end of the parameter list;
1167 // it is not part of a parameter declaration.
1168 if (ParenCount == 1 && NextToken().is(tok::r_paren))
1169 return true;
1170 goto consume_token;
1171 case tok::comma:
1172 // If we might be in a template, perform a tentative parse to check.
1173 if (!AngleCount)
1174 // Not a template argument: this is the end of the initializer.
1175 return true;
1176 if (KnownTemplateCount)
1177 goto consume_token;
1178
1179 // We hit a comma inside angle brackets. This is the hard case. The
1180 // rule we follow is:
1181 // * For a default argument, if the tokens after the comma form a
1182 // syntactically-valid parameter-declaration-clause, in which each
1183 // parameter has an initializer, then this comma ends the default
1184 // argument.
1185 // * For a default initializer, if the tokens after the comma form a
1186 // syntactically-valid init-declarator-list, then this comma ends
1187 // the default initializer.
1188 {
1189 TentativeParsingAction TPA(*this, /*Unannotated=*/true);
1190 Sema::TentativeAnalysisScope Scope(Actions);
1191
1192 TPResult Result = TPResult::Error;
1193 ConsumeToken();
1194 switch (CIK) {
1196 Result = TryParseInitDeclaratorList();
1197 // If we parsed a complete, ambiguous init-declarator-list, this
1198 // is only syntactically-valid if it's followed by a semicolon.
1199 if (Result == TPResult::Ambiguous && Tok.isNot(tok::semi))
1200 Result = TPResult::False;
1201 break;
1202
1204 bool InvalidAsDeclaration = false;
1205 Result = TryParseParameterDeclarationClause(
1206 &InvalidAsDeclaration, /*VersusTemplateArg=*/true);
1207 // If this is an expression or a declaration with a missing
1208 // 'typename', assume it's not a declaration.
1209 if (Result == TPResult::Ambiguous && InvalidAsDeclaration)
1210 Result = TPResult::False;
1211 break;
1212 }
1213
1214 // Put the token stream back and undo any annotations we performed
1215 // after the comma. They may reflect a different parse than the one
1216 // we will actually perform at the end of the class.
1217 TPA.Revert();
1218
1219 // If what follows could be a declaration, it is a declaration.
1220 if (Result != TPResult::False && Result != TPResult::Error)
1221 return true;
1222 }
1223
1224 // Keep going. We know we're inside a template argument list now.
1225 ++KnownTemplateCount;
1226 goto consume_token;
1227
1228 case tok::eof:
1229 // Ran out of tokens.
1230 return false;
1231
1232 case tok::less:
1233 // FIXME: A '<' can only start a template-id if it's preceded by an
1234 // identifier, an operator-function-id, or a literal-operator-id.
1235 ++AngleCount;
1236 goto consume_token;
1237
1238 case tok::question:
1239 // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
1240 // that is *never* the end of the initializer. Skip to the ':'.
1241 if (!ConsumeAndStoreConditional(Toks))
1242 return false;
1243 break;
1244
1245 case tok::greatergreatergreater:
1246 if (!getLangOpts().CPlusPlus11)
1247 goto consume_token;
1248 if (AngleCount) --AngleCount;
1249 if (KnownTemplateCount) --KnownTemplateCount;
1250 [[fallthrough]];
1251 case tok::greatergreater:
1252 if (!getLangOpts().CPlusPlus11)
1253 goto consume_token;
1254 if (AngleCount) --AngleCount;
1255 if (KnownTemplateCount) --KnownTemplateCount;
1256 [[fallthrough]];
1257 case tok::greater:
1258 if (AngleCount) --AngleCount;
1259 if (KnownTemplateCount) --KnownTemplateCount;
1260 goto consume_token;
1261
1262 case tok::kw_template:
1263 // 'template' identifier '<' is known to start a template argument list,
1264 // and can be used to disambiguate the parse.
1265 // FIXME: Support all forms of 'template' unqualified-id '<'.
1266 Toks.push_back(Tok);
1267 ConsumeToken();
1268 if (Tok.is(tok::identifier)) {
1269 Toks.push_back(Tok);
1270 ConsumeToken();
1271 if (Tok.is(tok::less)) {
1272 ++AngleCount;
1273 ++KnownTemplateCount;
1274 Toks.push_back(Tok);
1275 ConsumeToken();
1276 }
1277 }
1278 break;
1279
1280 case tok::kw_operator:
1281 // If 'operator' precedes other punctuation, that punctuation loses
1282 // its special behavior.
1283 Toks.push_back(Tok);
1284 ConsumeToken();
1285 switch (Tok.getKind()) {
1286 case tok::comma:
1287 case tok::greatergreatergreater:
1288 case tok::greatergreater:
1289 case tok::greater:
1290 case tok::less:
1291 Toks.push_back(Tok);
1292 ConsumeToken();
1293 break;
1294 default:
1295 break;
1296 }
1297 break;
1298
1299 case tok::l_paren:
1300 // Recursively consume properly-nested parens.
1301 Toks.push_back(Tok);
1302 ConsumeParen();
1303 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1304 break;
1305 case tok::l_square:
1306 // Recursively consume properly-nested square brackets.
1307 Toks.push_back(Tok);
1308 ConsumeBracket();
1309 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
1310 break;
1311 case tok::l_brace:
1312 // Recursively consume properly-nested braces.
1313 Toks.push_back(Tok);
1314 ConsumeBrace();
1315 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1316 break;
1317
1318 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
1319 // Since the user wasn't looking for this token (if they were, it would
1320 // already be handled), this isn't balanced. If there is a LHS token at a
1321 // higher level, we will assume that this matches the unbalanced token
1322 // and return it. Otherwise, this is a spurious RHS token, which we
1323 // consume and pass on to downstream code to diagnose.
1324 case tok::r_paren:
1326 return true; // End of the default argument.
1327 if (ParenCount && !IsFirstToken)
1328 return false;
1329 Toks.push_back(Tok);
1330 ConsumeParen();
1331 continue;
1332 case tok::r_square:
1333 if (BracketCount && !IsFirstToken)
1334 return false;
1335 Toks.push_back(Tok);
1336 ConsumeBracket();
1337 continue;
1338 case tok::r_brace:
1339 if (BraceCount && !IsFirstToken)
1340 return false;
1341 Toks.push_back(Tok);
1342 ConsumeBrace();
1343 continue;
1344
1345 case tok::code_completion:
1346 Toks.push_back(Tok);
1347 ConsumeCodeCompletionToken();
1348 break;
1349
1350 case tok::string_literal:
1351 case tok::wide_string_literal:
1352 case tok::utf8_string_literal:
1353 case tok::utf16_string_literal:
1354 case tok::utf32_string_literal:
1355 Toks.push_back(Tok);
1356 ConsumeStringToken();
1357 break;
1358 case tok::semi:
1360 return true; // End of the default initializer.
1361 [[fallthrough]];
1362 default:
1363 consume_token:
1364 // If it's an annotation token, then we've run out of tokens and should
1365 // bail out. Otherwise, cache the token and consume it.
1366 if (Tok.isAnnotation())
1367 return false;
1368
1369 Toks.push_back(Tok);
1370 ConsumeToken();
1371 break;
1372 }
1373 IsFirstToken = false;
1374 }
1375}
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
bool is(tok::TokenKind Kind) const
Token Tok
The Token.
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:826
bool hasConstexprSpecifier() const
Definition DeclSpec.h:842
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isFunctionOrFunctionTemplate() const
Whether this declaration is a function or function template.
Definition DeclBase.h:1132
bool isInIdentifierNamespace(unsigned NS) const
Definition DeclBase.h:906
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
@ IDNS_OrdinaryFriend
This declaration is a friend function.
Definition DeclBase.h:152
DeclContext * getDeclContext()
Definition DeclBase.h:456
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2477
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition DeclSpec.h:2762
RAII object that enters a new expression evaluation context.
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2812
QualType getReturnType() const
Definition Decl.h:2860
void setWillHaveBody(bool V=true)
Definition Decl.h:2701
This represents a decl that may have a name.
Definition Decl.h:274
bool isCXXInstanceMember() const
Determine whether the given declaration is an instance member of a C++ class.
Definition Decl.cpp:1975
RAII object that makes sure paren/bracket/brace count is correct after declaration/statement parsing,...
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition Decl.h:1934
bool hasUninstantiatedDefaultArg() const
Definition Decl.h:1938
Expr * getUninstantiatedDefaultArg()
Definition Decl.cpp:3054
Introduces zero or more scopes for parsing.
Definition Parser.h:444
ParseScope - Introduces a new scope for parsing.
Definition Parser.h:408
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Definition Parser.cpp:88
SourceLocation ConsumeToken()
ConsumeToken - Consume the current 'peek token' and lex the next one.
Definition Parser.h:263
Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies)
Definition Parser.cpp:59
void EnterScope(unsigned ScopeFlags)
EnterScope - Start a new scope.
Definition Parser.cpp:428
SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok=false)
ConsumeAnyToken - Dispatch to the right Consume* method based on the current token type.
Definition Parser.h:291
bool TryConsumeToken(tok::TokenKind Expected)
Definition Parser.h:271
Scope * getCurScope() const
Definition Parser.h:212
bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags=static_cast< SkipUntilFlags >(0))
SkipUntil - Read tokens until we get to the specified token, then consume it (unless StopBeforeMatch ...
Definition Parser.h:507
void SkipMalformedDecl()
SkipMalformedDecl - Read tokens until we get to some likely good stopping point for skipping past a s...
const LangOptions & getLangOpts() const
Definition Parser.h:205
friend class ParenBraceBracketBalancer
Definition Parser.h:199
@ StopBeforeMatch
Stop skipping at specified token, but don't skip the token itself.
Definition Parser.h:488
@ StopAtSemi
Stop skipping at semicolon.
Definition Parser.h:486
ExprResult ParseUnevaluatedStringLiteralExpression()
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition Parser.h:325
ExprResult ParseAssignmentExpression(TypoCorrectionTypeBehavior CorrectionBehavior=TypoCorrectionTypeBehavior::AllowNonTypes)
Parse an expr that doesn't include (top-level) commas.
Definition ParseExpr.cpp:75
friend class BalancedDelimiterTracker
Definition Parser.h:200
A class for parsing a declarator.
const ParsingDeclSpec & getDeclSpec() const
@ FunctionPrototypeScope
This is a scope that corresponds to the parameters within a function prototype.
Definition Scope.h:85
@ CompoundStmtScope
This is a compound statement scope.
Definition Scope.h:134
@ ClassScope
The scope of a struct/union/class definition.
Definition Scope.h:69
@ FunctionDeclarationScope
This is a scope that corresponds to the parameters within a function prototype for a function declara...
Definition Scope.h:91
@ FnScope
This indicates that the scope corresponds to a function, which means that labels are set here.
Definition Scope.h:51
@ DeclScope
This is a scope that can contain a declaration.
Definition Scope.h:63
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Definition Sema.h:6830
void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnStartDelayedCXXMethodDeclaration - We have completed parsing a top-level (non-nested) C++ class,...
void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param)
ActOnDelayedCXXMethodParameter - We've already started a delayed C++ method declaration.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1802
Token - This structure provides full information about a lexed token.
Definition Token.h:36
SourceLocation getEndLoc() const
Definition Token.h:169
void setKind(tok::TokenKind K)
Definition Token.h:100
bool isOneOf(Ts... Ks) const
Definition Token.h:105
void setEofData(const void *D)
Definition Token.h:214
void setLocation(SourceLocation L)
Definition Token.h:150
void startToken()
Reset all flags to cleared.
Definition Token.h:187
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2949
const Expr * getInit() const
Definition Decl.h:1383
Represents a C++11 virt-specifier-seq.
Definition DeclSpec.h:2801
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus11
@ CPlusPlus26
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:263
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:273
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ Delete
'delete' clause, allowed on the 'exit data' construct.
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:124
@ Result
The result type of a method or function.
Definition TypeBase.h:905
@ ExplicitSpecialization
We are parsing an explicit specialization.
Definition Parser.h:83
@ NonTemplate
We are not parsing a template at all.
Definition Parser.h:79
CachedInitKind
Definition Parser.h:88
U cast(CodeGen::Address addr)
Definition Address.h:327
SmallVector< Token, 4 > CachedTokens
A set of tokens that has been cached for later parsing.
Definition DeclSpec.h:1250
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5967
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
ReenterClassScopeRAII(Parser &P, ParsingClass &Class)
ReenterTemplateScopeRAII(Parser &P, Decl *MaybeTemplated, bool Enter=true)