git.delta.rocks / jrsonnet / refs/commits / bc97bc99f5fd

difftreelog

fix(evaluator) missing intrinsics for slice, mod

Yaroslav Bolyukin2021-01-06parent: #7c1d01a.patch.diff
in: master
Fixes #30

3 files changed

modifiedcrates/jrsonnet-evaluator/build.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/build.rs
+++ b/crates/jrsonnet-evaluator/build.rs
@@ -39,7 +39,8 @@
 								if **name == *"join" || **name == *"manifestJsonEx" ||
 								**name == *"escapeStringJson" || **name == *"equals" ||
 								**name == *"base64" || **name == *"foldl" || **name == *"foldr" ||
-								**name == *"sortImpl" || **name == *"format" || **name == *"range" || **name == *"reverse"
+								**name == *"sortImpl" || **name == *"format" || **name == *"range" ||
+								**name == *"reverse" || **name == *"slice" || **name == *"mod"
 							)
 						})
 						.collect(),
modifiedcrates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -16,6 +16,20 @@
 pub mod manifest;
 pub mod sort;
 
+fn std_format(str: Rc<str>, vals: Val) -> Result<Val> {
+	push(
+		&Some(ExprLocation(Rc::from(PathBuf::from("std.jsonnet")), 0, 0)),
+		|| format!("std.format of {}", str),
+		|| {
+			Ok(match vals {
+				Val::Arr(vals) => Val::Str(format_arr(&str, &vals)?.into()),
+				Val::Obj(obj) => Val::Str(format_obj(&str, &obj)?.into()),
+				o => Val::Str(format_arr(&str, &[o])?.into()),
+			})
+		},
+	)
+}
+
 #[allow(clippy::cognitive_complexity)]
 pub fn call_builtin(
 	context: Context,
@@ -99,6 +113,43 @@
 					.any(|(k, _v)| *k == *f),
 			))
 		})?,
+
+		// faster
+		"slice" => parse_args!(context, "slice", args, 4, [
+			0, indexable: [Val::Str | Val::Arr], vec![ValType::Str, ValType::Arr];
+			1, index, vec![ValType::Num, ValType::Null];
+			2, end, vec![ValType::Num, ValType::Null];
+			3, step, vec![ValType::Num, ValType::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).cloned().collect::<Vec<Val>>()).into()))
+				}
+				_ => unreachable!()
+			}
+		})?,
 		"primitiveEquals" => parse_args!(context, "std.primitiveEquals", args, 2, [
 			0, a, vec![];
 			1, b, vec![];
@@ -112,6 +163,16 @@
 		], {
 			Ok(Val::Bool(equals(&a, &b)?))
 		})?,
