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