git.delta.rocks / jrsonnet / refs/commits / 5f620e2b9aa7

difftreelog

refactor remove tla from state

Yaroslav Bolyukin2022-11-09parent: #7b01ecb.patch.diff
in: master

6 files changed

modifiedcmds/jrsonnet/src/main.rsdiffbeforeafterboth
55
6use clap::{CommandFactory, Parser};6use clap::{CommandFactory, Parser};
7use clap_complete::Shell;7use clap_complete::Shell;
8use jrsonnet_cli::{ConfigureState, GeneralOpts, ManifestOpts, OutputOpts};8use jrsonnet_cli::{ConfigureState, GeneralOpts, ManifestOpts, OutputOpts, TraceOpts};
9use jrsonnet_evaluator::{error::LocError, State};9use jrsonnet_evaluator::{apply_tla, error::LocError, throw, ResultExt, State, Val};
1010
11#[cfg(feature = "mimalloc")]11#[cfg(feature = "mimalloc")]
12#[global_allocator]12#[global_allocator]
121}121}
122122
123fn main_real(s: &State, opts: Opts) -> Result<(), Error> {123fn main_real(s: &State, opts: Opts) -> Result<(), Error> {
124 let _guards = opts.general.configure(s)?;124 let (_stack_guard, tla, _gc_guard) = opts.general.configure(s)?;
125 opts.manifest.configure(s)?;125 let manifest_format = opts.manifest.configure(s)?;
126126
127 let input = opts.input.input.ok_or(Error::MissingInputArgument)?;127 let input = opts.input.input.ok_or(Error::MissingInputArgument)?;
128 let val = if opts.input.exec {128 let val = if opts.input.exec {
136 s.import(&input)?136 s.import(&input)?
137 };137 };
138138
139 let val = s.with_tla(val)?;139 let val = apply_tla(s.clone(), &tla, val)?;
140140
141 if let Some(multi) = opts.output.multi {141 if let Some(multi) = opts.output.multi {
142 if opts.output.create_output_dirs {142 if opts.output.create_output_dirs {
modifiedcrates/jrsonnet-cli/src/lib.rsdiffbeforeafterboth
71 misc: MiscOpts,71 misc: MiscOpts,
7272
73 #[clap(flatten)]73 #[clap(flatten)]
74 tla: TLAOpts,74 tla: TlaOpts,
75 #[clap(flatten)]75 #[clap(flatten)]
76 std: StdOpts,76 std: StdOpts,
7777
85impl ConfigureState for GeneralOpts {85impl ConfigureState for GeneralOpts {
86 type Guards = (86 type Guards = (
87 <MiscOpts as ConfigureState>::Guards,87 <MiscOpts as ConfigureState>::Guards,
88 <TlaOpts as ConfigureState>::Guards,
88 <GcOpts as ConfigureState>::Guards,89 <GcOpts as ConfigureState>::Guards,
89 );90 );
90 fn configure(&self, s: &State) -> Result<Self::Guards> {91 fn configure(&self, s: &State) -> Result<Self::Guards> {
91 // Configure trace first, because tla-code/ext-code can throw92 // Configure trace first, because tla-code/ext-code can throw
92 self.trace.configure(s)?;93 self.trace.configure(s)?;
93 let misc_guards = self.misc.configure(s)?;94 let misc_guards = self.misc.configure(s)?;
94 self.tla.configure(s)?;95 let tla_guards = self.tla.configure(s)?;
95 self.std.configure(s)?;96 self.std.configure(s)?;
96 let gc_guards = self.gc.configure(s)?;97 let gc_guards = self.gc.configure(s)?;
97 Ok((misc_guards, gc_guards))98 Ok((misc_guards, tla_guards, gc_guards))
98 }99 }
99}100}
100101
modifiedcrates/jrsonnet-cli/src/tla.rsdiffbeforeafterboth
1use clap::Parser;1use clap::Parser;
2use jrsonnet_evaluator::{error::Result, State};2use jrsonnet_evaluator::{
3 error::{Error, Result},
4 function::TlaArg,
5 gc::GcHashMap,
6 IStr, State,
7};
8use jrsonnet_parser::{ParserSettings, Source};
39
4use crate::{ConfigureState, ExtFile, ExtStr};10use crate::{ConfigureState, ExtFile, ExtStr};
511
6#[derive(Parser)]12#[derive(Parser)]
7#[clap(next_help_heading = "TOP LEVEL ARGUMENTS")]13#[clap(next_help_heading = "TOP LEVEL ARGUMENTS")]
8pub struct TLAOpts {14pub struct TlaOpts {
9 /// Add top level string argument.15 /// Add top level string argument.
10 /// Top level arguments will be passed to function before manifestification stage.16 /// Top level arguments will be passed to function before manifestification stage.
11 /// This is preferred to ExtVars method.17 /// This is preferred to ExtVars method.
25 #[clap(long, name = "name=tla code path", number_of_values = 1)]31 #[clap(long, name = "name=tla code path", number_of_values = 1)]
26 tla_code_file: Vec<ExtFile>,32 tla_code_file: Vec<ExtFile>,
27}33}
28impl ConfigureState for TLAOpts {34impl ConfigureState for TlaOpts {
29 type Guards = ();35 type Guards = GcHashMap<IStr, TlaArg>;
30 fn configure(&self, s: &State) -> Result<()> {36 fn configure(&self, _s: &State) -> Result<Self::Guards> {
37 let mut out = GcHashMap::new();
31 for tla in self.tla_str.iter() {38 for (name, value) in self
39 .tla_str
40 .iter()
32 s.add_tla_str((&tla.name as &str).into(), (&tla.value as &str).into());41 .map(|c| (&c.name, &c.value))
33 }
34 for tla in self.tla_str_file.iter() {42 .chain(self.tla_str_file.iter().map(|c| (&c.name, &c.value)))
35 s.add_tla_str((&tla.name as &str).into(), (&tla.value as &str).into())
36 }
37 for tla in self.tla_code.iter() {43 {
38 s.add_tla_code((&tla.name as &str).into(), &tla.value as &str)?;44 out.insert(name.into(), TlaArg::String(value.into()));
39 }45 }
40 for tla in self.tla_code_file.iter() {46 for (name, code) in self
47 .tla_code
48 .iter()
49 .map(|c| (&c.name, &c.value))
50 .chain(self.tla_code_file.iter().map(|c| (&c.name, &c.value)))
51 {
52 let source = Source::new_virtual(format!("<top-level-arg:{name}>").into(), code.into());
41 s.add_tla_code((&tla.name as &str).into(), &tla.value as &str)?;53 out.insert(
54 (&name as &str).into(),
55 TlaArg::Code(
56 jrsonnet_parser::parse(
57 &code,
58 &ParserSettings {
59 source: source.clone(),
60 },
61 )
62 .map_err(|e| Error::ImportSyntaxError {
63 path: source,
64 error: Box::new(e),
65 })?,
66 ),
67 );
42 }68 }
43 Ok(())69 Ok(out)
44 }70 }
45}71}
4672
modifiedcrates/jrsonnet-evaluator/src/function/arglike.rsdiffbeforeafterboth
1use std::collections::HashMap;1use hashbrown::HashMap;
2
3use jrsonnet_gcmodule::Trace;2use jrsonnet_gcmodule::Trace;
4use jrsonnet_interner::IStr;3use jrsonnet_interner::IStr;
5use jrsonnet_parser::{ArgsDesc, LocExpr};4use jrsonnet_parser::{ArgsDesc, LocExpr};
65
7use crate::{error::Result, evaluate, tb, typed::Typed, val::ThunkValue, Context, Thunk, Val};6use crate::{
7 error::Result, evaluate, gc::GcHashMap, tb, typed::Typed, val::ThunkValue, Context, Thunk, Val,
8};
89
9/// Marker for arguments, which can be evaluated with context set to None10/// Marker for arguments, which can be evaluated with context set to None
214}215}
215impl<A, S> OptionalContext for HashMap<IStr, A, S> where A: ArgLike + OptionalContext {}216impl<A, S> OptionalContext for HashMap<IStr, A, S> where A: ArgLike + OptionalContext {}
217
218impl<A: ArgLike> ArgsLike for GcHashMap<IStr, A> {
219 fn unnamed_len(&self) -> usize {
220 self.0.unnamed_len()
221 }
222
223 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 }
231
232 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 }
240
241 fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {
242 self.0.named_names(handler)
243 }
244}
216245
217macro_rules! impl_args_like {246macro_rules! impl_args_like {
218 ($count:expr; $($gen:ident)*) => {247 ($count:expr; $($gen:ident)*) => {
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
55mod obj;55mod obj;
56pub mod stack;56pub mod stack;
57pub mod stdlib;57pub mod stdlib;
58mod tla;
58pub mod trace;59pub mod trace;
59pub mod typed;60pub mod typed;
60pub mod val;61pub mod val;
81use jrsonnet_parser::*;82use jrsonnet_parser::*;
82pub use obj::*;83pub use obj::*;
83use stack::check_depth;84use stack::check_depth;
84use trace::{CompactFormat, TraceFormat};85pub use tla::apply_tla;
85pub use val::{ManifestFormat, Thunk, Val};86pub use val::{ManifestFormat, Thunk, Val};
8687
87/// Thunk without bound `super`/`this`88/// Thunk without bound `super`/`this`
143/// Dynamically reconfigurable evaluation settings144/// Dynamically reconfigurable evaluation settings
144#[derive(Trace)]145#[derive(Trace)]
145pub struct EvaluationSettings {146pub struct EvaluationSettings {
146 /// Limits amount of stack trace items preserved
147 pub max_trace: usize,
148 /// TLA vars
149 pub tla_vars: HashMap<IStr, TlaArg>,
150 /// Context initializer, which will be used for imports and everything147 /// Context initializer, which will be used for imports and everything
151 /// [`NoopContextInitializer`] is used by default, most likely you want to have `jrsonnet-stdlib`148 /// [`NoopContextInitializer`] is used by default, most likely you want to have `jrsonnet-stdlib`
152 pub context_initializer: TraceBox<dyn ContextInitializer>,149 pub context_initializer: TraceBox<dyn ContextInitializer>,
160impl Default for EvaluationSettings {157impl Default for EvaluationSettings {
161 fn default() -> Self {158 fn default() -> Self {
162 Self {159 Self {
163 max_trace: 20,
164 context_initializer: tb!(DummyContextInitializer),160 context_initializer: tb!(DummyContextInitializer),
165 tla_vars: HashMap::default(),
166 import_resolver: tb!(DummyImportResolver),161 import_resolver: tb!(DummyImportResolver),
167 manifest_format: ManifestFormat::Json {
168 padding: 4,
169 #[cfg(feature = "exp-preserve-order")]
170 preserve_order: false,
171 },
172 trace_format: tb!(CompactFormat {
173 padding: 4,
174 resolver: trace::PathResolver::Absolute,
175 }),
176 }162 }
177 }163 }
178}164}
406 f().with_description(frame_desc)392 f().with_description(frame_desc)
407 }393 }
408
409 /// # Panics
410 /// In case of formatting failure
411 pub fn stringify_err(&self, e: &LocError) -> String {
412 let mut out = String::new();
413 self.settings()
414 .trace_format
415 .write_trace(&mut out, self, e)
416 .unwrap();
417 out
418 }
419
420 pub fn manifest(&self, val: Val) -> Result<IStr> {
421 Self::push_description(
422 || "manifestification".to_string(),
423 || val.manifest(&self.manifest_format()),
424 )
425 }
426 pub fn manifest_multi(&self, val: Val) -> Result<Vec<(IStr, IStr)>> {
427 val.manifest_multi(&self.manifest_format())
428 }
429 pub fn manifest_stream(&self, val: Val) -> Result<Vec<IStr>> {
430 val.manifest_stream(&self.manifest_format())
431 }
432
433 /// If passed value is function then call with set TLA
434 pub fn with_tla(&self, val: Val) -> Result<Val> {
435 Ok(match val {
436 Val::Func(func) => State::push_description(
437 || "during TLA call".to_owned(),
438 || {
439 func.evaluate(
440 self.create_default_context(Source::new_virtual(
441 "<tla>".into(),
442 IStr::empty(),
443 )),
444 CallLocation::native(),
445 &self.settings().tla_vars,
446 true,
447 )
448 },
449 )?,
450 v => v,
451 })
452 }
453}394}
454395
455/// Internals396/// Internals
487428
488/// Settings utilities429/// Settings utilities
489impl State {430impl State {
490 pub fn add_tla(&self, name: IStr, value: Val) {
491 self.settings_mut()
492 .tla_vars
493 .insert(name, TlaArg::Val(value));
494 }
495 pub fn add_tla_str(&self, name: IStr, value: IStr) {
496 self.settings_mut()
497 .tla_vars
498 .insert(name, TlaArg::String(value));
499 }
500 pub fn add_tla_code(&self, name: IStr, code: &str) -> Result<()> {
501 let source_name = format!("<top-level-arg:{name}>");
502 let source = Source::new_virtual(source_name.into(), code.into());
503 let parsed = jrsonnet_parser::parse(
504 code,
505 &ParserSettings {
506 file_name: source.clone(),
507 },
508 )
509 .map_err(|e| ImportSyntaxError {
510 path: source,
511 error: Box::new(e),
512 })?;
513 self.settings_mut()
514 .tla_vars
515 .insert(name, TlaArg::Code(parsed));
516 Ok(())
517 }
518
519 // Only panics in case of [`ImportResolver`] contract violation431 // Only panics in case of [`ImportResolver`] contract violation
520 #[allow(clippy::missing_panics_doc)]432 #[allow(clippy::missing_panics_doc)]
addedcrates/jrsonnet-evaluator/src/tla.rsdiffbeforeafterboth

no changes