-
Notifications
You must be signed in to change notification settings - Fork 12.6k
/
Copy pathParseExpr.cpp
3913 lines (3569 loc) · 147 KB
/
ParseExpr.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
//===--- ParseExpr.cpp - Expression Parsing -------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
///
/// \file
/// Provides the Expression parsing implementation.
///
/// Expressions in C99 basically consist of a bunch of binary operators with
/// unary operators and other random stuff at the leaves.
///
/// In the C99 grammar, these unary operators bind tightest and are represented
/// as the 'cast-expression' production. Everything else is either a binary
/// operator (e.g. '/') or a ternary operator ("?:"). The unary leaves are
/// handled by ParseCastExpression, the higher level pieces are handled by
/// ParseBinaryExpression.
///
//===----------------------------------------------------------------------===//
#include "clang/AST/ASTContext.h"
#include "clang/AST/ExprCXX.h"
#include "clang/Basic/PrettyStackTrace.h"
#include "clang/Lex/LiteralSupport.h"
#include "clang/Parse/Parser.h"
#include "clang/Parse/RAIIObjectsForParser.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/EnterExpressionEvaluationContext.h"
#include "clang/Sema/ParsedTemplate.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/TypoCorrection.h"
#include "llvm/ADT/SmallVector.h"
#include <optional>
using namespace clang;
/// Simple precedence-based parser for binary/ternary operators.
///
/// Note: we diverge from the C99 grammar when parsing the assignment-expression
/// production. C99 specifies that the LHS of an assignment operator should be
/// parsed as a unary-expression, but consistency dictates that it be a
/// conditional-expession. In practice, the important thing here is that the
/// LHS of an assignment has to be an l-value, which productions between
/// unary-expression and conditional-expression don't produce. Because we want
/// consistency, we parse the LHS as a conditional-expression, then check for
/// l-value-ness in semantic analysis stages.
///
/// \verbatim
/// pm-expression: [C++ 5.5]
/// cast-expression
/// pm-expression '.*' cast-expression
/// pm-expression '->*' cast-expression
///
/// multiplicative-expression: [C99 6.5.5]
/// Note: in C++, apply pm-expression instead of cast-expression
/// cast-expression
/// multiplicative-expression '*' cast-expression
/// multiplicative-expression '/' cast-expression
/// multiplicative-expression '%' cast-expression
///
/// additive-expression: [C99 6.5.6]
/// multiplicative-expression
/// additive-expression '+' multiplicative-expression
/// additive-expression '-' multiplicative-expression
///
/// shift-expression: [C99 6.5.7]
/// additive-expression
/// shift-expression '<<' additive-expression
/// shift-expression '>>' additive-expression
///
/// compare-expression: [C++20 expr.spaceship]
/// shift-expression
/// compare-expression '<=>' shift-expression
///
/// relational-expression: [C99 6.5.8]
/// compare-expression
/// relational-expression '<' compare-expression
/// relational-expression '>' compare-expression
/// relational-expression '<=' compare-expression
/// relational-expression '>=' compare-expression
///
/// equality-expression: [C99 6.5.9]
/// relational-expression
/// equality-expression '==' relational-expression
/// equality-expression '!=' relational-expression
///
/// AND-expression: [C99 6.5.10]
/// equality-expression
/// AND-expression '&' equality-expression
///
/// exclusive-OR-expression: [C99 6.5.11]
/// AND-expression
/// exclusive-OR-expression '^' AND-expression
///
/// inclusive-OR-expression: [C99 6.5.12]
/// exclusive-OR-expression
/// inclusive-OR-expression '|' exclusive-OR-expression
///
/// logical-AND-expression: [C99 6.5.13]
/// inclusive-OR-expression
/// logical-AND-expression '&&' inclusive-OR-expression
///
/// logical-OR-expression: [C99 6.5.14]
/// logical-AND-expression
/// logical-OR-expression '||' logical-AND-expression
///
/// conditional-expression: [C99 6.5.15]
/// logical-OR-expression
/// logical-OR-expression '?' expression ':' conditional-expression
/// [GNU] logical-OR-expression '?' ':' conditional-expression
/// [C++] the third operand is an assignment-expression
///
/// assignment-expression: [C99 6.5.16]
/// conditional-expression
/// unary-expression assignment-operator assignment-expression
/// [C++] throw-expression [C++ 15]
///
/// assignment-operator: one of
/// = *= /= %= += -= <<= >>= &= ^= |=
///
/// expression: [C99 6.5.17]
/// assignment-expression ...[opt]
/// expression ',' assignment-expression ...[opt]
/// \endverbatim
ExprResult Parser::ParseExpression(TypeCastState isTypeCast) {
ExprResult LHS(ParseAssignmentExpression(isTypeCast));
return ParseRHSOfBinaryExpression(LHS, prec::Comma);
}
/// This routine is called when the '@' is seen and consumed.
/// Current token is an Identifier and is not a 'try'. This
/// routine is necessary to disambiguate \@try-statement from,
/// for example, \@encode-expression.
///
ExprResult
Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
ExprResult LHS(ParseObjCAtExpression(AtLoc));
return ParseRHSOfBinaryExpression(LHS, prec::Comma);
}
/// This routine is called when a leading '__extension__' is seen and
/// consumed. This is necessary because the token gets consumed in the
/// process of disambiguating between an expression and a declaration.
ExprResult
Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) {
ExprResult LHS(true);
{
// Silence extension warnings in the sub-expression
ExtensionRAIIObject O(Diags);
LHS = ParseCastExpression(AnyCastExpr);
}
if (!LHS.isInvalid())
LHS = Actions.ActOnUnaryOp(getCurScope(), ExtLoc, tok::kw___extension__,
LHS.get());
return ParseRHSOfBinaryExpression(LHS, prec::Comma);
}
/// Parse an expr that doesn't include (top-level) commas.
ExprResult Parser::ParseAssignmentExpression(TypeCastState isTypeCast) {
if (Tok.is(tok::code_completion)) {
cutOffParsing();
Actions.CodeCompleteExpression(getCurScope(),
PreferredType.get(Tok.getLocation()));
return ExprError();
}
if (Tok.is(tok::kw_throw))
return ParseThrowExpression();
if (Tok.is(tok::kw_co_yield))
return ParseCoyieldExpression();
ExprResult LHS = ParseCastExpression(AnyCastExpr,
/*isAddressOfOperand=*/false,
isTypeCast);
return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
}
/// Parse an assignment expression where part of an Objective-C message
/// send has already been parsed.
///
/// In this case \p LBracLoc indicates the location of the '[' of the message
/// send, and either \p ReceiverName or \p ReceiverExpr is non-null indicating
/// the receiver of the message.
///
/// Since this handles full assignment-expression's, it handles postfix
/// expressions and other binary operators for these expressions as well.
ExprResult
Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc,
SourceLocation SuperLoc,
ParsedType ReceiverType,
Expr *ReceiverExpr) {
ExprResult R
= ParseObjCMessageExpressionBody(LBracLoc, SuperLoc,
ReceiverType, ReceiverExpr);
R = ParsePostfixExpressionSuffix(R);
return ParseRHSOfBinaryExpression(R, prec::Assignment);
}
ExprResult
Parser::ParseConstantExpressionInExprEvalContext(TypeCastState isTypeCast) {
assert(Actions.ExprEvalContexts.back().Context ==
Sema::ExpressionEvaluationContext::ConstantEvaluated &&
"Call this function only if your ExpressionEvaluationContext is "
"already ConstantEvaluated");
ExprResult LHS(ParseCastExpression(AnyCastExpr, false, isTypeCast));
ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
return Actions.ActOnConstantExpression(Res);
}
ExprResult Parser::ParseConstantExpression() {
// C++03 [basic.def.odr]p2:
// An expression is potentially evaluated unless it appears where an
// integral constant expression is required (see 5.19) [...].
// C++98 and C++11 have no such rule, but this is only a defect in C++98.
EnterExpressionEvaluationContext ConstantEvaluated(
Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
return ParseConstantExpressionInExprEvalContext(NotTypeCast);
}
ExprResult Parser::ParseArrayBoundExpression() {
EnterExpressionEvaluationContext ConstantEvaluated(
Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
// If we parse the bound of a VLA... we parse a non-constant
// constant-expression!
Actions.ExprEvalContexts.back().InConditionallyConstantEvaluateContext = true;
return ParseConstantExpressionInExprEvalContext(NotTypeCast);
}
ExprResult Parser::ParseCaseExpression(SourceLocation CaseLoc) {
EnterExpressionEvaluationContext ConstantEvaluated(
Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
ExprResult LHS(ParseCastExpression(AnyCastExpr, false, NotTypeCast));
ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
return Actions.ActOnCaseExpr(CaseLoc, Res);
}
/// Parse a constraint-expression.
///
/// \verbatim
/// constraint-expression: C++2a[temp.constr.decl]p1
/// logical-or-expression
/// \endverbatim
ExprResult Parser::ParseConstraintExpression() {
EnterExpressionEvaluationContext ConstantEvaluated(
Actions, Sema::ExpressionEvaluationContext::Unevaluated);
ExprResult LHS(ParseCastExpression(AnyCastExpr));
ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::LogicalOr));
if (Res.isUsable() && !Actions.CheckConstraintExpression(Res.get())) {
Actions.CorrectDelayedTyposInExpr(Res);
return ExprError();
}
return Res;
}
/// \brief Parse a constraint-logical-and-expression.
///
/// \verbatim
/// C++2a[temp.constr.decl]p1
/// constraint-logical-and-expression:
/// primary-expression
/// constraint-logical-and-expression '&&' primary-expression
///
/// \endverbatim
ExprResult
Parser::ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause) {
EnterExpressionEvaluationContext ConstantEvaluated(
Actions, Sema::ExpressionEvaluationContext::Unevaluated);
bool NotPrimaryExpression = false;
auto ParsePrimary = [&] () {
ExprResult E = ParseCastExpression(PrimaryExprOnly,
/*isAddressOfOperand=*/false,
/*isTypeCast=*/NotTypeCast,
/*isVectorLiteral=*/false,
&NotPrimaryExpression);
if (E.isInvalid())
return ExprError();
auto RecoverFromNonPrimary = [&] (ExprResult E, bool Note) {
E = ParsePostfixExpressionSuffix(E);
// Use InclusiveOr, the precedence just after '&&' to not parse the
// next arguments to the logical and.
E = ParseRHSOfBinaryExpression(E, prec::InclusiveOr);
if (!E.isInvalid())
Diag(E.get()->getExprLoc(),
Note
? diag::note_unparenthesized_non_primary_expr_in_requires_clause
: diag::err_unparenthesized_non_primary_expr_in_requires_clause)
<< FixItHint::CreateInsertion(E.get()->getBeginLoc(), "(")
<< FixItHint::CreateInsertion(
PP.getLocForEndOfToken(E.get()->getEndLoc()), ")")
<< E.get()->getSourceRange();
return E;
};
if (NotPrimaryExpression ||
// Check if the following tokens must be a part of a non-primary
// expression
getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
/*CPlusPlus11=*/true) > prec::LogicalAnd ||
// Postfix operators other than '(' (which will be checked for in
// CheckConstraintExpression).
Tok.isOneOf(tok::period, tok::plusplus, tok::minusminus) ||
(Tok.is(tok::l_square) && !NextToken().is(tok::l_square))) {
E = RecoverFromNonPrimary(E, /*Note=*/false);
if (E.isInvalid())
return ExprError();
NotPrimaryExpression = false;
}
bool PossibleNonPrimary;
bool IsConstraintExpr =
Actions.CheckConstraintExpression(E.get(), Tok, &PossibleNonPrimary,
IsTrailingRequiresClause);
if (!IsConstraintExpr || PossibleNonPrimary) {
// Atomic constraint might be an unparenthesized non-primary expression
// (such as a binary operator), in which case we might get here (e.g. in
// 'requires 0 + 1 && true' we would now be at '+', and parse and ignore
// the rest of the addition expression). Try to parse the rest of it here.
if (PossibleNonPrimary)
E = RecoverFromNonPrimary(E, /*Note=*/!IsConstraintExpr);
Actions.CorrectDelayedTyposInExpr(E);
return ExprError();
}
return E;
};
ExprResult LHS = ParsePrimary();
if (LHS.isInvalid())
return ExprError();
while (Tok.is(tok::ampamp)) {
SourceLocation LogicalAndLoc = ConsumeToken();
ExprResult RHS = ParsePrimary();
if (RHS.isInvalid()) {
Actions.CorrectDelayedTyposInExpr(LHS);
return ExprError();
}
ExprResult Op = Actions.ActOnBinOp(getCurScope(), LogicalAndLoc,
tok::ampamp, LHS.get(), RHS.get());
if (!Op.isUsable()) {
Actions.CorrectDelayedTyposInExpr(RHS);
Actions.CorrectDelayedTyposInExpr(LHS);
return ExprError();
}
LHS = Op;
}
return LHS;
}
/// \brief Parse a constraint-logical-or-expression.
///
/// \verbatim
/// C++2a[temp.constr.decl]p1
/// constraint-logical-or-expression:
/// constraint-logical-and-expression
/// constraint-logical-or-expression '||'
/// constraint-logical-and-expression
///
/// \endverbatim
ExprResult
Parser::ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause) {
ExprResult LHS(ParseConstraintLogicalAndExpression(IsTrailingRequiresClause));
if (!LHS.isUsable())
return ExprError();
while (Tok.is(tok::pipepipe)) {
SourceLocation LogicalOrLoc = ConsumeToken();
ExprResult RHS =
ParseConstraintLogicalAndExpression(IsTrailingRequiresClause);
if (!RHS.isUsable()) {
Actions.CorrectDelayedTyposInExpr(LHS);
return ExprError();
}
ExprResult Op = Actions.ActOnBinOp(getCurScope(), LogicalOrLoc,
tok::pipepipe, LHS.get(), RHS.get());
if (!Op.isUsable()) {
Actions.CorrectDelayedTyposInExpr(RHS);
Actions.CorrectDelayedTyposInExpr(LHS);
return ExprError();
}
LHS = Op;
}
return LHS;
}
bool Parser::isNotExpressionStart() {
tok::TokenKind K = Tok.getKind();
if (K == tok::l_brace || K == tok::r_brace ||
K == tok::kw_for || K == tok::kw_while ||
K == tok::kw_if || K == tok::kw_else ||
K == tok::kw_goto || K == tok::kw_try)
return true;
// If this is a decl-specifier, we can't be at the start of an expression.
return isKnownToBeDeclarationSpecifier();
}
bool Parser::isFoldOperator(prec::Level Level) const {
return Level > prec::Unknown && Level != prec::Conditional &&
Level != prec::Spaceship;
}
bool Parser::isFoldOperator(tok::TokenKind Kind) const {
return isFoldOperator(getBinOpPrecedence(Kind, GreaterThanIsOperator, true));
}
/// Parse a binary expression that starts with \p LHS and has a
/// precedence of at least \p MinPrec.
ExprResult
Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) {
prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(),
GreaterThanIsOperator,
getLangOpts().CPlusPlus11);
SourceLocation ColonLoc;
auto SavedType = PreferredType;
while (true) {
// Every iteration may rely on a preferred type for the whole expression.
PreferredType = SavedType;
// If this token has a lower precedence than we are allowed to parse (e.g.
// because we are called recursively, or because the token is not a binop),
// then we are done!
if (NextTokPrec < MinPrec)
return LHS;
// Consume the operator, saving the operator token for error reporting.
Token OpToken = Tok;
ConsumeToken();
if (OpToken.is(tok::caretcaret)) {
return ExprError(Diag(Tok, diag::err_opencl_logical_exclusive_or));
}
// If we're potentially in a template-id, we may now be able to determine
// whether we're actually in one or not.
if (OpToken.isOneOf(tok::comma, tok::greater, tok::greatergreater,
tok::greatergreatergreater) &&
checkPotentialAngleBracketDelimiter(OpToken))
return ExprError();
// Bail out when encountering a comma followed by a token which can't
// possibly be the start of an expression. For instance:
// int f() { return 1, }
// We can't do this before consuming the comma, because
// isNotExpressionStart() looks at the token stream.
if (OpToken.is(tok::comma) && isNotExpressionStart()) {
PP.EnterToken(Tok, /*IsReinject*/true);
Tok = OpToken;
return LHS;
}
// If the next token is an ellipsis, then this is a fold-expression. Leave
// it alone so we can handle it in the paren expression.
if (isFoldOperator(NextTokPrec) && Tok.is(tok::ellipsis)) {
// FIXME: We can't check this via lookahead before we consume the token
// because that tickles a lexer bug.
PP.EnterToken(Tok, /*IsReinject*/true);
Tok = OpToken;
return LHS;
}
// In Objective-C++, alternative operator tokens can be used as keyword args
// in message expressions. Unconsume the token so that it can reinterpreted
// as an identifier in ParseObjCMessageExpressionBody. i.e., we support:
// [foo meth:0 and:0];
// [foo not_eq];
if (getLangOpts().ObjC && getLangOpts().CPlusPlus &&
Tok.isOneOf(tok::colon, tok::r_square) &&
OpToken.getIdentifierInfo() != nullptr) {
PP.EnterToken(Tok, /*IsReinject*/true);
Tok = OpToken;
return LHS;
}
// Special case handling for the ternary operator.
ExprResult TernaryMiddle(true);
if (NextTokPrec == prec::Conditional) {
if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
// Parse a braced-init-list here for error recovery purposes.
SourceLocation BraceLoc = Tok.getLocation();
TernaryMiddle = ParseBraceInitializer();
if (!TernaryMiddle.isInvalid()) {
Diag(BraceLoc, diag::err_init_list_bin_op)
<< /*RHS*/ 1 << PP.getSpelling(OpToken)
<< Actions.getExprRange(TernaryMiddle.get());
TernaryMiddle = ExprError();
}
} else if (Tok.isNot(tok::colon)) {
// Don't parse FOO:BAR as if it were a typo for FOO::BAR.
ColonProtectionRAIIObject X(*this);
// Handle this production specially:
// logical-OR-expression '?' expression ':' conditional-expression
// In particular, the RHS of the '?' is 'expression', not
// 'logical-OR-expression' as we might expect.
TernaryMiddle = ParseExpression();
} else {
// Special case handling of "X ? Y : Z" where Y is empty:
// logical-OR-expression '?' ':' conditional-expression [GNU]
TernaryMiddle = nullptr;
Diag(Tok, diag::ext_gnu_conditional_expr);
}
if (TernaryMiddle.isInvalid()) {
Actions.CorrectDelayedTyposInExpr(LHS);
LHS = ExprError();
TernaryMiddle = nullptr;
}
if (!TryConsumeToken(tok::colon, ColonLoc)) {
// Otherwise, we're missing a ':'. Assume that this was a typo that
// the user forgot. If we're not in a macro expansion, we can suggest
// a fixit hint. If there were two spaces before the current token,
// suggest inserting the colon in between them, otherwise insert ": ".
SourceLocation FILoc = Tok.getLocation();
const char *FIText = ": ";
const SourceManager &SM = PP.getSourceManager();
if (FILoc.isFileID() || PP.isAtStartOfMacroExpansion(FILoc, &FILoc)) {
assert(FILoc.isFileID());
bool IsInvalid = false;
const char *SourcePtr =
SM.getCharacterData(FILoc.getLocWithOffset(-1), &IsInvalid);
if (!IsInvalid && *SourcePtr == ' ') {
SourcePtr =
SM.getCharacterData(FILoc.getLocWithOffset(-2), &IsInvalid);
if (!IsInvalid && *SourcePtr == ' ') {
FILoc = FILoc.getLocWithOffset(-1);
FIText = ":";
}
}
}
Diag(Tok, diag::err_expected)
<< tok::colon << FixItHint::CreateInsertion(FILoc, FIText);
Diag(OpToken, diag::note_matching) << tok::question;
ColonLoc = Tok.getLocation();
}
}
PreferredType.enterBinary(Actions, Tok.getLocation(), LHS.get(),
OpToken.getKind());
// Parse another leaf here for the RHS of the operator.
// ParseCastExpression works here because all RHS expressions in C have it
// as a prefix, at least. However, in C++, an assignment-expression could
// be a throw-expression, which is not a valid cast-expression.
// Therefore we need some special-casing here.
// Also note that the third operand of the conditional operator is
// an assignment-expression in C++, and in C++11, we can have a
// braced-init-list on the RHS of an assignment. For better diagnostics,
// parse as if we were allowed braced-init-lists everywhere, and check that
// they only appear on the RHS of assignments later.
ExprResult RHS;
bool RHSIsInitList = false;
if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
RHS = ParseBraceInitializer();
RHSIsInitList = true;
} else if (getLangOpts().CPlusPlus && NextTokPrec <= prec::Conditional)
RHS = ParseAssignmentExpression();
else
RHS = ParseCastExpression(AnyCastExpr);
if (RHS.isInvalid()) {
// FIXME: Errors generated by the delayed typo correction should be
// printed before errors from parsing the RHS, not after.
Actions.CorrectDelayedTyposInExpr(LHS);
if (TernaryMiddle.isUsable())
TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
LHS = ExprError();
}
// Remember the precedence of this operator and get the precedence of the
// operator immediately to the right of the RHS.
prec::Level ThisPrec = NextTokPrec;
NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
getLangOpts().CPlusPlus11);
// Assignment and conditional expressions are right-associative.
bool isRightAssoc = ThisPrec == prec::Conditional ||
ThisPrec == prec::Assignment;
// Get the precedence of the operator to the right of the RHS. If it binds
// more tightly with RHS than we do, evaluate it completely first.
if (ThisPrec < NextTokPrec ||
(ThisPrec == NextTokPrec && isRightAssoc)) {
if (!RHS.isInvalid() && RHSIsInitList) {
Diag(Tok, diag::err_init_list_bin_op)
<< /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(RHS.get());
RHS = ExprError();
}
// If this is left-associative, only parse things on the RHS that bind
// more tightly than the current operator. If it is left-associative, it
// is okay, to bind exactly as tightly. For example, compile A=B=C=D as
// A=(B=(C=D)), where each paren is a level of recursion here.
// The function takes ownership of the RHS.
RHS = ParseRHSOfBinaryExpression(RHS,
static_cast<prec::Level>(ThisPrec + !isRightAssoc));
RHSIsInitList = false;
if (RHS.isInvalid()) {
// FIXME: Errors generated by the delayed typo correction should be
// printed before errors from ParseRHSOfBinaryExpression, not after.
Actions.CorrectDelayedTyposInExpr(LHS);
if (TernaryMiddle.isUsable())
TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
LHS = ExprError();
}
NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
getLangOpts().CPlusPlus11);
}
if (!RHS.isInvalid() && RHSIsInitList) {
if (ThisPrec == prec::Assignment) {
Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_lists)
<< Actions.getExprRange(RHS.get());
} else if (ColonLoc.isValid()) {
Diag(ColonLoc, diag::err_init_list_bin_op)
<< /*RHS*/1 << ":"
<< Actions.getExprRange(RHS.get());
LHS = ExprError();
} else {
Diag(OpToken, diag::err_init_list_bin_op)
<< /*RHS*/1 << PP.getSpelling(OpToken)
<< Actions.getExprRange(RHS.get());
LHS = ExprError();
}
}
ExprResult OrigLHS = LHS;
if (!LHS.isInvalid()) {
// Combine the LHS and RHS into the LHS (e.g. build AST).
if (TernaryMiddle.isInvalid()) {
// If we're using '>>' as an operator within a template
// argument list (in C++98), suggest the addition of
// parentheses so that the code remains well-formed in C++0x.
if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater))
SuggestParentheses(OpToken.getLocation(),
diag::warn_cxx11_right_shift_in_template_arg,
SourceRange(Actions.getExprRange(LHS.get()).getBegin(),
Actions.getExprRange(RHS.get()).getEnd()));
ExprResult BinOp =
Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(),
OpToken.getKind(), LHS.get(), RHS.get());
if (BinOp.isInvalid())
BinOp = Actions.CreateRecoveryExpr(LHS.get()->getBeginLoc(),
RHS.get()->getEndLoc(),
{LHS.get(), RHS.get()});
LHS = BinOp;
} else {
ExprResult CondOp = Actions.ActOnConditionalOp(
OpToken.getLocation(), ColonLoc, LHS.get(), TernaryMiddle.get(),
RHS.get());
if (CondOp.isInvalid()) {
std::vector<clang::Expr *> Args;
// TernaryMiddle can be null for the GNU conditional expr extension.
if (TernaryMiddle.get())
Args = {LHS.get(), TernaryMiddle.get(), RHS.get()};
else
Args = {LHS.get(), RHS.get()};
CondOp = Actions.CreateRecoveryExpr(LHS.get()->getBeginLoc(),
RHS.get()->getEndLoc(), Args);
}
LHS = CondOp;
}
// In this case, ActOnBinOp or ActOnConditionalOp performed the
// CorrectDelayedTyposInExpr check.
if (!getLangOpts().CPlusPlus)
continue;
}
// Ensure potential typos aren't left undiagnosed.
if (LHS.isInvalid()) {
Actions.CorrectDelayedTyposInExpr(OrigLHS);
Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
Actions.CorrectDelayedTyposInExpr(RHS);
}
}
}
/// Parse a cast-expression, unary-expression or primary-expression, based
/// on \p ExprType.
///
/// \p isAddressOfOperand exists because an id-expression that is the
/// operand of address-of gets special treatment due to member pointers.
///
ExprResult Parser::ParseCastExpression(CastParseKind ParseKind,
bool isAddressOfOperand,
TypeCastState isTypeCast,
bool isVectorLiteral,
bool *NotPrimaryExpression) {
bool NotCastExpr;
ExprResult Res = ParseCastExpression(ParseKind,
isAddressOfOperand,
NotCastExpr,
isTypeCast,
isVectorLiteral,
NotPrimaryExpression);
if (NotCastExpr)
Diag(Tok, diag::err_expected_expression);
return Res;
}
namespace {
class CastExpressionIdValidator final : public CorrectionCandidateCallback {
public:
CastExpressionIdValidator(Token Next, bool AllowTypes, bool AllowNonTypes)
: NextToken(Next), AllowNonTypes(AllowNonTypes) {
WantTypeSpecifiers = WantFunctionLikeCasts = AllowTypes;
}
bool ValidateCandidate(const TypoCorrection &candidate) override {
NamedDecl *ND = candidate.getCorrectionDecl();
if (!ND)
return candidate.isKeyword();
if (isa<TypeDecl>(ND))
return WantTypeSpecifiers;
if (!AllowNonTypes || !CorrectionCandidateCallback::ValidateCandidate(candidate))
return false;
if (!NextToken.isOneOf(tok::equal, tok::arrow, tok::period))
return true;
for (auto *C : candidate) {
NamedDecl *ND = C->getUnderlyingDecl();
if (isa<ValueDecl>(ND) && !isa<FunctionDecl>(ND))
return true;
}
return false;
}
std::unique_ptr<CorrectionCandidateCallback> clone() override {
return std::make_unique<CastExpressionIdValidator>(*this);
}
private:
Token NextToken;
bool AllowNonTypes;
};
}
/// Parse a cast-expression, or, if \pisUnaryExpression is true, parse
/// a unary-expression.
///
/// \p isAddressOfOperand exists because an id-expression that is the operand
/// of address-of gets special treatment due to member pointers. NotCastExpr
/// is set to true if the token is not the start of a cast-expression, and no
/// diagnostic is emitted in this case and no tokens are consumed.
///
/// \verbatim
/// cast-expression: [C99 6.5.4]
/// unary-expression
/// '(' type-name ')' cast-expression
///
/// unary-expression: [C99 6.5.3]
/// postfix-expression
/// '++' unary-expression
/// '--' unary-expression
/// [Coro] 'co_await' cast-expression
/// unary-operator cast-expression
/// 'sizeof' unary-expression
/// 'sizeof' '(' type-name ')'
/// [C++11] 'sizeof' '...' '(' identifier ')'
/// [GNU] '__alignof' unary-expression
/// [GNU] '__alignof' '(' type-name ')'
/// [C11] '_Alignof' '(' type-name ')'
/// [C++11] 'alignof' '(' type-id ')'
/// [GNU] '&&' identifier
/// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7]
/// [C++] new-expression
/// [C++] delete-expression
///
/// unary-operator: one of
/// '&' '*' '+' '-' '~' '!'
/// [GNU] '__extension__' '__real' '__imag'
///
/// primary-expression: [C99 6.5.1]
/// [C99] identifier
/// [C++] id-expression
/// constant
/// string-literal
/// [C++] boolean-literal [C++ 2.13.5]
/// [C++11] 'nullptr' [C++11 2.14.7]
/// [C++11] user-defined-literal
/// '(' expression ')'
/// [C11] generic-selection
/// [C++2a] requires-expression
/// '__func__' [C99 6.4.2.2]
/// [GNU] '__FUNCTION__'
/// [MS] '__FUNCDNAME__'
/// [MS] 'L__FUNCTION__'
/// [MS] '__FUNCSIG__'
/// [MS] 'L__FUNCSIG__'
/// [GNU] '__PRETTY_FUNCTION__'
/// [GNU] '(' compound-statement ')'
/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
/// assign-expr ')'
/// [GNU] '__builtin_FILE' '(' ')'
/// [CLANG] '__builtin_FILE_NAME' '(' ')'
/// [GNU] '__builtin_FUNCTION' '(' ')'
/// [MS] '__builtin_FUNCSIG' '(' ')'
/// [GNU] '__builtin_LINE' '(' ')'
/// [CLANG] '__builtin_COLUMN' '(' ')'
/// [GNU] '__builtin_source_location' '(' ')'
/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
/// [GNU] '__null'
/// [OBJC] '[' objc-message-expr ']'
/// [OBJC] '\@selector' '(' objc-selector-arg ')'
/// [OBJC] '\@protocol' '(' identifier ')'
/// [OBJC] '\@encode' '(' type-name ')'
/// [OBJC] objc-string-literal
/// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
/// [C++11] simple-type-specifier braced-init-list [C++11 5.2.3]
/// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
/// [C++11] typename-specifier braced-init-list [C++11 5.2.3]
/// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
/// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
/// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
/// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
/// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
/// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
/// [C++] 'this' [C++ 9.3.2]
/// [G++] unary-type-trait '(' type-id ')'
/// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO]
/// [EMBT] array-type-trait '(' type-id ',' integer ')'
/// [clang] '^' block-literal
///
/// constant: [C99 6.4.4]
/// integer-constant
/// floating-constant
/// enumeration-constant -> identifier
/// character-constant
///
/// id-expression: [C++ 5.1]
/// unqualified-id
/// qualified-id
///
/// unqualified-id: [C++ 5.1]
/// identifier
/// operator-function-id
/// conversion-function-id
/// '~' class-name
/// template-id
///
/// new-expression: [C++ 5.3.4]
/// '::'[opt] 'new' new-placement[opt] new-type-id
/// new-initializer[opt]
/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
/// new-initializer[opt]
///
/// delete-expression: [C++ 5.3.5]
/// '::'[opt] 'delete' cast-expression
/// '::'[opt] 'delete' '[' ']' cast-expression
///
/// [GNU/Embarcadero] unary-type-trait:
/// '__is_arithmetic'
/// '__is_floating_point'
/// '__is_integral'
/// '__is_lvalue_expr'
/// '__is_rvalue_expr'
/// '__is_complete_type'
/// '__is_void'
/// '__is_array'
/// '__is_function'
/// '__is_reference'
/// '__is_lvalue_reference'
/// '__is_rvalue_reference'
/// '__is_fundamental'
/// '__is_object'
/// '__is_scalar'
/// '__is_compound'
/// '__is_pointer'
/// '__is_member_object_pointer'
/// '__is_member_function_pointer'
/// '__is_member_pointer'
/// '__is_const'
/// '__is_volatile'
/// '__is_trivial'
/// '__is_standard_layout'
/// '__is_signed'
/// '__is_unsigned'
///
/// [GNU] unary-type-trait:
/// '__has_nothrow_assign'
/// '__has_nothrow_copy'
/// '__has_nothrow_constructor'
/// '__has_trivial_assign' [TODO]
/// '__has_trivial_copy' [TODO]
/// '__has_trivial_constructor'
/// '__has_trivial_destructor'
/// '__has_virtual_destructor'
/// '__is_abstract' [TODO]
/// '__is_class'
/// '__is_empty' [TODO]
/// '__is_enum'
/// '__is_final'
/// '__is_pod'
/// '__is_polymorphic'
/// '__is_sealed' [MS]
/// '__is_trivial'
/// '__is_union'
/// '__has_unique_object_representations'
///
/// [Clang] unary-type-trait:
/// '__is_aggregate'
/// '__trivially_copyable'
///
/// binary-type-trait:
/// [GNU] '__is_base_of'
/// [MS] '__is_convertible_to'
/// '__is_convertible'
/// '__is_same'
///
/// [Embarcadero] array-type-trait:
/// '__array_rank'
/// '__array_extent'
///
/// [Embarcadero] expression-trait:
/// '__is_lvalue_expr'
/// '__is_rvalue_expr'
/// \endverbatim
///
ExprResult Parser::ParseCastExpression(CastParseKind ParseKind,
bool isAddressOfOperand,
bool &NotCastExpr,
TypeCastState isTypeCast,
bool isVectorLiteral,
bool *NotPrimaryExpression) {
ExprResult Res;
tok::TokenKind SavedKind = Tok.getKind();
auto SavedType = PreferredType;
NotCastExpr = false;
// Are postfix-expression suffix operators permitted after this
// cast-expression? If not, and we find some, we'll parse them anyway and
// diagnose them.
bool AllowSuffix = true;
// This handles all of cast-expression, unary-expression, postfix-expression,
// and primary-expression. We handle them together like this for efficiency
// and to simplify handling of an expression starting with a '(' token: which
// may be one of a parenthesized expression, cast-expression, compound literal
// expression, or statement expression.
//
// If the parsed tokens consist of a primary-expression, the cases below
// break out of the switch; at the end we call ParsePostfixExpressionSuffix
// to handle the postfix expression suffixes. Cases that cannot be followed
// by postfix exprs should set AllowSuffix to false.
switch (SavedKind) {
case tok::l_paren: {
// If this expression is limited to being a unary-expression, the paren can
// not start a cast expression.
ParenParseOption ParenExprType;
switch (ParseKind) {
case CastParseKind::UnaryExprOnly:
assert(getLangOpts().CPlusPlus && "not possible to get here in C");
[[fallthrough]];
case CastParseKind::AnyCastExpr:
ParenExprType = ParenParseOption::CastExpr;
break;
case CastParseKind::PrimaryExprOnly:
ParenExprType = FoldExpr;
break;
}
ParsedType CastTy;
SourceLocation RParenLoc;
Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/,
isTypeCast == IsTypeCast, CastTy, RParenLoc);
// FIXME: What should we do if a vector literal is followed by a
// postfix-expression suffix? Usually postfix operators are permitted on
// literals.
if (isVectorLiteral)
return Res;
switch (ParenExprType) {
case SimpleExpr: break; // Nothing else to do.
case CompoundStmt: break; // Nothing else to do.
case CompoundLiteral:
// We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
// postfix-expression exist, parse them now.
break;
case CastExpr:
// We have parsed the cast-expression and no postfix-expr pieces are
// following.
return Res;
case FoldExpr:
// We only parsed a fold-expression. There might be postfix-expr pieces
// afterwards; parse them now.
break;
}
break;
}
// primary-expression