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