Skip to content

Commit

Permalink
Use the new API for the interpreter in wasm
Browse files Browse the repository at this point in the history
Improve the ComponenetDefinition::from_source
  • Loading branch information
ogoffart committed Mar 15, 2021
1 parent 4833337 commit fef4a10
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 42 deletions.
44 changes: 23 additions & 21 deletions api/sixtyfps-wasm-interpreter/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ LICENSE END */
//! This wasm library can be loaded from JS to load and display the content of .60 files
#![cfg(target_arch = "wasm32")]

use std::rc::Rc;
use std::path::Path;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;
Expand All @@ -33,21 +33,24 @@ pub async fn compile_from_string(
#[cfg(feature = "console_error_panic_hook")]
console_error_panic_hook::set_once();

let mut config = sixtyfps_interpreter::new_compiler_configuration();
let mut config = sixtyfps_interpreter::CompilerConfiguration::new();

if let (Some(resolver_callback), Some(load_callback)) =
(optional_resolve_import_callback, optional_import_callback)
{
config.resolve_import_fallback = Some(Box::new(move |file_name| {
let resolve_import_fallback = move |file_name: String| -> Option<String> {
resolver_callback
.clone()
.call1(&JsValue::UNDEFINED, &file_name.into())
.ok()
.and_then(|path_value| path_value.as_string())
}));
config.open_import_fallback = Some(Box::new(move |file_name| {
};
let open_import_fallback = move |file_name: &Path| -> core::pin::Pin<
Box<dyn core::future::Future<Output = std::io::Result<String>>>,
> {
Box::pin({
let load_callback = load_callback.clone();
let file_name: String = file_name.to_string_lossy().into();
async move {
let result = load_callback.call1(&JsValue::UNDEFINED, &file_name.into());
let promise: js_sys::Promise = result.unwrap().into();
Expand All @@ -61,23 +64,25 @@ pub async fn compile_from_string(
}
}
})
}));
};
config = config.with_file_loader(open_import_fallback, resolve_import_fallback);
}

let c = match sixtyfps_interpreter::load(source, base_url.into(), config).await {
(Ok(c), ..) => {
//TODO: warnings.print();
c
}
(Err(()), errors) => {
let (c, diags) =
sixtyfps_interpreter::ComponentDefinition::from_source(source, base_url.into(), config)
.await;

match c {
Some(c) => Ok(WrappedCompiledComp(c)),
None => {
let line_key = JsValue::from_str("lineNumber");
let column_key = JsValue::from_str("columnNumber");
let message_key = JsValue::from_str("message");
let file_key = JsValue::from_str("fileName");
let level_key = JsValue::from_str("level");
let mut error_as_string = String::new();
let array = js_sys::Array::new();
for d in errors.into_iter() {
for d in diags.into_iter() {
let filename = d
.source_file()
.as_ref()
Expand Down Expand Up @@ -107,15 +112,13 @@ pub async fn compile_from_string(

let error = js_sys::Error::new(&error_as_string);
js_sys::Reflect::set(&error, &JsValue::from_str("errors"), &array)?;
return Err((**error).clone());
Err((**error).clone())
}
};

Ok(WrappedCompiledComp(c))
}
}

#[wasm_bindgen]
pub struct WrappedCompiledComp(Rc<sixtyfps_interpreter::ComponentDescription>);
pub struct WrappedCompiledComp(sixtyfps_interpreter::ComponentDefinition);

#[wasm_bindgen]
impl WrappedCompiledComp {
Expand All @@ -124,9 +127,8 @@ impl WrappedCompiledComp {
/// where the result is gonna be rendered
#[wasm_bindgen]
pub fn run(&self, canvas_id: String) {
let component = self.0.clone().create(canvas_id);
component.window().show();
sixtyfps_interpreter::run_event_loop();
let component = self.0.create_with_canvas_id(&canvas_id);
component.run();
}
}

Expand Down
38 changes: 21 additions & 17 deletions sixtyfps_runtime/interpreter/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use core::convert::TryInto;
use sixtyfps_corelib::{Brush, ImageReference, PathData, SharedString, SharedVector};
use std::collections::HashMap;
use std::iter::FromIterator;
use std::path::Path;
use std::path::{Path, PathBuf};
use std::rc::Rc;

#[doc(inline)]
Expand Down Expand Up @@ -369,24 +369,23 @@ impl ComponentDefinition {
}
/// Compile some .60 code into a ComponentDefinition
///
/// The `path` argument will be used for diagnostics and to compute relative
/// path while importing
///
/// The first element of the returned tuple is going to be the compiled
/// ComponentDefinition if there was no errors. This function also return
/// a vector if diagnostics with errors and/or warnings
pub async fn from_string(
source_code: &str,
pub async fn from_source(
source_code: String,
path: PathBuf,
config: CompilerConfiguration,
) -> (Option<Self>, Vec<Diagnostic>) {
// We create here a 'static guard. That's alright because we make sure
// in this module that we only use erased component
let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };

let (c, diag) = crate::dynamic_component::load(
source_code.into(),
Default::default(),
config.config,
guard,
)
.await;
let (c, diag) =
crate::dynamic_component::load(source_code, path, config.config, guard).await;
(c.ok().map(|inner| Self { inner }), diag.into_iter().collect())
}

Expand Down Expand Up @@ -614,15 +613,20 @@ impl CompilerConfiguration {

/// Create a new configuration that will use the provided callback for loading.
pub fn with_file_loader(
_file_loader_fallback: Box<
dyn Fn(
self,
file_loader_fallback: impl Fn(
&Path,
) -> core::pin::Pin<
Box<dyn core::future::Future<Output = std::io::Result<String>>>,
>,
>,
)
-> core::pin::Pin<Box<dyn core::future::Future<Output = std::io::Result<String>>>>
+ 'static,
// FIXME: remove that argument
resolve: impl Fn(String) -> Option<String> + 'static,
) -> Self {
todo!();
let mut config = self.config;
config.open_import_fallback =
Some(Box::new(move |path| file_loader_fallback(Path::new(path.as_str()))));
config.resolve_import_fallback = Some(Box::new(resolve));
Self { config }
}
}

Expand Down
10 changes: 6 additions & 4 deletions tests/driver/interpreter/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,12 @@ pub fn test(testcase: &test_driver_lib::TestCase) -> Result<(), Box<dyn Error>>
let mut config =
sixtyfps_interpreter::CompilerConfiguration::new().with_include_paths(include_paths);

// FIXME: use from_source instead of from_path
let (component, diags) = spin_on::spin_on(
sixtyfps_interpreter::ComponentDefinition::from_path(&testcase.absolute_path, config),
);
let (component, diags) =
spin_on::spin_on(sixtyfps_interpreter::ComponentDefinition::from_source(
source,
testcase.absolute_path,
config,
));

let component = match component {
None => {
Expand Down

0 comments on commit fef4a10

Please sign in to comment.