From d03139e6bf26b822f1c4a212d789d25112541336 Mon Sep 17 00:00:00 2001 From: Aryan-Mi Date: Wed, 4 Nov 2026 11:20:26 +0100 Subject: [PATCH] fix: register hook translators before transforming nested macros --- crates/lingui_macro/src/js_macro_folder.rs | 170 ++++++++++++++++ crates/lingui_macro/src/lib.rs | 184 +----------------- ...ested_plural_in_callback_using_core_t.snap | 17 ++ ...sted_plural_in_callback_using_outer_t.snap | 24 +++ ..._lingui__nested_plural_in_forward_ref.snap | 24 +++ ..._nested_plural_in_function_expression.snap | 24 +++ .../use_lingui__nested_plural_in_memo.snap | 24 +++ ..._lingui__nested_plural_in_nested_hook.snap | 35 ++++ ...ingui__nested_plural_in_object_method.snap | 28 +++ ...plural_in_wrapped_function_expression.snap | 24 +++ crates/lingui_macro/tests/use_lingui.rs | 106 ++++++++++ 11 files changed, 482 insertions(+), 178 deletions(-) create mode 100644 crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_callback_using_core_t.snap create mode 100644 crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_callback_using_outer_t.snap create mode 100644 crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_forward_ref.snap create mode 100644 crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_function_expression.snap create mode 100644 crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_memo.snap create mode 100644 crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_nested_hook.snap create mode 100644 crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_object_method.snap create mode 100644 crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_wrapped_function_expression.snap diff --git a/crates/lingui_macro/src/js_macro_folder.rs b/crates/lingui_macro/src/js_macro_folder.rs index 1789be4..e4b232c 100644 --- a/crates/lingui_macro/src/js_macro_folder.rs +++ b/crates/lingui_macro/src/js_macro_folder.rs @@ -4,8 +4,11 @@ use crate::comment_directive::DirectiveValues; use crate::generate_id::generate_message_id; use crate::macro_utils::*; use crate::tokens::MsgToken; +use crate::IdentReplacer; use swc_core::common::comments::Comments; use swc_core::common::{Span, Spanned, SyntaxContext}; +use swc_core::ecma::utils::{private_ident, quote_ident}; +use swc_core::plugin::errors::HANDLER; use swc_core::{ common::DUMMY_SP, ecma::{ @@ -31,6 +34,142 @@ where JsMacroFolder { ctx, comments } } + fn handle_use_lingui(&mut self, n: FunctionBody) -> FunctionBody { + let mut ctx = self.ctx.clone(); + + let mut ident_replacer: Option = None; + + let stmts: Vec = n + .stmts + .into_iter() + .map(|stmt| match stmt { + Stmt::Decl(Decl::Var(var_decl)) => { + let decl = *var_decl; + + let underscore_ident = private_ident!("$__"); + let decls: Vec = decl + .decls + .into_iter() + .map(|declarator| { + if let Some(init) = &declarator.init { + let expr = init.as_ref(); + + if let Expr::Call(call) = &expr { + if match_callee_name(call, |n| { + self.ctx.is_lingui_ident("useLingui", n) + }) + .is_some() + { + self.ctx.should_add_uselingui_import = true; + + if let Pat::Object(obj_pat) = declarator.name { + let mut new_props: Vec = obj_pat + .props + .into_iter() + .filter_map(|prop| { + if let Some(ident) = + get_local_ident_from_object_pat_prop( + &prop, "t", + ) + { + ctx.register_reference( + &"t".into(), + &ident.to_id(), + ); + + ident_replacer = Some(IdentReplacer { + from: ident.to_id(), + to: underscore_ident.clone(), + }); + + ctx.runtime_idents.use_lingui_t = + Some(underscore_ident.clone()); + + // `t` is dropped: the `_: $__` binding + // pushed below is called directly + return None; + } + + Some(prop) + }) + .collect(); + + new_props.push(ObjectPatProp::KeyValue( + KeyValuePatProp { + value: Box::new(Pat::Ident( + underscore_ident.clone().into(), + )), + key: PropName::Ident(quote_ident!("_")), + }, + )); + + return VarDeclarator { + init: Some(Box::new(Expr::Call(CallExpr { + callee: Callee::Expr(Box::new(Expr::Ident( + ctx.runtime_idents + .use_lingui + .clone() + .into(), + ))), + ..call.clone() + }))), + + definite: true, + span: declarator.span, + name: Pat::Object(ObjectPat { + optional: false, + type_ann: None, + span: DUMMY_SP, + props: new_props, + }), + }; + } else { + HANDLER.with(|h| { + h.struct_span_warn(decl.span, "Unsupported Syntax") + .note( +r#"You have to destructure `t` when using the `useLingui` macro, i.e: + const { t } = useLingui() + or + const { t: _ } = useLingui()"#) + .emit() + }); + } + } + } + } + + declarator + }) + .collect(); + + Stmt::Decl(Decl::Var(Box::new(VarDecl { + span: decl.span, + decls, + declare: false, + kind: decl.kind, + ctxt: SyntaxContext::empty(), + }))) + } + _ => stmt, + }) + .collect(); + + let mut block = FunctionBody { + span: n.span, + stmts, + }; + + // use lingui matched above + if let Some(mut replacer) = ident_replacer { + block = block + .fold_children_with(&mut JsMacroFolder::new(&mut ctx, self.comments)) + // replace other + .fold_children_with(&mut replacer); + } + + block + } + fn create_message_descriptor_from_tokens( &mut self, tokens: Vec, @@ -245,6 +384,37 @@ impl Fold for JsMacroFolder<'_, C> where C: Comments, { + // Enter hook scopes before folding their expressions, including functions + // reached through a call argument or another expression. Otherwise a nested + // plural can be compiled before its enclosing hook-bound `t` is registered. + fn fold_arrow_expr(&mut self, n: ArrowExpr) -> ArrowExpr { + let mut func = n; + + if let ArrowFunctionBody::FunctionBody(body) = *func.body { + func = ArrowExpr { + body: Box::new(ArrowFunctionBody::FunctionBody( + self.handle_use_lingui(body), + )), + ..func + } + } + + func.fold_children_with(self) + } + + fn fold_function(&mut self, n: Function) -> Function { + let mut func = n; + + if let Some(body) = func.body { + func = Function { + body: Some(self.handle_use_lingui(body)), + ..func + }; + } + + func.fold_children_with(self) + } + fn fold_expr(&mut self, expr: Expr) -> Expr { // t`Message` if let Expr::TaggedTpl(tagged_tpl) = &expr { diff --git a/crates/lingui_macro/src/lib.rs b/crates/lingui_macro/src/lib.rs index 411df45..db288b4 100644 --- a/crates/lingui_macro/src/lib.rs +++ b/crates/lingui_macro/src/lib.rs @@ -1,10 +1,8 @@ use std::collections::HashSet; use swc_core::common::sync::Lrc; -use swc_core::common::{SourceMapper, Span, Spanned, SyntaxContext, DUMMY_SP}; +use swc_core::common::{SourceMapper, Span, Spanned, DUMMY_SP}; use swc_core::common::comments::*; -use swc_core::ecma::utils::private_ident; -use swc_core::plugin::errors::HANDLER; use swc_core::{ ecma::{ ast::*, @@ -269,142 +267,6 @@ where }, } } - - pub fn handle_use_lingui(&mut self, n: FunctionBody) -> FunctionBody { - let mut ctx = self.ctx.clone(); - - let mut ident_replacer: Option = None; - - let stmts: Vec = n - .stmts - .into_iter() - .map(|stmt| match stmt { - Stmt::Decl(Decl::Var(var_decl)) => { - let decl = *var_decl; - - let underscore_ident = private_ident!("$__"); - let decls: Vec = decl - .decls - .into_iter() - .map(|declarator| { - if let Some(init) = &declarator.init { - let expr = init.as_ref(); - - if let Expr::Call(call) = &expr { - if match_callee_name(call, |n| { - self.ctx.is_lingui_ident("useLingui", n) - }) - .is_some() - { - self.ctx.should_add_uselingui_import = true; - - if let Pat::Object(obj_pat) = declarator.name { - let mut new_props: Vec = obj_pat - .props - .into_iter() - .filter_map(|prop| { - if let Some(ident) = - get_local_ident_from_object_pat_prop( - &prop, "t", - ) - { - ctx.register_reference( - &"t".into(), - &ident.to_id(), - ); - - ident_replacer = Some(IdentReplacer { - from: ident.to_id(), - to: underscore_ident.clone(), - }); - - ctx.runtime_idents.use_lingui_t = - Some(underscore_ident.clone()); - - // `t` is dropped: the `_: $__` binding - // pushed below is called directly - return None; - } - - Some(prop) - }) - .collect(); - - new_props.push(ObjectPatProp::KeyValue( - KeyValuePatProp { - value: Box::new(Pat::Ident( - underscore_ident.clone().into(), - )), - key: PropName::Ident(quote_ident!("_")), - }, - )); - - return VarDeclarator { - init: Some(Box::new(Expr::Call(CallExpr { - callee: Callee::Expr(Box::new(Expr::Ident( - ctx.runtime_idents - .use_lingui - .clone() - .into(), - ))), - ..call.clone() - }))), - - definite: true, - span: declarator.span, - name: Pat::Object(ObjectPat { - optional: false, - type_ann: None, - span: DUMMY_SP, - props: new_props, - }), - }; - } else { - HANDLER.with(|h| { - h.struct_span_warn(decl.span, "Unsupported Syntax") - .note( -r#"You have to destructure `t` when using the `useLingui` macro, i.e: - const { t } = useLingui() - or - const { t: _ } = useLingui()"#) - .emit() - }); - } - } - } - } - - declarator - }) - .collect(); - - Stmt::Decl(Decl::Var(Box::new(VarDecl { - span: decl.span, - decls, - declare: false, - kind: decl.kind, - ctxt: SyntaxContext::empty(), - }))) - } - _ => stmt, - }) - .collect(); - - let mut block = FunctionBody { - span: n.span, - stmts, - }; - - // use lingui matched above - if let Some(mut replacer) = ident_replacer { - block = block - .fold_children_with(&mut JsMacroFolder::new(&mut ctx, &self.comments)) - // replace other - .fold_children_with(&mut replacer); - } - - block.fold_children_with(self) - } } impl Fold for LinguiMacroFolder @@ -491,44 +353,14 @@ where node } - fn fold_arrow_expr(&mut self, n: ArrowExpr) -> ArrowExpr { - // If no package that we care about is imported, skip the following - // transformation logic. + fn fold_function(&mut self, function: Function) -> Function { if !self.has_lingui_macro_imports { - return n; - } - - let mut func = n; - - if let ArrowFunctionBody::FunctionBody(body) = *func.body { - func = ArrowExpr { - body: Box::new(ArrowFunctionBody::FunctionBody( - self.handle_use_lingui(body), - )), - ..func - } + return function; } - func.fold_children_with(self) - } - - fn fold_function(&mut self, n: Function) -> Function { - // If no package that we care about is imported, skip the following - // transformation logic. - if !self.has_lingui_macro_imports { - return n; - } - - let mut func = n; - - if let Some(body) = func.body { - func = Function { - body: Some(self.handle_use_lingui(body)), - ..func - }; - } - - func.fold_children_with(self) + JsMacroFolder::new(&mut self.ctx, &self.comments) + .fold_function(function) + .fold_children_with(self) } fn fold_expr(&mut self, expr: Expr) -> Expr { @@ -538,10 +370,6 @@ where return expr; } - if let Expr::Arrow(arrow_expr) = expr { - return Expr::Arrow(self.fold_arrow_expr(arrow_expr)); - } - let mut folder = JsMacroFolder::new(&mut self.ctx, &self.comments); folder.fold_expr(expr).fold_children_with(self) diff --git a/crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_callback_using_core_t.snap b/crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_callback_using_core_t.snap new file mode 100644 index 0000000..ff54e8e --- /dev/null +++ b/crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_callback_using_core_t.snap @@ -0,0 +1,17 @@ +--- +source: crates/lingui_macro/tests/use_lingui.rs +--- +import { t, plural } from "@lingui/core/macro"; + +const Component = wrap(() => t`Selected ${plural(count, { one: '# item', other: '# items' })}`); + +↓ ↓ ↓ ↓ ↓ ↓ + +import { i18n as $_i18n } from "@lingui/core"; +const Component = wrap(()=>$_i18n._(/*i18n*/ { + id: "oDeoLE", + message: "Selected {count, plural, one {# item} other {# items}}", + values: { + count: count + } + })); diff --git a/crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_callback_using_outer_t.snap b/crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_callback_using_outer_t.snap new file mode 100644 index 0000000..d01015f --- /dev/null +++ b/crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_callback_using_outer_t.snap @@ -0,0 +1,24 @@ +--- +source: crates/lingui_macro/tests/use_lingui.rs +--- +import { useLingui } from "@lingui/react/macro"; +import { plural } from "@lingui/core/macro"; + +function Component() { + const { t } = useLingui(); + return wrap(() => t`Selected ${plural(count, { one: '# item', other: '# items' })}`); +} + +↓ ↓ ↓ ↓ ↓ ↓ + +import { useLingui as $_useLingui } from "@lingui/react"; +function Component() { + const { _: $__ } = $_useLingui(); + return wrap(()=>$__(/*i18n*/ { + id: "oDeoLE", + message: "Selected {count, plural, one {# item} other {# items}}", + values: { + count: count + } + })); +} diff --git a/crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_forward_ref.snap b/crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_forward_ref.snap new file mode 100644 index 0000000..c21c319 --- /dev/null +++ b/crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_forward_ref.snap @@ -0,0 +1,24 @@ +--- +source: crates/lingui_macro/tests/use_lingui.rs +--- +import { useLingui } from "@lingui/react/macro"; +import { plural } from "@lingui/core/macro"; + +const Component = forwardRef(() => { + const { t } = useLingui(); + return t`Selected ${plural(count, { one: '# item', other: '# items' })}`; +}); + +↓ ↓ ↓ ↓ ↓ ↓ + +import { useLingui as $_useLingui } from "@lingui/react"; +const Component = forwardRef(()=>{ + const { _: $__ } = $_useLingui(); + return $__(/*i18n*/ { + id: "oDeoLE", + message: "Selected {count, plural, one {# item} other {# items}}", + values: { + count: count + } + }); +}); diff --git a/crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_function_expression.snap b/crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_function_expression.snap new file mode 100644 index 0000000..416a83a --- /dev/null +++ b/crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_function_expression.snap @@ -0,0 +1,24 @@ +--- +source: crates/lingui_macro/tests/use_lingui.rs +--- +import { useLingui } from "@lingui/react/macro"; +import { plural } from "@lingui/core/macro"; + +const Component = function () { + const { t } = useLingui(); + return t`Selected ${plural(count, { one: '# item', other: '# items' })}`; +}; + +↓ ↓ ↓ ↓ ↓ ↓ + +import { useLingui as $_useLingui } from "@lingui/react"; +const Component = function() { + const { _: $__ } = $_useLingui(); + return $__(/*i18n*/ { + id: "oDeoLE", + message: "Selected {count, plural, one {# item} other {# items}}", + values: { + count: count + } + }); +}; diff --git a/crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_memo.snap b/crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_memo.snap new file mode 100644 index 0000000..c30a45f --- /dev/null +++ b/crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_memo.snap @@ -0,0 +1,24 @@ +--- +source: crates/lingui_macro/tests/use_lingui.rs +--- +import { useLingui } from "@lingui/react/macro"; +import { plural } from "@lingui/core/macro"; + +const Component = memo(() => { + const { t } = useLingui(); + return t`Selected ${plural(count, { one: '# item', other: '# items' })}`; +}); + +↓ ↓ ↓ ↓ ↓ ↓ + +import { useLingui as $_useLingui } from "@lingui/react"; +const Component = memo(()=>{ + const { _: $__ } = $_useLingui(); + return $__(/*i18n*/ { + id: "oDeoLE", + message: "Selected {count, plural, one {# item} other {# items}}", + values: { + count: count + } + }); +}); diff --git a/crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_nested_hook.snap b/crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_nested_hook.snap new file mode 100644 index 0000000..37ee750 --- /dev/null +++ b/crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_nested_hook.snap @@ -0,0 +1,35 @@ +--- +source: crates/lingui_macro/tests/use_lingui.rs +--- +import { useLingui } from "@lingui/react/macro"; +import { plural } from "@lingui/core/macro"; + +function Outer() { + const { t } = useLingui(); + const label = t`Outer`; + return wrap(() => { + const { t } = useLingui(); + return t`Selected ${plural(count, { one: '# item', other: '# items' })}`; + }); +} + +↓ ↓ ↓ ↓ ↓ ↓ + +import { useLingui as $_useLingui } from "@lingui/react"; +function Outer() { + const { _: $__ } = $_useLingui(); + const label = $__(/*i18n*/ { + id: "wVGQ6j", + message: "Outer" + }); + return wrap(()=>{ + const { _: $__ } = $_useLingui(); + return $__(/*i18n*/ { + id: "oDeoLE", + message: "Selected {count, plural, one {# item} other {# items}}", + values: { + count: count + } + }); + }); +} diff --git a/crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_object_method.snap b/crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_object_method.snap new file mode 100644 index 0000000..7b366ad --- /dev/null +++ b/crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_object_method.snap @@ -0,0 +1,28 @@ +--- +source: crates/lingui_macro/tests/use_lingui.rs +--- +import { useLingui } from "@lingui/react/macro"; +import { plural } from "@lingui/core/macro"; + +const obj = { + Component() { + const { t } = useLingui(); + return t`Selected ${plural(count, { one: '# item', other: '# items' })}`; + } +}; + +↓ ↓ ↓ ↓ ↓ ↓ + +import { useLingui as $_useLingui } from "@lingui/react"; +const obj = { + Component () { + const { _: $__ } = $_useLingui(); + return $__(/*i18n*/ { + id: "oDeoLE", + message: "Selected {count, plural, one {# item} other {# items}}", + values: { + count: count + } + }); + } +}; diff --git a/crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_wrapped_function_expression.snap b/crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_wrapped_function_expression.snap new file mode 100644 index 0000000..9f4950f --- /dev/null +++ b/crates/lingui_macro/tests/snapshots/use_lingui__nested_plural_in_wrapped_function_expression.snap @@ -0,0 +1,24 @@ +--- +source: crates/lingui_macro/tests/use_lingui.rs +--- +import { useLingui } from "@lingui/react/macro"; +import { plural } from "@lingui/core/macro"; + +const Component = wrap(function Component() { + const { t } = useLingui(); + return t`Selected ${plural(count, { one: '# item', other: '# items' })}`; +}); + +↓ ↓ ↓ ↓ ↓ ↓ + +import { useLingui as $_useLingui } from "@lingui/react"; +const Component = wrap(function Component() { + const { _: $__ } = $_useLingui(); + return $__(/*i18n*/ { + id: "oDeoLE", + message: "Selected {count, plural, one {# item} other {# items}}", + values: { + count: count + } + }); +}); diff --git a/crates/lingui_macro/tests/use_lingui.rs b/crates/lingui_macro/tests/use_lingui.rs index 38ac5e7..55702ae 100644 --- a/crates/lingui_macro/tests/use_lingui.rs +++ b/crates/lingui_macro/tests/use_lingui.rs @@ -217,3 +217,109 @@ export function Label({ device }) { } "# ); + +to!( + nested_plural_in_forward_ref, + r#" +import { useLingui } from "@lingui/react/macro"; +import { plural } from "@lingui/core/macro"; + +const Component = forwardRef(() => { + const { t } = useLingui(); + return t`Selected ${plural(count, { one: '# item', other: '# items' })}`; +}); + "# +); + +to!( + nested_plural_in_memo, + r#" +import { useLingui } from "@lingui/react/macro"; +import { plural } from "@lingui/core/macro"; + +const Component = memo(() => { + const { t } = useLingui(); + return t`Selected ${plural(count, { one: '# item', other: '# items' })}`; +}); + "# +); + +to!( + nested_plural_in_function_expression, + r#" +import { useLingui } from "@lingui/react/macro"; +import { plural } from "@lingui/core/macro"; + +const Component = function () { + const { t } = useLingui(); + return t`Selected ${plural(count, { one: '# item', other: '# items' })}`; +}; + "# +); + +to!( + nested_plural_in_wrapped_function_expression, + r#" +import { useLingui } from "@lingui/react/macro"; +import { plural } from "@lingui/core/macro"; + +const Component = wrap(function Component() { + const { t } = useLingui(); + return t`Selected ${plural(count, { one: '# item', other: '# items' })}`; +}); + "# +); + +to!( + nested_plural_in_object_method, + r#" +import { useLingui } from "@lingui/react/macro"; +import { plural } from "@lingui/core/macro"; + +const obj = { + Component() { + const { t } = useLingui(); + return t`Selected ${plural(count, { one: '# item', other: '# items' })}`; + } +}; + "# +); + +to!( + nested_plural_in_nested_hook, + r#" +import { useLingui } from "@lingui/react/macro"; +import { plural } from "@lingui/core/macro"; + +function Outer() { + const { t } = useLingui(); + const label = t`Outer`; + return wrap(() => { + const { t } = useLingui(); + return t`Selected ${plural(count, { one: '# item', other: '# items' })}`; + }); +} + "# +); + +to!( + nested_plural_in_callback_using_outer_t, + r#" +import { useLingui } from "@lingui/react/macro"; +import { plural } from "@lingui/core/macro"; + +function Component() { + const { t } = useLingui(); + return wrap(() => t`Selected ${plural(count, { one: '# item', other: '# items' })}`); +} + "# +); + +to!( + nested_plural_in_callback_using_core_t, + r#" +import { t, plural } from "@lingui/core/macro"; + +const Component = wrap(() => t`Selected ${plural(count, { one: '# item', other: '# items' })}`); + "# +);