difftreelog
style enforce import style
in: master
38 files changed
.rustfmt.tomldiffbeforeafterboth--- a/.rustfmt.toml
+++ b/.rustfmt.toml
@@ -1 +1,3 @@
hard_tabs = true
+imports_granularity = "crate"
+group_imports = "stdexternalcrate"
bindings/jsonnet/src/import.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/import.rs
+++ b/bindings/jsonnet/src/import.rs
@@ -1,9 +1,5 @@
//! Import resolution manipulation utilities
-use jrsonnet_evaluator::{
- error::{Error::*, Result},
- throw, EvaluationState, ImportResolver,
-};
use std::{
any::Any,
cell::RefCell,
@@ -17,6 +13,11 @@
rc::Rc,
};
+use jrsonnet_evaluator::{
+ error::{Error::*, Result},
+ throw, EvaluationState, ImportResolver,
+};
+
pub type JsonnetImportCallback = unsafe extern "C" fn(
ctx: *mut c_void,
base: *const c_char,
bindings/jsonnet/src/interop.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/interop.rs
+++ b/bindings/jsonnet/src/interop.rs
@@ -1,12 +1,14 @@
//! Jrsonnet specific additional binding helpers
-use crate::{import::jsonnet_import_callback, native::jsonnet_native_callback};
-use jrsonnet_evaluator::{EvaluationState, Val};
use std::{
ffi::c_void,
os::raw::{c_char, c_int},
};
+use jrsonnet_evaluator::{EvaluationState, Val};
+
+use crate::{import::jsonnet_import_callback, native::jsonnet_native_callback};
+
extern "C" {
pub fn _jrsonnet_static_import_callback(
ctx: *mut c_void,
bindings/jsonnet/src/lib.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -8,8 +8,6 @@
pub mod val_modify;
pub mod vars_tlas;
-use import::NativeImportResolver;
-use jrsonnet_evaluator::{EvaluationState, IStr, ManifestFormat, Val};
use std::{
alloc::Layout,
ffi::{CStr, CString},
@@ -17,6 +15,9 @@
path::PathBuf,
};
+use import::NativeImportResolver;
+use jrsonnet_evaluator::{EvaluationState, IStr, ManifestFormat, Val};
+
/// WASM stub
#[cfg(target_arch = "wasm32")]
#[no_mangle]
bindings/jsonnet/src/native.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/native.rs
+++ b/bindings/jsonnet/src/native.rs
@@ -1,3 +1,11 @@
+use std::{
+ convert::TryFrom,
+ ffi::{c_void, CStr},
+ os::raw::{c_char, c_int},
+ path::Path,
+ rc::Rc,
+};
+
use gcmodule::Cc;
use jrsonnet_evaluator::{
error::{Error, LocError},
@@ -5,13 +13,6 @@
gc::TraceBox,
native::{NativeCallback, NativeCallbackHandler},
EvaluationState, IStr, Val,
-};
-use std::{
- convert::TryFrom,
- ffi::{c_void, CStr},
- os::raw::{c_char, c_int},
- path::Path,
- rc::Rc,
};
type JsonnetNativeCallback = unsafe extern "C" fn(
bindings/jsonnet/src/val_extract.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/val_extract.rs
+++ b/bindings/jsonnet/src/val_extract.rs
@@ -1,12 +1,12 @@
//! Extract values from VM
-use jrsonnet_evaluator::{EvaluationState, Val};
-
use std::{
ffi::CString,
os::raw::{c_char, c_double, c_int},
};
+use jrsonnet_evaluator::{EvaluationState, Val};
+
#[no_mangle]
pub extern "C" fn jsonnet_json_extract_string(_vm: &EvaluationState, v: &Val) -> *mut c_char {
match v {
bindings/jsonnet/src/val_make.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/val_make.rs
+++ b/bindings/jsonnet/src/val_make.rs
@@ -1,12 +1,13 @@
//! Create values in VM
-use gcmodule::Cc;
-use jrsonnet_evaluator::{ArrValue, EvaluationState, ObjValue, Val};
use std::{
ffi::CStr,
os::raw::{c_char, c_double, c_int},
};
+use gcmodule::Cc;
+use jrsonnet_evaluator::{val::ArrValue, EvaluationState, ObjValue, Val};
+
/// # Safety
///
/// This function is safe, if received v is a pointer to normal C string
bindings/jsonnet/src/val_modify.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/val_modify.rs
+++ b/bindings/jsonnet/src/val_modify.rs
@@ -2,10 +2,11 @@
//! Only tested with variables, which haven't altered by code before appearing here
//! In jrsonnet every value is immutable, and this code is probally broken
+use std::{ffi::CStr, os::raw::c_char};
+
use gcmodule::Cc;
-use jrsonnet_evaluator::{ArrValue, EvaluationState, LazyBinding, LazyVal, ObjMember, Val};
+use jrsonnet_evaluator::{val::ArrValue, EvaluationState, LazyBinding, LazyVal, ObjMember, Val};
use jrsonnet_parser::Visibility;
-use std::{ffi::CStr, os::raw::c_char};
/// # Safety
///
bindings/jsonnet/src/vars_tlas.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/vars_tlas.rs
+++ b/bindings/jsonnet/src/vars_tlas.rs
@@ -1,8 +1,9 @@
//! Manipulate external variables and top level arguments
-use jrsonnet_evaluator::EvaluationState;
use std::{ffi::CStr, os::raw::c_char};
+use jrsonnet_evaluator::EvaluationState;
+
/// # Safety
#[no_mangle]
pub unsafe extern "C" fn jsonnet_ext_var(
cmds/jrsonnet/src/main.rsdiffbeforeafterboth--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -1,13 +1,13 @@
+use std::{
+ fs::{create_dir_all, File},
+ io::{Read, Write},
+ path::PathBuf,
+};
+
use clap::{AppSettings, IntoApp, Parser};
use clap_complete::Shell;
use jrsonnet_cli::{ConfigureState, GcOpts, GeneralOpts, InputOpts, ManifestOpts, OutputOpts};
use jrsonnet_evaluator::{error::LocError, EvaluationState};
-use std::{
- fs::{create_dir_all, File},
- io::Read,
- io::Write,
- path::PathBuf,
-};
#[cfg(feature = "mimalloc")]
#[global_allocator]
crates/jrsonnet-cli/src/ext.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/ext.rs
+++ b/crates/jrsonnet-cli/src/ext.rs
@@ -1,8 +1,10 @@
-use crate::ConfigureState;
+use std::{fs::read_to_string, str::FromStr};
+
use clap::Parser;
use jrsonnet_evaluator::{error::Result, EvaluationState};
-use std::{fs::read_to_string, str::FromStr};
+use crate::ConfigureState;
+
#[derive(Clone)]
pub struct ExtStr {
pub name: String,
crates/jrsonnet-cli/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/lib.rs
+++ b/crates/jrsonnet-cli/src/lib.rs
@@ -3,14 +3,14 @@
mod tla;
mod trace;
+use std::{env, path::PathBuf};
+
+use clap::Parser;
pub use ext::*;
+use jrsonnet_evaluator::{error::Result, EvaluationState, FileImportResolver};
pub use manifest::*;
pub use tla::*;
pub use trace::*;
-
-use clap::Parser;
-use jrsonnet_evaluator::{error::Result, EvaluationState, FileImportResolver};
-use std::{env, path::PathBuf};
pub trait ConfigureState {
fn configure(&self, state: &EvaluationState) -> Result<()>;
crates/jrsonnet-cli/src/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/manifest.rs
+++ b/crates/jrsonnet-cli/src/manifest.rs
@@ -1,8 +1,10 @@
-use crate::ConfigureState;
+use std::{path::PathBuf, str::FromStr};
+
use clap::Parser;
use jrsonnet_evaluator::{error::Result, EvaluationState, ManifestFormat};
-use std::{path::PathBuf, str::FromStr};
+use crate::ConfigureState;
+
pub enum ManifestFormatName {
/// Expect string as output, and write them directly
String,
crates/jrsonnet-cli/src/tla.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/tla.rs
+++ b/crates/jrsonnet-cli/src/tla.rs
@@ -1,7 +1,8 @@
-use crate::{ConfigureState, ExtFile, ExtStr};
use clap::Parser;
use jrsonnet_evaluator::{error::Result, EvaluationState};
+use crate::{ConfigureState, ExtFile, ExtStr};
+
#[derive(Parser)]
#[clap(next_help_heading = "TOP LEVEL ARGUMENTS")]
pub struct TLAOpts {
crates/jrsonnet-cli/src/trace.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/trace.rs
+++ b/crates/jrsonnet-cli/src/trace.rs
@@ -1,12 +1,14 @@
-use crate::ConfigureState;
+use std::str::FromStr;
+
use clap::Parser;
use jrsonnet_evaluator::{
error::Result,
trace::{CompactFormat, ExplainingFormat, PathResolver},
EvaluationState,
};
-use std::str::FromStr;
+use crate::ConfigureState;
+
#[derive(PartialEq)]
pub enum TraceFormatName {
Compact,
crates/jrsonnet-evaluator/build.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/build.rs
+++ b/crates/jrsonnet-evaluator/build.rs
@@ -1,6 +1,3 @@
-use bincode::serialize;
-use jrsonnet_parser::{parse, ParserSettings};
-use jrsonnet_stdlib::STDLIB_STR;
use std::{
env,
fs::File,
@@ -8,6 +5,10 @@
path::{Path, PathBuf},
};
+use bincode::serialize;
+use jrsonnet_parser::{parse, ParserSettings};
+use jrsonnet_stdlib::STDLIB_STR;
+
fn main() {
let parsed = parse(
STDLIB_STR,
crates/jrsonnet-evaluator/src/builtin/format.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/format.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/format.rs
@@ -1,13 +1,15 @@
//! faster std.format impl
#![allow(clippy::too_many_arguments)]
-use crate::{error::Error::*, throw, LocError, ObjValue, Result, Val};
+use std::convert::TryFrom;
+
use gcmodule::Trace;
use jrsonnet_interner::IStr;
use jrsonnet_types::ValType;
-use std::convert::TryFrom;
use thiserror::Error;
+use crate::{error::Error::*, throw, LocError, ObjValue, Result, Val};
+
#[derive(Debug, Clone, Error, Trace)]
pub enum FormatError {
#[error("truncated format code")]
crates/jrsonnet-evaluator/src/builtin/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/manifest.rs
@@ -1,7 +1,7 @@
-use crate::error::Error::*;
-use crate::error::Result;
-use crate::push_description_frame;
-use crate::{throw, Val};
+use crate::{
+ error::{Error::*, Result},
+ push_description_frame, throw, Val,
+};
#[derive(PartialEq, Clone, Copy)]
pub enum ManifestType {
crates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -1,23 +1,25 @@
-use crate::function::{CallLocation, StaticBuiltin};
-use crate::typed::{Any, Bytes, PositiveF64, VecVal, M1};
-use crate::{
- builtin::manifest::{manifest_yaml_ex, ManifestYamlOptions},
- equals,
- error::{Error::*, Result},
- operator::evaluate_mod_op,
- primitive_equals, push_frame, throw,
- typed::{Either2, Either4},
- with_state, ArrValue, FuncVal, IndexableVal, Val,
+use std::{
+ collections::HashMap,
+ convert::{TryFrom, TryInto},
};
-use crate::{Either, ObjValue};
+
use format::{format_arr, format_obj};
use gcmodule::Cc;
use jrsonnet_interner::IStr;
use serde::Deserialize;
use serde_yaml::DeserializingQuirks;
-use std::collections::HashMap;
-use std::convert::{TryFrom, TryInto};
+use crate::{
+ builtin::manifest::{manifest_yaml_ex, ManifestYamlOptions},
+ error::{Error::*, Result},
+ function::{CallLocation, StaticBuiltin},
+ operator::evaluate_mod_op,
+ push_frame, throw,
+ typed::{Any, BoundedUsize, Bytes, Either2, Either4, PositiveF64, VecVal, M1},
+ val::{equals, primitive_equals, ArrValue, FuncVal, IndexableVal, Slice},
+ with_state, Either, ObjValue, Val,
+};
+
pub mod stdlib;
pub use stdlib::*;
@@ -58,12 +60,12 @@
}
Ok(Val::Str(
- (s.chars()
- .skip(index)
- .take(end - index)
- .step_by(step)
- .collect::<String>())
- .into(),
+ (s.chars()
+ .skip(index)
+ .take(end - index)
+ .step_by(step)
+ .collect::<String>())
+ .into(),
))
}
IndexableVal::Arr(arr) => {
crates/jrsonnet-evaluator/src/builtin/sort.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/sort.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/sort.rs
@@ -1,10 +1,12 @@
+use gcmodule::{Cc, Trace};
+
use crate::{
error::{Error, LocError, Result},
throw,
typed::Any,
- FuncVal, Val,
+ val::FuncVal,
+ Val,
};
-use gcmodule::{Cc, Trace};
#[derive(Debug, Clone, thiserror::Error, Trace)]
pub enum SortError {
crates/jrsonnet-evaluator/src/builtin/stdlib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/stdlib.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/stdlib.rs
@@ -1,6 +1,7 @@
-use jrsonnet_parser::{LocExpr, ParserSettings};
use std::path::PathBuf;
+use jrsonnet_parser::{LocExpr, ParserSettings};
+
thread_local! {
/// To avoid parsing again when issued from the same thread
#[allow(unreachable_code)]
crates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -1,12 +1,12 @@
-use crate::cc_ptr_eq;
-use crate::gc::GcHashMap;
+use std::fmt::Debug;
+
+use gcmodule::{Cc, Trace};
+use jrsonnet_interner::IStr;
+
use crate::{
- error::Error::*, map::LayeredHashMap, FutureWrapper, LazyBinding, LazyVal, ObjValue, Result,
- Val,
+ cc_ptr_eq, error::Error::*, gc::GcHashMap, map::LayeredHashMap, FutureWrapper, LazyBinding,
+ LazyVal, ObjValue, Result, Val,
};
-use gcmodule::{Cc, Trace};
-use jrsonnet_interner::IStr;
-use std::fmt::Debug;
#[derive(Clone, Trace)]
pub struct ContextCreator(pub Context, pub FutureWrapper<GcHashMap<IStr, LazyBinding>>);
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -1,16 +1,18 @@
-use crate::{
- builtin::{format::FormatError, sort::SortError},
- typed::TypeLocError,
+use std::{
+ path::{Path, PathBuf},
+ rc::Rc,
};
+
use gcmodule::Trace;
use jrsonnet_interner::IStr;
use jrsonnet_parser::{BinaryOpType, ExprLocation, UnaryOpType};
use jrsonnet_types::ValType;
-use std::{
- path::{Path, PathBuf},
- rc::Rc,
+use thiserror::Error;
+
+use crate::{
+ builtin::{format::FormatError, sort::SortError},
+ typed::TypeLocError,
};
-use thiserror::Error;
#[derive(Error, Debug, Clone, Trace)]
pub enum Error {
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -1,15 +1,5 @@
use std::convert::TryFrom;
-use crate::{
- builtin::{std_slice, BUILTINS},
- error::Error::*,
- evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},
- function::CallLocation,
- gc::TraceBox,
- push_frame, throw, with_state, ArrValue, Bindable, Context, ContextCreator, FuncDesc, FuncVal,
- FutureWrapper, GcHashMap, LazyBinding, LazyVal, LazyValValue, ObjValue, ObjValueBuilder,
- ObjectAssertion, Result, Val,
-};
use gcmodule::{Cc, Trace};
use jrsonnet_interner::IStr;
use jrsonnet_parser::{
@@ -17,6 +7,19 @@
LiteralType, LocExpr, Member, ObjBody, ParamsDesc,
};
use jrsonnet_types::ValType;
+
+use crate::{
+ builtin::{std_slice, BUILTINS},
+ error::Error::*,
+ evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},
+ function::CallLocation,
+ gc::TraceBox,
+ push_frame, throw,
+ typed::BoundedUsize,
+ val::{ArrValue, FuncDesc, FuncVal, LazyValValue},
+ with_state, Bindable, Context, ContextCreator, FutureWrapper, GcHashMap, LazyBinding, LazyVal,
+ ObjValue, ObjValueBuilder, ObjectAssertion, Result, Val,
+};
pub mod operator;
pub fn evaluate_binding_in_future(
crates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -1,10 +1,11 @@
use std::convert::TryInto;
-use crate::builtin::std_format;
-use crate::{equals, evaluate, Context, Val};
-use crate::{error::Error::*, throw, Result};
use jrsonnet_parser::{BinaryOpType, LocExpr, UnaryOpType};
+use crate::{
+ builtin::std_format, error::Error::*, evaluate, throw, val::equals, Context, Result, Val,
+};
+
pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {
use UnaryOpType::*;
use Val::*;
crates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth1use crate::{2 error::{Error::*, LocError},3 evaluate, evaluate_named,4 gc::TraceBox,5 throw,6 typed::Typed,7 Context, FutureWrapper, GcHashMap, LazyVal, LazyValValue, Result, Val,8};9use gcmodule::Trace;10use jrsonnet_interner::IStr;11pub use jrsonnet_macros::builtin;12use jrsonnet_parser::{ArgsDesc, ExprLocation, LocExpr, ParamsDesc};13use std::{borrow::Cow, collections::HashMap, convert::TryFrom};1415#[derive(Clone, Copy)]16pub struct CallLocation<'l>(pub Option<&'l ExprLocation>);17impl<'l> CallLocation<'l> {18 pub const fn new(loc: &'l ExprLocation) -> Self {19 Self(Some(loc))20 }21}22impl CallLocation<'static> {23 pub const fn native() -> Self {24 Self(None)25 }26}2728#[derive(Trace)]29struct EvaluateLazyVal {30 context: Context,31 expr: LocExpr,32}33impl LazyValValue for EvaluateLazyVal {34 fn get(self: Box<Self>) -> Result<Val> {35 evaluate(self.context, &self.expr)36 }37}3839#[derive(Trace)]40struct EvaluateNamedLazyVal {41 future_context: FutureWrapper<Context>,42 name: IStr,43 value: LocExpr,44}45impl LazyValValue for EvaluateNamedLazyVal {46 fn get(self: Box<Self>) -> Result<Val> {47 evaluate_named(self.future_context.unwrap(), &self.value, self.name)48 }49}5051pub trait ArgLike {52 fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<LazyVal>;53}54impl ArgLike for &LocExpr {55 fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<LazyVal> {56 Ok(if tailstrict {57 LazyVal::new_resolved(evaluate(ctx, self)?)58 } else {59 LazyVal::new(TraceBox(Box::new(EvaluateLazyVal {60 context: ctx,61 expr: (*self).clone(),62 })))63 })64 }65}66impl<T> ArgLike for T67where68 T: Typed + Clone,69 Val: TryFrom<T, Error = LocError>,70{71 fn evaluate_arg(&self, _ctx: Context, _tailstrict: bool) -> Result<LazyVal> {72 let val: Val = Val::try_from(self.clone())?;73 Ok(LazyVal::new_resolved(val))74 }75}76pub enum TlaArg {77 String(IStr),78 Code(LocExpr),79 Val(Val),80}81impl ArgLike for TlaArg {82 fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<LazyVal> {83 match self {84 TlaArg::String(s) => Ok(LazyVal::new_resolved(Val::Str(s.clone()))),85 TlaArg::Code(code) => Ok(if tailstrict {86 LazyVal::new_resolved(evaluate(ctx, code)?)87 } else {88 LazyVal::new(TraceBox(Box::new(EvaluateLazyVal {89 context: ctx,90 expr: code.clone(),91 })))92 }),93 TlaArg::Val(val) => Ok(LazyVal::new_resolved(val.clone())),94 }95 }96}9798pub trait ArgsLike {99 fn unnamed_len(&self) -> usize;100 fn unnamed_iter(101 &self,102 ctx: Context,103 tailstrict: bool,104 handler: &mut dyn FnMut(usize, LazyVal) -> Result<()>,105 ) -> Result<()>;106 fn named_iter(107 &self,108 ctx: Context,109 tailstrict: bool,110 handler: &mut dyn FnMut(&IStr, LazyVal) -> Result<()>,111 ) -> Result<()>;112 fn named_names(&self, handler: &mut dyn FnMut(&IStr));113}114115impl ArgsLike for ArgsDesc {116 fn unnamed_len(&self) -> usize {117 self.unnamed.len()118 }119120 fn unnamed_iter(121 &self,122 ctx: Context,123 tailstrict: bool,124 handler: &mut dyn FnMut(usize, LazyVal) -> Result<()>,125 ) -> Result<()> {126 for (id, arg) in self.unnamed.iter().enumerate() {127 handler(128 id,129 if tailstrict {130 LazyVal::new_resolved(evaluate(ctx.clone(), arg)?)131 } else {132 LazyVal::new(TraceBox(Box::new(EvaluateLazyVal {133 context: ctx.clone(),134 expr: arg.clone(),135 })))136 },137 )?;138 }139 Ok(())140 }141142 fn named_iter(143 &self,144 ctx: Context,145 tailstrict: bool,146 handler: &mut dyn FnMut(&IStr, LazyVal) -> Result<()>,147 ) -> Result<()> {148 for (name, arg) in self.named.iter() {149 handler(150 name,151 if tailstrict {152 LazyVal::new_resolved(evaluate(ctx.clone(), arg)?)153 } else {154 LazyVal::new(TraceBox(Box::new(EvaluateLazyVal {155 context: ctx.clone(),156 expr: arg.clone(),157 })))158 },159 )?;160 }161 Ok(())162 }163164 fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {165 for (name, _) in self.named.iter() {166 handler(name)167 }168 }169}170171impl<A: ArgLike> ArgsLike for [(IStr, A)] {172 fn unnamed_len(&self) -> usize {173 0174 }175176 fn unnamed_iter(177 &self,178 _ctx: Context,179 _tailstrict: bool,180 _handler: &mut dyn FnMut(usize, LazyVal) -> Result<()>,181 ) -> Result<()> {182 Ok(())183 }184185 fn named_iter(186 &self,187 ctx: Context,188 tailstrict: bool,189 handler: &mut dyn FnMut(&IStr, LazyVal) -> Result<()>,190 ) -> Result<()> {191 for (name, val) in self.iter() {192 handler(name, val.evaluate_arg(ctx.clone(), tailstrict)?)?;193 }194 Ok(())195 }196197 fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {198 for (name, _) in self.iter() {199 handler(name);200 }201 }202}203204impl<A: ArgLike> ArgsLike for HashMap<IStr, A> {205 fn unnamed_len(&self) -> usize {206 0207 }208209 fn unnamed_iter(210 &self,211 _ctx: Context,212 _tailstrict: bool,213 _handler: &mut dyn FnMut(usize, LazyVal) -> Result<()>,214 ) -> Result<()> {215 Ok(())216 }217218 fn named_iter(219 &self,220 ctx: Context,221 tailstrict: bool,222 handler: &mut dyn FnMut(&IStr, LazyVal) -> Result<()>,223 ) -> Result<()> {224 for (name, value) in self.iter() {225 handler(name, value.evaluate_arg(ctx.clone(), tailstrict)?)?;226 }227 Ok(())228 }229230 fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {231 for (name, _) in self.iter() {232 handler(name);233 }234 }235}236237impl<A: ArgLike> ArgsLike for [A] {238 fn unnamed_len(&self) -> usize {239 self.len()240 }241242 fn unnamed_iter(243 &self,244 ctx: Context,245 tailstrict: bool,246 handler: &mut dyn FnMut(usize, LazyVal) -> Result<()>,247 ) -> Result<()> {248 for (i, arg) in self.iter().enumerate() {249 handler(i, arg.evaluate_arg(ctx.clone(), tailstrict)?)?;250 }251 Ok(())252 }253254 fn named_iter(255 &self,256 _ctx: Context,257 _tailstrict: bool,258 _handler: &mut dyn FnMut(&IStr, LazyVal) -> Result<()>,259 ) -> Result<()> {260 Ok(())261 }262263 fn named_names(&self, _handler: &mut dyn FnMut(&IStr)) {}264}265impl<A: ArgLike> ArgsLike for &[A] {266 fn unnamed_len(&self) -> usize {267 (*self).unnamed_len()268 }269270 fn unnamed_iter(271 &self,272 ctx: Context,273 tailstrict: bool,274 handler: &mut dyn FnMut(usize, LazyVal) -> Result<()>,275 ) -> Result<()> {276 (*self).unnamed_iter(ctx, tailstrict, handler)277 }278279 fn named_iter(280 &self,281 ctx: Context,282 tailstrict: bool,283 handler: &mut dyn FnMut(&IStr, LazyVal) -> Result<()>,284 ) -> Result<()> {285 (*self).named_iter(ctx, tailstrict, handler)286 }287288 fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {289 (*self).named_names(handler)290 }291}292293/// Creates correct [context](Context) for function body evaluation returning error on invalid call.294///295/// ## Parameters296/// * `ctx`: used for passed argument expressions' execution and for body execution (if `body_ctx` is not set)297/// * `body_ctx`: used for default parameter values' execution and for body execution (if set)298/// * `params`: function parameters' definition299/// * `args`: passed function arguments300/// * `tailstrict`: if set to `true` function arguments are eagerly executed, otherwise - lazily301pub fn parse_function_call(302 ctx: Context,303 body_ctx: Context,304 params: &ParamsDesc,305 args: &dyn ArgsLike,306 tailstrict: bool,307) -> Result<Context> {308 let mut passed_args = GcHashMap::with_capacity(params.len());309 if args.unnamed_len() > params.len() {310 throw!(TooManyArgsFunctionHas(params.len()))311 }312313 let mut filled_args = 0;314315 args.unnamed_iter(ctx.clone(), tailstrict, &mut |id, arg| {316 let name = params[id].0.clone();317 passed_args.insert(name, arg);318 filled_args += 1;319 Ok(())320 })?;321322 args.named_iter(ctx, tailstrict, &mut |name, value| {323 // FIXME: O(n) for arg existence check324 if !params.iter().any(|p| &p.0 == name) {325 throw!(UnknownFunctionParameter((name as &str).to_owned()));326 }327 if passed_args.insert(name.clone(), value).is_some() {328 throw!(BindingParameterASecondTime(name.clone()));329 }330 filled_args += 1;331 Ok(())332 })?;333334 if filled_args < params.len() {335 // Some args are unset, but maybe we have defaults for them336 // Default values should be created in newly created context337 let future_context = Context::new_future();338 let mut defaults = GcHashMap::with_capacity(params.len() - filled_args);339340 for param in params.iter().filter(|p| p.1.is_some()) {341 if passed_args.contains_key(¶m.0.clone()) {342 continue;343 }344 LazyVal::new(TraceBox(Box::new(EvaluateNamedLazyVal {345 future_context: future_context.clone(),346 name: param.0.clone(),347 value: param.1.clone().unwrap(),348 })));349350 defaults.insert(351 param.0.clone(),352 LazyVal::new(TraceBox(Box::new(EvaluateNamedLazyVal {353 future_context: future_context.clone(),354 name: param.0.clone(),355 value: param.1.clone().unwrap(),356 }))),357 );358 filled_args += 1;359 }360361 // Some args still wasn't filled362 if filled_args != params.len() {363 for param in params.iter().skip(args.unnamed_len()) {364 let mut found = false;365 args.named_names(&mut |name| {366 if name == ¶m.0 {367 found = true;368 }369 });370 if !found {371 throw!(FunctionParameterNotBoundInCall(param.0.clone()));372 }373 }374 unreachable!();375 }376377 Ok(body_ctx378 .extend(passed_args, None, None, None)379 .extend_bound(defaults)380 .into_future(future_context))381 } else {382 let body_ctx = body_ctx.extend(passed_args, None, None, None);383 Ok(body_ctx)384 }385}386387type BuiltinParamName = Cow<'static, str>;388389#[derive(Clone, Trace)]390pub struct BuiltinParam {391 pub name: BuiltinParamName,392 pub has_default: bool,393}394395/// Do not implement it directly, instead use #[builtin] macro396pub trait Builtin: Trace {397 fn name(&self) -> &str;398 fn params(&self) -> &[BuiltinParam];399 fn call(&self, context: Context, loc: CallLocation, args: &dyn ArgsLike) -> Result<Val>;400}401402pub trait StaticBuiltin: Builtin + Send + Sync403where404 Self: 'static,405{406 // In impl, to make it object safe:407 // const INST: &'static Self;408}409410/// You shouldn't probally use this function, use jrsonnet_macros::builtin instead411///412/// ## Parameters413/// * `ctx`: used for passed argument expressions' execution and for body execution (if `body_ctx` is not set)414/// * `params`: function parameters' definition415/// * `args`: passed function arguments416/// * `tailstrict`: if set to `true` function arguments are eagerly executed, otherwise - lazily417pub fn parse_builtin_call(418 ctx: Context,419 params: &[BuiltinParam],420 args: &dyn ArgsLike,421 tailstrict: bool,422) -> Result<GcHashMap<BuiltinParamName, LazyVal>> {423 let mut passed_args = GcHashMap::with_capacity(params.len());424 if args.unnamed_len() > params.len() {425 throw!(TooManyArgsFunctionHas(params.len()))426 }427428 let mut filled_args = 0;429430 args.unnamed_iter(ctx.clone(), tailstrict, &mut |id, arg| {431 let name = params[id].name.clone();432 passed_args.insert(name, arg);433 filled_args += 1;434 Ok(())435 })?;436437 args.named_iter(ctx, tailstrict, &mut |name, arg| {438 // FIXME: O(n) for arg existence check439 let p = params440 .iter()441 .find(|p| p.name == name as &str)442 .ok_or_else(|| UnknownFunctionParameter((name as &str).to_owned()))?;443 if passed_args.insert(p.name.clone(), arg).is_some() {444 throw!(BindingParameterASecondTime(name.clone()));445 }446 filled_args += 1;447 Ok(())448 })?;449450 if filled_args < params.len() {451 for param in params.iter().filter(|p| p.has_default) {452 if passed_args.contains_key(¶m.name) {453 continue;454 }455 filled_args += 1;456 }457458 // Some args still wasn't filled459 if filled_args != params.len() {460 for param in params.iter().skip(args.unnamed_len()) {461 let mut found = false;462 args.named_names(&mut |name| {463 if name as &str == ¶m.name as &str {464 found = true;465 }466 });467 if !found {468 throw!(FunctionParameterNotBoundInCall(param.name.clone().into()));469 }470 }471 unreachable!();472 }473 }474 Ok(passed_args)475}476477/// Creates Context, which has all argument default values applied478/// and with unbound values causing error to be returned479pub fn parse_default_function_call(body_ctx: Context, params: &ParamsDesc) -> Context {480 let ctx = Context::new_future();481482 let mut bindings = GcHashMap::new();483484 #[derive(Trace)]485 struct DependsOnUnbound(IStr);486 impl LazyValValue for DependsOnUnbound {487 fn get(self: Box<Self>) -> Result<Val> {488 Err(FunctionParameterNotBoundInCall(self.0.clone()).into())489 }490 }491492 for param in params.iter() {493 if let Some(v) = ¶m.1 {494 bindings.insert(495 param.0.clone(),496 LazyVal::new(TraceBox(Box::new(EvaluateNamedLazyVal {497 future_context: ctx.clone(),498 name: param.0.clone(),499 value: v.clone(),500 }))),501 );502 } else {503 bindings.insert(504 param.0.clone(),505 LazyVal::new(TraceBox(Box::new(DependsOnUnbound(param.0.clone())))),506 );507 }508 }509510 body_ctx.extend(bindings, None, None, None).into_future(ctx)511}1use std::{borrow::Cow, collections::HashMap, convert::TryFrom};23use gcmodule::Trace;4use jrsonnet_interner::IStr;5pub use jrsonnet_macros::builtin;6use jrsonnet_parser::{ArgsDesc, ExprLocation, LocExpr, ParamsDesc};78use crate::{9 error::{Error::*, LocError},10 evaluate, evaluate_named,11 gc::TraceBox,12 throw,13 typed::Typed,14 val::LazyValValue,15 Context, FutureWrapper, GcHashMap, LazyVal, Result, Val,16};1718#[derive(Clone, Copy)]19pub struct CallLocation<'l>(pub Option<&'l ExprLocation>);20impl<'l> CallLocation<'l> {21 pub const fn new(loc: &'l ExprLocation) -> Self {22 Self(Some(loc))23 }24}25impl CallLocation<'static> {26 pub const fn native() -> Self {27 Self(None)28 }29}3031#[derive(Trace)]32struct EvaluateLazyVal {33 context: Context,34 expr: LocExpr,35}36impl LazyValValue for EvaluateLazyVal {37 fn get(self: Box<Self>) -> Result<Val> {38 evaluate(self.context, &self.expr)39 }40}4142#[derive(Trace)]43struct EvaluateNamedLazyVal {44 future_context: FutureWrapper<Context>,45 name: IStr,46 value: LocExpr,47}48impl LazyValValue for EvaluateNamedLazyVal {49 fn get(self: Box<Self>) -> Result<Val> {50 evaluate_named(self.future_context.unwrap(), &self.value, self.name)51 }52}5354pub trait ArgLike {55 fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<LazyVal>;56}57impl ArgLike for &LocExpr {58 fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<LazyVal> {59 Ok(if tailstrict {60 LazyVal::new_resolved(evaluate(ctx, self)?)61 } else {62 LazyVal::new(TraceBox(Box::new(EvaluateLazyVal {63 context: ctx,64 expr: (*self).clone(),65 })))66 })67 }68}69impl<T> ArgLike for T70where71 T: Typed + Clone,72 Val: TryFrom<T, Error = LocError>,73{74 fn evaluate_arg(&self, _ctx: Context, _tailstrict: bool) -> Result<LazyVal> {75 let val: Val = Val::try_from(self.clone())?;76 Ok(LazyVal::new_resolved(val))77 }78}79pub enum TlaArg {80 String(IStr),81 Code(LocExpr),82 Val(Val),83}84impl ArgLike for TlaArg {85 fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<LazyVal> {86 match self {87 TlaArg::String(s) => Ok(LazyVal::new_resolved(Val::Str(s.clone()))),88 TlaArg::Code(code) => Ok(if tailstrict {89 LazyVal::new_resolved(evaluate(ctx, code)?)90 } else {91 LazyVal::new(TraceBox(Box::new(EvaluateLazyVal {92 context: ctx,93 expr: code.clone(),94 })))95 }),96 TlaArg::Val(val) => Ok(LazyVal::new_resolved(val.clone())),97 }98 }99}100101pub trait ArgsLike {102 fn unnamed_len(&self) -> usize;103 fn unnamed_iter(104 &self,105 ctx: Context,106 tailstrict: bool,107 handler: &mut dyn FnMut(usize, LazyVal) -> Result<()>,108 ) -> Result<()>;109 fn named_iter(110 &self,111 ctx: Context,112 tailstrict: bool,113 handler: &mut dyn FnMut(&IStr, LazyVal) -> Result<()>,114 ) -> Result<()>;115 fn named_names(&self, handler: &mut dyn FnMut(&IStr));116}117118impl ArgsLike for ArgsDesc {119 fn unnamed_len(&self) -> usize {120 self.unnamed.len()121 }122123 fn unnamed_iter(124 &self,125 ctx: Context,126 tailstrict: bool,127 handler: &mut dyn FnMut(usize, LazyVal) -> Result<()>,128 ) -> Result<()> {129 for (id, arg) in self.unnamed.iter().enumerate() {130 handler(131 id,132 if tailstrict {133 LazyVal::new_resolved(evaluate(ctx.clone(), arg)?)134 } else {135 LazyVal::new(TraceBox(Box::new(EvaluateLazyVal {136 context: ctx.clone(),137 expr: arg.clone(),138 })))139 },140 )?;141 }142 Ok(())143 }144145 fn named_iter(146 &self,147 ctx: Context,148 tailstrict: bool,149 handler: &mut dyn FnMut(&IStr, LazyVal) -> Result<()>,150 ) -> Result<()> {151 for (name, arg) in self.named.iter() {152 handler(153 name,154 if tailstrict {155 LazyVal::new_resolved(evaluate(ctx.clone(), arg)?)156 } else {157 LazyVal::new(TraceBox(Box::new(EvaluateLazyVal {158 context: ctx.clone(),159 expr: arg.clone(),160 })))161 },162 )?;163 }164 Ok(())165 }166167 fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {168 for (name, _) in self.named.iter() {169 handler(name)170 }171 }172}173174impl<A: ArgLike> ArgsLike for [(IStr, A)] {175 fn unnamed_len(&self) -> usize {176 0177 }178179 fn unnamed_iter(180 &self,181 _ctx: Context,182 _tailstrict: bool,183 _handler: &mut dyn FnMut(usize, LazyVal) -> Result<()>,184 ) -> Result<()> {185 Ok(())186 }187188 fn named_iter(189 &self,190 ctx: Context,191 tailstrict: bool,192 handler: &mut dyn FnMut(&IStr, LazyVal) -> Result<()>,193 ) -> Result<()> {194 for (name, val) in self.iter() {195 handler(name, val.evaluate_arg(ctx.clone(), tailstrict)?)?;196 }197 Ok(())198 }199200 fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {201 for (name, _) in self.iter() {202 handler(name);203 }204 }205}206207impl<A: ArgLike> ArgsLike for HashMap<IStr, A> {208 fn unnamed_len(&self) -> usize {209 0210 }211212 fn unnamed_iter(213 &self,214 _ctx: Context,215 _tailstrict: bool,216 _handler: &mut dyn FnMut(usize, LazyVal) -> Result<()>,217 ) -> Result<()> {218 Ok(())219 }220221 fn named_iter(222 &self,223 ctx: Context,224 tailstrict: bool,225 handler: &mut dyn FnMut(&IStr, LazyVal) -> Result<()>,226 ) -> Result<()> {227 for (name, value) in self.iter() {228 handler(name, value.evaluate_arg(ctx.clone(), tailstrict)?)?;229 }230 Ok(())231 }232233 fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {234 for (name, _) in self.iter() {235 handler(name);236 }237 }238}239240impl<A: ArgLike> ArgsLike for [A] {241 fn unnamed_len(&self) -> usize {242 self.len()243 }244245 fn unnamed_iter(246 &self,247 ctx: Context,248 tailstrict: bool,249 handler: &mut dyn FnMut(usize, LazyVal) -> Result<()>,250 ) -> Result<()> {251 for (i, arg) in self.iter().enumerate() {252 handler(i, arg.evaluate_arg(ctx.clone(), tailstrict)?)?;253 }254 Ok(())255 }256257 fn named_iter(258 &self,259 _ctx: Context,260 _tailstrict: bool,261 _handler: &mut dyn FnMut(&IStr, LazyVal) -> Result<()>,262 ) -> Result<()> {263 Ok(())264 }265266 fn named_names(&self, _handler: &mut dyn FnMut(&IStr)) {}267}268impl<A: ArgLike> ArgsLike for &[A] {269 fn unnamed_len(&self) -> usize {270 (*self).unnamed_len()271 }272273 fn unnamed_iter(274 &self,275 ctx: Context,276 tailstrict: bool,277 handler: &mut dyn FnMut(usize, LazyVal) -> Result<()>,278 ) -> Result<()> {279 (*self).unnamed_iter(ctx, tailstrict, handler)280 }281282 fn named_iter(283 &self,284 ctx: Context,285 tailstrict: bool,286 handler: &mut dyn FnMut(&IStr, LazyVal) -> Result<()>,287 ) -> Result<()> {288 (*self).named_iter(ctx, tailstrict, handler)289 }290291 fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {292 (*self).named_names(handler)293 }294}295296/// Creates correct [context](Context) for function body evaluation returning error on invalid call.297///298/// ## Parameters299/// * `ctx`: used for passed argument expressions' execution and for body execution (if `body_ctx` is not set)300/// * `body_ctx`: used for default parameter values' execution and for body execution (if set)301/// * `params`: function parameters' definition302/// * `args`: passed function arguments303/// * `tailstrict`: if set to `true` function arguments are eagerly executed, otherwise - lazily304pub fn parse_function_call(305 ctx: Context,306 body_ctx: Context,307 params: &ParamsDesc,308 args: &dyn ArgsLike,309 tailstrict: bool,310) -> Result<Context> {311 let mut passed_args = GcHashMap::with_capacity(params.len());312 if args.unnamed_len() > params.len() {313 throw!(TooManyArgsFunctionHas(params.len()))314 }315316 let mut filled_args = 0;317318 args.unnamed_iter(ctx.clone(), tailstrict, &mut |id, arg| {319 let name = params[id].0.clone();320 passed_args.insert(name, arg);321 filled_args += 1;322 Ok(())323 })?;324325 args.named_iter(ctx, tailstrict, &mut |name, value| {326 // FIXME: O(n) for arg existence check327 if !params.iter().any(|p| &p.0 == name) {328 throw!(UnknownFunctionParameter((name as &str).to_owned()));329 }330 if passed_args.insert(name.clone(), value).is_some() {331 throw!(BindingParameterASecondTime(name.clone()));332 }333 filled_args += 1;334 Ok(())335 })?;336337 if filled_args < params.len() {338 // Some args are unset, but maybe we have defaults for them339 // Default values should be created in newly created context340 let future_context = Context::new_future();341 let mut defaults = GcHashMap::with_capacity(params.len() - filled_args);342343 for param in params.iter().filter(|p| p.1.is_some()) {344 if passed_args.contains_key(¶m.0.clone()) {345 continue;346 }347 LazyVal::new(TraceBox(Box::new(EvaluateNamedLazyVal {348 future_context: future_context.clone(),349 name: param.0.clone(),350 value: param.1.clone().unwrap(),351 })));352353 defaults.insert(354 param.0.clone(),355 LazyVal::new(TraceBox(Box::new(EvaluateNamedLazyVal {356 future_context: future_context.clone(),357 name: param.0.clone(),358 value: param.1.clone().unwrap(),359 }))),360 );361 filled_args += 1;362 }363364 // Some args still wasn't filled365 if filled_args != params.len() {366 for param in params.iter().skip(args.unnamed_len()) {367 let mut found = false;368 args.named_names(&mut |name| {369 if name == ¶m.0 {370 found = true;371 }372 });373 if !found {374 throw!(FunctionParameterNotBoundInCall(param.0.clone()));375 }376 }377 unreachable!();378 }379380 Ok(body_ctx381 .extend(passed_args, None, None, None)382 .extend_bound(defaults)383 .into_future(future_context))384 } else {385 let body_ctx = body_ctx.extend(passed_args, None, None, None);386 Ok(body_ctx)387 }388}389390type BuiltinParamName = Cow<'static, str>;391392#[derive(Clone, Trace)]393pub struct BuiltinParam {394 pub name: BuiltinParamName,395 pub has_default: bool,396}397398/// Do not implement it directly, instead use #[builtin] macro399pub trait Builtin: Trace {400 fn name(&self) -> &str;401 fn params(&self) -> &[BuiltinParam];402 fn call(&self, context: Context, loc: CallLocation, args: &dyn ArgsLike) -> Result<Val>;403}404405pub trait StaticBuiltin: Builtin + Send + Sync406where407 Self: 'static,408{409 // In impl, to make it object safe:410 // const INST: &'static Self;411}412413/// You shouldn't probally use this function, use jrsonnet_macros::builtin instead414///415/// ## Parameters416/// * `ctx`: used for passed argument expressions' execution and for body execution (if `body_ctx` is not set)417/// * `params`: function parameters' definition418/// * `args`: passed function arguments419/// * `tailstrict`: if set to `true` function arguments are eagerly executed, otherwise - lazily420pub fn parse_builtin_call(421 ctx: Context,422 params: &[BuiltinParam],423 args: &dyn ArgsLike,424 tailstrict: bool,425) -> Result<GcHashMap<BuiltinParamName, LazyVal>> {426 let mut passed_args = GcHashMap::with_capacity(params.len());427 if args.unnamed_len() > params.len() {428 throw!(TooManyArgsFunctionHas(params.len()))429 }430431 let mut filled_args = 0;432433 args.unnamed_iter(ctx.clone(), tailstrict, &mut |id, arg| {434 let name = params[id].name.clone();435 passed_args.insert(name, arg);436 filled_args += 1;437 Ok(())438 })?;439440 args.named_iter(ctx, tailstrict, &mut |name, arg| {441 // FIXME: O(n) for arg existence check442 let p = params443 .iter()444 .find(|p| p.name == name as &str)445 .ok_or_else(|| UnknownFunctionParameter((name as &str).to_owned()))?;446 if passed_args.insert(p.name.clone(), arg).is_some() {447 throw!(BindingParameterASecondTime(name.clone()));448 }449 filled_args += 1;450 Ok(())451 })?;452453 if filled_args < params.len() {454 for param in params.iter().filter(|p| p.has_default) {455 if passed_args.contains_key(¶m.name) {456 continue;457 }458 filled_args += 1;459 }460461 // Some args still wasn't filled462 if filled_args != params.len() {463 for param in params.iter().skip(args.unnamed_len()) {464 let mut found = false;465 args.named_names(&mut |name| {466 if name as &str == ¶m.name as &str {467 found = true;468 }469 });470 if !found {471 throw!(FunctionParameterNotBoundInCall(param.name.clone().into()));472 }473 }474 unreachable!();475 }476 }477 Ok(passed_args)478}479480/// Creates Context, which has all argument default values applied481/// and with unbound values causing error to be returned482pub fn parse_default_function_call(body_ctx: Context, params: &ParamsDesc) -> Context {483 let ctx = Context::new_future();484485 let mut bindings = GcHashMap::new();486487 #[derive(Trace)]488 struct DependsOnUnbound(IStr);489 impl LazyValValue for DependsOnUnbound {490 fn get(self: Box<Self>) -> Result<Val> {491 Err(FunctionParameterNotBoundInCall(self.0.clone()).into())492 }493 }494495 for param in params.iter() {496 if let Some(v) = ¶m.1 {497 bindings.insert(498 param.0.clone(),499 LazyVal::new(TraceBox(Box::new(EvaluateNamedLazyVal {500 future_context: ctx.clone(),501 name: param.0.clone(),502 value: v.clone(),503 }))),504 );505 } else {506 bindings.insert(507 param.0.clone(),508 LazyVal::new(TraceBox(Box::new(DependsOnUnbound(param.0.clone())))),509 );510 }511 }512513 body_ctx.extend(bindings, None, None, None).into_future(ctx)514}crates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/import.rs
+++ b/crates/jrsonnet-evaluator/src/import.rs
@@ -1,17 +1,20 @@
-use crate::{
- error::{Error::*, Result},
- throw,
-};
-use fs::File;
-use jrsonnet_interner::IStr;
-use std::fs;
use std::{
any::Any,
+ convert::TryFrom,
+ fs,
+ io::Read,
path::{Path, PathBuf},
rc::Rc,
};
-use std::{convert::TryFrom, io::Read};
+use fs::File;
+use jrsonnet_interner::IStr;
+
+use crate::{
+ error::{Error::*, Result},
+ throw,
+};
+
/// Implements file resolution logic for `import` and `importStr`
pub trait ImportResolver {
/// Resolves real file path, e.g. `(/home/user/manifests, b.libjsonnet)` can correspond
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -1,9 +1,11 @@
+use std::convert::{TryFrom, TryInto};
+
+use serde_json::{Map, Number, Value};
+
use crate::{
error::{Error::*, LocError, Result},
throw, ObjValueBuilder, Val,
};
-use serde_json::{Map, Number, Value};
-use std::convert::{TryFrom, TryInto};
impl TryFrom<&Val> for Value {
type Error = LocError;
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -13,6 +13,7 @@
pub mod error;
mod evaluate;
pub mod function;
+pub mod gc;
mod import;
mod integrations;
mod map;
@@ -20,9 +21,15 @@
mod obj;
pub mod trace;
pub mod typed;
-mod val;
+pub mod val;
-pub use jrsonnet_parser as parser;
+use std::{
+ cell::{Ref, RefCell, RefMut},
+ collections::HashMap,
+ fmt::Debug,
+ path::{Path, PathBuf},
+ rc::Rc,
+};
pub use ctx::*;
pub use dynamic::*;
@@ -33,18 +40,11 @@
use gcmodule::{Cc, Trace, Weak};
pub use import::*;
pub use jrsonnet_interner::IStr;
+pub use jrsonnet_parser as parser;
use jrsonnet_parser::*;
pub use obj::*;
-use std::{
- cell::{Ref, RefCell, RefMut},
- collections::HashMap,
- fmt::Debug,
- path::{Path, PathBuf},
- rc::Rc,
-};
use trace::{location_to_offset, offset_to_location, CodeLocation, CompactFormat, TraceFormat};
-pub use val::*;
-pub mod gc;
+pub use val::{LazyVal, ManifestFormat, Val};
pub trait Bindable: Trace + 'static {
fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal>;
@@ -693,18 +693,24 @@
#[cfg(test)]
pub mod tests {
- use super::Val;
- use crate::{
- error::Error::*, function::BuiltinParam, gc::TraceBox, native::NativeCallbackHandler,
- primitive_equals, EvaluationState,
- };
- use gcmodule::{Cc, Trace};
- use jrsonnet_parser::*;
use std::{
path::{Path, PathBuf},
rc::Rc,
};
+ use gcmodule::{Cc, Trace};
+ use jrsonnet_parser::*;
+
+ use super::Val;
+ use crate::{
+ error::Error::*,
+ function::{BuiltinParam, CallLocation},
+ gc::TraceBox,
+ native::NativeCallbackHandler,
+ val::primitive_equals,
+ EvaluationState,
+ };
+
#[test]
#[should_panic]
fn eval_state_stacktrace() {
@@ -712,11 +718,15 @@
state.run_in_state(|| {
state
.push(
- Some(&ExprLocation(PathBuf::from("test1.jsonnet").into(), 10, 20)),
+ CallLocation::new(&ExprLocation(PathBuf::from("test1.jsonnet").into(), 10, 20)),
|| "outer".to_owned(),
|| {
state.push(
- Some(&ExprLocation(PathBuf::from("test2.jsonnet").into(), 30, 40)),
+ CallLocation::new(&ExprLocation(
+ PathBuf::from("test2.jsonnet").into(),
+ 30,
+ 40,
+ )),
|| "inner".to_owned(),
|| Err(RuntimeError("".into()).into()),
)?;
@@ -1290,10 +1300,11 @@
}
mod derive_typed {
+ use std::path::PathBuf;
+
use crate::{typed::Typed, EvaluationState};
- use std::path::PathBuf;
- #[derive(Typed, PartialEq, Debug)]
+ #[derive(PartialEq, Debug, Typed)]
struct MyTyped {
a: u32,
#[typed(rename = "b")]
crates/jrsonnet-evaluator/src/native.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/native.rs
+++ b/crates/jrsonnet-evaluator/src/native.rs
@@ -1,13 +1,16 @@
#![allow(clippy::type_complexity)]
-use crate::function::{parse_builtin_call, ArgsLike, Builtin, BuiltinParam, CallLocation};
-use crate::gc::TraceBox;
-use crate::Context;
-use crate::{error::Result, Val};
+use std::{path::Path, rc::Rc};
+
use gcmodule::Trace;
-use std::path::Path;
-use std::rc::Rc;
+use crate::{
+ error::Result,
+ function::{parse_builtin_call, ArgsLike, Builtin, BuiltinParam, CallLocation},
+ gc::TraceBox,
+ Context, Val,
+};
+
#[derive(Trace)]
pub struct NativeCallback {
pub(crate) params: Vec<BuiltinParam>,
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -1,20 +1,23 @@
-use crate::error::LocError;
-use crate::function::CallLocation;
-use crate::gc::{GcHashMap, GcHashSet, TraceBox};
-use crate::operator::evaluate_add_op;
-use crate::push_frame;
-use crate::{
- cc_ptr_eq, error::Error::*, throw, weak_ptr_eq, weak_raw, Bindable, LazyBinding, LazyVal,
- Result, Val,
+use std::{
+ cell::RefCell,
+ fmt::Debug,
+ hash::{Hash, Hasher},
};
+
use gcmodule::{Cc, Trace, Weak};
use jrsonnet_interner::IStr;
use jrsonnet_parser::{ExprLocation, Visibility};
use rustc_hash::FxHashMap;
-use std::cell::RefCell;
-use std::fmt::Debug;
-use std::hash::{Hash, Hasher};
+use crate::{
+ cc_ptr_eq,
+ error::{Error::*, LocError},
+ function::CallLocation,
+ gc::{GcHashMap, GcHashSet, TraceBox},
+ operator::evaluate_add_op,
+ push_frame, throw, weak_ptr_eq, weak_raw, Bindable, LazyBinding, LazyVal, Result, Val,
+};
+
#[derive(Debug, Trace)]
pub struct ObjMember {
pub add: bool,
crates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -1,8 +1,10 @@
mod location;
+use std::path::{Path, PathBuf};
+
+pub use location::*;
+
use crate::{error::Error, EvaluationState, LocError};
-pub use location::*;
-use std::path::{Path, PathBuf};
/// The way paths should be displayed
pub enum PathResolver {
crates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/mod.rs
+++ b/crates/jrsonnet-evaluator/src/typed/mod.rs
@@ -2,14 +2,14 @@
mod conversions;
pub use conversions::*;
+use gcmodule::Trace;
+pub use jrsonnet_types::{ComplexValType, ValType};
+use thiserror::Error;
use crate::{
error::{Error, LocError, Result},
push_description_frame, Val,
};
-use gcmodule::Trace;
-pub use jrsonnet_types::{ComplexValType, ValType};
-use thiserror::Error;
#[derive(Debug, Error, Clone, Trace)]
pub enum TypeError {
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -1,3 +1,10 @@
+use std::{cell::RefCell, fmt::Debug, rc::Rc};
+
+use gcmodule::{Cc, Trace};
+use jrsonnet_interner::IStr;
+use jrsonnet_parser::{LocExpr, ParamsDesc};
+use jrsonnet_types::ValType;
+
use crate::{
builtin::manifest::{
manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType, ManifestYamlOptions,
@@ -12,11 +19,6 @@
gc::TraceBox,
throw, Context, ObjValue, Result,
};
-use gcmodule::{Cc, Trace};
-use jrsonnet_interner::IStr;
-use jrsonnet_parser::{LocExpr, ParamsDesc};
-use jrsonnet_types::ValType;
-use std::{cell::RefCell, fmt::Debug, rc::Rc};
pub trait LazyValValue: Trace {
fn get(self: Box<Self>) -> Result<Val>;
crates/jrsonnet-interner/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-interner/src/lib.rs
+++ b/crates/jrsonnet-interner/src/lib.rs
@@ -1,6 +1,3 @@
-use gcmodule::Trace;
-use rustc_hash::FxHashMap;
-use serde::{Deserialize, Serialize};
use std::{
borrow::Cow,
cell::RefCell,
@@ -12,6 +9,10 @@
str::Utf8Error,
};
+use gcmodule::Trace;
+use rustc_hash::FxHashMap;
+use serde::{Deserialize, Serialize};
+
#[derive(Clone, PartialOrd, Ord, Eq)]
pub struct IStr(Rc<str>);
impl Trace for IStr {
crates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/expr.rs
+++ b/crates/jrsonnet-parser/src/expr.rs
@@ -1,7 +1,3 @@
-use gcmodule::Trace;
-use jrsonnet_interner::IStr;
-#[cfg(feature = "serde")]
-use serde::{Deserialize, Serialize};
use std::{
fmt::{Debug, Display},
ops::Deref,
@@ -9,6 +5,11 @@
rc::Rc,
};
+use gcmodule::Trace;
+use jrsonnet_interner::IStr;
+#[cfg(feature = "serde")]
+use serde::{Deserialize, Serialize};
+
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, PartialEq, Trace)]
pub enum FieldName {
crates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/lib.rs
+++ b/crates/jrsonnet-parser/src/lib.rs
@@ -1,10 +1,11 @@
#![allow(clippy::redundant_closure_call)]
-use peg::parser;
use std::{
path::{Path, PathBuf},
rc::Rc,
};
+
+use peg::parser;
mod expr;
pub use expr::*;
pub use jrsonnet_interner::IStr;
@@ -317,11 +318,13 @@
#[cfg(test)]
pub mod tests {
- use super::{expr::*, parse};
- use crate::ParserSettings;
use std::path::PathBuf;
+
use BinaryOpType::*;
+ use super::{expr::*, parse};
+ use crate::ParserSettings;
+
macro_rules! parse {
($s:expr) => {
parse(
crates/jrsonnet-types/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-types/src/lib.rs
+++ b/crates/jrsonnet-types/src/lib.rs
@@ -1,8 +1,9 @@
#![allow(clippy::redundant_closure_call)]
-use gcmodule::Trace;
use std::fmt::Display;
+use gcmodule::Trace;
+
#[macro_export]
macro_rules! ty {
((Array<number>)) => {{