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