Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(es/minifier): Do not index a string with a surrogate pair #9013

Merged
merged 3 commits into from
Jun 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
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
Loading