fix(es/typescript): Fix panic on invalid jsx pragma (#8513)

**Description:**

Currently a jsx pragma with an invalid js identifier (eg, with dashes: `@jsx bad-pragma` causes a panic.

This PR prevents a panic and will ignore an invalid pragma in a comment.

(There may be an argument for showing an error or warning instead, but
given a jsx pragma is still valid ES I'm not sure whether that makes
sense?)

[Original (Deno) issue
here](https://github.com/denoland/deno/issues/21927)
This commit is contained in:
melbourne2991 2024-01-19 12:25:46 +11:00 committed by GitHub
parent 3c00098dbe
commit f40f59bd70
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 38 additions and 13 deletions

View File

@ -122,14 +122,12 @@ where
/// Get an [Id] which will used by expression.
///
/// For `React#1.createElement`, this returns `React#1`.
fn id_for_jsx(e: &Expr) -> Id {
fn id_for_jsx(e: &Expr) -> Option<Id> {
match e {
Expr::Ident(i) => i.to_id(),
Expr::Member(MemberExpr { obj, .. }) => id_for_jsx(obj),
Expr::Lit(Lit::Null(..)) => ("null".into(), Default::default()),
_ => {
panic!("failed to determine top-level Id for jsx expression")
}
Expr::Ident(i) => Some(i.to_id()),
Expr::Member(MemberExpr { obj, .. }) => Some(id_for_jsx(obj)).flatten(),
Expr::Lit(Lit::Null(..)) => Some(("null".into(), Default::default())),
_ => None,
}
}
@ -175,8 +173,8 @@ where
self.top_level_mark,
);
let pragma_id = id_for_jsx(&pragma);
let pragma_frag_id = id_for_jsx(&pragma_frag);
let pragma_id = id_for_jsx(&pragma).unwrap();
let pragma_frag_id = id_for_jsx(&pragma_frag).unwrap();
self.id_usage.insert(pragma_id);
self.id_usage.insert(pragma_frag_id);
@ -199,13 +197,15 @@ where
});
if let Some(pragma) = pragma {
let pragma_id = id_for_jsx(&pragma);
self.id_usage.insert(pragma_id);
if let Some(pragma_id) = id_for_jsx(&pragma) {
self.id_usage.insert(pragma_id);
}
}
if let Some(pragma_frag) = pragma_frag {
let pragma_frag_id = id_for_jsx(&pragma_frag);
self.id_usage.insert(pragma_frag_id);
if let Some(pragma_frag_id) = id_for_jsx(&pragma_frag) {
self.id_usage.insert(pragma_frag_id);
}
}
}
}

View File

@ -2797,3 +2797,27 @@ test!(
console.log(I.A);
"#
);
test!(
Syntax::Typescript(TsConfig::default()),
|t| {
let unresolved_mark = Mark::new();
let top_level_mark = Mark::new();
chain!(
resolver(unresolved_mark, top_level_mark, false),
tsx(
t.cm.clone(),
typescript::Config {
verbatim_module_syntax: false,
..Default::default()
},
TsxConfig::default(),
t.comments.clone(),
top_level_mark,
)
)
},
ts_jsx_bad_pragma,
r#"/** @jsx bad-pragma */"#
);