difftreelog
Merge pull request #19 from CertainLach/std-intrinsic
in: master
Prevent changing meaning of std in desugared expressions
7 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
@@ -20,13 +20,12 @@
pub fn call_builtin(
context: Context,
loc: &Option<ExprLocation>,
- ns: &str,
name: &str,
args: &ArgsDesc,
) -> Result<Val> {
- Ok(match (ns, name as &str) {
+ Ok(match name as &str {
// arr/string/function
- ("std", "length") => parse_args!(context, "std.length", args, 1, [
+ "length" => parse_args!(context, "std.length", args, 1, [
0, x: [Val::Str|Val::Arr|Val::Obj], vec![ValType::Str, ValType::Arr, ValType::Obj];
], {
Ok(match x {
@@ -42,13 +41,13 @@
})
})?,
// any
- ("std", "type") => parse_args!(context, "std.type", args, 1, [
+ "type" => parse_args!(context, "std.type", args, 1, [
0, x, vec![];
], {
Ok(Val::Str(x.value_type()?.name().into()))
})?,
// length, idx=>any
- ("std", "makeArray") => parse_args!(context, "std.makeArray", args, 2, [
+ "makeArray" => parse_args!(context, "std.makeArray", args, 2, [
0, sz: [Val::Num]!!Val::Num, vec![ValType::Num];
1, func: [Val::Func]!!Val::Func, vec![ValType::Func];
], {
@@ -65,7 +64,7 @@
Ok(Val::Arr(Rc::new(out)))
})?,
// string
- ("std", "codepoint") => parse_args!(context, "std.codepoint", args, 1, [
+ "codepoint" => parse_args!(context, "std.codepoint", args, 1, [
0, str: [Val::Str]!!Val::Str, vec![ValType::Str];
], {
assert!(
@@ -75,7 +74,7 @@
Ok(Val::Num(str.chars().take(1).next().unwrap() as u32 as f64))
})?,
// object, includeHidden
- ("std", "objectFieldsEx") => parse_args!(context, "std.objectFieldsEx",args, 2, [
+ "objectFieldsEx" => parse_args!(context, "std.objectFieldsEx",args, 2, [
0, obj: [Val::Obj]!!Val::Obj, vec![ValType::Obj];
1, inc_hidden: [Val::Bool]!!Val::Bool, vec![ValType::Bool];
], {
@@ -88,7 +87,7 @@
Ok(Val::Arr(Rc::new(out.into_iter().map(Val::Str).collect())))
})?,
// object, field, includeHidden
- ("std", "objectHasEx") => parse_args!(context, "std.objectHasEx", args, 3, [
+ "objectHasEx" => parse_args!(context, "std.objectHasEx", args, 3, [
0, obj: [Val::Obj]!!Val::Obj, vec![ValType::Obj];
1, f: [Val::Str]!!Val::Str, vec![ValType::Str];
2, inc_hidden: [Val::Bool]!!Val::Bool, vec![ValType::Bool];
@@ -100,36 +99,36 @@
.any(|(k, _v)| *k == *f),
))
})?,
- ("std", "primitiveEquals") => parse_args!(context, "std.primitiveEquals", args, 2, [
+ "primitiveEquals" => parse_args!(context, "std.primitiveEquals", args, 2, [
0, a, vec![];
1, b, vec![];
], {
Ok(Val::Bool(primitive_equals(&a, &b)?))
})?,
// faster
- ("std", "equals") => parse_args!(context, "std.equals", args, 2, [
+ "equals" => parse_args!(context, "std.equals", args, 2, [
0, a, vec![];
1, b, vec![];
], {
Ok(Val::Bool(equals(&a, &b)?))
})?,
- ("std", "modulo") => parse_args!(context, "std.modulo", args, 2, [
+ "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];
], {
Ok(Val::Num(a % b))
})?,
- ("std", "floor") => parse_args!(context, "std.floor", args, 1, [
+ "floor" => parse_args!(context, "std.floor", args, 1, [
0, x: [Val::Num]!!Val::Num, vec![ValType::Num];
], {
Ok(Val::Num(x.floor()))
})?,
- ("std", "log") => parse_args!(context, "std.log", args, 2, [
+ "log" => parse_args!(context, "std.log", args, 2, [
0, n: [Val::Num]!!Val::Num, vec![ValType::Num];
], {
Ok(Val::Num(n.ln()))
})?,
- ("std", "trace") => parse_args!(context, "std.trace", args, 2, [
+ "trace" => parse_args!(context, "std.trace", args, 2, [
0, str: [Val::Str]!!Val::Str, vec![ValType::Str];
1, rest, vec![];
], {
@@ -143,27 +142,27 @@
eprintln!(" {}", str);
Ok(rest)
})?,
- ("std", "pow") => parse_args!(context, "std.modulo", args, 2, [
+ "pow" => parse_args!(context, "std.modulo", args, 2, [
0, x: [Val::Num]!!Val::Num, vec![ValType::Num];
1, n: [Val::Num]!!Val::Num, vec![ValType::Num];
], {
Ok(Val::Num(x.powf(n)))
})?,
- ("std", "extVar") => parse_args!(context, "std.extVar", args, 1, [
+ "extVar" => parse_args!(context, "std.extVar", args, 1, [
0, x: [Val::Str]!!Val::Str, vec![ValType::Str];
], {
Ok(with_state(|s| s.settings().ext_vars.get(&x).cloned()).ok_or_else(
|| UndefinedExternalVariable(x),
)?)
})?,
- ("std", "native") => parse_args!(context, "std.native", args, 1, [
+ "native" => parse_args!(context, "std.native", args, 1, [
0, x: [Val::Str]!!Val::Str, vec![ValType::Str];
], {
Ok(with_state(|s| s.settings().ext_natives.get(&x).cloned()).map(|v| Val::Func(Rc::new(FuncVal::NativeExt(x.clone(), v)))).ok_or_else(
|| UndefinedExternalFunction(x),
)?)
})?,
- ("std", "filter") => parse_args!(context, "std.filter", args, 2, [
+ "filter" => parse_args!(context, "std.filter", args, 2, [
0, func: [Val::Func]!!Val::Func, vec![ValType::Func];
1, arr: [Val::Arr]!!Val::Arr, vec![ValType::Arr];
], {
@@ -181,7 +180,7 @@
)))
})?,
// faster
- ("std", "foldl") => parse_args!(context, "std.foldl", args, 3, [
+ "foldl" => parse_args!(context, "std.foldl", args, 3, [
0, func: [Val::Func]!!Val::Func, vec![ValType::Func];
1, arr: [Val::Arr]!!Val::Arr, vec![ValType::Arr];
2, init, vec![];
@@ -193,7 +192,7 @@
Ok(acc)
})?,
// faster
- ("std", "foldr") => parse_args!(context, "std.foldr", args, 3, [
+ "foldr" => parse_args!(context, "std.foldr", args, 3, [
0, func: [Val::Func]!!Val::Func, vec![ValType::Func];
1, arr: [Val::Arr]!!Val::Arr, vec![ValType::Arr];
2, init, vec![];
@@ -206,7 +205,7 @@
})?,
// faster
#[allow(non_snake_case)]
- ("std", "sortImpl") => parse_args!(context, "std.sort", args, 2, [
+ "sortImpl" => parse_args!(context, "std.sort", args, 2, [
0, arr: [Val::Arr]!!Val::Arr, vec![ValType::Arr];
1, keyF: [Val::Func]!!Val::Func, vec![ValType::Func];
], {
@@ -216,7 +215,7 @@
Ok(Val::Arr(sort::sort(context, arr, &keyF)?))
})?,
// faster
- ("std", "format") => parse_args!(context, "std.format", args, 2, [
+ "format" => parse_args!(context, "std.format", args, 2, [
0, str: [Val::Str]!!Val::Str, vec![ValType::Str];
1, vals, vec![]
], {
@@ -229,7 +228,7 @@
})
})?,
// faster
- ("std", "range") => parse_args!(context, "std.range", args, 2, [
+ "range" => parse_args!(context, "std.range", args, 2, [
0, from: [Val::Num]!!Val::Num, vec![ValType::Num];
1, to: [Val::Num]!!Val::Num, vec![ValType::Num];
], {
@@ -239,7 +238,7 @@
}
Ok(Val::Arr(Rc::new(out)))
})?,
- ("std", "char") => parse_args!(context, "std.char", args, 1, [
+ "char" => parse_args!(context, "std.char", args, 1, [
0, n: [Val::Num]!!Val::Num, vec![ValType::Num];
], {
let mut out = String::new();
@@ -248,18 +247,18 @@
)?);
Ok(Val::Str(out.into()))
})?,
- ("std", "encodeUTF8") => parse_args!(context, "std.encodeUtf8", args, 1, [
+ "encodeUTF8" => parse_args!(context, "std.encodeUtf8", args, 1, [
0, str: [Val::Str]!!Val::Str, vec![ValType::Str];
], {
Ok(Val::Arr(Rc::new(str.bytes().map(|b| Val::Num(b as f64)).collect())))
})?,
- ("std", "md5") => parse_args!(context, "std.md5", args, 1, [
+ "md5" => parse_args!(context, "std.md5", args, 1, [
0, str: [Val::Str]!!Val::Str, vec![ValType::Str];
], {
Ok(Val::Str(format!("{:x}", md5::compute(&str.as_bytes())).into()))
})?,
// faster
- ("std", "base64") => parse_args!(context, "std.base64", args, 1, [
+ "base64" => parse_args!(context, "std.base64", args, 1, [
0, input: [Val::Str | Val::Arr], vec![ValType::Arr, ValType::Str];
], {
Ok(Val::Str(match input {
@@ -275,7 +274,7 @@
}))
})?,
// faster
- ("std", "join") => parse_args!(context, "std.join", args, 2, [
+ "join" => parse_args!(context, "std.join", args, 2, [
0, sep: [Val::Str|Val::Arr], vec![ValType::Str, ValType::Arr];
1, arr: [Val::Arr]!!Val::Arr, vec![ValType::Arr];
], {
@@ -322,13 +321,13 @@
})
})?,
// Faster
- ("std", "escapeStringJson") => parse_args!(context, "std.escapeStringJson", args, 1, [
+ "escapeStringJson" => parse_args!(context, "std.escapeStringJson", args, 1, [
0, str_: [Val::Str]!!Val::Str, vec![ValType::Str];
], {
Ok(Val::Str(escape_string_json(&str_).into()))
})?,
// Faster
- ("std", "manifestJsonEx") => parse_args!(context, "std.manifestJsonEx", args, 2, [
+ "manifestJsonEx" => parse_args!(context, "std.manifestJsonEx", args, 2, [
0, value, vec![];
1, indent: [Val::Str]!!Val::Str, vec![ValType::Str];
], {
@@ -338,18 +337,18 @@
})?.into()))
})?,
// Faster
- ("std", "reverse") => parse_args!(context, "std.reverse", args, 1, [
+ "reverse" => parse_args!(context, "std.reverse", args, 1, [
0, arr: [Val::Arr]!!Val::Arr, vec![ValType::Arr];
], {
let mut marr = arr;
Rc::make_mut(&mut marr).reverse();
Ok(Val::Arr(marr))
})?,
- ("std", "id") => parse_args!(context, "std.id", args, 1, [
+ "id" => parse_args!(context, "std.id", args, 1, [
0, v, vec![];
], {
Ok(v)
})?,
- (ns, name) => throw!(IntrinsicNotFound(ns.into(), name.into())),
+ name => throw!(IntrinsicNotFound(name.into())),
})
}
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -8,8 +8,8 @@
#[derive(Error, Debug, Clone)]
pub enum Error {
- #[error("intrinsic not found: {0}.{1}")]
- IntrinsicNotFound(Rc<str>, Rc<str>),
+ #[error("intrinsic not found: {0}")]
+ IntrinsicNotFound(Rc<str>),
#[error("argument reordering in intrisics not supported yet")]
IntrinsicArgumentReorderingIsNotSupportedYet,
crates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate.rs
@@ -466,10 +466,8 @@
|| {
if let Some(v) = v.get(s.clone())? {
Ok(v.unwrap_if_lazy()?)
- } else if let Some(Val::Str(n)) =
- v.get("__intrinsic_namespace__".into())?
- {
- Ok(Val::Func(Rc::new(FuncVal::Intrinsic(n, s))))
+ } else if v.get("__intrinsic_namespace__".into())?.is_some() {
+ Ok(Val::Func(Rc::new(FuncVal::Intrinsic(s))))
} else {
throw!(NoSuchField(s))
}
@@ -558,6 +556,7 @@
Function(params, body) => {
evaluate_method(context, "anonymous".into(), params.clone(), body.clone())
}
+ Intrinsic(name) => Val::Func(Rc::new(FuncVal::Intrinsic(name.clone()))),
AssertExpr(AssertStmt(value, msg), returned) => {
let assertion_result = push(
&value.1,
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -893,4 +893,12 @@
)?;
Ok(())
}
+
+ #[test]
+ fn constant_intrinsic() -> crate::error::Result<()> {
+ assert_eval!(
+ "local std2 = std; local std = std2 { primitiveEquals(a, b):: false }; 1 == 1"
+ );
+ Ok(())
+ }
}
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -76,7 +76,7 @@
/// Plain function implemented in jsonnet
Normal(FuncDesc),
/// Standard library function
- Intrinsic(Rc<str>, Rc<str>),
+ Intrinsic(Rc<str>),
/// Library functions implemented in native
NativeExt(Rc<str>, Rc<NativeCallback>),
}
@@ -85,7 +85,7 @@
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Normal(a), Self::Normal(b)) => a == b,
- (Self::Intrinsic(ans, an), Self::Intrinsic(bns, bn)) => ans == bns && an == bn,
+ (Self::Intrinsic(an), Self::Intrinsic(bn)) => an == bn,
(Self::NativeExt(an, _), Self::NativeExt(bn, _)) => an == bn,
(..) => false,
}
@@ -93,12 +93,12 @@
}
impl FuncVal {
pub fn is_ident(&self) -> bool {
- matches!(&self, Self::Intrinsic(ns, n) if ns as &str == "std" && n as &str == "id")
+ matches!(&self, Self::Intrinsic(n) if n as &str == "id")
}
pub fn name(&self) -> Rc<str> {
match self {
Self::Normal(normal) => normal.name.clone(),
- Self::Intrinsic(ns, name) => format!("intrinsic.{}.{}", ns, name).into(),
+ Self::Intrinsic(name) => format!("std.{}", name).into(),
Self::NativeExt(n, _) => format!("native.{}", n).into(),
}
}
@@ -120,7 +120,7 @@
)?;
evaluate(ctx, &func.body)
}
- Self::Intrinsic(ns, name) => call_builtin(call_ctx, loc, ns, name, args),
+ Self::Intrinsic(name) => call_builtin(call_ctx, loc, name, args),
Self::NativeExt(_name, handler) => {
let args = parse_function_call(call_ctx, None, &handler.params, args, true)?;
let mut out_args = Vec::with_capacity(handler.params.len());
@@ -149,7 +149,7 @@
)?;
evaluate(ctx, &func.body)
}
- Self::Intrinsic(_, _) => todo!(),
+ Self::Intrinsic(_) => todo!(),
Self::NativeExt(_, _) => todo!(),
}
}
@@ -160,7 +160,7 @@
let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;
evaluate(ctx, &func.body)
}
- Self::Intrinsic(_, _) => todo!(),
+ Self::Intrinsic(_) => todo!(),
Self::NativeExt(_, _) => todo!(),
}
}
crates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth1#[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 Add,101 Sub,102103 Lhs,104 Rhs,105106 Lt,107 Gt,108 Lte,109 Gte,110111 BitAnd,112 BitOr,113 BitXor,114115 And,116 Or,117}118impl Display for BinaryOpType {119 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {120 use BinaryOpType::*;121 write!(122 f,123 "{}",124 match self {125 Mul => "*",126 Div => "/",127 Add => "+",128 Sub => "-",129 Lhs => "<<",130 Rhs => ">>",131 Lt => "<",132 Gt => ">",133 Lte => "<=",134 Gte => ">=",135 BitAnd => "&",136 BitOr => "|",137 BitXor => "^",138 And => "&&",139 Or => "||",140 }141 )142 }143}144145/// name, default value146#[cfg_attr(feature = "dump", derive(Codegen))]147#[cfg_attr(feature = "serialize", derive(Serialize))]148#[cfg_attr(feature = "deserialize", derive(Deserialize))]149#[derive(Debug, PartialEq)]150pub struct Param(pub Rc<str>, pub Option<LocExpr>);151152/// Defined function parameters153#[cfg_attr(feature = "dump", derive(Codegen))]154#[cfg_attr(feature = "serialize", derive(Serialize))]155#[cfg_attr(feature = "deserialize", derive(Deserialize))]156#[derive(Debug, Clone, PartialEq)]157pub struct ParamsDesc(pub Rc<Vec<Param>>);158impl Deref for ParamsDesc {159 type Target = Vec<Param>;160 fn deref(&self) -> &Self::Target {161 &self.0162 }163}164165#[cfg_attr(feature = "dump", derive(Codegen))]166#[cfg_attr(feature = "serialize", derive(Serialize))]167#[cfg_attr(feature = "deserialize", derive(Deserialize))]168#[derive(Debug, PartialEq)]169pub struct Arg(pub Option<String>, pub LocExpr);170171#[cfg_attr(feature = "dump", derive(Codegen))]172#[cfg_attr(feature = "serialize", derive(Serialize))]173#[cfg_attr(feature = "deserialize", derive(Deserialize))]174#[derive(Debug, PartialEq)]175pub struct ArgsDesc(pub Vec<Arg>);176impl Deref for ArgsDesc {177 type Target = Vec<Arg>;178 fn deref(&self) -> &Self::Target {179 &self.0180 }181}182183#[cfg_attr(feature = "dump", derive(Codegen))]184#[cfg_attr(feature = "serialize", derive(Serialize))]185#[cfg_attr(feature = "deserialize", derive(Deserialize))]186#[derive(Debug, Clone, PartialEq)]187pub struct BindSpec {188 pub name: Rc<str>,189 pub params: Option<ParamsDesc>,190 pub value: LocExpr,191}192193#[cfg_attr(feature = "dump", derive(Codegen))]194#[cfg_attr(feature = "serialize", derive(Serialize))]195#[cfg_attr(feature = "deserialize", derive(Deserialize))]196#[derive(Debug, PartialEq)]197pub struct IfSpecData(pub LocExpr);198199#[cfg_attr(feature = "dump", derive(Codegen))]200#[cfg_attr(feature = "serialize", derive(Serialize))]201#[cfg_attr(feature = "deserialize", derive(Deserialize))]202#[derive(Debug, PartialEq)]203pub struct ForSpecData(pub Rc<str>, pub LocExpr);204205#[cfg_attr(feature = "dump", derive(Codegen))]206#[cfg_attr(feature = "serialize", derive(Serialize))]207#[cfg_attr(feature = "deserialize", derive(Deserialize))]208#[derive(Debug, PartialEq)]209pub enum CompSpec {210 IfSpec(IfSpecData),211 ForSpec(ForSpecData),212}213214#[cfg_attr(feature = "dump", derive(Codegen))]215#[cfg_attr(feature = "serialize", derive(Serialize))]216#[cfg_attr(feature = "deserialize", derive(Deserialize))]217#[derive(Debug, PartialEq)]218pub struct ObjComp {219 pub pre_locals: Vec<BindSpec>,220 pub key: LocExpr,221 pub value: LocExpr,222 pub post_locals: Vec<BindSpec>,223 pub compspecs: Vec<CompSpec>,224}225226#[cfg_attr(feature = "dump", derive(Codegen))]227#[cfg_attr(feature = "serialize", derive(Serialize))]228#[cfg_attr(feature = "deserialize", derive(Deserialize))]229#[derive(Debug, PartialEq)]230pub enum ObjBody {231 MemberList(Vec<Member>),232 ObjComp(ObjComp),233}234235#[cfg_attr(feature = "dump", derive(Codegen))]236#[cfg_attr(feature = "serialize", derive(Serialize))]237#[cfg_attr(feature = "deserialize", derive(Deserialize))]238#[derive(Debug, PartialEq, Clone, Copy)]239pub enum LiteralType {240 This,241 Super,242 Dollar,243 Null,244 True,245 False,246}247248#[derive(Debug, PartialEq)]249pub struct SliceDesc {250 pub start: Option<LocExpr>,251 pub end: Option<LocExpr>,252 pub step: Option<LocExpr>,253}254255/// Syntax base256#[cfg_attr(feature = "dump", derive(Codegen))]257#[cfg_attr(feature = "serialize", derive(Serialize))]258#[cfg_attr(feature = "deserialize", derive(Deserialize))]259#[derive(Debug, PartialEq)]260pub enum Expr {261 Literal(LiteralType),262263 /// String value: "hello"264 Str(Rc<str>),265 /// Number: 1, 2.0, 2e+20266 Num(f64),267 /// Variable name: test268 Var(Rc<str>),269270 /// Array of expressions: [1, 2, "Hello"]271 Arr(Vec<LocExpr>),272 /// Array comprehension:273 /// ```jsonnet274 /// ingredients: [275 /// { kind: kind, qty: 4 / 3 }276 /// for kind in [277 /// 'Honey Syrup',278 /// 'Lemon Juice',279 /// 'Farmers Gin',280 /// ]281 /// ],282 /// ```283 ArrComp(LocExpr, Vec<CompSpec>),284285 /// Object: {a: 2}286 Obj(ObjBody),287 /// Object extension: var1 {b: 2}288 ObjExtend(LocExpr, ObjBody),289290 /// (obj)291 Parened(LocExpr),292293 /// -2294 UnaryOp(UnaryOpType, LocExpr),295 /// 2 - 2296 BinaryOp(LocExpr, BinaryOpType, LocExpr),297 /// assert 2 == 2 : "Math is broken"298 AssertExpr(AssertStmt, LocExpr),299 /// local a = 2; { b: a }300 LocalExpr(Vec<BindSpec>, LocExpr),301302 /// import "hello"303 Import(PathBuf),304 /// importStr "file.txt"305 ImportStr(PathBuf),306 /// error "I'm broken"307 ErrorStmt(LocExpr),308 /// a(b, c)309 Apply(LocExpr, ArgsDesc, bool),310 /// a[b]311 Index(LocExpr, LocExpr),312 /// function(x) x313 Function(ParamsDesc, LocExpr),314 /// if true == false then 1 else 2315 IfElse {316 cond: IfSpecData,317 cond_then: LocExpr,318 cond_else: Option<LocExpr>,319 },320}321322/// file, begin offset, end offset323#[cfg_attr(feature = "dump", derive(Codegen))]324#[cfg_attr(feature = "serialize", derive(Serialize))]325#[cfg_attr(feature = "deserialize", derive(Deserialize))]326#[derive(Clone, PartialEq)]327pub struct ExprLocation(pub Rc<PathBuf>, pub usize, pub usize);328impl Debug for ExprLocation {329 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {330 write!(f, "{:?}:{:?}-{:?}", self.0, self.1, self.2)331 }332}333334/// Holds AST expression and its location in source file335#[cfg_attr(feature = "dump", derive(Codegen))]336#[cfg_attr(feature = "serialize", derive(Serialize))]337#[cfg_attr(feature = "deserialize", derive(Deserialize))]338#[derive(Clone, PartialEq)]339pub struct LocExpr(pub Rc<Expr>, pub Option<ExprLocation>);340impl Debug for LocExpr {341 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {342 write!(f, "{:?} from {:?}", self.0, self.1)343 }344}345346/// Creates LocExpr from Expr and ExprLocation components347#[macro_export]348macro_rules! loc_expr {349 ($expr:expr, $need_loc:expr,($name:expr, $start:expr, $end:expr)) => {350 LocExpr(351 std::rc::Rc::new($expr),352 if $need_loc {353 Some(ExprLocation($name, $start, $end))354 } else {355 None356 },357 )358 };359}360361/// Creates LocExpr without location info362#[macro_export]363macro_rules! loc_expr_todo {364 ($expr:expr) => {365 LocExpr(Rc::new($expr), None)366 };367}crates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/lib.rs
+++ b/crates/jrsonnet-parser/src/lib.rs
@@ -221,18 +221,12 @@
a:(@) _ "&" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::BitAnd, b))}
--
a:(@) _ "==" _ b:@ {loc_expr_todo!(Expr::Apply(
- el!(Expr::Index(
- el!(Expr::Var("std".into())),
- el!(Expr::Str("equals".into()))
- )),
+ el!(Expr::Intrinsic("equals".into())),
ArgsDesc(vec![Arg(None, a), Arg(None, b)]),
true
))}
a:(@) _ "!=" _ b:@ {loc_expr_todo!(Expr::UnaryOp(UnaryOpType::Not, el!(Expr::Apply(
- el!(Expr::Index(
- el!(Expr::Var("std".into())),
- el!(Expr::Str("equals".into()))
- )),
+ el!(Expr::Intrinsic("equals".into())),
ArgsDesc(vec![Arg(None, a), Arg(None, b)]),
true
))))}
@@ -242,10 +236,7 @@
a:(@) _ "<=" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Lte, b))}
a:(@) _ ">=" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Gte, b))}
a:(@) _ keyword("in") _ b:@ {loc_expr_todo!(Expr::Apply(
- el!(Expr::Index(
- el!(Expr::Var("std".into())),
- el!(Expr::Str("objectHasEx".into()))
- )), ArgsDesc(vec![Arg(None, b), Arg(None, a), Arg(None, el!(Expr::Literal(LiteralType::True)))]),
+ el!(Expr::Intrinsic("objectHasEx".into())), ArgsDesc(vec![Arg(None, b), Arg(None, a), Arg(None, el!(Expr::Literal(LiteralType::True)))]),
true
))}
--
@@ -258,10 +249,7 @@
a:(@) _ "*" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Mul, b))}
a:(@) _ "/" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Div, b))}
a:(@) _ "%" _ b:@ {loc_expr_todo!(Expr::Apply(
- el!(Expr::Index(
- el!(Expr::Var("std".into())),
- el!(Expr::Str("mod".into()))
- )), ArgsDesc(vec![Arg(None, a), Arg(None, b)]),
+ el!(Expr::Intrinsic("mod".into())), ArgsDesc(vec![Arg(None, a), Arg(None, b)]),
false
))}
--
@@ -270,10 +258,7 @@
"~" _ b:@ { loc_expr_todo!(Expr::UnaryOp(UnaryOpType::BitNot, b)) }
--
a:(@) _ "[" _ s:slice_desc(s) _ "]" {loc_expr_todo!(Expr::Apply(
- el!(Expr::Index(
- el!(Expr::Var("std".into())),
- el!(Expr::Str("slice".into())),
- )),
+ el!(Expr::Intrinsic("slice".into())),
ArgsDesc(vec![
Arg(None, a),
Arg(None, s.start.unwrap_or_else(||el!(Expr::Literal(LiteralType::Null)))),