Skip to content

Commit

Permalink
fix(es/minifier): Fix evaluation of String.charCodeAt (#8946)
Browse files Browse the repository at this point in the history
**Related issue:**

 - Closes #8943
  • Loading branch information
kdy1 committed May 13, 2024
1 parent 94ed67e commit 772c50f
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
43 changes: 43 additions & 0 deletions crates/swc_ecma_minifier/src/compress/pure/evaluate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -711,8 +711,13 @@ impl Pure<'_> {

let idx = value.round() as i64 as usize;
let c = s.value.chars().nth(idx);

match c {
Some(v) => {
let mut b = [0; 2];
v.encode_utf16(&mut b);
let v = b[0];

self.changed = true;
report_change!(
"evaluate: Evaluated `charCodeAt` of a string literal as `{}`",
Expand All @@ -738,6 +743,44 @@ impl Pure<'_> {
}
return;
}
"codePointAt" => {
if call.args.len() != 1 {
return;
}
if let Expr::Lit(Lit::Num(Number { value, .. })) = &*call.args[0].expr {
if value.fract() != 0.0 {
return;
}

let idx = value.round() as i64 as usize;
let c = s.value.chars().nth(idx);
match c {
Some(v) => {
self.changed = true;
report_change!(
"evaluate: Evaluated `codePointAt` of a string literal as `{}`",
v
);
*e = Expr::Lit(Lit::Num(Number {
span: call.span,
value: v as usize as f64,
raw: None,
}))
}
None => {
self.changed = true;
report_change!(
"evaluate: Evaluated `codePointAt` of a string literal as `NaN`",
);
*e = Expr::Ident(Ident::new(
"NaN".into(),
e.span().with_ctxt(SyntaxContext::empty()),
))
}
}
}
return;
}
_ => return,
};

Expand Down
13 changes: 13 additions & 0 deletions crates/swc_ecma_minifier/tests/exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11250,3 +11250,16 @@ fn issue_8937() {
",
);
}

#[test]
fn issue_8943() {
run_default_exec_test(
"
'use strict';
const k = (() => {
return '👨‍👩‍👦'.charCodeAt(0);
});
console.log(k());
",
);
}

0 comments on commit 772c50f

Please sign in to comment.