Struct JsonnetVm

Source
pub struct JsonnetVm(/* private fields */);
Expand description

Jsonnet virtual machine context.

Implementations§

Source§

impl JsonnetVm

Source

pub fn new() -> Self

Create a new Jsonnet virtual machine.

Source

pub fn max_stack(&mut self, v: u32)

Set the maximum stack depth.

Source

pub fn gc_min_objects(&mut self, v: u32)

Set the number of objects required before a garbage collection cycle is allowed.

Source

pub fn gc_growth_trigger(&mut self, v: f64)

Run the garbage collector after this amount of growth in the number of objects.

Source

pub fn string_output(&mut self, v: bool)

Expect a string as output and don’t JSON encode it.

Source

pub fn import_callback<F>(&mut self, cb: F)
where F: Fn(&JsonnetVm, &Path, &Path) -> Result<(PathBuf, String), String>,

Override the callback used to locate imports.

§Examples
use std::path::{Path,PathBuf};
use std::ffi::OsStr;
use jsonnet::JsonnetVm;

let mut vm = JsonnetVm::new();
vm.import_callback(|_vm, base, rel| {
   if rel.file_stem() == Some(OsStr::new("bar")) {
      let newbase = base.into();
      let contents = "2 + 3".to_owned();
      Ok((newbase, contents))
   } else {
      Err("not found".to_owned())
   }
});

{
   let output = vm.evaluate_snippet("myimport", "import 'x/bar.jsonnet'").unwrap();
   assert_eq!(output.to_string(), "5\n");
}

{
   let result = vm.evaluate_snippet("myimport", "import 'x/foo.jsonnet'");
   assert!(result.is_err());
}
Source

pub fn native_callback<F>(&mut self, name: &str, cb: F, params: &[&str])
where for<'a> F: Fn(&'a JsonnetVm, &[JsonVal<'a>]) -> Result<JsonValue<'a>, String>,

Register a native extension.

This will appear in Jsonnet as a function type and can be accessed from std.native("foo").

§Examples
use jsonnet::{JsonnetVm, JsonVal, JsonValue};

fn myadd<'a>(vm: &'a JsonnetVm, args: &[JsonVal<'a>]) -> Result<JsonValue<'a>, String> {
   let a = args[0].as_num().ok_or("Expected a number")?;
   let b = args[1].as_num().ok_or("Expected a number")?;
   Ok(JsonValue::from_num(vm, a + b))
}

let mut vm = JsonnetVm::new();
vm.native_callback("myadd", myadd, &["a", "b"]);

{
   let result = vm.evaluate_snippet("nativetest",
      "std.native('myadd')(2, 3)");
   assert_eq!(result.unwrap().as_str(), "5\n");
}

{
   let result = vm.evaluate_snippet("nativefail",
      "std.native('myadd')('foo', 'bar')");
   assert!(result.is_err());
}

vm.native_callback("upcase", |vm, args| {
      let s = args[0].as_str().ok_or("Expected a string")?;
      Ok(JsonValue::from_str(vm, &s.to_uppercase()))
   }, &["s"]);
{
   let result = vm.evaluate_snippet("nativeclosure",
      "std.native('upcase')('foO')");
   assert_eq!(result.unwrap().as_str(), "\"FOO\"\n");
}
§Panics

Panics if name or params contain any embedded nul characters.

Source

pub fn ext_var(&mut self, key: &str, val: &str)

Bind a Jsonnet external var to the given string.

§Panics

Panics if key or val contain embedded nul characters.

Source

pub fn ext_code(&mut self, key: &str, code: &str)

Bind a Jsonnet external var to the given code.

§Panics

Panics if key or code contain embedded nul characters.

Source

pub fn tla_var(&mut self, key: &str, val: &str)

Bind a string top-level argument for a top-level parameter.

§Panics

Panics if key or val contain embedded nul characters.

Source

pub fn tla_code(&mut self, key: &str, code: &str)

Bind a code top-level argument for a top-level parameter.

§Panics

Panics if key or code contain embedded nul characters.

Source

pub fn fmt_indent(&mut self, n: u32)

Indentation level when reformatting (number of spaces).

Source

pub fn fmt_max_blank_lines(&mut self, n: u32)

Maximum number of blank lines when reformatting.

Source

pub fn fmt_string(&mut self, fmt: FmtString)

Preferred style for string literals ("" or '').

Source

pub fn fmt_comment(&mut self, fmt: FmtComment)

Preferred style for line comments (# or //).

Source

pub fn fmt_pad_arrays(&mut self, pad: bool)

Whether to add an extra space on the inside of arrays.

Source

pub fn fmt_pad_objects(&mut self, pad: bool)

Whether to add an extra space on the inside of objects.

Source

pub fn fmt_pretty_field_names(&mut self, sugar: bool)

Use syntax sugar where possible with field names.

Source

pub fn fmt_sort_import(&mut self, sort: bool)

Sort top-level imports in alphabetical order

Source

pub fn fmt_debug_desugaring(&mut self, reformat: bool)

Reformat the Jsonnet input after desugaring.

Source

pub fn fmt_file<'a, P>( &'a mut self, filename: P, ) -> Result<JsonnetString<'a>, Error<'a>>
where P: AsRef<OsStr>,

Reformat a file containing Jsonnet code, return a Jsonnet string.

§Panics

Panics if filename contains embedded nul characters.

Source

pub fn fmt_snippet<'a, P>( &'a mut self, filename: P, snippet: &str, ) -> Result<JsonnetString<'a>, Error<'a>>
where P: AsRef<OsStr>,

Reformat a string containing Jsonnet code, return a Jsonnet string.

§Panics

Panics if filename or snippet contain embedded nul characters.

Source

pub fn max_trace(&mut self, limit: Option<u32>)

Set the number of lines of stack trace to display (None for unlimited).

Source

pub fn jpath_add<P>(&mut self, path: P)
where P: AsRef<OsStr>,

Add to the default import callback’s library search path.

Search order is last to first, so more recently appended paths take precedence.

§Panics

Panics if path contains embedded nul characters.

Source

pub fn evaluate_file<'a, P>( &'a mut self, filename: P, ) -> Result<JsonnetString<'a>, Error<'a>>
where P: AsRef<OsStr>,

