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

source code of clang/lib/Parse/Parser.cpp