Debian Codegraph @

clang/lib/Parse/Parser.cpp

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