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