Unverified Commit 1095b9eb authored by Sam Poder's avatar Sam Poder Committed by GitHub

Fix short circuit evaluation of AND / OR in the Turbopack analyzer for string &…

Fix short circuit evaluation of AND / OR in the Turbopack analyzer for string & nullish-related methods (#94159)

Here is the original description of the bug:

```
1. shortcircuit_if_known predicates are swapped for Logical(And) and
Logical(Or) (lines 2541–2548, 2573–2582, 2634–2643)

is_nullish, is_string, and is_empty_string all do this for AND/OR:

LogicalOperator::And => shortcircuit_if_known(list, JsValue::is_truthy, …),
LogicalOperator::Or => shortcircuit_if_known(list, JsValue::is_falsy, …),

shortcircuit_if_known returns item_value(item) for the first item where
use_item == Some(true). But:
- a && b returns a when a is falsy, else b → use_item should be is_falsy.
- a || b returns a when a is truthy, else b → use_item should be is_truthy.

Concretely:
- is_nullish(1 && null): code does is_truthy(1) = Some(true) → return
is_nullish(1) = Some(false). JS answer is true. Wrong.
- is_nullish(null || 2): code does is_falsy(null) = Some(true) → return
is_nullish(null) = Some(true). JS answer is false. Wrong.
```

As mentioned, in the issue `is_string`, `is_empty_string`, and
`is_nullish`'s short circuit evaluation of `&&` and `||` was reversed.
This PR reverses them so that for AND expressions, the first false-y
value is evaluated (otherwise the last value is). For OR expressions,
the first truth-y value is evaluated (otherwise the last value is).

I’ve added unit tests to this PR. To verify these unit tests with
JavaScript’s behaviour I used Claude Code to generate this node script:

```javascript
const PREDICATES = {
  is_string: (v) => typeof v === 'string',
  is_empty_string: (v) => v === '',
  is_nullish: (v) => v == null,
  is_not_nullish: (v) => v != null,
}

const cases = [
  {
    test: 'is_string_constant',
    rust: `assert_eq!(value.is_string(), Some(true));`,
    expr: `'hello'`,
    predicate: 'is_string',
    expected: true,
  },

  {
    test: 'is_string_and_short_circuit',
    rust: `assert_eq!(eval("'hello' && 2").is_string(), Some(false));`,
    expr: `'hello' && 2`,
    predicate: 'is_string',
    expected: false,
  },
  {
    test: 'is_string_and_short_circuit',
    rust: `assert_eq!(eval("2 && 1 && 'hello'").is_string(), Some(true));`,
    expr: `2 && 1 && 'hello'`,
    predicate: 'is_string',
    expected: true,
  },

  {
    test: 'is_string_or_short_circuit',
    rust: `assert_eq!(eval("'hello' || 'bye' || 2").is_string(), Some(true));`,
    expr: `'hello' || 'bye' || 2`,
    predicate: 'is_string',
    expected: true,
  },
  {
    test: 'is_string_or_short_circuit',
    rust: `assert_eq!(eval("'hello' || 2 || 1 || 'bye'").is_string(), Some(true));`,
    expr: `'hello' || 2 || 1 || 'bye'`,
    predicate: 'is_string',
    expected: true,
  },
  {
    test: 'is_string_or_short_circuit',
    rust: `assert_eq!(eval("2 || 1 || 'hello' || 'bye'").is_string(), Some(false));`,
    expr: `2 || 1 || 'hello' || 'bye'`,
    predicate: 'is_string',
    expected: false,
  },

  {
    test: 'is_empty_string_and_short_circuit',
    rust: `assert_eq!(eval("'' && 'string'").is_empty_string(), Some(true));`,
    expr: `'' && 'string'`,
    predicate: 'is_empty_string',
    expected: true,
  },
  {
    test: 'is_empty_string_and_short_circuit',
    rust: `assert_eq!(eval("false && ''").is_empty_string(), Some(false));`,
    expr: `false && ''`,
    predicate: 'is_empty_string',
    expected: false,
  },
  {
    test: 'is_empty_string_and_short_circuit',
    rust: `assert_eq!(eval("0 && false && ''").is_empty_string(), Some(false));`,
    expr: `0 && false && ''`,
    predicate: 'is_empty_string',
    expected: false,
  },

  {
    test: 'is_empty_string_or_short_circuit',
    rust: `assert_eq!(eval("'' || 'string'").is_empty_string(), Some(false));`,
    expr: `'' || 'string'`,
    predicate: 'is_empty_string',
    expected: false,
  },
  {
    test: 'is_empty_string_or_short_circuit',
    rust: `assert_eq!(eval("false || ''").is_empty_string(), Some(true));`,
    expr: `false || ''`,
    predicate: 'is_empty_string',
    expected: true,
  },
  {
    test: 'is_empty_string_or_short_circuit',
    rust: `assert_eq!(eval("0 || false || ''").is_empty_string(), Some(true));`,
    expr: `0 || false || ''`,
    predicate: 'is_empty_string',
    expected: true,
  },

  {
    test: 'is_nullish_and_short_circuit',
    rust: `assert_eq!(eval("'' && null").is_nullish(), Some(false));`,
    expr: `'' && null`,
    predicate: 'is_nullish',
    expected: false,
  },
  {
    test: 'is_nullish_and_short_circuit',
    rust: `assert_eq!(eval("null && ''").is_nullish(), Some(true));`,
    expr: `null && ''`,
    predicate: 'is_nullish',
    expected: true,
  },
  {
    test: 'is_nullish_and_short_circuit',
    rust: `assert_eq!(eval("0 && null && ''").is_nullish(), Some(false));`,
    expr: `0 && null && ''`,
    predicate: 'is_nullish',
    expected: false,
  },
  {
    test: 'is_nullish_and_short_circuit',
    rust: `assert_eq!(eval("null && 1 && 2").is_nullish(), Some(true));`,
    expr: `null && 1 && 2`,
    predicate: 'is_nullish',
    expected: true,
  },

  {
    test: 'is_nullish_or_short_circuit',
    rust: `assert_eq!(eval("'' || null").is_nullish(), Some(true));`,
    expr: `'' || null`,
    predicate: 'is_nullish',
    expected: true,
  },
  {
    test: 'is_nullish_or_short_circuit',
    rust: `assert_eq!(eval("null || ''").is_nullish(), Some(false));`,
    expr: `null || ''`,
    predicate: 'is_nullish',
    expected: false,
  },
  {
    test: 'is_nullish_or_short_circuit',
    rust: `assert_eq!(eval("0 || '' || null").is_nullish(), Some(true));`,
    expr: `0 || '' || null`,
    predicate: 'is_nullish',
    expected: true,
  },
  {
    test: 'is_nullish_or_short_circuit',
    rust: `assert_eq!(eval("null || 1 || 2").is_nullish(), Some(false));`,
    expr: `null || 1 || 2`,
    predicate: 'is_nullish',
    expected: false,
  },

  {
    test: 'is_not_nullish_and_short_circuit',
    rust: `assert_eq!(eval("'' && null").is_not_nullish(), Some(true));`,
    expr: `'' && null`,
    predicate: 'is_not_nullish',
    expected: true,
  },
  {
    test: 'is_not_nullish_and_short_circuit',
    rust: `assert_eq!(eval("null && ''").is_not_nullish(), Some(false));`,
    expr: `null && ''`,
    predicate: 'is_not_nullish',
    expected: false,
  },
  {
    test: 'is_not_nullish_and_short_circuit',
    rust: `assert_eq!(eval("0 && null && ''").is_not_nullish(), Some(true));`,
    expr: `0 && null && ''`,
    predicate: 'is_not_nullish',
    expected: true,
  },
  {
    test: 'is_not_nullish_and_short_circuit',
    rust: `assert_eq!(eval("null && 1 && 2").is_not_nullish(), Some(false));`,
    expr: `null && 1 && 2`,
    predicate: 'is_not_nullish',
    expected: false,
  },

  {
    test: 'is_not_nullish_or_short_circuit',
    rust: `assert_eq!(eval("'' || null").is_not_nullish(), Some(false));`,
    expr: `'' || null`,
    predicate: 'is_not_nullish',
    expected: false,
  },
  {
    test: 'is_not_nullish_or_short_circuit',
    rust: `assert_eq!(eval("null || ''").is_not_nullish(), Some(true));`,
    expr: `null || ''`,
    predicate: 'is_not_nullish',
    expected: true,
  },
  {
    test: 'is_not_nullish_or_short_circuit',
    rust: `assert_eq!(eval("0 || '' || null").is_not_nullish(), Some(false));`,
    expr: `0 || '' || null`,
    predicate: 'is_not_nullish',
    expected: false,
  },
  {
    test: 'is_not_nullish_or_short_circuit',
    rust: `assert_eq!(eval("null || 1 || 2").is_not_nullish(), Some(true));`,
    expr: `null || 1 || 2`,
    predicate: 'is_not_nullish',
    expected: true,
  },
]

let passed = 0
let failed = 0
let currentTest = null

for (const c of cases) {
  if (c.test !== currentTest) {
    console.log(`\n#[test] fn ${c.test}()`)
    currentTest = c.test
  }
  console.log(`  ${c.rust}`)

  const result = (0, eval)(c.expr)
  const actual = PREDICATES[c.predicate](result)
  const ok = actual === c.expected
  const status = ok ? 'PASS' : 'FAIL'
  console.log(
    `    -> JS result = ${JSON.stringify(result)}, ${c.predicate} = ${actual}, expected = ${c.expected}  [${status}]`
  )

  if (ok) passed++
  else failed++
}

