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