Skip to content

Commit

Permalink
fix(optimizer): keep extensions and dropped imports (#478)
Browse files Browse the repository at this point in the history
  • Loading branch information
manucorporat authored May 14, 2022
1 parent 6615f03 commit f245ff8
Show file tree
Hide file tree
Showing 47 changed files with 1,433 additions and 736 deletions.
463 changes: 218 additions & 245 deletions Cargo.lock

Large diffs are not rendered by default.

19 changes: 9 additions & 10 deletions packages/qwik/src/optimizer/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,24 @@ categories = ["development-tools", "development-tools::cargo-plugins"]
crate-type = ["rlib"]

[dependencies]
swc_ecmascript = { version = "0.131.0", features = ["parser", "transforms", "module", "typescript", "optimization", "minifier", "react", "utils", "visit", "codegen", "utils"] }
swc_common = { version = "0.17.14", features = ["sourcemap"] }
swc_atoms = "0.2.9"
serde = "1.0.136"
serde_bytes = "0.11.5"
swc_ecmascript = { version = "0.156.0", features = ["parser", "transforms", "module", "typescript", "optimization", "minifier", "react", "utils", "visit", "codegen", "utils"] }
swc_common = { version = "0.18.1", features = ["sourcemap"] }
swc_atoms = "0.2.11"
serde = "1.0.137"
serde_bytes = "0.11.6"
simple-error = "0.2.3"
base64 = "0.13.0"
pathdiff = "0.2.1"
relative-path = "1.6.1"
relative-path = "1.7.0"
lazy_static = "1.4.0"
regex = "1.5.4"
anyhow = "1.0.53"
anyhow = "1.0.57"
derivative = "2.2.0"
rayon = "1.5.1"
path-slash="0.1.4"

[dev-dependencies]
insta = "1.12.0"
serde_json = "1.0.78"
insta = "1.14.0"
serde_json = "1.0.81"

[features]
fs=[]
Expand Down
24 changes: 14 additions & 10 deletions packages/qwik/src/optimizer/core/src/code_move.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,7 @@ pub fn new_module(ctx: NewModuleCtx) -> Result<(ast::Module, SingleThreadedComme
src: ast::Str {
span: DUMMY_SP,
value: fix_path(ctx.origin, "a", import.source.as_ref())?,
kind: ast::StrKind::Synthesized,
has_escape: false,
raw: None,
},
specifiers: vec![specifier],
},
Expand All @@ -100,8 +99,7 @@ pub fn new_module(ctx: NewModuleCtx) -> Result<(ast::Module, SingleThreadedComme
src: ast::Str {
span: DUMMY_SP,
value: fix_path(ctx.origin, "a", &format!("./{}", ctx.path.file_stem))?,
kind: ast::StrKind::Synthesized,
has_escape: false,
raw: None,
},
specifiers: vec![ast::ImportSpecifier::Named(ast::ImportNamedSpecifier {
is_type_only: false,
Expand Down Expand Up @@ -217,7 +215,10 @@ fn test_fix_path() {
assert!(fix_path("/components", "a", "./state").is_err())
}

pub fn generate_entries(mut output: TransformOutput) -> Result<TransformOutput, anyhow::Error> {
pub fn generate_entries(
mut output: TransformOutput,
explicity_extensions: bool,
) -> Result<TransformOutput, anyhow::Error> {
let source_map = Lrc::new(SourceMap::default());
let mut entries_map: BTreeMap<&str, Vec<&HookAnalysis>> = BTreeMap::new();
let mut new_modules = Vec::with_capacity(output.modules.len());
Expand All @@ -233,7 +234,7 @@ pub fn generate_entries(mut output: TransformOutput) -> Result<TransformOutput,
}

for (entry, hooks) in &entries_map {
let module = new_entry_module(hooks);
let module = new_entry_module(hooks, explicity_extensions);
let (code, map) = emit_source_code(Lrc::clone(&source_map), None, &module, false)
.context("Emitting source code")?;
new_modules.push(TransformModule {
Expand All @@ -251,13 +252,17 @@ pub fn generate_entries(mut output: TransformOutput) -> Result<TransformOutput,
Ok(output)
}

fn new_entry_module(hooks: &[&HookAnalysis]) -> ast::Module {
fn new_entry_module(hooks: &[&HookAnalysis], explicity_extensions: bool) -> ast::Module {
let mut module = ast::Module {
span: DUMMY_SP,
body: Vec::with_capacity(hooks.len()),
shebang: None,
};
for hook in hooks {
let mut src = ["./", &hook.canonical_filename].concat();
if explicity_extensions {
src = src + "." + hook.extension.as_ref();
}
module
.body
.push(ast::ModuleItem::ModuleDecl(ast::ModuleDecl::ExportNamed(
Expand All @@ -267,9 +272,8 @@ fn new_entry_module(hooks: &[&HookAnalysis]) -> ast::Module {
asserts: None,
src: Some(ast::Str {
span: DUMMY_SP,
value: JsWord::from(["./", &hook.canonical_filename].concat()),
kind: ast::StrKind::Synthesized,
has_escape: false,
value: JsWord::from(src),
raw: None,
}),
specifiers: vec![ast::ExportSpecifier::Named(ast::ExportNamedSpecifier {
is_type_only: false,
Expand Down
6 changes: 4 additions & 2 deletions packages/qwik/src/optimizer/core/src/entry_strategy.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::parse::PathData;
use crate::transform::HookData;
use crate::words::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use swc_atoms::JsWord;
Expand Down Expand Up @@ -89,11 +90,12 @@ impl EntryPolicy for SmartStrategy {
_symbol: &str,
_path: &PathData,
context: &[String],
_hook_data: &HookData,
hook_data: &HookData,
) -> Option<JsWord> {
if context.iter().any(|h| h == "onMount") {
if hook_data.ctx_name == *USE_SERVER_MOUNT {
return Some(ENTRY_SERVER.clone());
}
if context.iter().any(|h| h == "onMount") {}
Some(context.first().map_or_else(
|| ENTRY_HOOKS.clone(),
|root| JsWord::from(["entry_", root].concat()),
Expand Down
4 changes: 2 additions & 2 deletions packages/qwik/src/optimizer/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ pub fn transform_fs(config: TransformFsOptions) -> Result<TransformOutput, Error
.reduce(|| Ok(TransformOutput::new()), |x, y| Ok(x?.append(&mut y?)))?;

final_output.modules.sort_unstable_by_key(|key| key.order);
final_output = generate_entries(final_output)?;
final_output = generate_entries(final_output, config.explicity_extensions)?;
Ok(final_output)
}

Expand Down Expand Up @@ -142,7 +142,7 @@ pub fn transform_modules(config: TransformModulesOptions) -> Result<TransformOut

let mut final_output = final_output?;
final_output.modules.sort_unstable_by_key(|key| key.order);
final_output = generate_entries(final_output)?;
final_output = generate_entries(final_output, config.explicity_extensions)?;

Ok(final_output)
}
Expand Down
31 changes: 20 additions & 11 deletions packages/qwik/src/optimizer/core/src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ use swc_ecmascript::codegen::text_writer::JsWriter;
use swc_ecmascript::parser::lexer::Lexer;
use swc_ecmascript::parser::{EsConfig, PResult, Parser, StringInput, Syntax, TsConfig};
use swc_ecmascript::transforms::{
fixer, hygiene::hygiene_with_config, optimization::simplify, react, resolver_with_mark,
typescript,
fixer, hygiene::hygiene_with_config, optimization::simplify, react, resolver, typescript,
};
use swc_ecmascript::visit::{FoldWith, VisitMutWith};

Expand All @@ -45,6 +44,7 @@ pub struct HookAnalysis {
pub ctx_kind: HookKind,
pub ctx_name: JsWord,
pub captures: bool,
pub loc: (u32, u32),
}

#[derive(Debug, Serialize, Deserialize, Copy, Clone, PartialEq, Eq)]
Expand Down Expand Up @@ -153,7 +153,9 @@ pub fn transform_code(config: TransformCodeOptions) -> Result<TransformOutput, a

swc_common::GLOBALS.set(&Globals::new(), || {
swc_common::errors::HANDLER.set(&handler, || {
let global_mark = Mark::fresh(Mark::root());
let unresolved_mark = Mark::new();
let top_level_mark = Mark::new();

let mut main_module = main_module;

// Transpile JSX
Expand All @@ -167,31 +169,35 @@ pub fn transform_code(config: TransformCodeOptions) -> Result<TransformOutput, a
..Default::default()
},
Some(&comments),
global_mark,
top_level_mark,
))
} else {
main_module.fold_with(&mut typescript::strip(global_mark))
main_module.fold_with(&mut typescript::strip(top_level_mark))
}
}

// Transpile JSX
if transpile && is_jsx {
let mut react_options = react::Options::default();
if is_jsx {
react_options.throw_if_namespace = false;
react_options.throw_if_namespace = Some(false);
react_options.runtime = Some(react::Runtime::Automatic);
react_options.import_source = "@builder.io/qwik".to_string();
react_options.import_source = Some("@builder.io/qwik".to_string());
};
main_module = main_module.fold_with(&mut react::react(
Lrc::clone(&source_map),
Some(&comments),
react_options,
global_mark,
top_level_mark,
));
}

// Resolve with mark
main_module.visit_mut_with(&mut resolver_with_mark(global_mark));
main_module.visit_mut_with(&mut resolver(
unresolved_mark,
top_level_mark,
is_type_script && !transpile,
));

// Collect import/export metadata
let collect = global_collect(&main_module);
Expand All @@ -209,8 +215,10 @@ pub fn transform_code(config: TransformCodeOptions) -> Result<TransformOutput, a
main_module = main_module.fold_with(&mut qwik_transform);

if config.minify != MinifyMode::None {
main_module =
main_module.fold_with(&mut simplify::simplifier(Default::default()));
main_module = main_module.fold_with(&mut simplify::simplifier(
unresolved_mark,
Default::default(),
));
}
main_module.visit_mut_with(&mut hygiene_with_config(Default::default()));
main_module.visit_mut_with(&mut fixer(None));
Expand Down Expand Up @@ -265,6 +273,7 @@ pub fn transform_code(config: TransformCodeOptions) -> Result<TransformOutput, a
captures: !h.data.scoped_idents.is_empty(),
display_name: h.data.display_name,
hash: h.data.hash,
loc: (h.span.lo.0, h.span.hi.0),
}),
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,11 @@ export { hW as handleWatch };
"parent": null,
"ctxKind": "function",
"ctxName": "$",
"captures": false
"captures": false,
"loc": [
92,
175
]
}
*/
============================= renderheader_1_cpyr0uahiik.tsx (ENTRY POINT)==
Expand All @@ -66,7 +70,11 @@ export { hW as handleWatch };
"parent": null,
"ctxKind": "function",
"ctxName": "$",
"captures": false
"captures": false,
"loc": [
211,
261
]
}
*/
============================= test.tsx ==
Expand Down Expand Up @@ -99,7 +107,11 @@ export { hW as handleWatch };
"parent": "renderHeader_zBbHWn4e8Cg",
"ctxKind": "function",
"ctxName": "$",
"captures": false
"captures": false,
"loc": [
137,
162
]
}
*/
== DIAGNOSTICS ==
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,11 @@ export { hW as handleWatch };
"parent": null,
"ctxKind": "function",
"ctxName": "$",
"captures": false
"captures": false,
"loc": [
69,
455
]
}
*/
============================= project/test.tsx ==
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,11 @@ export const Header_component_Header_onClick_KjD9TCNkNxY = (ev)=>dep3(ev)
"parent": "Header_component_UVBJuFYfvDo",
"ctxKind": "function",
"ctxName": "$",
"captures": false
"captures": false,
"loc": [
242,
258
]
}
*/
============================= header_component_uvbjufyfvdo.tsx ==
Expand Down Expand Up @@ -73,7 +77,11 @@ export const Header_component_UVBJuFYfvDo = ()=>{
"parent": null,
"ctxKind": "function",
"ctxName": "component$",
"captures": false
"captures": false,
"loc": [
194,
323
]
}
*/
============================= app_component_wgkrhwxaqjs.tsx ==
Expand All @@ -97,7 +105,11 @@ export const App_component_wGkRHWXaqjs = ()=>{
"parent": null,
"ctxKind": "function",
"ctxName": "component$",
"captures": false
"captures": false,
"loc": [
357,
419
]
}
*/
============================= project/test.tsx ==
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,11 @@ export { hW as handleWatch };
"parent": null,
"ctxKind": "function",
"ctxName": "component$",
"captures": false
"captures": false,
"loc": [
85,
194
]
}
*/
============================= test.tsx ==
Expand Down Expand Up @@ -68,7 +72,11 @@ export { hW as handleWatch };
"parent": "Header_component_J4uyIhaBNR4",
"ctxKind": "function",
"ctxName": "$",
"captures": false
"captures": false,
"loc": [
156,
181
]
}
*/
== DIAGNOSTICS ==
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,11 @@ export { hW as handleWatch };
"parent": null,
"ctxKind": "function",
"ctxName": "component$",
"captures": false
"captures": false,
"loc": [
109,
238
]
}
*/
============================= app_header_component_div_onclick_ao7ui7iw6oq.tsx (ENTRY POINT)==
Expand All @@ -64,7 +68,11 @@ export { hW as handleWatch };
"parent": "App_Header_component_B9F3YeqcO1w",
"ctxKind": "function",
"ctxName": "$",
"captures": false
"captures": false,
"loc": [
192,
217
]
}
*/
============================= test.tsx ==
Expand Down
Loading

0 comments on commit f245ff8

Please sign in to comment.