difftreelog
feat convert ParamName into enum
in: master
10 files changed
crates/jrsonnet-evaluator/src/evaluate/destructure.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
@@ -5,7 +5,7 @@
use crate::{
bail,
error::{ErrorKind::*, Result},
- evaluate, evaluate_method, evaluate_named, Context, Pending, Thunk, Val,
+ evaluate_method, evaluate_named_param, Context, Pending, Thunk, Val,
};
#[allow(clippy::too_many_lines)]
@@ -170,10 +170,7 @@
let value = value.clone();
let data = {
let fctx = fctx.clone();
- Thunk!(move || name.0.map_or_else(
- || evaluate(fctx.unwrap(), &value),
- |name| evaluate_named(fctx.unwrap(), &value, name),
- ))
+ Thunk!(move || evaluate_named_param(fctx.unwrap(), &value, name))
};
destruct(into, data, fctx, new_bindings)?;
}
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -380,9 +380,9 @@
}
pub fn evaluate_named_param(ctx: Context, expr: &Spanned<Expr>, name: ParamName) -> Result<Val> {
- match name.0 {
- Some(name) => evaluate_named(ctx, expr, name),
- None => evaluate(ctx, expr),
+ match name {
+ ParamName::Named(name) => evaluate_named(ctx, expr, name),
+ ParamName::Unnamed => evaluate(ctx, expr),
}
}
crates/jrsonnet-evaluator/src/function/builtin.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/builtin.rs
+++ b/crates/jrsonnet-evaluator/src/function/builtin.rs
@@ -1,8 +1,6 @@
use std::any::Any;
-use std::fmt;
-use jrsonnet_gcmodule::{cc_dyn, Acyclic, Trace, TraceBox};
-use jrsonnet_interner::IStr;
+use jrsonnet_gcmodule::{cc_dyn, Trace, TraceBox};
use jrsonnet_parser::function::{FunctionSignature, ParamDefault, ParamName, ParamParse};
use super::{arglike::ArgsLike, parse::parse_builtin_call, CallLocation};
@@ -10,8 +8,8 @@
#[macro_export]
macro_rules! params {
- (@name unnamed) => { ParamName::ANONYMOUS };
- (@name named $name:literal) => { ParamName::new($crate::IStr::from($name)) };
+ (@name unnamed) => { ParamName::Unnamed };
+ (@name named $name:literal) => { ParamName::Named($crate::IStr::from($name)) };
($($(#[$meta:meta])* [$kind:ident $(($lit:literal))? => $default:expr]),* $(,)?) => {
thread_local! {
static PARAMS: FunctionSignature = FunctionSignature::new([
@@ -79,7 +77,7 @@
params: FunctionSignature::new(
params
.into_iter()
- .map(|n| ParamParse::new(ParamName::new(n.into()), ParamDefault::None))
+ .map(|n| ParamParse::new(ParamName::Named(n.into()), ParamDefault::None))
.collect(),
),
handler: TraceBox(Box::new(handler)),
@@ -88,7 +86,7 @@
}
impl Builtin for NativeCallback {
- fn name(&self) -> &str {
+ fn name(&self) -> &'static str {
// TODO: standard natives gets their names from definition
// But builitins should already have them
"<native>"
crates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -14,8 +14,8 @@
parse::{parse_default_function_call, parse_function_call},
};
use crate::{
- bail, error::ErrorKind::*, evaluate, evaluate_trivial, function::builtin::BuiltinFunc, params,
- Context, ContextBuilder, Result, Thunk, Val,
+ bail, error::ErrorKind::*, evaluate, evaluate_trivial, function::builtin::BuiltinFunc, Context,
+ ContextBuilder, Result, Thunk, Val,
};
pub mod arglike;
crates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/parse.rs
+++ b/crates/jrsonnet-evaluator/src/function/parse.rs
@@ -1,7 +1,9 @@
use std::mem::replace;
-use jrsonnet_interner::IStr;
-use jrsonnet_parser::{function::FunctionSignature, ExprParams};
+use jrsonnet_parser::{
+ function::{FunctionSignature, ParamName},
+ ExprParams,
+};
use rustc_hash::FxHashMap;
use super::arglike::ArgsLike;
@@ -9,7 +11,7 @@
bail,
destructure::destruct,
error::{ErrorKind::*, Result},
- evaluate_named, evaluate_named_param,
+ evaluate_named_param,
gc::WithCapacityExt as _,
Context, Pending, Thunk, Val,
};
@@ -76,7 +78,7 @@
.enumerate()
.filter_map(|(i, p)| Some((i, &p.destruct, p.default.as_ref()?)))
{
- if let Some(name) = into.name().0 {
+ if let ParamName::Named(name) = into.name() {
if passed_args.contains_key(&name) {
continue;
}
crates/jrsonnet-evaluator/src/function/prepared.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/prepared.rs
+++ b/crates/jrsonnet-evaluator/src/function/prepared.rs
@@ -4,9 +4,8 @@
use crate::destructure::destruct;
use crate::gc::WithCapacityExt;
-use crate::val::ThunkValue as _;
use crate::{bail, error::ErrorKind::*, Result};
-use crate::{evaluate_named, evaluate_named_param, Context, ContextBuilder, Pending, Thunk, Val};
+use crate::{evaluate_named_param, Context, ContextBuilder, Pending, Thunk, Val};
pub struct PreparedCall {
// Param, named input.
crates/jrsonnet-interner/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-interner/src/lib.rs
+++ b/crates/jrsonnet-interner/src/lib.rs
@@ -31,6 +31,10 @@
false
}
}
+
+/// SAFETY:
+///
+/// `IStr` is acyclic
unsafe impl Acyclic for IStr {}
impl IStr {
crates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth1use std::{2 fmt::{self, Debug, Display},3 ops::Deref,4 rc::Rc,5};67use jrsonnet_gcmodule::Acyclic;8use jrsonnet_interner::IStr;910use crate::{11 function::{FunctionSignature, ParamDefault, ParamName, ParamParse},12 source::Source,13};1415#[derive(Debug, PartialEq, Acyclic)]16pub enum FieldName {17 /// {fixed: 2}18 Fixed(IStr),19 /// {["dyn"+"amic"]: 3}20 Dyn(Spanned<Expr>),21}2223#[derive(Debug, Clone, Copy, PartialEq, Eq, Acyclic)]24#[repr(u8)]25pub enum Visibility {26 /// :27 Normal,28 /// ::29 Hidden,30 /// :::31 Unhide,32}3334impl Visibility {35 pub fn is_visible(&self) -> bool {36 matches!(self, Self::Normal | Self::Unhide)37 }38}3940#[derive(Debug, PartialEq, Acyclic)]41pub struct AssertStmt(pub Spanned<Expr>, pub Option<Spanned<Expr>>);4243#[derive(Debug, PartialEq, Acyclic)]44pub struct FieldMember {45 pub name: FieldName,46 pub plus: bool,47 pub params: Option<ExprParams>,48 pub visibility: Visibility,49 pub value: Rc<Spanned<Expr>>,50}5152#[derive(Debug, PartialEq, Acyclic)]53pub(crate) enum Member {54 Field(FieldMember),55 BindStmt(BindSpec),56 AssertStmt(AssertStmt),57}5859#[derive(Debug, Clone, Copy, PartialEq, Eq, Acyclic)]60pub enum UnaryOpType {61 Plus,62 Minus,63 BitNot,64 Not,65}6667impl Display for UnaryOpType {68 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {69 use UnaryOpType::*;70 write!(71 f,72 "{}",73 match self {74 Plus => "+",75 Minus => "-",76 BitNot => "~",77 Not => "!",78 }79 )80 }81}8283#[derive(Debug, Clone, Copy, PartialEq, Eq, Acyclic)]84pub enum BinaryOpType {85 Mul,86 Div,8788 /// Implemented as intrinsic, put here for completeness89 Mod,9091 Add,92 Sub,9394 Lhs,95 Rhs,9697 Lt,98 Gt,99 Lte,100 Gte,101102 BitAnd,103 BitOr,104 BitXor,105106 Eq,107 Neq,108109 And,110 Or,111 #[cfg(feature = "exp-null-coaelse")]112 NullCoaelse,113114 // Equialent to std.objectHasEx(a, b, true)115 In,116}117118impl Display for BinaryOpType {119 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {120 use BinaryOpType::*;121 write!(122 f,123 "{}",124 match self {125 Mul => "*",126 Div => "/",127 Mod => "%",128 Add => "+",129 Sub => "-",130 Lhs => "<<",131 Rhs => ">>",132 Lt => "<",133 Gt => ">",134 Lte => "<=",135 Gte => ">=",136 BitAnd => "&",137 BitOr => "|",138 BitXor => "^",139 Eq => "==",140 Neq => "!=",141 And => "&&",142 Or => "||",143 In => "in",144 #[cfg(feature = "exp-null-coaelse")]145 NullCoaelse => "??",146 }147 )148 }149}150151/// name, default value152#[derive(Debug, PartialEq, Acyclic)]153pub struct ExprParam {154 pub destruct: Destruct,155 pub default: Option<Rc<Spanned<Expr>>>,156}157158/// Defined function parameters159#[derive(Debug, Clone, PartialEq, Acyclic)]160pub struct ExprParams {161 pub exprs: Rc<Vec<ExprParam>>,162 pub signature: FunctionSignature,163 binds_len: usize,164}165impl ExprParams {166 pub fn len(&self) -> usize {167 self.exprs.len()168 }169 pub fn binds_len(&self) -> usize {170 self.binds_len171 }172 pub fn new(exprs: Vec<ExprParam>) -> Self {173 Self {174 signature: FunctionSignature::new(175 exprs176 .iter()177 .map(|p| {178 ParamParse::new(179 p.destruct.name(),180 ParamDefault::exists(p.default.is_some()),181 )182 })183 .collect(),184 ),185 binds_len: exprs.iter().map(|v| v.destruct.binds_len()).sum(),186 exprs: Rc::new(exprs),187 }188 }189}190191#[derive(Debug, PartialEq, Acyclic)]192pub struct ArgsDesc {193 pub unnamed: Vec<Rc<Spanned<Expr>>>,194 pub named: Vec<(IStr, Rc<Spanned<Expr>>)>,195}196impl ArgsDesc {197 pub fn new(unnamed: Vec<Rc<Spanned<Expr>>>, named: Vec<(IStr, Rc<Spanned<Expr>>)>) -> Self {198 Self { unnamed, named }199 }200}201202#[derive(Debug, Clone, PartialEq, Eq, Acyclic)]203pub enum DestructRest {204 /// ...rest205 Keep(IStr),206 /// ...207 Drop,208}209210#[derive(Debug, Clone, PartialEq, Acyclic)]211pub enum Destruct {212 Full(IStr),213 #[cfg(feature = "exp-destruct")]214 Skip,215 #[cfg(feature = "exp-destruct")]216 Array {217 start: Vec<Destruct>,218 rest: Option<DestructRest>,219 end: Vec<Destruct>,220 },221 #[cfg(feature = "exp-destruct")]222 Object {223 fields: Vec<(IStr, Option<Destruct>, Option<Spanned<Expr>>)>,224 rest: Option<DestructRest>,225 },226}227impl Destruct {228 /// Name of destructure, used for function parameter names229 pub fn name(&self) -> ParamName {230 ParamName(match self {231 Self::Full(name) => Some(name.clone()),232 #[cfg(feature = "exp-destruct")]233 _ => None,234 })235 }236 pub fn binds_len(&self) -> usize {237 #[cfg(feature = "exp-destruct")]238 fn cap_rest(rest: &Option<DestructRest>) -> usize {239 match rest {240 Some(DestructRest::Keep(_)) => 1,241 Some(DestructRest::Drop) => 0,242 None => 0,243 }244 }245 match self {246 Self::Full(_) => 1,247 #[cfg(feature = "exp-destruct")]248 Self::Skip => 0,249 #[cfg(feature = "exp-destruct")]250 Self::Array { start, rest, end } => {251 start.iter().map(Destruct::binds_len).sum::<usize>()252 + end.iter().map(Destruct::binds_len).sum::<usize>()253 + cap_rest(rest)254 }255 #[cfg(feature = "exp-destruct")]256 Self::Object { fields, rest } => {257 let mut out = 0;258 for (_, into, _) in fields {259 match into {260 Some(v) => out += v.capacity_hint(),261 // Field is destructured to default name262 None => out += 1,263 }264 }265 out + cap_rest(rest)266 }267 }268 }269}270271#[derive(Debug, PartialEq, Acyclic)]272pub enum BindSpec {273 Field {274 into: Destruct,275 value: Rc<Spanned<Expr>>,276 },277 Function {278 name: IStr,279 params: ExprParams,280 value: Rc<Spanned<Expr>>,281 },282}283impl BindSpec {284 pub fn binds_len(&self) -> usize {285 match self {286 BindSpec::Field { into, .. } => into.binds_len(),287 BindSpec::Function { .. } => 1,288 }289 }290}291292#[derive(Debug, PartialEq, Acyclic)]293pub struct IfSpecData(pub Spanned<Expr>);294295#[derive(Debug, PartialEq, Acyclic)]296pub struct ForSpecData(pub Destruct, pub Spanned<Expr>);297298#[derive(Debug, PartialEq, Acyclic)]299pub enum CompSpec {300 IfSpec(IfSpecData),301 ForSpec(ForSpecData),302}303304#[derive(Debug, PartialEq, Acyclic)]305pub struct ObjComp {306 pub locals: Rc<Vec<BindSpec>>,307 pub field: Rc<FieldMember>,308 pub compspecs: Vec<CompSpec>,309}310311#[derive(Debug, PartialEq, Acyclic)]312pub struct ObjMembers {313 pub locals: Rc<Vec<BindSpec>>,314 pub asserts: Rc<Vec<AssertStmt>>,315 pub fields: Vec<FieldMember>,316}317318#[derive(Debug, PartialEq, Acyclic)]319pub enum ObjBody {320 MemberList(ObjMembers),321 ObjComp(ObjComp),322}323324#[derive(Debug, PartialEq, Eq, Clone, Copy, Acyclic)]325pub enum LiteralType {326 This,327 Super,328 Dollar,329 Null,330 True,331 False,332}333334#[derive(Debug, PartialEq, Acyclic)]335pub struct SliceDesc {336 pub start: Option<Spanned<Expr>>,337 pub end: Option<Spanned<Expr>>,338 pub step: Option<Spanned<Expr>>,339}340341#[derive(Debug, PartialEq, Acyclic)]342pub struct AssertExpr {343 pub assert: AssertStmt,344 pub rest: Spanned<Expr>,345}346347#[derive(Debug, PartialEq, Acyclic)]348pub struct BinaryOp {349 pub lhs: Spanned<Expr>,350 pub op: BinaryOpType,351 pub rhs: Spanned<Expr>,352}353354#[derive(Debug, PartialEq, Acyclic)]355pub enum ImportKind {356 Normal,357 Str,358 Bin,359}360361#[derive(Debug, PartialEq, Acyclic)]362pub struct IfElse {363 pub cond: IfSpecData,364 pub cond_then: Spanned<Expr>,365 pub cond_else: Option<Spanned<Expr>>,366}367368#[derive(Debug, PartialEq, Acyclic)]369pub struct Slice {370 pub value: Spanned<Expr>,371 pub slice: SliceDesc,372}373374/// Syntax base375#[derive(Debug, PartialEq, Acyclic)]376pub enum Expr {377 Literal(LiteralType),378379 /// String value: "hello"380 Str(IStr),381 /// Number: 1, 2.0, 2e+20382 Num(f64),383 /// Variable name: test384 Var(IStr),385386 /// Array of expressions: [1, 2, "Hello"]387 Arr(Rc<Vec<Spanned<Expr>>>),388 /// Array comprehension:389 /// ```jsonnet390 /// ingredients: [391 /// { kind: kind, qty: 4 / 3 }392 /// for kind in [393 /// 'Honey Syrup',394 /// 'Lemon Juice',395 /// 'Farmers Gin',396 /// ]397 /// ],398 /// ```399 ArrComp(Rc<Spanned<Expr>>, Vec<CompSpec>),400401 /// Object: {a: 2}402 Obj(ObjBody),403 /// Object extension: var1 {b: 2}404 ObjExtend(Rc<Spanned<Expr>>, ObjBody),405406 /// -2407 UnaryOp(UnaryOpType, Box<Spanned<Expr>>),408 /// 2 - 2409 BinaryOp(Box<BinaryOp>),410 /// assert 2 == 2 : "Math is broken"411 AssertExpr(Rc<AssertExpr>),412 /// local a = 2; { b: a }413 LocalExpr(Vec<BindSpec>, Box<Spanned<Expr>>),414415 /// import* "hello"416 Import(ImportKind, Box<Spanned<Expr>>),417 /// error "I'm broken"418 ErrorStmt(Box<Spanned<Expr>>),419 /// a(b, c)420 Apply(Box<Spanned<Expr>>, ArgsDesc, bool),421 /// a[b], a.b, a?.b422 Index {423 indexable: Box<Spanned<Expr>>,424 parts: Vec<IndexPart>,425 },426 /// function(x) x427 Function(ExprParams, Rc<Spanned<Expr>>),428 /// if true == false then 1 else 2429 IfElse(Box<IfElse>),430 Slice(Box<Slice>),431}432433#[derive(Debug, PartialEq, Acyclic)]434pub struct IndexPart {435 pub value: Spanned<Expr>,436 #[cfg(feature = "exp-null-coaelse")]437 pub null_coaelse: bool,438}439440/// file, begin offset, end offset441#[derive(Clone, PartialEq, Eq, Acyclic)]442#[repr(C)]443pub struct Span(pub Source, pub u32, pub u32);444impl Span {445 pub fn belongs_to(&self, other: &Span) -> bool {446 other.0 == self.0 && other.1 <= self.1 && other.2 >= self.2447 }448}449450static_assertions::assert_eq_size!(Span, (usize, usize));451452impl Debug for Span {453 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {454 write!(f, "{:?}:{:?}-{:?}", self.0, self.1, self.2)455 }456}457458#[derive(Clone, PartialEq, Acyclic)]459pub struct Spanned<T: Acyclic>(T, Span);460impl<T: Acyclic> Deref for Spanned<T> {461 type Target = T;462 fn deref(&self) -> &Self::Target {463 &self.0464 }465}466impl<T: Acyclic> Spanned<T> {467 #[inline]468 pub fn new(v: T, s: Span) -> Self {469 Self(v, s)470 }471 #[inline]472 pub fn span(&self) -> Span {473 self.1.clone()474 }475}476477impl<T: Debug + Acyclic> Debug for Spanned<T> {478 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {479 let expr = &**self;480 if f.alternate() {481 write!(f, "{:#?}", expr)?;482 } else {483 write!(f, "{:?}", expr)?;484 }485 write!(f, " from {:?}", self.span())?;486 Ok(())487 }488}crates/jrsonnet-parser/src/function.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/function.rs
+++ b/crates/jrsonnet-parser/src/function.rs
@@ -6,32 +6,38 @@
use jrsonnet_interner::IStr;
#[derive(Clone, Acyclic, Debug, PartialEq, Eq)]
-pub struct ParamName(pub Option<IStr>);
+pub enum ParamName {
+ Unnamed,
+ Named(IStr),
+}
impl ParamName {
- pub const ANONYMOUS: Self = Self(None);
- pub fn new(name: IStr) -> Self {
- Self(Some(name))
- }
pub fn as_str(&self) -> Option<&str> {
- self.0.as_deref()
+ match self {
+ ParamName::Unnamed => None,
+ ParamName::Named(istr) => Some(istr),
+ }
}
pub fn is_anonymous(&self) -> bool {
- self.0.is_none()
+ matches!(self, Self::Unnamed)
+ }
+ pub fn is_named(&self) -> bool {
+ matches!(self, Self::Named(_))
}
}
impl PartialEq<IStr> for ParamName {
fn eq(&self, other: &IStr) -> bool {
- self.0
- .as_ref()
- .map_or(false, |s| s.as_bytes() == other.as_bytes())
+ match self {
+ ParamName::Unnamed => false,
+ ParamName::Named(istr) => istr == other,
+ }
}
}
impl fmt::Display for ParamName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- match &self.0 {
- Some(v) => write!(f, "{v}"),
- None => write!(f, "<unnamed>"),
+ match &self {
+ Self::Named(v) => write!(f, "{v}"),
+ Self::Unnamed => write!(f, "<unnamed>"),
}
}
}
crates/jrsonnet-parser/src/snapshots/jrsonnet_parser__tests__default_param_before_nondefault.snapdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/snapshots/jrsonnet_parser__tests__default_param_before_nondefault.snap
+++ b/crates/jrsonnet-parser/src/snapshots/jrsonnet_parser__tests__default_param_before_nondefault.snap
@@ -28,18 +28,14 @@
signature: FunctionSignature(
[
ParamParse {
- name: ParamName(
- Some(
- "foo",
- ),
+ name: Named(
+ "foo",
),
default: Exists,
},
ParamParse {
- name: ParamName(
- Some(
- "bar",
- ),
+ name: Named(
+ "bar",
),
default: None,
},