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