difftreelog
refactor drop ArgsLike abstraction
in: master
17 files changed
bindings/jsonnet/src/lib.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -22,11 +22,11 @@
use jrsonnet_evaluator::{
apply_tla, bail,
- function::TlaArg,
gc::WithCapacityExt as _,
manifest::{JsonFormat, ManifestFormat, ToStringFormat},
rustc_hash::FxHashMap,
stack::set_stack_depth_limit,
+ tla::TlaArg,
trace::{CompactFormat, PathResolver, TraceFormat},
AsPathLike, FileImportResolver, IStr, ImportResolver, Result, State, Val,
};
@@ -40,6 +40,7 @@
pub extern "C" fn _start() {}
/// Return the version string of the Jsonnet interpreter.
+///
/// Conforms to [semantic versioning](http://semver.org/).
/// If this does not match `LIB_JSONNET_VERSION`
/// then there is a mismatch between header and compiled library.
bindings/jsonnet/src/vars_tlas.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/vars_tlas.rs
+++ b/bindings/jsonnet/src/vars_tlas.rs
@@ -2,7 +2,8 @@
use std::{ffi::CStr, os::raw::c_char};
-use jrsonnet_evaluator::{function::TlaArg, IStr};
+use jrsonnet_evaluator::tla::TlaArg;
+use jrsonnet_evaluator::IStr;
use crate::VM;
crates/jrsonnet-cli/src/stdlib.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/stdlib.rs
+++ b/crates/jrsonnet-cli/src/stdlib.rs
@@ -1,7 +1,8 @@
use std::str::FromStr;
use clap::Parser;
-use jrsonnet_evaluator::{function::TlaArg, trace::PathResolver, Result};
+use jrsonnet_evaluator::tla::TlaArg;
+use jrsonnet_evaluator::{trace::PathResolver, Result};
use jrsonnet_stdlib::ContextInitializer;
#[derive(Clone)]
crates/jrsonnet-cli/src/tla.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/tla.rs
+++ b/crates/jrsonnet-cli/src/tla.rs
@@ -1,7 +1,6 @@
use clap::Parser;
-use jrsonnet_evaluator::{
- error::Result, function::TlaArg, gc::WithCapacityExt as _, rustc_hash::FxHashMap, IStr,
-};
+use jrsonnet_evaluator::tla::TlaArg;
+use jrsonnet_evaluator::{error::Result, gc::WithCapacityExt as _, rustc_hash::FxHashMap, IStr};
use crate::{ExtFile, ExtStr};
crates/jrsonnet-evaluator/src/arr/mod.rsdiffbeforeafterboth1use std::{2 any::Any,3 fmt::{self},4 num::NonZeroU32,5 rc::Rc,6};78use jrsonnet_gcmodule::{cc_dyn, Cc};9use jrsonnet_interner::IBytes;10use jrsonnet_parser::{Expr, Spanned};1112use crate::{typed::NativeFn, Context, Result, Thunk, Val};1314mod spec;15pub use spec::{ArrayLike, *};1617cc_dyn!(18 #[doc = "Represents a Jsonnet array value."]19 #[derive(Clone)]20 ArrValue,21 ArrayLike,22 pub fn new() {...}23);24impl fmt::Debug for ArrValue {25 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {26 self.0.fmt(f)27 }28}2930pub trait ArrayLikeIter<T>: Iterator<Item = T> + DoubleEndedIterator + ExactSizeIterator {}31impl<I, T> ArrayLikeIter<T> for I where32 I: Iterator<Item = T> + DoubleEndedIterator + ExactSizeIterator33{34}3536impl ArrValue {37 pub fn empty() -> Self {38 Self::new(RangeArray::empty())39 }4041 pub fn expr(ctx: Context, exprs: Rc<Vec<Spanned<Expr>>>) -> Self {42 Self::new(ExprArray::new(ctx, exprs))43 }4445 pub fn lazy(thunks: Vec<Thunk<Val>>) -> Self {46 Self::new(LazyArray(thunks))47 }4849 pub fn eager(values: Vec<Val>) -> Self {50 Self::new(EagerArray(values))51 }5253 pub fn repeated(data: Self, repeats: usize) -> Option<Self> {54 Some(Self::new(RepeatedArray::new(data, repeats)?))55 }5657 pub fn bytes(bytes: IBytes) -> Self {58 Self::new(BytesArray(bytes))59 }60 pub fn chars(chars: impl Iterator<Item = char>) -> Self {61 Self::new(CharArray(chars.collect()))62 }6364 #[must_use]65 pub fn map(self, mapper: NativeFn!((Val) -> Val)) -> Self {66 Self::new(<MappedArray>::new(self, ArrayMapper::Plain(mapper)))67 }6869 #[must_use]70 pub fn map_with_index(self, mapper: NativeFn!((u32, Val) -> Val)) -> Self {71 Self::new(<MappedArray>::new(self, ArrayMapper::WithIndex(mapper)))72 }7374 pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {75 // TODO: ArrValue::Picked(inner, indexes) for large arrays76 let mut out = Vec::new();77 for i in self.iter() {78 let i = i?;79 if filter(&i)? {80 out.push(i);81 }82 }83 Ok(Self::eager(out))84 }8586 pub fn extended(a: Self, b: Self) -> Self {87 // TODO: benchmark for an optimal value, currently just a arbitrary choice88 const ARR_EXTEND_THRESHOLD: usize = 100;8990 if a.is_empty() {91 b92 } else if b.is_empty() {93 a94 } else if a.len() + b.len() > ARR_EXTEND_THRESHOLD {95 Self::new(ExtendedArray::new(a, b))96 } else if let (Some(a), Some(b)) = (a.iter_cheap(), b.iter_cheap()) {97 let mut out = Vec::with_capacity(a.len() + b.len());98 out.extend(a);99 out.extend(b);100 Self::eager(out)101 } else {102 let mut out = Vec::with_capacity(a.len() + b.len());103 out.extend(a.iter_lazy());104 out.extend(b.iter_lazy());105 Self::lazy(out)106 }107 }108109 pub fn range_exclusive(a: i32, b: i32) -> Self {110 Self::new(RangeArray::new_exclusive(a, b))111 }112 pub fn range_inclusive(a: i32, b: i32) -> Self {113 Self::new(RangeArray::new_inclusive(a, b))114 }115116 #[must_use]117 pub fn slice(self, index: Option<i32>, end: Option<i32>, step: Option<NonZeroU32>) -> Self {118 let get_idx = |pos: Option<i32>, len: usize, default| match pos {119 Some(v) if v < 0 => len.saturating_sub((-v) as usize),120 Some(v) => (v as usize).min(len),121 None => default,122 };123 let index = get_idx(index, self.len(), 0);124 let end = get_idx(end, self.len(), self.len());125 let step = step.unwrap_or_else(|| NonZeroU32::new(1).expect("1 != 0"));126127 if index >= end {128 return Self::empty();129 }130131 Self::new(SliceArray {132 inner: self,133 from: index as u32,134 to: end as u32,135 step: step.get(),136 })137 }138139 /// Array length.140 pub fn len(&self) -> usize {141 self.0.len()142 }143144 /// Is array contains no elements?145 pub fn is_empty(&self) -> bool {146 self.0.is_empty()147 }148149 /// Get array element by index, evaluating it, if it is lazy.150 ///151 /// Returns `None` on out-of-bounds condition.152 pub fn get(&self, index: usize) -> Result<Option<Val>> {153 self.0.get(index)154 }155156 /// Returns None if get is either non cheap, or out of bounds157 /// Note that non-cheap access includes errorable values158 ///159 /// Prefer it to `get_lazy`, but use `get` when you can.160 fn get_cheap(&self, index: usize) -> Option<Val> {161 self.0.get_cheap(index)162 }163164 /// Get array element by index, without evaluation.165 ///166 /// Returns `None` on out-of-bounds condition.167 pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {168 self.0.get_lazy(index)169 }170171 pub fn iter(&self) -> impl ArrayLikeIter<Result<Val>> + '_ {172 (0..self.len()).map(|i| self.get(i).transpose().expect("length checked"))173 }174175 /// Iterate over elements, returning lazy values.176 pub fn iter_lazy(&self) -> impl ArrayLikeIter<Thunk<Val>> + '_ {177 (0..self.len()).map(|i| self.get_lazy(i).expect("length checked"))178 }179180 /// Prefer it over `iter_lazy`, but do not use it where `iter` will do.181 pub fn iter_cheap(&self) -> Option<impl ArrayLikeIter<Val> + '_> {182 if self.is_cheap() {183 Some((0..self.len()).map(|i| self.get_cheap(i).expect("length and is_cheap checked")))184 } else {185 None186 }187 }188189 /// Return a reversed view on current array.190 #[must_use]191 pub fn reversed(self) -> Self {192 Self::new(ReverseArray(self))193 }194195 pub fn ptr_eq(a: &Self, b: &Self) -> bool {196 Cc::ptr_eq(&a.0, &b.0)197 }198199 /// Is this vec supports `.get_cheap()?`200 pub fn is_cheap(&self) -> bool {201 self.0.is_cheap()202 }203204 pub fn as_any(&self) -> &dyn Any {205 &self.0206 }207}208impl From<Vec<Val>> for ArrValue {209 fn from(value: Vec<Val>) -> Self {210 Self::eager(value)211 }212}213impl From<Vec<Thunk<Val>>> for ArrValue {214 fn from(value: Vec<Thunk<Val>>) -> Self {215 Self::lazy(value)216 }217}218impl FromIterator<Val> for ArrValue {219 fn from_iter<T: IntoIterator<Item = Val>>(iter: T) -> Self {220 Self::eager(iter.into_iter().collect())221 }222}223impl ArrayLike for ArrValue {224 fn len(&self) -> usize {225 self.0.len()226 }227228 fn get(&self, index: usize) -> Result<Option<Val>> {229 self.0.get(index)230 }231232 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {233 self.0.get_lazy(index)234 }235236 fn get_cheap(&self, index: usize) -> Option<Val> {237 self.0.get_cheap(index)238 }239240 fn is_cheap(&self) -> bool {241 self.0.is_cheap()242 }243}1use std::{2 any::Any,3 fmt::{self},4 num::NonZeroU32,5 rc::Rc,6};78use jrsonnet_gcmodule::{cc_dyn, Cc};9use jrsonnet_interner::IBytes;10use jrsonnet_parser::{Expr, Spanned};1112use crate::{function::NativeFn, Context, Result, Thunk, Val};1314mod spec;15pub use spec::{ArrayLike, *};1617cc_dyn!(18 #[doc = "Represents a Jsonnet array value."]19 #[derive(Clone)]20 ArrValue,21 ArrayLike,22 pub fn new() {...}23);24impl fmt::Debug for ArrValue {25 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {26 self.0.fmt(f)27 }28}2930pub trait ArrayLikeIter<T>: Iterator<Item = T> + DoubleEndedIterator + ExactSizeIterator {}31impl<I, T> ArrayLikeIter<T> for I where32 I: Iterator<Item = T> + DoubleEndedIterator + ExactSizeIterator33{34}3536impl ArrValue {37 pub fn empty() -> Self {38 Self::new(RangeArray::empty())39 }4041 pub fn expr(ctx: Context, exprs: Rc<Vec<Spanned<Expr>>>) -> Self {42 Self::new(ExprArray::new(ctx, exprs))43 }4445 pub fn lazy(thunks: Vec<Thunk<Val>>) -> Self {46 Self::new(LazyArray(thunks))47 }4849 pub fn eager(values: Vec<Val>) -> Self {50 Self::new(EagerArray(values))51 }5253 pub fn repeated(data: Self, repeats: usize) -> Option<Self> {54 Some(Self::new(RepeatedArray::new(data, repeats)?))55 }5657 pub fn bytes(bytes: IBytes) -> Self {58 Self::new(BytesArray(bytes))59 }60 pub fn chars(chars: impl Iterator<Item = char>) -> Self {61 Self::new(CharArray(chars.collect()))62 }6364 #[must_use]65 pub fn map(self, mapper: NativeFn!((Val) -> Val)) -> Self {66 Self::new(<MappedArray>::new(self, ArrayMapper::Plain(mapper)))67 }6869 #[must_use]70 pub fn map_with_index(self, mapper: NativeFn!((u32, Val) -> Val)) -> Self {71 Self::new(<MappedArray>::new(self, ArrayMapper::WithIndex(mapper)))72 }7374 pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {75 // TODO: ArrValue::Picked(inner, indexes) for large arrays76 let mut out = Vec::new();77 for i in self.iter() {78 let i = i?;79 if filter(&i)? {80 out.push(i);81 }82 }83 Ok(Self::eager(out))84 }8586 pub fn extended(a: Self, b: Self) -> Self {87 // TODO: benchmark for an optimal value, currently just a arbitrary choice88 const ARR_EXTEND_THRESHOLD: usize = 100;8990 if a.is_empty() {91 b92 } else if b.is_empty() {93 a94 } else if a.len() + b.len() > ARR_EXTEND_THRESHOLD {95 Self::new(ExtendedArray::new(a, b))96 } else if let (Some(a), Some(b)) = (a.iter_cheap(), b.iter_cheap()) {97 let mut out = Vec::with_capacity(a.len() + b.len());98 out.extend(a);99 out.extend(b);100 Self::eager(out)101 } else {102 let mut out = Vec::with_capacity(a.len() + b.len());103 out.extend(a.iter_lazy());104 out.extend(b.iter_lazy());105 Self::lazy(out)106 }107 }108109 pub fn range_exclusive(a: i32, b: i32) -> Self {110 Self::new(RangeArray::new_exclusive(a, b))111 }112 pub fn range_inclusive(a: i32, b: i32) -> Self {113 Self::new(RangeArray::new_inclusive(a, b))114 }115116 #[must_use]117 pub fn slice(self, index: Option<i32>, end: Option<i32>, step: Option<NonZeroU32>) -> Self {118 let get_idx = |pos: Option<i32>, len: usize, default| match pos {119 Some(v) if v < 0 => len.saturating_sub((-v) as usize),120 Some(v) => (v as usize).min(len),121 None => default,122 };123 let index = get_idx(index, self.len(), 0);124 let end = get_idx(end, self.len(), self.len());125 let step = step.unwrap_or_else(|| NonZeroU32::new(1).expect("1 != 0"));126127 if index >= end {128 return Self::empty();129 }130131 Self::new(SliceArray {132 inner: self,133 from: index as u32,134 to: end as u32,135 step: step.get(),136 })137 }138139 /// Array length.140 pub fn len(&self) -> usize {141 self.0.len()142 }143144 /// Is array contains no elements?145 pub fn is_empty(&self) -> bool {146 self.0.is_empty()147 }148149 /// Get array element by index, evaluating it, if it is lazy.150 ///151 /// Returns `None` on out-of-bounds condition.152 pub fn get(&self, index: usize) -> Result<Option<Val>> {153 self.0.get(index)154 }155156 /// Returns None if get is either non cheap, or out of bounds157 /// Note that non-cheap access includes errorable values158 ///159 /// Prefer it to `get_lazy`, but use `get` when you can.160 fn get_cheap(&self, index: usize) -> Option<Val> {161 self.0.get_cheap(index)162 }163164 /// Get array element by index, without evaluation.165 ///166 /// Returns `None` on out-of-bounds condition.167 pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {168 self.0.get_lazy(index)169 }170171 pub fn iter(&self) -> impl ArrayLikeIter<Result<Val>> + '_ {172 (0..self.len()).map(|i| self.get(i).transpose().expect("length checked"))173 }174175 /// Iterate over elements, returning lazy values.176 pub fn iter_lazy(&self) -> impl ArrayLikeIter<Thunk<Val>> + '_ {177 (0..self.len()).map(|i| self.get_lazy(i).expect("length checked"))178 }179180 /// Prefer it over `iter_lazy`, but do not use it where `iter` will do.181 pub fn iter_cheap(&self) -> Option<impl ArrayLikeIter<Val> + '_> {182 if self.is_cheap() {183 Some((0..self.len()).map(|i| self.get_cheap(i).expect("length and is_cheap checked")))184 } else {185 None186 }187 }188189 /// Return a reversed view on current array.190 #[must_use]191 pub fn reversed(self) -> Self {192 Self::new(ReverseArray(self))193 }194195 pub fn ptr_eq(a: &Self, b: &Self) -> bool {196 Cc::ptr_eq(&a.0, &b.0)197 }198199 /// Is this vec supports `.get_cheap()?`200 pub fn is_cheap(&self) -> bool {201 self.0.is_cheap()202 }203204 pub fn as_any(&self) -> &dyn Any {205 &self.0206 }207}208impl From<Vec<Val>> for ArrValue {209 fn from(value: Vec<Val>) -> Self {210 Self::eager(value)211 }212}213impl From<Vec<Thunk<Val>>> for ArrValue {214 fn from(value: Vec<Thunk<Val>>) -> Self {215 Self::lazy(value)216 }217}218impl FromIterator<Val> for ArrValue {219 fn from_iter<T: IntoIterator<Item = Val>>(iter: T) -> Self {220 Self::eager(iter.into_iter().collect())221 }222}223impl ArrayLike for ArrValue {224 fn len(&self) -> usize {225 self.0.len()226 }227228 fn get(&self, index: usize) -> Result<Option<Val>> {229 self.0.get(index)230 }231232 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {233 self.0.get_lazy(index)234 }235236 fn get_cheap(&self, index: usize) -> Option<Val> {237 self.0.get_cheap(index)238 }239240 fn is_cheap(&self) -> bool {241 self.0.is_cheap()242 }243}crates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/spec.rs
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -6,8 +6,7 @@
use jrsonnet_parser::{Expr, Spanned};
use super::ArrValue;
-use crate::typed::NativeFn;
-use crate::val::NumValue;
+use crate::function::NativeFn;
use crate::{
error::ErrorKind::InfiniteRecursionDetected, evaluate, typed::Typed, val::ThunkValue, Context,
Error, ObjValue, Result, Thunk, Val,
crates/jrsonnet-evaluator/src/function/arglike.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/arglike.rs
+++ /dev/null
@@ -1,197 +0,0 @@
-use std::collections::HashMap;
-use std::rc::Rc;
-
-use jrsonnet_gcmodule::Trace;
-use jrsonnet_interner::IStr;
-use jrsonnet_parser::{ArgsDesc, Expr, SourceFifo, SourcePath, Spanned};
-
-use crate::{evaluate, typed::Typed, with_state, Context, Result, Thunk, Val};
-
-pub trait ArgLike {
- fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<Thunk<Val>>;
-}
-
-impl ArgLike for &Rc<Spanned<Expr>> {
- fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<Thunk<Val>> {
- Ok(if tailstrict {
- Thunk::evaluated(evaluate(ctx, self)?)
- } else {
- let expr = (*self).clone();
- Thunk!(move || evaluate(ctx, &expr))
- })
- }
-}
-
-impl<T> ArgLike for T
-where
- T: Typed + Clone,
-{
- fn evaluate_arg(&self, _ctx: Context, tailstrict: bool) -> Result<Thunk<Val>> {
- if T::provides_lazy() && !tailstrict {
- return Ok(T::into_lazy_untyped(self.clone()));
- }
- let val = T::into_untyped(self.clone())?;
- Ok(Thunk::evaluated(val))
- }
-}
-
-#[derive(Clone, Trace)]
-pub enum TlaArg {
- String(IStr),
- Val(Val),
- Lazy(Thunk<Val>),
- Import(String),
- ImportStr(String),
- InlineCode(String),
-}
-impl TlaArg {
- pub fn evaluate_tailstrict(&self) -> Result<Val> {
- match self {
- Self::String(s) => Ok(Val::string(s.clone())),
- Self::Val(val) => Ok(val.clone()),
- Self::Lazy(lazy) => Ok(lazy.evaluate()?),
- Self::Import(p) => with_state(|s| {
- let resolved = s.resolve_from_default(&p.as_str())?;
- s.import_resolved(resolved)
- }),
- Self::ImportStr(p) => with_state(|s| {
- let resolved = s.resolve_from_default(&p.as_str())?;
- s.import_resolved_str(resolved).map(Val::string)
- }),
- Self::InlineCode(p) => with_state(|s| {
- let resolved =
- SourcePath::new(SourceFifo("<inline code>".to_owned(), p.as_bytes().into()));
- s.import_resolved(resolved)
- }),
- }
- }
- pub fn evaluate(&self) -> Result<Thunk<Val>> {
- match self {
- Self::String(s) => Ok(Thunk::evaluated(Val::string(s.clone()))),
- Self::Val(val) => Ok(Thunk::evaluated(val.clone())),
- Self::Lazy(lazy) => Ok(lazy.clone()),
- Self::Import(p) => with_state(|s| {
- let resolved = s.resolve_from_default(&p.as_str())?;
- Ok(Thunk!(move || s.import_resolved(resolved)))
- }),
- Self::ImportStr(p) => with_state(|s| {
- let resolved = s.resolve_from_default(&p.as_str())?;
- Ok(Thunk!(move || s
- .import_resolved_str(resolved)
- .map(Val::string)))
- }),
- Self::InlineCode(p) => with_state(|s| {
- let resolved =
- SourcePath::new(SourceFifo("<inline code>".to_owned(), p.as_bytes().into()));
- Ok(Thunk!(move || s.import_resolved(resolved)))
- }),
- }
- }
-}
-
-pub trait ArgsLike {
- fn unnamed_len(&self) -> usize;
- fn unnamed_iter(
- &self,
- ctx: Context,
- tailstrict: bool,
- handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,
- ) -> Result<()>;
- fn named_iter(
- &self,
- ctx: Context,
- tailstrict: bool,
- handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,
- ) -> Result<()>;
- fn named_names(&self, handler: &mut dyn FnMut(&IStr));
- fn is_empty(&self) -> bool;
-}
-
-impl ArgsLike for Vec<Val> {
- fn unnamed_len(&self) -> usize {
- self.len()
- }
- fn unnamed_iter(
- &self,
- _ctx: Context,
- _tailstrict: bool,
- handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,
- ) -> Result<()> {
- for (idx, el) in self.iter().enumerate() {
- handler(idx, Thunk::evaluated(el.clone()))?;
- }
- Ok(())
- }
- fn named_iter(
- &self,
- _ctx: Context,
- _tailstrict: bool,
- _handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,
- ) -> Result<()> {
- Ok(())
- }
- fn named_names(&self, _handler: &mut dyn FnMut(&IStr)) {}
- fn is_empty(&self) -> bool {
- self.is_empty()
- }
-}
-
-impl ArgsLike for ArgsDesc {
- fn unnamed_len(&self) -> usize {
- self.unnamed.len()
- }
-
- fn unnamed_iter(
- &self,
- ctx: Context,
- tailstrict: bool,
- handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,
- ) -> Result<()> {
- for (id, arg) in self.unnamed.iter().enumerate() {
- handler(
- id,
- if tailstrict {
- Thunk::evaluated(evaluate(ctx.clone(), arg)?)
- } else {
- let ctx = ctx.clone();
- let arg = arg.clone();
-
- Thunk!(move || evaluate(ctx, &arg))
- },
- )?;
- }
- Ok(())
- }
-
- fn named_iter(
- &self,
- ctx: Context,
- tailstrict: bool,
- handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,
- ) -> Result<()> {
- for (name, arg) in &self.named {
- handler(
- name,
- if tailstrict {
- Thunk::evaluated(evaluate(ctx.clone(), arg)?)
- } else {
- let ctx = ctx.clone();
- let arg = arg.clone();
-
- Thunk!(move || evaluate(ctx, &arg))
- },
- )?;
- }
- Ok(())
- }
-
- fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {
- for (name, _) in &self.named {
- handler(name);
- }
- }
-
- fn is_empty(&self) -> bool {
- self.unnamed.is_empty() && self.named.is_empty()
- }
-}
crates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -1,11 +1,10 @@
use std::{fmt::Debug, rc::Rc};
-pub use arglike::{ArgLike, ArgsLike, TlaArg};
use educe::Educe;
use jrsonnet_gcmodule::{Cc, Trace};
use jrsonnet_interner::IStr;
pub use jrsonnet_macros::builtin;
-use jrsonnet_parser::{Destruct, Expr, ExprParams, Span, Spanned};
+use jrsonnet_parser::{ArgsDesc, Destruct, Expr, ExprParams, Span, Spanned};
use self::{
builtin::{Builtin, StaticBuiltin},
@@ -17,12 +16,12 @@
Result, Thunk, Val,
};
-pub mod arglike;
pub mod builtin;
-pub mod native;
-pub mod parse;
+mod native;
+mod parse;
mod prepared;
+pub use native::NativeFn;
pub use prepared::PreparedFuncVal;
pub use jrsonnet_parser::function::*;
@@ -81,10 +80,10 @@
}
/// Create context, with which body code will run
- pub fn call_body_context(
+ pub(crate) fn call_body_context(
&self,
call_ctx: Context,
- args: &dyn ArgsLike,
+ args: &ArgsDesc,
tailstrict: bool,
) -> Result<Context> {
parse_function_call(call_ctx, self.ctx.clone(), &self.params, args, tailstrict)
@@ -170,7 +169,7 @@
&self,
call_ctx: Context,
loc: CallLocation<'_>,
- args: &dyn ArgsLike,
+ args: &ArgsDesc,
tailstrict: bool,
) -> Result<Val> {
match self {
@@ -179,7 +178,7 @@
evaluate(body_ctx, &func.body)
}
Self::Thunk(thunk) => {
- if !args.is_empty() {
+ if !args.named.is_empty() || !args.unnamed.is_empty() {
bail!(TooManyArgsFunctionHas(0, FunctionSignature::empty()))
}
thunk.evaluate()
crates/jrsonnet-evaluator/src/function/native.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/native.rs
+++ b/crates/jrsonnet-evaluator/src/function/native.rs
@@ -1,2 +1,68 @@
+use std::marker::PhantomData;
+
+use jrsonnet_gcmodule::Trace;
+
use super::PreparedFuncVal;
-use crate::{typed::Typed, CallLocation, Result, Thunk};
+use crate::{bail, function::FuncVal, typed::Typed, CallLocation, Result, Val};
+use jrsonnet_types::{ComplexValType, ValType};
+
+#[derive(Debug, Trace, Clone)]
+pub struct NativeFn<D: 'static>(pub(crate) PreparedFuncVal, PhantomData<D>);
+macro_rules! impl_native_desc {
+ ($i:expr; $($gen:ident)*) => {
+ impl<$($gen,)* O> NativeFn<($($gen,)* O,)>
+ where
+ $($gen: Typed,)*
+ O: Typed,
+ {
+ #[allow(non_snake_case, clippy::too_many_arguments)]
+ pub fn call(
+ &self,
+ $($gen: $gen,)*
+ ) -> Result<O> {
+ let val = self.0.call(
+ CallLocation::native(),
+ &[$(Typed::into_lazy_untyped($gen),)*],
+ &[],
+ )?;
+ O::from_untyped(val)
+ }
+ }
+ impl<$($gen,)* O> Typed for NativeFn<($($gen,)* O,)> {
+ const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);
+
+ fn into_untyped(_typed: Self) -> Result<Val> {
+ bail!("can only convert functions from jsonnet to native")
+ }
+
+ fn from_untyped(untyped: Val) -> Result<Self> {
+ let func = FuncVal::from_untyped(untyped)?;
+ Ok(Self(
+ PreparedFuncVal::new(func, $i, &[])?,
+ PhantomData,
+ ))
+ }
+ }
+ };
+ ($i:expr; $($cur:ident)* @ $c:ident $($rest:ident)*) => {
+ impl_native_desc!($i; $($cur)*);
+ impl_native_desc!($i + 1; $($cur)* $c @ $($rest)*);
+ };
+ ($i:expr; $($cur:ident)* @) => {
+ impl_native_desc!($i; $($cur)*);
+ }
+}
+
+impl_native_desc! {
+ 0; @ A B C D E F G H I J K L
+}
+
+mod native_macro {
+ #[macro_export]
+ macro_rules! NativeFn {
+ (($($t:ty),* $(,)?) -> $res:ty) => {
+ NativeFn<($($t,)* $res)>
+ }
+ }
+}
+pub use crate::NativeFn;
crates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/parse.rs
+++ b/crates/jrsonnet-evaluator/src/function/parse.rs
@@ -1,19 +1,29 @@
+use std::rc::Rc;
+
use jrsonnet_parser::{
function::{FunctionSignature, ParamName},
- ExprParams,
+ ArgsDesc, Expr, ExprParams, Spanned,
};
use rustc_hash::FxHashMap;
-use super::arglike::ArgsLike;
use crate::{
bail,
destructure::destruct,
error::{ErrorKind::*, Result},
- evaluate_named_param,
+ evaluate, evaluate_named_param,
gc::WithCapacityExt as _,
Context, Pending, Thunk, Val,
};
+fn eval_arg(ctx: Context, arg: &Rc<Spanned<Expr>>, tailstrict: bool) -> Result<Thunk<Val>> {
+ if tailstrict {
+ Ok(Thunk::evaluated(evaluate(ctx, arg)?))
+ } else {
+ let arg = arg.clone();
+ Ok(Thunk!(move || evaluate(ctx, &arg)))
+ }
+}
+
/// Creates correct [context](Context) for function body evaluation returning error on invalid call.
///
/// ## Parameters
@@ -22,15 +32,15 @@
/// * `params`: function parameters' definition
/// * `args`: passed function arguments
/// * `tailstrict`: if set to `true` function arguments are eagerly executed, otherwise - lazily
-pub fn parse_function_call(
+pub(crate) fn parse_function_call(
ctx: Context,
body_ctx: Context,
params: &ExprParams,
- args: &dyn ArgsLike,
+ args: &ArgsDesc,
tailstrict: bool,
) -> Result<Context> {
let mut passed_args = FxHashMap::with_capacity(params.binds_len());
- if args.unnamed_len() > params.signature.len() {
+ if args.unnamed.len() > params.signature.len() {
bail!(TooManyArgsFunctionHas(
params.signature.len(),
params.signature.clone(),
@@ -40,28 +50,29 @@
let mut filled_named = 0;
let mut filled_positionals = 0;
- args.unnamed_iter(ctx.clone(), tailstrict, &mut |id, arg| {
+ for (id, arg) in args.unnamed.iter().enumerate() {
destruct(
¶ms.exprs[id].destruct,
- arg,
+ eval_arg(ctx.clone(), arg, tailstrict)?,
Pending::new_filled(ctx.clone()),
&mut passed_args,
)?;
filled_positionals += 1;
- Ok(())
- })?;
+ }
- args.named_iter(ctx, tailstrict, &mut |name, value| {
+ for (name, value) in &args.named {
// FIXME: O(n) for arg existence check
if !params.exprs.iter().any(|p| &p.destruct.name() == name) {
bail!(UnknownFunctionParameter(name.clone()));
}
- if passed_args.insert(name.clone(), value).is_some() {
+ if passed_args
+ .insert(name.clone(), eval_arg(ctx.clone(), value, tailstrict)?)
+ .is_some()
+ {
bail!(BindingParameterASecondTime(name.clone()));
}
filled_named += 1;
- Ok(())
- })?;
+ }
if filled_named + filled_positionals < params.len() {
// Some args are unset, but maybe we have defaults for them
@@ -104,13 +115,13 @@
// Some args still weren't filled
if filled_named + filled_positionals != params.len() {
- for param in params.exprs.iter().skip(args.unnamed_len()) {
+ for param in params.exprs.iter().skip(args.unnamed.len()) {
let mut found = false;
- args.named_names(&mut |name| {
+ for (name, _) in &args.named {
if ¶m.destruct.name() == name {
found = true;
}
- });
+ }
if !found {
bail!(FunctionParameterNotBoundInCall(
param.destruct.name(),
@@ -141,34 +152,35 @@
pub fn parse_builtin_call(
ctx: Context,
params: FunctionSignature,
- args: &dyn ArgsLike,
+ args: &ArgsDesc,
tailstrict: bool,
) -> Result<Vec<Option<Thunk<Val>>>> {
let mut passed_args: Vec<Option<Thunk<Val>>> = vec![None; params.len()];
- if args.unnamed_len() > params.len() {
+ if args.unnamed.len() > params.len() {
bail!(TooManyArgsFunctionHas(params.len(), params,))
}
let mut filled_args = 0;
- args.unnamed_iter(ctx.clone(), tailstrict, &mut |id, arg| {
- passed_args[id] = Some(arg);
+ for (id, arg) in args.unnamed.iter().enumerate() {
+ passed_args[id] = Some(eval_arg(ctx.clone(), arg, tailstrict)?);
filled_args += 1;
- Ok(())
- })?;
+ }
- args.named_iter(ctx, tailstrict, &mut |name, arg| {
+ for (name, arg) in &args.named {
// FIXME: O(n) for arg existence check
let id = params
.iter()
.position(|p| p.name() == name)
.ok_or_else(|| UnknownFunctionParameter(name.clone()))?;
- if passed_args[id].replace(arg).is_some() {
+ if passed_args[id]
+ .replace(eval_arg(ctx.clone(), arg, tailstrict)?)
+ .is_some()
+ {
bail!(BindingParameterASecondTime(name.clone()));
}
filled_args += 1;
- Ok(())
- })?;
+ }
if filled_args < params.len() {
for (id, _) in params.iter().enumerate().filter(|(_, p)| p.has_default()) {
@@ -180,13 +192,13 @@
// Some args still wasn't filled
if filled_args != params.len() {
- for param in params.iter().skip(args.unnamed_len()) {
+ for param in params.iter().skip(args.unnamed.len()) {
let mut found = false;
- args.named_names(&mut |name| {
+ for (name, _) in &args.named {
if param.name() == name {
found = true;
}
- });
+ }
if !found {
bail!(FunctionParameterNotBoundInCall(
param.name().clone(),
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -19,7 +19,7 @@
mod obj;
pub mod stack;
pub mod stdlib;
-mod tla;
+pub mod tla;
pub mod trace;
pub mod typed;
pub mod val;
crates/jrsonnet-evaluator/src/tla.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/tla.rs
+++ b/crates/jrsonnet-evaluator/src/tla.rs
@@ -1,12 +1,68 @@
use std::{collections::HashMap, hash::BuildHasher};
+use jrsonnet_gcmodule::Trace;
use jrsonnet_interner::IStr;
+use jrsonnet_parser::{SourceFifo, SourcePath};
use crate::{
- function::{CallLocation, PreparedFuncVal, TlaArg},
- in_description_frame, Result, Val,
+ function::{CallLocation, PreparedFuncVal},
+ in_description_frame, with_state, Result, Thunk, Val,
};
+#[derive(Clone, Trace)]
+pub enum TlaArg {
+ String(IStr),
+ Val(Val),
+ Lazy(Thunk<Val>),
+ Import(String),
+ ImportStr(String),
+ InlineCode(String),
+}
+impl TlaArg {
+ pub fn evaluate_tailstrict(&self) -> Result<Val> {
+ match self {
+ Self::String(s) => Ok(Val::string(s.clone())),
+ Self::Val(val) => Ok(val.clone()),
+ Self::Lazy(lazy) => Ok(lazy.evaluate()?),
+ Self::Import(p) => with_state(|s| {
+ let resolved = s.resolve_from_default(&p.as_str())?;
+ s.import_resolved(resolved)
+ }),
+ Self::ImportStr(p) => with_state(|s| {
+ let resolved = s.resolve_from_default(&p.as_str())?;
+ s.import_resolved_str(resolved).map(Val::string)
+ }),
+ Self::InlineCode(p) => with_state(|s| {
+ let resolved =
+ SourcePath::new(SourceFifo("<inline code>".to_owned(), p.as_bytes().into()));
+ s.import_resolved(resolved)
+ }),
+ }
+ }
+ pub fn evaluate(&self) -> Result<Thunk<Val>> {
+ match self {
+ Self::String(s) => Ok(Thunk::evaluated(Val::string(s.clone()))),
+ Self::Val(val) => Ok(Thunk::evaluated(val.clone())),
+ Self::Lazy(lazy) => Ok(lazy.clone()),
+ Self::Import(p) => with_state(|s| {
+ let resolved = s.resolve_from_default(&p.as_str())?;
+ Ok(Thunk!(move || s.import_resolved(resolved)))
+ }),
+ Self::ImportStr(p) => with_state(|s| {
+ let resolved = s.resolve_from_default(&p.as_str())?;
+ Ok(Thunk!(move || s
+ .import_resolved_str(resolved)
+ .map(Val::string)))
+ }),
+ Self::InlineCode(p) => with_state(|s| {
+ let resolved =
+ SourcePath::new(SourceFifo("<inline code>".to_owned(), p.as_bytes().into()));
+ Ok(Thunk!(move || s.import_resolved(resolved)))
+ }),
+ }
+ }
+}
+
pub fn apply_tla<H: BuildHasher>(args: &HashMap<IStr, TlaArg, H>, val: Val) -> Result<Val> {
Ok(if let Val::Func(func) = val {
in_description_frame(
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -8,7 +8,7 @@
use crate::{
arr::{ArrValue, BytesArray},
bail,
- function::{CallLocation, FuncDesc, FuncVal, PreparedFuncVal},
+ function::{FuncDesc, FuncVal},
typed::CheckType,
val::{IndexableVal, NumValue, StrValue, ThunkMapper},
ObjValue, ObjValueBuilder, Result, ResultExt, Thunk, Val,
@@ -671,69 +671,9 @@
Ok(None)
} else {
T::from_untyped(untyped).map(Some)
- }
- }
-}
-
-#[derive(Debug, Trace, Clone)]
-pub struct NativeFn<D: 'static>(pub(crate) PreparedFuncVal, PhantomData<D>);
-macro_rules! impl_native_desc {
- ($i:expr; $($gen:ident)*) => {
- impl<$($gen,)* O> NativeFn<($($gen,)* O,)>
- where
- $($gen: Typed,)*
- O: Typed,
- {
- pub fn call(
- &self,
- $($gen: $gen,)*
- ) -> Result<O> {
- let val = self.0.call(
- CallLocation::native(),
- &[$(Typed::into_lazy_untyped($gen),)*],
- &[],
- )?;
- O::from_untyped(val)
- }
- }
- impl<$($gen,)* O> Typed for NativeFn<($($gen,)* O,)> {
- const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);
-
- fn into_untyped(_typed: Self) -> Result<Val> {
- bail!("can only convert functions from jsonnet to native")
- }
-
- fn from_untyped(untyped: Val) -> Result<Self> {
- let func = FuncVal::from_untyped(untyped)?;
- Ok(Self(
- PreparedFuncVal::new(func, $i, &[])?,
- PhantomData,
- ))
- }
}
- };
- ($i:expr; $($cur:ident)* @ $c:ident $($rest:ident)*) => {
- impl_native_desc!($i; $($cur)*);
- impl_native_desc!($i + 1; $($cur)* $c @ $($rest)*);
- };
- ($i:expr; $($cur:ident)* @) => {
- impl_native_desc!($i; $($cur)*);
}
-}
-
-impl_native_desc! {
- 0; @ A B C D E F G H I J K L
}
-
-mod native_macro {
- #[macro_export]
- macro_rules! NativeFn {
- (($($t:ty),* $(,)?) -> $res:ty) => {
- NativeFn<($($t,)* $res)>
- }
- }
-}
-pub use crate::NativeFn;
impl Typed for NumValue {
const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -405,7 +405,7 @@
const _: () = {
use ::jrsonnet_evaluator::{
State, Val,
- function::{builtin::{Builtin, StaticBuiltin}, FunctionSignature, ParamParse, ParamName, ParamDefault, CallLocation, ArgsLike, parse::parse_builtin_call},
+ function::{builtin::{Builtin, StaticBuiltin}, FunctionSignature, ParamParse, ParamName, ParamDefault, CallLocation},
Result, Context, typed::Typed,
parser::Span, params, Thunk,
};
crates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -2,9 +2,9 @@
use jrsonnet_evaluator::{
bail,
- function::{builtin, FuncVal},
+ function::{builtin, FuncVal, NativeFn},
runtime_error,
- typed::{BoundedI32, BoundedUsize, Either2, NativeFn, Typed},
+ typed::{BoundedI32, BoundedUsize, Either2, Typed},
val::{equals, ArrValue, IndexableVal},
Either, IStr, ObjValue, ObjValueBuilder, Result, ResultExt, Thunk, Val,
};
crates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -13,7 +13,8 @@
pub use hash::*;
use jrsonnet_evaluator::{
error::Result,
- function::{CallLocation, FuncVal, TlaArg},
+ function::{CallLocation, FuncVal},
+ tla::TlaArg,
trace::PathResolver,
val::NumValue,
ContextBuilder, IStr, ObjValue, ObjValueBuilder, Thunk, Val,
tests/tests/cpp_test_suite.rsdiffbeforeafterboth--- a/tests/tests/cpp_test_suite.rs
+++ b/tests/tests/cpp_test_suite.rs
@@ -6,10 +6,10 @@
use jrsonnet_evaluator::{
FileImportResolver, IStr, ObjValueBuilder, State, Val, apply_tla,
- function::TlaArg,
gc::WithCapacityExt as _,
manifest::JsonFormat,
rustc_hash::FxHashMap,
+ tla::TlaArg,
trace::{CompactFormat, PathResolver, TraceFormat},
};
use jrsonnet_stdlib::ContextInitializer;