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