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