+		"mod" => parse_args!(context, "std.mod", args, 2, [
+			0, a: [Val::Num | Val::Str], vec![ValType::Num, ValType::Str];
+			1, b, vec![];
+		], {
+			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(jrsonnet_parser::BinaryOpType::Mod, a.value_type()?, b.value_type()?))
+			}
+		})?,
 		"modulo" => parse_args!(context, "std.modulo", args, 2, [
 			0, a: [Val::Num]!!Val::Num, vec![ValType::Num];
 			1, b: [Val::Num]!!Val::Num, vec![ValType::Num];
@@ -219,13 +280,7 @@
 			0, str: [Val::Str]!!Val::Str, vec![ValType::Str];
 			1, vals, vec![]
 		], {
-			push(&Some(ExprLocation(Rc::from(PathBuf::from("std.jsonnet")), 0, 0)), ||format!("std.format of {}", str), ||{
-				Ok(match vals {
-					Val::Arr(vals) => Val::Str(format_arr(&str, &vals)?.into()),
-					Val::Obj(obj) => Val::Str(format_obj(&str, &obj)?.into()),
-					o => Val::Str(format_arr(&str, &[o])?.into()),
-				})
-			})
+			std_format(str, vals)
 		})?,
 		// faster
 		"range" => parse_args!(context, "std.range", args, 2, [
modifiedcrates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth
after · crates/jrsonnet-parser/src/expr.rs
1#[cfg(feature = "deserialize")]2use serde::Deserialize;3#[cfg(feature = "serialize")]4use serde::Serialize;5use std::{6	fmt::{Debug, Display},7	ops::Deref,8	path::PathBuf,9	rc::Rc,10};11#[cfg(feature = "dump")]12use structdump_derive::Codegen;1314#[cfg_attr(feature = "dump", derive(Codegen))]15#[cfg_attr(feature = "serialize", derive(Serialize))]16#[cfg_attr(feature = "deserialize", derive(Deserialize))]17#[derive(Debug, PartialEq)]18pub enum FieldName {19	/// {fixed: 2}20	Fixed(Rc<str>),21	/// {["dyn"+"amic"]: 3}22	Dyn(LocExpr),23}2425#[cfg_attr(feature = "dump", derive(Codegen))]26#[cfg_attr(feature = "serialize", derive(Serialize))]27#[cfg_attr(feature = "deserialize", derive(Deserialize))]28#[derive(Debug, Clone, Copy, PartialEq)]29pub enum Visibility {30	/// :31	Normal,32	/// ::33	Hidden,34	/// :::35	Unhide,36}3738#[cfg_attr(feature = "dump", derive(Codegen))]39#[cfg_attr(feature = "serialize", derive(Serialize))]40#[cfg_attr(feature = "deserialize", derive(Deserialize))]41#[derive(Debug, PartialEq)]42pub struct AssertStmt(pub LocExpr, pub Option<LocExpr>);4344#[cfg_attr(feature = "dump", derive(Codegen))]45#[cfg_attr(feature = "serialize", derive(Serialize))]46#[cfg_attr(feature = "deserialize", derive(Deserialize))]47#[derive(Debug, PartialEq)]48pub struct FieldMember {49	pub name: FieldName,50	pub plus: bool,51	pub params: Option<ParamsDesc>,52	pub visibility: Visibility,53	pub value: LocExpr,54}5556#[cfg_attr(feature = "dump", derive(Codegen))]57#[cfg_attr(feature = "serialize", derive(Serialize))]58#[cfg_attr(feature = "deserialize", derive(Deserialize))]59#[derive(Debug, PartialEq)]60pub enum Member {61	Field(FieldMember),62	BindStmt(BindSpec),63	AssertStmt(AssertStmt),64}6566#[cfg_attr(feature = "dump", derive(Codegen))]67#[cfg_attr(feature = "serialize", derive(Serialize))]68#[cfg_attr(feature = "deserialize", derive(Deserialize))]69#[derive(Debug, Clone, Copy, PartialEq)]70pub enum UnaryOpType {71	Plus,72	Minus,73	BitNot,74	Not,75}76impl Display for UnaryOpType {77	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {78		use UnaryOpType::*;79		write!(80			f,81			"{}",82			match self {83				Plus => "+",84				Minus => "-",85				BitNot => "~",86				Not => "!",87			}88		)89	}90}9192#[cfg_attr(feature = "dump", derive(Codegen))]93#[cfg_attr(feature = "serialize", derive(Serialize))]94#[cfg_attr(feature = "deserialize", derive(Deserialize))]95#[derive(Debug, Clone, Copy, PartialEq)]96pub enum BinaryOpType {97	Mul,98	Div,99100	Mod,101102	Add,103	Sub,104105	Lhs,106	Rhs,107108	Lt,109	Gt,110	Lte,111	Gte,112113	BitAnd,114	BitOr,115	BitXor,116117	And,118	Or,119}120impl Display for BinaryOpType {121	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {122		use BinaryOpType::*;123		write!(124			f,125			"{}",126			match self {127				Mul => "*",128				Div => "/",129				Mod => "%",130				Add => "+",131				Sub => "-",132				Lhs => "<<",133				Rhs => ">>",134				Lt => "<",135				Gt => ">",136				Lte => "<=",137				Gte => ">=",138				BitAnd => "&",139				BitOr => "|",140				BitXor => "^",141				And => "&&",142				Or => "||",143			}144		)145	}146}147148/// name, default value149#[cfg_attr(feature = "dump", derive(Codegen))]150#[cfg_attr(feature = "serialize", derive(Serialize))]151#[cfg_attr(feature = "deserialize", derive(Deserialize))]152#[derive(Debug, PartialEq)]153pub struct Param(pub Rc<str>, pub Option<LocExpr>);154155/// Defined function parameters156#[cfg_attr(feature = "dump", derive(Codegen))]157#[cfg_attr(feature = "serialize", derive(Serialize))]158#[cfg_attr(feature = "deserialize", derive(Deserialize))]159#[derive(Debug, Clone, PartialEq)]160pub struct ParamsDesc(pub Rc<Vec<Param>>);161impl Deref for ParamsDesc {162	type Target = Vec<Param>;163	fn deref(&self) -> &Self::Target {164		&self.0165	}166}167168#[cfg_attr(feature = "dump", derive(Codegen))]169#[cfg_attr(feature = "serialize", derive(Serialize))]170#[cfg_attr(feature = "deserialize", derive(Deserialize))]171#[derive(Debug, PartialEq)]172pub struct Arg(pub Option<String>, pub LocExpr);173174#[cfg_attr(feature = "dump", derive(Codegen))]175#[cfg_attr(feature = "serialize", derive(Serialize))]176#[cfg_attr(feature = "deserialize", derive(Deserialize))]177#[derive(Debug, PartialEq)]178pub struct ArgsDesc(pub Vec<Arg>);179impl Deref for ArgsDesc {180	type Target = Vec<Arg>;181	fn deref(&self) -> &Self::Target {182		&self.0183	}184}185186#[cfg_attr(feature = "dump", derive(Codegen))]187#[cfg_attr(feature = "serialize", derive(Serialize))]188#[cfg_attr(feature = "deserialize", derive(Deserialize))]189#[derive(Debug, Clone, PartialEq)]190pub struct BindSpec {191	pub name: Rc<str>,192	pub params: Option<ParamsDesc>,193	pub value: LocExpr,194}195196#[cfg_attr(feature = "dump", derive(Codegen))]197#[cfg_attr(feature = "serialize", derive(Serialize))]198#[cfg_attr(feature = "deserialize", derive(Deserialize))]199#[derive(Debug, PartialEq)]200pub struct IfSpecData(pub LocExpr);201202#[cfg_attr(feature = "dump", derive(Codegen))]203#[cfg_attr(feature = "serialize", derive(Serialize))]204#[cfg_attr(feature = "deserialize", derive(Deserialize))]205#[derive(Debug, PartialEq)]206pub struct ForSpecData(pub Rc<str>, pub LocExpr);207208#[cfg_attr(feature = "dump", derive(Codegen))]209#[cfg_attr(feature = "serialize", derive(Serialize))]210#[cfg_attr(feature = "deserialize", derive(Deserialize))]211#[derive(Debug, PartialEq)]212pub enum CompSpec {213	IfSpec(IfSpecData),214	ForSpec(ForSpecData),215}216217#[cfg_attr(feature = "dump", derive(Codegen))]218#[cfg_attr(feature = "serialize", derive(Serialize))]219#[cfg_attr(feature = "deserialize", derive(Deserialize))]220#[derive(Debug, PartialEq)]221pub struct ObjComp {222	pub pre_locals: Vec<BindSpec>,223	pub key: LocExpr,224	pub value: LocExpr,225	pub post_locals: Vec<BindSpec>,226	pub compspecs: Vec<CompSpec>,227}228229#[cfg_attr(feature = "dump", derive(Codegen))]230#[cfg_attr(feature = "serialize", derive(Serialize))]231#[cfg_attr(feature = "deserialize", derive(Deserialize))]232#[derive(Debug, PartialEq)]233pub enum ObjBody {234	MemberList(Vec<Member>),235	ObjComp(ObjComp),236}237238#[cfg_attr(feature = "dump", derive(Codegen))]239#[cfg_attr(feature = "serialize", derive(Serialize))]240#[cfg_attr(feature = "deserialize", derive(Deserialize))]241#[derive(Debug, PartialEq, Clone, Copy)]242pub enum LiteralType {243	This,244	Super,245	Dollar,246	Null,247	True,248	False,249}250251#[derive(Debug, PartialEq)]252pub struct SliceDesc {253	pub start: Option<LocExpr>,254	pub end: Option<LocExpr>,255	pub step: Option<LocExpr>,256}257258/// Syntax base259#[cfg_attr(feature = "dump", derive(Codegen))]260#[cfg_attr(feature = "serialize", derive(Serialize))]261#[cfg_attr(feature = "deserialize", derive(Deserialize))]262#[derive(Debug, PartialEq)]263pub enum Expr {264	Literal(LiteralType),265266	/// String value: "hello"267	Str(Rc<str>),268	/// Number: 1, 2.0, 2e+20269	Num(f64),270	/// Variable name: test271	Var(Rc<str>),272273	/// Array of expressions: [1, 2, "Hello"]274	Arr(Vec<LocExpr>),275	/// Array comprehension:276	/// ```jsonnet277	///  ingredients: [278	///    { kind: kind, qty: 4 / 3 }279	///    for kind in [280	///      'Honey Syrup',281	///      'Lemon Juice',282	///      'Farmers Gin',283	///    ]284	///  ],285	/// ```286	ArrComp(LocExpr, Vec<CompSpec>),287288	/// Object: {a: 2}289	Obj(ObjBody),290	/// Object extension: var1 {b: 2}291	ObjExtend(LocExpr, ObjBody),292293	/// (obj)294	Parened(LocExpr),295296	/// -2297	UnaryOp(UnaryOpType, LocExpr),298	/// 2 - 2299	BinaryOp(LocExpr, BinaryOpType, LocExpr),300	/// assert 2 == 2 : "Math is broken"301	AssertExpr(AssertStmt, LocExpr),302	/// local a = 2; { b: a }303	LocalExpr(Vec<BindSpec>, LocExpr),304305	/// import "hello"306	Import(PathBuf),307	/// importStr "file.txt"308	ImportStr(PathBuf),309	/// error "I'm broken"310	ErrorStmt(LocExpr),311	/// a(b, c)312	Apply(LocExpr, ArgsDesc, bool),313	/// a[b]314	Index(LocExpr, LocExpr),315	/// function(x) x316	Function(ParamsDesc, LocExpr),317	/// std.primitiveEquals318	Intrinsic(Rc<str>),319	/// if true == false then 1 else 2320	IfElse {321		cond: IfSpecData,322		cond_then: LocExpr,323		cond_else: Option<LocExpr>,324	},325}326327/// file, begin offset, end offset328#[cfg_attr(feature = "dump", derive(Codegen))]329#[cfg_attr(feature = "serialize", derive(Serialize))]330#[cfg_attr(feature = "deserialize", derive(Deserialize))]331#[derive(Clone, PartialEq)]332pub struct ExprLocation(pub Rc<PathBuf>, pub usize, pub usize);333impl Debug for ExprLocation {334	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {335		write!(f, "{:?}:{:?}-{:?}", self.0, self.1, self.2)336	}337}338339/// Holds AST expression and its location in source file340#[cfg_attr(feature = "dump", derive(Codegen))]341#[cfg_attr(feature = "serialize", derive(Serialize))]342#[cfg_attr(feature = "deserialize", derive(Deserialize))]343#[derive(Clone, PartialEq)]344pub struct LocExpr(pub Rc<Expr>, pub Option<ExprLocation>);345impl Debug for LocExpr {346	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {347		write!(f, "{:?} from {:?}", self.0, self.1)348	}349}350351/// Creates LocExpr from Expr and ExprLocation components352#[macro_export]353macro_rules! loc_expr {354	($expr:expr, $need_loc:expr,($name:expr, $start:expr, $end:expr)) => {355		LocExpr(356			std::rc::Rc::new($expr),357			if $need_loc {358				Some(ExprLocation($name, $start, $end))359			} else {360				None361				},362			)363	};364}365366/// Creates LocExpr without location info367#[macro_export]368macro_rules! loc_expr_todo {369	($expr:expr) => {370		LocExpr(Rc::new($expr), None)371	};372}