Evaluate a file containing Jsonnet code, returning a JSON string.

§Errors

Returns any jsonnet error during evaluation.

§Panics

Panics if filename contains embedded nul characters.

Source

pub fn evaluate_snippet<'a, P>( &'a mut self, filename: P, snippet: &str, ) -> Result<JsonnetString<'a>, Error<'a>>
where P: AsRef<OsStr>,

Evaluate a string containing Jsonnet code, returning a JSON string.

The filename argument is only used in error messages.

§Errors

Returns any jsonnet error during evaluation.

§Panics

Panics if filename or snippet contain embedded nul characters.

Source

pub fn evaluate_file_multi<'a, P>( &'a mut self, filename: P, ) -> Result<EvalMap<'a>, Error<'a>>
where P: AsRef<OsStr>,

Evaluate a file containing Jsonnet code, returning a number of named JSON files.

§Errors

Returns any jsonnet error during evaluation.

§Panics

Panics if filename contains embedded nul characters.

Source

pub fn evaluate_snippet_multi<'a, P>( &'a mut self, filename: P, snippet: &str, ) -> Result<EvalMap<'a>, Error<'a>>
where P: AsRef<OsStr>,

Evaluate a file containing Jsonnet code, returning a number of named JSON files.

§Errors

Returns any jsonnet error during evaluation.

§Panics

Panics if filename or snippet contain embedded nul characters.

§Examples
use std::collections::HashMap;
use jsonnet::JsonnetVm;

let mut vm = JsonnetVm::new();
let output = vm.evaluate_snippet_multi("multi",
   "{'foo.json': 'foo', 'bar.json': 'bar'}").unwrap();

let map: HashMap<_,_> = output.iter().collect();
assert_eq!(*map.get("bar.json").unwrap(), "\"bar\"\n");
Source

pub fn evaluate_file_stream<'a, P>( &'a mut self, filename: P, ) -> Result<EvalList<'a>, Error<'a>>
where P: AsRef<OsStr>,

Evaluate a file containing Jsonnet code, returning a number of JSON files.

§Errors

Returns any jsonnet error during evaluation.

§Panics

Panics if filename contains embedded nul characters.

Source

pub fn evaluate_snippet_stream<'a, P>( &'a mut self, filename: P, snippet: &str, ) -> Result<EvalList<'a>, Error<'a>>
where P: AsRef<OsStr>,

Evaluate a string containing Jsonnet code, returning a number of JSON files.

§Errors

Returns any jsonnet error during evaluation.

§Panics

Panics if filename or snippet contain embedded nul characters.

§Examples
use jsonnet::JsonnetVm;

let mut vm = JsonnetVm::new();
let output = vm.evaluate_snippet_stream("stream",
   "['foo', 'bar']").unwrap();

let list: Vec<_> = output.iter().collect();
assert_eq!(list, vec!["\"foo\"\n", "\"bar\"\n"]);

Trait Implementations§

Source§

impl Drop for JsonnetVm

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.