1//===--- Parser.cpp - C Language Family Parser ----------------------------===//
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 the Parser interfaces.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/Parse/Parser.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/Basic/DiagnosticParse.h"
19#include "clang/Basic/StackExhaustionHandler.h"
20#include "clang/Basic/TokenKinds.h"
21#include "clang/Lex/ModuleLoader.h"
22#include "clang/Lex/Preprocessor.h"
23#include "clang/Parse/RAIIObjectsForParser.h"
24#include "clang/Sema/DeclSpec.h"
25#include "clang/Sema/EnterExpressionEvaluationContext.h"
26#include "clang/Sema/ParsedTemplate.h"
27#include "clang/Sema/Scope.h"
28#include "clang/Sema/SemaCodeCompletion.h"
29#include "llvm/ADT/STLForwardCompat.h"
30#include "llvm/Support/Path.h"
31#include "llvm/Support/TimeProfiler.h"
32using namespace clang;
33
34
35namespace {
36/// A comment handler that passes comments found by the preprocessor
37/// to the parser action.
38class ActionCommentHandler : public CommentHandler {
39 Sema &S;
40
41public:
42 explicit ActionCommentHandler(Sema &S) : S(S) { }
43
44 bool HandleComment(Preprocessor &PP, SourceRange Comment) override {
45 S.ActOnComment(Comment);
46 return false;
47 }
48};
49} // end anonymous namespace
50
51IdentifierInfo *Parser::getSEHExceptKeyword() {
52 // __except is accepted as a (contextual) keyword
53 if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland))
54 Ident__except = PP.getIdentifierInfo(Name: "__except");
55
56 return Ident__except;
57}
58
59Parser::Parser(Preprocessor &pp, Sema &actions, bool skipFunctionBodies)
60 : PP(pp),
61 PreferredType(&actions.getASTContext(), pp.isCodeCompletionEnabled()),
62 Actions(actions), Diags(PP.getDiagnostics()), StackHandler(Diags),
63 GreaterThanIsOperator(true), ColonIsSacred(false),
64 InMessageExpression(false), ParsingInObjCContainer(false),
65 TemplateParameterDepth(0) {
66 SkipFunctionBodies = pp.isCodeCompletionEnabled() || skipFunctionBodies;
67 Tok.startToken();
68 Tok.setKind(tok::eof);
69 Actions.CurScope = nullptr;
70 NumCachedScopes = 0;
71 CurParsedObjCImpl = nullptr;
72
73 // Add #pragma handlers. These are removed and destroyed in the
74 // destructor.
75 initializePragmaHandlers();
76
77 CommentSemaHandler.reset(p: new ActionCommentHandler(actions));
78 PP.addCommentHandler(Handler: CommentSemaHandler.get());
79
80 PP.setCodeCompletionHandler(*this);
81
82 Actions.ParseTypeFromStringCallback =
83 [this](StringRef TypeStr, StringRef Context, SourceLocation IncludeLoc) {
84 return this->ParseTypeFromString(TypeStr, Context, IncludeLoc);
85 };
86}
87
88DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
89 return Diags.Report(Loc, DiagID);
90}
91
92DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
93 return Diag(Loc: Tok.getLocation(), DiagID);
94}
95
96DiagnosticBuilder Parser::DiagCompat(SourceLocation Loc,
97 unsigned CompatDiagId) {
98 return Diag(Loc, DiagID: DiagnosticIDs::getCompatDiagId(LangOpts: getLangOpts(), CompatDiagId));
99}
100
101DiagnosticBuilder Parser::DiagCompat(const Token &Tok, unsigned CompatDiagId) {
102 return DiagCompat(Loc: Tok.getLocation(), CompatDiagId);
103}
104
105void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
106 SourceRange ParenRange) {
107 SourceLocation EndLoc = PP.getLocForEndOfToken(Loc: ParenRange.getEnd());
108 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
109 // We can't display the parentheses, so just dig the
110 // warning/error and return.
111 Diag(Loc, DiagID: DK);
112 return;
113 }
114
115 Diag(Loc, DiagID: DK)
116 << FixItHint::CreateInsertion(InsertionLoc: ParenRange.getBegin(), Code: "(")
117 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ")");
118}
119
120static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {
121 switch (ExpectedTok) {
122 case tok::semi:
123 return Tok.is(K: tok::colon) || Tok.is(K: tok::comma); // : or , for ;
124 default: return false;
125 }
126}
127
128bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
129 StringRef Msg) {
130 if (Tok.is(K: ExpectedTok) || Tok.is(K: tok::code_completion)) {
131 ConsumeAnyToken();
132 return false;
133 }
134
135 // Detect common single-character typos and resume.
136 if (IsCommonTypo(ExpectedTok, Tok)) {
137 SourceLocation Loc = Tok.getLocation();
138 {
139 DiagnosticBuilder DB = Diag(Loc, DiagID);
140 DB << FixItHint::CreateReplacement(
141 RemoveRange: SourceRange(Loc), Code: tok::getPunctuatorSpelling(Kind: ExpectedTok));
142 if (DiagID == diag::err_expected)
143 DB << ExpectedTok;
144 else if (DiagID == diag::err_expected_after)
145 DB << Msg << ExpectedTok;
146 else
147 DB << Msg;
148 }
149
150 // Pretend there wasn't a problem.
151 ConsumeAnyToken();
152 return false;
153 }
154
155 SourceLocation EndLoc = PP.getLocForEndOfToken(Loc: PrevTokLocation);
156 const char *Spelling = nullptr;
157 if (EndLoc.isValid())
158 Spelling = tok::getPunctuatorSpelling(Kind: ExpectedTok);
159
160 DiagnosticBuilder DB =
161 Spelling
162 ? Diag(Loc: EndLoc, DiagID) << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: Spelling)
163 : Diag(Tok, DiagID);
164 if (DiagID == diag::err_expected)
165 DB << ExpectedTok;
166 else if (DiagID == diag::err_expected_after)
167 DB << Msg << ExpectedTok;
168 else
169 DB << Msg;
170
171 return true;
172}
173
174bool Parser::ExpectAndConsumeSemi(unsigned DiagID, StringRef TokenUsed) {
175 if (TryConsumeToken(Expected: tok::semi))
176 return false;
177
178 if (Tok.is(K: tok::code_completion)) {
179 handleUnexpectedCodeCompletionToken();
180 return false;
181 }
182
183 if ((Tok.is(K: tok::r_paren) || Tok.is(K: tok::r_square)) &&
184 NextToken().is(K: tok::semi)) {
185 Diag(Tok, DiagID: diag::err_extraneous_token_before_semi)
186 << PP.getSpelling(Tok)
187 << FixItHint::CreateRemoval(RemoveRange: Tok.getLocation());
188 ConsumeAnyToken(); // The ')' or ']'.
189 ConsumeToken(); // The ';'.
190 return false;
191 }
192
193 return ExpectAndConsume(ExpectedTok: tok::semi, DiagID , Msg: TokenUsed);
194}
195
196bool Parser::isLikelyAtStartOfNewDeclaration() {
197 return Tok.isAtStartOfLine() &&
198 isDeclarationSpecifier(AllowImplicitTypename: ImplicitTypenameContext::No);
199}
200
201void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST TST) {
202 if (!Tok.is(K: tok::semi)) return;
203
204 bool HadMultipleSemis = false;
205 SourceLocation StartLoc = Tok.getLocation();
206 SourceLocation EndLoc = Tok.getLocation();
207 ConsumeToken();
208
209 while ((Tok.is(K: tok::semi) && !Tok.isAtStartOfLine())) {
210 HadMultipleSemis = true;
211 EndLoc = Tok.getLocation();
212 ConsumeToken();
213 }
214
215 // C++11 allows extra semicolons at namespace scope, but not in any of the
216 // other contexts.
217 if (Kind == ExtraSemiKind::OutsideFunction && getLangOpts().CPlusPlus) {
218 if (getLangOpts().CPlusPlus11)
219 Diag(Loc: StartLoc, DiagID: diag::warn_cxx98_compat_top_level_semi)
220 << FixItHint::CreateRemoval(RemoveRange: SourceRange(StartLoc, EndLoc));
221 else
222 Diag(Loc: StartLoc, DiagID: diag::ext_extra_semi_cxx11)
223 << FixItHint::CreateRemoval(RemoveRange: SourceRange(StartLoc, EndLoc));
224 return;
225 }
226
227 if (Kind != ExtraSemiKind::AfterMemberFunctionDefinition || HadMultipleSemis)
228 Diag(Loc: StartLoc, DiagID: diag::ext_extra_semi)
229 << Kind
230 << DeclSpec::getSpecifierName(
231 T: TST, Policy: Actions.getASTContext().getPrintingPolicy())
232 << FixItHint::CreateRemoval(RemoveRange: SourceRange(StartLoc, EndLoc));
233 else
234 // A single semicolon is valid after a member function definition.
235 Diag(Loc: StartLoc, DiagID: diag::warn_extra_semi_after_mem_fn_def)
236 << FixItHint::CreateRemoval(RemoveRange: SourceRange(StartLoc, EndLoc));
237}
238
239bool Parser::expectIdentifier() {
240 if (Tok.is(K: tok::identifier))
241 return false;
242 if (const auto *II = Tok.getIdentifierInfo()) {
243 if (II->isCPlusPlusKeyword(LangOpts: getLangOpts())) {
244 Diag(Tok, DiagID: diag::err_expected_token_instead_of_objcxx_keyword)
245 << tok::identifier << Tok.getIdentifierInfo();
246 // Objective-C++: Recover by treating this keyword as a valid identifier.
247 return false;
248 }
249 }
250 Diag(Tok, DiagID: diag::err_expected) << tok::identifier;
251 return true;
252}
253
254void Parser::checkCompoundToken(SourceLocation FirstTokLoc,
255 tok::TokenKind FirstTokKind, CompoundToken Op) {
256 if (FirstTokLoc.isInvalid())
257 return;
258 SourceLocation SecondTokLoc = Tok.getLocation();
259
260 // If either token is in a macro, we expect both tokens to come from the same
261 // macro expansion.
262 if ((FirstTokLoc.isMacroID() || SecondTokLoc.isMacroID()) &&
263 PP.getSourceManager().getFileID(SpellingLoc: FirstTokLoc) !=
264 PP.getSourceManager().getFileID(SpellingLoc: SecondTokLoc)) {
265 Diag(Loc: FirstTokLoc, DiagID: diag::warn_compound_token_split_by_macro)
266 << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
267 << static_cast<int>(Op) << SourceRange(FirstTokLoc);
268 Diag(Loc: SecondTokLoc, DiagID: diag::note_compound_token_split_second_token_here)
269 << (FirstTokKind == Tok.getKind()) << Tok.getKind()
270 << SourceRange(SecondTokLoc);
271 return;
272 }
273
274 // We expect the tokens to abut.
275 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
276 SourceLocation SpaceLoc = PP.getLocForEndOfToken(Loc: FirstTokLoc);
277 if (SpaceLoc.isInvalid())
278 SpaceLoc = FirstTokLoc;
279 Diag(Loc: SpaceLoc, DiagID: diag::warn_compound_token_split_by_whitespace)
280 << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
281 << static_cast<int>(Op) << SourceRange(FirstTokLoc, SecondTokLoc);
282 return;
283 }
284}
285
286//===----------------------------------------------------------------------===//
287// Error recovery.
288//===----------------------------------------------------------------------===//
289
290static bool HasFlagsSet(Parser::SkipUntilFlags L, Parser::SkipUntilFlags R) {
291 return (static_cast<unsigned>(L) & static_cast<unsigned>(R)) != 0;
292}
293
294bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags) {
295 // We always want this function to skip at least one token if the first token
296 // isn't T and if not at EOF.
297 bool isFirstTokenSkipped = true;
298 while (true) {
299 // If we found one of the tokens, stop and return true.
300 for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
301 if (Tok.is(K: Toks[i])) {
302 if (HasFlagsSet(L: Flags, R: StopBeforeMatch)) {
303 // Noop, don't consume the token.
304 } else {
305 ConsumeAnyToken();
306 }
307 return true;
308 }
309 }
310
311 // Important special case: The caller has given up and just wants us to
312 // skip the rest of the file. Do this without recursing, since we can
313 // get here precisely because the caller detected too much recursion.
314 if (Toks.size() == 1 && Toks[0] == tok::eof &&
315 !HasFlagsSet(L: Flags, R: StopAtSemi) &&
316 !HasFlagsSet(L: Flags, R: StopAtCodeCompletion)) {
317 while (Tok.isNot(K: tok::eof))
318 ConsumeAnyToken();
319 return true;
320 }
321
322 switch (Tok.getKind()) {
323 case tok::eof:
324 // Ran out of tokens.
325 return false;
326
327 case tok::annot_pragma_openmp:
328 case tok::annot_attr_openmp:
329 case tok::annot_pragma_openmp_end:
330 // Stop before an OpenMP pragma boundary.
331 if (OpenMPDirectiveParsing)
332 return false;
333 ConsumeAnnotationToken();
334 break;
335 case tok::annot_pragma_openacc:
336 case tok::annot_pragma_openacc_end:
337 // Stop before an OpenACC pragma boundary.
338 if (OpenACCDirectiveParsing)
339 return false;
340 ConsumeAnnotationToken();
341 break;
342 case tok::annot_module_begin:
343 case tok::annot_module_end:
344 case tok::annot_module_include:
345 case tok::annot_repl_input_end:
346 // Stop before we change submodules. They generally indicate a "good"
347 // place to pick up parsing again (except in the special case where
348 // we're trying to skip to EOF).
349 return false;
350
351 case tok::code_completion:
352 if (!HasFlagsSet(L: Flags, R: StopAtCodeCompletion))
353 handleUnexpectedCodeCompletionToken();
354 return false;
355
356 case tok::l_paren:
357 // Recursively skip properly-nested parens.
358 ConsumeParen();
359 if (HasFlagsSet(L: Flags, R: StopAtCodeCompletion))
360 SkipUntil(T: tok::r_paren, Flags: StopAtCodeCompletion);
361 else
362 SkipUntil(T: tok::r_paren);
363 break;
364 case tok::l_square:
365 // Recursively skip properly-nested square brackets.
366 ConsumeBracket();
367 if (HasFlagsSet(L: Flags, R: StopAtCodeCompletion))
368 SkipUntil(T: tok::r_square, Flags: StopAtCodeCompletion);
369 else
370 SkipUntil(T: tok::r_square);
371 break;
372 case tok::l_brace:
373 // Recursively skip properly-nested braces.
374 ConsumeBrace();
375 if (HasFlagsSet(L: Flags, R: StopAtCodeCompletion))
376 SkipUntil(T: tok::r_brace, Flags: StopAtCodeCompletion);
377 else
378 SkipUntil(T: tok::r_brace);
379 break;
380 case tok::question:
381 // Recursively skip ? ... : pairs; these function as brackets. But
382 // still stop at a semicolon if requested.
383 ConsumeToken();
384 SkipUntil(T: tok::colon,
385 Flags: SkipUntilFlags(unsigned(Flags) &
386 unsigned(StopAtCodeCompletion | StopAtSemi)));
387 break;
388
389 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
390 // Since the user wasn't looking for this token (if they were, it would
391 // already be handled), this isn't balanced. If there is a LHS token at a
392 // higher level, we will assume that this matches the unbalanced token
393 // and return it. Otherwise, this is a spurious RHS token, which we skip.
394 case tok::r_paren:
395 if (ParenCount && !isFirstTokenSkipped)
396 return false; // Matches something.
397 ConsumeParen();
398 break;
399 case tok::r_square:
400 if (BracketCount && !isFirstTokenSkipped)
401 return false; // Matches something.
402 ConsumeBracket();
403 break;
404 case tok::r_brace:
405 if (BraceCount && !isFirstTokenSkipped)
406 return false; // Matches something.
407 ConsumeBrace();
408 break;
409
410 case tok::semi:
411 if (HasFlagsSet(L: Flags, R: StopAtSemi))
412 return false;
413 [[fallthrough]];
414 default:
415 // Skip this token.
416 ConsumeAnyToken();
417 break;
418 }
419 isFirstTokenSkipped = false;
420 }
421}
422
423//===----------------------------------------------------------------------===//
424// Scope manipulation
425//===----------------------------------------------------------------------===//
426
427void Parser::EnterScope(unsigned ScopeFlags) {
428 if (NumCachedScopes) {
429 Scope *N = ScopeCache[--NumCachedScopes];
430 N->Init(parent: getCurScope(), flags: ScopeFlags);
431 Actions.CurScope = N;
432 } else {
433 Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags);
434 }
435}
436
437void Parser::ExitScope() {
438 assert(getCurScope() && "Scope imbalance!");
439
440 // Inform the actions module that this scope is going away if there are any
441 // decls in it.
442 Actions.ActOnPopScope(Loc: Tok.getLocation(), S: getCurScope());
443
444 Scope *OldScope = getCurScope();
445 Actions.CurScope = OldScope->getParent();
446
447 if (NumCachedScopes == ScopeCacheSize)
448 delete OldScope;
449 else
450 ScopeCache[NumCachedScopes++] = OldScope;
451}
452
453Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags,
454 bool ManageFlags)
455 : CurScope(ManageFlags ? Self->getCurScope() : nullptr) {
456 if (CurScope) {
457 OldFlags = CurScope->getFlags();
458 CurScope->setFlags(ScopeFlags);
459 }
460}
461
462Parser::ParseScopeFlags::~ParseScopeFlags() {
463 if (CurScope)
464 CurScope->setFlags(OldFlags);
465}
466
467
468//===----------------------------------------------------------------------===//
469// C99 6.9: External Definitions.
470//===----------------------------------------------------------------------===//
471
472Parser::~Parser() {
473 // If we still have scopes active, delete the scope tree.
474 delete getCurScope();
475 Actions.CurScope = nullptr;
476
477 // Free the scope cache.
478 for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
479 delete ScopeCache[i];
480
481 resetPragmaHandlers();
482
483 PP.removeCommentHandler(Handler: CommentSemaHandler.get());
484
485 PP.clearCodeCompletionHandler();
486
487 DestroyTemplateIds();
488}
489
490void Parser::Initialize() {
491 // Create the translation unit scope. Install it as the current scope.
492 assert(getCurScope() == nullptr && "A scope is already active?");
493 EnterScope(ScopeFlags: Scope::DeclScope);
494 Actions.ActOnTranslationUnitScope(S: getCurScope());
495
496 // Initialization for Objective-C context sensitive keywords recognition.
497 // Referenced in Parser::ParseObjCTypeQualifierList.
498 if (getLangOpts().ObjC) {
499 ObjCTypeQuals[llvm::to_underlying(E: ObjCTypeQual::in)] =
500 &PP.getIdentifierTable().get(Name: "in");
501 ObjCTypeQuals[llvm::to_underlying(E: ObjCTypeQual::out)] =
502 &PP.getIdentifierTable().get(Name: "out");
503 ObjCTypeQuals[llvm::to_underlying(E: ObjCTypeQual::inout)] =
504 &PP.getIdentifierTable().get(Name: "inout");
505 ObjCTypeQuals[llvm::to_underlying(E: ObjCTypeQual::oneway)] =
506 &PP.getIdentifierTable().get(Name: "oneway");
507 ObjCTypeQuals[llvm::to_underlying(E: ObjCTypeQual::bycopy)] =
508 &PP.getIdentifierTable().get(Name: "bycopy");
509 ObjCTypeQuals[llvm::to_underlying(E: ObjCTypeQual::byref)] =
510 &PP.getIdentifierTable().get(Name: "byref");
511 ObjCTypeQuals[llvm::to_underlying(E: ObjCTypeQual::nonnull)] =
512 &PP.getIdentifierTable().get(Name: "nonnull");
513 ObjCTypeQuals[llvm::to_underlying(E: ObjCTypeQual::nullable)] =
514 &PP.getIdentifierTable().get(Name: "nullable");
515 ObjCTypeQuals[llvm::to_underlying(E: ObjCTypeQual::null_unspecified)] =
516 &PP.getIdentifierTable().get(Name: "null_unspecified");
517 }
518
519 Ident_instancetype = nullptr;
520 Ident_final = nullptr;
521 Ident_sealed = nullptr;
522 Ident_abstract = nullptr;
523 Ident_override = nullptr;
524 Ident_GNU_final = nullptr;
525
526 Ident_super = &PP.getIdentifierTable().get(Name: "super");
527
528 Ident_vector = nullptr;
529 Ident_bool = nullptr;
530 Ident_Bool = nullptr;
531 Ident_pixel = nullptr;
532 if (getLangOpts().AltiVec || getLangOpts().ZVector) {
533 Ident_vector = &PP.getIdentifierTable().get(Name: "vector");
534 Ident_bool = &PP.getIdentifierTable().get(Name: "bool");
535 Ident_Bool = &PP.getIdentifierTable().get(Name: "_Bool");
536 }
537 if (getLangOpts().AltiVec)
538 Ident_pixel = &PP.getIdentifierTable().get(Name: "pixel");
539
540 Ident_introduced = nullptr;
541 Ident_deprecated = nullptr;
542 Ident_obsoleted = nullptr;
543 Ident_unavailable = nullptr;
544 Ident_strict = nullptr;
545 Ident_replacement = nullptr;
546
547 Ident_language = Ident_defined_in = Ident_generated_declaration = Ident_USR =
548 nullptr;
549
550 Ident__except = nullptr;
551
552 Ident__exception_code = Ident__exception_info = nullptr;
553 Ident__abnormal_termination = Ident___exception_code = nullptr;
554 Ident___exception_info = Ident___abnormal_termination = nullptr;
555 Ident_GetExceptionCode = Ident_GetExceptionInfo = nullptr;
556 Ident_AbnormalTermination = nullptr;
557
558 if(getLangOpts().Borland) {
559 Ident__exception_info = PP.getIdentifierInfo(Name: "_exception_info");
560 Ident___exception_info = PP.getIdentifierInfo(Name: "__exception_info");
561 Ident_GetExceptionInfo = PP.getIdentifierInfo(Name: "GetExceptionInformation");
562 Ident__exception_code = PP.getIdentifierInfo(Name: "_exception_code");
563 Ident___exception_code = PP.getIdentifierInfo(Name: "__exception_code");
564 Ident_GetExceptionCode = PP.getIdentifierInfo(Name: "GetExceptionCode");
565 Ident__abnormal_termination = PP.getIdentifierInfo(Name: "_abnormal_termination");
566 Ident___abnormal_termination = PP.getIdentifierInfo(Name: "__abnormal_termination");
567 Ident_AbnormalTermination = PP.getIdentifierInfo(Name: "AbnormalTermination");
568
569 PP.SetPoisonReason(II: Ident__exception_code,DiagID: diag::err_seh___except_block);
570 PP.SetPoisonReason(II: Ident___exception_code,DiagID: diag::err_seh___except_block);
571 PP.SetPoisonReason(II: Ident_GetExceptionCode,DiagID: diag::err_seh___except_block);
572 PP.SetPoisonReason(II: Ident__exception_info,DiagID: diag::err_seh___except_filter);
573 PP.SetPoisonReason(II: Ident___exception_info,DiagID: diag::err_seh___except_filter);
574 PP.SetPoisonReason(II: Ident_GetExceptionInfo,DiagID: diag::err_seh___except_filter);
575 PP.SetPoisonReason(II: Ident__abnormal_termination,DiagID: diag::err_seh___finally_block);
576 PP.SetPoisonReason(II: Ident___abnormal_termination,DiagID: diag::err_seh___finally_block);
577 PP.SetPoisonReason(II: Ident_AbnormalTermination,DiagID: diag::err_seh___finally_block);
578 }
579
580 Actions.Initialize();
581
582 // Prime the lexer look-ahead.
583 ConsumeToken();
584}
585
586void Parser::DestroyTemplateIds() {
587 for (TemplateIdAnnotation *Id : TemplateIds)
588 Id->Destroy();
589 TemplateIds.clear();
590}
591
592bool Parser::ParseFirstTopLevelDecl(DeclGroupPtrTy &Result,
593 Sema::ModuleImportState &ImportState) {
594 Actions.ActOnStartOfTranslationUnit();
595
596 // For C++20 modules, a module decl must be the first in the TU. We also
597 // need to track module imports.
598 ImportState = Sema::ModuleImportState::FirstDecl;
599 bool NoTopLevelDecls = ParseTopLevelDecl(Result, ImportState);
600
601 // C11 6.9p1 says translation units must have at least one top-level
602 // declaration. C++ doesn't have this restriction. We also don't want to
603 // complain if we have a precompiled header, although technically if the PCH
604 // is empty we should still emit the (pedantic) diagnostic.
605 // If the main file is a header, we're only pretending it's a TU; don't warn.
606 if (NoTopLevelDecls && !Actions.getASTContext().getExternalSource() &&
607 !getLangOpts().CPlusPlus && !getLangOpts().IsHeaderFile)
608 Diag(DiagID: diag::ext_empty_translation_unit);
609
610 return NoTopLevelDecls;
611}
612
613bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result,
614 Sema::ModuleImportState &ImportState) {
615 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
616
617 Result = nullptr;
618 switch (Tok.getKind()) {
619 case tok::annot_pragma_unused:
620 HandlePragmaUnused();
621 return false;
622
623 case tok::kw_export:
624 switch (NextToken().getKind()) {
625 case tok::kw_module:
626 goto module_decl;
627 case tok::kw_import:
628 goto import_decl;
629 default:
630 break;
631 }
632 break;
633
634 case tok::kw_module:
635 module_decl:
636 Result = ParseModuleDecl(ImportState);
637 return false;
638
639 case tok::kw_import:
640 import_decl: {
641 Decl *ImportDecl = ParseModuleImport(AtLoc: SourceLocation(), ImportState);
642 Result = Actions.ConvertDeclToDeclGroup(Ptr: ImportDecl);
643 return false;
644 }
645
646 case tok::annot_module_include: {
647 auto Loc = Tok.getLocation();
648 Module *Mod = reinterpret_cast<Module *>(Tok.getAnnotationValue());
649 // FIXME: We need a better way to disambiguate C++ clang modules and
650 // standard C++ modules.
651 if (!getLangOpts().CPlusPlusModules || !Mod->isHeaderUnit())
652 Actions.ActOnAnnotModuleInclude(DirectiveLoc: Loc, Mod);
653 else {
654 DeclResult Import =
655 Actions.ActOnModuleImport(StartLoc: Loc, ExportLoc: SourceLocation(), ImportLoc: Loc, M: Mod);
656 Decl *ImportDecl = Import.isInvalid() ? nullptr : Import.get();
657 Result = Actions.ConvertDeclToDeclGroup(Ptr: ImportDecl);
658 }
659 ConsumeAnnotationToken();
660 return false;
661 }
662
663 case tok::annot_module_begin:
664 Actions.ActOnAnnotModuleBegin(
665 DirectiveLoc: Tok.getLocation(),
666 Mod: reinterpret_cast<Module *>(Tok.getAnnotationValue()));
667 ConsumeAnnotationToken();
668 ImportState = Sema::ModuleImportState::NotACXX20Module;
669 return false;
670
671 case tok::annot_module_end:
672 Actions.ActOnAnnotModuleEnd(
673 DirectiveLoc: Tok.getLocation(),
674 Mod: reinterpret_cast<Module *>(Tok.getAnnotationValue()));
675 ConsumeAnnotationToken();
676 ImportState = Sema::ModuleImportState::NotACXX20Module;
677 return false;
678
679 case tok::eof:
680 case tok::annot_repl_input_end:
681 // Check whether -fmax-tokens= was reached.
682 if (PP.getMaxTokens() != 0 && PP.getTokenCount() > PP.getMaxTokens()) {
683 PP.Diag(Loc: Tok.getLocation(), DiagID: diag::warn_max_tokens_total)
684 << PP.getTokenCount() << PP.getMaxTokens();
685 SourceLocation OverrideLoc = PP.getMaxTokensOverrideLoc();
686 if (OverrideLoc.isValid()) {
687 PP.Diag(Loc: OverrideLoc, DiagID: diag::note_max_tokens_total_override);
688 }
689 }
690
691 // Late template parsing can begin.
692 Actions.SetLateTemplateParser(LTP: LateTemplateParserCallback, P: this);
693 Actions.ActOnEndOfTranslationUnit();
694 //else don't tell Sema that we ended parsing: more input might come.
695 return true;
696 default:
697 break;
698 }
699
700 ParsedAttributes DeclAttrs(AttrFactory);
701 ParsedAttributes DeclSpecAttrs(AttrFactory);
702 // GNU attributes are applied to the declaration specification while the
703 // standard attributes are applied to the declaration. We parse the two
704 // attribute sets into different containters so we can apply them during
705 // the regular parsing process.
706 while (MaybeParseCXX11Attributes(Attrs&: DeclAttrs) ||
707 MaybeParseGNUAttributes(Attrs&: DeclSpecAttrs))
708 ;
709
710 Result = ParseExternalDeclaration(DeclAttrs, DeclSpecAttrs);
711 // An empty Result might mean a line with ';' or some parsing error, ignore
712 // it.
713 if (Result) {
714 if (ImportState == Sema::ModuleImportState::FirstDecl)
715 // First decl was not modular.
716 ImportState = Sema::ModuleImportState::NotACXX20Module;
717 else if (ImportState == Sema::ModuleImportState::ImportAllowed)
718 // Non-imports disallow further imports.
719 ImportState = Sema::ModuleImportState::ImportFinished;
720 else if (ImportState ==
721 Sema::ModuleImportState::PrivateFragmentImportAllowed)
722 // Non-imports disallow further imports.
723 ImportState = Sema::ModuleImportState::PrivateFragmentImportFinished;
724 }
725 return false;
726}
727
728Parser::DeclGroupPtrTy
729Parser::ParseExternalDeclaration(ParsedAttributes &Attrs,
730 ParsedAttributes &DeclSpecAttrs,
731 ParsingDeclSpec *DS) {
732 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
733 ParenBraceBracketBalancer BalancerRAIIObj(*this);
734
735 if (PP.isCodeCompletionReached()) {
736 cutOffParsing();
737 return nullptr;
738 }
739
740 Decl *SingleDecl = nullptr;
741 switch (Tok.getKind()) {
742 case tok::annot_pragma_vis:
743 HandlePragmaVisibility();
744 return nullptr;
745 case tok::annot_pragma_pack:
746 HandlePragmaPack();
747 return nullptr;
748 case tok::annot_pragma_msstruct:
749 HandlePragmaMSStruct();
750 return nullptr;
751 case tok::annot_pragma_align:
752 HandlePragmaAlign();
753 return nullptr;
754 case tok::annot_pragma_weak:
755 HandlePragmaWeak();
756 return nullptr;
757 case tok::annot_pragma_weakalias:
758 HandlePragmaWeakAlias();
759 return nullptr;
760 case tok::annot_pragma_redefine_extname:
761 HandlePragmaRedefineExtname();
762 return nullptr;
763 case tok::annot_pragma_fp_contract:
764 HandlePragmaFPContract();
765 return nullptr;
766 case tok::annot_pragma_fenv_access:
767 case tok::annot_pragma_fenv_access_ms:
768 HandlePragmaFEnvAccess();
769 return nullptr;
770 case tok::annot_pragma_fenv_round:
771 HandlePragmaFEnvRound();
772 return nullptr;
773 case tok::annot_pragma_cx_limited_range:
774 HandlePragmaCXLimitedRange();
775 return nullptr;
776 case tok::annot_pragma_float_control:
777 HandlePragmaFloatControl();
778 return nullptr;
779 case tok::annot_pragma_fp:
780 HandlePragmaFP();
781 break;
782 case tok::annot_pragma_opencl_extension:
783 HandlePragmaOpenCLExtension();
784 return nullptr;
785 case tok::annot_attr_openmp:
786 case tok::annot_pragma_openmp: {
787 AccessSpecifier AS = AS_none;
788 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
789 }
790 case tok::annot_pragma_openacc: {
791 AccessSpecifier AS = AS_none;
792 return ParseOpenACCDirectiveDecl(AS, Attrs, TagType: DeclSpec::TST_unspecified,
793 /*TagDecl=*/nullptr);
794 }
795 case tok::annot_pragma_ms_pointers_to_members:
796 HandlePragmaMSPointersToMembers();
797 return nullptr;
798 case tok::annot_pragma_ms_vtordisp:
799 HandlePragmaMSVtorDisp();
800 return nullptr;
801 case tok::annot_pragma_ms_pragma:
802 HandlePragmaMSPragma();
803 return nullptr;
804 case tok::annot_pragma_dump:
805 HandlePragmaDump();
806 return nullptr;
807 case tok::annot_pragma_attribute:
808 HandlePragmaAttribute();
809 return nullptr;
810 case tok::annot_pragma_export:
811 HandlePragmaExport();
812 return nullptr;
813 case tok::semi:
814 // Either a C++11 empty-declaration or attribute-declaration.
815 SingleDecl =
816 Actions.ActOnEmptyDeclaration(S: getCurScope(), AttrList: Attrs, SemiLoc: Tok.getLocation());
817 ConsumeExtraSemi(Kind: ExtraSemiKind::OutsideFunction);
818 break;
819 case tok::r_brace:
820 Diag(Tok, DiagID: diag::err_extraneous_closing_brace);
821 ConsumeBrace();
822 return nullptr;
823 case tok::eof:
824 Diag(Tok, DiagID: diag::err_expected_external_declaration);
825 return nullptr;
826 case tok::kw___extension__: {
827 // __extension__ silences extension warnings in the subexpression.
828 ExtensionRAIIObject O(Diags); // Use RAII to do this.
829 ConsumeToken();
830 return ParseExternalDeclaration(Attrs, DeclSpecAttrs);
831 }
832 case tok::kw_asm: {
833 ProhibitAttributes(Attrs);
834
835 SourceLocation StartLoc = Tok.getLocation();
836 SourceLocation EndLoc;
837
838 ExprResult Result(ParseSimpleAsm(/*ForAsmLabel*/ false, EndLoc: &EndLoc));
839
840 // Check if GNU-style InlineAsm is disabled.
841 // Empty asm string is allowed because it will not introduce
842 // any assembly code.
843 if (!(getLangOpts().GNUAsm || Result.isInvalid())) {
844 const auto *SL = cast<StringLiteral>(Val: Result.get());
845 if (!SL->getString().trim().empty())
846 Diag(Loc: StartLoc, DiagID: diag::err_gnu_inline_asm_disabled);
847 }
848
849 ExpectAndConsume(ExpectedTok: tok::semi, DiagID: diag::err_expected_after,
850 Msg: "top-level asm block");
851
852 if (Result.isInvalid())
853 return nullptr;
854 SingleDecl = Actions.ActOnFileScopeAsmDecl(expr: Result.get(), AsmLoc: StartLoc, RParenLoc: EndLoc);
855 break;
856 }
857 case tok::at:
858 return ParseObjCAtDirectives(DeclAttrs&: Attrs, DeclSpecAttrs);
859 case tok::minus:
860 case tok::plus:
861 if (!getLangOpts().ObjC) {
862 Diag(Tok, DiagID: diag::err_expected_external_declaration);
863 ConsumeToken();
864 return nullptr;
865 }
866 SingleDecl = ParseObjCMethodDefinition();
867 break;
868 case tok::code_completion:
869 cutOffParsing();
870 if (CurParsedObjCImpl) {
871 // Code-complete Objective-C methods even without leading '-'/'+' prefix.
872 Actions.CodeCompletion().CodeCompleteObjCMethodDecl(
873 S: getCurScope(),
874 /*IsInstanceMethod=*/std::nullopt,
875 /*ReturnType=*/nullptr);
876 }
877
878 SemaCodeCompletion::ParserCompletionContext PCC;
879 if (CurParsedObjCImpl) {
880 PCC = SemaCodeCompletion::PCC_ObjCImplementation;
881 } else if (PP.isIncrementalProcessingEnabled()) {
882 PCC = SemaCodeCompletion::PCC_TopLevelOrExpression;
883 } else {
884 PCC = SemaCodeCompletion::PCC_Namespace;
885 };
886 Actions.CodeCompletion().CodeCompleteOrdinaryName(S: getCurScope(), CompletionContext: PCC);
887 return nullptr;
888 case tok::kw_import: {
889 Sema::ModuleImportState IS = Sema::ModuleImportState::NotACXX20Module;
890 if (getLangOpts().CPlusPlusModules) {
891 Diag(Tok, DiagID: diag::err_unexpected_module_or_import_decl)
892 << /*IsImport*/ true;
893 SkipUntil(T: tok::semi);
894 return nullptr;
895 }
896 SingleDecl = ParseModuleImport(AtLoc: SourceLocation(), ImportState&: IS);
897 } break;
898 case tok::kw_export:
899 if (getLangOpts().CPlusPlusModules || getLangOpts().HLSL) {
900 ProhibitAttributes(Attrs);
901 SingleDecl = ParseExportDeclaration();
902 break;
903 }
904 // This must be 'export template'. Parse it so we can diagnose our lack
905 // of support.
906 [[fallthrough]];
907 case tok::kw_using:
908 case tok::kw_namespace:
909 case tok::kw_typedef:
910 case tok::kw_template:
911 case tok::kw_static_assert:
912 case tok::kw__Static_assert:
913 // A function definition cannot start with any of these keywords.
914 {
915 SourceLocation DeclEnd;
916 return ParseDeclaration(Context: DeclaratorContext::File, DeclEnd, DeclAttrs&: Attrs,
917 DeclSpecAttrs);
918 }
919
920 case tok::kw_cbuffer:
921 case tok::kw_tbuffer:
922 if (getLangOpts().HLSL) {
923 SourceLocation DeclEnd;
924 return ParseDeclaration(Context: DeclaratorContext::File, DeclEnd, DeclAttrs&: Attrs,
925 DeclSpecAttrs);
926 }
927 goto dont_know;
928
929 case tok::kw_static:
930 // Parse (then ignore) 'static' prior to a template instantiation. This is
931 // a GCC extension that we intentionally do not support.
932 if (getLangOpts().CPlusPlus && NextToken().is(K: tok::kw_template)) {
933 Diag(Loc: ConsumeToken(), DiagID: diag::warn_static_inline_explicit_inst_ignored)
934 << 0;
935 SourceLocation DeclEnd;
936 return ParseDeclaration(Context: DeclaratorContext::File, DeclEnd, DeclAttrs&: Attrs,
937 DeclSpecAttrs);
938 }
939 goto dont_know;
940
941 case tok::kw_inline:
942 if (getLangOpts().CPlusPlus) {
943 tok::TokenKind NextKind = NextToken().getKind();
944
945 // Inline namespaces. Allowed as an extension even in C++03.
946 if (NextKind == tok::kw_namespace) {
947 SourceLocation DeclEnd;
948 return ParseDeclaration(Context: DeclaratorContext::File, DeclEnd, DeclAttrs&: Attrs,
949 DeclSpecAttrs);
950 }
951
952 // Parse (then ignore) 'inline' prior to a template instantiation. This is
953 // a GCC extension that we intentionally do not support.
954 if (NextKind == tok::kw_template) {
955 Diag(Loc: ConsumeToken(), DiagID: diag::warn_static_inline_explicit_inst_ignored)
956 << 1;
957 SourceLocation DeclEnd;
958 return ParseDeclaration(Context: DeclaratorContext::File, DeclEnd, DeclAttrs&: Attrs,
959 DeclSpecAttrs);
960 }
961 }
962 goto dont_know;
963
964 case tok::kw_extern:
965 if (getLangOpts().CPlusPlus && NextToken().is(K: tok::kw_template)) {
966 ProhibitAttributes(Attrs);
967 ProhibitAttributes(Attrs&: DeclSpecAttrs);
968 // Extern templates
969 SourceLocation ExternLoc = ConsumeToken();
970 SourceLocation TemplateLoc = ConsumeToken();
971 Diag(Loc: ExternLoc, DiagID: getLangOpts().CPlusPlus11 ?
972 diag::warn_cxx98_compat_extern_template :
973 diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
974 SourceLocation DeclEnd;
975 return ParseExplicitInstantiation(Context: DeclaratorContext::File, ExternLoc,
976 TemplateLoc, DeclEnd, AccessAttrs&: Attrs);
977 }
978 goto dont_know;
979
980 case tok::kw___if_exists:
981 case tok::kw___if_not_exists:
982 ParseMicrosoftIfExistsExternalDeclaration();
983 return nullptr;
984
985 case tok::kw_module:
986 Diag(Tok, DiagID: diag::err_unexpected_module_or_import_decl) << /*IsImport*/ false;
987 SkipUntil(T: tok::semi);
988 return nullptr;
989
990 default:
991 dont_know:
992 if (Tok.isEditorPlaceholder()) {
993 ConsumeToken();
994 return nullptr;
995 }
996 if (getLangOpts().IncrementalExtensions &&
997 !isDeclarationStatement(/*DisambiguatingWithExpression=*/true))
998 return ParseTopLevelStmtDecl();
999
1000 // We can't tell whether this is a function-definition or declaration yet.
1001 if (!SingleDecl)
1002 return ParseDeclarationOrFunctionDefinition(DeclAttrs&: Attrs, DeclSpecAttrs, DS);
1003 }
1004
1005 // This routine returns a DeclGroup, if the thing we parsed only contains a
1006 // single decl, convert it now.
1007 return Actions.ConvertDeclToDeclGroup(Ptr: SingleDecl);
1008}
1009
1010bool Parser::isDeclarationAfterDeclarator() {
1011 // Check for '= delete' or '= default'
1012 if (getLangOpts().CPlusPlus && Tok.is(K: tok::equal)) {
1013 const Token &KW = NextToken();
1014 if (KW.is(K: tok::kw_default) || KW.is(K: tok::kw_delete))
1015 return false;
1016 }
1017
1018 return Tok.is(K: tok::equal) || // int X()= -> not a function def
1019 Tok.is(K: tok::comma) || // int X(), -> not a function def
1020 Tok.is(K: tok::semi) || // int X(); -> not a function def
1021 Tok.is(K: tok::kw_asm) || // int X() __asm__ -> not a function def
1022 Tok.is(K: tok::kw___attribute) || // int X() __attr__ -> not a function def
1023 (getLangOpts().CPlusPlus &&
1024 Tok.is(K: tok::l_paren)); // int X(0) -> not a function def [C++]
1025}
1026
1027bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
1028 assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
1029 if (Tok.is(K: tok::l_brace)) // int X() {}
1030 return true;
1031
1032 // Handle K&R C argument lists: int X(f) int f; {}
1033 if (!getLangOpts().CPlusPlus &&
1034 Declarator.getFunctionTypeInfo().isKNRPrototype())
1035 return isDeclarationSpecifier(AllowImplicitTypename: ImplicitTypenameContext::No);
1036
1037 if (getLangOpts().CPlusPlus && Tok.is(K: tok::equal)) {
1038 const Token &KW = NextToken();
1039 return KW.is(K: tok::kw_default) || KW.is(K: tok::kw_delete);
1040 }
1041
1042 return Tok.is(K: tok::colon) || // X() : Base() {} (used for ctors)
1043 Tok.is(K: tok::kw_try); // X() try { ... }
1044}
1045
1046Parser::DeclGroupPtrTy Parser::ParseDeclOrFunctionDefInternal(
1047 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1048 ParsingDeclSpec &DS, AccessSpecifier AS) {
1049 // Because we assume that the DeclSpec has not yet been initialised, we simply
1050 // overwrite the source range and attribute the provided leading declspec
1051 // attributes.
1052 assert(DS.getSourceRange().isInvalid() &&
1053 "expected uninitialised source range");
1054 DS.SetRangeStart(DeclSpecAttrs.Range.getBegin());
1055 DS.SetRangeEnd(DeclSpecAttrs.Range.getEnd());
1056 DS.takeAttributesAppendingingFrom(attrs&: DeclSpecAttrs);
1057
1058 ParsedTemplateInfo TemplateInfo;
1059 MaybeParseMicrosoftAttributes(Attrs&: DS.getAttributes());
1060 // Parse the common declaration-specifiers piece.
1061 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
1062 DSC: DeclSpecContext::DSC_top_level);
1063
1064 // If we had a free-standing type definition with a missing semicolon, we
1065 // may get this far before the problem becomes obvious.
1066 if (DS.hasTagDefinition() && DiagnoseMissingSemiAfterTagDefinition(
1067 DS, AS, DSContext: DeclSpecContext::DSC_top_level))
1068 return nullptr;
1069
1070 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1071 // declaration-specifiers init-declarator-list[opt] ';'
1072 if (Tok.is(K: tok::semi)) {
1073 // Suggest correct location to fix '[[attrib]] struct' to 'struct
1074 // [[attrib]]'
1075 SourceLocation CorrectLocationForAttributes{};
1076 TypeSpecifierType TKind = DS.getTypeSpecType();
1077 if (DeclSpec::isDeclRep(T: TKind)) {
1078 if (TKind == DeclSpec::TST_enum) {
1079 if (const auto *ED = dyn_cast_or_null<EnumDecl>(Val: DS.getRepAsDecl())) {
1080 CorrectLocationForAttributes =
1081 PP.getLocForEndOfToken(Loc: ED->getEnumKeyRange().getEnd());
1082 }
1083 }
1084 if (CorrectLocationForAttributes.isInvalid()) {
1085 const auto &Policy = Actions.getASTContext().getPrintingPolicy();
1086 unsigned Offset =
1087 StringRef(DeclSpec::getSpecifierName(T: TKind, Policy)).size();
1088 CorrectLocationForAttributes =
1089 DS.getTypeSpecTypeLoc().getLocWithOffset(Offset);
1090 }
1091 }
1092 ProhibitAttributes(Attrs, FixItLoc: CorrectLocationForAttributes);
1093 ConsumeToken();
1094 RecordDecl *AnonRecord = nullptr;
1095 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
1096 S: getCurScope(), AS: AS_none, DS, DeclAttrs: ParsedAttributesView::none(), AnonRecord);
1097 DS.complete(D: TheDecl);
1098 Actions.ActOnDefinedDeclarationSpecifier(D: TheDecl);
1099 if (AnonRecord) {
1100 Decl* decls[] = {AnonRecord, TheDecl};
1101 return Actions.BuildDeclaratorGroup(Group: decls);
1102 }
1103 return Actions.ConvertDeclToDeclGroup(Ptr: TheDecl);
1104 }
1105
1106 if (DS.hasTagDefinition())
1107 Actions.ActOnDefinedDeclarationSpecifier(D: DS.getRepAsDecl());
1108
1109 // ObjC2 allows prefix attributes on class interfaces and protocols.
1110 // FIXME: This still needs better diagnostics. We should only accept
1111 // attributes here, no types, etc.
1112 if (getLangOpts().ObjC && Tok.is(K: tok::at)) {
1113 SourceLocation AtLoc = ConsumeToken(); // the "@"
1114 if (!Tok.isObjCAtKeyword(objcKey: tok::objc_interface) &&
1115 !Tok.isObjCAtKeyword(objcKey: tok::objc_protocol) &&
1116 !Tok.isObjCAtKeyword(objcKey: tok::objc_implementation)) {
1117 Diag(Tok, DiagID: diag::err_objc_unexpected_attr);
1118 SkipUntil(T: tok::semi);
1119 return nullptr;
1120 }
1121
1122 DS.abort();
1123 DS.takeAttributesAppendingingFrom(attrs&: Attrs);
1124
1125 const char *PrevSpec = nullptr;
1126 unsigned DiagID;
1127 if (DS.SetTypeSpecType(T: DeclSpec::TST_unspecified, Loc: AtLoc, PrevSpec, DiagID,
1128 Policy: Actions.getASTContext().getPrintingPolicy()))
1129 Diag(Loc: AtLoc, DiagID) << PrevSpec;
1130
1131 if (Tok.isObjCAtKeyword(objcKey: tok::objc_protocol))
1132 return ParseObjCAtProtocolDeclaration(atLoc: AtLoc, prefixAttrs&: DS.getAttributes());
1133
1134 if (Tok.isObjCAtKeyword(objcKey: tok::objc_implementation))
1135 return ParseObjCAtImplementationDeclaration(AtLoc, Attrs&: DS.getAttributes());
1136
1137 return Actions.ConvertDeclToDeclGroup(
1138 Ptr: ParseObjCAtInterfaceDeclaration(AtLoc, prefixAttrs&: DS.getAttributes()));
1139 }
1140
1141 // If the declspec consisted only of 'extern' and we have a string
1142 // literal following it, this must be a C++ linkage specifier like
1143 // 'extern "C"'.
1144 if (getLangOpts().CPlusPlus && isTokenStringLiteral() &&
1145 DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
1146 DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
1147 ProhibitAttributes(Attrs);
1148 Decl *TheDecl = ParseLinkage(DS, Context: DeclaratorContext::File);
1149 return Actions.ConvertDeclToDeclGroup(Ptr: TheDecl);
1150 }
1151
1152 return ParseDeclGroup(DS, Context: DeclaratorContext::File, Attrs, TemplateInfo);
1153}
1154
1155Parser::DeclGroupPtrTy Parser::ParseDeclarationOrFunctionDefinition(
1156 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1157 ParsingDeclSpec *DS, AccessSpecifier AS) {
1158 // Add an enclosing time trace scope for a bunch of small scopes with
1159 // "EvaluateAsConstExpr".
1160 llvm::TimeTraceScope TimeScope("ParseDeclarationOrFunctionDefinition", [&]() {
1161 return Tok.getLocation().printToString(
1162 SM: Actions.getASTContext().getSourceManager());
1163 });
1164
1165 if (DS) {
1166 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, DS&: *DS, AS);
1167 } else {
1168 ParsingDeclSpec PDS(*this);
1169 // Must temporarily exit the objective-c container scope for
1170 // parsing c constructs and re-enter objc container scope
1171 // afterwards.
1172 ObjCDeclContextSwitch ObjCDC(*this);
1173
1174 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, DS&: PDS, AS);
1175 }
1176}
1177
1178Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
1179 const ParsedTemplateInfo &TemplateInfo,
1180 LateParsedAttrList *LateParsedAttrs) {
1181 llvm::TimeTraceScope TimeScope("ParseFunctionDefinition", [&]() {
1182 return Actions.GetNameForDeclarator(D).getName().getAsString();
1183 });
1184
1185 // Poison SEH identifiers so they are flagged as illegal in function bodies.
1186 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
1187 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1188 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1189
1190 // If this is C89 and the declspecs were completely missing, fudge in an
1191 // implicit int. We do this here because this is the only place where
1192 // declaration-specifiers are completely optional in the grammar.
1193 if (getLangOpts().isImplicitIntRequired() && D.getDeclSpec().isEmpty()) {
1194 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::warn_missing_type_specifier)
1195 << D.getDeclSpec().getSourceRange()
1196 << FixItHint::CreateInsertion(InsertionLoc: D.getDeclSpec().getBeginLoc(), Code: "int ");
1197 const char *PrevSpec;
1198 unsigned DiagID;
1199 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1200 D.getMutableDeclSpec().SetTypeSpecType(T: DeclSpec::TST_int,
1201 Loc: D.getIdentifierLoc(),
1202 PrevSpec, DiagID,
1203 Policy);
1204 D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
1205 }
1206
1207 // If this declaration was formed with a K&R-style identifier list for the
1208 // arguments, parse declarations for all of the args next.
1209 // int foo(a,b) int a; float b; {}
1210 if (FTI.isKNRPrototype())
1211 ParseKNRParamDeclarations(D);
1212
1213 // We should have either an opening brace or, in a C++ constructor,
1214 // we may have a colon.
1215 if (Tok.isNot(K: tok::l_brace) &&
1216 (!getLangOpts().CPlusPlus ||
1217 (Tok.isNot(K: tok::colon) && Tok.isNot(K: tok::kw_try) &&
1218 Tok.isNot(K: tok::equal)))) {
1219 Diag(Tok, DiagID: diag::err_expected_fn_body);
1220
1221 // Skip over garbage, until we get to '{'. Don't eat the '{'.
1222 SkipUntil(T: tok::l_brace, Flags: StopAtSemi | StopBeforeMatch);
1223
1224 // If we didn't find the '{', bail out.
1225 if (Tok.isNot(K: tok::l_brace))
1226 return nullptr;
1227 }
1228
1229 // Check to make sure that any normal attributes are allowed to be on
1230 // a definition. Late parsed attributes are checked at the end.
1231 if (Tok.isNot(K: tok::equal)) {
1232 for (const ParsedAttr &AL : D.getAttributes())
1233 if (AL.isKnownToGCC() && !AL.isStandardAttributeSyntax())
1234 Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_on_function_definition) << AL;
1235 }
1236
1237 // In delayed template parsing mode, for function template we consume the
1238 // tokens and store them for late parsing at the end of the translation unit.
1239 if (getLangOpts().DelayedTemplateParsing && Tok.isNot(K: tok::equal) &&
1240 TemplateInfo.Kind == ParsedTemplateKind::Template &&
1241 LateParsedAttrs->empty() && Actions.canDelayFunctionBody(D)) {
1242 MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
1243
1244 ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1245 Scope::CompoundStmtScope);
1246 Scope *ParentScope = getCurScope()->getParent();
1247
1248 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
1249 Decl *DP = Actions.HandleDeclarator(S: ParentScope, D,
1250 TemplateParameterLists);
1251 D.complete(D: DP);
1252 D.getMutableDeclSpec().abort();
1253
1254 if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(D: DP)) &&
1255 trySkippingFunctionBody()) {
1256 BodyScope.Exit();
1257 return Actions.ActOnSkippedFunctionBody(Decl: DP);
1258 }
1259
1260 CachedTokens Toks;
1261 LexTemplateFunctionForLateParsing(Toks);
1262
1263 if (DP) {
1264 FunctionDecl *FnD = DP->getAsFunction();
1265 Actions.CheckForFunctionRedefinition(FD: FnD);
1266 Actions.MarkAsLateParsedTemplate(FD: FnD, FnD: DP, Toks);
1267 }
1268 return DP;
1269 }
1270 if (CurParsedObjCImpl && !TemplateInfo.TemplateParams &&
1271 (Tok.is(K: tok::l_brace) || Tok.is(K: tok::kw_try) || Tok.is(K: tok::colon)) &&
1272 Actions.CurContext->isTranslationUnit()) {
1273 ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1274 Scope::CompoundStmtScope);
1275 Scope *ParentScope = getCurScope()->getParent();
1276
1277 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
1278 Decl *FuncDecl = Actions.HandleDeclarator(S: ParentScope, D,
1279 TemplateParameterLists: MultiTemplateParamsArg());
1280 D.complete(D: FuncDecl);
1281 D.getMutableDeclSpec().abort();
1282 if (FuncDecl) {
1283 // Consume the tokens and store them for later parsing.
1284 StashAwayMethodOrFunctionBodyTokens(MDecl: FuncDecl);
1285 CurParsedObjCImpl->HasCFunction = true;
1286 return FuncDecl;
1287 }
1288 // FIXME: Should we really fall through here?
1289 }
1290
1291 // Enter a scope for the function body.
1292 ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1293 Scope::CompoundStmtScope);
1294
1295 // Parse function body eagerly if it is either '= delete;' or '= default;' as
1296 // ActOnStartOfFunctionDef needs to know whether the function is deleted.
1297 StringLiteral *DeletedMessage = nullptr;
1298 Sema::FnBodyKind BodyKind = Sema::FnBodyKind::Other;
1299 SourceLocation KWLoc;
1300 if (TryConsumeToken(Expected: tok::equal)) {
1301 assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
1302
1303 if (TryConsumeToken(Expected: tok::kw_delete, Loc&: KWLoc)) {
1304 Diag(Loc: KWLoc, DiagID: getLangOpts().CPlusPlus11
1305 ? diag::warn_cxx98_compat_defaulted_deleted_function
1306 : diag::ext_defaulted_deleted_function)
1307 << 1 /* deleted */;
1308 BodyKind = Sema::FnBodyKind::Delete;
1309 DeletedMessage = ParseCXXDeletedFunctionMessage();
1310 D.SetRangeEnd(PrevTokLocation);
1311 } else if (TryConsumeToken(Expected: tok::kw_default, Loc&: KWLoc)) {
1312 Diag(Loc: KWLoc, DiagID: getLangOpts().CPlusPlus11
1313 ? diag::warn_cxx98_compat_defaulted_deleted_function
1314 : diag::ext_defaulted_deleted_function)
1315 << 0 /* defaulted */;
1316 BodyKind = Sema::FnBodyKind::Default;
1317 D.SetRangeEnd(PrevTokLocation);
1318 } else {
1319 llvm_unreachable("function definition after = not 'delete' or 'default'");
1320 }
1321
1322 if (Tok.is(K: tok::comma)) {
1323 Diag(Loc: KWLoc, DiagID: diag::err_default_delete_in_multiple_declaration)
1324 << (BodyKind == Sema::FnBodyKind::Delete);
1325 SkipUntil(T: tok::semi);
1326 } else if (ExpectAndConsume(ExpectedTok: tok::semi, DiagID: diag::err_expected_after,
1327 Msg: BodyKind == Sema::FnBodyKind::Delete
1328 ? "delete"
1329 : "default")) {
1330 SkipUntil(T: tok::semi);
1331 }
1332 }
1333
1334 Sema::FPFeaturesStateRAII SaveFPFeatures(Actions);
1335
1336 // Tell the actions module that we have entered a function definition with the
1337 // specified Declarator for the function.
1338 SkipBodyInfo SkipBody;
1339 Decl *Res = Actions.ActOnStartOfFunctionDef(S: getCurScope(), D,
1340 TemplateParamLists: TemplateInfo.TemplateParams
1341 ? *TemplateInfo.TemplateParams
1342 : MultiTemplateParamsArg(),
1343 SkipBody: &SkipBody, BodyKind);
1344
1345 if (SkipBody.ShouldSkip) {
1346 // Do NOT enter SkipFunctionBody if we already consumed the tokens.
1347 if (BodyKind == Sema::FnBodyKind::Other)
1348 SkipFunctionBody();
1349
1350 // ExpressionEvaluationContext is pushed in ActOnStartOfFunctionDef
1351 // and it would be popped in ActOnFinishFunctionBody.
1352 // We pop it explcitly here since ActOnFinishFunctionBody won't get called.
1353 //
1354 // Do not call PopExpressionEvaluationContext() if it is a lambda because
1355 // one is already popped when finishing the lambda in BuildLambdaExpr().
1356 //
1357 // FIXME: It looks not easy to balance PushExpressionEvaluationContext()
1358 // and PopExpressionEvaluationContext().
1359 if (!isLambdaCallOperator(DC: dyn_cast_if_present<FunctionDecl>(Val: Res)))
1360 Actions.PopExpressionEvaluationContext();
1361 return Res;
1362 }
1363
1364 // Break out of the ParsingDeclarator context before we parse the body.
1365 D.complete(D: Res);
1366
1367 // Break out of the ParsingDeclSpec context, too. This const_cast is
1368 // safe because we're always the sole owner.
1369 D.getMutableDeclSpec().abort();
1370
1371 if (BodyKind != Sema::FnBodyKind::Other) {
1372 Actions.SetFunctionBodyKind(D: Res, Loc: KWLoc, BodyKind, DeletedMessage);
1373 Stmt *GeneratedBody = Res ? Res->getBody() : nullptr;
1374 Actions.ActOnFinishFunctionBody(Decl: Res, Body: GeneratedBody, IsInstantiation: false);
1375 return Res;
1376 }
1377
1378 // With abbreviated function templates - we need to explicitly add depth to
1379 // account for the implicit template parameter list induced by the template.
1380 if (const auto *Template = dyn_cast_if_present<FunctionTemplateDecl>(Val: Res);
1381 Template && Template->isAbbreviated() &&
1382 Template->getTemplateParameters()->getParam(Idx: 0)->isImplicit())
1383 // First template parameter is implicit - meaning no explicit template
1384 // parameter list was specified.
1385 CurTemplateDepthTracker.addDepth(D: 1);
1386
1387 // Late attributes are parsed in the same scope as the function body.
1388 if (LateParsedAttrs)
1389 ParseLexedAttributeList(LAs&: *LateParsedAttrs, D: Res, /*EnterScope=*/false,
1390 /*OnDefinition=*/true);
1391
1392 if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(D: Res)) &&
1393 trySkippingFunctionBody()) {
1394 BodyScope.Exit();
1395 Actions.ActOnSkippedFunctionBody(Decl: Res);
1396 return Actions.ActOnFinishFunctionBody(Decl: Res, Body: nullptr, IsInstantiation: false);
1397 }
1398
1399 if (Tok.is(K: tok::kw_try))
1400 return ParseFunctionTryBlock(Decl: Res, BodyScope);
1401
1402 // If we have a colon, then we're probably parsing a C++
1403 // ctor-initializer.
1404 if (Tok.is(K: tok::colon)) {
1405 ParseConstructorInitializer(ConstructorDecl: Res);
1406
1407 // Recover from error.
1408 if (!Tok.is(K: tok::l_brace)) {
1409 BodyScope.Exit();
1410 Actions.ActOnFinishFunctionBody(Decl: Res, Body: nullptr);
1411 return Res;
1412 }
1413 } else
1414 Actions.ActOnDefaultCtorInitializers(CDtorDecl: Res);
1415
1416 return ParseFunctionStatementBody(Decl: Res, BodyScope);
1417}
1418
1419void Parser::SkipFunctionBody() {
1420 if (Tok.is(K: tok::equal)) {
1421 SkipUntil(T: tok::semi);
1422 return;
1423 }
1424
1425 bool IsFunctionTryBlock = Tok.is(K: tok::kw_try);
1426 if (IsFunctionTryBlock)
1427 ConsumeToken();
1428
1429 CachedTokens Skipped;
1430 if (ConsumeAndStoreFunctionPrologue(Toks&: Skipped))
1431 SkipMalformedDecl();
1432 else {
1433 SkipUntil(T: tok::r_brace);
1434 while (IsFunctionTryBlock && Tok.is(K: tok::kw_catch)) {
1435 SkipUntil(T: tok::l_brace);
1436 SkipUntil(T: tok::r_brace);
1437 }
1438 }
1439}
1440
1441void Parser::ParseKNRParamDeclarations(Declarator &D) {
1442 // We know that the top-level of this declarator is a function.
1443 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1444
1445 // Enter function-declaration scope, limiting any declarators to the
1446 // function prototype scope, including parameter declarators.
1447 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1448 Scope::FunctionDeclarationScope | Scope::DeclScope);
1449
1450 // Read all the argument declarations.
1451 while (isDeclarationSpecifier(AllowImplicitTypename: ImplicitTypenameContext::No)) {
1452 SourceLocation DSStart = Tok.getLocation();
1453
1454 // Parse the common declaration-specifiers piece.
1455 DeclSpec DS(AttrFactory);
1456 ParsedTemplateInfo TemplateInfo;
1457 ParseDeclarationSpecifiers(DS, TemplateInfo);
1458
1459 // C99 6.9.1p6: 'each declaration in the declaration list shall have at
1460 // least one declarator'.
1461 // NOTE: GCC just makes this an ext-warn. It's not clear what it does with
1462 // the declarations though. It's trivial to ignore them, really hard to do
1463 // anything else with them.
1464 if (TryConsumeToken(Expected: tok::semi)) {
1465 Diag(Loc: DSStart, DiagID: diag::err_declaration_does_not_declare_param);
1466 continue;
1467 }
1468
1469 // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
1470 // than register.
1471 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1472 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1473 Diag(Loc: DS.getStorageClassSpecLoc(),
1474 DiagID: diag::err_invalid_storage_class_in_func_decl);
1475 DS.ClearStorageClassSpecs();
1476 }
1477 if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) {
1478 Diag(Loc: DS.getThreadStorageClassSpecLoc(),
1479 DiagID: diag::err_invalid_storage_class_in_func_decl);
1480 DS.ClearStorageClassSpecs();
1481 }
1482
1483 // Parse the first declarator attached to this declspec.
1484 Declarator ParmDeclarator(DS, ParsedAttributesView::none(),
1485 DeclaratorContext::KNRTypeList);
1486 ParseDeclarator(D&: ParmDeclarator);
1487
1488 // Handle the full declarator list.
1489 while (true) {
1490 // If attributes are present, parse them.
1491 MaybeParseGNUAttributes(D&: ParmDeclarator);
1492
1493 // Ask the actions module to compute the type for this declarator.
1494 Decl *Param =
1495 Actions.ActOnParamDeclarator(S: getCurScope(), D&: ParmDeclarator);
1496
1497 if (Param &&
1498 // A missing identifier has already been diagnosed.
1499 ParmDeclarator.getIdentifier()) {
1500
1501 // Scan the argument list looking for the correct param to apply this
1502 // type.
1503 for (unsigned i = 0; ; ++i) {
1504 // C99 6.9.1p6: those declarators shall declare only identifiers from
1505 // the identifier list.
1506 if (i == FTI.NumParams) {
1507 Diag(Loc: ParmDeclarator.getIdentifierLoc(), DiagID: diag::err_no_matching_param)
1508 << ParmDeclarator.getIdentifier();
1509 break;
1510 }
1511
1512 if (FTI.Params[i].Ident == ParmDeclarator.getIdentifier()) {
1513 // Reject redefinitions of parameters.
1514 if (FTI.Params[i].Param) {
1515 Diag(Loc: ParmDeclarator.getIdentifierLoc(),
1516 DiagID: diag::err_param_redefinition)
1517 << ParmDeclarator.getIdentifier();
1518 } else {
1519 FTI.Params[i].Param = Param;
1520 }
1521 break;
1522 }
1523 }
1524 }
1525
1526 // If we don't have a comma, it is either the end of the list (a ';') or
1527 // an error, bail out.
1528 if (Tok.isNot(K: tok::comma))
1529 break;
1530
1531 ParmDeclarator.clear();
1532
1533 // Consume the comma.
1534 ParmDeclarator.setCommaLoc(ConsumeToken());
1535
1536 // Parse the next declarator.
1537 ParseDeclarator(D&: ParmDeclarator);
1538 }
1539
1540 // Consume ';' and continue parsing.
1541 if (!ExpectAndConsumeSemi(DiagID: diag::err_expected_semi_declaration))
1542 continue;
1543
1544 // Otherwise recover by skipping to next semi or mandatory function body.
1545 if (SkipUntil(T: tok::l_brace, Flags: StopAtSemi | StopBeforeMatch))
1546 break;
1547 TryConsumeToken(Expected: tok::semi);
1548 }
1549
1550 // The actions module must verify that all arguments were declared.
1551 Actions.ActOnFinishKNRParamDeclarations(S: getCurScope(), D, LocAfterDecls: Tok.getLocation());
1552}
1553
1554ExprResult Parser::ParseAsmStringLiteral(bool ForAsmLabel) {
1555
1556 ExprResult AsmString;
1557 if (isTokenStringLiteral()) {
1558 AsmString = ParseStringLiteralExpression();
1559 if (AsmString.isInvalid())
1560 return AsmString;
1561
1562 const auto *SL = cast<StringLiteral>(Val: AsmString.get());
1563 if (!SL->isOrdinary()) {
1564 Diag(Tok, DiagID: diag::err_asm_operand_wide_string_literal)
1565 << SL->isWide() << SL->getSourceRange();
1566 return ExprError();
1567 }
1568 } else if (!ForAsmLabel && getLangOpts().CPlusPlus11 &&
1569 Tok.is(K: tok::l_paren)) {
1570 ParenParseOption ExprType = ParenParseOption::SimpleExpr;
1571 SourceLocation RParenLoc;
1572 ParsedType CastTy;
1573
1574 EnterExpressionEvaluationContext ConstantEvaluated(
1575 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1576 AsmString = ParseParenExpression(
1577 ExprType, /*StopIfCastExr=*/StopIfCastExpr: true, ParenBehavior: ParenExprKind::Unknown,
1578 CorrectionBehavior: TypoCorrectionTypeBehavior::AllowBoth, CastTy, RParenLoc);
1579 if (!AsmString.isInvalid())
1580 AsmString = Actions.ActOnConstantExpression(Res: AsmString);
1581
1582 if (AsmString.isInvalid())
1583 return ExprError();
1584 } else {
1585 Diag(Tok, DiagID: diag::err_asm_expected_string) << /*and expression=*/(
1586 (getLangOpts().CPlusPlus11 && !ForAsmLabel) ? 0 : 1);
1587 }
1588
1589 return Actions.ActOnGCCAsmStmtString(Stm: AsmString.get(), ForAsmLabel);
1590}
1591
1592ExprResult Parser::ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc) {
1593 assert(Tok.is(tok::kw_asm) && "Not an asm!");
1594 SourceLocation Loc = ConsumeToken();
1595
1596 if (isGNUAsmQualifier(TokAfterAsm: Tok)) {
1597 // Remove from the end of 'asm' to the end of the asm qualifier.
1598 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1599 PP.getLocForEndOfToken(Loc: Tok.getLocation()));
1600 Diag(Tok, DiagID: diag::err_global_asm_qualifier_ignored)
1601 << GNUAsmQualifiers::getQualifierName(Qualifier: getGNUAsmQualifier(Tok))
1602 << FixItHint::CreateRemoval(RemoveRange: RemovalRange);
1603 ConsumeToken();
1604 }
1605
1606 BalancedDelimiterTracker T(*this, tok::l_paren);
1607 if (T.consumeOpen()) {
1608 Diag(Tok, DiagID: diag::err_expected_lparen_after) << "asm";
1609 return ExprError();
1610 }
1611
1612 ExprResult Result(ParseAsmStringLiteral(ForAsmLabel));
1613
1614 if (!Result.isInvalid()) {
1615 // Close the paren and get the location of the end bracket
1616 T.consumeClose();
1617 if (EndLoc)
1618 *EndLoc = T.getCloseLocation();
1619 } else if (SkipUntil(T: tok::r_paren, Flags: StopAtSemi | StopBeforeMatch)) {
1620 if (EndLoc)
1621 *EndLoc = Tok.getLocation();
1622 ConsumeParen();
1623 }
1624
1625 return Result;
1626}
1627
1628TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
1629 assert(tok.is(tok::annot_template_id) && "Expected template-id token");
1630 TemplateIdAnnotation *
1631 Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
1632 return Id;
1633}
1634
1635void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
1636 // Push the current token back into the token stream (or revert it if it is
1637 // cached) and use an annotation scope token for current token.
1638 if (PP.isBacktrackEnabled())
1639 PP.RevertCachedTokens(N: 1);
1640 else
1641 PP.EnterToken(Tok, /*IsReinject=*/true);
1642 Tok.setKind(tok::annot_cxxscope);
1643 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1644 Tok.setAnnotationRange(SS.getRange());
1645
1646 // In case the tokens were cached, have Preprocessor replace them
1647 // with the annotation token. We don't need to do this if we've
1648 // just reverted back to a prior state.
1649 if (IsNewAnnotation)
1650 PP.AnnotateCachedTokens(Tok);
1651}
1652
1653AnnotatedNameKind
1654Parser::TryAnnotateName(CorrectionCandidateCallback *CCC,
1655 ImplicitTypenameContext AllowImplicitTypename) {
1656 assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1657
1658 const bool EnteringContext = false;
1659 const bool WasScopeAnnotation = Tok.is(K: tok::annot_cxxscope);
1660
1661 CXXScopeSpec SS;
1662 if (getLangOpts().CPlusPlus &&
1663 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1664 /*ObjectHasErrors=*/false,
1665 EnteringContext))
1666 return AnnotatedNameKind::Error;
1667
1668 if (Tok.isNot(K: tok::identifier) || SS.isInvalid()) {
1669 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, IsNewScope: !WasScopeAnnotation,
1670 AllowImplicitTypename))
1671 return AnnotatedNameKind::Error;
1672 return AnnotatedNameKind::Unresolved;
1673 }
1674
1675 IdentifierInfo *Name = Tok.getIdentifierInfo();
1676 SourceLocation NameLoc = Tok.getLocation();
1677
1678 // FIXME: Move the tentative declaration logic into ClassifyName so we can
1679 // typo-correct to tentatively-declared identifiers.
1680 if (isTentativelyDeclared(II: Name) && SS.isEmpty()) {
1681 // Identifier has been tentatively declared, and thus cannot be resolved as
1682 // an expression. Fall back to annotating it as a type.
1683 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, IsNewScope: !WasScopeAnnotation,
1684 AllowImplicitTypename))
1685 return AnnotatedNameKind::Error;
1686 return Tok.is(K: tok::annot_typename) ? AnnotatedNameKind::Success
1687 : AnnotatedNameKind::TentativeDecl;
1688 }
1689
1690 Token Next = NextToken();
1691
1692 // Look up and classify the identifier. We don't perform any typo-correction
1693 // after a scope specifier, because in general we can't recover from typos
1694 // there (eg, after correcting 'A::template B<X>::C' [sic], we would need to
1695 // jump back into scope specifier parsing).
1696 Sema::NameClassification Classification = Actions.ClassifyName(
1697 S: getCurScope(), SS, Name, NameLoc, NextToken: Next, CCC: SS.isEmpty() ? CCC : nullptr);
1698
1699 // If name lookup found nothing and we guessed that this was a template name,
1700 // double-check before committing to that interpretation. C++20 requires that
1701 // we interpret this as a template-id if it can be, but if it can't be, then
1702 // this is an error recovery case.
1703 if (Classification.getKind() == NameClassificationKind::UndeclaredTemplate &&
1704 isTemplateArgumentList(TokensToSkip: 1) == TPResult::False) {
1705 // It's not a template-id; re-classify without the '<' as a hint.
1706 Token FakeNext = Next;
1707 FakeNext.setKind(tok::unknown);
1708 Classification =
1709 Actions.ClassifyName(S: getCurScope(), SS, Name, NameLoc, NextToken: FakeNext,
1710 CCC: SS.isEmpty() ? CCC : nullptr);
1711 }
1712
1713 switch (Classification.getKind()) {
1714 case NameClassificationKind::Error:
1715 return AnnotatedNameKind::Error;
1716
1717 case NameClassificationKind::Keyword:
1718 // The identifier was typo-corrected to a keyword.
1719 Tok.setIdentifierInfo(Name);
1720 Tok.setKind(Name->getTokenID());
1721 PP.TypoCorrectToken(Tok);
1722 if (SS.isNotEmpty())
1723 AnnotateScopeToken(SS, IsNewAnnotation: !WasScopeAnnotation);
1724 // We've "annotated" this as a keyword.
1725 return AnnotatedNameKind::Success;
1726
1727 case NameClassificationKind::Unknown:
1728 // It's not something we know about. Leave it unannotated.
1729 break;
1730
1731 case NameClassificationKind::Type: {
1732 if (TryAltiVecVectorToken())
1733 // vector has been found as a type id when altivec is enabled but
1734 // this is followed by a declaration specifier so this is really the
1735 // altivec vector token. Leave it unannotated.
1736 break;
1737 SourceLocation BeginLoc = NameLoc;
1738 if (SS.isNotEmpty())
1739 BeginLoc = SS.getBeginLoc();
1740
1741 /// An Objective-C object type followed by '<' is a specialization of
1742 /// a parameterized class type or a protocol-qualified type.
1743 ParsedType Ty = Classification.getType();
1744 QualType T = Actions.GetTypeFromParser(Ty);
1745 if (getLangOpts().ObjC && NextToken().is(K: tok::less) &&
1746 (T->isObjCObjectType() || T->isObjCObjectPointerType())) {
1747 // Consume the name.
1748 SourceLocation IdentifierLoc = ConsumeToken();
1749 SourceLocation NewEndLoc;
1750 TypeResult NewType
1751 = parseObjCTypeArgsAndProtocolQualifiers(loc: IdentifierLoc, type: Ty,
1752 /*consumeLastToken=*/false,
1753 endLoc&: NewEndLoc);
1754 if (NewType.isUsable())
1755 Ty = NewType.get();
1756 else if (Tok.is(K: tok::eof)) // Nothing to do here, bail out...
1757 return AnnotatedNameKind::Error;
1758 }
1759
1760 Tok.setKind(tok::annot_typename);
1761 setTypeAnnotation(Tok, T: Ty);
1762 Tok.setAnnotationEndLoc(Tok.getLocation());
1763 Tok.setLocation(BeginLoc);
1764 PP.AnnotateCachedTokens(Tok);
1765 return AnnotatedNameKind::Success;
1766 }
1767
1768 case NameClassificationKind::OverloadSet:
1769 Tok.setKind(tok::annot_overload_set);
1770 setExprAnnotation(Tok, ER: Classification.getExpression());
1771 Tok.setAnnotationEndLoc(NameLoc);
1772 if (SS.isNotEmpty())
1773 Tok.setLocation(SS.getBeginLoc());
1774 PP.AnnotateCachedTokens(Tok);
1775 return AnnotatedNameKind::Success;
1776
1777 case NameClassificationKind::NonType:
1778 if (TryAltiVecVectorToken())
1779 // vector has been found as a non-type id when altivec is enabled but
1780 // this is followed by a declaration specifier so this is really the
1781 // altivec vector token. Leave it unannotated.
1782 break;
1783 Tok.setKind(tok::annot_non_type);
1784 setNonTypeAnnotation(Tok, ND: Classification.getNonTypeDecl());
1785 Tok.setLocation(NameLoc);
1786 Tok.setAnnotationEndLoc(NameLoc);
1787 PP.AnnotateCachedTokens(Tok);
1788 if (SS.isNotEmpty())
1789 AnnotateScopeToken(SS, IsNewAnnotation: !WasScopeAnnotation);
1790 return AnnotatedNameKind::Success;
1791
1792 case NameClassificationKind::UndeclaredNonType:
1793 case NameClassificationKind::DependentNonType:
1794 Tok.setKind(Classification.getKind() ==
1795 NameClassificationKind::UndeclaredNonType
1796 ? tok::annot_non_type_undeclared
1797 : tok::annot_non_type_dependent);
1798 setIdentifierAnnotation(Tok, ND: Name);
1799 Tok.setLocation(NameLoc);
1800 Tok.setAnnotationEndLoc(NameLoc);
1801 PP.AnnotateCachedTokens(Tok);
1802 if (SS.isNotEmpty())
1803 AnnotateScopeToken(SS, IsNewAnnotation: !WasScopeAnnotation);
1804 return AnnotatedNameKind::Success;
1805
1806 case NameClassificationKind::TypeTemplate:
1807 if (Next.isNot(K: tok::less)) {
1808 // This may be a type or variable template being used as a template
1809 // template argument.
1810 if (SS.isNotEmpty())
1811 AnnotateScopeToken(SS, IsNewAnnotation: !WasScopeAnnotation);
1812 return AnnotatedNameKind::TemplateName;
1813 }
1814 [[fallthrough]];
1815 case NameClassificationKind::Concept:
1816 case NameClassificationKind::VarTemplate:
1817 case NameClassificationKind::FunctionTemplate:
1818 case NameClassificationKind::UndeclaredTemplate: {
1819 bool IsConceptName =
1820 Classification.getKind() == NameClassificationKind::Concept;
1821 // We have a template name followed by '<'. Consume the identifier token so
1822 // we reach the '<' and annotate it.
1823 UnqualifiedId Id;
1824 Id.setIdentifier(Id: Name, IdLoc: NameLoc);
1825 if (Next.is(K: tok::less))
1826 ConsumeToken();
1827 if (AnnotateTemplateIdToken(
1828 Template: TemplateTy::make(P: Classification.getTemplateName()),
1829 TNK: Classification.getTemplateNameKind(), SS, TemplateKWLoc: SourceLocation(), TemplateName&: Id,
1830 /*AllowTypeAnnotation=*/!IsConceptName,
1831 /*TypeConstraint=*/IsConceptName))
1832 return AnnotatedNameKind::Error;
1833 if (SS.isNotEmpty())
1834 AnnotateScopeToken(SS, IsNewAnnotation: !WasScopeAnnotation);
1835 return AnnotatedNameKind::Success;
1836 }
1837 }
1838
1839 // Unable to classify the name, but maybe we can annotate a scope specifier.
1840 if (SS.isNotEmpty())
1841 AnnotateScopeToken(SS, IsNewAnnotation: !WasScopeAnnotation);
1842 return AnnotatedNameKind::Unresolved;
1843}
1844
1845SourceLocation Parser::getEndOfPreviousToken() const {
1846 SourceLocation TokenEndLoc = PP.getLocForEndOfToken(Loc: PrevTokLocation);
1847 return TokenEndLoc.isValid() ? TokenEndLoc : Tok.getLocation();
1848}
1849
1850bool Parser::TryKeywordIdentFallback(bool DisableKeyword) {
1851 assert(Tok.isNot(tok::identifier));
1852 Diag(Tok, DiagID: diag::ext_keyword_as_ident)
1853 << PP.getSpelling(Tok)
1854 << DisableKeyword;
1855 if (DisableKeyword)
1856 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
1857 Tok.setKind(tok::identifier);
1858 return true;
1859}
1860
1861bool Parser::TryAnnotateTypeOrScopeToken(
1862 ImplicitTypenameContext AllowImplicitTypename, bool IsAddressOfOperand) {
1863 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1864 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
1865 Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
1866 Tok.is(tok::kw___super) || Tok.is(tok::kw_auto) ||
1867 Tok.is(tok::annot_pack_indexing_type)) &&
1868 "Cannot be a type or scope token!");
1869
1870 if (Tok.is(K: tok::kw_typename)) {
1871 // MSVC lets you do stuff like:
1872 // typename typedef T_::D D;
1873 //
1874 // We will consume the typedef token here and put it back after we have
1875 // parsed the first identifier, transforming it into something more like:
1876 // typename T_::D typedef D;
1877 if (getLangOpts().MSVCCompat && NextToken().is(K: tok::kw_typedef)) {
1878 Token TypedefToken;
1879 PP.Lex(Result&: TypedefToken);
1880 bool Result = TryAnnotateTypeOrScopeToken(AllowImplicitTypename);
1881 PP.EnterToken(Tok, /*IsReinject=*/true);
1882 Tok = TypedefToken;
1883 if (!Result)
1884 Diag(Loc: Tok.getLocation(), DiagID: diag::warn_expected_qualified_after_typename);
1885 return Result;
1886 }
1887
1888 // Parse a C++ typename-specifier, e.g., "typename T::type".
1889 //
1890 // typename-specifier:
1891 // 'typename' '::' [opt] nested-name-specifier identifier
1892 // 'typename' '::' [opt] nested-name-specifier template [opt]
1893 // simple-template-id
1894 SourceLocation TypenameLoc = ConsumeToken();
1895 CXXScopeSpec SS;
1896 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1897 /*ObjectHasErrors=*/false,
1898 /*EnteringContext=*/false, MayBePseudoDestructor: nullptr,
1899 /*IsTypename*/ true))
1900 return true;
1901 if (SS.isEmpty()) {
1902 if (Tok.is(K: tok::identifier) || Tok.is(K: tok::annot_template_id) ||
1903 Tok.is(K: tok::annot_decltype)) {
1904 // Attempt to recover by skipping the invalid 'typename'
1905 if (Tok.is(K: tok::annot_decltype) ||
1906 (!TryAnnotateTypeOrScopeToken(AllowImplicitTypename) &&
1907 Tok.isAnnotation())) {
1908 unsigned DiagID = diag::err_expected_qualified_after_typename;
1909 // MS compatibility: MSVC permits using known types with typename.
1910 // e.g. "typedef typename T* pointer_type"
1911 if (getLangOpts().MicrosoftExt)
1912 DiagID = diag::warn_expected_qualified_after_typename;
1913 Diag(Loc: Tok.getLocation(), DiagID);
1914 return false;
1915 }
1916 }
1917 if (Tok.isEditorPlaceholder())
1918 return true;
1919
1920 Diag(Loc: Tok.getLocation(), DiagID: diag::err_expected_qualified_after_typename);
1921 return true;
1922 }
1923
1924 bool TemplateKWPresent = false;
1925 if (Tok.is(K: tok::kw_template)) {
1926 ConsumeToken();
1927 TemplateKWPresent = true;
1928 }
1929
1930 TypeResult Ty;
1931 if (Tok.is(K: tok::identifier)) {
1932 if (TemplateKWPresent && NextToken().isNot(K: tok::less)) {
1933 Diag(Loc: Tok.getLocation(),
1934 DiagID: diag::missing_template_arg_list_after_template_kw);
1935 return true;
1936 }
1937 Ty = Actions.ActOnTypenameType(S: getCurScope(), TypenameLoc, SS,
1938 II: *Tok.getIdentifierInfo(),
1939 IdLoc: Tok.getLocation());
1940 } else if (Tok.is(K: tok::annot_template_id)) {
1941 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(tok: Tok);
1942 if (!TemplateId->mightBeType()) {
1943 Diag(Tok, DiagID: diag::err_typename_refers_to_non_type_template)
1944 << Tok.getAnnotationRange();
1945 return true;
1946 }
1947
1948 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1949 TemplateId->NumArgs);
1950
1951 Ty = TemplateId->isInvalid()
1952 ? TypeError()
1953 : Actions.ActOnTypenameType(
1954 S: getCurScope(), TypenameLoc, SS, TemplateLoc: TemplateId->TemplateKWLoc,
1955 TemplateName: TemplateId->Template, TemplateII: TemplateId->Name,
1956 TemplateIILoc: TemplateId->TemplateNameLoc, LAngleLoc: TemplateId->LAngleLoc,
1957 TemplateArgs: TemplateArgsPtr, RAngleLoc: TemplateId->RAngleLoc);
1958 } else {
1959 Diag(Tok, DiagID: diag::err_expected_type_name_after_typename)
1960 << SS.getRange();
1961 return true;
1962 }
1963
1964 SourceLocation EndLoc = Tok.getLastLoc();
1965 Tok.setKind(tok::annot_typename);
1966 setTypeAnnotation(Tok, T: Ty);
1967 Tok.setAnnotationEndLoc(EndLoc);
1968 Tok.setLocation(TypenameLoc);
1969 PP.AnnotateCachedTokens(Tok);
1970 return false;
1971 }
1972
1973 // Remembers whether the token was originally a scope annotation.
1974 bool WasScopeAnnotation = Tok.is(K: tok::annot_cxxscope);
1975
1976 CXXScopeSpec SS;
1977 if (getLangOpts().CPlusPlus)
1978 if (ParseOptionalCXXScopeSpecifier(
1979 SS, /*ObjectType=*/nullptr,
1980 /*ObjectHasErrors=*/false,
1981 /*EnteringContext=*/false,
1982 /*IsAddressOfOperand=*/IsAddressOfOperand))
1983 return true;
1984
1985 return TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, IsNewScope: !WasScopeAnnotation,
1986 AllowImplicitTypename);
1987}
1988
1989bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(
1990 CXXScopeSpec &SS, bool IsNewScope,
1991 ImplicitTypenameContext AllowImplicitTypename) {
1992 if (Tok.is(K: tok::identifier)) {
1993 // Determine whether the identifier is a type name.
1994 if (ParsedType Ty = Actions.getTypeName(
1995 II: *Tok.getIdentifierInfo(), NameLoc: Tok.getLocation(), S: getCurScope(), SS: &SS,
1996 isClassName: false, HasTrailingDot: NextToken().is(K: tok::period), ObjectType: nullptr,
1997 /*IsCtorOrDtorName=*/false,
1998 /*NonTrivialTypeSourceInfo=*/WantNontrivialTypeSourceInfo: true,
1999 /*IsClassTemplateDeductionContext=*/true, AllowImplicitTypename)) {
2000 SourceLocation BeginLoc = Tok.getLocation();
2001 if (SS.isNotEmpty()) // it was a C++ qualified type name.
2002 BeginLoc = SS.getBeginLoc();
2003
2004 QualType T = Actions.GetTypeFromParser(Ty);
2005
2006 /// An Objective-C object type followed by '<' is a specialization of
2007 /// a parameterized class type or a protocol-qualified type.
2008 if (getLangOpts().ObjC && NextToken().is(K: tok::less) &&
2009 (T->isObjCObjectType() || T->isObjCObjectPointerType())) {
2010 // Consume the name.
2011 SourceLocation IdentifierLoc = ConsumeToken();
2012 SourceLocation NewEndLoc;
2013 TypeResult NewType
2014 = parseObjCTypeArgsAndProtocolQualifiers(loc: IdentifierLoc, type: Ty,
2015 /*consumeLastToken=*/false,
2016 endLoc&: NewEndLoc);
2017 if (NewType.isUsable())
2018 Ty = NewType.get();
2019 else if (Tok.is(K: tok::eof)) // Nothing to do here, bail out...
2020 return false;
2021 }
2022
2023 // This is a typename. Replace the current token in-place with an
2024 // annotation type token.
2025 Tok.setKind(tok::annot_typename);
2026 setTypeAnnotation(Tok, T: Ty);
2027 Tok.setAnnotationEndLoc(Tok.getLocation());
2028 Tok.setLocation(BeginLoc);
2029
2030 // In case the tokens were cached, have Preprocessor replace
2031 // them with the annotation token.
2032 PP.AnnotateCachedTokens(Tok);
2033 return false;
2034 }
2035
2036 if (!getLangOpts().CPlusPlus) {
2037 // If we're in C, the only place we can have :: tokens is C23
2038 // attribute which is parsed elsewhere. If the identifier is not a type,
2039 // then it can't be scope either, just early exit.
2040 return false;
2041 }
2042
2043 // If this is a template-id, annotate with a template-id or type token.
2044 // FIXME: This appears to be dead code. We already have formed template-id
2045 // tokens when parsing the scope specifier; this can never form a new one.
2046 if (NextToken().is(K: tok::less)) {
2047 TemplateTy Template;
2048 UnqualifiedId TemplateName;
2049 TemplateName.setIdentifier(Id: Tok.getIdentifierInfo(), IdLoc: Tok.getLocation());
2050 bool MemberOfUnknownSpecialization;
2051 if (TemplateNameKind TNK = Actions.isTemplateName(
2052 S: getCurScope(), SS,
2053 /*hasTemplateKeyword=*/false, Name: TemplateName,
2054 /*ObjectType=*/nullptr, /*EnteringContext*/false, Template,
2055 MemberOfUnknownSpecialization)) {
2056 // Only annotate an undeclared template name as a template-id if the
2057 // following tokens have the form of a template argument list.
2058 if (TNK != TNK_Undeclared_template ||
2059 isTemplateArgumentList(TokensToSkip: 1) != TPResult::False) {
2060 // Consume the identifier.
2061 ConsumeToken();
2062 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc: SourceLocation(),
2063 TemplateName)) {
2064 // If an unrecoverable error occurred, we need to return true here,
2065 // because the token stream is in a damaged state. We may not
2066 // return a valid identifier.
2067 return true;
2068 }
2069 }
2070 }
2071 }
2072
2073 // The current token, which is either an identifier or a
2074 // template-id, is not part of the annotation. Fall through to
2075 // push that token back into the stream and complete the C++ scope
2076 // specifier annotation.
2077 }
2078
2079 if (Tok.is(K: tok::annot_template_id)) {
2080 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(tok: Tok);
2081 if (TemplateId->Kind == TNK_Type_template) {
2082 // A template-id that refers to a type was parsed into a
2083 // template-id annotation in a context where we weren't allowed
2084 // to produce a type annotation token. Update the template-id
2085 // annotation token to a type annotation token now.
2086 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
2087 return false;
2088 }
2089 }
2090
2091 if (SS.isEmpty()) {
2092 if (getLangOpts().ObjC && !getLangOpts().CPlusPlus &&
2093 Tok.is(K: tok::coloncolon)) {
2094 // ObjectiveC does not allow :: as as a scope token.
2095 Diag(Loc: ConsumeToken(), DiagID: diag::err_expected_type);
2096 return true;
2097 }
2098 return false;
2099 }
2100
2101 // A C++ scope specifier that isn't followed by a typename.
2102 AnnotateScopeToken(SS, IsNewAnnotation: IsNewScope);
2103 return false;
2104}
2105
2106bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
2107 assert(getLangOpts().CPlusPlus &&
2108 "Call sites of this function should be guarded by checking for C++");
2109 assert(MightBeCXXScopeToken() && "Cannot be a type or scope token!");
2110
2111 CXXScopeSpec SS;
2112 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
2113 /*ObjectHasErrors=*/false,
2114 EnteringContext))
2115 return true;
2116 if (SS.isEmpty())
2117 return false;
2118
2119 AnnotateScopeToken(SS, IsNewAnnotation: true);
2120 return false;
2121}
2122
2123bool Parser::isTokenEqualOrEqualTypo() {
2124 tok::TokenKind Kind = Tok.getKind();
2125 switch (Kind) {
2126 default:
2127 return false;
2128 case tok::ampequal: // &=
2129 case tok::starequal: // *=
2130 case tok::plusequal: // +=
2131 case tok::minusequal: // -=
2132 case tok::exclaimequal: // !=
2133 case tok::slashequal: // /=
2134 case tok::percentequal: // %=
2135 case tok::lessequal: // <=
2136 case tok::lesslessequal: // <<=
2137 case tok::greaterequal: // >=
2138 case tok::greatergreaterequal: // >>=
2139 case tok::caretequal: // ^=
2140 case tok::pipeequal: // |=
2141 case tok::equalequal: // ==
2142 Diag(Tok, DiagID: diag::err_invalid_token_after_declarator_suggest_equal)
2143 << Kind
2144 << FixItHint::CreateReplacement(RemoveRange: SourceRange(Tok.getLocation()), Code: "=");
2145 [[fallthrough]];
2146 case tok::equal:
2147 return true;
2148 }
2149}
2150
2151SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
2152 assert(Tok.is(tok::code_completion));
2153 PrevTokLocation = Tok.getLocation();
2154
2155 for (Scope *S = getCurScope(); S; S = S->getParent()) {
2156 if (S->isFunctionScope()) {
2157 cutOffParsing();
2158 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2159 S: getCurScope(), CompletionContext: SemaCodeCompletion::PCC_RecoveryInFunction);
2160 return PrevTokLocation;
2161 }
2162
2163 if (S->isClassScope()) {
2164 cutOffParsing();
2165 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2166 S: getCurScope(), CompletionContext: SemaCodeCompletion::PCC_Class);
2167 return PrevTokLocation;
2168 }
2169 }
2170
2171 cutOffParsing();
2172 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2173 S: getCurScope(), CompletionContext: SemaCodeCompletion::PCC_Namespace);
2174 return PrevTokLocation;
2175}
2176
2177// Code-completion pass-through functions
2178
2179void Parser::CodeCompleteDirective(bool InConditional) {
2180 Actions.CodeCompletion().CodeCompletePreprocessorDirective(InConditional);
2181}
2182
2183void Parser::CodeCompleteInConditionalExclusion() {
2184 Actions.CodeCompletion().CodeCompleteInPreprocessorConditionalExclusion(
2185 S: getCurScope());
2186}
2187
2188void Parser::CodeCompleteMacroName(bool IsDefinition) {
2189 Actions.CodeCompletion().CodeCompletePreprocessorMacroName(IsDefinition);
2190}
2191
2192void Parser::CodeCompletePreprocessorExpression() {
2193 Actions.CodeCompletion().CodeCompletePreprocessorExpression();
2194}
2195
2196void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
2197 MacroInfo *MacroInfo,
2198 unsigned ArgumentIndex) {
2199 Actions.CodeCompletion().CodeCompletePreprocessorMacroArgument(
2200 S: getCurScope(), Macro, MacroInfo, Argument: ArgumentIndex);
2201}
2202
2203void Parser::CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) {
2204 Actions.CodeCompletion().CodeCompleteIncludedFile(Dir, IsAngled);
2205}
2206
2207void Parser::CodeCompleteNaturalLanguage() {
2208 Actions.CodeCompletion().CodeCompleteNaturalLanguage();
2209}
2210
2211void Parser::CodeCompleteModuleImport(SourceLocation ImportLoc,
2212 ModuleIdPath Path) {
2213 Actions.CodeCompletion().CodeCompleteModuleImport(ImportLoc, Path);
2214}
2215
2216bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
2217 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
2218 "Expected '__if_exists' or '__if_not_exists'");
2219 Result.IsIfExists = Tok.is(K: tok::kw___if_exists);
2220 Result.KeywordLoc = ConsumeToken();
2221
2222 BalancedDelimiterTracker T(*this, tok::l_paren);
2223 if (T.consumeOpen()) {
2224 Diag(Tok, DiagID: diag::err_expected_lparen_after)
2225 << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
2226 return true;
2227 }
2228
2229 // Parse nested-name-specifier.
2230 if (getLangOpts().CPlusPlus)
2231 ParseOptionalCXXScopeSpecifier(SS&: Result.SS, /*ObjectType=*/nullptr,
2232 /*ObjectHasErrors=*/false,
2233 /*EnteringContext=*/false);
2234
2235 // Check nested-name specifier.
2236 if (Result.SS.isInvalid()) {
2237 T.skipToEnd();
2238 return true;
2239 }
2240
2241 // Parse the unqualified-id.
2242 SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
2243 if (ParseUnqualifiedId(SS&: Result.SS, /*ObjectType=*/nullptr,
2244 /*ObjectHadErrors=*/false, /*EnteringContext*/ false,
2245 /*AllowDestructorName*/ true,
2246 /*AllowConstructorName*/ true,
2247 /*AllowDeductionGuide*/ false, TemplateKWLoc: &TemplateKWLoc,
2248 Result&: Result.Name)) {
2249 T.skipToEnd();
2250 return true;
2251 }
2252
2253 if (T.consumeClose())
2254 return true;
2255
2256 // Check if the symbol exists.
2257 switch (Actions.CheckMicrosoftIfExistsSymbol(S: getCurScope(), KeywordLoc: Result.KeywordLoc,
2258 IsIfExists: Result.IsIfExists, SS&: Result.SS,
2259 Name&: Result.Name)) {
2260 case IfExistsResult::Exists:
2261 Result.Behavior =
2262 Result.IsIfExists ? IfExistsBehavior::Parse : IfExistsBehavior::Skip;
2263 break;
2264
2265 case IfExistsResult::DoesNotExist:
2266 Result.Behavior =
2267 !Result.IsIfExists ? IfExistsBehavior::Parse : IfExistsBehavior::Skip;
2268 break;
2269
2270 case IfExistsResult::Dependent:
2271 Result.Behavior = IfExistsBehavior::Dependent;
2272 break;
2273
2274 case IfExistsResult::Error:
2275 return true;
2276 }
2277
2278 return false;
2279}
2280
2281void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
2282 IfExistsCondition Result;
2283 if (ParseMicrosoftIfExistsCondition(Result))
2284 return;
2285
2286 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2287 if (Braces.consumeOpen()) {
2288 Diag(Tok, DiagID: diag::err_expected) << tok::l_brace;
2289 return;
2290 }
2291
2292 switch (Result.Behavior) {
2293 case IfExistsBehavior::Parse:
2294 // Parse declarations below.
2295 break;
2296
2297 case IfExistsBehavior::Dependent:
2298 llvm_unreachable("Cannot have a dependent external declaration");
2299
2300 case IfExistsBehavior::Skip:
2301 Braces.skipToEnd();
2302 return;
2303 }
2304
2305 // Parse the declarations.
2306 // FIXME: Support module import within __if_exists?
2307 while (Tok.isNot(K: tok::r_brace) && !isEofOrEom()) {
2308 ParsedAttributes Attrs(AttrFactory);
2309 MaybeParseCXX11Attributes(Attrs);
2310 ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
2311 DeclGroupPtrTy Result = ParseExternalDeclaration(Attrs, DeclSpecAttrs&: EmptyDeclSpecAttrs);
2312 if (Result && !getCurScope()->getParent())
2313 Actions.getASTConsumer().HandleTopLevelDecl(D: Result.get());
2314 }
2315 Braces.consumeClose();
2316}
2317
2318Parser::DeclGroupPtrTy
2319Parser::ParseModuleDecl(Sema::ModuleImportState &ImportState) {
2320 Token Introducer = Tok;
2321 SourceLocation StartLoc = Introducer.getLocation();
2322
2323 Sema::ModuleDeclKind MDK = TryConsumeToken(Expected: tok::kw_export)
2324 ? Sema::ModuleDeclKind::Interface
2325 : Sema::ModuleDeclKind::Implementation;
2326
2327 assert(Tok.is(tok::kw_module) && "not a module declaration");
2328
2329 SourceLocation ModuleLoc = ConsumeToken();
2330
2331 // Attributes appear after the module name, not before.
2332 // FIXME: Suggest moving the attributes later with a fixit.
2333 DiagnoseAndSkipCXX11Attributes();
2334
2335 // Parse a global-module-fragment, if present.
2336 if (getLangOpts().CPlusPlusModules && Tok.is(K: tok::semi)) {
2337 SourceLocation SemiLoc = ConsumeToken();
2338 if (ImportState != Sema::ModuleImportState::FirstDecl ||
2339 Introducer.hasSeenNoTrivialPPDirective()) {
2340 Diag(Loc: StartLoc, DiagID: diag::err_global_module_introducer_not_at_start)
2341 << SourceRange(StartLoc, SemiLoc);
2342 return nullptr;
2343 }
2344 if (MDK == Sema::ModuleDeclKind::Interface) {
2345 Diag(Loc: StartLoc, DiagID: diag::err_module_fragment_exported)
2346 << /*global*/0 << FixItHint::CreateRemoval(RemoveRange: StartLoc);
2347 }
2348 ImportState = Sema::ModuleImportState::GlobalFragment;
2349 return Actions.ActOnGlobalModuleFragmentDecl(ModuleLoc);
2350 }
2351
2352 // Parse a private-module-fragment, if present.
2353 if (getLangOpts().CPlusPlusModules && Tok.is(K: tok::colon) &&
2354 NextToken().is(K: tok::kw_private)) {
2355 if (MDK == Sema::ModuleDeclKind::Interface) {
2356 Diag(Loc: StartLoc, DiagID: diag::err_module_fragment_exported)
2357 << /*private*/1 << FixItHint::CreateRemoval(RemoveRange: StartLoc);
2358 }
2359 ConsumeToken();
2360 SourceLocation PrivateLoc = ConsumeToken();
2361 DiagnoseAndSkipCXX11Attributes();
2362 ExpectAndConsumeSemi(DiagID: diag::err_private_module_fragment_expected_semi);
2363 ImportState = ImportState == Sema::ModuleImportState::ImportAllowed
2364 ? Sema::ModuleImportState::PrivateFragmentImportAllowed
2365 : Sema::ModuleImportState::PrivateFragmentImportFinished;
2366 return Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc);
2367 }
2368
2369 SmallVector<IdentifierLoc, 2> Path;
2370 if (ParseModuleName(UseLoc: ModuleLoc, Path, /*IsImport*/ false))
2371 return nullptr;
2372
2373 // Parse the optional module-partition.
2374 SmallVector<IdentifierLoc, 2> Partition;
2375 if (Tok.is(K: tok::colon)) {
2376 SourceLocation ColonLoc = ConsumeToken();
2377 if (!getLangOpts().CPlusPlusModules)
2378 Diag(Loc: ColonLoc, DiagID: diag::err_unsupported_module_partition)
2379 << SourceRange(ColonLoc, Partition.back().getLoc());
2380 // Recover by ignoring the partition name.
2381 else if (ParseModuleName(UseLoc: ModuleLoc, Path&: Partition, /*IsImport*/ false))
2382 return nullptr;
2383 }
2384
2385 // This should already diagnosed in phase 4, just skip unil semicolon.
2386 if (!Tok.isOneOf(Ks: tok::semi, Ks: tok::l_square))
2387 SkipUntil(T: tok::semi, Flags: SkipUntilFlags::StopBeforeMatch);
2388
2389 // We don't support any module attributes yet; just parse them and diagnose.
2390 ParsedAttributes Attrs(AttrFactory);
2391 MaybeParseCXX11Attributes(Attrs);
2392 ProhibitCXX11Attributes(Attrs, AttrDiagID: diag::err_attribute_not_module_attr,
2393 KeywordDiagId: diag::err_keyword_not_module_attr,
2394 /*DiagnoseEmptyAttrs=*/false,
2395 /*WarnOnUnknownAttrs=*/true);
2396
2397 if (ExpectAndConsumeSemi(DiagID: diag::err_expected_semi_after_module_or_import,
2398 TokenUsed: tok::getKeywordSpelling(Kind: tok::kw_module)))
2399 SkipUntil(T: tok::semi);
2400
2401 return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, Partition,
2402 ImportState,
2403 SeenNoTrivialPPDirective: Introducer.hasSeenNoTrivialPPDirective());
2404}
2405
2406Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
2407 Sema::ModuleImportState &ImportState) {
2408 SourceLocation StartLoc = AtLoc.isInvalid() ? Tok.getLocation() : AtLoc;
2409
2410 SourceLocation ExportLoc;
2411 TryConsumeToken(Expected: tok::kw_export, Loc&: ExportLoc);
2412
2413 assert((AtLoc.isInvalid() ? Tok.is(tok::kw_import)
2414 : Tok.isObjCAtKeyword(tok::objc_import)) &&
2415 "Improper start to module import");
2416 bool IsObjCAtImport = Tok.isObjCAtKeyword(objcKey: tok::objc_import);
2417 SourceLocation ImportLoc = ConsumeToken();
2418
2419 // For C++20 modules, we can have "name" or ":Partition name" as valid input.
2420 SmallVector<IdentifierLoc, 2> Path;
2421 bool IsPartition = false;
2422 Module *HeaderUnit = nullptr;
2423 if (Tok.is(K: tok::header_name)) {
2424 // This is a header import that the preprocessor decided we should skip
2425 // because it was malformed in some way. Parse and ignore it; it's already
2426 // been diagnosed.
2427 ConsumeToken();
2428 } else if (Tok.is(K: tok::annot_header_unit)) {
2429 // This is a header import that the preprocessor mapped to a module import.
2430 HeaderUnit = reinterpret_cast<Module *>(Tok.getAnnotationValue());
2431 ConsumeAnnotationToken();
2432 } else if (Tok.is(K: tok::colon)) {
2433 SourceLocation ColonLoc = ConsumeToken();
2434 if (!getLangOpts().CPlusPlusModules)
2435 Diag(Loc: ColonLoc, DiagID: diag::err_unsupported_module_partition)
2436 << SourceRange(ColonLoc, Path.back().getLoc());
2437 // Recover by leaving partition empty.
2438 else if (ParseModuleName(UseLoc: ColonLoc, Path, /*IsImport=*/true))
2439 return nullptr;
2440 else
2441 IsPartition = true;
2442 } else {
2443 if (ParseModuleName(UseLoc: ImportLoc, Path, /*IsImport=*/true))
2444 return nullptr;
2445 }
2446
2447 ParsedAttributes Attrs(AttrFactory);
2448 MaybeParseCXX11Attributes(Attrs);
2449 // We don't support any module import attributes yet.
2450 ProhibitCXX11Attributes(Attrs, AttrDiagID: diag::err_attribute_not_import_attr,
2451 KeywordDiagId: diag::err_keyword_not_import_attr,
2452 /*DiagnoseEmptyAttrs=*/false,
2453 /*WarnOnUnknownAttrs=*/true);
2454
2455 // Clang modules can inject token streams while loading, so a fatal loader
2456 // failure must stop parsing. C++20 named module imports are ordinary
2457 // declarations, and a prior failed import should not hide later diagnostics.
2458 bool IsCXX20NamedModuleImport =
2459 getLangOpts().CPlusPlusModules && !IsObjCAtImport && !Path.empty();
2460
2461 if (PP.hadModuleLoaderFatalFailure() && !IsCXX20NamedModuleImport) {
2462 // With a fatal failure in the module loader, we abort parsing.
2463 cutOffParsing();
2464 return nullptr;
2465 }
2466
2467 // Diagnose mis-imports.
2468 bool SeenError = true;
2469 switch (ImportState) {
2470 case Sema::ModuleImportState::ImportAllowed:
2471 SeenError = false;
2472 break;
2473 case Sema::ModuleImportState::FirstDecl:
2474 // If we found an import decl as the first declaration, we must be not in
2475 // a C++20 module unit or we are in an invalid state.
2476 ImportState = Sema::ModuleImportState::NotACXX20Module;
2477 [[fallthrough]];
2478 case Sema::ModuleImportState::NotACXX20Module:
2479 // We can only import a partition within a module purview.
2480 if (IsPartition)
2481 Diag(Loc: ImportLoc, DiagID: diag::err_partition_import_outside_module);
2482 else
2483 SeenError = false;
2484 break;
2485 case Sema::ModuleImportState::GlobalFragment:
2486 case Sema::ModuleImportState::PrivateFragmentImportAllowed:
2487 // We can only have pre-processor directives in the global module fragment
2488 // which allows pp-import, but not of a partition (since the global module
2489 // does not have partitions).
2490 // We cannot import a partition into a private module fragment, since
2491 // [module.private.frag]/1 disallows private module fragments in a multi-
2492 // TU module.
2493 if (IsPartition || (HeaderUnit && HeaderUnit->Kind !=
2494 Module::ModuleKind::ModuleHeaderUnit))
2495 Diag(Loc: ImportLoc, DiagID: diag::err_import_in_wrong_fragment)
2496 << IsPartition
2497 << (ImportState == Sema::ModuleImportState::GlobalFragment ? 0 : 1);
2498 else
2499 SeenError = false;
2500 break;
2501 case Sema::ModuleImportState::ImportFinished:
2502 case Sema::ModuleImportState::PrivateFragmentImportFinished:
2503 if (getLangOpts().CPlusPlusModules)
2504 Diag(Loc: ImportLoc, DiagID: diag::err_import_not_allowed_here);
2505 else
2506 SeenError = false;
2507 break;
2508 }
2509
2510 bool LexedSemi = false;
2511 if (getLangOpts().CPlusPlusModules)
2512 LexedSemi =
2513 !ExpectAndConsumeSemi(DiagID: diag::err_expected_semi_after_module_or_import,
2514 TokenUsed: tok::getKeywordSpelling(Kind: tok::kw_import));
2515 else
2516 LexedSemi = !ExpectAndConsumeSemi(DiagID: diag::err_module_expected_semi);
2517
2518 if (!LexedSemi)
2519 SkipUntil(T: tok::semi);
2520
2521 if (SeenError)
2522 return nullptr;
2523
2524 DeclResult Import;
2525 if (HeaderUnit)
2526 Import =
2527 Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, M: HeaderUnit);
2528 else if (!Path.empty())
2529 Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path,
2530 IsPartition);
2531 if (Import.isInvalid())
2532 return nullptr;
2533
2534 // Using '@import' in framework headers requires modules to be enabled so that
2535 // the header is parseable. Emit a warning to make the user aware.
2536 if (IsObjCAtImport && AtLoc.isValid()) {
2537 auto &SrcMgr = PP.getSourceManager();
2538 auto FE = SrcMgr.getFileEntryRefForID(FID: SrcMgr.getFileID(SpellingLoc: AtLoc));
2539 if (FE && llvm::sys::path::parent_path(path: FE->getDir().getName())
2540 .ends_with(Suffix: ".framework"))
2541 Diags.Report(Loc: AtLoc, DiagID: diag::warn_atimport_in_framework_header);
2542 }
2543
2544 return Import.get();
2545}
2546
2547bool Parser::ParseModuleName(SourceLocation UseLoc,
2548 SmallVectorImpl<IdentifierLoc> &Path,
2549 bool IsImport) {
2550 if (Tok.isNot(K: tok::annot_module_name)) {
2551 SkipUntil(T: tok::semi);
2552 return true;
2553 }
2554 ModuleNameLoc *NameLoc =
2555 static_cast<ModuleNameLoc *>(Tok.getAnnotationValue());
2556 Path.assign(in_start: NameLoc->getModuleIdPath().begin(),
2557 in_end: NameLoc->getModuleIdPath().end());
2558 ConsumeAnnotationToken();
2559 return false;
2560}
2561
2562bool Parser::parseMisplacedModuleImport() {
2563 while (true) {
2564 switch (Tok.getKind()) {
2565 case tok::annot_module_end:
2566 // If we recovered from a misplaced module begin, we expect to hit a
2567 // misplaced module end too. Stay in the current context when this
2568 // happens.
2569 if (MisplacedModuleBeginCount) {
2570 --MisplacedModuleBeginCount;
2571 Actions.ActOnAnnotModuleEnd(
2572 DirectiveLoc: Tok.getLocation(),
2573 Mod: reinterpret_cast<Module *>(Tok.getAnnotationValue()));
2574 ConsumeAnnotationToken();
2575 continue;
2576 }
2577 // Inform caller that recovery failed, the error must be handled at upper
2578 // level. This will generate the desired "missing '}' at end of module"
2579 // diagnostics on the way out.
2580 return true;
2581 case tok::annot_module_begin:
2582 // Recover by entering the module (Sema will diagnose).
2583 Actions.ActOnAnnotModuleBegin(
2584 DirectiveLoc: Tok.getLocation(),
2585 Mod: reinterpret_cast<Module *>(Tok.getAnnotationValue()));
2586 ConsumeAnnotationToken();
2587 ++MisplacedModuleBeginCount;
2588 continue;
2589 case tok::annot_module_include:
2590 // Module import found where it should not be, for instance, inside a
2591 // namespace. Recover by importing the module.
2592 Actions.ActOnAnnotModuleInclude(
2593 DirectiveLoc: Tok.getLocation(),
2594 Mod: reinterpret_cast<Module *>(Tok.getAnnotationValue()));
2595 ConsumeAnnotationToken();
2596 // If there is another module import, process it.
2597 continue;
2598 default:
2599 return false;
2600 }
2601 }
2602 return false;
2603}
2604
2605void Parser::diagnoseUseOfC11Keyword(const Token &Tok) {
2606 // Warn that this is a C11 extension if in an older mode or if in C++.
2607 // Otherwise, warn that it is incompatible with standards before C11 if in
2608 // C11 or later.
2609 Diag(Tok, DiagID: getLangOpts().C11 ? diag::warn_c11_compat_keyword
2610 : diag::ext_c11_feature)
2611 << Tok.getName();
2612}
2613
2614bool BalancedDelimiterTracker::diagnoseOverflow() {
2615 P.Diag(Tok: P.Tok, DiagID: diag::err_bracket_depth_exceeded)
2616 << P.getLangOpts().BracketDepth;
2617 P.Diag(Tok: P.Tok, DiagID: diag::note_bracket_depth);
2618 P.cutOffParsing();
2619 return true;
2620}
2621
2622bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
2623 const char *Msg,
2624 tok::TokenKind SkipToTok) {
2625 LOpen = P.Tok.getLocation();
2626 if (P.ExpectAndConsume(ExpectedTok: Kind, DiagID, Msg)) {
2627 if (SkipToTok != tok::unknown)
2628 P.SkipUntil(T: SkipToTok, Flags: Parser::StopAtSemi);
2629 return true;
2630 }
2631
2632 if (getDepth() < P.getLangOpts().BracketDepth)
2633 return false;
2634
2635 return diagnoseOverflow();
2636}
2637
2638bool BalancedDelimiterTracker::diagnoseMissingClose() {
2639 assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
2640
2641 if (P.Tok.is(K: tok::annot_module_end))
2642 P.Diag(Tok: P.Tok, DiagID: diag::err_missing_before_module_end) << Close;
2643 else
2644 P.Diag(Tok: P.Tok, DiagID: diag::err_expected) << Close;
2645 P.Diag(Loc: LOpen, DiagID: diag::note_matching) << Kind;
2646
2647 // If we're not already at some kind of closing bracket, skip to our closing
2648 // token.
2649 if (P.Tok.isNot(K: tok::r_paren) && P.Tok.isNot(K: tok::r_brace) &&
2650 P.Tok.isNot(K: tok::r_square) &&
2651 P.SkipUntil(T1: Close, T2: FinalToken,
2652 Flags: Parser::StopAtSemi | Parser::StopBeforeMatch) &&
2653 P.Tok.is(K: Close))
2654 LClose = P.ConsumeAnyToken();
2655 return true;
2656}
2657
2658void BalancedDelimiterTracker::skipToEnd() {
2659 P.SkipUntil(T: Close, Flags: Parser::StopBeforeMatch);
2660 consumeClose();
2661}
2662