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

Feature/use lingui #90

Draft
wants to merge 1 commit into
base: next
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
281 changes: 206 additions & 75 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,35 +1,34 @@
use std::collections::HashSet;
use swc_core::common::{Spanned, DUMMY_SP};

Check warning on line 2 in src/lib.rs

View workflow job for this annotation

GitHub Actions / Test Suite

unused import: `Spanned`

Check warning on line 2 in src/lib.rs

View workflow job for this annotation

GitHub Actions / Check

unused import: `Spanned`
use swc_core::{
ecma::{
utils::quote_ident,
ast::*,
utils::quote_ident,
visit::{Fold, FoldWith, VisitWith},
},
plugin::{
metadata::TransformPluginMetadataContextKind,
plugin_transform,
metadata::TransformPluginMetadataContextKind, plugin_transform,
proxies::TransformPluginProgramMetadata,
},
};

mod tests;
mod builder;
mod tokens;
mod ast_utils;
mod macro_utils;
mod jsx_visitor;
mod builder;
mod generate_id;
mod js_macro_folder;
mod jsx_visitor;
mod macro_utils;
mod options;
mod generate_id;
mod tests;
mod tokens;

use builder::*;
use crate::generate_id::*;
use crate::macro_utils::*;
use crate::options::*;
use ast_utils::*;
use builder::*;
use js_macro_folder::JsMacroFolder;
use jsx_visitor::TransJSXVisitor;
use crate::macro_utils::{*};
use crate::options::{*};
use crate::generate_id::{*};


#[derive(Default)]
pub struct LinguiMacroFolder {
Expand All @@ -38,7 +37,7 @@
}

impl LinguiMacroFolder {
pub fn new(options: LinguiOptions) -> LinguiMacroFolder {
pub fn new(options: LinguiOptions) -> LinguiMacroFolder {
LinguiMacroFolder {
has_lingui_macro_imports: false,
ctx: MacroCtx::new(options),
Expand All @@ -56,50 +55,41 @@
el.visit_children_with(&mut trans_visitor);
}

let parsed = MessageBuilder::parse(trans_visitor.tokens);
let id_attr = get_jsx_attr(&el.opening, "id");

let context_attr_val = get_jsx_attr(&el.opening, "context")
.and_then(|attr| attr.value.as_ref())
.and_then(|value| get_jsx_attr_value_as_string(value));

let mut attrs = vec![
create_jsx_attribute(
"message".into(),
parsed.message,
),
];

if !id_attr.is_some() {
attrs.push(create_jsx_attribute(
"id",
generate_message_id(
&parsed.message_str,
&context_attr_val.unwrap_or_default()
).into(),
));
}
let parsed = MessageBuilder::parse(trans_visitor.tokens);
let id_attr = get_jsx_attr(&el.opening, "id");

if let Some(exp) = parsed.values {
attrs.push(create_jsx_attribute(
"values",
exp,
));
}
let context_attr_val = get_jsx_attr(&el.opening, "context")
.and_then(|attr| attr.value.as_ref())
.and_then(|value| get_jsx_attr_value_as_string(value));

let mut attrs = vec![create_jsx_attribute("message".into(), parsed.message)];

if let Some(exp) = parsed.components {
attrs.push(create_jsx_attribute(
"components",
exp,
if !id_attr.is_some() {
attrs.push(create_jsx_attribute(
"id",
generate_message_id(&parsed.message_str, &context_attr_val.unwrap_or_default())
.into(),
));
}

attrs.extend(
pick_jsx_attrs(el.opening.attrs, HashSet::from(["id", "render", "i18n"]))
);
if let Some(exp) = parsed.values {
attrs.push(create_jsx_attribute("values", exp));
}

if let Some(exp) = parsed.components {
attrs.push(create_jsx_attribute("components", exp));
}

attrs.extend(pick_jsx_attrs(
el.opening.attrs,
HashSet::from(["id", "render", "i18n"]),
));

if self.ctx.options.strip_non_essential_fields {
attrs = pick_jsx_attrs(attrs, HashSet::from(["id", "render", "i18n", "values", "components"]))
attrs = pick_jsx_attrs(
attrs,
HashSet::from(["id", "render", "i18n", "values", "components"]),
)
}

self.ctx.should_add_trans_import = true;
Expand All @@ -113,9 +103,7 @@
opening: JSXOpeningElement {
self_closing: true,
span: el.opening.span,
name: JSXElementName::Ident(
Ident::new(trans_export.into(), el.opening.span)
),
name: JSXElementName::Ident(Ident::new(trans_export.into(), el.opening.span)),
type_args: None,
attrs,
},
Expand Down Expand Up @@ -147,35 +135,183 @@
if &imp.src.value == &i18n_source && !imp.type_only {
for spec in &imp.specifiers {
if let ImportSpecifier::Named(spec) = spec {
has_i18n_import = if !has_i18n_import { &spec.local.sym == &i18n_export } else { true };
has_i18n_import = if !has_i18n_import {
&spec.local.sym == &i18n_export
} else {
true
};
}
}
}

if &imp.src.value == &trans_source && !imp.type_only {
for spec in &imp.specifiers {
if let ImportSpecifier::Named(spec) = spec {
has_trans_import = if !has_trans_import { &spec.local.sym == &trans_export } else { true };
has_trans_import = if !has_trans_import {
&spec.local.sym == &trans_export
} else {
true
};
}
}
}
}

index +=1;
true
index += 1;
true
});

n = n.fold_children_with(self);
n = n.fold_children_with(self);

if !has_i18n_import && self.ctx.should_add_18n_import {
n.insert(
insert_index,
create_import(i18n_source.into(), quote_ident!(i18n_export[..])),
);
}

if !has_trans_import && self.ctx.should_add_trans_import {
n.insert(
insert_index,
create_import(trans_source.into(), quote_ident!(trans_export[..])),
);
}

if !has_i18n_import && self.ctx.should_add_18n_import {
n.insert(insert_index, create_import(i18n_source.into(), quote_ident!(i18n_export[..])));
}
n
}
fn fold_arrow_expr(&mut self, n: ArrowExpr) -> ArrowExpr {
println!("arrow expr");
n.fold_children_with(self)
}
// fn fold_fn_decl(&mut self, n: FnDecl) -> FnDecl {
// println!("fold_fn_decl");
// n.fold_children_with(self)
// }
//
fn fold_fn_expr(&mut self, n: FnExpr) -> FnExpr {
println!("fold_fn_expr");
n.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;
}

if !has_trans_import && self.ctx.should_add_trans_import {
n.insert(insert_index, create_import(trans_source.into(), quote_ident!(trans_export[..])));
}
let mut ctx = self.ctx.clone();

if let Some(body) = n.body {
let stmts: Vec<Stmt> = body
.stmts
.into_iter()
.map(|stmt| {
return match stmt {
Stmt::Decl(Decl::Var(var_decl)) => {
let decl = *var_decl;

let decls: Vec<VarDeclarator> = 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()
{
if let Pat::Object(obj_pat) = declarator.name {
let mew_props: Vec<ObjectPatProp> =
obj_pat.props.into_iter().map(|prop| {
match prop {
ObjectPatProp::Assign(assign)
if &assign.key.sym == "t" =>
{
ctx.register_reference(
&assign.key.sym,
&assign.key.to_id(),
);

return ObjectPatProp::Assign(
AssignPatProp {
span: assign.span,
value: None,
key: BindingIdent {
id: Ident {
span: assign
.key
.span,
sym: "i18n".into(),
optional: false,
},
type_ann: None,
},
},
);
}
_ => {
return prop;
// panic: useLingui could be used only with object desctructuring
}
}
}).collect();

return VarDeclarator {
init: declarator.init,
definite: true,
span: declarator.span,
name: Pat::Object(ObjectPat {
optional: false,
type_ann: None,
span: DUMMY_SP,
props: mew_props

}),
}
} else {
//panic: useLingui could be used only with object desctructuring
}
}
}
}

return declarator;
}).collect();

return Stmt::Decl(Decl::Var(Box::new(VarDecl {
span: decl.span,
decls,
declare: false,
kind: decl.kind,
})))
}
_ => stmt,
};
})
.collect();

