This repository was archived by the owner on Nov 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathParseExprCXX.cpp
3236 lines (2862 loc) · 117 KB
/
ParseExprCXX.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Expression parsing implementation for C++.
//
//===----------------------------------------------------------------------===//
#include "clang/Parse/Parser.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/Basic/PrettyStackTrace.h"
#include "clang/Lex/LiteralSupport.h"
#include "clang/Parse/ParseDiagnostic.h"
#include "clang/Parse/RAIIObjectsForParser.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/ParsedTemplate.h"
#include "clang/Sema/Scope.h"
#include "llvm/Support/ErrorHandling.h"
using namespace clang;
static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
switch (Kind) {
// template name
case tok::unknown: return 0;
// casts
case tok::kw_const_cast: return 1;
case tok::kw_dynamic_cast: return 2;
case tok::kw_reinterpret_cast: return 3;
case tok::kw_static_cast: return 4;
default:
llvm_unreachable("Unknown type for digraph error message.");
}
}
// Are the two tokens adjacent in the same source file?
bool Parser::areTokensAdjacent(const Token &First, const Token &Second) {
SourceManager &SM = PP.getSourceManager();
SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
return FirstEnd == SM.getSpellingLoc(Second.getLocation());
}
// Suggest fixit for "<::" after a cast.
static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
// Pull '<:' and ':' off token stream.
if (!AtDigraph)
PP.Lex(DigraphToken);
PP.Lex(ColonToken);
SourceRange Range;
Range.setBegin(DigraphToken.getLocation());
Range.setEnd(ColonToken.getLocation());
P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
<< SelectDigraphErrorMessage(Kind)
<< FixItHint::CreateReplacement(Range, "< ::");
// Update token information to reflect their change in token type.
ColonToken.setKind(tok::coloncolon);
ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
ColonToken.setLength(2);
DigraphToken.setKind(tok::less);
DigraphToken.setLength(1);
// Push new tokens back to token stream.
PP.EnterToken(ColonToken);
if (!AtDigraph)
PP.EnterToken(DigraphToken);
}
// Check for '<::' which should be '< ::' instead of '[:' when following
// a template name.
void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
bool EnteringContext,
IdentifierInfo &II, CXXScopeSpec &SS) {
if (!Next.is(tok::l_square) || Next.getLength() != 2)
return;
Token SecondToken = GetLookAheadToken(2);
if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken))
return;
TemplateTy Template;
UnqualifiedId TemplateName;
TemplateName.setIdentifier(&II, Tok.getLocation());
bool MemberOfUnknownSpecialization;
if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
TemplateName, ObjectType, EnteringContext,
Template, MemberOfUnknownSpecialization))
return;
FixDigraph(*this, PP, Next, SecondToken, tok::unknown,
/*AtDigraph*/false);
}
/// \brief Parse global scope or nested-name-specifier if present.
///
/// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
/// may be preceded by '::'). Note that this routine will not parse ::new or
/// ::delete; it will just leave them in the token stream.
///
/// '::'[opt] nested-name-specifier
/// '::'
///
/// nested-name-specifier:
/// type-name '::'
/// namespace-name '::'
/// nested-name-specifier identifier '::'
/// nested-name-specifier 'template'[opt] simple-template-id '::'
///
///
/// \param SS the scope specifier that will be set to the parsed
/// nested-name-specifier (or empty)
///
/// \param ObjectType if this nested-name-specifier is being parsed following
/// the "." or "->" of a member access expression, this parameter provides the
/// type of the object whose members are being accessed.
///
/// \param EnteringContext whether we will be entering into the context of
/// the nested-name-specifier after parsing it.
///
/// \param MayBePseudoDestructor When non-NULL, points to a flag that
/// indicates whether this nested-name-specifier may be part of a
/// pseudo-destructor name. In this case, the flag will be set false
/// if we don't actually end up parsing a destructor name. Moreorover,
/// if we do end up determining that we are parsing a destructor name,
/// the last component of the nested-name-specifier is not parsed as
/// part of the scope specifier.
///
/// \param IsTypename If \c true, this nested-name-specifier is known to be
/// part of a type name. This is used to improve error recovery.
///
/// \param LastII When non-NULL, points to an IdentifierInfo* that will be
/// filled in with the leading identifier in the last component of the
/// nested-name-specifier, if any.
///
/// \param OnlyNamespace If true, only considers namespaces in lookup.
///
/// \returns true if there was an error parsing a scope specifier
bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
ParsedType ObjectType,
bool EnteringContext,
bool *MayBePseudoDestructor,
bool IsTypename,
IdentifierInfo **LastII,
bool OnlyNamespace) {
assert(getLangOpts().CPlusPlus &&
"Call sites of this function should be guarded by checking for C++");
if (Tok.is(tok::annot_cxxscope)) {
assert(!LastII && "want last identifier but have already annotated scope");
assert(!MayBePseudoDestructor && "unexpected annot_cxxscope");
Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
Tok.getAnnotationRange(),
SS);
ConsumeAnnotationToken();
return false;
}
if (Tok.is(tok::annot_template_id)) {
// If the current token is an annotated template id, it may already have
// a scope specifier. Restore it.
TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
SS = TemplateId->SS;
}
// Has to happen before any "return false"s in this function.
bool CheckForDestructor = false;
if (MayBePseudoDestructor && *MayBePseudoDestructor) {
CheckForDestructor = true;
*MayBePseudoDestructor = false;
}
if (LastII)
*LastII = nullptr;
bool HasScopeSpecifier = false;
if (Tok.is(tok::coloncolon)) {
// ::new and ::delete aren't nested-name-specifiers.
tok::TokenKind NextKind = NextToken().getKind();
if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
return false;
if (NextKind == tok::l_brace) {
// It is invalid to have :: {, consume the scope qualifier and pretend
// like we never saw it.
Diag(ConsumeToken(), diag::err_expected) << tok::identifier;
} else {
// '::' - Global scope qualifier.
if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
return true;
HasScopeSpecifier = true;
}
}
if (Tok.is(tok::kw___super)) {
SourceLocation SuperLoc = ConsumeToken();
if (!Tok.is(tok::coloncolon)) {
Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
return true;
}
return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
}
if (!HasScopeSpecifier &&
Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
DeclSpec DS(AttrFactory);
SourceLocation DeclLoc = Tok.getLocation();
SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
SourceLocation CCLoc;
// Work around a standard defect: 'decltype(auto)::' is not a
// nested-name-specifier.
if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto ||
!TryConsumeToken(tok::coloncolon, CCLoc)) {
AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
return false;
}
if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
HasScopeSpecifier = true;
}
while (true) {
if (HasScopeSpecifier) {
// C++ [basic.lookup.classref]p5:
// If the qualified-id has the form
//
// ::class-name-or-namespace-name::...
//
// the class-name-or-namespace-name is looked up in global scope as a
// class-name or namespace-name.
//
// To implement this, we clear out the object type as soon as we've
// seen a leading '::' or part of a nested-name-specifier.
ObjectType = nullptr;
if (Tok.is(tok::code_completion)) {
// Code completion for a nested-name-specifier, where the code
// completion token follows the '::'.
Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
// Include code completion token into the range of the scope otherwise
// when we try to annotate the scope tokens the dangling code completion
// token will cause assertion in
// Preprocessor::AnnotatePreviousCachedTokens.
SS.setEndLoc(Tok.getLocation());
cutOffParsing();
return true;
}
}
// nested-name-specifier:
// nested-name-specifier 'template'[opt] simple-template-id '::'
// Parse the optional 'template' keyword, then make sure we have
// 'identifier <' after it.
if (Tok.is(tok::kw_template)) {
// If we don't have a scope specifier or an object type, this isn't a
// nested-name-specifier, since they aren't allowed to start with
// 'template'.
if (!HasScopeSpecifier && !ObjectType)
break;
TentativeParsingAction TPA(*this);
SourceLocation TemplateKWLoc = ConsumeToken();
UnqualifiedId TemplateName;
if (Tok.is(tok::identifier)) {
// Consume the identifier.
TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
ConsumeToken();
} else if (Tok.is(tok::kw_operator)) {
// We don't need to actually parse the unqualified-id in this case,
// because a simple-template-id cannot start with 'operator', but
// go ahead and parse it anyway for consistency with the case where
// we already annotated the template-id.
if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
TemplateName)) {
TPA.Commit();
break;
}
if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
Diag(TemplateName.getSourceRange().getBegin(),
diag::err_id_after_template_in_nested_name_spec)
<< TemplateName.getSourceRange();
TPA.Commit();
break;
}
} else {
TPA.Revert();
break;
}
// If the next token is not '<', we have a qualified-id that refers
// to a template name, such as T::template apply, but is not a
// template-id.
if (Tok.isNot(tok::less)) {
TPA.Revert();
break;
}
// Commit to parsing the template-id.
TPA.Commit();
TemplateTy Template;
if (TemplateNameKind TNK = Actions.ActOnDependentTemplateName(
getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
EnteringContext, Template, /*AllowInjectedClassName*/ true)) {
if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
TemplateName, false))
return true;
} else
return true;
continue;
}
if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
// We have
//
// template-id '::'
//
// So we need to check whether the template-id is a simple-template-id of
// the right kind (it should name a type or be dependent), and then
// convert it into a type within the nested-name-specifier.
TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
*MayBePseudoDestructor = true;
return false;
}
if (LastII)
*LastII = TemplateId->Name;
// Consume the template-id token.
ConsumeAnnotationToken();
assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
SourceLocation CCLoc = ConsumeToken();
HasScopeSpecifier = true;
ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
TemplateId->NumArgs);
if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
SS,
TemplateId->TemplateKWLoc,
TemplateId->Template,
TemplateId->TemplateNameLoc,
TemplateId->LAngleLoc,
TemplateArgsPtr,
TemplateId->RAngleLoc,
CCLoc,
EnteringContext)) {
SourceLocation StartLoc
= SS.getBeginLoc().isValid()? SS.getBeginLoc()
: TemplateId->TemplateNameLoc;
SS.SetInvalid(SourceRange(StartLoc, CCLoc));
}
continue;
}
// The rest of the nested-name-specifier possibilities start with
// tok::identifier.
if (Tok.isNot(tok::identifier))
break;
IdentifierInfo &II = *Tok.getIdentifierInfo();
// nested-name-specifier:
// type-name '::'
// namespace-name '::'
// nested-name-specifier identifier '::'
Token Next = NextToken();
Sema::NestedNameSpecInfo IdInfo(&II, Tok.getLocation(), Next.getLocation(),
ObjectType);
// If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
// and emit a fixit hint for it.
if (Next.is(tok::colon) && !ColonIsSacred) {
if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, IdInfo,
EnteringContext) &&
// If the token after the colon isn't an identifier, it's still an
// error, but they probably meant something else strange so don't
// recover like this.
PP.LookAhead(1).is(tok::identifier)) {
Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
<< FixItHint::CreateReplacement(Next.getLocation(), "::");
// Recover as if the user wrote '::'.
Next.setKind(tok::coloncolon);
}
}
if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) {
// It is invalid to have :: {, consume the scope qualifier and pretend
// like we never saw it.
Token Identifier = Tok; // Stash away the identifier.
ConsumeToken(); // Eat the identifier, current token is now '::'.
Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected)
<< tok::identifier;
UnconsumeToken(Identifier); // Stick the identifier back.
Next = NextToken(); // Point Next at the '{' token.
}
if (Next.is(tok::coloncolon)) {
if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
!Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, IdInfo)) {
*MayBePseudoDestructor = true;
return false;
}
if (ColonIsSacred) {
const Token &Next2 = GetLookAheadToken(2);
if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
<< Next2.getName()
<< FixItHint::CreateReplacement(Next.getLocation(), ":");
Token ColonColon;
PP.Lex(ColonColon);
ColonColon.setKind(tok::colon);
PP.EnterToken(ColonColon);
break;
}
}
if (LastII)
*LastII = &II;
// We have an identifier followed by a '::'. Lookup this name
// as the name in a nested-name-specifier.
Token Identifier = Tok;
SourceLocation IdLoc = ConsumeToken();
assert(Tok.isOneOf(tok::coloncolon, tok::colon) &&
"NextToken() not working properly!");
Token ColonColon = Tok;
SourceLocation CCLoc = ConsumeToken();
bool IsCorrectedToColon = false;
bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
if (Actions.ActOnCXXNestedNameSpecifier(
getCurScope(), IdInfo, EnteringContext, SS, false,
CorrectionFlagPtr, OnlyNamespace)) {
// Identifier is not recognized as a nested name, but we can have
// mistyped '::' instead of ':'.
if (CorrectionFlagPtr && IsCorrectedToColon) {
ColonColon.setKind(tok::colon);
PP.EnterToken(Tok);
PP.EnterToken(ColonColon);
Tok = Identifier;
break;
}
SS.SetInvalid(SourceRange(IdLoc, CCLoc));
}
HasScopeSpecifier = true;
continue;
}
CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
// nested-name-specifier:
// type-name '<'
if (Next.is(tok::less)) {
TemplateTy Template;
UnqualifiedId TemplateName;
TemplateName.setIdentifier(&II, Tok.getLocation());
bool MemberOfUnknownSpecialization;
if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
/*hasTemplateKeyword=*/false,
TemplateName,
ObjectType,
EnteringContext,
Template,
MemberOfUnknownSpecialization)) {
// We have found a template name, so annotate this token
// with a template-id annotation. We do not permit the
// template-id to be translated into a type annotation,
// because some clients (e.g., the parsing of class template
// specializations) still want to see the original template-id
// token.
ConsumeToken();
if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
TemplateName, false))
return true;
continue;
}
if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
(IsTypename || IsTemplateArgumentList(1))) {
// We have something like t::getAs<T>, where getAs is a
// member of an unknown specialization. However, this will only
// parse correctly as a template, so suggest the keyword 'template'
// before 'getAs' and treat this as a dependent template name.
unsigned DiagID = diag::err_missing_dependent_template_keyword;
if (getLangOpts().MicrosoftExt)
DiagID = diag::warn_missing_dependent_template_keyword;
Diag(Tok.getLocation(), DiagID)
<< II.getName()
<< FixItHint::CreateInsertion(Tok.getLocation(), "template ");
if (TemplateNameKind TNK = Actions.ActOnDependentTemplateName(
getCurScope(), SS, SourceLocation(), TemplateName, ObjectType,
EnteringContext, Template, /*AllowInjectedClassName*/ true)) {
// Consume the identifier.
ConsumeToken();
if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
TemplateName, false))
return true;
}
else
return true;
continue;
}
}
// We don't have any tokens that form the beginning of a
// nested-name-specifier, so we're done.
break;
}
// Even if we didn't see any pieces of a nested-name-specifier, we
// still check whether there is a tilde in this position, which
// indicates a potential pseudo-destructor.
if (CheckForDestructor && Tok.is(tok::tilde))
*MayBePseudoDestructor = true;
return false;
}
ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
Token &Replacement) {
SourceLocation TemplateKWLoc;
UnqualifiedId Name;
if (ParseUnqualifiedId(SS,
/*EnteringContext=*/false,
/*AllowDestructorName=*/false,
/*AllowConstructorName=*/false,
/*AllowDeductionGuide=*/false,
/*ObjectType=*/nullptr, TemplateKWLoc, Name))
return ExprError();
// This is only the direct operand of an & operator if it is not
// followed by a postfix-expression suffix.
if (isAddressOfOperand && isPostfixExpressionSuffixStart())
isAddressOfOperand = false;
return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
Tok.is(tok::l_paren), isAddressOfOperand,
nullptr, /*IsInlineAsmIdentifier=*/false,
&Replacement);
}
/// ParseCXXIdExpression - Handle id-expression.
///
/// id-expression:
/// unqualified-id
/// qualified-id
///
/// qualified-id:
/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
/// '::' identifier
/// '::' operator-function-id
/// '::' template-id
///
/// NOTE: The standard specifies that, for qualified-id, the parser does not
/// expect:
///
/// '::' conversion-function-id
/// '::' '~' class-name
///
/// This may cause a slight inconsistency on diagnostics:
///
/// class C {};
/// namespace A {}
/// void f() {
/// :: A :: ~ C(); // Some Sema error about using destructor with a
/// // namespace.
/// :: ~ C(); // Some Parser error like 'unexpected ~'.
/// }
///
/// We simplify the parser a bit and make it work like:
///
/// qualified-id:
/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
/// '::' unqualified-id
///
/// That way Sema can handle and report similar errors for namespaces and the
/// global scope.
///
/// The isAddressOfOperand parameter indicates that this id-expression is a
/// direct operand of the address-of operator. This is, besides member contexts,
/// the only place where a qualified-id naming a non-static class member may
/// appear.
///
ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
// qualified-id:
// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
// '::' unqualified-id
//
CXXScopeSpec SS;
ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
Token Replacement;
ExprResult Result =
tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
if (Result.isUnset()) {
// If the ExprResult is valid but null, then typo correction suggested a
// keyword replacement that needs to be reparsed.
UnconsumeToken(Replacement);
Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
}
assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "
"for a previous keyword suggestion");
return Result;
}
/// ParseLambdaExpression - Parse a C++11 lambda expression.
///
/// lambda-expression:
/// lambda-introducer lambda-declarator[opt] compound-statement
///
/// lambda-introducer:
/// '[' lambda-capture[opt] ']'
///
/// lambda-capture:
/// capture-default
/// capture-list
/// capture-default ',' capture-list
///
/// capture-default:
/// '&'
/// '='
///
/// capture-list:
/// capture
/// capture-list ',' capture
///
/// capture:
/// simple-capture
/// init-capture [C++1y]
///
/// simple-capture:
/// identifier
/// '&' identifier
/// 'this'
///
/// init-capture: [C++1y]
/// identifier initializer
/// '&' identifier initializer
///
/// lambda-declarator:
/// '(' parameter-declaration-clause ')' attribute-specifier[opt]
/// 'mutable'[opt] exception-specification[opt]
/// trailing-return-type[opt]
///
ExprResult Parser::ParseLambdaExpression() {
// Parse lambda-introducer.
LambdaIntroducer Intro;
Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
if (DiagID) {
Diag(Tok, DiagID.getValue());
SkipUntil(tok::r_square, StopAtSemi);
SkipUntil(tok::l_brace, StopAtSemi);
SkipUntil(tok::r_brace, StopAtSemi);
return ExprError();
}
return ParseLambdaExpressionAfterIntroducer(Intro);
}
/// TryParseLambdaExpression - Use lookahead and potentially tentative
/// parsing to determine if we are looking at a C++0x lambda expression, and parse
/// it if we are.
///
/// If we are not looking at a lambda expression, returns ExprError().
ExprResult Parser::TryParseLambdaExpression() {
assert(getLangOpts().CPlusPlus11
&& Tok.is(tok::l_square)
&& "Not at the start of a possible lambda expression.");
const Token Next = NextToken();
if (Next.is(tok::eof)) // Nothing else to lookup here...
return ExprEmpty();
const Token After = GetLookAheadToken(2);
// If lookahead indicates this is a lambda...
if (Next.is(tok::r_square) || // []
Next.is(tok::equal) || // [=
(Next.is(tok::amp) && // [&] or [&,
(After.is(tok::r_square) ||
After.is(tok::comma))) ||
(Next.is(tok::identifier) && // [identifier]
After.is(tok::r_square))) {
return ParseLambdaExpression();
}
// If lookahead indicates an ObjC message send...
// [identifier identifier
if (Next.is(tok::identifier) && After.is(tok::identifier)) {
return ExprEmpty();
}
// Here, we're stuck: lambda introducers and Objective-C message sends are
// unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
// lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
// writing two routines to parse a lambda introducer, just try to parse
// a lambda introducer first, and fall back if that fails.
// (TryParseLambdaIntroducer never produces any diagnostic output.)
LambdaIntroducer Intro;
if (TryParseLambdaIntroducer(Intro))
return ExprEmpty();
return ParseLambdaExpressionAfterIntroducer(Intro);
}
/// \brief Parse a lambda introducer.
/// \param Intro A LambdaIntroducer filled in with information about the
/// contents of the lambda-introducer.
/// \param SkippedInits If non-null, we are disambiguating between an Obj-C
/// message send and a lambda expression. In this mode, we will
/// sometimes skip the initializers for init-captures and not fully
/// populate \p Intro. This flag will be set to \c true if we do so.
/// \return A DiagnosticID if it hit something unexpected. The location for
/// the diagnostic is that of the current token.
Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
bool *SkippedInits) {
typedef Optional<unsigned> DiagResult;
assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
BalancedDelimiterTracker T(*this, tok::l_square);
T.consumeOpen();
Intro.Range.setBegin(T.getOpenLocation());
bool first = true;
// Parse capture-default.
if (Tok.is(tok::amp) &&
(NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
Intro.Default = LCD_ByRef;
Intro.DefaultLoc = ConsumeToken();
first = false;
} else if (Tok.is(tok::equal)) {
Intro.Default = LCD_ByCopy;
Intro.DefaultLoc = ConsumeToken();
first = false;
}
while (Tok.isNot(tok::r_square)) {
if (!first) {
if (Tok.isNot(tok::comma)) {
// Provide a completion for a lambda introducer here. Except
// in Objective-C, where this is Almost Surely meant to be a message
// send. In that case, fail here and let the ObjC message
// expression parser perform the completion.
if (Tok.is(tok::code_completion) &&
!(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
!Intro.Captures.empty())) {
Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
/*AfterAmpersand=*/false);
cutOffParsing();
break;
}
return DiagResult(diag::err_expected_comma_or_rsquare);
}
ConsumeToken();
}
if (Tok.is(tok::code_completion)) {
// If we're in Objective-C++ and we have a bare '[', then this is more
// likely to be a message receiver.
if (getLangOpts().ObjC1 && first)
Actions.CodeCompleteObjCMessageReceiver(getCurScope());
else
Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
/*AfterAmpersand=*/false);
cutOffParsing();
break;
}
first = false;
// Parse capture.
LambdaCaptureKind Kind = LCK_ByCopy;
LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit;
SourceLocation Loc;
IdentifierInfo *Id = nullptr;
SourceLocation EllipsisLoc;
ExprResult Init;
if (Tok.is(tok::star)) {
Loc = ConsumeToken();
if (Tok.is(tok::kw_this)) {
ConsumeToken();
Kind = LCK_StarThis;
} else {
return DiagResult(diag::err_expected_star_this_capture);
}
} else if (Tok.is(tok::kw_this)) {
Kind = LCK_This;
Loc = ConsumeToken();
} else {
if (Tok.is(tok::amp)) {
Kind = LCK_ByRef;
ConsumeToken();
if (Tok.is(tok::code_completion)) {
Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
/*AfterAmpersand=*/true);
cutOffParsing();
break;
}
}
if (Tok.is(tok::identifier)) {
Id = Tok.getIdentifierInfo();
Loc = ConsumeToken();
} else if (Tok.is(tok::kw_this)) {
// FIXME: If we want to suggest a fixit here, will need to return more
// than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
// Clear()ed to prevent emission in case of tentative parsing?
return DiagResult(diag::err_this_captured_by_reference);
} else {
return DiagResult(diag::err_expected_capture);
}
if (Tok.is(tok::l_paren)) {
BalancedDelimiterTracker Parens(*this, tok::l_paren);
Parens.consumeOpen();
InitKind = LambdaCaptureInitKind::DirectInit;
ExprVector Exprs;
CommaLocsTy Commas;
if (SkippedInits) {
Parens.skipToEnd();
*SkippedInits = true;
} else if (ParseExpressionList(Exprs, Commas)) {
Parens.skipToEnd();
Init = ExprError();
} else {
Parens.consumeClose();
Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
Parens.getCloseLocation(),
Exprs);
}
} else if (Tok.isOneOf(tok::l_brace, tok::equal)) {
// Each lambda init-capture forms its own full expression, which clears
// Actions.MaybeODRUseExprs. So create an expression evaluation context
// to save the necessary state, and restore it later.
EnterExpressionEvaluationContext EC(
Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
if (TryConsumeToken(tok::equal))
InitKind = LambdaCaptureInitKind::CopyInit;
else
InitKind = LambdaCaptureInitKind::ListInit;
if (!SkippedInits) {
Init = ParseInitializer();
} else if (Tok.is(tok::l_brace)) {
BalancedDelimiterTracker Braces(*this, tok::l_brace);
Braces.consumeOpen();
Braces.skipToEnd();
*SkippedInits = true;
} else {
// We're disambiguating this:
//
// [..., x = expr
//
// We need to find the end of the following expression in order to
// determine whether this is an Obj-C message send's receiver, a
// C99 designator, or a lambda init-capture.
//
// Parse the expression to find where it ends, and annotate it back
// onto the tokens. We would have parsed this expression the same way
// in either case: both the RHS of an init-capture and the RHS of an
// assignment expression are parsed as an initializer-clause, and in
// neither case can anything be added to the scope between the '[' and
// here.
//
// FIXME: This is horrible. Adding a mechanism to skip an expression
// would be much cleaner.
// FIXME: If there is a ',' before the next ']' or ':', we can skip to
// that instead. (And if we see a ':' with no matching '?', we can
// classify this as an Obj-C message send.)
SourceLocation StartLoc = Tok.getLocation();
InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
Init = ParseInitializer();
if (!Init.isInvalid())
Init = Actions.CorrectDelayedTyposInExpr(Init.get());
if (Tok.getLocation() != StartLoc) {
// Back out the lexing of the token after the initializer.
PP.RevertCachedTokens(1);
// Replace the consumed tokens with an appropriate annotation.
Tok.setLocation(StartLoc);
Tok.setKind(tok::annot_primary_expr);
setExprAnnotation(Tok, Init);
Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
PP.AnnotateCachedTokens(Tok);
// Consume the annotated initializer.
ConsumeAnnotationToken();
}
}
} else
TryConsumeToken(tok::ellipsis, EllipsisLoc);
}
// If this is an init capture, process the initialization expression
// right away. For lambda init-captures such as the following:
// const int x = 10;
// auto L = [i = x+1](int a) {
// return [j = x+2,
// &k = x](char b) { };
// };
// keep in mind that each lambda init-capture has to have:
// - its initialization expression executed in the context
// of the enclosing/parent decl-context.
// - but the variable itself has to be 'injected' into the
// decl-context of its lambda's call-operator (which has
// not yet been created).
// Each init-expression is a full-expression that has to get
// Sema-analyzed (for capturing etc.) before its lambda's
// call-operator's decl-context, scope & scopeinfo are pushed on their
// respective stacks. Thus if any variable is odr-used in the init-capture
// it will correctly get captured in the enclosing lambda, if one exists.
// The init-variables above are created later once the lambdascope and
// call-operators decl-context is pushed onto its respective stack.
// Since the lambda init-capture's initializer expression occurs in the
// context of the enclosing function or lambda, therefore we can not wait
// till a lambda scope has been pushed on before deciding whether the
// variable needs to be captured. We also need to process all
// lvalue-to-rvalue conversions and discarded-value conversions,
// so that we can avoid capturing certain constant variables.
// For e.g.,
// void test() {
// const int x = 10;
// auto L = [&z = x](char a) { <-- don't capture by the current lambda
// return [y = x](int i) { <-- don't capture by enclosing lambda
// return y;
// }
// };
// }
// If x was not const, the second use would require 'L' to capture, and
// that would be an error.
ParsedType InitCaptureType;
if (!Init.isInvalid())
Init = Actions.CorrectDelayedTyposInExpr(Init.get());
if (Init.isUsable()) {
// Get the pointer and store it in an lvalue, so we can use it as an
// out argument.
Expr *InitExpr = Init.get();
// This performs any lvalue-to-rvalue conversions if necessary, which
// can affect what gets captured in the containing decl-context.
InitCaptureType = Actions.actOnLambdaInitCaptureInitialization(
Loc, Kind == LCK_ByRef, Id, InitKind, InitExpr);
Init = InitExpr;
}
Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
InitCaptureType);
}
T.consumeClose();
Intro.Range.setEnd(T.getCloseLocation());
return DiagResult();
}
/// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
///
/// Returns true if it hit something unexpected.
bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
{
bool SkippedInits = false;
TentativeParsingAction PA1(*this);
if (ParseLambdaIntroducer(Intro, &SkippedInits)) {
PA1.Revert();
return true;