difftreelog
refactor rework layout and path handling
in: master
32 files changed
bindings/jsonnet/src/import.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/import.rs
+++ b/bindings/jsonnet/src/import.rs
@@ -10,7 +10,6 @@
os::raw::{c_char, c_int},
path::{Path, PathBuf},
ptr::null_mut,
- rc::Rc,
};
use jrsonnet_evaluator::{
@@ -33,7 +32,7 @@
out: RefCell<HashMap<PathBuf, Vec<u8>>>,
}
impl ImportResolver for CallbackImportResolver {
- fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {
+ fn resolve_file(&self, from: &Path, path: &Path) -> Result<PathBuf> {
let base = CString::new(from.to_str().unwrap()).unwrap().into_raw();
let rel = CString::new(path.to_str().unwrap()).unwrap().into_raw();
let found_here: *mut c_char = null_mut();
@@ -73,7 +72,7 @@
unsafe { CString::from_raw(result_ptr) };
}
- Ok(found_here_buf.into())
+ Ok(found_here_buf)
}
fn load_file_contents(&self, resolved: &Path) -> Result<Vec<u8>> {
Ok(self.out.borrow().get(resolved).unwrap().clone())
@@ -109,7 +108,7 @@
}
}
impl ImportResolver for NativeImportResolver {
- fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {
+ fn resolve_file(&self, from: &Path, path: &Path) -> Result<PathBuf> {
let mut new_path = from.to_owned();
new_path.push(path);
if new_path.exists() {
bindings/jsonnet/src/lib.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -111,7 +111,7 @@
) -> *const c_char {
let filename = CStr::from_ptr(filename);
match vm
- .evaluate_file_raw_nocwd(&PathBuf::from(filename.to_str().unwrap()))
+ .import(PathBuf::from(filename.to_str().unwrap()))
.and_then(|v| vm.with_tla(v))
.and_then(|v| vm.manifest(v))
{
@@ -140,8 +140,8 @@
let filename = CStr::from_ptr(filename);
let snippet = CStr::from_ptr(snippet);
match vm
- .evaluate_snippet_raw(
- PathBuf::from(filename.to_str().unwrap()).into(),
+ .evaluate_snippet(
+ filename.to_str().unwrap().into(),
snippet.to_str().unwrap().into(),
)
.and_then(|v| vm.with_tla(v))
@@ -185,7 +185,7 @@
) -> *const c_char {
let filename = CStr::from_ptr(filename);
match vm
- .evaluate_file_raw_nocwd(&PathBuf::from(filename.to_str().unwrap()))
+ .import(PathBuf::from(filename.to_str().unwrap()))
.and_then(|v| vm.with_tla(v))
.and_then(|v| vm.manifest_multi(v))
{
@@ -212,8 +212,8 @@
let filename = CStr::from_ptr(filename);
let snippet = CStr::from_ptr(snippet);
match vm
- .evaluate_snippet_raw(
- PathBuf::from(filename.to_str().unwrap()).into(),
+ .evaluate_snippet(
+ filename.to_str().unwrap().into(),
snippet.to_str().unwrap().into(),
)
.and_then(|v| vm.with_tla(v))
@@ -255,7 +255,7 @@
) -> *const c_char {
let filename = CStr::from_ptr(filename);
match vm
- .evaluate_file_raw_nocwd(&PathBuf::from(filename.to_str().unwrap()))
+ .import(PathBuf::from(filename.to_str().unwrap()))
.and_then(|v| vm.with_tla(v))
.and_then(|v| vm.manifest_stream(v))
{
@@ -282,8 +282,8 @@
let filename = CStr::from_ptr(filename);
let snippet = CStr::from_ptr(snippet);
match vm
- .evaluate_snippet_raw(
- PathBuf::from(filename.to_str().unwrap()).into(),
+ .evaluate_snippet(
+ filename.to_str().unwrap().into(),
snippet.to_str().unwrap().into(),
)
.and_then(|v| vm.with_tla(v))
bindings/jsonnet/src/native.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/native.rs
+++ b/bindings/jsonnet/src/native.rs
@@ -1,8 +1,6 @@
use std::{
ffi::{c_void, CStr},
os::raw::{c_char, c_int},
- path::Path,
- rc::Rc,
};
use gcmodule::Cc;
@@ -28,7 +26,7 @@
cb: JsonnetNativeCallback,
}
impl NativeCallbackHandler for JsonnetNativeCallbackHandler {
- fn call(&self, s: State, _from: Option<Rc<Path>>, args: &[Val]) -> Result<Val, LocError> {
+ fn call(&self, s: State, args: &[Val]) -> Result<Val, LocError> {
let mut n_args = Vec::new();
for a in args {
n_args.push(Some(Box::new(a.clone())));
cmds/jrsonnet/src/main.rsdiffbeforeafterboth--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -120,17 +120,14 @@
opts.manifest.configure(s)?;
let val = if opts.input.exec {
- s.evaluate_snippet_raw(
- PathBuf::from("<cmdline>").into(),
- (&opts.input.input as &str).into(),
- )?
+ s.evaluate_snippet("<cmdline>".to_owned(), (&opts.input.input as &str).into())?
} else if opts.input.input == "-" {
let mut input = Vec::new();
std::io::stdin().read_to_end(&mut input)?;
let input_str = std::str::from_utf8(&input)?.into();
- s.evaluate_snippet_raw(PathBuf::from("<stdin>").into(), input_str)?
+ s.evaluate_snippet("<stdin>".to_owned(), input_str)?
} else {
- s.evaluate_file_raw(&PathBuf::from(opts.input.input))?
+ s.import(s.resolve_file(&PathBuf::new(), &opts.input.input)?)?
};
let val = s.with_tla(val)?;
crates/jrsonnet-cli/src/ext.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/ext.rs
+++ b/crates/jrsonnet-cli/src/ext.rs
@@ -108,10 +108,10 @@
s.add_ext_str((&ext.name as &str).into(), (&ext.value as &str).into());
}
for ext in self.ext_code.iter() {
- s.add_ext_code((&ext.name as &str).into(), (&ext.value as &str).into())?;
+ s.add_ext_code(&ext.name as &str, (&ext.value as &str).into())?;
}
for ext in self.ext_code_file.iter() {
- s.add_ext_code((&ext.name as &str).into(), (&ext.value as &str).into())?;
+ s.add_ext_code(&ext.name as &str, (&ext.value as &str).into())?;
}
Ok(())
}
crates/jrsonnet-cli/src/tla.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/tla.rs
+++ b/crates/jrsonnet-cli/src/tla.rs
@@ -55,10 +55,10 @@
s.add_tla_str((&tla.name as &str).into(), (&tla.value as &str).into())
}
for tla in self.tla_code.iter() {
- s.add_tla_code((&tla.name as &str).into(), (&tla.value as &str).into())?;
+ s.add_tla_code((&tla.name as &str).into(), &tla.value as &str)?;
}
for tla in self.tla_code_file.iter() {
- s.add_tla_code((&tla.name as &str).into(), (&tla.value as &str).into())?;
+ s.add_tla_code((&tla.name as &str).into(), &tla.value as &str)?;
}
Ok(())
}
crates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-evaluator/Cargo.toml
+++ b/crates/jrsonnet-evaluator/Cargo.toml
@@ -28,6 +28,8 @@
jrsonnet-types = { path = "../jrsonnet-types", version = "0.4.2" }
jrsonnet-macros = { path = "../jrsonnet-macros", version = "0.4.2" }
pathdiff = "0.2.1"
+hashbrown = "0.12.1"
+static_assertions = "1.1.0"
md5 = "0.7.0"
base64 = "0.13.0"
crates/jrsonnet-evaluator/build.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/build.rs
+++ b/crates/jrsonnet-evaluator/build.rs
@@ -1,19 +1,14 @@
-use std::{
- env,
- fs::File,
- io::Write,
- path::{Path, PathBuf},
-};
+use std::{borrow::Cow, env, fs::File, io::Write, path::Path};
use bincode::serialize;
-use jrsonnet_parser::{parse, ParserSettings};
+use jrsonnet_parser::{parse, ParserSettings, Source};
use jrsonnet_stdlib::STDLIB_STR;
fn main() {
let parsed = parse(
STDLIB_STR,
&ParserSettings {
- file_name: PathBuf::from("std.jsonnet").into(),
+ file_name: Source::new_virtual(Cow::Borrowed("<std>")),
},
)
.expect("parse");
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -1,12 +1,8 @@
-use std::{
- fmt::Debug,
- path::{Path, PathBuf},
- rc::Rc,
-};
+use std::{fmt::Debug, path::PathBuf};
use gcmodule::Trace;
use jrsonnet_interner::IStr;
-use jrsonnet_parser::{BinaryOpType, ExprLocation, UnaryOpType};
+use jrsonnet_parser::{BinaryOpType, ExprLocation, Source, UnaryOpType};
use jrsonnet_types::ValType;
use thiserror::Error;
@@ -85,7 +81,7 @@
StandaloneSuper,
#[error("can't resolve {1} from {0}")]
- ImportFileNotFound(PathBuf, PathBuf),
+ ImportFileNotFound(PathBuf, String),
#[error("resolved file not found: {0}")]
ResolvedFileNotFound(PathBuf),
#[error("imported file is not valid utf-8: {0:?}")]
@@ -94,6 +90,8 @@
ImportIo(String),
#[error("tried to import {1} from {0}, but imports is not supported")]
ImportNotSupported(PathBuf, PathBuf),
+ #[error("can't import from virtual file")]
+ CantImportFromVirtualFile,
#[error(
"syntax error: expected {}, got {:?}",
.error.expected,
@@ -101,8 +99,7 @@
.map_or_else(|| "EOF".into(), |c| c.to_string())
)]
ImportSyntaxError {
- #[skip_trace]
- path: Rc<Path>,
+ path: Source,
source_code: IStr,
#[skip_trace]
error: Box<jrsonnet_parser::ParseError>,
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -452,7 +452,7 @@
Ok(Some(v)) => Ok(v),
Ok(None) => throw!(NoSuchField(key.clone())),
Err(e) if matches!(e.error(), MagicThisFileUsed) => {
- Ok(Val::Str(loc.0.to_string_lossy().into()))
+ Ok(Val::Str(loc.0.full_path().into()))
}
Err(e) => Err(e),
},
@@ -617,28 +617,27 @@
std_slice(indexable.into_indexable()?, start, end, step)?
}
- Import(path) => {
+ i @ (Import(path) | ImportStr(path) | ImportBin(path)) => {
let tmp = loc.clone().0;
- let mut import_location = tmp.to_path_buf();
- import_location.pop();
- s.push(
+ let import_location = tmp
+ .path()
+ .map(|p| {
+ let mut p = p.to_owned();
+ p.pop();
+ p
+ })
+ .unwrap_or_default();
+ let path = s.resolve_file(&import_location, path as &str)?;
+ match i {
+ Import(_) => s.push(
CallLocation::new(loc),
- || format!("import {:?}", path),
- || s.import_file(&import_location, path),
- )?
- }
- ImportStr(path) => {
- let tmp = loc.clone().0;
- let mut import_location = tmp.to_path_buf();
- import_location.pop();
- Val::Str(s.import_file_str(&import_location, path)?)
+ || format!("import {:?}", path.clone()),
+ || s.import(path.clone()),
+ )?,
+ ImportStr(_) => Val::Str(s.import_str(path)?),
+ ImportBin(_) => Val::Arr(ArrValue::Bytes(s.import_bin(path)?)),
+ _ => unreachable!(),
}
- ImportBin(path) => {
- let tmp = loc.clone().0;
- let mut import_location = tmp.to_path_buf();
- import_location.pop();
- let bytes = s.import_file_bin(&import_location, path)?;
- Val::Arr(ArrValue::Bytes(bytes))
}
})
}
crates/jrsonnet-evaluator/src/function/arglike.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/arglike.rs
+++ b/crates/jrsonnet-evaluator/src/function/arglike.rs
@@ -47,6 +47,7 @@
}
}
+#[derive(Clone)]
pub enum TlaArg {
String(IStr),
Code(LocExpr),
crates/jrsonnet-evaluator/src/function/builtin.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/builtin.rs
+++ b/crates/jrsonnet-evaluator/src/function/builtin.rs
@@ -1,4 +1,4 @@
-use std::{borrow::Cow, path::Path, rc::Rc};
+use std::borrow::Cow;
use gcmodule::Trace;
@@ -51,16 +51,16 @@
&self.params
}
- fn call(&self, s: State, ctx: Context, loc: CallLocation, args: &dyn ArgsLike) -> Result<Val> {
+ fn call(&self, s: State, ctx: Context, _loc: CallLocation, args: &dyn ArgsLike) -> Result<Val> {
let args = parse_builtin_call(s.clone(), ctx, &self.params, args, true)?;
let mut out_args = Vec::with_capacity(self.params.len());
for p in &self.params {
out_args.push(args[&p.name].evaluate(s.clone())?);
}
- self.handler.call(s, loc.0.map(|l| l.0.clone()), &out_args)
+ self.handler.call(s, &out_args)
}
}
pub trait NativeCallbackHandler: Trace {
- fn call(&self, s: State, from: Option<Rc<Path>>, args: &[Val]) -> Result<Val>;
+ fn call(&self, s: State, args: &[Val]) -> Result<Val>;
}
crates/jrsonnet-evaluator/src/gc.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/gc.rs
+++ b/crates/jrsonnet-evaluator/src/gc.rs
@@ -1,13 +1,14 @@
/// Macros to help deal with Gc
use std::{
borrow::{Borrow, BorrowMut},
- collections::{HashMap, HashSet},
+ collections::HashSet,
hash::BuildHasherDefault,
ops::{Deref, DerefMut},
};
use gcmodule::{Trace, Tracer};
-use rustc_hash::{FxHashMap, FxHashSet};
+use hashbrown::HashMap;
+use rustc_hash::{FxHashSet, FxHasher};
/// Replacement for box, which assumes that the underlying type is [`Trace`]
/// Used in places, where `Cc<dyn Trait>` should be used instead, but it can't, because `CoerceUnsiced` is not stable
@@ -115,14 +116,13 @@
}
}
-#[derive(Clone)]
-pub struct GcHashMap<K, V>(pub FxHashMap<K, V>);
+pub struct GcHashMap<K, V>(pub HashMap<K, V, BuildHasherDefault<FxHasher>>);
impl<K, V> GcHashMap<K, V> {
pub fn new() -> Self {
Self(HashMap::default())
}
pub fn with_capacity(capacity: usize) -> Self {
- Self(FxHashMap::with_capacity_and_hasher(
+ Self(HashMap::with_capacity_and_hasher(
capacity,
BuildHasherDefault::default(),
))
@@ -141,7 +141,7 @@
}
}
impl<K, V> Deref for GcHashMap<K, V> {
- type Target = FxHashMap<K, V>;
+ type Target = HashMap<K, V, BuildHasherDefault<FxHasher>>;
fn deref(&self) -> &Self::Target {
&self.0
crates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/import.rs
+++ b/crates/jrsonnet-evaluator/src/import.rs
@@ -1,14 +1,11 @@
use std::{
any::Any,
- convert::TryFrom,
fs,
io::Read,
path::{Path, PathBuf},
- rc::Rc,
};
use fs::File;
-use jrsonnet_interner::IStr;
use crate::{
error::{Error::*, Result},
@@ -20,21 +17,10 @@
/// Resolves real file path, e.g. `(/home/user/manifests, b.libjsonnet)` can correspond
/// both to `/home/user/manifests/b.libjsonnet` and to `/home/user/${vendor}/b.libjsonnet`
/// where `${vendor}` is a library path.
- fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>>;
+ fn resolve_file(&self, from: &Path, path: &str) -> Result<PathBuf>;
fn load_file_contents(&self, resolved: &Path) -> Result<Vec<u8>>;
- /// Reads file from filesystem, should be used only with path received from `resolve_file`
- fn load_file_str(&self, resolved: &Path) -> Result<IStr> {
- Ok(IStr::try_from(&self.load_file_contents(resolved)? as &[u8])
- .map_err(|_| ImportBadFileUtf8(resolved.to_path_buf()))?)
- }
-
- /// Reads file from filesystem, should be used only with path received from `resolve_file`
- fn load_file_bin(&self, resolved: &Path) -> Result<Rc<[u8]>> {
- Ok(self.load_file_contents(resolved)?.into())
- }
-
/// # Safety
///
/// For use only in bindings, should not be used elsewhere.
@@ -46,7 +32,7 @@
/// Dummy resolver, can't resolve/load any file
pub struct DummyImportResolver;
impl ImportResolver for DummyImportResolver {
- fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {
+ fn resolve_file(&self, from: &Path, path: &str) -> Result<PathBuf> {
throw!(ImportNotSupported(from.into(), path.into()))
}
@@ -73,22 +59,23 @@
pub library_paths: Vec<PathBuf>,
}
impl ImportResolver for FileImportResolver {
- fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {
+ fn resolve_file(&self, from: &Path, path: &str) -> Result<PathBuf> {
let mut direct = from.to_path_buf();
direct.push(path);
if direct.exists() {
- Ok(direct.into())
+ Ok(direct.canonicalize().map_err(|e| ImportIo(e.to_string()))?)
} else {
for library_path in &self.library_paths {
let mut cloned = library_path.clone();
cloned.push(path);
if cloned.exists() {
- return Ok(cloned.into());
+ return Ok(cloned.canonicalize().map_err(|e| ImportIo(e.to_string()))?);
}
}
throw!(ImportFileNotFound(from.to_owned(), path.to_owned()))
}
}
+
fn load_file_contents(&self, id: &Path) -> Result<Vec<u8>> {
let mut file = File::open(id).map_err(|_e| ResolvedFileNotFound(id.to_owned()))?;
let mut out = Vec::new();
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -38,6 +38,7 @@
pub mod val;
use std::{
+ borrow::Cow,
cell::{Ref, RefCell, RefMut},
collections::HashMap,
fmt::{self, Debug},
@@ -52,7 +53,9 @@
use function::{builtin::Builtin, CallLocation, TlaArg};
use gc::{GcHashMap, TraceBox};
use gcmodule::{Cc, Trace, Weak};
+use hashbrown::hash_map::RawEntryMut;
pub use import::*;
+use jrsonnet_interner::IBytes;
pub use jrsonnet_interner::IStr;
pub use jrsonnet_parser as parser;
use jrsonnet_parser::*;
@@ -96,7 +99,7 @@
/// Limits amount of stack trace items preserved
pub max_trace: usize,
/// Used for s`td.extVar`
- pub ext_vars: HashMap<IStr, Val>,
+ pub ext_vars: HashMap<IStr, TlaArg>,
/// Used for ext.native
pub ext_natives: HashMap<IStr, Cc<TraceBox<dyn Builtin>>>,
/// TLA vars
@@ -141,16 +144,39 @@
stack_generation: usize,
breakpoints: Breakpoints,
+
/// Contains file source codes and evaluation results for imports and pretty-printed stacktraces
- files: GcHashMap<Rc<Path>, FileData>,
- str_files: GcHashMap<Rc<Path>, IStr>,
- bin_files: GcHashMap<Rc<Path>, Rc<[u8]>>,
+ files: GcHashMap<PathBuf, FileData>,
+ /// Contains tla arguments and others, which aren't needed to be obtained by name
+ volatile_files: GcHashMap<String, String>,
}
+struct FileData {
+ string: Option<IStr>,
+ bytes: Option<IBytes>,
+ parsed: Option<LocExpr>,
+ evaluated: Option<Val>,
-pub struct FileData {
- source_code: IStr,
- parsed: LocExpr,
- evaluated: Option<Val>,
+ evaluating: bool,
+}
+impl FileData {
+ fn new_string(data: IStr) -> Self {
+ Self {
+ string: Some(data),
+ bytes: None,
+ parsed: None,
+ evaluated: None,
+ evaluating: false,
+ }
+ }
+ fn new_bytes(data: IBytes) -> Self {
+ Self {
+ string: None,
+ bytes: Some(data),
+ parsed: None,
+ evaluated: None,
+ evaluating: false,
+ }
+ }
}
#[allow(clippy::type_complexity)]
@@ -198,61 +224,159 @@
pub struct State(Rc<EvaluationStateInternals>);
impl State {
- /// Parses and adds file as loaded
- pub fn add_file(&self, path: Rc<Path>, source_code: IStr) -> Result<LocExpr> {
- let parsed = parse(
- &source_code,
- &ParserSettings {
- file_name: path.clone(),
- },
- )
- .map_err(|error| ImportSyntaxError {
- error: Box::new(error),
- path: path.clone(),
- source_code: source_code.clone(),
- })?;
- self.add_parsed_file(path, source_code, parsed.clone())?;
+ pub fn import_str(&self, path: PathBuf) -> Result<IStr> {
+ let mut data = self.data_mut();
+ let mut file = data.files.raw_entry_mut().from_key(&path);
- Ok(parsed)
+ let file = match file {
+ RawEntryMut::Occupied(ref mut d) => d.get_mut(),
+ RawEntryMut::Vacant(v) => {
+ let data = self.settings().import_resolver.load_file_contents(&path)?;
+ v.insert(
+ path.clone(),
+ FileData::new_string(
+ std::str::from_utf8(&data)
+ .map_err(|_| ImportBadFileUtf8(path.clone()))?
+ .into(),
+ ),
+ )
+ .1
+ }
+ };
+ if let Some(str) = &file.string {
+ return Ok(str.clone());
+ }
+ if file.string.is_none() {
+ file.string = Some(
+ file.bytes
+ .as_ref()
+ .expect("either string or bytes should be set")
+ .clone()
+ .cast_str()
+ .ok_or_else(|| ImportBadFileUtf8(path.clone()))?,
+ );
+ }
+ Ok(file.string.as_ref().expect("just set").clone())
}
+ pub fn import_bin(&self, path: PathBuf) -> Result<IBytes> {
+ let mut data = self.data_mut();
+ let mut file = data.files.raw_entry_mut().from_key(&path);
- pub fn reset_evaluation_state(&self, name: &Path) {
- self.data_mut()
- .files
- .get_mut(name)
- .expect("file not found")
- .evaluated
- .take();
+ let file = match file {
+ RawEntryMut::Occupied(ref mut d) => d.get_mut(),
+ RawEntryMut::Vacant(v) => {
+ let data = self.settings().import_resolver.load_file_contents(&path)?;
+ v.insert(path.clone(), FileData::new_bytes(data.as_slice().into()))
+ .1
+ }
+ };
+ if let Some(str) = &file.bytes {
+ return Ok(str.clone());
+ }
+ if file.bytes.is_none() {
+ file.bytes = Some(
+ file.string
+ .as_ref()
+ .expect("either string or bytes should be set")
+ .clone()
+ .cast_bytes(),
+ );
+ }
+ Ok(file.bytes.as_ref().expect("just set").clone())
}
+ pub fn import(&self, path: PathBuf) -> Result<Val> {
+ let mut data = self.data_mut();
+ let mut file = data.files.raw_entry_mut().from_key(&path);
- /// Adds file by source code and parsed expr
- pub fn add_parsed_file(
- &self,
- name: Rc<Path>,
- source_code: IStr,
- parsed: LocExpr,
- ) -> Result<()> {
- self.data_mut().files.insert(
- name,
- FileData {
- source_code,
- parsed,
- evaluated: None,
- },
- );
+ let file = match file {
+ RawEntryMut::Occupied(ref mut d) => d.get_mut(),
+ RawEntryMut::Vacant(v) => {
+ let data = self.settings().import_resolver.load_file_contents(&path)?;
+ v.insert(
+ path.clone(),
+ FileData::new_string(
+ std::str::from_utf8(&data)
+ .map_err(|_| ImportBadFileUtf8(path.clone()))?
+ .into(),
+ ),
+ )
+ .1
+ }
+ };
+ if let Some(val) = &file.evaluated {
+ return Ok(val.clone());
+ }
+ if file.string.is_none() {
+ file.string = Some(
+ std::str::from_utf8(
+ file.bytes
+ .as_ref()
+ .expect("either string or bytes should be set"),
+ )
+ .map_err(|_| ImportBadFileUtf8(path.clone()))?
+ .into(),
+ );
+ }
+ let code = file.string.as_ref().expect("just set");
+ let file_name = Source::new(path.clone()).expect("resolver should return correct name");
+ if file.parsed.is_none() {
+ file.parsed = Some(
+ jrsonnet_parser::parse(
+ code,
+ &ParserSettings {
+ file_name: file_name.clone(),
+ },
+ )
+ .map_err(|e| ImportSyntaxError {
+ path: file_name,
+ source_code: code.clone(),
+ error: Box::new(e),
+ })?,
+ );
+ }
+ let parsed = file.parsed.as_ref().expect("just set").clone();
+ if file.evaluating {
+ throw!(InfiniteRecursionDetected)
+ }
+ file.evaluating = true;
+ // Dropping file here, as it borrows data, which may be used in evaluation
+ drop(data);
+ let res = evaluate(self.clone(), self.create_default_context(), &parsed);
+
+ let mut data = self.data_mut();
+ let mut file = data.files.raw_entry_mut().from_key(&path);
- Ok(())
+ let file = match file {
+ RawEntryMut::Occupied(ref mut d) => d.get_mut(),
+ RawEntryMut::Vacant(_) => unreachable!("this file was just here!"),
+ };
+ file.evaluating = false;
+ match res {
+ Ok(v) => {
+ file.evaluated = Some(v.clone());
+ Ok(v)
+ }
+ Err(e) => Err(e),
+ }
}
- pub fn get_source(&self, name: &Path) -> Option<IStr> {
- let ro_map = &self.data().files;
- ro_map.get(name).map(|value| value.source_code.clone())
+
+ pub fn get_source(&self, name: Source) -> Option<String> {
+ let data = self.data();
+ match name.repr() {
+ Ok(real) => data
+ .files
+ .get(real)
+ .and_then(|f| f.string.as_ref())
+ .map(ToString::to_string),
+ Err(e) => data.volatile_files.get(e).map(ToOwned::to_owned),
+ }
}
- pub fn map_source_locations(&self, file: &Path, locs: &[usize]) -> Vec<CodeLocation> {
+ pub fn map_source_locations(&self, file: Source, locs: &[u32]) -> Vec<CodeLocation> {
offset_to_location(&self.get_source(file).unwrap_or_else(|| "".into()), locs)
}
pub fn map_from_source_location(
&self,
- file: &Path,
+ file: Source,
line: usize,
column: usize,
) -> Option<usize> {
@@ -262,74 +386,14 @@
column,
)
}
- pub fn import_file(&self, from: &Path, path: &Path) -> Result<Val> {
- let file_path = self.resolve_file(from, path)?;
- {
- let data = self.data();
- let files = &data.files;
- if files.contains_key(&file_path as &Path) {
- drop(data);
- return self.evaluate_loaded_file_raw(&file_path);
- }
- }
- let contents = self.load_file_str(&file_path)?;
- self.add_file(file_path.clone(), contents)?;
- self.evaluate_loaded_file_raw(&file_path)
- }
- pub(crate) fn import_file_str(&self, from: &Path, path: &Path) -> Result<IStr> {
- let path = self.resolve_file(from, path)?;
- if !self.data().str_files.contains_key(&path) {
- let file_str = self.load_file_str(&path)?;
- self.data_mut().str_files.insert(path.clone(), file_str);
- }
- Ok(self.data().str_files.get(&path).cloned().unwrap())
- }
- pub(crate) fn import_file_bin(&self, from: &Path, path: &Path) -> Result<Rc<[u8]>> {
- let path = self.resolve_file(from, path)?;
- if !self.data().bin_files.contains_key(&path) {
- let file_bin = self.load_file_bin(&path)?;
- self.data_mut().bin_files.insert(path.clone(), file_bin);
- }
- Ok(self.data().bin_files.get(&path).cloned().unwrap())
- }
-
- fn evaluate_loaded_file_raw(&self, name: &Path) -> Result<Val> {
- let expr: LocExpr = {
- let ro_map = &self.data().files;
- let value = ro_map
- .get(name)
- .unwrap_or_else(|| panic!("file not added: {:?}", name));
- if let Some(ref evaluated) = value.evaluated {
- return Ok(evaluated.clone());
- }
- value.parsed.clone()
- };
- let value = evaluate(self.clone(), self.create_default_context(), &expr)?;
- {
- self.data_mut()
- .files
- .get_mut(name)
- .unwrap()
- .evaluated
- .replace(value.clone());
- }
- Ok(value)
- }
-
/// Adds standard library global variable (std) to this evaluator
pub fn with_stdlib(&self) -> &Self {
- use jrsonnet_stdlib::STDLIB_STR;
- let std_path: Rc<Path> = PathBuf::from("std.jsonnet").into();
-
- self.add_parsed_file(
- std_path.clone(),
- STDLIB_STR.to_owned().into(),
- stdlib::get_parsed_stdlib(),
+ let val = evaluate(
+ self.clone(),
+ self.create_default_context(),
+ &stdlib::get_parsed_stdlib(),
)
- .expect("stdlib is correct");
- let val = self
- .evaluate_loaded_file_raw(&std_path)
- .expect("stdlib is correct");
+ .expect("std should not fail");
self.settings_mut().globals.insert("std".into(), val);
self
}
@@ -506,46 +570,55 @@
/// Raw methods evaluate passed values but don't perform TLA execution
impl State {
- pub fn evaluate_file_raw(&self, name: &Path) -> Result<Val> {
- self.import_file(&std::env::current_dir().expect("cwd"), name)
- }
- pub fn evaluate_file_raw_nocwd(&self, name: &Path) -> Result<Val> {
- self.import_file(&PathBuf::from("."), name)
- }
/// Parses and evaluates the given snippet
- pub fn evaluate_snippet_raw(&self, source: Rc<Path>, code: IStr) -> Result<Val> {
- let parsed = parse(
+ pub fn evaluate_snippet(&self, name: String, code: String) -> Result<Val> {
+ let source = Source::new_virtual(Cow::Owned(name.clone()));
+ let parsed = jrsonnet_parser::parse(
&code,
&ParserSettings {
file_name: source.clone(),
},
)
.map_err(|e| ImportSyntaxError {
- path: source.clone(),
- source_code: code.clone(),
+ path: source,
+ source_code: code.clone().into(),
error: Box::new(e),
})?;
- self.add_parsed_file(source, code, parsed.clone())?;
- self.evaluate_expr_raw(parsed)
+ self.data_mut().volatile_files.insert(name, code);
+ evaluate(self.clone(), self.create_default_context(), &parsed)
}
- /// Evaluates the parsed expression
- pub fn evaluate_expr_raw(&self, code: LocExpr) -> Result<Val> {
- evaluate(self.clone(), self.create_default_context(), &code)
- }
}
/// Settings utilities
impl State {
pub fn add_ext_var(&self, name: IStr, value: Val) {
- self.settings_mut().ext_vars.insert(name, value);
+ self.settings_mut()
+ .ext_vars
+ .insert(name, TlaArg::Val(value));
}
pub fn add_ext_str(&self, name: IStr, value: IStr) {
- self.add_ext_var(name, Val::Str(value));
+ self.settings_mut()
+ .ext_vars
+ .insert(name, TlaArg::String(value));
}
- pub fn add_ext_code(&self, name: IStr, code: IStr) -> Result<()> {
- let value =
- self.evaluate_snippet_raw(PathBuf::from(format!("ext_code {}", name)).into(), code)?;
- self.add_ext_var(name, value);
+ pub fn add_ext_code(&self, name: &str, code: String) -> Result<()> {
+ let source_name = format!("<extvar:{}>", name);
+ let source = Source::new_virtual(Cow::Owned(source_name.clone()));
+ let parsed = jrsonnet_parser::parse(
+ &code,
+ &ParserSettings {
+ file_name: source.clone(),
+ },
+ )
+ .map_err(|e| ImportSyntaxError {
+ path: source,
+ source_code: code.clone().into(),
+ error: Box::new(e),
+ })?;
+ self.data_mut().volatile_files.insert(source_name, code);
+ self.settings_mut()
+ .ext_vars
+ .insert(name.into(), TlaArg::Code(parsed));
Ok(())
}
@@ -559,22 +632,33 @@
.tla_vars
.insert(name, TlaArg::String(value));
}
- pub fn add_tla_code(&self, name: IStr, code: IStr) -> Result<()> {
- let parsed = self.add_file(PathBuf::from(format!("tla_code {}", name)).into(), code)?;
+ pub fn add_tla_code(&self, name: IStr, code: &str) -> Result<()> {
+ let source_name = format!("<top-level-arg:{}>", name);
+ let source = Source::new_virtual(Cow::Owned(source_name.clone()));
+ let parsed = jrsonnet_parser::parse(
+ code,
+ &ParserSettings {
+ file_name: source.clone(),
+ },
+ )
+ .map_err(|e| ImportSyntaxError {
+ path: source,
+ source_code: code.into(),
+ error: Box::new(e),
+ })?;
+ self.data_mut()
+ .volatile_files
+ .insert(source_name, code.to_owned());
self.settings_mut()
.tla_vars
.insert(name, TlaArg::Code(parsed));
Ok(())
}
- pub fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {
- self.settings().import_resolver.resolve_file(from, path)
- }
- pub fn load_file_str(&self, path: &Path) -> Result<IStr> {
- self.settings().import_resolver.load_file_str(path)
- }
- pub fn load_file_bin(&self, path: &Path) -> Result<Rc<[u8]>> {
- self.settings().import_resolver.load_file_bin(path)
+ pub fn resolve_file(&self, from: &Path, path: &str) -> Result<PathBuf> {
+ self.settings()
+ .import_resolver
+ .resolve_file(from, path.as_ref())
}
pub fn import_resolver(&self) -> Ref<dyn ImportResolver> {
crates/jrsonnet-evaluator/src/map.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/map.rs
+++ b/crates/jrsonnet-evaluator/src/map.rs
@@ -14,6 +14,15 @@
pub struct LayeredHashMap(Cc<LayeredHashMapInternals>);
impl LayeredHashMap {
+ pub fn iter_keys(self, mut handler: impl FnMut(IStr)) {
+ for (k, _) in self.0.current.iter() {
+ handler(k.clone());
+ }
+ if let Some(parent) = self.0.parent.clone() {
+ parent.iter_keys(handler);
+ }
+ }
+
pub fn extend(self, new_layer: GcHashMap<IStr, Thunk<Val>>) -> Self {
Self(Cc::new(LayeredHashMapInternals {
parent: Some(self),
crates/jrsonnet-evaluator/src/stdlib/expr.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/expr.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/expr.rs
@@ -1,6 +1,6 @@
-use std::path::PathBuf;
+use std::borrow::Cow;
-use jrsonnet_parser::{LocExpr, ParserSettings};
+use jrsonnet_parser::{LocExpr, ParserSettings, Source};
thread_local! {
/// To avoid parsing again when issued from the same thread
@@ -16,7 +16,7 @@
jrsonnet_parser::parse(
jrsonnet_stdlib::STDLIB_STR,
&ParserSettings {
- file_name: PathBuf::from("std.jsonnet").into(),
+ file_name: Source::new_virtual(Cow::Borrowed("<std>")),
},
)
.unwrap()
crates/jrsonnet-evaluator/src/stdlib/mod.rsdiffbeforeafterboth1// All builtins should return results2#![allow(clippy::unnecessary_wraps)]34use std::collections::HashMap;56use format::{format_arr, format_obj};7use gcmodule::Cc;8use jrsonnet_interner::IStr;9use serde::Deserialize;10use serde_yaml::DeserializingQuirks;1112use crate::{13 error::{Error::*, Result},14 function::{builtin::StaticBuiltin, CallLocation, FuncVal},15 operator::evaluate_mod_op,16 stdlib::manifest::{manifest_yaml_ex, ManifestYamlOptions},17 throw,18 typed::{Any, BoundedUsize, Bytes, Either2, Either4, PositiveF64, Typed, VecVal, M1},19 val::{equals, primitive_equals, ArrValue, IndexableVal, Slice},20 Either, ObjValue, State, Val,21};2223pub mod expr;24pub use expr::*;2526use self::manifest::{escape_string_json, manifest_json_ex, ManifestJsonOptions, ManifestType};2728pub mod format;29pub mod manifest;30pub mod sort;3132pub fn std_format(s: State, str: IStr, vals: Val) -> Result<String> {33 s.push(34 CallLocation::native(),35 || format!("std.format of {}", str),36 || {37 Ok(match vals {38 Val::Arr(vals) => format_arr(s.clone(), &str, &vals.evaluated(s.clone())?)?,39 Val::Obj(obj) => format_obj(s.clone(), &str, &obj)?,40 o => format_arr(s.clone(), &str, &[o])?,41 })42 },43 )44}4546pub fn std_slice(47 indexable: IndexableVal,48 index: Option<BoundedUsize<0, { i32::MAX as usize }>>,49 end: Option<BoundedUsize<0, { i32::MAX as usize }>>,50 step: Option<BoundedUsize<1, { i32::MAX as usize }>>,51) -> Result<Val> {52 match &indexable {53 IndexableVal::Str(s) => {54 let index = index.as_deref().copied().unwrap_or(0);55 let end = end.as_deref().copied().unwrap_or(usize::MAX);56 let step = step.as_deref().copied().unwrap_or(1);5758 if index >= end {59 return Ok(Val::Str("".into()));60 }6162 Ok(Val::Str(63 (s.chars()64 .skip(index)65 .take(end - index)66 .step_by(step)67 .collect::<String>())68 .into(),69 ))70 }71 IndexableVal::Arr(arr) => {72 let index = index.as_deref().copied().unwrap_or(0);73 let end = end.as_deref().copied().unwrap_or(usize::MAX).min(arr.len());74 let step = step.as_deref().copied().unwrap_or(1);7576 if index >= end {77 return Ok(Val::Arr(ArrValue::new_eager()));78 }7980 Ok(Val::Arr(ArrValue::Slice(Box::new(Slice {81 inner: arr.clone(),82 from: index as u32,83 to: end as u32,84 step: step as u32,85 }))))86 }87 }88}8990type BuiltinsType = HashMap<IStr, &'static dyn StaticBuiltin>;9192thread_local! {93 pub static BUILTINS: BuiltinsType = {94 [95 ("length".into(), builtin_length::INST),96 ("type".into(), builtin_type::INST),97 ("makeArray".into(), builtin_make_array::INST),98 ("codepoint".into(), builtin_codepoint::INST),99 ("objectFieldsEx".into(), builtin_object_fields_ex::INST),100 ("objectHasEx".into(), builtin_object_has_ex::INST),101 ("slice".into(), builtin_slice::INST),102 ("substr".into(), builtin_substr::INST),103 ("primitiveEquals".into(), builtin_primitive_equals::INST),104 ("equals".into(), builtin_equals::INST),105 ("modulo".into(), builtin_modulo::INST),106 ("mod".into(), builtin_mod::INST),107 ("floor".into(), builtin_floor::INST),108 ("ceil".into(), builtin_ceil::INST),109 ("log".into(), builtin_log::INST),110 ("pow".into(), builtin_pow::INST),111 ("sqrt".into(), builtin_sqrt::INST),112 ("sin".into(), builtin_sin::INST),113 ("cos".into(), builtin_cos::INST),114 ("tan".into(), builtin_tan::INST),115 ("asin".into(), builtin_asin::INST),116 ("acos".into(), builtin_acos::INST),117 ("atan".into(), builtin_atan::INST),118 ("exp".into(), builtin_exp::INST),119 ("mantissa".into(), builtin_mantissa::INST),120 ("exponent".into(), builtin_exponent::INST),121 ("extVar".into(), builtin_ext_var::INST),122 ("native".into(), builtin_native::INST),123 ("filter".into(), builtin_filter::INST),124 ("map".into(), builtin_map::INST),125 ("flatMap".into(), builtin_flatmap::INST),126 ("foldl".into(), builtin_foldl::INST),127 ("foldr".into(), builtin_foldr::INST),128 ("sort".into(), builtin_sort::INST),129 ("format".into(), builtin_format::INST),130 ("range".into(), builtin_range::INST),131 ("char".into(), builtin_char::INST),132 ("encodeUTF8".into(), builtin_encode_utf8::INST),133 ("decodeUTF8".into(), builtin_decode_utf8::INST),134 ("md5".into(), builtin_md5::INST),135 ("base64".into(), builtin_base64::INST),136 ("base64DecodeBytes".into(), builtin_base64_decode_bytes::INST),137 ("base64Decode".into(), builtin_base64_decode::INST),138 ("trace".into(), builtin_trace::INST),139 ("join".into(), builtin_join::INST),140 ("escapeStringJson".into(), builtin_escape_string_json::INST),141 ("manifestJsonEx".into(), builtin_manifest_json_ex::INST),142 ("manifestYamlDoc".into(), builtin_manifest_yaml_doc::INST),143 ("reverse".into(), builtin_reverse::INST),144 ("strReplace".into(), builtin_str_replace::INST),145 ("splitLimit".into(), builtin_splitlimit::INST),146 ("parseJson".into(), builtin_parse_json::INST),147 ("parseYaml".into(), builtin_parse_yaml::INST),148 ("asciiUpper".into(), builtin_ascii_upper::INST),149 ("asciiLower".into(), builtin_ascii_lower::INST),150 ("member".into(), builtin_member::INST),151 ("count".into(), builtin_count::INST),152 ("any".into(), builtin_any::INST),153 ("all".into(), builtin_all::INST),154 ].iter().cloned().collect()155 };156}157158#[jrsonnet_macros::builtin]159fn builtin_length(x: Either![IStr, ArrValue, ObjValue, FuncVal]) -> Result<usize> {160 use Either4::*;161 Ok(match x {162 A(x) => x.chars().count(),163 B(x) => x.len(),164 C(x) => x.len(),165 D(f) => f.params_len(),166 })167}168169#[jrsonnet_macros::builtin]170fn builtin_type(x: Any) -> Result<IStr> {171 Ok(x.0.value_type().name().into())172}173174#[jrsonnet_macros::builtin]175fn builtin_make_array(s: State, sz: usize, func: FuncVal) -> Result<VecVal> {176 let mut out = Vec::with_capacity(sz);177 for i in 0..sz {178 out.push(func.evaluate_simple(s.clone(), &(i as f64,))?);179 }180 Ok(VecVal(Cc::new(out)))181}182183#[jrsonnet_macros::builtin]184const fn builtin_codepoint(str: char) -> Result<u32> {185 Ok(str as u32)186}187188#[jrsonnet_macros::builtin]189fn builtin_object_fields_ex(190 obj: ObjValue,191 inc_hidden: bool,192 #[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,193) -> Result<VecVal> {194 #[cfg(feature = "exp-preserve-order")]195 let preserve_order = preserve_order.unwrap_or(false);196 let out = obj.fields_ex(197 inc_hidden,198 #[cfg(feature = "exp-preserve-order")]199 preserve_order,200 );201 Ok(VecVal(Cc::new(202 out.into_iter().map(Val::Str).collect::<Vec<_>>(),203 )))204}205206#[jrsonnet_macros::builtin]207fn builtin_object_has_ex(obj: ObjValue, f: IStr, inc_hidden: bool) -> Result<bool> {208 Ok(obj.has_field_ex(f, inc_hidden))209}210211#[jrsonnet_macros::builtin]212fn builtin_parse_json(st: State, s: IStr) -> Result<Any> {213 use serde_json::Value;214 let value: Value = serde_json::from_str(&s)215 .map_err(|e| RuntimeError(format!("failed to parse json: {}", e).into()))?;216 Ok(Any(Value::into_untyped(value, st)?))217}218219#[jrsonnet_macros::builtin]220fn builtin_parse_yaml(st: State, s: IStr) -> Result<Any> {221 use serde_json::Value;222 let value = serde_yaml::Deserializer::from_str_with_quirks(223 &s,224 DeserializingQuirks { old_octals: true },225 );226 let mut out = vec![];227 for item in value {228 let value = Value::deserialize(item)229 .map_err(|e| RuntimeError(format!("failed to parse yaml: {}", e).into()))?;230 let val = Value::into_untyped(value, st.clone())?;231 out.push(val);232 }233 Ok(Any(if out.is_empty() {234 Val::Null235 } else if out.len() == 1 {236 out.into_iter().next().unwrap()237 } else {238 Val::Arr(out.into())239 }))240}241242#[jrsonnet_macros::builtin]243fn builtin_slice(244 indexable: IndexableVal,245 index: Option<BoundedUsize<0, { i32::MAX as usize }>>,246 end: Option<BoundedUsize<0, { i32::MAX as usize }>>,247 step: Option<BoundedUsize<1, { i32::MAX as usize }>>,248) -> Result<Any> {249 std_slice(indexable, index, end, step).map(Any)250}251252#[jrsonnet_macros::builtin]253fn builtin_substr(str: IStr, from: usize, len: usize) -> Result<String> {254 Ok(str.chars().skip(from as usize).take(len as usize).collect())255}256257#[jrsonnet_macros::builtin]258fn builtin_primitive_equals(a: Any, b: Any) -> Result<bool> {259 primitive_equals(&a.0, &b.0)260}261262#[jrsonnet_macros::builtin]263fn builtin_equals(s: State, a: Any, b: Any) -> Result<bool> {264 equals(s, &a.0, &b.0)265}266267#[jrsonnet_macros::builtin]268fn builtin_modulo(a: f64, b: f64) -> Result<f64> {269 Ok(a % b)270}271272#[jrsonnet_macros::builtin]273fn builtin_mod(s: State, a: Either![f64, IStr], b: Any) -> Result<Any> {274 use Either2::*;275 Ok(Any(evaluate_mod_op(276 s,277 &match a {278 A(v) => Val::Num(v),279 B(s) => Val::Str(s),280 },281 &b.0,282 )?))283}284285#[jrsonnet_macros::builtin]286fn builtin_floor(x: f64) -> Result<f64> {287 Ok(x.floor())288}289290#[jrsonnet_macros::builtin]291fn builtin_ceil(x: f64) -> Result<f64> {292 Ok(x.ceil())293}294295#[jrsonnet_macros::builtin]296fn builtin_log(n: f64) -> Result<f64> {297 Ok(n.ln())298}299300#[jrsonnet_macros::builtin]301fn builtin_pow(x: f64, n: f64) -> Result<f64> {302 Ok(x.powf(n))303}304305#[jrsonnet_macros::builtin]306fn builtin_sqrt(x: PositiveF64) -> Result<f64> {307 Ok(x.0.sqrt())308}309310#[jrsonnet_macros::builtin]311fn builtin_sin(x: f64) -> Result<f64> {312 Ok(x.sin())313}314315#[jrsonnet_macros::builtin]316fn builtin_cos(x: f64) -> Result<f64> {317 Ok(x.cos())318}319320#[jrsonnet_macros::builtin]321fn builtin_tan(x: f64) -> Result<f64> {322 Ok(x.tan())323}324325#[jrsonnet_macros::builtin]326fn builtin_asin(x: f64) -> Result<f64> {327 Ok(x.asin())328}329330#[jrsonnet_macros::builtin]331fn builtin_acos(x: f64) -> Result<f64> {332 Ok(x.acos())333}334335#[jrsonnet_macros::builtin]336fn builtin_atan(x: f64) -> Result<f64> {337 Ok(x.atan())338}339340#[jrsonnet_macros::builtin]341fn builtin_exp(x: f64) -> Result<f64> {342 Ok(x.exp())343}344345fn frexp(s: f64) -> (f64, i16) {346 if 0.0 == s {347 (s, 0)348 } else {349 let lg = s.abs().log2();350 let x = (lg - lg.floor() - 1.0).exp2();351 let exp = lg.floor() + 1.0;352 (s.signum() * x, exp as i16)353 }354}355356#[jrsonnet_macros::builtin]357fn builtin_mantissa(x: f64) -> Result<f64> {358 Ok(frexp(x).0)359}360361#[jrsonnet_macros::builtin]362fn builtin_exponent(x: f64) -> Result<i16> {363 Ok(frexp(x).1)364}365366#[jrsonnet_macros::builtin]367fn builtin_ext_var(s: State, x: IStr) -> Result<Any> {368 Ok(Any(s369 .settings()370 .ext_vars371 .get(&x)372 .cloned()373 .ok_or(UndefinedExternalVariable(x))?))374}375376#[jrsonnet_macros::builtin]377fn builtin_native(s: State, name: IStr) -> Result<Any> {378 Ok(Any(s379 .settings()380 .ext_natives381 .get(&name)382 .cloned()383 .map_or(Val::Null, |v| {384 Val::Func(FuncVal::Builtin(v.clone()))385 })))386}387388#[jrsonnet_macros::builtin]389fn builtin_filter(s: State, func: FuncVal, arr: ArrValue) -> Result<ArrValue> {390 arr.filter(s.clone(), |val| {391 bool::from_untyped(392 func.evaluate_simple(s.clone(), &(Any(val.clone()),))?,393 s.clone(),394 )395 })396}397398#[jrsonnet_macros::builtin]399fn builtin_map(s: State, func: FuncVal, arr: ArrValue) -> Result<ArrValue> {400 arr.map(s.clone(), |val| {401 func.evaluate_simple(s.clone(), &(Any(val),))402 })403}404405#[jrsonnet_macros::builtin]406fn builtin_flatmap(s: State, func: FuncVal, arr: IndexableVal) -> Result<IndexableVal> {407 match arr {408 IndexableVal::Str(str) => {409 let mut out = String::new();410 for c in str.chars() {411 match func.evaluate_simple(s.clone(), &(c.to_string(),))? {412 Val::Str(o) => out.push_str(&o),413 Val::Null => continue,414 _ => throw!(RuntimeError(415 "in std.join all items should be strings".into()416 )),417 };418 }419 Ok(IndexableVal::Str(out.into()))420 }421 IndexableVal::Arr(a) => {422 let mut out = Vec::new();423 for el in a.iter(s.clone()) {424 let el = el?;425 match func.evaluate_simple(s.clone(), &(Any(el),))? {426 Val::Arr(o) => {427 for oe in o.iter(s.clone()) {428 out.push(oe?);429 }430 }431 Val::Null => continue,432 _ => throw!(RuntimeError(433 "in std.join all items should be arrays".into()434 )),435 };436 }437 Ok(IndexableVal::Arr(out.into()))438 }439 }440}441442#[jrsonnet_macros::builtin]443fn builtin_foldl(s: State, func: FuncVal, arr: ArrValue, init: Any) -> Result<Any> {444 let mut acc = init.0;445 for i in arr.iter(s.clone()) {446 acc = func.evaluate_simple(s.clone(), &(Any(acc), Any(i?)))?;447 }448 Ok(Any(acc))449}450451#[jrsonnet_macros::builtin]452fn builtin_foldr(s: State, func: FuncVal, arr: ArrValue, init: Any) -> Result<Any> {453 let mut acc = init.0;454 for i in arr.iter(s.clone()).rev() {455 acc = func.evaluate_simple(s.clone(), &(Any(i?), Any(acc)))?;456 }457 Ok(Any(acc))458}459460#[jrsonnet_macros::builtin]461#[allow(non_snake_case)]462fn builtin_sort(s: State, arr: ArrValue, keyF: Option<FuncVal>) -> Result<ArrValue> {463 if arr.len() <= 1 {464 return Ok(arr);465 }466 Ok(ArrValue::Eager(sort::sort(467 s.clone(),468 arr.evaluated(s)?,469 keyF.unwrap_or_else(FuncVal::identity),470 )?))471}472473#[jrsonnet_macros::builtin]474fn builtin_format(s: State, str: IStr, vals: Any) -> Result<String> {475 std_format(s, str, vals.0)476}477478#[jrsonnet_macros::builtin]479fn builtin_range(from: i32, to: i32) -> Result<ArrValue> {480 if to < from {481 return Ok(ArrValue::new_eager());482 }483 Ok(ArrValue::new_range(from, to))484}485486#[jrsonnet_macros::builtin]487fn builtin_char(n: u32) -> Result<char> {488 Ok(std::char::from_u32(n as u32).ok_or(InvalidUnicodeCodepointGot(n as u32))?)489}490491#[jrsonnet_macros::builtin]492fn builtin_encode_utf8(str: IStr) -> Result<Bytes> {493 Ok(Bytes(str.bytes().collect::<Vec<u8>>().into()))494}495496#[jrsonnet_macros::builtin]497fn builtin_decode_utf8(arr: Bytes) -> Result<IStr> {498 Ok(std::str::from_utf8(&arr.0)499 .map_err(|_| RuntimeError("bad utf8".into()))?500 .into())501}502503#[jrsonnet_macros::builtin]504fn builtin_md5(str: IStr) -> Result<String> {505 Ok(format!("{:x}", md5::compute(&str.as_bytes())))506}507508#[jrsonnet_macros::builtin]509fn builtin_trace(s: State, loc: CallLocation, str: IStr, rest: Any) -> Result<Any> {510 eprint!("TRACE:");511 if let Some(loc) = loc.0 {512 let locs = s.map_source_locations(&loc.0, &[loc.1]);513 eprint!(514 " {}:{}",515 loc.0.file_name().unwrap().to_str().unwrap(),516 locs[0].line517 );518 }519 eprintln!(" {}", str);520 Ok(rest) as Result<Any>521}522523#[jrsonnet_macros::builtin]524fn builtin_base64(input: Either![Bytes, IStr]) -> Result<String> {525 use Either2::*;526 Ok(match input {527 A(a) => base64::encode(a.0),528 B(l) => base64::encode(l.bytes().collect::<Vec<_>>()),529 })530}531532#[jrsonnet_macros::builtin]533fn builtin_base64_decode_bytes(input: IStr) -> Result<Bytes> {534 Ok(Bytes(535 base64::decode(&input.as_bytes())536 .map_err(|_| RuntimeError("bad base64".into()))?537 .into(),538 ))539}540541#[jrsonnet_macros::builtin]542fn builtin_base64_decode(input: IStr) -> Result<String> {543 let bytes = base64::decode(&input.as_bytes()).map_err(|_| RuntimeError("bad base64".into()))?;544 Ok(String::from_utf8(bytes).map_err(|_| RuntimeError("bad utf8".into()))?)545}546547#[jrsonnet_macros::builtin]548fn builtin_join(s: State, sep: IndexableVal, arr: ArrValue) -> Result<IndexableVal> {549 Ok(match sep {550 IndexableVal::Arr(joiner_items) => {551 let mut out = Vec::new();552553 let mut first = true;554 for item in arr.iter(s.clone()) {555 let item = item?.clone();556 if let Val::Arr(items) = item {557 if !first {558 out.reserve(joiner_items.len());559 // TODO: extend560 for item in joiner_items.iter(s.clone()) {561 out.push(item?);562 }563 }564 first = false;565 out.reserve(items.len());566 for item in items.iter(s.clone()) {567 out.push(item?);568 }569 } else if matches!(item, Val::Null) {570 continue;571 } else {572 throw!(RuntimeError(573 "in std.join all items should be arrays".into()574 ));575 }576 }577578 IndexableVal::Arr(out.into())579 }580 IndexableVal::Str(sep) => {581 let mut out = String::new();582583 let mut first = true;584 for item in arr.iter(s) {585 let item = item?.clone();586 if let Val::Str(item) = item {587 if !first {588 out += &sep;589 }590 first = false;591 out += &item;592 } else if matches!(item, Val::Null) {593 continue;594 } else {595 throw!(RuntimeError(596 "in std.join all items should be strings".into()597 ));598 }599 }600601 IndexableVal::Str(out.into())602 }603 })604}605606#[jrsonnet_macros::builtin]607fn builtin_escape_string_json(str_: IStr) -> Result<String> {608 Ok(escape_string_json(&str_))609}610611#[jrsonnet_macros::builtin]612fn builtin_manifest_json_ex(613 s: State,614 value: Any,615 indent: IStr,616 newline: Option<IStr>,617 key_val_sep: Option<IStr>,618 #[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,619) -> Result<String> {620 let newline = newline.as_deref().unwrap_or("\n");621 let key_val_sep = key_val_sep.as_deref().unwrap_or(": ");622 manifest_json_ex(623 s,624 &value.0,625 &ManifestJsonOptions {626 padding: &indent,627 mtype: ManifestType::Std,628 newline,629 key_val_sep,630 #[cfg(feature = "exp-preserve-order")]631 preserve_order: preserve_order.unwrap_or(false),632 },633 )634}635636#[jrsonnet_macros::builtin]637fn builtin_manifest_yaml_doc(638 s: State,639 value: Any,640 indent_array_in_object: Option<bool>,641 quote_keys: Option<bool>,642 #[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,643) -> Result<String> {644 manifest_yaml_ex(645 s,646 &value.0,647 &ManifestYamlOptions {648 padding: " ",649 arr_element_padding: if indent_array_in_object.unwrap_or(false) {650 " "651 } else {652 ""653 },654 quote_keys: quote_keys.unwrap_or(true),655 #[cfg(feature = "exp-preserve-order")]656 preserve_order: preserve_order.unwrap_or(false),657 },658 )659}660661#[jrsonnet_macros::builtin]662fn builtin_reverse(value: ArrValue) -> Result<ArrValue> {663 Ok(value.reversed())664}665666#[jrsonnet_macros::builtin]667fn builtin_str_replace(str: String, from: IStr, to: IStr) -> Result<String> {668 Ok(str.replace(&from as &str, &to as &str))669}670671#[jrsonnet_macros::builtin]672fn builtin_splitlimit(str: IStr, c: IStr, maxsplits: Either![usize, M1]) -> Result<VecVal> {673 use Either2::*;674 Ok(VecVal(Cc::new(match maxsplits {675 A(n) => str676 .splitn(n + 1, &c as &str)677 .map(|s| Val::Str(s.into()))678 .collect(),679 B(_) => str.split(&c as &str).map(|s| Val::Str(s.into())).collect(),680 })))681}682683#[jrsonnet_macros::builtin]684fn builtin_ascii_upper(str: IStr) -> Result<String> {685 Ok(str.to_ascii_uppercase())686}687688#[jrsonnet_macros::builtin]689fn builtin_ascii_lower(str: IStr) -> Result<String> {690 Ok(str.to_ascii_lowercase())691}692693#[jrsonnet_macros::builtin]694fn builtin_member(s: State, arr: IndexableVal, x: Any) -> Result<bool> {695 match arr {696 IndexableVal::Str(str) => {697 let x: IStr = IStr::from_untyped(x.0, s)?;698 Ok(!x.is_empty() && str.contains(&*x))699 }700 IndexableVal::Arr(a) => {701 for item in a.iter(s.clone()) {702 let item = item?;703 if equals(s.clone(), &item, &x.0)? {704 return Ok(true);705 }706 }707 Ok(false)708 }709 }710}711712#[jrsonnet_macros::builtin]713fn builtin_count(s: State, arr: Vec<Any>, v: Any) -> Result<usize> {714 let mut count = 0;715 for item in &arr {716 if equals(s.clone(), &item.0, &v.0)? {717 count += 1;718 }719 }720 Ok(count)721}722723#[jrsonnet_macros::builtin]724fn builtin_any(s: State, arr: ArrValue) -> Result<bool> {725 for v in arr.iter(s.clone()) {726 let v = bool::from_untyped(v?, s.clone())?;727 if v {728 return Ok(true);729 }730 }731 Ok(false)732}733734#[jrsonnet_macros::builtin]735fn builtin_all(s: State, arr: ArrValue) -> Result<bool> {736 for v in arr.iter(s.clone()) {737 let v = bool::from_untyped(v?, s.clone())?;738 if !v {739 return Ok(false);740 }741 }742 Ok(true)743}1// All builtins should return results2#![allow(clippy::unnecessary_wraps)]34use std::collections::HashMap;56use format::{format_arr, format_obj};7use gcmodule::Cc;8use jrsonnet_interner::{IBytes, IStr};9use serde::Deserialize;10use serde_yaml::DeserializingQuirks;1112use crate::{13 error::{Error::*, Result},14 function::{builtin::StaticBuiltin, ArgLike, CallLocation, FuncVal},15 operator::evaluate_mod_op,16 stdlib::manifest::{manifest_yaml_ex, ManifestYamlOptions},17 throw,18 typed::{Any, BoundedUsize, Either2, Either4, PositiveF64, Typed, VecVal, M1},19 val::{equals, primitive_equals, ArrValue, IndexableVal, Slice},20 Either, ObjValue, State, Val,21};2223pub mod expr;24pub use expr::*;2526use self::manifest::{escape_string_json, manifest_json_ex, ManifestJsonOptions, ManifestType};2728pub mod format;29pub mod manifest;30pub mod sort;3132pub fn std_format(s: State, str: IStr, vals: Val) -> Result<String> {33 s.push(34 CallLocation::native(),35 || format!("std.format of {}", str),36 || {37 Ok(match vals {38 Val::Arr(vals) => format_arr(s.clone(), &str, &vals.evaluated(s.clone())?)?,39 Val::Obj(obj) => format_obj(s.clone(), &str, &obj)?,40 o => format_arr(s.clone(), &str, &[o])?,41 })42 },43 )44}4546pub fn std_slice(47 indexable: IndexableVal,48 index: Option<BoundedUsize<0, { i32::MAX as usize }>>,49 end: Option<BoundedUsize<0, { i32::MAX as usize }>>,50 step: Option<BoundedUsize<1, { i32::MAX as usize }>>,51) -> Result<Val> {52 match &indexable {53 IndexableVal::Str(s) => {54 let index = index.as_deref().copied().unwrap_or(0);55 let end = end.as_deref().copied().unwrap_or(usize::MAX);56 let step = step.as_deref().copied().unwrap_or(1);5758 if index >= end {59 return Ok(Val::Str("".into()));60 }6162 Ok(Val::Str(63 (s.chars()64 .skip(index)65 .take(end - index)66 .step_by(step)67 .collect::<String>())68 .into(),69 ))70 }71 IndexableVal::Arr(arr) => {72 let index = index.as_deref().copied().unwrap_or(0);73 let end = end.as_deref().copied().unwrap_or(usize::MAX).min(arr.len());74 let step = step.as_deref().copied().unwrap_or(1);7576 if index >= end {77 return Ok(Val::Arr(ArrValue::new_eager()));78 }7980 Ok(Val::Arr(ArrValue::Slice(Box::new(Slice {81 inner: arr.clone(),82 from: index as u32,83 to: end as u32,84 step: step as u32,85 }))))86 }87 }88}8990type BuiltinsType = HashMap<IStr, &'static dyn StaticBuiltin>;9192thread_local! {93 pub static BUILTINS: BuiltinsType = {94 [95 ("length".into(), builtin_length::INST),96 ("type".into(), builtin_type::INST),97 ("makeArray".into(), builtin_make_array::INST),98 ("codepoint".into(), builtin_codepoint::INST),99 ("objectFieldsEx".into(), builtin_object_fields_ex::INST),100 ("objectHasEx".into(), builtin_object_has_ex::INST),101 ("slice".into(), builtin_slice::INST),102 ("substr".into(), builtin_substr::INST),103 ("primitiveEquals".into(), builtin_primitive_equals::INST),104 ("equals".into(), builtin_equals::INST),105 ("modulo".into(), builtin_modulo::INST),106 ("mod".into(), builtin_mod::INST),107 ("floor".into(), builtin_floor::INST),108 ("ceil".into(), builtin_ceil::INST),109 ("log".into(), builtin_log::INST),110 ("pow".into(), builtin_pow::INST),111 ("sqrt".into(), builtin_sqrt::INST),112 ("sin".into(), builtin_sin::INST),113 ("cos".into(), builtin_cos::INST),114 ("tan".into(), builtin_tan::INST),115 ("asin".into(), builtin_asin::INST),116 ("acos".into(), builtin_acos::INST),117 ("atan".into(), builtin_atan::INST),118 ("exp".into(), builtin_exp::INST),119 ("mantissa".into(), builtin_mantissa::INST),120 ("exponent".into(), builtin_exponent::INST),121 ("extVar".into(), builtin_ext_var::INST),122 ("native".into(), builtin_native::INST),123 ("filter".into(), builtin_filter::INST),124 ("map".into(), builtin_map::INST),125 ("flatMap".into(), builtin_flatmap::INST),126 ("foldl".into(), builtin_foldl::INST),127 ("foldr".into(), builtin_foldr::INST),128 ("sort".into(), builtin_sort::INST),129 ("format".into(), builtin_format::INST),130 ("range".into(), builtin_range::INST),131 ("char".into(), builtin_char::INST),132 ("encodeUTF8".into(), builtin_encode_utf8::INST),133 ("decodeUTF8".into(), builtin_decode_utf8::INST),134 ("md5".into(), builtin_md5::INST),135 ("base64".into(), builtin_base64::INST),136 ("base64DecodeBytes".into(), builtin_base64_decode_bytes::INST),137 ("base64Decode".into(), builtin_base64_decode::INST),138 ("trace".into(), builtin_trace::INST),139 ("join".into(), builtin_join::INST),140 ("escapeStringJson".into(), builtin_escape_string_json::INST),141 ("manifestJsonEx".into(), builtin_manifest_json_ex::INST),142 ("manifestYamlDoc".into(), builtin_manifest_yaml_doc::INST),143 ("reverse".into(), builtin_reverse::INST),144 ("strReplace".into(), builtin_str_replace::INST),145 ("splitLimit".into(), builtin_splitlimit::INST),146 ("parseJson".into(), builtin_parse_json::INST),147 ("parseYaml".into(), builtin_parse_yaml::INST),148 ("asciiUpper".into(), builtin_ascii_upper::INST),149 ("asciiLower".into(), builtin_ascii_lower::INST),150 ("member".into(), builtin_member::INST),151 ("count".into(), builtin_count::INST),152 ("any".into(), builtin_any::INST),153 ("all".into(), builtin_all::INST),154 ].iter().cloned().collect()155 };156}157158#[jrsonnet_macros::builtin]159fn builtin_length(x: Either![IStr, ArrValue, ObjValue, FuncVal]) -> Result<usize> {160 use Either4::*;161 Ok(match x {162 A(x) => x.chars().count(),163 B(x) => x.len(),164 C(x) => x.len(),165 D(f) => f.params_len(),166 })167}168169#[jrsonnet_macros::builtin]170fn builtin_type(x: Any) -> Result<IStr> {171 Ok(x.0.value_type().name().into())172}173174#[jrsonnet_macros::builtin]175fn builtin_make_array(s: State, sz: usize, func: FuncVal) -> Result<VecVal> {176 let mut out = Vec::with_capacity(sz);177 for i in 0..sz {178 out.push(func.evaluate_simple(s.clone(), &(i as f64,))?);179 }180 Ok(VecVal(Cc::new(out)))181}182183#[jrsonnet_macros::builtin]184const fn builtin_codepoint(str: char) -> Result<u32> {185 Ok(str as u32)186}187188#[jrsonnet_macros::builtin]189fn builtin_object_fields_ex(190 obj: ObjValue,191 inc_hidden: bool,192 #[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,193) -> Result<VecVal> {194 #[cfg(feature = "exp-preserve-order")]195 let preserve_order = preserve_order.unwrap_or(false);196 let out = obj.fields_ex(197 inc_hidden,198 #[cfg(feature = "exp-preserve-order")]199 preserve_order,200 );201 Ok(VecVal(Cc::new(202 out.into_iter().map(Val::Str).collect::<Vec<_>>(),203 )))204}205206#[jrsonnet_macros::builtin]207fn builtin_object_has_ex(obj: ObjValue, f: IStr, inc_hidden: bool) -> Result<bool> {208 Ok(obj.has_field_ex(f, inc_hidden))209}210211#[jrsonnet_macros::builtin]212fn builtin_parse_json(st: State, s: IStr) -> Result<Any> {213 use serde_json::Value;214 let value: Value = serde_json::from_str(&s)215 .map_err(|e| RuntimeError(format!("failed to parse json: {}", e).into()))?;216 Ok(Any(Value::into_untyped(value, st)?))217}218219#[jrsonnet_macros::builtin]220fn builtin_parse_yaml(st: State, s: IStr) -> Result<Any> {221 use serde_json::Value;222 let value = serde_yaml::Deserializer::from_str_with_quirks(223 &s,224 DeserializingQuirks { old_octals: true },225 );226 let mut out = vec![];227 for item in value {228 let value = Value::deserialize(item)229 .map_err(|e| RuntimeError(format!("failed to parse yaml: {}", e).into()))?;230 let val = Value::into_untyped(value, st.clone())?;231 out.push(val);232 }233 Ok(Any(if out.is_empty() {234 Val::Null235 } else if out.len() == 1 {236 out.into_iter().next().unwrap()237 } else {238 Val::Arr(out.into())239 }))240}241242#[jrsonnet_macros::builtin]243fn builtin_slice(244 indexable: IndexableVal,245 index: Option<BoundedUsize<0, { i32::MAX as usize }>>,246 end: Option<BoundedUsize<0, { i32::MAX as usize }>>,247 step: Option<BoundedUsize<1, { i32::MAX as usize }>>,248) -> Result<Any> {249 std_slice(indexable, index, end, step).map(Any)250}251252#[jrsonnet_macros::builtin]253fn builtin_substr(str: IStr, from: usize, len: usize) -> Result<String> {254 Ok(str.chars().skip(from as usize).take(len as usize).collect())255}256257#[jrsonnet_macros::builtin]258fn builtin_primitive_equals(a: Any, b: Any) -> Result<bool> {259 primitive_equals(&a.0, &b.0)260}261262#[jrsonnet_macros::builtin]263fn builtin_equals(s: State, a: Any, b: Any) -> Result<bool> {264 equals(s, &a.0, &b.0)265}266267#[jrsonnet_macros::builtin]268fn builtin_modulo(a: f64, b: f64) -> Result<f64> {269 Ok(a % b)270}271272#[jrsonnet_macros::builtin]273fn builtin_mod(s: State, a: Either![f64, IStr], b: Any) -> Result<Any> {274 use Either2::*;275 Ok(Any(evaluate_mod_op(276 s,277 &match a {278 A(v) => Val::Num(v),279 B(s) => Val::Str(s),280 },281 &b.0,282 )?))283}284285#[jrsonnet_macros::builtin]286fn builtin_floor(x: f64) -> Result<f64> {287 Ok(x.floor())288}289290#[jrsonnet_macros::builtin]291fn builtin_ceil(x: f64) -> Result<f64> {292 Ok(x.ceil())293}294295#[jrsonnet_macros::builtin]296fn builtin_log(n: f64) -> Result<f64> {297 Ok(n.ln())298}299300#[jrsonnet_macros::builtin]301fn builtin_pow(x: f64, n: f64) -> Result<f64> {302 Ok(x.powf(n))303}304305#[jrsonnet_macros::builtin]306fn builtin_sqrt(x: PositiveF64) -> Result<f64> {307 Ok(x.0.sqrt())308}309310#[jrsonnet_macros::builtin]311fn builtin_sin(x: f64) -> Result<f64> {312 Ok(x.sin())313}314315#[jrsonnet_macros::builtin]316fn builtin_cos(x: f64) -> Result<f64> {317 Ok(x.cos())318}319320#[jrsonnet_macros::builtin]321fn builtin_tan(x: f64) -> Result<f64> {322 Ok(x.tan())323}324325#[jrsonnet_macros::builtin]326fn builtin_asin(x: f64) -> Result<f64> {327 Ok(x.asin())328}329330#[jrsonnet_macros::builtin]331fn builtin_acos(x: f64) -> Result<f64> {332 Ok(x.acos())333}334335#[jrsonnet_macros::builtin]336fn builtin_atan(x: f64) -> Result<f64> {337 Ok(x.atan())338}339340#[jrsonnet_macros::builtin]341fn builtin_exp(x: f64) -> Result<f64> {342 Ok(x.exp())343}344345fn frexp(s: f64) -> (f64, i16) {346 if 0.0 == s {347 (s, 0)348 } else {349 let lg = s.abs().log2();350 let x = (lg - lg.floor() - 1.0).exp2();351 let exp = lg.floor() + 1.0;352 (s.signum() * x, exp as i16)353 }354}355356#[jrsonnet_macros::builtin]357fn builtin_mantissa(x: f64) -> Result<f64> {358 Ok(frexp(x).0)359}360361#[jrsonnet_macros::builtin]362fn builtin_exponent(x: f64) -> Result<i16> {363 Ok(frexp(x).1)364}365366#[jrsonnet_macros::builtin]367fn builtin_ext_var(s: State, x: IStr) -> Result<Any> {368 let ctx = s.create_default_context();369 Ok(Any(s370 .clone()371 .settings()372 .ext_vars373 .get(&x)374 .cloned()375 .ok_or(UndefinedExternalVariable(x))?376 .evaluate_arg(s.clone(), ctx, true)?377 .evaluate(s)?))378}379380#[jrsonnet_macros::builtin]381fn builtin_native(s: State, name: IStr) -> Result<Any> {382 Ok(Any(s383 .settings()384 .ext_natives385 .get(&name)386 .cloned()387 .map_or(Val::Null, |v| {388 Val::Func(FuncVal::Builtin(v.clone()))389 })))390}391392#[jrsonnet_macros::builtin]393fn builtin_filter(s: State, func: FuncVal, arr: ArrValue) -> Result<ArrValue> {394 arr.filter(s.clone(), |val| {395 bool::from_untyped(396 func.evaluate_simple(s.clone(), &(Any(val.clone()),))?,397 s.clone(),398 )399 })400}401402#[jrsonnet_macros::builtin]403fn builtin_map(s: State, func: FuncVal, arr: ArrValue) -> Result<ArrValue> {404 arr.map(s.clone(), |val| {405 func.evaluate_simple(s.clone(), &(Any(val),))406 })407}408409#[jrsonnet_macros::builtin]410fn builtin_flatmap(s: State, func: FuncVal, arr: IndexableVal) -> Result<IndexableVal> {411 match arr {412 IndexableVal::Str(str) => {413 let mut out = String::new();414 for c in str.chars() {415 match func.evaluate_simple(s.clone(), &(c.to_string(),))? {416 Val::Str(o) => out.push_str(&o),417 Val::Null => continue,418 _ => throw!(RuntimeError(419 "in std.join all items should be strings".into()420 )),421 };422 }423 Ok(IndexableVal::Str(out.into()))424 }425 IndexableVal::Arr(a) => {426 let mut out = Vec::new();427 for el in a.iter(s.clone()) {428 let el = el?;429 match func.evaluate_simple(s.clone(), &(Any(el),))? {430 Val::Arr(o) => {431 for oe in o.iter(s.clone()) {432 out.push(oe?);433 }434 }435 Val::Null => continue,436 _ => throw!(RuntimeError(437 "in std.join all items should be arrays".into()438 )),439 };440 }441 Ok(IndexableVal::Arr(out.into()))442 }443 }444}445446#[jrsonnet_macros::builtin]447fn builtin_foldl(s: State, func: FuncVal, arr: ArrValue, init: Any) -> Result<Any> {448 let mut acc = init.0;449 for i in arr.iter(s.clone()) {450 acc = func.evaluate_simple(s.clone(), &(Any(acc), Any(i?)))?;451 }452 Ok(Any(acc))453}454455#[jrsonnet_macros::builtin]456fn builtin_foldr(s: State, func: FuncVal, arr: ArrValue, init: Any) -> Result<Any> {457 let mut acc = init.0;458 for i in arr.iter(s.clone()).rev() {459 acc = func.evaluate_simple(s.clone(), &(Any(i?), Any(acc)))?;460 }461 Ok(Any(acc))462}463464#[jrsonnet_macros::builtin]465#[allow(non_snake_case)]466fn builtin_sort(s: State, arr: ArrValue, keyF: Option<FuncVal>) -> Result<ArrValue> {467 if arr.len() <= 1 {468 return Ok(arr);469 }470 Ok(ArrValue::Eager(sort::sort(471 s.clone(),472 arr.evaluated(s)?,473 keyF.unwrap_or_else(FuncVal::identity),474 )?))475}476477#[jrsonnet_macros::builtin]478fn builtin_format(s: State, str: IStr, vals: Any) -> Result<String> {479 std_format(s, str, vals.0)480}481482#[jrsonnet_macros::builtin]483fn builtin_range(from: i32, to: i32) -> Result<ArrValue> {484 if to < from {485 return Ok(ArrValue::new_eager());486 }487 Ok(ArrValue::new_range(from, to))488}489490#[jrsonnet_macros::builtin]491fn builtin_char(n: u32) -> Result<char> {492 Ok(std::char::from_u32(n as u32).ok_or(InvalidUnicodeCodepointGot(n as u32))?)493}494495#[jrsonnet_macros::builtin]496fn builtin_encode_utf8(str: IStr) -> Result<IBytes> {497 Ok(str.cast_bytes())498}499500#[jrsonnet_macros::builtin]501fn builtin_decode_utf8(arr: IBytes) -> Result<IStr> {502 Ok(arr503 .cast_str()504 .ok_or_else(|| RuntimeError("bad utf8".into()))?)505}506507#[jrsonnet_macros::builtin]508fn builtin_md5(str: IStr) -> Result<String> {509 Ok(format!("{:x}", md5::compute(&str.as_bytes())))510}511512#[jrsonnet_macros::builtin]513fn builtin_trace(s: State, loc: CallLocation, str: IStr, rest: Any) -> Result<Any> {514 eprint!("TRACE:");515 if let Some(loc) = loc.0 {516 let locs = s.map_source_locations(loc.0.clone(), &[loc.1]);517 eprint!(" {}:{}", loc.0.short_display(), locs[0].line);518 }519 eprintln!(" {}", str);520 Ok(rest) as Result<Any>521}522523#[jrsonnet_macros::builtin]524fn builtin_base64(input: Either![IBytes, IStr]) -> Result<String> {525 use Either2::*;526 Ok(match input {527 A(a) => base64::encode(a.as_slice()),528 B(l) => base64::encode(l.bytes().collect::<Vec<_>>()),529 })530}531532#[jrsonnet_macros::builtin]533fn builtin_base64_decode_bytes(input: IStr) -> Result<IBytes> {534 Ok(base64::decode(&input.as_bytes())535 .map_err(|_| RuntimeError("bad base64".into()))?536 .as_slice()537 .into())538}539540#[jrsonnet_macros::builtin]541fn builtin_base64_decode(input: IStr) -> Result<String> {542 let bytes = base64::decode(&input.as_bytes()).map_err(|_| RuntimeError("bad base64".into()))?;543 Ok(String::from_utf8(bytes).map_err(|_| RuntimeError("bad utf8".into()))?)544}545546#[jrsonnet_macros::builtin]547fn builtin_join(s: State, sep: IndexableVal, arr: ArrValue) -> Result<IndexableVal> {548 Ok(match sep {549 IndexableVal::Arr(joiner_items) => {550 let mut out = Vec::new();551552 let mut first = true;553 for item in arr.iter(s.clone()) {554 let item = item?.clone();555 if let Val::Arr(items) = item {556 if !first {557 out.reserve(joiner_items.len());558 // TODO: extend559 for item in joiner_items.iter(s.clone()) {560 out.push(item?);561 }562 }563 first = false;564 out.reserve(items.len());565 for item in items.iter(s.clone()) {566 out.push(item?);567 }568 } else if matches!(item, Val::Null) {569 continue;570 } else {571 throw!(RuntimeError(572 "in std.join all items should be arrays".into()573 ));574 }575 }576577 IndexableVal::Arr(out.into())578 }579 IndexableVal::Str(sep) => {580 let mut out = String::new();581582 let mut first = true;583 for item in arr.iter(s) {584 let item = item?.clone();585 if let Val::Str(item) = item {586 if !first {587 out += &sep;588 }589 first = false;590 out += &item;591 } else if matches!(item, Val::Null) {592 continue;593 } else {594 throw!(RuntimeError(595 "in std.join all items should be strings".into()596 ));597 }598 }599600 IndexableVal::Str(out.into())601 }602 })603}604605#[jrsonnet_macros::builtin]606fn builtin_escape_string_json(str_: IStr) -> Result<String> {607 Ok(escape_string_json(&str_))608}609610#[jrsonnet_macros::builtin]611fn builtin_manifest_json_ex(612 s: State,613 value: Any,614 indent: IStr,615 newline: Option<IStr>,616 key_val_sep: Option<IStr>,617 #[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,618) -> Result<String> {619 let newline = newline.as_deref().unwrap_or("\n");620 let key_val_sep = key_val_sep.as_deref().unwrap_or(": ");621 manifest_json_ex(622 s,623 &value.0,624 &ManifestJsonOptions {625 padding: &indent,626 mtype: ManifestType::Std,627 newline,628 key_val_sep,629 #[cfg(feature = "exp-preserve-order")]630 preserve_order: preserve_order.unwrap_or(false),631 },632 )633}634635#[jrsonnet_macros::builtin]636fn builtin_manifest_yaml_doc(637 s: State,638 value: Any,639 indent_array_in_object: Option<bool>,640 quote_keys: Option<bool>,641 #[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,642) -> Result<String> {643 manifest_yaml_ex(644 s,645 &value.0,646 &ManifestYamlOptions {647 padding: " ",648 arr_element_padding: if indent_array_in_object.unwrap_or(false) {649 " "650 } else {651 ""652 },653 quote_keys: quote_keys.unwrap_or(true),654 #[cfg(feature = "exp-preserve-order")]655 preserve_order: preserve_order.unwrap_or(false),656 },657 )658}659660#[jrsonnet_macros::builtin]661fn builtin_reverse(value: ArrValue) -> Result<ArrValue> {662 Ok(value.reversed())663}664665#[jrsonnet_macros::builtin]666fn builtin_str_replace(str: String, from: IStr, to: IStr) -> Result<String> {667 Ok(str.replace(&from as &str, &to as &str))668}669670#[jrsonnet_macros::builtin]671fn builtin_splitlimit(str: IStr, c: IStr, maxsplits: Either![usize, M1]) -> Result<VecVal> {672 use Either2::*;673 Ok(VecVal(Cc::new(match maxsplits {674 A(n) => str675 .splitn(n + 1, &c as &str)676 .map(|s| Val::Str(s.into()))677 .collect(),678 B(_) => str.split(&c as &str).map(|s| Val::Str(s.into())).collect(),679 })))680}681682#[jrsonnet_macros::builtin]683fn builtin_ascii_upper(str: IStr) -> Result<String> {684 Ok(str.to_ascii_uppercase())685}686687#[jrsonnet_macros::builtin]688fn builtin_ascii_lower(str: IStr) -> Result<String> {689 Ok(str.to_ascii_lowercase())690}691692#[jrsonnet_macros::builtin]693fn builtin_member(s: State, arr: IndexableVal, x: Any) -> Result<bool> {694 match arr {695 IndexableVal::Str(str) => {696 let x: IStr = IStr::from_untyped(x.0, s)?;697 Ok(!x.is_empty() && str.contains(&*x))698 }699 IndexableVal::Arr(a) => {700 for item in a.iter(s.clone()) {701 let item = item?;702 if equals(s.clone(), &item, &x.0)? {703 return Ok(true);704 }705 }706 Ok(false)707 }708 }709}710711#[jrsonnet_macros::builtin]712fn builtin_count(s: State, arr: Vec<Any>, v: Any) -> Result<usize> {713 let mut count = 0;714 for item in &arr {715 if equals(s.clone(), &item.0, &v.0)? {716 count += 1;717 }718 }719 Ok(count)720}721722#[jrsonnet_macros::builtin]723fn builtin_any(s: State, arr: ArrValue) -> Result<bool> {724 for v in arr.iter(s.clone()) {725 let v = bool::from_untyped(v?, s.clone())?;726 if v {727 return Ok(true);728 }729 }730 Ok(false)731}732733#[jrsonnet_macros::builtin]734fn builtin_all(s: State, arr: ArrValue) -> Result<bool> {735 for v in arr.iter(s.clone()) {736 let v = bool::from_untyped(v?, s.clone())?;737 if !v {738 return Ok(false);739 }740 }741 Ok(true)742}crates/jrsonnet-evaluator/src/trace/location.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/trace/location.rs
+++ b/crates/jrsonnet-evaluator/src/trace/location.rs
@@ -24,7 +24,7 @@
}
#[allow(clippy::module_name_repetitions)]
-pub fn offset_to_location(file: &str, offsets: &[usize]) -> Vec<CodeLocation> {
+pub fn offset_to_location(file: &str, offsets: &[u32]) -> Vec<CodeLocation> {
if offsets.is_empty() {
return vec![];
}
@@ -59,7 +59,7 @@
{
column += 1;
match offset_map.last() {
- Some(x) if x.0 == pos => {
+ Some(x) if x.0 == pos as u32 => {
let out_idx = x.1;
with_no_known_line_ending.push(out_idx);
out[out_idx].offset = pos;
@@ -79,7 +79,7 @@
}
this_line_offset = pos + 1;
- if pos == max_offset + 1 {
+ if pos == max_offset as usize + 1 {
break;
}
}
crates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -2,6 +2,7 @@
use std::path::{Path, PathBuf};
+use jrsonnet_parser::Source;
pub use location::*;
use crate::{error::Error, LocError, State};
@@ -56,7 +57,7 @@
) -> Result<(), std::fmt::Error> {
if start.line == end.line {
if start.column == end.column {
- write!(out, "{}:{}", start.line, end.column - 1)?;
+ write!(out, "{}:{}", start.line, end.column.saturating_sub(1))?;
} else {
write!(out, "{}:{}-{}", start.line, start.column - 1, end.column)?;
}
@@ -96,7 +97,10 @@
use std::fmt::Write;
writeln!(out)?;
- let mut n = self.resolver.resolve(path);
+ let mut n = match path.repr() {
+ Ok(r) => self.resolver.resolve(r),
+ Err(v) => v.to_string(),
+ };
let mut offset = error.location.offset;
let is_eof = if offset >= source_code.len() {
offset = source_code.len().saturating_sub(1);
@@ -104,7 +108,7 @@
} else {
false
};
- let mut location = offset_to_location(source_code, &[offset])
+ let mut location = offset_to_location(source_code, &[offset as u32])
.into_iter()
.next()
.unwrap();
@@ -125,9 +129,13 @@
use std::fmt::Write;
#[allow(clippy::option_if_let_else)]
if let Some(location) = location {
- let mut resolved_path = self.resolver.resolve(&location.0);
+ let mut resolved_path = match location.0.repr() {
+ Ok(r) => self.resolver.resolve(r),
+ Err(v) => v.to_string(),
+ };
// TODO: Process all trace elements first
- let location = s.map_source_locations(&location.0, &[location.1, location.2]);
+ let location =
+ s.map_source_locations(location.0.clone(), &[location.1, location.2]);
write!(resolved_path, ":").unwrap();
print_code_location(&mut resolved_path, &location[0], &location[1]).unwrap();
write!(resolved_path, ":").unwrap();
@@ -176,15 +184,16 @@
writeln!(out)?;
let desc = &item.desc;
if let Some(source) = &item.location {
- let start_end = s.map_source_locations(&source.0, &[source.1, source.2]);
+ let start_end = s.map_source_locations(source.0.clone(), &[source.1, source.2]);
+ let resolved_path = match source.0.repr() {
+ Ok(r) => r.display().to_string(),
+ Err(v) => v.to_string(),
+ };
write!(
out,
" at {} ({}:{}:{})",
- desc,
- source.0.to_str().unwrap(),
- start_end[0].line,
- start_end[0].column,
+ desc, resolved_path, start_end[0].line, start_end[0].column,
)?;
} else {
write!(out, " during {}", desc)?;
@@ -216,7 +225,7 @@
{
writeln!(out)?;
let offset = error.location.offset;
- let location = offset_to_location(source_code, &[offset])
+ let location = offset_to_location(source_code, &[offset as u32])
.into_iter()
.next()
.unwrap();
@@ -237,10 +246,10 @@
writeln!(out)?;
let desc = &item.desc;
if let Some(source) = &item.location {
- let start_end = s.map_source_locations(&source.0, &[source.1, source.2]);
+ let start_end = s.map_source_locations(source.0.clone(), &[source.1, source.2]);
self.print_snippet(
out,
- &s.get_source(&source.0).unwrap(),
+ &s.get_source(source.0.clone()).unwrap(),
&source.0,
&start_end[0],
&start_end[1],
@@ -259,7 +268,7 @@
&self,
out: &mut dyn std::fmt::Write,
source: &str,
- origin: &Path,
+ origin: &Source,
start: &CodeLocation,
end: &CodeLocation,
desc: &str,
@@ -275,7 +284,10 @@
.take(end.line_end_offset - end.line_start_offset)
.collect();
- let origin = self.resolver.resolve(origin);
+ let origin = match origin.repr() {
+ Ok(r) => self.resolver.resolve(r),
+ Err(v) => v.to_string(),
+ };
let snippet = Snippet {
opt: FormatOptions {
color: true,
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -1,7 +1,7 @@
-use std::{ops::Deref, rc::Rc};
+use std::ops::Deref;
use gcmodule::Cc;
-use jrsonnet_interner::IStr;
+use jrsonnet_interner::{IBytes, IStr};
pub use jrsonnet_macros::Typed;
use jrsonnet_types::{ComplexValType, ValType};
@@ -303,19 +303,17 @@
}
/// Specialization
-pub struct Bytes(pub Rc<[u8]>);
-
-impl Typed for Bytes {
+impl Typed for IBytes {
const TYPE: &'static ComplexValType =
&ComplexValType::ArrayRef(&ComplexValType::BoundedNumber(Some(0.0), Some(255.0)));
fn into_untyped(value: Self, _: State) -> Result<Val> {
- Ok(Val::Arr(ArrValue::Bytes(value.0)))
+ Ok(Val::Arr(ArrValue::Bytes(value)))
}
fn from_untyped(value: Val, s: State) -> Result<Self> {
if let Val::Arr(ArrValue::Bytes(bytes)) = value {
- return Ok(Self(bytes));
+ return Ok(bytes);
}
<Self as Typed>::TYPE.check(s.clone(), &value)?;
match value {
@@ -325,7 +323,7 @@
let r = e?;
out.push(u8::from_untyped(r, s.clone())?);
}
- Ok(Self(out.into()))
+ Ok(out.as_slice().into())
}
_ => unreachable!(),
}
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -1,7 +1,7 @@
use std::{cell::RefCell, fmt::Debug, rc::Rc};
use gcmodule::{Cc, Trace};
-use jrsonnet_interner::IStr;
+use jrsonnet_interner::{IBytes, IStr};
use jrsonnet_types::ValType;
use crate::{
@@ -31,6 +31,7 @@
#[allow(clippy::module_name_repetitions)]
#[derive(Clone, Trace)]
pub struct Thunk<T>(Cc<RefCell<ThunkInner<T>>>);
+
impl<T> Thunk<T>
where
T: Clone + Trace,
@@ -186,7 +187,7 @@
#[derive(Debug, Clone, Trace)]
#[force_tracking]
pub enum ArrValue {
- Bytes(#[skip_trace] Rc<[u8]>),
+ Bytes(#[skip_trace] IBytes),
Lazy(Cc<Vec<Thunk<Val>>>),
Eager(Cc<Vec<Val>>),
Extended(Box<(Self, Self)>),
@@ -194,6 +195,10 @@
Slice(Box<Slice>),
Reversed(Box<Self>),
}
+
+#[cfg(target_pointer_width = "64")]
+static_assertions::assert_eq_size!(ArrValue, [u8; 16]);
+
impl ArrValue {
pub fn new_eager() -> Self {
Self::Eager(Cc::new(Vec::new()))
@@ -465,6 +470,9 @@
Func(FuncVal),
}
+#[cfg(target_pointer_width = "64")]
+static_assertions::assert_eq_size!(Val, [u8; 32]);
+
impl Val {
pub const fn as_bool(&self) -> Option<bool> {
match self {
crates/jrsonnet-evaluator/tests/as_native.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/as_native.rs
+++ b/crates/jrsonnet-evaluator/tests/as_native.rs
@@ -1,5 +1,3 @@
-use std::path::PathBuf;
-
use jrsonnet_evaluator::{error::Result, State};
mod common;
@@ -9,7 +7,7 @@
let s = State::default();
s.with_stdlib();
- let val = s.evaluate_snippet_raw(PathBuf::new().into(), r#"function(a, b) a + b"#.into())?;
+ let val = s.evaluate_snippet("snip".to_owned(), r#"function(a, b) a + b"#.into())?;
let func = val.as_func().expect("this is function");
let native = func.into_native::<((u32, u32), u32)>();
crates/jrsonnet-evaluator/tests/builtin.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/builtin.rs
+++ b/crates/jrsonnet-evaluator/tests/builtin.rs
@@ -1,7 +1,5 @@
mod common;
-use std::path::PathBuf;
-
use gcmodule::Cc;
use jrsonnet_evaluator::{
error::Result,
@@ -27,7 +25,7 @@
CallLocation::native(),
&(),
)?,
- s.clone(),
+ s,
)?;
ensure_eq!(v, 1);
@@ -48,8 +46,8 @@
Val::Func(FuncVal::StaticBuiltin(native_add::INST)),
);
- let v = s.evaluate_snippet_raw(
- PathBuf::new().into(),
+ let v = s.evaluate_snippet(
+ "snip".to_owned(),
"
assert nativeAdd(1, 2) == 3;
assert nativeAdd(100, 200) == 300;
@@ -57,7 +55,7 @@
"
.into(),
)?;
- ensure_val_eq!(s.clone(), v, Val::Null);
+ ensure_val_eq!(s, v, Val::Null);
Ok(())
}
@@ -82,8 +80,8 @@
Val::Func(FuncVal::StaticBuiltin(curry_add::INST)),
);
- let v = s.evaluate_snippet_raw(
- PathBuf::new().into(),
+ let v = s.evaluate_snippet(
+ "snip".to_owned(),
"
local a = curryAdd(1);
local b = curryAdd(4);
@@ -97,6 +95,6 @@
"
.into(),
)?;
- ensure_val_eq!(s.clone(), v, Val::Null);
+ ensure_val_eq!(s, v, Val::Null);
Ok(())
}
crates/jrsonnet-evaluator/tests/golden.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/golden.rs
+++ b/crates/jrsonnet-evaluator/tests/golden.rs
@@ -20,7 +20,7 @@
common::with_test(&s);
s.set_import_resolver(Box::new(FileImportResolver::default()));
- let v = match s.evaluate_file_raw(file) {
+ let v = match s.import(file.to_owned()) {
Ok(v) => v,
Err(e) => return s.stringify_err(&e),
};
crates/jrsonnet-evaluator/tests/golden/issue23.jsonnet.goldendiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/golden/issue23.jsonnet.golden
+++ b/crates/jrsonnet-evaluator/tests/golden/issue23.jsonnet.golden
@@ -1,202 +1,2 @@
-stack overflow, try to reduce recursion, or set --max-stack to bigger value
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
\ No newline at end of file
+infinite recursion detected
+ issue23.jsonnet:1:1-26: import "/home/lach/build/jrsonnet/crates/jrsonnet-evaluator/tests/golden/issue23.jsonnet"
\ No newline at end of file
crates/jrsonnet-evaluator/tests/golden/missing_binding.jsonnet.goldendiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/golden/missing_binding.jsonnet.golden
+++ b/crates/jrsonnet-evaluator/tests/golden/missing_binding.jsonnet.golden
@@ -1,2 +1,3 @@
-variable is not defined: a
+runtime error: variable is not defined: a
+There is variable(s) with similar names present: std, test
missing_binding.jsonnet:1:1-3: variable <a> access
\ No newline at end of file
crates/jrsonnet-evaluator/tests/sanity.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/sanity.rs
+++ b/crates/jrsonnet-evaluator/tests/sanity.rs
@@ -1,5 +1,3 @@
-use std::path::PathBuf;
-
use jrsonnet_evaluator::{error::Result, throw_runtime, State, Val};
mod common;
@@ -9,10 +7,10 @@
let s = State::default();
s.with_stdlib();
- let v = s.evaluate_snippet_raw(PathBuf::new().into(), "assert 1 == 1: 'fail'; null".into())?;
- ensure_val_eq!(s.clone(), v, Val::Null);
- let v = s.evaluate_snippet_raw(PathBuf::new().into(), "std.assertEqual(1, 1)".into())?;
- ensure_val_eq!(s.clone(), v, Val::Bool(true));
+ let v = s.evaluate_snippet("snip".to_owned(), "assert 1 == 1: 'fail'; null".into())?;
+ ensure_val_eq!(s, v, Val::Null);
+ let v = s.evaluate_snippet("snip".to_owned(), "std.assertEqual(1, 1)".into())?;
+ ensure_val_eq!(s, v, Val::Bool(true));
Ok(())
}
@@ -23,9 +21,7 @@
s.with_stdlib();
{
- let e = match s
- .evaluate_snippet_raw(PathBuf::new().into(), "assert 1 == 2: 'fail'; null".into())
- {
+ let e = match s.evaluate_snippet("snip".to_owned(), "assert 1 == 2: 'fail'; null".into()) {
Ok(_) => throw_runtime!("assertion should fail"),
Err(e) => e,
};
@@ -33,8 +29,7 @@
ensure!(e.starts_with("assert failed: fail\n"));
}
{
- let e = match s.evaluate_snippet_raw(PathBuf::new().into(), "std.assertEqual(1, 2)".into())
- {
+ let e = match s.evaluate_snippet("snip".to_owned(), "std.assertEqual(1, 2)".into()) {
Ok(_) => throw_runtime!("assertion should fail"),
Err(e) => e,
};
crates/jrsonnet-evaluator/tests/suite.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/suite.rs
+++ b/crates/jrsonnet-evaluator/tests/suite.rs
@@ -20,7 +20,7 @@
common::with_test(&s);
s.set_import_resolver(Box::new(FileImportResolver::default()));
- match s.evaluate_file_raw(file) {
+ match s.import(file.to_owned()) {
Ok(Val::Bool(true)) => {}
Ok(Val::Bool(false)) => panic!("test {} returned false", file.display()),
Ok(_) => panic!("test {} returned wrong type as result", file.display()),
crates/jrsonnet-evaluator/tests/typed_obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/typed_obj.rs
+++ b/crates/jrsonnet-evaluator/tests/typed_obj.rs
@@ -1,6 +1,6 @@
mod common;
-use std::{fmt::Debug, path::PathBuf};
+use std::fmt::Debug;
use jrsonnet_evaluator::{error::Result, typed::Typed, State};
@@ -25,11 +25,11 @@
let s = State::default();
s.with_stdlib();
let a = A::from_untyped(
- s.evaluate_snippet_raw(PathBuf::new().into(), "{a: 1, b: 2}".into())?,
+ s.evaluate_snippet("snip".to_owned(), "{a: 1, b: 2}".into())?,
s.clone(),
)?;
ensure_eq!(a, A { a: 1, b: 2 });
- test_roundtrip(a.clone(), s.clone())?;
+ test_roundtrip(a, s)?;
Ok(())
}
@@ -45,7 +45,7 @@
let s = State::default();
s.with_stdlib();
let b = B::from_untyped(
- s.evaluate_snippet_raw(PathBuf::new().into(), "{a: 1, c: 2}".into())?,
+ s.evaluate_snippet("snip".to_owned(), "{a: 1, c: 2}".into())?,
s.clone(),
)?;
ensure_eq!(b, B { a: 1, b: 2 });
@@ -53,7 +53,7 @@
&B::into_untyped(b.clone(), s.clone())?.to_string(s.clone())? as &str,
r#"{"a": 1, "c": 2}"#,
);
- test_roundtrip(b.clone(), s.clone())?;
+ test_roundtrip(b, s)?;
Ok(())
}
@@ -77,8 +77,8 @@
let s = State::default();
s.with_stdlib();
let obj = Object::from_untyped(
- s.evaluate_snippet_raw(
- PathBuf::new().into(),
+ s.evaluate_snippet(
+ "snip".to_owned(),
"{apiVersion: 'ver', kind: 'kind', b: 2}".into(),
)?,
s.clone(),
@@ -97,7 +97,7 @@
&Object::into_untyped(obj.clone(), s.clone())?.to_string(s.clone())? as &str,
r#"{"apiVersion": "ver", "b": 2, "kind": "kind"}"#,
);
- test_roundtrip(obj.clone(), s.clone())?;
+ test_roundtrip(obj, s)?;
Ok(())
}
@@ -112,7 +112,7 @@
let s = State::default();
s.with_stdlib();
let c = C::from_untyped(
- s.evaluate_snippet_raw(PathBuf::new().into(), "{a: 1, b: 2}".into())?,
+ s.evaluate_snippet("snip".to_owned(), "{a: 1, b: 2}".into())?,
s.clone(),
)?;
ensure_eq!(c, C { a: Some(1), b: 2 });
@@ -120,7 +120,7 @@
&C::into_untyped(c.clone(), s.clone())?.to_string(s.clone())? as &str,
r#"{"a": 1, "b": 2}"#,
);
- test_roundtrip(c.clone(), s.clone())?;
+ test_roundtrip(c, s)?;
Ok(())
}
@@ -129,7 +129,7 @@
let s = State::default();
s.with_stdlib();
let c = C::from_untyped(
- s.evaluate_snippet_raw(PathBuf::new().into(), "{b: 2}".into())?,
+ s.evaluate_snippet("snip".to_owned(), "{b: 2}".into())?,
s.clone(),
)?;
ensure_eq!(c, C { a: None, b: 2 });
@@ -137,7 +137,7 @@
&C::into_untyped(c.clone(), s.clone())?.to_string(s.clone())? as &str,
r#"{"b": 2}"#,
);
- test_roundtrip(c.clone(), s.clone())?;
+ test_roundtrip(c, s)?;
Ok(())
}
@@ -158,7 +158,7 @@
let s = State::default();
s.with_stdlib();
let d = D::from_untyped(
- s.evaluate_snippet_raw(PathBuf::new().into(), "{b: 2, v:1}".into())?,
+ s.evaluate_snippet("snip".to_owned(), "{b: 2, v:1}".into())?,
s.clone(),
)?;
ensure_eq!(
@@ -172,7 +172,7 @@
&D::into_untyped(d.clone(), s.clone())?.to_string(s.clone())? as &str,
r#"{"b": 2, "v": 1}"#,
);
- test_roundtrip(d.clone(), s.clone())?;
+ test_roundtrip(d, s)?;
Ok(())
}
@@ -181,7 +181,7 @@
let s = State::default();
s.with_stdlib();
let d = D::from_untyped(
- s.evaluate_snippet_raw(PathBuf::new().into(), "{b: 2, v: '1'}".into())?,
+ s.evaluate_snippet("snip".to_owned(), "{b: 2, v: '1'}".into())?,
s.clone(),
)?;
ensure_eq!(d, D { e: None, b: 2 });
@@ -189,6 +189,6 @@
&D::into_untyped(d.clone(), s.clone())?.to_string(s.clone())? as &str,
r#"{"b": 2}"#,
);
- test_roundtrip(d.clone(), s.clone())?;
+ test_roundtrip(d, s)?;
Ok(())
}
crates/jrsonnet-interner/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-interner/src/lib.rs
+++ b/crates/jrsonnet-interner/src/lib.rs
@@ -127,6 +127,11 @@
unsafe { Inner::assume_utf8(&self.0) };
IStr(self.0.clone())
}
+
+ #[must_use]
+ pub fn as_slice(&self) -> &[u8] {
+ self.0.as_slice()
+ }
}
impl Deref for IBytes {
crates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/lib.rs
+++ b/crates/jrsonnet-parser/src/lib.rs
@@ -362,7 +362,7 @@
#[cfg(test)]
pub mod tests {
- use std::path::PathBuf;
+ use std::borrow::Cow;
use BinaryOpType::*;
@@ -374,7 +374,7 @@
parse(
$s,
&ParserSettings {
- file_name: Source::new(PathBuf::from("test.jsonnet")).unwrap(),
+ file_name: Source::new_virtual(Cow::Borrowed("<test>")),
},
)
.unwrap()
@@ -385,11 +385,7 @@
($expr:expr, $from:expr, $to:expr$(,)?) => {
LocExpr(
std::rc::Rc::new($expr),
- ExprLocation(
- Source::new(PathBuf::from("test.jsonnet")).unwrap(),
- $from,
- $to,
- ),
+ ExprLocation(Source::new_virtual(Cow::Borrowed("<test>")), $from, $to),
)
};
}
@@ -727,12 +723,10 @@
fn add_location_info_to_all_sub_expressions() {
use Expr::*;
- let file_name = Source::new(PathBuf::from("test.jsonnet")).unwrap();
+ let file_name = Source::new_virtual(Cow::Borrowed("<test>"));
let expr = parse(
"{} { local x = 1, x: x } + {}",
- &ParserSettings {
- file_name: file_name.clone(),
- },
+ &ParserSettings { file_name },
)
.unwrap();
assert_eq!(