-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
mod.rs
3558 lines (3337 loc) · 127 KB
/
mod.rs
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
#![allow(clippy::redundant_closure_call)]
use std::{
borrow::Cow,
cmp::Ordering,
fmt::{Display, Write},
future::Future,
hash::{Hash, Hasher},
mem::take,
pin::Pin,
sync::Arc,
};
use anyhow::{bail, Context, Result};
use indexmap::{IndexMap, IndexSet};
use num_bigint::BigInt;
use num_traits::identities::Zero;
use once_cell::sync::Lazy;
use regex::Regex;
use swc_core::{
common::Mark,
ecma::{
ast::{Id, Ident, Lit},
atoms::{Atom, JsWord},
},
};
use turbo_tasks::Vc;
use turbopack_core::compile_time_info::CompileTimeDefineValue;
use url::Url;
use self::imports::ImportAnnotations;
pub(crate) use self::imports::ImportMap;
use crate::{references::require_context::RequireContextMap, utils::StringifyJs};
pub mod builtin;
pub mod graph;
pub mod imports;
pub mod linker;
pub mod top_level_await;
pub mod well_known;
type PinnedAsyncUntilSettledBox<'a, E> =
Pin<Box<dyn Future<Output = Result<(JsValue, bool), E>> + Send + 'a>>;
type PinnedAsyncBox<'a, E> = Pin<Box<dyn Future<Output = Result<(JsValue, bool), E>> + 'a>>;
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub enum ObjectPart {
KeyValue(JsValue, JsValue),
Spread(JsValue),
}
impl Default for ObjectPart {
fn default() -> Self {
ObjectPart::Spread(Default::default())
}
}
#[derive(Debug, Clone)]
pub struct ConstantNumber(pub f64);
fn integer_decode(val: f64) -> (u64, i16, i8) {
let bits: u64 = val.to_bits();
let sign: i8 = if bits >> 63 == 0 { 1 } else { -1 };
let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16;
let mantissa = if exponent == 0 {
(bits & 0xfffffffffffff) << 1
} else {
(bits & 0xfffffffffffff) | 0x10000000000000
};
exponent -= 1023 + 52;
(mantissa, exponent, sign)
}
impl ConstantNumber {
pub fn as_u32_index(&self) -> Option<usize> {
let index: u32 = self.0 as u32;
(index as f64 == self.0).then_some(index as usize)
}
}
impl Hash for ConstantNumber {
fn hash<H: Hasher>(&self, state: &mut H) {
integer_decode(self.0).hash(state);
}
}
impl PartialEq for ConstantNumber {
fn eq(&self, other: &Self) -> bool {
integer_decode(self.0) == integer_decode(other.0)
}
}
impl Eq for ConstantNumber {}
#[derive(Debug, Clone)]
pub enum ConstantString {
Word(JsWord),
Atom(Atom),
}
impl ConstantString {
pub fn as_str(&self) -> &str {
match self {
Self::Word(s) => s,
Self::Atom(s) => s,
}
}
pub fn is_empty(&self) -> bool {
self.as_str().is_empty()
}
}
impl PartialEq for ConstantString {
fn eq(&self, other: &Self) -> bool {
self.as_str() == other.as_str()
}
}
impl Eq for ConstantString {}
impl Hash for ConstantString {
fn hash<H: Hasher>(&self, state: &mut H) {
self.as_str().hash(state);
}
}
impl Display for ConstantString {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.as_str().fmt(f)
}
}
impl From<JsWord> for ConstantString {
fn from(v: JsWord) -> Self {
ConstantString::Word(v)
}
}
impl From<Atom> for ConstantString {
fn from(v: Atom) -> Self {
ConstantString::Atom(v)
}
}
impl From<&'static str> for ConstantString {
fn from(v: &'static str) -> Self {
ConstantString::Word(v.into())
}
}
impl From<String> for ConstantString {
fn from(v: String) -> Self {
ConstantString::Atom(v.into())
}
}
#[derive(Debug, Clone, Hash, PartialEq, Eq, Default)]
pub enum ConstantValue {
#[default]
Undefined,
Str(ConstantString),
Num(ConstantNumber),
True,
False,
Null,
BigInt(BigInt),
Regex(Atom, Atom),
}
impl ConstantValue {
pub fn as_str(&self) -> Option<&str> {
match self {
Self::Str(s) => Some(s.as_str()),
_ => None,
}
}
pub fn as_bool(&self) -> Option<bool> {
match self {
Self::True => Some(true),
Self::False => Some(false),
_ => None,
}
}
pub fn is_truthy(&self) -> bool {
match self {
Self::Undefined | Self::False | Self::Null => false,
Self::True | Self::Regex(..) => true,
Self::Str(s) => !s.is_empty(),
Self::Num(ConstantNumber(n)) => *n != 0.0,
Self::BigInt(n) => !n.is_zero(),
}
}
pub fn is_nullish(&self) -> bool {
match self {
Self::Undefined | Self::Null => true,
Self::Str(..)
| Self::Num(..)
| Self::True
| Self::False
| Self::BigInt(..)
| Self::Regex(..) => false,
}
}
pub fn is_empty_string(&self) -> bool {
match self {
Self::Str(s) => s.is_empty(),
_ => false,
}
}
pub fn is_value_type(&self) -> bool {
!matches!(self, Self::Regex(..))
}
}
impl From<bool> for ConstantValue {
fn from(v: bool) -> Self {
match v {
true => ConstantValue::True,
false => ConstantValue::False,
}
}
}
impl From<&'_ str> for ConstantValue {
fn from(v: &str) -> Self {
ConstantValue::Str(ConstantString::Word(v.into()))
}
}
impl From<Lit> for ConstantValue {
fn from(v: Lit) -> Self {
match v {
Lit::Str(v) => ConstantValue::Str(ConstantString::Word(v.value)),
Lit::Bool(v) => {
if v.value {
ConstantValue::True
} else {
ConstantValue::False
}
}
Lit::Null(_) => ConstantValue::Null,
Lit::Num(v) => ConstantValue::Num(ConstantNumber(v.value)),
Lit::BigInt(v) => ConstantValue::BigInt(*v.value),
Lit::Regex(v) => ConstantValue::Regex(v.exp, v.flags),
Lit::JSXText(v) => ConstantValue::Str(ConstantString::Atom(v.value)),
}
}
}
impl Display for ConstantValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ConstantValue::Undefined => write!(f, "undefined"),
ConstantValue::Str(str) => write!(f, "{}", StringifyJs(str.as_str())),
ConstantValue::True => write!(f, "true"),
ConstantValue::False => write!(f, "false"),
ConstantValue::Null => write!(f, "null"),
ConstantValue::Num(ConstantNumber(n)) => write!(f, "{n}"),
ConstantValue::BigInt(n) => write!(f, "{n}"),
ConstantValue::Regex(exp, flags) => write!(f, "/{exp}/{flags}"),
}
}
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct ModuleValue {
pub module: JsWord,
pub annotations: ImportAnnotations,
}
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum LogicalOperator {
And,
Or,
NullishCoalescing,
}
impl LogicalOperator {
fn joiner(&self) -> &'static str {
match self {
LogicalOperator::And => " && ",
LogicalOperator::Or => " || ",
LogicalOperator::NullishCoalescing => " ?? ",
}
}
fn multi_line_joiner(&self) -> &'static str {
match self {
LogicalOperator::And => "&& ",
LogicalOperator::Or => "|| ",
LogicalOperator::NullishCoalescing => "?? ",
}
}
}
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum BinaryOperator {
Equal,
NotEqual,
StrictEqual,
StrictNotEqual,
}
impl BinaryOperator {
fn joiner(&self) -> &'static str {
match self {
BinaryOperator::Equal => " == ",
BinaryOperator::NotEqual => " != ",
BinaryOperator::StrictEqual => " === ",
BinaryOperator::StrictNotEqual => " !== ",
}
}
fn positive_op(&self) -> (PositiveBinaryOperator, bool) {
match self {
BinaryOperator::Equal => (PositiveBinaryOperator::Equal, false),
BinaryOperator::NotEqual => (PositiveBinaryOperator::Equal, true),
BinaryOperator::StrictEqual => (PositiveBinaryOperator::StrictEqual, false),
BinaryOperator::StrictNotEqual => (PositiveBinaryOperator::StrictEqual, true),
}
}
}
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum PositiveBinaryOperator {
Equal,
StrictEqual,
}
/// The four categories of [JsValue]s.
enum JsValueMetaKind {
/// Doesn't contain nested values.
Leaf,
/// Contains nested values. Nested values represent some structure and can't
/// be replaced during linking. They might contain placeholders.
Nested,
/// Contains nested values. Operations are replaced during linking. They
/// might contain placeholders.
Operation,
/// These values are replaced during linking.
Placeholder,
}
/// TODO: Use `Arc`
/// There are 4 kinds of values: Leaves, Nested, Operations, and Placeholders
/// (see [JsValueMetaKind] for details). Values are processed in two phases:
/// - Analyze phase: We convert AST into [JsValue]s. We don't have contextual
/// information so we need to insert placeholders to represent that.
/// - Link phase: We try to reduce a value to a constant value. The link phase
/// has 5 substeps that are executed on each node in the graph depth-first.
/// When a value is modified, we need to visit the new children again.
/// - Replace variables with their values. This replaces [JsValue::Variable]. No
/// variable should be remaining after that.
/// - Replace placeholders with contextual information. This usually replaces
/// [JsValue::FreeVar] and [JsValue::Module]. Some [JsValue::Call] on well-
/// known functions might also be replaced. No free vars or modules should be
/// remaining after that.
/// - Replace operations on well-known objects and functions. This handles
/// [JsValue::Call] and [JsValue::Member] on well-known objects and functions.
/// - Replace all built-in functions with their values when they are
/// compile-time constant.
/// - For optimization, any nested operations are replaced with
/// [JsValue::Unknown]. So only one layer of operation remains.
/// Any remaining operation or placeholder can be treated as unknown.
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub enum JsValue {
// LEAF VALUES
// ----------------------------
/// A constant primitive value.
Constant(ConstantValue),
/// An constant URL object.
Url(Url),
/// Some kind of well-known object
/// (must not be an array, otherwise Array.concat needs to be changed)
WellKnownObject(WellKnownObjectKind),
/// Some kind of well-known function
WellKnownFunction(WellKnownFunctionKind),
/// Not-analyzable value. Might contain the original value for additional
/// info. Has a reason string for explanation.
Unknown(Option<Arc<JsValue>>, Cow<'static, str>),
// NESTED VALUES
// ----------------------------
/// An array of nested values
Array {
total_nodes: usize,
items: Vec<JsValue>,
mutable: bool,
},
/// An object of nested values
Object {
total_nodes: usize,
parts: Vec<ObjectPart>,
mutable: bool,
},
/// A list of alternative values
Alternatives(usize, Vec<JsValue>),
/// A function reference. The return value might contain [JsValue::Argument]
/// placeholders that need to be replaced when calling this function.
/// `(total_node_count, func_ident, return_value)`
Function(usize, u32, Box<JsValue>),
// OPERATIONS
// ----------------------------
/// A string concatenation of values.
/// `foo.${unknownVar}.js` => 'foo' + Unknown + '.js'
Concat(usize, Vec<JsValue>),
/// An addition of values.
/// This can be converted to [JsValue::Concat] if the type of the variable
/// is string.
Add(usize, Vec<JsValue>),
/// Logical negation `!expr`
Not(usize, Box<JsValue>),
/// Logical operator chain e. g. `expr && expr`
Logical(usize, LogicalOperator, Vec<JsValue>),
/// Binary expression e. g. `expr == expr`
Binary(usize, Box<JsValue>, BinaryOperator, Box<JsValue>),
/// A function call without a this context.
/// `(total_node_count, callee, args)`
Call(usize, Box<JsValue>, Vec<JsValue>),
/// A super call to the parent constructor.
/// `(total_node_count, args)`
SuperCall(usize, Vec<JsValue>),
/// A function call with a this context.
/// `(total_node_count, obj, prop, args)`
MemberCall(usize, Box<JsValue>, Box<JsValue>, Vec<JsValue>),
/// A member access `obj[prop]`
/// `(total_node_count, obj, prop)`
Member(usize, Box<JsValue>, Box<JsValue>),
// PLACEHOLDERS
// ----------------------------
/// A reference to a variable.
Variable(Id),
/// A reference to an function argument.
/// (func_ident, arg_index)
Argument(u32, usize),
// TODO no predefined kinds, only JsWord
/// A reference to a free variable.
FreeVar(JsWord),
/// This is a reference to a imported module.
Module(ModuleValue),
}
impl From<&'_ str> for JsValue {
fn from(v: &str) -> Self {
ConstantValue::Str(ConstantString::Word(v.into())).into()
}
}
impl From<JsWord> for JsValue {
fn from(v: JsWord) -> Self {
ConstantValue::Str(ConstantString::Word(v)).into()
}
}
impl From<Atom> for JsValue {
fn from(v: Atom) -> Self {
ConstantValue::Str(ConstantString::Atom(v)).into()
}
}
impl From<BigInt> for JsValue {
fn from(v: BigInt) -> Self {
ConstantValue::BigInt(v).into()
}
}
impl From<f64> for JsValue {
fn from(v: f64) -> Self {
ConstantValue::Num(ConstantNumber(v)).into()
}
}
impl From<String> for JsValue {
fn from(v: String) -> Self {
ConstantValue::Str(v.into()).into()
}
}
impl From<swc_core::ecma::ast::Str> for JsValue {
fn from(v: swc_core::ecma::ast::Str) -> Self {
ConstantValue::Str(v.value.into()).into()
}
}
impl From<ConstantValue> for JsValue {
fn from(v: ConstantValue) -> Self {
JsValue::Constant(v)
}
}
impl From<&CompileTimeDefineValue> for JsValue {
fn from(v: &CompileTimeDefineValue) -> Self {
match v {
CompileTimeDefineValue::String(s) => JsValue::Constant(s.as_str().into()),
CompileTimeDefineValue::Bool(b) => JsValue::Constant((*b).into()),
CompileTimeDefineValue::JSON(_) => JsValue::unknown_empty("compile time injected JSON"),
}
}
}
impl Default for JsValue {
fn default() -> Self {
JsValue::unknown_empty("")
}
}
impl Display for ObjectPart {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ObjectPart::KeyValue(key, value) => write!(f, "{key}: {value}"),
ObjectPart::Spread(value) => write!(f, "...{value}"),
}
}
}
impl Display for JsValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
JsValue::Constant(v) => write!(f, "{v}"),
JsValue::Url(url) => write!(f, "{}", url),
JsValue::Array { items, mutable, .. } => write!(
f,
"{}[{}]",
if *mutable { "" } else { "frozen " },
items
.iter()
.map(|v| v.to_string())
.collect::<Vec<_>>()
.join(", ")
),
JsValue::Object { parts, mutable, .. } => write!(
f,
"{}{{{}}}",
if *mutable { "" } else { "frozen " },
parts
.iter()
.map(|v| v.to_string())
.collect::<Vec<_>>()
.join(", ")
),
JsValue::Alternatives(_, list) => write!(
f,
"({})",
list.iter()
.map(|v| v.to_string())
.collect::<Vec<_>>()
.join(" | ")
),
JsValue::FreeVar(name) => write!(f, "FreeVar({:?})", name),
JsValue::Variable(name) => write!(f, "Variable({}#{:?})", name.0, name.1),
JsValue::Concat(_, list) => write!(
f,
"`{}`",
list.iter()
.map(|v| v
.as_str()
.map_or_else(|| format!("${{{}}}", v), |str| str.to_string()))
.collect::<Vec<_>>()
.join("")
),
JsValue::Add(_, list) => write!(
f,
"({})",
list.iter()
.map(|v| v.to_string())
.collect::<Vec<_>>()
.join(" + ")
),
JsValue::Not(_, value) => write!(f, "!({})", value),
JsValue::Logical(_, op, list) => write!(
f,
"({})",
list.iter()
.map(|v| v.to_string())
.collect::<Vec<_>>()
.join(op.joiner())
),
JsValue::Binary(_, a, op, b) => write!(f, "({}{}{})", a, op.joiner(), b),
JsValue::Call(_, callee, list) => write!(
f,
"{}({})",
callee,
list.iter()
.map(|v| v.to_string())
.collect::<Vec<_>>()
.join(", ")
),
JsValue::SuperCall(_, list) => write!(
f,
"super({})",
list.iter()
.map(|v| v.to_string())
.collect::<Vec<_>>()
.join(", ")
),
JsValue::MemberCall(_, obj, prop, list) => write!(
f,
"{}[{}]({})",
obj,
prop,
list.iter()
.map(|v| v.to_string())
.collect::<Vec<_>>()
.join(", ")
),
JsValue::Member(_, obj, prop) => write!(f, "{}[{}]", obj, prop),
JsValue::Module(ModuleValue {
module: name,
annotations,
}) => {
write!(f, "Module({}, {})", name, annotations)
}
JsValue::Unknown(..) => write!(f, "???"),
JsValue::WellKnownObject(obj) => write!(f, "WellKnownObject({:?})", obj),
JsValue::WellKnownFunction(func) => write!(f, "WellKnownFunction({:?})", func),
JsValue::Function(_, func_ident, return_value) => {
write!(f, "Function#{}(return = {:?})", func_ident, return_value)
}
JsValue::Argument(func_ident, index) => {
write!(f, "arguments[{}#{}]", index, func_ident)
}
}
}
}
fn pretty_join(
items: &[String],
indent_depth: usize,
single_line_separator: &str,
multi_line_separator_end: &str,
multi_line_separator_start: &str,
) -> String {
let multi_line = items
.iter()
.any(|item| item.len() > 50 || item.contains('\n'))
|| items
.iter()
.map(|item| item.len() + single_line_separator.len())
.sum::<usize>()
> 100;
if !multi_line {
items.join(single_line_separator)
} else if multi_line_separator_start.is_empty() {
format!(
"\n{}{}\n{}",
" ".repeat(indent_depth + 1),
items.join(&format!(
"{multi_line_separator_end}\n{}",
" ".repeat(indent_depth + 1)
)),
" ".repeat(indent_depth)
)
} else {
format!(
"\n{}{multi_line_separator_start}{}\n{}",
" ".repeat(indent_depth * 4 + 4 - multi_line_separator_start.len()),
items.join(&format!(
"{multi_line_separator_end}\n{}{multi_line_separator_start}",
" ".repeat(indent_depth * 4 + 4 - multi_line_separator_start.len())
)),
" ".repeat(indent_depth)
)
}
}
fn total_nodes(vec: &[JsValue]) -> usize {
vec.iter().map(|v| v.total_nodes()).sum::<usize>()
}
// Private meta methods
impl JsValue {
fn meta_type(&self) -> JsValueMetaKind {
match self {
JsValue::Constant(..)
| JsValue::Url(..)
| JsValue::WellKnownObject(..)
| JsValue::WellKnownFunction(..)
| JsValue::Unknown(..) => JsValueMetaKind::Leaf,
JsValue::Array { .. }
| JsValue::Object { .. }
| JsValue::Alternatives(..)
| JsValue::Function(..)
| JsValue::Member(..) => JsValueMetaKind::Nested,
JsValue::Concat(..)
| JsValue::Add(..)
| JsValue::Not(..)
| JsValue::Logical(..)
| JsValue::Binary(..)
| JsValue::Call(..)
| JsValue::SuperCall(..)
| JsValue::MemberCall(..) => JsValueMetaKind::Operation,
JsValue::Variable(..)
| JsValue::Argument(..)
| JsValue::FreeVar(..)
| JsValue::Module(..) => JsValueMetaKind::Placeholder,
}
}
}
// Constructors
impl JsValue {
pub fn alternatives(list: Vec<JsValue>) -> Self {
Self::Alternatives(1 + total_nodes(&list), list)
}
pub fn concat(list: Vec<JsValue>) -> Self {
Self::Concat(1 + total_nodes(&list), list)
}
pub fn add(list: Vec<JsValue>) -> Self {
Self::Add(1 + total_nodes(&list), list)
}
pub fn logical_and(list: Vec<JsValue>) -> Self {
Self::Logical(1 + total_nodes(&list), LogicalOperator::And, list)
}
pub fn logical_or(list: Vec<JsValue>) -> Self {
Self::Logical(1 + total_nodes(&list), LogicalOperator::Or, list)
}
pub fn nullish_coalescing(list: Vec<JsValue>) -> Self {
Self::Logical(
1 + total_nodes(&list),
LogicalOperator::NullishCoalescing,
list,
)
}
pub fn equal(a: JsValue, b: JsValue) -> Self {
Self::Binary(
1 + a.total_nodes() + b.total_nodes(),
Box::new(a),
BinaryOperator::Equal,
Box::new(b),
)
}
pub fn not_equal(a: JsValue, b: JsValue) -> Self {
Self::Binary(
1 + a.total_nodes() + b.total_nodes(),
Box::new(a),
BinaryOperator::NotEqual,
Box::new(b),
)
}
pub fn strict_equal(a: JsValue, b: JsValue) -> Self {
Self::Binary(
1 + a.total_nodes() + b.total_nodes(),
Box::new(a),
BinaryOperator::StrictEqual,
Box::new(b),
)
}
pub fn strict_not_equal(a: JsValue, b: JsValue) -> Self {
Self::Binary(
1 + a.total_nodes() + b.total_nodes(),
Box::new(a),
BinaryOperator::StrictNotEqual,
Box::new(b),
)
}
pub fn logical_not(inner: Box<JsValue>) -> Self {
Self::Not(1 + inner.total_nodes(), inner)
}
pub fn array(items: Vec<JsValue>) -> Self {
Self::Array {
total_nodes: 1 + total_nodes(&items),
items,
mutable: true,
}
}
pub fn frozen_array(items: Vec<JsValue>) -> Self {
Self::Array {
total_nodes: 1 + total_nodes(&items),
items,
mutable: false,
}
}
pub fn function(func_ident: u32, return_value: Box<JsValue>) -> Self {
Self::Function(1 + return_value.total_nodes(), func_ident, return_value)
}
pub fn object(list: Vec<ObjectPart>) -> Self {
Self::Object {
total_nodes: 1 + list
.iter()
.map(|v| match v {
ObjectPart::KeyValue(k, v) => k.total_nodes() + v.total_nodes(),
ObjectPart::Spread(s) => s.total_nodes(),
})
.sum::<usize>(),
parts: list,
mutable: true,
}
}
pub fn frozen_object(list: Vec<ObjectPart>) -> Self {
Self::Object {
total_nodes: 1 + list
.iter()
.map(|v| match v {
ObjectPart::KeyValue(k, v) => k.total_nodes() + v.total_nodes(),
ObjectPart::Spread(s) => s.total_nodes(),
})
.sum::<usize>(),
parts: list,
mutable: false,
}
}
pub fn call(f: Box<JsValue>, args: Vec<JsValue>) -> Self {
Self::Call(1 + f.total_nodes() + total_nodes(&args), f, args)
}
pub fn super_call(args: Vec<JsValue>) -> Self {
Self::SuperCall(1 + total_nodes(&args), args)
}
pub fn member_call(o: Box<JsValue>, p: Box<JsValue>, args: Vec<JsValue>) -> Self {
Self::MemberCall(
1 + o.total_nodes() + p.total_nodes() + total_nodes(&args),
o,
p,
args,
)
}
pub fn member(o: Box<JsValue>, p: Box<JsValue>) -> Self {
Self::Member(1 + o.total_nodes() + p.total_nodes(), o, p)
}
pub fn unknown(value: impl Into<Arc<JsValue>>, reason: impl Into<Cow<'static, str>>) -> Self {
Self::Unknown(Some(value.into()), reason.into())
}
pub fn unknown_empty(reason: impl Into<Cow<'static, str>>) -> Self {
Self::Unknown(None, reason.into())
}
}
// Methods regarding node count
impl JsValue {
pub fn total_nodes(&self) -> usize {
match self {
JsValue::Constant(_)
| JsValue::Url(_)
| JsValue::FreeVar(_)
| JsValue::Variable(_)
| JsValue::Module(..)
| JsValue::WellKnownObject(_)
| JsValue::WellKnownFunction(_)
| JsValue::Unknown(_, _)
| JsValue::Argument(..) => 1,
JsValue::Array { total_nodes: c, .. }
| JsValue::Object { total_nodes: c, .. }
| JsValue::Alternatives(c, _)
| JsValue::Concat(c, _)
| JsValue::Add(c, _)
| JsValue::Not(c, _)
| JsValue::Logical(c, _, _)
| JsValue::Binary(c, _, _, _)
| JsValue::Call(c, _, _)
| JsValue::SuperCall(c, _)
| JsValue::MemberCall(c, _, _, _)
| JsValue::Member(c, _, _)
| JsValue::Function(c, _, _) => *c,
}
}
fn update_total_nodes(&mut self) {
match self {
JsValue::Constant(_)
| JsValue::Url(_)
| JsValue::FreeVar(_)
| JsValue::Variable(_)
| JsValue::Module(..)
| JsValue::WellKnownObject(_)
| JsValue::WellKnownFunction(_)
| JsValue::Unknown(_, _)
| JsValue::Argument(..) => {}
JsValue::Array {
total_nodes: c,
items: list,
..
}
| JsValue::Alternatives(c, list)
| JsValue::Concat(c, list)
| JsValue::Add(c, list)
| JsValue::Logical(c, _, list) => {
*c = 1 + total_nodes(list);
}
JsValue::Binary(c, a, _, b) => {
*c = 1 + a.total_nodes() + b.total_nodes();
}
JsValue::Not(c, r) => {
*c = 1 + r.total_nodes();
}
JsValue::Object {
total_nodes: c,
parts,
mutable: _,
} => {
*c = 1 + parts
.iter()
.map(|v| match v {
ObjectPart::KeyValue(k, v) => k.total_nodes() + v.total_nodes(),
ObjectPart::Spread(s) => s.total_nodes(),
})
.sum::<usize>();
}
JsValue::Call(c, f, list) => {
*c = 1 + f.total_nodes() + total_nodes(list);
}
JsValue::SuperCall(c, list) => {
*c = 1 + total_nodes(list);
}
JsValue::MemberCall(c, o, m, list) => {
*c = 1 + o.total_nodes() + m.total_nodes() + total_nodes(list);
}
JsValue::Member(c, o, p) => {
*c = 1 + o.total_nodes() + p.total_nodes();
}
JsValue::Function(c, _, r) => {
*c = 1 + r.total_nodes();
}
}
}
#[cfg(debug_assertions)]
pub fn debug_assert_total_nodes_up_to_date(&mut self) {
let old = self.total_nodes();
self.update_total_nodes();
assert_eq!(
old,
self.total_nodes(),
"total nodes not up to date {:?}",
self
);
}
#[cfg(not(debug_assertions))]
pub fn debug_assert_total_nodes_up_to_date(&mut self) {}
pub fn ensure_node_limit(&mut self, limit: usize) {
fn cmp_nodes(a: &JsValue, b: &JsValue) -> Ordering {
a.total_nodes().cmp(&b.total_nodes())
}
fn make_max_unknown<'a>(iter: impl Iterator<Item = &'a mut JsValue>) {
if let Some(item) = iter.max_by(|a, b| cmp_nodes(a, b)) {
item.make_unknown_without_content("node limit reached");
}
}
if self.total_nodes() > limit {
match self {
JsValue::Constant(_)
| JsValue::Url(_)
| JsValue::FreeVar(_)
| JsValue::Variable(_)
| JsValue::Module(..)
| JsValue::WellKnownObject(_)
| JsValue::WellKnownFunction(_)
| JsValue::Unknown(_, _)
| JsValue::Argument(..) => self.make_unknown_without_content("node limit reached"),
JsValue::Array { items: list, .. }
| JsValue::Alternatives(_, list)
| JsValue::Concat(_, list)
| JsValue::Logical(_, _, list)
| JsValue::Add(_, list) => {
make_max_unknown(list.iter_mut());
self.update_total_nodes();
}
JsValue::Not(_, r) => {
r.make_unknown_without_content("node limit reached");
}
JsValue::Binary(_, a, _, b) => {
if a.total_nodes() > b.total_nodes() {
a.make_unknown_without_content("node limit reached");
} else {
b.make_unknown_without_content("node limit reached");