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