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