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