git.delta.rocks / jrsonnet / refs/commits / 0b0d703c6d05

difftreelog

refactor do not desugar mod/slice

Yaroslav Bolyukin2021-07-04parent: #53ec857.patch.diff
in: master

7 files changed

modifiedcrates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -1,13 +1,14 @@
 use crate::{
 	equals,
 	error::{Error::*, Result},
+	operator::evaluate_mod_op,
 	parse_args, primitive_equals, push, throw, with_state, ArrValue, Context, EvaluationState,
-	FuncVal, LazyVal, Val,
+	FuncVal, IndexableVal, LazyVal, Val,
 };
 use format::{format_arr, format_obj};
 use jrsonnet_gc::Gc;
 use jrsonnet_interner::IStr;
-use jrsonnet_parser::{ArgsDesc, BinaryOpType, ExprLocation};
+use jrsonnet_parser::{ArgsDesc, ExprLocation};
 use jrsonnet_types::ty;
 use std::{collections::HashMap, path::PathBuf, rc::Rc};
 
@@ -20,7 +21,7 @@
 pub mod manifest;
 pub mod sort;
 
-fn std_format(str: IStr, vals: Val) -> Result<Val> {
+pub fn std_format(str: IStr, vals: Val) -> Result<Val> {
 	push(
 		Some(&ExprLocation(Rc::from(PathBuf::from("std.jsonnet")), 0, 0)),
 		|| format!("std.format of {}", str),
@@ -34,6 +35,38 @@
 	)
 }
 
+pub fn std_slice(
+	indexable: IndexableVal,
+	index: Option<usize>,
+	end: Option<usize>,
+	step: Option<usize>,
+) -> Result<Val> {
+	let index = index.unwrap_or(0);
+	let end = end.unwrap_or_else(|| match &indexable {
+		IndexableVal::Str(_) => usize::MAX,
+		IndexableVal::Arr(v) => v.len(),
+	});
+	let step = step.unwrap_or(1);
+	match &indexable {
+		IndexableVal::Str(s) => Ok(Val::Str(
+			(s.chars()
+				.skip(index)
+				.take(end - index)
+				.step_by(step)
+				.collect::<String>())
+			.into(),
+		)),
+		IndexableVal::Arr(arr) => Ok(Val::Arr(
+			(arr.iter()
+				.skip(index)
+				.take(end - index)
+				.step_by(step)
+				.collect::<Result<Vec<Val>>>()?)
+			.into(),
+		)),
+	}
+}
+
 type Builtin = fn(context: Context, loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val>;
 
 type BuiltinsType = HashMap<Box<str>, Builtin>;
@@ -188,34 +221,12 @@
 		2, end: ty!((number | null));
 		3, step: ty!((number | null));
 	], {
-		let index = match index {
-			Val::Num(v) => v as usize,
-			Val::Null => 0,
-			_ => unreachable!(),
-		};
-		let end = match end {
-			Val::Num(v) => v as usize,
-			Val::Null => match &indexable {
-				Val::Str(s) => s.chars().count(),
-				Val::Arr(v) => v.len(),
-				_ => unreachable!()
-			},
-			_ => unreachable!()
-		};
-		let step = match step {
-			Val::Num(v) => v as usize,
-			Val::Null => 1,
-			_ => unreachable!()
-		};
-		match &indexable {
-			Val::Str(s) => {
-				Ok(Val::Str((s.chars().skip(index).take(end-index).step_by(step).collect::<String>()).into()))
-			}
-			Val::Arr(arr) => {
-				Ok(Val::Arr((arr.iter().skip(index).take(end-index).step_by(step).collect::<Result<Vec<Val>>>()?).into()))
-			}
-			_ => unreachable!()
-		}
+		std_slice(
+			indexable.to_indexable()?,
+			index.try_cast_nullable_num("index")?.map(|v| v as usize),
+			end.try_cast_nullable_num("end")?.map(|v| v as usize),
+			step.try_cast_nullable_num("step")?.map(|v| v as usize),
+		)
 	})
 }
 
@@ -257,11 +268,7 @@
 		0, a: ty!((number | string));
 		1, b: ty!(any);
 	], {
-		match (a, b) {
-			(Val::Num(a), Val::Num(b)) => Ok(Val::Num(a % b)),
-			(Val::Str(str), vals) => std_format(str, vals),
-			(a, b) => throw!(BinaryOperatorDoesNotOperateOnValues(BinaryOpType::Mod, a.value_type(), b.value_type()))
-		}
+		evaluate_mod_op(&a, &b)
 	})
 }
 
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -73,6 +73,8 @@
 	ValueIndexMustBeTypeGot(ValType, ValType, ValType),
 	#[error("cant index into {0}")]
 	CantIndexInto(ValType),
+	#[error("{0} is not indexable")]
+	ValueIsNotIndexable(ValType),
 
 	#[error("super can't be used standalone")]
 	StandaloneSuper,
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -1,4 +1,5 @@
 use crate::{
+	builtin::std_slice,
 	error::Error::*,
 	evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},
 	push, throw, with_state, ArrValue, Bindable, Context, ContextCreator, FuncDesc, FuncVal,
@@ -679,6 +680,28 @@
 				}
 			}
 		}
+		Slice(value, desc) => {
+			let indexable = evaluate(context.clone(), value)?;
+
+			fn parse_num(
+				context: &Context,
+				expr: Option<&LocExpr>,
+				desc: &'static str,
+			) -> Result<Option<usize>> {
+				Ok(match expr {
+					Some(s) => evaluate(context.clone(), &s)?
+						.try_cast_nullable_num(desc)?
+						.map(|v| v as usize),
+					None => None,
+				})
+			}
+
+			let start = parse_num(&context, desc.start.as_ref(), "start")?;
+			let end = parse_num(&context, desc.end.as_ref(), "end")?;
+			let step = parse_num(&context, desc.step.as_ref(), "step")?;
+
+			std_slice(indexable.to_indexable()?, start, end, step)?
+		}
 		Import(path) => {
 			let tmp = loc
 				.clone()
modifiedcrates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/evaluate/operator.rs
1use crate::{equals, evaluate, Context, Val};2use crate::{error::Error::*, throw, Result};3use jrsonnet_parser::{BinaryOpType, LocExpr, UnaryOpType};45pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {6	use UnaryOpType::*;7	use Val::*;8	Ok(match (op, b) {9		(Not, Bool(v)) => Bool(!v),10		(Minus, Num(n)) => Num(-*n),11		(BitNot, Num(n)) => Num(!(*n as i32) as f64),12		(op, o) => throw!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),13	})14}1516pub fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {17	use Val::*;18	Ok(match (a, b) {19		(Str(v1), Str(v2)) => Str(((**v1).to_owned() + v2).into()),2021		// Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)22		(Num(n), Str(o)) => Str(format!("{}{}", n, o).into()),23		(Str(o), Num(n)) => Str(format!("{}{}", o, n).into()),2425		(Str(s), o) => Str(format!("{}{}", s, o.clone().to_string()?).into()),26		(o, Str(s)) => Str(format!("{}{}", o.clone().to_string()?, s).into()),2728		(Obj(v1), Obj(v2)) => Obj(v2.extend_from(v1.clone())),29		(Arr(a), Arr(b)) => {30			let mut out = Vec::with_capacity(a.len() + b.len());31			out.extend(a.iter_lazy());32			out.extend(b.iter_lazy());33			Arr(out.into())34		}35		(Num(v1), Num(v2)) => Val::new_checked_num(v1 + v2)?,36		_ => throw!(BinaryOperatorDoesNotOperateOnValues(37			BinaryOpType::Add,38			a.value_type(),39			b.value_type(),40		)),41	})42}4344pub fn evaluate_binary_op_special(45	context: Context,46	a: &LocExpr,47	op: BinaryOpType,48	b: &LocExpr,49) -> Result<Val> {50	use BinaryOpType::*;51	use Val::*;52	Ok(match (evaluate(context.clone(), a)?, op, b) {53		(Bool(true), Or, _o) => Val::Bool(true),54		(Bool(false), And, _o) => Val::Bool(false),55		(a, op, eb) => evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?)?,56	})57}5859pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {60	use BinaryOpType::*;61	use Val::*;62	Ok(match (a, op, b) {63		(Str(a), In, Obj(obj)) => Bool(obj.has_field_ex(a.clone(), true)),6465		(a, Add, b) => evaluate_add_op(a, b)?,6667		(a, Eq, b) => Bool(equals(a, b)?),68		(a, Neq, b) => Bool(!equals(a, b)?),6970		(Str(v1), Mul, Num(v2)) => Str(v1.repeat(*v2 as usize).into()),7172		// Bool X Bool73		(Bool(a), And, Bool(b)) => Bool(*a && *b),74		(Bool(a), Or, Bool(b)) => Bool(*a || *b),7576		// Str X Str77		(Str(v1), Lt, Str(v2)) => Bool(v1 < v2),78		(Str(v1), Gt, Str(v2)) => Bool(v1 > v2),79		(Str(v1), Lte, Str(v2)) => Bool(v1 <= v2),80		(Str(v1), Gte, Str(v2)) => Bool(v1 >= v2),8182		// Num X Num83		(Num(v1), Mul, Num(v2)) => Val::new_checked_num(v1 * v2)?,84		(Num(v1), Div, Num(v2)) => {85			if *v2 <= f64::EPSILON {86				throw!(DivisionByZero)87			}88			Val::new_checked_num(v1 / v2)?89		}9091		(Num(v1), Sub, Num(v2)) => Val::new_checked_num(v1 - v2)?,9293		(Num(v1), Lt, Num(v2)) => Bool(v1 < v2),94		(Num(v1), Gt, Num(v2)) => Bool(v1 > v2),95		(Num(v1), Lte, Num(v2)) => Bool(v1 <= v2),96		(Num(v1), Gte, Num(v2)) => Bool(v1 >= v2),9798		(Num(v1), BitAnd, Num(v2)) => Num(((*v1 as i32) & (*v2 as i32)) as f64),99		(Num(v1), BitOr, Num(v2)) => Num(((*v1 as i32) | (*v2 as i32)) as f64),100		(Num(v1), BitXor, Num(v2)) => Num(((*v1 as i32) ^ (*v2 as i32)) as f64),101		(Num(v1), Lhs, Num(v2)) => {102			if *v2 < 0.0 {103				throw!(RuntimeError("shift by negative exponent".into()))104			}105			Num(((*v1 as i32) << (*v2 as i32)) as f64)106		}107		(Num(v1), Rhs, Num(v2)) => {108			if *v2 < 0.0 {109				throw!(RuntimeError("shift by negative exponent".into()))110			}111			Num(((*v1 as i32) >> (*v2 as i32)) as f64)112		}113114		_ => throw!(BinaryOperatorDoesNotOperateOnValues(115			op,116			a.value_type(),117			b.value_type(),118		)),119	})120}
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -345,6 +345,11 @@
 	}
 }
 
+pub enum IndexableVal {
+	Str(IStr),
+	Arr(ArrValue),
+}
+
 #[derive(Debug, Clone, Trace)]
 #[trivially_drop]
 pub enum Val {
@@ -402,6 +407,17 @@
 		self.assert_type(context, ValType::Num)?;
 		self.unwrap_num()
 	}
+	pub fn try_cast_nullable_num(self, context: &'static str) -> Result<Option<f64>> {
+		Ok(match self {
+			Val::Null => None,
+			Val::Num(num) => Some(num),
+			_ => throw!(TypeMismatch(
+				context,
+				vec![ValType::Null, ValType::Num],
+				self.value_type()
+			)),
+		})
+	}
 	pub const fn value_type(&self) -> ValType {
 		match self {
 			Self::Str(..) => ValType::Str,
@@ -580,6 +596,13 @@
 			.try_cast_str("to json")
 		})
 	}
+	pub fn to_indexable(self) -> Result<IndexableVal> {
+		Ok(match self {
+			Val::Str(s) => IndexableVal::Str(s),
+			Val::Arr(arr) => IndexableVal::Arr(arr),
+			_ => throw!(ValueIsNotIndexable(self.value_type())),
+		})
+	}
 }
 
 const fn is_function_like(val: &Val) -> bool {
modifiedcrates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth
--- a/crates/jrsonnet-parser/src/expr.rs
+++ b/crates/jrsonnet-parser/src/expr.rs
@@ -274,6 +274,8 @@
 	False,
 }
 
+#[cfg_attr(feature = "serialize", derive(Serialize))]
+#[cfg_attr(feature = "deserialize", derive(Deserialize))]
 #[derive(Debug, PartialEq, Trace)]
 #[trivially_drop]
 pub struct SliceDesc {
@@ -349,6 +351,7 @@
 		cond_then: LocExpr,
 		cond_else: Option<LocExpr>,
 	},
+	Slice(LocExpr, SliceDesc),
 }
 
 /// file, begin offset, end offset
modifiedcrates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-parser/src/lib.rs
+++ b/crates/jrsonnet-parser/src/lib.rs
@@ -14,6 +14,17 @@
 	pub file_name: Rc<Path>,
 }
 
