Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: use State::import(..) for file-sourced TLAs #135

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 14 additions & 14 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion cmds/jrsonnet/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ fn main_real(s: &State, opts: Opts) -> Result<(), Error> {
s.import(&input)?
};

let tla = opts.tla.tla_opts()?;
let tla = opts.tla.into_args_in(s)?;
#[allow(unused_mut)]
let mut val = apply_tla(s.clone(), &tla, val)?;

Expand Down
97 changes: 79 additions & 18 deletions crates/jrsonnet-cli/src/tla.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,22 @@
use std::{
ffi::{OsStr, OsString},
os::unix::ffi::OsStrExt,
path::{Path, PathBuf},
};

use clap::Parser;
use jrsonnet_evaluator::{
bail,
error::{ErrorKind, Result},
function::TlaArg,
gc::GcHashMap,
IStr,
val::ThunkValue,
IStr, State, Thunk, Val,
};
use jrsonnet_gcmodule::Trace;
use jrsonnet_parser::{ParserSettings, Source};

use crate::{ExtFile, ExtStr};
use crate::ExtStr;

#[derive(Parser)]
#[clap(next_help_heading = "TOP LEVEL ARGUMENTS")]
Expand All @@ -21,36 +30,36 @@ pub struct TlaOpts {
/// Read top level argument string from file.
/// See also `--tla-str`
#[clap(long, name = "name=tla path", number_of_values = 1)]
tla_str_file: Vec<ExtFile>,
tla_str_file: Vec<OsString>,
/// Add top level argument from code.
/// See also `--tla-str`
#[clap(long, name = "name[=tla source]", number_of_values = 1)]
tla_code: Vec<ExtStr>,
/// Read top level argument code from file.
/// See also `--tla-str`
#[clap(long, name = "name=tla code path", number_of_values = 1)]
tla_code_file: Vec<ExtFile>,
tla_code_file: Vec<OsString>,
}
impl TlaOpts {
pub fn tla_opts(&self) -> Result<GcHashMap<IStr, TlaArg>> {
pub fn into_args_in(self, state: &State) -> Result<GcHashMap<IStr, TlaArg>> {
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)))
{
for (name, value) in self.tla_str.iter().map(|c| (&c.name, &c.value)) {
out.insert(name.into(), TlaArg::String(value.into()));
}
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)))
{
for file in self.tla_str_file {
let (key, path) = parse_named_tla_path(&file)?;
out.insert(
key.into(),
TlaArg::Lazy(Thunk::new(ImportStrThunk {
state: state.clone(),
path,
})),
);
}
for (name, code) in self.tla_code.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(),
name.into(),
TlaArg::Code(
jrsonnet_parser::parse(
code,
Expand All @@ -65,6 +74,58 @@ impl TlaOpts {
),
);
}
for file in self.tla_code_file {
let (key, path) = parse_named_tla_path(&file)?;
out.insert(
key.into(),
TlaArg::Lazy(Thunk::new(ImportCodeThunk {
state: state.clone(),
path,
})),
);
}
Ok(out)
}
}

fn parse_named_tla_path(raw: &OsString) -> Result<(&str, PathBuf)> {
let mut parts = raw.as_bytes().splitn(2, |&byte| byte == b'=');
let Some(key) = parts.next() else {
bail!("No TLA key was specified");
};

let Ok(key) = std::str::from_utf8(key) else {
bail!("Invalid TLA map");
};
Ok(if let Some(value) = parts.next() {
(key, Path::new(OsStr::from_bytes(value)).to_owned())
} else {
(key, std::env::var_os(key).unwrap_or_default().into())
})
}

#[derive(Trace)]
struct ImportStrThunk {
path: PathBuf,
state: State,
}
impl ThunkValue for ImportStrThunk {
type Output = Val;

fn get(self: Box<Self>) -> Result<Self::Output> {
self.state.import_str(self.path).map(|s| Val::Str(s.into()))
}
}

#[derive(Trace)]
struct ImportCodeThunk {
path: PathBuf,
state: State,
}
impl ThunkValue for ImportCodeThunk {
type Output = Val;

fn get(self: Box<Self>) -> Result<Self::Output> {
self.state.import(self.path)
}
}
2 changes: 1 addition & 1 deletion crates/jrsonnet-evaluator/src/evaluate/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@
specs: &[CompSpec],
callback: &mut impl FnMut(Context) -> Result<()>,
) -> Result<()> {
match specs.get(0) {

Check warning on line 92 in crates/jrsonnet-evaluator/src/evaluate/mod.rs

View workflow job for this annotation

GitHub Actions / clippy

accessing first element with `specs.get(0)`

warning: accessing first element with `specs.get(0)` --> crates/jrsonnet-evaluator/src/evaluate/mod.rs:92:8 | 92 | match specs.get(0) { | ^^^^^^^^^^^^ help: try: `specs.first()` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#get_first note: the lint level is defined here --> crates/jrsonnet-evaluator/src/lib.rs:5:2 | 5 | clippy::all, | ^^^^^^^^^^^ = note: `#[warn(clippy::get_first)]` implied by `#[warn(clippy::all)]`
None => callback(ctx)?,
Some(CompSpec::IfSpec(IfSpecData(cond))) => {
if bool::from_untyped(evaluate(ctx.clone(), cond)?)? {
Expand Down Expand Up @@ -667,7 +667,7 @@
IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?)?
}
i @ (Import(path) | ImportStr(path) | ImportBin(path)) => {
let Expr::Str(path) = &*path.0 else {
let Str(path) = &*path.0 else {
bail!("computed imports are not supported")
};
let tmp = loc.clone().0;
Expand Down
18 changes: 13 additions & 5 deletions crates/jrsonnet-evaluator/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
//! jsonnet interpreter implementation
#![cfg_attr(feature = "nightly", feature(thread_local, type_alias_impl_trait))]
#![deny(unsafe_op_in_unsafe_fn)]
#![warn(
clippy::all,
clippy::nursery,
clippy::pedantic,
// missing_docs,
elided_lifetimes_in_paths,
explicit_outlives_requirements,
noop_method_call,

Check warning on line 11 in crates/jrsonnet-evaluator/src/lib.rs

View workflow job for this annotation

GitHub Actions / clippy

pub(crate) import inside private module

warning: pub(crate) import inside private module --> crates/jrsonnet-evaluator/src/lib.rs:1:1 | 1 | / //! jsonnet interpreter implementation 2 | | #![cfg_attr(feature = "nightly", feature(thread_local, type_alias_impl_trait))] 3 | | #![deny(unsafe_op_in_unsafe_fn)] 4 | | #![warn( ... | 10 | | explicit_outlives_requirements, 11 | | noop_method_call, | |_ | ::: crates/jrsonnet-evaluator/src/arr/mod.rs:11:1 | 11 | pub(crate) use spec::*; | ---------- help: consider using: `pub` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#redundant_pub_crate = note: `#[warn(clippy::redundant_pub_crate)]` implied by `#[warn(clippy::nursery)]`
single_use_lifetimes,
variant_size_differences,
rustdoc::all
Expand Down Expand Up @@ -346,7 +346,7 @@
let file_name = Source::new(path.clone(), code.clone());
if file.parsed.is_none() {
file.parsed = Some(
jrsonnet_parser::parse(
parse(
&code,
&ParserSettings {
source: file_name.clone(),
Expand Down Expand Up @@ -393,6 +393,10 @@
let resolved = self.resolve(path)?;
self.import_resolved(resolved)
}
pub fn import_str(&self, path: impl AsRef<Path>) -> Result<IStr> {
let resolved = self.resolve(path)?;
self.import_resolved_str(resolved)
}

/// Creates context with all passed global variables
pub fn create_default_context(&self, source: Source) -> Context {
Expand Down Expand Up @@ -518,7 +522,7 @@
pub fn evaluate_snippet(&self, name: impl Into<IStr>, code: impl Into<IStr>) -> Result<Val> {
let code = code.into();
let source = Source::new_virtual(name.into(), code.clone());
let parsed = jrsonnet_parser::parse(
let parsed = parse(
&code,
&ParserSettings {
source: source.clone(),
Expand All @@ -539,7 +543,7 @@
) -> Result<Val> {
let code = code.into();
let source = Source::new_virtual(name.into(), code.clone());
let parsed = jrsonnet_parser::parse(
let parsed = parse(
&code,
&ParserSettings {
source: source.clone(),
Expand All @@ -558,13 +562,17 @@

/// Settings utilities
impl State {
// Only panics in case of [`ImportResolver`] contract violation
// # Panics
//
// If [`ImportResolver`] contract is violated.
#[allow(clippy::missing_panics_doc)]
pub fn resolve_from(&self, from: &SourcePath, path: &str) -> Result<SourcePath> {
self.import_resolver().resolve_from(from, path.as_ref())
}

// Only panics in case of [`ImportResolver`] contract violation
// # Panics
//
// If [`ImportResolver`] contract is violated.
#[allow(clippy::missing_panics_doc)]
pub fn resolve(&self, path: impl AsRef<Path>) -> Result<SourcePath> {
self.import_resolver().resolve(path.as_ref())
Expand Down
2 changes: 0 additions & 2 deletions crates/jrsonnet-stdlib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -352,8 +352,6 @@ impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {
}
#[cfg(feature = "legacy-this-file")]
fn populate(&self, source: Source, builder: &mut ContextBuilder) {
use jrsonnet_evaluator::val::StrValue;

let mut std = ObjValueBuilder::new();
std.with_super(self.stdlib_obj.clone());
std.field("thisFile")
Expand Down
Loading