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}1use 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::function::NativeFn;10use crate::{11 error::ErrorKind::InfiniteRecursionDetected, evaluate, typed::Typed, val::ThunkValue, Context,12 Error, ObjValue, Result, Thunk, Val,13};1415pub trait ArrayLike: Any + Trace + Debug {16 fn len(&self) -> usize;17 fn is_empty(&self) -> bool {18 self.len() == 019 }20 fn get(&self, index: usize) -> Result<Option<Val>>;21 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>>;22 fn get_cheap(&self, index: usize) -> Option<Val>;2324 fn is_cheap(&self) -> bool;25}2627#[derive(Debug, Trace)]28pub struct SliceArray {29 pub(crate) inner: ArrValue,30 pub(crate) from: u32,31 pub(crate) to: u32,32 pub(crate) step: u32,33}3435impl SliceArray {36 fn map_idx(&self, index: usize) -> usize {37 self.from as usize + self.step as usize * index38 }39}40impl ArrayLike for SliceArray {41 fn len(&self) -> usize {42 (self.to - self.from).div_ceil(self.step) as usize43 }4445 fn get(&self, index: usize) -> Result<Option<Val>> {46 self.inner.get(self.map_idx(index))47 }4849 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {50 self.inner.get_lazy(self.map_idx(index))51 }5253 fn get_cheap(&self, index: usize) -> Option<Val> {54 self.inner.get_cheap(self.map_idx(index))55 }56 fn is_cheap(&self) -> bool {57 self.inner.is_cheap()58 }59}6061#[derive(Trace, Debug)]62pub struct CharArray(pub Vec<char>);63impl ArrayLike for CharArray {64 fn len(&self) -> usize {65 self.0.len()66 }6768 fn get(&self, index: usize) -> Result<Option<Val>> {69 Ok(self.get_cheap(index))70 }7172 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {73 self.get_cheap(index).map(Thunk::evaluated)74 }7576 fn get_cheap(&self, index: usize) -> Option<Val> {77 self.0.get(index).map(|v| Val::string(*v))78 }79 fn is_cheap(&self) -> bool {80 true81 }82}8384#[derive(Trace, Debug)]85pub struct BytesArray(pub IBytes);86impl ArrayLike for BytesArray {87 fn len(&self) -> usize {88 self.0.len()89 }9091 fn get(&self, index: usize) -> Result<Option<Val>> {92 Ok(self.get_cheap(index))93 }9495 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {96 self.get_cheap(index).map(Thunk::evaluated)97 }9899 fn get_cheap(&self, index: usize) -> Option<Val> {100 self.0.get(index).map(|v| Val::Num((*v).into()))101 }102 fn is_cheap(&self) -> bool {103 true104 }105}106107#[derive(Debug, Trace, Clone)]108enum ArrayThunk {109 Computed(Val),110 Errored(Error),111 Waiting,112 Pending,113}114115#[derive(Debug, Trace, Clone)]116pub struct ExprArray {117 ctx: Context,118 src: Rc<Vec<Spanned<Expr>>>,119 cached: Cc<RefCell<Vec<ArrayThunk>>>,120}121impl ExprArray {122 pub fn new(ctx: Context, src: Rc<Vec<Spanned<Expr>>>) -> Self {123 Self {124 ctx,125 cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting; src.len()])),126 src,127 }128 }129}130impl ArrayLike for ExprArray {131 fn len(&self) -> usize {132 self.cached.borrow().len()133 }134 fn get(&self, index: usize) -> Result<Option<Val>> {135 if index >= self.len() {136 return Ok(None);137 }138 match &self.cached.borrow()[index] {139 ArrayThunk::Computed(c) => return Ok(Some(c.clone())),140 ArrayThunk::Errored(e) => return Err(e.clone()),141 ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),142 ArrayThunk::Waiting => {}143 }144145 let ArrayThunk::Waiting =146 replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)147 else {148 unreachable!()149 };150151 let new_value = match evaluate(self.ctx.clone(), &self.src[index]) {152 Ok(v) => v,153 Err(e) => {154 self.cached.borrow_mut()[index] = ArrayThunk::Errored(e.clone());155 return Err(e);156 }157 };158 self.cached.borrow_mut()[index] = ArrayThunk::Computed(new_value.clone());159 Ok(Some(new_value))160 }161 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {162 #[derive(Trace)]163 struct ExprArrThunk {164 expr: ExprArray,165 index: usize,166 }167 impl ThunkValue for ExprArrThunk {168 type Output = Val;169170 fn get(&self) -> Result<Self::Output> {171 self.expr172 .get(self.index)173 .transpose()174 .expect("index checked")175 }176 }177178 if index >= self.len() {179 return None;180 }181 match &self.cached.borrow()[index] {182 ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),183 ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),184 ArrayThunk::Waiting | ArrayThunk::Pending => {}185 }186187 Some(Thunk::new(ExprArrThunk {188 expr: self.clone(),189 index,190 }))191 }192 fn get_cheap(&self, _index: usize) -> Option<Val> {193 None194 }195 fn is_cheap(&self) -> bool {196 false197 }198}199200#[derive(Trace, Debug)]201pub struct ExtendedArray {202 pub a: ArrValue,203 pub b: ArrValue,204 split: usize,205 len: usize,206}207impl ExtendedArray {208 pub fn new(a: ArrValue, b: ArrValue) -> Self {209 let a_len = a.len();210 let b_len = b.len();211 Self {212 a,213 b,214 split: a_len,215 len: a_len.checked_add(b_len).expect("too large array value"),216 }217 }218}219220struct WithExactSize<I>(I, usize);221impl<I, T> Iterator for WithExactSize<I>222where223 I: Iterator<Item = T>,224{225 type Item = T;226227 fn next(&mut self) -> Option<Self::Item> {228 self.0.next()229 }230 fn nth(&mut self, n: usize) -> Option<Self::Item> {231 self.0.nth(n)232 }233 fn size_hint(&self) -> (usize, Option<usize>) {234 (self.1, Some(self.1))235 }236}237impl<I> DoubleEndedIterator for WithExactSize<I>238where239 I: DoubleEndedIterator,240{241 fn next_back(&mut self) -> Option<Self::Item> {242 self.0.next_back()243 }244 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {245 self.0.nth_back(n)246 }247}248impl<I> ExactSizeIterator for WithExactSize<I>249where250 I: Iterator,251{252 fn len(&self) -> usize {253 self.1254 }255}256impl ArrayLike for ExtendedArray {257 fn get(&self, index: usize) -> Result<Option<Val>> {258 if self.split > index {259 self.a.get(index)260 } else {261 self.b.get(index - self.split)262 }263 }264 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {265 if self.split > index {266 self.a.get_lazy(index)267 } else {268 self.b.get_lazy(index - self.split)269 }270 }271272 fn len(&self) -> usize {273 self.len274 }275276 fn get_cheap(&self, index: usize) -> Option<Val> {277 if self.split > index {278 self.a.get_cheap(index)279 } else {280 self.b.get_cheap(index - self.split)281 }282 }283 fn is_cheap(&self) -> bool {284 self.a.is_cheap() && self.b.is_cheap()285 }286}287288#[derive(Trace, Debug)]289pub struct LazyArray(pub Vec<Thunk<Val>>);290impl ArrayLike for LazyArray {291 fn len(&self) -> usize {292 self.0.len()293 }294 fn get(&self, index: usize) -> Result<Option<Val>> {295 let Some(v) = self.0.get(index) else {296 return Ok(None);297 };298 v.evaluate().map(Some)299 }300 fn get_cheap(&self, _index: usize) -> Option<Val> {301 None302 }303 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {304 self.0.get(index).cloned()305 }306 fn is_cheap(&self) -> bool {307 false308 }309}310311#[derive(Trace, Debug)]312pub struct EagerArray(pub Vec<Val>);313impl ArrayLike for EagerArray {314 fn len(&self) -> usize {315 self.0.len()316 }317318 fn get(&self, index: usize) -> Result<Option<Val>> {319 Ok(self.0.get(index).cloned())320 }321322 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {323 self.0.get(index).cloned().map(Thunk::evaluated)324 }325326 fn get_cheap(&self, index: usize) -> Option<Val> {327 self.0.get(index).cloned()328 }329 fn is_cheap(&self) -> bool {330 true331 }332}333334/// Inclusive range type335#[derive(Debug, Trace, PartialEq, Eq)]336pub struct RangeArray {337 start: i32,338 end: i32,339}340impl RangeArray {341 pub fn empty() -> Self {342 Self::new_exclusive(0, 0)343 }344 pub fn new_exclusive(start: i32, end: i32) -> Self {345 end.checked_sub(1)346 .map_or_else(Self::empty, |end| Self { start, end })347 }348 pub fn new_inclusive(start: i32, end: i32) -> Self {349 Self { start, end }350 }351 fn range(&self) -> impl ExactSizeIterator<Item = i32> + DoubleEndedIterator {352 WithExactSize(353 self.start..=self.end,354 (self.end as usize)355 .wrapping_sub(self.start as usize)356 .wrapping_add(1),357 )358 }359}360361impl ArrayLike for RangeArray {362 fn len(&self) -> usize {363 self.range().len()364 }365 fn is_empty(&self) -> bool {366 self.range().len() == 0367 }368369 fn get(&self, index: usize) -> Result<Option<Val>> {370 Ok(self.get_cheap(index))371 }372373 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {374 self.get_cheap(index).map(Thunk::evaluated)375 }376377 fn get_cheap(&self, index: usize) -> Option<Val> {378 self.range().nth(index).map(|i| Val::Num(i.into()))379 }380 fn is_cheap(&self) -> bool {381 true382 }383}384385#[derive(Debug, Trace)]386pub struct ReverseArray(pub ArrValue);387impl ArrayLike for ReverseArray {388 fn len(&self) -> usize {389 self.0.len()390 }391392 fn get(&self, index: usize) -> Result<Option<Val>> {393 self.0.get(self.0.len() - index - 1)394 }395396 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {397 self.0.get_lazy(self.0.len() - index - 1)398 }399400 fn get_cheap(&self, index: usize) -> Option<Val> {401 self.0.get_cheap(self.0.len() - index - 1)402 }403 fn is_cheap(&self) -> bool {404 self.0.is_cheap()405 }406}407408#[derive(Trace, Clone, Debug)]409pub enum ArrayMapper {410 Plain(NativeFn!((Val) -> Val)),411 WithIndex(NativeFn!((u32, Val) -> Val)),412}413414#[derive(Trace, Debug, Clone)]415pub struct MappedArray {416 inner: ArrValue,417 cached: Cc<RefCell<Vec<ArrayThunk>>>,418 mapper: ArrayMapper,419}420impl MappedArray {421 pub fn new(inner: ArrValue, mapper: ArrayMapper) -> Self {422 let len = inner.len();423 Self {424 inner,425 cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting; len])),426 mapper,427 }428 }429 fn evaluate(&self, index: usize, value: Val) -> Result<Val> {430 match &self.mapper {431 ArrayMapper::Plain(f) => f.call(value),432 ArrayMapper::WithIndex(f) => f.call(index as u32, value),433 }434 }435}436impl ArrayLike for MappedArray {437 fn len(&self) -> usize {438 self.cached.borrow().len()439 }440441 fn get(&self, index: usize) -> Result<Option<Val>> {442 if index >= self.len() {443 return Ok(None);444 }445 match &self.cached.borrow()[index] {446 ArrayThunk::Computed(c) => return Ok(Some(c.clone())),447 ArrayThunk::Errored(e) => return Err(e.clone()),448 ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),449 ArrayThunk::Waiting => {}450 }451452 let ArrayThunk::Waiting =453 replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)454 else {455 unreachable!()456 };457458 let val = self459 .inner460 .get(index)461 .transpose()462 .expect("index checked")463 .and_then(|r| self.evaluate(index, r));464465 let new_value = match val {466 Ok(v) => v,467 Err(e) => {468 self.cached.borrow_mut()[index] = ArrayThunk::Errored(e.clone());469 return Err(e);470 }471 };472 self.cached.borrow_mut()[index] = ArrayThunk::Computed(new_value.clone());473 Ok(Some(new_value))474 }475 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {476 #[derive(Trace)]477 struct MappedArrayThunk {478 arr: MappedArray,479 index: usize,480 }481 impl ThunkValue for MappedArrayThunk {482 type Output = Val;483484 fn get(&self) -> Result<Self::Output> {485 self.arr.get(self.index).transpose().expect("index checked")486 }487 }488489 if index >= self.len() {490 return None;491 }492 match &self.cached.borrow()[index] {493 ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),494 ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),495 ArrayThunk::Waiting | ArrayThunk::Pending => {}496 }497498 Some(Thunk::new(MappedArrayThunk {499 arr: self.clone(),500 index,501 }))502 }503504 fn get_cheap(&self, _index: usize) -> Option<Val> {505 None506 }507 fn is_cheap(&self) -> bool {508 false509 }510}511512#[derive(Trace, Debug)]513pub struct RepeatedArray {514 data: ArrValue,515 repeats: usize,516 total_len: usize,517}518impl RepeatedArray {519 pub fn new(data: ArrValue, repeats: usize) -> Option<Self> {520 let total_len = data.len().checked_mul(repeats)?;521 Some(Self {522 data,523 repeats,524 total_len,525 })526 }527}528529impl ArrayLike for RepeatedArray {530 fn len(&self) -> usize {531 self.total_len532 }533534 fn get(&self, index: usize) -> Result<Option<Val>> {535 if index > self.total_len {536 return Ok(None);537 }538 self.data.get(index % self.data.len())539 }540541 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {542 if index > self.total_len {543 return None;544 }545 self.data.get_lazy(index % self.data.len())546 }547548 fn get_cheap(&self, index: usize) -> Option<Val> {549 if index > self.total_len {550 return None;551 }552 self.data.get_cheap(index % self.data.len())553 }554 fn is_cheap(&self) -> bool {555 self.data.is_cheap()556 }557}558559#[derive(Trace, Debug)]560pub struct PickObjectValues {561 obj: ObjValue,562 keys: Vec<IStr>,563}564565impl PickObjectValues {566 pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {567 Self { obj, keys }568 }569}570571impl ArrayLike for PickObjectValues {572 fn len(&self) -> usize {573 self.keys.len()574 }575576 fn get(&self, index: usize) -> Result<Option<Val>> {577 let Some(key) = self.keys.get(index) else {578 return Ok(None);579 };580 Ok(Some(self.obj.get_or_bail(key.clone())?))581 }582583 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {584 let key = self.keys.get(index)?;585 Some(self.obj.get_lazy_or_bail(key.clone()))586 }587588 fn get_cheap(&self, _index: usize) -> Option<Val> {589 None590 }591592 fn is_cheap(&self) -> bool {593 false594 }595}596597#[derive(Trace, Debug)]598pub struct PickObjectKeyValues {599 obj: ObjValue,600 keys: Vec<IStr>,601}602603impl PickObjectKeyValues {604 pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {605 Self { obj, keys }606 }607}608609#[derive(Typed)]610pub struct KeyValue {611 key: IStr,612 value: Thunk<Val>,613}614615impl ArrayLike for PickObjectKeyValues {616 fn len(&self) -> usize {617 self.keys.len()618 }619620 fn get(&self, index: usize) -> Result<Option<Val>> {621 let Some(key) = self.keys.get(index) else {622 return Ok(None);623 };624 Ok(Some(625 KeyValue::into_untyped(KeyValue {626 key: key.clone(),627 value: Thunk::evaluated(self.obj.get_or_bail(key.clone())?),628 })629 .expect("convertible"),630 ))631 }632633 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {634 let key = self.keys.get(index)?;635 // Nothing can fail in the key part, yet value is still636 // lazy-evaluated637 Some(Thunk::evaluated(638 KeyValue::into_untyped(KeyValue {639 key: key.clone(),640 value: self.obj.get_lazy_or_bail(key.clone()),641 })642 .expect("convertible"),643 ))644 }645646 fn get_cheap(&self, _index: usize) -> Option<Val> {647 None648 }649650 fn is_cheap(&self) -> bool {651 false652 }653}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;