console.log(`\n${passed} passed, ${failed} failed`)
```

After running it on my machine:

```
28 passed, 0 failed
```

---------
Co-authored-by: 's avatarvercel[bot] <35613825+vercel[bot]@users.noreply.github.com>
Co-authored-by: 's avatarLuke Sandberg <lukesandberg@users.noreply.github.com>
parent 95f80a54
...@@ -10402,6 +10402,7 @@ dependencies = [ ...@@ -10402,6 +10402,7 @@ dependencies = [
"petgraph 0.8.3", "petgraph 0.8.3",
"phf", "phf",
"regex", "regex",
"rstest",
"rustc-hash 2.1.1", "rustc-hash 2.1.1",
"serde", "serde",
"serde_json", "serde_json",
......
...@@ -88,6 +88,7 @@ swc_core = { workspace = true, features = [ ...@@ -88,6 +88,7 @@ swc_core = { workspace = true, features = [
[dev-dependencies] [dev-dependencies]
criterion = { workspace = true, features = ["async_tokio"] } criterion = { workspace = true, features = ["async_tokio"] }
rstest = { workspace = true }
turbo-tasks-backend = { workspace = true } turbo-tasks-backend = { workspace = true }
turbo-tasks-malloc = { workspace = true, features = ["custom_allocator"] } turbo-tasks-malloc = { workspace = true, features = ["custom_allocator"] }
turbo-tasks-testing = { workspace = true } turbo-tasks-testing = { workspace = true }
......
...@@ -2526,10 +2526,10 @@ impl JsValue { ...@@ -2526,10 +2526,10 @@ impl JsValue {
}, },
JsValue::Logical(_, op, list) => match op { JsValue::Logical(_, op, list) => match op {
LogicalOperator::And => { LogicalOperator::And => {
shortcircuit_if_known(list, JsValue::is_truthy, JsValue::is_nullish) shortcircuit_if_known(list, JsValue::is_falsy, JsValue::is_nullish)
} }
LogicalOperator::Or => { LogicalOperator::Or => {
shortcircuit_if_known(list, JsValue::is_falsy, JsValue::is_nullish) shortcircuit_if_known(list, JsValue::is_truthy, JsValue::is_nullish)
} }
LogicalOperator::NullishCoalescing => all_if_known(list, JsValue::is_nullish), LogicalOperator::NullishCoalescing => all_if_known(list, JsValue::is_nullish),
}, },
...@@ -2558,10 +2558,10 @@ impl JsValue { ...@@ -2558,10 +2558,10 @@ impl JsValue {
} => merge_if_known(values, JsValue::is_empty_string), } => merge_if_known(values, JsValue::is_empty_string),
JsValue::Logical(_, op, list) => match op { JsValue::Logical(_, op, list) => match op {
LogicalOperator::And => { LogicalOperator::And => {
shortcircuit_if_known(list, JsValue::is_truthy, JsValue::is_empty_string) shortcircuit_if_known(list, JsValue::is_falsy, JsValue::is_empty_string)
} }
LogicalOperator::Or => { LogicalOperator::Or => {
shortcircuit_if_known(list, JsValue::is_falsy, JsValue::is_empty_string) shortcircuit_if_known(list, JsValue::is_truthy, JsValue::is_empty_string)
} }
LogicalOperator::NullishCoalescing => { LogicalOperator::NullishCoalescing => {
shortcircuit_if_known(list, JsValue::is_not_nullish, JsValue::is_empty_string) shortcircuit_if_known(list, JsValue::is_not_nullish, JsValue::is_empty_string)
...@@ -2619,10 +2619,10 @@ impl JsValue { ...@@ -2619,10 +2619,10 @@ impl JsValue {
JsValue::Add(_, list) => any_if_known(list, JsValue::is_string), JsValue::Add(_, list) => any_if_known(list, JsValue::is_string),
JsValue::Logical(_, op, list) => match op { JsValue::Logical(_, op, list) => match op {
LogicalOperator::And => { LogicalOperator::And => {
shortcircuit_if_known(list, JsValue::is_truthy, JsValue::is_string) shortcircuit_if_known(list, JsValue::is_falsy, JsValue::is_string)
} }
LogicalOperator::Or => { LogicalOperator::Or => {
shortcircuit_if_known(list, JsValue::is_falsy, JsValue::is_string) shortcircuit_if_known(list, JsValue::is_truthy, JsValue::is_string)
} }
LogicalOperator::NullishCoalescing => { LogicalOperator::NullishCoalescing => {
shortcircuit_if_known(list, JsValue::is_not_nullish, JsValue::is_string) shortcircuit_if_known(list, JsValue::is_not_nullish, JsValue::is_string)
...@@ -3996,6 +3996,7 @@ mod tests { ...@@ -3996,6 +3996,7 @@ mod tests {
use std::{mem::take, path::PathBuf, time::Instant}; use std::{mem::take, path::PathBuf, time::Instant};
use parking_lot::Mutex; use parking_lot::Mutex;
use rstest::rstest;
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use swc_core::{ use swc_core::{
common::{Mark, comments::SingleThreadedComments}, common::{Mark, comments::SingleThreadedComments},
...@@ -4491,4 +4492,198 @@ mod tests { ...@@ -4491,4 +4492,198 @@ mod tests {
fn jsvalue_size() { fn jsvalue_size() {
assert_eq!(32, size_of::<JsValue>()); assert_eq!(32, size_of::<JsValue>());
} }
#[test]
fn is_string_constant() {
let value = EvalContext::eval_single_expr_lit(&rcstr!("'hello'")).unwrap();
assert_eq!(value.is_string(), Some(true));
}
#[rstest]
#[case("1 && 'hello'")]
#[case("'hello' || 'bye' || 2")]
fn is_string_short_circuiting_positive(#[case] input: &str) {
assert_eq!(
EvalContext::eval_single_expr_lit(&input.into())
.unwrap()
.is_string(),
Some(true),
"expected '{}' to be a string",
input
);
}
#[rstest]
#[case("'hello' && 2")]
#[case("2 || 1 || 'hello' || 'bye'")]
fn is_string_short_circuiting_negative(#[case] input: &str) {
assert_eq!(
EvalContext::eval_single_expr_lit(&input.into())
.unwrap()
.is_string(),
Some(false),
"expected '{}' not to be a string",
input
);
}
#[rstest]
#[case("x && 2")]
#[case("1 && x")]
#[case("1 && 'a' && x")]
#[case("x || 'bye'")]
#[case("false || x")]
fn is_string_short_circuiting_unknown(#[case] input: &str) {
assert_eq!(
EvalContext::eval_single_expr_lit(&input.into())
.unwrap()
.is_string(),
None,
"expected to be unable to determine whether '{}' is a string",
input
);
}
#[rstest]
#[case("'' && 'string'")]
#[case("false || ''")]
#[case("1 && 'a' && ''")]
fn is_empty_string_short_circuiting_positive(#[case] input: &str) {
assert_eq!(
EvalContext::eval_single_expr_lit(&input.into())
.unwrap()
.is_empty_string(),
Some(true),
"expected '{}' to be an empty string",
input
);
}
#[rstest]
#[case("false && ''")]
#[case("'' || 'string'")]
#[case("'' || 0 || 'string'")]
fn is_empty_string_short_circuiting_negative(#[case] input: &str) {
assert_eq!(
EvalContext::eval_single_expr_lit(&input.into())
.unwrap()
.is_empty_string(),
Some(false),
"expected '{}' not to be an empty string",
input
);
}
#[rstest]
#[case("x && ''")]
#[case("1 && x")]
#[case("x || ''")]
#[case("'' || x")]
#[case("false || 0 || x")]
fn is_empty_string_short_circuiting_unknown(#[case] input: &str) {
assert_eq!(
EvalContext::eval_single_expr_lit(&input.into())
.unwrap()
.is_empty_string(),
None,
"expected to be unable to determine whether '{}' is an empty string",
input
);
}
#[rstest]
#[case("null && ''")]
#[case("'' || null")]
#[case("1 && 2 && null")]
fn is_nullish_short_circuiting_positive(#[case] input: &str) {
assert_eq!(
EvalContext::eval_single_expr_lit(&input.into())
.unwrap()
.is_nullish(),
Some(true),
"expected '{}' to be nullish",
input
);
}
#[rstest]
#[case("'' && null")]
#[case("null || ''")]
#[case("null || '' || 'a'")]
fn is_nullish_short_circuiting_negative(#[case] input: &str) {
assert_eq!(
EvalContext::eval_single_expr_lit(&input.into())
.unwrap()
.is_nullish(),
Some(false),
"expected '{}' not to be nullish",
input
);
}
#[rstest]
#[case("x && null")]
#[case("1 && x")]
#[case("x || null")]
#[case("null || x")]
#[case("false || x")]
#[case("1 && x && null")]
fn is_nullish_short_circuiting_unknown(#[case] input: &str) {
assert_eq!(
EvalContext::eval_single_expr_lit(&input.into())
.unwrap()
.is_nullish(),
None,
"expected to be unable to determine whether '{}' is nullish",
input
);
}
#[rstest]
#[case("'' && null")]
#[case("null || ''")]
#[case("null || 0 || 'a'")]
fn is_not_nullish_short_circuiting_positive(#[case] input: &str) {
assert_eq!(
EvalContext::eval_single_expr_lit(&input.into())
.unwrap()
.is_not_nullish(),
Some(true),
"expected '{}' to be not-nullish",
input
);
}
#[rstest]
#[case("null && ''")]
#[case("'' || null")]
#[case("'' || 0 || null")]
fn is_not_nullish_short_circuiting_negative(#[case] input: &str) {
assert_eq!(
EvalContext::eval_single_expr_lit(&input.into())
.unwrap()
.is_not_nullish(),
Some(false),
"expected '{}' not to be not-nullish",
input
);
}
#[rstest]
#[case("x && null")]
#[case("1 && x")]
#[case("x || null")]
#[case("null || x")]
#[case("false || x")]
#[case("false || x || ''")]
fn is_not_nullish_short_circuiting_unknown(#[case] input: &str) {
assert_eq!(
EvalContext::eval_single_expr_lit(&input.into())
.unwrap()
.is_not_nullish(),
None,
"expected to be unable to determine whether '{}' is not-nullish",
input
);
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment