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.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/mod.rs
+++ b/crates/jrsonnet-evaluator/src/arr/mod.rs
@@ -9,7 +9,7 @@
use jrsonnet_interner::IBytes;
use jrsonnet_parser::{Expr, Spanned};
-use crate::{typed::NativeFn, Context, Result, Thunk, Val};
+use crate::{function::NativeFn, Context, Result, Thunk, Val};
mod spec;
pub use spec::{ArrayLike, *};
crates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth1use std::rc::Rc;2use std::{any::Any, cell::RefCell, fmt::Debug, mem::replace};34use jrsonnet_gcmodule::{Cc, Trace};5use jrsonnet_interner::{IBytes, IStr};6use jrsonnet_parser::{Expr, Spanned};78use super::ArrValue;9use crate::typed::NativeFn;10use crate::val::NumValue;11use crate::{12 error::ErrorKind::InfiniteRecursionDetected, evaluate, typed::Typed, val::ThunkValue, Context,13 Error, ObjValue, Result, Thunk, Val,14};1516pub trait ArrayLike: Any + Trace + Debug {17 fn len(&self) -> usize;18 fn is_empty(&self) -> bool {19 self.len() == 020 }21 fn get(&self, index: usize) -> Result<Option<Val>>;22 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>>;23 fn get_cheap(&self, index: usize) -> Option<Val>;2425 fn is_cheap(&self) -> bool;26}2728#[derive(Debug, Trace)]29pub struct SliceArray {30 pub(crate) inner: ArrValue,31 pub(crate) from: u32,32 pub(crate) to: u32,33 pub(crate) step: u32,34}3536impl SliceArray {37 fn map_idx(&self, index: usize) -> usize {38 self.from as usize + self.step as usize * index39 }40}41impl ArrayLike for SliceArray {42 fn len(&self) -> usize {43 (self.to - self.from).div_ceil(self.step) as usize44 }4546 fn get(&self, index: usize) -> Result<Option<Val>> {47 self.inner.get(self.map_idx(index))48 }4950 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {51 self.inner.get_lazy(self.map_idx(index))52 }5354 fn get_cheap(&self, index: usize) -> Option<Val> {55 self.inner.get_cheap(self.map_idx(index))56 }57 fn is_cheap(&self) -> bool {58 self.inner.is_cheap()59 }60}6162#[derive(Trace, Debug)]63pub struct CharArray(pub Vec<char>);64impl ArrayLike for CharArray {65 fn len(&self) -> usize {66 self.0.len()67 }6869 fn get(&self, index: usize) -> Result<Option<Val>> {70 Ok(self.get_cheap(index))71 }7273 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {74 self.get_cheap(index).map(Thunk::evaluated)75 }7677 fn get_cheap(&self, index: usize) -> Option<Val> {78 self.0.get(index).map(|v| Val::string(*v))79 }80 fn is_cheap(&self) -> bool {81 true82 }83}8485#[derive(Trace, Debug)]86pub struct BytesArray(pub IBytes);87impl ArrayLike for BytesArray {88 fn len(&self) -> usize {89 self.0.len()90 }9192 fn get(&self, index: usize) -> Result<Option<Val>> {93 Ok(self.get_cheap(index))94 }9596 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {97 self.get_cheap(index).map(Thunk::evaluated)98 }99100 fn get_cheap(&self, index: usize) -> Option<Val> {101 self.0.get(index).map(|v| Val::Num((*v).into()))102 }103 fn is_cheap(&self) -> bool {104 true105 }106}107108#[derive(Debug, Trace, Clone)]109enum ArrayThunk {110 Computed(Val),111 Errored(Error),112 Waiting,113 Pending,114}115116#[derive(Debug, Trace, Clone)]117pub struct ExprArray {118 ctx: Context,119 src: Rc<Vec<Spanned<Expr>>>,120 cached: Cc<RefCell<Vec<ArrayThunk>>>,121}122impl ExprArray {123 pub fn new(ctx: Context, src: Rc<Vec<Spanned<Expr>>>) -> Self {124 Self {125 ctx,126 cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting; src.len()])),127 src,128 }129 }130}131impl ArrayLike for ExprArray {132 fn len(&self) -> usize {133 self.cached.borrow().len()134 }135 fn get(&self, index: usize) -> Result<Option<Val>> {136 if index >= self.len() {137 return Ok(None);138 }139 match &self.cached.borrow()[index] {140 ArrayThunk::Computed(c) => return Ok(Some(c.clone())),141 ArrayThunk::Errored(e) => return Err(e.clone()),142 ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),143 ArrayThunk::Waiting => {}144 }145146 let ArrayThunk::Waiting =147 replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)148 else {149 unreachable!()150 };151152 let new_value = match evaluate(self.ctx.clone(), &self.src[index]) {153 Ok(v) => v,154 Err(e) => {155 self.cached.borrow_mut()[index] = ArrayThunk::Errored(e.clone());156 return Err(e);157 }158 };159 self.cached.borrow_mut()[index] = ArrayThunk::Computed(new_value.clone());160 Ok(Some(new_value))161 }162 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {163 #[derive(Trace)]164 struct ExprArrThunk {165 expr: ExprArray,166 index: usize,167 }168 impl ThunkValue for ExprArrThunk {169 type Output = Val;170171 fn get(&self) -> Result<Self::Output> {172 self.expr173 .get(self.index)174 .transpose()175 .expect("index checked")176 }177 }178179 if index >= self.len() {180 return None;181 }182 match &self.cached.borrow()[index] {183 ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),184 ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),185 ArrayThunk::Waiting | ArrayThunk::Pending => {}186 }187188 Some(Thunk::new(ExprArrThunk {189 expr: self.clone(),190 index,191 }))192 }193 fn get_cheap(&self, _index: usize) -> Option<Val> {194 None195 }196 fn is_cheap(&self) -> bool {197 false198 }199}200201#[derive(Trace, Debug)]202pub struct ExtendedArray {203 pub a: ArrValue,204 pub b: ArrValue,205 split: usize,206 len: usize,207}208impl ExtendedArray {209 pub fn new(a: ArrValue, b: ArrValue) -> Self {210 let a_len = a.len();211 let b_len = b.len();212 Self {213 a,214 b,215 split: a_len,216 len: a_len.checked_add(b_len).expect("too large array value"),217 }218 }219}220221struct WithExactSize<I>(I, usize);222impl<I, T> Iterator for WithExactSize<I>223where224 I: Iterator<Item = T>,225{226 type Item = T;227228 fn next(&mut self) -> Option<Self::Item> {229 self.0.next()230 }231 fn nth(&mut self, n: usize) -> Option<Self::Item> {232 self.0.nth(n)233 }234 fn size_hint(&self) -> (usize, Option<usize>) {235 (self.1, Some(self.1))236 }237}238impl<I> DoubleEndedIterator for WithExactSize<I>239where240 I: DoubleEndedIterator,241{242 fn next_back(&mut self) -> Option<Self::Item> {243 self.0.next_back()244 }245 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {246 self.0.nth_back(n)247 }248}249impl<I> ExactSizeIterator for WithExactSize<I>250where251 I: Iterator,252{253 fn len(&self) -> usize {254 self.1255 }256}257impl ArrayLike for ExtendedArray {258 fn get(&self, index: usize) -> Result<Option<Val>> {259 if self.split > index {260 self.a.get(index)261 } else {262 self.b.get(index - self.split)263 }264 }265 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {266 if self.split > index {267 self.a.get_lazy(index)268 } else {269 self.b.get_lazy(index - self.split)270 }271 }272273 fn len(&self) -> usize {274 self.len275 }276277 fn get_cheap(&self, index: usize) -> Option<Val> {278 if self.split > index {279 self.a.get_cheap(index)280 } else {281 self.b.get_cheap(index - self.split)282 }283 }284 fn is_cheap(&self) -> bool {285 self.a.is_cheap() && self.b.is_cheap()286 }287}288289#[derive(Trace, Debug)]290pub struct LazyArray(pub Vec<Thunk<Val>>);291impl ArrayLike for LazyArray {292 fn len(&self) -> usize {293 self.0.len()294 }295 fn get(&self, index: usize) -> Result<Option<Val>> {296 let Some(v) = self.0.get(index) else {297 return Ok(None);298 };299 v.evaluate().map(Some)300 }301 fn get_cheap(&self, _index: usize) -> Option<Val> {302 None303 }304 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {305 self.0.get(index).cloned()306 }307 fn is_cheap(&self) -> bool {308 false309 }310}311312#[derive(Trace, Debug)]313pub struct EagerArray(pub Vec<Val>);314impl ArrayLike for EagerArray {315 fn len(&self) -> usize {316 self.0.len()317 }318319 fn get(&self, index: usize) -> Result<Option<Val>> {320 Ok(self.0.get(index).cloned())321 }322323 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {324 self.0.get(index).cloned().map(Thunk::evaluated)325 }326327 fn get_cheap(&self, index: usize) -> Option<Val> {328 self.0.get(index).cloned()329 }330 fn is_cheap(&self) -> bool {331 true332 }333}334335/// Inclusive range type336#[derive(Debug, Trace, PartialEq, Eq)]337pub struct RangeArray {338 start: i32,339 end: i32,340}341impl RangeArray {342 pub fn empty() -> Self {343 Self::new_exclusive(0, 0)344 }345 pub fn new_exclusive(start: i32, end: i32) -> Self {346 end.checked_sub(1)347 .map_or_else(Self::empty, |end| Self { start, end })348 }349 pub fn new_inclusive(start: i32, end: i32) -> Self {350 Self { start, end }351 }352 fn range(&self) -> impl ExactSizeIterator<Item = i32> + DoubleEndedIterator {353 WithExactSize(354 self.start..=self.end,355 (self.end as usize)356 .wrapping_sub(self.start as usize)357 .wrapping_add(1),358 )359 }360}361362impl ArrayLike for RangeArray {363 fn len(&self) -> usize {364 self.range().len()365 }366 fn is_empty(&self) -> bool {367 self.range().len() == 0368 }369370 fn get(&self, index: usize) -> Result<Option<Val>> {371 Ok(self.get_cheap(index))372 }373374 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {375 self.get_cheap(index).map(Thunk::evaluated)376 }377378 fn get_cheap(&self, index: usize) -> Option<Val> {379 self.range().nth(index).map(|i| Val::Num(i.into()))380 }381 fn is_cheap(&self) -> bool {382 true383 }384}385386#[derive(Debug, Trace)]387pub struct ReverseArray(pub ArrValue);388impl ArrayLike for ReverseArray {389 fn len(&self) -> usize {390 self.0.len()391 }392393 fn get(&self, index: usize) -> Result<Option<Val>> {394 self.0.get(self.0.len() - index - 1)395 }396397 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {398 self.0.get_lazy(self.0.len() - index - 1)399 }400401 fn get_cheap(&self, index: usize) -> Option<Val> {402 self.0.get_cheap(self.0.len() - index - 1)403 }404 fn is_cheap(&self) -> bool {405 self.0.is_cheap()406 }407}408409#[derive(Trace, Clone, Debug)]410pub enum ArrayMapper {411 Plain(NativeFn!((Val) -> Val)),412 WithIndex(NativeFn!((u32, Val) -> Val)),413}414415#[derive(Trace, Debug, Clone)]416pub struct MappedArray {417 inner: ArrValue,418 cached: Cc<RefCell<Vec<ArrayThunk>>>,419 mapper: ArrayMapper,420}421impl MappedArray {422 pub fn new(inner: ArrValue, mapper: ArrayMapper) -> Self {423 let len = inner.len();424 Self {425 inner,426 cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting; len])),427 mapper,428 }429 }430 fn evaluate(&self, index: usize, value: Val) -> Result<Val> {431 match &self.mapper {432 ArrayMapper::Plain(f) => f.call(value),433 ArrayMapper::WithIndex(f) => f.call(index as u32, value),434 }435 }436}437impl ArrayLike for MappedArray {438 fn len(&self) -> usize {439 self.cached.borrow().len()440 }441442 fn get(&self, index: usize) -> Result<Option<Val>> {443 if index >= self.len() {444 return Ok(None);445 }446 match &self.cached.borrow()[index] {447 ArrayThunk::Computed(c) => return Ok(Some(c.clone())),448 ArrayThunk::Errored(e) => return Err(e.clone()),449 ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),450 ArrayThunk::Waiting => {}451 }452453 let ArrayThunk::Waiting =454 replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)455 else {456 unreachable!()457 };458459 let val = self460 .inner461 .get(index)462 .transpose()463 .expect("index checked")464 .and_then(|r| self.evaluate(index, r));465466 let new_value = match val {467 Ok(v) => v,468 Err(e) => {469 self.cached.borrow_mut()[index] = ArrayThunk::Errored(e.clone());470 return Err(e);471 }472 };473 self.cached.borrow_mut()[index] = ArrayThunk::Computed(new_value.clone());474 Ok(Some(new_value))475 }476 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {477 #[derive(Trace)]478 struct MappedArrayThunk {479 arr: MappedArray,480 index: usize,481 }482 impl ThunkValue for MappedArrayThunk {483 type Output = Val;484485 fn get(&self) -> Result<Self::Output> {486 self.arr.get(self.index).transpose().expect("index checked")487 }488 }489490 if index >= self.len() {491 return None;492 }493 match &self.cached.borrow()[index] {494 ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),495 ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),496 ArrayThunk::Waiting | ArrayThunk::Pending => {}497 }498499 Some(Thunk::new(MappedArrayThunk {500 arr: self.clone(),501 index,502 }))503 }504505 fn get_cheap(&self, _index: usize) -> Option<Val> {506 None507 }508 fn is_cheap(&self) -> bool {509 false510 }511}512513#[derive(Trace, Debug)]514pub struct RepeatedArray {515 data: ArrValue,516 repeats: usize,517 total_len: usize,518}519impl RepeatedArray {520 pub fn new(data: ArrValue, repeats: usize) -> Option<Self> {521 let total_len = data.len().checked_mul(repeats)?;522 Some(Self {523 data,524 repeats,525 total_len,526 })527 }528}529530impl ArrayLike for RepeatedArray {531 fn len(&self) -> usize {532 self.total_len533 }534535 fn get(&self, index: usize) -> Result<Option<Val>> {536 if index > self.total_len {537 return Ok(None);538 }539 self.data.get(index % self.data.len())540 }541542 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {543 if index > self.total_len {544 return None;545 }546 self.data.get_lazy(index % self.data.len())547 }548549 fn get_cheap(&self, index: usize) -> Option<Val> {550 if index > self.total_len {551 return None;552 }553 self.data.get_cheap(index % self.data.len())554 }555 fn is_cheap(&self) -> bool {556 self.data.is_cheap()557 }558}559560#[derive(Trace, Debug)]561pub struct PickObjectValues {562 obj: ObjValue,563 keys: Vec<IStr>,564}565566impl PickObjectValues {567 pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {568 Self { obj, keys }569 }570}571572impl ArrayLike for PickObjectValues {573 fn len(&self) -> usize {574 self.keys.len()575 }576577 fn get(&self, index: usize) -> Result<Option<Val>> {578 let Some(key) = self.keys.get(index) else {579 return Ok(None);580 };581 Ok(Some(self.obj.get_or_bail(key.clone())?))582 }583584 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {585 let key = self.keys.get(index)?;586 Some(self.obj.get_lazy_or_bail(key.clone()))587 }588589 fn get_cheap(&self, _index: usize) -> Option<Val> {590 None591 }592593 fn is_cheap(&self) -> bool {594 false595 }596}597598#[derive(Trace, Debug)]599pub struct PickObjectKeyValues {600 obj: ObjValue,601 keys: Vec<IStr>,602}603604impl PickObjectKeyValues {605 pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {606 Self { obj, keys }607 }608}609610#[derive(Typed)]611pub struct KeyValue {612 key: IStr,613 value: Thunk<Val>,614}615616impl ArrayLike for PickObjectKeyValues {617 fn len(&self) -> usize {618 self.keys.len()619 }620621 fn get(&self, index: usize) -> Result<Option<Val>> {622 let Some(key) = self.keys.get(index) else {623 return Ok(None);624 };625 Ok(Some(626 KeyValue::into_untyped(KeyValue {627 key: key.clone(),628 value: Thunk::evaluated(self.obj.get_or_bail(key.clone())?),629 })630 .expect("convertible"),631 ))632 }633634 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {635 let key = self.keys.get(index)?;636 // Nothing can fail in the key part, yet value is still637 // lazy-evaluated638 Some(Thunk::evaluated(639 KeyValue::into_untyped(KeyValue {640 key: key.clone(),641 value: self.obj.get_lazy_or_bail(key.clone()),642 })643 .expect("convertible"),644 ))645 }646647 fn get_cheap(&self, _index: usize) -> Option<Val> {648 None649 }650651 fn is_cheap(&self) -> bool {652 false653 }654}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;