-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFoldConstants.cpp
1553 lines (1319 loc) · 49.5 KB
/
FoldConstants.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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "frontend/FoldConstants.h"
#include "mozilla/FloatingPoint.h"
#include "jslibmath.h"
#include "jsnum.h"
#include "frontend/ParseNode.h"
#include "frontend/ParseNodeVisitor.h"
#include "frontend/Parser.h"
#include "js/Conversions.h"
#include "vm/StringType.h"
using namespace js;
using namespace js::frontend;
using JS::GenericNaN;
using JS::ToInt32;
using JS::ToUint32;
using mozilla::IsNaN;
using mozilla::IsNegative;
using mozilla::NegativeInfinity;
using mozilla::PositiveInfinity;
// Don't use ReplaceNode directly, because we want the constant folder to keep
// the attributes isInParens and isDirectRHSAnonFunction of the old node being
// replaced.
inline MOZ_MUST_USE bool TryReplaceNode(ParseNode** pnp, ParseNode* pn) {
// convenience check: can call TryReplaceNode(pnp, alloc_parsenode())
// directly, without having to worry about alloc returning null.
if (!pn) {
return false;
}
pn->setInParens((*pnp)->isInParens());
pn->setDirectRHSAnonFunction((*pnp)->isDirectRHSAnonFunction());
ReplaceNode(pnp, pn);
return true;
}
static bool ContainsHoistedDeclaration(JSContext* cx, ParseNode* node,
bool* result);
static bool ListContainsHoistedDeclaration(JSContext* cx, ListNode* list,
bool* result) {
for (ParseNode* node : list->contents()) {
if (!ContainsHoistedDeclaration(cx, node, result)) {
return false;
}
if (*result) {
return true;
}
}
*result = false;
return true;
}
// Determines whether the given ParseNode contains any declarations whose
// visibility will extend outside the node itself -- that is, whether the
// ParseNode contains any var statements.
//
// THIS IS NOT A GENERAL-PURPOSE FUNCTION. It is only written to work in the
// specific context of deciding that |node|, as one arm of a ParseNodeKind::If
// controlled by a constant condition, contains a declaration that forbids
// |node| being completely eliminated as dead.
static bool ContainsHoistedDeclaration(JSContext* cx, ParseNode* node,
bool* result) {
if (!CheckRecursionLimit(cx)) {
return false;
}
restart:
// With a better-typed AST, we would have distinct parse node classes for
// expressions and for statements and would characterize expressions with
// ExpressionKind and statements with StatementKind. Perhaps someday. In
// the meantime we must characterize every ParseNodeKind, even the
// expression/sub-expression ones that, if we handle all statement kinds
// correctly, we'll never see.
switch (node->getKind()) {
// Base case.
case ParseNodeKind::VarStmt:
*result = true;
return true;
// Non-global lexical declarations are block-scoped (ergo not hoistable).
case ParseNodeKind::LetDecl:
case ParseNodeKind::ConstDecl:
MOZ_ASSERT(node->is<ListNode>());
*result = false;
return true;
// Similarly to the lexical declarations above, classes cannot add hoisted
// declarations
case ParseNodeKind::ClassDecl:
MOZ_ASSERT(node->is<ClassNode>());
*result = false;
return true;
// Function declarations *can* be hoisted declarations. But in the
// magical world of the rewritten frontend, the declaration necessitated
// by a nested function statement, not at body level, doesn't require
// that we preserve an unreachable function declaration node against
// dead-code removal.
case ParseNodeKind::Function:
*result = false;
return true;
case ParseNodeKind::Module:
*result = false;
return true;
// Statements with no sub-components at all.
case ParseNodeKind::EmptyStmt:
MOZ_ASSERT(node->is<NullaryNode>());
*result = false;
return true;
case ParseNodeKind::DebuggerStmt:
MOZ_ASSERT(node->is<DebuggerStatement>());
*result = false;
return true;
// Statements containing only an expression have no declarations.
case ParseNodeKind::ExpressionStmt:
case ParseNodeKind::ThrowStmt:
case ParseNodeKind::ReturnStmt:
MOZ_ASSERT(node->is<UnaryNode>());
*result = false;
return true;
// These two aren't statements in the spec, but we sometimes insert them
// in statement lists anyway.
case ParseNodeKind::InitialYield:
case ParseNodeKind::YieldStarExpr:
case ParseNodeKind::YieldExpr:
MOZ_ASSERT(node->is<UnaryNode>());
*result = false;
return true;
// Other statements with no sub-statement components.
case ParseNodeKind::BreakStmt:
case ParseNodeKind::ContinueStmt:
case ParseNodeKind::ImportDecl:
case ParseNodeKind::ImportSpecList:
case ParseNodeKind::ImportSpec:
case ParseNodeKind::ExportFromStmt:
case ParseNodeKind::ExportDefaultStmt:
case ParseNodeKind::ExportSpecList:
case ParseNodeKind::ExportSpec:
case ParseNodeKind::ExportStmt:
case ParseNodeKind::ExportBatchSpecStmt:
case ParseNodeKind::CallImportExpr:
*result = false;
return true;
// Statements possibly containing hoistable declarations only in the left
// half, in ParseNode terms -- the loop body in AST terms.
case ParseNodeKind::DoWhileStmt:
return ContainsHoistedDeclaration(cx, node->as<BinaryNode>().left(),
result);
// Statements possibly containing hoistable declarations only in the
// right half, in ParseNode terms -- the loop body or nested statement
// (usually a block statement), in AST terms.
case ParseNodeKind::WhileStmt:
case ParseNodeKind::WithStmt:
return ContainsHoistedDeclaration(cx, node->as<BinaryNode>().right(),
result);
case ParseNodeKind::LabelStmt:
return ContainsHoistedDeclaration(
cx, node->as<LabeledStatement>().statement(), result);
// Statements with more complicated structures.
// if-statement nodes may have hoisted declarations in their consequent
// and alternative components.
case ParseNodeKind::IfStmt: {
TernaryNode* ifNode = &node->as<TernaryNode>();
ParseNode* consequent = ifNode->kid2();
if (!ContainsHoistedDeclaration(cx, consequent, result)) {
return false;
}
if (*result) {
return true;
}
if ((node = ifNode->kid3())) {
goto restart;
}
*result = false;
return true;
}
// try-statements have statements to execute, and one or both of a
// catch-list and a finally-block.
case ParseNodeKind::TryStmt: {
TernaryNode* tryNode = &node->as<TernaryNode>();
MOZ_ASSERT(tryNode->kid2() || tryNode->kid3(),
"must have either catch or finally");
ParseNode* tryBlock = tryNode->kid1();
if (!ContainsHoistedDeclaration(cx, tryBlock, result)) {
return false;
}
if (*result) {
return true;
}
if (ParseNode* catchScope = tryNode->kid2()) {
BinaryNode* catchNode =
&catchScope->as<LexicalScopeNode>().scopeBody()->as<BinaryNode>();
MOZ_ASSERT(catchNode->isKind(ParseNodeKind::Catch));
ParseNode* catchStatements = catchNode->right();
if (!ContainsHoistedDeclaration(cx, catchStatements, result)) {
return false;
}
if (*result) {
return true;
}
}
if (ParseNode* finallyBlock = tryNode->kid3()) {
return ContainsHoistedDeclaration(cx, finallyBlock, result);
}
*result = false;
return true;
}
// A switch node's left half is an expression; only its right half (a
// list of cases/defaults, or a block node) could contain hoisted
// declarations.
case ParseNodeKind::SwitchStmt: {
SwitchStatement* switchNode = &node->as<SwitchStatement>();
return ContainsHoistedDeclaration(cx, &switchNode->lexicalForCaseList(),
result);
}
case ParseNodeKind::Case: {
CaseClause* caseClause = &node->as<CaseClause>();
return ContainsHoistedDeclaration(cx, caseClause->statementList(),
result);
}
case ParseNodeKind::ForStmt: {
ForNode* forNode = &node->as<ForNode>();
TernaryNode* loopHead = forNode->head();
MOZ_ASSERT(loopHead->isKind(ParseNodeKind::ForHead) ||
loopHead->isKind(ParseNodeKind::ForIn) ||
loopHead->isKind(ParseNodeKind::ForOf));
if (loopHead->isKind(ParseNodeKind::ForHead)) {
// for (init?; cond?; update?), with only init possibly containing
// a hoisted declaration. (Note: a lexical-declaration |init| is
// (at present) hoisted in SpiderMonkey parlance -- but such
// hoisting doesn't extend outside of this statement, so it is not
// hoisting in the sense meant by ContainsHoistedDeclaration.)
ParseNode* init = loopHead->kid1();
if (init && init->isKind(ParseNodeKind::VarStmt)) {
*result = true;
return true;
}
} else {
MOZ_ASSERT(loopHead->isKind(ParseNodeKind::ForIn) ||
loopHead->isKind(ParseNodeKind::ForOf));
// for each? (target in ...), where only target may introduce
// hoisted declarations.
//
// -- or --
//
// for (target of ...), where only target may introduce hoisted
// declarations.
//
// Either way, if |target| contains a declaration, it's |loopHead|'s
// first kid.
ParseNode* decl = loopHead->kid1();
if (decl && decl->isKind(ParseNodeKind::VarStmt)) {
*result = true;
return true;
}
}
ParseNode* loopBody = forNode->body();
return ContainsHoistedDeclaration(cx, loopBody, result);
}
case ParseNodeKind::LexicalScope: {
LexicalScopeNode* scope = &node->as<LexicalScopeNode>();
ParseNode* expr = scope->scopeBody();
if (expr->isKind(ParseNodeKind::ForStmt) || expr->is<FunctionNode>()) {
return ContainsHoistedDeclaration(cx, expr, result);
}
MOZ_ASSERT(expr->isKind(ParseNodeKind::StatementList));
return ListContainsHoistedDeclaration(
cx, &scope->scopeBody()->as<ListNode>(), result);
}
// List nodes with all non-null children.
case ParseNodeKind::StatementList:
return ListContainsHoistedDeclaration(cx, &node->as<ListNode>(), result);
// Grammar sub-components that should never be reached directly by this
// method, because some parent component should have asserted itself.
case ParseNodeKind::ObjectPropertyName:
case ParseNodeKind::ComputedName:
case ParseNodeKind::Spread:
case ParseNodeKind::MutateProto:
case ParseNodeKind::PropertyDefinition:
case ParseNodeKind::Shorthand:
case ParseNodeKind::ConditionalExpr:
case ParseNodeKind::TypeOfNameExpr:
case ParseNodeKind::TypeOfExpr:
case ParseNodeKind::AwaitExpr:
case ParseNodeKind::VoidExpr:
case ParseNodeKind::NotExpr:
case ParseNodeKind::BitNotExpr:
case ParseNodeKind::DeleteNameExpr:
case ParseNodeKind::DeletePropExpr:
case ParseNodeKind::DeleteElemExpr:
case ParseNodeKind::DeleteOptionalChainExpr:
case ParseNodeKind::DeleteExpr:
case ParseNodeKind::PosExpr:
case ParseNodeKind::NegExpr:
case ParseNodeKind::PreIncrementExpr:
case ParseNodeKind::PostIncrementExpr:
case ParseNodeKind::PreDecrementExpr:
case ParseNodeKind::PostDecrementExpr:
case ParseNodeKind::CoalesceExpr:
case ParseNodeKind::OrExpr:
case ParseNodeKind::AndExpr:
case ParseNodeKind::BitOrExpr:
case ParseNodeKind::BitXorExpr:
case ParseNodeKind::BitAndExpr:
case ParseNodeKind::StrictEqExpr:
case ParseNodeKind::EqExpr:
case ParseNodeKind::StrictNeExpr:
case ParseNodeKind::NeExpr:
case ParseNodeKind::LtExpr:
case ParseNodeKind::LeExpr:
case ParseNodeKind::GtExpr:
case ParseNodeKind::GeExpr:
case ParseNodeKind::InstanceOfExpr:
case ParseNodeKind::InExpr:
case ParseNodeKind::LshExpr:
case ParseNodeKind::RshExpr:
case ParseNodeKind::UrshExpr:
case ParseNodeKind::AddExpr:
case ParseNodeKind::SubExpr:
case ParseNodeKind::MulExpr:
case ParseNodeKind::DivExpr:
case ParseNodeKind::ModExpr:
case ParseNodeKind::PowExpr:
case ParseNodeKind::InitExpr:
case ParseNodeKind::AssignExpr:
case ParseNodeKind::AddAssignExpr:
case ParseNodeKind::SubAssignExpr:
case ParseNodeKind::CoalesceAssignExpr:
case ParseNodeKind::OrAssignExpr:
case ParseNodeKind::AndAssignExpr:
case ParseNodeKind::BitOrAssignExpr:
case ParseNodeKind::BitXorAssignExpr:
case ParseNodeKind::BitAndAssignExpr:
case ParseNodeKind::LshAssignExpr:
case ParseNodeKind::RshAssignExpr:
case ParseNodeKind::UrshAssignExpr:
case ParseNodeKind::MulAssignExpr:
case ParseNodeKind::DivAssignExpr:
case ParseNodeKind::ModAssignExpr:
case ParseNodeKind::PowAssignExpr:
case ParseNodeKind::CommaExpr:
case ParseNodeKind::ArrayExpr:
case ParseNodeKind::ObjectExpr:
case ParseNodeKind::PropertyNameExpr:
case ParseNodeKind::DotExpr:
case ParseNodeKind::ElemExpr:
case ParseNodeKind::Arguments:
case ParseNodeKind::CallExpr:
case ParseNodeKind::OptionalChain:
case ParseNodeKind::OptionalDotExpr:
case ParseNodeKind::OptionalElemExpr:
case ParseNodeKind::OptionalCallExpr:
case ParseNodeKind::Name:
case ParseNodeKind::PrivateName:
case ParseNodeKind::TemplateStringExpr:
case ParseNodeKind::TemplateStringListExpr:
case ParseNodeKind::TaggedTemplateExpr:
case ParseNodeKind::CallSiteObj:
case ParseNodeKind::StringExpr:
case ParseNodeKind::RegExpExpr:
case ParseNodeKind::TrueExpr:
case ParseNodeKind::FalseExpr:
case ParseNodeKind::NullExpr:
case ParseNodeKind::RawUndefinedExpr:
case ParseNodeKind::ThisExpr:
case ParseNodeKind::Elision:
case ParseNodeKind::NumberExpr:
case ParseNodeKind::BigIntExpr:
case ParseNodeKind::NewExpr:
case ParseNodeKind::Generator:
case ParseNodeKind::ParamsBody:
case ParseNodeKind::Catch:
case ParseNodeKind::ForIn:
case ParseNodeKind::ForOf:
case ParseNodeKind::ForHead:
case ParseNodeKind::ClassMethod:
case ParseNodeKind::ClassField:
case ParseNodeKind::ClassMemberList:
case ParseNodeKind::ClassNames:
case ParseNodeKind::NewTargetExpr:
case ParseNodeKind::ImportMetaExpr:
case ParseNodeKind::PosHolder:
case ParseNodeKind::SuperCallExpr:
case ParseNodeKind::SuperBase:
case ParseNodeKind::SetThis:
MOZ_CRASH(
"ContainsHoistedDeclaration should have indicated false on "
"some parent node without recurring to test this node");
case ParseNodeKind::PipelineExpr:
MOZ_ASSERT(node->is<ListNode>());
*result = false;
return true;
case ParseNodeKind::LastUnused:
case ParseNodeKind::Limit:
MOZ_CRASH("unexpected sentinel ParseNodeKind in node");
}
MOZ_CRASH("invalid node kind");
}
/*
* Fold from one constant type to another.
* XXX handles only strings and numbers for now
*/
static bool FoldType(JSContext* cx, FullParseHandler* handler, ParseNode** pnp,
ParseNodeKind kind) {
const ParseNode* pn = *pnp;
if (!pn->isKind(kind)) {
switch (kind) {
case ParseNodeKind::NumberExpr:
if (pn->isKind(ParseNodeKind::StringExpr)) {
double d;
if (!StringToNumber(cx, pn->as<NameNode>().atom(), &d)) {
return false;
}
if (!TryReplaceNode(pnp,
handler->newNumber(d, NoDecimal, pn->pn_pos))) {
return false;
}
}
break;
case ParseNodeKind::StringExpr:
if (pn->isKind(ParseNodeKind::NumberExpr)) {
JSAtom* atom = pn->as<NumericLiteral>().toAtom(cx);
if (!atom) {
return false;
}
if (!TryReplaceNode(pnp,
handler->newStringLiteral(atom, pn->pn_pos))) {
return false;
}
}
break;
default:
MOZ_CRASH("Invalid type in constant folding FoldType");
}
}
return true;
}
static bool IsEffectless(ParseNode* node) {
return node->isKind(ParseNodeKind::TrueExpr) ||
node->isKind(ParseNodeKind::FalseExpr) ||
node->isKind(ParseNodeKind::StringExpr) ||
node->isKind(ParseNodeKind::TemplateStringExpr) ||
node->isKind(ParseNodeKind::NumberExpr) ||
node->isKind(ParseNodeKind::BigIntExpr) ||
node->isKind(ParseNodeKind::NullExpr) ||
node->isKind(ParseNodeKind::RawUndefinedExpr) ||
node->isKind(ParseNodeKind::Function);
}
enum Truthiness { Truthy, Falsy, Unknown };
static Truthiness Boolish(ParseNode* pn) {
switch (pn->getKind()) {
case ParseNodeKind::NumberExpr:
return (pn->as<NumericLiteral>().value() != 0 &&
!IsNaN(pn->as<NumericLiteral>().value()))
? Truthy
: Falsy;
case ParseNodeKind::BigIntExpr:
return (pn->as<BigIntLiteral>().isZero()) ? Falsy : Truthy;
case ParseNodeKind::StringExpr:
case ParseNodeKind::TemplateStringExpr:
return (pn->as<NameNode>().atom()->length() > 0) ? Truthy : Falsy;
case ParseNodeKind::TrueExpr:
case ParseNodeKind::Function:
return Truthy;
case ParseNodeKind::FalseExpr:
case ParseNodeKind::NullExpr:
case ParseNodeKind::RawUndefinedExpr:
return Falsy;
case ParseNodeKind::VoidExpr: {
// |void <foo>| evaluates to |undefined| which isn't truthy. But the
// sense of this method requires that the expression be literally
// replaceable with true/false: not the case if the nested expression
// is effectful, might throw, &c. Walk past the |void| (and nested
// |void| expressions, for good measure) and check that the nested
// expression doesn't break this requirement before indicating falsity.
do {
pn = pn->as<UnaryNode>().kid();
} while (pn->isKind(ParseNodeKind::VoidExpr));
return IsEffectless(pn) ? Falsy : Unknown;
}
default:
return Unknown;
}
}
static bool SimplifyCondition(JSContext* cx, FullParseHandler* handler,
ParseNode** nodePtr) {
// Conditions fold like any other expression, but then they sometimes can be
// further folded to constants. *nodePtr should already have been
// constant-folded.
ParseNode* node = *nodePtr;
if (Truthiness t = Boolish(node); t != Unknown) {
// We can turn function nodes into constant nodes here, but mutating
// function nodes is tricky --- in particular, mutating a function node
// that appears on a method list corrupts the method list. However,
// methods are M's in statements of the form 'this.foo = M;', which we
// never fold, so we're okay.
if (!TryReplaceNode(
nodePtr, handler->newBooleanLiteral(t == Truthy, node->pn_pos))) {
return false;
}
}
return true;
}
static bool FoldTypeOfExpr(JSContext* cx, FullParseHandler* handler,
ParseNode** nodePtr) {
UnaryNode* node = &(*nodePtr)->as<UnaryNode>();
MOZ_ASSERT(node->isKind(ParseNodeKind::TypeOfExpr));
ParseNode* expr = node->kid();
// Constant-fold the entire |typeof| if given a constant with known type.
RootedPropertyName result(cx);
if (expr->isKind(ParseNodeKind::StringExpr) ||
expr->isKind(ParseNodeKind::TemplateStringExpr)) {
result = cx->names().string;
} else if (expr->isKind(ParseNodeKind::NumberExpr)) {
result = cx->names().number;
} else if (expr->isKind(ParseNodeKind::BigIntExpr)) {
result = cx->names().bigint;
} else if (expr->isKind(ParseNodeKind::NullExpr)) {
result = cx->names().object;
} else if (expr->isKind(ParseNodeKind::TrueExpr) ||
expr->isKind(ParseNodeKind::FalseExpr)) {
result = cx->names().boolean;
} else if (expr->is<FunctionNode>()) {
result = cx->names().function;
}
if (result) {
if (!TryReplaceNode(nodePtr,
handler->newStringLiteral(result, node->pn_pos))) {
return false;
}
}
return true;
}
static bool FoldDeleteExpr(JSContext* cx, FullParseHandler* handler,
ParseNode** nodePtr) {
UnaryNode* node = &(*nodePtr)->as<UnaryNode>();
MOZ_ASSERT(node->isKind(ParseNodeKind::DeleteExpr));
ParseNode* expr = node->kid();
// Expression deletion evaluates the expression, then evaluates to true.
// For effectless expressions, eliminate the expression evaluation.
if (IsEffectless(expr)) {
if (!TryReplaceNode(nodePtr,
handler->newBooleanLiteral(true, node->pn_pos))) {
return false;
}
}
return true;
}
static bool FoldDeleteElement(JSContext* cx, FullParseHandler* handler,
ParseNode** nodePtr) {
UnaryNode* node = &(*nodePtr)->as<UnaryNode>();
MOZ_ASSERT(node->isKind(ParseNodeKind::DeleteElemExpr));
ParseNode* expr = node->kid();
// If we're deleting an element, but constant-folding converted our
// element reference into a dotted property access, we must *also*
// morph the node's kind.
//
// In principle this also applies to |super["foo"] -> super.foo|,
// but we don't constant-fold |super["foo"]| yet.
MOZ_ASSERT(expr->isKind(ParseNodeKind::ElemExpr) ||
expr->isKind(ParseNodeKind::DotExpr));
if (expr->isKind(ParseNodeKind::DotExpr)) {
// newDelete will detect and use DeletePropExpr
if (!TryReplaceNode(nodePtr,
handler->newDelete(node->pn_pos.begin, expr))) {
return false;
}
MOZ_ASSERT((*nodePtr)->getKind() == ParseNodeKind::DeletePropExpr);
}
return true;
}
static bool FoldNot(JSContext* cx, FullParseHandler* handler,
ParseNode** nodePtr) {
UnaryNode* node = &(*nodePtr)->as<UnaryNode>();
MOZ_ASSERT(node->isKind(ParseNodeKind::NotExpr));
if (!SimplifyCondition(cx, handler, node->unsafeKidReference())) {
return false;
}
ParseNode* expr = node->kid();
if (expr->isKind(ParseNodeKind::TrueExpr) ||
expr->isKind(ParseNodeKind::FalseExpr)) {
bool newval = !expr->isKind(ParseNodeKind::TrueExpr);
if (!TryReplaceNode(nodePtr,
handler->newBooleanLiteral(newval, node->pn_pos))) {
return false;
}
}
return true;
}
static bool FoldUnaryArithmetic(JSContext* cx, FullParseHandler* handler,
ParseNode** nodePtr) {
UnaryNode* node = &(*nodePtr)->as<UnaryNode>();
MOZ_ASSERT(node->isKind(ParseNodeKind::BitNotExpr) ||
node->isKind(ParseNodeKind::PosExpr) ||
node->isKind(ParseNodeKind::NegExpr),
"need a different method for this node kind");
ParseNode* expr = node->kid();
if (expr->isKind(ParseNodeKind::NumberExpr) ||
expr->isKind(ParseNodeKind::TrueExpr) ||
expr->isKind(ParseNodeKind::FalseExpr)) {
double d = expr->isKind(ParseNodeKind::NumberExpr)
? expr->as<NumericLiteral>().value()
: double(expr->isKind(ParseNodeKind::TrueExpr));
if (node->isKind(ParseNodeKind::BitNotExpr)) {
d = ~ToInt32(d);
} else if (node->isKind(ParseNodeKind::NegExpr)) {
d = -d;
} else {
MOZ_ASSERT(node->isKind(ParseNodeKind::PosExpr)); // nothing to do
}
if (!TryReplaceNode(nodePtr,
handler->newNumber(d, NoDecimal, node->pn_pos))) {
return false;
}
}
return true;
}
static bool FoldAndOrCoalesce(JSContext* cx, ParseNode** nodePtr) {
ListNode* node = &(*nodePtr)->as<ListNode>();
MOZ_ASSERT(node->isKind(ParseNodeKind::AndExpr) ||
node->isKind(ParseNodeKind::CoalesceExpr) ||
node->isKind(ParseNodeKind::OrExpr));
bool isOrNode = node->isKind(ParseNodeKind::OrExpr);
bool isAndNode = node->isKind(ParseNodeKind::AndExpr);
bool isCoalesceNode = node->isKind(ParseNodeKind::CoalesceExpr);
ParseNode** elem = node->unsafeHeadReference();
do {
Truthiness t = Boolish(*elem);
// If we don't know the constant-folded node's truthiness, we can't
// reduce this node with its surroundings. Continue folding any
// remaining nodes.
if (t == Unknown) {
elem = &(*elem)->pn_next;
continue;
}
bool isTruthyCoalesceNode =
isCoalesceNode && !((*elem)->isKind(ParseNodeKind::NullExpr) ||
(*elem)->isKind(ParseNodeKind::VoidExpr) ||
(*elem)->isKind(ParseNodeKind::RawUndefinedExpr));
bool canShortCircuit = (isOrNode && t == Truthy) ||
(isAndNode && t == Falsy) || isTruthyCoalesceNode;
// If the constant-folded node's truthiness will terminate the
// condition -- `a || true || expr` or `b && false && expr` or
// `false ?? c ?? expr` -- then trailing nodes will never be
// evaluated. Truncate the list after the known-truthiness node,
// as it's the overall result.
if (canShortCircuit) {
for (ParseNode* next = (*elem)->pn_next; next; next = next->pn_next) {
node->unsafeDecrementCount();
}
// Terminate the original and/or list at the known-truthiness
// node.
(*elem)->pn_next = nullptr;
elem = &(*elem)->pn_next;
break;
}
// We've encountered a vacuous node that'll never short-circuit
// evaluation.
if ((*elem)->pn_next) {
// This node is never the overall result when there are
// subsequent nodes. Remove it.
ParseNode* elt = *elem;
*elem = elt->pn_next;
node->unsafeDecrementCount();
} else {
// Otherwise this node is the result of the overall expression,
// so leave it alone. And we're done.
elem = &(*elem)->pn_next;
break;
}
} while (*elem);
node->unsafeReplaceTail(elem);
// If we removed nodes, we may have to replace a one-element list with
// its element.
if (node->count() == 1) {
ParseNode* first = node->head();
if (!TryReplaceNode(nodePtr, first)) {
;
return false;
}
}
return true;
}
static bool Fold(JSContext* cx, FullParseHandler* handler, ParseNode** pnp);
static bool FoldConditional(JSContext* cx, FullParseHandler* handler,
ParseNode** nodePtr) {
ParseNode** nextNode = nodePtr;
do {
// |nextNode| on entry points to the C?T:F expression to be folded.
// Reset it to exit the loop in the common case where F isn't another
// ?: expression.
nodePtr = nextNode;
nextNode = nullptr;
TernaryNode* node = &(*nodePtr)->as<TernaryNode>();
MOZ_ASSERT(node->isKind(ParseNodeKind::ConditionalExpr));
ParseNode** expr = node->unsafeKid1Reference();
if (!Fold(cx, handler, expr)) {
return false;
}
if (!SimplifyCondition(cx, handler, expr)) {
return false;
}
ParseNode** ifTruthy = node->unsafeKid2Reference();
if (!Fold(cx, handler, ifTruthy)) {
return false;
}
ParseNode** ifFalsy = node->unsafeKid3Reference();
// If our C?T:F node has F as another ?: node, *iteratively* constant-
// fold F *after* folding C and T (and possibly eliminating C and one
// of T/F entirely); otherwise fold F normally. Making |nextNode| non-
// null causes this loop to run again to fold F.
//
// Conceivably we could instead/also iteratively constant-fold T, if T
// were more complex than F. Such an optimization is unimplemented.
if ((*ifFalsy)->isKind(ParseNodeKind::ConditionalExpr)) {
MOZ_ASSERT((*ifFalsy)->is<TernaryNode>());
nextNode = ifFalsy;
} else {
if (!Fold(cx, handler, ifFalsy)) {
return false;
}
}
// Try to constant-fold based on the condition expression.
Truthiness t = Boolish(*expr);
if (t == Unknown) {
continue;
}
// Otherwise reduce 'C ? T : F' to T or F as directed by C.
ParseNode* replacement = t == Truthy ? *ifTruthy : *ifFalsy;
// Otherwise perform a replacement. This invalidates |nextNode|, so
// reset it (if the replacement requires folding) or clear it (if
// |ifFalsy| is dead code) as needed.
if (nextNode) {
nextNode = (*nextNode == replacement) ? nodePtr : nullptr;
}
ReplaceNode(nodePtr, replacement);
} while (nextNode);
return true;
}
static bool FoldIf(JSContext* cx, FullParseHandler* handler,
ParseNode** nodePtr) {
ParseNode** nextNode = nodePtr;
do {
// |nextNode| on entry points to the initial |if| to be folded. Reset
// it to exit the loop when the |else| arm isn't another |if|.
nodePtr = nextNode;
nextNode = nullptr;
TernaryNode* node = &(*nodePtr)->as<TernaryNode>();
MOZ_ASSERT(node->isKind(ParseNodeKind::IfStmt));
ParseNode** expr = node->unsafeKid1Reference();
if (!Fold(cx, handler, expr)) {
return false;
}
if (!SimplifyCondition(cx, handler, expr)) {
return false;
}
ParseNode** consequent = node->unsafeKid2Reference();
if (!Fold(cx, handler, consequent)) {
return false;
}
ParseNode** alternative = node->unsafeKid3Reference();
if (*alternative) {
// If in |if (C) T; else F;| we have |F| as another |if|,
// *iteratively* constant-fold |F| *after* folding |C| and |T| (and
// possibly completely replacing the whole thing with |T| or |F|);
// otherwise fold F normally. Making |nextNode| non-null causes
// this loop to run again to fold F.
if ((*alternative)->isKind(ParseNodeKind::IfStmt)) {
MOZ_ASSERT((*alternative)->is<TernaryNode>());
nextNode = alternative;
} else {
if (!Fold(cx, handler, alternative)) {
return false;
}
}
}
// Eliminate the consequent or alternative if the condition has
// constant truthiness.
Truthiness t = Boolish(*expr);
if (t == Unknown) {
continue;
}
// Careful! Either of these can be null: |replacement| in |if (0) T;|,
// and |discarded| in |if (true) T;|.
ParseNode* replacement;
ParseNode* discarded;
if (t == Truthy) {
replacement = *consequent;
discarded = *alternative;
} else {
replacement = *alternative;
discarded = *consequent;
}
bool performReplacement = true;
if (discarded) {
// A declaration that hoists outside the discarded arm prevents the
// |if| from being folded away.
bool containsHoistedDecls;
if (!ContainsHoistedDeclaration(cx, discarded, &containsHoistedDecls)) {
return false;
}
performReplacement = !containsHoistedDecls;
}
if (!performReplacement) {
continue;
}
if (!replacement) {
// If there's no replacement node, we have a constantly-false |if|
// with no |else|. Replace the entire thing with an empty
// statement list.
if (!TryReplaceNode(nodePtr, handler->newStatementList(node->pn_pos))) {
return false;
}
} else {
// Replacement invalidates |nextNode|, so reset it (if the
// replacement requires folding) or clear it (if |alternative|
// is dead code) as needed.
if (nextNode) {
nextNode = (*nextNode == replacement) ? nodePtr : nullptr;
}
ReplaceNode(nodePtr, replacement);
}
} while (nextNode);
return true;
}
static double ComputeBinary(ParseNodeKind kind, double left, double right) {
if (kind == ParseNodeKind::AddExpr) {
return left + right;
}
if (kind == ParseNodeKind::SubExpr) {
return left - right;
}
if (kind == ParseNodeKind::MulExpr) {
return left * right;
}
if (kind == ParseNodeKind::ModExpr) {
return NumberMod(left, right);
}
if (kind == ParseNodeKind::UrshExpr) {
return ToUint32(left) >> (ToUint32(right) & 31);
}
if (kind == ParseNodeKind::DivExpr) {
return NumberDiv(left, right);
}
MOZ_ASSERT(kind == ParseNodeKind::LshExpr || kind == ParseNodeKind::RshExpr);
int32_t i = ToInt32(left);
uint32_t j = ToUint32(right) & 31;
return int32_t((kind == ParseNodeKind::LshExpr) ? uint32_t(i) << j : i >> j);
}
static bool FoldBinaryArithmetic(JSContext* cx, FullParseHandler* handler,
ParseNode** nodePtr) {
ListNode* node = &(*nodePtr)->as<ListNode>();
MOZ_ASSERT(node->isKind(ParseNodeKind::SubExpr) ||
node->isKind(ParseNodeKind::MulExpr) ||
node->isKind(ParseNodeKind::LshExpr) ||
node->isKind(ParseNodeKind::RshExpr) ||
node->isKind(ParseNodeKind::UrshExpr) ||
node->isKind(ParseNodeKind::DivExpr) ||
node->isKind(ParseNodeKind::ModExpr));
MOZ_ASSERT(node->count() >= 2);
// Fold each operand to a number if possible.
ParseNode** listp = node->unsafeHeadReference();
for (; *listp; listp = &(*listp)->pn_next) {
if (!FoldType(cx, handler, listp, ParseNodeKind::NumberExpr)) {
return false;
}
}
node->unsafeReplaceTail(listp);