difftreelog
refactor(bindings) extra interop methods
in: master
5 files changed
bindings/c/libjsonnet_test_file.cdiffbeforeafterboth--- a/bindings/c/libjsonnet_test_file.c
+++ b/bindings/c/libjsonnet_test_file.c
@@ -1,16 +1,3 @@
-/*
-Copyright 2015 Google Inc. All rights reserved.
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
#include <stdlib.h>
#include <stdio.h>
bindings/jsonnet/Cargo.tomldiffbeforeafterboth--- a/bindings/jsonnet/Cargo.toml
+++ b/bindings/jsonnet/Cargo.toml
@@ -27,11 +27,17 @@
[lib]
name = "jsonnet"
-crate-type = ["cdylib"]
+crate-type = ["cdylib", "staticlib"]
[features]
+default = ["interop-common", "interop-wasm", "interop-threading"]
# Export additional functions for native integration, i.e ability to set custom trace format
-interop = []
+interop-common = []
+# Provide ability to statically override callbacks from WASM (by using imports)
+interop-wasm = []
+# Provide ability to move jsonnet vm state between threads
+interop-threading = []
+
experimental = ["exp-preserve-order", "exp-destruct"]
exp-preserve-order = ["jrsonnet-evaluator/exp-preserve-order"]
exp-destruct = ["jrsonnet-evaluator/exp-destruct"]
bindings/jsonnet/src/import.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/import.rs
+++ b/bindings/jsonnet/src/import.rs
@@ -15,7 +15,7 @@
use jrsonnet_evaluator::{
bail,
error::{ErrorKind::*, Result},
- FileImportResolver, ImportResolver,
+ ImportResolver,
};
use jrsonnet_gcmodule::Trace;
use jrsonnet_parser::{SourceDirectory, SourceFile, SourcePath};
@@ -106,6 +106,10 @@
fn as_any(&self) -> &dyn Any {
self
}
+
+ fn as_any_mut(&mut self) -> &mut dyn Any {
+ self
+ }
}
/// # Safety
@@ -117,7 +121,7 @@
cb: JsonnetImportCallback,
ctx: *mut c_void,
) {
- vm.state.set_import_resolver(CallbackImportResolver {
+ vm.replace_import_resolver(CallbackImportResolver {
cb,
ctx,
out: RefCell::new(HashMap::new()),
@@ -131,10 +135,5 @@
pub unsafe extern "C" fn jsonnet_jpath_add(vm: &VM, path: *const c_char) {
let cstr = unsafe { CStr::from_ptr(path) };
let path = PathBuf::from(cstr.to_str().unwrap());
- let any_resolver = vm.state.import_resolver();
- let resolver = any_resolver
- .as_any()
- .downcast_ref::<FileImportResolver>()
- .expect("jpaths are not compatible with callback imports!");
- resolver.add_jpath(path);
+ vm.add_jpath(path);
}
bindings/jsonnet/src/interop.rsdiffbeforeafterboth1//! Jrsonnet specific additional binding helpers23use std::{4 ffi::c_void,5 os::raw::{c_char, c_int},6};78use jrsonnet_evaluator::Val;910use crate::{import::jsonnet_import_callback, native::jsonnet_native_callback};1112extern "C" {13 pub fn _jrsonnet_static_import_callback(14 ctx: *mut c_void,15 base: *const c_char,16 rel: *const c_char,17 found_here: *mut *const c_char,18 success: &mut c_int,19 ) -> *const c_char;2021 #[allow(improper_ctypes)]22 pub fn _jrsonnet_static_native_callback(23 ctx: *const c_void,24 argv: *const *const Val,25 success: *mut c_int,26 ) -> *mut Val;27}2829/// # Safety30#[no_mangle]31pub unsafe extern "C" fn jrsonnet_apply_static_import_callback(vm: &VM, ctx: *mut c_void) {32 jsonnet_import_callback(vm, _jrsonnet_static_import_callback, ctx)33}3435/// # Safety36#[no_mangle]37pub unsafe extern "C" fn jrsonnet_apply_static_native_callback(38 vm: &VM,39 name: *const c_char,40 ctx: *mut c_void,41 raw_params: *const *const c_char,42) {43 jsonnet_native_callback(vm, name, _jrsonnet_static_native_callback, ctx, raw_params)44}4546#[no_mangle]47pub extern "C" fn jrsonnet_set_trace_format(vm: &VM, format: u8) {48 use jrsonnet_evaluator::trace::JsFormat;49 match format {50 1 => vm.set_trace_format(Box::new(JsFormat)),51 _ => panic!("unknown trace format"),52 }53}bindings/jsonnet/src/lib.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -1,6 +1,5 @@
#![allow(clippy::box_default)]
-#[cfg(feature = "interop")]
pub mod interop;
pub mod import;
@@ -12,22 +11,27 @@
use std::{
alloc::Layout,
+ any::Any,
borrow::Cow,
+ cell::RefCell,
ffi::{CStr, CString, OsStr},
os::raw::{c_char, c_double, c_int, c_uint},
- path::Path,
+ path::{Path, PathBuf},
};
use jrsonnet_evaluator::{
apply_tla, bail,
function::TlaArg,
- gc::GcHashMap,
+ gc::{GcHashMap, TraceBox},
manifest::{JsonFormat, ManifestFormat, ToStringFormat},
stack::set_stack_depth_limit,
tb,
trace::{CompactFormat, PathResolver, TraceFormat},
- FileImportResolver, IStr, Result, State, Val,
+ FileImportResolver, IStr, ImportResolver, Result, State, Val,
};
+use jrsonnet_gcmodule::Trace;
+use jrsonnet_parser::SourcePath;
+use jrsonnet_stdlib::ContextInitializer;
/// WASM stub
#[cfg(target_arch = "wasm32")]
@@ -72,22 +76,84 @@
}
}
+#[derive(Trace)]
+struct VMImportResolver {
+ #[trace(tracking(force))]
+ inner: RefCell<TraceBox<dyn ImportResolver>>,
+}
+impl VMImportResolver {
+ fn new(value: impl ImportResolver) -> Self {
+ Self {
+ inner: RefCell::new(tb!(value)),
+ }
+ }
+}
+impl ImportResolver for VMImportResolver {
+ fn load_file_contents(&self, resolved: &SourcePath) -> Result<Vec<u8>> {
+ self.inner.borrow().load_file_contents(resolved)
+ }
+
+ fn resolve_from(&self, from: &SourcePath, path: &str) -> Result<SourcePath> {
+ self.inner.borrow().resolve_from(from, path)
+ }
+
+ fn resolve_from_default(&self, path: &str) -> Result<SourcePath> {
+ self.inner.borrow().resolve_from_default(path)
+ }
+
+ fn resolve(&self, path: &Path) -> Result<SourcePath> {
+ self.inner.borrow().resolve(path)
+ }
+
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+ fn as_any_mut(&mut self) -> &mut dyn Any {
+ self
+ }
+}
+
pub struct VM {
state: State,
manifest_format: Box<dyn ManifestFormat>,
trace_format: Box<dyn TraceFormat>,
tla_args: GcHashMap<IStr, TlaArg>,
}
+impl VM {
+ fn replace_import_resolver(&self, resolver: impl ImportResolver) {
+ *self
+ .state
+ .import_resolver()
+ .as_any()
+ .downcast_ref::<VMImportResolver>()
+ .expect("valid resolver ty")
+ .inner
+ .borrow_mut() = tb!(resolver);
+ }
+ fn add_jpath(&self, path: PathBuf) {
+ self.state
+ .import_resolver()
+ .as_any()
+ .downcast_ref::<VMImportResolver>()
+ .expect("valid resolver ty")
+ .inner
+ .borrow_mut()
+ .as_any_mut()
+ .downcast_mut::<FileImportResolver>()
+ .expect("jpaths are not compatible with callback imports!")
+ .add_jpath(path);
+ }
+}
/// Creates a new Jsonnet virtual machine.
#[no_mangle]
#[allow(clippy::box_default)]
pub extern "C" fn jsonnet_make() -> *mut VM {
- let state = State::default();
- state.settings_mut().import_resolver = tb!(FileImportResolver::default());
- state.settings_mut().context_initializer = tb!(jrsonnet_stdlib::ContextInitializer::new(
- PathResolver::new_cwd_fallback(),
- ));
+ let mut state = State::builder();
+ state
+ .import_resolver(VMImportResolver::new(FileImportResolver::default()))
+ .context_initializer(ContextInitializer::new(PathResolver::new_cwd_fallback()));
+ let state = state.build();
Box::into_raw(Box::new(VM {
state,
manifest_format: Box::new(JsonFormat::default()),