Skip to content

Commit

Permalink
fix(es/minifier): Do not index a string with a surrogate pair (#9013)
Browse files Browse the repository at this point in the history
**Related issue:**

 - Closes #9008
  • Loading branch information
kdy1 authored Jun 2, 2024
1 parent 04c1839 commit 2879a4d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 9 deletions.
5 changes: 5 additions & 0 deletions crates/swc_ecma_minifier/tests/exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11294,6 +11294,11 @@ fn issue_8964() {
);
}

#[test]
fn issue_9008() {
run_default_exec_test("console.log('💖'[0]);")
}

#[test]
fn issue_8982_1() {
run_default_exec_test(
Expand Down
20 changes: 11 additions & 9 deletions crates/swc_ecma_transforms_optimization/src/simplify/expr/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,13 +159,11 @@ impl SimplifyExpr {

// 'foo'[1]
KnownOp::Index(idx) if (idx as usize) < value.len() => {
self.changed = true;

if idx < 0 {
self.changed = true;
*expr = *undefined(*span)
} else {
let value = nth_char(value, idx as _);

} else if let Some(value) = nth_char(value, idx as _) {
self.changed = true;
*expr = Expr::Lit(Lit::Str(Str {
raw: None,
value: value.into(),
Expand Down Expand Up @@ -1661,9 +1659,13 @@ where
ctx.preserve_effects(span, Expr::Lit(Lit::Bool(Bool { value, span })), orig)
}

fn nth_char(s: &str, mut idx: usize) -> Cow<str> {
fn nth_char(s: &str, mut idx: usize) -> Option<Cow<str>> {
if s.chars().any(|c| c.len_utf16() > 1) {
return None;
}

if !s.contains("\\ud") && !s.contains("\\uD") {
return Cow::Owned(s.chars().nth(idx).unwrap().to_string());
return Some(Cow::Owned(s.chars().nth(idx).unwrap().to_string()));
}

let mut iter = s.chars().peekable();
Expand All @@ -1674,7 +1676,7 @@ fn nth_char(s: &str, mut idx: usize) -> Cow<str> {
let mut buf = String::new();
buf.push('\\');
buf.extend(iter.take(5));
return Cow::Owned(buf);
return Some(Cow::Owned(buf));
} else {
for _ in 0..5 {
iter.next();
Expand All @@ -1683,7 +1685,7 @@ fn nth_char(s: &str, mut idx: usize) -> Cow<str> {
}

if idx == 0 {
return Cow::Owned(c.to_string());
return Some(Cow::Owned(c.to_string()));
}

idx -= 1;
Expand Down

0 comments on commit 2879a4d

Please sign in to comment.