File: | build/source/clang/lib/Parse/ParseExprCXX.cpp |
Warning: | line 2126, column 5 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===// | |||
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 Expression parsing implementation for C++. | |||
10 | // | |||
11 | //===----------------------------------------------------------------------===// | |||
12 | #include "clang/AST/ASTContext.h" | |||
13 | #include "clang/AST/Decl.h" | |||
14 | #include "clang/AST/DeclTemplate.h" | |||
15 | #include "clang/AST/ExprCXX.h" | |||
16 | #include "clang/Basic/PrettyStackTrace.h" | |||
17 | #include "clang/Basic/TokenKinds.h" | |||
18 | #include "clang/Lex/LiteralSupport.h" | |||
19 | #include "clang/Parse/ParseDiagnostic.h" | |||
20 | #include "clang/Parse/Parser.h" | |||
21 | #include "clang/Parse/RAIIObjectsForParser.h" | |||
22 | #include "clang/Sema/DeclSpec.h" | |||
23 | #include "clang/Sema/ParsedTemplate.h" | |||
24 | #include "clang/Sema/Scope.h" | |||
25 | #include "llvm/Support/Compiler.h" | |||
26 | #include "llvm/Support/ErrorHandling.h" | |||
27 | #include <numeric> | |||
28 | ||||
29 | using namespace clang; | |||
30 | ||||
31 | static int SelectDigraphErrorMessage(tok::TokenKind Kind) { | |||
32 | switch (Kind) { | |||
33 | // template name | |||
34 | case tok::unknown: return 0; | |||
35 | // casts | |||
36 | case tok::kw_addrspace_cast: return 1; | |||
37 | case tok::kw_const_cast: return 2; | |||
38 | case tok::kw_dynamic_cast: return 3; | |||
39 | case tok::kw_reinterpret_cast: return 4; | |||
40 | case tok::kw_static_cast: return 5; | |||
41 | default: | |||
42 | llvm_unreachable("Unknown type for digraph error message.")::llvm::llvm_unreachable_internal("Unknown type for digraph error message." , "clang/lib/Parse/ParseExprCXX.cpp", 42); | |||
43 | } | |||
44 | } | |||
45 | ||||
46 | // Are the two tokens adjacent in the same source file? | |||
47 | bool Parser::areTokensAdjacent(const Token &First, const Token &Second) { | |||
48 | SourceManager &SM = PP.getSourceManager(); | |||
49 | SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation()); | |||
50 | SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength()); | |||
51 | return FirstEnd == SM.getSpellingLoc(Second.getLocation()); | |||
52 | } | |||
53 | ||||
54 | // Suggest fixit for "<::" after a cast. | |||
55 | static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken, | |||
56 | Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) { | |||
57 | // Pull '<:' and ':' off token stream. | |||
58 | if (!AtDigraph) | |||
59 | PP.Lex(DigraphToken); | |||
60 | PP.Lex(ColonToken); | |||
61 | ||||
62 | SourceRange Range; | |||
63 | Range.setBegin(DigraphToken.getLocation()); | |||
64 | Range.setEnd(ColonToken.getLocation()); | |||
65 | P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph) | |||
66 | << SelectDigraphErrorMessage(Kind) | |||
67 | << FixItHint::CreateReplacement(Range, "< ::"); | |||
68 | ||||
69 | // Update token information to reflect their change in token type. | |||
70 | ColonToken.setKind(tok::coloncolon); | |||
71 | ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1)); | |||
72 | ColonToken.setLength(2); | |||
73 | DigraphToken.setKind(tok::less); | |||
74 | DigraphToken.setLength(1); | |||
75 | ||||
76 | // Push new tokens back to token stream. | |||
77 | PP.EnterToken(ColonToken, /*IsReinject*/ true); | |||
78 | if (!AtDigraph) | |||
79 | PP.EnterToken(DigraphToken, /*IsReinject*/ true); | |||
80 | } | |||
81 | ||||
82 | // Check for '<::' which should be '< ::' instead of '[:' when following | |||
83 | // a template name. | |||
84 | void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType, | |||
85 | bool EnteringContext, | |||
86 | IdentifierInfo &II, CXXScopeSpec &SS) { | |||
87 | if (!Next.is(tok::l_square) || Next.getLength() != 2) | |||
88 | return; | |||
89 | ||||
90 | Token SecondToken = GetLookAheadToken(2); | |||
91 | if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken)) | |||
92 | return; | |||
93 | ||||
94 | TemplateTy Template; | |||
95 | UnqualifiedId TemplateName; | |||
96 | TemplateName.setIdentifier(&II, Tok.getLocation()); | |||
97 | bool MemberOfUnknownSpecialization; | |||
98 | if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false, | |||
99 | TemplateName, ObjectType, EnteringContext, | |||
100 | Template, MemberOfUnknownSpecialization)) | |||
101 | return; | |||
102 | ||||
103 | FixDigraph(*this, PP, Next, SecondToken, tok::unknown, | |||
104 | /*AtDigraph*/false); | |||
105 | } | |||
106 | ||||
107 | /// Parse global scope or nested-name-specifier if present. | |||
108 | /// | |||
109 | /// Parses a C++ global scope specifier ('::') or nested-name-specifier (which | |||
110 | /// may be preceded by '::'). Note that this routine will not parse ::new or | |||
111 | /// ::delete; it will just leave them in the token stream. | |||
112 | /// | |||
113 | /// '::'[opt] nested-name-specifier | |||
114 | /// '::' | |||
115 | /// | |||
116 | /// nested-name-specifier: | |||
117 | /// type-name '::' | |||
118 | /// namespace-name '::' | |||
119 | /// nested-name-specifier identifier '::' | |||
120 | /// nested-name-specifier 'template'[opt] simple-template-id '::' | |||
121 | /// | |||
122 | /// | |||
123 | /// \param SS the scope specifier that will be set to the parsed | |||
124 | /// nested-name-specifier (or empty) | |||
125 | /// | |||
126 | /// \param ObjectType if this nested-name-specifier is being parsed following | |||
127 | /// the "." or "->" of a member access expression, this parameter provides the | |||
128 | /// type of the object whose members are being accessed. | |||
129 | /// | |||
130 | /// \param ObjectHadErrors if this unqualified-id occurs within a member access | |||
131 | /// expression, indicates whether the original subexpressions had any errors. | |||
132 | /// When true, diagnostics for missing 'template' keyword will be supressed. | |||
133 | /// | |||
134 | /// \param EnteringContext whether we will be entering into the context of | |||
135 | /// the nested-name-specifier after parsing it. | |||
136 | /// | |||
137 | /// \param MayBePseudoDestructor When non-NULL, points to a flag that | |||
138 | /// indicates whether this nested-name-specifier may be part of a | |||
139 | /// pseudo-destructor name. In this case, the flag will be set false | |||
140 | /// if we don't actually end up parsing a destructor name. Moreover, | |||
141 | /// if we do end up determining that we are parsing a destructor name, | |||
142 | /// the last component of the nested-name-specifier is not parsed as | |||
143 | /// part of the scope specifier. | |||
144 | /// | |||
145 | /// \param IsTypename If \c true, this nested-name-specifier is known to be | |||
146 | /// part of a type name. This is used to improve error recovery. | |||
147 | /// | |||
148 | /// \param LastII When non-NULL, points to an IdentifierInfo* that will be | |||
149 | /// filled in with the leading identifier in the last component of the | |||
150 | /// nested-name-specifier, if any. | |||
151 | /// | |||
152 | /// \param OnlyNamespace If true, only considers namespaces in lookup. | |||
153 | /// | |||
154 | /// | |||
155 | /// \returns true if there was an error parsing a scope specifier | |||
156 | bool Parser::ParseOptionalCXXScopeSpecifier( | |||
157 | CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, | |||
158 | bool EnteringContext, bool *MayBePseudoDestructor, bool IsTypename, | |||
159 | IdentifierInfo **LastII, bool OnlyNamespace, bool InUsingDeclaration) { | |||
160 | assert(getLangOpts().CPlusPlus &&(static_cast <bool> (getLangOpts().CPlusPlus && "Call sites of this function should be guarded by checking for C++" ) ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"Call sites of this function should be guarded by checking for C++\"" , "clang/lib/Parse/ParseExprCXX.cpp", 161, __extension__ __PRETTY_FUNCTION__ )) | |||
161 | "Call sites of this function should be guarded by checking for C++")(static_cast <bool> (getLangOpts().CPlusPlus && "Call sites of this function should be guarded by checking for C++" ) ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"Call sites of this function should be guarded by checking for C++\"" , "clang/lib/Parse/ParseExprCXX.cpp", 161, __extension__ __PRETTY_FUNCTION__ )); | |||
162 | ||||
163 | if (Tok.is(tok::annot_cxxscope)) { | |||
164 | assert(!LastII && "want last identifier but have already annotated scope")(static_cast <bool> (!LastII && "want last identifier but have already annotated scope" ) ? void (0) : __assert_fail ("!LastII && \"want last identifier but have already annotated scope\"" , "clang/lib/Parse/ParseExprCXX.cpp", 164, __extension__ __PRETTY_FUNCTION__ )); | |||
165 | assert(!MayBePseudoDestructor && "unexpected annot_cxxscope")(static_cast <bool> (!MayBePseudoDestructor && "unexpected annot_cxxscope" ) ? void (0) : __assert_fail ("!MayBePseudoDestructor && \"unexpected annot_cxxscope\"" , "clang/lib/Parse/ParseExprCXX.cpp", 165, __extension__ __PRETTY_FUNCTION__ )); | |||
166 | Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(), | |||
167 | Tok.getAnnotationRange(), | |||
168 | SS); | |||
169 | ConsumeAnnotationToken(); | |||
170 | return false; | |||
171 | } | |||
172 | ||||
173 | // Has to happen before any "return false"s in this function. | |||
174 | bool CheckForDestructor = false; | |||
175 | if (MayBePseudoDestructor && *MayBePseudoDestructor) { | |||
176 | CheckForDestructor = true; | |||
177 | *MayBePseudoDestructor = false; | |||
178 | } | |||
179 | ||||
180 | if (LastII) | |||
181 | *LastII = nullptr; | |||
182 | ||||
183 | bool HasScopeSpecifier = false; | |||
184 | ||||
185 | if (Tok.is(tok::coloncolon)) { | |||
186 | // ::new and ::delete aren't nested-name-specifiers. | |||
187 | tok::TokenKind NextKind = NextToken().getKind(); | |||
188 | if (NextKind == tok::kw_new || NextKind == tok::kw_delete) | |||
189 | return false; | |||
190 | ||||
191 | if (NextKind == tok::l_brace) { | |||
192 | // It is invalid to have :: {, consume the scope qualifier and pretend | |||
193 | // like we never saw it. | |||
194 | Diag(ConsumeToken(), diag::err_expected) << tok::identifier; | |||
195 | } else { | |||
196 | // '::' - Global scope qualifier. | |||
197 | if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS)) | |||
198 | return true; | |||
199 | ||||
200 | HasScopeSpecifier = true; | |||
201 | } | |||
202 | } | |||
203 | ||||
204 | if (Tok.is(tok::kw___super)) { | |||
205 | SourceLocation SuperLoc = ConsumeToken(); | |||
206 | if (!Tok.is(tok::coloncolon)) { | |||
207 | Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super); | |||
208 | return true; | |||
209 | } | |||
210 | ||||
211 | return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS); | |||
212 | } | |||
213 | ||||
214 | if (!HasScopeSpecifier && | |||
215 | Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) { | |||
216 | DeclSpec DS(AttrFactory); | |||
217 | SourceLocation DeclLoc = Tok.getLocation(); | |||
218 | SourceLocation EndLoc = ParseDecltypeSpecifier(DS); | |||
219 | ||||
220 | SourceLocation CCLoc; | |||
221 | // Work around a standard defect: 'decltype(auto)::' is not a | |||
222 | // nested-name-specifier. | |||
223 | if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto || | |||
224 | !TryConsumeToken(tok::coloncolon, CCLoc)) { | |||
225 | AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc); | |||
226 | return false; | |||
227 | } | |||
228 | ||||
229 | if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc)) | |||
230 | SS.SetInvalid(SourceRange(DeclLoc, CCLoc)); | |||
231 | ||||
232 | HasScopeSpecifier = true; | |||
233 | } | |||
234 | ||||
235 | // Preferred type might change when parsing qualifiers, we need the original. | |||
236 | auto SavedType = PreferredType; | |||
237 | while (true) { | |||
238 | if (HasScopeSpecifier) { | |||
239 | if (Tok.is(tok::code_completion)) { | |||
240 | cutOffParsing(); | |||
241 | // Code completion for a nested-name-specifier, where the code | |||
242 | // completion token follows the '::'. | |||
243 | Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext, | |||
244 | InUsingDeclaration, ObjectType.get(), | |||
245 | SavedType.get(SS.getBeginLoc())); | |||
246 | // Include code completion token into the range of the scope otherwise | |||
247 | // when we try to annotate the scope tokens the dangling code completion | |||
248 | // token will cause assertion in | |||
249 | // Preprocessor::AnnotatePreviousCachedTokens. | |||
250 | SS.setEndLoc(Tok.getLocation()); | |||
251 | return true; | |||
252 | } | |||
253 | ||||
254 | // C++ [basic.lookup.classref]p5: | |||
255 | // If the qualified-id has the form | |||
256 | // | |||
257 | // ::class-name-or-namespace-name::... | |||
258 | // | |||
259 | // the class-name-or-namespace-name is looked up in global scope as a | |||
260 | // class-name or namespace-name. | |||
261 | // | |||
262 | // To implement this, we clear out the object type as soon as we've | |||
263 | // seen a leading '::' or part of a nested-name-specifier. | |||
264 | ObjectType = nullptr; | |||
265 | } | |||
266 | ||||
267 | // nested-name-specifier: | |||
268 | // nested-name-specifier 'template'[opt] simple-template-id '::' | |||
269 | ||||
270 | // Parse the optional 'template' keyword, then make sure we have | |||
271 | // 'identifier <' after it. | |||
272 | if (Tok.is(tok::kw_template)) { | |||
273 | // If we don't have a scope specifier or an object type, this isn't a | |||
274 | // nested-name-specifier, since they aren't allowed to start with | |||
275 | // 'template'. | |||
276 | if (!HasScopeSpecifier && !ObjectType) | |||
277 | break; | |||
278 | ||||
279 | TentativeParsingAction TPA(*this); | |||
280 | SourceLocation TemplateKWLoc = ConsumeToken(); | |||
281 | ||||
282 | UnqualifiedId TemplateName; | |||
283 | if (Tok.is(tok::identifier)) { | |||
284 | // Consume the identifier. | |||
285 | TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); | |||
286 | ConsumeToken(); | |||
287 | } else if (Tok.is(tok::kw_operator)) { | |||
288 | // We don't need to actually parse the unqualified-id in this case, | |||
289 | // because a simple-template-id cannot start with 'operator', but | |||
290 | // go ahead and parse it anyway for consistency with the case where | |||
291 | // we already annotated the template-id. | |||
292 | if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, | |||
293 | TemplateName)) { | |||
294 | TPA.Commit(); | |||
295 | break; | |||
296 | } | |||
297 | ||||
298 | if (TemplateName.getKind() != UnqualifiedIdKind::IK_OperatorFunctionId && | |||
299 | TemplateName.getKind() != UnqualifiedIdKind::IK_LiteralOperatorId) { | |||
300 | Diag(TemplateName.getSourceRange().getBegin(), | |||
301 | diag::err_id_after_template_in_nested_name_spec) | |||
302 | << TemplateName.getSourceRange(); | |||
303 | TPA.Commit(); | |||
304 | break; | |||
305 | } | |||
306 | } else { | |||
307 | TPA.Revert(); | |||
308 | break; | |||
309 | } | |||
310 | ||||
311 | // If the next token is not '<', we have a qualified-id that refers | |||
312 | // to a template name, such as T::template apply, but is not a | |||
313 | // template-id. | |||
314 | if (Tok.isNot(tok::less)) { | |||
315 | TPA.Revert(); | |||
316 | break; | |||
317 | } | |||
318 | ||||
319 | // Commit to parsing the template-id. | |||
320 | TPA.Commit(); | |||
321 | TemplateTy Template; | |||
322 | TemplateNameKind TNK = Actions.ActOnTemplateName( | |||
323 | getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType, | |||
324 | EnteringContext, Template, /*AllowInjectedClassName*/ true); | |||
325 | if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc, | |||
326 | TemplateName, false)) | |||
327 | return true; | |||
328 | ||||
329 | continue; | |||
330 | } | |||
331 | ||||
332 | if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) { | |||
333 | // We have | |||
334 | // | |||
335 | // template-id '::' | |||
336 | // | |||
337 | // So we need to check whether the template-id is a simple-template-id of | |||
338 | // the right kind (it should name a type or be dependent), and then | |||
339 | // convert it into a type within the nested-name-specifier. | |||
340 | TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); | |||
341 | if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) { | |||
342 | *MayBePseudoDestructor = true; | |||
343 | return false; | |||
344 | } | |||
345 | ||||
346 | if (LastII) | |||
347 | *LastII = TemplateId->Name; | |||
348 | ||||
349 | // Consume the template-id token. | |||
350 | ConsumeAnnotationToken(); | |||
351 | ||||
352 | assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!")(static_cast <bool> (Tok.is(tok::coloncolon) && "NextToken() not working properly!") ? void (0) : __assert_fail ("Tok.is(tok::coloncolon) && \"NextToken() not working properly!\"" , "clang/lib/Parse/ParseExprCXX.cpp", 352, __extension__ __PRETTY_FUNCTION__ )); | |||
353 | SourceLocation CCLoc = ConsumeToken(); | |||
354 | ||||
355 | HasScopeSpecifier = true; | |||
356 | ||||
357 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), | |||
358 | TemplateId->NumArgs); | |||
359 | ||||
360 | if (TemplateId->isInvalid() || | |||
361 | Actions.ActOnCXXNestedNameSpecifier(getCurScope(), | |||
362 | SS, | |||
363 | TemplateId->TemplateKWLoc, | |||
364 | TemplateId->Template, | |||
365 | TemplateId->TemplateNameLoc, | |||
366 | TemplateId->LAngleLoc, | |||
367 | TemplateArgsPtr, | |||
368 | TemplateId->RAngleLoc, | |||
369 | CCLoc, | |||
370 | EnteringContext)) { | |||
371 | SourceLocation StartLoc | |||
372 | = SS.getBeginLoc().isValid()? SS.getBeginLoc() | |||
373 | : TemplateId->TemplateNameLoc; | |||
374 | SS.SetInvalid(SourceRange(StartLoc, CCLoc)); | |||
375 | } | |||
376 | ||||
377 | continue; | |||
378 | } | |||
379 | ||||
380 | // The rest of the nested-name-specifier possibilities start with | |||
381 | // tok::identifier. | |||
382 | if (Tok.isNot(tok::identifier)) | |||
383 | break; | |||
384 | ||||
385 | IdentifierInfo &II = *Tok.getIdentifierInfo(); | |||
386 | ||||
387 | // nested-name-specifier: | |||
388 | // type-name '::' | |||
389 | // namespace-name '::' | |||
390 | // nested-name-specifier identifier '::' | |||
391 | Token Next = NextToken(); | |||
392 | Sema::NestedNameSpecInfo IdInfo(&II, Tok.getLocation(), Next.getLocation(), | |||
393 | ObjectType); | |||
394 | ||||
395 | // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover | |||
396 | // and emit a fixit hint for it. | |||
397 | if (Next.is(tok::colon) && !ColonIsSacred) { | |||
398 | if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, IdInfo, | |||
399 | EnteringContext) && | |||
400 | // If the token after the colon isn't an identifier, it's still an | |||
401 | // error, but they probably meant something else strange so don't | |||
402 | // recover like this. | |||
403 | PP.LookAhead(1).is(tok::identifier)) { | |||
404 | Diag(Next, diag::err_unexpected_colon_in_nested_name_spec) | |||
405 | << FixItHint::CreateReplacement(Next.getLocation(), "::"); | |||
406 | // Recover as if the user wrote '::'. | |||
407 | Next.setKind(tok::coloncolon); | |||
408 | } | |||
409 | } | |||
410 | ||||
411 | if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) { | |||
412 | // It is invalid to have :: {, consume the scope qualifier and pretend | |||
413 | // like we never saw it. | |||
414 | Token Identifier = Tok; // Stash away the identifier. | |||
415 | ConsumeToken(); // Eat the identifier, current token is now '::'. | |||
416 | Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected) | |||
417 | << tok::identifier; | |||
418 | UnconsumeToken(Identifier); // Stick the identifier back. | |||
419 | Next = NextToken(); // Point Next at the '{' token. | |||
420 | } | |||
421 | ||||
422 | if (Next.is(tok::coloncolon)) { | |||
423 | if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) { | |||
424 | *MayBePseudoDestructor = true; | |||
425 | return false; | |||
426 | } | |||
427 | ||||
428 | if (ColonIsSacred) { | |||
429 | const Token &Next2 = GetLookAheadToken(2); | |||
430 | if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) || | |||
431 | Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) { | |||
432 | Diag(Next2, diag::err_unexpected_token_in_nested_name_spec) | |||
433 | << Next2.getName() | |||
434 | << FixItHint::CreateReplacement(Next.getLocation(), ":"); | |||
435 | Token ColonColon; | |||
436 | PP.Lex(ColonColon); | |||
437 | ColonColon.setKind(tok::colon); | |||
438 | PP.EnterToken(ColonColon, /*IsReinject*/ true); | |||
439 | break; | |||
440 | } | |||
441 | } | |||
442 | ||||
443 | if (LastII) | |||
444 | *LastII = &II; | |||
445 | ||||
446 | // We have an identifier followed by a '::'. Lookup this name | |||
447 | // as the name in a nested-name-specifier. | |||
448 | Token Identifier = Tok; | |||
449 | SourceLocation IdLoc = ConsumeToken(); | |||
450 | assert(Tok.isOneOf(tok::coloncolon, tok::colon) &&(static_cast <bool> (Tok.isOneOf(tok::coloncolon, tok:: colon) && "NextToken() not working properly!") ? void (0) : __assert_fail ("Tok.isOneOf(tok::coloncolon, tok::colon) && \"NextToken() not working properly!\"" , "clang/lib/Parse/ParseExprCXX.cpp", 451, __extension__ __PRETTY_FUNCTION__ )) | |||
451 | "NextToken() not working properly!")(static_cast <bool> (Tok.isOneOf(tok::coloncolon, tok:: colon) && "NextToken() not working properly!") ? void (0) : __assert_fail ("Tok.isOneOf(tok::coloncolon, tok::colon) && \"NextToken() not working properly!\"" , "clang/lib/Parse/ParseExprCXX.cpp", 451, __extension__ __PRETTY_FUNCTION__ )); | |||
452 | Token ColonColon = Tok; | |||
453 | SourceLocation CCLoc = ConsumeToken(); | |||
454 | ||||
455 | bool IsCorrectedToColon = false; | |||
456 | bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr; | |||
457 | if (Actions.ActOnCXXNestedNameSpecifier( | |||
458 | getCurScope(), IdInfo, EnteringContext, SS, CorrectionFlagPtr, | |||
459 | OnlyNamespace)) { | |||
460 | // Identifier is not recognized as a nested name, but we can have | |||
461 | // mistyped '::' instead of ':'. | |||
462 | if (CorrectionFlagPtr && IsCorrectedToColon) { | |||
463 | ColonColon.setKind(tok::colon); | |||
464 | PP.EnterToken(Tok, /*IsReinject*/ true); | |||
465 | PP.EnterToken(ColonColon, /*IsReinject*/ true); | |||
466 | Tok = Identifier; | |||
467 | break; | |||
468 | } | |||
469 | SS.SetInvalid(SourceRange(IdLoc, CCLoc)); | |||
470 | } | |||
471 | HasScopeSpecifier = true; | |||
472 | continue; | |||
473 | } | |||
474 | ||||
475 | CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS); | |||
476 | ||||
477 | // nested-name-specifier: | |||
478 | // type-name '<' | |||
479 | if (Next.is(tok::less)) { | |||
480 | ||||
481 | TemplateTy Template; | |||
482 | UnqualifiedId TemplateName; | |||
483 | TemplateName.setIdentifier(&II, Tok.getLocation()); | |||
484 | bool MemberOfUnknownSpecialization; | |||
485 | if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS, | |||
486 | /*hasTemplateKeyword=*/false, | |||
487 | TemplateName, | |||
488 | ObjectType, | |||
489 | EnteringContext, | |||
490 | Template, | |||
491 | MemberOfUnknownSpecialization)) { | |||
492 | // If lookup didn't find anything, we treat the name as a template-name | |||
493 | // anyway. C++20 requires this, and in prior language modes it improves | |||
494 | // error recovery. But before we commit to this, check that we actually | |||
495 | // have something that looks like a template-argument-list next. | |||
496 | if (!IsTypename && TNK == TNK_Undeclared_template && | |||
497 | isTemplateArgumentList(1) == TPResult::False) | |||
498 | break; | |||
499 | ||||
500 | // We have found a template name, so annotate this token | |||
501 | // with a template-id annotation. We do not permit the | |||
502 | // template-id to be translated into a type annotation, | |||
503 | // because some clients (e.g., the parsing of class template | |||
504 | // specializations) still want to see the original template-id | |||
505 | // token, and it might not be a type at all (e.g. a concept name in a | |||
506 | // type-constraint). | |||
507 | ConsumeToken(); | |||
508 | if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(), | |||
509 | TemplateName, false)) | |||
510 | return true; | |||
511 | continue; | |||
512 | } | |||
513 | ||||
514 | if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) && | |||
515 | (IsTypename || isTemplateArgumentList(1) == TPResult::True)) { | |||
516 | // If we had errors before, ObjectType can be dependent even without any | |||
517 | // templates. Do not report missing template keyword in that case. | |||
518 | if (!ObjectHadErrors) { | |||
519 | // We have something like t::getAs<T>, where getAs is a | |||
520 | // member of an unknown specialization. However, this will only | |||
521 | // parse correctly as a template, so suggest the keyword 'template' | |||
522 | // before 'getAs' and treat this as a dependent template name. | |||
523 | unsigned DiagID = diag::err_missing_dependent_template_keyword; | |||
524 | if (getLangOpts().MicrosoftExt) | |||
525 | DiagID = diag::warn_missing_dependent_template_keyword; | |||
526 | ||||
527 | Diag(Tok.getLocation(), DiagID) | |||
528 | << II.getName() | |||
529 | << FixItHint::CreateInsertion(Tok.getLocation(), "template "); | |||
530 | } | |||
531 | ||||
532 | SourceLocation TemplateNameLoc = ConsumeToken(); | |||
533 | ||||
534 | TemplateNameKind TNK = Actions.ActOnTemplateName( | |||
535 | getCurScope(), SS, TemplateNameLoc, TemplateName, ObjectType, | |||
536 | EnteringContext, Template, /*AllowInjectedClassName*/ true); | |||
537 | if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(), | |||
538 | TemplateName, false)) | |||
539 | return true; | |||
540 | ||||
541 | continue; | |||
542 | } | |||
543 | } | |||
544 | ||||
545 | // We don't have any tokens that form the beginning of a | |||
546 | // nested-name-specifier, so we're done. | |||
547 | break; | |||
548 | } | |||
549 | ||||
550 | // Even if we didn't see any pieces of a nested-name-specifier, we | |||
551 | // still check whether there is a tilde in this position, which | |||
552 | // indicates a potential pseudo-destructor. | |||
553 | if (CheckForDestructor && !HasScopeSpecifier && Tok.is(tok::tilde)) | |||
554 | *MayBePseudoDestructor = true; | |||
555 | ||||
556 | return false; | |||
557 | } | |||
558 | ||||
559 | ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS, | |||
560 | bool isAddressOfOperand, | |||
561 | Token &Replacement) { | |||
562 | ExprResult E; | |||
563 | ||||
564 | // We may have already annotated this id-expression. | |||
565 | switch (Tok.getKind()) { | |||
566 | case tok::annot_non_type: { | |||
567 | NamedDecl *ND = getNonTypeAnnotation(Tok); | |||
568 | SourceLocation Loc = ConsumeAnnotationToken(); | |||
569 | E = Actions.ActOnNameClassifiedAsNonType(getCurScope(), SS, ND, Loc, Tok); | |||
570 | break; | |||
571 | } | |||
572 | ||||
573 | case tok::annot_non_type_dependent: { | |||
574 | IdentifierInfo *II = getIdentifierAnnotation(Tok); | |||
575 | SourceLocation Loc = ConsumeAnnotationToken(); | |||
576 | ||||
577 | // This is only the direct operand of an & operator if it is not | |||
578 | // followed by a postfix-expression suffix. | |||
579 | if (isAddressOfOperand && isPostfixExpressionSuffixStart()) | |||
580 | isAddressOfOperand = false; | |||
581 | ||||
582 | E = Actions.ActOnNameClassifiedAsDependentNonType(SS, II, Loc, | |||
583 | isAddressOfOperand); | |||
584 | break; | |||
585 | } | |||
586 | ||||
587 | case tok::annot_non_type_undeclared: { | |||
588 | assert(SS.isEmpty() &&(static_cast <bool> (SS.isEmpty() && "undeclared non-type annotation should be unqualified" ) ? void (0) : __assert_fail ("SS.isEmpty() && \"undeclared non-type annotation should be unqualified\"" , "clang/lib/Parse/ParseExprCXX.cpp", 589, __extension__ __PRETTY_FUNCTION__ )) | |||
589 | "undeclared non-type annotation should be unqualified")(static_cast <bool> (SS.isEmpty() && "undeclared non-type annotation should be unqualified" ) ? void (0) : __assert_fail ("SS.isEmpty() && \"undeclared non-type annotation should be unqualified\"" , "clang/lib/Parse/ParseExprCXX.cpp", 589, __extension__ __PRETTY_FUNCTION__ )); | |||
590 | IdentifierInfo *II = getIdentifierAnnotation(Tok); | |||
591 | SourceLocation Loc = ConsumeAnnotationToken(); | |||
592 | E = Actions.ActOnNameClassifiedAsUndeclaredNonType(II, Loc); | |||
593 | break; | |||
594 | } | |||
595 | ||||
596 | default: | |||
597 | SourceLocation TemplateKWLoc; | |||
598 | UnqualifiedId Name; | |||
599 | if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr, | |||
600 | /*ObjectHadErrors=*/false, | |||
601 | /*EnteringContext=*/false, | |||
602 | /*AllowDestructorName=*/false, | |||
603 | /*AllowConstructorName=*/false, | |||
604 | /*AllowDeductionGuide=*/false, &TemplateKWLoc, Name)) | |||
605 | return ExprError(); | |||
606 | ||||
607 | // This is only the direct operand of an & operator if it is not | |||
608 | // followed by a postfix-expression suffix. | |||
609 | if (isAddressOfOperand && isPostfixExpressionSuffixStart()) | |||
610 | isAddressOfOperand = false; | |||
611 | ||||
612 | E = Actions.ActOnIdExpression( | |||
613 | getCurScope(), SS, TemplateKWLoc, Name, Tok.is(tok::l_paren), | |||
614 | isAddressOfOperand, /*CCC=*/nullptr, /*IsInlineAsmIdentifier=*/false, | |||
615 | &Replacement); | |||
616 | break; | |||
617 | } | |||
618 | ||||
619 | if (!E.isInvalid() && !E.isUnset() && Tok.is(tok::less)) | |||
620 | checkPotentialAngleBracket(E); | |||
621 | return E; | |||
622 | } | |||
623 | ||||
624 | /// ParseCXXIdExpression - Handle id-expression. | |||
625 | /// | |||
626 | /// id-expression: | |||
627 | /// unqualified-id | |||
628 | /// qualified-id | |||
629 | /// | |||
630 | /// qualified-id: | |||
631 | /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id | |||
632 | /// '::' identifier | |||
633 | /// '::' operator-function-id | |||
634 | /// '::' template-id | |||
635 | /// | |||
636 | /// NOTE: The standard specifies that, for qualified-id, the parser does not | |||
637 | /// expect: | |||
638 | /// | |||
639 | /// '::' conversion-function-id | |||
640 | /// '::' '~' class-name | |||
641 | /// | |||
642 | /// This may cause a slight inconsistency on diagnostics: | |||
643 | /// | |||
644 | /// class C {}; | |||
645 | /// namespace A {} | |||
646 | /// void f() { | |||
647 | /// :: A :: ~ C(); // Some Sema error about using destructor with a | |||
648 | /// // namespace. | |||
649 | /// :: ~ C(); // Some Parser error like 'unexpected ~'. | |||
650 | /// } | |||
651 | /// | |||
652 | /// We simplify the parser a bit and make it work like: | |||
653 | /// | |||
654 | /// qualified-id: | |||
655 | /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id | |||
656 | /// '::' unqualified-id | |||
657 | /// | |||
658 | /// That way Sema can handle and report similar errors for namespaces and the | |||
659 | /// global scope. | |||
660 | /// | |||
661 | /// The isAddressOfOperand parameter indicates that this id-expression is a | |||
662 | /// direct operand of the address-of operator. This is, besides member contexts, | |||
663 | /// the only place where a qualified-id naming a non-static class member may | |||
664 | /// appear. | |||
665 | /// | |||
666 | ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) { | |||
667 | // qualified-id: | |||
668 | // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id | |||
669 | // '::' unqualified-id | |||
670 | // | |||
671 | CXXScopeSpec SS; | |||
672 | ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr, | |||
673 | /*ObjectHasErrors=*/false, | |||
674 | /*EnteringContext=*/false); | |||
675 | ||||
676 | Token Replacement; | |||
677 | ExprResult Result = | |||
678 | tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement); | |||
679 | if (Result.isUnset()) { | |||
680 | // If the ExprResult is valid but null, then typo correction suggested a | |||
681 | // keyword replacement that needs to be reparsed. | |||
682 | UnconsumeToken(Replacement); | |||
683 | Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement); | |||
684 | } | |||
685 | assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "(static_cast <bool> (!Result.isUnset() && "Typo correction suggested a keyword replacement " "for a previous keyword suggestion") ? void (0) : __assert_fail ("!Result.isUnset() && \"Typo correction suggested a keyword replacement \" \"for a previous keyword suggestion\"" , "clang/lib/Parse/ParseExprCXX.cpp", 686, __extension__ __PRETTY_FUNCTION__ )) | |||
686 | "for a previous keyword suggestion")(static_cast <bool> (!Result.isUnset() && "Typo correction suggested a keyword replacement " "for a previous keyword suggestion") ? void (0) : __assert_fail ("!Result.isUnset() && \"Typo correction suggested a keyword replacement \" \"for a previous keyword suggestion\"" , "clang/lib/Parse/ParseExprCXX.cpp", 686, __extension__ __PRETTY_FUNCTION__ )); | |||
687 | return Result; | |||
688 | } | |||
689 | ||||
690 | /// ParseLambdaExpression - Parse a C++11 lambda expression. | |||
691 | /// | |||
692 | /// lambda-expression: | |||
693 | /// lambda-introducer lambda-declarator compound-statement | |||
694 | /// lambda-introducer '<' template-parameter-list '>' | |||
695 | /// requires-clause[opt] lambda-declarator compound-statement | |||
696 | /// | |||
697 | /// lambda-introducer: | |||
698 | /// '[' lambda-capture[opt] ']' | |||
699 | /// | |||
700 | /// lambda-capture: | |||
701 | /// capture-default | |||
702 | /// capture-list | |||
703 | /// capture-default ',' capture-list | |||
704 | /// | |||
705 | /// capture-default: | |||
706 | /// '&' | |||
707 | /// '=' | |||
708 | /// | |||
709 | /// capture-list: | |||
710 | /// capture | |||
711 | /// capture-list ',' capture | |||
712 | /// | |||
713 | /// capture: | |||
714 | /// simple-capture | |||
715 | /// init-capture [C++1y] | |||
716 | /// | |||
717 | /// simple-capture: | |||
718 | /// identifier | |||
719 | /// '&' identifier | |||
720 | /// 'this' | |||
721 | /// | |||
722 | /// init-capture: [C++1y] | |||
723 | /// identifier initializer | |||
724 | /// '&' identifier initializer | |||
725 | /// | |||
726 | /// lambda-declarator: | |||
727 | /// lambda-specifiers [C++2b] | |||
728 | /// '(' parameter-declaration-clause ')' lambda-specifiers | |||
729 | /// requires-clause[opt] | |||
730 | /// | |||
731 | /// lambda-specifiers: | |||
732 | /// decl-specifier-seq[opt] noexcept-specifier[opt] | |||
733 | /// attribute-specifier-seq[opt] trailing-return-type[opt] | |||
734 | /// | |||
735 | ExprResult Parser::ParseLambdaExpression() { | |||
736 | // Parse lambda-introducer. | |||
737 | LambdaIntroducer Intro; | |||
738 | if (ParseLambdaIntroducer(Intro)) { | |||
739 | SkipUntil(tok::r_square, StopAtSemi); | |||
740 | SkipUntil(tok::l_brace, StopAtSemi); | |||
741 | SkipUntil(tok::r_brace, StopAtSemi); | |||
742 | return ExprError(); | |||
743 | } | |||
744 | ||||
745 | return ParseLambdaExpressionAfterIntroducer(Intro); | |||
746 | } | |||
747 | ||||
748 | /// Use lookahead and potentially tentative parsing to determine if we are | |||
749 | /// looking at a C++11 lambda expression, and parse it if we are. | |||
750 | /// | |||
751 | /// If we are not looking at a lambda expression, returns ExprError(). | |||
752 | ExprResult Parser::TryParseLambdaExpression() { | |||
753 | assert(getLangOpts().CPlusPlus11(static_cast <bool> (getLangOpts().CPlusPlus11 && Tok.is(tok::l_square) && "Not at the start of a possible lambda expression." ) ? void (0) : __assert_fail ("getLangOpts().CPlusPlus11 && Tok.is(tok::l_square) && \"Not at the start of a possible lambda expression.\"" , "clang/lib/Parse/ParseExprCXX.cpp", 755, __extension__ __PRETTY_FUNCTION__ )) | |||
754 | && Tok.is(tok::l_square)(static_cast <bool> (getLangOpts().CPlusPlus11 && Tok.is(tok::l_square) && "Not at the start of a possible lambda expression." ) ? void (0) : __assert_fail ("getLangOpts().CPlusPlus11 && Tok.is(tok::l_square) && \"Not at the start of a possible lambda expression.\"" , "clang/lib/Parse/ParseExprCXX.cpp", 755, __extension__ __PRETTY_FUNCTION__ )) | |||
755 | && "Not at the start of a possible lambda expression.")(static_cast <bool> (getLangOpts().CPlusPlus11 && Tok.is(tok::l_square) && "Not at the start of a possible lambda expression." ) ? void (0) : __assert_fail ("getLangOpts().CPlusPlus11 && Tok.is(tok::l_square) && \"Not at the start of a possible lambda expression.\"" , "clang/lib/Parse/ParseExprCXX.cpp", 755, __extension__ __PRETTY_FUNCTION__ )); | |||
756 | ||||
757 | const Token Next = NextToken(); | |||
758 | if (Next.is(tok::eof)) // Nothing else to lookup here... | |||
759 | return ExprEmpty(); | |||
760 | ||||
761 | const Token After = GetLookAheadToken(2); | |||
762 | // If lookahead indicates this is a lambda... | |||
763 | if (Next.is(tok::r_square) || // [] | |||
764 | Next.is(tok::equal) || // [= | |||
765 | (Next.is(tok::amp) && // [&] or [&, | |||
766 | After.isOneOf(tok::r_square, tok::comma)) || | |||
767 | (Next.is(tok::identifier) && // [identifier] | |||
768 | After.is(tok::r_square)) || | |||
769 | Next.is(tok::ellipsis)) { // [... | |||
770 | return ParseLambdaExpression(); | |||
771 | } | |||
772 | ||||
773 | // If lookahead indicates an ObjC message send... | |||
774 | // [identifier identifier | |||
775 | if (Next.is(tok::identifier) && After.is(tok::identifier)) | |||
776 | return ExprEmpty(); | |||
777 | ||||
778 | // Here, we're stuck: lambda introducers and Objective-C message sends are | |||
779 | // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a | |||
780 | // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of | |||
781 | // writing two routines to parse a lambda introducer, just try to parse | |||
782 | // a lambda introducer first, and fall back if that fails. | |||
783 | LambdaIntroducer Intro; | |||
784 | { | |||
785 | TentativeParsingAction TPA(*this); | |||
786 | LambdaIntroducerTentativeParse Tentative; | |||
787 | if (ParseLambdaIntroducer(Intro, &Tentative)) { | |||
788 | TPA.Commit(); | |||
789 | return ExprError(); | |||
790 | } | |||
791 | ||||
792 | switch (Tentative) { | |||
793 | case LambdaIntroducerTentativeParse::Success: | |||
794 | TPA.Commit(); | |||
795 | break; | |||
796 | ||||
797 | case LambdaIntroducerTentativeParse::Incomplete: | |||
798 | // Didn't fully parse the lambda-introducer, try again with a | |||
799 | // non-tentative parse. | |||
800 | TPA.Revert(); | |||
801 | Intro = LambdaIntroducer(); | |||
802 | if (ParseLambdaIntroducer(Intro)) | |||
803 | return ExprError(); | |||
804 | break; | |||
805 | ||||
806 | case LambdaIntroducerTentativeParse::MessageSend: | |||
807 | case LambdaIntroducerTentativeParse::Invalid: | |||
808 | // Not a lambda-introducer, might be a message send. | |||
809 | TPA.Revert(); | |||
810 | return ExprEmpty(); | |||
811 | } | |||
812 | } | |||
813 | ||||
814 | return ParseLambdaExpressionAfterIntroducer(Intro); | |||
815 | } | |||
816 | ||||
817 | /// Parse a lambda introducer. | |||
818 | /// \param Intro A LambdaIntroducer filled in with information about the | |||
819 | /// contents of the lambda-introducer. | |||
820 | /// \param Tentative If non-null, we are disambiguating between a | |||
821 | /// lambda-introducer and some other construct. In this mode, we do not | |||
822 | /// produce any diagnostics or take any other irreversible action unless | |||
823 | /// we're sure that this is a lambda-expression. | |||
824 | /// \return \c true if parsing (or disambiguation) failed with a diagnostic and | |||
825 | /// the caller should bail out / recover. | |||
826 | bool Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro, | |||
827 | LambdaIntroducerTentativeParse *Tentative) { | |||
828 | if (Tentative) | |||
829 | *Tentative = LambdaIntroducerTentativeParse::Success; | |||
830 | ||||
831 | assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.")(static_cast <bool> (Tok.is(tok::l_square) && "Lambda expressions begin with '['." ) ? void (0) : __assert_fail ("Tok.is(tok::l_square) && \"Lambda expressions begin with '['.\"" , "clang/lib/Parse/ParseExprCXX.cpp", 831, __extension__ __PRETTY_FUNCTION__ )); | |||
832 | BalancedDelimiterTracker T(*this, tok::l_square); | |||
833 | T.consumeOpen(); | |||
834 | ||||
835 | Intro.Range.setBegin(T.getOpenLocation()); | |||
836 | ||||
837 | bool First = true; | |||
838 | ||||
839 | // Produce a diagnostic if we're not tentatively parsing; otherwise track | |||
840 | // that our parse has failed. | |||
841 | auto Invalid = [&](llvm::function_ref<void()> Action) { | |||
842 | if (Tentative) { | |||
843 | *Tentative = LambdaIntroducerTentativeParse::Invalid; | |||
844 | return false; | |||
845 | } | |||
846 | Action(); | |||
847 | return true; | |||
848 | }; | |||
849 | ||||
850 | // Perform some irreversible action if this is a non-tentative parse; | |||
851 | // otherwise note that our actions were incomplete. | |||
852 | auto NonTentativeAction = [&](llvm::function_ref<void()> Action) { | |||
853 | if (Tentative) | |||
854 | *Tentative = LambdaIntroducerTentativeParse::Incomplete; | |||
855 | else | |||
856 | Action(); | |||
857 | }; | |||
858 | ||||
859 | // Parse capture-default. | |||
860 | if (Tok.is(tok::amp) && | |||
861 | (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) { | |||
862 | Intro.Default = LCD_ByRef; | |||
863 | Intro.DefaultLoc = ConsumeToken(); | |||
864 | First = false; | |||
865 | if (!Tok.getIdentifierInfo()) { | |||
866 | // This can only be a lambda; no need for tentative parsing any more. | |||
867 | // '[[and]]' can still be an attribute, though. | |||
868 | Tentative = nullptr; | |||
869 | } | |||
870 | } else if (Tok.is(tok::equal)) { | |||
871 | Intro.Default = LCD_ByCopy; | |||
872 | Intro.DefaultLoc = ConsumeToken(); | |||
873 | First = false; | |||
874 | Tentative = nullptr; | |||
875 | } | |||
876 | ||||
877 | while (Tok.isNot(tok::r_square)) { | |||
878 | if (!First) { | |||
879 | if (Tok.isNot(tok::comma)) { | |||
880 | // Provide a completion for a lambda introducer here. Except | |||
881 | // in Objective-C, where this is Almost Surely meant to be a message | |||
882 | // send. In that case, fail here and let the ObjC message | |||
883 | // expression parser perform the completion. | |||
884 | if (Tok.is(tok::code_completion) && | |||
885 | !(getLangOpts().ObjC && Tentative)) { | |||
886 | cutOffParsing(); | |||
887 | Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro, | |||
888 | /*AfterAmpersand=*/false); | |||
889 | break; | |||
890 | } | |||
891 | ||||
892 | return Invalid([&] { | |||
893 | Diag(Tok.getLocation(), diag::err_expected_comma_or_rsquare); | |||
894 | }); | |||
895 | } | |||
896 | ConsumeToken(); | |||
897 | } | |||
898 | ||||
899 | if (Tok.is(tok::code_completion)) { | |||
900 | cutOffParsing(); | |||
901 | // If we're in Objective-C++ and we have a bare '[', then this is more | |||
902 | // likely to be a message receiver. | |||
903 | if (getLangOpts().ObjC && Tentative && First) | |||
904 | Actions.CodeCompleteObjCMessageReceiver(getCurScope()); | |||
905 | else | |||
906 | Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro, | |||
907 | /*AfterAmpersand=*/false); | |||
908 | break; | |||
909 | } | |||
910 | ||||
911 | First = false; | |||
912 | ||||
913 | // Parse capture. | |||
914 | LambdaCaptureKind Kind = LCK_ByCopy; | |||
915 | LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit; | |||
916 | SourceLocation Loc; | |||
917 | IdentifierInfo *Id = nullptr; | |||
918 | SourceLocation EllipsisLocs[4]; | |||
919 | ExprResult Init; | |||
920 | SourceLocation LocStart = Tok.getLocation(); | |||
921 | ||||
922 | if (Tok.is(tok::star)) { | |||
923 | Loc = ConsumeToken(); | |||
924 | if (Tok.is(tok::kw_this)) { | |||
925 | ConsumeToken(); | |||
926 | Kind = LCK_StarThis; | |||
927 | } else { | |||
928 | return Invalid([&] { | |||
929 | Diag(Tok.getLocation(), diag::err_expected_star_this_capture); | |||
930 | }); | |||
931 | } | |||
932 | } else if (Tok.is(tok::kw_this)) { | |||
933 | Kind = LCK_This; | |||
934 | Loc = ConsumeToken(); | |||
935 | } else if (Tok.isOneOf(tok::amp, tok::equal) && | |||
936 | NextToken().isOneOf(tok::comma, tok::r_square) && | |||
937 | Intro.Default == LCD_None) { | |||
938 | // We have a lone "&" or "=" which is either a misplaced capture-default | |||
939 | // or the start of a capture (in the "&" case) with the rest of the | |||
940 | // capture missing. Both are an error but a misplaced capture-default | |||
941 | // is more likely if we don't already have a capture default. | |||
942 | return Invalid( | |||
943 | [&] { Diag(Tok.getLocation(), diag::err_capture_default_first); }); | |||
944 | } else { | |||
945 | TryConsumeToken(tok::ellipsis, EllipsisLocs[0]); | |||
946 | ||||
947 | if (Tok.is(tok::amp)) { | |||
948 | Kind = LCK_ByRef; | |||
949 | ConsumeToken(); | |||
950 | ||||
951 | if (Tok.is(tok::code_completion)) { | |||
952 | cutOffParsing(); | |||
953 | Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro, | |||
954 | /*AfterAmpersand=*/true); | |||
955 | break; | |||
956 | } | |||
957 | } | |||
958 | ||||
959 | TryConsumeToken(tok::ellipsis, EllipsisLocs[1]); | |||
960 | ||||
961 | if (Tok.is(tok::identifier)) { | |||
962 | Id = Tok.getIdentifierInfo(); | |||
963 | Loc = ConsumeToken(); | |||
964 | } else if (Tok.is(tok::kw_this)) { | |||
965 | return Invalid([&] { | |||
966 | // FIXME: Suggest a fixit here. | |||
967 | Diag(Tok.getLocation(), diag::err_this_captured_by_reference); | |||
968 | }); | |||
969 | } else { | |||
970 | return Invalid([&] { | |||
971 | Diag(Tok.getLocation(), diag::err_expected_capture); | |||
972 | }); | |||
973 | } | |||
974 | ||||
975 | TryConsumeToken(tok::ellipsis, EllipsisLocs[2]); | |||
976 | ||||
977 | if (Tok.is(tok::l_paren)) { | |||
978 | BalancedDelimiterTracker Parens(*this, tok::l_paren); | |||
979 | Parens.consumeOpen(); | |||
980 | ||||
981 | InitKind = LambdaCaptureInitKind::DirectInit; | |||
982 | ||||
983 | ExprVector Exprs; | |||
984 | if (Tentative) { | |||
985 | Parens.skipToEnd(); | |||
986 | *Tentative = LambdaIntroducerTentativeParse::Incomplete; | |||
987 | } else if (ParseExpressionList(Exprs)) { | |||
988 | Parens.skipToEnd(); | |||
989 | Init = ExprError(); | |||
990 | } else { | |||
991 | Parens.consumeClose(); | |||
992 | Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(), | |||
993 | Parens.getCloseLocation(), | |||
994 | Exprs); | |||
995 | } | |||
996 | } else if (Tok.isOneOf(tok::l_brace, tok::equal)) { | |||
997 | // Each lambda init-capture forms its own full expression, which clears | |||
998 | // Actions.MaybeODRUseExprs. So create an expression evaluation context | |||
999 | // to save the necessary state, and restore it later. | |||
1000 | EnterExpressionEvaluationContext EC( | |||
1001 | Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); | |||
1002 | ||||
1003 | if (TryConsumeToken(tok::equal)) | |||
1004 | InitKind = LambdaCaptureInitKind::CopyInit; | |||
1005 | else | |||
1006 | InitKind = LambdaCaptureInitKind::ListInit; | |||
1007 | ||||
1008 | if (!Tentative) { | |||
1009 | Init = ParseInitializer(); | |||
1010 | } else if (Tok.is(tok::l_brace)) { | |||
1011 | BalancedDelimiterTracker Braces(*this, tok::l_brace); | |||
1012 | Braces.consumeOpen(); | |||
1013 | Braces.skipToEnd(); | |||
1014 | *Tentative = LambdaIntroducerTentativeParse::Incomplete; | |||
1015 | } else { | |||
1016 | // We're disambiguating this: | |||
1017 | // | |||
1018 | // [..., x = expr | |||
1019 | // | |||
1020 | // We need to find the end of the following expression in order to | |||
1021 | // determine whether this is an Obj-C message send's receiver, a | |||
1022 | // C99 designator, or a lambda init-capture. | |||
1023 | // | |||
1024 | // Parse the expression to find where it ends, and annotate it back | |||
1025 | // onto the tokens. We would have parsed this expression the same way | |||
1026 | // in either case: both the RHS of an init-capture and the RHS of an | |||
1027 | // assignment expression are parsed as an initializer-clause, and in | |||
1028 | // neither case can anything be added to the scope between the '[' and | |||
1029 | // here. | |||
1030 | // | |||
1031 | // FIXME: This is horrible. Adding a mechanism to skip an expression | |||
1032 | // would be much cleaner. | |||
1033 | // FIXME: If there is a ',' before the next ']' or ':', we can skip to | |||
1034 | // that instead. (And if we see a ':' with no matching '?', we can | |||
1035 | // classify this as an Obj-C message send.) | |||
1036 | SourceLocation StartLoc = Tok.getLocation(); | |||
1037 | InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true); | |||
1038 | Init = ParseInitializer(); | |||
1039 | if (!Init.isInvalid()) | |||
1040 | Init = Actions.CorrectDelayedTyposInExpr(Init.get()); | |||
1041 | ||||
1042 | if (Tok.getLocation() != StartLoc) { | |||
1043 | // Back out the lexing of the token after the initializer. | |||
1044 | PP.RevertCachedTokens(1); | |||
1045 | ||||
1046 | // Replace the consumed tokens with an appropriate annotation. | |||
1047 | Tok.setLocation(StartLoc); | |||
1048 | Tok.setKind(tok::annot_primary_expr); | |||
1049 | setExprAnnotation(Tok, Init); | |||
1050 | Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation()); | |||
1051 | PP.AnnotateCachedTokens(Tok); | |||
1052 | ||||
1053 | // Consume the annotated initializer. | |||
1054 | ConsumeAnnotationToken(); | |||
1055 | } | |||
1056 | } | |||
1057 | } | |||
1058 | ||||
1059 | TryConsumeToken(tok::ellipsis, EllipsisLocs[3]); | |||
1060 | } | |||
1061 | ||||
1062 | // Check if this is a message send before we act on a possible init-capture. | |||
1063 | if (Tentative && Tok.is(tok::identifier) && | |||
1064 | NextToken().isOneOf(tok::colon, tok::r_square)) { | |||
1065 | // This can only be a message send. We're done with disambiguation. | |||
1066 | *Tentative = LambdaIntroducerTentativeParse::MessageSend; | |||
1067 | return false; | |||
1068 | } | |||
1069 | ||||
1070 | // Ensure that any ellipsis was in the right place. | |||
1071 | SourceLocation EllipsisLoc; | |||
1072 | if (llvm::any_of(EllipsisLocs, | |||
1073 | [](SourceLocation Loc) { return Loc.isValid(); })) { | |||
1074 | // The '...' should appear before the identifier in an init-capture, and | |||
1075 | // after the identifier otherwise. | |||
1076 | bool InitCapture = InitKind != LambdaCaptureInitKind::NoInit; | |||
1077 | SourceLocation *ExpectedEllipsisLoc = | |||
1078 | !InitCapture ? &EllipsisLocs[2] : | |||
1079 | Kind == LCK_ByRef ? &EllipsisLocs[1] : | |||
1080 | &EllipsisLocs[0]; | |||
1081 | EllipsisLoc = *ExpectedEllipsisLoc; | |||
1082 | ||||
1083 | unsigned DiagID = 0; | |||
1084 | if (EllipsisLoc.isInvalid()) { | |||
1085 | DiagID = diag::err_lambda_capture_misplaced_ellipsis; | |||
1086 | for (SourceLocation Loc : EllipsisLocs) { | |||
1087 | if (Loc.isValid()) | |||
1088 | EllipsisLoc = Loc; | |||
1089 | } | |||
1090 | } else { | |||
1091 | unsigned NumEllipses = std::accumulate( | |||
1092 | std::begin(EllipsisLocs), std::end(EllipsisLocs), 0, | |||
1093 | [](int N, SourceLocation Loc) { return N + Loc.isValid(); }); | |||
1094 | if (NumEllipses > 1) | |||
1095 | DiagID = diag::err_lambda_capture_multiple_ellipses; | |||
1096 | } | |||
1097 | if (DiagID) { | |||
1098 | NonTentativeAction([&] { | |||
1099 | // Point the diagnostic at the first misplaced ellipsis. | |||
1100 | SourceLocation DiagLoc; | |||
1101 | for (SourceLocation &Loc : EllipsisLocs) { | |||
1102 | if (&Loc != ExpectedEllipsisLoc && Loc.isValid()) { | |||
1103 | DiagLoc = Loc; | |||
1104 | break; | |||
1105 | } | |||
1106 | } | |||
1107 | assert(DiagLoc.isValid() && "no location for diagnostic")(static_cast <bool> (DiagLoc.isValid() && "no location for diagnostic" ) ? void (0) : __assert_fail ("DiagLoc.isValid() && \"no location for diagnostic\"" , "clang/lib/Parse/ParseExprCXX.cpp", 1107, __extension__ __PRETTY_FUNCTION__ )); | |||
1108 | ||||
1109 | // Issue the diagnostic and produce fixits showing where the ellipsis | |||
1110 | // should have been written. | |||
1111 | auto &&D = Diag(DiagLoc, DiagID); | |||
1112 | if (DiagID == diag::err_lambda_capture_misplaced_ellipsis) { | |||
1113 | SourceLocation ExpectedLoc = | |||
1114 | InitCapture ? Loc | |||
1115 | : Lexer::getLocForEndOfToken( | |||
1116 | Loc, 0, PP.getSourceManager(), getLangOpts()); | |||
1117 | D << InitCapture << FixItHint::CreateInsertion(ExpectedLoc, "..."); | |||
1118 | } | |||
1119 | for (SourceLocation &Loc : EllipsisLocs) { | |||
1120 | if (&Loc != ExpectedEllipsisLoc && Loc.isValid()) | |||
1121 | D << FixItHint::CreateRemoval(Loc); | |||
1122 | } | |||
1123 | }); | |||
1124 | } | |||
1125 | } | |||
1126 | ||||
1127 | // Process the init-capture initializers now rather than delaying until we | |||
1128 | // form the lambda-expression so that they can be handled in the context | |||
1129 | // enclosing the lambda-expression, rather than in the context of the | |||
1130 | // lambda-expression itself. | |||
1131 | ParsedType InitCaptureType; | |||
1132 | if (Init.isUsable()) | |||
1133 | Init = Actions.CorrectDelayedTyposInExpr(Init.get()); | |||
1134 | if (Init.isUsable()) { | |||
1135 | NonTentativeAction([&] { | |||
1136 | // Get the pointer and store it in an lvalue, so we can use it as an | |||
1137 | // out argument. | |||
1138 | Expr *InitExpr = Init.get(); | |||
1139 | // This performs any lvalue-to-rvalue conversions if necessary, which | |||
1140 | // can affect what gets captured in the containing decl-context. | |||
1141 | InitCaptureType = Actions.actOnLambdaInitCaptureInitialization( | |||
1142 | Loc, Kind == LCK_ByRef, EllipsisLoc, Id, InitKind, InitExpr); | |||
1143 | Init = InitExpr; | |||
1144 | }); | |||
1145 | } | |||
1146 | ||||
1147 | SourceLocation LocEnd = PrevTokLocation; | |||
1148 | ||||
1149 | Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init, | |||
1150 | InitCaptureType, SourceRange(LocStart, LocEnd)); | |||
1151 | } | |||
1152 | ||||
1153 | T.consumeClose(); | |||
1154 | Intro.Range.setEnd(T.getCloseLocation()); | |||
1155 | return false; | |||
1156 | } | |||
1157 | ||||
1158 | static void tryConsumeLambdaSpecifierToken(Parser &P, | |||
1159 | SourceLocation &MutableLoc, | |||
1160 | SourceLocation &StaticLoc, | |||
1161 | SourceLocation &ConstexprLoc, | |||
1162 | SourceLocation &ConstevalLoc, | |||
1163 | SourceLocation &DeclEndLoc) { | |||
1164 | assert(MutableLoc.isInvalid())(static_cast <bool> (MutableLoc.isInvalid()) ? void (0) : __assert_fail ("MutableLoc.isInvalid()", "clang/lib/Parse/ParseExprCXX.cpp" , 1164, __extension__ __PRETTY_FUNCTION__)); | |||
1165 | assert(StaticLoc.isInvalid())(static_cast <bool> (StaticLoc.isInvalid()) ? void (0) : __assert_fail ("StaticLoc.isInvalid()", "clang/lib/Parse/ParseExprCXX.cpp" , 1165, __extension__ __PRETTY_FUNCTION__)); | |||
1166 | assert(ConstexprLoc.isInvalid())(static_cast <bool> (ConstexprLoc.isInvalid()) ? void ( 0) : __assert_fail ("ConstexprLoc.isInvalid()", "clang/lib/Parse/ParseExprCXX.cpp" , 1166, __extension__ __PRETTY_FUNCTION__)); | |||
1167 | assert(ConstevalLoc.isInvalid())(static_cast <bool> (ConstevalLoc.isInvalid()) ? void ( 0) : __assert_fail ("ConstevalLoc.isInvalid()", "clang/lib/Parse/ParseExprCXX.cpp" , 1167, __extension__ __PRETTY_FUNCTION__)); | |||
1168 | // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc | |||
1169 | // to the final of those locations. Emit an error if we have multiple | |||
1170 | // copies of those keywords and recover. | |||
1171 | ||||
1172 | auto ConsumeLocation = [&P, &DeclEndLoc](SourceLocation &SpecifierLoc, | |||
1173 | int DiagIndex) { | |||
1174 | if (SpecifierLoc.isValid()) { | |||
1175 | P.Diag(P.getCurToken().getLocation(), | |||
1176 | diag::err_lambda_decl_specifier_repeated) | |||
1177 | << DiagIndex | |||
1178 | << FixItHint::CreateRemoval(P.getCurToken().getLocation()); | |||
1179 | } | |||
1180 | SpecifierLoc = P.ConsumeToken(); | |||
1181 | DeclEndLoc = SpecifierLoc; | |||
1182 | }; | |||
1183 | ||||
1184 | while (true) { | |||
1185 | switch (P.getCurToken().getKind()) { | |||
1186 | case tok::kw_mutable: | |||
1187 | ConsumeLocation(MutableLoc, 0); | |||
1188 | break; | |||
1189 | case tok::kw_static: | |||
1190 | ConsumeLocation(StaticLoc, 1); | |||
1191 | break; | |||
1192 | case tok::kw_constexpr: | |||
1193 | ConsumeLocation(ConstexprLoc, 2); | |||
1194 | break; | |||
1195 | case tok::kw_consteval: | |||
1196 | ConsumeLocation(ConstevalLoc, 3); | |||
1197 | break; | |||
1198 | default: | |||
1199 | return; | |||
1200 | } | |||
1201 | } | |||
1202 | } | |||
1203 | ||||
1204 | static void addStaticToLambdaDeclSpecifier(Parser &P, SourceLocation StaticLoc, | |||
1205 | DeclSpec &DS) { | |||
1206 | if (StaticLoc.isValid()) { | |||
1207 | P.Diag(StaticLoc, !P.getLangOpts().CPlusPlus2b | |||
1208 | ? diag::err_static_lambda | |||
1209 | : diag::warn_cxx20_compat_static_lambda); | |||
1210 | const char *PrevSpec = nullptr; | |||
1211 | unsigned DiagID = 0; | |||
1212 | DS.SetStorageClassSpec(P.getActions(), DeclSpec::SCS_static, StaticLoc, | |||
1213 | PrevSpec, DiagID, | |||
1214 | P.getActions().getASTContext().getPrintingPolicy()); | |||
1215 | assert(PrevSpec == nullptr && DiagID == 0 &&(static_cast <bool> (PrevSpec == nullptr && DiagID == 0 && "Static cannot have been set previously!") ? void (0) : __assert_fail ("PrevSpec == nullptr && DiagID == 0 && \"Static cannot have been set previously!\"" , "clang/lib/Parse/ParseExprCXX.cpp", 1216, __extension__ __PRETTY_FUNCTION__ )) | |||
1216 | "Static cannot have been set previously!")(static_cast <bool> (PrevSpec == nullptr && DiagID == 0 && "Static cannot have been set previously!") ? void (0) : __assert_fail ("PrevSpec == nullptr && DiagID == 0 && \"Static cannot have been set previously!\"" , "clang/lib/Parse/ParseExprCXX.cpp", 1216, __extension__ __PRETTY_FUNCTION__ )); | |||
1217 | } | |||
1218 | } | |||
1219 | ||||
1220 | static void | |||
1221 | addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc, | |||
1222 | DeclSpec &DS) { | |||
1223 | if (ConstexprLoc.isValid()) { | |||
1224 | P.Diag(ConstexprLoc, !P.getLangOpts().CPlusPlus17 | |||
1225 | ? diag::ext_constexpr_on_lambda_cxx17 | |||
1226 | : diag::warn_cxx14_compat_constexpr_on_lambda); | |||
1227 | const char *PrevSpec = nullptr; | |||
1228 | unsigned DiagID = 0; | |||
1229 | DS.SetConstexprSpec(ConstexprSpecKind::Constexpr, ConstexprLoc, PrevSpec, | |||
1230 | DiagID); | |||
1231 | assert(PrevSpec == nullptr && DiagID == 0 &&(static_cast <bool> (PrevSpec == nullptr && DiagID == 0 && "Constexpr cannot have been set previously!" ) ? void (0) : __assert_fail ("PrevSpec == nullptr && DiagID == 0 && \"Constexpr cannot have been set previously!\"" , "clang/lib/Parse/ParseExprCXX.cpp", 1232, __extension__ __PRETTY_FUNCTION__ )) | |||
1232 | "Constexpr cannot have been set previously!")(static_cast <bool> (PrevSpec == nullptr && DiagID == 0 && "Constexpr cannot have been set previously!" ) ? void (0) : __assert_fail ("PrevSpec == nullptr && DiagID == 0 && \"Constexpr cannot have been set previously!\"" , "clang/lib/Parse/ParseExprCXX.cpp", 1232, __extension__ __PRETTY_FUNCTION__ )); | |||
1233 | } | |||
1234 | } | |||
1235 | ||||
1236 | static void addConstevalToLambdaDeclSpecifier(Parser &P, | |||
1237 | SourceLocation ConstevalLoc, | |||
1238 | DeclSpec &DS) { | |||
1239 | if (ConstevalLoc.isValid()) { | |||
1240 | P.Diag(ConstevalLoc, diag::warn_cxx20_compat_consteval); | |||
1241 | const char *PrevSpec = nullptr; | |||
1242 | unsigned DiagID = 0; | |||
1243 | DS.SetConstexprSpec(ConstexprSpecKind::Consteval, ConstevalLoc, PrevSpec, | |||
1244 | DiagID); | |||
1245 | if (DiagID != 0) | |||
1246 | P.Diag(ConstevalLoc, DiagID) << PrevSpec; | |||
1247 | } | |||
1248 | } | |||
1249 | ||||
1250 | static void DiagnoseStaticSpecifierRestrictions(Parser &P, | |||
1251 | SourceLocation StaticLoc, | |||
1252 | SourceLocation MutableLoc, | |||
1253 | const LambdaIntroducer &Intro) { | |||
1254 | if (StaticLoc.isInvalid()) | |||
1255 | return; | |||
1256 | ||||
1257 | // [expr.prim.lambda.general] p4 | |||
1258 | // The lambda-specifier-seq shall not contain both mutable and static. | |||
1259 | // If the lambda-specifier-seq contains static, there shall be no | |||
1260 | // lambda-capture. | |||
1261 | if (MutableLoc.isValid()) | |||
1262 | P.Diag(StaticLoc, diag::err_static_mutable_lambda); | |||
1263 | if (Intro.hasLambdaCapture()) { | |||
1264 | P.Diag(StaticLoc, diag::err_static_lambda_captures); | |||
1265 | } | |||
1266 | } | |||
1267 | ||||
1268 | /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda | |||
1269 | /// expression. | |||
1270 | ExprResult Parser::ParseLambdaExpressionAfterIntroducer( | |||
1271 | LambdaIntroducer &Intro) { | |||
1272 | SourceLocation LambdaBeginLoc = Intro.Range.getBegin(); | |||
1273 | Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda); | |||
1274 | ||||
1275 | PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc, | |||
1276 | "lambda expression parsing"); | |||
1277 | ||||
1278 | // Parse lambda-declarator[opt]. | |||
1279 | DeclSpec DS(AttrFactory); | |||
1280 | Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::LambdaExpr); | |||
1281 | TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth); | |||
1282 | ||||
1283 | ParseScope LambdaScope(this, Scope::LambdaScope | Scope::DeclScope | | |||
1284 | Scope::FunctionDeclarationScope | | |||
1285 | Scope::FunctionPrototypeScope); | |||
1286 | ||||
1287 | Actions.PushLambdaScope(); | |||
1288 | Actions.ActOnLambdaExpressionAfterIntroducer(Intro, getCurScope()); | |||
1289 | ||||
1290 | ParsedAttributes Attributes(AttrFactory); | |||
1291 | if (getLangOpts().CUDA) { | |||
1292 | // In CUDA code, GNU attributes are allowed to appear immediately after the | |||
1293 | // "[...]", even if there is no "(...)" before the lambda body. | |||
1294 | // | |||
1295 | // Note that we support __noinline__ as a keyword in this mode and thus | |||
1296 | // it has to be separately handled. | |||
1297 | while (true) { | |||
1298 | if (Tok.is(tok::kw___noinline__)) { | |||
1299 | IdentifierInfo *AttrName = Tok.getIdentifierInfo(); | |||
1300 | SourceLocation AttrNameLoc = ConsumeToken(); | |||
1301 | Attributes.addNew(AttrName, AttrNameLoc, /*ScopeName=*/nullptr, | |||
1302 | AttrNameLoc, /*ArgsUnion=*/nullptr, | |||
1303 | /*numArgs=*/0, ParsedAttr::AS_Keyword); | |||
1304 | } else if (Tok.is(tok::kw___attribute)) | |||
1305 | ParseGNUAttributes(Attributes, /*LatePArsedAttrList=*/nullptr, &D); | |||
1306 | else | |||
1307 | break; | |||
1308 | } | |||
1309 | ||||
1310 | D.takeAttributes(Attributes); | |||
1311 | } | |||
1312 | ||||
1313 | // Helper to emit a warning if we see a CUDA host/device/global attribute | |||
1314 | // after '(...)'. nvcc doesn't accept this. | |||
1315 | auto WarnIfHasCUDATargetAttr = [&] { | |||
1316 | if (getLangOpts().CUDA) | |||
1317 | for (const ParsedAttr &A : Attributes) | |||
1318 | if (A.getKind() == ParsedAttr::AT_CUDADevice || | |||
1319 | A.getKind() == ParsedAttr::AT_CUDAHost || | |||
1320 | A.getKind() == ParsedAttr::AT_CUDAGlobal) | |||
1321 | Diag(A.getLoc(), diag::warn_cuda_attr_lambda_position) | |||
1322 | << A.getAttrName()->getName(); | |||
1323 | }; | |||
1324 | ||||
1325 | MultiParseScope TemplateParamScope(*this); | |||
1326 | if (Tok.is(tok::less)) { | |||
1327 | Diag(Tok, getLangOpts().CPlusPlus20 | |||
1328 | ? diag::warn_cxx17_compat_lambda_template_parameter_list | |||
1329 | : diag::ext_lambda_template_parameter_list); | |||
1330 | ||||
1331 | SmallVector<NamedDecl*, 4> TemplateParams; | |||
1332 | SourceLocation LAngleLoc, RAngleLoc; | |||
1333 | if (ParseTemplateParameters(TemplateParamScope, | |||
1334 | CurTemplateDepthTracker.getDepth(), | |||
1335 | TemplateParams, LAngleLoc, RAngleLoc)) { | |||
1336 | Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope()); | |||
1337 | return ExprError(); | |||
1338 | } | |||
1339 | ||||
1340 | if (TemplateParams.empty()) { | |||
1341 | Diag(RAngleLoc, | |||
1342 | diag::err_lambda_template_parameter_list_empty); | |||
1343 | } else { | |||
1344 | ExprResult RequiresClause; | |||
1345 | if (TryConsumeToken(tok::kw_requires)) { | |||
1346 | RequiresClause = | |||
1347 | Actions.ActOnRequiresClause(ParseConstraintLogicalOrExpression( | |||
1348 | /*IsTrailingRequiresClause=*/false)); | |||
1349 | if (RequiresClause.isInvalid()) | |||
1350 | SkipUntil({tok::l_brace, tok::l_paren}, StopAtSemi | StopBeforeMatch); | |||
1351 | } | |||
1352 | ||||
1353 | Actions.ActOnLambdaExplicitTemplateParameterList( | |||
1354 | Intro, LAngleLoc, TemplateParams, RAngleLoc, RequiresClause); | |||
1355 | ++CurTemplateDepthTracker; | |||
1356 | } | |||
1357 | } | |||
1358 | ||||
1359 | // Implement WG21 P2173, which allows attributes immediately before the | |||
1360 | // lambda declarator and applies them to the corresponding function operator | |||
1361 | // or operator template declaration. We accept this as a conforming extension | |||
1362 | // in all language modes that support lambdas. | |||
1363 | if (isCXX11AttributeSpecifier()) { | |||
1364 | Diag(Tok, getLangOpts().CPlusPlus2b | |||
1365 | ? diag::warn_cxx20_compat_decl_attrs_on_lambda | |||
1366 | : diag::ext_decl_attrs_on_lambda); | |||
1367 | MaybeParseCXX11Attributes(D); | |||
1368 | } | |||
1369 | ||||
1370 | TypeResult TrailingReturnType; | |||
1371 | SourceLocation TrailingReturnTypeLoc; | |||
1372 | SourceLocation LParenLoc, RParenLoc; | |||
1373 | SourceLocation DeclEndLoc; | |||
1374 | bool HasParentheses = false; | |||
1375 | bool HasSpecifiers = false; | |||
1376 | SourceLocation MutableLoc; | |||
1377 | ||||
1378 | auto ParseConstexprAndMutableSpecifiers = [&] { | |||
1379 | // GNU-style attributes must be parsed before the mutable specifier to | |||
1380 | // be compatible with GCC. MSVC-style attributes must be parsed before | |||
1381 | // the mutable specifier to be compatible with MSVC. | |||
1382 | MaybeParseAttributes(PAKM_GNU | PAKM_Declspec, Attributes); | |||
1383 | // Parse mutable-opt and/or constexpr-opt or consteval-opt, and update | |||
1384 | // the DeclEndLoc. | |||
1385 | SourceLocation ConstexprLoc; | |||
1386 | SourceLocation ConstevalLoc; | |||
1387 | SourceLocation StaticLoc; | |||
1388 | ||||
1389 | tryConsumeLambdaSpecifierToken(*this, MutableLoc, StaticLoc, ConstexprLoc, | |||
1390 | ConstevalLoc, DeclEndLoc); | |||
1391 | ||||
1392 | DiagnoseStaticSpecifierRestrictions(*this, StaticLoc, MutableLoc, Intro); | |||
1393 | ||||
1394 | addStaticToLambdaDeclSpecifier(*this, StaticLoc, DS); | |||
1395 | addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS); | |||
1396 | addConstevalToLambdaDeclSpecifier(*this, ConstevalLoc, DS); | |||
1397 | }; | |||
1398 | ||||
1399 | auto ParseLambdaSpecifiers = | |||
1400 | [&](MutableArrayRef<DeclaratorChunk::ParamInfo> ParamInfo, | |||
1401 | SourceLocation EllipsisLoc) { | |||
1402 | // Parse exception-specification[opt]. | |||
1403 | ExceptionSpecificationType ESpecType = EST_None; | |||
1404 | SourceRange ESpecRange; | |||
1405 | SmallVector<ParsedType, 2> DynamicExceptions; | |||
1406 | SmallVector<SourceRange, 2> DynamicExceptionRanges; | |||
1407 | ExprResult NoexceptExpr; | |||
1408 | CachedTokens *ExceptionSpecTokens; | |||
1409 | ||||
1410 | ESpecType = tryParseExceptionSpecification( | |||
1411 | /*Delayed=*/false, ESpecRange, DynamicExceptions, | |||
1412 | DynamicExceptionRanges, NoexceptExpr, ExceptionSpecTokens); | |||
1413 | ||||
1414 | if (ESpecType != EST_None) | |||
1415 | DeclEndLoc = ESpecRange.getEnd(); | |||
1416 | ||||
1417 | // Parse attribute-specifier[opt]. | |||
1418 | if (MaybeParseCXX11Attributes(Attributes)) | |||
1419 | DeclEndLoc = Attributes.Range.getEnd(); | |||
1420 | ||||
1421 | // Parse OpenCL addr space attribute. | |||
1422 | if (Tok.isOneOf(tok::kw___private, tok::kw___global, tok::kw___local, | |||
1423 | tok::kw___constant, tok::kw___generic)) { | |||
1424 | ParseOpenCLQualifiers(DS.getAttributes()); | |||
1425 | ConsumeToken(); | |||
1426 | } | |||
1427 | ||||
1428 | SourceLocation FunLocalRangeEnd = DeclEndLoc; | |||
1429 | ||||
1430 | // Parse trailing-return-type[opt]. | |||
1431 | if (Tok.is(tok::arrow)) { | |||
1432 | FunLocalRangeEnd = Tok.getLocation(); | |||
1433 | SourceRange Range; | |||
1434 | TrailingReturnType = ParseTrailingReturnType( | |||
1435 | Range, /*MayBeFollowedByDirectInit*/ false); | |||
1436 | TrailingReturnTypeLoc = Range.getBegin(); | |||
1437 | if (Range.getEnd().isValid()) | |||
1438 | DeclEndLoc = Range.getEnd(); | |||
1439 | } | |||
1440 | ||||
1441 | SourceLocation NoLoc; | |||
1442 | D.AddTypeInfo( | |||
1443 | DeclaratorChunk::getFunction( | |||
1444 | /*HasProto=*/true, | |||
1445 | /*IsAmbiguous=*/false, LParenLoc, ParamInfo.data(), | |||
1446 | ParamInfo.size(), EllipsisLoc, RParenLoc, | |||
1447 | /*RefQualifierIsLvalueRef=*/true, | |||
1448 | /*RefQualifierLoc=*/NoLoc, MutableLoc, ESpecType, ESpecRange, | |||
1449 | DynamicExceptions.data(), DynamicExceptionRanges.data(), | |||
1450 | DynamicExceptions.size(), | |||
1451 | NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr, | |||
1452 | /*ExceptionSpecTokens*/ nullptr, | |||
1453 | /*DeclsInPrototype=*/std::nullopt, LParenLoc, FunLocalRangeEnd, | |||
1454 | D, TrailingReturnType, TrailingReturnTypeLoc, &DS), | |||
1455 | std::move(Attributes), DeclEndLoc); | |||
1456 | ||||
1457 | Actions.ActOnLambdaClosureQualifiers(Intro, MutableLoc); | |||
1458 | ||||
1459 | if (HasParentheses && Tok.is(tok::kw_requires)) | |||
1460 | ParseTrailingRequiresClause(D); | |||
1461 | }; | |||
1462 | ||||
1463 | ParseScope Prototype(this, Scope::FunctionPrototypeScope | | |||
1464 | Scope::FunctionDeclarationScope | | |||
1465 | Scope::DeclScope); | |||
1466 | ||||
1467 | // Parse parameter-declaration-clause. | |||
1468 | SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; | |||
1469 | SourceLocation EllipsisLoc; | |||
1470 | ||||
1471 | if (Tok.is(tok::l_paren)) { | |||
1472 | BalancedDelimiterTracker T(*this, tok::l_paren); | |||
1473 | T.consumeOpen(); | |||
1474 | LParenLoc = T.getOpenLocation(); | |||
1475 | ||||
1476 | if (Tok.isNot(tok::r_paren)) { | |||
1477 | Actions.RecordParsingTemplateParameterDepth( | |||
1478 | CurTemplateDepthTracker.getOriginalDepth()); | |||
1479 | ||||
1480 | ParseParameterDeclarationClause(D, Attributes, ParamInfo, EllipsisLoc); | |||
1481 | // For a generic lambda, each 'auto' within the parameter declaration | |||
1482 | // clause creates a template type parameter, so increment the depth. | |||
1483 | // If we've parsed any explicit template parameters, then the depth will | |||
1484 | // have already been incremented. So we make sure that at most a single | |||
1485 | // depth level is added. | |||
1486 | if (Actions.getCurGenericLambda()) | |||
1487 | CurTemplateDepthTracker.setAddedDepth(1); | |||
1488 | } | |||
1489 | ||||
1490 | T.consumeClose(); | |||
1491 | DeclEndLoc = RParenLoc = T.getCloseLocation(); | |||
1492 | HasParentheses = true; | |||
1493 | } | |||
1494 | ||||
1495 | HasSpecifiers = | |||
1496 | Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute, | |||
1497 | tok::kw_constexpr, tok::kw_consteval, tok::kw_static, | |||
1498 | tok::kw___private, tok::kw___global, tok::kw___local, | |||
1499 | tok::kw___constant, tok::kw___generic, tok::kw_groupshared, | |||
1500 | tok::kw_requires, tok::kw_noexcept) || | |||
1501 | (Tok.is(tok::l_square) && NextToken().is(tok::l_square)); | |||
1502 | ||||
1503 | if (HasSpecifiers && !HasParentheses && !getLangOpts().CPlusPlus2b) { | |||
1504 | // It's common to forget that one needs '()' before 'mutable', an | |||
1505 | // attribute specifier, the result type, or the requires clause. Deal with | |||
1506 | // this. | |||
1507 | Diag(Tok, diag::ext_lambda_missing_parens) | |||
1508 | << FixItHint::CreateInsertion(Tok.getLocation(), "() "); | |||
1509 | } | |||
1510 | ||||
1511 | if (HasParentheses || HasSpecifiers) | |||
1512 | ParseConstexprAndMutableSpecifiers(); | |||
1513 | ||||
1514 | Actions.ActOnLambdaClosureParameters(getCurScope(), ParamInfo); | |||
1515 | ||||
1516 | if (!HasParentheses) | |||
1517 | Actions.ActOnLambdaClosureQualifiers(Intro, MutableLoc); | |||
1518 | ||||
1519 | if (HasSpecifiers || HasParentheses) | |||
1520 | ParseLambdaSpecifiers(ParamInfo, EllipsisLoc); | |||
1521 | ||||
1522 | WarnIfHasCUDATargetAttr(); | |||
1523 | ||||
1524 | Prototype.Exit(); | |||
1525 | ||||
1526 | // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using | |||
1527 | // it. | |||
1528 | unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope | | |||
1529 | Scope::CompoundStmtScope; | |||
1530 | ParseScope BodyScope(this, ScopeFlags); | |||
1531 | ||||
1532 | Actions.ActOnStartOfLambdaDefinition(Intro, D, DS); | |||
1533 | ||||
1534 | // Parse compound-statement. | |||
1535 | if (!Tok.is(tok::l_brace)) { | |||
1536 | Diag(Tok, diag::err_expected_lambda_body); | |||
1537 | Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope()); | |||
1538 | return ExprError(); | |||
1539 | } | |||
1540 | ||||
1541 | StmtResult Stmt(ParseCompoundStatementBody()); | |||
1542 | BodyScope.Exit(); | |||
1543 | TemplateParamScope.Exit(); | |||
1544 | LambdaScope.Exit(); | |||
1545 | ||||
1546 | if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid()) | |||
1547 | return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope()); | |||
1548 | ||||
1549 | Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope()); | |||
1550 | return ExprError(); | |||
1551 | } | |||
1552 | ||||
1553 | /// ParseCXXCasts - This handles the various ways to cast expressions to another | |||
1554 | /// type. | |||
1555 | /// | |||
1556 | /// postfix-expression: [C++ 5.2p1] | |||
1557 | /// 'dynamic_cast' '<' type-name '>' '(' expression ')' | |||
1558 | /// 'static_cast' '<' type-name '>' '(' expression ')' | |||
1559 | /// 'reinterpret_cast' '<' type-name '>' '(' expression ')' | |||
1560 | /// 'const_cast' '<' type-name '>' '(' expression ')' | |||
1561 | /// | |||
1562 | /// C++ for OpenCL s2.3.1 adds: | |||
1563 | /// 'addrspace_cast' '<' type-name '>' '(' expression ')' | |||
1564 | ExprResult Parser::ParseCXXCasts() { | |||
1565 | tok::TokenKind Kind = Tok.getKind(); | |||
1566 | const char *CastName = nullptr; // For error messages | |||
1567 | ||||
1568 | switch (Kind) { | |||
1569 | default: llvm_unreachable("Unknown C++ cast!")::llvm::llvm_unreachable_internal("Unknown C++ cast!", "clang/lib/Parse/ParseExprCXX.cpp" , 1569); | |||
1570 | case tok::kw_addrspace_cast: CastName = "addrspace_cast"; break; | |||
1571 | case tok::kw_const_cast: CastName = "const_cast"; break; | |||
1572 | case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break; | |||
1573 | case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break; | |||
1574 | case tok::kw_static_cast: CastName = "static_cast"; break; | |||
1575 | } | |||
1576 | ||||
1577 | SourceLocation OpLoc = ConsumeToken(); | |||
1578 | SourceLocation LAngleBracketLoc = Tok.getLocation(); | |||
1579 | ||||
1580 | // Check for "<::" which is parsed as "[:". If found, fix token stream, | |||
1581 | // diagnose error, suggest fix, and recover parsing. | |||
1582 | if (Tok.is(tok::l_square) && Tok.getLength() == 2) { | |||
1583 | Token Next = NextToken(); | |||
1584 | if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next)) | |||
1585 | FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true); | |||
1586 | } | |||
1587 | ||||
1588 | if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName)) | |||
1589 | return ExprError(); | |||
1590 | ||||
1591 | // Parse the common declaration-specifiers piece. | |||
1592 | DeclSpec DS(AttrFactory); | |||
1593 | ParseSpecifierQualifierList(DS, /*AccessSpecifier=*/AS_none, | |||
1594 | DeclSpecContext::DSC_type_specifier); | |||
1595 | ||||
1596 | // Parse the abstract-declarator, if present. | |||
1597 | Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), | |||
1598 | DeclaratorContext::TypeName); | |||
1599 | ParseDeclarator(DeclaratorInfo); | |||
1600 | ||||
1601 | SourceLocation RAngleBracketLoc = Tok.getLocation(); | |||
1602 | ||||
1603 | if (ExpectAndConsume(tok::greater)) | |||
1604 | return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less); | |||
1605 | ||||
1606 | BalancedDelimiterTracker T(*this, tok::l_paren); | |||
1607 | ||||
1608 | if (T.expectAndConsume(diag::err_expected_lparen_after, CastName)) | |||
1609 | return ExprError(); | |||
1610 | ||||
1611 | ExprResult Result = ParseExpression(); | |||
1612 | ||||
1613 | // Match the ')'. | |||
1614 | T.consumeClose(); | |||
1615 | ||||
1616 | if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType()) | |||
1617 | Result = Actions.ActOnCXXNamedCast(OpLoc, Kind, | |||
1618 | LAngleBracketLoc, DeclaratorInfo, | |||
1619 | RAngleBracketLoc, | |||
1620 | T.getOpenLocation(), Result.get(), | |||
1621 | T.getCloseLocation()); | |||
1622 | ||||
1623 | return Result; | |||
1624 | } | |||
1625 | ||||
1626 | /// ParseCXXTypeid - This handles the C++ typeid expression. | |||
1627 | /// | |||
1628 | /// postfix-expression: [C++ 5.2p1] | |||
1629 | /// 'typeid' '(' expression ')' | |||
1630 | /// 'typeid' '(' type-id ')' | |||
1631 | /// | |||
1632 | ExprResult Parser::ParseCXXTypeid() { | |||
1633 | assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!")(static_cast <bool> (Tok.is(tok::kw_typeid) && "Not 'typeid'!" ) ? void (0) : __assert_fail ("Tok.is(tok::kw_typeid) && \"Not 'typeid'!\"" , "clang/lib/Parse/ParseExprCXX.cpp", 1633, __extension__ __PRETTY_FUNCTION__ )); | |||
1634 | ||||
1635 | SourceLocation OpLoc = ConsumeToken(); | |||
1636 | SourceLocation LParenLoc, RParenLoc; | |||
1637 | BalancedDelimiterTracker T(*this, tok::l_paren); | |||
1638 | ||||
1639 | // typeid expressions are always parenthesized. | |||
1640 | if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid")) | |||
1641 | return ExprError(); | |||
1642 | LParenLoc = T.getOpenLocation(); | |||
1643 | ||||
1644 | ExprResult Result; | |||
1645 | ||||
1646 | // C++0x [expr.typeid]p3: | |||
1647 | // When typeid is applied to an expression other than an lvalue of a | |||
1648 | // polymorphic class type [...] The expression is an unevaluated | |||
1649 | // operand (Clause 5). | |||
1650 | // | |||
1651 | // Note that we can't tell whether the expression is an lvalue of a | |||
1652 | // polymorphic class type until after we've parsed the expression; we | |||
1653 | // speculatively assume the subexpression is unevaluated, and fix it up | |||
1654 | // later. | |||
1655 | // | |||
1656 | // We enter the unevaluated context before trying to determine whether we | |||
1657 | // have a type-id, because the tentative parse logic will try to resolve | |||
1658 | // names, and must treat them as unevaluated. | |||
1659 | EnterExpressionEvaluationContext Unevaluated( | |||
1660 | Actions, Sema::ExpressionEvaluationContext::Unevaluated, | |||
1661 | Sema::ReuseLambdaContextDecl); | |||
1662 | ||||
1663 | if (isTypeIdInParens()) { | |||
1664 | TypeResult Ty = ParseTypeName(); | |||
1665 | ||||
1666 | // Match the ')'. | |||
1667 | T.consumeClose(); | |||
1668 | RParenLoc = T.getCloseLocation(); | |||
1669 | if (Ty.isInvalid() || RParenLoc.isInvalid()) | |||
1670 | return ExprError(); | |||
1671 | ||||
1672 | Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true, | |||
1673 | Ty.get().getAsOpaquePtr(), RParenLoc); | |||
1674 | } else { | |||
1675 | Result = ParseExpression(); | |||
1676 | ||||
1677 | // Match the ')'. | |||
1678 | if (Result.isInvalid()) | |||
1679 | SkipUntil(tok::r_paren, StopAtSemi); | |||
1680 | else { | |||
1681 | T.consumeClose(); | |||
1682 | RParenLoc = T.getCloseLocation(); | |||
1683 | if (RParenLoc.isInvalid()) | |||
1684 | return ExprError(); | |||
1685 | ||||
1686 | Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false, | |||
1687 | Result.get(), RParenLoc); | |||
1688 | } | |||
1689 | } | |||
1690 | ||||
1691 | return Result; | |||
1692 | } | |||
1693 | ||||
1694 | /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression. | |||
1695 | /// | |||
1696 | /// '__uuidof' '(' expression ')' | |||
1697 | /// '__uuidof' '(' type-id ')' | |||
1698 | /// | |||
1699 | ExprResult Parser::ParseCXXUuidof() { | |||
1700 | assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!")(static_cast <bool> (Tok.is(tok::kw___uuidof) && "Not '__uuidof'!") ? void (0) : __assert_fail ("Tok.is(tok::kw___uuidof) && \"Not '__uuidof'!\"" , "clang/lib/Parse/ParseExprCXX.cpp", 1700, __extension__ __PRETTY_FUNCTION__ )); | |||
1701 | ||||
1702 | SourceLocation OpLoc = ConsumeToken(); | |||
1703 | BalancedDelimiterTracker T(*this, tok::l_paren); | |||
1704 | ||||
1705 | // __uuidof expressions are always parenthesized. | |||
1706 | if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof")) | |||
1707 | return ExprError(); | |||
1708 | ||||
1709 | ExprResult Result; | |||
1710 | ||||
1711 | if (isTypeIdInParens()) { | |||
1712 | TypeResult Ty = ParseTypeName(); | |||
1713 | ||||
1714 | // Match the ')'. | |||
1715 | T.consumeClose(); | |||
1716 | ||||
1717 | if (Ty.isInvalid()) | |||
1718 | return ExprError(); | |||
1719 | ||||
1720 | Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true, | |||
1721 | Ty.get().getAsOpaquePtr(), | |||
1722 | T.getCloseLocation()); | |||
1723 | } else { | |||
1724 | EnterExpressionEvaluationContext Unevaluated( | |||
1725 | Actions, Sema::ExpressionEvaluationContext::Unevaluated); | |||
1726 | Result = ParseExpression(); | |||
1727 | ||||
1728 | // Match the ')'. | |||
1729 | if (Result.isInvalid()) | |||
1730 | SkipUntil(tok::r_paren, StopAtSemi); | |||
1731 | else { | |||
1732 | T.consumeClose(); | |||
1733 | ||||
1734 | Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), | |||
1735 | /*isType=*/false, | |||
1736 | Result.get(), T.getCloseLocation()); | |||
1737 | } | |||
1738 | } | |||
1739 | ||||
1740 | return Result; | |||
1741 | } | |||
1742 | ||||
1743 | /// Parse a C++ pseudo-destructor expression after the base, | |||
1744 | /// . or -> operator, and nested-name-specifier have already been | |||
1745 | /// parsed. We're handling this fragment of the grammar: | |||
1746 | /// | |||
1747 | /// postfix-expression: [C++2a expr.post] | |||
1748 | /// postfix-expression . template[opt] id-expression | |||
1749 | /// postfix-expression -> template[opt] id-expression | |||
1750 | /// | |||
1751 | /// id-expression: | |||
1752 | /// qualified-id | |||
1753 | /// unqualified-id | |||
1754 | /// | |||
1755 | /// qualified-id: | |||
1756 | /// nested-name-specifier template[opt] unqualified-id | |||
1757 | /// | |||
1758 | /// nested-name-specifier: | |||
1759 | /// type-name :: | |||
1760 | /// decltype-specifier :: FIXME: not implemented, but probably only | |||
1761 | /// allowed in C++ grammar by accident | |||
1762 | /// nested-name-specifier identifier :: | |||
1763 | /// nested-name-specifier template[opt] simple-template-id :: | |||
1764 | /// [...] | |||
1765 | /// | |||
1766 | /// unqualified-id: | |||
1767 | /// ~ type-name | |||
1768 | /// ~ decltype-specifier | |||
1769 | /// [...] | |||
1770 | /// | |||
1771 | /// ... where the all but the last component of the nested-name-specifier | |||
1772 | /// has already been parsed, and the base expression is not of a non-dependent | |||
1773 | /// class type. | |||
1774 | ExprResult | |||
1775 | Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc, | |||
1776 | tok::TokenKind OpKind, | |||
1777 | CXXScopeSpec &SS, | |||
1778 | ParsedType ObjectType) { | |||
1779 | // If the last component of the (optional) nested-name-specifier is | |||
1780 | // template[opt] simple-template-id, it has already been annotated. | |||
1781 | UnqualifiedId FirstTypeName; | |||
1782 | SourceLocation CCLoc; | |||
1783 | if (Tok.is(tok::identifier)) { | |||
1784 | FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); | |||
1785 | ConsumeToken(); | |||
1786 | assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail")(static_cast <bool> (Tok.is(tok::coloncolon) && "ParseOptionalCXXScopeSpecifier fail") ? void (0) : __assert_fail ("Tok.is(tok::coloncolon) &&\"ParseOptionalCXXScopeSpecifier fail\"" , "clang/lib/Parse/ParseExprCXX.cpp", 1786, __extension__ __PRETTY_FUNCTION__ )); | |||
1787 | CCLoc = ConsumeToken(); | |||
1788 | } else if (Tok.is(tok::annot_template_id)) { | |||
1789 | TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); | |||
1790 | // FIXME: Carry on and build an AST representation for tooling. | |||
1791 | if (TemplateId->isInvalid()) | |||
1792 | return ExprError(); | |||
1793 | FirstTypeName.setTemplateId(TemplateId); | |||
1794 | ConsumeAnnotationToken(); | |||
1795 | assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail")(static_cast <bool> (Tok.is(tok::coloncolon) && "ParseOptionalCXXScopeSpecifier fail") ? void (0) : __assert_fail ("Tok.is(tok::coloncolon) &&\"ParseOptionalCXXScopeSpecifier fail\"" , "clang/lib/Parse/ParseExprCXX.cpp", 1795, __extension__ __PRETTY_FUNCTION__ )); | |||
1796 | CCLoc = ConsumeToken(); | |||
1797 | } else { | |||
1798 | assert(SS.isEmpty() && "missing last component of nested name specifier")(static_cast <bool> (SS.isEmpty() && "missing last component of nested name specifier" ) ? void (0) : __assert_fail ("SS.isEmpty() && \"missing last component of nested name specifier\"" , "clang/lib/Parse/ParseExprCXX.cpp", 1798, __extension__ __PRETTY_FUNCTION__ )); | |||
1799 | FirstTypeName.setIdentifier(nullptr, SourceLocation()); | |||
1800 | } | |||
1801 | ||||
1802 | // Parse the tilde. | |||
1803 | assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail")(static_cast <bool> (Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail" ) ? void (0) : __assert_fail ("Tok.is(tok::tilde) && \"ParseOptionalCXXScopeSpecifier fail\"" , "clang/lib/Parse/ParseExprCXX.cpp", 1803, __extension__ __PRETTY_FUNCTION__ )); | |||
1804 | SourceLocation TildeLoc = ConsumeToken(); | |||
1805 | ||||
1806 | if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid()) { | |||
1807 | DeclSpec DS(AttrFactory); | |||
1808 | ParseDecltypeSpecifier(DS); | |||
1809 | if (DS.getTypeSpecType() == TST_error) | |||
1810 | return ExprError(); | |||
1811 | return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind, | |||
1812 | TildeLoc, DS); | |||
1813 | } | |||
1814 | ||||
1815 | if (!Tok.is(tok::identifier)) { | |||
1816 | Diag(Tok, diag::err_destructor_tilde_identifier); | |||
1817 | return ExprError(); | |||
1818 | } | |||
1819 | ||||
1820 | // Parse the second type. | |||
1821 | UnqualifiedId SecondTypeName; | |||
1822 | IdentifierInfo *Name = Tok.getIdentifierInfo(); | |||
1823 | SourceLocation NameLoc = ConsumeToken(); | |||
1824 | SecondTypeName.setIdentifier(Name, NameLoc); | |||
1825 | ||||
1826 | // If there is a '<', the second type name is a template-id. Parse | |||
1827 | // it as such. | |||
1828 | // | |||
1829 | // FIXME: This is not a context in which a '<' is assumed to start a template | |||
1830 | // argument list. This affects examples such as | |||
1831 | // void f(auto *p) { p->~X<int>(); } | |||
1832 | // ... but there's no ambiguity, and nowhere to write 'template' in such an | |||
1833 | // example, so we accept it anyway. | |||
1834 | if (Tok.is(tok::less) && | |||
1835 | ParseUnqualifiedIdTemplateId( | |||
1836 | SS, ObjectType, Base && Base->containsErrors(), SourceLocation(), | |||
1837 | Name, NameLoc, false, SecondTypeName, | |||
1838 | /*AssumeTemplateId=*/true)) | |||
1839 | return ExprError(); | |||
1840 | ||||
1841 | return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind, | |||
1842 | SS, FirstTypeName, CCLoc, TildeLoc, | |||
1843 | SecondTypeName); | |||
1844 | } | |||
1845 | ||||
1846 | /// ParseCXXBoolLiteral - This handles the C++ Boolean literals. | |||
1847 | /// | |||
1848 | /// boolean-literal: [C++ 2.13.5] | |||
1849 | /// 'true' | |||
1850 | /// 'false' | |||
1851 | ExprResult Parser::ParseCXXBoolLiteral() { | |||
1852 | tok::TokenKind Kind = Tok.getKind(); | |||
1853 | return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind); | |||
1854 | } | |||
1855 | ||||
1856 | /// ParseThrowExpression - This handles the C++ throw expression. | |||
1857 | /// | |||
1858 | /// throw-expression: [C++ 15] | |||
1859 | /// 'throw' assignment-expression[opt] | |||
1860 | ExprResult Parser::ParseThrowExpression() { | |||
1861 | assert(Tok.is(tok::kw_throw) && "Not throw!")(static_cast <bool> (Tok.is(tok::kw_throw) && "Not throw!" ) ? void (0) : __assert_fail ("Tok.is(tok::kw_throw) && \"Not throw!\"" , "clang/lib/Parse/ParseExprCXX.cpp", 1861, __extension__ __PRETTY_FUNCTION__ )); | |||
1862 | SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token. | |||
1863 | ||||
1864 | // If the current token isn't the start of an assignment-expression, | |||
1865 | // then the expression is not present. This handles things like: | |||
1866 | // "C ? throw : (void)42", which is crazy but legal. | |||
1867 | switch (Tok.getKind()) { // FIXME: move this predicate somewhere common. | |||
1868 | case tok::semi: | |||
1869 | case tok::r_paren: | |||
1870 | case tok::r_square: | |||
1871 | case tok::r_brace: | |||
1872 | case tok::colon: | |||
1873 | case tok::comma: | |||
1874 | return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr); | |||
1875 | ||||
1876 | default: | |||
1877 | ExprResult Expr(ParseAssignmentExpression()); | |||
1878 | if (Expr.isInvalid()) return Expr; | |||
1879 | return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get()); | |||
1880 | } | |||
1881 | } | |||
1882 | ||||
1883 | /// Parse the C++ Coroutines co_yield expression. | |||
1884 | /// | |||
1885 | /// co_yield-expression: | |||
1886 | /// 'co_yield' assignment-expression[opt] | |||
1887 | ExprResult Parser::ParseCoyieldExpression() { | |||
1888 | assert(Tok.is(tok::kw_co_yield) && "Not co_yield!")(static_cast <bool> (Tok.is(tok::kw_co_yield) && "Not co_yield!") ? void (0) : __assert_fail ("Tok.is(tok::kw_co_yield) && \"Not co_yield!\"" , "clang/lib/Parse/ParseExprCXX.cpp", 1888, __extension__ __PRETTY_FUNCTION__ )); | |||
1889 | ||||
1890 | SourceLocation Loc = ConsumeToken(); | |||
1891 | ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer() | |||
1892 | : ParseAssignmentExpression(); | |||
1893 | if (!Expr.isInvalid()) | |||
1894 | Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get()); | |||
1895 | return Expr; | |||
1896 | } | |||
1897 | ||||
1898 | /// ParseCXXThis - This handles the C++ 'this' pointer. | |||
1899 | /// | |||
1900 | /// C++ 9.3.2: In the body of a non-static member function, the keyword this is | |||
1901 | /// a non-lvalue expression whose value is the address of the object for which | |||
1902 | /// the function is called. | |||
1903 | ExprResult Parser::ParseCXXThis() { | |||
1904 | assert(Tok.is(tok::kw_this) && "Not 'this'!")(static_cast <bool> (Tok.is(tok::kw_this) && "Not 'this'!" ) ? void (0) : __assert_fail ("Tok.is(tok::kw_this) && \"Not 'this'!\"" , "clang/lib/Parse/ParseExprCXX.cpp", 1904, __extension__ __PRETTY_FUNCTION__ )); | |||
1905 | SourceLocation ThisLoc = ConsumeToken(); | |||
1906 | return Actions.ActOnCXXThis(ThisLoc); | |||
1907 | } | |||
1908 | ||||
1909 | /// ParseCXXTypeConstructExpression - Parse construction of a specified type. | |||
1910 | /// Can be interpreted either as function-style casting ("int(x)") | |||
1911 | /// or class type construction ("ClassType(x,y,z)") | |||
1912 | /// or creation of a value-initialized type ("int()"). | |||
1913 | /// See [C++ 5.2.3]. | |||
1914 | /// | |||
1915 | /// postfix-expression: [C++ 5.2p1] | |||
1916 | /// simple-type-specifier '(' expression-list[opt] ')' | |||
1917 | /// [C++0x] simple-type-specifier braced-init-list | |||
1918 | /// typename-specifier '(' expression-list[opt] ')' | |||
1919 | /// [C++0x] typename-specifier braced-init-list | |||
1920 | /// | |||
1921 | /// In C++1z onwards, the type specifier can also be a template-name. | |||
1922 | ExprResult | |||
1923 | Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) { | |||
1924 | Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), | |||
1925 | DeclaratorContext::FunctionalCast); | |||
1926 | ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get(); | |||
1927 | ||||
1928 | assert((Tok.is(tok::l_paren) ||(static_cast <bool> ((Tok.is(tok::l_paren) || (getLangOpts ().CPlusPlus11 && Tok.is(tok::l_brace))) && "Expected '(' or '{'!" ) ? void (0) : __assert_fail ("(Tok.is(tok::l_paren) || (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))) && \"Expected '(' or '{'!\"" , "clang/lib/Parse/ParseExprCXX.cpp", 1930, __extension__ __PRETTY_FUNCTION__ )) | |||
1929 | (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))(static_cast <bool> ((Tok.is(tok::l_paren) || (getLangOpts ().CPlusPlus11 && Tok.is(tok::l_brace))) && "Expected '(' or '{'!" ) ? void (0) : __assert_fail ("(Tok.is(tok::l_paren) || (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))) && \"Expected '(' or '{'!\"" , "clang/lib/Parse/ParseExprCXX.cpp", 1930, __extension__ __PRETTY_FUNCTION__ )) | |||
1930 | && "Expected '(' or '{'!")(static_cast <bool> ((Tok.is(tok::l_paren) || (getLangOpts ().CPlusPlus11 && Tok.is(tok::l_brace))) && "Expected '(' or '{'!" ) ? void (0) : __assert_fail ("(Tok.is(tok::l_paren) || (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))) && \"Expected '(' or '{'!\"" , "clang/lib/Parse/ParseExprCXX.cpp", 1930, __extension__ __PRETTY_FUNCTION__ )); | |||
1931 | ||||
1932 | if (Tok.is(tok::l_brace)) { | |||
1933 | PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get()); | |||
1934 | ExprResult Init = ParseBraceInitializer(); | |||
1935 | if (Init.isInvalid()) | |||
1936 | return Init; | |||
1937 | Expr *InitList = Init.get(); | |||
1938 | return Actions.ActOnCXXTypeConstructExpr( | |||
1939 | TypeRep, InitList->getBeginLoc(), MultiExprArg(&InitList, 1), | |||
1940 | InitList->getEndLoc(), /*ListInitialization=*/true); | |||
1941 | } else { | |||
1942 | BalancedDelimiterTracker T(*this, tok::l_paren); | |||
1943 | T.consumeOpen(); | |||
1944 | ||||
1945 | PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get()); | |||
1946 | ||||
1947 | ExprVector Exprs; | |||
1948 | ||||
1949 | auto RunSignatureHelp = [&]() { | |||
1950 | QualType PreferredType; | |||
1951 | if (TypeRep) | |||
1952 | PreferredType = Actions.ProduceConstructorSignatureHelp( | |||
1953 | TypeRep.get()->getCanonicalTypeInternal(), DS.getEndLoc(), Exprs, | |||
1954 | T.getOpenLocation(), /*Braced=*/false); | |||
1955 | CalledSignatureHelp = true; | |||
1956 | return PreferredType; | |||
1957 | }; | |||
1958 | ||||
1959 | if (Tok.isNot(tok::r_paren)) { | |||
1960 | if (ParseExpressionList(Exprs, [&] { | |||
1961 | PreferredType.enterFunctionArgument(Tok.getLocation(), | |||
1962 | RunSignatureHelp); | |||
1963 | })) { | |||
1964 | if (PP.isCodeCompletionReached() && !CalledSignatureHelp) | |||
1965 | RunSignatureHelp(); | |||
1966 | SkipUntil(tok::r_paren, StopAtSemi); | |||
1967 | return ExprError(); | |||
1968 | } | |||
1969 | } | |||
1970 | ||||
1971 | // Match the ')'. | |||
1972 | T.consumeClose(); | |||
1973 | ||||
1974 | // TypeRep could be null, if it references an invalid typedef. | |||
1975 | if (!TypeRep) | |||
1976 | return ExprError(); | |||
1977 | ||||
1978 | return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(), | |||
1979 | Exprs, T.getCloseLocation(), | |||
1980 | /*ListInitialization=*/false); | |||
1981 | } | |||
1982 | } | |||
1983 | ||||
1984 | Parser::DeclGroupPtrTy | |||
1985 | Parser::ParseAliasDeclarationInInitStatement(DeclaratorContext Context, | |||
1986 | ParsedAttributes &Attrs) { | |||
1987 | assert(Tok.is(tok::kw_using) && "Expected using")(static_cast <bool> (Tok.is(tok::kw_using) && "Expected using" ) ? void (0) : __assert_fail ("Tok.is(tok::kw_using) && \"Expected using\"" , "clang/lib/Parse/ParseExprCXX.cpp", 1987, __extension__ __PRETTY_FUNCTION__ )); | |||
1988 | assert((Context == DeclaratorContext::ForInit ||(static_cast <bool> ((Context == DeclaratorContext::ForInit || Context == DeclaratorContext::SelectionInit) && "Unexpected Declarator Context" ) ? void (0) : __assert_fail ("(Context == DeclaratorContext::ForInit || Context == DeclaratorContext::SelectionInit) && \"Unexpected Declarator Context\"" , "clang/lib/Parse/ParseExprCXX.cpp", 1990, __extension__ __PRETTY_FUNCTION__ )) | |||
1989 | Context == DeclaratorContext::SelectionInit) &&(static_cast <bool> ((Context == DeclaratorContext::ForInit || Context == DeclaratorContext::SelectionInit) && "Unexpected Declarator Context" ) ? void (0) : __assert_fail ("(Context == DeclaratorContext::ForInit || Context == DeclaratorContext::SelectionInit) && \"Unexpected Declarator Context\"" , "clang/lib/Parse/ParseExprCXX.cpp", 1990, __extension__ __PRETTY_FUNCTION__ )) | |||
1990 | "Unexpected Declarator Context")(static_cast <bool> ((Context == DeclaratorContext::ForInit || Context == DeclaratorContext::SelectionInit) && "Unexpected Declarator Context" ) ? void (0) : __assert_fail ("(Context == DeclaratorContext::ForInit || Context == DeclaratorContext::SelectionInit) && \"Unexpected Declarator Context\"" , "clang/lib/Parse/ParseExprCXX.cpp", 1990, __extension__ __PRETTY_FUNCTION__ )); | |||
1991 | DeclGroupPtrTy DG; | |||
1992 | SourceLocation DeclStart = ConsumeToken(), DeclEnd; | |||
1993 | ||||
1994 | DG = ParseUsingDeclaration(Context, {}, DeclStart, DeclEnd, Attrs, AS_none); | |||
1995 | if (!DG) | |||
1996 | return DG; | |||
1997 | ||||
1998 | Diag(DeclStart, !getLangOpts().CPlusPlus2b | |||
1999 | ? diag::ext_alias_in_init_statement | |||
2000 | : diag::warn_cxx20_alias_in_init_statement) | |||
2001 | << SourceRange(DeclStart, DeclEnd); | |||
2002 | ||||
2003 | return DG; | |||
2004 | } | |||
2005 | ||||
2006 | /// ParseCXXCondition - if/switch/while condition expression. | |||
2007 | /// | |||
2008 | /// condition: | |||
2009 | /// expression | |||
2010 | /// type-specifier-seq declarator '=' assignment-expression | |||
2011 | /// [C++11] type-specifier-seq declarator '=' initializer-clause | |||
2012 | /// [C++11] type-specifier-seq declarator braced-init-list | |||
2013 | /// [Clang] type-specifier-seq ref-qualifier[opt] '[' identifier-list ']' | |||
2014 | /// brace-or-equal-initializer | |||
2015 | /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt] | |||
2016 | /// '=' assignment-expression | |||
2017 | /// | |||
2018 | /// In C++1z, a condition may in some contexts be preceded by an | |||
2019 | /// optional init-statement. This function will parse that too. | |||
2020 | /// | |||
2021 | /// \param InitStmt If non-null, an init-statement is permitted, and if present | |||
2022 | /// will be parsed and stored here. | |||
2023 | /// | |||
2024 | /// \param Loc The location of the start of the statement that requires this | |||
2025 | /// condition, e.g., the "for" in a for loop. | |||
2026 | /// | |||
2027 | /// \param MissingOK Whether an empty condition is acceptable here. Otherwise | |||
2028 | /// it is considered an error to be recovered from. | |||
2029 | /// | |||
2030 | /// \param FRI If non-null, a for range declaration is permitted, and if | |||
2031 | /// present will be parsed and stored here, and a null result will be returned. | |||
2032 | /// | |||
2033 | /// \param EnterForConditionScope If true, enter a continue/break scope at the | |||
2034 | /// appropriate moment for a 'for' loop. | |||
2035 | /// | |||
2036 | /// \returns The parsed condition. | |||
2037 | Sema::ConditionResult | |||
2038 | Parser::ParseCXXCondition(StmtResult *InitStmt, SourceLocation Loc, | |||
2039 | Sema::ConditionKind CK, bool MissingOK, | |||
2040 | ForRangeInfo *FRI, bool EnterForConditionScope) { | |||
2041 | // Helper to ensure we always enter a continue/break scope if requested. | |||
2042 | struct ForConditionScopeRAII { | |||
2043 | Scope *S; | |||
2044 | void enter(bool IsConditionVariable) { | |||
2045 | if (S) { | |||
2046 | S->AddFlags(Scope::BreakScope | Scope::ContinueScope); | |||
2047 | S->setIsConditionVarScope(IsConditionVariable); | |||
2048 | } | |||
2049 | } | |||
2050 | ~ForConditionScopeRAII() { | |||
2051 | if (S) | |||
2052 | S->setIsConditionVarScope(false); | |||
2053 | } | |||
2054 | } ForConditionScope{EnterForConditionScope
| |||
| ||||
2055 | ||||
2056 | ParenBraceBracketBalancer BalancerRAIIObj(*this); | |||
2057 | PreferredType.enterCondition(Actions, Tok.getLocation()); | |||
2058 | ||||
2059 | if (Tok.is(tok::code_completion)) { | |||
2060 | cutOffParsing(); | |||
2061 | Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition); | |||
2062 | return Sema::ConditionError(); | |||
2063 | } | |||
2064 | ||||
2065 | ParsedAttributes attrs(AttrFactory); | |||
2066 | MaybeParseCXX11Attributes(attrs); | |||
2067 | ||||
2068 | const auto WarnOnInit = [this, &CK] { | |||
2069 | Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 | |||
2070 | ? diag::warn_cxx14_compat_init_statement | |||
2071 | : diag::ext_init_statement) | |||
2072 | << (CK == Sema::ConditionKind::Switch); | |||
2073 | }; | |||
2074 | ||||
2075 | // Determine what kind of thing we have. | |||
2076 | switch (isCXXConditionDeclarationOrInitStatement(InitStmt, FRI)) { | |||
2077 | case ConditionOrInitStatement::Expression: { | |||
2078 | // If this is a for loop, we're entering its condition. | |||
2079 | ForConditionScope.enter(/*IsConditionVariable=*/false); | |||
2080 | ||||
2081 | ProhibitAttributes(attrs); | |||
2082 | ||||
2083 | // We can have an empty expression here. | |||
2084 | // if (; true); | |||
2085 | if (InitStmt && Tok.is(tok::semi)) { | |||
2086 | WarnOnInit(); | |||
2087 | SourceLocation SemiLoc = Tok.getLocation(); | |||
2088 | if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID()) { | |||
2089 | Diag(SemiLoc, diag::warn_empty_init_statement) | |||
2090 | << (CK == Sema::ConditionKind::Switch) | |||
2091 | << FixItHint::CreateRemoval(SemiLoc); | |||
2092 | } | |||
2093 | ConsumeToken(); | |||
2094 | *InitStmt = Actions.ActOnNullStmt(SemiLoc); | |||
2095 | return ParseCXXCondition(nullptr, Loc, CK, MissingOK); | |||
2096 | } | |||
2097 | ||||
2098 | // Parse the expression. | |||
2099 | ExprResult Expr = ParseExpression(); // expression | |||
2100 | if (Expr.isInvalid()) | |||
2101 | return Sema::ConditionError(); | |||
2102 | ||||
2103 | if (InitStmt && Tok.is(tok::semi)) { | |||
2104 | WarnOnInit(); | |||
2105 | *InitStmt = Actions.ActOnExprStmt(Expr.get()); | |||
2106 | ConsumeToken(); | |||
2107 | return ParseCXXCondition(nullptr, Loc, CK, MissingOK); | |||
2108 | } | |||
2109 | ||||
2110 | return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK, | |||
2111 | MissingOK); | |||
2112 | } | |||
2113 | ||||
2114 | case ConditionOrInitStatement::InitStmtDecl: { | |||
2115 | WarnOnInit(); | |||
2116 | DeclGroupPtrTy DG; | |||
2117 | SourceLocation DeclStart = Tok.getLocation(), DeclEnd; | |||
2118 | if (Tok.is(tok::kw_using)) | |||
2119 | DG = ParseAliasDeclarationInInitStatement( | |||
2120 | DeclaratorContext::SelectionInit, attrs); | |||
2121 | else { | |||
2122 | ParsedAttributes DeclSpecAttrs(AttrFactory); | |||
2123 | DG = ParseSimpleDeclaration(DeclaratorContext::SelectionInit, DeclEnd, | |||
2124 | attrs, DeclSpecAttrs, /*RequireSemi=*/true); | |||
2125 | } | |||
2126 | *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd); | |||
| ||||
2127 | return ParseCXXCondition(nullptr, Loc, CK, MissingOK); | |||
2128 | } | |||
2129 | ||||
2130 | case ConditionOrInitStatement::ForRangeDecl: { | |||
2131 | // This is 'for (init-stmt; for-range-decl : range-expr)'. | |||
2132 | // We're not actually in a for loop yet, so 'break' and 'continue' aren't | |||
2133 | // permitted here. | |||
2134 | assert(FRI && "should not parse a for range declaration here")(static_cast <bool> (FRI && "should not parse a for range declaration here" ) ? void (0) : __assert_fail ("FRI && \"should not parse a for range declaration here\"" , "clang/lib/Parse/ParseExprCXX.cpp", 2134, __extension__ __PRETTY_FUNCTION__ )); | |||
2135 | SourceLocation DeclStart = Tok.getLocation(), DeclEnd; | |||
2136 | ParsedAttributes DeclSpecAttrs(AttrFactory); | |||
2137 | DeclGroupPtrTy DG = ParseSimpleDeclaration( | |||
2138 | DeclaratorContext::ForInit, DeclEnd, attrs, DeclSpecAttrs, false, FRI); | |||
2139 | FRI->LoopVar = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation()); | |||
2140 | assert((FRI->ColonLoc.isValid() || !DG) &&(static_cast <bool> ((FRI->ColonLoc.isValid() || !DG ) && "cannot find for range declaration") ? void (0) : __assert_fail ("(FRI->ColonLoc.isValid() || !DG) && \"cannot find for range declaration\"" , "clang/lib/Parse/ParseExprCXX.cpp", 2141, __extension__ __PRETTY_FUNCTION__ )) | |||
2141 | "cannot find for range declaration")(static_cast <bool> ((FRI->ColonLoc.isValid() || !DG ) && "cannot find for range declaration") ? void (0) : __assert_fail ("(FRI->ColonLoc.isValid() || !DG) && \"cannot find for range declaration\"" , "clang/lib/Parse/ParseExprCXX.cpp", 2141, __extension__ __PRETTY_FUNCTION__ )); | |||
2142 | return Sema::ConditionResult(); | |||
2143 | } | |||
2144 | ||||
2145 | case ConditionOrInitStatement::ConditionDecl: | |||
2146 | case ConditionOrInitStatement::Error: | |||
2147 | break; | |||
2148 | } | |||
2149 | ||||
2150 | // If this is a for loop, we're entering its condition. | |||
2151 | ForConditionScope.enter(/*IsConditionVariable=*/true); | |||
2152 | ||||
2153 | // type-specifier-seq | |||
2154 | DeclSpec DS(AttrFactory); | |||
2155 | ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_condition); | |||
2156 | ||||
2157 | // declarator | |||
2158 | Declarator DeclaratorInfo(DS, attrs, DeclaratorContext::Condition); | |||
2159 | ParseDeclarator(DeclaratorInfo); | |||
2160 | ||||
2161 | // simple-asm-expr[opt] | |||
2162 | if (Tok.is(tok::kw_asm)) { | |||
2163 | SourceLocation Loc; | |||
2164 | ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc)); | |||
2165 | if (AsmLabel.isInvalid()) { | |||
2166 | SkipUntil(tok::semi, StopAtSemi); | |||
2167 | return Sema::ConditionError(); | |||
2168 | } | |||
2169 | DeclaratorInfo.setAsmLabel(AsmLabel.get()); | |||
2170 | DeclaratorInfo.SetRangeEnd(Loc); | |||
2171 | } | |||
2172 | ||||
2173 | // If attributes are present, parse them. | |||
2174 | MaybeParseGNUAttributes(DeclaratorInfo); | |||
2175 | ||||
2176 | // Type-check the declaration itself. | |||
2177 | DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(), | |||
2178 | DeclaratorInfo); | |||
2179 | if (Dcl.isInvalid()) | |||
2180 | return Sema::ConditionError(); | |||
2181 | Decl *DeclOut = Dcl.get(); | |||
2182 | ||||
2183 | // '=' assignment-expression | |||
2184 | // If a '==' or '+=' is found, suggest a fixit to '='. | |||
2185 | bool CopyInitialization = isTokenEqualOrEqualTypo(); | |||
2186 | if (CopyInitialization) | |||
2187 | ConsumeToken(); | |||
2188 | ||||
2189 | ExprResult InitExpr = ExprError(); | |||
2190 | if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { | |||
2191 | Diag(Tok.getLocation(), | |||
2192 | diag::warn_cxx98_compat_generalized_initializer_lists); | |||
2193 | InitExpr = ParseBraceInitializer(); | |||
2194 | } else if (CopyInitialization) { | |||
2195 | PreferredType.enterVariableInit(Tok.getLocation(), DeclOut); | |||
2196 | InitExpr = ParseAssignmentExpression(); | |||
2197 | } else if (Tok.is(tok::l_paren)) { | |||
2198 | // This was probably an attempt to initialize the variable. | |||
2199 | SourceLocation LParen = ConsumeParen(), RParen = LParen; | |||
2200 | if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) | |||
2201 | RParen = ConsumeParen(); | |||
2202 | Diag(DeclOut->getLocation(), | |||
2203 | diag::err_expected_init_in_condition_lparen) | |||
2204 | << SourceRange(LParen, RParen); | |||
2205 | } else { | |||
2206 | Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition); | |||
2207 | } | |||
2208 | ||||
2209 | if (!InitExpr.isInvalid()) | |||
2210 | Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization); | |||
2211 | else | |||
2212 | Actions.ActOnInitializerError(DeclOut); | |||
2213 | ||||
2214 | Actions.FinalizeDeclaration(DeclOut); | |||
2215 | return Actions.ActOnConditionVariable(DeclOut, Loc, CK); | |||
2216 | } | |||
2217 | ||||
2218 | /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers. | |||
2219 | /// This should only be called when the current token is known to be part of | |||
2220 | /// simple-type-specifier. | |||
2221 | /// | |||
2222 | /// simple-type-specifier: | |||
2223 | /// '::'[opt] nested-name-specifier[opt] type-name | |||
2224 | /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO] | |||
2225 | /// char | |||
2226 | /// wchar_t | |||
2227 | /// bool | |||
2228 | /// short | |||
2229 | /// int | |||
2230 | /// long | |||
2231 | /// signed | |||
2232 | /// unsigned | |||
2233 | /// float | |||
2234 | /// double | |||
2235 | /// void | |||
2236 | /// [GNU] typeof-specifier | |||
2237 | /// [C++0x] auto [TODO] | |||
2238 | /// | |||
2239 | /// type-name: | |||
2240 | /// class-name | |||
2241 | /// enum-name | |||
2242 | /// typedef-name | |||
2243 | /// | |||
2244 | void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) { | |||
2245 | DS.SetRangeStart(Tok.getLocation()); | |||
2246 | const char *PrevSpec; | |||
2247 | unsigned DiagID; | |||
2248 | SourceLocation Loc = Tok.getLocation(); | |||
2249 | const clang::PrintingPolicy &Policy = | |||
2250 | Actions.getASTContext().getPrintingPolicy(); | |||
2251 | ||||
2252 | switch (Tok.getKind()) { | |||
2253 | case tok::identifier: // foo::bar | |||
2254 | case tok::coloncolon: // ::foo::bar | |||
2255 | llvm_unreachable("Annotation token should already be formed!")::llvm::llvm_unreachable_internal("Annotation token should already be formed!" , "clang/lib/Parse/ParseExprCXX.cpp", 2255); | |||
2256 | default: | |||
2257 | llvm_unreachable("Not a simple-type-specifier token!")::llvm::llvm_unreachable_internal("Not a simple-type-specifier token!" , "clang/lib/Parse/ParseExprCXX.cpp", 2257); | |||
2258 | ||||
2259 | // type-name | |||
2260 | case tok::annot_typename: { | |||
2261 | DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, | |||
2262 | getTypeAnnotation(Tok), Policy); | |||
2263 | DS.SetRangeEnd(Tok.getAnnotationEndLoc()); | |||
2264 | ConsumeAnnotationToken(); | |||
2265 | ||||
2266 | DS.Finish(Actions, Policy); | |||
2267 | return; | |||
2268 | } | |||
2269 | ||||
2270 | case tok::kw__ExtInt: | |||
2271 | case tok::kw__BitInt: { | |||
2272 | DiagnoseBitIntUse(Tok); | |||
2273 | ExprResult ER = ParseExtIntegerArgument(); | |||
2274 | if (ER.isInvalid()) | |||
2275 | DS.SetTypeSpecError(); | |||
2276 | else | |||
2277 | DS.SetBitIntType(Loc, ER.get(), PrevSpec, DiagID, Policy); | |||
2278 | ||||
2279 | // Do this here because we have already consumed the close paren. | |||
2280 | DS.SetRangeEnd(PrevTokLocation); | |||
2281 | DS.Finish(Actions, Policy); | |||
2282 | return; | |||
2283 | } | |||
2284 | ||||
2285 | // builtin types | |||
2286 | case tok::kw_short: | |||
2287 | DS.SetTypeSpecWidth(TypeSpecifierWidth::Short, Loc, PrevSpec, DiagID, | |||
2288 | Policy); | |||
2289 | break; | |||
2290 | case tok::kw_long: | |||
2291 | DS.SetTypeSpecWidth(TypeSpecifierWidth::Long, Loc, PrevSpec, DiagID, | |||
2292 | Policy); | |||
2293 | break; | |||
2294 | case tok::kw___int64: | |||
2295 | DS.SetTypeSpecWidth(TypeSpecifierWidth::LongLong, Loc, PrevSpec, DiagID, | |||
2296 | Policy); | |||
2297 | break; | |||
2298 | case tok::kw_signed: | |||
2299 | DS.SetTypeSpecSign(TypeSpecifierSign::Signed, Loc, PrevSpec, DiagID); | |||
2300 | break; | |||
2301 | case tok::kw_unsigned: | |||
2302 | DS.SetTypeSpecSign(TypeSpecifierSign::Unsigned, Loc, PrevSpec, DiagID); | |||
2303 | break; | |||
2304 | case tok::kw_void: | |||
2305 | DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy); | |||
2306 | break; | |||
2307 | case tok::kw_auto: | |||
2308 | DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, DiagID, Policy); | |||
2309 | break; | |||
2310 | case tok::kw_char: | |||
2311 | DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy); | |||
2312 | break; | |||
2313 | case tok::kw_int: | |||
2314 | DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy); | |||
2315 | break; | |||
2316 | case tok::kw___int128: | |||
2317 | DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy); | |||
2318 | break; | |||
2319 | case tok::kw___bf16: | |||
2320 | DS.SetTypeSpecType(DeclSpec::TST_BFloat16, Loc, PrevSpec, DiagID, Policy); | |||
2321 | break; | |||
2322 | case tok::kw_half: | |||
2323 | DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy); | |||
2324 | break; | |||
2325 | case tok::kw_float: | |||
2326 | DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy); | |||
2327 | break; | |||
2328 | case tok::kw_double: | |||
2329 | DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy); | |||
2330 | break; | |||
2331 | case tok::kw__Float16: | |||
2332 | DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec, DiagID, Policy); | |||
2333 | break; | |||
2334 | case tok::kw___float128: | |||
2335 | DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy); | |||
2336 | break; | |||
2337 | case tok::kw___ibm128: | |||
2338 | DS.SetTypeSpecType(DeclSpec::TST_ibm128, Loc, PrevSpec, DiagID, Policy); | |||
2339 | break; | |||
2340 | case tok::kw_wchar_t: | |||
2341 | DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy); | |||
2342 | break; | |||
2343 | case tok::kw_char8_t: | |||
2344 | DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec, DiagID, Policy); | |||
2345 | break; | |||
2346 | case tok::kw_char16_t: | |||
2347 | DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy); | |||
2348 | break; | |||
2349 | case tok::kw_char32_t: | |||
2350 | DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy); | |||
2351 | break; | |||
2352 | case tok::kw_bool: | |||
2353 | DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy); | |||
2354 | break; | |||
2355 | #define GENERIC_IMAGE_TYPE(ImgType, Id) \ | |||
2356 | case tok::kw_##ImgType##_t: \ | |||
2357 | DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, DiagID, \ | |||
2358 | Policy); \ | |||
2359 | break; | |||
2360 | #include "clang/Basic/OpenCLImageTypes.def" | |||
2361 | ||||
2362 | case tok::annot_decltype: | |||
2363 | case tok::kw_decltype: | |||
2364 | DS.SetRangeEnd(ParseDecltypeSpecifier(DS)); | |||
2365 | return DS.Finish(Actions, Policy); | |||
2366 | ||||
2367 | // GNU typeof support. | |||
2368 | case tok::kw_typeof: | |||
2369 | ParseTypeofSpecifier(DS); | |||
2370 | DS.Finish(Actions, Policy); | |||
2371 | return; | |||
2372 | } | |||
2373 | ConsumeAnyToken(); | |||
2374 | DS.SetRangeEnd(PrevTokLocation); | |||
2375 | DS.Finish(Actions, Policy); | |||
2376 | } | |||
2377 | ||||
2378 | /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++ | |||
2379 | /// [dcl.name]), which is a non-empty sequence of type-specifiers, | |||
2380 | /// e.g., "const short int". Note that the DeclSpec is *not* finished | |||
2381 | /// by parsing the type-specifier-seq, because these sequences are | |||
2382 | /// typically followed by some form of declarator. Returns true and | |||
2383 | /// emits diagnostics if this is not a type-specifier-seq, false | |||
2384 | /// otherwise. | |||
2385 | /// | |||
2386 | /// type-specifier-seq: [C++ 8.1] | |||
2387 | /// type-specifier type-specifier-seq[opt] | |||
2388 | /// | |||
2389 | bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS, DeclaratorContext Context) { | |||
2390 | ParseSpecifierQualifierList(DS, AS_none, | |||
2391 | getDeclSpecContextFromDeclaratorContext(Context)); | |||
2392 | DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy()); | |||
2393 | return false; | |||
2394 | } | |||
2395 | ||||
2396 | /// Finish parsing a C++ unqualified-id that is a template-id of | |||
2397 | /// some form. | |||
2398 | /// | |||
2399 | /// This routine is invoked when a '<' is encountered after an identifier or | |||
2400 | /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine | |||
2401 | /// whether the unqualified-id is actually a template-id. This routine will | |||
2402 | /// then parse the template arguments and form the appropriate template-id to | |||
2403 | /// return to the caller. | |||
2404 | /// | |||
2405 | /// \param SS the nested-name-specifier that precedes this template-id, if | |||
2406 | /// we're actually parsing a qualified-id. | |||
2407 | /// | |||
2408 | /// \param ObjectType if this unqualified-id occurs within a member access | |||
2409 | /// expression, the type of the base object whose member is being accessed. | |||
2410 | /// | |||
2411 | /// \param ObjectHadErrors this unqualified-id occurs within a member access | |||
2412 | /// expression, indicates whether the original subexpressions had any errors. | |||
2413 | /// | |||
2414 | /// \param Name for constructor and destructor names, this is the actual | |||
2415 | /// identifier that may be a template-name. | |||
2416 | /// | |||
2417 | /// \param NameLoc the location of the class-name in a constructor or | |||
2418 | /// destructor. | |||
2419 | /// | |||
2420 | /// \param EnteringContext whether we're entering the scope of the | |||
2421 | /// nested-name-specifier. | |||
2422 | /// | |||
2423 | /// \param Id as input, describes the template-name or operator-function-id | |||
2424 | /// that precedes the '<'. If template arguments were parsed successfully, | |||
2425 | /// will be updated with the template-id. | |||
2426 | /// | |||
2427 | /// \param AssumeTemplateId When true, this routine will assume that the name | |||
2428 | /// refers to a template without performing name lookup to verify. | |||
2429 | /// | |||
2430 | /// \returns true if a parse error occurred, false otherwise. | |||
2431 | bool Parser::ParseUnqualifiedIdTemplateId( | |||
2432 | CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, | |||
2433 | SourceLocation TemplateKWLoc, IdentifierInfo *Name, SourceLocation NameLoc, | |||
2434 | bool EnteringContext, UnqualifiedId &Id, bool AssumeTemplateId) { | |||
2435 | assert(Tok.is(tok::less) && "Expected '<' to finish parsing a template-id")(static_cast <bool> (Tok.is(tok::less) && "Expected '<' to finish parsing a template-id" ) ? void (0) : __assert_fail ("Tok.is(tok::less) && \"Expected '<' to finish parsing a template-id\"" , "clang/lib/Parse/ParseExprCXX.cpp", 2435, __extension__ __PRETTY_FUNCTION__ )); | |||
2436 | ||||
2437 | TemplateTy Template; | |||
2438 | TemplateNameKind TNK = TNK_Non_template; | |||
2439 | switch (Id.getKind()) { | |||
2440 | case UnqualifiedIdKind::IK_Identifier: | |||
2441 | case UnqualifiedIdKind::IK_OperatorFunctionId: | |||
2442 | case UnqualifiedIdKind::IK_LiteralOperatorId: | |||
2443 | if (AssumeTemplateId) { | |||
2444 | // We defer the injected-class-name checks until we've found whether | |||
2445 | // this template-id is used to form a nested-name-specifier or not. | |||
2446 | TNK = Actions.ActOnTemplateName(getCurScope(), SS, TemplateKWLoc, Id, | |||
2447 | ObjectType, EnteringContext, Template, | |||
2448 | /*AllowInjectedClassName*/ true); | |||
2449 | } else { | |||
2450 | bool MemberOfUnknownSpecialization; | |||
2451 | TNK = Actions.isTemplateName(getCurScope(), SS, | |||
2452 | TemplateKWLoc.isValid(), Id, | |||
2453 | ObjectType, EnteringContext, Template, | |||
2454 | MemberOfUnknownSpecialization); | |||
2455 | // If lookup found nothing but we're assuming that this is a template | |||
2456 | // name, double-check that makes sense syntactically before committing | |||
2457 | // to it. | |||
2458 | if (TNK == TNK_Undeclared_template && | |||
2459 | isTemplateArgumentList(0) == TPResult::False) | |||
2460 | return false; | |||
2461 | ||||
2462 | if (TNK == TNK_Non_template && MemberOfUnknownSpecialization && | |||
2463 | ObjectType && isTemplateArgumentList(0) == TPResult::True) { | |||
2464 | // If we had errors before, ObjectType can be dependent even without any | |||
2465 | // templates, do not report missing template keyword in that case. | |||
2466 | if (!ObjectHadErrors) { | |||
2467 | // We have something like t->getAs<T>(), where getAs is a | |||
2468 | // member of an unknown specialization. However, this will only | |||
2469 | // parse correctly as a template, so suggest the keyword 'template' | |||
2470 | // before 'getAs' and treat this as a dependent template name. | |||
2471 | std::string Name; | |||
2472 | if (Id.getKind() == UnqualifiedIdKind::IK_Identifier) | |||
2473 | Name = std::string(Id.Identifier->getName()); | |||
2474 | else { | |||
2475 | Name = "operator "; | |||
2476 | if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId) | |||
2477 | Name += getOperatorSpelling(Id.OperatorFunctionId.Operator); | |||
2478 | else | |||
2479 | Name += Id.Identifier->getName(); | |||
2480 | } | |||
2481 | Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword) | |||
2482 | << Name | |||
2483 | << FixItHint::CreateInsertion(Id.StartLocation, "template "); | |||
2484 | } | |||
2485 | TNK = Actions.ActOnTemplateName( | |||
2486 | getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext, | |||
2487 | Template, /*AllowInjectedClassName*/ true); | |||
2488 | } else if (TNK == TNK_Non_template) { | |||
2489 | return false; | |||
2490 | } | |||
2491 | } | |||
2492 | break; | |||
2493 | ||||
2494 | case UnqualifiedIdKind::IK_ConstructorName: { | |||
2495 | UnqualifiedId TemplateName; | |||
2496 | bool MemberOfUnknownSpecialization; | |||
2497 | TemplateName.setIdentifier(Name, NameLoc); | |||
2498 | TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(), | |||
2499 | TemplateName, ObjectType, | |||
2500 | EnteringContext, Template, | |||
2501 | MemberOfUnknownSpecialization); | |||
2502 | if (TNK == TNK_Non_template) | |||
2503 | return false; | |||
2504 | break; | |||
2505 | } | |||
2506 | ||||
2507 | case UnqualifiedIdKind::IK_DestructorName: { | |||
2508 | UnqualifiedId TemplateName; | |||
2509 | bool MemberOfUnknownSpecialization; | |||
2510 | TemplateName.setIdentifier(Name, NameLoc); | |||
2511 | if (ObjectType) { | |||
2512 | TNK = Actions.ActOnTemplateName( | |||
2513 | getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType, | |||
2514 | EnteringContext, Template, /*AllowInjectedClassName*/ true); | |||
2515 | } else { | |||
2516 | TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(), | |||
2517 | TemplateName, ObjectType, | |||
2518 | EnteringContext, Template, | |||
2519 | MemberOfUnknownSpecialization); | |||
2520 | ||||
2521 | if (TNK == TNK_Non_template && !Id.DestructorName.get()) { | |||
2522 | Diag(NameLoc, diag::err_destructor_template_id) | |||
2523 | << Name << SS.getRange(); | |||
2524 | // Carry on to parse the template arguments before bailing out. | |||
2525 | } | |||
2526 | } | |||
2527 | break; | |||
2528 | } | |||
2529 | ||||
2530 | default: | |||
2531 | return false; | |||
2532 | } | |||
2533 | ||||
2534 | // Parse the enclosed template argument list. | |||
2535 | SourceLocation LAngleLoc, RAngleLoc; | |||
2536 | TemplateArgList TemplateArgs; | |||
2537 | if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs, RAngleLoc, | |||
2538 | Template)) | |||
2539 | return true; | |||
2540 | ||||
2541 | // If this is a non-template, we already issued a diagnostic. | |||
2542 | if (TNK == TNK_Non_template) | |||
2543 | return true; | |||
2544 | ||||
2545 | if (Id.getKind() == UnqualifiedIdKind::IK_Identifier || | |||
2546 | Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId || | |||
2547 | Id.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) { | |||
2548 | // Form a parsed representation of the template-id to be stored in the | |||
2549 | // UnqualifiedId. | |||
2550 | ||||
2551 | // FIXME: Store name for literal operator too. | |||
2552 | IdentifierInfo *TemplateII = | |||
2553 | Id.getKind() == UnqualifiedIdKind::IK_Identifier ? Id.Identifier | |||
2554 | : nullptr; | |||
2555 | OverloadedOperatorKind OpKind = | |||
2556 | Id.getKind() == UnqualifiedIdKind::IK_Identifier | |||
2557 | ? OO_None | |||
2558 | : Id.OperatorFunctionId.Operator; | |||
2559 | ||||
2560 | TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create( | |||
2561 | TemplateKWLoc, Id.StartLocation, TemplateII, OpKind, Template, TNK, | |||
2562 | LAngleLoc, RAngleLoc, TemplateArgs, /*ArgsInvalid*/false, TemplateIds); | |||
2563 | ||||
2564 | Id.setTemplateId(TemplateId); | |||
2565 | return false; | |||
2566 | } | |||
2567 | ||||
2568 | // Bundle the template arguments together. | |||
2569 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs); | |||
2570 | ||||
2571 | // Constructor and destructor names. | |||
2572 | TypeResult Type = Actions.ActOnTemplateIdType( | |||
2573 | getCurScope(), SS, TemplateKWLoc, Template, Name, NameLoc, LAngleLoc, | |||
2574 | TemplateArgsPtr, RAngleLoc, /*IsCtorOrDtorName=*/true); | |||
2575 | if (Type.isInvalid()) | |||
2576 | return true; | |||
2577 | ||||
2578 | if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName) | |||
2579 | Id.setConstructorName(Type.get(), NameLoc, RAngleLoc); | |||
2580 | else | |||
2581 | Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc); | |||
2582 | ||||
2583 | return false; | |||
2584 | } | |||
2585 | ||||
2586 | /// Parse an operator-function-id or conversion-function-id as part | |||
2587 | /// of a C++ unqualified-id. | |||
2588 | /// | |||
2589 | /// This routine is responsible only for parsing the operator-function-id or | |||
2590 | /// conversion-function-id; it does not handle template arguments in any way. | |||
2591 | /// | |||
2592 | /// \code | |||
2593 | /// operator-function-id: [C++ 13.5] | |||
2594 | /// 'operator' operator | |||
2595 | /// | |||
2596 | /// operator: one of | |||
2597 | /// new delete new[] delete[] | |||
2598 | /// + - * / % ^ & | ~ | |||
2599 | /// ! = < > += -= *= /= %= | |||
2600 | /// ^= &= |= << >> >>= <<= == != | |||
2601 | /// <= >= && || ++ -- , ->* -> | |||
2602 | /// () [] <=> | |||
2603 | /// | |||
2604 | /// conversion-function-id: [C++ 12.3.2] | |||
2605 | /// operator conversion-type-id | |||
2606 | /// | |||
2607 | /// conversion-type-id: | |||
2608 | /// type-specifier-seq conversion-declarator[opt] | |||
2609 | /// | |||
2610 | /// conversion-declarator: | |||
2611 | /// ptr-operator conversion-declarator[opt] | |||
2612 | /// \endcode | |||
2613 | /// | |||
2614 | /// \param SS The nested-name-specifier that preceded this unqualified-id. If | |||
2615 | /// non-empty, then we are parsing the unqualified-id of a qualified-id. | |||
2616 | /// | |||
2617 | /// \param EnteringContext whether we are entering the scope of the | |||
2618 | /// nested-name-specifier. | |||
2619 | /// | |||
2620 | /// \param ObjectType if this unqualified-id occurs within a member access | |||
2621 | /// expression, the type of the base object whose member is being accessed. | |||
2622 | /// | |||
2623 | /// \param Result on a successful parse, contains the parsed unqualified-id. | |||
2624 | /// | |||
2625 | /// \returns true if parsing fails, false otherwise. | |||
2626 | bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, | |||
2627 | ParsedType ObjectType, | |||
2628 | UnqualifiedId &Result) { | |||
2629 | assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword")(static_cast <bool> (Tok.is(tok::kw_operator) && "Expected 'operator' keyword") ? void (0) : __assert_fail ("Tok.is(tok::kw_operator) && \"Expected 'operator' keyword\"" , "clang/lib/Parse/ParseExprCXX.cpp", 2629, __extension__ __PRETTY_FUNCTION__ )); | |||
2630 | ||||
2631 | // Consume the 'operator' keyword. | |||
2632 | SourceLocation KeywordLoc = ConsumeToken(); | |||
2633 | ||||
2634 | // Determine what kind of operator name we have. | |||
2635 | unsigned SymbolIdx = 0; | |||
2636 | SourceLocation SymbolLocations[3]; | |||
2637 | OverloadedOperatorKind Op = OO_None; | |||
2638 | switch (Tok.getKind()) { | |||
2639 | case tok::kw_new: | |||
2640 | case tok::kw_delete: { | |||
2641 | bool isNew = Tok.getKind() == tok::kw_new; | |||
2642 | // Consume the 'new' or 'delete'. | |||
2643 | SymbolLocations[SymbolIdx++] = ConsumeToken(); | |||
2644 | // Check for array new/delete. | |||
2645 | if (Tok.is(tok::l_square) && | |||
2646 | (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) { | |||
2647 | // Consume the '[' and ']'. | |||
2648 | BalancedDelimiterTracker T(*this, tok::l_square); | |||
2649 | T.consumeOpen(); | |||
2650 | T.consumeClose(); | |||
2651 | if (T.getCloseLocation().isInvalid()) | |||
2652 | return true; | |||
2653 | ||||
2654 | SymbolLocations[SymbolIdx++] = T.getOpenLocation(); | |||
2655 | SymbolLocations[SymbolIdx++] = T.getCloseLocation(); | |||
2656 | Op = isNew? OO_Array_New : OO_Array_Delete; | |||
2657 | } else { | |||
2658 | Op = isNew? OO_New : OO_Delete; | |||
2659 | } | |||
2660 | break; | |||
2661 | } | |||
2662 | ||||
2663 | #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ | |||
2664 | case tok::Token: \ | |||
2665 | SymbolLocations[SymbolIdx++] = ConsumeToken(); \ | |||
2666 | Op = OO_##Name; \ | |||
2667 | break; | |||
2668 | #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly) | |||
2669 | #include "clang/Basic/OperatorKinds.def" | |||
2670 | ||||
2671 | case tok::l_paren: { | |||
2672 | // Consume the '(' and ')'. | |||
2673 | BalancedDelimiterTracker T(*this, tok::l_paren); | |||
2674 | T.consumeOpen(); | |||
2675 | T.consumeClose(); | |||
2676 | if (T.getCloseLocation().isInvalid()) | |||
2677 | return true; | |||
2678 | ||||
2679 | SymbolLocations[SymbolIdx++] = T.getOpenLocation(); | |||
2680 | SymbolLocations[SymbolIdx++] = T.getCloseLocation(); | |||
2681 | Op = OO_Call; | |||
2682 | break; | |||
2683 | } | |||
2684 | ||||
2685 | case tok::l_square: { | |||
2686 | // Consume the '[' and ']'. | |||
2687 | BalancedDelimiterTracker T(*this, tok::l_square); | |||
2688 | T.consumeOpen(); | |||
2689 | T.consumeClose(); | |||
2690 | if (T.getCloseLocation().isInvalid()) | |||
2691 | return true; | |||
2692 | ||||
2693 | SymbolLocations[SymbolIdx++] = T.getOpenLocation(); | |||
2694 | SymbolLocations[SymbolIdx++] = T.getCloseLocation(); | |||
2695 | Op = OO_Subscript; | |||
2696 | break; | |||
2697 | } | |||
2698 | ||||
2699 | case tok::code_completion: { | |||
2700 | // Don't try to parse any further. | |||
2701 | cutOffParsing(); | |||
2702 | // Code completion for the operator name. | |||
2703 | Actions.CodeCompleteOperatorName(getCurScope()); | |||
2704 | return true; | |||
2705 | } | |||
2706 | ||||
2707 | default: | |||
2708 | break; | |||
2709 | } | |||
2710 | ||||
2711 | if (Op != OO_None) { | |||
2712 | // We have parsed an operator-function-id. | |||
2713 | Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations); | |||
2714 | return false; | |||
2715 | } | |||
2716 | ||||
2717 | // Parse a literal-operator-id. | |||
2718 | // | |||
2719 | // literal-operator-id: C++11 [over.literal] | |||
2720 | // operator string-literal identifier | |||
2721 | // operator user-defined-string-literal | |||
2722 | ||||
2723 | if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) { | |||
2724 | Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator); | |||
2725 | ||||
2726 | SourceLocation DiagLoc; | |||
2727 | unsigned DiagId = 0; | |||
2728 | ||||
2729 | // We're past translation phase 6, so perform string literal concatenation | |||
2730 | // before checking for "". | |||
2731 | SmallVector<Token, 4> Toks; | |||
2732 | SmallVector<SourceLocation, 4> TokLocs; | |||
2733 | while (isTokenStringLiteral()) { | |||
2734 | if (!Tok.is(tok::string_literal) && !DiagId) { | |||
2735 | // C++11 [over.literal]p1: | |||
2736 | // The string-literal or user-defined-string-literal in a | |||
2737 | // literal-operator-id shall have no encoding-prefix [...]. | |||
2738 | DiagLoc = Tok.getLocation(); | |||
2739 | DiagId = diag::err_literal_operator_string_prefix; | |||
2740 | } | |||
2741 | Toks.push_back(Tok); | |||
2742 | TokLocs.push_back(ConsumeStringToken()); | |||
2743 | } | |||
2744 | ||||
2745 | StringLiteralParser Literal(Toks, PP); | |||
2746 | if (Literal.hadError) | |||
2747 | return true; | |||
2748 | ||||
2749 | // Grab the literal operator's suffix, which will be either the next token | |||
2750 | // or a ud-suffix from the string literal. | |||
2751 | bool IsUDSuffix = !Literal.getUDSuffix().empty(); | |||
2752 | IdentifierInfo *II = nullptr; | |||
2753 | SourceLocation SuffixLoc; | |||
2754 | if (IsUDSuffix) { | |||
2755 | II = &PP.getIdentifierTable().get(Literal.getUDSuffix()); | |||
2756 | SuffixLoc = | |||
2757 | Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()], | |||
2758 | Literal.getUDSuffixOffset(), | |||
2759 | PP.getSourceManager(), getLangOpts()); | |||
2760 | } else if (Tok.is(tok::identifier)) { | |||
2761 | II = Tok.getIdentifierInfo(); | |||
2762 | SuffixLoc = ConsumeToken(); | |||
2763 | TokLocs.push_back(SuffixLoc); | |||
2764 | } else { | |||
2765 | Diag(Tok.getLocation(), diag::err_expected) << tok::identifier; | |||
2766 | return true; | |||
2767 | } | |||
2768 | ||||
2769 | // The string literal must be empty. | |||
2770 | if (!Literal.GetString().empty() || Literal.Pascal) { | |||
2771 | // C++11 [over.literal]p1: | |||
2772 | // The string-literal or user-defined-string-literal in a | |||
2773 | // literal-operator-id shall [...] contain no characters | |||
2774 | // other than the implicit terminating '\0'. | |||
2775 | DiagLoc = TokLocs.front(); | |||
2776 | DiagId = diag::err_literal_operator_string_not_empty; | |||
2777 | } | |||
2778 | ||||
2779 | if (DiagId) { | |||
2780 | // This isn't a valid literal-operator-id, but we think we know | |||
2781 | // what the user meant. Tell them what they should have written. | |||
2782 | SmallString<32> Str; | |||
2783 | Str += "\"\""; | |||
2784 | Str += II->getName(); | |||
2785 | Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement( | |||
2786 | SourceRange(TokLocs.front(), TokLocs.back()), Str); | |||
2787 | } | |||
2788 | ||||
2789 | Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc); | |||
2790 | ||||
2791 | return Actions.checkLiteralOperatorId(SS, Result, IsUDSuffix); | |||
2792 | } | |||
2793 | ||||
2794 | // Parse a conversion-function-id. | |||
2795 | // | |||
2796 | // conversion-function-id: [C++ 12.3.2] | |||
2797 | // operator conversion-type-id | |||
2798 | // | |||
2799 | // conversion-type-id: | |||
2800 | // type-specifier-seq conversion-declarator[opt] | |||
2801 | // | |||
2802 | // conversion-declarator: | |||
2803 | // ptr-operator conversion-declarator[opt] | |||
2804 | ||||
2805 | // Parse the type-specifier-seq. | |||
2806 | DeclSpec DS(AttrFactory); | |||
2807 | if (ParseCXXTypeSpecifierSeq( | |||
2808 | DS, DeclaratorContext::ConversionId)) // FIXME: ObjectType? | |||
2809 | return true; | |||
2810 | ||||
2811 | // Parse the conversion-declarator, which is merely a sequence of | |||
2812 | // ptr-operators. | |||
2813 | Declarator D(DS, ParsedAttributesView::none(), | |||
2814 | DeclaratorContext::ConversionId); | |||
2815 | ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr); | |||
2816 | ||||
2817 | // Finish up the type. | |||
2818 | TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D); | |||
2819 | if (Ty.isInvalid()) | |||
2820 | return true; | |||
2821 | ||||
2822 | // Note that this is a conversion-function-id. | |||
2823 | Result.setConversionFunctionId(KeywordLoc, Ty.get(), | |||
2824 | D.getSourceRange().getEnd()); | |||
2825 | return false; | |||
2826 | } | |||
2827 | ||||
2828 | /// Parse a C++ unqualified-id (or a C identifier), which describes the | |||
2829 | /// name of an entity. | |||
2830 | /// | |||
2831 | /// \code | |||
2832 | /// unqualified-id: [C++ expr.prim.general] | |||
2833 | /// identifier | |||
2834 | /// operator-function-id | |||
2835 | /// conversion-function-id | |||
2836 | /// [C++0x] literal-operator-id [TODO] | |||
2837 | /// ~ class-name | |||
2838 | /// template-id | |||
2839 | /// | |||
2840 | /// \endcode | |||
2841 | /// | |||
2842 | /// \param SS The nested-name-specifier that preceded this unqualified-id. If | |||
2843 | /// non-empty, then we are parsing the unqualified-id of a qualified-id. | |||
2844 | /// | |||
2845 | /// \param ObjectType if this unqualified-id occurs within a member access | |||
2846 | /// expression, the type of the base object whose member is being accessed. | |||
2847 | /// | |||
2848 | /// \param ObjectHadErrors if this unqualified-id occurs within a member access | |||
2849 | /// expression, indicates whether the original subexpressions had any errors. | |||
2850 | /// When true, diagnostics for missing 'template' keyword will be supressed. | |||
2851 | /// | |||
2852 | /// \param EnteringContext whether we are entering the scope of the | |||
2853 | /// nested-name-specifier. | |||
2854 | /// | |||
2855 | /// \param AllowDestructorName whether we allow parsing of a destructor name. | |||
2856 | /// | |||
2857 | /// \param AllowConstructorName whether we allow parsing a constructor name. | |||
2858 | /// | |||
2859 | /// \param AllowDeductionGuide whether we allow parsing a deduction guide name. | |||
2860 | /// | |||
2861 | /// \param Result on a successful parse, contains the parsed unqualified-id. | |||
2862 | /// | |||
2863 | /// \returns true if parsing fails, false otherwise. | |||
2864 | bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType, | |||
2865 | bool ObjectHadErrors, bool EnteringContext, | |||
2866 | bool AllowDestructorName, | |||
2867 | bool AllowConstructorName, | |||
2868 | bool AllowDeductionGuide, | |||
2869 | SourceLocation *TemplateKWLoc, | |||
2870 | UnqualifiedId &Result) { | |||
2871 | if (TemplateKWLoc) | |||
2872 | *TemplateKWLoc = SourceLocation(); | |||
2873 | ||||
2874 | // Handle 'A::template B'. This is for template-ids which have not | |||
2875 | // already been annotated by ParseOptionalCXXScopeSpecifier(). | |||
2876 | bool TemplateSpecified = false; | |||
2877 | if (Tok.is(tok::kw_template)) { | |||
2878 | if (TemplateKWLoc && (ObjectType || SS.isSet())) { | |||
2879 | TemplateSpecified = true; | |||
2880 | *TemplateKWLoc = ConsumeToken(); | |||
2881 | } else { | |||
2882 | SourceLocation TemplateLoc = ConsumeToken(); | |||
2883 | Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id) | |||
2884 | << FixItHint::CreateRemoval(TemplateLoc); | |||
2885 | } | |||
2886 | } | |||
2887 | ||||
2888 | // unqualified-id: | |||
2889 | // identifier | |||
2890 | // template-id (when it hasn't already been annotated) | |||
2891 | if (Tok.is(tok::identifier)) { | |||
2892 | ParseIdentifier: | |||
2893 | // Consume the identifier. | |||
2894 | IdentifierInfo *Id = Tok.getIdentifierInfo(); | |||
2895 | SourceLocation IdLoc = ConsumeToken(); | |||
2896 | ||||
2897 | if (!getLangOpts().CPlusPlus) { | |||
2898 | // If we're not in C++, only identifiers matter. Record the | |||
2899 | // identifier and return. | |||
2900 | Result.setIdentifier(Id, IdLoc); | |||
2901 | return false; | |||
2902 | } | |||
2903 | ||||
2904 | ParsedTemplateTy TemplateName; | |||
2905 | if (AllowConstructorName && | |||
2906 | Actions.isCurrentClassName(*Id, getCurScope(), &SS)) { | |||
2907 | // We have parsed a constructor name. | |||
2908 | ParsedType Ty = Actions.getConstructorName(*Id, IdLoc, getCurScope(), SS, | |||
2909 | EnteringContext); | |||
2910 | if (!Ty) | |||
2911 | return true; | |||
2912 | Result.setConstructorName(Ty, IdLoc, IdLoc); | |||
2913 | } else if (getLangOpts().CPlusPlus17 && | |||
2914 | AllowDeductionGuide && SS.isEmpty() && | |||
2915 | Actions.isDeductionGuideName(getCurScope(), *Id, IdLoc, | |||
2916 | &TemplateName)) { | |||
2917 | // We have parsed a template-name naming a deduction guide. | |||
2918 | Result.setDeductionGuideName(TemplateName, IdLoc); | |||
2919 | } else { | |||
2920 | // We have parsed an identifier. | |||
2921 | Result.setIdentifier(Id, IdLoc); | |||
2922 | } | |||
2923 | ||||
2924 | // If the next token is a '<', we may have a template. | |||
2925 | TemplateTy Template; | |||
2926 | if (Tok.is(tok::less)) | |||
2927 | return ParseUnqualifiedIdTemplateId( | |||
2928 | SS, ObjectType, ObjectHadErrors, | |||
2929 | TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), Id, IdLoc, | |||
2930 | EnteringContext, Result, TemplateSpecified); | |||
2931 | else if (TemplateSpecified && | |||
2932 | Actions.ActOnTemplateName( | |||
2933 | getCurScope(), SS, *TemplateKWLoc, Result, ObjectType, | |||
2934 | EnteringContext, Template, | |||
2935 | /*AllowInjectedClassName*/ true) == TNK_Non_template) | |||
2936 | return true; | |||
2937 | ||||
2938 | return false; | |||
2939 | } | |||
2940 | ||||
2941 | // unqualified-id: | |||
2942 | // template-id (already parsed and annotated) | |||
2943 | if (Tok.is(tok::annot_template_id)) { | |||
2944 | TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); | |||
2945 | ||||
2946 | // FIXME: Consider passing invalid template-ids on to callers; they may | |||
2947 | // be able to recover better than we can. | |||
2948 | if (TemplateId->isInvalid()) { | |||
2949 | ConsumeAnnotationToken(); | |||
2950 | return true; | |||
2951 | } | |||
2952 | ||||
2953 | // If the template-name names the current class, then this is a constructor | |||
2954 | if (AllowConstructorName && TemplateId->Name && | |||
2955 | Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) { | |||
2956 | if (SS.isSet()) { | |||
2957 | // C++ [class.qual]p2 specifies that a qualified template-name | |||
2958 | // is taken as the constructor name where a constructor can be | |||
2959 | // declared. Thus, the template arguments are extraneous, so | |||
2960 | // complain about them and remove them entirely. | |||
2961 | Diag(TemplateId->TemplateNameLoc, | |||
2962 | diag::err_out_of_line_constructor_template_id) | |||
2963 | << TemplateId->Name | |||
2964 | << FixItHint::CreateRemoval( | |||
2965 | SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)); | |||
2966 | ParsedType Ty = Actions.getConstructorName( | |||
2967 | *TemplateId->Name, TemplateId->TemplateNameLoc, getCurScope(), SS, | |||
2968 | EnteringContext); | |||
2969 | if (!Ty) | |||
2970 | return true; | |||
2971 | Result.setConstructorName(Ty, TemplateId->TemplateNameLoc, | |||
2972 | TemplateId->RAngleLoc); | |||
2973 | ConsumeAnnotationToken(); | |||
2974 | return false; | |||
2975 | } | |||
2976 | ||||
2977 | Result.setConstructorTemplateId(TemplateId); | |||
2978 | ConsumeAnnotationToken(); | |||
2979 | return false; | |||
2980 | } | |||
2981 | ||||
2982 | // We have already parsed a template-id; consume the annotation token as | |||
2983 | // our unqualified-id. | |||
2984 | Result.setTemplateId(TemplateId); | |||
2985 | SourceLocation TemplateLoc = TemplateId->TemplateKWLoc; | |||
2986 | if (TemplateLoc.isValid()) { | |||
2987 | if (TemplateKWLoc && (ObjectType || SS.isSet())) | |||
2988 | *TemplateKWLoc = TemplateLoc; | |||
2989 | else | |||
2990 | Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id) | |||
2991 | << FixItHint::CreateRemoval(TemplateLoc); | |||
2992 | } | |||
2993 | ConsumeAnnotationToken(); | |||
2994 | return false; | |||
2995 | } | |||
2996 | ||||
2997 | // unqualified-id: | |||
2998 | // operator-function-id | |||
2999 | // conversion-function-id | |||
3000 | if (Tok.is(tok::kw_operator)) { | |||
3001 | if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result)) | |||
3002 | return true; | |||
3003 | ||||
3004 | // If we have an operator-function-id or a literal-operator-id and the next | |||
3005 | // token is a '<', we may have a | |||
3006 | // | |||
3007 | // template-id: | |||
3008 | // operator-function-id < template-argument-list[opt] > | |||
3009 | TemplateTy Template; | |||
3010 | if ((Result.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId || | |||
3011 | Result.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) && | |||
3012 | Tok.is(tok::less)) | |||
3013 | return ParseUnqualifiedIdTemplateId( | |||
3014 | SS, ObjectType, ObjectHadErrors, | |||
3015 | TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), nullptr, | |||
3016 | SourceLocation(), EnteringContext, Result, TemplateSpecified); | |||
3017 | else if (TemplateSpecified && | |||
3018 | Actions.ActOnTemplateName( | |||
3019 | getCurScope(), SS, *TemplateKWLoc, Result, ObjectType, | |||
3020 | EnteringContext, Template, | |||
3021 | /*AllowInjectedClassName*/ true) == TNK_Non_template) | |||
3022 | return true; | |||
3023 | ||||
3024 | return false; | |||
3025 | } | |||
3026 | ||||
3027 | if (getLangOpts().CPlusPlus && | |||
3028 | (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) { | |||
3029 | // C++ [expr.unary.op]p10: | |||
3030 | // There is an ambiguity in the unary-expression ~X(), where X is a | |||
3031 | // class-name. The ambiguity is resolved in favor of treating ~ as a | |||
3032 | // unary complement rather than treating ~X as referring to a destructor. | |||
3033 | ||||
3034 | // Parse the '~'. | |||
3035 | SourceLocation TildeLoc = ConsumeToken(); | |||
3036 | ||||
3037 | if (TemplateSpecified) { | |||
3038 | // C++ [temp.names]p3: | |||
3039 | // A name prefixed by the keyword template shall be a template-id [...] | |||
3040 | // | |||
3041 | // A template-id cannot begin with a '~' token. This would never work | |||
3042 | // anyway: x.~A<int>() would specify that the destructor is a template, | |||
3043 | // not that 'A' is a template. | |||
3044 | // | |||
3045 | // FIXME: Suggest replacing the attempted destructor name with a correct | |||
3046 | // destructor name and recover. (This is not trivial if this would become | |||
3047 | // a pseudo-destructor name). | |||
3048 | Diag(*TemplateKWLoc, diag::err_unexpected_template_in_destructor_name) | |||
3049 | << Tok.getLocation(); | |||
3050 | return true; | |||
3051 | } | |||
3052 | ||||
3053 | if (SS.isEmpty() && Tok.is(tok::kw_decltype)) { | |||
3054 | DeclSpec DS(AttrFactory); | |||
3055 | SourceLocation EndLoc = ParseDecltypeSpecifier(DS); | |||
3056 | if (ParsedType Type = | |||
3057 | Actions.getDestructorTypeForDecltype(DS, ObjectType)) { | |||
3058 | Result.setDestructorName(TildeLoc, Type, EndLoc); | |||
3059 | return false; | |||
3060 | } | |||
3061 | return true; | |||
3062 | } | |||
3063 | ||||
3064 | // Parse the class-name. | |||
3065 | if (Tok.isNot(tok::identifier)) { | |||
3066 | Diag(Tok, diag::err_destructor_tilde_identifier); | |||
3067 | return true; | |||
3068 | } | |||
3069 | ||||
3070 | // If the user wrote ~T::T, correct it to T::~T. | |||
3071 | DeclaratorScopeObj DeclScopeObj(*this, SS); | |||
3072 | if (NextToken().is(tok::coloncolon)) { | |||
3073 | // Don't let ParseOptionalCXXScopeSpecifier() "correct" | |||
3074 | // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`, | |||
3075 | // it will confuse this recovery logic. | |||
3076 | ColonProtectionRAIIObject ColonRAII(*this, false); | |||
3077 | ||||
3078 | if (SS.isSet()) { | |||
3079 | AnnotateScopeToken(SS, /*NewAnnotation*/true); | |||
3080 | SS.clear(); | |||
3081 | } | |||
3082 | if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, ObjectHadErrors, | |||
3083 | EnteringContext)) | |||
3084 | return true; | |||
3085 | if (SS.isNotEmpty()) | |||
3086 | ObjectType = nullptr; | |||
3087 | if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) || | |||
3088 | !SS.isSet()) { | |||
3089 | Diag(TildeLoc, diag::err_destructor_tilde_scope); | |||
3090 | return true; | |||
3091 | } | |||
3092 | ||||
3093 | // Recover as if the tilde had been written before the identifier. | |||
3094 | Diag(TildeLoc, diag::err_destructor_tilde_scope) | |||
3095 | << FixItHint::CreateRemoval(TildeLoc) | |||
3096 | << FixItHint::CreateInsertion(Tok.getLocation(), "~"); | |||
3097 | ||||
3098 | // Temporarily enter the scope for the rest of this function. | |||
3099 | if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS)) | |||
3100 | DeclScopeObj.EnterDeclaratorScope(); | |||
3101 | } | |||
3102 | ||||
3103 | // Parse the class-name (or template-name in a simple-template-id). | |||
3104 | IdentifierInfo *ClassName = Tok.getIdentifierInfo(); | |||
3105 | SourceLocation ClassNameLoc = ConsumeToken(); | |||
3106 | ||||
3107 | if (Tok.is(tok::less)) { | |||
3108 | Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc); | |||
3109 | return ParseUnqualifiedIdTemplateId( | |||
3110 | SS, ObjectType, ObjectHadErrors, | |||
3111 | TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), ClassName, | |||
3112 | ClassNameLoc, EnteringContext, Result, TemplateSpecified); | |||
3113 | } | |||
3114 | ||||
3115 | // Note that this is a destructor name. | |||
3116 | ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName, | |||
3117 | ClassNameLoc, getCurScope(), | |||
3118 | SS, ObjectType, | |||
3119 | EnteringContext); | |||
3120 | if (!Ty) | |||
3121 | return true; | |||
3122 | ||||
3123 | Result.setDestructorName(TildeLoc, Ty, ClassNameLoc); | |||
3124 | return false; | |||
3125 | } | |||
3126 | ||||
3127 | switch (Tok.getKind()) { | |||
3128 | #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait: | |||
3129 | #include "clang/Basic/TransformTypeTraits.def" | |||
3130 | if (!NextToken().is(tok::l_paren)) { | |||
3131 | Tok.setKind(tok::identifier); | |||
3132 | Diag(Tok, diag::ext_keyword_as_ident) | |||
3133 | << Tok.getIdentifierInfo()->getName() << 0; | |||
3134 | goto ParseIdentifier; | |||
3135 | } | |||
3136 | [[fallthrough]]; | |||
3137 | default: | |||
3138 | Diag(Tok, diag::err_expected_unqualified_id) << getLangOpts().CPlusPlus; | |||
3139 | return true; | |||
3140 | } | |||
3141 | } | |||
3142 | ||||
3143 | /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate | |||
3144 | /// memory in a typesafe manner and call constructors. | |||
3145 | /// | |||
3146 | /// This method is called to parse the new expression after the optional :: has | |||
3147 | /// been already parsed. If the :: was present, "UseGlobal" is true and "Start" | |||
3148 | /// is its location. Otherwise, "Start" is the location of the 'new' token. | |||
3149 | /// | |||
3150 | /// new-expression: | |||
3151 | /// '::'[opt] 'new' new-placement[opt] new-type-id | |||
3152 | /// new-initializer[opt] | |||
3153 | /// '::'[opt] 'new' new-placement[opt] '(' type-id ')' | |||
3154 | /// new-initializer[opt] | |||
3155 | /// | |||
3156 | /// new-placement: | |||
3157 | /// '(' expression-list ')' | |||
3158 | /// | |||
3159 | /// new-type-id: | |||
3160 | /// type-specifier-seq new-declarator[opt] | |||
3161 | /// [GNU] attributes type-specifier-seq new-declarator[opt] | |||
3162 | /// | |||
3163 | /// new-declarator: | |||
3164 | /// ptr-operator new-declarator[opt] | |||
3165 | /// direct-new-declarator | |||
3166 | /// | |||
3167 | /// new-initializer: | |||
3168 | /// '(' expression-list[opt] ')' | |||
3169 | /// [C++0x] braced-init-list | |||
3170 | /// | |||
3171 | ExprResult | |||
3172 | Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) { | |||
3173 | assert(Tok.is(tok::kw_new) && "expected 'new' token")(static_cast <bool> (Tok.is(tok::kw_new) && "expected 'new' token" ) ? void (0) : __assert_fail ("Tok.is(tok::kw_new) && \"expected 'new' token\"" , "clang/lib/Parse/ParseExprCXX.cpp", 3173, __extension__ __PRETTY_FUNCTION__ )); | |||
3174 | ConsumeToken(); // Consume 'new' | |||
3175 | ||||
3176 | // A '(' now can be a new-placement or the '(' wrapping the type-id in the | |||
3177 | // second form of new-expression. It can't be a new-type-id. | |||
3178 | ||||
3179 | ExprVector PlacementArgs; | |||
3180 | SourceLocation PlacementLParen, PlacementRParen; | |||
3181 | ||||
3182 | SourceRange TypeIdParens; | |||
3183 | DeclSpec DS(AttrFactory); | |||
3184 | Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), | |||
3185 | DeclaratorContext::CXXNew); | |||
3186 | if (Tok.is(tok::l_paren)) { | |||
3187 | // If it turns out to be a placement, we change the type location. | |||
3188 | BalancedDelimiterTracker T(*this, tok::l_paren); | |||
3189 | T.consumeOpen(); | |||
3190 | PlacementLParen = T.getOpenLocation(); | |||
3191 | if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) { | |||
3192 | SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch); | |||
3193 | return ExprError(); | |||
3194 | } | |||
3195 | ||||
3196 | T.consumeClose(); | |||
3197 | PlacementRParen = T.getCloseLocation(); | |||
3198 | if (PlacementRParen.isInvalid()) { | |||
3199 | SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch); | |||
3200 | return ExprError(); | |||
3201 | } | |||
3202 | ||||
3203 | if (PlacementArgs.empty()) { | |||
3204 | // Reset the placement locations. There was no placement. | |||
3205 | TypeIdParens = T.getRange(); | |||
3206 | PlacementLParen = PlacementRParen = SourceLocation(); | |||
3207 | } else { | |||
3208 | // We still need the type. | |||
3209 | if (Tok.is(tok::l_paren)) { | |||
3210 | BalancedDelimiterTracker T(*this, tok::l_paren); | |||
3211 | T.consumeOpen(); | |||
3212 | MaybeParseGNUAttributes(DeclaratorInfo); | |||
3213 | ParseSpecifierQualifierList(DS); | |||
3214 | DeclaratorInfo.SetSourceRange(DS.getSourceRange()); | |||
3215 | ParseDeclarator(DeclaratorInfo); | |||
3216 | T.consumeClose(); | |||
3217 | TypeIdParens = T.getRange(); | |||
3218 | } else { | |||
3219 | MaybeParseGNUAttributes(DeclaratorInfo); | |||
3220 | if (ParseCXXTypeSpecifierSeq(DS)) | |||
3221 | DeclaratorInfo.setInvalidType(true); | |||
3222 | else { | |||
3223 | DeclaratorInfo.SetSourceRange(DS.getSourceRange()); | |||
3224 | ParseDeclaratorInternal(DeclaratorInfo, | |||
3225 | &Parser::ParseDirectNewDeclarator); | |||
3226 | } | |||
3227 | } | |||
3228 | } | |||
3229 | } else { | |||
3230 | // A new-type-id is a simplified type-id, where essentially the | |||
3231 | // direct-declarator is replaced by a direct-new-declarator. | |||
3232 | MaybeParseGNUAttributes(DeclaratorInfo); | |||
3233 | if (ParseCXXTypeSpecifierSeq(DS)) | |||
3234 | DeclaratorInfo.setInvalidType(true); | |||
3235 | else { | |||
3236 | DeclaratorInfo.SetSourceRange(DS.getSourceRange()); | |||
3237 | ParseDeclaratorInternal(DeclaratorInfo, | |||
3238 | &Parser::ParseDirectNewDeclarator); | |||
3239 | } | |||
3240 | } | |||
3241 | if (DeclaratorInfo.isInvalidType()) { | |||
3242 | SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch); | |||
3243 | return ExprError(); | |||
3244 | } | |||
3245 | ||||
3246 | ExprResult Initializer; | |||
3247 | ||||
3248 | if (Tok.is(tok::l_paren)) { | |||
3249 | SourceLocation ConstructorLParen, ConstructorRParen; | |||
3250 | ExprVector ConstructorArgs; | |||
3251 | BalancedDelimiterTracker T(*this, tok::l_paren); | |||
3252 | T.consumeOpen(); | |||
3253 | ConstructorLParen = T.getOpenLocation(); | |||
3254 | if (Tok.isNot(tok::r_paren)) { | |||
3255 | auto RunSignatureHelp = [&]() { | |||
3256 | ParsedType TypeRep = | |||
3257 | Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get(); | |||
3258 | QualType PreferredType; | |||
3259 | // ActOnTypeName might adjust DeclaratorInfo and return a null type even | |||
3260 | // the passing DeclaratorInfo is valid, e.g. running SignatureHelp on | |||
3261 | // `new decltype(invalid) (^)`. | |||
3262 | if (TypeRep) | |||
3263 | PreferredType = Actions.ProduceConstructorSignatureHelp( | |||
3264 | TypeRep.get()->getCanonicalTypeInternal(), | |||
3265 | DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen, | |||
3266 | /*Braced=*/false); | |||
3267 | CalledSignatureHelp = true; | |||
3268 | return PreferredType; | |||
3269 | }; | |||
3270 | if (ParseExpressionList(ConstructorArgs, [&] { | |||
3271 | PreferredType.enterFunctionArgument(Tok.getLocation(), | |||
3272 | RunSignatureHelp); | |||
3273 | })) { | |||
3274 | if (PP.isCodeCompletionReached() && !CalledSignatureHelp) | |||
3275 | RunSignatureHelp(); | |||
3276 | SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch); | |||
3277 | return ExprError(); | |||
3278 | } | |||
3279 | } | |||
3280 | T.consumeClose(); | |||
3281 | ConstructorRParen = T.getCloseLocation(); | |||
3282 | if (ConstructorRParen.isInvalid()) { | |||
3283 | SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch); | |||
3284 | return ExprError(); | |||
3285 | } | |||
3286 | Initializer = Actions.ActOnParenListExpr(ConstructorLParen, | |||
3287 | ConstructorRParen, | |||
3288 | ConstructorArgs); | |||
3289 | } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) { | |||
3290 | Diag(Tok.getLocation(), | |||
3291 | diag::warn_cxx98_compat_generalized_initializer_lists); | |||
3292 | Initializer = ParseBraceInitializer(); | |||
3293 | } | |||
3294 | if (Initializer.isInvalid()) | |||
3295 | return Initializer; | |||
3296 | ||||
3297 | return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen, | |||
3298 | PlacementArgs, PlacementRParen, | |||
3299 | TypeIdParens, DeclaratorInfo, Initializer.get()); | |||
3300 | } | |||
3301 | ||||
3302 | /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be | |||
3303 | /// passed to ParseDeclaratorInternal. | |||
3304 | /// | |||
3305 | /// direct-new-declarator: | |||
3306 | /// '[' expression[opt] ']' | |||
3307 | /// direct-new-declarator '[' constant-expression ']' | |||
3308 | /// | |||
3309 | void Parser::ParseDirectNewDeclarator(Declarator &D) { | |||
3310 | // Parse the array dimensions. | |||
3311 | bool First = true; | |||
3312 | while (Tok.is(tok::l_square)) { | |||
3313 | // An array-size expression can't start with a lambda. | |||
3314 | if (CheckProhibitedCXX11Attribute()) | |||
3315 | continue; | |||
3316 | ||||
3317 | BalancedDelimiterTracker T(*this, tok::l_square); | |||
3318 | T.consumeOpen(); | |||
3319 | ||||
3320 | ExprResult Size = | |||
3321 | First ? (Tok.is(tok::r_square) ? ExprResult() : ParseExpression()) | |||
3322 | : ParseConstantExpression(); | |||
3323 | if (Size.isInvalid()) { | |||
3324 | // Recover | |||
3325 | SkipUntil(tok::r_square, StopAtSemi); | |||
3326 | return; | |||
3327 | } | |||
3328 | First = false; | |||
3329 | ||||
3330 | T.consumeClose(); | |||
3331 | ||||
3332 | // Attributes here appertain to the array type. C++11 [expr.new]p5. | |||
3333 | ParsedAttributes Attrs(AttrFactory); | |||
3334 | MaybeParseCXX11Attributes(Attrs); | |||
3335 | ||||
3336 | D.AddTypeInfo(DeclaratorChunk::getArray(0, | |||
3337 | /*isStatic=*/false, /*isStar=*/false, | |||
3338 | Size.get(), T.getOpenLocation(), | |||
3339 | T.getCloseLocation()), | |||
3340 | std::move(Attrs), T.getCloseLocation()); | |||
3341 | ||||
3342 | if (T.getCloseLocation().isInvalid()) | |||
3343 | return; | |||
3344 | } | |||
3345 | } | |||
3346 | ||||
3347 | /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id. | |||
3348 | /// This ambiguity appears in the syntax of the C++ new operator. | |||
3349 | /// | |||
3350 | /// new-expression: | |||
3351 | /// '::'[opt] 'new' new-placement[opt] '(' type-id ')' | |||
3352 | /// new-initializer[opt] | |||
3353 | /// | |||
3354 | /// new-placement: | |||
3355 | /// '(' expression-list ')' | |||
3356 | /// | |||
3357 | bool Parser::ParseExpressionListOrTypeId( | |||
3358 | SmallVectorImpl<Expr*> &PlacementArgs, | |||
3359 | Declarator &D) { | |||
3360 | // The '(' was already consumed. | |||
3361 | if (isTypeIdInParens()) { | |||
3362 | ParseSpecifierQualifierList(D.getMutableDeclSpec()); | |||
3363 | D.SetSourceRange(D.getDeclSpec().getSourceRange()); | |||
3364 | ParseDeclarator(D); | |||
3365 | return D.isInvalidType(); | |||
3366 | } | |||
3367 | ||||
3368 | // It's not a type, it has to be an expression list. | |||
3369 | return ParseExpressionList(PlacementArgs); | |||
3370 | } | |||
3371 | ||||
3372 | /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used | |||
3373 | /// to free memory allocated by new. | |||
3374 | /// | |||
3375 | /// This method is called to parse the 'delete' expression after the optional | |||
3376 | /// '::' has been already parsed. If the '::' was present, "UseGlobal" is true | |||
3377 | /// and "Start" is its location. Otherwise, "Start" is the location of the | |||
3378 | /// 'delete' token. | |||
3379 | /// | |||
3380 | /// delete-expression: | |||
3381 | /// '::'[opt] 'delete' cast-expression | |||
3382 | /// '::'[opt] 'delete' '[' ']' cast-expression | |||
3383 | ExprResult | |||
3384 | Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) { | |||
3385 | assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword")(static_cast <bool> (Tok.is(tok::kw_delete) && "Expected 'delete' keyword" ) ? void (0) : __assert_fail ("Tok.is(tok::kw_delete) && \"Expected 'delete' keyword\"" , "clang/lib/Parse/ParseExprCXX.cpp", 3385, __extension__ __PRETTY_FUNCTION__ )); | |||
3386 | ConsumeToken(); // Consume 'delete' | |||
3387 | ||||
3388 | // Array delete? | |||
3389 | bool ArrayDelete = false; | |||
3390 | if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) { | |||
3391 | // C++11 [expr.delete]p1: | |||
3392 | // Whenever the delete keyword is followed by empty square brackets, it | |||
3393 | // shall be interpreted as [array delete]. | |||
3394 | // [Footnote: A lambda expression with a lambda-introducer that consists | |||
3395 | // of empty square brackets can follow the delete keyword if | |||
3396 | // the lambda expression is enclosed in parentheses.] | |||
3397 | ||||
3398 | const Token Next = GetLookAheadToken(2); | |||
3399 | ||||
3400 | // Basic lookahead to check if we have a lambda expression. | |||
3401 | if (Next.isOneOf(tok::l_brace, tok::less) || | |||
3402 | (Next.is(tok::l_paren) && | |||
3403 | (GetLookAheadToken(3).is(tok::r_paren) || | |||
3404 | (GetLookAheadToken(3).is(tok::identifier) && | |||
3405 | GetLookAheadToken(4).is(tok::identifier))))) { | |||
3406 | TentativeParsingAction TPA(*this); | |||
3407 | SourceLocation LSquareLoc = Tok.getLocation(); | |||
3408 | SourceLocation RSquareLoc = NextToken().getLocation(); | |||
3409 | ||||
3410 | // SkipUntil can't skip pairs of </*...*/>; don't emit a FixIt in this | |||
3411 | // case. | |||
3412 | SkipUntil({tok::l_brace, tok::less}, StopBeforeMatch); | |||
3413 | SourceLocation RBraceLoc; | |||
3414 | bool EmitFixIt = false; | |||
3415 | if (Tok.is(tok::l_brace)) { | |||
3416 | ConsumeBrace(); | |||
3417 | SkipUntil(tok::r_brace, StopBeforeMatch); | |||
3418 | RBraceLoc = Tok.getLocation(); | |||
3419 | EmitFixIt = true; | |||
3420 | } | |||
3421 | ||||
3422 | TPA.Revert(); | |||
3423 | ||||
3424 | if (EmitFixIt) | |||
3425 | Diag(Start, diag::err_lambda_after_delete) | |||
3426 | << SourceRange(Start, RSquareLoc) | |||
3427 | << FixItHint::CreateInsertion(LSquareLoc, "(") | |||
3428 | << FixItHint::CreateInsertion( | |||
3429 | Lexer::getLocForEndOfToken( | |||
3430 | RBraceLoc, 0, Actions.getSourceManager(), getLangOpts()), | |||
3431 | ")"); | |||
3432 | else | |||
3433 | Diag(Start, diag::err_lambda_after_delete) | |||
3434 | << SourceRange(Start, RSquareLoc); | |||
3435 | ||||
3436 | // Warn that the non-capturing lambda isn't surrounded by parentheses | |||
3437 | // to disambiguate it from 'delete[]'. | |||
3438 | ExprResult Lambda = ParseLambdaExpression(); | |||
3439 | if (Lambda.isInvalid()) | |||
3440 | return ExprError(); | |||
3441 | ||||
3442 | // Evaluate any postfix expressions used on the lambda. | |||
3443 | Lambda = ParsePostfixExpressionSuffix(Lambda); | |||
3444 | if (Lambda.isInvalid()) | |||
3445 | return ExprError(); | |||
3446 | return Actions.ActOnCXXDelete(Start, UseGlobal, /*ArrayForm=*/false, | |||
3447 | Lambda.get()); | |||
3448 | } | |||
3449 | ||||
3450 | ArrayDelete = true; | |||
3451 | BalancedDelimiterTracker T(*this, tok::l_square); | |||
3452 | ||||
3453 | T.consumeOpen(); | |||
3454 | T.consumeClose(); | |||
3455 | if (T.getCloseLocation().isInvalid()) | |||
3456 | return ExprError(); | |||
3457 | } | |||
3458 | ||||
3459 | ExprResult Operand(ParseCastExpression(AnyCastExpr)); | |||
3460 | if (Operand.isInvalid()) | |||
3461 | return Operand; | |||
3462 | ||||
3463 | return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get()); | |||
3464 | } | |||
3465 | ||||
3466 | /// ParseRequiresExpression - Parse a C++2a requires-expression. | |||
3467 | /// C++2a [expr.prim.req]p1 | |||
3468 | /// A requires-expression provides a concise way to express requirements on | |||
3469 | /// template arguments. A requirement is one that can be checked by name | |||
3470 | /// lookup (6.4) or by checking properties of types and expressions. | |||
3471 | /// | |||
3472 | /// requires-expression: | |||
3473 | /// 'requires' requirement-parameter-list[opt] requirement-body | |||
3474 | /// | |||
3475 | /// requirement-parameter-list: | |||
3476 | /// '(' parameter-declaration-clause[opt] ')' | |||
3477 | /// | |||
3478 | /// requirement-body: | |||
3479 | /// '{' requirement-seq '}' | |||
3480 | /// | |||
3481 | /// requirement-seq: | |||
3482 | /// requirement | |||
3483 | /// requirement-seq requirement | |||
3484 | /// | |||
3485 | /// requirement: | |||
3486 | /// simple-requirement | |||
3487 | /// type-requirement | |||
3488 | /// compound-requirement | |||
3489 | /// nested-requirement | |||
3490 | ExprResult Parser::ParseRequiresExpression() { | |||
3491 | assert(Tok.is(tok::kw_requires) && "Expected 'requires' keyword")(static_cast <bool> (Tok.is(tok::kw_requires) && "Expected 'requires' keyword") ? void (0) : __assert_fail ("Tok.is(tok::kw_requires) && \"Expected 'requires' keyword\"" , "clang/lib/Parse/ParseExprCXX.cpp", 3491, __extension__ __PRETTY_FUNCTION__ )); | |||
3492 | SourceLocation RequiresKWLoc = ConsumeToken(); // Consume 'requires' | |||
3493 | ||||
3494 | llvm::SmallVector<ParmVarDecl *, 2> LocalParameterDecls; | |||
3495 | if (Tok.is(tok::l_paren)) { | |||
3496 | // requirement parameter list is present. | |||
3497 | ParseScope LocalParametersScope(this, Scope::FunctionPrototypeScope | | |||
3498 | Scope::DeclScope); | |||
3499 | BalancedDelimiterTracker Parens(*this, tok::l_paren); | |||
3500 | Parens.consumeOpen(); | |||
3501 | if (!Tok.is(tok::r_paren)) { | |||
3502 | ParsedAttributes FirstArgAttrs(getAttrFactory()); | |||
3503 | SourceLocation EllipsisLoc; | |||
3504 | llvm::SmallVector<DeclaratorChunk::ParamInfo, 2> LocalParameters; | |||
3505 | ParseParameterDeclarationClause(DeclaratorContext::RequiresExpr, | |||
3506 | FirstArgAttrs, LocalParameters, | |||
3507 | EllipsisLoc); | |||
3508 | if (EllipsisLoc.isValid()) | |||
3509 | Diag(EllipsisLoc, diag::err_requires_expr_parameter_list_ellipsis); | |||
3510 | for (auto &ParamInfo : LocalParameters) | |||
3511 | LocalParameterDecls.push_back(cast<ParmVarDecl>(ParamInfo.Param)); | |||
3512 | } | |||
3513 | Parens.consumeClose(); | |||
3514 | } | |||
3515 | ||||
3516 | BalancedDelimiterTracker Braces(*this, tok::l_brace); | |||
3517 | if (Braces.expectAndConsume()) | |||
3518 | return ExprError(); | |||
3519 | ||||
3520 | // Start of requirement list | |||
3521 | llvm::SmallVector<concepts::Requirement *, 2> Requirements; | |||
3522 | ||||
3523 | // C++2a [expr.prim.req]p2 | |||
3524 | // Expressions appearing within a requirement-body are unevaluated operands. | |||
3525 | EnterExpressionEvaluationContext Ctx( | |||
3526 | Actions, Sema::ExpressionEvaluationContext::Unevaluated); | |||
3527 | ||||
3528 | ParseScope BodyScope(this, Scope::DeclScope); | |||
3529 | // Create a separate diagnostic pool for RequiresExprBodyDecl. | |||
3530 | // Dependent diagnostics are attached to this Decl and non-depenedent | |||
3531 | // diagnostics are surfaced after this parse. | |||
3532 | ParsingDeclRAIIObject ParsingBodyDecl(*this, ParsingDeclRAIIObject::NoParent); | |||
3533 | RequiresExprBodyDecl *Body = Actions.ActOnStartRequiresExpr( | |||
3534 | RequiresKWLoc, LocalParameterDecls, getCurScope()); | |||
3535 | ||||
3536 | if (Tok.is(tok::r_brace)) { | |||
3537 | // Grammar does not allow an empty body. | |||
3538 | // requirement-body: | |||
3539 | // { requirement-seq } | |||
3540 | // requirement-seq: | |||
3541 | // requirement | |||
3542 | // requirement-seq requirement | |||
3543 | Diag(Tok, diag::err_empty_requires_expr); | |||
3544 | // Continue anyway and produce a requires expr with no requirements. | |||
3545 | } else { | |||
3546 | while (!Tok.is(tok::r_brace)) { | |||
3547 | switch (Tok.getKind()) { | |||
3548 | case tok::l_brace: { | |||
3549 | // Compound requirement | |||
3550 | // C++ [expr.prim.req.compound] | |||
3551 | // compound-requirement: | |||
3552 | // '{' expression '}' 'noexcept'[opt] | |||
3553 | // return-type-requirement[opt] ';' | |||
3554 | // return-type-requirement: | |||
3555 | // trailing-return-type | |||
3556 | // '->' cv-qualifier-seq[opt] constrained-parameter | |||
3557 | // cv-qualifier-seq[opt] abstract-declarator[opt] | |||
3558 | BalancedDelimiterTracker ExprBraces(*this, tok::l_brace); | |||
3559 | ExprBraces.consumeOpen(); | |||
3560 | ExprResult Expression = | |||
3561 | Actions.CorrectDelayedTyposInExpr(ParseExpression()); | |||
3562 | if (!Expression.isUsable()) { | |||
3563 | ExprBraces.skipToEnd(); | |||
3564 | SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch); | |||
3565 | break; | |||
3566 | } | |||
3567 | if (ExprBraces.consumeClose()) | |||
3568 | ExprBraces.skipToEnd(); | |||
3569 | ||||
3570 | concepts::Requirement *Req = nullptr; | |||
3571 | SourceLocation NoexceptLoc; | |||
3572 | TryConsumeToken(tok::kw_noexcept, NoexceptLoc); | |||
3573 | if (Tok.is(tok::semi)) { | |||
3574 | Req = Actions.ActOnCompoundRequirement(Expression.get(), NoexceptLoc); | |||
3575 | if (Req) | |||
3576 | Requirements.push_back(Req); | |||
3577 | break; | |||
3578 | } | |||
3579 | if (!TryConsumeToken(tok::arrow)) | |||
3580 | // User probably forgot the arrow, remind them and try to continue. | |||
3581 | Diag(Tok, diag::err_requires_expr_missing_arrow) | |||
3582 | << FixItHint::CreateInsertion(Tok.getLocation(), "->"); | |||
3583 | // Try to parse a 'type-constraint' | |||
3584 | if (TryAnnotateTypeConstraint()) { | |||
3585 | SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch); | |||
3586 | break; | |||
3587 | } | |||
3588 | if (!isTypeConstraintAnnotation()) { | |||
3589 | Diag(Tok, diag::err_requires_expr_expected_type_constraint); | |||
3590 | SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch); | |||
3591 | break; | |||
3592 | } | |||
3593 | CXXScopeSpec SS; | |||
3594 | if (Tok.is(tok::annot_cxxscope)) { | |||
3595 | Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(), | |||
3596 | Tok.getAnnotationRange(), | |||
3597 | SS); | |||
3598 | ConsumeAnnotationToken(); | |||
3599 | } | |||
3600 | ||||
3601 | Req = Actions.ActOnCompoundRequirement( | |||
3602 | Expression.get(), NoexceptLoc, SS, takeTemplateIdAnnotation(Tok), | |||
3603 | TemplateParameterDepth); | |||
3604 | ConsumeAnnotationToken(); | |||
3605 | if (Req) | |||
3606 | Requirements.push_back(Req); | |||
3607 | break; | |||
3608 | } | |||
3609 | default: { | |||
3610 | bool PossibleRequiresExprInSimpleRequirement = false; | |||
3611 | if (Tok.is(tok::kw_requires)) { | |||
3612 | auto IsNestedRequirement = [&] { | |||
3613 | RevertingTentativeParsingAction TPA(*this); | |||
3614 | ConsumeToken(); // 'requires' | |||
3615 | if (Tok.is(tok::l_brace)) | |||
3616 | // This is a requires expression | |||
3617 | // requires (T t) { | |||
3618 | // requires { t++; }; | |||
3619 | // ... ^ | |||
3620 | // } | |||
3621 | return false; | |||
3622 | if (Tok.is(tok::l_paren)) { | |||
3623 | // This might be the parameter list of a requires expression | |||
3624 | ConsumeParen(); | |||
3625 | auto Res = TryParseParameterDeclarationClause(); | |||
3626 | if (Res != TPResult::False) { | |||
3627 | // Skip to the closing parenthesis | |||
3628 | // FIXME: Don't traverse these tokens twice (here and in | |||
3629 | // TryParseParameterDeclarationClause). | |||
3630 | unsigned Depth = 1; | |||
3631 | while (Depth != 0) { | |||
3632 | if (Tok.is(tok::l_paren)) | |||
3633 | Depth++; | |||
3634 | else if (Tok.is(tok::r_paren)) | |||
3635 | Depth--; | |||
3636 | ConsumeAnyToken(); | |||
3637 | } | |||
3638 | // requires (T t) { | |||
3639 | // requires () ? | |||
3640 | // ... ^ | |||
3641 | // - OR - | |||
3642 | // requires (int x) ? | |||
3643 | // ... ^ | |||
3644 | // } | |||
3645 | if (Tok.is(tok::l_brace)) | |||
3646 | // requires (...) { | |||
3647 | // ^ - a requires expression as a | |||
3648 | // simple-requirement. | |||
3649 | return false; | |||
3650 | } | |||
3651 | } | |||
3652 | return true; | |||
3653 | }; | |||
3654 | if (IsNestedRequirement()) { | |||
3655 | ConsumeToken(); | |||
3656 | // Nested requirement | |||
3657 | // C++ [expr.prim.req.nested] | |||
3658 | // nested-requirement: | |||
3659 | // 'requires' constraint-expression ';' | |||
3660 | ExprResult ConstraintExpr = | |||
3661 | Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression()); | |||
3662 | if (ConstraintExpr.isInvalid() || !ConstraintExpr.isUsable()) { | |||
3663 | SkipUntil(tok::semi, tok::r_brace, | |||
3664 | SkipUntilFlags::StopBeforeMatch); | |||
3665 | break; | |||
3666 | } | |||
3667 | if (auto *Req = | |||
3668 | Actions.ActOnNestedRequirement(ConstraintExpr.get())) | |||
3669 | Requirements.push_back(Req); | |||
3670 | else { | |||
3671 | SkipUntil(tok::semi, tok::r_brace, | |||
3672 | SkipUntilFlags::StopBeforeMatch); | |||
3673 | break; | |||
3674 | } | |||
3675 | break; | |||
3676 | } else | |||
3677 | PossibleRequiresExprInSimpleRequirement = true; | |||
3678 | } else if (Tok.is(tok::kw_typename)) { | |||
3679 | // This might be 'typename T::value_type;' (a type requirement) or | |||
3680 | // 'typename T::value_type{};' (a simple requirement). | |||
3681 | TentativeParsingAction TPA(*this); | |||
3682 | ||||
3683 | // We need to consume the typename to allow 'requires { typename a; }' | |||
3684 | SourceLocation TypenameKWLoc = ConsumeToken(); | |||
3685 | if (TryAnnotateOptionalCXXScopeToken()) { | |||
3686 | TPA.Commit(); | |||
3687 | SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch); | |||
3688 | break; | |||
3689 | } | |||
3690 | CXXScopeSpec SS; | |||
3691 | if (Tok.is(tok::annot_cxxscope)) { | |||
3692 | Actions.RestoreNestedNameSpecifierAnnotation( | |||
3693 | Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS); | |||
3694 | ConsumeAnnotationToken(); | |||
3695 | } | |||
3696 | ||||
3697 | if (Tok.isOneOf(tok::identifier, tok::annot_template_id) && | |||
3698 | !NextToken().isOneOf(tok::l_brace, tok::l_paren)) { | |||
3699 | TPA.Commit(); | |||
3700 | SourceLocation NameLoc = Tok.getLocation(); | |||
3701 | IdentifierInfo *II = nullptr; | |||
3702 | TemplateIdAnnotation *TemplateId = nullptr; | |||
3703 | if (Tok.is(tok::identifier)) { | |||
3704 | II = Tok.getIdentifierInfo(); | |||
3705 | ConsumeToken(); | |||
3706 | } else { | |||
3707 | TemplateId = takeTemplateIdAnnotation(Tok); | |||
3708 | ConsumeAnnotationToken(); | |||
3709 | if (TemplateId->isInvalid()) | |||
3710 | break; | |||
3711 | } | |||
3712 | ||||
3713 | if (auto *Req = Actions.ActOnTypeRequirement(TypenameKWLoc, SS, | |||
3714 | NameLoc, II, | |||
3715 | TemplateId)) { | |||
3716 | Requirements.push_back(Req); | |||
3717 | } | |||
3718 | break; | |||
3719 | } | |||
3720 | TPA.Revert(); | |||
3721 | } | |||
3722 | // Simple requirement | |||
3723 | // C++ [expr.prim.req.simple] | |||
3724 | // simple-requirement: | |||
3725 | // expression ';' | |||
3726 | SourceLocation StartLoc = Tok.getLocation(); | |||
3727 | ExprResult Expression = | |||
3728 | Actions.CorrectDelayedTyposInExpr(ParseExpression()); | |||
3729 | if (!Expression.isUsable()) { | |||
3730 | SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch); | |||
3731 | break; | |||
3732 | } | |||
3733 | if (!Expression.isInvalid() && PossibleRequiresExprInSimpleRequirement) | |||
3734 | Diag(StartLoc, diag::err_requires_expr_in_simple_requirement) | |||
3735 | << FixItHint::CreateInsertion(StartLoc, "requires"); | |||
3736 | if (auto *Req = Actions.ActOnSimpleRequirement(Expression.get())) | |||
3737 | Requirements.push_back(Req); | |||
3738 | else { | |||
3739 | SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch); | |||
3740 | break; | |||
3741 | } | |||
3742 | // User may have tried to put some compound requirement stuff here | |||
3743 | if (Tok.is(tok::kw_noexcept)) { | |||
3744 | Diag(Tok, diag::err_requires_expr_simple_requirement_noexcept) | |||
3745 | << FixItHint::CreateInsertion(StartLoc, "{") | |||
3746 | << FixItHint::CreateInsertion(Tok.getLocation(), "}"); | |||
3747 | SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch); | |||
3748 | break; | |||
3749 | } | |||
3750 | break; | |||
3751 | } | |||
3752 | } | |||
3753 | if (ExpectAndConsumeSemi(diag::err_expected_semi_requirement)) { | |||
3754 | SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch); | |||
3755 | TryConsumeToken(tok::semi); | |||
3756 | break; | |||
3757 | } | |||
3758 | } | |||
3759 | if (Requirements.empty()) { | |||
3760 | // Don't emit an empty requires expr here to avoid confusing the user with | |||
3761 | // other diagnostics quoting an empty requires expression they never | |||
3762 | // wrote. | |||
3763 | Braces.consumeClose(); | |||
3764 | Actions.ActOnFinishRequiresExpr(); | |||
3765 | return ExprError(); | |||
3766 | } | |||
3767 | } | |||
3768 | Braces.consumeClose(); | |||
3769 | Actions.ActOnFinishRequiresExpr(); | |||
3770 | ParsingBodyDecl.complete(Body); | |||
3771 | return Actions.ActOnRequiresExpr(RequiresKWLoc, Body, LocalParameterDecls, | |||
3772 | Requirements, Braces.getCloseLocation()); | |||
3773 | } | |||
3774 | ||||
3775 | static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) { | |||
3776 | switch (kind) { | |||
3777 | default: llvm_unreachable("Not a known type trait")::llvm::llvm_unreachable_internal("Not a known type trait", "clang/lib/Parse/ParseExprCXX.cpp" , 3777); | |||
3778 | #define TYPE_TRAIT_1(Spelling, Name, Key) \ | |||
3779 | case tok::kw_ ## Spelling: return UTT_ ## Name; | |||
3780 | #define TYPE_TRAIT_2(Spelling, Name, Key) \ | |||
3781 | case tok::kw_ ## Spelling: return BTT_ ## Name; | |||
3782 | #include "clang/Basic/TokenKinds.def" | |||
3783 | #define TYPE_TRAIT_N(Spelling, Name, Key) \ | |||
3784 | case tok::kw_ ## Spelling: return TT_ ## Name; | |||
3785 | #include "clang/Basic/TokenKinds.def" | |||
3786 | } | |||
3787 | } | |||
3788 | ||||
3789 | static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) { | |||
3790 | switch (kind) { | |||
3791 | default: | |||
3792 | llvm_unreachable("Not a known array type trait")::llvm::llvm_unreachable_internal("Not a known array type trait" , "clang/lib/Parse/ParseExprCXX.cpp", 3792); | |||
3793 | #define ARRAY_TYPE_TRAIT(Spelling, Name, Key) \ | |||
3794 | case tok::kw_##Spelling: \ | |||
3795 | return ATT_##Name; | |||
3796 | #include "clang/Basic/TokenKinds.def" | |||
3797 | } | |||
3798 | } | |||
3799 | ||||
3800 | static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) { | |||
3801 | switch (kind) { | |||
3802 | default: | |||
3803 | llvm_unreachable("Not a known unary expression trait.")::llvm::llvm_unreachable_internal("Not a known unary expression trait." , "clang/lib/Parse/ParseExprCXX.cpp", 3803); | |||
3804 | #define EXPRESSION_TRAIT(Spelling, Name, Key) \ | |||
3805 | case tok::kw_##Spelling: \ | |||
3806 | return ET_##Name; | |||
3807 | #include "clang/Basic/TokenKinds.def" | |||
3808 | } | |||
3809 | } | |||
3810 | ||||
3811 | /// Parse the built-in type-trait pseudo-functions that allow | |||
3812 | /// implementation of the TR1/C++11 type traits templates. | |||
3813 | /// | |||
3814 | /// primary-expression: | |||
3815 | /// unary-type-trait '(' type-id ')' | |||
3816 | /// binary-type-trait '(' type-id ',' type-id ')' | |||
3817 | /// type-trait '(' type-id-seq ')' | |||
3818 | /// | |||
3819 | /// type-id-seq: | |||
3820 | /// type-id ...[opt] type-id-seq[opt] | |||
3821 | /// | |||
3822 | ExprResult Parser::ParseTypeTrait() { | |||
3823 | tok::TokenKind Kind = Tok.getKind(); | |||
3824 | ||||
3825 | SourceLocation Loc = ConsumeToken(); | |||
3826 | ||||
3827 | BalancedDelimiterTracker Parens(*this, tok::l_paren); | |||
3828 | if (Parens.expectAndConsume()) | |||
3829 | return ExprError(); | |||
3830 | ||||
3831 | SmallVector<ParsedType, 2> Args; | |||
3832 | do { | |||
3833 | // Parse the next type. | |||
3834 | TypeResult Ty = ParseTypeName(); | |||
3835 | if (Ty.isInvalid()) { | |||
3836 | Parens.skipToEnd(); | |||
3837 | return ExprError(); | |||
3838 | } | |||
3839 | ||||
3840 | // Parse the ellipsis, if present. | |||
3841 | if (Tok.is(tok::ellipsis)) { | |||
3842 | Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken()); | |||
3843 | if (Ty.isInvalid()) { | |||
3844 | Parens.skipToEnd(); | |||
3845 | return ExprError(); | |||
3846 | } | |||
3847 | } | |||
3848 | ||||
3849 | // Add this type to the list of arguments. | |||
3850 | Args.push_back(Ty.get()); | |||
3851 | } while (TryConsumeToken(tok::comma)); | |||
3852 | ||||
3853 | if (Parens.consumeClose()) | |||
3854 | return ExprError(); | |||
3855 | ||||
3856 | SourceLocation EndLoc = Parens.getCloseLocation(); | |||
3857 | ||||
3858 | return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc); | |||
3859 | } | |||
3860 | ||||
3861 | /// ParseArrayTypeTrait - Parse the built-in array type-trait | |||
3862 | /// pseudo-functions. | |||
3863 | /// | |||
3864 | /// primary-expression: | |||
3865 | /// [Embarcadero] '__array_rank' '(' type-id ')' | |||
3866 | /// [Embarcadero] '__array_extent' '(' type-id ',' expression ')' | |||
3867 | /// | |||
3868 | ExprResult Parser::ParseArrayTypeTrait() { | |||
3869 | ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind()); | |||
3870 | SourceLocation Loc = ConsumeToken(); | |||
3871 | ||||
3872 | BalancedDelimiterTracker T(*this, tok::l_paren); | |||
3873 | if (T.expectAndConsume()) | |||
3874 | return ExprError(); | |||
3875 | ||||
3876 | TypeResult Ty = ParseTypeName(); | |||
3877 | if (Ty.isInvalid()) { | |||
3878 | SkipUntil(tok::comma, StopAtSemi); | |||
3879 | SkipUntil(tok::r_paren, StopAtSemi); | |||
3880 | return ExprError(); | |||
3881 | } | |||
3882 | ||||
3883 | switch (ATT) { | |||
3884 | case ATT_ArrayRank: { | |||
3885 | T.consumeClose(); | |||
3886 | return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr, | |||
3887 | T.getCloseLocation()); | |||
3888 | } | |||
3889 | case ATT_ArrayExtent: { | |||
3890 | if (ExpectAndConsume(tok::comma)) { | |||
3891 | SkipUntil(tok::r_paren, StopAtSemi); | |||
3892 | return ExprError(); | |||
3893 | } | |||
3894 | ||||
3895 | ExprResult DimExpr = ParseExpression(); | |||
3896 | T.consumeClose(); | |||
3897 | ||||
3898 | return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(), | |||
3899 | T.getCloseLocation()); | |||
3900 | } | |||
3901 | } | |||
3902 | llvm_unreachable("Invalid ArrayTypeTrait!")::llvm::llvm_unreachable_internal("Invalid ArrayTypeTrait!", "clang/lib/Parse/ParseExprCXX.cpp" , 3902); | |||
3903 | } | |||
3904 | ||||
3905 | /// ParseExpressionTrait - Parse built-in expression-trait | |||
3906 | /// pseudo-functions like __is_lvalue_expr( xxx ). | |||
3907 | /// | |||
3908 | /// primary-expression: | |||
3909 | /// [Embarcadero] expression-trait '(' expression ')' | |||
3910 | /// | |||
3911 | ExprResult Parser::ParseExpressionTrait() { | |||
3912 | ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind()); | |||
3913 | SourceLocation Loc = ConsumeToken(); | |||
3914 | ||||
3915 | BalancedDelimiterTracker T(*this, tok::l_paren); | |||
3916 | if (T.expectAndConsume()) | |||
3917 | return ExprError(); | |||
3918 | ||||
3919 | ExprResult Expr = ParseExpression(); | |||
3920 | ||||
3921 | T.consumeClose(); | |||
3922 | ||||
3923 | return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(), | |||
3924 | T.getCloseLocation()); | |||
3925 | } | |||
3926 | ||||
3927 | ||||
3928 | /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a | |||
3929 | /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate | |||
3930 | /// based on the context past the parens. | |||
3931 | ExprResult | |||
3932 | Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType, | |||
3933 | ParsedType &CastTy, | |||
3934 | BalancedDelimiterTracker &Tracker, | |||
3935 | ColonProtectionRAIIObject &ColonProt) { | |||
3936 | assert(getLangOpts().CPlusPlus && "Should only be called for C++!")(static_cast <bool> (getLangOpts().CPlusPlus && "Should only be called for C++!") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"Should only be called for C++!\"" , "clang/lib/Parse/ParseExprCXX.cpp", 3936, __extension__ __PRETTY_FUNCTION__ )); | |||
3937 | assert(ExprType == CastExpr && "Compound literals are not ambiguous!")(static_cast <bool> (ExprType == CastExpr && "Compound literals are not ambiguous!" ) ? void (0) : __assert_fail ("ExprType == CastExpr && \"Compound literals are not ambiguous!\"" , "clang/lib/Parse/ParseExprCXX.cpp", 3937, __extension__ __PRETTY_FUNCTION__ )); | |||
3938 | assert(isTypeIdInParens() && "Not a type-id!")(static_cast <bool> (isTypeIdInParens() && "Not a type-id!" ) ? void (0) : __assert_fail ("isTypeIdInParens() && \"Not a type-id!\"" , "clang/lib/Parse/ParseExprCXX.cpp", 3938, __extension__ __PRETTY_FUNCTION__ )); | |||
3939 | ||||
3940 | ExprResult Result(true); | |||
3941 | CastTy = nullptr; | |||
3942 | ||||
3943 | // We need to disambiguate a very ugly part of the C++ syntax: | |||
3944 | // | |||
3945 | // (T())x; - type-id | |||
3946 | // (T())*x; - type-id | |||
3947 | // (T())/x; - expression | |||
3948 | // (T()); - expression | |||
3949 | // | |||
3950 | // The bad news is that we cannot use the specialized tentative parser, since | |||
3951 | // it can only verify that the thing inside the parens can be parsed as | |||
3952 | // type-id, it is not useful for determining the context past the parens. | |||
3953 | // | |||
3954 | // The good news is that the parser can disambiguate this part without | |||
3955 | // making any unnecessary Action calls. | |||
3956 | // | |||
3957 | // It uses a scheme similar to parsing inline methods. The parenthesized | |||
3958 | // tokens are cached, the context that follows is determined (possibly by | |||
3959 | // parsing a cast-expression), and then we re-introduce the cached tokens | |||
3960 | // into the token stream and parse them appropriately. | |||
3961 | ||||
3962 | ParenParseOption ParseAs; | |||
3963 | CachedTokens Toks; | |||
3964 | ||||
3965 | // Store the tokens of the parentheses. We will parse them after we determine | |||
3966 | // the context that follows them. | |||
3967 | if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) { | |||
3968 | // We didn't find the ')' we expected. | |||
3969 | Tracker.consumeClose(); | |||
3970 | return ExprError(); | |||
3971 | } | |||
3972 | ||||
3973 | if (Tok.is(tok::l_brace)) { | |||
3974 | ParseAs = CompoundLiteral; | |||
3975 | } else { | |||
3976 | bool NotCastExpr; | |||
3977 | if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) { | |||
3978 | NotCastExpr = true; | |||
3979 | } else { | |||
3980 | // Try parsing the cast-expression that may follow. | |||
3981 | // If it is not a cast-expression, NotCastExpr will be true and no token | |||
3982 | // will be consumed. | |||
3983 | ColonProt.restore(); | |||
3984 | Result = ParseCastExpression(AnyCastExpr, | |||
3985 | false/*isAddressofOperand*/, | |||
3986 | NotCastExpr, | |||
3987 | // type-id has priority. | |||
3988 | IsTypeCast); | |||
3989 | } | |||
3990 | ||||
3991 | // If we parsed a cast-expression, it's really a type-id, otherwise it's | |||
3992 | // an expression. | |||
3993 | ParseAs = NotCastExpr ? SimpleExpr : CastExpr; | |||
3994 | } | |||
3995 | ||||
3996 | // Create a fake EOF to mark end of Toks buffer. | |||
3997 | Token AttrEnd; | |||
3998 | AttrEnd.startToken(); | |||
3999 | AttrEnd.setKind(tok::eof); | |||
4000 | AttrEnd.setLocation(Tok.getLocation()); | |||
4001 | AttrEnd.setEofData(Toks.data()); | |||
4002 | Toks.push_back(AttrEnd); | |||
4003 | ||||
4004 | // The current token should go after the cached tokens. | |||
4005 | Toks.push_back(Tok); | |||
4006 | // Re-enter the stored parenthesized tokens into the token stream, so we may | |||
4007 | // parse them now. | |||
4008 | PP.EnterTokenStream(Toks, /*DisableMacroExpansion*/ true, | |||
4009 | /*IsReinject*/ true); | |||
4010 | // Drop the current token and bring the first cached one. It's the same token | |||
4011 | // as when we entered this function. | |||
4012 | ConsumeAnyToken(); | |||
4013 | ||||
4014 | if (ParseAs >= CompoundLiteral) { | |||
4015 | // Parse the type declarator. | |||
4016 | DeclSpec DS(AttrFactory); | |||
4017 | Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), | |||
4018 | DeclaratorContext::TypeName); | |||
4019 | { | |||
4020 | ColonProtectionRAIIObject InnerColonProtection(*this); | |||
4021 | ParseSpecifierQualifierList(DS); | |||
4022 | ParseDeclarator(DeclaratorInfo); | |||
4023 | } | |||
4024 | ||||
4025 | // Match the ')'. | |||
4026 | Tracker.consumeClose(); | |||
4027 | ColonProt.restore(); | |||
4028 | ||||
4029 | // Consume EOF marker for Toks buffer. | |||
4030 | assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())(static_cast <bool> (Tok.is(tok::eof) && Tok.getEofData () == AttrEnd.getEofData()) ? void (0) : __assert_fail ("Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData()" , "clang/lib/Parse/ParseExprCXX.cpp", 4030, __extension__ __PRETTY_FUNCTION__ )); | |||
4031 | ConsumeAnyToken(); | |||
4032 | ||||
4033 | if (ParseAs == CompoundLiteral) { | |||
4034 | ExprType = CompoundLiteral; | |||
4035 | if (DeclaratorInfo.isInvalidType()) | |||
4036 | return ExprError(); | |||
4037 | ||||
4038 | TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); | |||
4039 | return ParseCompoundLiteralExpression(Ty.get(), | |||
4040 | Tracker.getOpenLocation(), | |||
4041 | Tracker.getCloseLocation()); | |||
4042 | } | |||
4043 | ||||
4044 | // We parsed '(' type-id ')' and the thing after it wasn't a '{'. | |||
4045 | assert(ParseAs == CastExpr)(static_cast <bool> (ParseAs == CastExpr) ? void (0) : __assert_fail ("ParseAs == CastExpr", "clang/lib/Parse/ParseExprCXX.cpp", 4045 , __extension__ __PRETTY_FUNCTION__)); | |||
4046 | ||||
4047 | if (DeclaratorInfo.isInvalidType()) | |||
4048 | return ExprError(); | |||
4049 | ||||
4050 | // Result is what ParseCastExpression returned earlier. | |||
4051 | if (!Result.isInvalid()) | |||
4052 | Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(), | |||
4053 | DeclaratorInfo, CastTy, | |||
4054 | Tracker.getCloseLocation(), Result.get()); | |||
4055 | return Result; | |||
4056 | } | |||
4057 | ||||
4058 | // Not a compound literal, and not followed by a cast-expression. | |||
4059 | assert(ParseAs == SimpleExpr)(static_cast <bool> (ParseAs == SimpleExpr) ? void (0) : __assert_fail ("ParseAs == SimpleExpr", "clang/lib/Parse/ParseExprCXX.cpp" , 4059, __extension__ __PRETTY_FUNCTION__)); | |||
4060 | ||||
4061 | ExprType = SimpleExpr; | |||
4062 | Result = ParseExpression(); | |||
4063 | if (!Result.isInvalid() && Tok.is(tok::r_paren)) | |||
4064 | Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(), | |||
4065 | Tok.getLocation(), Result.get()); | |||
4066 | ||||
4067 | // Match the ')'. | |||
4068 | if (Result.isInvalid()) { | |||
4069 | while (Tok.isNot(tok::eof)) | |||
4070 | ConsumeAnyToken(); | |||
4071 | assert(Tok.getEofData() == AttrEnd.getEofData())(static_cast <bool> (Tok.getEofData() == AttrEnd.getEofData ()) ? void (0) : __assert_fail ("Tok.getEofData() == AttrEnd.getEofData()" , "clang/lib/Parse/ParseExprCXX.cpp", 4071, __extension__ __PRETTY_FUNCTION__ )); | |||
4072 | ConsumeAnyToken(); | |||
4073 | return ExprError(); | |||
4074 | } | |||
4075 | ||||
4076 | Tracker.consumeClose(); | |||
4077 | // Consume EOF marker for Toks buffer. | |||
4078 | assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())(static_cast <bool> (Tok.is(tok::eof) && Tok.getEofData () == AttrEnd.getEofData()) ? void (0) : __assert_fail ("Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData()" , "clang/lib/Parse/ParseExprCXX.cpp", 4078, __extension__ __PRETTY_FUNCTION__ )); | |||
4079 | ConsumeAnyToken(); | |||
4080 | return Result; | |||
4081 | } | |||
4082 | ||||
4083 | /// Parse a __builtin_bit_cast(T, E). | |||
4084 | ExprResult Parser::ParseBuiltinBitCast() { | |||
4085 | SourceLocation KWLoc = ConsumeToken(); | |||
4086 | ||||
4087 | BalancedDelimiterTracker T(*this, tok::l_paren); | |||
4088 | if (T.expectAndConsume(diag::err_expected_lparen_after, "__builtin_bit_cast")) | |||
4089 | return ExprError(); | |||
4090 | ||||
4091 | // Parse the common declaration-specifiers piece. | |||
4092 | DeclSpec DS(AttrFactory); | |||
4093 | ParseSpecifierQualifierList(DS); | |||
4094 | ||||
4095 | // Parse the abstract-declarator, if present. | |||
4096 | Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), | |||
4097 | DeclaratorContext::TypeName); | |||
4098 | ParseDeclarator(DeclaratorInfo); | |||
4099 | ||||
4100 | if (ExpectAndConsume(tok::comma)) { | |||
4101 | Diag(Tok.getLocation(), diag::err_expected) << tok::comma; | |||
4102 | SkipUntil(tok::r_paren, StopAtSemi); | |||
4103 | return ExprError(); | |||
4104 | } | |||
4105 | ||||
4106 | ExprResult Operand = ParseExpression(); | |||
4107 | ||||
4108 | if (T.consumeClose()) | |||
4109 | return ExprError(); | |||
4110 | ||||
4111 | if (Operand.isInvalid() || DeclaratorInfo.isInvalidType()) | |||
4112 | return ExprError(); | |||
4113 | ||||
4114 | return Actions.ActOnBuiltinBitCastExpr(KWLoc, DeclaratorInfo, Operand, | |||
4115 | T.getCloseLocation()); | |||
4116 | } |