+macro_rules! expr_bin {
+	($a:ident $op:ident $b:ident) => {
+		loc_expr_todo!(Expr::BinaryOp($a, $op, $b))
+	};
+}
+macro_rules! expr_un {
+	($op:ident $a:ident) => {
+		loc_expr_todo!(Expr::UnaryOp($op, $a))
+	};
+}
+
 parser! {
 	grammar jsonnet_parser() for str {
 		use peg::ParseLiteral;
@@ -219,54 +230,43 @@
 
 
 		use BinaryOpType::*;
+		use UnaryOpType::*;
 		rule expr(s: &ParserSettings) -> LocExpr
 			= start:position!() a:precedence! {
-				a:(@) _ binop(<"||">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, Or, b))}
+				a:(@) _ binop(<"||">) _ b:@ {expr_bin!(a Or b)}
 				--
-				a:(@) _ binop(<"&&">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, And, b))}
+				a:(@) _ binop(<"&&">) _ b:@ {expr_bin!(a And b)}
 				--
-				a:(@) _ binop(<"|">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BitOr, b))}
+				a:(@) _ binop(<"|">) _ b:@ {expr_bin!(a BitOr b)}
 				--
-				a:@ _ binop(<"^">) _ b:(@) {loc_expr_todo!(Expr::BinaryOp(a, BitXor, b))}
+				a:@ _ binop(<"^">) _ b:(@) {expr_bin!(a BitXor b)}
 				--
-				a:(@) _ binop(<"&">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BitAnd, b))}
+				a:(@) _ binop(<"&">) _ b:@ {expr_bin!(a BitAnd b)}
 				--
-				a:(@) _ binop(<"==">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, Eq, b))}
-				a:(@) _ binop(<"!=">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, Neq, b))}
+				a:(@) _ binop(<"==">) _ b:@ {expr_bin!(a Eq b)}
+				a:(@) _ binop(<"!=">) _ b:@ {expr_bin!(a Neq b)}
 				--
-				a:(@) _ binop(<"<">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, Lt, b))}
-				a:(@) _ binop(<">">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, Gt, b))}
-				a:(@) _ binop(<"<=">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, Lte, b))}
-				a:(@) _ binop(<">=">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, Gte, b))}
-				a:(@) _ binop(<keyword("in")>) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, In, b))}
+				a:(@) _ binop(<"<">) _ b:@ {expr_bin!(a Lt b)}
+				a:(@) _ binop(<">">) _ b:@ {expr_bin!(a Gt b)}
+				a:(@) _ binop(<"<=">) _ b:@ {expr_bin!(a Lte b)}
+				a:(@) _ binop(<">=">) _ b:@ {expr_bin!(a Gte b)}
+				a:(@) _ binop(<keyword("in")>) _ b:@ {expr_bin!(a In b)}
 				--
-				a:(@) _ binop(<"<<">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, Lhs, b))}
-				a:(@) _ binop(<">>">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, Rhs, b))}
+				a:(@) _ binop(<"<<">) _ b:@ {expr_bin!(a Lhs b)}
+				a:(@) _ binop(<">>">) _ b:@ {expr_bin!(a Rhs b)}
 				--
-				a:(@) _ binop(<"+">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, Add, b))}
-				a:(@) _ binop(<"-">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, Sub, b))}
+				a:(@) _ binop(<"+">) _ b:@ {expr_bin!(a Add b)}
+				a:(@) _ binop(<"-">) _ b:@ {expr_bin!(a Sub b)}
 				--
-				a:(@) _ binop(<"*">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, Mul, b))}
-				a:(@) _ binop(<"/">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, Div, b))}
-				a:(@) _ binop(<"%">) _ b:@ {loc_expr_todo!(Expr::Apply(
-					el!(Expr::Intrinsic("mod".into())), ArgsDesc(vec![Arg(None, a), Arg(None, b)]),
-					false
-				))}
+				a:(@) _ binop(<"*">) _ b:@ {expr_bin!(a Mul b)}
+				a:(@) _ binop(<"/">) _ b:@ {expr_bin!(a Div b)}
+				a:(@) _ binop(<"%">) _ b:@ {expr_bin!(a Mod b)}
 				--
-						unaryop(<"-">) _ b:@ {loc_expr_todo!(Expr::UnaryOp(UnaryOpType::Minus, b))}
-						unaryop(<"!">) _ b:@ {loc_expr_todo!(Expr::UnaryOp(UnaryOpType::Not, b))}
-						unaryop(<"~">) _ b:@ { loc_expr_todo!(Expr::UnaryOp(UnaryOpType::BitNot, b)) }
+						unaryop(<"-">) _ b:@ {expr_un!(Minus b)}
+						unaryop(<"!">) _ b:@ {expr_un!(Not b)}
+						unaryop(<"~">) _ b:@ {expr_un!(BitNot b)}
 				--
-				a:(@) _ "[" _ s:slice_desc(s) _ "]" {loc_expr_todo!(Expr::Apply(
-					el!(Expr::Intrinsic("slice".into())),
-					ArgsDesc(vec![
-						Arg(None, a),
-						Arg(None, s.start.unwrap_or_else(||el!(Expr::Literal(LiteralType::Null)))),
-						Arg(None, s.end.unwrap_or_else(||el!(Expr::Literal(LiteralType::Null)))),
-						Arg(None, s.step.unwrap_or_else(||el!(Expr::Literal(LiteralType::Null)))),
-					]),
-					true,
-				))}
+				a:(@) _ "[" _ s:slice_desc(s) _ "]" {loc_expr_todo!(Expr::Slice(a, s))}
 				a:(@) _ "." _ s:$(id()) {loc_expr_todo!(Expr::Index(a, el!(Expr::Str(s.into()))))}
 				a:(@) _ "[" _ s:expr(s) _ "]" {loc_expr_todo!(Expr::Index(a, s))}
 				a:(@) _ "(" _ args:args(s) _ ")" ts:(_ keyword("tailstrict"))? {loc_expr_todo!(Expr::Apply(a, args, ts.is_some()))}