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

difftreelog

refactor trivial arrays

pynwztymYaroslav Bolyukin2026-05-08parent: #b89fdd3.patch.diff
in: master

5 files changed

modifiedcrates/jrsonnet-evaluator/src/analyze.rsdiffbeforeafterboth
138#[derive(Debug, Acyclic)]138#[derive(Debug, Acyclic)]
139pub enum LExpr {139pub enum LExpr {
140 Slot(LSlot),140 Slot(LSlot),
141 Null,
142 Bool(bool),141 Trivial(TrivialVal),
143 Str(IStr),
144 Num(NumValue),
145 Arr {142 Arr {
146 shape: ClosureShape,143 shape: ClosureShape,
147 items: Rc<Vec<LExpr>>,144 items: Rc<Vec<LExpr>>,
148 },145 },
146 ArrConst(Rc<Vec<TrivialVal>>),
149 ArrComp(Box<LArrComp>),147 ArrComp(Box<LArrComp>),
150 Obj(LObjBody),148 Obj(LObjBody),
151 ObjExtend(Box<LExpr>, LObjBody),149 ObjExtend(Box<LExpr>, LObjBody),
1345#[allow(clippy::too_many_lines)]1343#[allow(clippy::too_many_lines)]
1346pub fn analyze(expr: &Expr, stack: &mut AnalysisStack, taint: &mut AnalysisResult) -> LExpr {1344pub fn analyze(expr: &Expr, stack: &mut AnalysisStack, taint: &mut AnalysisResult) -> LExpr {
1347 match expr {1345 match expr {
1348 Expr::Literal(span, l) => match l {1346 Expr::Identity(span, l) => match l {
1349 LiteralType::This => stack.use_this(taint).map_or_else(1347 IdentityKind::This => stack.use_this(taint).map_or_else(
1350 || {1348 || {
1351 stack.report_error("`self` used outside of object", Some(span.clone()));1349 stack.report_error("`self` used outside of object", Some(span.clone()));
1352 LExpr::BadLocal("self")1350 LExpr::BadLocal("self")
1353 },1351 },
1354 LExpr::Slot,1352 LExpr::Slot,
1355 ),1353 ),
1356 LiteralType::Super => {1354 IdentityKind::Super => {
1357 if stack.use_super(taint).is_some() {1355 if stack.use_super(taint).is_some() {
1358 LExpr::Super1356 LExpr::Super
1359 } else {1357 } else {
1360 stack.report_error("`super` used outside of object", Some(span.clone()));1358 stack.report_error("`super` used outside of object", Some(span.clone()));
1361 LExpr::BadLocal("super")1359 LExpr::BadLocal("super")
1362 }1360 }
1363 }1361 }
1364 LiteralType::Dollar => stack.use_dollar(taint).map_or_else(1362 IdentityKind::Dollar => stack.use_dollar(taint).map_or_else(
1365 || {1363 || {
1366 stack.report_error("`$` used outside of object", Some(span.clone()));1364 stack.report_error("`$` used outside of object", Some(span.clone()));
1367 LExpr::BadLocal("$")1365 LExpr::BadLocal("$")
1368 },1366 },
1369 LExpr::Slot,1367 LExpr::Slot,
1370 ),1368 ),
1371 LiteralType::Null => LExpr::Null,
1372 LiteralType::True => LExpr::Bool(true),
1373 LiteralType::False => LExpr::Bool(false),
1374 },1369 },
1375 Expr::Str(s) => LExpr::Str(s.clone()),1370 Expr::Trivial(tv) => LExpr::Trivial(tv.clone()),
1376 Expr::Num(n) => LExpr::Num(*n),
1377 Expr::Var(v) => stack1371 Expr::Var(v) => stack
1378 .use_local(&v.value, v.span.clone(), taint)1372 .use_local(&v.value, v.span.clone(), taint)
1379 .map_or_else(|| LExpr::BadLocal("ref"), LExpr::Slot),1373 .map_or_else(|| LExpr::BadLocal("ref"), LExpr::Slot),
1380 Expr::Arr(a) => {1374 Expr::Arr(a) => {
1375 if a.iter().all(|i| matches!(i, Expr::Trivial(_))) {
1376 let trivials: Vec<_> = a
1377 .iter()
1378 .map(|i| match i {
1379 Expr::Trivial(tv) => tv.clone(),
1380 _ => unreachable!("checked above"),
1381 })
1382 .collect();
1383 return LExpr::ArrConst(Rc::new(trivials));
1384 }
1381 let (shape, items) = stack1385 let (shape, items) = stack.in_using_closure(|stack| {
1382 .in_using_closure(|stack| a.iter().map(|v| analyze(v, stack, taint)).collect());1386 a.iter()
1387 .map(|v| analyze(v, stack, taint))
1388 .collect::<Vec<_>>()
1389 });
1383 LExpr::Arr {1390 LExpr::Arr {
1384 shape,1391 shape,
1385 items: Rc::new(items),1392 items: Rc::new(items),
1412 }1419 }
1413 Expr::LocalExpr(binds, body) => analyze_local_expr(binds, body, stack, taint),1420 Expr::LocalExpr(binds, body) => analyze_local_expr(binds, body, stack, taint),
1414 Expr::Import(kind, path_expr) => {1421 Expr::Import(kind, path_expr) => {
1415 let Expr::Str(path) = &**path_expr else {1422 let Expr::Trivial(TrivialVal::Str(path)) = &**path_expr else {
1416 stack.report_error(1423 stack.report_error(
1417 "import path must be a string literal",1424 "import path must be a string literal",
1418 Some(kind.span.clone()),1425 Some(kind.span.clone()),
modifiedcrates/jrsonnet-evaluator/src/arr/mod.rsdiffbeforeafterboth
1010
11use crate::{11use crate::{Context, Result, Thunk, Val, analyze::LExpr, function::NativeFn, typed::IntoUntyped};
12 Context, Result, Thunk, Val,
13 analyze::{ClosureShape, LExpr},
14 function::NativeFn,
15 typed::IntoUntyped,
16};
1712
18mod spec;13mod spec;
42 Self::new(())37 Self::new(())
43 }38 }
4439
45 pub fn expr(ctx: Context, shape: &ClosureShape, exprs: Rc<Vec<LExpr>>) -> Self {40 pub fn expr(ctx: Context, exprs: Rc<Vec<LExpr>>) -> Self {
46 Self::new(ExprArray::new(ctx, shape, exprs))41 Self::new(ExprArray::new(ctx, exprs))
47 }42 }
4843
49 pub fn repeated(data: Self, repeats: u32) -> Option<Self> {44 pub fn repeated(data: Self, repeats: u32) -> Option<Self> {
modifiedcrates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth
88
9use jrsonnet_gcmodule::{Cc, Trace};9use jrsonnet_gcmodule::{Cc, Trace};
10use jrsonnet_interner::{IBytes, IStr};10use jrsonnet_interner::{IBytes, IStr};
11use jrsonnet_ir::TrivialVal;
1112
12use super::{ArrValue, arridx};13use super::{ArrValue, arridx};
13use crate::{14use crate::{
14 Context, Error, ObjValue, Result, Thunk, Val,15 Context, Error, ObjValue, Result, Thunk, Val,
15 analyze::{ClosureShape, LExpr},16 analyze::LExpr,
16 error::ErrorKind::InfiniteRecursionDetected,17 error::ErrorKind::InfiniteRecursionDetected,
17 evaluate::evaluate,18 evaluate::evaluate,
18 function::NativeFn,19 function::NativeFn,
108 }109 }
109}110}
111
112impl ArrayCheap for Rc<Vec<TrivialVal>> {
113 fn get(&self, index: u32) -> Option<Val> {
114 self.as_slice()
115 .get(index as usize)
116 .map(|tv| tv.clone().into())
117 }
118
119 fn len(&self) -> u32 {
120 arridx(self.as_slice().len())
121 }
122}
110123
111#[derive(Debug, Trace, Clone)]124#[derive(Debug, Trace, Clone)]
112enum ArrayThunk {125enum ArrayThunk {
123 cached: Cc<RefCell<Vec<ArrayThunk>>>,136 cached: Cc<RefCell<Vec<ArrayThunk>>>,
124}137}
125impl ExprArray {138impl ExprArray {
126 pub fn new(outer: Context, shape: &ClosureShape, src: Rc<Vec<LExpr>>) -> Self {139 pub fn new(ctx: Context, src: Rc<Vec<LExpr>>) -> Self {
127 Self {140 Self {
128 ctx: Context::enter_using(&outer, shape),141 ctx,
129 cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting; src.len()])),142 cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting; src.len()])),
130 src,143 src,
131 }144 }
153 unreachable!()166 unreachable!()
154 };167 };
155168
156 let new_value: Val = evaluate(self.ctx.clone(), &self.src[index as usize])?;169 let result = evaluate(self.ctx.clone(), &self.src[index as usize]);
170 match result {
171 Ok(new_value) => {
157 self.cached.borrow_mut()[index as usize] = ArrayThunk::Computed(new_value.clone());172 self.cached.borrow_mut()[index as usize] = ArrayThunk::Computed(new_value.clone());
158 Ok(Some(new_value))173 Ok(Some(new_value))
174 }
175 Err(e) => {
176 self.cached.borrow_mut()[index as usize] = ArrayThunk::Waiting;
177 Err(e)
178 }
179 }
159 }180 }
160 fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {181 fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {
161 #[derive(Trace)]182 #[derive(Trace)]
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
52}52}
5353
54pub fn evaluate_trivial(expr: &LExpr) -> Option<Val> {54pub fn evaluate_trivial(expr: &LExpr) -> Option<Val> {
55 // TODO: Eager trivial array
56 Some(match expr {55 if let LExpr::Trivial(tv) = expr {
57 LExpr::Str(s) => Val::string(s.clone()),56 Some(tv.clone().into())
58 LExpr::Num(n) => Val::Num(*n),
59 LExpr::Bool(false) => Val::Bool(false),
60 LExpr::Bool(true) => Val::Bool(true),
61 LExpr::Null => Val::Null,
62 _ => return None,
63 })57 } else {
58 None
59 }
64}60}
6561
66pub fn evaluate_method(ctx: Context, name: IStr, func: &Rc<LFunction>) -> Val {62pub fn evaluate_method(ctx: Context, name: IStr, func: &Rc<LFunction>) -> Val {
119pub fn evaluate(mut ctx: Context, mut expr: &LExpr) -> Result<Val> {115pub fn evaluate(mut ctx: Context, mut expr: &LExpr) -> Result<Val> {
120 loop {116 loop {
121 return Ok(match expr {117 return Ok(match expr {
122 LExpr::Null => Val::Null,
123 LExpr::Bool(b) => Val::Bool(*b),
124 LExpr::Str(s) => Val::string(s.clone()),118 LExpr::Trivial(tv) => tv.clone().into(),
125 LExpr::Num(n) => Val::Num(*n),
126 LExpr::Slot(slot) => ctx.slot(*slot).evaluate()?,119 LExpr::Slot(slot) => ctx.slot(*slot).evaluate()?,
127 LExpr::BadLocal(name) => panic!("unresolvable reference: {name}"),120 LExpr::BadLocal(name) => panic!("unresolvable reference: {name}"),
121 LExpr::ArrConst(rc) => Val::Arr(ArrValue::new(rc.clone())),
128 LExpr::Arr { shape, items } => Val::Arr(ArrValue::expr(ctx, shape, items.clone())),122 LExpr::Arr { shape, items } => {
123 let inner = Context::enter_using(&ctx, shape);
124 'eager: {
125 let mut out: Vec<Val> = Vec::with_capacity(items.len());
126 for item in items.iter() {
127 let Ok(r) = evaluate(inner.clone(), item) else {
128 break 'eager;
129 };
130 out.push(r);
131 }
132 return Ok(Val::Arr(ArrValue::new(out)));
133 }
134 Val::Arr(ArrValue::expr(inner, items.clone()))
135 }
129 LExpr::UnaryOp(op, value) => {136 LExpr::UnaryOp(op, value) => {
130 let value = evaluate(ctx, value)?;137 let value = evaluate(ctx, value)?;
131 evaluate_unary_op(*op, &value)?138 evaluate_unary_op(*op, &value)?
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
1010
11use jrsonnet_gcmodule::{Acyclic, Cc, Trace, cc_dyn};11use jrsonnet_gcmodule::{Acyclic, Cc, Trace, cc_dyn};
12use jrsonnet_interner::IStr;12use jrsonnet_interner::IStr;
13use jrsonnet_ir::BinaryOpType;13use jrsonnet_ir::{BinaryOpType, TrivialVal};
14pub use jrsonnet_macros::Thunk;14pub use jrsonnet_macros::Thunk;
15use jrsonnet_types::ValType;15use jrsonnet_types::ValType;
16use rustc_hash::FxHashMap;16use rustc_hash::FxHashMap;
621 Self::Bool(value)621 Self::Bool(value)
622 }622 }
623}623}
624impl From<TrivialVal> for Val {
625 fn from(tv: TrivialVal) -> Self {
626 match tv {
627 TrivialVal::Null => Self::Null,
628 TrivialVal::Bool(b) => Self::Bool(b),
629 TrivialVal::Num(n) => Self::Num(n),
630 TrivialVal::Str(s) => Self::string(s),
631 }
632 }
633}
624634
625const fn is_function_like(val: &Val) -> bool {635const fn is_function_like(val: &Val) -> bool {
626 matches!(val, Val::Func(_))636 matches!(val, Val::Func(_))