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