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.rsdiffbeforeafterboth1#![warn(clippy::all, clippy::nursery, clippy::pedantic)]2#![allow(3 macro_expanded_macro_exports_accessed_by_absolute_paths,4 clippy::ptr_arg,5 // Too verbose6 clippy::must_use_candidate,7 // A lot of functions pass around errors thrown by code8 clippy::missing_errors_doc,9 // A lot of pointers have interior Rc10 clippy::needless_pass_by_value,11 // Its fine12 clippy::wildcard_imports,13 clippy::enum_glob_use,14 clippy::module_name_repetitions,15 // TODO: fix individual issues, however this works as intended almost everywhere16 clippy::cast_precision_loss,17 clippy::cast_possible_wrap,18 clippy::cast_possible_truncation,19 clippy::cast_sign_loss,20)]2122// For jrsonnet-macros23extern crate self as jrsonnet_evaluator;2425mod ctx;26mod dynamic;27pub mod error;28mod evaluate;29pub mod function;30pub mod gc;31mod import;32mod integrations;33mod map;34mod obj;35mod stdlib;36pub mod trace;37pub mod typed;38pub mod val;3940use std::{41 cell::{Ref, RefCell, RefMut},42 collections::HashMap,43 fmt::{self, Debug},44 path::{Path, PathBuf},45 rc::Rc,46};4748pub use ctx::*;49pub use dynamic::*;50use error::{Error::*, LocError, Result, StackTraceElement};51pub use evaluate::*;52use function::{builtin::Builtin, CallLocation, TlaArg};53use gc::{GcHashMap, TraceBox};54use gcmodule::{Cc, Trace, Weak};55pub use import::*;56pub use jrsonnet_interner::IStr;57pub use jrsonnet_parser as parser;58use jrsonnet_parser::*;59pub use obj::*;60use trace::{location_to_offset, offset_to_location, CodeLocation, CompactFormat, TraceFormat};61pub use val::{ManifestFormat, Thunk, Val};6263pub trait Unbound: Trace {64 type Bound;65 fn bind(&self, s: State, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Self::Bound>;66}6768#[derive(Clone, Trace)]69pub enum LazyBinding {70 Bindable(Cc<TraceBox<dyn Unbound<Bound = Thunk<Val>>>>),71 Bound(Thunk<Val>),72}7374impl Debug for LazyBinding {75 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {76 write!(f, "LazyBinding")77 }78}79impl LazyBinding {80 pub fn evaluate(81 &self,82 s: State,83 sup: Option<ObjValue>,84 this: Option<ObjValue>,85 ) -> Result<Thunk<Val>> {86 match self {87 Self::Bindable(v) => v.bind(s, sup, this),88 Self::Bound(v) => Ok(v.clone()),89 }90 }91}9293pub struct EvaluationSettings {94 /// Limits recursion by limiting the number of stack frames95 pub max_stack: usize,96 /// Limits amount of stack trace items preserved97 pub max_trace: usize,98 /// Used for s`td.extVar`99 pub ext_vars: HashMap<IStr, Val>,100 /// Used for ext.native101 pub ext_natives: HashMap<IStr, Cc<TraceBox<dyn Builtin>>>,102 /// TLA vars103 pub tla_vars: HashMap<IStr, TlaArg>,104 /// Global variables are inserted in default context105 pub globals: HashMap<IStr, Val>,106 /// Used to resolve file locations/contents107 pub import_resolver: Box<dyn ImportResolver>,108 /// Used in manifestification functions109 pub manifest_format: ManifestFormat,110 /// Used for bindings111 pub trace_format: Box<dyn TraceFormat>,112}113impl Default for EvaluationSettings {114 fn default() -> Self {115 Self {116 max_stack: 200,117 max_trace: 20,118 globals: HashMap::default(),119 ext_vars: HashMap::default(),120 ext_natives: HashMap::default(),121 tla_vars: HashMap::default(),122 import_resolver: Box::new(DummyImportResolver),123 manifest_format: ManifestFormat::Json {124 padding: 4,125 #[cfg(feature = "exp-preserve-order")]126 preserve_order: false,127 },128 trace_format: Box::new(CompactFormat {129 padding: 4,130 resolver: trace::PathResolver::Absolute,131 }),132 }133 }134}135136#[derive(Default)]137struct EvaluationData {138 /// Used for stack overflow detection, stacktrace is populated on unwind139 stack_depth: usize,140 /// Updated every time stack entry is popt141 stack_generation: usize,142143 breakpoints: Breakpoints,144 /// Contains file source codes and evaluation results for imports and pretty-printed stacktraces145 files: GcHashMap<Rc<Path>, FileData>,146 str_files: GcHashMap<Rc<Path>, IStr>,147 bin_files: GcHashMap<Rc<Path>, Rc<[u8]>>,148}149150pub struct FileData {151 source_code: IStr,152 parsed: LocExpr,153 evaluated: Option<Val>,154}155156#[allow(clippy::type_complexity)]157pub struct Breakpoint {158 loc: ExprLocation,159 collected: RefCell<HashMap<usize, (usize, Vec<Result<Val>>)>>,160}161#[derive(Default)]162struct Breakpoints(Vec<Rc<Breakpoint>>);163impl Breakpoints {164 fn insert(165 &self,166 stack_depth: usize,167 stack_generation: usize,168 loc: &ExprLocation,169 result: Result<Val>,170 ) -> Result<Val> {171 if self.0.is_empty() {172 return result;173 }174 for item in &self.0 {175 if item.loc.belongs_to(loc) {176 let mut collected = item.collected.borrow_mut();177 let (depth, vals) = collected.entry(stack_generation).or_default();178 if stack_depth > *depth {179 vals.clear();180 }181 vals.push(result.clone());182 }183 }184 result185 }186}187188#[derive(Default)]189pub struct EvaluationStateInternals {190 /// Internal state191 data: RefCell<EvaluationData>,192 /// Settings, safe to change at runtime193 settings: RefCell<EvaluationSettings>,194}195196/// Maintains stack trace and import resolution197#[derive(Default, Clone)]198pub struct State(Rc<EvaluationStateInternals>);199200impl State {201 /// Parses and adds file as loaded202 pub fn add_file(&self, path: Rc<Path>, source_code: IStr) -> Result<LocExpr> {203 let parsed = parse(204 &source_code,205 &ParserSettings {206 file_name: path.clone(),207 },208 )209 .map_err(|error| ImportSyntaxError {210 error: Box::new(error),211 path: path.clone(),212 source_code: source_code.clone(),213 })?;214 self.add_parsed_file(path, source_code, parsed.clone())?;215216 Ok(parsed)217 }218219 pub fn reset_evaluation_state(&self, name: &Path) {220 self.data_mut()221 .files222 .get_mut(name)223 .expect("file not found")224 .evaluated225 .take();226 }227228 /// Adds file by source code and parsed expr229 pub fn add_parsed_file(230 &self,231 name: Rc<Path>,232 source_code: IStr,233 parsed: LocExpr,234 ) -> Result<()> {235 self.data_mut().files.insert(236 name,237 FileData {238 source_code,239 parsed,240 evaluated: None,241 },242 );243244 Ok(())245 }246 pub fn get_source(&self, name: &Path) -> Option<IStr> {247 let ro_map = &self.data().files;248 ro_map.get(name).map(|value| value.source_code.clone())249 }250 pub fn map_source_locations(&self, file: &Path, locs: &[usize]) -> Vec<CodeLocation> {251 offset_to_location(&self.get_source(file).unwrap_or_else(|| "".into()), locs)252 }253 pub fn map_from_source_location(254 &self,255 file: &Path,256 line: usize,257 column: usize,258 ) -> Option<usize> {259 location_to_offset(260 &self.get_source(file).expect("file not found"),261 line,262 column,263 )264 }265 pub fn import_file(&self, from: &Path, path: &Path) -> Result<Val> {266 let file_path = self.resolve_file(from, path)?;267 {268 let data = self.data();269 let files = &data.files;270 if files.contains_key(&file_path as &Path) {271 drop(data);272 return self.evaluate_loaded_file_raw(&file_path);273 }274 }275 let contents = self.load_file_str(&file_path)?;276 self.add_file(file_path.clone(), contents)?;277 self.evaluate_loaded_file_raw(&file_path)278 }279 pub(crate) fn import_file_str(&self, from: &Path, path: &Path) -> Result<IStr> {280 let path = self.resolve_file(from, path)?;281 if !self.data().str_files.contains_key(&path) {282 let file_str = self.load_file_str(&path)?;283 self.data_mut().str_files.insert(path.clone(), file_str);284 }285 Ok(self.data().str_files.get(&path).cloned().unwrap())286 }287 pub(crate) fn import_file_bin(&self, from: &Path, path: &Path) -> Result<Rc<[u8]>> {288 let path = self.resolve_file(from, path)?;289 if !self.data().bin_files.contains_key(&path) {290 let file_bin = self.load_file_bin(&path)?;291 self.data_mut().bin_files.insert(path.clone(), file_bin);292 }293 Ok(self.data().bin_files.get(&path).cloned().unwrap())294 }295296 fn evaluate_loaded_file_raw(&self, name: &Path) -> Result<Val> {297 let expr: LocExpr = {298 let ro_map = &self.data().files;299 let value = ro_map300 .get(name)301 .unwrap_or_else(|| panic!("file not added: {:?}", name));302 if let Some(ref evaluated) = value.evaluated {303 return Ok(evaluated.clone());304 }305 value.parsed.clone()306 };307 let value = evaluate(self.clone(), self.create_default_context(), &expr)?;308 {309 self.data_mut()310 .files311 .get_mut(name)312 .unwrap()313 .evaluated314 .replace(value.clone());315 }316 Ok(value)317 }318319 /// Adds standard library global variable (std) to this evaluator320 pub fn with_stdlib(&self) -> &Self {321 use jrsonnet_stdlib::STDLIB_STR;322 let std_path: Rc<Path> = PathBuf::from("std.jsonnet").into();323324 self.add_parsed_file(325 std_path.clone(),326 STDLIB_STR.to_owned().into(),327 stdlib::get_parsed_stdlib(),328 )329 .expect("stdlib is correct");330 let val = self331 .evaluate_loaded_file_raw(&std_path)332 .expect("stdlib is correct");333 self.settings_mut().globals.insert("std".into(), val);334 self335 }336337 /// Creates context with all passed global variables338 pub fn create_default_context(&self) -> Context {339 let globals = &self.settings().globals;340 let mut new_bindings = GcHashMap::with_capacity(globals.len());341 for (name, value) in globals.iter() {342 new_bindings.insert(name.clone(), Thunk::evaluated(value.clone()));343 }344 Context::new().extend(new_bindings, None, None, None)345 }346347 /// Executes code creating a new stack frame348 pub fn push<T>(349 &self,350 e: CallLocation,351 frame_desc: impl FnOnce() -> String,352 f: impl FnOnce() -> Result<T>,353 ) -> Result<T> {354 {355 let mut data = self.data_mut();356 let stack_depth = &mut data.stack_depth;357 if *stack_depth > self.max_stack() {358 // Error creation uses data, so i drop guard here359 drop(data);360 throw!(StackOverflow);361 }362 *stack_depth += 1;363 }364 let result = f();365 {366 let mut data = self.data_mut();367 data.stack_depth -= 1;368 data.stack_generation += 1;369 }370 if let Err(mut err) = result {371 err.trace_mut().0.push(StackTraceElement {372 location: e.0.cloned(),373 desc: frame_desc(),374 });375 return Err(err);376 }377 result378 }379380 /// Executes code creating a new stack frame381 pub fn push_val(382 &self,383 e: &ExprLocation,384 frame_desc: impl FnOnce() -> String,385 f: impl FnOnce() -> Result<Val>,386 ) -> Result<Val> {387 {388 let mut data = self.data_mut();389 let stack_depth = &mut data.stack_depth;390 if *stack_depth > self.max_stack() {391 // Error creation uses data, so i drop guard here392 drop(data);393 throw!(StackOverflow);394 }395 *stack_depth += 1;396 }397 let mut result = f();398 {399 let mut data = self.data_mut();400 data.stack_depth -= 1;401 data.stack_generation += 1;402 result = data403 .breakpoints404 .insert(data.stack_depth, data.stack_generation, e, result);405 }406 if let Err(mut err) = result {407 err.trace_mut().0.push(StackTraceElement {408 location: Some(e.clone()),409 desc: frame_desc(),410 });411 return Err(err);412 }413 result414 }415 /// Executes code creating a new stack frame416 pub fn push_description<T>(417 &self,418 frame_desc: impl FnOnce() -> String,419 f: impl FnOnce() -> Result<T>,420 ) -> Result<T> {421 {422 let mut data = self.data_mut();423 let stack_depth = &mut data.stack_depth;424 if *stack_depth > self.max_stack() {425 // Error creation uses data, so i drop guard here426 drop(data);427 throw!(StackOverflow);428 }429 *stack_depth += 1;430 }431 let result = f();432 {433 let mut data = self.data_mut();434 data.stack_depth -= 1;435 data.stack_generation += 1;436 }437 if let Err(mut err) = result {438 err.trace_mut().0.push(StackTraceElement {439 location: None,440 desc: frame_desc(),441 });442 return Err(err);443 }444 result445 }446447 /// # Panics448 /// In case of formatting failure449 pub fn stringify_err(&self, e: &LocError) -> String {450 let mut out = String::new();451 self.settings()452 .trace_format453 .write_trace(&mut out, self, e)454 .unwrap();455 out456 }457458 pub fn manifest(&self, val: Val) -> Result<IStr> {459 self.push_description(460 || "manifestification".to_string(),461 || val.manifest(self.clone(), &self.manifest_format()),462 )463 }464 pub fn manifest_multi(&self, val: Val) -> Result<Vec<(IStr, IStr)>> {465 val.manifest_multi(self.clone(), &self.manifest_format())466 }467 pub fn manifest_stream(&self, val: Val) -> Result<Vec<IStr>> {468 val.manifest_stream(self.clone(), &self.manifest_format())469 }470471 /// If passed value is function then call with set TLA472 pub fn with_tla(&self, val: Val) -> Result<Val> {473 Ok(match val {474 Val::Func(func) => self.push_description(475 || "during TLA call".to_owned(),476 || {477 func.evaluate(478 self.clone(),479 self.create_default_context(),480 CallLocation::native(),481 &self.settings().tla_vars,482 true,483 )484 },485 )?,486 v => v,487 })488 }489}490491/// Internals492impl State {493 fn data(&self) -> Ref<EvaluationData> {494 self.0.data.borrow()495 }496 fn data_mut(&self) -> RefMut<EvaluationData> {497 self.0.data.borrow_mut()498 }499 pub fn settings(&self) -> Ref<EvaluationSettings> {500 self.0.settings.borrow()501 }502 pub fn settings_mut(&self) -> RefMut<EvaluationSettings> {503 self.0.settings.borrow_mut()504 }505}506507/// Raw methods evaluate passed values but don't perform TLA execution508impl State {509 pub fn evaluate_file_raw(&self, name: &Path) -> Result<Val> {510 self.import_file(&std::env::current_dir().expect("cwd"), name)511 }512 pub fn evaluate_file_raw_nocwd(&self, name: &Path) -> Result<Val> {513 self.import_file(&PathBuf::from("."), name)514 }515 /// Parses and evaluates the given snippet516 pub fn evaluate_snippet_raw(&self, source: Rc<Path>, code: IStr) -> Result<Val> {517 let parsed = parse(518 &code,519 &ParserSettings {520 file_name: source.clone(),521 },522 )523 .map_err(|e| ImportSyntaxError {524 path: source.clone(),525 source_code: code.clone(),526 error: Box::new(e),527 })?;528 self.add_parsed_file(source, code, parsed.clone())?;529 self.evaluate_expr_raw(parsed)530 }531 /// Evaluates the parsed expression532 pub fn evaluate_expr_raw(&self, code: LocExpr) -> Result<Val> {533 evaluate(self.clone(), self.create_default_context(), &code)534 }535}536537/// Settings utilities538impl State {539 pub fn add_ext_var(&self, name: IStr, value: Val) {540 self.settings_mut().ext_vars.insert(name, value);541 }542 pub fn add_ext_str(&self, name: IStr, value: IStr) {543 self.add_ext_var(name, Val::Str(value));544 }545 pub fn add_ext_code(&self, name: IStr, code: IStr) -> Result<()> {546 let value =547 self.evaluate_snippet_raw(PathBuf::from(format!("ext_code {}", name)).into(), code)?;548 self.add_ext_var(name, value);549 Ok(())550 }551552 pub fn add_tla(&self, name: IStr, value: Val) {553 self.settings_mut()554 .tla_vars555 .insert(name, TlaArg::Val(value));556 }557 pub fn add_tla_str(&self, name: IStr, value: IStr) {558 self.settings_mut()559 .tla_vars560 .insert(name, TlaArg::String(value));561 }562 pub fn add_tla_code(&self, name: IStr, code: IStr) -> Result<()> {563 let parsed = self.add_file(PathBuf::from(format!("tla_code {}", name)).into(), code)?;564 self.settings_mut()565 .tla_vars566 .insert(name, TlaArg::Code(parsed));567 Ok(())568 }569570 pub fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {571 self.settings().import_resolver.resolve_file(from, path)572 }573 pub fn load_file_str(&self, path: &Path) -> Result<IStr> {574 self.settings().import_resolver.load_file_str(path)575 }576 pub fn load_file_bin(&self, path: &Path) -> Result<Rc<[u8]>> {577 self.settings().import_resolver.load_file_bin(path)578 }579580 pub fn import_resolver(&self) -> Ref<dyn ImportResolver> {581 Ref::map(self.settings(), |s| &*s.import_resolver)582 }583 pub fn set_import_resolver(&self, resolver: Box<dyn ImportResolver>) {584 self.settings_mut().import_resolver = resolver;585 }586587 pub fn add_native(&self, name: IStr, cb: Cc<TraceBox<dyn Builtin>>) {588 self.settings_mut().ext_natives.insert(name, cb);589 }590591 pub fn manifest_format(&self) -> ManifestFormat {592 self.settings().manifest_format.clone()593 }594 pub fn set_manifest_format(&self, format: ManifestFormat) {595 self.settings_mut().manifest_format = format;596 }597598 pub fn trace_format(&self) -> Ref<dyn TraceFormat> {599 Ref::map(self.settings(), |s| &*s.trace_format)600 }601 pub fn set_trace_format(&self, format: Box<dyn TraceFormat>) {602 self.settings_mut().trace_format = format;603 }604605 pub fn max_trace(&self) -> usize {606 self.settings().max_trace607 }608 pub fn set_max_trace(&self, trace: usize) {609 self.settings_mut().max_trace = trace;610 }611612 pub fn max_stack(&self) -> usize {613 self.settings().max_stack614 }615 pub fn set_max_stack(&self, trace: usize) {616 self.settings_mut().max_stack = trace;617 }618}619620pub fn cc_ptr_eq<T>(a: &Cc<T>, b: &Cc<T>) -> bool {621 let a = a as &T;622 let b = b as &T;623 std::ptr::eq(a, b)624}625626fn weak_raw<T>(a: Weak<T>) -> *const () {627 unsafe { std::mem::transmute(a) }628}629fn weak_ptr_eq<T>(a: Weak<T>, b: Weak<T>) -> bool {630 std::ptr::eq(weak_raw(a), weak_raw(b))631}632633#[test]634fn weak_unsafe() {635 let a = Cc::new(1);636 let b = Cc::new(2);637638 let aw1 = a.clone().downgrade();639 let aw2 = a.clone().downgrade();640 let aw3 = a.clone().downgrade();641642 let bw = b.clone().downgrade();643644 assert!(weak_ptr_eq(aw1, aw2));645 assert!(!weak_ptr_eq(aw3, bw));646}1#![warn(clippy::all, clippy::nursery, clippy::pedantic)]2#![allow(3 macro_expanded_macro_exports_accessed_by_absolute_paths,4 clippy::ptr_arg,5 // Too verbose6 clippy::must_use_candidate,7 // A lot of functions pass around errors thrown by code8 clippy::missing_errors_doc,9 // A lot of pointers have interior Rc10 clippy::needless_pass_by_value,11 // Its fine12 clippy::wildcard_imports,13 clippy::enum_glob_use,14 clippy::module_name_repetitions,15 // TODO: fix individual issues, however this works as intended almost everywhere16 clippy::cast_precision_loss,17 clippy::cast_possible_wrap,18 clippy::cast_possible_truncation,19 clippy::cast_sign_loss,20)]2122// For jrsonnet-macros23extern crate self as jrsonnet_evaluator;2425mod ctx;26mod dynamic;27pub mod error;28mod evaluate;29pub mod function;30pub mod gc;31mod import;32mod integrations;33mod map;34mod obj;35mod stdlib;36pub mod trace;37pub mod typed;38pub mod val;3940use std::{41 borrow::Cow,42 cell::{Ref, RefCell, RefMut},43 collections::HashMap,44 fmt::{self, Debug},45 path::{Path, PathBuf},46 rc::Rc,47};4849pub use ctx::*;50pub use dynamic::*;51use error::{Error::*, LocError, Result, StackTraceElement};52pub use evaluate::*;53use function::{builtin::Builtin, CallLocation, TlaArg};54use gc::{GcHashMap, TraceBox};55use gcmodule::{Cc, Trace, Weak};56use hashbrown::hash_map::RawEntryMut;57pub use import::*;58use jrsonnet_interner::IBytes;59pub use jrsonnet_interner::IStr;60pub use jrsonnet_parser as parser;61use jrsonnet_parser::*;62pub use obj::*;63use trace::{location_to_offset, offset_to_location, CodeLocation, CompactFormat, TraceFormat};64pub use val::{ManifestFormat, Thunk, Val};6566pub trait Unbound: Trace {67 type Bound;68 fn bind(&self, s: State, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Self::Bound>;69}7071#[derive(Clone, Trace)]72pub enum LazyBinding {73 Bindable(Cc<TraceBox<dyn Unbound<Bound = Thunk<Val>>>>),74 Bound(Thunk<Val>),75}7677impl Debug for LazyBinding {78 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {79 write!(f, "LazyBinding")80 }81}82impl LazyBinding {83 pub fn evaluate(84 &self,85 s: State,86 sup: Option<ObjValue>,87 this: Option<ObjValue>,88 ) -> Result<Thunk<Val>> {89 match self {90 Self::Bindable(v) => v.bind(s, sup, this),91 Self::Bound(v) => Ok(v.clone()),92 }93 }94}9596pub struct EvaluationSettings {97 /// Limits recursion by limiting the number of stack frames98 pub max_stack: usize,99 /// Limits amount of stack trace items preserved100 pub max_trace: usize,101 /// Used for s`td.extVar`102 pub ext_vars: HashMap<IStr, TlaArg>,103 /// Used for ext.native104 pub ext_natives: HashMap<IStr, Cc<TraceBox<dyn Builtin>>>,105 /// TLA vars106 pub tla_vars: HashMap<IStr, TlaArg>,107 /// Global variables are inserted in default context108 pub globals: HashMap<IStr, Val>,109 /// Used to resolve file locations/contents110 pub import_resolver: Box<dyn ImportResolver>,111 /// Used in manifestification functions112 pub manifest_format: ManifestFormat,113 /// Used for bindings114 pub trace_format: Box<dyn TraceFormat>,115}116impl Default for EvaluationSettings {117 fn default() -> Self {118 Self {119 max_stack: 200,120 max_trace: 20,121 globals: HashMap::default(),122 ext_vars: HashMap::default(),123 ext_natives: HashMap::default(),124 tla_vars: HashMap::default(),125 import_resolver: Box::new(DummyImportResolver),126 manifest_format: ManifestFormat::Json {127 padding: 4,128 #[cfg(feature = "exp-preserve-order")]129 preserve_order: false,130 },131 trace_format: Box::new(CompactFormat {132 padding: 4,133 resolver: trace::PathResolver::Absolute,134 }),135 }136 }137}138139#[derive(Default)]140struct EvaluationData {141 /// Used for stack overflow detection, stacktrace is populated on unwind142 stack_depth: usize,143 /// Updated every time stack entry is popt144 stack_generation: usize,145146 breakpoints: Breakpoints,147148 /// Contains file source codes and evaluation results for imports and pretty-printed stacktraces149 files: GcHashMap<PathBuf, FileData>,150 /// Contains tla arguments and others, which aren't needed to be obtained by name151 volatile_files: GcHashMap<String, String>,152}153struct FileData {154 string: Option<IStr>,155 bytes: Option<IBytes>,156 parsed: Option<LocExpr>,157 evaluated: Option<Val>,158159 evaluating: bool,160}161impl FileData {162 fn new_string(data: IStr) -> Self {163 Self {164 string: Some(data),165 bytes: None,166 parsed: None,167 evaluated: None,168 evaluating: false,169 }170 }171 fn new_bytes(data: IBytes) -> Self {172 Self {173 string: None,174 bytes: Some(data),175 parsed: None,176 evaluated: None,177 evaluating: false,178 }179 }180}181182#[allow(clippy::type_complexity)]183pub struct Breakpoint {184 loc: ExprLocation,185 collected: RefCell<HashMap<usize, (usize, Vec<Result<Val>>)>>,186}187#[derive(Default)]188struct Breakpoints(Vec<Rc<Breakpoint>>);189impl Breakpoints {190 fn insert(191 &self,192 stack_depth: usize,193 stack_generation: usize,194 loc: &ExprLocation,195 result: Result<Val>,196 ) -> Result<Val> {197 if self.0.is_empty() {198 return result;199 }200 for item in &self.0 {201 if item.loc.belongs_to(loc) {202 let mut collected = item.collected.borrow_mut();203 let (depth, vals) = collected.entry(stack_generation).or_default();204 if stack_depth > *depth {205 vals.clear();206 }207 vals.push(result.clone());208 }209 }210 result211 }212}213214#[derive(Default)]215pub struct EvaluationStateInternals {216 /// Internal state217 data: RefCell<EvaluationData>,218 /// Settings, safe to change at runtime219 settings: RefCell<EvaluationSettings>,220}221222/// Maintains stack trace and import resolution223#[derive(Default, Clone)]224pub struct State(Rc<EvaluationStateInternals>);225226impl State {227 pub fn import_str(&self, path: PathBuf) -> Result<IStr> {228 let mut data = self.data_mut();229 let mut file = data.files.raw_entry_mut().from_key(&path);230231 let file = match file {232 RawEntryMut::Occupied(ref mut d) => d.get_mut(),233 RawEntryMut::Vacant(v) => {234 let data = self.settings().import_resolver.load_file_contents(&path)?;235 v.insert(236 path.clone(),237 FileData::new_string(238 std::str::from_utf8(&data)239 .map_err(|_| ImportBadFileUtf8(path.clone()))?240 .into(),241 ),242 )243 .1244 }245 };246 if let Some(str) = &file.string {247 return Ok(str.clone());248 }249 if file.string.is_none() {250 file.string = Some(251 file.bytes252 .as_ref()253 .expect("either string or bytes should be set")254 .clone()255 .cast_str()256 .ok_or_else(|| ImportBadFileUtf8(path.clone()))?,257 );258 }259 Ok(file.string.as_ref().expect("just set").clone())260 }261 pub fn import_bin(&self, path: PathBuf) -> Result<IBytes> {262 let mut data = self.data_mut();263 let mut file = data.files.raw_entry_mut().from_key(&path);264265 let file = match file {266 RawEntryMut::Occupied(ref mut d) => d.get_mut(),267 RawEntryMut::Vacant(v) => {268 let data = self.settings().import_resolver.load_file_contents(&path)?;269 v.insert(path.clone(), FileData::new_bytes(data.as_slice().into()))270 .1271 }272 };273 if let Some(str) = &file.bytes {274 return Ok(str.clone());275 }276 if file.bytes.is_none() {277 file.bytes = Some(278 file.string279 .as_ref()280 .expect("either string or bytes should be set")281 .clone()282 .cast_bytes(),283 );284 }285 Ok(file.bytes.as_ref().expect("just set").clone())286 }287 pub fn import(&self, path: PathBuf) -> Result<Val> {288 let mut data = self.data_mut();289 let mut file = data.files.raw_entry_mut().from_key(&path);290291 let file = match file {292 RawEntryMut::Occupied(ref mut d) => d.get_mut(),293 RawEntryMut::Vacant(v) => {294 let data = self.settings().import_resolver.load_file_contents(&path)?;295 v.insert(296 path.clone(),297 FileData::new_string(298 std::str::from_utf8(&data)299 .map_err(|_| ImportBadFileUtf8(path.clone()))?300 .into(),301 ),302 )303 .1304 }305 };306 if let Some(val) = &file.evaluated {307 return Ok(val.clone());308 }309 if file.string.is_none() {310 file.string = Some(311 std::str::from_utf8(312 file.bytes313 .as_ref()314 .expect("either string or bytes should be set"),315 )316 .map_err(|_| ImportBadFileUtf8(path.clone()))?317 .into(),318 );319 }320 let code = file.string.as_ref().expect("just set");321 let file_name = Source::new(path.clone()).expect("resolver should return correct name");322 if file.parsed.is_none() {323 file.parsed = Some(324 jrsonnet_parser::parse(325 code,326 &ParserSettings {327 file_name: file_name.clone(),328 },329 )330 .map_err(|e| ImportSyntaxError {331 path: file_name,332 source_code: code.clone(),333 error: Box::new(e),334 })?,335 );336 }337 let parsed = file.parsed.as_ref().expect("just set").clone();338 if file.evaluating {339 throw!(InfiniteRecursionDetected)340 }341 file.evaluating = true;342 // Dropping file here, as it borrows data, which may be used in evaluation343 drop(data);344 let res = evaluate(self.clone(), self.create_default_context(), &parsed);345346 let mut data = self.data_mut();347 let mut file = data.files.raw_entry_mut().from_key(&path);348349 let file = match file {350 RawEntryMut::Occupied(ref mut d) => d.get_mut(),351 RawEntryMut::Vacant(_) => unreachable!("this file was just here!"),352 };353 file.evaluating = false;354 match res {355 Ok(v) => {356 file.evaluated = Some(v.clone());357 Ok(v)358 }359 Err(e) => Err(e),360 }361 }362363 pub fn get_source(&self, name: Source) -> Option<String> {364 let data = self.data();365 match name.repr() {366 Ok(real) => data367 .files368 .get(real)369 .and_then(|f| f.string.as_ref())370 .map(ToString::to_string),371 Err(e) => data.volatile_files.get(e).map(ToOwned::to_owned),372 }373 }374 pub fn map_source_locations(&self, file: Source, locs: &[u32]) -> Vec<CodeLocation> {375 offset_to_location(&self.get_source(file).unwrap_or_else(|| "".into()), locs)376 }377 pub fn map_from_source_location(378 &self,379 file: Source,380 line: usize,381 column: usize,382 ) -> Option<usize> {383 location_to_offset(384 &self.get_source(file).expect("file not found"),385 line,386 column,387 )388 }389 /// Adds standard library global variable (std) to this evaluator390 pub fn with_stdlib(&self) -> &Self {391 let val = evaluate(392 self.clone(),393 self.create_default_context(),394 &stdlib::get_parsed_stdlib(),395 )396 .expect("std should not fail");397 self.settings_mut().globals.insert("std".into(), val);398 self399 }400401 /// Creates context with all passed global variables402 pub fn create_default_context(&self) -> Context {403 let globals = &self.settings().globals;404 let mut new_bindings = GcHashMap::with_capacity(globals.len());405 for (name, value) in globals.iter() {406 new_bindings.insert(name.clone(), Thunk::evaluated(value.clone()));407 }408 Context::new().extend(new_bindings, None, None, None)409 }410411 /// Executes code creating a new stack frame412 pub fn push<T>(413 &self,414 e: CallLocation,415 frame_desc: impl FnOnce() -> String,416 f: impl FnOnce() -> Result<T>,417 ) -> Result<T> {418 {419 let mut data = self.data_mut();420 let stack_depth = &mut data.stack_depth;421 if *stack_depth > self.max_stack() {422 // Error creation uses data, so i drop guard here423 drop(data);424 throw!(StackOverflow);425 }426 *stack_depth += 1;427 }428 let result = f();429 {430 let mut data = self.data_mut();431 data.stack_depth -= 1;432 data.stack_generation += 1;433 }434 if let Err(mut err) = result {435 err.trace_mut().0.push(StackTraceElement {436 location: e.0.cloned(),437 desc: frame_desc(),438 });439 return Err(err);440 }441 result442 }443444 /// Executes code creating a new stack frame445 pub fn push_val(446 &self,447 e: &ExprLocation,448 frame_desc: impl FnOnce() -> String,449 f: impl FnOnce() -> Result<Val>,450 ) -> Result<Val> {451 {452 let mut data = self.data_mut();453 let stack_depth = &mut data.stack_depth;454 if *stack_depth > self.max_stack() {455 // Error creation uses data, so i drop guard here456 drop(data);457 throw!(StackOverflow);458 }459 *stack_depth += 1;460 }461 let mut result = f();462 {463 let mut data = self.data_mut();464 data.stack_depth -= 1;465 data.stack_generation += 1;466 result = data467 .breakpoints468 .insert(data.stack_depth, data.stack_generation, e, result);469 }470 if let Err(mut err) = result {471 err.trace_mut().0.push(StackTraceElement {472 location: Some(e.clone()),473 desc: frame_desc(),474 });475 return Err(err);476 }477 result478 }479 /// Executes code creating a new stack frame480 pub fn push_description<T>(481 &self,482 frame_desc: impl FnOnce() -> String,483 f: impl FnOnce() -> Result<T>,484 ) -> Result<T> {485 {486 let mut data = self.data_mut();487 let stack_depth = &mut data.stack_depth;488 if *stack_depth > self.max_stack() {489 // Error creation uses data, so i drop guard here490 drop(data);491 throw!(StackOverflow);492 }493 *stack_depth += 1;494 }495 let result = f();496 {497 let mut data = self.data_mut();498 data.stack_depth -= 1;499 data.stack_generation += 1;500 }501 if let Err(mut err) = result {502 err.trace_mut().0.push(StackTraceElement {503 location: None,504 desc: frame_desc(),505 });506 return Err(err);507 }508 result509 }510511 /// # Panics512 /// In case of formatting failure513 pub fn stringify_err(&self, e: &LocError) -> String {514 let mut out = String::new();515 self.settings()516 .trace_format517 .write_trace(&mut out, self, e)518 .unwrap();519 out520 }521522 pub fn manifest(&self, val: Val) -> Result<IStr> {523 self.push_description(524 || "manifestification".to_string(),525 || val.manifest(self.clone(), &self.manifest_format()),526 )527 }528 pub fn manifest_multi(&self, val: Val) -> Result<Vec<(IStr, IStr)>> {529 val.manifest_multi(self.clone(), &self.manifest_format())530 }531 pub fn manifest_stream(&self, val: Val) -> Result<Vec<IStr>> {532 val.manifest_stream(self.clone(), &self.manifest_format())533 }534535 /// If passed value is function then call with set TLA536 pub fn with_tla(&self, val: Val) -> Result<Val> {537 Ok(match val {538 Val::Func(func) => self.push_description(539 || "during TLA call".to_owned(),540 || {541 func.evaluate(542 self.clone(),543 self.create_default_context(),544 CallLocation::native(),545 &self.settings().tla_vars,546 true,547 )548 },549 )?,550 v => v,551 })552 }553}554555/// Internals556impl State {557 fn data(&self) -> Ref<EvaluationData> {558 self.0.data.borrow()559 }560 fn data_mut(&self) -> RefMut<EvaluationData> {561 self.0.data.borrow_mut()562 }563 pub fn settings(&self) -> Ref<EvaluationSettings> {564 self.0.settings.borrow()565 }566 pub fn settings_mut(&self) -> RefMut<EvaluationSettings> {567 self.0.settings.borrow_mut()568 }569}570571/// Raw methods evaluate passed values but don't perform TLA execution572impl State {573 /// Parses and evaluates the given snippet574 pub fn evaluate_snippet(&self, name: String, code: String) -> Result<Val> {575 let source = Source::new_virtual(Cow::Owned(name.clone()));576 let parsed = jrsonnet_parser::parse(577 &code,578 &ParserSettings {579 file_name: source.clone(),580 },581 )582 .map_err(|e| ImportSyntaxError {583 path: source,584 source_code: code.clone().into(),585 error: Box::new(e),586 })?;587 self.data_mut().volatile_files.insert(name, code);588 evaluate(self.clone(), self.create_default_context(), &parsed)589 }590}591592/// Settings utilities593impl State {594 pub fn add_ext_var(&self, name: IStr, value: Val) {595 self.settings_mut()596 .ext_vars597 .insert(name, TlaArg::Val(value));598 }599 pub fn add_ext_str(&self, name: IStr, value: IStr) {600 self.settings_mut()601 .ext_vars602 .insert(name, TlaArg::String(value));603 }604 pub fn add_ext_code(&self, name: &str, code: String) -> Result<()> {605 let source_name = format!("<extvar:{}>", name);606 let source = Source::new_virtual(Cow::Owned(source_name.clone()));607 let parsed = jrsonnet_parser::parse(608 &code,609 &ParserSettings {610 file_name: source.clone(),611 },612 )613 .map_err(|e| ImportSyntaxError {614 path: source,615 source_code: code.clone().into(),616 error: Box::new(e),617 })?;618 self.data_mut().volatile_files.insert(source_name, code);619 self.settings_mut()620 .ext_vars621 .insert(name.into(), TlaArg::Code(parsed));622 Ok(())623 }624625 pub fn add_tla(&self, name: IStr, value: Val) {626 self.settings_mut()627 .tla_vars628 .insert(name, TlaArg::Val(value));629 }630 pub fn add_tla_str(&self, name: IStr, value: IStr) {631 self.settings_mut()632 .tla_vars633 .insert(name, TlaArg::String(value));634 }635 pub fn add_tla_code(&self, name: IStr, code: &str) -> Result<()> {636 let source_name = format!("<top-level-arg:{}>", name);637 let source = Source::new_virtual(Cow::Owned(source_name.clone()));638 let parsed = jrsonnet_parser::parse(639 code,640 &ParserSettings {641 file_name: source.clone(),642 },643 )644 .map_err(|e| ImportSyntaxError {645 path: source,646 source_code: code.into(),647 error: Box::new(e),648 })?;649 self.data_mut()650 .volatile_files651 .insert(source_name, code.to_owned());652 self.settings_mut()653 .tla_vars654 .insert(name, TlaArg::Code(parsed));655 Ok(())656 }657658 pub fn resolve_file(&self, from: &Path, path: &str) -> Result<PathBuf> {659 self.settings()660 .import_resolver661 .resolve_file(from, path.as_ref())662 }663664 pub fn import_resolver(&self) -> Ref<dyn ImportResolver> {665 Ref::map(self.settings(), |s| &*s.import_resolver)666 }667 pub fn set_import_resolver(&self, resolver: Box<dyn ImportResolver>) {668 self.settings_mut().import_resolver = resolver;669 }670671 pub fn add_native(&self, name: IStr, cb: Cc<TraceBox<dyn Builtin>>) {672 self.settings_mut().ext_natives.insert(name, cb);673 }674675 pub fn manifest_format(&self) -> ManifestFormat {676 self.settings().manifest_format.clone()677 }678 pub fn set_manifest_format(&self, format: ManifestFormat) {679 self.settings_mut().manifest_format = format;680 }681682 pub fn trace_format(&self) -> Ref<dyn TraceFormat> {683 Ref::map(self.settings(), |s| &*s.trace_format)684 }685 pub fn set_trace_format(&self, format: Box<dyn TraceFormat>) {686 self.settings_mut().trace_format = format;687 }688689 pub fn max_trace(&self) -> usize {690 self.settings().max_trace691 }692 pub fn set_max_trace(&self, trace: usize) {693 self.settings_mut().max_trace = trace;694 }695696 pub fn max_stack(&self) -> usize {697 self.settings().max_stack698 }699 pub fn set_max_stack(&self, trace: usize) {700 self.settings_mut().max_stack = trace;701 }702}703704pub fn cc_ptr_eq<T>(a: &Cc<T>, b: &Cc<T>) -> bool {705 let a = a as &T;706 let b = b as &T;707 std::ptr::eq(a, b)708}709710fn weak_raw<T>(a: Weak<T>) -> *const () {711 unsafe { std::mem::transmute(a) }712}713fn weak_ptr_eq<T>(a: Weak<T>, b: Weak<T>) -> bool {714 std::ptr::eq(weak_raw(a), weak_raw(b))715}716717#[test]718fn weak_unsafe() {719 let a = Cc::new(1);720 let b = Cc::new(2);721722 let aw1 = a.clone().downgrade();723 let aw2 = a.clone().downgrade();724 let aw3 = a.clone().downgrade();725726 let bw = b.clone().downgrade();727728 assert!(weak_ptr_eq(aw1, aw2));729 assert!(!weak_ptr_eq(aw3, bw));730}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.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/mod.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/mod.rs
@@ -5,17 +5,17 @@
use format::{format_arr, format_obj};
use gcmodule::Cc;
-use jrsonnet_interner::IStr;
+use jrsonnet_interner::{IBytes, IStr};
use serde::Deserialize;
use serde_yaml::DeserializingQuirks;
use crate::{
error::{Error::*, Result},
- function::{builtin::StaticBuiltin, CallLocation, FuncVal},
+ function::{builtin::StaticBuiltin, ArgLike, CallLocation, FuncVal},
operator::evaluate_mod_op,
stdlib::manifest::{manifest_yaml_ex, ManifestYamlOptions},
throw,
- typed::{Any, BoundedUsize, Bytes, Either2, Either4, PositiveF64, Typed, VecVal, M1},
+ typed::{Any, BoundedUsize, Either2, Either4, PositiveF64, Typed, VecVal, M1},
val::{equals, primitive_equals, ArrValue, IndexableVal, Slice},
Either, ObjValue, State, Val,
};
@@ -365,12 +365,16 @@
#[jrsonnet_macros::builtin]
fn builtin_ext_var(s: State, x: IStr) -> Result<Any> {
+ let ctx = s.create_default_context();
Ok(Any(s
+ .clone()
.settings()
.ext_vars
.get(&x)
.cloned()
- .ok_or(UndefinedExternalVariable(x))?))
+ .ok_or(UndefinedExternalVariable(x))?
+ .evaluate_arg(s.clone(), ctx, true)?
+ .evaluate(s)?))
}
#[jrsonnet_macros::builtin]
@@ -489,15 +493,15 @@
}
#[jrsonnet_macros::builtin]
-fn builtin_encode_utf8(str: IStr) -> Result<Bytes> {
- Ok(Bytes(str.bytes().collect::<Vec<u8>>().into()))
+fn builtin_encode_utf8(str: IStr) -> Result<IBytes> {
+ Ok(str.cast_bytes())
}
#[jrsonnet_macros::builtin]
-fn builtin_decode_utf8(arr: Bytes) -> Result<IStr> {
- Ok(std::str::from_utf8(&arr.0)
- .map_err(|_| RuntimeError("bad utf8".into()))?
- .into())
+fn builtin_decode_utf8(arr: IBytes) -> Result<IStr> {
+ Ok(arr
+ .cast_str()
+ .ok_or_else(|| RuntimeError("bad utf8".into()))?)
}
#[jrsonnet_macros::builtin]
@@ -509,33 +513,28 @@
fn builtin_trace(s: State, loc: CallLocation, str: IStr, rest: Any) -> Result<Any> {
eprint!("TRACE:");
if let Some(loc) = loc.0 {
- let locs = s.map_source_locations(&loc.0, &[loc.1]);
- eprint!(
- " {}:{}",
- loc.0.file_name().unwrap().to_str().unwrap(),
- locs[0].line
- );
+ let locs = s.map_source_locations(loc.0.clone(), &[loc.1]);
+ eprint!(" {}:{}", loc.0.short_display(), locs[0].line);
}
eprintln!(" {}", str);
Ok(rest) as Result<Any>
}
#[jrsonnet_macros::builtin]
-fn builtin_base64(input: Either![Bytes, IStr]) -> Result<String> {
+fn builtin_base64(input: Either![IBytes, IStr]) -> Result<String> {
use Either2::*;
Ok(match input {
- A(a) => base64::encode(a.0),
+ A(a) => base64::encode(a.as_slice()),
B(l) => base64::encode(l.bytes().collect::<Vec<_>>()),
})
}
#[jrsonnet_macros::builtin]
-fn builtin_base64_decode_bytes(input: IStr) -> Result<Bytes> {
- Ok(Bytes(
- base64::decode(&input.as_bytes())
- .map_err(|_| RuntimeError("bad base64".into()))?
- .into(),
- ))
+fn builtin_base64_decode_bytes(input: IStr) -> Result<IBytes> {
+ Ok(base64::decode(&input.as_bytes())
+ .map_err(|_| RuntimeError("bad base64".into()))?
+ .as_slice()
+ .into())
}
#[jrsonnet_macros::builtin]
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!(