difftreelog
refactor remove tla from state
in: master
6 files changed
cmds/jrsonnet/src/main.rsdiffbeforeafterboth--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -5,8 +5,8 @@
use clap::{CommandFactory, Parser};
use clap_complete::Shell;
-use jrsonnet_cli::{ConfigureState, GeneralOpts, ManifestOpts, OutputOpts};
-use jrsonnet_evaluator::{error::LocError, State};
+use jrsonnet_cli::{ConfigureState, GeneralOpts, ManifestOpts, OutputOpts, TraceOpts};
+use jrsonnet_evaluator::{apply_tla, error::LocError, throw, ResultExt, State, Val};
#[cfg(feature = "mimalloc")]
#[global_allocator]
@@ -121,8 +121,8 @@
}
fn main_real(s: &State, opts: Opts) -> Result<(), Error> {
- let _guards = opts.general.configure(s)?;
- opts.manifest.configure(s)?;
+ let (_stack_guard, tla, _gc_guard) = opts.general.configure(s)?;
+ let manifest_format = opts.manifest.configure(s)?;
let input = opts.input.input.ok_or(Error::MissingInputArgument)?;
let val = if opts.input.exec {
@@ -136,7 +136,7 @@
s.import(&input)?
};
- let val = s.with_tla(val)?;
+ let val = apply_tla(s.clone(), &tla, val)?;
if let Some(multi) = opts.output.multi {
if opts.output.create_output_dirs {
crates/jrsonnet-cli/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/lib.rs
+++ b/crates/jrsonnet-cli/src/lib.rs
@@ -71,7 +71,7 @@
misc: MiscOpts,
#[clap(flatten)]
- tla: TLAOpts,
+ tla: TlaOpts,
#[clap(flatten)]
std: StdOpts,
@@ -85,16 +85,17 @@
impl ConfigureState for GeneralOpts {
type Guards = (
<MiscOpts as ConfigureState>::Guards,
+ <TlaOpts as ConfigureState>::Guards,
<GcOpts as ConfigureState>::Guards,
);
fn configure(&self, s: &State) -> Result<Self::Guards> {
// Configure trace first, because tla-code/ext-code can throw
self.trace.configure(s)?;
let misc_guards = self.misc.configure(s)?;
- self.tla.configure(s)?;
+ let tla_guards = self.tla.configure(s)?;
self.std.configure(s)?;
let gc_guards = self.gc.configure(s)?;
- Ok((misc_guards, gc_guards))
+ Ok((misc_guards, tla_guards, gc_guards))
}
}
crates/jrsonnet-cli/src/tla.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/tla.rs
+++ b/crates/jrsonnet-cli/src/tla.rs
@@ -1,11 +1,17 @@
use clap::Parser;
-use jrsonnet_evaluator::{error::Result, State};
+use jrsonnet_evaluator::{
+ error::{Error, Result},
+ function::TlaArg,
+ gc::GcHashMap,
+ IStr, State,
+};
+use jrsonnet_parser::{ParserSettings, Source};
use crate::{ConfigureState, ExtFile, ExtStr};
#[derive(Parser)]
#[clap(next_help_heading = "TOP LEVEL ARGUMENTS")]
-pub struct TLAOpts {
+pub struct TlaOpts {
/// Add top level string argument.
/// Top level arguments will be passed to function before manifestification stage.
/// This is preferred to ExtVars method.
@@ -25,21 +31,41 @@
#[clap(long, name = "name=tla code path", number_of_values = 1)]
tla_code_file: Vec<ExtFile>,
}
-impl ConfigureState for TLAOpts {
- type Guards = ();
- fn configure(&self, s: &State) -> Result<()> {
- for tla in self.tla_str.iter() {
- s.add_tla_str((&tla.name as &str).into(), (&tla.value as &str).into());
+impl ConfigureState for TlaOpts {
+ type Guards = GcHashMap<IStr, TlaArg>;
+ fn configure(&self, _s: &State) -> Result<Self::Guards> {
+ let mut out = GcHashMap::new();
+ for (name, value) in self
+ .tla_str
+ .iter()
+ .map(|c| (&c.name, &c.value))
+ .chain(self.tla_str_file.iter().map(|c| (&c.name, &c.value)))
+ {
+ out.insert(name.into(), TlaArg::String(value.into()));
}
- for tla in self.tla_str_file.iter() {
- s.add_tla_str((&tla.name as &str).into(), (&tla.value as &str).into())
- }
- for tla in self.tla_code.iter() {
- s.add_tla_code((&tla.name as &str).into(), &tla.value as &str)?;
- }
- for tla in self.tla_code_file.iter() {
- s.add_tla_code((&tla.name as &str).into(), &tla.value as &str)?;
+ for (name, code) in self
+ .tla_code
+ .iter()
+ .map(|c| (&c.name, &c.value))
+ .chain(self.tla_code_file.iter().map(|c| (&c.name, &c.value)))
+ {
+ let source = Source::new_virtual(format!("<top-level-arg:{name}>").into(), code.into());
+ out.insert(
+ (&name as &str).into(),
+ TlaArg::Code(
+ jrsonnet_parser::parse(
+ &code,
+ &ParserSettings {
+ source: source.clone(),
+ },
+ )
+ .map_err(|e| Error::ImportSyntaxError {
+ path: source,
+ error: Box::new(e),
+ })?,
+ ),
+ );
}
- Ok(())
+ Ok(out)
}
}
crates/jrsonnet-evaluator/src/function/arglike.rsdiffbeforeafterboth1use hashbrown::HashMap;2use jrsonnet_gcmodule::Trace;3use jrsonnet_interner::IStr;4use jrsonnet_parser::{ArgsDesc, LocExpr};56use crate::{7 error::Result, evaluate, gc::GcHashMap, tb, typed::Typed, val::ThunkValue, Context, Thunk, Val,8};910/// Marker for arguments, which can be evaluated with context set to None11pub trait OptionalContext {}1213#[derive(Trace)]14struct EvaluateThunk {15 ctx: Context,16 expr: LocExpr,17}18impl ThunkValue for EvaluateThunk {19 type Output = Val;20 fn get(self: Box<Self>) -> Result<Val> {21 evaluate(self.ctx, &self.expr)22 }23}2425pub trait ArgLike {26 fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<Thunk<Val>>;27}2829impl ArgLike for &LocExpr {30 fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<Thunk<Val>> {31 Ok(if tailstrict {32 Thunk::evaluated(evaluate(ctx, self)?)33 } else {34 Thunk::new(tb!(EvaluateThunk {35 ctx,36 expr: (*self).clone(),37 }))38 })39 }40}4142impl<T> ArgLike for T43where44 T: Typed + Clone,45{46 fn evaluate_arg(&self, _ctx: Context, _tailstrict: bool) -> Result<Thunk<Val>> {47 let val = T::into_untyped(self.clone())?;48 Ok(Thunk::evaluated(val))49 }50}51impl<T> OptionalContext for T where T: Typed + Clone {}5253#[derive(Clone, Trace)]54pub enum TlaArg {55 String(IStr),56 Code(LocExpr),57 Val(Val),58}59impl ArgLike for TlaArg {60 fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<Thunk<Val>> {61 match self {62 TlaArg::String(s) => Ok(Thunk::evaluated(Val::Str(s.clone()))),63 TlaArg::Code(code) => Ok(if tailstrict {64 Thunk::evaluated(evaluate(ctx, code)?)65 } else {66 Thunk::new(tb!(EvaluateThunk {67 ctx,68 expr: code.clone(),69 }))70 }),71 TlaArg::Val(val) => Ok(Thunk::evaluated(val.clone())),72 }73 }74}7576mod sealed {77 /// Implemented for `ArgsLike`, where only unnamed arguments present78 pub trait Unnamed {}79 /// Implemented for `ArgsLike`, where only named arguments present80 pub trait Named {}81}8283pub trait ArgsLike {84 fn unnamed_len(&self) -> usize;85 fn unnamed_iter(86 &self,87 ctx: Context,88 tailstrict: bool,89 handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,90 ) -> Result<()>;91 fn named_iter(92 &self,93 ctx: Context,94 tailstrict: bool,95 handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,96 ) -> Result<()>;97 fn named_names(&self, handler: &mut dyn FnMut(&IStr));98}99100impl ArgsLike for Vec<Val> {101 fn unnamed_len(&self) -> usize {102 self.len()103 }104 fn unnamed_iter(105 &self,106 _ctx: Context,107 _tailstrict: bool,108 handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,109 ) -> Result<()> {110 for (idx, el) in self.iter().enumerate() {111 handler(idx, Thunk::evaluated(el.clone()))?;112 }113 Ok(())114 }115 fn named_iter(116 &self,117 _ctx: Context,118 _tailstrict: bool,119 _handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,120 ) -> Result<()> {121 Ok(())122 }123 fn named_names(&self, _handler: &mut dyn FnMut(&IStr)) {}124}125impl OptionalContext for Vec<Val> {}126127impl ArgsLike for ArgsDesc {128 fn unnamed_len(&self) -> usize {129 self.unnamed.len()130 }131132 fn unnamed_iter(133 &self,134 ctx: Context,135 tailstrict: bool,136 handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,137 ) -> Result<()> {138 for (id, arg) in self.unnamed.iter().enumerate() {139 handler(140 id,141 if tailstrict {142 Thunk::evaluated(evaluate(ctx.clone(), arg)?)143 } else {144 Thunk::new(tb!(EvaluateThunk {145 ctx: ctx.clone(),146 expr: arg.clone(),147 }))148 },149 )?;150 }151 Ok(())152 }153154 fn named_iter(155 &self,156 ctx: Context,157 tailstrict: bool,158 handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,159 ) -> Result<()> {160 for (name, arg) in &self.named {161 handler(162 name,163 if tailstrict {164 Thunk::evaluated(evaluate(ctx.clone(), arg)?)165 } else {166 Thunk::new(tb!(EvaluateThunk {167 ctx: ctx.clone(),168 expr: arg.clone(),169 }))170 },171 )?;172 }173 Ok(())174 }175176 fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {177 for (name, _) in &self.named {178 handler(name);179 }180 }181}182183impl<A: ArgLike, S> sealed::Named for HashMap<IStr, A, S> {}184impl<A: ArgLike, S> ArgsLike for HashMap<IStr, A, S> {185 fn unnamed_len(&self) -> usize {186 0187 }188189 fn unnamed_iter(190 &self,191 _ctx: Context,192 _tailstrict: bool,193 _handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,194 ) -> Result<()> {195 Ok(())196 }197198 fn named_iter(199 &self,200 ctx: Context,201 tailstrict: bool,202 handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,203 ) -> Result<()> {204 for (name, value) in self.iter() {205 handler(name, value.evaluate_arg(ctx.clone(), tailstrict)?)?;206 }207 Ok(())208 }209210 fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {211 for (name, _) in self.iter() {212 handler(name);213 }214 }215}216impl<A, S> OptionalContext for HashMap<IStr, A, S> where A: ArgLike + OptionalContext {}217218impl<A: ArgLike> ArgsLike for GcHashMap<IStr, A> {219 fn unnamed_len(&self) -> usize {220 self.0.unnamed_len()221 }222223 fn unnamed_iter(224 &self,225 ctx: Context,226 tailstrict: bool,227 handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,228 ) -> Result<()> {229 self.0.unnamed_iter(ctx, tailstrict, handler)230 }231232 fn named_iter(233 &self,234 ctx: Context,235 tailstrict: bool,236 handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,237 ) -> Result<()> {238 self.0.named_iter(ctx, tailstrict, handler)239 }240241 fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {242 self.0.named_names(handler)243 }244}245246macro_rules! impl_args_like {247 ($count:expr; $($gen:ident)*) => {248 impl<$($gen: ArgLike,)*> sealed::Unnamed for ($($gen,)*) {}249 impl<$($gen: ArgLike,)*> ArgsLike for ($($gen,)*) {250 fn unnamed_len(&self) -> usize {251 $count252 }253 #[allow(non_snake_case, unused_assignments)]254 fn unnamed_iter(255 &self,256 ctx: Context,257 tailstrict: bool,258 handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,259 ) -> Result<()> {260 let mut i = 0usize;261 let ($($gen,)*) = self;262 $(263 handler(i, $gen.evaluate_arg(ctx.clone(), tailstrict)?)?;264 i+=1;265 )*266 Ok(())267 }268 fn named_iter(269 &self,270 _ctx: Context,271 _tailstrict: bool,272 _handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,273 ) -> Result<()> {274 Ok(())275 }276 fn named_names(&self, _handler: &mut dyn FnMut(&IStr)) {}277 }278 impl<$($gen: ArgLike,)*> OptionalContext for ($($gen,)*) where $($gen: OptionalContext),* {}279280 impl<$($gen: ArgLike,)*> sealed::Named for ($((IStr, $gen),)*) {}281 impl<$($gen: ArgLike,)*> ArgsLike for ($((IStr, $gen),)*) {282 fn unnamed_len(&self) -> usize {283 0284 }285 fn unnamed_iter(286 &self,287 _ctx: Context,288 _tailstrict: bool,289 _handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,290 ) -> Result<()> {291 Ok(())292 }293 #[allow(non_snake_case)]294 fn named_iter(295 &self,296 ctx: Context,297 tailstrict: bool,298 handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,299 ) -> Result<()> {300 let ($($gen,)*) = self;301 $(302 handler(&$gen.0, $gen.1.evaluate_arg(ctx.clone(), tailstrict)?)?;303 )*304 Ok(())305 }306 #[allow(non_snake_case)]307 fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {308 let ($($gen,)*) = self;309 $(310 handler(&$gen.0);311 )*312 }313 }314 impl<$($gen: ArgLike,)*> OptionalContext for ($((IStr, $gen),)*) where $($gen: OptionalContext),* {}315 };316 ($count:expr; $($cur:ident)* @ $c:ident $($rest:ident)*) => {317 impl_args_like!($count; $($cur)*);318 impl_args_like!($count + 1usize; $($cur)* $c @ $($rest)*);319 };320 ($count:expr; $($cur:ident)* @) => {321 impl_args_like!($count; $($cur)*);322 }323}324impl_args_like! {325 // First argument is already in position, so count starts from 1326 1usize; A @ B C D E F G H I J K L327}328329impl ArgsLike for () {330 fn unnamed_len(&self) -> usize {331 0332 }333334 fn unnamed_iter(335 &self,336 _ctx: Context,337 _tailstrict: bool,338 _handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,339 ) -> Result<()> {340 Ok(())341 }342343 fn named_iter(344 &self,345 _ctx: Context,346 _tailstrict: bool,347 _handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,348 ) -> Result<()> {349 Ok(())350 }351352 fn named_names(&self, _handler: &mut dyn FnMut(&IStr)) {}353}354impl OptionalContext for () {}crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -55,6 +55,7 @@
mod obj;
pub mod stack;
pub mod stdlib;
+mod tla;
pub mod trace;
pub mod typed;
pub mod val;
@@ -81,7 +82,7 @@
use jrsonnet_parser::*;
pub use obj::*;
use stack::check_depth;
-use trace::{CompactFormat, TraceFormat};
+pub use tla::apply_tla;
pub use val::{ManifestFormat, Thunk, Val};
/// Thunk without bound `super`/`this`
@@ -143,10 +144,6 @@
/// Dynamically reconfigurable evaluation settings
#[derive(Trace)]
pub struct EvaluationSettings {
- /// Limits amount of stack trace items preserved
- pub max_trace: usize,
- /// TLA vars
- pub tla_vars: HashMap<IStr, TlaArg>,
/// Context initializer, which will be used for imports and everything
/// [`NoopContextInitializer`] is used by default, most likely you want to have `jrsonnet-stdlib`
pub context_initializer: TraceBox<dyn ContextInitializer>,
@@ -160,19 +157,8 @@
impl Default for EvaluationSettings {
fn default() -> Self {
Self {
- max_trace: 20,
context_initializer: tb!(DummyContextInitializer),
- tla_vars: HashMap::default(),
import_resolver: tb!(DummyImportResolver),
- manifest_format: ManifestFormat::Json {
- padding: 4,
- #[cfg(feature = "exp-preserve-order")]
- preserve_order: false,
- },
- trace_format: tb!(CompactFormat {
- padding: 4,
- resolver: trace::PathResolver::Absolute,
- }),
}
}
}
@@ -404,51 +390,6 @@
let _guard = check_depth()?;
f().with_description(frame_desc)
- }
-
- /// # Panics
- /// In case of formatting failure
- pub fn stringify_err(&self, e: &LocError) -> String {
- let mut out = String::new();
- self.settings()
- .trace_format
- .write_trace(&mut out, self, e)
- .unwrap();
- out
- }
-
- pub fn manifest(&self, val: Val) -> Result<IStr> {
- Self::push_description(
- || "manifestification".to_string(),
- || val.manifest(&self.manifest_format()),
- )
- }
- pub fn manifest_multi(&self, val: Val) -> Result<Vec<(IStr, IStr)>> {
- val.manifest_multi(&self.manifest_format())
- }
- pub fn manifest_stream(&self, val: Val) -> Result<Vec<IStr>> {
- val.manifest_stream(&self.manifest_format())
- }
-
- /// If passed value is function then call with set TLA
- pub fn with_tla(&self, val: Val) -> Result<Val> {
- Ok(match val {
- Val::Func(func) => State::push_description(
- || "during TLA call".to_owned(),
- || {
- func.evaluate(
- self.create_default_context(Source::new_virtual(
- "<tla>".into(),
- IStr::empty(),
- )),
- CallLocation::native(),
- &self.settings().tla_vars,
- true,
- )
- },
- )?,
- v => v,
- })
}
}
@@ -487,35 +428,6 @@
/// Settings utilities
impl State {
- pub fn add_tla(&self, name: IStr, value: Val) {
- self.settings_mut()
- .tla_vars
- .insert(name, TlaArg::Val(value));
- }
- pub fn add_tla_str(&self, name: IStr, value: IStr) {
- self.settings_mut()
- .tla_vars
- .insert(name, TlaArg::String(value));
- }
- pub fn add_tla_code(&self, name: IStr, code: &str) -> Result<()> {
- let source_name = format!("<top-level-arg:{name}>");
- let source = Source::new_virtual(source_name.into(), code.into());
- let parsed = jrsonnet_parser::parse(
- code,
- &ParserSettings {
- file_name: source.clone(),
- },
- )
- .map_err(|e| ImportSyntaxError {
- path: source,
- error: Box::new(e),
- })?;
- self.settings_mut()
- .tla_vars
- .insert(name, TlaArg::Code(parsed));
- Ok(())
- }
-
// Only panics in case of [`ImportResolver`] contract violation
#[allow(clippy::missing_panics_doc)]
pub fn resolve_from(&self, from: &SourcePath, path: &str) -> Result<SourcePath> {
crates/jrsonnet-evaluator/src/tla.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/jrsonnet-evaluator/src/tla.rs
@@ -0,0 +1,25 @@
+use jrsonnet_interner::IStr;
+use jrsonnet_parser::Source;
+
+use crate::{
+ function::{ArgsLike, CallLocation},
+ Result, State, Val,
+};
+
+pub fn apply_tla<A: ArgsLike>(s: State, args: &A, val: Val) -> Result<Val> {
+ Ok(if let Val::Func(func) = val {
+ State::push_description(
+ || "during TLA call".to_owned(),
+ || {
+ func.evaluate(
+ s.create_default_context(Source::new_virtual("<top-level-arg>".into(), IStr::empty())),
+ CallLocation::native(),
+ args,
+ false,
+ )
+ },
+ )?
+ } else {
+ val
+ })
+}