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