Skip to content

Commit

Permalink
🦄 refactor: Add default() to TranspileOptions
Browse files Browse the repository at this point in the history
  • Loading branch information
caoccao committed Mar 9, 2024
1 parent 9ecb50f commit bb404ec
Show file tree
Hide file tree
Showing 8 changed files with 58 additions and 83 deletions.
10 changes: 6 additions & 4 deletions rust/src/converter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
use jni::objects::JString;
use jni::sys::{jboolean, jstring};
use jni::JNIEnv;
use std::ptr::null_mut;

use deno_media_type::MediaType;

Expand Down Expand Up @@ -67,9 +66,12 @@ pub fn media_type_id_to_media_type(media_type_id: i32) -> MediaType {
}
}

pub fn string_to_jstring<'local>(env: &JNIEnv<'local>, s: &'local str) -> jstring {
pub fn string_to_jstring<'local, 'a>(env: &JNIEnv<'local>, s: &str) -> JString<'a>
where
'local: 'a,
{
match env.new_string(s) {
Ok(s) => s.to_owned(),
Err(_) => null_mut(),
Ok(s) => s,
Err(_) => Default::default(),
}
}
8 changes: 4 additions & 4 deletions rust/src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,9 @@ pub fn transpile<'local>(code: String, options: options::TranspileOptions) -> Re
scope_analysis: false,
}) {
Ok(parsed_source) => {
let default_emit_options = EmitOptions::default();
let emit_options = EmitOptions {
emit_metadata: default_emit_options.emit_metadata,
imports_not_used_as_values: default_emit_options.imports_not_used_as_values,
// emit_metadata: options.emit_metadata,
// imports_not_used_as_values: options.imports_not_used_as_values,
inline_source_map: options.inline_source_map,
inline_sources: options.inline_sources,
jsx_automatic: options.jsx_automatic,
Expand All @@ -45,7 +44,8 @@ pub fn transpile<'local>(code: String, options: options::TranspileOptions) -> Re
precompile_jsx: options.precompile_jsx,
source_map: options.source_map,
transform_jsx: options.transform_jsx,
var_decl_imports: default_emit_options.var_decl_imports,
// var_decl_imports: options.var_decl_imports,
..Default::default()
};
match parsed_source.transpile(&emit_options) {
Ok(transpiled_js_code) => Ok(outputs::TranspileOutput {
Expand Down
2 changes: 1 addition & 1 deletion rust/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ pub fn init<'local>(env: &mut JNIEnv<'local>) {

pub fn throw_transpile_error<'local, 'a>(env: &mut JNIEnv<'local>, message: &'a str) {
let message = jvalue {
l: converter::string_to_jstring(env, message),
l: converter::string_to_jstring(env, message).as_raw(),
};
let exception = unsafe {
JThrowable::from_raw(
Expand Down
6 changes: 3 additions & 3 deletions rust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ pub extern "system" fn Java_com_caoccao_javet_swc4j_Swc4jNative_coreGetVersion<'
env: JNIEnv<'local>,
_: JClass<'local>,
) -> jstring {
converter::string_to_jstring(&env, core::get_version())
converter::string_to_jstring(&env, core::get_version()).as_raw()
}

#[no_mangle]
Expand All @@ -60,10 +60,10 @@ pub extern "system" fn Java_com_caoccao_javet_swc4j_Swc4jNative_coreTranspile<'l
let code = converter::jstring_to_string(&mut env, code);
let options = options::TranspileOptions::from_jni_type(&mut env, options);
match core::transpile(code, options) {
Ok(output) => output.to_jni_type(&mut env),
Ok(output) => output.to_jni_type(&mut env).as_raw(),
Err(message) => {
error::throw_transpile_error(&mut env, message.as_str());
null_mut()
},
}
}
}
19 changes: 19 additions & 0 deletions rust/src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,25 @@ pub struct TranspileOptions {
pub precompile_jsx: bool,
}

impl Default for TranspileOptions {
fn default() -> Self {
TranspileOptions {
inline_source_map: true,
inline_sources: true,
jsx_automatic: false,
jsx_development: false,
jsx_factory: "React.createElement".into(),
jsx_fragment_factory: "React.Fragment".into(),
jsx_import_source: None,
media_type: MediaType::TypeScript,
precompile_jsx: false,
source_map: false,
specifier: "file:///main.js".to_owned(),
transform_jsx: true,
}
}
}

impl FromJniType for TranspileOptions {
fn from_jni_type<'local>(env: &mut JNIEnv<'local>, o: jobject) -> TranspileOptions {
let o = unsafe { JObject::from_raw(o) };
Expand Down
24 changes: 16 additions & 8 deletions rust/src/outputs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
* limitations under the License.
*/

use jni::objects::{GlobalRef, JMethodID};
use jni::sys::{jobject, jvalue};
use jni::objects::{GlobalRef, JMethodID, JObject};
use jni::sys::jvalue;
use jni::JNIEnv;

use std::ptr::null_mut;
Expand All @@ -40,7 +40,11 @@ pub fn init<'local>(env: &mut JNIEnv<'local>) {
.new_global_ref(jclass_transpile_output)
.expect("Couldn't globalize class Swc4jTranspileOutput");
let jmethod_id_transpile_output_constructor = env
.get_method_id(&jclass_transpile_output, "<init>", "(Ljava/lang/String;Ljava/lang/String;Z)V")
.get_method_id(
&jclass_transpile_output,
"<init>",
"(Ljava/lang/String;Ljava/lang/String;Z)V",
)
.expect("Couldn't find method Swc4jTranspileOutput.Swc4jTranspileOutput");
unsafe {
JNI_CALLS = Some(JniCalls {
Expand All @@ -51,7 +55,9 @@ pub fn init<'local>(env: &mut JNIEnv<'local>) {
}

pub trait ToJniType {
fn to_jni_type<'local>(&self, env: &mut JNIEnv<'local>) -> jobject;
fn to_jni_type<'local, 'a>(&self, env: &mut JNIEnv<'local>) -> JObject<'a>
where
'local: 'a;
}

#[derive(Debug)]
Expand All @@ -62,16 +68,19 @@ pub struct TranspileOutput {
}

impl ToJniType for TranspileOutput {
fn to_jni_type<'local>(&self, env: &mut JNIEnv<'local>) -> jobject {
fn to_jni_type<'local, 'a>(&self, env: &mut JNIEnv<'local>) -> JObject<'a>
where
'local: 'a,
{
let code = jvalue {
l: converter::string_to_jstring(env, &self.code),
l: converter::string_to_jstring(env, &self.code).as_raw(),
};
let module = jvalue {
z: if self.module { 1u8 } else { 0u8 },
};
let source_map = jvalue {
l: match &self.source_map {
Some(s) => converter::string_to_jstring(env, &s),
Some(s) => converter::string_to_jstring(env, &s).as_raw(),
None => null_mut(),
},
};
Expand All @@ -83,7 +92,6 @@ impl ToJniType for TranspileOutput {
&[code, source_map, module],
)
.expect("Couldn't create Swc4jTranspileOutput")
.as_raw()
}
}
}
66 changes: 8 additions & 58 deletions rust/tests/test_core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,18 +42,9 @@ fn test_transpile_jsx_with_custom_jsx_factory() {
+ "export default App;\n";
let expected_source_map_prefix = "//# sourceMappingURL=data:application/json;base64,";
let options = options::TranspileOptions {
inline_source_map: true,
inline_sources: true,
jsx_automatic: false,
jsx_development: false,
jsx_factory: "CustomJsxFactory.createElement".into(),
jsx_fragment_factory: "React.Fragment".into(),
jsx_import_source: None,
media_type: MediaType::Jsx,
precompile_jsx: false,
source_map: false,
specifier: "file:///abc.ts".to_owned(),
transform_jsx: true,
..Default::default()
};
let output = core::transpile(code.to_owned(), options);
assert!(output.is_ok());
Expand Down Expand Up @@ -82,18 +73,8 @@ fn test_transpile_jsx_with_default_options() {
+ "export default App;\n";
let expected_source_map_prefix = "//# sourceMappingURL=data:application/json;base64,";
let options = options::TranspileOptions {
inline_source_map: true,
inline_sources: true,
jsx_automatic: false,
jsx_development: false,
jsx_factory: "React.createElement".into(),
jsx_fragment_factory: "React.Fragment".into(),
jsx_import_source: None,
media_type: MediaType::Jsx,
precompile_jsx: false,
source_map: false,
specifier: "file:///abc.ts".to_owned(),
transform_jsx: true,
..Default::default()
};
let output = core::transpile(code.to_owned(), options);
assert!(output.is_ok());
Expand All @@ -109,20 +90,7 @@ fn test_transpile_type_script_with_inline_source_map() {
let code = "function add(a:number, b:number) { return a+b; }";
let expected_code = "function add(a, b) {\n return a + b;\n}\n";
let expected_source_map_prefix = "//# sourceMappingURL=data:application/json;base64,";
let options = options::TranspileOptions {
inline_source_map: true,
inline_sources: true,
jsx_automatic: false,
jsx_development: false,
jsx_factory: "React.createElement".into(),
jsx_fragment_factory: "React.Fragment".into(),
jsx_import_source: None,
media_type: MediaType::TypeScript,
precompile_jsx: false,
source_map: false,
specifier: "file:///abc.ts".to_owned(),
transform_jsx: true,
};
let options = options::TranspileOptions::default();
let output = core::transpile(code.to_owned(), options);
assert!(output.is_ok());
let output = output.unwrap();
Expand All @@ -140,23 +108,15 @@ fn test_transpile_type_script_without_inline_source_map() {
"version",
"sources",
"sourcesContent",
"file:///abc.ts",
"file:///main.ts",
"names",
"mappings",
];
let options = options::TranspileOptions {
inline_source_map: false,
inline_sources: true,
jsx_automatic: false,
jsx_development: false,
jsx_factory: "React.createElement".into(),
jsx_fragment_factory: "React.Fragment".into(),
jsx_import_source: None,
media_type: MediaType::TypeScript,
precompile_jsx: false,
source_map: true,
specifier: "file:///abc.ts".to_owned(),
transform_jsx: true,
specifier: "file:///main.ts".to_owned(),
..Default::default()
};
let output = core::transpile(code.to_owned(), options);
assert!(output.is_ok());
Expand All @@ -173,23 +133,13 @@ fn test_transpile_type_script_without_inline_source_map() {
#[test]
fn test_transpile_wrong_media_type() {
let code = "function add(a:number, b:number) { return a+b; }";
let expected_error = String::from("Expected ',', got ':' at file:///abc.ts:1:15\n")
let expected_error = String::from("Expected ',', got ':' at file:///main.js:1:15\n")
+ "\n"
+ " function add(a:number, b:number) { return a+b; }\n"
+ " ~";
let options = options::TranspileOptions {
inline_source_map: true,
inline_sources: true,
jsx_automatic: false,
jsx_development: false,
jsx_factory: "React.createElement".into(),
jsx_fragment_factory: "React.Fragment".into(),
jsx_import_source: None,
media_type: MediaType::JavaScript,
precompile_jsx: false,
source_map: false,
specifier: "file:///abc.ts".to_owned(),
transform_jsx: true,
..Default::default()
};
let output = core::transpile(code.to_owned(), options);
assert!(output.is_err());
Expand Down
6 changes: 1 addition & 5 deletions src/test/java/com/caoccao/javet/swc4j/TestSwc4j.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ public void testTranspileJSXWithCustomJsxFactory() throws Swc4jCoreException {
"export default App;\n";
String expectedSourceMapPrefix = "//# sourceMappingURL=data:application/json;base64,";
Swc4jTranspileOptions options = new Swc4jTranspileOptions()
.setSpecifier("file:///abc.ts")
.setJsxFactory("CustomJsxFactory.createElement")
.setMediaType(Swc4jMediaType.Jsx);
Swc4jTranspileOutput output = swc4j.transpile(code, options);
Expand Down Expand Up @@ -89,7 +88,6 @@ public void testTranspileJSXWithDefaultOptions() throws Swc4jCoreException {
"export default App;\n";
String expectedSourceMapPrefix = "//# sourceMappingURL=data:application/json;base64,";
Swc4jTranspileOptions options = new Swc4jTranspileOptions()
.setSpecifier("file:///abc.ts")
.setMediaType(Swc4jMediaType.Jsx);
Swc4jTranspileOutput output = swc4j.transpile(code, options);
assertNotNull(output);
Expand All @@ -111,7 +109,6 @@ public void testTranspileTypeScriptWithInlineSourceMap() throws Swc4jCoreExcepti
"}\n";
String expectedSourceMapPrefix = "//# sourceMappingURL=data:application/json;base64,";
Swc4jTranspileOptions options = new Swc4jTranspileOptions()
.setSpecifier("file:///abc.ts")
.setMediaType(Swc4jMediaType.TypeScript);
Swc4jTranspileOutput output = swc4j.transpile(code, options);
assertNotNull(output);
Expand Down Expand Up @@ -152,10 +149,9 @@ public void testTranspileTypeScriptWithoutInlineSourceMap() throws Swc4jCoreExce
public void testTranspileWrongMediaType() {
String code = "function add(a:number, b:number) { return a+b; }";
Swc4jTranspileOptions options = new Swc4jTranspileOptions()
.setSpecifier("file:///abc.ts")
.setMediaType(Swc4jMediaType.JavaScript);
assertEquals(
"Expected ',', got ':' at file:///abc.ts:1:15\n" +
"Expected ',', got ':' at file:///main.js:1:15\n" +
"\n" +
" function add(a:number, b:number) { return a+b; }\n" +
" ~",
Expand Down

0 comments on commit bb404ec

Please sign in to comment.