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