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.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.rsdiffbeforeafterboth1#![allow(clippy::similar_names)]23use std::{4 cell::{Ref, RefCell, RefMut},5 collections::HashMap,6 f64,7 rc::Rc,8};910pub use arrays::*;11pub use compat::*;12pub use encoding::*;13pub use hash::*;14use jrsonnet_evaluator::{15 error::Result,16 function::{CallLocation, FuncVal, TlaArg},17 trace::PathResolver,18 val::NumValue,19 ContextBuilder, IStr, ObjValue, ObjValueBuilder, Thunk, Val,20};21use jrsonnet_gcmodule::{Acyclic, Cc, Trace};22use jrsonnet_parser::Source;23pub use manifest::*;24pub use math::*;25pub use misc::*;26pub use objects::*;27pub use operator::*;28pub use parse::*;29pub use sets::*;30pub use sort::*;31pub use strings::*;32pub use types::*;3334#[cfg(feature = "exp-regex")]35pub use crate::regex::*;3637mod arrays;38mod compat;39mod encoding;40mod hash;41mod keyf;42mod manifest;43mod math;44mod misc;45mod objects;46mod operator;47mod parse;48#[cfg(feature = "exp-regex")]49mod regex;50mod sets;51mod sort;52mod strings;53mod types;5455#[allow(clippy::too_many_lines)]56pub fn stdlib_uncached(settings: Cc<RefCell<Settings>>) -> ObjValue {57 let mut builder = ObjValueBuilder::new();5859 // FIXME: Use PHF60 for (name, builtin) in [61 // Types62 ("type", builtin_type::INST),63 ("isString", builtin_is_string::INST),64 ("isNumber", builtin_is_number::INST),65 ("isBoolean", builtin_is_boolean::INST),66 ("isObject", builtin_is_object::INST),67 ("isArray", builtin_is_array::INST),68 ("isFunction", builtin_is_function::INST),69 ("isNull", builtin_is_null::INST),70 // Arrays71 ("makeArray", builtin_make_array::INST),72 ("repeat", builtin_repeat::INST),73 ("slice", builtin_slice::INST),74 ("map", builtin_map::INST),75 ("mapWithIndex", builtin_map_with_index::INST),76 ("mapWithKey", builtin_map_with_key::INST),77 ("flatMap", builtin_flatmap::INST),78 ("filter", builtin_filter::INST),79 ("foldl", builtin_foldl::INST),80 ("foldr", builtin_foldr::INST),81 ("range", builtin_range::INST),82 ("join", builtin_join::INST),83 ("lines", builtin_lines::INST),84 ("resolvePath", builtin_resolve_path::INST),85 ("deepJoin", builtin_deep_join::INST),86 ("reverse", builtin_reverse::INST),87 ("any", builtin_any::INST),88 ("all", builtin_all::INST),89 ("member", builtin_member::INST),90 ("find", builtin_find::INST),91 ("contains", builtin_contains::INST),92 ("count", builtin_count::INST),93 ("avg", builtin_avg::INST),94 ("removeAt", builtin_remove_at::INST),95 ("remove", builtin_remove::INST),96 ("flattenArrays", builtin_flatten_arrays::INST),97 ("flattenDeepArray", builtin_flatten_deep_array::INST),98 ("prune", builtin_prune::INST),99 ("filterMap", builtin_filter_map::INST),100 // Math101 ("abs", builtin_abs::INST),102 ("sign", builtin_sign::INST),103 ("max", builtin_max::INST),104 ("min", builtin_min::INST),105 ("clamp", builtin_clamp::INST),106 ("sum", builtin_sum::INST),107 ("modulo", builtin_modulo::INST),108 ("floor", builtin_floor::INST),109 ("ceil", builtin_ceil::INST),110 ("log", builtin_log::INST),111 ("log2", builtin_log2::INST),112 ("log10", builtin_log10::INST),113 ("pow", builtin_pow::INST),114 ("sqrt", builtin_sqrt::INST),115 ("sin", builtin_sin::INST),116 ("cos", builtin_cos::INST),117 ("tan", builtin_tan::INST),118 ("asin", builtin_asin::INST),119 ("acos", builtin_acos::INST),120 ("atan", builtin_atan::INST),121 ("atan2", builtin_atan2::INST),122 ("exp", builtin_exp::INST),123 ("mantissa", builtin_mantissa::INST),124 ("exponent", builtin_exponent::INST),125 ("round", builtin_round::INST),126 ("isEven", builtin_is_even::INST),127 ("isOdd", builtin_is_odd::INST),128 ("isInteger", builtin_is_integer::INST),129 ("isDecimal", builtin_is_decimal::INST),130 ("deg2rad", builtin_deg2rad::INST),131 ("rad2deg", builtin_rad2deg::INST),132 ("hypot", builtin_hypot::INST),133 // Operator134 ("mod", builtin_mod::INST),135 ("primitiveEquals", builtin_primitive_equals::INST),136 ("equals", builtin_equals::INST),137 ("xor", builtin_xor::INST),138 ("xnor", builtin_xnor::INST),139 ("format", builtin_format::INST),140 // Sort141 ("sort", builtin_sort::INST),142 ("uniq", builtin_uniq::INST),143 ("set", builtin_set::INST),144 ("minArray", builtin_min_array::INST),145 ("maxArray", builtin_max_array::INST),146 // Hash147 ("md5", builtin_md5::INST),148 ("sha1", builtin_sha1::INST),149 ("sha256", builtin_sha256::INST),150 ("sha512", builtin_sha512::INST),151 ("sha3", builtin_sha3::INST),152 // Encoding153 ("encodeUTF8", builtin_encode_utf8::INST),154 ("decodeUTF8", builtin_decode_utf8::INST),155 ("base64", builtin_base64::INST),156 ("base64Decode", builtin_base64_decode::INST),157 ("base64DecodeBytes", builtin_base64_decode_bytes::INST),158 // Objects159 ("objectFieldsEx", builtin_object_fields_ex::INST),160 ("objectFields", builtin_object_fields::INST),161 ("objectFieldsAll", builtin_object_fields_all::INST),162 ("objectValues", builtin_object_values::INST),163 ("objectValuesAll", builtin_object_values_all::INST),164 ("objectKeysValues", builtin_object_keys_values::INST),165 ("objectKeysValuesAll", builtin_object_keys_values_all::INST),166 ("objectHasEx", builtin_object_has_ex::INST),167 ("objectHas", builtin_object_has::INST),168 ("objectHasAll", builtin_object_has_all::INST),169 ("objectRemoveKey", builtin_object_remove_key::INST),170 // Manifest171 ("escapeStringJson", builtin_escape_string_json::INST),172 ("escapeStringPython", builtin_escape_string_python::INST),173 ("escapeStringXML", builtin_escape_string_xml::INST),174 ("manifestJsonEx", builtin_manifest_json_ex::INST),175 ("manifestJson", builtin_manifest_json::INST),176 ("manifestJsonMinified", builtin_manifest_json_minified::INST),177 ("manifestYamlDoc", builtin_manifest_yaml_doc::INST),178 ("manifestYamlStream", builtin_manifest_yaml_stream::INST),179 ("manifestTomlEx", builtin_manifest_toml_ex::INST),180 ("manifestToml", builtin_manifest_toml::INST),181 ("toString", builtin_to_string::INST),182 ("manifestPython", builtin_manifest_python::INST),183 ("manifestPythonVars", builtin_manifest_python_vars::INST),184 ("manifestXmlJsonml", builtin_manifest_xml_jsonml::INST),185 ("manifestIni", builtin_manifest_ini::INST),186 // Parse187 ("parseJson", builtin_parse_json::INST),188 ("parseYaml", builtin_parse_yaml::INST),189 // Strings190 ("codepoint", builtin_codepoint::INST),191 ("substr", builtin_substr::INST),192 ("char", builtin_char::INST),193 ("strReplace", builtin_str_replace::INST),194 ("escapeStringBash", builtin_escape_string_bash::INST),195 ("escapeStringDollars", builtin_escape_string_dollars::INST),196 ("isEmpty", builtin_is_empty::INST),197 ("equalsIgnoreCase", builtin_equals_ignore_case::INST),198 ("splitLimit", builtin_splitlimit::INST),199 ("splitLimitR", builtin_splitlimitr::INST),200 ("split", builtin_split::INST),201 ("asciiUpper", builtin_ascii_upper::INST),202 ("asciiLower", builtin_ascii_lower::INST),203 ("findSubstr", builtin_find_substr::INST),204 ("parseInt", builtin_parse_int::INST),205 #[cfg(feature = "exp-bigint")]206 ("bigint", builtin_bigint::INST),207 ("parseOctal", builtin_parse_octal::INST),208 ("parseHex", builtin_parse_hex::INST),209 ("stringChars", builtin_string_chars::INST),210 ("lstripChars", builtin_lstrip_chars::INST),211 ("rstripChars", builtin_rstrip_chars::INST),212 ("stripChars", builtin_strip_chars::INST),213 ("trim", builtin_trim::INST),214 // Misc215 ("length", builtin_length::INST),216 ("get", builtin_get::INST),217 ("startsWith", builtin_starts_with::INST),218 ("endsWith", builtin_ends_with::INST),219 ("assertEqual", builtin_assert_equal::INST),220 ("mergePatch", builtin_merge_patch::INST),221 // Sets222 ("setMember", builtin_set_member::INST),223 ("setInter", builtin_set_inter::INST),224 ("setDiff", builtin_set_diff::INST),225 ("setUnion", builtin_set_union::INST),226 // Regex227 #[cfg(feature = "exp-regex")]228 ("regexQuoteMeta", builtin_regex_quote_meta::INST),229 // Compat230 ("__compare", builtin___compare::INST),231 ("__compare_array", builtin___compare_array::INST),232 ("__array_less", builtin___array_less::INST),233 ("__array_greater", builtin___array_greater::INST),234 ("__array_less_or_equal", builtin___array_less_or_equal::INST),235 (236 "__array_greater_or_equal",237 builtin___array_greater_or_equal::INST,238 ),239 ]240 .iter()241 .copied()242 {243 builder.method(name, builtin);244 }245246 builder.method(247 "extVar",248 builtin_ext_var {249 settings: settings.clone(),250 },251 );252 builder.method(253 "native",254 builtin_native {255 settings: settings.clone(),256 },257 );258 builder.method("trace", builtin_trace { settings });259 builder.method("id", FuncVal::Id);260261 builder.field("pi").hide().value(Val::Num(262 NumValue::new(f64::consts::PI).expect("pi is finite"),263 ));264265 #[cfg(feature = "exp-regex")]266 {267 // Regex268 let regex_cache = RegexCache::default();269 builder.method(270 "regexFullMatch",271 builtin_regex_full_match {272 cache: regex_cache.clone(),273 },274 );275 builder.method(276 "regexPartialMatch",277 builtin_regex_partial_match {278 cache: regex_cache.clone(),279 },280 );281 builder.method(282 "regexReplace",283 builtin_regex_replace {284 cache: regex_cache.clone(),285 },286 );287 builder.method(288 "regexGlobalReplace",289 builtin_regex_global_replace { cache: regex_cache },290 );291 };292293 builder.build()294}295296pub trait TracePrinter: Acyclic {297 fn print_trace(&self, loc: CallLocation, value: IStr);298}299300#[derive(Acyclic)]301pub struct StdTracePrinter {302 resolver: PathResolver,303}304impl StdTracePrinter {305 pub fn new(resolver: PathResolver) -> Self {306 Self { resolver }307 }308}309impl TracePrinter for StdTracePrinter {310 fn print_trace(&self, loc: CallLocation, value: IStr) {311 eprint!("TRACE:");312 if let Some(loc) = loc.0 {313 let locs = loc.0.map_source_locations(&[loc.1]);314 eprint!(315 " {}:{}",316 loc.0.source_path().path().map_or_else(317 || loc.0.source_path().to_string(),318 |p| self.resolver.resolve(p)319 ),320 locs[0].line321 );322 }323 eprintln!(" {value}");324 }325}326327#[derive(Clone, Trace)]328pub struct Settings {329 /// Used for `std.extVar`330 pub ext_vars: HashMap<IStr, TlaArg>,331 /// Used for `std.native`332 pub ext_natives: HashMap<IStr, FuncVal>,333 /// Used for `std.trace`334 pub trace_printer: Rc<dyn TracePrinter>,335 /// Used for `std.thisFile`336 pub path_resolver: PathResolver,337}338339#[derive(Trace, Clone)]340pub struct ContextInitializer {341 /// std without applied thisFile overlay342 stdlib_obj: ObjValue,343 settings: Cc<RefCell<Settings>>,344}345impl ContextInitializer {346 pub fn new(resolver: PathResolver) -> Self {347 let settings = Settings {348 ext_vars: HashMap::new(),349 ext_natives: HashMap::new(),350 trace_printer: Rc::new(StdTracePrinter::new(resolver.clone())),351 path_resolver: resolver,352 };353 let settings = Cc::new(RefCell::new(settings));354 let stdlib_obj = stdlib_uncached(settings.clone());355 Self {356 stdlib_obj,357 settings,358 }359 }360 pub fn settings(&self) -> Ref<'_, Settings> {361 self.settings.borrow()362 }363 pub fn settings_mut(&self) -> RefMut<'_, Settings> {364 self.settings.borrow_mut()365 }366 pub fn add_ext_var(&self, name: IStr, value: Val) {367 self.settings_mut()368 .ext_vars369 .insert(name, TlaArg::Val(value));370 }371 pub fn add_ext_str(&self, name: IStr, value: IStr) {372 self.settings_mut()373 .ext_vars374 .insert(name, TlaArg::String(value));375 }376 pub fn add_ext_code(&self, name: &str, code: impl AsRef<str>) -> Result<()> {377 // self.data_mut().volatile_files.insert(source_name, code);378 self.settings_mut()379 .ext_vars380 .insert(name.into(), TlaArg::InlineCode(code.as_ref().to_owned()));381 Ok(())382 }383 pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {384 self.settings_mut()385 .ext_natives386 .insert(name.into(), cb.into());387 }388}389impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {390 fn reserve_vars(&self) -> usize {391 1392 }393 fn populate(&self, source: Source, builder: &mut ContextBuilder) {394 let mut std = ObjValueBuilder::new();395 std.with_super(self.stdlib_obj.clone());396 std.field("thisFile").hide().value({397 let source_path = source.source_path();398 source_path.path().map_or_else(399 || source_path.to_string(),400 |p| self.settings().path_resolver.resolve(p),401 )402 });403 let stdlib_with_this_file = std.build();404405 builder.bind("std", Thunk::evaluated(Val::Obj(stdlib_with_this_file)));406 }407 fn as_any(&self) -> &dyn std::any::Any {408 self409 }410}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;