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