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