[RISCV] Add shrinkwrap test cases showing gaps in current impl
[llvm-project.git] / clang / lib / Parse / Parser.cpp
blob36e56a92c3092e423c8a4349f74ad73d853e033f
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.
11 //===----------------------------------------------------------------------===//
13 #include "clang/Parse/Parser.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/Basic/DiagnosticParse.h"
19 #include "clang/Basic/FileManager.h"
20 #include "clang/Parse/RAIIObjectsForParser.h"
21 #include "clang/Sema/DeclSpec.h"
22 #include "clang/Sema/ParsedTemplate.h"
23 #include "clang/Sema/Scope.h"
24 #include "clang/Sema/SemaCodeCompletion.h"
25 #include "llvm/Support/Path.h"
26 #include "llvm/Support/TimeProfiler.h"
27 using namespace clang;
30 namespace {
31 /// A comment handler that passes comments found by the preprocessor
32 /// to the parser action.
33 class ActionCommentHandler : public CommentHandler {
34 Sema &S;
36 public:
37 explicit ActionCommentHandler(Sema &S) : S(S) { }
39 bool HandleComment(Preprocessor &PP, SourceRange Comment) override {
40 S.ActOnComment(Comment);
41 return false;
44 } // end anonymous namespace
46 IdentifierInfo *Parser::getSEHExceptKeyword() {
47 // __except is accepted as a (contextual) keyword
48 if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland))
49 Ident__except = PP.getIdentifierInfo("__except");
51 return Ident__except;
54 Parser::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;
66 // Add #pragma handlers. These are removed and destroyed in the
67 // destructor.
68 initializePragmaHandlers();
70 CommentSemaHandler.reset(new ActionCommentHandler(actions));
71 PP.addCommentHandler(CommentSemaHandler.get());
73 PP.setCodeCompletionHandler(*this);
75 Actions.ParseTypeFromStringCallback =
76 [this](StringRef TypeStr, StringRef Context, SourceLocation IncludeLoc) {
77 return this->ParseTypeFromString(TypeStr, Context, IncludeLoc);
81 DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
82 return Diags.Report(Loc, DiagID);
85 DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
86 return Diag(Tok.getLocation(), DiagID);
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.
95 void 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;
105 Diag(Loc, DK)
106 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
107 << FixItHint::CreateInsertion(EndLoc, ")");
110 static 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;
118 bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
119 StringRef Msg) {
120 if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
121 ConsumeAnyToken();
122 return false;
125 // Detect common single-character typos and resume.
126 if (IsCommonTypo(ExpectedTok, Tok)) {
127 SourceLocation Loc = Tok.getLocation();
129 DiagnosticBuilder DB = Diag(Loc, DiagID);
130 DB << FixItHint::CreateReplacement(
131 SourceRange(Loc), tok::getPunctuatorSpelling(ExpectedTok));
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;
140 // Pretend there wasn't a problem.
141 ConsumeAnyToken();
142 return false;
145 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
146 const char *Spelling = nullptr;
147 if (EndLoc.isValid())
148 Spelling = tok::getPunctuatorSpelling(ExpectedTok);
150 DiagnosticBuilder DB =
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;
161 return true;
164 bool Parser::ExpectAndConsumeSemi(unsigned DiagID, StringRef TokenUsed) {
165 if (TryConsumeToken(tok::semi))
166 return false;
168 if (Tok.is(tok::code_completion)) {
169 handleUnexpectedCodeCompletionToken();
170 return false;
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)
177 << FixItHint::CreateRemoval(Tok.getLocation());
178 ConsumeAnyToken(); // The ')' or ']'.
179 ConsumeToken(); // The ';'.
180 return false;
183 return ExpectAndConsume(tok::semi, DiagID , TokenUsed);
186 void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST TST) {
187 if (!Tok.is(tok::semi)) return;
189 bool HadMultipleSemis = false;
190 SourceLocation StartLoc = Tok.getLocation();
191 SourceLocation EndLoc = Tok.getLocation();
192 ConsumeToken();
194 while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
195 HadMultipleSemis = true;
196 EndLoc = Tok.getLocation();
197 ConsumeToken();
200 // C++11 allows extra semicolons at namespace scope, but not in any of the
201 // other contexts.
202 if (Kind == OutsideFunction && getLangOpts().CPlusPlus) {
203 if (getLangOpts().CPlusPlus11)
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;
212 if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis)
213 Diag(StartLoc, diag::ext_extra_semi)
214 << Kind << DeclSpec::getSpecifierName(TST,
215 Actions.getASTContext().getPrintingPolicy())
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));
223 bool 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;
234 Diag(Tok, diag::err_expected) << tok::identifier;
235 return true;
238 void Parser::checkCompoundToken(SourceLocation FirstTokLoc,
239 tok::TokenKind FirstTokKind, CompoundToken Op) {
240 if (FirstTokLoc.isInvalid())
241 return;
242 SourceLocation SecondTokLoc = Tok.getLocation();
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;
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;
270 //===----------------------------------------------------------------------===//
271 // Error recovery.
272 //===----------------------------------------------------------------------===//
274 static bool HasFlagsSet(Parser::SkipUntilFlags L, Parser::SkipUntilFlags R) {
275 return (static_cast<unsigned>(L) & static_cast<unsigned>(R)) != 0;
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.
284 /// If SkipUntil finds the specified token, it returns true, otherwise it
285 /// returns false.
286 bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags) {
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 {
297 ConsumeAnyToken();
299 return true;
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) &&
308 !HasFlagsSet(Flags, StopAtCodeCompletion)) {
309 while (Tok.isNot(tok::eof))
310 ConsumeAnyToken();
311 return true;
314 switch (Tok.getKind()) {
315 case tok::eof:
316 // Ran out of tokens.
317 return false;
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;
343 case tok::code_completion:
344 if (!HasFlagsSet(Flags, StopAtCodeCompletion))
345 handleUnexpectedCodeCompletionToken();
346 return false;
348 case tok::l_paren:
349 // Recursively skip properly-nested parens.
350 ConsumeParen();
351 if (HasFlagsSet(Flags, StopAtCodeCompletion))
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();
359 if (HasFlagsSet(Flags, StopAtCodeCompletion))
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();
367 if (HasFlagsSet(Flags, StopAtCodeCompletion))
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;
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;
402 case tok::semi:
403 if (HasFlagsSet(Flags, StopAtSemi))
404 return false;
405 [[fallthrough]];
406 default:
407 // Skip this token.
408 ConsumeAnyToken();
409 break;
411 isFirstTokenSkipped = false;
415 //===----------------------------------------------------------------------===//
416 // Scope manipulation
417 //===----------------------------------------------------------------------===//
419 /// EnterScope - Start a new scope.
420 void 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);
430 /// ExitScope - Pop a scope off the scope stack.
431 void Parser::ExitScope() {
432 assert(getCurScope() && "Scope imbalance!");
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());
438 Scope *OldScope = getCurScope();
439 Actions.CurScope = OldScope->getParent();
441 if (NumCachedScopes == ScopeCacheSize)
442 delete OldScope;
443 else
444 ScopeCache[NumCachedScopes++] = OldScope;
447 /// Set the flags for the current scope to ScopeFlags. If ManageFlags is false,
448 /// this object does nothing.
449 Parser::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);
458 /// Restore the flags for the current scope to what they were before this
459 /// object overrode them.
460 Parser::ParseScopeFlags::~ParseScopeFlags() {
461 if (CurScope)
462 CurScope->setFlags(OldFlags);
466 //===----------------------------------------------------------------------===//
467 // C99 6.9: External Definitions.
468 //===----------------------------------------------------------------------===//
470 Parser::~Parser() {
471 // If we still have scopes active, delete the scope tree.
472 delete getCurScope();
473 Actions.CurScope = nullptr;
475 // Free the scope cache.
476 for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
477 delete ScopeCache[i];
479 resetPragmaHandlers();
481 PP.removeCommentHandler(CommentSemaHandler.get());
483 PP.clearCodeCompletionHandler();
485 DestroyTemplateIds();
488 /// Initialize - Warm up the parser.
490 void Parser::Initialize() {
491 // Create the translation unit scope. Install it as the current scope.
492 assert(getCurScope() == nullptr && "A scope is already active?");
493 EnterScope(Scope::DeclScope);
494 Actions.ActOnTranslationUnitScope(getCurScope());
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");
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;
520 Ident_super = &PP.getIdentifierTable().get("super");
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");
531 if (getLangOpts().AltiVec)
532 Ident_pixel = &PP.getIdentifierTable().get("pixel");
534 Ident_introduced = nullptr;
535 Ident_deprecated = nullptr;
536 Ident_obsoleted = nullptr;
537 Ident_unavailable = nullptr;
538 Ident_strict = nullptr;
539 Ident_replacement = nullptr;
541 Ident_language = Ident_defined_in = Ident_generated_declaration = Ident_USR =
542 nullptr;
544 Ident__except = nullptr;
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;
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");
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);
574 if (getLangOpts().CPlusPlusModules) {
575 Ident_import = PP.getIdentifierInfo("import");
576 Ident_module = PP.getIdentifierInfo("module");
579 Actions.Initialize();
581 // Prime the lexer look-ahead.
582 ConsumeToken();
585 void Parser::DestroyTemplateIds() {
586 for (TemplateIdAnnotation *Id : TemplateIds)
587 Id->Destroy();
588 TemplateIds.clear();
591 /// Parse the first top-level declaration in a translation unit.
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]
600 /// Note that in C, it is an error if there is no first declaration.
601 bool Parser::ParseFirstTopLevelDecl(DeclGroupPtrTy &Result,
602 Sema::ModuleImportState &ImportState) {
603 Actions.ActOnStartOfTranslationUnit();
605 // For C++20 modules, a module decl must be the first in the TU. We also
606 // need to track module imports.
607 ImportState = Sema::ModuleImportState::FirstDecl;
608 bool NoTopLevelDecls = ParseTopLevelDecl(Result, ImportState);
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);
619 return NoTopLevelDecls;
622 /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
623 /// action tells us to. This returns true if the EOF was encountered.
625 /// top-level-declaration:
626 /// declaration
627 /// [C++20] module-import-declaration
628 bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result,
629 Sema::ModuleImportState &ImportState) {
630 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
632 Result = nullptr;
633 switch (Tok.getKind()) {
634 case tok::annot_pragma_unused:
635 HandlePragmaUnused();
636 return false;
638 case tok::kw_export:
639 switch (NextToken().getKind()) {
640 case tok::kw_module:
641 goto module_decl;
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.
647 // Recognize context-sensitive C++20 'export module' and 'export import'
648 // declarations.
649 case tok::identifier: {
650 IdentifierInfo *II = NextToken().getIdentifierInfo();
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;
658 break;
661 default:
662 break;
664 break;
666 case tok::kw_module:
667 module_decl:
668 Result = ParseModuleDecl(ImportState);
669 return false;
671 case tok::kw_import:
672 import_decl: {
673 Decl *ImportDecl = ParseModuleImport(SourceLocation(), ImportState);
674 Result = Actions.ConvertDeclToDeclGroup(ImportDecl);
675 return false;
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();
689 Result = Actions.ConvertDeclToDeclGroup(ImportDecl);
691 ConsumeAnnotationToken();
692 return false;
695 case tok::annot_module_begin:
696 Actions.ActOnAnnotModuleBegin(
697 Tok.getLocation(),
698 reinterpret_cast<Module *>(Tok.getAnnotationValue()));
699 ConsumeAnnotationToken();
700 ImportState = Sema::ModuleImportState::NotACXX20Module;
701 return false;
703 case tok::annot_module_end:
704 Actions.ActOnAnnotModuleEnd(
705 Tok.getLocation(),
706 reinterpret_cast<Module *>(Tok.getAnnotationValue()));
707 ConsumeAnnotationToken();
708 ImportState = Sema::ModuleImportState::NotACXX20Module;
709 return false;
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);
723 // Late template parsing can begin.
724 Actions.SetLateTemplateParser(LateTemplateParserCallback, nullptr, this);
725 Actions.ActOnEndOfTranslationUnit();
726 //else don't tell Sema that we ended parsing: more input might come.
727 return true;
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;
742 break;
744 default:
745 break;
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))
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.
764 ImportState = Sema::ModuleImportState::NotACXX20Module;
765 else if (ImportState == Sema::ModuleImportState::ImportAllowed)
766 // Non-imports disallow further imports.
767 ImportState = Sema::ModuleImportState::ImportFinished;
768 else if (ImportState ==
769 Sema::ModuleImportState::PrivateFragmentImportAllowed)
770 // Non-imports disallow further imports.
771 ImportState = Sema::ModuleImportState::PrivateFragmentImportFinished;
773 return false;
776 /// ParseExternalDeclaration:
778 /// The `Attrs` that are passed in are C++11 attributes and appertain to the
779 /// declaration.
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
798 /// [C++11] empty-declaration:
799 /// ';'
801 /// [C++0x/GNU] 'extern' 'template' declaration
803 /// [C++20] module-import-declaration
805 Parser::DeclGroupPtrTy
806 Parser::ParseExternalDeclaration(ParsedAttributes &Attrs,
807 ParsedAttributes &DeclSpecAttrs,
808 ParsingDeclSpec *DS) {
809 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
810 ParenBraceBracketBalancer BalancerRAIIObj(*this);
812 if (PP.isCodeCompletionReached()) {
813 cutOffParsing();
814 return nullptr;
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: {
864 AccessSpecifier AS = AS_none;
865 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
867 case tok::annot_pragma_openacc:
868 return ParseOpenACCDirectiveDecl();
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);
903 case tok::kw_asm: {
904 ProhibitAttributes(Attrs);
906 SourceLocation StartLoc = Tok.getLocation();
907 SourceLocation EndLoc;
909 ExprResult Result(ParseSimpleAsm(/*ForAsmLabel*/ false, &EndLoc));
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);
920 ExpectAndConsume(tok::semi, diag::err_expected_after,
921 "top-level asm block");
923 if (Result.isInvalid())
924 return nullptr;
925 SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
926 break;
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;
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.
943 Actions.CodeCompletion().CodeCompleteObjCMethodDecl(
944 getCurScope(),
945 /*IsInstanceMethod=*/std::nullopt,
946 /*ReturnType=*/nullptr);
949 SemaCodeCompletion::ParserCompletionContext PCC;
950 if (CurParsedObjCImpl) {
951 PCC = SemaCodeCompletion::PCC_ObjCImplementation;
952 } else if (PP.isIncrementalProcessingEnabled()) {
953 PCC = SemaCodeCompletion::PCC_TopLevelOrExpression;
954 } else {
955 PCC = SemaCodeCompletion::PCC_Namespace;
957 Actions.CodeCompletion().CodeCompleteOrdinaryName(getCurScope(), PCC);
958 return nullptr;
959 case tok::kw_import: {
960 Sema::ModuleImportState IS = Sema::ModuleImportState::NotACXX20Module;
961 if (getLangOpts().CPlusPlusModules) {
962 llvm_unreachable("not expecting a c++20 import here");
963 ProhibitAttributes(Attrs);
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;
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.
984 SourceLocation DeclEnd;
985 return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
986 DeclSpecAttrs);
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);
996 goto dont_know;
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);
1008 goto dont_know;
1010 case tok::kw_inline:
1011 if (getLangOpts().CPlusPlus) {
1012 tok::TokenKind NextKind = NextToken().getKind();
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);
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);
1031 goto dont_know;
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);
1045 goto dont_know;
1047 case tok::kw___if_exists:
1048 case tok::kw___if_not_exists:
1049 ParseMicrosoftIfExistsExternalDeclaration();
1050 return nullptr;
1052 case tok::kw_module:
1053 Diag(Tok, diag::err_unexpected_module_decl);
1054 SkipUntil(tok::semi);
1055 return nullptr;
1057 default:
1058 dont_know:
1059 if (Tok.isEditorPlaceholder()) {
1060 ConsumeToken();
1061 return nullptr;
1063 if (getLangOpts().IncrementalExtensions &&
1064 !isDeclarationStatement(/*DisambiguatingWithExpression=*/true))
1065 return ParseTopLevelStmtDecl();
1067 // We can't tell whether this is a function-definition or declaration yet.
1068 if (!SingleDecl)
1069 return ParseDeclarationOrFunctionDefinition(Attrs, DeclSpecAttrs, DS);
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);
1077 /// Determine whether the current token, if it occurs after a
1078 /// declarator, continues a declaration or declaration list.
1079 bool 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;
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++]
1096 /// Determine whether the current token, if it occurs after a
1097 /// declarator, indicates the start of a function definition.
1098 bool 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;
1103 // Handle K&R C argument lists: int X(f) int f; {}
1104 if (!getLangOpts().CPlusPlus &&
1105 Declarator.getFunctionTypeInfo().isKNRPrototype())
1106 return isDeclarationSpecifier(ImplicitTypenameContext::No);
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);
1113 return Tok.is(tok::colon) || // X() : Base() {} (used for ctors)
1114 Tok.is(tok::kw_try); // X() try { ... }
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.
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
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]
1133 Parser::DeclGroupPtrTy Parser::ParseDeclOrFunctionDefInternal(
1134 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1135 ParsingDeclSpec &DS, AccessSpecifier AS) {
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);
1145 ParsedTemplateInfo TemplateInfo;
1146 MaybeParseMicrosoftAttributes(DS.getAttributes());
1147 // Parse the common declaration-specifiers piece.
1148 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
1149 DeclSpecContext::DSC_top_level);
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;
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) {
1163 case DeclSpec::TST_class:
1164 return 5;
1165 case DeclSpec::TST_struct:
1166 return 6;
1167 case DeclSpec::TST_union:
1168 return 5;
1169 case DeclSpec::TST_enum:
1170 return 4;
1171 case DeclSpec::TST_interface:
1172 return 9;
1173 default:
1174 llvm_unreachable("we only expect to get the length of the class/struct/union/enum");
1178 // Suggest correct location to fix '[[attrib]] struct' to 'struct [[attrib]]'
1179 SourceLocation CorrectLocationForAttributes =
1180 DeclSpec::isDeclRep(DS.getTypeSpecType())
1181 ? DS.getTypeSpecTypeLoc().getLocWithOffset(
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);
1195 return Actions.ConvertDeclToDeclGroup(TheDecl);
1198 if (DS.hasTagDefinition())
1199 Actions.ActOnDefinedDeclarationSpecifier(DS.getRepAsDecl());
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;
1214 DS.abort();
1215 DS.takeAttributesFrom(Attrs);
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;
1223 if (Tok.isObjCAtKeyword(tok::objc_protocol))
1224 return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
1226 if (Tok.isObjCAtKeyword(tok::objc_implementation))
1227 return ParseObjCAtImplementationDeclaration(AtLoc, DS.getAttributes());
1229 return Actions.ConvertDeclToDeclGroup(
1230 ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
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() &&
1237 DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
1238 DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
1239 ProhibitAttributes(Attrs);
1240 Decl *TheDecl = ParseLinkage(DS, DeclaratorContext::File);
1241 return Actions.ConvertDeclToDeclGroup(TheDecl);
1244 return ParseDeclGroup(DS, DeclaratorContext::File, Attrs, TemplateInfo);
1247 Parser::DeclGroupPtrTy Parser::ParseDeclarationOrFunctionDefinition(
1248 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1249 ParsingDeclSpec *DS, AccessSpecifier AS) {
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());
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);
1266 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, PDS, AS);
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.
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
1284 Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
1285 const ParsedTemplateInfo &TemplateInfo,
1286 LateParsedAttrList *LateParsedAttrs) {
1287 llvm::TimeTraceScope TimeScope("ParseFunctionDefinition", [&]() {
1288 return Actions.GetNameForDeclarator(D).getName().getAsString();
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);
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());
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);
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);
1326 // Skip over garbage, until we get to '{'. Don't eat the '{'.
1327 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
1329 // If we didn't find the '{', bail out.
1330 if (Tok.isNot(tok::l_brace))
1331 return nullptr;
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;
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);
1349 ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1350 Scope::CompoundStmtScope);
1351 Scope *ParentScope = getCurScope()->getParent();
1353 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
1354 Decl *DP = Actions.HandleDeclarator(ParentScope, D,
1355 TemplateParameterLists);
1356 D.complete(DP);
1357 D.getMutableDeclSpec().abort();
1359 if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) &&
1360 trySkippingFunctionBody()) {
1361 BodyScope.Exit();
1362 return Actions.ActOnSkippedFunctionBody(DP);
1365 CachedTokens Toks;
1366 LexTemplateFunctionForLateParsing(Toks);
1368 if (DP) {
1369 FunctionDecl *FnD = DP->getAsFunction();
1370 Actions.CheckForFunctionRedefinition(FnD);
1371 Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
1373 return DP;
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 |
1381 Scope::CompoundStmtScope);
1382 Scope *ParentScope = getCurScope()->getParent();
1384 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
1385 Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1386 MultiTemplateParamsArg());
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;
1395 // FIXME: Should we really fall through here?
1398 // Enter a scope for the function body.
1399 ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1400 Scope::CompoundStmtScope);
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;
1405 Sema::FnBodyKind BodyKind = Sema::FnBodyKind::Other;
1406 SourceLocation KWLoc;
1407 if (TryConsumeToken(tok::equal)) {
1408 assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
1410 if (TryConsumeToken(tok::kw_delete, KWLoc)) {
1411 Diag(KWLoc, getLangOpts().CPlusPlus11
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)) {
1418 Diag(KWLoc, getLangOpts().CPlusPlus11
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'");
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);
1439 Sema::FPFeaturesStateRAII SaveFPFeatures(Actions);
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
1447 : MultiTemplateParamsArg(),
1448 &SkipBody, BodyKind);
1450 if (SkipBody.ShouldSkip) {
1451 // Do NOT enter SkipFunctionBody if we already consumed the tokens.
1452 if (BodyKind == Sema::FnBodyKind::Other)
1453 SkipFunctionBody();
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.
1459 // Do not call PopExpressionEvaluationContext() if it is a lambda because
1460 // one is already popped when finishing the lambda in BuildLambdaExpr().
1462 // FIXME: It looks not easy to balance PushExpressionEvaluationContext()
1463 // and PopExpressionEvaluationContext().
1464 if (!isLambdaCallOperator(dyn_cast_if_present<FunctionDecl>(Res)))
1465 Actions.PopExpressionEvaluationContext();
1466 return Res;
1469 // Break out of the ParsingDeclarator context before we parse the body.
1470 D.complete(Res);
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();
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;
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);
1492 if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&
1493 trySkippingFunctionBody()) {
1494 BodyScope.Exit();
1495 Actions.ActOnSkippedFunctionBody(Res);
1496 return Actions.ActOnFinishFunctionBody(Res, nullptr, false);
1499 if (Tok.is(tok::kw_try))
1500 return ParseFunctionTryBlock(Res, BodyScope);
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);
1507 // Recover from error.
1508 if (!Tok.is(tok::l_brace)) {
1509 BodyScope.Exit();
1510 Actions.ActOnFinishFunctionBody(Res, nullptr);
1511 return Res;
1513 } else
1514 Actions.ActOnDefaultCtorInitializers(Res);
1516 // Late attributes are parsed in the same scope as the function body.
1517 if (LateParsedAttrs)
1518 ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
1520 return ParseFunctionStatementBody(Res, BodyScope);
1523 void Parser::SkipFunctionBody() {
1524 if (Tok.is(tok::equal)) {
1525 SkipUntil(tok::semi);
1526 return;
1529 bool IsFunctionTryBlock = Tok.is(tok::kw_try);
1530 if (IsFunctionTryBlock)
1531 ConsumeToken();
1533 CachedTokens Skipped;
1534 if (ConsumeAndStoreFunctionPrologue(Skipped))
1535 SkipMalformedDecl();
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);
1545 /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
1546 /// types for a function with a K&R-style identifier list for arguments.
1547 void Parser::ParseKNRParamDeclarations(Declarator &D) {
1548 // We know that the top-level of this declarator is a function.
1549 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1551 // Enter function-declaration scope, limiting any declarators to the
1552 // function prototype scope, including parameter declarators.
1553 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1554 Scope::FunctionDeclarationScope | Scope::DeclScope);
1556 // Read all the argument declarations.
1557 while (isDeclarationSpecifier(ImplicitTypenameContext::No)) {
1558 SourceLocation DSStart = Tok.getLocation();
1560 // Parse the common declaration-specifiers piece.
1561 DeclSpec DS(AttrFactory);
1562 ParsedTemplateInfo TemplateInfo;
1563 ParseDeclarationSpecifiers(DS, TemplateInfo);
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;
1575 // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
1576 // than register.
1577 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1578 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1579 Diag(DS.getStorageClassSpecLoc(),
1580 diag::err_invalid_storage_class_in_func_decl);
1581 DS.ClearStorageClassSpecs();
1583 if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) {
1584 Diag(DS.getThreadStorageClassSpecLoc(),
1585 diag::err_invalid_storage_class_in_func_decl);
1586 DS.ClearStorageClassSpecs();
1589 // Parse the first declarator attached to this declspec.
1590 Declarator ParmDeclarator(DS, ParsedAttributesView::none(),
1591 DeclaratorContext::KNRTypeList);
1592 ParseDeclarator(ParmDeclarator);
1594 // Handle the full declarator list.
1595 while (true) {
1596 // If attributes are present, parse them.
1597 MaybeParseGNUAttributes(ParmDeclarator);
1599 // Ask the actions module to compute the type for this declarator.
1600 Decl *Param =
1601 Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
1603 if (Param &&
1604 // A missing identifier has already been diagnosed.
1605 ParmDeclarator.getIdentifier()) {
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;
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;
1627 break;
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;
1637 ParmDeclarator.clear();
1639 // Consume the comma.
1640 ParmDeclarator.setCommaLoc(ConsumeToken());
1642 // Parse the next declarator.
1643 ParseDeclarator(ParmDeclarator);
1646 // Consume ';' and continue parsing.
1647 if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
1648 continue;
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);
1656 // The actions module must verify that all arguments were declared.
1657 Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
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.
1667 /// [GNU] asm-string-literal:
1668 /// string-literal
1670 ExprResult Parser::ParseAsmStringLiteral(bool ForAsmLabel) {
1671 if (!isTokenStringLiteral()) {
1672 Diag(Tok, diag::err_expected_string_literal)
1673 << /*Source='in...'*/0 << "'asm'";
1674 return ExprError();
1677 ExprResult AsmString(ParseStringLiteralExpression());
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();
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();
1692 return AsmString;
1695 /// ParseSimpleAsm
1697 /// [GNU] simple-asm-expr:
1698 /// 'asm' '(' asm-string-literal ')'
1700 ExprResult Parser::ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc) {
1701 assert(Tok.is(tok::kw_asm) && "Not an asm!");
1702 SourceLocation Loc = ConsumeToken();
1704 if (isGNUAsmQualifier(Tok)) {
1705 // Remove from the end of 'asm' to the end of the asm qualifier.
1706 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1707 PP.getLocForEndOfToken(Tok.getLocation()));
1708 Diag(Tok, diag::err_global_asm_qualifier_ignored)
1709 << GNUAsmQualifiers::getQualifierName(getGNUAsmQualifier(Tok))
1710 << FixItHint::CreateRemoval(RemovalRange);
1711 ConsumeToken();
1714 BalancedDelimiterTracker T(*this, tok::l_paren);
1715 if (T.consumeOpen()) {
1716 Diag(Tok, diag::err_expected_lparen_after) << "asm";
1717 return ExprError();
1720 ExprResult Result(ParseAsmStringLiteral(ForAsmLabel));
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();
1733 return Result;
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.
1739 TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
1740 assert(tok.is(tok::annot_template_id) && "Expected template-id token");
1741 TemplateIdAnnotation *
1742 Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
1743 return Id;
1746 void 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);
1754 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1755 Tok.setAnnotationRange(SS.getRange());
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);
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.
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).
1774 Parser::AnnotatedNameKind
1775 Parser::TryAnnotateName(CorrectionCandidateCallback *CCC,
1776 ImplicitTypenameContext AllowImplicitTypename) {
1777 assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1779 const bool EnteringContext = false;
1780 const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1782 CXXScopeSpec SS;
1783 if (getLangOpts().CPlusPlus &&
1784 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1785 /*ObjectHasErrors=*/false,
1786 EnteringContext))
1787 return ANK_Error;
1789 if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
1790 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation,
1791 AllowImplicitTypename))
1792 return ANK_Error;
1793 return ANK_Unresolved;
1796 IdentifierInfo *Name = Tok.getIdentifierInfo();
1797 SourceLocation NameLoc = Tok.getLocation();
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;
1810 Token Next = NextToken();
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);
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);
1833 switch (Classification.getKind()) {
1834 case Sema::NC_Error:
1835 return ANK_Error;
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;
1847 case Sema::NC_Unknown:
1848 // It's not something we know about. Leave it unannotated.
1849 break;
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();
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.
1868 SourceLocation IdentifierLoc = ConsumeToken();
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;
1880 Tok.setKind(tok::annot_typename);
1881 setTypeAnnotation(Tok, Ty);
1882 Tok.setAnnotationEndLoc(Tok.getLocation());
1883 Tok.setLocation(BeginLoc);
1884 PP.AnnotateCachedTokens(Tok);
1885 return ANK_Success;
1888 case Sema::NC_OverloadSet:
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;
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;
1912 case Sema::NC_UndeclaredNonType:
1913 case Sema::NC_DependentNonType:
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;
1925 case Sema::NC_TypeTemplate:
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;
1932 [[fallthrough]];
1933 case Sema::NC_Concept:
1934 case Sema::NC_VarTemplate:
1935 case Sema::NC_FunctionTemplate:
1936 case Sema::NC_UndeclaredTemplate: {
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();
1942 UnqualifiedId Id;
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;
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;
1962 bool 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)
1968 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
1969 Tok.setKind(tok::identifier);
1970 return true;
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).
1991 /// This returns true if an error occurred.
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.
1995 bool Parser::TryAnnotateTypeOrScopeToken(
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!");
2004 if (Tok.is(tok::kw_typename)) {
2005 // MSVC lets you do stuff like:
2006 // typename typedef T_::D D;
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;
2022 // Parse a C++ typename-specifier, e.g., "typename T::type".
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;
2051 if (Tok.isEditorPlaceholder())
2052 return true;
2054 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
2055 return true;
2058 bool TemplateKWPresent = false;
2059 if (Tok.is(tok::kw_template)) {
2060 ConsumeToken();
2061 TemplateKWPresent = true;
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;
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;
2082 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
2083 TemplateId->NumArgs);
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;
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;
2107 // Remembers whether the token was originally a scope annotation.
2108 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
2110 CXXScopeSpec SS;
2111 if (getLangOpts().CPlusPlus)
2112 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
2113 /*ObjectHasErrors=*/false,
2114 /*EnteringContext*/ false))
2115 return true;
2117 return TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation,
2118 AllowImplicitTypename);
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.
2124 bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(
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();
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.
2145 SourceLocation IdentifierLoc = ConsumeToken();
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;
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);
2161 Tok.setAnnotationEndLoc(Tok.getLocation());
2162 Tok.setLocation(BeginLoc);
2164 // In case the tokens were cached, have Preprocessor replace
2165 // them with the annotation token.
2166 PP.AnnotateCachedTokens(Tok);
2167 return false;
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;
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;
2182 UnqualifiedId TemplateName;
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;
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.
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;
2225 if (SS.isEmpty())
2226 return false;
2228 // A C++ scope specifier that isn't followed by a typename.
2229 AnnotateScopeToken(SS, IsNewScope);
2230 return false;
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.
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.
2239 bool 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!");
2244 CXXScopeSpec SS;
2245 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
2246 /*ObjectHasErrors=*/false,
2247 EnteringContext))
2248 return true;
2249 if (SS.isEmpty())
2250 return false;
2252 AnnotateScopeToken(SS, true);
2253 return false;
2256 bool 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
2277 << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
2278 [[fallthrough]];
2279 case tok::equal:
2280 return true;
2284 SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
2285 assert(Tok.is(tok::code_completion));
2286 PrevTokLocation = Tok.getLocation();
2288 for (Scope *S = getCurScope(); S; S = S->getParent()) {
2289 if (S->isFunctionScope()) {
2290 cutOffParsing();
2291 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2292 getCurScope(), SemaCodeCompletion::PCC_RecoveryInFunction);
2293 return PrevTokLocation;
2296 if (S->isClassScope()) {
2297 cutOffParsing();
2298 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2299 getCurScope(), SemaCodeCompletion::PCC_Class);
2300 return PrevTokLocation;
2304 cutOffParsing();
2305 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2306 getCurScope(), SemaCodeCompletion::PCC_Namespace);
2307 return PrevTokLocation;
2310 // Code-completion pass-through functions
2312 void Parser::CodeCompleteDirective(bool InConditional) {
2313 Actions.CodeCompletion().CodeCompletePreprocessorDirective(InConditional);
2316 void Parser::CodeCompleteInConditionalExclusion() {
2317 Actions.CodeCompletion().CodeCompleteInPreprocessorConditionalExclusion(
2318 getCurScope());
2321 void Parser::CodeCompleteMacroName(bool IsDefinition) {
2322 Actions.CodeCompletion().CodeCompletePreprocessorMacroName(IsDefinition);
2325 void Parser::CodeCompletePreprocessorExpression() {
2326 Actions.CodeCompletion().CodeCompletePreprocessorExpression();
2329 void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
2330 MacroInfo *MacroInfo,
2331 unsigned ArgumentIndex) {
2332 Actions.CodeCompletion().CodeCompletePreprocessorMacroArgument(
2333 getCurScope(), Macro, MacroInfo, ArgumentIndex);
2336 void Parser::CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) {
2337 Actions.CodeCompletion().CodeCompleteIncludedFile(Dir, IsAngled);
2340 void Parser::CodeCompleteNaturalLanguage() {
2341 Actions.CodeCompletion().CodeCompleteNaturalLanguage();
2344 bool 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();
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;
2357 // Parse nested-name-specifier.
2358 if (getLangOpts().CPlusPlus)
2359 ParseOptionalCXXScopeSpecifier(Result.SS, /*ObjectType=*/nullptr,
2360 /*ObjectHasErrors=*/false,
2361 /*EnteringContext=*/false);
2363 // Check nested-name specifier.
2364 if (Result.SS.isInvalid()) {
2365 T.skipToEnd();
2366 return true;
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;
2381 if (T.consumeClose())
2382 return true;
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;
2392 case Sema::IER_DoesNotExist:
2393 Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
2394 break;
2396 case Sema::IER_Dependent:
2397 Result.Behavior = IEB_Dependent;
2398 break;
2400 case Sema::IER_Error:
2401 return true;
2404 return false;
2407 void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
2408 IfExistsCondition Result;
2409 if (ParseMicrosoftIfExistsCondition(Result))
2410 return;
2412 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2413 if (Braces.consumeOpen()) {
2414 Diag(Tok, diag::err_expected) << tok::l_brace;
2415 return;
2418 switch (Result.Behavior) {
2419 case IEB_Parse:
2420 // Parse declarations below.
2421 break;
2423 case IEB_Dependent:
2424 llvm_unreachable("Cannot have a dependent external declaration");
2426 case IEB_Skip:
2427 Braces.skipToEnd();
2428 return;
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());
2441 Braces.consumeClose();
2444 /// Parse a declaration beginning with the 'module' keyword or C++20
2445 /// context-sensitive keyword (optionally preceded by 'export').
2447 /// module-declaration: [C++20]
2448 /// 'export'[opt] 'module' module-name attribute-specifier-seq[opt] ';'
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]
2457 Parser::DeclGroupPtrTy
2458 Parser::ParseModuleDecl(Sema::ModuleImportState &ImportState) {
2459 SourceLocation StartLoc = Tok.getLocation();
2461 Sema::ModuleDeclKind MDK = TryConsumeToken(tok::kw_export)
2462 ? Sema::ModuleDeclKind::Interface
2463 : Sema::ModuleDeclKind::Implementation;
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();
2471 // Attributes appear after the module name, not before.
2472 // FIXME: Suggest moving the attributes later with a fixit.
2473 DiagnoseAndSkipCXX11Attributes();
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;
2483 if (MDK == Sema::ModuleDeclKind::Interface) {
2484 Diag(StartLoc, diag::err_module_fragment_exported)
2485 << /*global*/0 << FixItHint::CreateRemoval(StartLoc);
2487 ImportState = Sema::ModuleImportState::GlobalFragment;
2488 return Actions.ActOnGlobalModuleFragmentDecl(ModuleLoc);
2491 // Parse a private-module-fragment, if present.
2492 if (getLangOpts().CPlusPlusModules && Tok.is(tok::colon) &&
2493 NextToken().is(tok::kw_private)) {
2494 if (MDK == Sema::ModuleDeclKind::Interface) {
2495 Diag(StartLoc, diag::err_module_fragment_exported)
2496 << /*private*/1 << FixItHint::CreateRemoval(StartLoc);
2498 ConsumeToken();
2499 SourceLocation PrivateLoc = ConsumeToken();
2500 DiagnoseAndSkipCXX11Attributes();
2501 ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi);
2502 ImportState = ImportState == Sema::ModuleImportState::ImportAllowed
2503 ? Sema::ModuleImportState::PrivateFragmentImportAllowed
2504 : Sema::ModuleImportState::PrivateFragmentImportFinished;
2505 return Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc);
2508 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
2509 if (ParseModuleName(ModuleLoc, Path, /*IsImport*/ false))
2510 return nullptr;
2512 // Parse the optional module-partition.
2513 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> 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;
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);
2532 ExpectAndConsumeSemi(diag::err_module_expected_semi);
2534 return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, Partition,
2535 ImportState);
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++).
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] ';'
2553 Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
2554 Sema::ModuleImportState &ImportState) {
2555 SourceLocation StartLoc = AtLoc.isInvalid() ? Tok.getLocation() : AtLoc;
2557 SourceLocation ExportLoc;
2558 TryConsumeToken(tok::kw_export, ExportLoc);
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();
2566 // For C++20 modules, we can have "name" or ":Partition name" as valid input.
2567 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
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;
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);
2602 if (PP.hadModuleLoaderFatalFailure()) {
2603 // With a fatal failure in the module loader, we abort parsing.
2604 cutOffParsing();
2605 return nullptr;
2608 // Diagnose mis-imports.
2609 bool SeenError = true;
2610 switch (ImportState) {
2611 case Sema::ModuleImportState::ImportAllowed:
2612 SeenError = false;
2613 break;
2614 case Sema::ModuleImportState::FirstDecl:
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.
2617 ImportState = Sema::ModuleImportState::NotACXX20Module;
2618 [[fallthrough]];
2619 case Sema::ModuleImportState::NotACXX20Module:
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;
2626 case Sema::ModuleImportState::GlobalFragment:
2627 case Sema::ModuleImportState::PrivateFragmentImportAllowed:
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 !=
2635 Module::ModuleKind::ModuleHeaderUnit))
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;
2642 case Sema::ModuleImportState::ImportFinished:
2643 case Sema::ModuleImportState::PrivateFragmentImportFinished:
2644 if (getLangOpts().CPlusPlusModules)
2645 Diag(ImportLoc, diag::err_import_not_allowed_here);
2646 else
2647 SeenError = false;
2648 break;
2650 if (SeenError) {
2651 ExpectAndConsumeSemi(diag::err_module_expected_semi);
2652 return nullptr;
2655 DeclResult Import;
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;
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);
2676 return Import.get();
2679 /// Parse a C++ / Objective-C module name (both forms use the same
2680 /// grammar).
2682 /// module-name:
2683 /// module-name-qualifier[opt] identifier
2684 /// module-name-qualifier:
2685 /// module-name-qualifier[opt] identifier '.'
2686 bool 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;
2699 Diag(Tok, diag::err_module_expected_ident) << IsImport;
2700 SkipUntil(tok::semi);
2701 return true;
2704 // Record this part of the module path.
2705 Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
2706 ConsumeToken();
2708 if (Tok.isNot(tok::period))
2709 return false;
2711 ConsumeToken();
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.
2719 bool 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;
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.
2749 Actions.ActOnAnnotModuleInclude(
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;
2759 return false;
2762 void 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();
2771 bool 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;
2779 bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
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;
2789 if (getDepth() < P.getLangOpts().BracketDepth)
2790 return false;
2792 return diagnoseOverflow();
2795 bool BalancedDelimiterTracker::diagnoseMissingClose() {
2796 assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
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;
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,
2809 Parser::StopAtSemi | Parser::StopBeforeMatch) &&
2810 P.Tok.is(Close))
2811 LClose = P.ConsumeAnyToken();
2812 return true;
2815 void BalancedDelimiterTracker::skipToEnd() {
2816 P.SkipUntil(Close, Parser::StopBeforeMatch);
2817 consumeClose();