File size: 29,479 Bytes
1e92f2d |
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 |
use std::mem::take;
use swc_core::ecma::atoms::atom;
use super::{ConstantNumber, ConstantValue, JsValue, LogicalOperator, LogicalProperty, ObjectPart};
use crate::analyzer::JsValueUrlKind;
/// Replaces some builtin values with their resulting values. Called early
/// without lazy nested values. This allows to skip a lot of work to process the
/// arguments.
pub fn early_replace_builtin(value: &mut JsValue) -> bool {
match value {
// matching calls like `callee(arg1, arg2, ...)`
JsValue::Call(_, box callee, args) => {
let args_have_side_effects = || args.iter().any(|arg| arg.has_side_effects());
match callee {
// We don't know what the callee is, so we can early return
&mut JsValue::Unknown {
original_value: _,
reason: _,
has_side_effects,
} => {
let has_side_effects = has_side_effects || args_have_side_effects();
value.make_unknown(has_side_effects, "unknown callee");
true
}
// We known that these callee will lead to an error at runtime, so we can skip
// processing them
JsValue::Constant(_)
| JsValue::Url(_, _)
| JsValue::WellKnownObject(_)
| JsValue::Array { .. }
| JsValue::Object { .. }
| JsValue::Alternatives { .. }
| JsValue::Concat(_, _)
| JsValue::Add(_, _)
| JsValue::Not(_, _) => {
let has_side_effects = args_have_side_effects();
value.make_unknown(has_side_effects, "non-function callee");
true
}
_ => false,
}
}
// matching calls with this context like `obj.prop(arg1, arg2, ...)`
JsValue::MemberCall(_, box obj, box prop, args) => {
let args_have_side_effects = || args.iter().any(|arg| arg.has_side_effects());
match obj {
// We don't know what the callee is, so we can early return
&mut JsValue::Unknown {
original_value: _,
reason: _,
has_side_effects,
} => {
let side_effects =
has_side_effects || prop.has_side_effects() || args_have_side_effects();
value.make_unknown(side_effects, "unknown callee object");
true
}
// otherwise we need to look at the property
_ => match prop {
// We don't know what the property is, so we can early return
&mut JsValue::Unknown {
original_value: _,
reason: _,
has_side_effects,
} => {
let side_effects = has_side_effects || args_have_side_effects();
value.make_unknown(side_effects, "unknown callee property");
true
}
_ => false,
},
}
}
// matching property access like `obj.prop` when we don't know what the obj is.
// We can early return here
&mut JsValue::Member(
_,
box JsValue::Unknown {
original_value: _,
reason: _,
has_side_effects,
},
box ref mut prop,
) => {
let side_effects = has_side_effects || prop.has_side_effects();
value.make_unknown(side_effects, "unknown object");
true
}
_ => false,
}
}
/// Replaces some builtin functions and values with their resulting values. In
/// contrast to early_replace_builtin this has all inner values already
/// processed.
pub fn replace_builtin(value: &mut JsValue) -> bool {
match value {
JsValue::Add(_, list) => {
// numeric addition
let mut sum = 0f64;
for arg in list {
let JsValue::Constant(ConstantValue::Num(num)) = arg else {
return false;
};
sum += num.0;
}
*value = JsValue::Constant(ConstantValue::Num(ConstantNumber(sum)));
true
}
// matching property access like `obj.prop`
// Accessing a property on something can be handled in some cases
JsValue::Member(_, box obj, prop) => match obj {
// matching property access when obj is a bunch of alternatives
// like `(obj1 | obj2 | obj3).prop`
// We expand these to `obj1.prop | obj2.prop | obj3.prop`
JsValue::Alternatives {
total_nodes: _,
values,
logical_property: _,
} => {
*value = JsValue::alternatives(
take(values)
.into_iter()
.map(|alt| JsValue::member(Box::new(alt), prop.clone()))
.collect(),
);
true
}
// matching property access on an array like `[1,2,3].prop` or `[1,2,3][1]`
&mut JsValue::Array {
ref mut items,
mutable,
..
} => {
fn items_to_alternatives(items: &mut Vec<JsValue>, prop: &mut JsValue) -> JsValue {
items.push(JsValue::unknown(
JsValue::member(Box::new(JsValue::array(Vec::new())), Box::new(take(prop))),
false,
"unknown array prototype methods or values",
));
JsValue::alternatives(take(items))
}
match &mut **prop {
// accessing a numeric property on an array like `[1,2,3][1]`
// We can replace this with the value at the index
JsValue::Constant(ConstantValue::Num(num @ ConstantNumber(_))) => {
if let Some(index) = num.as_u32_index() {
if index < items.len() {
*value = items.swap_remove(index);
if mutable {
value.add_unknown_mutations(true);
}
true
} else {
*value = JsValue::unknown(
JsValue::member(Box::new(take(obj)), Box::new(take(prop))),
false,
"invalid index",
);
true
}
} else {
value.make_unknown(false, "non-num constant property on array");
true
}
}
// accessing a non-numeric property on an array like `[1,2,3].length`
// We don't know what happens here
JsValue::Constant(_) => {
value.make_unknown(false, "non-num constant property on array");
true
}
// accessing multiple alternative properties on an array like `[1,2,3][(1 | 2 |
// prop3)]`
JsValue::Alternatives {
total_nodes: _,
values,
logical_property: _,
} => {
*value = JsValue::alternatives(
take(values)
.into_iter()
.map(|alt| JsValue::member(Box::new(obj.clone()), Box::new(alt)))
.collect(),
);
true
}
// otherwise we can say that this might gives an item of the array
// but we also add an unknown value to the alternatives for other properties
_ => {
*value = items_to_alternatives(items, prop);
true
}
}
}
// matching property access on an object like `{a: 1, b: 2}.a`
&mut JsValue::Object {
ref mut parts,
mutable,
..
} => {
fn parts_to_alternatives(
parts: &mut Vec<ObjectPart>,
prop: &mut Box<JsValue>,
include_unknown: bool,
) -> JsValue {
let mut values = Vec::new();
for part in parts {
match part {
ObjectPart::KeyValue(_, value) => {
values.push(take(value));
}
ObjectPart::Spread(_) => {
values.push(JsValue::unknown(
JsValue::member(
Box::new(JsValue::object(vec![take(part)])),
prop.clone(),
),
true,
"spread object",
));
}
}
}
if include_unknown {
values.push(JsValue::unknown(
JsValue::member(
Box::new(JsValue::object(Vec::new())),
Box::new(take(prop)),
),
true,
"unknown object prototype methods or values",
));
}
JsValue::alternatives(values)
}
/// Convert a list of potential values into
/// JsValue::Alternatives Optionally add a
/// unknown value to the alternatives for object prototype
/// methods
fn potential_values_to_alternatives(
mut potential_values: Vec<usize>,
parts: &mut Vec<ObjectPart>,
prop: &mut Box<JsValue>,
include_unknown: bool,
) -> JsValue {
// Note: potential_values are already in reverse order
let mut potential_values = take(parts)
.into_iter()
.enumerate()
.filter(|(i, _)| {
if potential_values.last() == Some(i) {
potential_values.pop();
true
} else {
false
}
})
.map(|(_, part)| part)
.collect();
parts_to_alternatives(&mut potential_values, prop, include_unknown)
}
match &mut **prop {
// matching constant string property access on an object like `{a: 1, b:
// 2}["a"]`
JsValue::Constant(ConstantValue::Str(_)) => {
let prop_str = prop.as_str().unwrap();
let mut potential_values = Vec::new();
for (i, part) in parts.iter_mut().enumerate().rev() {
match part {
ObjectPart::KeyValue(key, val) => {
if let Some(key) = key.as_str() {
if key == prop_str {
if potential_values.is_empty() {
*value = take(val);
} else {
potential_values.push(i);
*value = potential_values_to_alternatives(
potential_values,
parts,
prop,
false,
);
}
if mutable {
value.add_unknown_mutations(true);
}
return true;
}
} else {
potential_values.push(i);
}
}
ObjectPart::Spread(_) => {
value.make_unknown(true, "spread object");
return true;
}
}
}
if potential_values.is_empty() {
*value = JsValue::FreeVar(atom!("undefined"));
} else {
*value = potential_values_to_alternatives(
potential_values,
parts,
prop,
true,
);
}
if mutable {
value.add_unknown_mutations(true);
}
true
}
// matching multiple alternative properties on an object like `{a: 1, b: 2}[(a |
// b)]`
JsValue::Alternatives {
total_nodes: _,
values,
logical_property: _,
} => {
*value = JsValue::alternatives(
take(values)
.into_iter()
.map(|alt| JsValue::member(Box::new(obj.clone()), Box::new(alt)))
.collect(),
);
true
}
_ => {
*value = parts_to_alternatives(parts, prop, true);
true
}
}
}
_ => false,
},
// matching calls with this context like `obj.prop(arg1, arg2, ...)`
JsValue::MemberCall(_, box obj, box prop, args) => {
match obj {
// matching calls on an array like `[1,2,3].concat([4,5,6])`
JsValue::Array { items, mutable, .. } => {
// matching cases where the property is a const string
if let Some(str) = prop.as_str() {
match str {
// The Array.prototype.concat method
"concat" => {
if args.iter().all(|arg| {
matches!(
arg,
JsValue::Array { .. }
| JsValue::Constant(_)
| JsValue::Url(_, JsValueUrlKind::Absolute)
| JsValue::Concat(..)
| JsValue::Add(..)
| JsValue::WellKnownObject(_)
| JsValue::WellKnownFunction(_)
| JsValue::Function(..)
)
}) {
for arg in args {
match arg {
JsValue::Array {
items: inner,
mutable: inner_mutable,
..
} => {
items.extend(take(inner));
*mutable |= *inner_mutable;
}
JsValue::Constant(_)
| JsValue::Url(_, JsValueUrlKind::Absolute)
| JsValue::Concat(..)
| JsValue::Add(..)
| JsValue::WellKnownObject(_)
| JsValue::WellKnownFunction(_)
| JsValue::Function(..) => {
items.push(take(arg));
}
_ => {
unreachable!();
}
}
}
obj.update_total_nodes();
*value = take(obj);
return true;
}
}
// The Array.prototype.map method
"map" => {
if let Some(func) = args.first() {
*value = JsValue::array(
take(items)
.into_iter()
.enumerate()
.map(|(i, item)| {
JsValue::call(
Box::new(func.clone()),
vec![
item,
JsValue::Constant(ConstantValue::Num(
ConstantNumber(i as f64),
)),
],
)
})
.collect(),
);
return true;
}
}
_ => {}
}
}
}
// matching calls on multiple alternative objects like `(obj1 | obj2).prop(arg1,
// arg2, ...)`
JsValue::Alternatives {
total_nodes: _,
values,
logical_property: _,
} => {
*value = JsValue::alternatives(
take(values)
.into_iter()
.map(|alt| {
JsValue::member_call(
Box::new(alt),
Box::new(prop.clone()),
args.clone(),
)
})
.collect(),
);
return true;
}
_ => {}
}
// matching calls on strings like `"dayjs/locale/".concat(userLocale, ".js")`
if obj.is_string() == Some(true)
&& let Some(str) = prop.as_str()
{
// The String.prototype.concat method
if str == "concat" {
let mut values = vec![take(obj)];
values.extend(take(args));
*value = JsValue::concat(values);
return true;
}
}
// without special handling, we convert it into a normal call like
// `(obj.prop)(arg1, arg2, ...)`
*value = JsValue::call(
Box::new(JsValue::member(Box::new(take(obj)), Box::new(take(prop)))),
take(args),
);
true
}
// match calls when the callee are multiple alternative functions like `(func1 |
// func2)(arg1, arg2, ...)`
JsValue::Call(
_,
box JsValue::Alternatives {
total_nodes: _,
values,
logical_property: _,
},
args,
) => {
*value = JsValue::alternatives(
take(values)
.into_iter()
.map(|alt| JsValue::call(Box::new(alt), args.clone()))
.collect(),
);
true
}
// match object literals
JsValue::Object { parts, mutable, .. } => {
// If the object contains any spread, we might be able to flatten that
if parts
.iter()
.any(|part| matches!(part, ObjectPart::Spread(JsValue::Object { .. })))
{
let old_parts = take(parts);
for part in old_parts {
if let ObjectPart::Spread(JsValue::Object {
parts: inner_parts,
mutable: inner_mutable,
..
}) = part
{
parts.extend(inner_parts);
*mutable |= inner_mutable;
} else {
parts.push(part);
}
}
value.update_total_nodes();
true
} else {
false
}
}
// match logical expressions like `a && b` or `a || b || c` or `a ?? b`
// Reduce logical expressions to their final value(s)
JsValue::Logical(_, op, parts) => {
let len = parts.len();
let input_parts: Vec<JsValue> = take(parts);
*parts = Vec::with_capacity(len);
let mut part_properties = Vec::with_capacity(len);
for (i, part) in input_parts.into_iter().enumerate() {
// The last part is never skipped.
if i == len - 1 {
// We intentionally omit the part_properties for the last part.
// This isn't always needed so we only compute it when actually needed.
parts.push(part);
break;
}
let property = match op {
LogicalOperator::And => part.is_truthy(),
LogicalOperator::Or => part.is_falsy(),
LogicalOperator::NullishCoalescing => part.is_nullish(),
};
// We might know at compile-time if a part is skipped or the final value.
match property {
Some(true) => {
// We known this part is skipped, so we can remove it.
continue;
}
Some(false) => {
// We known this part is the final value, so we can remove the rest.
part_properties.push(property);
parts.push(part);
break;
}
None => {
// We don't know if this part is skipped or the final value, so we keep it.
part_properties.push(property);
parts.push(part);
continue;
}
}
}
// If we reduced the expression to a single value, we can replace it.
if parts.len() == 1 {
*value = parts.pop().unwrap();
true
} else {
// If not, we know that it will be one of the remaining values.
let last_part = parts.last().unwrap();
let property = match op {
LogicalOperator::And => last_part.is_truthy(),
LogicalOperator::Or => last_part.is_falsy(),
LogicalOperator::NullishCoalescing => last_part.is_nullish(),
};
part_properties.push(property);
let (any_unset, all_set) =
part_properties
.iter()
.fold((false, true), |(any_unset, all_set), part| match part {
Some(true) => (any_unset, all_set),
Some(false) => (true, false),
None => (any_unset, false),
});
let property = match op {
LogicalOperator::Or => {
if any_unset {
Some(LogicalProperty::Truthy)
} else if all_set {
Some(LogicalProperty::Falsy)
} else {
None
}
}
LogicalOperator::And => {
if any_unset {
Some(LogicalProperty::Falsy)
} else if all_set {
Some(LogicalProperty::Truthy)
} else {
None
}
}
LogicalOperator::NullishCoalescing => {
if any_unset {
Some(LogicalProperty::NonNullish)
} else if all_set {
Some(LogicalProperty::Nullish)
} else {
None
}
}
};
if let Some(property) = property {
*value = JsValue::alternatives_with_additional_property(take(parts), property);
true
} else {
*value = JsValue::alternatives(take(parts));
true
}
}
}
JsValue::Tenary(_, test, cons, alt) => {
if test.is_truthy() == Some(true) {
*value = take(cons);
true
} else if test.is_falsy() == Some(true) {
*value = take(alt);
true
} else {
false
}
}
// match a binary operator like `a == b`
JsValue::Binary(..) => {
if let Some(v) = value.is_truthy() {
let v = if v {
ConstantValue::True
} else {
ConstantValue::False
};
*value = JsValue::Constant(v);
true
} else {
false
}
}
// match the not operator like `!a`
// Evaluate not when the inner value is truthy or falsy
JsValue::Not(_, inner) => match inner.is_truthy() {
Some(true) => {
*value = JsValue::Constant(ConstantValue::False);
true
}
Some(false) => {
*value = JsValue::Constant(ConstantValue::True);
true
}
None => false,
},
JsValue::Iterated(_, iterable) => {
if let JsValue::Array { items, mutable, .. } = &mut **iterable {
let mut new_value = JsValue::alternatives(take(items));
if *mutable {
new_value.add_unknown_mutations(true);
}
*value = new_value;
true
} else {
false
}
}
JsValue::Awaited(_, operand) => {
if let JsValue::Promise(_, inner) = &mut **operand {
*value = take(inner);
true
} else {
*value = take(operand);
true
}
}
_ => false,
}
}
|