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 std::collections::HashMap;23use jrsonnet_gcmodule::Trace;4use jrsonnet_interner::IStr;5use jrsonnet_parser::{ArgsDesc, LocExpr};67use crate::{error::Result, evaluate, tb, typed::Typed, val::ThunkValue, Context, Thunk, Val};89/// Marker for arguments, which can be evaluated with context set to None10pub trait OptionalContext {}1112#[derive(Trace)]13struct EvaluateThunk {14 ctx: Context,15 expr: LocExpr,16}17impl ThunkValue for EvaluateThunk {18 type Output = Val;19 fn get(self: Box<Self>) -> Result<Val> {20 evaluate(self.ctx, &self.expr)21 }22}2324pub trait ArgLike {25 fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<Thunk<Val>>;26}2728impl ArgLike for &LocExpr {29 fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<Thunk<Val>> {30 Ok(if tailstrict {31 Thunk::evaluated(evaluate(ctx, self)?)32 } else {33 Thunk::new(tb!(EvaluateThunk {34 ctx,35 expr: (*self).clone(),36 }))37 })38 }39}4041impl<T> ArgLike for T42where43 T: Typed + Clone,44{45 fn evaluate_arg(&self, _ctx: Context, _tailstrict: bool) -> Result<Thunk<Val>> {46 let val = T::into_untyped(self.clone())?;47 Ok(Thunk::evaluated(val))48 }49}50impl<T> OptionalContext for T where T: Typed + Clone {}5152#[derive(Clone, Trace)]53pub enum TlaArg {54 String(IStr),55 Code(LocExpr),56 Val(Val),57}58impl ArgLike for TlaArg {59 fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<Thunk<Val>> {60 match self {61 TlaArg::String(s) => Ok(Thunk::evaluated(Val::Str(s.clone()))),62 TlaArg::Code(code) => Ok(if tailstrict {63 Thunk::evaluated(evaluate(ctx, code)?)64 } else {65 Thunk::new(tb!(EvaluateThunk {66 ctx,67 expr: code.clone(),68 }))69 }),70 TlaArg::Val(val) => Ok(Thunk::evaluated(val.clone())),71 }72 }73}7475mod sealed {76 /// Implemented for `ArgsLike`, where only unnamed arguments present77 pub trait Unnamed {}78 /// Implemented for `ArgsLike`, where only named arguments present79 pub trait Named {}80}8182pub trait ArgsLike {83 fn unnamed_len(&self) -> usize;84 fn unnamed_iter(85 &self,86 ctx: Context,87 tailstrict: bool,88 handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,89 ) -> Result<()>;90 fn named_iter(91 &self,92 ctx: Context,93 tailstrict: bool,94 handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,95 ) -> Result<()>;96 fn named_names(&self, handler: &mut dyn FnMut(&IStr));97}9899impl ArgsLike for Vec<Val> {100 fn unnamed_len(&self) -> usize {101 self.len()102 }103 fn unnamed_iter(104 &self,105 _ctx: Context,106 _tailstrict: bool,107 handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,108 ) -> Result<()> {109 for (idx, el) in self.iter().enumerate() {110 handler(idx, Thunk::evaluated(el.clone()))?;111 }112 Ok(())113 }114 fn named_iter(115 &self,116 _ctx: Context,117 _tailstrict: bool,118 _handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,119 ) -> Result<()> {120 Ok(())121 }122 fn named_names(&self, _handler: &mut dyn FnMut(&IStr)) {}123}124impl OptionalContext for Vec<Val> {}125126impl ArgsLike for ArgsDesc {127 fn unnamed_len(&self) -> usize {128 self.unnamed.len()129 }130131 fn unnamed_iter(132 &self,133 ctx: Context,134 tailstrict: bool,135 handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,136 ) -> Result<()> {137 for (id, arg) in self.unnamed.iter().enumerate() {138 handler(139 id,140 if tailstrict {141 Thunk::evaluated(evaluate(ctx.clone(), arg)?)142 } else {143 Thunk::new(tb!(EvaluateThunk {144 ctx: ctx.clone(),145 expr: arg.clone(),146 }))147 },148 )?;149 }150 Ok(())151 }152153 fn named_iter(154 &self,155 ctx: Context,156 tailstrict: bool,157 handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,158 ) -> Result<()> {159 for (name, arg) in &self.named {160 handler(161 name,162 if tailstrict {163 Thunk::evaluated(evaluate(ctx.clone(), arg)?)164 } else {165 Thunk::new(tb!(EvaluateThunk {166 ctx: ctx.clone(),167 expr: arg.clone(),168 }))169 },170 )?;171 }172 Ok(())173 }174175 fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {176 for (name, _) in &self.named {177 handler(name);178 }179 }180}181182impl<A: ArgLike, S> sealed::Named for HashMap<IStr, A, S> {}183impl<A: ArgLike, S> ArgsLike for HashMap<IStr, A, S> {184 fn unnamed_len(&self) -> usize {185 0186 }187188 fn unnamed_iter(189 &self,190 _ctx: Context,191 _tailstrict: bool,192 _handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,193 ) -> Result<()> {194 Ok(())195 }196197 fn named_iter(198 &self,199 ctx: Context,200 tailstrict: bool,201 handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,202 ) -> Result<()> {203 for (name, value) in self.iter() {204 handler(name, value.evaluate_arg(ctx.clone(), tailstrict)?)?;205 }206 Ok(())207 }208209 fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {210 for (name, _) in self.iter() {211 handler(name);212 }213 }214}215impl<A, S> OptionalContext for HashMap<IStr, A, S> where A: ArgLike + OptionalContext {}216217macro_rules! impl_args_like {218 ($count:expr; $($gen:ident)*) => {219 impl<$($gen: ArgLike,)*> sealed::Unnamed for ($($gen,)*) {}220 impl<$($gen: ArgLike,)*> ArgsLike for ($($gen,)*) {221 fn unnamed_len(&self) -> usize {222 $count223 }224 #[allow(non_snake_case, unused_assignments)]225 fn unnamed_iter(226 &self,227 ctx: Context,228 tailstrict: bool,229 handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,230 ) -> Result<()> {231 let mut i = 0usize;232 let ($($gen,)*) = self;233 $(234 handler(i, $gen.evaluate_arg(ctx.clone(), tailstrict)?)?;235 i+=1;236 )*237 Ok(())238 }239 fn named_iter(240 &self,241 _ctx: Context,242 _tailstrict: bool,243 _handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,244 ) -> Result<()> {245 Ok(())246 }247 fn named_names(&self, _handler: &mut dyn FnMut(&IStr)) {}248 }249 impl<$($gen: ArgLike,)*> OptionalContext for ($($gen,)*) where $($gen: OptionalContext),* {}250251 impl<$($gen: ArgLike,)*> sealed::Named for ($((IStr, $gen),)*) {}252 impl<$($gen: ArgLike,)*> ArgsLike for ($((IStr, $gen),)*) {253 fn unnamed_len(&self) -> usize {254 0255 }256 fn unnamed_iter(257 &self,258 _ctx: Context,259 _tailstrict: bool,260 _handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,261 ) -> Result<()> {262 Ok(())263 }264 #[allow(non_snake_case)]265 fn named_iter(266 &self,267 ctx: Context,268 tailstrict: bool,269 handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,270 ) -> Result<()> {271 let ($($gen,)*) = self;272 $(273 handler(&$gen.0, $gen.1.evaluate_arg(ctx.clone(), tailstrict)?)?;274 )*275 Ok(())276 }277 #[allow(non_snake_case)]278 fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {279 let ($($gen,)*) = self;280 $(281 handler(&$gen.0);282 )*283 }284 }285 impl<$($gen: ArgLike,)*> OptionalContext for ($((IStr, $gen),)*) where $($gen: OptionalContext),* {}286 };287 ($count:expr; $($cur:ident)* @ $c:ident $($rest:ident)*) => {288 impl_args_like!($count; $($cur)*);289 impl_args_like!($count + 1usize; $($cur)* $c @ $($rest)*);290 };291 ($count:expr; $($cur:ident)* @) => {292 impl_args_like!($count; $($cur)*);293 }294}295impl_args_like! {296 // First argument is already in position, so count starts from 1297 1usize; A @ B C D E F G H I J K L298}299300impl ArgsLike for () {301 fn unnamed_len(&self) -> usize {302 0303 }304305 fn unnamed_iter(306 &self,307 _ctx: Context,308 _tailstrict: bool,309 _handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,310 ) -> Result<()> {311 Ok(())312 }313314 fn named_iter(315 &self,316 _ctx: Context,317 _tailstrict: bool,318 _handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,319 ) -> Result<()> {320 Ok(())321 }322323 fn named_names(&self, _handler: &mut dyn FnMut(&IStr)) {}324}325impl 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
+ })
+}