let new_func = Function {
params: n.params,
body: Some(BlockStmt {
span: body.span,
stmts,
}),
decorators: n.decorators,
span: n.span,
is_async: n.is_async,
is_generator: n.is_generator,
return_type: n.return_type,
type_params: n.type_params,
};

let mut folder = JsMacroFolder::new(&mut ctx);
return new_func
.fold_children_with(&mut folder)
.fold_children_with(self);
// folder.fold_expr(n).fold_children_with(self)
}

n
n.fold_children_with(self)
}

fn fold_expr(&mut self, expr: Expr) -> Expr {
Expand All @@ -187,9 +323,7 @@

let mut folder = JsMacroFolder::new(&mut self.ctx);

folder
.fold_expr(expr)
.fold_children_with(self)
folder.fold_expr(expr).fold_children_with(self)
}

fn fold_call_expr(&mut self, expr: CallExpr) -> CallExpr {
Expand All @@ -201,9 +335,7 @@

let mut folder = JsMacroFolder::new(&mut self.ctx);

folder
.fold_call_expr(expr)
.fold_children_with(self)
folder.fold_call_expr(expr).fold_children_with(self)
}

fn fold_jsx_element(&mut self, mut el: JSXElement) -> JSXElement {
Expand Down Expand Up @@ -231,15 +363,14 @@
}
}


#[plugin_transform]
pub fn process_transform(program: Program, metadata: TransformPluginProgramMetadata) -> Program {
let config = serde_json::from_str::<LinguiJsOptions>(
&metadata
.get_transform_plugin_config()
.expect("failed to get plugin config for lingui-plugin"),
)
.expect("invalid config for lingui-plugin");
.expect("invalid config for lingui-plugin");

let config = config.to_options(
&metadata
Expand Down