Bug Summary

File:tools/clang/lib/Parse/ParseExprCXX.cpp
Warning:line 1789, column 5
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ParseExprCXX.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/lib/Parse -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn329677/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/lib/Parse -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-04-11-031539-24776-1 -x c++ /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp
1//===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expression parsing implementation for C++.
11//
12//===----------------------------------------------------------------------===//
13#include "clang/Parse/Parser.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/DeclTemplate.h"
16#include "clang/Basic/PrettyStackTrace.h"
17#include "clang/Lex/LiteralSupport.h"
18#include "clang/Parse/ParseDiagnostic.h"
19#include "clang/Parse/RAIIObjectsForParser.h"
20#include "clang/Sema/DeclSpec.h"
21#include "clang/Sema/ParsedTemplate.h"
22#include "clang/Sema/Scope.h"
23#include "llvm/Support/ErrorHandling.h"
24
25
26using namespace clang;
27
28static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
29 switch (Kind) {
30 // template name
31 case tok::unknown: return 0;
32 // casts
33 case tok::kw_const_cast: return 1;
34 case tok::kw_dynamic_cast: return 2;
35 case tok::kw_reinterpret_cast: return 3;
36 case tok::kw_static_cast: return 4;
37 default:
38 llvm_unreachable("Unknown type for digraph error message.")::llvm::llvm_unreachable_internal("Unknown type for digraph error message."
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 38)
;
39 }
40}
41
42// Are the two tokens adjacent in the same source file?
43bool Parser::areTokensAdjacent(const Token &First, const Token &Second) {
44 SourceManager &SM = PP.getSourceManager();
45 SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
46 SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
47 return FirstEnd == SM.getSpellingLoc(Second.getLocation());
48}
49
50// Suggest fixit for "<::" after a cast.
51static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
52 Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
53 // Pull '<:' and ':' off token stream.
54 if (!AtDigraph)
55 PP.Lex(DigraphToken);
56 PP.Lex(ColonToken);
57
58 SourceRange Range;
59 Range.setBegin(DigraphToken.getLocation());
60 Range.setEnd(ColonToken.getLocation());
61 P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
62 << SelectDigraphErrorMessage(Kind)
63 << FixItHint::CreateReplacement(Range, "< ::");
64
65 // Update token information to reflect their change in token type.
66 ColonToken.setKind(tok::coloncolon);
67 ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
68 ColonToken.setLength(2);
69 DigraphToken.setKind(tok::less);
70 DigraphToken.setLength(1);
71
72 // Push new tokens back to token stream.
73 PP.EnterToken(ColonToken);
74 if (!AtDigraph)
75 PP.EnterToken(DigraphToken);
76}
77
78// Check for '<::' which should be '< ::' instead of '[:' when following
79// a template name.
80void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
81 bool EnteringContext,
82 IdentifierInfo &II, CXXScopeSpec &SS) {
83 if (!Next.is(tok::l_square) || Next.getLength() != 2)
84 return;
85
86 Token SecondToken = GetLookAheadToken(2);
87 if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken))
88 return;
89
90 TemplateTy Template;
91 UnqualifiedId TemplateName;
92 TemplateName.setIdentifier(&II, Tok.getLocation());
93 bool MemberOfUnknownSpecialization;
94 if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
95 TemplateName, ObjectType, EnteringContext,
96 Template, MemberOfUnknownSpecialization))
97 return;
98
99 FixDigraph(*this, PP, Next, SecondToken, tok::unknown,
100 /*AtDigraph*/false);
101}
102
103/// \brief Parse global scope or nested-name-specifier if present.
104///
105/// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
106/// may be preceded by '::'). Note that this routine will not parse ::new or
107/// ::delete; it will just leave them in the token stream.
108///
109/// '::'[opt] nested-name-specifier
110/// '::'
111///
112/// nested-name-specifier:
113/// type-name '::'
114/// namespace-name '::'
115/// nested-name-specifier identifier '::'
116/// nested-name-specifier 'template'[opt] simple-template-id '::'
117///
118///
119/// \param SS the scope specifier that will be set to the parsed
120/// nested-name-specifier (or empty)
121///
122/// \param ObjectType if this nested-name-specifier is being parsed following
123/// the "." or "->" of a member access expression, this parameter provides the
124/// type of the object whose members are being accessed.
125///
126/// \param EnteringContext whether we will be entering into the context of
127/// the nested-name-specifier after parsing it.
128///
129/// \param MayBePseudoDestructor When non-NULL, points to a flag that
130/// indicates whether this nested-name-specifier may be part of a
131/// pseudo-destructor name. In this case, the flag will be set false
132/// if we don't actually end up parsing a destructor name. Moreorover,
133/// if we do end up determining that we are parsing a destructor name,
134/// the last component of the nested-name-specifier is not parsed as
135/// part of the scope specifier.
136///
137/// \param IsTypename If \c true, this nested-name-specifier is known to be
138/// part of a type name. This is used to improve error recovery.
139///
140/// \param LastII When non-NULL, points to an IdentifierInfo* that will be
141/// filled in with the leading identifier in the last component of the
142/// nested-name-specifier, if any.
143///
144/// \param OnlyNamespace If true, only considers namespaces in lookup.
145///
146/// \returns true if there was an error parsing a scope specifier
147bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
148 ParsedType ObjectType,
149 bool EnteringContext,
150 bool *MayBePseudoDestructor,
151 bool IsTypename,
152 IdentifierInfo **LastII,
153 bool OnlyNamespace) {
154 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++\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 155, __extension__ __PRETTY_FUNCTION__))
155 "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++\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 155, __extension__ __PRETTY_FUNCTION__))
;
156
157 if (Tok.is(tok::annot_cxxscope)) {
158 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 158, __extension__ __PRETTY_FUNCTION__))
;
159 assert(!MayBePseudoDestructor && "unexpected annot_cxxscope")(static_cast <bool> (!MayBePseudoDestructor && "unexpected annot_cxxscope"
) ? void (0) : __assert_fail ("!MayBePseudoDestructor && \"unexpected annot_cxxscope\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 159, __extension__ __PRETTY_FUNCTION__))
;
160 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
161 Tok.getAnnotationRange(),
162 SS);
163 ConsumeAnnotationToken();
164 return false;
165 }
166
167 if (Tok.is(tok::annot_template_id)) {
168 // If the current token is an annotated template id, it may already have
169 // a scope specifier. Restore it.
170 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
171 SS = TemplateId->SS;
172 }
173
174 // Has to happen before any "return false"s in this function.
175 bool CheckForDestructor = false;
176 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
177 CheckForDestructor = true;
178 *MayBePseudoDestructor = false;
179 }
180
181 if (LastII)
182 *LastII = nullptr;
183
184 bool HasScopeSpecifier = false;
185
186 if (Tok.is(tok::coloncolon)) {
187 // ::new and ::delete aren't nested-name-specifiers.
188 tok::TokenKind NextKind = NextToken().getKind();
189 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
190 return false;
191
192 if (NextKind == tok::l_brace) {
193 // It is invalid to have :: {, consume the scope qualifier and pretend
194 // like we never saw it.
195 Diag(ConsumeToken(), diag::err_expected) << tok::identifier;
196 } else {
197 // '::' - Global scope qualifier.
198 if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
199 return true;
200
201 HasScopeSpecifier = true;
202 }
203 }
204
205 if (Tok.is(tok::kw___super)) {
206 SourceLocation SuperLoc = ConsumeToken();
207 if (!Tok.is(tok::coloncolon)) {
208 Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
209 return true;
210 }
211
212 return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
213 }
214
215 if (!HasScopeSpecifier &&
216 Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
217 DeclSpec DS(AttrFactory);
218 SourceLocation DeclLoc = Tok.getLocation();
219 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
220
221 SourceLocation CCLoc;
222 // Work around a standard defect: 'decltype(auto)::' is not a
223 // nested-name-specifier.
224 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto ||
225 !TryConsumeToken(tok::coloncolon, CCLoc)) {
226 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
227 return false;
228 }
229
230 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
231 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
232
233 HasScopeSpecifier = true;
234 }
235
236 while (true) {
237 if (HasScopeSpecifier) {
238 // C++ [basic.lookup.classref]p5:
239 // If the qualified-id has the form
240 //
241 // ::class-name-or-namespace-name::...
242 //
243 // the class-name-or-namespace-name is looked up in global scope as a
244 // class-name or namespace-name.
245 //
246 // To implement this, we clear out the object type as soon as we've
247 // seen a leading '::' or part of a nested-name-specifier.
248 ObjectType = nullptr;
249
250 if (Tok.is(tok::code_completion)) {
251 // Code completion for a nested-name-specifier, where the code
252 // completion token follows the '::'.
253 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
254 // Include code completion token into the range of the scope otherwise
255 // when we try to annotate the scope tokens the dangling code completion
256 // token will cause assertion in
257 // Preprocessor::AnnotatePreviousCachedTokens.
258 SS.setEndLoc(Tok.getLocation());
259 cutOffParsing();
260 return true;
261 }
262 }
263
264 // nested-name-specifier:
265 // nested-name-specifier 'template'[opt] simple-template-id '::'
266
267 // Parse the optional 'template' keyword, then make sure we have
268 // 'identifier <' after it.
269 if (Tok.is(tok::kw_template)) {
270 // If we don't have a scope specifier or an object type, this isn't a
271 // nested-name-specifier, since they aren't allowed to start with
272 // 'template'.
273 if (!HasScopeSpecifier && !ObjectType)
274 break;
275
276 TentativeParsingAction TPA(*this);
277 SourceLocation TemplateKWLoc = ConsumeToken();
278
279 UnqualifiedId TemplateName;
280 if (Tok.is(tok::identifier)) {
281 // Consume the identifier.
282 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
283 ConsumeToken();
284 } else if (Tok.is(tok::kw_operator)) {
285 // We don't need to actually parse the unqualified-id in this case,
286 // because a simple-template-id cannot start with 'operator', but
287 // go ahead and parse it anyway for consistency with the case where
288 // we already annotated the template-id.
289 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
290 TemplateName)) {
291 TPA.Commit();
292 break;
293 }
294
295 if (TemplateName.getKind() != UnqualifiedIdKind::IK_OperatorFunctionId &&
296 TemplateName.getKind() != UnqualifiedIdKind::IK_LiteralOperatorId) {
297 Diag(TemplateName.getSourceRange().getBegin(),
298 diag::err_id_after_template_in_nested_name_spec)
299 << TemplateName.getSourceRange();
300 TPA.Commit();
301 break;
302 }
303 } else {
304 TPA.Revert();
305 break;
306 }
307
308 // If the next token is not '<', we have a qualified-id that refers
309 // to a template name, such as T::template apply, but is not a
310 // template-id.
311 if (Tok.isNot(tok::less)) {
312 TPA.Revert();
313 break;
314 }
315
316 // Commit to parsing the template-id.
317 TPA.Commit();
318 TemplateTy Template;
319 if (TemplateNameKind TNK = Actions.ActOnDependentTemplateName(
320 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
321 EnteringContext, Template, /*AllowInjectedClassName*/ true)) {
322 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
323 TemplateName, false))
324 return true;
325 } else
326 return true;
327
328 continue;
329 }
330
331 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
332 // We have
333 //
334 // template-id '::'
335 //
336 // So we need to check whether the template-id is a simple-template-id of
337 // the right kind (it should name a type or be dependent), and then
338 // convert it into a type within the nested-name-specifier.
339 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
340 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
341 *MayBePseudoDestructor = true;
342 return false;
343 }
344
345 if (LastII)
346 *LastII = TemplateId->Name;
347
348 // Consume the template-id token.
349 ConsumeAnnotationToken();
350
351 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!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 351, __extension__ __PRETTY_FUNCTION__))
;
352 SourceLocation CCLoc = ConsumeToken();
353
354 HasScopeSpecifier = true;
355
356 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
357 TemplateId->NumArgs);
358
359 if (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 !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, IdInfo)) {
423 *MayBePseudoDestructor = true;
424 return false;
425 }
426
427 if (ColonIsSacred) {
428 const Token &Next2 = GetLookAheadToken(2);
429 if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
430 Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
431 Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
432 << Next2.getName()
433 << FixItHint::CreateReplacement(Next.getLocation(), ":");
434 Token ColonColon;
435 PP.Lex(ColonColon);
436 ColonColon.setKind(tok::colon);
437 PP.EnterToken(ColonColon);
438 break;
439 }
440 }
441
442 if (LastII)
443 *LastII = &II;
444
445 // We have an identifier followed by a '::'. Lookup this name
446 // as the name in a nested-name-specifier.
447 Token Identifier = Tok;
448 SourceLocation IdLoc = ConsumeToken();
449 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!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 450, __extension__ __PRETTY_FUNCTION__))
450 "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!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 450, __extension__ __PRETTY_FUNCTION__))
;
451 Token ColonColon = Tok;
452 SourceLocation CCLoc = ConsumeToken();
453
454 bool IsCorrectedToColon = false;
455 bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
456 if (Actions.ActOnCXXNestedNameSpecifier(
457 getCurScope(), IdInfo, EnteringContext, SS, false,
458 CorrectionFlagPtr, OnlyNamespace)) {
459 // Identifier is not recognized as a nested name, but we can have
460 // mistyped '::' instead of ':'.
461 if (CorrectionFlagPtr && IsCorrectedToColon) {
462 ColonColon.setKind(tok::colon);
463 PP.EnterToken(Tok);
464 PP.EnterToken(ColonColon);
465 Tok = Identifier;
466 break;
467 }
468 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
469 }
470 HasScopeSpecifier = true;
471 continue;
472 }
473
474 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
475
476 // nested-name-specifier:
477 // type-name '<'
478 if (Next.is(tok::less)) {
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 // We have found a template name, so annotate this token
491 // with a template-id annotation. We do not permit the
492 // template-id to be translated into a type annotation,
493 // because some clients (e.g., the parsing of class template
494 // specializations) still want to see the original template-id
495 // token.
496 ConsumeToken();
497 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
498 TemplateName, false))
499 return true;
500 continue;
501 }
502
503 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
504 (IsTypename || IsTemplateArgumentList(1))) {
505 // We have something like t::getAs<T>, where getAs is a
506 // member of an unknown specialization. However, this will only
507 // parse correctly as a template, so suggest the keyword 'template'
508 // before 'getAs' and treat this as a dependent template name.
509 unsigned DiagID = diag::err_missing_dependent_template_keyword;
510 if (getLangOpts().MicrosoftExt)
511 DiagID = diag::warn_missing_dependent_template_keyword;
512
513 Diag(Tok.getLocation(), DiagID)
514 << II.getName()
515 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
516
517 if (TemplateNameKind TNK = Actions.ActOnDependentTemplateName(
518 getCurScope(), SS, SourceLocation(), TemplateName, ObjectType,
519 EnteringContext, Template, /*AllowInjectedClassName*/ true)) {
520 // Consume the identifier.
521 ConsumeToken();
522 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
523 TemplateName, false))
524 return true;
525 }
526 else
527 return true;
528
529 continue;
530 }
531 }
532
533 // We don't have any tokens that form the beginning of a
534 // nested-name-specifier, so we're done.
535 break;
536 }
537
538 // Even if we didn't see any pieces of a nested-name-specifier, we
539 // still check whether there is a tilde in this position, which
540 // indicates a potential pseudo-destructor.
541 if (CheckForDestructor && Tok.is(tok::tilde))
542 *MayBePseudoDestructor = true;
543
544 return false;
545}
546
547ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
548 Token &Replacement) {
549 SourceLocation TemplateKWLoc;
550 UnqualifiedId Name;
551 if (ParseUnqualifiedId(SS,
552 /*EnteringContext=*/false,
553 /*AllowDestructorName=*/false,
554 /*AllowConstructorName=*/false,
555 /*AllowDeductionGuide=*/false,
556 /*ObjectType=*/nullptr, TemplateKWLoc, Name))
557 return ExprError();
558
559 // This is only the direct operand of an & operator if it is not
560 // followed by a postfix-expression suffix.
561 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
562 isAddressOfOperand = false;
563
564 return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
565 Tok.is(tok::l_paren), isAddressOfOperand,
566 nullptr, /*IsInlineAsmIdentifier=*/false,
567 &Replacement);
568}
569
570/// ParseCXXIdExpression - Handle id-expression.
571///
572/// id-expression:
573/// unqualified-id
574/// qualified-id
575///
576/// qualified-id:
577/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
578/// '::' identifier
579/// '::' operator-function-id
580/// '::' template-id
581///
582/// NOTE: The standard specifies that, for qualified-id, the parser does not
583/// expect:
584///
585/// '::' conversion-function-id
586/// '::' '~' class-name
587///
588/// This may cause a slight inconsistency on diagnostics:
589///
590/// class C {};
591/// namespace A {}
592/// void f() {
593/// :: A :: ~ C(); // Some Sema error about using destructor with a
594/// // namespace.
595/// :: ~ C(); // Some Parser error like 'unexpected ~'.
596/// }
597///
598/// We simplify the parser a bit and make it work like:
599///
600/// qualified-id:
601/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
602/// '::' unqualified-id
603///
604/// That way Sema can handle and report similar errors for namespaces and the
605/// global scope.
606///
607/// The isAddressOfOperand parameter indicates that this id-expression is a
608/// direct operand of the address-of operator. This is, besides member contexts,
609/// the only place where a qualified-id naming a non-static class member may
610/// appear.
611///
612ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
613 // qualified-id:
614 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
615 // '::' unqualified-id
616 //
617 CXXScopeSpec SS;
618 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
619
620 Token Replacement;
621 ExprResult Result =
622 tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
623 if (Result.isUnset()) {
624 // If the ExprResult is valid but null, then typo correction suggested a
625 // keyword replacement that needs to be reparsed.
626 UnconsumeToken(Replacement);
627 Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
628 }
629 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 630, __extension__ __PRETTY_FUNCTION__))
630 "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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 630, __extension__ __PRETTY_FUNCTION__))
;
631 return Result;
632}
633
634/// ParseLambdaExpression - Parse a C++11 lambda expression.
635///
636/// lambda-expression:
637/// lambda-introducer lambda-declarator[opt] compound-statement
638///
639/// lambda-introducer:
640/// '[' lambda-capture[opt] ']'
641///
642/// lambda-capture:
643/// capture-default
644/// capture-list
645/// capture-default ',' capture-list
646///
647/// capture-default:
648/// '&'
649/// '='
650///
651/// capture-list:
652/// capture
653/// capture-list ',' capture
654///
655/// capture:
656/// simple-capture
657/// init-capture [C++1y]
658///
659/// simple-capture:
660/// identifier
661/// '&' identifier
662/// 'this'
663///
664/// init-capture: [C++1y]
665/// identifier initializer
666/// '&' identifier initializer
667///
668/// lambda-declarator:
669/// '(' parameter-declaration-clause ')' attribute-specifier[opt]
670/// 'mutable'[opt] exception-specification[opt]
671/// trailing-return-type[opt]
672///
673ExprResult Parser::ParseLambdaExpression() {
674 // Parse lambda-introducer.
675 LambdaIntroducer Intro;
676 Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
677 if (DiagID) {
678 Diag(Tok, DiagID.getValue());
679 SkipUntil(tok::r_square, StopAtSemi);
680 SkipUntil(tok::l_brace, StopAtSemi);
681 SkipUntil(tok::r_brace, StopAtSemi);
682 return ExprError();
683 }
684
685 return ParseLambdaExpressionAfterIntroducer(Intro);
686}
687
688/// TryParseLambdaExpression - Use lookahead and potentially tentative
689/// parsing to determine if we are looking at a C++0x lambda expression, and parse
690/// it if we are.
691///
692/// If we are not looking at a lambda expression, returns ExprError().
693ExprResult Parser::TryParseLambdaExpression() {
694 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.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 696, __extension__ __PRETTY_FUNCTION__))
695 && 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.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 696, __extension__ __PRETTY_FUNCTION__))
696 && "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.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 696, __extension__ __PRETTY_FUNCTION__))
;
697
698 const Token Next = NextToken();
699 if (Next.is(tok::eof)) // Nothing else to lookup here...
700 return ExprEmpty();
701
702 const Token After = GetLookAheadToken(2);
703 // If lookahead indicates this is a lambda...
704 if (Next.is(tok::r_square) || // []
705 Next.is(tok::equal) || // [=
706 (Next.is(tok::amp) && // [&] or [&,
707 (After.is(tok::r_square) ||
708 After.is(tok::comma))) ||
709 (Next.is(tok::identifier) && // [identifier]
710 After.is(tok::r_square))) {
711 return ParseLambdaExpression();
712 }
713
714 // If lookahead indicates an ObjC message send...
715 // [identifier identifier
716 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
717 return ExprEmpty();
718 }
719
720 // Here, we're stuck: lambda introducers and Objective-C message sends are
721 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
722 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
723 // writing two routines to parse a lambda introducer, just try to parse
724 // a lambda introducer first, and fall back if that fails.
725 // (TryParseLambdaIntroducer never produces any diagnostic output.)
726 LambdaIntroducer Intro;
727 if (TryParseLambdaIntroducer(Intro))
728 return ExprEmpty();
729
730 return ParseLambdaExpressionAfterIntroducer(Intro);
731}
732
733/// \brief Parse a lambda introducer.
734/// \param Intro A LambdaIntroducer filled in with information about the
735/// contents of the lambda-introducer.
736/// \param SkippedInits If non-null, we are disambiguating between an Obj-C
737/// message send and a lambda expression. In this mode, we will
738/// sometimes skip the initializers for init-captures and not fully
739/// populate \p Intro. This flag will be set to \c true if we do so.
740/// \return A DiagnosticID if it hit something unexpected. The location for
741/// the diagnostic is that of the current token.
742Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
743 bool *SkippedInits) {
744 typedef Optional<unsigned> DiagResult;
745
746 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 '['.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 746, __extension__ __PRETTY_FUNCTION__))
;
747 BalancedDelimiterTracker T(*this, tok::l_square);
748 T.consumeOpen();
749
750 Intro.Range.setBegin(T.getOpenLocation());
751
752 bool first = true;
753
754 // Parse capture-default.
755 if (Tok.is(tok::amp) &&
756 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
757 Intro.Default = LCD_ByRef;
758 Intro.DefaultLoc = ConsumeToken();
759 first = false;
760 } else if (Tok.is(tok::equal)) {
761 Intro.Default = LCD_ByCopy;
762 Intro.DefaultLoc = ConsumeToken();
763 first = false;
764 }
765
766 while (Tok.isNot(tok::r_square)) {
767 if (!first) {
768 if (Tok.isNot(tok::comma)) {
769 // Provide a completion for a lambda introducer here. Except
770 // in Objective-C, where this is Almost Surely meant to be a message
771 // send. In that case, fail here and let the ObjC message
772 // expression parser perform the completion.
773 if (Tok.is(tok::code_completion) &&
774 !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
775 !Intro.Captures.empty())) {
776 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
777 /*AfterAmpersand=*/false);
778 cutOffParsing();
779 break;
780 }
781
782 return DiagResult(diag::err_expected_comma_or_rsquare);
783 }
784 ConsumeToken();
785 }
786
787 if (Tok.is(tok::code_completion)) {
788 // If we're in Objective-C++ and we have a bare '[', then this is more
789 // likely to be a message receiver.
790 if (getLangOpts().ObjC1 && first)
791 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
792 else
793 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
794 /*AfterAmpersand=*/false);
795 cutOffParsing();
796 break;
797 }
798
799 first = false;
800
801 // Parse capture.
802 LambdaCaptureKind Kind = LCK_ByCopy;
803 LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit;
804 SourceLocation Loc;
805 IdentifierInfo *Id = nullptr;
806 SourceLocation EllipsisLoc;
807 ExprResult Init;
808
809 if (Tok.is(tok::star)) {
810 Loc = ConsumeToken();
811 if (Tok.is(tok::kw_this)) {
812 ConsumeToken();
813 Kind = LCK_StarThis;
814 } else {
815 return DiagResult(diag::err_expected_star_this_capture);
816 }
817 } else if (Tok.is(tok::kw_this)) {
818 Kind = LCK_This;
819 Loc = ConsumeToken();
820 } else {
821 if (Tok.is(tok::amp)) {
822 Kind = LCK_ByRef;
823 ConsumeToken();
824
825 if (Tok.is(tok::code_completion)) {
826 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
827 /*AfterAmpersand=*/true);
828 cutOffParsing();
829 break;
830 }
831 }
832
833 if (Tok.is(tok::identifier)) {
834 Id = Tok.getIdentifierInfo();
835 Loc = ConsumeToken();
836 } else if (Tok.is(tok::kw_this)) {
837 // FIXME: If we want to suggest a fixit here, will need to return more
838 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
839 // Clear()ed to prevent emission in case of tentative parsing?
840 return DiagResult(diag::err_this_captured_by_reference);
841 } else {
842 return DiagResult(diag::err_expected_capture);
843 }
844
845 if (Tok.is(tok::l_paren)) {
846 BalancedDelimiterTracker Parens(*this, tok::l_paren);
847 Parens.consumeOpen();
848
849 InitKind = LambdaCaptureInitKind::DirectInit;
850
851 ExprVector Exprs;
852 CommaLocsTy Commas;
853 if (SkippedInits) {
854 Parens.skipToEnd();
855 *SkippedInits = true;
856 } else if (ParseExpressionList(Exprs, Commas)) {
857 Parens.skipToEnd();
858 Init = ExprError();
859 } else {
860 Parens.consumeClose();
861 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
862 Parens.getCloseLocation(),
863 Exprs);
864 }
865 } else if (Tok.isOneOf(tok::l_brace, tok::equal)) {
866 // Each lambda init-capture forms its own full expression, which clears
867 // Actions.MaybeODRUseExprs. So create an expression evaluation context
868 // to save the necessary state, and restore it later.
869 EnterExpressionEvaluationContext EC(
870 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
871
872 if (TryConsumeToken(tok::equal))
873 InitKind = LambdaCaptureInitKind::CopyInit;
874 else
875 InitKind = LambdaCaptureInitKind::ListInit;
876
877 if (!SkippedInits) {
878 Init = ParseInitializer();
879 } else if (Tok.is(tok::l_brace)) {
880 BalancedDelimiterTracker Braces(*this, tok::l_brace);
881 Braces.consumeOpen();
882 Braces.skipToEnd();
883 *SkippedInits = true;
884 } else {
885 // We're disambiguating this:
886 //
887 // [..., x = expr
888 //
889 // We need to find the end of the following expression in order to
890 // determine whether this is an Obj-C message send's receiver, a
891 // C99 designator, or a lambda init-capture.
892 //
893 // Parse the expression to find where it ends, and annotate it back
894 // onto the tokens. We would have parsed this expression the same way
895 // in either case: both the RHS of an init-capture and the RHS of an
896 // assignment expression are parsed as an initializer-clause, and in
897 // neither case can anything be added to the scope between the '[' and
898 // here.
899 //
900 // FIXME: This is horrible. Adding a mechanism to skip an expression
901 // would be much cleaner.
902 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
903 // that instead. (And if we see a ':' with no matching '?', we can
904 // classify this as an Obj-C message send.)
905 SourceLocation StartLoc = Tok.getLocation();
906 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
907 Init = ParseInitializer();
908 if (!Init.isInvalid())
909 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
910
911 if (Tok.getLocation() != StartLoc) {
912 // Back out the lexing of the token after the initializer.
913 PP.RevertCachedTokens(1);
914
915 // Replace the consumed tokens with an appropriate annotation.
916 Tok.setLocation(StartLoc);
917 Tok.setKind(tok::annot_primary_expr);
918 setExprAnnotation(Tok, Init);
919 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
920 PP.AnnotateCachedTokens(Tok);
921
922 // Consume the annotated initializer.
923 ConsumeAnnotationToken();
924 }
925 }
926 } else
927 TryConsumeToken(tok::ellipsis, EllipsisLoc);
928 }
929 // If this is an init capture, process the initialization expression
930 // right away. For lambda init-captures such as the following:
931 // const int x = 10;
932 // auto L = [i = x+1](int a) {
933 // return [j = x+2,
934 // &k = x](char b) { };
935 // };
936 // keep in mind that each lambda init-capture has to have:
937 // - its initialization expression executed in the context
938 // of the enclosing/parent decl-context.
939 // - but the variable itself has to be 'injected' into the
940 // decl-context of its lambda's call-operator (which has
941 // not yet been created).
942 // Each init-expression is a full-expression that has to get
943 // Sema-analyzed (for capturing etc.) before its lambda's
944 // call-operator's decl-context, scope & scopeinfo are pushed on their
945 // respective stacks. Thus if any variable is odr-used in the init-capture
946 // it will correctly get captured in the enclosing lambda, if one exists.
947 // The init-variables above are created later once the lambdascope and
948 // call-operators decl-context is pushed onto its respective stack.
949
950 // Since the lambda init-capture's initializer expression occurs in the
951 // context of the enclosing function or lambda, therefore we can not wait
952 // till a lambda scope has been pushed on before deciding whether the
953 // variable needs to be captured. We also need to process all
954 // lvalue-to-rvalue conversions and discarded-value conversions,
955 // so that we can avoid capturing certain constant variables.
956 // For e.g.,
957 // void test() {
958 // const int x = 10;
959 // auto L = [&z = x](char a) { <-- don't capture by the current lambda
960 // return [y = x](int i) { <-- don't capture by enclosing lambda
961 // return y;
962 // }
963 // };
964 // }
965 // If x was not const, the second use would require 'L' to capture, and
966 // that would be an error.
967
968 ParsedType InitCaptureType;
969 if (!Init.isInvalid())
970 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
971 if (Init.isUsable()) {
972 // Get the pointer and store it in an lvalue, so we can use it as an
973 // out argument.
974 Expr *InitExpr = Init.get();
975 // This performs any lvalue-to-rvalue conversions if necessary, which
976 // can affect what gets captured in the containing decl-context.
977 InitCaptureType = Actions.actOnLambdaInitCaptureInitialization(
978 Loc, Kind == LCK_ByRef, Id, InitKind, InitExpr);
979 Init = InitExpr;
980 }
981 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
982 InitCaptureType);
983 }
984
985 T.consumeClose();
986 Intro.Range.setEnd(T.getCloseLocation());
987 return DiagResult();
988}
989
990/// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
991///
992/// Returns true if it hit something unexpected.
993bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
994 {
995 bool SkippedInits = false;
996 TentativeParsingAction PA1(*this);
997
998 if (ParseLambdaIntroducer(Intro, &SkippedInits)) {
999 PA1.Revert();
1000 return true;
1001 }
1002
1003 if (!SkippedInits) {
1004 PA1.Commit();
1005 return false;
1006 }
1007
1008 PA1.Revert();
1009 }
1010
1011 // Try to parse it again, but this time parse the init-captures too.
1012 Intro = LambdaIntroducer();
1013 TentativeParsingAction PA2(*this);
1014
1015 if (!ParseLambdaIntroducer(Intro)) {
1016 PA2.Commit();
1017 return false;
1018 }
1019
1020 PA2.Revert();
1021 return true;
1022}
1023
1024static void
1025tryConsumeMutableOrConstexprToken(Parser &P, SourceLocation &MutableLoc,
1026 SourceLocation &ConstexprLoc,
1027 SourceLocation &DeclEndLoc) {
1028 assert(MutableLoc.isInvalid())(static_cast <bool> (MutableLoc.isInvalid()) ? void (0)
: __assert_fail ("MutableLoc.isInvalid()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 1028, __extension__ __PRETTY_FUNCTION__))
;
1029 assert(ConstexprLoc.isInvalid())(static_cast <bool> (ConstexprLoc.isInvalid()) ? void (
0) : __assert_fail ("ConstexprLoc.isInvalid()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 1029, __extension__ __PRETTY_FUNCTION__))
;
1030 // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc
1031 // to the final of those locations. Emit an error if we have multiple
1032 // copies of those keywords and recover.
1033
1034 while (true) {
1035 switch (P.getCurToken().getKind()) {
1036 case tok::kw_mutable: {
1037 if (MutableLoc.isValid()) {
1038 P.Diag(P.getCurToken().getLocation(),
1039 diag::err_lambda_decl_specifier_repeated)
1040 << 0 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1041 }
1042 MutableLoc = P.ConsumeToken();
1043 DeclEndLoc = MutableLoc;
1044 break /*switch*/;
1045 }
1046 case tok::kw_constexpr:
1047 if (ConstexprLoc.isValid()) {
1048 P.Diag(P.getCurToken().getLocation(),
1049 diag::err_lambda_decl_specifier_repeated)
1050 << 1 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1051 }
1052 ConstexprLoc = P.ConsumeToken();
1053 DeclEndLoc = ConstexprLoc;
1054 break /*switch*/;
1055 default:
1056 return;
1057 }
1058 }
1059}
1060
1061static void
1062addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc,
1063 DeclSpec &DS) {
1064 if (ConstexprLoc.isValid()) {
1065 P.Diag(ConstexprLoc, !P.getLangOpts().CPlusPlus17
1066 ? diag::ext_constexpr_on_lambda_cxx17
1067 : diag::warn_cxx14_compat_constexpr_on_lambda);
1068 const char *PrevSpec = nullptr;
1069 unsigned DiagID = 0;
1070 DS.SetConstexprSpec(ConstexprLoc, PrevSpec, DiagID);
1071 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!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 1072, __extension__ __PRETTY_FUNCTION__))
1072 "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!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 1072, __extension__ __PRETTY_FUNCTION__))
;
1073 }
1074}
1075
1076/// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1077/// expression.
1078ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1079 LambdaIntroducer &Intro) {
1080 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1081 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1082
1083 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1084 "lambda expression parsing");
1085
1086
1087
1088 // FIXME: Call into Actions to add any init-capture declarations to the
1089 // scope while parsing the lambda-declarator and compound-statement.
1090
1091 // Parse lambda-declarator[opt].
1092 DeclSpec DS(AttrFactory);
1093 Declarator D(DS, DeclaratorContext::LambdaExprContext);
1094 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1095 Actions.PushLambdaScope();
1096
1097 ParsedAttributes Attr(AttrFactory);
1098 SourceLocation DeclLoc = Tok.getLocation();
1099 if (getLangOpts().CUDA) {
1100 // In CUDA code, GNU attributes are allowed to appear immediately after the
1101 // "[...]", even if there is no "(...)" before the lambda body.
1102 MaybeParseGNUAttributes(D);
1103 }
1104
1105 // Helper to emit a warning if we see a CUDA host/device/global attribute
1106 // after '(...)'. nvcc doesn't accept this.
1107 auto WarnIfHasCUDATargetAttr = [&] {
1108 if (getLangOpts().CUDA)
1109 for (auto *A = Attr.getList(); A != nullptr; A = A->getNext())
1110 if (A->getKind() == AttributeList::AT_CUDADevice ||
1111 A->getKind() == AttributeList::AT_CUDAHost ||
1112 A->getKind() == AttributeList::AT_CUDAGlobal)
1113 Diag(A->getLoc(), diag::warn_cuda_attr_lambda_position)
1114 << A->getName()->getName();
1115 };
1116
1117 TypeResult TrailingReturnType;
1118 if (Tok.is(tok::l_paren)) {
1119 ParseScope PrototypeScope(this,
1120 Scope::FunctionPrototypeScope |
1121 Scope::FunctionDeclarationScope |
1122 Scope::DeclScope);
1123
1124 BalancedDelimiterTracker T(*this, tok::l_paren);
1125 T.consumeOpen();
1126 SourceLocation LParenLoc = T.getOpenLocation();
1127
1128 // Parse parameter-declaration-clause.
1129 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1130 SourceLocation EllipsisLoc;
1131
1132 if (Tok.isNot(tok::r_paren)) {
1133 Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
1134 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
1135 // For a generic lambda, each 'auto' within the parameter declaration
1136 // clause creates a template type parameter, so increment the depth.
1137 if (Actions.getCurGenericLambda())
1138 ++CurTemplateDepthTracker;
1139 }
1140 T.consumeClose();
1141 SourceLocation RParenLoc = T.getCloseLocation();
1142 SourceLocation DeclEndLoc = RParenLoc;
1143
1144 // GNU-style attributes must be parsed before the mutable specifier to be
1145 // compatible with GCC.
1146 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1147
1148 // MSVC-style attributes must be parsed before the mutable specifier to be
1149 // compatible with MSVC.
1150 MaybeParseMicrosoftDeclSpecs(Attr, &DeclEndLoc);
1151
1152 // Parse mutable-opt and/or constexpr-opt, and update the DeclEndLoc.
1153 SourceLocation MutableLoc;
1154 SourceLocation ConstexprLoc;
1155 tryConsumeMutableOrConstexprToken(*this, MutableLoc, ConstexprLoc,
1156 DeclEndLoc);
1157
1158 addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS);
1159
1160 // Parse exception-specification[opt].
1161 ExceptionSpecificationType ESpecType = EST_None;
1162 SourceRange ESpecRange;
1163 SmallVector<ParsedType, 2> DynamicExceptions;
1164 SmallVector<SourceRange, 2> DynamicExceptionRanges;
1165 ExprResult NoexceptExpr;
1166 CachedTokens *ExceptionSpecTokens;
1167 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1168 ESpecRange,
1169 DynamicExceptions,
1170 DynamicExceptionRanges,
1171 NoexceptExpr,
1172 ExceptionSpecTokens);
1173
1174 if (ESpecType != EST_None)
1175 DeclEndLoc = ESpecRange.getEnd();
1176
1177 // Parse attribute-specifier[opt].
1178 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1179
1180 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1181
1182 // Parse trailing-return-type[opt].
1183 if (Tok.is(tok::arrow)) {
1184 FunLocalRangeEnd = Tok.getLocation();
1185 SourceRange Range;
1186 TrailingReturnType =
1187 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
1188 if (Range.getEnd().isValid())
1189 DeclEndLoc = Range.getEnd();
1190 }
1191
1192 PrototypeScope.Exit();
1193
1194 WarnIfHasCUDATargetAttr();
1195
1196 SourceLocation NoLoc;
1197 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
1198 /*isAmbiguous=*/false,
1199 LParenLoc,
1200 ParamInfo.data(), ParamInfo.size(),
1201 EllipsisLoc, RParenLoc,
1202 DS.getTypeQualifiers(),
1203 /*RefQualifierIsLValueRef=*/true,
1204 /*RefQualifierLoc=*/NoLoc,
1205 /*ConstQualifierLoc=*/NoLoc,
1206 /*VolatileQualifierLoc=*/NoLoc,
1207 /*RestrictQualifierLoc=*/NoLoc,
1208 MutableLoc,
1209 ESpecType, ESpecRange,
1210 DynamicExceptions.data(),
1211 DynamicExceptionRanges.data(),
1212 DynamicExceptions.size(),
1213 NoexceptExpr.isUsable() ?
1214 NoexceptExpr.get() : nullptr,
1215 /*ExceptionSpecTokens*/nullptr,
1216 /*DeclsInPrototype=*/None,
1217 LParenLoc, FunLocalRangeEnd, D,
1218 TrailingReturnType),
1219 Attr, DeclEndLoc);
1220 } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute,
1221 tok::kw_constexpr) ||
1222 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1223 // It's common to forget that one needs '()' before 'mutable', an attribute
1224 // specifier, or the result type. Deal with this.
1225 unsigned TokKind = 0;
1226 switch (Tok.getKind()) {
1227 case tok::kw_mutable: TokKind = 0; break;
1228 case tok::arrow: TokKind = 1; break;
1229 case tok::kw___attribute:
1230 case tok::l_square: TokKind = 2; break;
1231 case tok::kw_constexpr: TokKind = 3; break;
1232 default: llvm_unreachable("Unknown token kind")::llvm::llvm_unreachable_internal("Unknown token kind", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 1232)
;
1233 }
1234
1235 Diag(Tok, diag::err_lambda_missing_parens)
1236 << TokKind
1237 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1238 SourceLocation DeclEndLoc = DeclLoc;
1239
1240 // GNU-style attributes must be parsed before the mutable specifier to be
1241 // compatible with GCC.
1242 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1243
1244 // Parse 'mutable', if it's there.
1245 SourceLocation MutableLoc;
1246 if (Tok.is(tok::kw_mutable)) {
1247 MutableLoc = ConsumeToken();
1248 DeclEndLoc = MutableLoc;
1249 }
1250
1251 // Parse attribute-specifier[opt].
1252 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1253
1254 // Parse the return type, if there is one.
1255 if (Tok.is(tok::arrow)) {
1256 SourceRange Range;
1257 TrailingReturnType =
1258 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
1259 if (Range.getEnd().isValid())
1260 DeclEndLoc = Range.getEnd();
1261 }
1262
1263 WarnIfHasCUDATargetAttr();
1264
1265 SourceLocation NoLoc;
1266 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
1267 /*isAmbiguous=*/false,
1268 /*LParenLoc=*/NoLoc,
1269 /*Params=*/nullptr,
1270 /*NumParams=*/0,
1271 /*EllipsisLoc=*/NoLoc,
1272 /*RParenLoc=*/NoLoc,
1273 /*TypeQuals=*/0,
1274 /*RefQualifierIsLValueRef=*/true,
1275 /*RefQualifierLoc=*/NoLoc,
1276 /*ConstQualifierLoc=*/NoLoc,
1277 /*VolatileQualifierLoc=*/NoLoc,
1278 /*RestrictQualifierLoc=*/NoLoc,
1279 MutableLoc,
1280 EST_None,
1281 /*ESpecRange=*/SourceRange(),
1282 /*Exceptions=*/nullptr,
1283 /*ExceptionRanges=*/nullptr,
1284 /*NumExceptions=*/0,
1285 /*NoexceptExpr=*/nullptr,
1286 /*ExceptionSpecTokens=*/nullptr,
1287 /*DeclsInPrototype=*/None,
1288 DeclLoc, DeclEndLoc, D,
1289 TrailingReturnType),
1290 Attr, DeclEndLoc);
1291 }
1292
1293 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1294 // it.
1295 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope |
1296 Scope::CompoundStmtScope;
1297 ParseScope BodyScope(this, ScopeFlags);
1298
1299 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1300
1301 // Parse compound-statement.
1302 if (!Tok.is(tok::l_brace)) {
1303 Diag(Tok, diag::err_expected_lambda_body);
1304 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1305 return ExprError();
1306 }
1307
1308 StmtResult Stmt(ParseCompoundStatementBody());
1309 BodyScope.Exit();
1310
1311 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
1312 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
1313
1314 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1315 return ExprError();
1316}
1317
1318/// ParseCXXCasts - This handles the various ways to cast expressions to another
1319/// type.
1320///
1321/// postfix-expression: [C++ 5.2p1]
1322/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1323/// 'static_cast' '<' type-name '>' '(' expression ')'
1324/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1325/// 'const_cast' '<' type-name '>' '(' expression ')'
1326///
1327ExprResult Parser::ParseCXXCasts() {
1328 tok::TokenKind Kind = Tok.getKind();
1329 const char *CastName = nullptr; // For error messages
1330
1331 switch (Kind) {
1332 default: llvm_unreachable("Unknown C++ cast!")::llvm::llvm_unreachable_internal("Unknown C++ cast!", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 1332)
;
1333 case tok::kw_const_cast: CastName = "const_cast"; break;
1334 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1335 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1336 case tok::kw_static_cast: CastName = "static_cast"; break;
1337 }
1338
1339 SourceLocation OpLoc = ConsumeToken();
1340 SourceLocation LAngleBracketLoc = Tok.getLocation();
1341
1342 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1343 // diagnose error, suggest fix, and recover parsing.
1344 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1345 Token Next = NextToken();
1346 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1347 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1348 }
1349
1350 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
1351 return ExprError();
1352
1353 // Parse the common declaration-specifiers piece.
1354 DeclSpec DS(AttrFactory);
1355 ParseSpecifierQualifierList(DS);
1356
1357 // Parse the abstract-declarator, if present.
1358 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1359 ParseDeclarator(DeclaratorInfo);
1360
1361 SourceLocation RAngleBracketLoc = Tok.getLocation();
1362
1363 if (ExpectAndConsume(tok::greater))
1364 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
1365
1366 BalancedDelimiterTracker T(*this, tok::l_paren);
1367
1368 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
1369 return ExprError();
1370
1371 ExprResult Result = ParseExpression();
1372
1373 // Match the ')'.
1374 T.consumeClose();
1375
1376 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
1377 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
1378 LAngleBracketLoc, DeclaratorInfo,
1379 RAngleBracketLoc,
1380 T.getOpenLocation(), Result.get(),
1381 T.getCloseLocation());
1382
1383 return Result;
1384}
1385
1386/// ParseCXXTypeid - This handles the C++ typeid expression.
1387///
1388/// postfix-expression: [C++ 5.2p1]
1389/// 'typeid' '(' expression ')'
1390/// 'typeid' '(' type-id ')'
1391///
1392ExprResult Parser::ParseCXXTypeid() {
1393 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'!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 1393, __extension__ __PRETTY_FUNCTION__))
;
1394
1395 SourceLocation OpLoc = ConsumeToken();
1396 SourceLocation LParenLoc, RParenLoc;
1397 BalancedDelimiterTracker T(*this, tok::l_paren);
1398
1399 // typeid expressions are always parenthesized.
1400 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
1401 return ExprError();
1402 LParenLoc = T.getOpenLocation();
1403
1404 ExprResult Result;
1405
1406 // C++0x [expr.typeid]p3:
1407 // When typeid is applied to an expression other than an lvalue of a
1408 // polymorphic class type [...] The expression is an unevaluated
1409 // operand (Clause 5).
1410 //
1411 // Note that we can't tell whether the expression is an lvalue of a
1412 // polymorphic class type until after we've parsed the expression; we
1413 // speculatively assume the subexpression is unevaluated, and fix it up
1414 // later.
1415 //
1416 // We enter the unevaluated context before trying to determine whether we
1417 // have a type-id, because the tentative parse logic will try to resolve
1418 // names, and must treat them as unevaluated.
1419 EnterExpressionEvaluationContext Unevaluated(
1420 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
1421 Sema::ReuseLambdaContextDecl);
1422
1423 if (isTypeIdInParens()) {
1424 TypeResult Ty = ParseTypeName();
1425
1426 // Match the ')'.
1427 T.consumeClose();
1428 RParenLoc = T.getCloseLocation();
1429 if (Ty.isInvalid() || RParenLoc.isInvalid())
1430 return ExprError();
1431
1432 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
1433 Ty.get().getAsOpaquePtr(), RParenLoc);
1434 } else {
1435 Result = ParseExpression();
1436
1437 // Match the ')'.
1438 if (Result.isInvalid())
1439 SkipUntil(tok::r_paren, StopAtSemi);
1440 else {
1441 T.consumeClose();
1442 RParenLoc = T.getCloseLocation();
1443 if (RParenLoc.isInvalid())
1444 return ExprError();
1445
1446 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1447 Result.get(), RParenLoc);
1448 }
1449 }
1450
1451 return Result;
1452}
1453
1454/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1455///
1456/// '__uuidof' '(' expression ')'
1457/// '__uuidof' '(' type-id ')'
1458///
1459ExprResult Parser::ParseCXXUuidof() {
1460 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'!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 1460, __extension__ __PRETTY_FUNCTION__))
;
1461
1462 SourceLocation OpLoc = ConsumeToken();
1463 BalancedDelimiterTracker T(*this, tok::l_paren);
1464
1465 // __uuidof expressions are always parenthesized.
1466 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1467 return ExprError();
1468
1469 ExprResult Result;
1470
1471 if (isTypeIdInParens()) {
1472 TypeResult Ty = ParseTypeName();
1473
1474 // Match the ')'.
1475 T.consumeClose();
1476
1477 if (Ty.isInvalid())
1478 return ExprError();
1479
1480 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1481 Ty.get().getAsOpaquePtr(),
1482 T.getCloseLocation());
1483 } else {
1484 EnterExpressionEvaluationContext Unevaluated(
1485 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
1486 Result = ParseExpression();
1487
1488 // Match the ')'.
1489 if (Result.isInvalid())
1490 SkipUntil(tok::r_paren, StopAtSemi);
1491 else {
1492 T.consumeClose();
1493
1494 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1495 /*isType=*/false,
1496 Result.get(), T.getCloseLocation());
1497 }
1498 }
1499
1500 return Result;
1501}
1502
1503/// \brief Parse a C++ pseudo-destructor expression after the base,
1504/// . or -> operator, and nested-name-specifier have already been
1505/// parsed.
1506///
1507/// postfix-expression: [C++ 5.2]
1508/// postfix-expression . pseudo-destructor-name
1509/// postfix-expression -> pseudo-destructor-name
1510///
1511/// pseudo-destructor-name:
1512/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1513/// ::[opt] nested-name-specifier template simple-template-id ::
1514/// ~type-name
1515/// ::[opt] nested-name-specifier[opt] ~type-name
1516///
1517ExprResult
1518Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1519 tok::TokenKind OpKind,
1520 CXXScopeSpec &SS,
1521 ParsedType ObjectType) {
1522 // We're parsing either a pseudo-destructor-name or a dependent
1523 // member access that has the same form as a
1524 // pseudo-destructor-name. We parse both in the same way and let
1525 // the action model sort them out.
1526 //
1527 // Note that the ::[opt] nested-name-specifier[opt] has already
1528 // been parsed, and if there was a simple-template-id, it has
1529 // been coalesced into a template-id annotation token.
1530 UnqualifiedId FirstTypeName;
1531 SourceLocation CCLoc;
1532 if (Tok.is(tok::identifier)) {
1533 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1534 ConsumeToken();
1535 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 1535, __extension__ __PRETTY_FUNCTION__))
;
1536 CCLoc = ConsumeToken();
1537 } else if (Tok.is(tok::annot_template_id)) {
1538 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1539 // store it in the pseudo-dtor node (to be used when instantiating it).
1540 FirstTypeName.setTemplateId(
1541 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1542 ConsumeAnnotationToken();
1543 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 1543, __extension__ __PRETTY_FUNCTION__))
;
1544 CCLoc = ConsumeToken();
1545 } else {
1546 FirstTypeName.setIdentifier(nullptr, SourceLocation());
1547 }
1548
1549 // Parse the tilde.
1550 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 1550, __extension__ __PRETTY_FUNCTION__))
;
1551 SourceLocation TildeLoc = ConsumeToken();
1552
1553 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1554 DeclSpec DS(AttrFactory);
1555 ParseDecltypeSpecifier(DS);
1556 if (DS.getTypeSpecType() == TST_error)
1557 return ExprError();
1558 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1559 TildeLoc, DS);
1560 }
1561
1562 if (!Tok.is(tok::identifier)) {
1563 Diag(Tok, diag::err_destructor_tilde_identifier);
1564 return ExprError();
1565 }
1566
1567 // Parse the second type.
1568 UnqualifiedId SecondTypeName;
1569 IdentifierInfo *Name = Tok.getIdentifierInfo();
1570 SourceLocation NameLoc = ConsumeToken();
1571 SecondTypeName.setIdentifier(Name, NameLoc);
1572
1573 // If there is a '<', the second type name is a template-id. Parse
1574 // it as such.
1575 if (Tok.is(tok::less) &&
1576 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1577 Name, NameLoc,
1578 false, ObjectType, SecondTypeName,
1579 /*AssumeTemplateName=*/true))
1580 return ExprError();
1581
1582 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1583 SS, FirstTypeName, CCLoc, TildeLoc,
1584 SecondTypeName);
1585}
1586
1587/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1588///
1589/// boolean-literal: [C++ 2.13.5]
1590/// 'true'
1591/// 'false'
1592ExprResult Parser::ParseCXXBoolLiteral() {
1593 tok::TokenKind Kind = Tok.getKind();
1594 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1595}
1596
1597/// ParseThrowExpression - This handles the C++ throw expression.
1598///
1599/// throw-expression: [C++ 15]
1600/// 'throw' assignment-expression[opt]
1601ExprResult Parser::ParseThrowExpression() {
1602 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!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 1602, __extension__ __PRETTY_FUNCTION__))
;
1603 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
1604
1605 // If the current token isn't the start of an assignment-expression,
1606 // then the expression is not present. This handles things like:
1607 // "C ? throw : (void)42", which is crazy but legal.
1608 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1609 case tok::semi:
1610 case tok::r_paren:
1611 case tok::r_square:
1612 case tok::r_brace:
1613 case tok::colon:
1614 case tok::comma:
1615 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
1616
1617 default:
1618 ExprResult Expr(ParseAssignmentExpression());
1619 if (Expr.isInvalid()) return Expr;
1620 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
1621 }
1622}
1623
1624/// \brief Parse the C++ Coroutines co_yield expression.
1625///
1626/// co_yield-expression:
1627/// 'co_yield' assignment-expression[opt]
1628ExprResult Parser::ParseCoyieldExpression() {
1629 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!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 1629, __extension__ __PRETTY_FUNCTION__))
;
1630
1631 SourceLocation Loc = ConsumeToken();
1632 ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
1633 : ParseAssignmentExpression();
1634 if (!Expr.isInvalid())
1635 Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
1636 return Expr;
1637}
1638
1639/// ParseCXXThis - This handles the C++ 'this' pointer.
1640///
1641/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1642/// a non-lvalue expression whose value is the address of the object for which
1643/// the function is called.
1644ExprResult Parser::ParseCXXThis() {
1645 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'!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 1645, __extension__ __PRETTY_FUNCTION__))
;
1646 SourceLocation ThisLoc = ConsumeToken();
1647 return Actions.ActOnCXXThis(ThisLoc);
1648}
1649
1650/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1651/// Can be interpreted either as function-style casting ("int(x)")
1652/// or class type construction ("ClassType(x,y,z)")
1653/// or creation of a value-initialized type ("int()").
1654/// See [C++ 5.2.3].
1655///
1656/// postfix-expression: [C++ 5.2p1]
1657/// simple-type-specifier '(' expression-list[opt] ')'
1658/// [C++0x] simple-type-specifier braced-init-list
1659/// typename-specifier '(' expression-list[opt] ')'
1660/// [C++0x] typename-specifier braced-init-list
1661///
1662/// In C++1z onwards, the type specifier can also be a template-name.
1663ExprResult
1664Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1665 Declarator DeclaratorInfo(DS, DeclaratorContext::FunctionalCastContext);
1666 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
1667
1668 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 '{'!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 1670, __extension__ __PRETTY_FUNCTION__))
1669 (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 '{'!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 1670, __extension__ __PRETTY_FUNCTION__))
1670 && "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 '{'!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 1670, __extension__ __PRETTY_FUNCTION__))
;
1671
1672 if (Tok.is(tok::l_brace)) {
1673 ExprResult Init = ParseBraceInitializer();
1674 if (Init.isInvalid())
1675 return Init;
1676 Expr *InitList = Init.get();
1677 return Actions.ActOnCXXTypeConstructExpr(
1678 TypeRep, InitList->getLocStart(), MultiExprArg(&InitList, 1),
1679 InitList->getLocEnd(), /*ListInitialization=*/true);
1680 } else {
1681 BalancedDelimiterTracker T(*this, tok::l_paren);
1682 T.consumeOpen();
1683
1684 ExprVector Exprs;
1685 CommaLocsTy CommaLocs;
1686
1687 if (Tok.isNot(tok::r_paren)) {
1688 if (ParseExpressionList(Exprs, CommaLocs, [&] {
1689 Actions.CodeCompleteConstructor(getCurScope(),
1690 TypeRep.get()->getCanonicalTypeInternal(),
1691 DS.getLocEnd(), Exprs);
1692 })) {
1693 SkipUntil(tok::r_paren, StopAtSemi);
1694 return ExprError();
1695 }
1696 }
1697
1698 // Match the ')'.
1699 T.consumeClose();
1700
1701 // TypeRep could be null, if it references an invalid typedef.
1702 if (!TypeRep)
1703 return ExprError();
1704
1705 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!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 1706, __extension__ __PRETTY_FUNCTION__))
1706 "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!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 1706, __extension__ __PRETTY_FUNCTION__))
;
1707 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1708 Exprs, T.getCloseLocation(),
1709 /*ListInitialization=*/false);
1710 }
1711}
1712
1713/// ParseCXXCondition - if/switch/while condition expression.
1714///
1715/// condition:
1716/// expression
1717/// type-specifier-seq declarator '=' assignment-expression
1718/// [C++11] type-specifier-seq declarator '=' initializer-clause
1719/// [C++11] type-specifier-seq declarator braced-init-list
1720/// [Clang] type-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
1721/// brace-or-equal-initializer
1722/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1723/// '=' assignment-expression
1724///
1725/// In C++1z, a condition may in some contexts be preceded by an
1726/// optional init-statement. This function will parse that too.
1727///
1728/// \param InitStmt If non-null, an init-statement is permitted, and if present
1729/// will be parsed and stored here.
1730///
1731/// \param Loc The location of the start of the statement that requires this
1732/// condition, e.g., the "for" in a for loop.
1733///
1734/// \returns The parsed condition.
1735Sema::ConditionResult Parser::ParseCXXCondition(StmtResult *InitStmt,
1736 SourceLocation Loc,
1737 Sema::ConditionKind CK) {
1738 if (Tok.is(tok::code_completion)) {
1
Taking false branch
5
Taking false branch
1739 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
1740 cutOffParsing();
1741 return Sema::ConditionError();
1742 }
1743
1744 ParsedAttributesWithRange attrs(AttrFactory);
1745 MaybeParseCXX11Attributes(attrs);
1746
1747 const auto WarnOnInit = [this, &CK] {
1748 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
1749 ? diag::warn_cxx14_compat_init_statement
1750 : diag::ext_init_statement)
1751 << (CK == Sema::ConditionKind::Switch);
1752 };
1753
1754 // Determine what kind of thing we have.
1755 switch (isCXXConditionDeclarationOrInitStatement(InitStmt)) {
2
Control jumps to 'case InitStmtDecl:' at line 1783
6
Control jumps to 'case InitStmtDecl:' at line 1783
1756 case ConditionOrInitStatement::Expression: {
1757 ProhibitAttributes(attrs);
1758
1759 // We can have an empty expression here.
1760 // if (; true);
1761 if (InitStmt && Tok.is(tok::semi)) {
1762 WarnOnInit();
1763 SourceLocation SemiLoc = ConsumeToken();
1764 *InitStmt = Actions.ActOnNullStmt(SemiLoc);
1765 return ParseCXXCondition(nullptr, Loc, CK);
1766 }
1767
1768 // Parse the expression.
1769 ExprResult Expr = ParseExpression(); // expression
1770 if (Expr.isInvalid())
1771 return Sema::ConditionError();
1772
1773 if (InitStmt && Tok.is(tok::semi)) {
1774 WarnOnInit();
1775 *InitStmt = Actions.ActOnExprStmt(Expr.get());
1776 ConsumeToken();
1777 return ParseCXXCondition(nullptr, Loc, CK);
1778 }
1779
1780 return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK);
1781 }
1782
1783 case ConditionOrInitStatement::InitStmtDecl: {
1784 WarnOnInit();
1785 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1786 DeclGroupPtrTy DG =
1787 ParseSimpleDeclaration(DeclaratorContext::InitStmtContext, DeclEnd,
1788 attrs, /*RequireSemi=*/true);
1789 *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
7
Called C++ object pointer is null
1790 return ParseCXXCondition(nullptr, Loc, CK);
3
Passing null pointer value via 1st parameter 'InitStmt'
4
Calling 'Parser::ParseCXXCondition'
1791 }
1792
1793 case ConditionOrInitStatement::ConditionDecl:
1794 case ConditionOrInitStatement::Error:
1795 break;
1796 }
1797
1798 // type-specifier-seq
1799 DeclSpec DS(AttrFactory);
1800 DS.takeAttributesFrom(attrs);
1801 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_condition);
1802
1803 // declarator
1804 Declarator DeclaratorInfo(DS, DeclaratorContext::ConditionContext);
1805 ParseDeclarator(DeclaratorInfo);
1806
1807 // simple-asm-expr[opt]
1808 if (Tok.is(tok::kw_asm)) {
1809 SourceLocation Loc;
1810 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1811 if (AsmLabel.isInvalid()) {
1812 SkipUntil(tok::semi, StopAtSemi);
1813 return Sema::ConditionError();
1814 }
1815 DeclaratorInfo.setAsmLabel(AsmLabel.get());
1816 DeclaratorInfo.SetRangeEnd(Loc);
1817 }
1818
1819 // If attributes are present, parse them.
1820 MaybeParseGNUAttributes(DeclaratorInfo);
1821
1822 // Type-check the declaration itself.
1823 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
1824 DeclaratorInfo);
1825 if (Dcl.isInvalid())
1826 return Sema::ConditionError();
1827 Decl *DeclOut = Dcl.get();
1828
1829 // '=' assignment-expression
1830 // If a '==' or '+=' is found, suggest a fixit to '='.
1831 bool CopyInitialization = isTokenEqualOrEqualTypo();
1832 if (CopyInitialization)
1833 ConsumeToken();
1834
1835 ExprResult InitExpr = ExprError();
1836 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1837 Diag(Tok.getLocation(),
1838 diag::warn_cxx98_compat_generalized_initializer_lists);
1839 InitExpr = ParseBraceInitializer();
1840 } else if (CopyInitialization) {
1841 InitExpr = ParseAssignmentExpression();
1842 } else if (Tok.is(tok::l_paren)) {
1843 // This was probably an attempt to initialize the variable.
1844 SourceLocation LParen = ConsumeParen(), RParen = LParen;
1845 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
1846 RParen = ConsumeParen();
1847 Diag(DeclOut->getLocation(),
1848 diag::err_expected_init_in_condition_lparen)
1849 << SourceRange(LParen, RParen);
1850 } else {
1851 Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
1852 }
1853
1854 if (!InitExpr.isInvalid())
1855 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization);
1856 else
1857 Actions.ActOnInitializerError(DeclOut);
1858
1859 Actions.FinalizeDeclaration(DeclOut);
1860 return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
1861}
1862
1863/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1864/// This should only be called when the current token is known to be part of
1865/// simple-type-specifier.
1866///
1867/// simple-type-specifier:
1868/// '::'[opt] nested-name-specifier[opt] type-name
1869/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1870/// char
1871/// wchar_t
1872/// bool
1873/// short
1874/// int
1875/// long
1876/// signed
1877/// unsigned
1878/// float
1879/// double
1880/// void
1881/// [GNU] typeof-specifier
1882/// [C++0x] auto [TODO]
1883///
1884/// type-name:
1885/// class-name
1886/// enum-name
1887/// typedef-name
1888///
1889void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1890 DS.SetRangeStart(Tok.getLocation());
1891 const char *PrevSpec;
1892 unsigned DiagID;
1893 SourceLocation Loc = Tok.getLocation();
1894 const clang::PrintingPolicy &Policy =
1895 Actions.getASTContext().getPrintingPolicy();
1896
1897 switch (Tok.getKind()) {
1898 case tok::identifier: // foo::bar
1899 case tok::coloncolon: // ::foo::bar
1900 llvm_unreachable("Annotation token should already be formed!")::llvm::llvm_unreachable_internal("Annotation token should already be formed!"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 1900)
;
1901 default:
1902 llvm_unreachable("Not a simple-type-specifier token!")::llvm::llvm_unreachable_internal("Not a simple-type-specifier token!"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 1902)
;
1903
1904 // type-name
1905 case tok::annot_typename: {
1906 if (getTypeAnnotation(Tok))
1907 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
1908 getTypeAnnotation(Tok), Policy);
1909 else
1910 DS.SetTypeSpecError();
1911
1912 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1913 ConsumeAnnotationToken();
1914
1915 DS.Finish(Actions, Policy);
1916 return;
1917 }
1918
1919 // builtin types
1920 case tok::kw_short:
1921 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
1922 break;
1923 case tok::kw_long:
1924 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
1925 break;
1926 case tok::kw___int64:
1927 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
1928 break;
1929 case tok::kw_signed:
1930 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1931 break;
1932 case tok::kw_unsigned:
1933 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
1934 break;
1935 case tok::kw_void:
1936 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
1937 break;
1938 case tok::kw_char:
1939 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
1940 break;
1941 case tok::kw_int:
1942 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
1943 break;
1944 case tok::kw___int128:
1945 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
1946 break;
1947 case tok::kw_half:
1948 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
1949 break;
1950 case tok::kw_float:
1951 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
1952 break;
1953 case tok::kw_double:
1954 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
1955 break;
1956 case tok::kw__Float16:
1957 DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec, DiagID, Policy);
1958 break;
1959 case tok::kw___float128:
1960 DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
1961 break;
1962 case tok::kw_wchar_t:
1963 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
1964 break;
1965 case tok::kw_char16_t:
1966 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
1967 break;
1968 case tok::kw_char32_t:
1969 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
1970 break;
1971 case tok::kw_bool:
1972 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
1973 break;
1974 case tok::annot_decltype:
1975 case tok::kw_decltype:
1976 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
1977 return DS.Finish(Actions, Policy);
1978
1979 // GNU typeof support.
1980 case tok::kw_typeof:
1981 ParseTypeofSpecifier(DS);
1982 DS.Finish(Actions, Policy);
1983 return;
1984 }
1985 ConsumeAnyToken();
1986 DS.SetRangeEnd(PrevTokLocation);
1987 DS.Finish(Actions, Policy);
1988}
1989
1990/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1991/// [dcl.name]), which is a non-empty sequence of type-specifiers,
1992/// e.g., "const short int". Note that the DeclSpec is *not* finished
1993/// by parsing the type-specifier-seq, because these sequences are
1994/// typically followed by some form of declarator. Returns true and
1995/// emits diagnostics if this is not a type-specifier-seq, false
1996/// otherwise.
1997///
1998/// type-specifier-seq: [C++ 8.1]
1999/// type-specifier type-specifier-seq[opt]
2000///
2001bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
2002 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_type_specifier);
2003 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
2004 return false;
2005}
2006
2007/// \brief Finish parsing a C++ unqualified-id that is a template-id of
2008/// some form.
2009///
2010/// This routine is invoked when a '<' is encountered after an identifier or
2011/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
2012/// whether the unqualified-id is actually a template-id. This routine will
2013/// then parse the template arguments and form the appropriate template-id to
2014/// return to the caller.
2015///
2016/// \param SS the nested-name-specifier that precedes this template-id, if
2017/// we're actually parsing a qualified-id.
2018///
2019/// \param Name for constructor and destructor names, this is the actual
2020/// identifier that may be a template-name.
2021///
2022/// \param NameLoc the location of the class-name in a constructor or
2023/// destructor.
2024///
2025/// \param EnteringContext whether we're entering the scope of the
2026/// nested-name-specifier.
2027///
2028/// \param ObjectType if this unqualified-id occurs within a member access
2029/// expression, the type of the base object whose member is being accessed.
2030///
2031/// \param Id as input, describes the template-name or operator-function-id
2032/// that precedes the '<'. If template arguments were parsed successfully,
2033/// will be updated with the template-id.
2034///
2035/// \param AssumeTemplateId When true, this routine will assume that the name
2036/// refers to a template without performing name lookup to verify.
2037///
2038/// \returns true if a parse error occurred, false otherwise.
2039bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
2040 SourceLocation TemplateKWLoc,
2041 IdentifierInfo *Name,
2042 SourceLocation NameLoc,
2043 bool EnteringContext,
2044 ParsedType ObjectType,
2045 UnqualifiedId &Id,
2046 bool AssumeTemplateId) {
2047 assert((AssumeTemplateId || Tok.is(tok::less)) &&(static_cast <bool> ((AssumeTemplateId || Tok.is(tok::less
)) && "Expected '<' to finish parsing a template-id"
) ? void (0) : __assert_fail ("(AssumeTemplateId || Tok.is(tok::less)) && \"Expected '<' to finish parsing a template-id\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 2048, __extension__ __PRETTY_FUNCTION__))
2048 "Expected '<' to finish parsing a template-id")(static_cast <bool> ((AssumeTemplateId || Tok.is(tok::less
)) && "Expected '<' to finish parsing a template-id"
) ? void (0) : __assert_fail ("(AssumeTemplateId || Tok.is(tok::less)) && \"Expected '<' to finish parsing a template-id\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 2048, __extension__ __PRETTY_FUNCTION__))
;
2049
2050 TemplateTy Template;
2051 TemplateNameKind TNK = TNK_Non_template;
2052 switch (Id.getKind()) {
2053 case UnqualifiedIdKind::IK_Identifier:
2054 case UnqualifiedIdKind::IK_OperatorFunctionId:
2055 case UnqualifiedIdKind::IK_LiteralOperatorId:
2056 if (AssumeTemplateId) {
2057 // We defer the injected-class-name checks until we've found whether
2058 // this template-id is used to form a nested-name-specifier or not.
2059 TNK = Actions.ActOnDependentTemplateName(
2060 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2061 Template, /*AllowInjectedClassName*/ true);
2062 if (TNK == TNK_Non_template)
2063 return true;
2064 } else {
2065 bool MemberOfUnknownSpecialization;
2066 TNK = Actions.isTemplateName(getCurScope(), SS,
2067 TemplateKWLoc.isValid(), Id,
2068 ObjectType, EnteringContext, Template,
2069 MemberOfUnknownSpecialization);
2070
2071 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
2072 ObjectType && IsTemplateArgumentList()) {
2073 // We have something like t->getAs<T>(), where getAs is a
2074 // member of an unknown specialization. However, this will only
2075 // parse correctly as a template, so suggest the keyword 'template'
2076 // before 'getAs' and treat this as a dependent template name.
2077 std::string Name;
2078 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier)
2079 Name = Id.Identifier->getName();
2080 else {
2081 Name = "operator ";
2082 if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId)
2083 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
2084 else
2085 Name += Id.Identifier->getName();
2086 }
2087 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
2088 << Name
2089 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
2090 TNK = Actions.ActOnDependentTemplateName(
2091 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2092 Template, /*AllowInjectedClassName*/ true);
2093 if (TNK == TNK_Non_template)
2094 return true;
2095 }
2096 }
2097 break;
2098
2099 case UnqualifiedIdKind::IK_ConstructorName: {
2100 UnqualifiedId TemplateName;
2101 bool MemberOfUnknownSpecialization;
2102 TemplateName.setIdentifier(Name, NameLoc);
2103 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2104 TemplateName, ObjectType,
2105 EnteringContext, Template,
2106 MemberOfUnknownSpecialization);
2107 break;
2108 }
2109
2110 case UnqualifiedIdKind::IK_DestructorName: {
2111 UnqualifiedId TemplateName;
2112 bool MemberOfUnknownSpecialization;
2113 TemplateName.setIdentifier(Name, NameLoc);
2114 if (ObjectType) {
2115 TNK = Actions.ActOnDependentTemplateName(
2116 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
2117 EnteringContext, Template, /*AllowInjectedClassName*/ true);
2118 if (TNK == TNK_Non_template)
2119 return true;
2120 } else {
2121 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2122 TemplateName, ObjectType,
2123 EnteringContext, Template,
2124 MemberOfUnknownSpecialization);
2125
2126 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
2127 Diag(NameLoc, diag::err_destructor_template_id)
2128 << Name << SS.getRange();
2129 return true;
2130 }
2131 }
2132 break;
2133 }
2134
2135 default:
2136 return false;
2137 }
2138
2139 if (TNK == TNK_Non_template)
2140 return false;
2141
2142 // Parse the enclosed template argument list.
2143 SourceLocation LAngleLoc, RAngleLoc;
2144 TemplateArgList TemplateArgs;
2145 if (Tok.is(tok::less) && ParseTemplateIdAfterTemplateName(
2146 true, LAngleLoc, TemplateArgs, RAngleLoc))
2147 return true;
2148
2149 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier ||
2150 Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2151 Id.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) {
2152 // Form a parsed representation of the template-id to be stored in the
2153 // UnqualifiedId.
2154
2155 // FIXME: Store name for literal operator too.
2156 IdentifierInfo *TemplateII =
2157 Id.getKind() == UnqualifiedIdKind::IK_Identifier ? Id.Identifier
2158 : nullptr;
2159 OverloadedOperatorKind OpKind =
2160 Id.getKind() == UnqualifiedIdKind::IK_Identifier
2161 ? OO_None
2162 : Id.OperatorFunctionId.Operator;
2163
2164 TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
2165 SS, TemplateKWLoc, Id.StartLocation, TemplateII, OpKind, Template, TNK,
2166 LAngleLoc, RAngleLoc, TemplateArgs, TemplateIds);
2167
2168 Id.setTemplateId(TemplateId);
2169 return false;
2170 }
2171
2172 // Bundle the template arguments together.
2173 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
2174
2175 // Constructor and destructor names.
2176 TypeResult Type
2177 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
2178 Template, Name, NameLoc,
2179 LAngleLoc, TemplateArgsPtr, RAngleLoc,
2180 /*IsCtorOrDtorName=*/true);
2181 if (Type.isInvalid())
2182 return true;
2183
2184 if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName)
2185 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2186 else
2187 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2188
2189 return false;
2190}
2191
2192/// \brief Parse an operator-function-id or conversion-function-id as part
2193/// of a C++ unqualified-id.
2194///
2195/// This routine is responsible only for parsing the operator-function-id or
2196/// conversion-function-id; it does not handle template arguments in any way.
2197///
2198/// \code
2199/// operator-function-id: [C++ 13.5]
2200/// 'operator' operator
2201///
2202/// operator: one of
2203/// new delete new[] delete[]
2204/// + - * / % ^ & | ~
2205/// ! = < > += -= *= /= %=
2206/// ^= &= |= << >> >>= <<= == !=
2207/// <= >= && || ++ -- , ->* ->
2208/// () [] <=>
2209///
2210/// conversion-function-id: [C++ 12.3.2]
2211/// operator conversion-type-id
2212///
2213/// conversion-type-id:
2214/// type-specifier-seq conversion-declarator[opt]
2215///
2216/// conversion-declarator:
2217/// ptr-operator conversion-declarator[opt]
2218/// \endcode
2219///
2220/// \param SS The nested-name-specifier that preceded this unqualified-id. If
2221/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2222///
2223/// \param EnteringContext whether we are entering the scope of the
2224/// nested-name-specifier.
2225///
2226/// \param ObjectType if this unqualified-id occurs within a member access
2227/// expression, the type of the base object whose member is being accessed.
2228///
2229/// \param Result on a successful parse, contains the parsed unqualified-id.
2230///
2231/// \returns true if parsing fails, false otherwise.
2232bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2233 ParsedType ObjectType,
2234 UnqualifiedId &Result) {
2235 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 2235, __extension__ __PRETTY_FUNCTION__))
;
2236
2237 // Consume the 'operator' keyword.
2238 SourceLocation KeywordLoc = ConsumeToken();
2239
2240 // Determine what kind of operator name we have.
2241 unsigned SymbolIdx = 0;
2242 SourceLocation SymbolLocations[3];
2243 OverloadedOperatorKind Op = OO_None;
2244 switch (Tok.getKind()) {
2245 case tok::kw_new:
2246 case tok::kw_delete: {
2247 bool isNew = Tok.getKind() == tok::kw_new;
2248 // Consume the 'new' or 'delete'.
2249 SymbolLocations[SymbolIdx++] = ConsumeToken();
2250 // Check for array new/delete.
2251 if (Tok.is(tok::l_square) &&
2252 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
2253 // Consume the '[' and ']'.
2254 BalancedDelimiterTracker T(*this, tok::l_square);
2255 T.consumeOpen();
2256 T.consumeClose();
2257 if (T.getCloseLocation().isInvalid())
2258 return true;
2259
2260 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2261 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2262 Op = isNew? OO_Array_New : OO_Array_Delete;
2263 } else {
2264 Op = isNew? OO_New : OO_Delete;
2265 }
2266 break;
2267 }
2268
2269#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2270 case tok::Token: \
2271 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2272 Op = OO_##Name; \
2273 break;
2274#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2275#include "clang/Basic/OperatorKinds.def"
2276
2277 case tok::l_paren: {
2278 // Consume the '(' and ')'.
2279 BalancedDelimiterTracker T(*this, tok::l_paren);
2280 T.consumeOpen();
2281 T.consumeClose();
2282 if (T.getCloseLocation().isInvalid())
2283 return true;
2284
2285 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2286 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2287 Op = OO_Call;
2288 break;
2289 }
2290
2291 case tok::l_square: {
2292 // Consume the '[' and ']'.
2293 BalancedDelimiterTracker T(*this, tok::l_square);
2294 T.consumeOpen();
2295 T.consumeClose();
2296 if (T.getCloseLocation().isInvalid())
2297 return true;
2298
2299 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2300 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2301 Op = OO_Subscript;
2302 break;
2303 }
2304
2305 case tok::code_completion: {
2306 // Code completion for the operator name.
2307 Actions.CodeCompleteOperatorName(getCurScope());
2308 cutOffParsing();
2309 // Don't try to parse any further.
2310 return true;
2311 }
2312
2313 default:
2314 break;
2315 }
2316
2317 if (Op != OO_None) {
2318 // We have parsed an operator-function-id.
2319 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2320 return false;
2321 }
2322
2323 // Parse a literal-operator-id.
2324 //
2325 // literal-operator-id: C++11 [over.literal]
2326 // operator string-literal identifier
2327 // operator user-defined-string-literal
2328
2329 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
2330 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
2331
2332 SourceLocation DiagLoc;
2333 unsigned DiagId = 0;
2334
2335 // We're past translation phase 6, so perform string literal concatenation
2336 // before checking for "".
2337 SmallVector<Token, 4> Toks;
2338 SmallVector<SourceLocation, 4> TokLocs;
2339 while (isTokenStringLiteral()) {
2340 if (!Tok.is(tok::string_literal) && !DiagId) {
2341 // C++11 [over.literal]p1:
2342 // The string-literal or user-defined-string-literal in a
2343 // literal-operator-id shall have no encoding-prefix [...].
2344 DiagLoc = Tok.getLocation();
2345 DiagId = diag::err_literal_operator_string_prefix;
2346 }
2347 Toks.push_back(Tok);
2348 TokLocs.push_back(ConsumeStringToken());
2349 }
2350
2351 StringLiteralParser Literal(Toks, PP);
2352 if (Literal.hadError)
2353 return true;
2354
2355 // Grab the literal operator's suffix, which will be either the next token
2356 // or a ud-suffix from the string literal.
2357 IdentifierInfo *II = nullptr;
2358 SourceLocation SuffixLoc;
2359 if (!Literal.getUDSuffix().empty()) {
2360 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2361 SuffixLoc =
2362 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2363 Literal.getUDSuffixOffset(),
2364 PP.getSourceManager(), getLangOpts());
2365 } else if (Tok.is(tok::identifier)) {
2366 II = Tok.getIdentifierInfo();
2367 SuffixLoc = ConsumeToken();
2368 TokLocs.push_back(SuffixLoc);
2369 } else {
2370 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
2371 return true;
2372 }
2373
2374 // The string literal must be empty.
2375 if (!Literal.GetString().empty() || Literal.Pascal) {
2376 // C++11 [over.literal]p1:
2377 // The string-literal or user-defined-string-literal in a
2378 // literal-operator-id shall [...] contain no characters
2379 // other than the implicit terminating '\0'.
2380 DiagLoc = TokLocs.front();
2381 DiagId = diag::err_literal_operator_string_not_empty;
2382 }
2383
2384 if (DiagId) {
2385 // This isn't a valid literal-operator-id, but we think we know
2386 // what the user meant. Tell them what they should have written.
2387 SmallString<32> Str;
2388 Str += "\"\"";
2389 Str += II->getName();
2390 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2391 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2392 }
2393
2394 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
2395
2396 return Actions.checkLiteralOperatorId(SS, Result);
2397 }
2398
2399 // Parse a conversion-function-id.
2400 //
2401 // conversion-function-id: [C++ 12.3.2]
2402 // operator conversion-type-id
2403 //
2404 // conversion-type-id:
2405 // type-specifier-seq conversion-declarator[opt]
2406 //
2407 // conversion-declarator:
2408 // ptr-operator conversion-declarator[opt]
2409
2410 // Parse the type-specifier-seq.
2411 DeclSpec DS(AttrFactory);
2412 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
2413 return true;
2414
2415 // Parse the conversion-declarator, which is merely a sequence of
2416 // ptr-operators.
2417 Declarator D(DS, DeclaratorContext::ConversionIdContext);
2418 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2419
2420 // Finish up the type.
2421 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
2422 if (Ty.isInvalid())
2423 return true;
2424
2425 // Note that this is a conversion-function-id.
2426 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2427 D.getSourceRange().getEnd());
2428 return false;
2429}
2430
2431/// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
2432/// name of an entity.
2433///
2434/// \code
2435/// unqualified-id: [C++ expr.prim.general]
2436/// identifier
2437/// operator-function-id
2438/// conversion-function-id
2439/// [C++0x] literal-operator-id [TODO]
2440/// ~ class-name
2441/// template-id
2442///
2443/// \endcode
2444///
2445/// \param SS The nested-name-specifier that preceded this unqualified-id. If
2446/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2447///
2448/// \param EnteringContext whether we are entering the scope of the
2449/// nested-name-specifier.
2450///
2451/// \param AllowDestructorName whether we allow parsing of a destructor name.
2452///
2453/// \param AllowConstructorName whether we allow parsing a constructor name.
2454///
2455/// \param AllowDeductionGuide whether we allow parsing a deduction guide name.
2456///
2457/// \param ObjectType if this unqualified-id occurs within a member access
2458/// expression, the type of the base object whose member is being accessed.
2459///
2460/// \param Result on a successful parse, contains the parsed unqualified-id.
2461///
2462/// \returns true if parsing fails, false otherwise.
2463bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2464 bool AllowDestructorName,
2465 bool AllowConstructorName,
2466 bool AllowDeductionGuide,
2467 ParsedType ObjectType,
2468 SourceLocation& TemplateKWLoc,
2469 UnqualifiedId &Result) {
2470
2471 // Handle 'A::template B'. This is for template-ids which have not
2472 // already been annotated by ParseOptionalCXXScopeSpecifier().
2473 bool TemplateSpecified = false;
2474 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
2475 (ObjectType || SS.isSet())) {
2476 TemplateSpecified = true;
2477 TemplateKWLoc = ConsumeToken();
2478 }
2479
2480 // unqualified-id:
2481 // identifier
2482 // template-id (when it hasn't already been annotated)
2483 if (Tok.is(tok::identifier)) {
2484 // Consume the identifier.
2485 IdentifierInfo *Id = Tok.getIdentifierInfo();
2486 SourceLocation IdLoc = ConsumeToken();
2487
2488 if (!getLangOpts().CPlusPlus) {
2489 // If we're not in C++, only identifiers matter. Record the
2490 // identifier and return.
2491 Result.setIdentifier(Id, IdLoc);
2492 return false;
2493 }
2494
2495 ParsedTemplateTy TemplateName;
2496 if (AllowConstructorName &&
2497 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
2498 // We have parsed a constructor name.
2499 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, false,
2500 false, nullptr,
2501 /*IsCtorOrDtorName=*/true,
2502 /*NonTrivialTypeSourceInfo=*/true);
2503 Result.setConstructorName(Ty, IdLoc, IdLoc);
2504 } else if (getLangOpts().CPlusPlus17 &&
2505 AllowDeductionGuide && SS.isEmpty() &&
2506 Actions.isDeductionGuideName(getCurScope(), *Id, IdLoc,
2507 &TemplateName)) {
2508 // We have parsed a template-name naming a deduction guide.
2509 Result.setDeductionGuideName(TemplateName, IdLoc);
2510 } else {
2511 // We have parsed an identifier.
2512 Result.setIdentifier(Id, IdLoc);
2513 }
2514
2515 // If the next token is a '<', we may have a template.
2516 if (TemplateSpecified || Tok.is(tok::less))
2517 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2518 EnteringContext, ObjectType,
2519 Result, TemplateSpecified);
2520
2521 return false;
2522 }
2523
2524 // unqualified-id:
2525 // template-id (already parsed and annotated)
2526 if (Tok.is(tok::annot_template_id)) {
2527 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2528
2529 // If the template-name names the current class, then this is a constructor
2530 if (AllowConstructorName && TemplateId->Name &&
2531 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2532 if (SS.isSet()) {
2533 // C++ [class.qual]p2 specifies that a qualified template-name
2534 // is taken as the constructor name where a constructor can be
2535 // declared. Thus, the template arguments are extraneous, so
2536 // complain about them and remove them entirely.
2537 Diag(TemplateId->TemplateNameLoc,
2538 diag::err_out_of_line_constructor_template_id)
2539 << TemplateId->Name
2540 << FixItHint::CreateRemoval(
2541 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
2542 ParsedType Ty =
2543 Actions.getTypeName(*TemplateId->Name, TemplateId->TemplateNameLoc,
2544 getCurScope(), &SS, false, false, nullptr,
2545 /*IsCtorOrDtorName=*/true,
2546 /*NontrivialTypeSourceInfo=*/true);
2547 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
2548 TemplateId->RAngleLoc);
2549 ConsumeAnnotationToken();
2550 return false;
2551 }
2552
2553 Result.setConstructorTemplateId(TemplateId);
2554 ConsumeAnnotationToken();
2555 return false;
2556 }
2557
2558 // We have already parsed a template-id; consume the annotation token as
2559 // our unqualified-id.
2560 Result.setTemplateId(TemplateId);
2561 TemplateKWLoc = TemplateId->TemplateKWLoc;
2562 ConsumeAnnotationToken();
2563 return false;
2564 }
2565
2566 // unqualified-id:
2567 // operator-function-id
2568 // conversion-function-id
2569 if (Tok.is(tok::kw_operator)) {
2570 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
2571 return true;
2572
2573 // If we have an operator-function-id or a literal-operator-id and the next
2574 // token is a '<', we may have a
2575 //
2576 // template-id:
2577 // operator-function-id < template-argument-list[opt] >
2578 if ((Result.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2579 Result.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) &&
2580 (TemplateSpecified || Tok.is(tok::less)))
2581 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2582 nullptr, SourceLocation(),
2583 EnteringContext, ObjectType,
2584 Result, TemplateSpecified);
2585
2586 return false;
2587 }
2588
2589 if (getLangOpts().CPlusPlus &&
2590 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
2591 // C++ [expr.unary.op]p10:
2592 // There is an ambiguity in the unary-expression ~X(), where X is a
2593 // class-name. The ambiguity is resolved in favor of treating ~ as a
2594 // unary complement rather than treating ~X as referring to a destructor.
2595
2596 // Parse the '~'.
2597 SourceLocation TildeLoc = ConsumeToken();
2598
2599 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2600 DeclSpec DS(AttrFactory);
2601 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2602 if (ParsedType Type =
2603 Actions.getDestructorTypeForDecltype(DS, ObjectType)) {
2604 Result.setDestructorName(TildeLoc, Type, EndLoc);
2605 return false;
2606 }
2607 return true;
2608 }
2609
2610 // Parse the class-name.
2611 if (Tok.isNot(tok::identifier)) {
2612 Diag(Tok, diag::err_destructor_tilde_identifier);
2613 return true;
2614 }
2615
2616 // If the user wrote ~T::T, correct it to T::~T.
2617 DeclaratorScopeObj DeclScopeObj(*this, SS);
2618 if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
2619 // Don't let ParseOptionalCXXScopeSpecifier() "correct"
2620 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
2621 // it will confuse this recovery logic.
2622 ColonProtectionRAIIObject ColonRAII(*this, false);
2623
2624 if (SS.isSet()) {
2625 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2626 SS.clear();
2627 }
2628 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2629 return true;
2630 if (SS.isNotEmpty())
2631 ObjectType = nullptr;
2632 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
2633 !SS.isSet()) {
2634 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2635 return true;
2636 }
2637
2638 // Recover as if the tilde had been written before the identifier.
2639 Diag(TildeLoc, diag::err_destructor_tilde_scope)
2640 << FixItHint::CreateRemoval(TildeLoc)
2641 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
2642
2643 // Temporarily enter the scope for the rest of this function.
2644 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2645 DeclScopeObj.EnterDeclaratorScope();
2646 }
2647
2648 // Parse the class-name (or template-name in a simple-template-id).
2649 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2650 SourceLocation ClassNameLoc = ConsumeToken();
2651
2652 if (TemplateSpecified || Tok.is(tok::less)) {
2653 Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
2654 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2655 ClassName, ClassNameLoc,
2656 EnteringContext, ObjectType,
2657 Result, TemplateSpecified);
2658 }
2659
2660 // Note that this is a destructor name.
2661 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2662 ClassNameLoc, getCurScope(),
2663 SS, ObjectType,
2664 EnteringContext);
2665 if (!Ty)
2666 return true;
2667
2668 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
2669 return false;
2670 }
2671
2672 Diag(Tok, diag::err_expected_unqualified_id)
2673 << getLangOpts().CPlusPlus;
2674 return true;
2675}
2676
2677/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2678/// memory in a typesafe manner and call constructors.
2679///
2680/// This method is called to parse the new expression after the optional :: has
2681/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2682/// is its location. Otherwise, "Start" is the location of the 'new' token.
2683///
2684/// new-expression:
2685/// '::'[opt] 'new' new-placement[opt] new-type-id
2686/// new-initializer[opt]
2687/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2688/// new-initializer[opt]
2689///
2690/// new-placement:
2691/// '(' expression-list ')'
2692///
2693/// new-type-id:
2694/// type-specifier-seq new-declarator[opt]
2695/// [GNU] attributes type-specifier-seq new-declarator[opt]
2696///
2697/// new-declarator:
2698/// ptr-operator new-declarator[opt]
2699/// direct-new-declarator
2700///
2701/// new-initializer:
2702/// '(' expression-list[opt] ')'
2703/// [C++0x] braced-init-list
2704///
2705ExprResult
2706Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2707 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 2707, __extension__ __PRETTY_FUNCTION__))
;
2708 ConsumeToken(); // Consume 'new'
2709
2710 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2711 // second form of new-expression. It can't be a new-type-id.
2712
2713 ExprVector PlacementArgs;
2714 SourceLocation PlacementLParen, PlacementRParen;
2715
2716 SourceRange TypeIdParens;
2717 DeclSpec DS(AttrFactory);
2718 Declarator DeclaratorInfo(DS, DeclaratorContext::CXXNewContext);
2719 if (Tok.is(tok::l_paren)) {
2720 // If it turns out to be a placement, we change the type location.
2721 BalancedDelimiterTracker T(*this, tok::l_paren);
2722 T.consumeOpen();
2723 PlacementLParen = T.getOpenLocation();
2724 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
2725 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2726 return ExprError();
2727 }
2728
2729 T.consumeClose();
2730 PlacementRParen = T.getCloseLocation();
2731 if (PlacementRParen.isInvalid()) {
2732 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2733 return ExprError();
2734 }
2735
2736 if (PlacementArgs.empty()) {
2737 // Reset the placement locations. There was no placement.
2738 TypeIdParens = T.getRange();
2739 PlacementLParen = PlacementRParen = SourceLocation();
2740 } else {
2741 // We still need the type.
2742 if (Tok.is(tok::l_paren)) {
2743 BalancedDelimiterTracker T(*this, tok::l_paren);
2744 T.consumeOpen();
2745 MaybeParseGNUAttributes(DeclaratorInfo);
2746 ParseSpecifierQualifierList(DS);
2747 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2748 ParseDeclarator(DeclaratorInfo);
2749 T.consumeClose();
2750 TypeIdParens = T.getRange();
2751 } else {
2752 MaybeParseGNUAttributes(DeclaratorInfo);
2753 if (ParseCXXTypeSpecifierSeq(DS))
2754 DeclaratorInfo.setInvalidType(true);
2755 else {
2756 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2757 ParseDeclaratorInternal(DeclaratorInfo,
2758 &Parser::ParseDirectNewDeclarator);
2759 }
2760 }
2761 }
2762 } else {
2763 // A new-type-id is a simplified type-id, where essentially the
2764 // direct-declarator is replaced by a direct-new-declarator.
2765 MaybeParseGNUAttributes(DeclaratorInfo);
2766 if (ParseCXXTypeSpecifierSeq(DS))
2767 DeclaratorInfo.setInvalidType(true);
2768 else {
2769 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2770 ParseDeclaratorInternal(DeclaratorInfo,
2771 &Parser::ParseDirectNewDeclarator);
2772 }
2773 }
2774 if (DeclaratorInfo.isInvalidType()) {
2775 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2776 return ExprError();
2777 }
2778
2779 ExprResult Initializer;
2780
2781 if (Tok.is(tok::l_paren)) {
2782 SourceLocation ConstructorLParen, ConstructorRParen;
2783 ExprVector ConstructorArgs;
2784 BalancedDelimiterTracker T(*this, tok::l_paren);
2785 T.consumeOpen();
2786 ConstructorLParen = T.getOpenLocation();
2787 if (Tok.isNot(tok::r_paren)) {
2788 CommaLocsTy CommaLocs;
2789 if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
2790 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(),
2791 DeclaratorInfo).get();
2792 Actions.CodeCompleteConstructor(getCurScope(),
2793 TypeRep.get()->getCanonicalTypeInternal(),
2794 DeclaratorInfo.getLocEnd(),
2795 ConstructorArgs);
2796 })) {
2797 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2798 return ExprError();
2799 }
2800 }
2801 T.consumeClose();
2802 ConstructorRParen = T.getCloseLocation();
2803 if (ConstructorRParen.isInvalid()) {
2804 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2805 return ExprError();
2806 }
2807 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2808 ConstructorRParen,
2809 ConstructorArgs);
2810 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
2811 Diag(Tok.getLocation(),
2812 diag::warn_cxx98_compat_generalized_initializer_lists);
2813 Initializer = ParseBraceInitializer();
2814 }
2815 if (Initializer.isInvalid())
2816 return Initializer;
2817
2818 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
2819 PlacementArgs, PlacementRParen,
2820 TypeIdParens, DeclaratorInfo, Initializer.get());
2821}
2822
2823/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2824/// passed to ParseDeclaratorInternal.
2825///
2826/// direct-new-declarator:
2827/// '[' expression ']'
2828/// direct-new-declarator '[' constant-expression ']'
2829///
2830void Parser::ParseDirectNewDeclarator(Declarator &D) {
2831 // Parse the array dimensions.
2832 bool first = true;
2833 while (Tok.is(tok::l_square)) {
2834 // An array-size expression can't start with a lambda.
2835 if (CheckProhibitedCXX11Attribute())
2836 continue;
2837
2838 BalancedDelimiterTracker T(*this, tok::l_square);
2839 T.consumeOpen();
2840
2841 ExprResult Size(first ? ParseExpression()
2842 : ParseConstantExpression());
2843 if (Size.isInvalid()) {
2844 // Recover
2845 SkipUntil(tok::r_square, StopAtSemi);
2846 return;
2847 }
2848 first = false;
2849
2850 T.consumeClose();
2851
2852 // Attributes here appertain to the array type. C++11 [expr.new]p5.
2853 ParsedAttributes Attrs(AttrFactory);
2854 MaybeParseCXX11Attributes(Attrs);
2855
2856 D.AddTypeInfo(DeclaratorChunk::getArray(0,
2857 /*static=*/false, /*star=*/false,
2858 Size.get(),
2859 T.getOpenLocation(),
2860 T.getCloseLocation()),
2861 Attrs, T.getCloseLocation());
2862
2863 if (T.getCloseLocation().isInvalid())
2864 return;
2865 }
2866}
2867
2868/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2869/// This ambiguity appears in the syntax of the C++ new operator.
2870///
2871/// new-expression:
2872/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2873/// new-initializer[opt]
2874///
2875/// new-placement:
2876/// '(' expression-list ')'
2877///
2878bool Parser::ParseExpressionListOrTypeId(
2879 SmallVectorImpl<Expr*> &PlacementArgs,
2880 Declarator &D) {
2881 // The '(' was already consumed.
2882 if (isTypeIdInParens()) {
2883 ParseSpecifierQualifierList(D.getMutableDeclSpec());
2884 D.SetSourceRange(D.getDeclSpec().getSourceRange());
2885 ParseDeclarator(D);
2886 return D.isInvalidType();
2887 }
2888
2889 // It's not a type, it has to be an expression list.
2890 // Discard the comma locations - ActOnCXXNew has enough parameters.
2891 CommaLocsTy CommaLocs;
2892 return ParseExpressionList(PlacementArgs, CommaLocs);
2893}
2894
2895/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2896/// to free memory allocated by new.
2897///
2898/// This method is called to parse the 'delete' expression after the optional
2899/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2900/// and "Start" is its location. Otherwise, "Start" is the location of the
2901/// 'delete' token.
2902///
2903/// delete-expression:
2904/// '::'[opt] 'delete' cast-expression
2905/// '::'[opt] 'delete' '[' ']' cast-expression
2906ExprResult
2907Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2908 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 2908, __extension__ __PRETTY_FUNCTION__))
;
2909 ConsumeToken(); // Consume 'delete'
2910
2911 // Array delete?
2912 bool ArrayDelete = false;
2913 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
2914 // C++11 [expr.delete]p1:
2915 // Whenever the delete keyword is followed by empty square brackets, it
2916 // shall be interpreted as [array delete].
2917 // [Footnote: A lambda expression with a lambda-introducer that consists
2918 // of empty square brackets can follow the delete keyword if
2919 // the lambda expression is enclosed in parentheses.]
2920 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2921 // lambda-introducer.
2922 ArrayDelete = true;
2923 BalancedDelimiterTracker T(*this, tok::l_square);
2924
2925 T.consumeOpen();
2926 T.consumeClose();
2927 if (T.getCloseLocation().isInvalid())
2928 return ExprError();
2929 }
2930
2931 ExprResult Operand(ParseCastExpression(false));
2932 if (Operand.isInvalid())
2933 return Operand;
2934
2935 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
2936}
2937
2938static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2939 switch (kind) {
2940 default: llvm_unreachable("Not a known type trait")::llvm::llvm_unreachable_internal("Not a known type trait", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 2940)
;
2941#define TYPE_TRAIT_1(Spelling, Name, Key) \
2942case tok::kw_ ## Spelling: return UTT_ ## Name;
2943#define TYPE_TRAIT_2(Spelling, Name, Key) \
2944case tok::kw_ ## Spelling: return BTT_ ## Name;
2945#include "clang/Basic/TokenKinds.def"
2946#define TYPE_TRAIT_N(Spelling, Name, Key) \
2947 case tok::kw_ ## Spelling: return TT_ ## Name;
2948#include "clang/Basic/TokenKinds.def"
2949 }
2950}
2951
2952static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2953 switch(kind) {
2954 default: llvm_unreachable("Not a known binary type trait")::llvm::llvm_unreachable_internal("Not a known binary type trait"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 2954)
;
2955 case tok::kw___array_rank: return ATT_ArrayRank;
2956 case tok::kw___array_extent: return ATT_ArrayExtent;
2957 }
2958}
2959
2960static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2961 switch(kind) {
2962 default: llvm_unreachable("Not a known unary expression trait.")::llvm::llvm_unreachable_internal("Not a known unary expression trait."
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 2962)
;
2963 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2964 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2965 }
2966}
2967
2968static unsigned TypeTraitArity(tok::TokenKind kind) {
2969 switch (kind) {
2970 default: llvm_unreachable("Not a known type trait")::llvm::llvm_unreachable_internal("Not a known type trait", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 2970)
;
2971#define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
2972#include "clang/Basic/TokenKinds.def"
2973 }
2974}
2975
2976/// \brief Parse the built-in type-trait pseudo-functions that allow
2977/// implementation of the TR1/C++11 type traits templates.
2978///
2979/// primary-expression:
2980/// unary-type-trait '(' type-id ')'
2981/// binary-type-trait '(' type-id ',' type-id ')'
2982/// type-trait '(' type-id-seq ')'
2983///
2984/// type-id-seq:
2985/// type-id ...[opt] type-id-seq[opt]
2986///
2987ExprResult Parser::ParseTypeTrait() {
2988 tok::TokenKind Kind = Tok.getKind();
2989 unsigned Arity = TypeTraitArity(Kind);
2990
2991 SourceLocation Loc = ConsumeToken();
2992
2993 BalancedDelimiterTracker Parens(*this, tok::l_paren);
2994 if (Parens.expectAndConsume())
2995 return ExprError();
2996
2997 SmallVector<ParsedType, 2> Args;
2998 do {
2999 // Parse the next type.
3000 TypeResult Ty = ParseTypeName();
3001 if (Ty.isInvalid()) {
3002 Parens.skipToEnd();
3003 return ExprError();
3004 }
3005
3006 // Parse the ellipsis, if present.
3007 if (Tok.is(tok::ellipsis)) {
3008 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
3009 if (Ty.isInvalid()) {
3010 Parens.skipToEnd();
3011 return ExprError();
3012 }
3013 }
3014
3015 // Add this type to the list of arguments.
3016 Args.push_back(Ty.get());
3017 } while (TryConsumeToken(tok::comma));
3018
3019 if (Parens.consumeClose())
3020 return ExprError();
3021
3022 SourceLocation EndLoc = Parens.getCloseLocation();
3023
3024 if (Arity && Args.size() != Arity) {
3025 Diag(EndLoc, diag::err_type_trait_arity)
3026 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
3027 return ExprError();
3028 }
3029
3030 if (!Arity && Args.empty()) {
3031 Diag(EndLoc, diag::err_type_trait_arity)
3032 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
3033 return ExprError();
3034 }
3035
3036 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
3037}
3038
3039/// ParseArrayTypeTrait - Parse the built-in array type-trait
3040/// pseudo-functions.
3041///
3042/// primary-expression:
3043/// [Embarcadero] '__array_rank' '(' type-id ')'
3044/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
3045///
3046ExprResult Parser::ParseArrayTypeTrait() {
3047 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
3048 SourceLocation Loc = ConsumeToken();
3049
3050 BalancedDelimiterTracker T(*this, tok::l_paren);
3051 if (T.expectAndConsume())
3052 return ExprError();
3053
3054 TypeResult Ty = ParseTypeName();
3055 if (Ty.isInvalid()) {
3056 SkipUntil(tok::comma, StopAtSemi);
3057 SkipUntil(tok::r_paren, StopAtSemi);
3058 return ExprError();
3059 }
3060
3061 switch (ATT) {
3062 case ATT_ArrayRank: {
3063 T.consumeClose();
3064 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
3065 T.getCloseLocation());
3066 }
3067 case ATT_ArrayExtent: {
3068 if (ExpectAndConsume(tok::comma)) {
3069 SkipUntil(tok::r_paren, StopAtSemi);
3070 return ExprError();
3071 }
3072
3073 ExprResult DimExpr = ParseExpression();
3074 T.consumeClose();
3075
3076 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
3077 T.getCloseLocation());
3078 }
3079 }
3080 llvm_unreachable("Invalid ArrayTypeTrait!")::llvm::llvm_unreachable_internal("Invalid ArrayTypeTrait!", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 3080)
;
3081}
3082
3083/// ParseExpressionTrait - Parse built-in expression-trait
3084/// pseudo-functions like __is_lvalue_expr( xxx ).
3085///
3086/// primary-expression:
3087/// [Embarcadero] expression-trait '(' expression ')'
3088///
3089ExprResult Parser::ParseExpressionTrait() {
3090 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
3091 SourceLocation Loc = ConsumeToken();
3092
3093 BalancedDelimiterTracker T(*this, tok::l_paren);
3094 if (T.expectAndConsume())
3095 return ExprError();
3096
3097 ExprResult Expr = ParseExpression();
3098
3099 T.consumeClose();
3100
3101 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3102 T.getCloseLocation());
3103}
3104
3105
3106/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3107/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3108/// based on the context past the parens.
3109ExprResult
3110Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
3111 ParsedType &CastTy,
3112 BalancedDelimiterTracker &Tracker,
3113 ColonProtectionRAIIObject &ColonProt) {
3114 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++!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 3114, __extension__ __PRETTY_FUNCTION__))
;
3115 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!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 3115, __extension__ __PRETTY_FUNCTION__))
;
3116 assert(isTypeIdInParens() && "Not a type-id!")(static_cast <bool> (isTypeIdInParens() && "Not a type-id!"
) ? void (0) : __assert_fail ("isTypeIdInParens() && \"Not a type-id!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 3116, __extension__ __PRETTY_FUNCTION__))
;
3117
3118 ExprResult Result(true);
3119 CastTy = nullptr;
3120
3121 // We need to disambiguate a very ugly part of the C++ syntax:
3122 //
3123 // (T())x; - type-id
3124 // (T())*x; - type-id
3125 // (T())/x; - expression
3126 // (T()); - expression
3127 //
3128 // The bad news is that we cannot use the specialized tentative parser, since
3129 // it can only verify that the thing inside the parens can be parsed as
3130 // type-id, it is not useful for determining the context past the parens.
3131 //
3132 // The good news is that the parser can disambiguate this part without
3133 // making any unnecessary Action calls.
3134 //
3135 // It uses a scheme similar to parsing inline methods. The parenthesized
3136 // tokens are cached, the context that follows is determined (possibly by
3137 // parsing a cast-expression), and then we re-introduce the cached tokens
3138 // into the token stream and parse them appropriately.
3139
3140 ParenParseOption ParseAs;
3141 CachedTokens Toks;
3142
3143 // Store the tokens of the parentheses. We will parse them after we determine
3144 // the context that follows them.
3145 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
3146 // We didn't find the ')' we expected.
3147 Tracker.consumeClose();
3148 return ExprError();
3149 }
3150
3151 if (Tok.is(tok::l_brace)) {
3152 ParseAs = CompoundLiteral;
3153 } else {
3154 bool NotCastExpr;
3155 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3156 NotCastExpr = true;
3157 } else {
3158 // Try parsing the cast-expression that may follow.
3159 // If it is not a cast-expression, NotCastExpr will be true and no token
3160 // will be consumed.
3161 ColonProt.restore();
3162 Result = ParseCastExpression(false/*isUnaryExpression*/,
3163 false/*isAddressofOperand*/,
3164 NotCastExpr,
3165 // type-id has priority.
3166 IsTypeCast);
3167 }
3168
3169 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3170 // an expression.
3171 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
3172 }
3173
3174 // Create a fake EOF to mark end of Toks buffer.
3175 Token AttrEnd;
3176 AttrEnd.startToken();
3177 AttrEnd.setKind(tok::eof);
3178 AttrEnd.setLocation(Tok.getLocation());
3179 AttrEnd.setEofData(Toks.data());
3180 Toks.push_back(AttrEnd);
3181
3182 // The current token should go after the cached tokens.
3183 Toks.push_back(Tok);
3184 // Re-enter the stored parenthesized tokens into the token stream, so we may
3185 // parse them now.
3186 PP.EnterTokenStream(Toks, true /*DisableMacroExpansion*/);
3187 // Drop the current token and bring the first cached one. It's the same token
3188 // as when we entered this function.
3189 ConsumeAnyToken();
3190
3191 if (ParseAs >= CompoundLiteral) {
3192 // Parse the type declarator.
3193 DeclSpec DS(AttrFactory);
3194 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
3195 {
3196 ColonProtectionRAIIObject InnerColonProtection(*this);
3197 ParseSpecifierQualifierList(DS);
3198 ParseDeclarator(DeclaratorInfo);
3199 }
3200
3201 // Match the ')'.
3202 Tracker.consumeClose();
3203 ColonProt.restore();
3204
3205 // Consume EOF marker for Toks buffer.
3206 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()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 3206, __extension__ __PRETTY_FUNCTION__))
;
3207 ConsumeAnyToken();
3208
3209 if (ParseAs == CompoundLiteral) {
3210 ExprType = CompoundLiteral;
3211 if (DeclaratorInfo.isInvalidType())
3212 return ExprError();
3213
3214 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3215 return ParseCompoundLiteralExpression(Ty.get(),
3216 Tracker.getOpenLocation(),
3217 Tracker.getCloseLocation());
3218 }
3219
3220 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3221 assert(ParseAs == CastExpr)(static_cast <bool> (ParseAs == CastExpr) ? void (0) : __assert_fail
("ParseAs == CastExpr", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 3221, __extension__ __PRETTY_FUNCTION__))
;
3222
3223 if (DeclaratorInfo.isInvalidType())
3224 return ExprError();
3225
3226 // Result is what ParseCastExpression returned earlier.
3227 if (!Result.isInvalid())
3228 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3229 DeclaratorInfo, CastTy,
3230 Tracker.getCloseLocation(), Result.get());
3231 return Result;
3232 }
3233
3234 // Not a compound literal, and not followed by a cast-expression.
3235 assert(ParseAs == SimpleExpr)(static_cast <bool> (ParseAs == SimpleExpr) ? void (0) :
__assert_fail ("ParseAs == SimpleExpr", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 3235, __extension__ __PRETTY_FUNCTION__))
;
3236
3237 ExprType = SimpleExpr;
3238 Result = ParseExpression();
3239 if (!Result.isInvalid() && Tok.is(tok::r_paren))
3240 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
3241 Tok.getLocation(), Result.get());
3242
3243 // Match the ')'.
3244 if (Result.isInvalid()) {
3245 while (Tok.isNot(tok::eof))
3246 ConsumeAnyToken();
3247 assert(Tok.getEofData() == AttrEnd.getEofData())(static_cast <bool> (Tok.getEofData() == AttrEnd.getEofData
()) ? void (0) : __assert_fail ("Tok.getEofData() == AttrEnd.getEofData()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 3247, __extension__ __PRETTY_FUNCTION__))
;
3248 ConsumeAnyToken();
3249 return ExprError();
3250 }
3251
3252 Tracker.consumeClose();
3253 // Consume EOF marker for Toks buffer.
3254 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()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Parse/ParseExprCXX.cpp"
, 3254, __extension__ __PRETTY_FUNCTION__))
;
3255 ConsumeAnyToken();
3256 return Result;
3257}