difftreelog
feat lazy evaluation of function default params
in: master
Fixes #59
7 files changed
crates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -73,6 +73,9 @@
.cloned()
.ok_or(VariableIsNotDefined(name))?)
}
+ pub fn contains_binding(&self, name: IStr) -> bool {
+ self.0.bindings.contains_key(&name)
+ }
pub fn into_future(self, ctx: FutureWrapper<Self>) -> Self {
{
ctx.0.borrow_mut().replace(self);
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -56,7 +56,7 @@
BindingParameterASecondTime(IStr),
#[error("too many args, function has {0}")]
TooManyArgsFunctionHas(usize),
- #[error("founction argument is not passed: {0}")]
+ #[error("function argument is not passed: {0}")]
FunctionParameterNotBoundInCall(IStr),
#[error("external variable is not defined: {0}")]
crates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function.rs
+++ b/crates/jrsonnet-evaluator/src/function.rs
@@ -1,4 +1,7 @@
-use crate::{error::Error::*, evaluate, throw, Context, LazyVal, LazyValValue, Result, Val};
+use crate::{
+ error::Error::*, evaluate, evaluate_named, throw, Context, FutureWrapper, LazyVal,
+ LazyValValue, Result, Val,
+};
use jrsonnet_gc::Trace;
use jrsonnet_interner::IStr;
use jrsonnet_parser::{ArgsDesc, LocExpr, ParamsDesc};
@@ -8,6 +11,18 @@
const NO_DEFAULT_CONTEXT: &str =
"no default context set for call with defined default parameter value";
+#[derive(Trace)]
+#[trivially_drop]
+struct EvaluateLazyVal {
+ context: Context,
+ expr: LocExpr,
+}
+impl LazyValValue for EvaluateLazyVal {
+ fn get(self: Box<Self>) -> Result<Val> {
+ evaluate(self.context, &self.expr)
+ }
+}
+
/// Creates correct [context](Context) for function body evaluation returning error on invalid call.
///
/// ## Parameters
@@ -18,64 +33,119 @@
/// * `tailstrict`: if set to `true` function arguments are eagerly executed, otherwise - lazily
pub fn parse_function_call(
ctx: Context,
- body_ctx: Option<Context>,
+ body_ctx: Context,
params: &ParamsDesc,
args: &ArgsDesc,
tailstrict: bool,
) -> Result<Context> {
- let mut out = HashMap::with_capacity_and_hasher(params.len(), BuildHasherDefault::default());
- let mut positioned_args = vec![None; params.0.len()];
- for (id, arg) in args.iter().enumerate() {
- let idx = if let Some(name) = &arg.0 {
- params
- .iter()
- .position(|p| *p.0 == *name)
- .ok_or_else(|| UnknownFunctionParameter(name.clone()))?
- } else {
- id
- };
+ let mut passed_args =
+ HashMap::with_capacity_and_hasher(params.len(), BuildHasherDefault::default());
+ if args.unnamed.len() > params.len() {
+ throw!(TooManyArgsFunctionHas(params.len()))
+ }
+
+ let mut filled_args = 0;
- if idx >= params.len() {
- throw!(TooManyArgsFunctionHas(params.len()));
+ for (id, arg) in args.unnamed.iter().enumerate() {
+ let name = params[id].0.clone();
+ passed_args.insert(
+ name,
+ if tailstrict {
+ LazyVal::new_resolved(evaluate(ctx.clone(), arg)?)
+ } else {
+ LazyVal::new(Box::new(EvaluateLazyVal {
+ context: ctx.clone(),
+ expr: arg.clone(),
+ }))
+ },
+ );
+ filled_args += 1;
+ }
+
+ for (name, value) in args.named.iter() {
+ // FIXME: O(n) for arg existence check
+ if !params.iter().any(|p| &p.0 == name) {
+ throw!(UnknownFunctionParameter((name as &str).to_owned()));
}
- if positioned_args[idx].is_some() {
- throw!(BindingParameterASecondTime(params[idx].0.clone()));
+ if passed_args
+ .insert(
+ name.clone(),
+ if tailstrict {
+ LazyVal::new_resolved(evaluate(ctx.clone(), value)?)
+ } else {
+ LazyVal::new(Box::new(EvaluateLazyVal {
+ context: ctx.clone(),
+ expr: value.clone(),
+ }))
+ },
+ )
+ .is_some()
+ {
+ throw!(BindingParameterASecondTime(name.clone()));
}
- positioned_args[idx] = Some(arg.1.clone());
+ filled_args += 1;
}
- // Fill defaults
- for (id, p) in params.iter().enumerate() {
- let (ctx, expr) = if let Some(arg) = &positioned_args[id] {
- (ctx.clone(), arg)
- } else if let Some(default) = &p.1 {
- (body_ctx.clone().expect(NO_DEFAULT_CONTEXT), default)
- } else {
- throw!(FunctionParameterNotBoundInCall(p.0.clone()));
- };
- let val = if tailstrict {
- LazyVal::new_resolved(evaluate(ctx, expr)?)
- } else {
+
+ if filled_args < params.len() {
+ // Some args are unset, but maybe we have defaults for them
+ // Default values should be created in newly created context
+ let future_context = FutureWrapper::<Context>::new();
+ let mut defaults = HashMap::with_capacity_and_hasher(
+ params.len() - filled_args,
+ BuildHasherDefault::default(),
+ );
+
+ for param in params.iter().filter(|p| p.1.is_some()) {
+ if passed_args.contains_key(¶m.0.clone()) {
+ continue;
+ }
#[derive(Trace)]
#[trivially_drop]
- struct EvaluateLazyVal {
- context: Context,
- expr: LocExpr,
+ struct LazyNamedBinding {
+ future_context: FutureWrapper<Context>,
+ name: IStr,
+ value: LocExpr,
}
- impl LazyValValue for EvaluateLazyVal {
+ impl LazyValValue for LazyNamedBinding {
fn get(self: Box<Self>) -> Result<Val> {
- evaluate(self.context, &self.expr)
+ evaluate_named(self.future_context.unwrap(), &self.value, self.name)
}
}
+ LazyVal::new(Box::new(LazyNamedBinding {
+ future_context: future_context.clone(),
+ name: param.0.clone(),
+ value: param.1.clone().unwrap(),
+ }));
- LazyVal::new(Box::new(EvaluateLazyVal {
- context: ctx.clone(),
- expr: expr.clone(),
- }))
- };
- out.insert(p.0.clone(), val);
- }
+ defaults.insert(
+ param.0.clone(),
+ LazyVal::new(Box::new(LazyNamedBinding {
+ future_context: future_context.clone(),
+ name: param.0.clone(),
+ value: param.1.clone().unwrap(),
+ })),
+ );
+ filled_args += 1;
+ }
+
+ // Some args still wasn't filled
+ if filled_args != params.len() {
+ for param in params.iter().skip(args.unnamed.len()) {
+ if !args.named.iter().any(|a| a.0 == param.0) {
+ throw!(FunctionParameterNotBoundInCall(param.0.clone()));
+ }
+ }
+ unreachable!();
+ }
- Ok(body_ctx.unwrap_or(ctx).extend(out, None, None, None))
+ Ok(body_ctx
+ .extend(passed_args, None, None, None)
+ .extend_bound(defaults)
+ .into_future(future_context))
+ } else {
+ let body_ctx = body_ctx.extend(passed_args, None, None, None);
+ Ok(body_ctx)
+ }
}
pub fn parse_function_call_map(
@@ -176,21 +246,25 @@
use $crate::{error::Error::*, throw, evaluate, push_stack_frame, typed::CheckType};
let args = $args;
- if args.len() > $total_args {
+ if args.unnamed.len() + args.named.len() > $total_args {
throw!(TooManyArgsFunctionHas($total_args));
}
$(
- if args.len() <= $id {
+ if args.unnamed.len() + args.named.len() <= $id {
throw!(FunctionParameterNotBoundInCall(stringify!($name).into()));
}
- let $name = &args[$id];
- if $name.0.is_some() {
- if $name.0.as_ref().unwrap() != stringify!($name) {
+ // Is named
+ let $name = if $id >= $args.unnamed.len() {
+ let named = &args.named[$id - $args.unnamed.len()];
+ if &named.0 != stringify!($name) {
throw!(IntrinsicArgumentReorderingIsNotSupportedYet);
}
- }
+ &named.1
+ } else {
+ &$args.unnamed[$id]
+ };
let $name = push_stack_frame(None, || format!("evaluating argument"), || {
- let value = evaluate($ctx.clone(), &$name.1)?;
+ let value = evaluate($ctx.clone(), &$name)?;
$ty.check(&value)?;
Ok(value)
})?;
crates/jrsonnet-evaluator/src/map.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/map.rs
+++ b/crates/jrsonnet-evaluator/src/map.rs
@@ -29,6 +29,16 @@
.get(key)
.or_else(|| self.0.parent.as_ref().and_then(|p| p.get(key)))
}
+
+ pub fn contains_key(&self, key: &IStr) -> bool {
+ (self.0).current.contains_key(key)
+ || self
+ .0
+ .parent
+ .as_ref()
+ .map(|p| p.contains_key(key))
+ .unwrap_or(false)
+ }
}
impl Clone for LayeredHashMap {
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth1use crate::{2 builtin::{3 call_builtin,4 manifest::{manifest_json_ex, ManifestJsonOptions, ManifestType},5 },6 error::{Error::*, LocError},7 evaluate,8 function::{parse_function_call, parse_function_call_map, place_args},9 native::NativeCallback,10 throw, with_state, Context, ObjValue, Result,11};12use jrsonnet_gc::{Gc, GcCell, Trace};13use jrsonnet_interner::IStr;14use jrsonnet_parser::{el, Arg, ArgsDesc, Expr, ExprLocation, LiteralType, LocExpr, ParamsDesc};15use jrsonnet_types::ValType;16use std::{collections::HashMap, fmt::Debug, rc::Rc};1718pub trait LazyValValue: Trace {19 fn get(self: Box<Self>) -> Result<Val>;20}2122#[derive(Trace)]23#[trivially_drop]24enum LazyValInternals {25 Computed(Val),26 Errored(LocError),27 Waiting(Box<dyn LazyValValue>),28 Pending,29}3031#[derive(Clone, Trace)]32#[trivially_drop]33pub struct LazyVal(Gc<GcCell<LazyValInternals>>);34impl LazyVal {35 pub fn new(f: Box<dyn LazyValValue>) -> Self {36 Self(Gc::new(GcCell::new(LazyValInternals::Waiting(f))))37 }38 pub fn new_resolved(val: Val) -> Self {39 Self(Gc::new(GcCell::new(LazyValInternals::Computed(val))))40 }41 pub fn evaluate(&self) -> Result<Val> {42 match &*self.0.borrow() {43 LazyValInternals::Computed(v) => return Ok(v.clone()),44 LazyValInternals::Errored(e) => return Err(e.clone()),45 LazyValInternals::Pending => return Err(RecursiveLazyValueEvaluation.into()),46 _ => (),47 };48 let value = if let LazyValInternals::Waiting(value) =49 std::mem::replace(&mut *self.0.borrow_mut(), LazyValInternals::Pending)50 {51 value52 } else {53 unreachable!()54 };55 let new_value = match value.get() {56 Ok(v) => v,57 Err(e) => {58 *self.0.borrow_mut() = LazyValInternals::Errored(e.clone());59 return Err(e);60 }61 };62 *self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());63 Ok(new_value)64 }65}6667impl Debug for LazyVal {68 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {69 write!(f, "Lazy")70 }71}72impl PartialEq for LazyVal {73 fn eq(&self, other: &Self) -> bool {74 Gc::ptr_eq(&self.0, &other.0)75 }76}7778#[derive(Debug, PartialEq, Trace)]79#[trivially_drop]80pub struct FuncDesc {81 pub name: IStr,82 pub ctx: Context,83 pub params: ParamsDesc,84 pub body: LocExpr,85}8687#[derive(Debug, Trace)]88#[trivially_drop]89pub enum FuncVal {90 /// Plain function implemented in jsonnet91 Normal(FuncDesc),92 /// Standard library function93 Intrinsic(IStr),94 /// Library functions implemented in native95 NativeExt(IStr, Gc<NativeCallback>),96}9798impl PartialEq for FuncVal {99 fn eq(&self, other: &Self) -> bool {100 match (self, other) {101 (Self::Normal(a), Self::Normal(b)) => a == b,102 (Self::Intrinsic(an), Self::Intrinsic(bn)) => an == bn,103 (Self::NativeExt(an, _), Self::NativeExt(bn, _)) => an == bn,104 (..) => false,105 }106 }107}108impl FuncVal {109 pub fn is_ident(&self) -> bool {110 matches!(&self, Self::Intrinsic(n) if n as &str == "id")111 }112 pub fn name(&self) -> IStr {113 match self {114 Self::Normal(normal) => normal.name.clone(),115 Self::Intrinsic(name) => format!("std.{}", name).into(),116 Self::NativeExt(n, _) => format!("native.{}", n).into(),117 }118 }119 pub fn evaluate(120 &self,121 call_ctx: Context,122 loc: Option<&ExprLocation>,123 args: &ArgsDesc,124 tailstrict: bool,125 ) -> Result<Val> {126 match self {127 Self::Normal(func) => {128 let ctx = parse_function_call(129 call_ctx,130 Some(func.ctx.clone()),131 &func.params,132 args,133 tailstrict,134 )?;135 evaluate(ctx, &func.body)136 }137 Self::Intrinsic(name) => call_builtin(call_ctx, loc, name, args),138 Self::NativeExt(_name, handler) => {139 let args = parse_function_call(call_ctx, None, &handler.params, args, true)?;140 let mut out_args = Vec::with_capacity(handler.params.len());141 for p in handler.params.0.iter() {142 out_args.push(args.binding(p.0.clone())?.evaluate()?);143 }144 Ok(handler.call(loc.map(|l| l.0.clone()), &out_args)?)145 }146 }147 }148149 pub fn evaluate_map(150 &self,151 call_ctx: Context,152 args: &HashMap<IStr, Val>,153 tailstrict: bool,154 ) -> Result<Val> {155 match self {156 Self::Normal(func) => {157 let ctx = parse_function_call_map(158 call_ctx,159 Some(func.ctx.clone()),160 &func.params,161 args,162 tailstrict,163 )?;164 evaluate(ctx, &func.body)165 }166 Self::Intrinsic(_) => todo!(),167 Self::NativeExt(_, _) => todo!(),168 }169 }170171 pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {172 match self {173 Self::Normal(func) => {174 let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;175 evaluate(ctx, &func.body)176 }177 Self::Intrinsic(_) => todo!(),178 Self::NativeExt(_, _) => todo!(),179 }180 }181}182183#[derive(Clone)]184pub enum ManifestFormat {185 YamlStream(Box<ManifestFormat>),186 Yaml(usize),187 Json(usize),188 ToString,189 String,190}191192#[derive(Debug, Clone, Trace)]193#[trivially_drop]194pub enum ArrValue {195 Lazy(Gc<Vec<LazyVal>>),196 Eager(Gc<Vec<Val>>),197 Extended(Box<(Self, Self)>),198}199impl ArrValue {200 pub fn new_eager() -> Self {201 Self::Eager(Gc::new(Vec::new()))202 }203204 pub fn len(&self) -> usize {205 match self {206 Self::Lazy(l) => l.len(),207 Self::Eager(e) => e.len(),208 Self::Extended(v) => v.0.len() + v.1.len(),209 }210 }211212 pub fn is_empty(&self) -> bool {213 self.len() == 0214 }215216 pub fn get(&self, index: usize) -> Result<Option<Val>> {217 match self {218 Self::Lazy(vec) => {219 if let Some(v) = vec.get(index) {220 Ok(Some(v.evaluate()?))221 } else {222 Ok(None)223 }224 }225 Self::Eager(vec) => Ok(vec.get(index).cloned()),226 Self::Extended(v) => {227 let a_len = v.0.len();228 if a_len > index {229 v.0.get(index)230 } else {231 v.1.get(index - a_len)232 }233 }234 }235 }236237 pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {238 match self {239 Self::Lazy(vec) => vec.get(index).cloned(),240 Self::Eager(vec) => vec.get(index).cloned().map(LazyVal::new_resolved),241 Self::Extended(v) => {242 let a_len = v.0.len();243 if a_len > index {244 v.0.get_lazy(index)245 } else {246 v.1.get_lazy(index - a_len)247 }248 }249 }250 }251252 pub fn evaluated(&self) -> Result<Gc<Vec<Val>>> {253 Ok(match self {254 Self::Lazy(vec) => {255 let mut out = Vec::with_capacity(vec.len());256 for item in vec.iter() {257 out.push(item.evaluate()?);258 }259 Gc::new(out)260 }261 Self::Eager(vec) => vec.clone(),262 Self::Extended(_v) => {263 let mut out = Vec::with_capacity(self.len());264 for item in self.iter() {265 out.push(item?);266 }267 Gc::new(out)268 }269 })270 }271272 pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {273 (0..self.len()).map(move |idx| match self {274 Self::Lazy(l) => l[idx].evaluate(),275 Self::Eager(e) => Ok(e[idx].clone()),276 Self::Extended(_) => self.get(idx).map(|e| e.unwrap()),277 })278 }279280 pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {281 (0..self.len()).map(move |idx| match self {282 Self::Lazy(l) => l[idx].clone(),283 Self::Eager(e) => LazyVal::new_resolved(e[idx].clone()),284 Self::Extended(_) => self.get_lazy(idx).unwrap(),285 })286 }287288 pub fn reversed(self) -> Self {289 match self {290 Self::Lazy(vec) => {291 let mut out = (&vec as &Vec<_>).clone();292 out.reverse();293 Self::Lazy(Gc::new(out))294 }295 Self::Eager(vec) => {296 let mut out = (&vec as &Vec<_>).clone();297 out.reverse();298 Self::Eager(Gc::new(out))299 }300 Self::Extended(b) => Self::Extended(Box::new((b.1.reversed(), b.0.reversed()))),301 }302 }303304 pub fn map(self, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {305 let mut out = Vec::with_capacity(self.len());306307 for value in self.iter() {308 out.push(mapper(value?)?);309 }310311 Ok(Self::Eager(Gc::new(out)))312 }313314 pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {315 let mut out = Vec::with_capacity(self.len());316317 for value in self.iter() {318 let value = value?;319 if filter(&value)? {320 out.push(value);321 }322 }323324 Ok(Self::Eager(Gc::new(out)))325 }326327 pub fn ptr_eq(a: &Self, b: &Self) -> bool {328 match (a, b) {329 (Self::Lazy(a), Self::Lazy(b)) => Gc::ptr_eq(a, b),330 (Self::Eager(a), Self::Eager(b)) => Gc::ptr_eq(a, b),331 _ => false,332 }333 }334}335336impl From<Vec<LazyVal>> for ArrValue {337 fn from(v: Vec<LazyVal>) -> Self {338 Self::Lazy(Gc::new(v))339 }340}341342impl From<Vec<Val>> for ArrValue {343 fn from(v: Vec<Val>) -> Self {344 Self::Eager(Gc::new(v))345 }346}347348pub enum IndexableVal {349 Str(IStr),350 Arr(ArrValue),351}352353#[derive(Debug, Clone, Trace)]354#[trivially_drop]355pub enum Val {356 Bool(bool),357 Null,358 Str(IStr),359 Num(f64),360 Arr(ArrValue),361 Obj(ObjValue),362 Func(Gc<FuncVal>),363}364365macro_rules! matches_unwrap {366 ($e: expr, $p: pat, $r: expr) => {367 match $e {368 $p => $r,369 _ => panic!("no match"),370 }371 };372}373impl Val {374 /// Creates `Val::Num` after checking for numeric overflow.375 /// As numbers are `f64`, we can just check for their finity.376 pub fn new_checked_num(num: f64) -> Result<Self> {377 if num.is_finite() {378 Ok(Self::Num(num))379 } else {380 throw!(RuntimeError("overflow".into()))381 }382 }383384 pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {385 let this_type = self.value_type();386 if this_type != val_type {387 throw!(TypeMismatch(context, vec![val_type], this_type))388 } else {389 Ok(())390 }391 }392 pub fn unwrap_num(self) -> Result<f64> {393 Ok(matches_unwrap!(self, Self::Num(v), v))394 }395 pub fn unwrap_func(self) -> Result<Gc<FuncVal>> {396 Ok(matches_unwrap!(self, Self::Func(v), v))397 }398 pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {399 self.assert_type(context, ValType::Bool)?;400 Ok(matches_unwrap!(self, Self::Bool(v), v))401 }402 pub fn try_cast_str(self, context: &'static str) -> Result<IStr> {403 self.assert_type(context, ValType::Str)?;404 Ok(matches_unwrap!(self, Self::Str(v), v))405 }406 pub fn try_cast_num(self, context: &'static str) -> Result<f64> {407 self.assert_type(context, ValType::Num)?;408 self.unwrap_num()409 }410 pub fn try_cast_nullable_num(self, context: &'static str) -> Result<Option<f64>> {411 Ok(match self {412 Val::Null => None,413 Val::Num(num) => Some(num),414 _ => throw!(TypeMismatch(415 context,416 vec![ValType::Null, ValType::Num],417 self.value_type()418 )),419 })420 }421 pub const fn value_type(&self) -> ValType {422 match self {423 Self::Str(..) => ValType::Str,424 Self::Num(..) => ValType::Num,425 Self::Arr(..) => ValType::Arr,426 Self::Obj(..) => ValType::Obj,427 Self::Bool(_) => ValType::Bool,428 Self::Null => ValType::Null,429 Self::Func(..) => ValType::Func,430 }431 }432433 pub fn to_string(&self) -> Result<IStr> {434 Ok(match self {435 Self::Bool(true) => "true".into(),436 Self::Bool(false) => "false".into(),437 Self::Null => "null".into(),438 Self::Str(s) => s.clone(),439 v => manifest_json_ex(440 v,441 &ManifestJsonOptions {442 padding: "",443 mtype: ManifestType::ToString,444 },445 )?446 .into(),447 })448 }449450 /// Expects value to be object, outputs (key, manifested value) pairs451 pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {452 let obj = match self {453 Self::Obj(obj) => obj,454 _ => throw!(MultiManifestOutputIsNotAObject),455 };456 let keys = obj.fields();457 let mut out = Vec::with_capacity(keys.len());458 for key in keys {459 let value = obj460 .get(key.clone())?461 .expect("item in object")462 .manifest(ty)?;463 out.push((key, value));464 }465 Ok(out)466 }467468 /// Expects value to be array, outputs manifested values469 pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<IStr>> {470 let arr = match self {471 Self::Arr(a) => a,472 _ => throw!(StreamManifestOutputIsNotAArray),473 };474 let mut out = Vec::with_capacity(arr.len());475 for i in arr.iter() {476 out.push(i?.manifest(ty)?);477 }478 Ok(out)479 }480481 pub fn manifest(&self, ty: &ManifestFormat) -> Result<IStr> {482 Ok(match ty {483 ManifestFormat::YamlStream(format) => {484 let arr = match self {485 Self::Arr(a) => a,486 _ => throw!(StreamManifestOutputIsNotAArray),487 };488 let mut out = String::new();489490 match format as &ManifestFormat {491 ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),492 ManifestFormat::String => throw!(StreamManifestCannotNestString),493 _ => {}494 };495496 if !arr.is_empty() {497 for v in arr.iter() {498 out.push_str("---\n");499 out.push_str(&v?.manifest(format)?);500 out.push('\n');501 }502 out.push_str("...");503 }504505 out.into()506 }507 ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,508 ManifestFormat::Json(padding) => self.to_json(*padding)?,509 ManifestFormat::ToString => self.to_string()?,510 ManifestFormat::String => match self {511 Self::Str(s) => s.clone(),512 _ => throw!(StringManifestOutputIsNotAString),513 },514 })515 }516517 /// For manifestification518 pub fn to_json(&self, padding: usize) -> Result<IStr> {519 manifest_json_ex(520 self,521 &ManifestJsonOptions {522 padding: &" ".repeat(padding),523 mtype: if padding == 0 {524 ManifestType::Minify525 } else {526 ManifestType::Manifest527 },528 },529 )530 .map(|s| s.into())531 }532533 /// Calls `std.manifestJson`534 pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {535 manifest_json_ex(536 self,537 &ManifestJsonOptions {538 padding: &" ".repeat(padding),539 mtype: ManifestType::Std,540 },541 )542 .map(|s| s.into())543 }544545 pub fn to_yaml(&self, padding: usize) -> Result<IStr> {546 with_state(|s| {547 let ctx = s548 .create_default_context()549 .with_var("__tmp__to_json__".into(), self.clone());550 evaluate(551 ctx,552 &el!(Expr::Apply(553 el!(Expr::Index(554 el!(Expr::Var("std".into())),555 el!(Expr::Str("manifestYamlDoc".into()))556 )),557 ArgsDesc(vec![558 Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),559 Arg(560 None,561 el!(Expr::Literal(if padding != 0 {562 LiteralType::True563 } else {564 LiteralType::False565 }))566 )567 ]),568 false569 )),570 )?571 .try_cast_str("to json")572 })573 }574 pub fn into_indexable(self) -> Result<IndexableVal> {575 Ok(match self {576 Val::Str(s) => IndexableVal::Str(s),577 Val::Arr(arr) => IndexableVal::Arr(arr),578 _ => throw!(ValueIsNotIndexable(self.value_type())),579 })580 }581}582583const fn is_function_like(val: &Val) -> bool {584 matches!(val, Val::Func(_))585}586587/// Native implementation of `std.primitiveEquals`588pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {589 Ok(match (val_a, val_b) {590 (Val::Bool(a), Val::Bool(b)) => a == b,591 (Val::Null, Val::Null) => true,592 (Val::Str(a), Val::Str(b)) => a == b,593 (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,594 (Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(595 "primitiveEquals operates on primitive types, got array".into(),596 )),597 (Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(598 "primitiveEquals operates on primitive types, got object".into(),599 )),600 (a, b) if is_function_like(a) && is_function_like(b) => {601 throw!(RuntimeError("cannot test equality of functions".into()))602 }603 (_, _) => false,604 })605}606607/// Native implementation of `std.equals`608pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {609 if val_a.value_type() != val_b.value_type() {610 return Ok(false);611 }612 match (val_a, val_b) {613 (Val::Arr(a), Val::Arr(b)) => {614 if ArrValue::ptr_eq(a, b) {615 return Ok(true);616 }617 if a.len() != b.len() {618 return Ok(false);619 }620 for (a, b) in a.iter().zip(b.iter()) {621 if !equals(&a?, &b?)? {622 return Ok(false);623 }624 }625 Ok(true)626 }627 (Val::Obj(a), Val::Obj(b)) => {628 if ObjValue::ptr_eq(a, b) {629 return Ok(true);630 }631 let fields = a.fields();632 if fields != b.fields() {633 return Ok(false);634 }635 for field in fields {636 if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {637 return Ok(false);638 }639 }640 Ok(true)641 }642 (a, b) => Ok(primitive_equals(a, b)?),643 }644}1use crate::{2 builtin::{3 call_builtin,4 manifest::{manifest_json_ex, ManifestJsonOptions, ManifestType},5 },6 error::{Error::*, LocError},7 evaluate,8 function::{parse_function_call, parse_function_call_map, place_args},9 native::NativeCallback,10 throw, with_state, Context, ObjValue, Result,11};12use jrsonnet_gc::{Gc, GcCell, Trace};13use jrsonnet_interner::IStr;14use jrsonnet_parser::{el, ArgsDesc, Expr, ExprLocation, LiteralType, LocExpr, ParamsDesc};15use jrsonnet_types::ValType;16use std::{collections::HashMap, fmt::Debug, rc::Rc};1718pub trait LazyValValue: Trace {19 fn get(self: Box<Self>) -> Result<Val>;20}2122#[derive(Trace)]23#[trivially_drop]24enum LazyValInternals {25 Computed(Val),26 Errored(LocError),27 Waiting(Box<dyn LazyValValue>),28 Pending,29}3031#[derive(Clone, Trace)]32#[trivially_drop]33pub struct LazyVal(Gc<GcCell<LazyValInternals>>);34impl LazyVal {35 pub fn new(f: Box<dyn LazyValValue>) -> Self {36 Self(Gc::new(GcCell::new(LazyValInternals::Waiting(f))))37 }38 pub fn new_resolved(val: Val) -> Self {39 Self(Gc::new(GcCell::new(LazyValInternals::Computed(val))))40 }41 pub fn evaluate(&self) -> Result<Val> {42 match &*self.0.borrow() {43 LazyValInternals::Computed(v) => return Ok(v.clone()),44 LazyValInternals::Errored(e) => return Err(e.clone()),45 LazyValInternals::Pending => return Err(RecursiveLazyValueEvaluation.into()),46 _ => (),47 };48 let value = if let LazyValInternals::Waiting(value) =49 std::mem::replace(&mut *self.0.borrow_mut(), LazyValInternals::Pending)50 {51 value52 } else {53 unreachable!()54 };55 let new_value = match value.get() {56 Ok(v) => v,57 Err(e) => {58 *self.0.borrow_mut() = LazyValInternals::Errored(e.clone());59 return Err(e);60 }61 };62 *self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());63 Ok(new_value)64 }65}6667impl Debug for LazyVal {68 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {69 write!(f, "Lazy")70 }71}72impl PartialEq for LazyVal {73 fn eq(&self, other: &Self) -> bool {74 Gc::ptr_eq(&self.0, &other.0)75 }76}7778#[derive(Debug, PartialEq, Trace)]79#[trivially_drop]80pub struct FuncDesc {81 pub name: IStr,82 pub ctx: Context,83 pub params: ParamsDesc,84 pub body: LocExpr,85}8687#[derive(Debug, Trace)]88#[trivially_drop]89pub enum FuncVal {90 /// Plain function implemented in jsonnet91 Normal(FuncDesc),92 /// Standard library function93 Intrinsic(IStr),94 /// Library functions implemented in native95 NativeExt(IStr, Gc<NativeCallback>),96}9798impl PartialEq for FuncVal {99 fn eq(&self, other: &Self) -> bool {100 match (self, other) {101 (Self::Normal(a), Self::Normal(b)) => a == b,102 (Self::Intrinsic(an), Self::Intrinsic(bn)) => an == bn,103 (Self::NativeExt(an, _), Self::NativeExt(bn, _)) => an == bn,104 (..) => false,105 }106 }107}108impl FuncVal {109 pub fn is_ident(&self) -> bool {110 matches!(&self, Self::Intrinsic(n) if n as &str == "id")111 }112 pub fn name(&self) -> IStr {113 match self {114 Self::Normal(normal) => normal.name.clone(),115 Self::Intrinsic(name) => format!("std.{}", name).into(),116 Self::NativeExt(n, _) => format!("native.{}", n).into(),117 }118 }119 pub fn evaluate(120 &self,121 call_ctx: Context,122 loc: Option<&ExprLocation>,123 args: &ArgsDesc,124 tailstrict: bool,125 ) -> Result<Val> {126 match self {127 Self::Normal(func) => {128 let ctx = parse_function_call(129 call_ctx,130 func.ctx.clone(),131 &func.params,132 args,133 tailstrict,134 )?;135 evaluate(ctx, &func.body)136 }137 Self::Intrinsic(name) => call_builtin(call_ctx, loc, name, args),138 Self::NativeExt(_name, handler) => {139 let args =140 parse_function_call(call_ctx, Context::new(), &handler.params, args, true)?;141 let mut out_args = Vec::with_capacity(handler.params.len());142 for p in handler.params.0.iter() {143 out_args.push(args.binding(p.0.clone())?.evaluate()?);144 }145 Ok(handler.call(loc.map(|l| l.0.clone()), &out_args)?)146 }147 }148 }149150 pub fn evaluate_map(151 &self,152 call_ctx: Context,153 args: &HashMap<IStr, Val>,154 tailstrict: bool,155 ) -> Result<Val> {156 match self {157 Self::Normal(func) => {158 let ctx = parse_function_call_map(159 call_ctx,160 Some(func.ctx.clone()),161 &func.params,162 args,163 tailstrict,164 )?;165 evaluate(ctx, &func.body)166 }167 Self::Intrinsic(_) => todo!(),168 Self::NativeExt(_, _) => todo!(),169 }170 }171172 pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {173 match self {174 Self::Normal(func) => {175 let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;176 evaluate(ctx, &func.body)177 }178 Self::Intrinsic(_) => todo!(),179 Self::NativeExt(_, _) => todo!(),180 }181 }182}183184#[derive(Clone)]185pub enum ManifestFormat {186 YamlStream(Box<ManifestFormat>),187 Yaml(usize),188 Json(usize),189 ToString,190 String,191}192193#[derive(Debug, Clone, Trace)]194#[trivially_drop]195pub enum ArrValue {196 Lazy(Gc<Vec<LazyVal>>),197 Eager(Gc<Vec<Val>>),198 Extended(Box<(Self, Self)>),199}200impl ArrValue {201 pub fn new_eager() -> Self {202 Self::Eager(Gc::new(Vec::new()))203 }204205 pub fn len(&self) -> usize {206 match self {207 Self::Lazy(l) => l.len(),208 Self::Eager(e) => e.len(),209 Self::Extended(v) => v.0.len() + v.1.len(),210 }211 }212213 pub fn is_empty(&self) -> bool {214 self.len() == 0215 }216217 pub fn get(&self, index: usize) -> Result<Option<Val>> {218 match self {219 Self::Lazy(vec) => {220 if let Some(v) = vec.get(index) {221 Ok(Some(v.evaluate()?))222 } else {223 Ok(None)224 }225 }226 Self::Eager(vec) => Ok(vec.get(index).cloned()),227 Self::Extended(v) => {228 let a_len = v.0.len();229 if a_len > index {230 v.0.get(index)231 } else {232 v.1.get(index - a_len)233 }234 }235 }236 }237238 pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {239 match self {240 Self::Lazy(vec) => vec.get(index).cloned(),241 Self::Eager(vec) => vec.get(index).cloned().map(LazyVal::new_resolved),242 Self::Extended(v) => {243 let a_len = v.0.len();244 if a_len > index {245 v.0.get_lazy(index)246 } else {247 v.1.get_lazy(index - a_len)248 }249 }250 }251 }252253 pub fn evaluated(&self) -> Result<Gc<Vec<Val>>> {254 Ok(match self {255 Self::Lazy(vec) => {256 let mut out = Vec::with_capacity(vec.len());257 for item in vec.iter() {258 out.push(item.evaluate()?);259 }260 Gc::new(out)261 }262 Self::Eager(vec) => vec.clone(),263 Self::Extended(_v) => {264 let mut out = Vec::with_capacity(self.len());265 for item in self.iter() {266 out.push(item?);267 }268 Gc::new(out)269 }270 })271 }272273 pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {274 (0..self.len()).map(move |idx| match self {275 Self::Lazy(l) => l[idx].evaluate(),276 Self::Eager(e) => Ok(e[idx].clone()),277 Self::Extended(_) => self.get(idx).map(|e| e.unwrap()),278 })279 }280281 pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {282 (0..self.len()).map(move |idx| match self {283 Self::Lazy(l) => l[idx].clone(),284 Self::Eager(e) => LazyVal::new_resolved(e[idx].clone()),285 Self::Extended(_) => self.get_lazy(idx).unwrap(),286 })287 }288289 pub fn reversed(self) -> Self {290 match self {291 Self::Lazy(vec) => {292 let mut out = (&vec as &Vec<_>).clone();293 out.reverse();294 Self::Lazy(Gc::new(out))295 }296 Self::Eager(vec) => {297 let mut out = (&vec as &Vec<_>).clone();298 out.reverse();299 Self::Eager(Gc::new(out))300 }301 Self::Extended(b) => Self::Extended(Box::new((b.1.reversed(), b.0.reversed()))),302 }303 }304305 pub fn map(self, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {306 let mut out = Vec::with_capacity(self.len());307308 for value in self.iter() {309 out.push(mapper(value?)?);310 }311312 Ok(Self::Eager(Gc::new(out)))313 }314315 pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {316 let mut out = Vec::with_capacity(self.len());317318 for value in self.iter() {319 let value = value?;320 if filter(&value)? {321 out.push(value);322 }323 }324325 Ok(Self::Eager(Gc::new(out)))326 }327328 pub fn ptr_eq(a: &Self, b: &Self) -> bool {329 match (a, b) {330 (Self::Lazy(a), Self::Lazy(b)) => Gc::ptr_eq(a, b),331 (Self::Eager(a), Self::Eager(b)) => Gc::ptr_eq(a, b),332 _ => false,333 }334 }335}336337impl From<Vec<LazyVal>> for ArrValue {338 fn from(v: Vec<LazyVal>) -> Self {339 Self::Lazy(Gc::new(v))340 }341}342343impl From<Vec<Val>> for ArrValue {344 fn from(v: Vec<Val>) -> Self {345 Self::Eager(Gc::new(v))346 }347}348349pub enum IndexableVal {350 Str(IStr),351 Arr(ArrValue),352}353354#[derive(Debug, Clone, Trace)]355#[trivially_drop]356pub enum Val {357 Bool(bool),358 Null,359 Str(IStr),360 Num(f64),361 Arr(ArrValue),362 Obj(ObjValue),363 Func(Gc<FuncVal>),364}365366macro_rules! matches_unwrap {367 ($e: expr, $p: pat, $r: expr) => {368 match $e {369 $p => $r,370 _ => panic!("no match"),371 }372 };373}374impl Val {375 /// Creates `Val::Num` after checking for numeric overflow.376 /// As numbers are `f64`, we can just check for their finity.377 pub fn new_checked_num(num: f64) -> Result<Self> {378 if num.is_finite() {379 Ok(Self::Num(num))380 } else {381 throw!(RuntimeError("overflow".into()))382 }383 }384385 pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {386 let this_type = self.value_type();387 if this_type != val_type {388 throw!(TypeMismatch(context, vec![val_type], this_type))389 } else {390 Ok(())391 }392 }393 pub fn unwrap_num(self) -> Result<f64> {394 Ok(matches_unwrap!(self, Self::Num(v), v))395 }396 pub fn unwrap_func(self) -> Result<Gc<FuncVal>> {397 Ok(matches_unwrap!(self, Self::Func(v), v))398 }399 pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {400 self.assert_type(context, ValType::Bool)?;401 Ok(matches_unwrap!(self, Self::Bool(v), v))402 }403 pub fn try_cast_str(self, context: &'static str) -> Result<IStr> {404 self.assert_type(context, ValType::Str)?;405 Ok(matches_unwrap!(self, Self::Str(v), v))406 }407 pub fn try_cast_num(self, context: &'static str) -> Result<f64> {408 self.assert_type(context, ValType::Num)?;409 self.unwrap_num()410 }411 pub fn try_cast_nullable_num(self, context: &'static str) -> Result<Option<f64>> {412 Ok(match self {413 Val::Null => None,414 Val::Num(num) => Some(num),415 _ => throw!(TypeMismatch(416 context,417 vec![ValType::Null, ValType::Num],418 self.value_type()419 )),420 })421 }422 pub const fn value_type(&self) -> ValType {423 match self {424 Self::Str(..) => ValType::Str,425 Self::Num(..) => ValType::Num,426 Self::Arr(..) => ValType::Arr,427 Self::Obj(..) => ValType::Obj,428 Self::Bool(_) => ValType::Bool,429 Self::Null => ValType::Null,430 Self::Func(..) => ValType::Func,431 }432 }433434 pub fn to_string(&self) -> Result<IStr> {435 Ok(match self {436 Self::Bool(true) => "true".into(),437 Self::Bool(false) => "false".into(),438 Self::Null => "null".into(),439 Self::Str(s) => s.clone(),440 v => manifest_json_ex(441 v,442 &ManifestJsonOptions {443 padding: "",444 mtype: ManifestType::ToString,445 },446 )?447 .into(),448 })449 }450451 /// Expects value to be object, outputs (key, manifested value) pairs452 pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {453 let obj = match self {454 Self::Obj(obj) => obj,455 _ => throw!(MultiManifestOutputIsNotAObject),456 };457 let keys = obj.fields();458 let mut out = Vec::with_capacity(keys.len());459 for key in keys {460 let value = obj461 .get(key.clone())?462 .expect("item in object")463 .manifest(ty)?;464 out.push((key, value));465 }466 Ok(out)467 }468469 /// Expects value to be array, outputs manifested values470 pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<IStr>> {471 let arr = match self {472 Self::Arr(a) => a,473 _ => throw!(StreamManifestOutputIsNotAArray),474 };475 let mut out = Vec::with_capacity(arr.len());476 for i in arr.iter() {477 out.push(i?.manifest(ty)?);478 }479 Ok(out)480 }481482 pub fn manifest(&self, ty: &ManifestFormat) -> Result<IStr> {483 Ok(match ty {484 ManifestFormat::YamlStream(format) => {485 let arr = match self {486 Self::Arr(a) => a,487 _ => throw!(StreamManifestOutputIsNotAArray),488 };489 let mut out = String::new();490491 match format as &ManifestFormat {492 ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),493 ManifestFormat::String => throw!(StreamManifestCannotNestString),494 _ => {}495 };496497 if !arr.is_empty() {498 for v in arr.iter() {499 out.push_str("---\n");500 out.push_str(&v?.manifest(format)?);501 out.push('\n');502 }503 out.push_str("...");504 }505506 out.into()507 }508 ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,509 ManifestFormat::Json(padding) => self.to_json(*padding)?,510 ManifestFormat::ToString => self.to_string()?,511 ManifestFormat::String => match self {512 Self::Str(s) => s.clone(),513 _ => throw!(StringManifestOutputIsNotAString),514 },515 })516 }517518 /// For manifestification519 pub fn to_json(&self, padding: usize) -> Result<IStr> {520 manifest_json_ex(521 self,522 &ManifestJsonOptions {523 padding: &" ".repeat(padding),524 mtype: if padding == 0 {525 ManifestType::Minify526 } else {527 ManifestType::Manifest528 },529 },530 )531 .map(|s| s.into())532 }533534 /// Calls `std.manifestJson`535 pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {536 manifest_json_ex(537 self,538 &ManifestJsonOptions {539 padding: &" ".repeat(padding),540 mtype: ManifestType::Std,541 },542 )543 .map(|s| s.into())544 }545546 pub fn to_yaml(&self, padding: usize) -> Result<IStr> {547 with_state(|s| {548 let ctx = s549 .create_default_context()550 .with_var("__tmp__to_json__".into(), self.clone());551 evaluate(552 ctx,553 &el!(Expr::Apply(554 el!(Expr::Index(555 el!(Expr::Var("std".into())),556 el!(Expr::Str("manifestYamlDoc".into()))557 )),558 ArgsDesc::new(559 vec![560 el!(Expr::Var("__tmp__to_json__".into())),561 el!(Expr::Literal(if padding != 0 {562 LiteralType::True563 } else {564 LiteralType::False565 })),566 ],567 vec![]568 ),569 false570 )),571 )?572 .try_cast_str("to json")573 })574 }575 pub fn into_indexable(self) -> Result<IndexableVal> {576 Ok(match self {577 Val::Str(s) => IndexableVal::Str(s),578 Val::Arr(arr) => IndexableVal::Arr(arr),579 _ => throw!(ValueIsNotIndexable(self.value_type())),580 })581 }582}583584const fn is_function_like(val: &Val) -> bool {585 matches!(val, Val::Func(_))586}587588/// Native implementation of `std.primitiveEquals`589pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {590 Ok(match (val_a, val_b) {591 (Val::Bool(a), Val::Bool(b)) => a == b,592 (Val::Null, Val::Null) => true,593 (Val::Str(a), Val::Str(b)) => a == b,594 (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,595 (Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(596 "primitiveEquals operates on primitive types, got array".into(),597 )),598 (Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(599 "primitiveEquals operates on primitive types, got object".into(),600 )),601 (a, b) if is_function_like(a) && is_function_like(b) => {602 throw!(RuntimeError("cannot test equality of functions".into()))603 }604 (_, _) => false,605 })606}607608/// Native implementation of `std.equals`609pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {610 if val_a.value_type() != val_b.value_type() {611 return Ok(false);612 }613 match (val_a, val_b) {614 (Val::Arr(a), Val::Arr(b)) => {615 if ArrValue::ptr_eq(a, b) {616 return Ok(true);617 }618 if a.len() != b.len() {619 return Ok(false);620 }621 for (a, b) in a.iter().zip(b.iter()) {622 if !equals(&a?, &b?)? {623 return Ok(false);624 }625 }626 Ok(true)627 }628 (Val::Obj(a), Val::Obj(b)) => {629 if ObjValue::ptr_eq(a, b) {630 return Ok(true);631 }632 let fields = a.fields();633 if fields != b.fields() {634 return Ok(false);635 }636 for field in fields {637 if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {638 return Ok(false);639 }640 }641 Ok(true)642 }643 (a, b) => Ok(primitive_equals(a, b)?),644 }645}crates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/expr.rs
+++ b/crates/jrsonnet-parser/src/expr.rs
@@ -194,18 +194,13 @@
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[derive(Debug, PartialEq, Trace)]
#[trivially_drop]
-pub struct Arg(pub Option<String>, pub LocExpr);
-
-#[cfg_attr(feature = "serialize", derive(Serialize))]
-#[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, PartialEq, Trace)]
-#[trivially_drop]
-pub struct ArgsDesc(pub Vec<Arg>);
-
-impl Deref for ArgsDesc {
- type Target = Vec<Arg>;
- fn deref(&self) -> &Self::Target {
- &self.0
+pub struct ArgsDesc {
+ pub unnamed: Vec<LocExpr>,
+ pub named: Vec<(IStr, LocExpr)>,
+}
+impl ArgsDesc {
+ pub fn new(unnamed: Vec<LocExpr>, named: Vec<(IStr, LocExpr)>) -> Self {
+ Self { unnamed, named }
}
}
crates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/lib.rs
+++ b/crates/jrsonnet-parser/src/lib.rs
@@ -7,6 +7,7 @@
};
mod expr;
pub use expr::*;
+pub use jrsonnet_interner::IStr;
pub use peg;
pub struct ParserSettings {
@@ -70,19 +71,29 @@
}
/ { expr::ParamsDesc(Rc::new(Vec::new())) }
- pub rule arg(s: &ParserSettings) -> expr::Arg
- = name:$(id()) _ "=" _ expr:expr(s) {expr::Arg(Some(name.into()), expr)}
- / expr:expr(s) {expr::Arg(None, expr)}
+ pub rule arg(s: &ParserSettings) -> (Option<IStr>, LocExpr)
+ = quiet! { name:(s:$(id()) _ "=" _ {s})? expr:expr(s) {(name.map(Into::into), expr)} }
+ / expected!("<argument>")
+
pub rule args(s: &ParserSettings) -> expr::ArgsDesc
- = args:arg(s) ** comma() comma()? {
+ = args:arg(s)**comma() comma()? {?
+ let unnamed_count = args.iter().take_while(|(n, _)| n.is_none()).count();
+ let mut unnamed = Vec::with_capacity(unnamed_count);
+ let mut named = Vec::with_capacity(args.len() - unnamed_count);
let mut named_started = false;
- for arg in &args {
- named_started = named_started || arg.0.is_some();
- assert_eq!(named_started, arg.0.is_some(), "named args should be used after all positionals");
+ for (name, value) in args {
+ if let Some(name) = name {
+ named_started = true;
+ named.push((name, value));
+ } else {
+ if named_started {
+ return Err("<named argument>")
+ }
+ unnamed.push(value);
+ }
}
- expr::ArgsDesc(args)
+ Ok(expr::ArgsDesc::new(unnamed, named))
}
- / { expr::ArgsDesc(Vec::new()) }
pub rule bind(s: &ParserSettings) -> expr::BindSpec
= name:$(id()) _ "=" _ expr:expr(s) {expr::BindSpec{name:name.into(), params: None, value: expr}}
@@ -493,7 +504,7 @@
el!(ArrComp(
el!(Apply(
el!(Index(el!(Var("std".into())), el!(Str("deepJoin".into())))),
- ArgsDesc(vec![Arg(None, el!(Var("x".into())))]),
+ ArgsDesc::new(vec![el!(Var("x".into()))], vec![]),
false,
)),
vec![CompSpec::ForSpec(ForSpecData(