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