difftreelog
feat string interning
in: master
20 files changed
bindings/jsonnet/Cargo.tomldiffbeforeafterboth--- a/bindings/jsonnet/Cargo.toml
+++ b/bindings/jsonnet/Cargo.toml
@@ -5,6 +5,7 @@
edition = "2018"
[dependencies]
+jrsonnet-interner = { path = "../../crates/jrsonnet-interner", version = "0.3.3" }
jrsonnet-evaluator = { path = "../../crates/jrsonnet-evaluator", version = "0.3.3" }
jrsonnet-parser = { path = "../../crates/jrsonnet-parser", version = "0.3.3" }
bindings/jsonnet/src/import.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/import.rs
+++ b/bindings/jsonnet/src/import.rs
@@ -4,6 +4,7 @@
error::{Error::*, Result},
throw, EvaluationState, ImportResolver,
};
+use jrsonnet_interner::IStr;
use std::{
any::Any,
cell::RefCell,
@@ -30,7 +31,7 @@
cb: JsonnetImportCallback,
ctx: *mut c_void,
- out: RefCell<HashMap<PathBuf, Rc<str>>>,
+ out: RefCell<HashMap<PathBuf, IStr>>,
}
impl ImportResolver for CallbackImportResolver {
fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {
@@ -75,7 +76,7 @@
Ok(Rc::new(found_here_buf))
}
- fn load_file_contents(&self, resolved: &PathBuf) -> Result<Rc<str>> {
+ fn load_file_contents(&self, resolved: &PathBuf) -> Result<IStr> {
Ok(self.out.borrow().get(resolved).unwrap().clone())
}
unsafe fn as_any(&self) -> &dyn Any {
@@ -124,7 +125,7 @@
throw!(ImportFileNotFound(from.clone(), path.clone()))
}
}
- fn load_file_contents(&self, id: &PathBuf) -> Result<Rc<str>> {
+ fn load_file_contents(&self, id: &PathBuf) -> Result<IStr> {
let mut file = File::open(id).map_err(|_e| ResolvedFileNotFound(id.clone()))?;
let mut out = String::new();
file.read_to_string(&mut out)
bindings/jsonnet/src/lib.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -8,6 +8,7 @@
use import::NativeImportResolver;
use jrsonnet_evaluator::{EvaluationState, ManifestFormat, Val};
+use jrsonnet_interner::IStr;
use std::{
alloc::Layout,
ffi::{CStr, CString},
@@ -161,7 +162,7 @@
})
}
-fn multi_to_raw(multi: Vec<(Rc<str>, Rc<str>)>) -> *const c_char {
+fn multi_to_raw(multi: Vec<(IStr, IStr)>) -> *const c_char {
let mut out = Vec::new();
for (i, (k, v)) in multi.iter().enumerate() {
if i != 0 {
@@ -237,7 +238,7 @@
})
}
-fn stream_to_raw(multi: Vec<Rc<str>>) -> *const c_char {
+fn stream_to_raw(multi: Vec<IStr>) -> *const c_char {
let mut out = Vec::new();
for (i, v) in multi.iter().enumerate() {
if i != 0 {
crates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-evaluator/Cargo.toml
+++ b/crates/jrsonnet-evaluator/Cargo.toml
@@ -12,8 +12,6 @@
serialized-stdlib = ["serde", "bincode", "jrsonnet-parser/deserialize"]
# Allow to convert Val into serde_json::Value and backwards
serde-json = ["serde", "serde_json"]
-# Same as above, but with generated code instead of serde. Reduces memory usage, but increases binary size and compilation time
-codegenerated-stdlib = []
# Replace some standard library functions with faster implementations (I.e manifestJsonEx)
# Library works fine without this feature, but requires more memory and time for std function calls
faster = []
@@ -24,6 +22,7 @@
unstable = []
[dependencies]
+jrsonnet-interner = { path = "../jrsonnet-interner" }
jrsonnet-parser = { path = "../jrsonnet-parser", version = "0.3.3" }
jrsonnet-stdlib = { path = "../jrsonnet-stdlib", version = "0.3.3" }
jrsonnet-types = { path = "../jrsonnet-types", version = "0.3.3" }
@@ -58,8 +57,7 @@
optional = true
[build-dependencies]
-jrsonnet-parser = { path = "../jrsonnet-parser", features = ["dump", "serialize", "deserialize"], version = "0.3.3" }
+jrsonnet-parser = { path = "../jrsonnet-parser", features = ["serialize", "deserialize"], version = "0.3.3" }
jrsonnet-stdlib = { path = "../jrsonnet-stdlib", version = "0.3.3" }
-structdump = "0.1.2"
serde = "1.0"
bincode = "1.3.1"
crates/jrsonnet-evaluator/build.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/build.rs
+++ b/crates/jrsonnet-evaluator/build.rs
@@ -10,7 +10,6 @@
path::{Path, PathBuf},
rc::Rc,
};
-use structdump::CodegenResult;
fn main() {
let parsed = parse(
@@ -36,11 +35,11 @@
name: FieldName::Fixed(name),
..
})
- if **name == *"join" || **name == *"manifestJsonEx" ||
- **name == *"escapeStringJson" || **name == *"equals" ||
- **name == *"base64" || **name == *"foldl" || **name == *"foldr" ||
- **name == *"sortImpl" || **name == *"format" || **name == *"range" ||
- **name == *"reverse" || **name == *"slice" || **name == *"mod"
+ if name == "join" || name == "manifestJsonEx" ||
+ name == "escapeStringJson" || name == "equals" ||
+ name == "base64" || name == "foldl" || name == "foldr" ||
+ name == "sortImpl" || name == "format" || name == "range" ||
+ name == "reverse" || name == "slice" || name == "mod"
)
})
.collect(),
@@ -52,15 +51,6 @@
} else {
parsed
};
- {
- let mut codegen = CodegenResult::default();
- let code = codegen.codegen(&parsed);
-
- let out_dir = env::var("OUT_DIR").unwrap();
- let dest_path = Path::new(&out_dir).join("stdlib.rs");
- let mut f = File::create(&dest_path).unwrap();
- f.write_all(&code.as_bytes()).unwrap();
- }
{
let out_dir = env::var("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("stdlib.bincode");
crates/jrsonnet-evaluator/src/builtin/format.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/format.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/format.rs
@@ -2,6 +2,7 @@
#![allow(clippy::too_many_arguments)]
use crate::{error::Error::*, throw, LocError, ObjValue, Result, Val};
+use jrsonnet_interner::IStr;
use jrsonnet_types::ValType;
use thiserror::Error;
@@ -20,7 +21,7 @@
#[error("mapping keys required")]
MappingKeysRequired,
#[error("no such format field: {0}")]
- NoSuchFormatField(Rc<str>),
+ NoSuchFormatField(IStr),
}
impl From<FormatError> for LocError {
@@ -29,7 +30,6 @@
}
}
-use std::rc::Rc;
use FormatError::*;
type ParseResult<'t, T> = std::result::Result<(T, &'t str), FormatError>;
@@ -680,7 +680,7 @@
}
Element::Code(c) => {
// TODO: Operate on ref
- let f: Rc<str> = c.mkey.into();
+ let f: IStr = c.mkey.into();
let width = match c.width {
Width::Star => {
throw!(CannotUseStarWidthWithObject);
crates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -6,6 +6,7 @@
with_state, ArrValue, Context, FuncVal, LazyVal, Val,
};
use format::{format_arr, format_obj};
+use jrsonnet_interner::IStr;
use jrsonnet_parser::{ArgsDesc, BinaryOpType, ExprLocation};
use jrsonnet_types::ty;
use std::{collections::HashMap, path::PathBuf, rc::Rc};
@@ -19,7 +20,7 @@
pub mod manifest;
pub mod sort;
-fn std_format(str: Rc<str>, vals: Val) -> Result<Val> {
+fn std_format(str: IStr, vals: Val) -> Result<Val> {
push(
&Some(ExprLocation(Rc::from(PathBuf::from("std.jsonnet")), 0, 0)),
|| format!("std.format of {}", str),
crates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -2,6 +2,7 @@
error::Error::*, future_wrapper, map::LayeredHashMap, rc_fn_helper, resolved_lazy_val,
LazyBinding, LazyVal, ObjValue, Result, Val,
};
+use jrsonnet_interner::IStr;
use rustc_hash::FxHashMap;
use std::hash::BuildHasherDefault;
use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};
@@ -18,7 +19,7 @@
dollar: Option<ObjValue>,
this: Option<ObjValue>,
super_obj: Option<ObjValue>,
- bindings: LayeredHashMap<Rc<str>, LazyVal>,
+ bindings: LayeredHashMap<IStr, LazyVal>,
}
impl Debug for ContextInternals {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
@@ -57,7 +58,7 @@
}))
}
- pub fn binding(&self, name: Rc<str>) -> Result<LazyVal> {
+ pub fn binding(&self, name: IStr) -> Result<LazyVal> {
Ok(self
.0
.bindings
@@ -72,7 +73,7 @@
ctx.unwrap()
}
- pub fn with_var(self, name: Rc<str>, value: Val) -> Self {
+ pub fn with_var(self, name: IStr, value: Val) -> Self {
let mut new_bindings =
FxHashMap::with_capacity_and_hasher(1, BuildHasherDefault::default());
new_bindings.insert(name, resolved_lazy_val!(value));
@@ -81,7 +82,7 @@
pub fn extend(
self,
- new_bindings: FxHashMap<Rc<str>, LazyVal>,
+ new_bindings: FxHashMap<IStr, LazyVal>,
new_dollar: Option<ObjValue>,
new_this: Option<ObjValue>,
new_super_obj: Option<ObjValue>,
@@ -123,7 +124,7 @@
}
pub fn extend_unbound(
self,
- new_bindings: HashMap<Rc<str>, LazyBinding>,
+ new_bindings: HashMap<IStr, LazyBinding>,
new_dollar: Option<ObjValue>,
new_this: Option<ObjValue>,
new_super_obj: Option<ObjValue>,
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -2,6 +2,7 @@
builtin::{format::FormatError, sort::SortError},
typed::TypeLocError,
};
+use jrsonnet_interner::IStr;
use jrsonnet_parser::{BinaryOpType, ExprLocation, UnaryOpType};
use jrsonnet_types::ValType;
use std::{path::PathBuf, rc::Rc};
@@ -10,7 +11,7 @@
#[derive(Error, Debug, Clone)]
pub enum Error {
#[error("intrinsic not found: {0}")]
- IntrinsicNotFound(Rc<str>),
+ IntrinsicNotFound(IStr),
#[error("argument reordering in intrisics not supported yet")]
IntrinsicArgumentReorderingIsNotSupportedYet,
@@ -33,36 +34,36 @@
ArrayBoundsError(usize, usize),
#[error("assert failed: {0}")]
- AssertionFailed(Rc<str>),
+ AssertionFailed(IStr),
#[error("variable is not defined: {0}")]
- VariableIsNotDefined(Rc<str>),
+ VariableIsNotDefined(IStr),
#[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]
TypeMismatch(&'static str, Vec<ValType>, ValType),
#[error("no such field: {0}")]
- NoSuchField(Rc<str>),
+ NoSuchField(IStr),
#[error("only functions can be called, got {0}")]
OnlyFunctionsCanBeCalledGot(ValType),
#[error("parameter {0} is not defined")]
UnknownFunctionParameter(String),
#[error("argument {0} is already bound")]
- BindingParameterASecondTime(Rc<str>),
+ BindingParameterASecondTime(IStr),
#[error("too many args, function has {0}")]
TooManyArgsFunctionHas(usize),
#[error("founction argument is not passed: {0}")]
- FunctionParameterNotBoundInCall(Rc<str>),
+ FunctionParameterNotBoundInCall(IStr),
#[error("external variable is not defined: {0}")]
- UndefinedExternalVariable(Rc<str>),
+ UndefinedExternalVariable(IStr),
#[error("native is not defined: {0}")]
- UndefinedExternalFunction(Rc<str>),
+ UndefinedExternalFunction(IStr),
#[error("field name should be string, got {0}")]
FieldMustBeStringGot(ValType),
#[error("attempted to index array with string {0}")]
- AttemptedIndexAnArrayWithString(Rc<str>),
+ AttemptedIndexAnArrayWithString(IStr),
#[error("{0} index type should be {1}, got {2}")]
ValueIndexMustBeTypeGot(ValType, ValType, ValType),
#[error("cant index into {0}")]
@@ -86,12 +87,12 @@
)]
ImportSyntaxError {
path: Rc<PathBuf>,
- source_code: Rc<str>,
+ source_code: IStr,
error: Box<jrsonnet_parser::ParseError>,
},
#[error("runtime error: {0}")]
- RuntimeError(Rc<str>),
+ RuntimeError(IStr),
#[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]
StackOverflow,
#[error("tried to index by fractional value")]
crates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate.rs
@@ -3,6 +3,7 @@
ContextCreator, FuncDesc, FuncVal, LazyBinding, LazyVal, ObjMember, ObjValue, Result, Val,
};
use closure::closure;
+use jrsonnet_interner::IStr;
use jrsonnet_parser::{
ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, ExprLocation, FieldMember,
ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType,
@@ -12,7 +13,7 @@
use rustc_hash::FxHashMap;
use std::{collections::HashMap, rc::Rc};
-pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (Rc<str>, LazyBinding) {
+pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (IStr, LazyBinding) {
let b = b.clone();
if let Some(params) = &b.params {
let params = params.clone();
@@ -45,7 +46,7 @@
}
}
-pub fn evaluate_method(ctx: Context, name: Rc<str>, params: ParamsDesc, body: LocExpr) -> Val {
+pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {
Val::Func(Rc::new(FuncVal::Normal(FuncDesc {
name,
ctx,
@@ -57,7 +58,7 @@
pub fn evaluate_field_name(
context: Context,
field_name: &jrsonnet_parser::FieldName,
-) -> Result<Option<Rc<str>>> {
+) -> Result<Option<IStr>> {
Ok(match field_name {
jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),
jrsonnet_parser::FieldName::Dyn(expr) => {
@@ -182,7 +183,7 @@
})
}
-future_wrapper!(HashMap<Rc<str>, LazyBinding>, FutureNewBindings);
+future_wrapper!(HashMap<IStr, LazyBinding>, FutureNewBindings);
future_wrapper!(ObjValue, FutureObjValue);
pub fn evaluate_comp<T>(
@@ -230,7 +231,7 @@
})
);
{
- let mut bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();
+ let mut bindings: HashMap<IStr, LazyBinding> = HashMap::new();
for (n, b) in members
.iter()
.filter_map(|m| match m {
@@ -334,7 +335,7 @@
)?)
})
);
- let mut bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();
+ let mut bindings: HashMap<IStr, LazyBinding> = HashMap::new();
for (n, b) in obj
.pre_locals
.iter()
@@ -401,7 +402,7 @@
})
}
-pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: Rc<str>) -> Result<Val> {
+pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: IStr) -> Result<Val> {
use Expr::*;
let LocExpr(expr, _loc) = lexpr;
Ok(match &**expr {
@@ -498,7 +499,7 @@
}
}
LocalExpr(bindings, returned) => {
- let mut new_bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();
+ let mut new_bindings: HashMap<IStr, LazyBinding> = HashMap::new();
let future_context = Context::new_future();
let context_creator = context_creator!(
crates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function.rs
+++ b/crates/jrsonnet-evaluator/src/function.rs
@@ -1,8 +1,9 @@
use crate::{error::Error::*, evaluate, lazy_val, resolved_lazy_val, throw, Context, Result, Val};
use closure::closure;
+use jrsonnet_interner::IStr;
use jrsonnet_parser::{ArgsDesc, ParamsDesc};
use rustc_hash::FxHashMap;
-use std::{collections::HashMap, hash::BuildHasherDefault, rc::Rc};
+use std::{collections::HashMap, hash::BuildHasherDefault};
const NO_DEFAULT_CONTEXT: &str =
"no default context set for call with defined default parameter value";
@@ -66,7 +67,7 @@
ctx: Context,
body_ctx: Option<Context>,
params: &ParamsDesc,
- args: &HashMap<Rc<str>, Val>,
+ args: &HashMap<IStr, Val>,
tailstrict: bool,
) -> Result<Context> {
let mut out = FxHashMap::with_capacity_and_hasher(params.len(), BuildHasherDefault::default());
crates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/import.rs
+++ b/crates/jrsonnet-evaluator/src/import.rs
@@ -3,6 +3,7 @@
throw,
};
use fs::File;
+use jrsonnet_interner::IStr;
use std::fs;
use std::io::Read;
use std::{any::Any, cell::RefCell, collections::HashMap, path::PathBuf, rc::Rc};
@@ -15,7 +16,7 @@
fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>>;
/// Reads file from filesystem, should be used only with path received from `resolve_file`
- fn load_file_contents(&self, resolved: &PathBuf) -> Result<Rc<str>>;
+ fn load_file_contents(&self, resolved: &PathBuf) -> Result<IStr>;
/// # Safety
///
@@ -32,7 +33,7 @@
throw!(ImportNotSupported(from.clone(), path.clone()))
}
- fn load_file_contents(&self, _resolved: &PathBuf) -> Result<Rc<str>> {
+ fn load_file_contents(&self, _resolved: &PathBuf) -> Result<IStr> {
// Can be only caused by library direct consumer, not by supplied jsonnet
panic!("dummy resolver can't load any file")
}
@@ -72,7 +73,7 @@
throw!(ImportFileNotFound(from.clone(), path.clone()))
}
}
- fn load_file_contents(&self, id: &PathBuf) -> Result<Rc<str>> {
+ fn load_file_contents(&self, id: &PathBuf) -> Result<IStr> {
let mut file = File::open(id).map_err(|_e| ResolvedFileNotFound(id.clone()))?;
let mut out = String::new();
file.read_to_string(&mut out)
@@ -89,7 +90,7 @@
/// Caches results of the underlying resolver
pub struct CachingImportResolver {
resolution_cache: RefCell<HashMap<ResolutionData, Result<Rc<PathBuf>>>>,
- loading_cache: RefCell<HashMap<PathBuf, Result<Rc<str>>>>,
+ loading_cache: RefCell<HashMap<PathBuf, Result<IStr>>>,
inner: Box<dyn ImportResolver>,
}
impl ImportResolver for CachingImportResolver {
@@ -101,7 +102,7 @@
.clone()
}
- fn load_file_contents(&self, resolved: &PathBuf) -> Result<Rc<str>> {
+ fn load_file_contents(&self, resolved: &PathBuf) -> Result<IStr> {
self.loading_cache
.borrow_mut()
.entry(resolved.clone())
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -23,6 +23,7 @@
pub use evaluate::*;
pub use function::parse_function_call;
pub use import::*;
+use jrsonnet_interner::IStr;
use jrsonnet_parser::*;
use native::NativeCallback;
pub use obj::*;
@@ -63,13 +64,13 @@
/// Limits amount of stack trace items preserved
pub max_trace: usize,
/// Used for s`td.extVar`
- pub ext_vars: HashMap<Rc<str>, Val>,
+ pub ext_vars: HashMap<IStr, Val>,
/// Used for ext.native
- pub ext_natives: HashMap<Rc<str>, Rc<NativeCallback>>,
+ pub ext_natives: HashMap<IStr, Rc<NativeCallback>>,
/// TLA vars
- pub tla_vars: HashMap<Rc<str>, Val>,
+ pub tla_vars: HashMap<IStr, Val>,
/// Global variables are inserted in default context
- pub globals: HashMap<Rc<str>, Val>,
+ pub globals: HashMap<IStr, Val>,
/// Used to resolve file locations/contents
pub import_resolver: Box<dyn ImportResolver>,
/// Used in manifestification functions
@@ -102,11 +103,11 @@
stack_depth: usize,
/// Contains file source codes and evaluation results for imports and pretty-printed stacktraces
files: HashMap<Rc<PathBuf>, FileData>,
- str_files: HashMap<Rc<PathBuf>, Rc<str>>,
+ str_files: HashMap<Rc<PathBuf>, IStr>,
}
pub struct FileData {
- source_code: Rc<str>,
+ source_code: IStr,
parsed: LocExpr,
evaluated: Option<Val>,
}
@@ -144,7 +145,7 @@
impl EvaluationState {
/// Parses and adds file as loaded
- pub fn add_file(&self, path: Rc<PathBuf>, source_code: Rc<str>) -> Result<()> {
+ pub fn add_file(&self, path: Rc<PathBuf>, source_code: IStr) -> Result<()> {
self.add_parsed_file(
path.clone(),
source_code.clone(),
@@ -169,7 +170,7 @@
pub fn add_parsed_file(
&self,
name: Rc<PathBuf>,
- source_code: Rc<str>,
+ source_code: IStr,
parsed: LocExpr,
) -> Result<()> {
self.data_mut().files.insert(
@@ -183,7 +184,7 @@
Ok(())
}
- pub fn get_source(&self, name: &PathBuf) -> Option<Rc<str>> {
+ pub fn get_source(&self, name: &PathBuf) -> Option<IStr> {
let ro_map = &self.data().files;
ro_map.get(name).map(|value| value.source_code.clone())
}
@@ -205,7 +206,7 @@
self.add_file(file_path.clone(), contents)?;
self.evaluate_loaded_file_raw(&file_path)
}
- pub(crate) fn import_file_str(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<str>> {
+ pub(crate) fn import_file_str(&self, from: &PathBuf, path: &PathBuf) -> Result<IStr> {
let path = self.resolve_file(from, path)?;
if !self.data().str_files.contains_key(&path) {
let file_str = self.load_file_contents(&path)?;
@@ -257,7 +258,7 @@
/// Creates context with all passed global variables
pub fn create_default_context(&self) -> Result<Context> {
let globals = &self.settings().globals;
- let mut new_bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();
+ let mut new_bindings: HashMap<IStr, LazyBinding> = HashMap::new();
for (name, value) in globals.iter() {
new_bindings.insert(
name.clone(),
@@ -321,13 +322,13 @@
out
}
- pub fn manifest(&self, val: Val) -> Result<Rc<str>> {
+ pub fn manifest(&self, val: Val) -> Result<IStr> {
self.run_in_state(|| val.manifest(&self.manifest_format()))
}
- pub fn manifest_multi(&self, val: Val) -> Result<Vec<(Rc<str>, Rc<str>)>> {
+ pub fn manifest_multi(&self, val: Val) -> Result<Vec<(IStr, IStr)>> {
self.run_in_state(|| val.manifest_multi(&self.manifest_format()))
}
- pub fn manifest_stream(&self, val: Val) -> Result<Vec<Rc<str>>> {
+ pub fn manifest_stream(&self, val: Val) -> Result<Vec<IStr>> {
self.run_in_state(|| val.manifest_stream(&self.manifest_format()))
}
@@ -371,7 +372,7 @@
self.run_in_state(|| self.import_file(&PathBuf::from("."), name))
}
/// Parses and evaluates the given snippet
- pub fn evaluate_snippet_raw(&self, source: Rc<PathBuf>, code: Rc<str>) -> Result<Val> {
+ pub fn evaluate_snippet_raw(&self, source: Rc<PathBuf>, code: IStr) -> Result<Val> {
let parsed = parse(
&code,
&ParserSettings {
@@ -391,26 +392,26 @@
/// Settings utilities
impl EvaluationState {
- pub fn add_ext_var(&self, name: Rc<str>, value: Val) {
+ pub fn add_ext_var(&self, name: IStr, value: Val) {
self.settings_mut().ext_vars.insert(name, value);
}
- pub fn add_ext_str(&self, name: Rc<str>, value: Rc<str>) {
+ pub fn add_ext_str(&self, name: IStr, value: IStr) {
self.add_ext_var(name, Val::Str(value));
}
- pub fn add_ext_code(&self, name: Rc<str>, code: Rc<str>) -> Result<()> {
+ pub fn add_ext_code(&self, name: IStr, code: IStr) -> Result<()> {
let value =
self.evaluate_snippet_raw(Rc::new(PathBuf::from(format!("ext_code {}", name))), code)?;
self.add_ext_var(name, value);
Ok(())
}
- pub fn add_tla(&self, name: Rc<str>, value: Val) {
+ pub fn add_tla(&self, name: IStr, value: Val) {
self.settings_mut().tla_vars.insert(name, value);
}
- pub fn add_tla_str(&self, name: Rc<str>, value: Rc<str>) {
+ pub fn add_tla_str(&self, name: IStr, value: IStr) {
self.add_tla(name, Val::Str(value));
}
- pub fn add_tla_code(&self, name: Rc<str>, code: Rc<str>) -> Result<()> {
+ pub fn add_tla_code(&self, name: IStr, code: IStr) -> Result<()> {
let value =
self.evaluate_snippet_raw(Rc::new(PathBuf::from(format!("tla_code {}", name))), code)?;
self.add_tla(name, value);
@@ -420,7 +421,7 @@
pub fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {
Ok(self.settings().import_resolver.resolve_file(from, path)?)
}
- pub fn load_file_contents(&self, path: &PathBuf) -> Result<Rc<str>> {
+ pub fn load_file_contents(&self, path: &PathBuf) -> Result<IStr> {
Ok(self.settings().import_resolver.load_file_contents(path)?)
}
@@ -431,7 +432,7 @@
self.settings_mut().import_resolver = resolver;
}
- pub fn add_native(&self, name: Rc<str>, cb: Rc<NativeCallback>) {
+ pub fn add_native(&self, name: IStr, cb: Rc<NativeCallback>) {
self.settings_mut().ext_natives.insert(name, cb);
}
@@ -468,6 +469,7 @@
pub mod tests {
use super::Val;
use crate::{error::Error::*, primitive_equals, EvaluationState};
+ use jrsonnet_interner::IStr;
use jrsonnet_parser::*;
use std::{path::PathBuf, rc::Rc};
@@ -905,13 +907,13 @@
Ok(())
}
- struct TestImportResolver(Rc<str>);
+ struct TestImportResolver(IStr);
impl crate::import::ImportResolver for TestImportResolver {
fn resolve_file(&self, _: &PathBuf, _: &PathBuf) -> crate::error::Result<Rc<PathBuf>> {
Ok(Rc::new(PathBuf::from("/test")))
}
- fn load_file_contents(&self, _: &PathBuf) -> crate::error::Result<Rc<str>> {
+ fn load_file_contents(&self, _: &PathBuf) -> crate::error::Result<IStr> {
Ok(self.0.clone())
}
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -1,5 +1,6 @@
use crate::{evaluate_add_op, LazyBinding, Result, Val};
use indexmap::IndexMap;
+use jrsonnet_interner::IStr;
use jrsonnet_parser::{ExprLocation, Visibility};
use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};
@@ -12,11 +13,11 @@
}
// Field => This
-type CacheKey = (Rc<str>, usize);
+type CacheKey = (IStr, usize);
#[derive(Debug)]
pub struct ObjValueInternals {
super_obj: Option<ObjValue>,
- this_entries: Rc<HashMap<Rc<str>, ObjMember>>,
+ this_entries: Rc<HashMap<IStr, ObjMember>>,
value_cache: RefCell<HashMap<CacheKey, Option<Val>>>,
}
#[derive(Clone)]
@@ -33,7 +34,7 @@
}
let mut debug = f.debug_struct("ObjValue");
for (name, member) in self.0.this_entries.iter() {
- debug.field(name, member);
+ debug.field(&name, member);
}
#[cfg(feature = "unstable")]
{
@@ -47,7 +48,7 @@
}
impl ObjValue {
- pub fn new(super_obj: Option<Self>, this_entries: Rc<HashMap<Rc<str>, ObjMember>>) -> Self {
+ pub fn new(super_obj: Option<Self>, this_entries: Rc<HashMap<IStr, ObjMember>>) -> Self {
Self(Rc::new(ObjValueInternals {
super_obj,
this_entries,
@@ -63,7 +64,7 @@
Some(v) => Self::new(Some(v.with_super(super_obj)), self.0.this_entries.clone()),
}
}
- pub fn enum_fields(&self, handler: &impl Fn(&Rc<str>, &Visibility)) {
+ pub fn enum_fields(&self, handler: &impl Fn(&IStr, &Visibility)) {
if let Some(s) = &self.0.super_obj {
s.enum_fields(handler);
}
@@ -71,7 +72,7 @@
handler(name, &member.visibility);
}
}
- pub fn fields_visibility(&self) -> IndexMap<Rc<str>, bool> {
+ pub fn fields_visibility(&self) -> IndexMap<IStr, bool> {
let out = Rc::new(RefCell::new(IndexMap::new()));
self.enum_fields(&|name, visibility| {
let mut out = out.borrow_mut();
@@ -91,7 +92,7 @@
});
Rc::try_unwrap(out).unwrap().into_inner()
}
- pub fn visible_fields(&self) -> Vec<Rc<str>> {
+ pub fn visible_fields(&self) -> Vec<IStr> {
let mut visible_fields: Vec<_> = self
.fields_visibility()
.into_iter()
@@ -101,10 +102,10 @@
visible_fields.sort();
visible_fields
}
- pub fn get(&self, key: Rc<str>) -> Result<Option<Val>> {
+ pub fn get(&self, key: IStr) -> Result<Option<Val>> {
Ok(self.get_raw(key, None)?)
}
- pub(crate) fn get_raw(&self, key: Rc<str>, real_this: Option<&Self>) -> Result<Option<Val>> {
+ pub(crate) fn get_raw(&self, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {
let real_this = real_this.unwrap_or(self);
let cache_key = (key.clone(), Rc::as_ptr(&real_this.0) as usize);
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth1use crate::{2 builtin::{3 call_builtin,4 manifest::{manifest_json_ex, ManifestJsonOptions, ManifestType},5 },6 error::Error::*,7 evaluate,8 function::{parse_function_call, parse_function_call_map, place_args},9 native::NativeCallback,10 throw, with_state, Context, ObjValue, Result,11};12use jrsonnet_parser::{el, Arg, ArgsDesc, Expr, ExprLocation, LiteralType, LocExpr, ParamsDesc};13use jrsonnet_types::ValType;14use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};1516enum LazyValInternals {17 Computed(Val),18 Waiting(Box<dyn Fn() -> Result<Val>>),19}20#[derive(Clone)]21pub struct LazyVal(Rc<RefCell<LazyValInternals>>);22impl LazyVal {23 pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {24 Self(Rc::new(RefCell::new(LazyValInternals::Waiting(f))))25 }26 pub fn new_resolved(val: Val) -> Self {27 Self(Rc::new(RefCell::new(LazyValInternals::Computed(val))))28 }29 pub fn evaluate(&self) -> Result<Val> {30 let new_value = match &*self.0.borrow() {31 LazyValInternals::Computed(v) => return Ok(v.clone()),32 LazyValInternals::Waiting(f) => f()?,33 };34 *self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());35 Ok(new_value)36 }37}3839#[macro_export]40macro_rules! lazy_val {41 ($f: expr) => {42 $crate::LazyVal::new(Box::new($f))43 };44}45#[macro_export]46macro_rules! resolved_lazy_val {47 ($f: expr) => {48 $crate::LazyVal::new_resolved($f)49 };50}51impl Debug for LazyVal {52 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {53 write!(f, "Lazy")54 }55}56impl PartialEq for LazyVal {57 fn eq(&self, other: &Self) -> bool {58 Rc::ptr_eq(&self.0, &other.0)59 }60}6162#[derive(Debug, PartialEq)]63pub struct FuncDesc {64 pub name: Rc<str>,65 pub ctx: Context,66 pub params: ParamsDesc,67 pub body: LocExpr,68}6970#[derive(Debug)]71pub enum FuncVal {72 /// Plain function implemented in jsonnet73 Normal(FuncDesc),74 /// Standard library function75 Intrinsic(Rc<str>),76 /// Library functions implemented in native77 NativeExt(Rc<str>, Rc<NativeCallback>),78}7980impl PartialEq for FuncVal {81 fn eq(&self, other: &Self) -> bool {82 match (self, other) {83 (Self::Normal(a), Self::Normal(b)) => a == b,84 (Self::Intrinsic(an), Self::Intrinsic(bn)) => an == bn,85 (Self::NativeExt(an, _), Self::NativeExt(bn, _)) => an == bn,86 (..) => false,87 }88 }89}90impl FuncVal {91 pub fn is_ident(&self) -> bool {92 matches!(&self, Self::Intrinsic(n) if n as &str == "id")93 }94 pub fn name(&self) -> Rc<str> {95 match self {96 Self::Normal(normal) => normal.name.clone(),97 Self::Intrinsic(name) => format!("std.{}", name).into(),98 Self::NativeExt(n, _) => format!("native.{}", n).into(),99 }100 }101 pub fn evaluate(102 &self,103 call_ctx: Context,104 loc: &Option<ExprLocation>,105 args: &ArgsDesc,106 tailstrict: bool,107 ) -> Result<Val> {108 match self {109 Self::Normal(func) => {110 let ctx = parse_function_call(111 call_ctx,112 Some(func.ctx.clone()),113 &func.params,114 args,115 tailstrict,116 )?;117 evaluate(ctx, &func.body)118 }119 Self::Intrinsic(name) => call_builtin(call_ctx, loc, name, args),120 Self::NativeExt(_name, handler) => {121 let args = parse_function_call(call_ctx, None, &handler.params, args, true)?;122 let mut out_args = Vec::with_capacity(handler.params.len());123 for p in handler.params.0.iter() {124 out_args.push(args.binding(p.0.clone())?.evaluate()?);125 }126 Ok(handler.call(&out_args)?)127 }128 }129 }130131 pub fn evaluate_map(132 &self,133 call_ctx: Context,134 args: &HashMap<Rc<str>, Val>,135 tailstrict: bool,136 ) -> Result<Val> {137 match self {138 Self::Normal(func) => {139 let ctx = parse_function_call_map(140 call_ctx,141 Some(func.ctx.clone()),142 &func.params,143 args,144 tailstrict,145 )?;146 evaluate(ctx, &func.body)147 }148 Self::Intrinsic(_) => todo!(),149 Self::NativeExt(_, _) => todo!(),150 }151 }152153 pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {154 match self {155 Self::Normal(func) => {156 let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;157 evaluate(ctx, &func.body)158 }159 Self::Intrinsic(_) => todo!(),160 Self::NativeExt(_, _) => todo!(),161 }162 }163}164165#[derive(Clone)]166pub enum ManifestFormat {167 YamlStream(Box<ManifestFormat>),168 Yaml(usize),169 Json(usize),170 ToString,171 String,172}173174#[derive(Debug, Clone)]175pub enum ArrValue {176 Lazy(Rc<Vec<LazyVal>>),177 Eager(Rc<Vec<Val>>),178}179impl ArrValue {180 pub fn len(&self) -> usize {181 match self {182 ArrValue::Lazy(l) => l.len(),183 ArrValue::Eager(e) => e.len(),184 }185 }186187 pub fn is_empty(&self) -> bool {188 self.len() == 0189 }190191 pub fn get(&self, index: usize) -> Result<Option<Val>> {192 match self {193 ArrValue::Lazy(vec) => {194 if let Some(v) = vec.get(index) {195 Ok(Some(v.evaluate()?))196 } else {197 Ok(None)198 }199 }200 ArrValue::Eager(vec) => Ok(vec.get(index).cloned()),201 }202 }203204 pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {205 match self {206 ArrValue::Lazy(vec) => vec.get(index).cloned(),207 ArrValue::Eager(vec) => vec208 .get(index)209 .cloned()210 .map(|val| LazyVal::new_resolved(val)),211 }212 }213214 pub fn evaluated(&self) -> Result<Rc<Vec<Val>>> {215 Ok(match self {216 ArrValue::Lazy(vec) => {217 let mut out = Vec::with_capacity(vec.len());218 for item in vec.iter() {219 out.push(item.evaluate()?);220 }221 Rc::new(out)222 }223 ArrValue::Eager(vec) => vec.clone(),224 })225 }226227 pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {228 (0..self.len()).map(move |idx| match self {229 ArrValue::Lazy(l) => l[idx].evaluate(),230 ArrValue::Eager(e) => Ok(e[idx].clone()),231 })232 }233234 pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {235 (0..self.len()).map(move |idx| match self {236 ArrValue::Lazy(l) => l[idx].clone(),237 ArrValue::Eager(e) => LazyVal::new_resolved(e[idx].clone()),238 })239 }240241 pub fn reversed(self) -> Self {242 match self {243 ArrValue::Lazy(vec) => {244 let mut out = (&vec as &Vec<_>).clone();245 out.reverse();246 Self::Lazy(Rc::new(out))247 }248 ArrValue::Eager(vec) => {249 let mut out = (&vec as &Vec<_>).clone();250 out.reverse();251 Self::Eager(Rc::new(out))252 }253 }254 }255}256257impl From<Vec<LazyVal>> for ArrValue {258 fn from(v: Vec<LazyVal>) -> Self {259 Self::Lazy(Rc::new(v))260 }261}262263impl From<Vec<Val>> for ArrValue {264 fn from(v: Vec<Val>) -> Self {265 Self::Eager(Rc::new(v))266 }267}268269#[derive(Debug, Clone)]270pub enum Val {271 Bool(bool),272 Null,273 Str(Rc<str>),274 Num(f64),275 Arr(ArrValue),276 Obj(ObjValue),277 Func(Rc<FuncVal>),278}279280macro_rules! matches_unwrap {281 ($e: expr, $p: pat, $r: expr) => {282 match $e {283 $p => $r,284 _ => panic!("no match"),285 }286 };287}288impl Val {289 /// Creates `Val::Num` after checking for numeric overflow.290 /// As numbers are `f64`, we can just check for their finity.291 pub fn new_checked_num(num: f64) -> Result<Self> {292 if num.is_finite() {293 Ok(Self::Num(num))294 } else {295 throw!(RuntimeError("overflow".into()))296 }297 }298299 pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {300 let this_type = self.value_type();301 if this_type != val_type {302 throw!(TypeMismatch(context, vec![val_type], this_type))303 } else {304 Ok(())305 }306 }307 pub fn unwrap_num(self) -> Result<f64> {308 Ok(matches_unwrap!(self, Self::Num(v), v))309 }310 pub fn unwrap_func(self) -> Result<Rc<FuncVal>> {311 Ok(matches_unwrap!(self, Self::Func(v), v))312 }313 pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {314 self.assert_type(context, ValType::Bool)?;315 Ok(matches_unwrap!(self, Self::Bool(v), v))316 }317 pub fn try_cast_str(self, context: &'static str) -> Result<Rc<str>> {318 self.assert_type(context, ValType::Str)?;319 Ok(matches_unwrap!(self, Self::Str(v), v))320 }321 pub fn try_cast_num(self, context: &'static str) -> Result<f64> {322 self.assert_type(context, ValType::Num)?;323 self.unwrap_num()324 }325 pub fn value_type(&self) -> ValType {326 match self {327 Self::Str(..) => ValType::Str,328 Self::Num(..) => ValType::Num,329 Self::Arr(..) => ValType::Arr,330 Self::Obj(..) => ValType::Obj,331 Self::Bool(_) => ValType::Bool,332 Self::Null => ValType::Null,333 Self::Func(..) => ValType::Func,334 }335 }336337 pub fn to_string(&self) -> Result<Rc<str>> {338 Ok(match self {339 Self::Bool(true) => "true".into(),340 Self::Bool(false) => "false".into(),341 Self::Null => "null".into(),342 Self::Str(s) => s.clone(),343 v => manifest_json_ex(344 &v,345 &ManifestJsonOptions {346 padding: "",347 mtype: ManifestType::ToString,348 },349 )?350 .into(),351 })352 }353354 /// Expects value to be object, outputs (key, manifested value) pairs355 pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(Rc<str>, Rc<str>)>> {356 let obj = match self {357 Self::Obj(obj) => obj,358 _ => throw!(MultiManifestOutputIsNotAObject),359 };360 let keys = obj.visible_fields();361 let mut out = Vec::with_capacity(keys.len());362 for key in keys {363 let value = obj364 .get(key.clone())?365 .expect("item in object")366 .manifest(ty)?;367 out.push((key, value));368 }369 Ok(out)370 }371372 /// Expects value to be array, outputs manifested values373 pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<Rc<str>>> {374 let arr = match self {375 Self::Arr(a) => a,376 _ => throw!(StreamManifestOutputIsNotAArray),377 };378 let mut out = Vec::with_capacity(arr.len());379 for i in arr.iter() {380 out.push(i?.manifest(ty)?);381 }382 Ok(out)383 }384385 pub fn manifest(&self, ty: &ManifestFormat) -> Result<Rc<str>> {386 Ok(match ty {387 ManifestFormat::YamlStream(format) => {388 let arr = match self {389 Self::Arr(a) => a,390 _ => throw!(StreamManifestOutputIsNotAArray),391 };392 let mut out = String::new();393394 match format as &ManifestFormat {395 ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),396 ManifestFormat::String => throw!(StreamManifestCannotNestString),397 _ => {}398 };399400 if !arr.is_empty() {401 for v in arr.iter() {402 out.push_str("---\n");403 out.push_str(&v?.manifest(format)?);404 out.push('\n');405 }406 out.push_str("...");407 }408409 out.into()410 }411 ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,412 ManifestFormat::Json(padding) => self.to_json(*padding)?,413 ManifestFormat::ToString => self.to_string()?,414 ManifestFormat::String => match self {415 Self::Str(s) => s.clone(),416 _ => throw!(StringManifestOutputIsNotAString),417 },418 })419 }420421 /// For manifestification422 pub fn to_json(&self, padding: usize) -> Result<Rc<str>> {423 manifest_json_ex(424 self,425 &ManifestJsonOptions {426 padding: &" ".repeat(padding),427 mtype: if padding == 0 {428 ManifestType::Minify429 } else {430 ManifestType::Manifest431 },432 },433 )434 .map(|s| s.into())435 }436437 /// Calls `std.manifestJson`438 #[cfg(feature = "faster")]439 pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {440 manifest_json_ex(441 self,442 &ManifestJsonOptions {443 padding: &" ".repeat(padding),444 mtype: ManifestType::Std,445 },446 )447 .map(|s| s.into())448 }449450 /// Calls `std.manifestJson`451 #[cfg(not(feature = "faster"))]452 pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {453 with_state(|s| {454 let ctx = s455 .create_default_context()?456 .with_var("__tmp__to_json__".into(), self.clone())?;457 Ok(evaluate(458 ctx,459 &el!(Expr::Apply(460 el!(Expr::Index(461 el!(Expr::Var("std".into())),462 el!(Expr::Str("manifestJsonEx".into()))463 )),464 ArgsDesc(vec![465 Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),466 Arg(None, el!(Expr::Str(" ".repeat(padding).into())))467 ]),468 false469 )),470 )?471 .try_cast_str("to json")?)472 })473 }474 pub fn to_yaml(&self, padding: usize) -> Result<Rc<str>> {475 with_state(|s| {476 let ctx = s477 .create_default_context()?478 .with_var("__tmp__to_json__".into(), self.clone());479 Ok(evaluate(480 ctx,481 &el!(Expr::Apply(482 el!(Expr::Index(483 el!(Expr::Var("std".into())),484 el!(Expr::Str("manifestYamlDoc".into()))485 )),486 ArgsDesc(vec![487 Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),488 Arg(489 None,490 el!(Expr::Literal(if padding != 0 {491 LiteralType::True492 } else {493 LiteralType::False494 }))495 )496 ]),497 false498 )),499 )?500 .try_cast_str("to json")?)501 })502 }503}504505const fn is_function_like(val: &Val) -> bool {506 matches!(val, Val::Func(_))507}508509/// Native implementation of `std.primitiveEquals`510pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {511 Ok(match (val_a, val_b) {512 (Val::Bool(a), Val::Bool(b)) => a == b,513 (Val::Null, Val::Null) => true,514 (Val::Str(a), Val::Str(b)) => a == b,515 (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,516 (Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(517 "primitiveEquals operates on primitive types, got array".into(),518 )),519 (Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(520 "primitiveEquals operates on primitive types, got object".into(),521 )),522 (a, b) if is_function_like(&a) && is_function_like(&b) => {523 throw!(RuntimeError("cannot test equality of functions".into()))524 }525 (_, _) => false,526 })527}528529/// Native implementation of `std.equals`530pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {531 if val_a.value_type() != val_b.value_type() {532 return Ok(false);533 }534 match (val_a, val_b) {535 // Cant test for ptr equality, because all fields needs to be evaluated536 (Val::Arr(a), Val::Arr(b)) => {537 if a.len() != b.len() {538 return Ok(false);539 }540 for (a, b) in a.iter().zip(b.iter()) {541 if !equals(&a?, &b?)? {542 return Ok(false);543 }544 }545 Ok(true)546 }547 (Val::Obj(a), Val::Obj(b)) => {548 let fields = a.visible_fields();549 if fields != b.visible_fields() {550 return Ok(false);551 }552 for field in fields {553 if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {554 return Ok(false);555 }556 }557 Ok(true)558 }559 (a, b) => Ok(primitive_equals(&a, &b)?),560 }561}1use crate::{2 builtin::{3 call_builtin,4 manifest::{manifest_json_ex, ManifestJsonOptions, ManifestType},5 },6 error::Error::*,7 evaluate,8 function::{parse_function_call, parse_function_call_map, place_args},9 native::NativeCallback,10 throw, with_state, Context, ObjValue, Result,11};12use jrsonnet_interner::IStr;13use jrsonnet_parser::{el, Arg, ArgsDesc, Expr, ExprLocation, LiteralType, LocExpr, ParamsDesc};14use jrsonnet_types::ValType;15use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};1617enum LazyValInternals {18 Computed(Val),19 Waiting(Box<dyn Fn() -> Result<Val>>),20}21#[derive(Clone)]22pub struct LazyVal(Rc<RefCell<LazyValInternals>>);23impl LazyVal {24 pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {25 Self(Rc::new(RefCell::new(LazyValInternals::Waiting(f))))26 }27 pub fn new_resolved(val: Val) -> Self {28 Self(Rc::new(RefCell::new(LazyValInternals::Computed(val))))29 }30 pub fn evaluate(&self) -> Result<Val> {31 let new_value = match &*self.0.borrow() {32 LazyValInternals::Computed(v) => return Ok(v.clone()),33 LazyValInternals::Waiting(f) => f()?,34 };35 *self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());36 Ok(new_value)37 }38}3940#[macro_export]41macro_rules! lazy_val {42 ($f: expr) => {43 $crate::LazyVal::new(Box::new($f))44 };45}46#[macro_export]47macro_rules! resolved_lazy_val {48 ($f: expr) => {49 $crate::LazyVal::new_resolved($f)50 };51}52impl Debug for LazyVal {53 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {54 write!(f, "Lazy")55 }56}57impl PartialEq for LazyVal {58 fn eq(&self, other: &Self) -> bool {59 Rc::ptr_eq(&self.0, &other.0)60 }61}6263#[derive(Debug, PartialEq)]64pub struct FuncDesc {65 pub name: IStr,66 pub ctx: Context,67 pub params: ParamsDesc,68 pub body: LocExpr,69}7071#[derive(Debug)]72pub enum FuncVal {73 /// Plain function implemented in jsonnet74 Normal(FuncDesc),75 /// Standard library function76 Intrinsic(IStr),77 /// Library functions implemented in native78 NativeExt(IStr, Rc<NativeCallback>),79}8081impl PartialEq for FuncVal {82 fn eq(&self, other: &Self) -> bool {83 match (self, other) {84 (Self::Normal(a), Self::Normal(b)) => a == b,85 (Self::Intrinsic(an), Self::Intrinsic(bn)) => an == bn,86 (Self::NativeExt(an, _), Self::NativeExt(bn, _)) => an == bn,87 (..) => false,88 }89 }90}91impl FuncVal {92 pub fn is_ident(&self) -> bool {93 matches!(&self, Self::Intrinsic(n) if n as &str == "id")94 }95 pub fn name(&self) -> IStr {96 match self {97 Self::Normal(normal) => normal.name.clone(),98 Self::Intrinsic(name) => format!("std.{}", name).into(),99 Self::NativeExt(n, _) => format!("native.{}", n).into(),100 }101 }102 pub fn evaluate(103 &self,104 call_ctx: Context,105 loc: &Option<ExprLocation>,106 args: &ArgsDesc,107 tailstrict: bool,108 ) -> Result<Val> {109 match self {110 Self::Normal(func) => {111 let ctx = parse_function_call(112 call_ctx,113 Some(func.ctx.clone()),114 &func.params,115 args,116 tailstrict,117 )?;118 evaluate(ctx, &func.body)119 }120 Self::Intrinsic(name) => call_builtin(call_ctx, loc, name, args),121 Self::NativeExt(_name, handler) => {122 let args = parse_function_call(call_ctx, None, &handler.params, args, true)?;123 let mut out_args = Vec::with_capacity(handler.params.len());124 for p in handler.params.0.iter() {125 out_args.push(args.binding(p.0.clone())?.evaluate()?);126 }127 Ok(handler.call(&out_args)?)128 }129 }130 }131132 pub fn evaluate_map(133 &self,134 call_ctx: Context,135 args: &HashMap<IStr, Val>,136 tailstrict: bool,137 ) -> Result<Val> {138 match self {139 Self::Normal(func) => {140 let ctx = parse_function_call_map(141 call_ctx,142 Some(func.ctx.clone()),143 &func.params,144 args,145 tailstrict,146 )?;147 evaluate(ctx, &func.body)148 }149 Self::Intrinsic(_) => todo!(),150 Self::NativeExt(_, _) => todo!(),151 }152 }153154 pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {155 match self {156 Self::Normal(func) => {157 let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;158 evaluate(ctx, &func.body)159 }160 Self::Intrinsic(_) => todo!(),161 Self::NativeExt(_, _) => todo!(),162 }163 }164}165166#[derive(Clone)]167pub enum ManifestFormat {168 YamlStream(Box<ManifestFormat>),169 Yaml(usize),170 Json(usize),171 ToString,172 String,173}174175#[derive(Debug, Clone)]176pub enum ArrValue {177 Lazy(Rc<Vec<LazyVal>>),178 Eager(Rc<Vec<Val>>),179}180impl ArrValue {181 pub fn len(&self) -> usize {182 match self {183 ArrValue::Lazy(l) => l.len(),184 ArrValue::Eager(e) => e.len(),185 }186 }187188 pub fn is_empty(&self) -> bool {189 self.len() == 0190 }191192 pub fn get(&self, index: usize) -> Result<Option<Val>> {193 match self {194 ArrValue::Lazy(vec) => {195 if let Some(v) = vec.get(index) {196 Ok(Some(v.evaluate()?))197 } else {198 Ok(None)199 }200 }201 ArrValue::Eager(vec) => Ok(vec.get(index).cloned()),202 }203 }204205 pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {206 match self {207 ArrValue::Lazy(vec) => vec.get(index).cloned(),208 ArrValue::Eager(vec) => vec209 .get(index)210 .cloned()211 .map(|val| LazyVal::new_resolved(val)),212 }213 }214215 pub fn evaluated(&self) -> Result<Rc<Vec<Val>>> {216 Ok(match self {217 ArrValue::Lazy(vec) => {218 let mut out = Vec::with_capacity(vec.len());219 for item in vec.iter() {220 out.push(item.evaluate()?);221 }222 Rc::new(out)223 }224 ArrValue::Eager(vec) => vec.clone(),225 })226 }227228 pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {229 (0..self.len()).map(move |idx| match self {230 ArrValue::Lazy(l) => l[idx].evaluate(),231 ArrValue::Eager(e) => Ok(e[idx].clone()),232 })233 }234235 pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {236 (0..self.len()).map(move |idx| match self {237 ArrValue::Lazy(l) => l[idx].clone(),238 ArrValue::Eager(e) => LazyVal::new_resolved(e[idx].clone()),239 })240 }241242 pub fn reversed(self) -> Self {243 match self {244 ArrValue::Lazy(vec) => {245 let mut out = (&vec as &Vec<_>).clone();246 out.reverse();247 Self::Lazy(Rc::new(out))248 }249 ArrValue::Eager(vec) => {250 let mut out = (&vec as &Vec<_>).clone();251 out.reverse();252 Self::Eager(Rc::new(out))253 }254 }255 }256}257258impl From<Vec<LazyVal>> for ArrValue {259 fn from(v: Vec<LazyVal>) -> Self {260 Self::Lazy(Rc::new(v))261 }262}263264impl From<Vec<Val>> for ArrValue {265 fn from(v: Vec<Val>) -> Self {266 Self::Eager(Rc::new(v))267 }268}269270#[derive(Debug, Clone)]271pub enum Val {272 Bool(bool),273 Null,274 Str(IStr),275 Num(f64),276 Arr(ArrValue),277 Obj(ObjValue),278 Func(Rc<FuncVal>),279}280281macro_rules! matches_unwrap {282 ($e: expr, $p: pat, $r: expr) => {283 match $e {284 $p => $r,285 _ => panic!("no match"),286 }287 };288}289impl Val {290 /// Creates `Val::Num` after checking for numeric overflow.291 /// As numbers are `f64`, we can just check for their finity.292 pub fn new_checked_num(num: f64) -> Result<Self> {293 if num.is_finite() {294 Ok(Self::Num(num))295 } else {296 throw!(RuntimeError("overflow".into()))297 }298 }299300 pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {301 let this_type = self.value_type();302 if this_type != val_type {303 throw!(TypeMismatch(context, vec![val_type], this_type))304 } else {305 Ok(())306 }307 }308 pub fn unwrap_num(self) -> Result<f64> {309 Ok(matches_unwrap!(self, Self::Num(v), v))310 }311 pub fn unwrap_func(self) -> Result<Rc<FuncVal>> {312 Ok(matches_unwrap!(self, Self::Func(v), v))313 }314 pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {315 self.assert_type(context, ValType::Bool)?;316 Ok(matches_unwrap!(self, Self::Bool(v), v))317 }318 pub fn try_cast_str(self, context: &'static str) -> Result<IStr> {319 self.assert_type(context, ValType::Str)?;320 Ok(matches_unwrap!(self, Self::Str(v), v))321 }322 pub fn try_cast_num(self, context: &'static str) -> Result<f64> {323 self.assert_type(context, ValType::Num)?;324 self.unwrap_num()325 }326 pub fn value_type(&self) -> ValType {327 match self {328 Self::Str(..) => ValType::Str,329 Self::Num(..) => ValType::Num,330 Self::Arr(..) => ValType::Arr,331 Self::Obj(..) => ValType::Obj,332 Self::Bool(_) => ValType::Bool,333 Self::Null => ValType::Null,334 Self::Func(..) => ValType::Func,335 }336 }337338 pub fn to_string(&self) -> Result<IStr> {339 Ok(match self {340 Self::Bool(true) => "true".into(),341 Self::Bool(false) => "false".into(),342 Self::Null => "null".into(),343 Self::Str(s) => s.clone(),344 v => manifest_json_ex(345 &v,346 &ManifestJsonOptions {347 padding: "",348 mtype: ManifestType::ToString,349 },350 )?351 .into(),352 })353 }354355 /// Expects value to be object, outputs (key, manifested value) pairs356 pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {357 let obj = match self {358 Self::Obj(obj) => obj,359 _ => throw!(MultiManifestOutputIsNotAObject),360 };361 let keys = obj.visible_fields();362 let mut out = Vec::with_capacity(keys.len());363 for key in keys {364 let value = obj365 .get(key.clone())?366 .expect("item in object")367 .manifest(ty)?;368 out.push((key, value));369 }370 Ok(out)371 }372373 /// Expects value to be array, outputs manifested values374 pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<IStr>> {375 let arr = match self {376 Self::Arr(a) => a,377 _ => throw!(StreamManifestOutputIsNotAArray),378 };379 let mut out = Vec::with_capacity(arr.len());380 for i in arr.iter() {381 out.push(i?.manifest(ty)?);382 }383 Ok(out)384 }385386 pub fn manifest(&self, ty: &ManifestFormat) -> Result<IStr> {387 Ok(match ty {388 ManifestFormat::YamlStream(format) => {389 let arr = match self {390 Self::Arr(a) => a,391 _ => throw!(StreamManifestOutputIsNotAArray),392 };393 let mut out = String::new();394395 match format as &ManifestFormat {396 ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),397 ManifestFormat::String => throw!(StreamManifestCannotNestString),398 _ => {}399 };400401 if !arr.is_empty() {402 for v in arr.iter() {403 out.push_str("---\n");404 out.push_str(&v?.manifest(format)?);405 out.push('\n');406 }407 out.push_str("...");408 }409410 out.into()411 }412 ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,413 ManifestFormat::Json(padding) => self.to_json(*padding)?,414 ManifestFormat::ToString => self.to_string()?,415 ManifestFormat::String => match self {416 Self::Str(s) => s.clone(),417 _ => throw!(StringManifestOutputIsNotAString),418 },419 })420 }421422 /// For manifestification423 pub fn to_json(&self, padding: usize) -> Result<IStr> {424 manifest_json_ex(425 self,426 &ManifestJsonOptions {427 padding: &" ".repeat(padding),428 mtype: if padding == 0 {429 ManifestType::Minify430 } else {431 ManifestType::Manifest432 },433 },434 )435 .map(|s| s.into())436 }437438 /// Calls `std.manifestJson`439 #[cfg(feature = "faster")]440 pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {441 manifest_json_ex(442 self,443 &ManifestJsonOptions {444 padding: &" ".repeat(padding),445 mtype: ManifestType::Std,446 },447 )448 .map(|s| s.into())449 }450451 /// Calls `std.manifestJson`452 #[cfg(not(feature = "faster"))]453 pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {454 with_state(|s| {455 let ctx = s456 .create_default_context()?457 .with_var("__tmp__to_json__".into(), self.clone())?;458 Ok(evaluate(459 ctx,460 &el!(Expr::Apply(461 el!(Expr::Index(462 el!(Expr::Var("std".into())),463 el!(Expr::Str("manifestJsonEx".into()))464 )),465 ArgsDesc(vec![466 Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),467 Arg(None, el!(Expr::Str(" ".repeat(padding).into())))468 ]),469 false470 )),471 )?472 .try_cast_str("to json")?)473 })474 }475 pub fn to_yaml(&self, padding: usize) -> Result<IStr> {476 with_state(|s| {477 let ctx = s478 .create_default_context()?479 .with_var("__tmp__to_json__".into(), self.clone());480 Ok(evaluate(481 ctx,482 &el!(Expr::Apply(483 el!(Expr::Index(484 el!(Expr::Var("std".into())),485 el!(Expr::Str("manifestYamlDoc".into()))486 )),487 ArgsDesc(vec![488 Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),489 Arg(490 None,491 el!(Expr::Literal(if padding != 0 {492 LiteralType::True493 } else {494 LiteralType::False495 }))496 )497 ]),498 false499 )),500 )?501 .try_cast_str("to json")?)502 })503 }504}505506const fn is_function_like(val: &Val) -> bool {507 matches!(val, Val::Func(_))508}509510/// Native implementation of `std.primitiveEquals`511pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {512 Ok(match (val_a, val_b) {513 (Val::Bool(a), Val::Bool(b)) => a == b,514 (Val::Null, Val::Null) => true,515 (Val::Str(a), Val::Str(b)) => a == b,516 (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,517 (Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(518 "primitiveEquals operates on primitive types, got array".into(),519 )),520 (Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(521 "primitiveEquals operates on primitive types, got object".into(),522 )),523 (a, b) if is_function_like(&a) && is_function_like(&b) => {524 throw!(RuntimeError("cannot test equality of functions".into()))525 }526 (_, _) => false,527 })528}529530/// Native implementation of `std.equals`531pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {532 if val_a.value_type() != val_b.value_type() {533 return Ok(false);534 }535 match (val_a, val_b) {536 // Cant test for ptr equality, because all fields needs to be evaluated537 (Val::Arr(a), Val::Arr(b)) => {538 if a.len() != b.len() {539 return Ok(false);540 }541 for (a, b) in a.iter().zip(b.iter()) {542 if !equals(&a?, &b?)? {543 return Ok(false);544 }545 }546 Ok(true)547 }548 (Val::Obj(a), Val::Obj(b)) => {549 let fields = a.visible_fields();550 if fields != b.visible_fields() {551 return Ok(false);552 }553 for field in fields {554 if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {555 return Ok(false);556 }557 }558 Ok(true)559 }560 (a, b) => Ok(primitive_equals(&a, &b)?),561 }562}crates/jrsonnet-interner/.gitignorediffbeforeafterboth--- /dev/null
+++ b/crates/jrsonnet-interner/.gitignore
@@ -0,0 +1,2 @@
+/target
+Cargo.lock
crates/jrsonnet-interner/Cargo.tomldiffbeforeafterboth--- /dev/null
+++ b/crates/jrsonnet-interner/Cargo.toml
@@ -0,0 +1,9 @@
+[package]
+name = "jrsonnet-interner"
+version = "0.3.3"
+authors = ["Yaroslav Bolyukin <iam@lach.pw>"]
+edition = "2018"
+
+[dependencies]
+serde = { version = "1.0" }
+rustc-hash = "1.1.0"
crates/jrsonnet-interner/src/lib.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/jrsonnet-interner/src/lib.rs
@@ -0,0 +1,104 @@
+use rustc_hash::FxHashMap;
+use serde::{Deserialize, Serialize};
+use std::{
+ cell::RefCell,
+ fmt::{self, Display},
+ hash::{BuildHasherDefault, Hash, Hasher},
+ ops::Deref,
+ rc::Rc,
+};
+
+#[derive(Clone, PartialOrd, Ord, Eq)]
+pub struct IStr(Rc<str>);
+
+impl Deref for IStr {
+ type Target = str;
+
+ fn deref(&self) -> &Self::Target {
+ &self.0
+ }
+}
+
+impl PartialEq for IStr {
+ fn eq(&self, other: &Self) -> bool {
+ // It is ok, since all IStr should be inlined into same pool
+ Rc::ptr_eq(&self.0, &other.0)
+ }
+}
+
+impl PartialEq<str> for IStr {
+ fn eq(&self, other: &str) -> bool {
+ &self.0 as &str == other
+ }
+}
+
+impl Hash for IStr {
+ fn hash<H: Hasher>(&self, state: &mut H) {
+ state.write_usize(Rc::as_ptr(&self.0) as *const () as usize)
+ }
+}
+
+impl Drop for IStr {
+ fn drop(&mut self) {
+ // First reference - current object, second - POOL
+ if Rc::strong_count(&self.0) <= 2 {
+ STR_POOL.with(|pool| pool.borrow_mut().remove(&self.0));
+ }
+ }
+}
+
+impl fmt::Debug for IStr {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{:?}", &self.0)
+ }
+}
+
+impl Display for IStr {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(&self.0)
+ }
+}
+
+thread_local! {
+ static STR_POOL: RefCell<FxHashMap<Rc<str>, ()>> = RefCell::new(FxHashMap::with_capacity_and_hasher(200, BuildHasherDefault::default()));
+}
+
+impl From<&str> for IStr {
+ fn from(str: &str) -> Self {
+ IStr(STR_POOL.with(|pool| {
+ let mut pool = pool.borrow_mut();
+ if let Some((k, _)) = pool.get_key_value(str) {
+ return k.clone();
+ } else {
+ let rc: Rc<str> = str.into();
+ pool.insert(rc.clone(), ());
+ rc
+ }
+ }))
+ }
+}
+
+impl From<String> for IStr {
+ fn from(str: String) -> Self {
+ (&str as &str).into()
+ }
+}
+
+impl Serialize for IStr {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: serde::Serializer,
+ {
+ (&self.0 as &str).serialize(serializer)
+ }
+}
+
+impl<'de> Deserialize<'de> for IStr {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ let s = <&str>::deserialize(deserializer)?;
+ Ok(s.into())
+ }
+}
crates/jrsonnet-parser/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-parser/Cargo.toml
+++ b/crates/jrsonnet-parser/Cargo.toml
@@ -10,16 +10,14 @@
default = []
serialize = ["serde"]
deserialize = ["serde"]
-# Adds ability to dump AST as source code for easy embedding
-dump = ["structdump", "structdump-derive"]
[dependencies]
+jrsonnet-interner = { path = "../jrsonnet-interner" }
+
peg = "0.6.3"
unescape = "0.1.0"
serde = { version = "1.0", features = ["derive", "rc"], optional = true }
-structdump = { version = "0.1.2", optional = true }
-structdump-derive = { version = "0.1.2", optional = true }
[dev-dependencies]
jrsonnet-stdlib = { path = "../jrsonnet-stdlib", version = "0.3.3" }
crates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/expr.rs
+++ b/crates/jrsonnet-parser/src/expr.rs
@@ -1,3 +1,4 @@
+use jrsonnet_interner::IStr;
#[cfg(feature = "deserialize")]
use serde::Deserialize;
#[cfg(feature = "serialize")]
@@ -8,21 +9,17 @@
path::PathBuf,
rc::Rc,
};
-#[cfg(feature = "dump")]
-use structdump_derive::Codegen;
-#[cfg_attr(feature = "dump", derive(Codegen))]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[derive(Debug, PartialEq)]
pub enum FieldName {
/// {fixed: 2}
- Fixed(Rc<str>),
+ Fixed(IStr),
/// {["dyn"+"amic"]: 3}
Dyn(LocExpr),
}
-#[cfg_attr(feature = "dump", derive(Codegen))]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq)]
@@ -35,13 +32,11 @@
Unhide,
}
-#[cfg_attr(feature = "dump", derive(Codegen))]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[derive(Debug, PartialEq)]
pub struct AssertStmt(pub LocExpr, pub Option<LocExpr>);
-#[cfg_attr(feature = "dump", derive(Codegen))]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[derive(Debug, PartialEq)]
@@ -53,7 +48,6 @@
pub value: LocExpr,
}
-#[cfg_attr(feature = "dump", derive(Codegen))]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[derive(Debug, PartialEq)]
@@ -63,7 +57,6 @@
AssertStmt(AssertStmt),
}
-#[cfg_attr(feature = "dump", derive(Codegen))]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq)]
@@ -89,7 +82,6 @@
}
}
-#[cfg_attr(feature = "dump", derive(Codegen))]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq)]
@@ -147,14 +139,12 @@
}
/// name, default value
-#[cfg_attr(feature = "dump", derive(Codegen))]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[derive(Debug, PartialEq)]
-pub struct Param(pub Rc<str>, pub Option<LocExpr>);
+pub struct Param(pub IStr, pub Option<LocExpr>);
/// Defined function parameters
-#[cfg_attr(feature = "dump", derive(Codegen))]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[derive(Debug, Clone, PartialEq)]
@@ -166,13 +156,11 @@
}
}
-#[cfg_attr(feature = "dump", derive(Codegen))]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[derive(Debug, PartialEq)]
pub struct Arg(pub Option<String>, pub LocExpr);
-#[cfg_attr(feature = "dump", derive(Codegen))]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[derive(Debug, PartialEq)]
@@ -184,29 +172,25 @@
}
}
-#[cfg_attr(feature = "dump", derive(Codegen))]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub struct BindSpec {
- pub name: Rc<str>,
+ pub name: IStr,
pub params: Option<ParamsDesc>,
pub value: LocExpr,
}
-#[cfg_attr(feature = "dump", derive(Codegen))]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[derive(Debug, PartialEq)]
pub struct IfSpecData(pub LocExpr);
-#[cfg_attr(feature = "dump", derive(Codegen))]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[derive(Debug, PartialEq)]
-pub struct ForSpecData(pub Rc<str>, pub LocExpr);
+pub struct ForSpecData(pub IStr, pub LocExpr);
-#[cfg_attr(feature = "dump", derive(Codegen))]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[derive(Debug, PartialEq)]
@@ -215,7 +199,6 @@
ForSpec(ForSpecData),
}
-#[cfg_attr(feature = "dump", derive(Codegen))]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[derive(Debug, PartialEq)]
@@ -227,7 +210,6 @@
pub compspecs: Vec<CompSpec>,
}
-#[cfg_attr(feature = "dump", derive(Codegen))]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[derive(Debug, PartialEq)]
@@ -236,7 +218,6 @@
ObjComp(ObjComp),
}
-#[cfg_attr(feature = "dump", derive(Codegen))]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[derive(Debug, PartialEq, Clone, Copy)]
@@ -257,7 +238,6 @@
}
/// Syntax base
-#[cfg_attr(feature = "dump", derive(Codegen))]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[derive(Debug, PartialEq)]
@@ -265,11 +245,11 @@
Literal(LiteralType),
/// String value: "hello"
- Str(Rc<str>),
+ Str(IStr),
/// Number: 1, 2.0, 2e+20
Num(f64),
/// Variable name: test
- Var(Rc<str>),
+ Var(IStr),
/// Array of expressions: [1, 2, "Hello"]
Arr(Vec<LocExpr>),
@@ -316,7 +296,7 @@
/// function(x) x
Function(ParamsDesc, LocExpr),
/// std.primitiveEquals
- Intrinsic(Rc<str>),
+ Intrinsic(IStr),
/// if true == false then 1 else 2
IfElse {
cond: IfSpecData,
@@ -326,7 +306,6 @@
}
/// file, begin offset, end offset
-#[cfg_attr(feature = "dump", derive(Codegen))]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[derive(Clone, PartialEq)]
@@ -338,7 +317,6 @@
}
/// Holds AST expression and its location in source file
-#[cfg_attr(feature = "dump", derive(Codegen))]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[derive(Clone, PartialEq)]