clang 20.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 Result = nullptr;
633 switch (Tok.getKind()) {
634 case tok::annot_pragma_unused:
635 HandlePragmaUnused();
636 return false;
637
638 case tok::kw_export:
639 switch (NextToken().getKind()) {
640 case tok::kw_module:
641 goto module_decl;
642
643 // Note: no need to handle kw_import here. We only form kw_import under
644 // the Standard C++ Modules, and in that case 'export import' is parsed as
645 // an export-declaration containing an import-declaration.
646
647 // Recognize context-sensitive C++20 'export module' and 'export import'
648 // declarations.
649 case tok::identifier: {
651 if ((II == Ident_module || II == Ident_import) &&
652 GetLookAheadToken(2).isNot(tok::coloncolon)) {
653 if (II == Ident_module)
654 goto module_decl;
655 else
656 goto import_decl;
657 }
658 break;
659 }
660
661 default:
662 break;
663 }
664 break;
665
666 case tok::kw_module:
667 module_decl:
668 Result = ParseModuleDecl(ImportState);
669 return false;
670
671 case tok::kw_import:
672 import_decl: {
673 Decl *ImportDecl = ParseModuleImport(SourceLocation(), ImportState);
675 return false;
676 }
677
678 case tok::annot_module_include: {
679 auto Loc = Tok.getLocation();
680 Module *Mod = reinterpret_cast<Module *>(Tok.getAnnotationValue());
681 // FIXME: We need a better way to disambiguate C++ clang modules and
682 // standard C++ modules.
683 if (!getLangOpts().CPlusPlusModules || !Mod->isHeaderUnit())
684 Actions.ActOnAnnotModuleInclude(Loc, Mod);
685 else {
686 DeclResult Import =
687 Actions.ActOnModuleImport(Loc, SourceLocation(), Loc, Mod);
688 Decl *ImportDecl = Import.isInvalid() ? nullptr : Import.get();
690 }
691 ConsumeAnnotationToken();
692 return false;
693 }
694
695 case tok::annot_module_begin:
696 Actions.ActOnAnnotModuleBegin(
697 Tok.getLocation(),
698 reinterpret_cast<Module *>(Tok.getAnnotationValue()));
699 ConsumeAnnotationToken();
701 return false;
702
703 case tok::annot_module_end:
704 Actions.ActOnAnnotModuleEnd(
705 Tok.getLocation(),
706 reinterpret_cast<Module *>(Tok.getAnnotationValue()));
707 ConsumeAnnotationToken();
709 return false;
710
711 case tok::eof:
712 case tok::annot_repl_input_end:
713 // Check whether -fmax-tokens= was reached.
714 if (PP.getMaxTokens() != 0 && PP.getTokenCount() > PP.getMaxTokens()) {
715 PP.Diag(Tok.getLocation(), diag::warn_max_tokens_total)
716 << PP.getTokenCount() << PP.getMaxTokens();
717 SourceLocation OverrideLoc = PP.getMaxTokensOverrideLoc();
718 if (OverrideLoc.isValid()) {
719 PP.Diag(OverrideLoc, diag::note_max_tokens_total_override);
720 }
721 }
722
723 // Late template parsing can begin.
724 Actions.SetLateTemplateParser(LateTemplateParserCallback, nullptr, this);
726 //else don't tell Sema that we ended parsing: more input might come.
727 return true;
728
729 case tok::identifier:
730 // C++2a [basic.link]p3:
731 // A token sequence beginning with 'export[opt] module' or
732 // 'export[opt] import' and not immediately followed by '::'
733 // is never interpreted as the declaration of a top-level-declaration.
734 if ((Tok.getIdentifierInfo() == Ident_module ||
735 Tok.getIdentifierInfo() == Ident_import) &&
736 NextToken().isNot(tok::coloncolon)) {
737 if (Tok.getIdentifierInfo() == Ident_module)
738 goto module_decl;
739 else
740 goto import_decl;
741 }
742 break;
743
744 default:
745 break;
746 }
747
748 ParsedAttributes DeclAttrs(AttrFactory);
749 ParsedAttributes DeclSpecAttrs(AttrFactory);
750 // GNU attributes are applied to the declaration specification while the
751 // standard attributes are applied to the declaration. We parse the two
752 // attribute sets into different containters so we can apply them during
753 // the regular parsing process.
754 while (MaybeParseCXX11Attributes(DeclAttrs) ||
755 MaybeParseGNUAttributes(DeclSpecAttrs))
756 ;
757
758 Result = ParseExternalDeclaration(DeclAttrs, DeclSpecAttrs);
759 // An empty Result might mean a line with ';' or some parsing error, ignore
760 // it.
761 if (Result) {
762 if (ImportState == Sema::ModuleImportState::FirstDecl)
763 // First decl was not modular.
765 else if (ImportState == Sema::ModuleImportState::ImportAllowed)
766 // Non-imports disallow further imports.
768 else if (ImportState ==
770 // Non-imports disallow further imports.
772 }
773 return false;
774}
775
776/// ParseExternalDeclaration:
777///
778/// The `Attrs` that are passed in are C++11 attributes and appertain to the
779/// declaration.
780///
781/// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
782/// function-definition
783/// declaration
784/// [GNU] asm-definition
785/// [GNU] __extension__ external-declaration
786/// [OBJC] objc-class-definition
787/// [OBJC] objc-class-declaration
788/// [OBJC] objc-alias-declaration
789/// [OBJC] objc-protocol-definition
790/// [OBJC] objc-method-definition
791/// [OBJC] @end
792/// [C++] linkage-specification
793/// [GNU] asm-definition:
794/// simple-asm-expr ';'
795/// [C++11] empty-declaration
796/// [C++11] attribute-declaration
797///
798/// [C++11] empty-declaration:
799/// ';'
800///
801/// [C++0x/GNU] 'extern' 'template' declaration
802///
803/// [C++20] module-import-declaration
804///
806Parser::ParseExternalDeclaration(ParsedAttributes &Attrs,
807 ParsedAttributes &DeclSpecAttrs,
808 ParsingDeclSpec *DS) {
809 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
810 ParenBraceBracketBalancer BalancerRAIIObj(*this);
811
812 if (PP.isCodeCompletionReached()) {
813 cutOffParsing();
814 return nullptr;
815 }
816
817 Decl *SingleDecl = nullptr;
818 switch (Tok.getKind()) {
819 case tok::annot_pragma_vis:
820 HandlePragmaVisibility();
821 return nullptr;
822 case tok::annot_pragma_pack:
823 HandlePragmaPack();
824 return nullptr;
825 case tok::annot_pragma_msstruct:
826 HandlePragmaMSStruct();
827 return nullptr;
828 case tok::annot_pragma_align:
829 HandlePragmaAlign();
830 return nullptr;
831 case tok::annot_pragma_weak:
832 HandlePragmaWeak();
833 return nullptr;
834 case tok::annot_pragma_weakalias:
835 HandlePragmaWeakAlias();
836 return nullptr;
837 case tok::annot_pragma_redefine_extname:
838 HandlePragmaRedefineExtname();
839 return nullptr;
840 case tok::annot_pragma_fp_contract:
841 HandlePragmaFPContract();
842 return nullptr;
843 case tok::annot_pragma_fenv_access:
844 case tok::annot_pragma_fenv_access_ms:
845 HandlePragmaFEnvAccess();
846 return nullptr;
847 case tok::annot_pragma_fenv_round:
848 HandlePragmaFEnvRound();
849 return nullptr;
850 case tok::annot_pragma_cx_limited_range:
851 HandlePragmaCXLimitedRange();
852 return nullptr;
853 case tok::annot_pragma_float_control:
854 HandlePragmaFloatControl();
855 return nullptr;
856 case tok::annot_pragma_fp:
857 HandlePragmaFP();
858 break;
859 case tok::annot_pragma_opencl_extension:
860 HandlePragmaOpenCLExtension();
861 return nullptr;
862 case tok::annot_attr_openmp:
863 case tok::annot_pragma_openmp: {
865 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
866 }
867 case tok::annot_pragma_openacc:
869 case tok::annot_pragma_ms_pointers_to_members:
870 HandlePragmaMSPointersToMembers();
871 return nullptr;
872 case tok::annot_pragma_ms_vtordisp:
873 HandlePragmaMSVtorDisp();
874 return nullptr;
875 case tok::annot_pragma_ms_pragma:
876 HandlePragmaMSPragma();
877 return nullptr;
878 case tok::annot_pragma_dump:
879 HandlePragmaDump();
880 return nullptr;
881 case tok::annot_pragma_attribute:
882 HandlePragmaAttribute();
883 return nullptr;
884 case tok::semi:
885 // Either a C++11 empty-declaration or attribute-declaration.
886 SingleDecl =
887 Actions.ActOnEmptyDeclaration(getCurScope(), Attrs, Tok.getLocation());
888 ConsumeExtraSemi(OutsideFunction);
889 break;
890 case tok::r_brace:
891 Diag(Tok, diag::err_extraneous_closing_brace);
892 ConsumeBrace();
893 return nullptr;
894 case tok::eof:
895 Diag(Tok, diag::err_expected_external_declaration);
896 return nullptr;
897 case tok::kw___extension__: {
898 // __extension__ silences extension warnings in the subexpression.
899 ExtensionRAIIObject O(Diags); // Use RAII to do this.
900 ConsumeToken();
901 return ParseExternalDeclaration(Attrs, DeclSpecAttrs);
902 }
903 case tok::kw_asm: {
904 ProhibitAttributes(Attrs);
905
906 SourceLocation StartLoc = Tok.getLocation();
907 SourceLocation EndLoc;
908
909 ExprResult Result(ParseSimpleAsm(/*ForAsmLabel*/ false, &EndLoc));
910
911 // Check if GNU-style InlineAsm is disabled.
912 // Empty asm string is allowed because it will not introduce
913 // any assembly code.
914 if (!(getLangOpts().GNUAsm || Result.isInvalid())) {
915 const auto *SL = cast<StringLiteral>(Result.get());
916 if (!SL->getString().trim().empty())
917 Diag(StartLoc, diag::err_gnu_inline_asm_disabled);
918 }
919
920 ExpectAndConsume(tok::semi, diag::err_expected_after,
921 "top-level asm block");
922
923 if (Result.isInvalid())
924 return nullptr;
925 SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
926 break;
927 }
928 case tok::at:
929 return ParseObjCAtDirectives(Attrs, DeclSpecAttrs);
930 case tok::minus:
931 case tok::plus:
932 if (!getLangOpts().ObjC) {
933 Diag(Tok, diag::err_expected_external_declaration);
934 ConsumeToken();
935 return nullptr;
936 }
937 SingleDecl = ParseObjCMethodDefinition();
938 break;
939 case tok::code_completion:
940 cutOffParsing();
941 if (CurParsedObjCImpl) {
942 // Code-complete Objective-C methods even without leading '-'/'+' prefix.
944 getCurScope(),
945 /*IsInstanceMethod=*/std::nullopt,
946 /*ReturnType=*/nullptr);
947 }
948
950 if (CurParsedObjCImpl) {
952 } else if (PP.isIncrementalProcessingEnabled()) {
954 } else {
956 };
958 return nullptr;
959 case tok::kw_import: {
961 if (getLangOpts().CPlusPlusModules) {
962 llvm_unreachable("not expecting a c++20 import here");
963 ProhibitAttributes(Attrs);
964 }
965 SingleDecl = ParseModuleImport(SourceLocation(), IS);
966 } break;
967 case tok::kw_export:
968 if (getLangOpts().CPlusPlusModules || getLangOpts().HLSL) {
969 ProhibitAttributes(Attrs);
970 SingleDecl = ParseExportDeclaration();
971 break;
972 }
973 // This must be 'export template'. Parse it so we can diagnose our lack
974 // of support.
975 [[fallthrough]];
976 case tok::kw_using:
977 case tok::kw_namespace:
978 case tok::kw_typedef:
979 case tok::kw_template:
980 case tok::kw_static_assert:
981 case tok::kw__Static_assert:
982 // A function definition cannot start with any of these keywords.
983 {
984 SourceLocation DeclEnd;
985 return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
986 DeclSpecAttrs);
987 }
988
989 case tok::kw_cbuffer:
990 case tok::kw_tbuffer:
991 if (getLangOpts().HLSL) {
992 SourceLocation DeclEnd;
993 return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
994 DeclSpecAttrs);
995 }
996 goto dont_know;
997
998 case tok::kw_static:
999 // Parse (then ignore) 'static' prior to a template instantiation. This is
1000 // a GCC extension that we intentionally do not support.
1001 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
1002 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
1003 << 0;
1004 SourceLocation DeclEnd;
1005 return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
1006 DeclSpecAttrs);
1007 }
1008 goto dont_know;
1009
1010 case tok::kw_inline:
1011 if (getLangOpts().CPlusPlus) {
1012 tok::TokenKind NextKind = NextToken().getKind();
1013
1014 // Inline namespaces. Allowed as an extension even in C++03.
1015 if (NextKind == tok::kw_namespace) {
1016 SourceLocation DeclEnd;
1017 return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
1018 DeclSpecAttrs);
1019 }
1020
1021 // Parse (then ignore) 'inline' prior to a template instantiation. This is
1022 // a GCC extension that we intentionally do not support.
1023 if (NextKind == tok::kw_template) {
1024 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
1025 << 1;
1026 SourceLocation DeclEnd;
1027 return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
1028 DeclSpecAttrs);
1029 }
1030 }
1031 goto dont_know;
1032
1033 case tok::kw_extern:
1034 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
1035 // Extern templates
1036 SourceLocation ExternLoc = ConsumeToken();
1037 SourceLocation TemplateLoc = ConsumeToken();
1038 Diag(ExternLoc, getLangOpts().CPlusPlus11 ?
1039 diag::warn_cxx98_compat_extern_template :
1040 diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
1041 SourceLocation DeclEnd;
1042 return ParseExplicitInstantiation(DeclaratorContext::File, ExternLoc,
1043 TemplateLoc, DeclEnd, Attrs);
1044 }
1045 goto dont_know;
1046
1047 case tok::kw___if_exists:
1048 case tok::kw___if_not_exists:
1049 ParseMicrosoftIfExistsExternalDeclaration();
1050 return nullptr;
1051
1052 case tok::kw_module:
1053 Diag(Tok, diag::err_unexpected_module_decl);
1054 SkipUntil(tok::semi);
1055 return nullptr;
1056
1057 default:
1058 dont_know:
1059 if (Tok.isEditorPlaceholder()) {
1060 ConsumeToken();
1061 return nullptr;
1062 }
1063 if (getLangOpts().IncrementalExtensions &&
1064 !isDeclarationStatement(/*DisambiguatingWithExpression=*/true))
1065 return ParseTopLevelStmtDecl();
1066
1067 // We can't tell whether this is a function-definition or declaration yet.
1068 if (!SingleDecl)
1069 return ParseDeclarationOrFunctionDefinition(Attrs, DeclSpecAttrs, DS);
1070 }
1071
1072 // This routine returns a DeclGroup, if the thing we parsed only contains a
1073 // single decl, convert it now.
1074 return Actions.ConvertDeclToDeclGroup(SingleDecl);
1075}
1076
1077/// Determine whether the current token, if it occurs after a
1078/// declarator, continues a declaration or declaration list.
1079bool Parser::isDeclarationAfterDeclarator() {
1080 // Check for '= delete' or '= default'
1081 if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
1082 const Token &KW = NextToken();
1083 if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
1084 return false;
1085 }
1086
1087 return Tok.is(tok::equal) || // int X()= -> not a function def
1088 Tok.is(tok::comma) || // int X(), -> not a function def
1089 Tok.is(tok::semi) || // int X(); -> not a function def
1090 Tok.is(tok::kw_asm) || // int X() __asm__ -> not a function def
1091 Tok.is(tok::kw___attribute) || // int X() __attr__ -> not a function def
1092 (getLangOpts().CPlusPlus &&
1093 Tok.is(tok::l_paren)); // int X(0) -> not a function def [C++]
1094}
1095
1096/// Determine whether the current token, if it occurs after a
1097/// declarator, indicates the start of a function definition.
1098bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
1099 assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
1100 if (Tok.is(tok::l_brace)) // int X() {}
1101 return true;
1102
1103 // Handle K&R C argument lists: int X(f) int f; {}
1104 if (!getLangOpts().CPlusPlus &&
1106 return isDeclarationSpecifier(ImplicitTypenameContext::No);
1107
1108 if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
1109 const Token &KW = NextToken();
1110 return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
1111 }
1112
1113 return Tok.is(tok::colon) || // X() : Base() {} (used for ctors)
1114 Tok.is(tok::kw_try); // X() try { ... }
1115}
1116
1117/// Parse either a function-definition or a declaration. We can't tell which
1118/// we have until we read up to the compound-statement in function-definition.
1119/// TemplateParams, if non-NULL, provides the template parameters when we're
1120/// parsing a C++ template-declaration.
1121///
1122/// function-definition: [C99 6.9.1]
1123/// decl-specs declarator declaration-list[opt] compound-statement
1124/// [C90] function-definition: [C99 6.7.1] - implicit int result
1125/// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
1126///
1127/// declaration: [C99 6.7]
1128/// declaration-specifiers init-declarator-list[opt] ';'
1129/// [!C99] init-declarator-list ';' [TODO: warn in c99 mode]
1130/// [OMP] threadprivate-directive
1131/// [OMP] allocate-directive [TODO]
1132///
1133Parser::DeclGroupPtrTy Parser::ParseDeclOrFunctionDefInternal(
1134 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1136 // Because we assume that the DeclSpec has not yet been initialised, we simply
1137 // overwrite the source range and attribute the provided leading declspec
1138 // attributes.
1139 assert(DS.getSourceRange().isInvalid() &&
1140 "expected uninitialised source range");
1141 DS.SetRangeStart(DeclSpecAttrs.Range.getBegin());
1142 DS.SetRangeEnd(DeclSpecAttrs.Range.getEnd());
1143 DS.takeAttributesFrom(DeclSpecAttrs);
1144
1145 ParsedTemplateInfo TemplateInfo;
1146 MaybeParseMicrosoftAttributes(DS.getAttributes());
1147 // Parse the common declaration-specifiers piece.
1148 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
1149 DeclSpecContext::DSC_top_level);
1150
1151 // If we had a free-standing type definition with a missing semicolon, we
1152 // may get this far before the problem becomes obvious.
1153 if (DS.hasTagDefinition() && DiagnoseMissingSemiAfterTagDefinition(
1154 DS, AS, DeclSpecContext::DSC_top_level))
1155 return nullptr;
1156
1157 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1158 // declaration-specifiers init-declarator-list[opt] ';'
1159 if (Tok.is(tok::semi)) {
1160 auto LengthOfTSTToken = [](DeclSpec::TST TKind) {
1161 assert(DeclSpec::isDeclRep(TKind));
1162 switch(TKind) {
1164 return 5;
1166 return 6;
1168 return 5;
1169 case DeclSpec::TST_enum:
1170 return 4;
1172 return 9;
1173 default:
1174 llvm_unreachable("we only expect to get the length of the class/struct/union/enum");
1175 }
1176
1177 };
1178 // Suggest correct location to fix '[[attrib]] struct' to 'struct [[attrib]]'
1179 SourceLocation CorrectLocationForAttributes =
1182 LengthOfTSTToken(DS.getTypeSpecType()))
1183 : SourceLocation();
1184 ProhibitAttributes(Attrs, CorrectLocationForAttributes);
1185 ConsumeToken();
1186 RecordDecl *AnonRecord = nullptr;
1187 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
1188 getCurScope(), AS_none, DS, ParsedAttributesView::none(), AnonRecord);
1189 DS.complete(TheDecl);
1190 Actions.ActOnDefinedDeclarationSpecifier(TheDecl);
1191 if (AnonRecord) {
1192 Decl* decls[] = {AnonRecord, TheDecl};
1193 return Actions.BuildDeclaratorGroup(decls);
1194 }
1195 return Actions.ConvertDeclToDeclGroup(TheDecl);
1196 }
1197
1198 if (DS.hasTagDefinition())
1200
1201 // ObjC2 allows prefix attributes on class interfaces and protocols.
1202 // FIXME: This still needs better diagnostics. We should only accept
1203 // attributes here, no types, etc.
1204 if (getLangOpts().ObjC && Tok.is(tok::at)) {
1205 SourceLocation AtLoc = ConsumeToken(); // the "@"
1206 if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
1207 !Tok.isObjCAtKeyword(tok::objc_protocol) &&
1208 !Tok.isObjCAtKeyword(tok::objc_implementation)) {
1209 Diag(Tok, diag::err_objc_unexpected_attr);
1210 SkipUntil(tok::semi);
1211 return nullptr;
1212 }
1213
1214 DS.abort();
1215 DS.takeAttributesFrom(Attrs);
1216
1217 const char *PrevSpec = nullptr;
1218 unsigned DiagID;
1219 if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID,
1220 Actions.getASTContext().getPrintingPolicy()))
1221 Diag(AtLoc, DiagID) << PrevSpec;
1222
1223 if (Tok.isObjCAtKeyword(tok::objc_protocol))
1224 return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
1225
1226 if (Tok.isObjCAtKeyword(tok::objc_implementation))
1227 return ParseObjCAtImplementationDeclaration(AtLoc, DS.getAttributes());
1228
1229 return Actions.ConvertDeclToDeclGroup(
1230 ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
1231 }
1232
1233 // If the declspec consisted only of 'extern' and we have a string
1234 // literal following it, this must be a C++ linkage specifier like
1235 // 'extern "C"'.
1236 if (getLangOpts().CPlusPlus && isTokenStringLiteral() &&
1239 ProhibitAttributes(Attrs);
1240 Decl *TheDecl = ParseLinkage(DS, DeclaratorContext::File);
1241 return Actions.ConvertDeclToDeclGroup(TheDecl);
1242 }
1243
1244 return ParseDeclGroup(DS, DeclaratorContext::File, Attrs, TemplateInfo);
1245}
1246
1247Parser::DeclGroupPtrTy Parser::ParseDeclarationOrFunctionDefinition(
1248 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1250 // Add an enclosing time trace scope for a bunch of small scopes with
1251 // "EvaluateAsConstExpr".
1252 llvm::TimeTraceScope TimeScope("ParseDeclarationOrFunctionDefinition", [&]() {
1253 return Tok.getLocation().printToString(
1254 Actions.getASTContext().getSourceManager());
1255 });
1256
1257 if (DS) {
1258 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, *DS, AS);
1259 } else {
1260 ParsingDeclSpec PDS(*this);
1261 // Must temporarily exit the objective-c container scope for
1262 // parsing c constructs and re-enter objc container scope
1263 // afterwards.
1264 ObjCDeclContextSwitch ObjCDC(*this);
1265
1266 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, PDS, AS);
1267 }
1268}
1269
1270/// ParseFunctionDefinition - We parsed and verified that the specified
1271/// Declarator is well formed. If this is a K&R-style function, read the
1272/// parameters declaration-list, then start the compound-statement.
1273///
1274/// function-definition: [C99 6.9.1]
1275/// decl-specs declarator declaration-list[opt] compound-statement
1276/// [C90] function-definition: [C99 6.7.1] - implicit int result
1277/// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
1278/// [C++] function-definition: [C++ 8.4]
1279/// decl-specifier-seq[opt] declarator ctor-initializer[opt]
1280/// function-body
1281/// [C++] function-definition: [C++ 8.4]
1282/// decl-specifier-seq[opt] declarator function-try-block
1283///
1284Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
1285 const ParsedTemplateInfo &TemplateInfo,
1286 LateParsedAttrList *LateParsedAttrs) {
1287 llvm::TimeTraceScope TimeScope("ParseFunctionDefinition", [&]() {
1288 return Actions.GetNameForDeclarator(D).getName().getAsString();
1289 });
1290
1291 // Poison SEH identifiers so they are flagged as illegal in function bodies.
1292 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
1293 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1294 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1295
1296 // If this is C89 and the declspecs were completely missing, fudge in an
1297 // implicit int. We do this here because this is the only place where
1298 // declaration-specifiers are completely optional in the grammar.
1299 if (getLangOpts().isImplicitIntRequired() && D.getDeclSpec().isEmpty()) {
1300 Diag(D.getIdentifierLoc(), diag::warn_missing_type_specifier)
1301 << D.getDeclSpec().getSourceRange();
1302 const char *PrevSpec;
1303 unsigned DiagID;
1304 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1305 D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
1306 D.getIdentifierLoc(),
1307 PrevSpec, DiagID,
1308 Policy);
1309 D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
1310 }
1311
1312 // If this declaration was formed with a K&R-style identifier list for the
1313 // arguments, parse declarations for all of the args next.
1314 // int foo(a,b) int a; float b; {}
1315 if (FTI.isKNRPrototype())
1316 ParseKNRParamDeclarations(D);
1317
1318 // We should have either an opening brace or, in a C++ constructor,
1319 // we may have a colon.
1320 if (Tok.isNot(tok::l_brace) &&
1321 (!getLangOpts().CPlusPlus ||
1322 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
1323 Tok.isNot(tok::equal)))) {
1324 Diag(Tok, diag::err_expected_fn_body);
1325
1326 // Skip over garbage, until we get to '{'. Don't eat the '{'.
1327 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
1328
1329 // If we didn't find the '{', bail out.
1330 if (Tok.isNot(tok::l_brace))
1331 return nullptr;
1332 }
1333
1334 // Check to make sure that any normal attributes are allowed to be on
1335 // a definition. Late parsed attributes are checked at the end.
1336 if (Tok.isNot(tok::equal)) {
1337 for (const ParsedAttr &AL : D.getAttributes())
1338 if (AL.isKnownToGCC() && !AL.isStandardAttributeSyntax())
1339 Diag(AL.getLoc(), diag::warn_attribute_on_function_definition) << AL;
1340 }
1341
1342 // In delayed template parsing mode, for function template we consume the
1343 // tokens and store them for late parsing at the end of the translation unit.
1344 if (getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
1345 TemplateInfo.Kind == ParsedTemplateInfo::Template &&
1346 Actions.canDelayFunctionBody(D)) {
1347 MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
1348
1349 ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1351 Scope *ParentScope = getCurScope()->getParent();
1352
1353 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
1354 Decl *DP = Actions.HandleDeclarator(ParentScope, D,
1356 D.complete(DP);
1357 D.getMutableDeclSpec().abort();
1358
1359 if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) &&
1360 trySkippingFunctionBody()) {
1361 BodyScope.Exit();
1362 return Actions.ActOnSkippedFunctionBody(DP);
1363 }
1364
1365 CachedTokens Toks;
1366 LexTemplateFunctionForLateParsing(Toks);
1367
1368 if (DP) {
1369 FunctionDecl *FnD = DP->getAsFunction();
1370 Actions.CheckForFunctionRedefinition(FnD);
1371 Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
1372 }
1373 return DP;
1374 }
1375 else if (CurParsedObjCImpl &&
1376 !TemplateInfo.TemplateParams &&
1377 (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
1378 Tok.is(tok::colon)) &&
1379 Actions.CurContext->isTranslationUnit()) {
1380 ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1382 Scope *ParentScope = getCurScope()->getParent();
1383
1384 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
1385 Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1387 D.complete(FuncDecl);
1388 D.getMutableDeclSpec().abort();
1389 if (FuncDecl) {
1390 // Consume the tokens and store them for later parsing.
1391 StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1392 CurParsedObjCImpl->HasCFunction = true;
1393 return FuncDecl;
1394 }
1395 // FIXME: Should we really fall through here?
1396 }
1397
1398 // Enter a scope for the function body.
1399 ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1401
1402 // Parse function body eagerly if it is either '= delete;' or '= default;' as
1403 // ActOnStartOfFunctionDef needs to know whether the function is deleted.
1404 StringLiteral *DeletedMessage = nullptr;
1406 SourceLocation KWLoc;
1407 if (TryConsumeToken(tok::equal)) {
1408 assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
1409
1410 if (TryConsumeToken(tok::kw_delete, KWLoc)) {
1412 ? diag::warn_cxx98_compat_defaulted_deleted_function
1413 : diag::ext_defaulted_deleted_function)
1414 << 1 /* deleted */;
1415 BodyKind = Sema::FnBodyKind::Delete;
1416 DeletedMessage = ParseCXXDeletedFunctionMessage();
1417 } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
1419 ? diag::warn_cxx98_compat_defaulted_deleted_function
1420 : diag::ext_defaulted_deleted_function)
1421 << 0 /* defaulted */;
1422 BodyKind = Sema::FnBodyKind::Default;
1423 } else {
1424 llvm_unreachable("function definition after = not 'delete' or 'default'");
1425 }
1426
1427 if (Tok.is(tok::comma)) {
1428 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1429 << (BodyKind == Sema::FnBodyKind::Delete);
1430 SkipUntil(tok::semi);
1431 } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
1432 BodyKind == Sema::FnBodyKind::Delete
1433 ? "delete"
1434 : "default")) {
1435 SkipUntil(tok::semi);
1436 }
1437 }
1438
1439 Sema::FPFeaturesStateRAII SaveFPFeatures(Actions);
1440
1441 // Tell the actions module that we have entered a function definition with the
1442 // specified Declarator for the function.
1443 SkipBodyInfo SkipBody;
1444 Decl *Res = Actions.ActOnStartOfFunctionDef(getCurScope(), D,
1445 TemplateInfo.TemplateParams
1446 ? *TemplateInfo.TemplateParams
1448 &SkipBody, BodyKind);
1449
1450 if (SkipBody.ShouldSkip) {
1451 // Do NOT enter SkipFunctionBody if we already consumed the tokens.
1452 if (BodyKind == Sema::FnBodyKind::Other)
1453 SkipFunctionBody();
1454
1455 // ExpressionEvaluationContext is pushed in ActOnStartOfFunctionDef
1456 // and it would be popped in ActOnFinishFunctionBody.
1457 // We pop it explcitly here since ActOnFinishFunctionBody won't get called.
1458 //
1459 // Do not call PopExpressionEvaluationContext() if it is a lambda because
1460 // one is already popped when finishing the lambda in BuildLambdaExpr().
1461 //
1462 // FIXME: It looks not easy to balance PushExpressionEvaluationContext()
1463 // and PopExpressionEvaluationContext().
1464 if (!isLambdaCallOperator(dyn_cast_if_present<FunctionDecl>(Res)))
1466 return Res;
1467 }
1468
1469 // Break out of the ParsingDeclarator context before we parse the body.
1470 D.complete(Res);
1471
1472 // Break out of the ParsingDeclSpec context, too. This const_cast is
1473 // safe because we're always the sole owner.
1474 D.getMutableDeclSpec().abort();
1475
1476 if (BodyKind != Sema::FnBodyKind::Other) {
1477 Actions.SetFunctionBodyKind(Res, KWLoc, BodyKind, DeletedMessage);
1478 Stmt *GeneratedBody = Res ? Res->getBody() : nullptr;
1479 Actions.ActOnFinishFunctionBody(Res, GeneratedBody, false);
1480 return Res;
1481 }
1482
1483 // With abbreviated function templates - we need to explicitly add depth to
1484 // account for the implicit template parameter list induced by the template.
1485 if (const auto *Template = dyn_cast_if_present<FunctionTemplateDecl>(Res);
1486 Template && Template->isAbbreviated() &&
1487 Template->getTemplateParameters()->getParam(0)->isImplicit())
1488 // First template parameter is implicit - meaning no explicit template
1489 // parameter list was specified.
1490 CurTemplateDepthTracker.addDepth(1);
1491
1492 if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&
1493 trySkippingFunctionBody()) {
1494 BodyScope.Exit();
1495 Actions.ActOnSkippedFunctionBody(Res);
1496 return Actions.ActOnFinishFunctionBody(Res, nullptr, false);
1497 }
1498
1499 if (Tok.is(tok::kw_try))
1500 return ParseFunctionTryBlock(Res, BodyScope);
1501
1502 // If we have a colon, then we're probably parsing a C++
1503 // ctor-initializer.
1504 if (Tok.is(tok::colon)) {
1505 ParseConstructorInitializer(Res);
1506
1507 // Recover from error.
1508 if (!Tok.is(tok::l_brace)) {
1509 BodyScope.Exit();
1510 Actions.ActOnFinishFunctionBody(Res, nullptr);
1511 return Res;
1512 }
1513 } else
1514 Actions.ActOnDefaultCtorInitializers(Res);
1515
1516 // Late attributes are parsed in the same scope as the function body.
1517 if (LateParsedAttrs)
1518 ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
1519
1520 return ParseFunctionStatementBody(Res, BodyScope);
1521}
1522
1523void Parser::SkipFunctionBody() {
1524 if (Tok.is(tok::equal)) {
1525 SkipUntil(tok::semi);
1526 return;
1527 }
1528
1529 bool IsFunctionTryBlock = Tok.is(tok::kw_try);
1530 if (IsFunctionTryBlock)
1531 ConsumeToken();
1532
1533 CachedTokens Skipped;
1534 if (ConsumeAndStoreFunctionPrologue(Skipped))
1536 else {
1537 SkipUntil(tok::r_brace);
1538 while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) {
1539 SkipUntil(tok::l_brace);
1540 SkipUntil(tok::r_brace);
1541 }
1542 }
1543}
1544
1545/// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
1546/// types for a function with a K&R-style identifier list for arguments.
1547void Parser::ParseKNRParamDeclarations(Declarator &D) {
1548 // We know that the top-level of this declarator is a function.
1549 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1550
1551 // Enter function-declaration scope, limiting any declarators to the
1552 // function prototype scope, including parameter declarators.
1553 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1555
1556 // Read all the argument declarations.
1557 while (isDeclarationSpecifier(ImplicitTypenameContext::No)) {
1558 SourceLocation DSStart = Tok.getLocation();
1559
1560 // Parse the common declaration-specifiers piece.
1561 DeclSpec DS(AttrFactory);
1562 ParsedTemplateInfo TemplateInfo;
1563 ParseDeclarationSpecifiers(DS, TemplateInfo);
1564
1565 // C99 6.9.1p6: 'each declaration in the declaration list shall have at
1566 // least one declarator'.
1567 // NOTE: GCC just makes this an ext-warn. It's not clear what it does with
1568 // the declarations though. It's trivial to ignore them, really hard to do
1569 // anything else with them.
1570 if (TryConsumeToken(tok::semi)) {
1571 Diag(DSStart, diag::err_declaration_does_not_declare_param);
1572 continue;
1573 }
1574
1575 // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
1576 // than register.
1580 diag::err_invalid_storage_class_in_func_decl);
1582 }
1585 diag::err_invalid_storage_class_in_func_decl);
1587 }
1588
1589 // Parse the first declarator attached to this declspec.
1590 Declarator ParmDeclarator(DS, ParsedAttributesView::none(),
1592 ParseDeclarator(ParmDeclarator);
1593
1594 // Handle the full declarator list.
1595 while (true) {
1596 // If attributes are present, parse them.
1597 MaybeParseGNUAttributes(ParmDeclarator);
1598
1599 // Ask the actions module to compute the type for this declarator.
1600 Decl *Param =
1601 Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
1602
1603 if (Param &&
1604 // A missing identifier has already been diagnosed.
1605 ParmDeclarator.getIdentifier()) {
1606
1607 // Scan the argument list looking for the correct param to apply this
1608 // type.
1609 for (unsigned i = 0; ; ++i) {
1610 // C99 6.9.1p6: those declarators shall declare only identifiers from
1611 // the identifier list.
1612 if (i == FTI.NumParams) {
1613 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1614 << ParmDeclarator.getIdentifier();
1615 break;
1616 }
1617
1618 if (FTI.Params[i].Ident == ParmDeclarator.getIdentifier()) {
1619 // Reject redefinitions of parameters.
1620 if (FTI.Params[i].Param) {
1621 Diag(ParmDeclarator.getIdentifierLoc(),
1622 diag::err_param_redefinition)
1623 << ParmDeclarator.getIdentifier();
1624 } else {
1625 FTI.Params[i].Param = Param;
1626 }
1627 break;
1628 }
1629 }
1630 }
1631
1632 // If we don't have a comma, it is either the end of the list (a ';') or
1633 // an error, bail out.
1634 if (Tok.isNot(tok::comma))
1635 break;
1636
1637 ParmDeclarator.clear();
1638
1639 // Consume the comma.
1640 ParmDeclarator.setCommaLoc(ConsumeToken());
1641
1642 // Parse the next declarator.
1643 ParseDeclarator(ParmDeclarator);
1644 }
1645
1646 // Consume ';' and continue parsing.
1647 if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
1648 continue;
1649
1650 // Otherwise recover by skipping to next semi or mandatory function body.
1651 if (SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch))
1652 break;
1653 TryConsumeToken(tok::semi);
1654 }
1655
1656 // The actions module must verify that all arguments were declared.
1658}
1659
1660
1661/// ParseAsmStringLiteral - This is just a normal string-literal, but is not
1662/// allowed to be a wide string, and is not subject to character translation.
1663/// Unlike GCC, we also diagnose an empty string literal when parsing for an
1664/// asm label as opposed to an asm statement, because such a construct does not
1665/// behave well.
1666///
1667/// [GNU] asm-string-literal:
1668/// string-literal
1669///
1670ExprResult Parser::ParseAsmStringLiteral(bool ForAsmLabel) {
1671 if (!isTokenStringLiteral()) {
1672 Diag(Tok, diag::err_expected_string_literal)
1673 << /*Source='in...'*/0 << "'asm'";
1674 return ExprError();
1675 }
1676
1678 if (!AsmString.isInvalid()) {
1679 const auto *SL = cast<StringLiteral>(AsmString.get());
1680 if (!SL->isOrdinary()) {
1681 Diag(Tok, diag::err_asm_operand_wide_string_literal)
1682 << SL->isWide()
1683 << SL->getSourceRange();
1684 return ExprError();
1685 }
1686 if (ForAsmLabel && SL->getString().empty()) {
1687 Diag(Tok, diag::err_asm_operand_wide_string_literal)
1688 << 2 /* an empty */ << SL->getSourceRange();
1689 return ExprError();
1690 }
1691 }
1692 return AsmString;
1693}
1694
1695/// ParseSimpleAsm
1696///
1697/// [GNU] simple-asm-expr:
1698/// 'asm' '(' asm-string-literal ')'
1699///
1700ExprResult Parser::ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc) {
1701 assert(Tok.is(tok::kw_asm) && "Not an asm!");
1703
1704 if (isGNUAsmQualifier(Tok)) {
1705 // Remove from the end of 'asm' to the end of the asm qualifier.
1706 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1708 Diag(Tok, diag::err_global_asm_qualifier_ignored)
1709 << GNUAsmQualifiers::getQualifierName(getGNUAsmQualifier(Tok))
1710 << FixItHint::CreateRemoval(RemovalRange);
1711 ConsumeToken();
1712 }
1713
1714 BalancedDelimiterTracker T(*this, tok::l_paren);
1715 if (T.consumeOpen()) {
1716 Diag(Tok, diag::err_expected_lparen_after) << "asm";
1717 return ExprError();
1718 }
1719
1720 ExprResult Result(ParseAsmStringLiteral(ForAsmLabel));
1721
1722 if (!Result.isInvalid()) {
1723 // Close the paren and get the location of the end bracket
1724 T.consumeClose();
1725 if (EndLoc)
1726 *EndLoc = T.getCloseLocation();
1727 } else if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
1728 if (EndLoc)
1729 *EndLoc = Tok.getLocation();
1730 ConsumeParen();
1731 }
1732
1733 return Result;
1734}
1735
1736/// Get the TemplateIdAnnotation from the token and put it in the
1737/// cleanup pool so that it gets destroyed when parsing the current top level
1738/// declaration is finished.
1739TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
1740 assert(tok.is(tok::annot_template_id) && "Expected template-id token");
1742 Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
1743 return Id;
1744}
1745
1746void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
1747 // Push the current token back into the token stream (or revert it if it is
1748 // cached) and use an annotation scope token for current token.
1749 if (PP.isBacktrackEnabled())
1750 PP.RevertCachedTokens(1);
1751 else
1752 PP.EnterToken(Tok, /*IsReinject=*/true);
1753 Tok.setKind(tok::annot_cxxscope);
1755 Tok.setAnnotationRange(SS.getRange());
1756
1757 // In case the tokens were cached, have Preprocessor replace them
1758 // with the annotation token. We don't need to do this if we've
1759 // just reverted back to a prior state.
1760 if (IsNewAnnotation)
1761 PP.AnnotateCachedTokens(Tok);
1762}
1763
1764/// Attempt to classify the name at the current token position. This may
1765/// form a type, scope or primary expression annotation, or replace the token
1766/// with a typo-corrected keyword. This is only appropriate when the current
1767/// name must refer to an entity which has already been declared.
1768///
1769/// \param CCC Indicates how to perform typo-correction for this name. If NULL,
1770/// no typo correction will be performed.
1771/// \param AllowImplicitTypename Whether we are in a context where a dependent
1772/// nested-name-specifier without typename is treated as a type (e.g.
1773/// T::type).
1774Parser::AnnotatedNameKind
1775Parser::TryAnnotateName(CorrectionCandidateCallback *CCC,
1776 ImplicitTypenameContext AllowImplicitTypename) {
1777 assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1778
1779 const bool EnteringContext = false;
1780 const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1781
1782 CXXScopeSpec SS;
1783 if (getLangOpts().CPlusPlus &&
1784 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1785 /*ObjectHasErrors=*/false,
1786 EnteringContext))
1787 return ANK_Error;
1788
1789 if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
1790 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation,
1791 AllowImplicitTypename))
1792 return ANK_Error;
1793 return ANK_Unresolved;
1794 }
1795
1796 IdentifierInfo *Name = Tok.getIdentifierInfo();
1797 SourceLocation NameLoc = Tok.getLocation();
1798
1799 // FIXME: Move the tentative declaration logic into ClassifyName so we can
1800 // typo-correct to tentatively-declared identifiers.
1801 if (isTentativelyDeclared(Name) && SS.isEmpty()) {
1802 // Identifier has been tentatively declared, and thus cannot be resolved as
1803 // an expression. Fall back to annotating it as a type.
1804 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation,
1805 AllowImplicitTypename))
1806 return ANK_Error;
1807 return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
1808 }
1809
1810 Token Next = NextToken();
1811
1812 // Look up and classify the identifier. We don't perform any typo-correction
1813 // after a scope specifier, because in general we can't recover from typos
1814 // there (eg, after correcting 'A::template B<X>::C' [sic], we would need to
1815 // jump back into scope specifier parsing).
1816 Sema::NameClassification Classification = Actions.ClassifyName(
1817 getCurScope(), SS, Name, NameLoc, Next, SS.isEmpty() ? CCC : nullptr);
1818
1819 // If name lookup found nothing and we guessed that this was a template name,
1820 // double-check before committing to that interpretation. C++20 requires that
1821 // we interpret this as a template-id if it can be, but if it can't be, then
1822 // this is an error recovery case.
1823 if (Classification.getKind() == Sema::NC_UndeclaredTemplate &&
1824 isTemplateArgumentList(1) == TPResult::False) {
1825 // It's not a template-id; re-classify without the '<' as a hint.
1826 Token FakeNext = Next;
1827 FakeNext.setKind(tok::unknown);
1828 Classification =
1829 Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, FakeNext,
1830 SS.isEmpty() ? CCC : nullptr);
1831 }
1832
1833 switch (Classification.getKind()) {
1834 case Sema::NC_Error:
1835 return ANK_Error;
1836
1837 case Sema::NC_Keyword:
1838 // The identifier was typo-corrected to a keyword.
1839 Tok.setIdentifierInfo(Name);
1840 Tok.setKind(Name->getTokenID());
1841 PP.TypoCorrectToken(Tok);
1842 if (SS.isNotEmpty())
1843 AnnotateScopeToken(SS, !WasScopeAnnotation);
1844 // We've "annotated" this as a keyword.
1845 return ANK_Success;
1846
1847 case Sema::NC_Unknown:
1848 // It's not something we know about. Leave it unannotated.
1849 break;
1850
1851 case Sema::NC_Type: {
1852 if (TryAltiVecVectorToken())
1853 // vector has been found as a type id when altivec is enabled but
1854 // this is followed by a declaration specifier so this is really the
1855 // altivec vector token. Leave it unannotated.
1856 break;
1857 SourceLocation BeginLoc = NameLoc;
1858 if (SS.isNotEmpty())
1859 BeginLoc = SS.getBeginLoc();
1860
1861 /// An Objective-C object type followed by '<' is a specialization of
1862 /// a parameterized class type or a protocol-qualified type.
1863 ParsedType Ty = Classification.getType();
1864 if (getLangOpts().ObjC && NextToken().is(tok::less) &&
1865 (Ty.get()->isObjCObjectType() ||
1866 Ty.get()->isObjCObjectPointerType())) {
1867 // Consume the name.
1869 SourceLocation NewEndLoc;
1870 TypeResult NewType
1871 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1872 /*consumeLastToken=*/false,
1873 NewEndLoc);
1874 if (NewType.isUsable())
1875 Ty = NewType.get();
1876 else if (Tok.is(tok::eof)) // Nothing to do here, bail out...
1877 return ANK_Error;
1878 }
1879
1880 Tok.setKind(tok::annot_typename);
1881 setTypeAnnotation(Tok, Ty);
1883 Tok.setLocation(BeginLoc);
1884 PP.AnnotateCachedTokens(Tok);
1885 return ANK_Success;
1886 }
1887
1889 Tok.setKind(tok::annot_overload_set);
1890 setExprAnnotation(Tok, Classification.getExpression());
1891 Tok.setAnnotationEndLoc(NameLoc);
1892 if (SS.isNotEmpty())
1893 Tok.setLocation(SS.getBeginLoc());
1894 PP.AnnotateCachedTokens(Tok);
1895 return ANK_Success;
1896
1897 case Sema::NC_NonType:
1898 if (TryAltiVecVectorToken())
1899 // vector has been found as a non-type id when altivec is enabled but
1900 // this is followed by a declaration specifier so this is really the
1901 // altivec vector token. Leave it unannotated.
1902 break;
1903 Tok.setKind(tok::annot_non_type);
1904 setNonTypeAnnotation(Tok, Classification.getNonTypeDecl());
1905 Tok.setLocation(NameLoc);
1906 Tok.setAnnotationEndLoc(NameLoc);
1907 PP.AnnotateCachedTokens(Tok);
1908 if (SS.isNotEmpty())
1909 AnnotateScopeToken(SS, !WasScopeAnnotation);
1910 return ANK_Success;
1911
1914 Tok.setKind(Classification.getKind() == Sema::NC_UndeclaredNonType
1915 ? tok::annot_non_type_undeclared
1916 : tok::annot_non_type_dependent);
1917 setIdentifierAnnotation(Tok, Name);
1918 Tok.setLocation(NameLoc);
1919 Tok.setAnnotationEndLoc(NameLoc);
1920 PP.AnnotateCachedTokens(Tok);
1921 if (SS.isNotEmpty())
1922 AnnotateScopeToken(SS, !WasScopeAnnotation);
1923 return ANK_Success;
1924
1926 if (Next.isNot(tok::less)) {
1927 // This may be a type template being used as a template template argument.
1928 if (SS.isNotEmpty())
1929 AnnotateScopeToken(SS, !WasScopeAnnotation);
1930 return ANK_TemplateName;
1931 }
1932 [[fallthrough]];
1933 case Sema::NC_Concept:
1937 bool IsConceptName = Classification.getKind() == Sema::NC_Concept;
1938 // We have a template name followed by '<'. Consume the identifier token so
1939 // we reach the '<' and annotate it.
1940 if (Next.is(tok::less))
1941 ConsumeToken();
1943 Id.setIdentifier(Name, NameLoc);
1944 if (AnnotateTemplateIdToken(
1945 TemplateTy::make(Classification.getTemplateName()),
1946 Classification.getTemplateNameKind(), SS, SourceLocation(), Id,
1947 /*AllowTypeAnnotation=*/!IsConceptName,
1948 /*TypeConstraint=*/IsConceptName))
1949 return ANK_Error;
1950 if (SS.isNotEmpty())
1951 AnnotateScopeToken(SS, !WasScopeAnnotation);
1952 return ANK_Success;
1953 }
1954 }
1955
1956 // Unable to classify the name, but maybe we can annotate a scope specifier.
1957 if (SS.isNotEmpty())
1958 AnnotateScopeToken(SS, !WasScopeAnnotation);
1959 return ANK_Unresolved;
1960}
1961
1962bool Parser::TryKeywordIdentFallback(bool DisableKeyword) {
1963 assert(Tok.isNot(tok::identifier));
1964 Diag(Tok, diag::ext_keyword_as_ident)
1965 << PP.getSpelling(Tok)
1966 << DisableKeyword;
1967 if (DisableKeyword)
1969 Tok.setKind(tok::identifier);
1970 return true;
1971}
1972
1973/// TryAnnotateTypeOrScopeToken - If the current token position is on a
1974/// typename (possibly qualified in C++) or a C++ scope specifier not followed
1975/// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
1976/// with a single annotation token representing the typename or C++ scope
1977/// respectively.
1978/// This simplifies handling of C++ scope specifiers and allows efficient
1979/// backtracking without the need to re-parse and resolve nested-names and
1980/// typenames.
1981/// It will mainly be called when we expect to treat identifiers as typenames
1982/// (if they are typenames). For example, in C we do not expect identifiers
1983/// inside expressions to be treated as typenames so it will not be called
1984/// for expressions in C.
1985/// The benefit for C/ObjC is that a typename will be annotated and
1986/// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
1987/// will not be called twice, once to check whether we have a declaration
1988/// specifier, and another one to get the actual type inside
1989/// ParseDeclarationSpecifiers).
1990///
1991/// This returns true if an error occurred.
1992///
1993/// Note that this routine emits an error if you call it with ::new or ::delete
1994/// as the current tokens, so only call it in contexts where these are invalid.
1996 ImplicitTypenameContext AllowImplicitTypename) {
1997 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1998 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
1999 Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
2000 Tok.is(tok::kw___super) || Tok.is(tok::kw_auto) ||
2001 Tok.is(tok::annot_pack_indexing_type)) &&
2002 "Cannot be a type or scope token!");
2003
2004 if (Tok.is(tok::kw_typename)) {
2005 // MSVC lets you do stuff like:
2006 // typename typedef T_::D D;
2007 //
2008 // We will consume the typedef token here and put it back after we have
2009 // parsed the first identifier, transforming it into something more like:
2010 // typename T_::D typedef D;
2011 if (getLangOpts().MSVCCompat && NextToken().is(tok::kw_typedef)) {
2012 Token TypedefToken;
2013 PP.Lex(TypedefToken);
2014 bool Result = TryAnnotateTypeOrScopeToken(AllowImplicitTypename);
2015 PP.EnterToken(Tok, /*IsReinject=*/true);
2016 Tok = TypedefToken;
2017 if (!Result)
2018 Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
2019 return Result;
2020 }
2021
2022 // Parse a C++ typename-specifier, e.g., "typename T::type".
2023 //
2024 // typename-specifier:
2025 // 'typename' '::' [opt] nested-name-specifier identifier
2026 // 'typename' '::' [opt] nested-name-specifier template [opt]
2027 // simple-template-id
2028 SourceLocation TypenameLoc = ConsumeToken();
2029 CXXScopeSpec SS;
2030 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
2031 /*ObjectHasErrors=*/false,
2032 /*EnteringContext=*/false, nullptr,
2033 /*IsTypename*/ true))
2034 return true;
2035 if (SS.isEmpty()) {
2036 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
2037 Tok.is(tok::annot_decltype)) {
2038 // Attempt to recover by skipping the invalid 'typename'
2039 if (Tok.is(tok::annot_decltype) ||
2040 (!TryAnnotateTypeOrScopeToken(AllowImplicitTypename) &&
2041 Tok.isAnnotation())) {
2042 unsigned DiagID = diag::err_expected_qualified_after_typename;
2043 // MS compatibility: MSVC permits using known types with typename.
2044 // e.g. "typedef typename T* pointer_type"
2045 if (getLangOpts().MicrosoftExt)
2046 DiagID = diag::warn_expected_qualified_after_typename;
2047 Diag(Tok.getLocation(), DiagID);
2048 return false;
2049 }
2050 }
2051 if (Tok.isEditorPlaceholder())
2052 return true;
2053
2054 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
2055 return true;
2056 }
2057
2058 bool TemplateKWPresent = false;
2059 if (Tok.is(tok::kw_template)) {
2060 ConsumeToken();
2061 TemplateKWPresent = true;
2062 }
2063
2064 TypeResult Ty;
2065 if (Tok.is(tok::identifier)) {
2066 if (TemplateKWPresent && NextToken().isNot(tok::less)) {
2067 Diag(Tok.getLocation(),
2068 diag::missing_template_arg_list_after_template_kw);
2069 return true;
2070 }
2071 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
2072 *Tok.getIdentifierInfo(),
2073 Tok.getLocation());
2074 } else if (Tok.is(tok::annot_template_id)) {
2075 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2076 if (!TemplateId->mightBeType()) {
2077 Diag(Tok, diag::err_typename_refers_to_non_type_template)
2078 << Tok.getAnnotationRange();
2079 return true;
2080 }
2081
2082 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
2083 TemplateId->NumArgs);
2084
2085 Ty = TemplateId->isInvalid()
2086 ? TypeError()
2087 : Actions.ActOnTypenameType(
2088 getCurScope(), TypenameLoc, SS, TemplateId->TemplateKWLoc,
2089 TemplateId->Template, TemplateId->Name,
2090 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc,
2091 TemplateArgsPtr, TemplateId->RAngleLoc);
2092 } else {
2093 Diag(Tok, diag::err_expected_type_name_after_typename)
2094 << SS.getRange();
2095 return true;
2096 }
2097
2098 SourceLocation EndLoc = Tok.getLastLoc();
2099 Tok.setKind(tok::annot_typename);
2100 setTypeAnnotation(Tok, Ty);
2101 Tok.setAnnotationEndLoc(EndLoc);
2102 Tok.setLocation(TypenameLoc);
2103 PP.AnnotateCachedTokens(Tok);
2104 return false;
2105 }
2106
2107 // Remembers whether the token was originally a scope annotation.
2108 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
2109
2110 CXXScopeSpec SS;
2111 if (getLangOpts().CPlusPlus)
2112 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
2113 /*ObjectHasErrors=*/false,
2114 /*EnteringContext*/ false))
2115 return true;
2116
2117 return TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation,
2118 AllowImplicitTypename);
2119}
2120
2121/// Try to annotate a type or scope token, having already parsed an
2122/// optional scope specifier. \p IsNewScope should be \c true unless the scope
2123/// specifier was extracted from an existing tok::annot_cxxscope annotation.
2125 CXXScopeSpec &SS, bool IsNewScope,
2126 ImplicitTypenameContext AllowImplicitTypename) {
2127 if (Tok.is(tok::identifier)) {
2128 // Determine whether the identifier is a type name.
2129 if (ParsedType Ty = Actions.getTypeName(
2130 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), &SS,
2131 false, NextToken().is(tok::period), nullptr,
2132 /*IsCtorOrDtorName=*/false,
2133 /*NonTrivialTypeSourceInfo=*/true,
2134 /*IsClassTemplateDeductionContext=*/true, AllowImplicitTypename)) {
2135 SourceLocation BeginLoc = Tok.getLocation();
2136 if (SS.isNotEmpty()) // it was a C++ qualified type name.
2137 BeginLoc = SS.getBeginLoc();
2138
2139 /// An Objective-C object type followed by '<' is a specialization of
2140 /// a parameterized class type or a protocol-qualified type.
2141 if (getLangOpts().ObjC && NextToken().is(tok::less) &&
2142 (Ty.get()->isObjCObjectType() ||
2143 Ty.get()->isObjCObjectPointerType())) {
2144 // Consume the name.
2146 SourceLocation NewEndLoc;
2147 TypeResult NewType
2148 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
2149 /*consumeLastToken=*/false,
2150 NewEndLoc);
2151 if (NewType.isUsable())
2152 Ty = NewType.get();
2153 else if (Tok.is(tok::eof)) // Nothing to do here, bail out...
2154 return false;
2155 }
2156
2157 // This is a typename. Replace the current token in-place with an
2158 // annotation type token.
2159 Tok.setKind(tok::annot_typename);
2160 setTypeAnnotation(Tok, Ty);
2162 Tok.setLocation(BeginLoc);
2163
2164 // In case the tokens were cached, have Preprocessor replace
2165 // them with the annotation token.
2166 PP.AnnotateCachedTokens(Tok);
2167 return false;
2168 }
2169
2170 if (!getLangOpts().CPlusPlus) {
2171 // If we're in C, the only place we can have :: tokens is C23
2172 // attribute which is parsed elsewhere. If the identifier is not a type,
2173 // then it can't be scope either, just early exit.
2174 return false;
2175 }
2176
2177 // If this is a template-id, annotate with a template-id or type token.
2178 // FIXME: This appears to be dead code. We already have formed template-id
2179 // tokens when parsing the scope specifier; this can never form a new one.
2180 if (NextToken().is(tok::less)) {
2181 TemplateTy Template;
2183 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
2184 bool MemberOfUnknownSpecialization;
2185 if (TemplateNameKind TNK = Actions.isTemplateName(
2186 getCurScope(), SS,
2187 /*hasTemplateKeyword=*/false, TemplateName,
2188 /*ObjectType=*/nullptr, /*EnteringContext*/false, Template,
2189 MemberOfUnknownSpecialization)) {
2190 // Only annotate an undeclared template name as a template-id if the
2191 // following tokens have the form of a template argument list.
2192 if (TNK != TNK_Undeclared_template ||
2193 isTemplateArgumentList(1) != TPResult::False) {
2194 // Consume the identifier.
2195 ConsumeToken();
2196 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
2197 TemplateName)) {
2198 // If an unrecoverable error occurred, we need to return true here,
2199 // because the token stream is in a damaged state. We may not
2200 // return a valid identifier.
2201 return true;
2202 }
2203 }
2204 }
2205 }
2206
2207 // The current token, which is either an identifier or a
2208 // template-id, is not part of the annotation. Fall through to
2209 // push that token back into the stream and complete the C++ scope
2210 // specifier annotation.
2211 }
2212
2213 if (Tok.is(tok::annot_template_id)) {
2214 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2215 if (TemplateId->Kind == TNK_Type_template) {
2216 // A template-id that refers to a type was parsed into a
2217 // template-id annotation in a context where we weren't allowed
2218 // to produce a type annotation token. Update the template-id
2219 // annotation token to a type annotation token now.
2220 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
2221 return false;
2222 }
2223 }
2224
2225 if (SS.isEmpty())
2226 return false;
2227
2228 // A C++ scope specifier that isn't followed by a typename.
2229 AnnotateScopeToken(SS, IsNewScope);
2230 return false;
2231}
2232
2233/// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
2234/// annotates C++ scope specifiers and template-ids. This returns
2235/// true if there was an error that could not be recovered from.
2236///
2237/// Note that this routine emits an error if you call it with ::new or ::delete
2238/// as the current tokens, so only call it in contexts where these are invalid.
2239bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
2240 assert(getLangOpts().CPlusPlus &&
2241 "Call sites of this function should be guarded by checking for C++");
2242 assert(MightBeCXXScopeToken() && "Cannot be a type or scope token!");
2243
2244 CXXScopeSpec SS;
2245 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
2246 /*ObjectHasErrors=*/false,
2247 EnteringContext))
2248 return true;
2249 if (SS.isEmpty())
2250 return false;
2251
2252 AnnotateScopeToken(SS, true);
2253 return false;
2254}
2255
2256bool Parser::isTokenEqualOrEqualTypo() {
2257 tok::TokenKind Kind = Tok.getKind();
2258 switch (Kind) {
2259 default:
2260 return false;
2261 case tok::ampequal: // &=
2262 case tok::starequal: // *=
2263 case tok::plusequal: // +=
2264 case tok::minusequal: // -=
2265 case tok::exclaimequal: // !=
2266 case tok::slashequal: // /=
2267 case tok::percentequal: // %=
2268 case tok::lessequal: // <=
2269 case tok::lesslessequal: // <<=
2270 case tok::greaterequal: // >=
2271 case tok::greatergreaterequal: // >>=
2272 case tok::caretequal: // ^=
2273 case tok::pipeequal: // |=
2274 case tok::equalequal: // ==
2275 Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
2276 << Kind
2278 [[fallthrough]];
2279 case tok::equal:
2280 return true;
2281 }
2282}
2283
2284SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
2285 assert(Tok.is(tok::code_completion));
2286 PrevTokLocation = Tok.getLocation();
2287
2288 for (Scope *S = getCurScope(); S; S = S->getParent()) {
2289 if (S->isFunctionScope()) {
2290 cutOffParsing();
2293 return PrevTokLocation;
2294 }
2295
2296 if (S->isClassScope()) {
2297 cutOffParsing();
2300 return PrevTokLocation;
2301 }
2302 }
2303
2304 cutOffParsing();
2307 return PrevTokLocation;
2308}
2309
2310// Code-completion pass-through functions
2311
2312void Parser::CodeCompleteDirective(bool InConditional) {
2313 Actions.CodeCompletion().CodeCompletePreprocessorDirective(InConditional);
2314}
2315
2316void Parser::CodeCompleteInConditionalExclusion() {
2318 getCurScope());
2319}
2320
2321void Parser::CodeCompleteMacroName(bool IsDefinition) {
2322 Actions.CodeCompletion().CodeCompletePreprocessorMacroName(IsDefinition);
2323}
2324
2325void Parser::CodeCompletePreprocessorExpression() {
2327}
2328
2329void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
2331 unsigned ArgumentIndex) {
2333 getCurScope(), Macro, MacroInfo, ArgumentIndex);
2334}
2335
2336void Parser::CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) {
2337 Actions.CodeCompletion().CodeCompleteIncludedFile(Dir, IsAngled);
2338}
2339
2340void Parser::CodeCompleteNaturalLanguage() {
2342}
2343
2344bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
2345 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
2346 "Expected '__if_exists' or '__if_not_exists'");
2347 Result.IsIfExists = Tok.is(tok::kw___if_exists);
2348 Result.KeywordLoc = ConsumeToken();
2349
2350 BalancedDelimiterTracker T(*this, tok::l_paren);
2351 if (T.consumeOpen()) {
2352 Diag(Tok, diag::err_expected_lparen_after)
2353 << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
2354 return true;
2355 }
2356
2357 // Parse nested-name-specifier.
2358 if (getLangOpts().CPlusPlus)
2359 ParseOptionalCXXScopeSpecifier(Result.SS, /*ObjectType=*/nullptr,
2360 /*ObjectHasErrors=*/false,
2361 /*EnteringContext=*/false);
2362
2363 // Check nested-name specifier.
2364 if (Result.SS.isInvalid()) {
2365 T.skipToEnd();
2366 return true;
2367 }
2368
2369 // Parse the unqualified-id.
2370 SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
2371 if (ParseUnqualifiedId(Result.SS, /*ObjectType=*/nullptr,
2372 /*ObjectHadErrors=*/false, /*EnteringContext*/ false,
2373 /*AllowDestructorName*/ true,
2374 /*AllowConstructorName*/ true,
2375 /*AllowDeductionGuide*/ false, &TemplateKWLoc,
2376 Result.Name)) {
2377 T.skipToEnd();
2378 return true;
2379 }
2380
2381 if (T.consumeClose())
2382 return true;
2383
2384 // Check if the symbol exists.
2385 switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
2386 Result.IsIfExists, Result.SS,
2387 Result.Name)) {
2388 case Sema::IER_Exists:
2389 Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
2390 break;
2391
2393 Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
2394 break;
2395
2397 Result.Behavior = IEB_Dependent;
2398 break;
2399
2400 case Sema::IER_Error:
2401 return true;
2402 }
2403
2404 return false;
2405}
2406
2407void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
2408 IfExistsCondition Result;
2409 if (ParseMicrosoftIfExistsCondition(Result))
2410 return;
2411
2412 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2413 if (Braces.consumeOpen()) {
2414 Diag(Tok, diag::err_expected) << tok::l_brace;
2415 return;
2416 }
2417
2418 switch (Result.Behavior) {
2419 case IEB_Parse:
2420 // Parse declarations below.
2421 break;
2422
2423 case IEB_Dependent:
2424 llvm_unreachable("Cannot have a dependent external declaration");
2425
2426 case IEB_Skip:
2427 Braces.skipToEnd();
2428 return;
2429 }
2430
2431 // Parse the declarations.
2432 // FIXME: Support module import within __if_exists?
2433 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
2434 ParsedAttributes Attrs(AttrFactory);
2435 MaybeParseCXX11Attributes(Attrs);
2436 ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
2437 DeclGroupPtrTy Result = ParseExternalDeclaration(Attrs, EmptyDeclSpecAttrs);
2438 if (Result && !getCurScope()->getParent())
2439 Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
2440 }
2441 Braces.consumeClose();
2442}
2443
2444/// Parse a declaration beginning with the 'module' keyword or C++20
2445/// context-sensitive keyword (optionally preceded by 'export').
2446///
2447/// module-declaration: [C++20]
2448/// 'export'[opt] 'module' module-name attribute-specifier-seq[opt] ';'
2449///
2450/// global-module-fragment: [C++2a]
2451/// 'module' ';' top-level-declaration-seq[opt]
2452/// module-declaration: [C++2a]
2453/// 'export'[opt] 'module' module-name module-partition[opt]
2454/// attribute-specifier-seq[opt] ';'
2455/// private-module-fragment: [C++2a]
2456/// 'module' ':' 'private' ';' top-level-declaration-seq[opt]
2458Parser::ParseModuleDecl(Sema::ModuleImportState &ImportState) {
2459 SourceLocation StartLoc = Tok.getLocation();
2460
2461 Sema::ModuleDeclKind MDK = TryConsumeToken(tok::kw_export)
2464
2465 assert(
2466 (Tok.is(tok::kw_module) ||
2467 (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_module)) &&
2468 "not a module declaration");
2469 SourceLocation ModuleLoc = ConsumeToken();
2470
2471 // Attributes appear after the module name, not before.
2472 // FIXME: Suggest moving the attributes later with a fixit.
2473 DiagnoseAndSkipCXX11Attributes();
2474
2475 // Parse a global-module-fragment, if present.
2476 if (getLangOpts().CPlusPlusModules && Tok.is(tok::semi)) {
2477 SourceLocation SemiLoc = ConsumeToken();
2478 if (ImportState != Sema::ModuleImportState::FirstDecl) {
2479 Diag(StartLoc, diag::err_global_module_introducer_not_at_start)
2480 << SourceRange(StartLoc, SemiLoc);
2481 return nullptr;
2482 }
2484 Diag(StartLoc, diag::err_module_fragment_exported)
2485 << /*global*/0 << FixItHint::CreateRemoval(StartLoc);
2486 }
2488 return Actions.ActOnGlobalModuleFragmentDecl(ModuleLoc);
2489 }
2490
2491 // Parse a private-module-fragment, if present.
2492 if (getLangOpts().CPlusPlusModules && Tok.is(tok::colon) &&
2493 NextToken().is(tok::kw_private)) {
2495 Diag(StartLoc, diag::err_module_fragment_exported)
2496 << /*private*/1 << FixItHint::CreateRemoval(StartLoc);
2497 }
2498 ConsumeToken();
2499 SourceLocation PrivateLoc = ConsumeToken();
2500 DiagnoseAndSkipCXX11Attributes();
2501 ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi);
2502 ImportState = ImportState == Sema::ModuleImportState::ImportAllowed
2505 return Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc);
2506 }
2507
2509 if (ParseModuleName(ModuleLoc, Path, /*IsImport*/ false))
2510 return nullptr;
2511
2512 // Parse the optional module-partition.
2514 if (Tok.is(tok::colon)) {
2515 SourceLocation ColonLoc = ConsumeToken();
2516 if (!getLangOpts().CPlusPlusModules)
2517 Diag(ColonLoc, diag::err_unsupported_module_partition)
2518 << SourceRange(ColonLoc, Partition.back().second);
2519 // Recover by ignoring the partition name.
2520 else if (ParseModuleName(ModuleLoc, Partition, /*IsImport*/ false))
2521 return nullptr;
2522 }
2523
2524 // We don't support any module attributes yet; just parse them and diagnose.
2525 ParsedAttributes Attrs(AttrFactory);
2526 MaybeParseCXX11Attributes(Attrs);
2527 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr,
2528 diag::err_keyword_not_module_attr,
2529 /*DiagnoseEmptyAttrs=*/false,
2530 /*WarnOnUnknownAttrs=*/true);
2531
2532 ExpectAndConsumeSemi(diag::err_module_expected_semi);
2533
2534 return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, Partition,
2535 ImportState);
2536}
2537
2538/// Parse a module import declaration. This is essentially the same for
2539/// Objective-C and C++20 except for the leading '@' (in ObjC) and the
2540/// trailing optional attributes (in C++).
2541///
2542/// [ObjC] @import declaration:
2543/// '@' 'import' module-name ';'
2544/// [ModTS] module-import-declaration:
2545/// 'import' module-name attribute-specifier-seq[opt] ';'
2546/// [C++20] module-import-declaration:
2547/// 'export'[opt] 'import' module-name
2548/// attribute-specifier-seq[opt] ';'
2549/// 'export'[opt] 'import' module-partition
2550/// attribute-specifier-seq[opt] ';'
2551/// 'export'[opt] 'import' header-name
2552/// attribute-specifier-seq[opt] ';'
2553Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
2554 Sema::ModuleImportState &ImportState) {
2555 SourceLocation StartLoc = AtLoc.isInvalid() ? Tok.getLocation() : AtLoc;
2556
2557 SourceLocation ExportLoc;
2558 TryConsumeToken(tok::kw_export, ExportLoc);
2559
2560 assert((AtLoc.isInvalid() ? Tok.isOneOf(tok::kw_import, tok::identifier)
2561 : Tok.isObjCAtKeyword(tok::objc_import)) &&
2562 "Improper start to module import");
2563 bool IsObjCAtImport = Tok.isObjCAtKeyword(tok::objc_import);
2564 SourceLocation ImportLoc = ConsumeToken();
2565
2566 // For C++20 modules, we can have "name" or ":Partition name" as valid input.
2568 bool IsPartition = false;
2569 Module *HeaderUnit = nullptr;
2570 if (Tok.is(tok::header_name)) {
2571 // This is a header import that the preprocessor decided we should skip
2572 // because it was malformed in some way. Parse and ignore it; it's already
2573 // been diagnosed.
2574 ConsumeToken();
2575 } else if (Tok.is(tok::annot_header_unit)) {
2576 // This is a header import that the preprocessor mapped to a module import.
2577 HeaderUnit = reinterpret_cast<Module *>(Tok.getAnnotationValue());
2578 ConsumeAnnotationToken();
2579 } else if (Tok.is(tok::colon)) {
2580 SourceLocation ColonLoc = ConsumeToken();
2581 if (!getLangOpts().CPlusPlusModules)
2582 Diag(ColonLoc, diag::err_unsupported_module_partition)
2583 << SourceRange(ColonLoc, Path.back().second);
2584 // Recover by leaving partition empty.
2585 else if (ParseModuleName(ColonLoc, Path, /*IsImport*/ true))
2586 return nullptr;
2587 else
2588 IsPartition = true;
2589 } else {
2590 if (ParseModuleName(ImportLoc, Path, /*IsImport*/ true))
2591 return nullptr;
2592 }
2593
2594 ParsedAttributes Attrs(AttrFactory);
2595 MaybeParseCXX11Attributes(Attrs);
2596 // We don't support any module import attributes yet.
2597 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr,
2598 diag::err_keyword_not_import_attr,
2599 /*DiagnoseEmptyAttrs=*/false,
2600 /*WarnOnUnknownAttrs=*/true);
2601
2602 if (PP.hadModuleLoaderFatalFailure()) {
2603 // With a fatal failure in the module loader, we abort parsing.
2604 cutOffParsing();
2605 return nullptr;
2606 }
2607
2608 // Diagnose mis-imports.
2609 bool SeenError = true;
2610 switch (ImportState) {
2612 SeenError = false;
2613 break;
2615 // If we found an import decl as the first declaration, we must be not in
2616 // a C++20 module unit or we are in an invalid state.
2618 [[fallthrough]];
2620 // We can only import a partition within a module purview.
2621 if (IsPartition)
2622 Diag(ImportLoc, diag::err_partition_import_outside_module);
2623 else
2624 SeenError = false;
2625 break;
2628 // We can only have pre-processor directives in the global module fragment
2629 // which allows pp-import, but not of a partition (since the global module
2630 // does not have partitions).
2631 // We cannot import a partition into a private module fragment, since
2632 // [module.private.frag]/1 disallows private module fragments in a multi-
2633 // TU module.
2634 if (IsPartition || (HeaderUnit && HeaderUnit->Kind !=
2636 Diag(ImportLoc, diag::err_import_in_wrong_fragment)
2637 << IsPartition
2638 << (ImportState == Sema::ModuleImportState::GlobalFragment ? 0 : 1);
2639 else
2640 SeenError = false;
2641 break;
2644 if (getLangOpts().CPlusPlusModules)
2645 Diag(ImportLoc, diag::err_import_not_allowed_here);
2646 else
2647 SeenError = false;
2648 break;
2649 }
2650 if (SeenError) {
2651 ExpectAndConsumeSemi(diag::err_module_expected_semi);
2652 return nullptr;
2653 }
2654
2656 if (HeaderUnit)
2657 Import =
2658 Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit);
2659 else if (!Path.empty())
2660 Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path,
2661 IsPartition);
2662 ExpectAndConsumeSemi(diag::err_module_expected_semi);
2663 if (Import.isInvalid())
2664 return nullptr;
2665
2666 // Using '@import' in framework headers requires modules to be enabled so that
2667 // the header is parseable. Emit a warning to make the user aware.
2668 if (IsObjCAtImport && AtLoc.isValid()) {
2669 auto &SrcMgr = PP.getSourceManager();
2670 auto FE = SrcMgr.getFileEntryRefForID(SrcMgr.getFileID(AtLoc));
2671 if (FE && llvm::sys::path::parent_path(FE->getDir().getName())
2672 .ends_with(".framework"))
2673 Diags.Report(AtLoc, diag::warn_atimport_in_framework_header);
2674 }
2675
2676 return Import.get();
2677}
2678
2679/// Parse a C++ / Objective-C module name (both forms use the same
2680/// grammar).
2681///
2682/// module-name:
2683/// module-name-qualifier[opt] identifier
2684/// module-name-qualifier:
2685/// module-name-qualifier[opt] identifier '.'
2686bool Parser::ParseModuleName(
2687 SourceLocation UseLoc,
2688 SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
2689 bool IsImport) {
2690 // Parse the module path.
2691 while (true) {
2692 if (!Tok.is(tok::identifier)) {
2693 if (Tok.is(tok::code_completion)) {
2694 cutOffParsing();
2695 Actions.CodeCompletion().CodeCompleteModuleImport(UseLoc, Path);
2696 return true;
2697 }
2698
2699 Diag(Tok, diag::err_module_expected_ident) << IsImport;
2700 SkipUntil(tok::semi);
2701 return true;
2702 }
2703
2704 // Record this part of the module path.
2705 Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
2706 ConsumeToken();
2707
2708 if (Tok.isNot(tok::period))
2709 return false;
2710
2711 ConsumeToken();
2712 }
2713}
2714
2715/// Try recover parser when module annotation appears where it must not
2716/// be found.
2717/// \returns false if the recover was successful and parsing may be continued, or
2718/// true if parser must bail out to top level and handle the token there.
2719bool Parser::parseMisplacedModuleImport() {
2720 while (true) {
2721 switch (Tok.getKind()) {
2722 case tok::annot_module_end:
2723 // If we recovered from a misplaced module begin, we expect to hit a
2724 // misplaced module end too. Stay in the current context when this
2725 // happens.
2726 if (MisplacedModuleBeginCount) {
2727 --MisplacedModuleBeginCount;
2728 Actions.ActOnAnnotModuleEnd(
2729 Tok.getLocation(),
2730 reinterpret_cast<Module *>(Tok.getAnnotationValue()));
2731 ConsumeAnnotationToken();
2732 continue;
2733 }
2734 // Inform caller that recovery failed, the error must be handled at upper
2735 // level. This will generate the desired "missing '}' at end of module"
2736 // diagnostics on the way out.
2737 return true;
2738 case tok::annot_module_begin:
2739 // Recover by entering the module (Sema will diagnose).
2740 Actions.ActOnAnnotModuleBegin(
2741 Tok.getLocation(),
2742 reinterpret_cast<Module *>(Tok.getAnnotationValue()));
2743 ConsumeAnnotationToken();
2744 ++MisplacedModuleBeginCount;
2745 continue;
2746 case tok::annot_module_include:
2747 // Module import found where it should not be, for instance, inside a
2748 // namespace. Recover by importing the module.
2750 Tok.getLocation(),
2751 reinterpret_cast<Module *>(Tok.getAnnotationValue()));
2752 ConsumeAnnotationToken();
2753 // If there is another module import, process it.
2754 continue;
2755 default:
2756 return false;
2757 }
2758 }
2759 return false;
2760}
2761
2762void Parser::diagnoseUseOfC11Keyword(const Token &Tok) {
2763 // Warn that this is a C11 extension if in an older mode or if in C++.
2764 // Otherwise, warn that it is incompatible with standards before C11 if in
2765 // C11 or later.
2766 Diag(Tok, getLangOpts().C11 ? diag::warn_c11_compat_keyword
2767 : diag::ext_c11_feature)
2768 << Tok.getName();
2769}
2770
2771bool BalancedDelimiterTracker::diagnoseOverflow() {
2772 P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
2773 << P.getLangOpts().BracketDepth;
2774 P.Diag(P.Tok, diag::note_bracket_depth);
2775 P.cutOffParsing();
2776 return true;
2777}
2778
2780 const char *Msg,
2781 tok::TokenKind SkipToTok) {
2782 LOpen = P.Tok.getLocation();
2783 if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
2784 if (SkipToTok != tok::unknown)
2785 P.SkipUntil(SkipToTok, Parser::StopAtSemi);
2786 return true;
2787 }
2788
2789 if (getDepth() < P.getLangOpts().BracketDepth)
2790 return false;
2791
2792 return diagnoseOverflow();
2793}
2794
2795bool BalancedDelimiterTracker::diagnoseMissingClose() {
2796 assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
2797
2798 if (P.Tok.is(tok::annot_module_end))
2799 P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
2800 else
2801 P.Diag(P.Tok, diag::err_expected) << Close;
2802 P.Diag(LOpen, diag::note_matching) << Kind;
2803
2804 // If we're not already at some kind of closing bracket, skip to our closing
2805 // token.
2806 if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
2807 P.Tok.isNot(tok::r_square) &&
2808 P.SkipUntil(Close, FinalToken,
2810 P.Tok.is(Close))
2811 LClose = P.ConsumeAnyToken();
2812 return true;
2813}
2814
2817 consumeClose();
2818}
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
const Decl * D
IndirectLocalPath & Path
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1171
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)
uint32_t Id
Definition: SemaARM.cpp:1143
This file declares facilities that support code completion.
SourceLocation Loc
Definition: SemaObjC.cpp:758
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
SourceManager & getSourceManager()
Definition: ASTContext.h:721
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:713
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1227
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:2779
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:2166
Captures information about "declaration specifiers".
Definition: DeclSpec.h:247
void ClearStorageClassSpecs()
Definition: DeclSpec.h:515
TST getTypeSpecType() const
Definition: DeclSpec.h:537
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:510
SCS getStorageClassSpec() const
Definition: DeclSpec.h:501
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:863
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:574
void SetRangeEnd(SourceLocation Loc)
Definition: DeclSpec.h:709
static const TST TST_interface
Definition: DeclSpec.h:304
void SetRangeStart(SourceLocation Loc)
Definition: DeclSpec.h:708
static const TST TST_union
Definition: DeclSpec.h:302
static const TST TST_int
Definition: DeclSpec.h:285
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:502
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:873
static const TST TST_enum
Definition: DeclSpec.h:301
static bool isDeclRep(TST T)
Definition: DeclSpec.h:469
static const TST TST_class
Definition: DeclSpec.h:305
bool hasTagDefinition() const
Definition: DeclSpec.cpp:462
unsigned getParsedSpecifiers() const
Return a bitmask of which flavors of specifiers this DeclSpec includes.
Definition: DeclSpec.cpp:471
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:561
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:511
Decl * getRepAsDecl() const
Definition: DeclSpec.h:551
static const TST TST_unspecified
Definition: DeclSpec.h:278
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:582
void takeAttributesFrom(ParsedAttributes &attrs)
Definition: DeclSpec.h:876
@ PQ_StorageClassSpecifier
Definition: DeclSpec.h:346
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:249
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:434
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1903
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition: DeclSpec.h:2459
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2490
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:1932
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:4783
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:2124
SourceLocation ConsumeToken()
ConsumeToken - Consume the current 'peek token' and lex the next one.
Definition: Parser.h:548
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:537
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:576
bool TryConsumeToken(tok::TokenKind Expected)
Definition: Parser.h:556
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition: Parser.h:513
Scope * getCurScope() const
Definition: Parser.h:502
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:1294
void SkipMalformedDecl()
SkipMalformedDecl - Read tokens until we get to some likely good stopping point for skipping past a s...
Definition: ParseDecl.cpp:2214
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:495
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:1272
@ StopBeforeMatch
Stop skipping at specified token, but don't skip the token itself.
Definition: Parser.h:1275
@ StopAtCodeCompletion
Stop at code completion.
Definition: Parser.h:1276
@ StopAtSemi
Stop skipping at semicolon.
Definition: Parser.h:1273
bool TryAnnotateTypeOrScopeToken(ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
TryAnnotateTypeOrScopeToken - If the current token position is on a typename (possibly qualified in C...
Definition: Parser.cpp:1995
bool MightBeCXXScopeToken()
Definition: Parser.h:929
ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral=false)
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition: Parser.h:872
SmallVector< TemplateParameterList *, 4 > TemplateParameterLists
Definition: Parser.h:516
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:2239
A class for parsing a DeclSpec.
A class for parsing a declarator.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:137
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:4145
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:13604
ExprResult getExpression() const
Definition: Sema.h:3345
NameClassificationKind getKind() const
Definition: Sema.h:3343
NamedDecl * getNonTypeDecl() const
Definition: Sema.h:3355
TemplateName getTemplateName() const
Definition: Sema.h:3360
ParsedType getType() const
Definition: Sema.h:3350
TemplateNameKind getTemplateNameKind() const
Definition: Sema.h:3367
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:535
void ActOnPopScope(SourceLocation Loc, Scope *S)
Definition: SemaDecl.cpp:2178
void ActOnDefinedDeclarationSpecifier(Decl *D)
Called once it is known whether a tag declaration is an anonymous union or struct.
Definition: SemaDecl.cpp:5294
Decl * ActOnSkippedFunctionBody(Decl *Decl)
Definition: SemaDecl.cpp:15730
void ActOnAnnotModuleBegin(SourceLocation DirectiveLoc, Module *Mod)
The parsed has entered a submodule.
Definition: SemaModule.cpp:761
void ActOnAnnotModuleInclude(SourceLocation DirectiveLoc, Module *Mod)
The parser has processed a module import translated from a #include or similar preprocessing directiv...
Definition: SemaModule.cpp:722
@ IER_DoesNotExist
The symbol does not exist.
Definition: Sema.h:8532
@ IER_Dependent
The name is a dependent name, so the results will differ from one instantiation to the next.
Definition: Sema.h:8536
@ IER_Error
An error occurred.
Definition: Sema.h:8539
@ IER_Exists
The symbol exists.
Definition: Sema.h:8529
Decl * ActOnParamDeclarator(Scope *S, Declarator &D, SourceLocation ExplicitThisLoc={})
ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() to introduce parameters into fun...
Definition: SemaDecl.cpp:14928
void Initialize()
Perform initialization that occurs after the parser has been initialized but before it parses anythin...
Definition: Sema.cpp:312
ModuleDeclKind
Definition: Sema.h:9672
@ 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:6206
void ActOnComment(SourceRange Comment)
Definition: Sema.cpp:2442
@ 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:1171
void ActOnTranslationUnitScope(Scope *S)
Scope actions.
Definition: Sema.cpp:151
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:259
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:20114
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:5770
void ActOnAnnotModuleEnd(SourceLocation DirectiveLoc, Module *Mod)
The parser has left a submodule.
Definition: SemaModule.cpp:785
DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, ModuleIdPath Path, bool IsPartition=false)
The parser has processed a module import declaration.
Definition: SemaModule.cpp:574
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition: SemaDecl.cpp:71
ASTContext & getASTContext() const
Definition: Sema.h:602
@ NC_Unknown
This name is not a type or template in this context, but might be something else.
Definition: Sema.h:3235
@ NC_VarTemplate
The name was classified as a variable template name.
Definition: Sema.h:3262
@ NC_NonType
The name was classified as a specific non-type, non-template declaration.
Definition: Sema.h:3245
@ NC_TypeTemplate
The name was classified as a template whose specializations are types.
Definition: Sema.h:3260
@ NC_Error
Classification failed; an error has been produced.
Definition: Sema.h:3237
@ NC_FunctionTemplate
The name was classified as a function template name.
Definition: Sema.h:3264
@ NC_DependentNonType
The name denotes a member of a dependent type that could not be resolved.
Definition: Sema.h:3253
@ NC_UndeclaredNonType
The name was classified as an ADL-only function name.
Definition: Sema.h:3249
@ NC_UndeclaredTemplate
The name was classified as an ADL-only function template name.
Definition: Sema.h:3266
@ NC_Keyword
The name has been typo-corrected to a keyword.
Definition: Sema.h:3239
@ NC_Type
The name was classified as a type.
Definition: Sema.h:3241
@ NC_OverloadSet
The name was classified as an overload set, and an expression representing that overload set has been...
Definition: Sema.h:3258
@ NC_Concept
The name was classified as a concept name.
Definition: Sema.h:3268
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:17595
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:1050
SemaCodeCompletion & CodeCompletion()
Definition: Sema.h:1161
ASTConsumer & getASTConsumer() const
Definition: Sema.h:603
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
Definition: SemaDecl.cpp:15224
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:15688
std::function< TypeResult(StringRef, StringRef, SourceLocation)> ParseTypeFromStringCallback
Callback to the parser to parse a type expressed as a string.
Definition: Sema.h:1059
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:858
DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc)
The parser has processed a global-module-fragment declaration that begins the definition of the globa...
Definition: SemaModule.cpp:163
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
Definition: SemaDecl.cpp:14794
void CheckForFunctionRedefinition(FunctionDecl *FD, const FunctionDecl *EffectiveDefinition=nullptr, SkipBodyInfo *SkipBody=nullptr)
Definition: SemaDecl.cpp:15330
IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, const DeclarationNameInfo &TargetNameInfo)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1139
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:512
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:15712
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
Definition: SemaDecl.cpp:15740
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:1100
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:287
ModuleImportState
An enumeration to represent the transition of states in parsing module fragments and imports.
Definition: Sema.h:9682
@ 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:4776
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls)
Definition: SemaDecl.cpp:15176
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:1778
Represents a C++ template name within the type system.
Definition: TemplateName.h:203
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:8149
bool isObjCObjectPointerType() const
Definition: Type.h:8145
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1028
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:1886
@ CPlusPlus
Definition: LangStandard.h:56
@ CPlusPlus11
Definition: LangStandard.h:57
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:123
@ AS_none
Definition: Specifiers.h:127
#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:1428
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1403
bool isKNRPrototype() const
isKNRPrototype - Return true if this is a K&R style identifier list, like "void foo(a,...
Definition: DeclSpec.h:1508
const IdentifierInfo * Ident
Definition: DeclSpec.h:1334
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.