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