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): Fix evaluation of String.charCodeAt #8946

Merged
merged 5 commits into from
May 13, 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
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());
",
);
}
Loading