difftreelog
feat lazy values in builtin
in: master
8 files changed
crates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -1,4 +1,4 @@
-use crate::function::StaticBuiltin;
+use crate::function::{CallLocation, StaticBuiltin};
use crate::typed::{Any, PositiveF64, VecVal, M1};
use crate::{
builtin::manifest::{manifest_yaml_ex, ManifestYamlOptions},
@@ -12,7 +12,6 @@
use crate::{Either, ObjValue};
use format::{format_arr, format_obj};
use jrsonnet_interner::IStr;
-use jrsonnet_parser::ExprLocation;
use serde::Deserialize;
use serde_yaml::DeserializingQuirks;
use std::collections::HashMap;
@@ -29,7 +28,7 @@
pub fn std_format(str: IStr, vals: Val) -> Result<String> {
push_frame(
- None,
+ CallLocation::native(),
|| format!("std.format of {}", str),
|| {
Ok(match vals {
@@ -467,9 +466,9 @@
}
#[jrsonnet_macros::builtin]
-fn builtin_trace(#[location] loc: Option<&ExprLocation>, str: IStr, rest: Any) -> Result<Any> {
+fn builtin_trace(loc: CallLocation, str: IStr, rest: Any) -> Result<Any> {
eprint!("TRACE:");
- if let Some(loc) = loc {
+ if let Some(loc) = loc.0 {
with_state(|s| {
let locs = s.map_source_locations(&loc.0, &[loc.1]);
eprint!(
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -4,6 +4,7 @@
builtin::{std_slice, BUILTINS},
error::Error::*,
evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},
+ function::CallLocation,
gc::TraceBox,
push_frame, throw, with_state, ArrValue, Bindable, Context, ContextCreator, FuncDesc, FuncVal,
FutureWrapper, GcHashMap, LazyBinding, LazyVal, LazyValValue, ObjValue, ObjValueBuilder,
@@ -12,8 +13,8 @@
use gcmodule::{Cc, Trace};
use jrsonnet_interner::IStr;
use jrsonnet_parser::{
- ArgsDesc, AssertStmt, BindSpec, CompSpec, Expr, ExprLocation, FieldMember, ForSpecData,
- IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc,
+ ArgsDesc, AssertStmt, BindSpec, CompSpec, Expr, FieldMember, ForSpecData, IfSpecData,
+ LiteralType, LocExpr, Member, ObjBody, ParamsDesc,
};
use jrsonnet_types::ValType;
pub mod operator;
@@ -192,7 +193,7 @@
Ok(match field_name {
jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),
jrsonnet_parser::FieldName::Dyn(expr) => push_frame(
- Some(&expr.1),
+ CallLocation::new(&expr.1),
|| "evaluating field name".to_string(),
|| {
let value = evaluate(context, expr)?;
@@ -442,7 +443,7 @@
context: Context,
value: &LocExpr,
args: &ArgsDesc,
- loc: Option<&ExprLocation>,
+ loc: CallLocation,
tailstrict: bool,
) -> Result<Val> {
let value = evaluate(context.clone(), value)?;
@@ -463,13 +464,13 @@
let value = &assertion.0;
let msg = &assertion.1;
let assertion_result = push_frame(
- Some(&value.1),
+ CallLocation::new(&value.1),
|| "assertion condition".to_owned(),
|| bool::try_from(evaluate(context.clone(), value)?),
)?;
if !assertion_result {
push_frame(
- Some(&value.1),
+ CallLocation::new(&value.1),
|| "assertion failure".to_owned(),
|| {
if let Some(msg) = msg {
@@ -519,7 +520,7 @@
BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, v1, *o, v2)?,
UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,
Var(name) => push_frame(
- Some(loc),
+ CallLocation::new(loc),
|| format!("variable <{}> access", name),
|| context.binding(name.clone())?.evaluate(),
)?,
@@ -528,7 +529,7 @@
(Val::Obj(v), Val::Str(s)) => {
let sn = s.clone();
push_frame(
- Some(loc),
+ CallLocation::new(loc),
|| format!("field <{}> access", sn),
|| {
if let Some(v) = v.get(s.clone())? {
@@ -625,7 +626,7 @@
&Val::Obj(evaluate_object(context, t)?),
)?,
Apply(value, args, tailstrict) => {
- evaluate_apply(context, value, args, Some(loc), *tailstrict)?
+ evaluate_apply(context, value, args, CallLocation::new(loc), *tailstrict)?
}
Function(params, body) => {
evaluate_method(context, "anonymous".into(), params.clone(), body.clone())
@@ -640,7 +641,7 @@
evaluate(context, returned)?
}
ErrorStmt(e) => push_frame(
- Some(loc),
+ CallLocation::new(loc),
|| "error statement".to_owned(),
|| throw!(RuntimeError(IStr::try_from(evaluate(context, e)?)?,)),
)?,
@@ -650,7 +651,7 @@
cond_else,
} => {
if push_frame(
- Some(loc),
+ CallLocation::new(loc),
|| "if condition".to_owned(),
|| bool::try_from(evaluate(context.clone(), &cond.0)?),
)? {
@@ -689,7 +690,7 @@
let mut import_location = tmp.to_path_buf();
import_location.pop();
push_frame(
- Some(loc),
+ CallLocation::new(loc),
|| format!("import {:?}", path),
|| with_state(|s| s.import_file(&import_location, path)),
)?
crates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function.rs
+++ b/crates/jrsonnet-evaluator/src/function.rs
@@ -12,6 +12,19 @@
use jrsonnet_parser::{ArgsDesc, ExprLocation, LocExpr, ParamsDesc};
use std::{borrow::Cow, collections::HashMap, convert::TryFrom};
+#[derive(Clone, Copy)]
+pub struct CallLocation<'l>(pub Option<&'l ExprLocation>);
+impl<'l> CallLocation<'l> {
+ pub fn new(loc: &'l ExprLocation) -> Self {
+ Self(Some(loc))
+ }
+}
+impl CallLocation<'static> {
+ pub fn native() -> Self {
+ Self(None)
+ }
+}
+
#[derive(Trace)]
struct EvaluateLazyVal {
context: Context,
@@ -383,12 +396,7 @@
pub trait Builtin: Trace {
fn name(&self) -> &str;
fn params(&self) -> &[BuiltinParam];
- fn call(
- &self,
- context: Context,
- loc: Option<&ExprLocation>,
- args: &dyn ArgsLike,
- ) -> Result<Val>;
+ fn call(&self, context: Context, loc: CallLocation, args: &dyn ArgsLike) -> Result<Val>;
}
pub trait StaticBuiltin: Builtin + Send + Sync
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -28,7 +28,7 @@
pub use dynamic::*;
use error::{Error::*, LocError, Result, StackTraceElement};
pub use evaluate::*;
-use function::{Builtin, TlaArg};
+use function::{Builtin, CallLocation, TlaArg};
use gc::{GcHashMap, TraceBox};
use gcmodule::{Cc, Trace, Weak};
pub use import::*;
@@ -173,6 +173,7 @@
/// Global state is fine here.
pub(crate) static EVAL_STATE: RefCell<Option<EvaluationState>> = RefCell::new(None)
}
+
pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {
EVAL_STATE.with(|s| {
f(s.borrow().as_ref().expect(
@@ -181,7 +182,7 @@
})
}
pub fn push_frame<T>(
- e: Option<&ExprLocation>,
+ e: CallLocation,
frame_desc: impl FnOnce() -> String,
f: impl FnOnce() -> Result<T>,
) -> Result<T> {
@@ -345,7 +346,7 @@
/// Executes code creating a new stack frame
pub fn push<T>(
&self,
- e: Option<&ExprLocation>,
+ e: CallLocation,
frame_desc: impl FnOnce() -> String,
f: impl FnOnce() -> Result<T>,
) -> Result<T> {
@@ -368,7 +369,7 @@
}
if let Err(mut err) = result {
err.trace_mut().0.push(StackTraceElement {
- location: e.cloned(),
+ location: e.0.cloned(),
desc: frame_desc(),
});
return Err(err);
@@ -512,7 +513,7 @@
|| {
func.evaluate(
self.create_default_context(),
- None,
+ CallLocation::native(),
&self.settings().tla_vars,
true,
)
crates/jrsonnet-evaluator/src/native.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/native.rs
+++ b/crates/jrsonnet-evaluator/src/native.rs
@@ -1,11 +1,10 @@
#![allow(clippy::type_complexity)]
-use crate::function::{parse_builtin_call, ArgsLike, Builtin, BuiltinParam};
+use crate::function::{parse_builtin_call, ArgsLike, Builtin, BuiltinParam, CallLocation};
use crate::gc::TraceBox;
use crate::Context;
use crate::{error::Result, Val};
use gcmodule::Trace;
-use jrsonnet_parser::ExprLocation;
use std::path::Path;
use std::rc::Rc;
@@ -32,18 +31,13 @@
&self.params
}
- fn call(
- &self,
- context: Context,
- loc: Option<&ExprLocation>,
- args: &dyn ArgsLike,
- ) -> Result<Val> {
+ fn call(&self, context: Context, loc: CallLocation, args: &dyn ArgsLike) -> Result<Val> {
let args = parse_builtin_call(context, &self.params, args, true)?;
let mut out_args = Vec::with_capacity(self.params.len());
for p in self.params.iter() {
out_args.push(args[&p.name].evaluate()?);
}
- self.handler.call(loc.map(|l| l.0.clone()), &out_args)
+ self.handler.call(loc.0.map(|l| l.0.clone()), &out_args)
}
}
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth1use std::convert::{TryFrom, TryInto};23use jrsonnet_interner::IStr;4pub use jrsonnet_macros::Typed;5use jrsonnet_types::{ComplexValType, ValType};67use crate::{8 error::{Error::*, LocError, Result},9 throw,10 typed::CheckType,11 ArrValue, FuncVal, IndexableVal, ObjValue, ObjValueBuilder, Val,12};1314pub trait TypedObj: Typed {15 fn serialize(self, out: &mut ObjValueBuilder) -> Result<()>;16 fn parse(obj: &ObjValue) -> Result<Self>;17 fn into_object(self) -> Result<ObjValue> {18 let mut builder = ObjValueBuilder::new();19 self.serialize(&mut builder)?;20 Ok(builder.build())21 }22}2324pub trait Typed: TryFrom<Val, Error = LocError> + TryInto<Val, Error = LocError> {25 const TYPE: &'static ComplexValType;26}2728macro_rules! impl_int {29 ($($ty:ty)*) => {$(30 impl Typed for $ty {31 const TYPE: &'static ComplexValType =32 &ComplexValType::BoundedNumber(Some(Self::MIN as f64), Some(Self::MAX as f64));33 }34 impl TryFrom<Val> for $ty {35 type Error = LocError;3637 fn try_from(value: Val) -> Result<Self> {38 <Self as Typed>::TYPE.check(&value)?;39 match value {40 Val::Num(n) => {41 if n.trunc() != n {42 throw!(RuntimeError(43 format!(44 "cannot convert number with fractional part to {}",45 stringify!($ty)46 )47 .into()48 ))49 }50 Ok(n as Self)51 }52 _ => unreachable!(),53 }54 }55 }56 impl TryFrom<$ty> for Val {57 type Error = LocError;5859 fn try_from(value: $ty) -> Result<Self> {60 Ok(Self::Num(value as f64))61 }62 }63 )*};64}6566impl_int!(i8 u8 i16 u16 i32 u32);6768impl Typed for f64 {69 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);70}71impl TryFrom<Val> for f64 {72 type Error = LocError;7374 fn try_from(value: Val) -> Result<Self> {75 <Self as Typed>::TYPE.check(&value)?;76 match value {77 Val::Num(n) => Ok(n),78 _ => unreachable!(),79 }80 }81}82impl TryFrom<f64> for Val {83 type Error = LocError;8485 fn try_from(value: f64) -> Result<Self> {86 Ok(Self::Num(value))87 }88}8990pub struct PositiveF64(pub f64);91impl Typed for PositiveF64 {92 const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(0.0), None);93}94impl TryFrom<Val> for PositiveF64 {95 type Error = LocError;9697 fn try_from(value: Val) -> Result<Self> {98 <Self as Typed>::TYPE.check(&value)?;99 match value {100 Val::Num(n) => Ok(Self(n)),101 _ => unreachable!(),102 }103 }104}105impl TryFrom<PositiveF64> for Val {106 type Error = LocError;107108 fn try_from(value: PositiveF64) -> Result<Self> {109 Ok(Self::Num(value.0))110 }111}112113impl Typed for usize {114 // It is possible to store 54 bits of precision in f64, but leaving u32::MAX here for compatibility115 const TYPE: &'static ComplexValType =116 &ComplexValType::BoundedNumber(Some(0.0), Some(4294967295.0));117}118impl TryFrom<Val> for usize {119 type Error = LocError;120121 fn try_from(value: Val) -> Result<Self> {122 <Self as Typed>::TYPE.check(&value)?;123 match value {124 Val::Num(n) => {125 if n.trunc() != n {126 throw!(RuntimeError(127 "cannot convert number with fractional part to usize".into()128 ))129 }130 Ok(n as Self)131 }132 _ => unreachable!(),133 }134 }135}136impl TryFrom<usize> for Val {137 type Error = LocError;138139 fn try_from(value: usize) -> Result<Self> {140 if value > u32::MAX as usize {141 throw!(RuntimeError("number is too large".into()))142 }143 Ok(Self::Num(value as f64))144 }145}146147impl Typed for IStr {148 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);149}150impl TryFrom<Val> for IStr {151 type Error = LocError;152153 fn try_from(value: Val) -> Result<Self> {154 <Self as Typed>::TYPE.check(&value)?;155 match value {156 Val::Str(s) => Ok(s),157 _ => unreachable!(),158 }159 }160}161impl TryFrom<IStr> for Val {162 type Error = LocError;163164 fn try_from(value: IStr) -> Result<Self> {165 Ok(Self::Str(value))166 }167}168169impl Typed for String {170 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);171}172impl TryFrom<Val> for String {173 type Error = LocError;174175 fn try_from(value: Val) -> Result<Self> {176 <Self as Typed>::TYPE.check(&value)?;177 match value {178 Val::Str(s) => Ok(s.to_string()),179 _ => unreachable!(),180 }181 }182}183impl TryFrom<String> for Val {184 type Error = LocError;185186 fn try_from(value: String) -> Result<Self> {187 Ok(Self::Str(value.into()))188 }189}190191impl Typed for char {192 const TYPE: &'static ComplexValType = &ComplexValType::Char;193}194impl TryFrom<Val> for char {195 type Error = LocError;196197 fn try_from(value: Val) -> Result<Self> {198 <Self as Typed>::TYPE.check(&value)?;199 match value {200 Val::Str(s) => Ok(s.chars().next().unwrap()),201 _ => unreachable!(),202 }203 }204}205impl TryFrom<char> for Val {206 type Error = LocError;207208 fn try_from(value: char) -> Result<Self> {209 Ok(Self::Str(value.to_string().into()))210 }211}212213impl<T> Typed for Vec<T>214where215 T: Typed,216 T: TryFrom<Val, Error = LocError>,217 T: TryInto<Val, Error = LocError>,218{219 const TYPE: &'static ComplexValType = &ComplexValType::ArrayRef(T::TYPE);220}221impl<T> TryFrom<Val> for Vec<T>222where223 T: Typed,224 T: TryFrom<Val, Error = LocError>,225 T: TryInto<Val, Error = LocError>,226{227 type Error = LocError;228229 fn try_from(value: Val) -> Result<Self> {230 <Self as Typed>::TYPE.check(&value)?;231 match value {232 Val::Arr(a) => {233 let mut o = Self::with_capacity(a.len());234 for i in a.iter() {235 o.push(T::try_from(i?)?);236 }237 Ok(o)238 }239 _ => unreachable!(),240 }241 }242}243impl<T> TryFrom<Vec<T>> for Val244where245 T: Typed,246 T: TryFrom<Self, Error = LocError>,247 T: TryInto<Self, Error = LocError>,248{249 type Error = LocError;250251 fn try_from(value: Vec<T>) -> Result<Self> {252 let mut o = Vec::with_capacity(value.len());253 for i in value {254 o.push(i.try_into()?);255 }256 Ok(Self::Arr(o.into()))257 }258}259260/// To be used in Vec<Any>261/// Regular Val can't be used here, because it has wrong TryFrom::Error type262#[derive(Clone)]263pub struct Any(pub Val);264265impl Typed for Any {266 const TYPE: &'static ComplexValType = &ComplexValType::Any;267}268impl TryFrom<Val> for Any {269 type Error = LocError;270271 fn try_from(value: Val) -> Result<Self> {272 Ok(Self(value))273 }274}275impl TryFrom<Any> for Val {276 type Error = LocError;277278 fn try_from(value: Any) -> Result<Self> {279 Ok(value.0)280 }281}282283/// Specialization, provides faster TryFrom<VecVal> for Val284pub struct VecVal(pub Vec<Val>);285286impl Typed for VecVal {287 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);288}289impl TryFrom<Val> for VecVal {290 type Error = LocError;291292 fn try_from(value: Val) -> Result<Self> {293 <Self as Typed>::TYPE.check(&value)?;294 match value {295 Val::Arr(a) => Ok(Self(a.evaluated()?.to_vec())),296 _ => unreachable!(),297 }298 }299}300impl TryFrom<VecVal> for Val {301 type Error = LocError;302303 fn try_from(value: VecVal) -> Result<Self> {304 Ok(Self::Arr(value.0.into()))305 }306}307308pub struct M1;309impl Typed for M1 {310 const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(-1.0), Some(-1.0));311}312impl TryFrom<Val> for M1 {313 type Error = LocError;314315 fn try_from(value: Val) -> Result<Self> {316 <Self as Typed>::TYPE.check(&value)?;317 Ok(Self)318 }319}320impl TryFrom<M1> for Val {321 type Error = LocError;322323 fn try_from(_: M1) -> Result<Self> {324 Ok(Self::Num(-1.0))325 }326}327328macro_rules! decl_either {329 ($($name: ident, $($id: ident)*);*) => {$(330 pub enum $name<$($id),*> {331 $($id($id)),*332 }333 impl<$($id),*> Typed for $name<$($id),*>334 where335 $($id: Typed,)*336 {337 const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[$($id::TYPE),*]);338 }339 impl<$($id),*> TryFrom<Val> for $name<$($id),*>340 where341 $($id: Typed,)*342 {343 type Error = LocError;344345 fn try_from(value: Val) -> Result<Self> {346 $(347 if $id::TYPE.check(&value).is_ok() {348 $id::try_from(value).map(Self::$id)349 } else350 )* {351 <Self as Typed>::TYPE.check(&value)?;352 unreachable!()353 }354 }355 }356 impl<$($id),*> TryFrom<$name<$($id),*>> for Val357 where358 $($id: Typed,)*359 {360 type Error = LocError;361 fn try_from(value: $name<$($id),*>) -> Result<Self> {362 match value {$(363 $name::$id(v) => v.try_into()364 ),*}365 }366 }367 )*}368}369decl_either!(370 Either1, A;371 Either2, A B;372 Either3, A B C;373 Either4, A B C D;374 Either5, A B C D E;375 Either6, A B C D E F;376 Either7, A B C D E F G377);378#[macro_export]379macro_rules! Either {380 ($a:ty) => {Either1<$a>};381 ($a:ty, $b:ty) => {Either2<$a, $b>};382 ($a:ty, $b:ty, $c:ty) => {Either3<$a, $b, $c>};383 ($a:ty, $b:ty, $c:ty, $d:ty) => {Either4<$a, $b, $c, $d>};384 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty) => {Either5<$a, $b, $c, $d, $e>};385 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty) => {Either6<$a, $b, $c, $d, $e, $f>};386 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty, $g:ty) => {Either7<$a, $b, $c, $d, $e, $f, $g>};387}388389pub type MyType = Either![u32, f64, String];390391impl Typed for ArrValue {392 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);393}394impl TryFrom<Val> for ArrValue {395 type Error = LocError;396397 fn try_from(value: Val) -> Result<Self> {398 <Self as Typed>::TYPE.check(&value)?;399 match value {400 Val::Arr(a) => Ok(a),401 _ => unreachable!(),402 }403 }404}405impl TryFrom<ArrValue> for Val {406 type Error = LocError;407408 fn try_from(value: ArrValue) -> Result<Self> {409 Ok(Self::Arr(value))410 }411}412413impl Typed for FuncVal {414 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);415}416impl TryFrom<Val> for FuncVal {417 type Error = LocError;418419 fn try_from(value: Val) -> Result<Self> {420 <Self as Typed>::TYPE.check(&value)?;421 match value {422 Val::Func(a) => Ok(a),423 _ => unreachable!(),424 }425 }426}427impl TryFrom<FuncVal> for Val {428 type Error = LocError;429430 fn try_from(value: FuncVal) -> Result<Self> {431 Ok(Self::Func(value))432 }433}434impl Typed for ObjValue {435 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Obj);436}437impl TryFrom<Val> for ObjValue {438 type Error = LocError;439440 fn try_from(value: Val) -> Result<Self> {441 <Self as Typed>::TYPE.check(&value)?;442 match value {443 Val::Obj(a) => Ok(a),444 _ => unreachable!(),445 }446 }447}448impl TryFrom<ObjValue> for Val {449 type Error = LocError;450451 fn try_from(value: ObjValue) -> Result<Self> {452 Ok(Self::Obj(value))453 }454}455456impl Typed for bool {457 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Bool);458}459impl TryFrom<Val> for bool {460 type Error = LocError;461462 fn try_from(value: Val) -> Result<Self> {463 <Self as Typed>::TYPE.check(&value)?;464 match value {465 Val::Bool(a) => Ok(a),466 _ => unreachable!(),467 }468 }469}470impl TryFrom<bool> for Val {471 type Error = LocError;472473 fn try_from(value: bool) -> Result<Self> {474 Ok(Self::Bool(value))475 }476}477478impl Typed for IndexableVal {479 const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[480 &ComplexValType::Simple(ValType::Arr),481 &ComplexValType::Simple(ValType::Str),482 ]);483}484impl TryFrom<Val> for IndexableVal {485 type Error = LocError;486487 fn try_from(value: Val) -> Result<Self> {488 <Self as Typed>::TYPE.check(&value)?;489 value.into_indexable()490 }491}492impl TryFrom<IndexableVal> for Val {493 type Error = LocError;494495 fn try_from(value: IndexableVal) -> Result<Self> {496 match value {497 IndexableVal::Str(s) => Ok(Self::Str(s)),498 IndexableVal::Arr(a) => Ok(Self::Arr(a)),499 }500 }501}502503pub struct Null;504impl Typed for Null {505 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Null);506}507impl TryFrom<Val> for Null {508 type Error = LocError;509510 fn try_from(value: Val) -> Result<Self> {511 <Self as Typed>::TYPE.check(&value)?;512 Ok(Self)513 }514}515impl TryFrom<Null> for Val {516 type Error = LocError;517518 fn try_from(_: Null) -> Result<Self> {519 Ok(Self::Null)520 }521}crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -6,14 +6,15 @@
error::{Error::*, LocError},
evaluate,
function::{
- parse_default_function_call, parse_function_call, ArgsLike, Builtin, StaticBuiltin,
+ parse_default_function_call, parse_function_call, ArgsLike, Builtin, CallLocation,
+ StaticBuiltin,
},
gc::TraceBox,
throw, Context, ObjValue, Result,
};
use gcmodule::{Cc, Trace};
use jrsonnet_interner::IStr;
-use jrsonnet_parser::{ExprLocation, LocExpr, ParamsDesc};
+use jrsonnet_parser::{LocExpr, ParamsDesc};
use jrsonnet_types::ValType;
use std::{cell::RefCell, fmt::Debug, rc::Rc};
@@ -152,7 +153,7 @@
pub fn evaluate(
&self,
call_ctx: Context,
- loc: Option<&ExprLocation>,
+ loc: CallLocation,
args: &dyn ArgsLike,
tailstrict: bool,
) -> Result<Val> {
@@ -166,7 +167,7 @@
}
}
pub fn evaluate_simple(&self, args: &dyn ArgsLike) -> Result<Val> {
- self.evaluate(Context::default(), None, args, true)
+ self.evaluate(Context::default(), CallLocation::native(), args, true)
}
}
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -1,5 +1,5 @@
use proc_macro2::TokenStream;
-use quote::{quote, quote_spanned};
+use quote::quote;
use syn::{
parenthesized,
parse::{Parse, ParseStream},
@@ -7,8 +7,8 @@
punctuated::Punctuated,
spanned::Spanned,
token::Comma,
- Attribute, DeriveInput, Error, FnArg, GenericArgument, Ident, ItemFn, LitStr, Pat, PatType,
- Path, PathArguments, Result, Token, Type,
+ Attribute, DeriveInput, Error, FnArg, GenericArgument, Ident, ItemFn, LitStr, Pat, Path,
+ PathArguments, Result, ReturnType, Token, Type,
};
fn parse_attr<A: Parse, I>(attrs: &[Attribute], ident: I) -> Result<Option<A>>
@@ -33,49 +33,42 @@
Ok(Some(attr))
}
-fn is_location_arg(t: &PatType) -> bool {
- t.attrs.iter().any(|a| a.path.is_ident("location"))
-}
-fn is_self_arg(t: &PatType) -> bool {
- t.attrs.iter().any(|a| a.path.is_ident("self"))
+fn path_is(path: &Path, needed: &str) -> bool {
+ path.leading_colon.is_none()
+ && path.segments.len() >= 1
+ && path.segments.iter().last().unwrap().ident == needed
}
-trait RetainHad<T> {
- fn retain_had(&mut self, h: impl FnMut(&T) -> bool) -> bool;
-}
-impl<T> RetainHad<T> for Vec<T> {
- fn retain_had(&mut self, h: impl FnMut(&T) -> bool) -> bool {
- let before = self.len();
- self.retain(h);
- let after = self.len();
- before != after
+fn type_is_path<'ty>(ty: &'ty Type, needed: &str) -> Option<&'ty PathArguments> {
+ match ty {
+ Type::Path(path) if path.qself.is_none() && path_is(&path.path, needed) => {
+ let args = &path.path.segments.iter().last().unwrap().arguments;
+ Some(args)
+ }
+ _ => None,
}
}
-fn extract_type_from_option(ty: &Type) -> Option<&Type> {
- fn path_is_option(path: &Path) -> bool {
- path.leading_colon.is_none()
- && path.segments.len() == 1
- && path.segments.iter().next().unwrap().ident == "Option"
- }
-
- match ty {
- Type::Path(typepath) if typepath.qself.is_none() && path_is_option(&typepath.path) => {
- // Get the first segment of the path (there is only one, in fact: "Option"):
- let type_params = &typepath.path.segments.iter().next().unwrap().arguments;
- // It should have only on angle-bracketed param ("<String>"):
- let generic_arg = match type_params {
- PathArguments::AngleBracketed(params) => params.args.iter().next().unwrap(),
- _ => panic!("missing option generic"),
- };
- // This argument must be a type:
- match generic_arg {
- GenericArgument::Type(ty) => Some(ty),
- _ => panic!("option generic should be a type"),
+fn extract_type_from_option(ty: &Type) -> Result<Option<&Type>> {
+ Ok(if let Some(args) = type_is_path(ty, "Option") {
+ // It should have only on angle-bracketed param ("<String>"):
+ let generic_arg = match args {
+ PathArguments::AngleBracketed(params) => params.args.iter().next().unwrap(),
+ _ => return Err(Error::new(args.span(), "missing option generic")),
+ };
+ // This argument must be a type:
+ match generic_arg {
+ GenericArgument::Type(ty) => Some(ty),
+ _ => {
+ return Err(Error::new(
+ generic_arg.span(),
+ "option generic should be a type",
+ ))
}
}
- _ => None,
- }
+ } else {
+ None
+ })
}
struct Field {
@@ -101,7 +94,7 @@
struct EmptyAttr;
impl Parse for EmptyAttr {
- fn parse(input: ParseStream) -> Result<Self> {
+ fn parse(_input: ParseStream) -> Result<Self> {
Ok(Self)
}
}
@@ -124,107 +117,158 @@
}
}
+enum ArgInfo {
+ Normal {
+ ty: Type,
+ is_option: bool,
+ name: String,
+ // ident: Ident,
+ },
+ Lazy {
+ is_option: bool,
+ name: String,
+ },
+ Location,
+ This,
+}
+
+impl ArgInfo {
+ fn parse(arg: &FnArg) -> Result<Self> {
+ let typed = match arg {
+ FnArg::Receiver(_) => unreachable!(),
+ FnArg::Typed(a) => a,
+ };
+ let ident = match &typed.pat as &Pat {
+ Pat::Ident(i) => i.ident.clone(),
+ _ => {
+ return Err(Error::new(
+ typed.pat.span(),
+ "arg should be plain identifier",
+ ))
+ }
+ };
+ let ty = &typed.ty as &Type;
+ if type_is_path(&ty, "CallLocation").is_some() {
+ return Ok(Self::Location);
+ } else if type_is_path(&ty, "Self").is_some() {
+ return Ok(Self::This);
+ } else if type_is_path(&ty, "LazyVal").is_some() {
+ return Ok(Self::Lazy {
+ is_option: false,
+ name: ident.to_string(),
+ });
+ }
+
+ let (is_option, ty) = if let Some(ty) = extract_type_from_option(&ty)? {
+ if type_is_path(&ty, "LazyVal").is_some() {
+ return Ok(Self::Lazy {
+ is_option: true,
+ name: ident.to_string(),
+ });
+ }
+
+ (true, ty.clone())
+ } else {
+ (false, ty.clone())
+ };
+
+ Ok(Self::Normal {
+ ty,
+ is_option,
+ name: ident.to_string(),
+ // ident,
+ })
+ }
+}
+
#[proc_macro_attribute]
pub fn builtin(
attr: proc_macro::TokenStream,
item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
- let attrs = parse_macro_input!(attr as BuiltinAttrs);
- let mut fun: ItemFn = parse_macro_input!(item);
+ let attr = parse_macro_input!(attr as BuiltinAttrs);
+ let item: ItemFn = parse_macro_input!(item);
+
+ match builtin_inner(attr, item) {
+ Ok(v) => v.into(),
+ Err(e) => e.into_compile_error().into(),
+ }
+}
+fn builtin_inner(attr: BuiltinAttrs, fun: ItemFn) -> syn::Result<TokenStream> {
let result = match fun.sig.output {
- syn::ReturnType::Default => {
- return quote_spanned! { fun.sig.span() =>
- compile_error!("builtins should return something");
- }
- .into()
+ ReturnType::Default => {
+ return Err(Error::new(
+ fun.sig.span(),
+ "builtin should return something",
+ ))
}
- syn::ReturnType::Type(_, ref ty) => ty.clone(),
+ ReturnType::Type(_, ref ty) => ty.clone(),
};
- let params = fun
+ let args = fun
.sig
.inputs
.iter()
- .map(|i| match i {
- FnArg::Receiver(_) => unreachable!(),
- FnArg::Typed(t) => t,
- })
- .filter(|a| !is_location_arg(a) && !is_self_arg(a))
- .map(|t| {
- let ident = match &t.pat as &Pat {
- Pat::Ident(i) => i.ident.to_string(),
- _ => {
- return quote_spanned! { t.pat.span() =>
- compile_error!("args should be plain identifiers")
- }
- .into()
- }
- };
- let optional = extract_type_from_option(&t.ty).is_some();
- quote! {
- BuiltinParam {
- name: std::borrow::Cow::Borrowed(#ident),
- has_default: #optional,
- }
+ .map(|a| ArgInfo::parse(a))
+ .collect::<Result<Vec<_>>>()?;
+
+ let params_desc = args.iter().flat_map(|a| match a {
+ ArgInfo::Normal {
+ is_option, name, ..
+ }
+ | ArgInfo::Lazy { is_option, name } => Some(quote! {
+ BuiltinParam {
+ name: std::borrow::Cow::Borrowed(#name),
+ has_default: #is_option,
}
- })
- .collect::<Vec<_>>();
+ }),
+ ArgInfo::Location => None,
+ ArgInfo::This => None,
+ });
- let args = fun
- .sig
- .inputs
- .iter_mut()
- .map(|i| match i {
- FnArg::Receiver(_) => unreachable!(),
- FnArg::Typed(t) => t,
- })
- .map(|t| {
- if t.attrs.retain_had(|a| !a.path.is_ident("location")) {
- quote! {{
- loc
+ let pass = args.iter().map(|a| match a {
+ ArgInfo::Normal {
+ ty,
+ is_option,
+ name,
+ // ident,
+ } => {
+ let eval = quote! {::jrsonnet_evaluator::push_description_frame(
+ || format!("argument <{}> evaluation", #name),
+ || <#ty>::try_from(value.evaluate()?),
+ )?};
+ if *is_option {
+ quote! {if let Some(value) = parsed.get(#name) {
+ Some(#eval)
+ } else {
+ None
}}
- } else if t.attrs.retain_had(|a| !a.path.is_ident("self")) {
+ } else {
quote! {{
- self
+ let value = parsed.get(#name).expect("args shape is checked");
+ #eval
}}
- } else {
- let ident = match &t.pat as &Pat {
- Pat::Ident(i) => i.ident.to_string(),
- _ => {
- return quote_spanned! { t.pat.span() =>
- compile_error!("args should be plain identifiers")
- }
- .into()
- }
- };
- let ty = &t.ty;
- if let Some(opt_ty) = extract_type_from_option(&t.ty) {
- quote! {{
- if let Some(value) = parsed.get(#ident) {
- Some(::jrsonnet_evaluator::push_description_frame(
- || format!("argument <{}> evaluation", #ident),
- || <#opt_ty>::try_from(value.evaluate()?),
- )?)
- } else {
- None
- }
- }}
+ }
+ }
+ ArgInfo::Lazy { is_option, name } => {
+ if *is_option {
+ quote! {if let Some(value) = parsed.get(#name) {
+ Some(value.clone())
} else {
- quote! {{
- let value = parsed.get(#ident).unwrap();
-
- ::jrsonnet_evaluator::push_description_frame(
- || format!("argument <{}> evaluation", #ident),
- || <#ty>::try_from(value.evaluate()?),
- )?
- }}
+ None
+ }}
+ } else {
+ quote! {
+ parsed.get(#name).expect("args shape is correct").clone()
}
}
- })
- .collect::<Vec<_>>();
+ }
+ ArgInfo::Location => quote! {location},
+ ArgInfo::This => quote! {self},
+ });
- let fields = attrs.fields.iter().map(|field| {
+ let fields = attr.fields.iter().map(|field| {
let name = &field.name;
let ty = &field.ty;
quote! {
@@ -234,7 +278,7 @@
let name = &fun.sig.ident;
let vis = &fun.vis;
- let static_ext = if attrs.fields.is_empty() {
+ let static_ext = if attr.fields.is_empty() {
quote! {
impl #name {
pub const INST: &'static dyn StaticBuiltin = &#name {};
@@ -244,13 +288,13 @@
} else {
quote! {}
};
- let static_derive_copy = if attrs.fields.is_empty() {
+ let static_derive_copy = if attr.fields.is_empty() {
quote! {, Copy}
} else {
quote! {}
};
- (quote! {
+ Ok(quote! {
#fun
#[doc(hidden)]
#[allow(non_camel_case_types)]
@@ -260,12 +304,12 @@
}
const _: () = {
use ::jrsonnet_evaluator::{
- function::{Builtin, StaticBuiltin, BuiltinParam, ArgsLike, parse_builtin_call},
+ function::{Builtin, CallLocation, StaticBuiltin, BuiltinParam, ArgsLike, parse_builtin_call},
error::Result, Context,
parser::ExprLocation,
};
const PARAMS: &'static [BuiltinParam] = &[
- #(#params),*
+ #(#params_desc),*
];
#static_ext
@@ -279,17 +323,16 @@
fn params(&self) -> &[BuiltinParam] {
PARAMS
}
- fn call(&self, context: Context, loc: Option<&ExprLocation>, args: &dyn ArgsLike) -> Result<Val> {
+ fn call(&self, context: Context, location: CallLocation, args: &dyn ArgsLike) -> Result<Val> {
let parsed = parse_builtin_call(context, &PARAMS, args, false)?;
- let result: #result = #name(#(#args),*);
+ let result: #result = #name(#(#pass),*);
let result = result?;
result.try_into()
}
}
};
})
- .into()
}
#[derive(Default)]
@@ -366,15 +409,6 @@
)
}
- fn expand_shallow_field(&self) -> Option<TokenStream> {
- if self.is_option() {
- return None;
- }
- let name = self.name()?;
- Some(quote! {
- (#name, ComplexValType::Any)
- })
- }
fn expand_field(&self) -> Option<TokenStream> {
if self.is_option() {
return None;
@@ -450,7 +484,7 @@
}
fn as_option(&self) -> Option<&Type> {
- extract_type_from_option(&self.0.ty)
+ extract_type_from_option(&self.0.ty).unwrap()
}
fn is_option(&self) -> bool {
self.as_option().is_some()
@@ -460,25 +494,25 @@
#[proc_macro_derive(Typed, attributes(typed))]
pub fn derive_typed(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = parse_macro_input!(item as DeriveInput);
+
+ match derive_typed_inner(input) {
+ Ok(v) => v.into(),
+ Err(e) => e.to_compile_error().into(),
+ }
+}
+
+fn derive_typed_inner(input: DeriveInput) -> Result<TokenStream> {
let data = match &input.data {
syn::Data::Struct(s) => s,
- _ => {
- return syn::Error::new(input.span(), "only structs supported")
- .to_compile_error()
- .into()
- }
+ _ => return Err(Error::new(input.span(), "only structs supported")),
};
let ident = &input.ident;
- let fields = match data
+ let fields = data
.fields
.iter()
.map(TypedField::try_new)
- .collect::<Result<Vec<_>>>()
- {
- Ok(v) => v,
- Err(e) => return e.to_compile_error().into(),
- };
+ .collect::<Result<Vec<_>>>()?;
let typed = {
let fields = fields
@@ -499,7 +533,7 @@
let fields_parse = fields.iter().map(TypedField::expand_parse);
let fields_serialize = fields.iter().map(TypedField::expand_serialize);
- quote! {
+ Ok(quote! {
const _: () = {
use ::jrsonnet_evaluator::{
typed::{ComplexValType, Typed, TypedObj, CheckType},
@@ -540,6 +574,5 @@
}
()
};
- }
- .into()
+ })
}