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