difftreelog
style fix formatting
in: master
3 files changed
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -4,8 +4,8 @@
evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},
gc::TraceBox,
push_frame, throw, with_state, ArrValue, Bindable, Context, ContextCreator, FuncDesc, FuncVal,
- FutureWrapper, GcHashMap, LazyBinding, LazyVal, LazyValValue, ObjValue,
- ObjValueBuilder, ObjectAssertion, Result, Val,
+ FutureWrapper, GcHashMap, LazyBinding, LazyVal, LazyValValue, ObjValue, ObjValueBuilder,
+ ObjectAssertion, Result, Val,
};
use gcmodule::{Cc, Trace};
use jrsonnet_interner::IStr;
@@ -103,17 +103,15 @@
}
impl Bindable for BindableMethod {
fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {
- Ok(LazyVal::new(TraceBox(Box::new(
- BindableMethodLazyVal {
- this,
- super_obj,
+ Ok(LazyVal::new(TraceBox(Box::new(BindableMethodLazyVal {
+ this,
+ super_obj,
- context_creator: self.context_creator.clone(),
- name: self.name.clone(),
- params: self.params.clone(),
- value: self.value.clone(),
- },
- ))))
+ context_creator: self.context_creator.clone(),
+ name: self.name.clone(),
+ params: self.params.clone(),
+ value: self.value.clone(),
+ }))))
}
}
@@ -154,16 +152,14 @@
}
impl Bindable for BindableNamed {
fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {
- Ok(LazyVal::new(TraceBox(Box::new(
- BindableNamedLazyVal {
- this,
- super_obj,
+ Ok(LazyVal::new(TraceBox(Box::new(BindableNamedLazyVal {
+ this,
+ super_obj,
- context_creator: self.context_creator.clone(),
- name: self.name.clone(),
- value: self.value.clone(),
- },
- ))))
+ context_creator: self.context_creator.clone(),
+ name: self.name.clone(),
+ value: self.value.clone(),
+ }))))
}
}
crates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function.rs
+++ b/crates/jrsonnet-evaluator/src/function.rs
@@ -1,4 +1,7 @@
-use crate::{Context, FutureWrapper, GcHashMap, LazyVal, LazyValValue, Result, Val, error::Error::*, evaluate, evaluate_named, gc::TraceBox, throw};
+use crate::{
+ error::Error::*, evaluate, evaluate_named, gc::TraceBox, throw, Context, FutureWrapper,
+ GcHashMap, LazyVal, LazyValValue, Result, Val,
+};
use gcmodule::Trace;
use jrsonnet_interner::IStr;
use jrsonnet_parser::{ArgsDesc, LocExpr, ParamsDesc};
@@ -187,10 +190,7 @@
)
}
}
- LazyVal::new(TraceBox(Box::new(EvaluateLazyVal {
- body_ctx,
- default,
- })))
+ LazyVal::new(TraceBox(Box::new(EvaluateLazyVal { body_ctx, default })))
}
} else {
throw!(FunctionParameterNotBoundInCall(p.0.clone()));
crates/jrsonnet-evaluator/src/typed.rsdiffbeforeafterboth1use std::{fmt::Display, rc::Rc};23use crate::{Val, error::{Error, LocError, Result}, push_description_frame};4use gcmodule::Trace;5use jrsonnet_types::{ComplexValType, ValType};6use thiserror::Error;78#[macro_export]9macro_rules! unwrap_type {10 ($desc: expr, $value: expr, $typ: expr => $match: path) => {{11 use $crate::{push_stack_frame, typed::CheckType};12 push_stack_frame(None, $desc, || Ok($typ.check(&$value)?))?;13 match $value {14 $match(v) => v,15 _ => unreachable!(),16 }17 }};18}1920#[derive(Debug, Error, Clone, Trace)]21pub enum TypeError {22 #[error("expected {0}, got {1}")]23 ExpectedGot(ComplexValType, ValType),24 #[error("missing property {0} from {1:?}")]25 MissingProperty(#[skip_trace] Rc<str>, ComplexValType),26 #[error("every failed from {0}:\n{1}")]27 UnionFailed(ComplexValType, TypeLocErrorList),28 #[error(29 "number out of bounds: {0} not in {}..{}",30 .1.map(|v|v.to_string()).unwrap_or_else(|| "".to_owned()),31 .2.map(|v|v.to_string()).unwrap_or_else(|| "".to_owned()),32 )]33 BoundsFailed(f64, Option<f64>, Option<f64>),34}35impl From<TypeError> for LocError {36 fn from(e: TypeError) -> Self {37 Error::TypeError(e.into()).into()38 }39}4041#[derive(Debug, Clone, Trace)]42pub struct TypeLocError(Box<TypeError>, ValuePathStack);43impl From<TypeError> for TypeLocError {44 fn from(e: TypeError) -> Self {45 Self(Box::new(e), ValuePathStack(Vec::new()))46 }47}48impl From<TypeLocError> for LocError {49 fn from(e: TypeLocError) -> Self {50 Error::TypeError(e).into()51 }52}53impl Display for TypeLocError {54 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {55 write!(f, "{}", self.0)?;56 if !(self.1).0.is_empty() {57 write!(f, " at {}", self.1)?;58 }59 Ok(())60 }61}6263#[derive(Debug, Clone, Trace)]64pub struct TypeLocErrorList(Vec<TypeLocError>);65impl Display for TypeLocErrorList {66 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {67 use std::fmt::Write;68 let mut out = String::new();69 for (i, err) in self.0.iter().enumerate() {70 if i != 0 {71 writeln!(f)?;72 }73 out.clear();74 write!(out, "{}", err)?;7576 for (i, line) in out.lines().enumerate() {77 if line.trim().is_empty() {78 continue;79 }80 if i != 0 {81 writeln!(f)?;82 write!(f, " ")?;83 } else {84 write!(f, " - ")?;85 }86 write!(f, "{}", line)?;87 }88 }89 Ok(())90 }91}9293fn push_type_description(94 error_reason: impl Fn() -> String,95 path: impl Fn() -> ValuePathItem,96 item: impl Fn() -> Result<()>,97) -> Result<()> {98 push_description_frame(error_reason, || match item() {99 Ok(_) => Ok(()),100 Err(mut e) => {101 if let Error::TypeError(e) = &mut e.error_mut() {102 (e.1).0.push(path())103 }104 Err(e)105 }106 })107}108109// TODO: check_fast for fast path of union type checking110pub trait CheckType {111 fn check(&self, value: &Val) -> Result<()>;112}113114impl CheckType for ValType {115 fn check(&self, value: &Val) -> Result<()> {116 let got = value.value_type();117 if got != *self {118 let loc_error: TypeLocError = TypeError::ExpectedGot((*self).into(), got).into();119 return Err(loc_error.into());120 }121 Ok(())122 }123}124125#[derive(Clone, Debug, Trace)]126enum ValuePathItem {127 Field(#[skip_trace] Rc<str>),128 Index(u64),129}130impl Display for ValuePathItem {131 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {132 match self {133 Self::Field(name) => write!(f, ".{}", name)?,134 Self::Index(idx) => write!(f, "[{}]", idx)?,135 }136 Ok(())137 }138}139140#[derive(Clone, Debug, Trace)]141struct ValuePathStack(Vec<ValuePathItem>);142impl Display for ValuePathStack {143 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {144 write!(f, "self")?;145 for elem in self.0.iter().rev() {146 write!(f, "{}", elem)?;147 }148 Ok(())149 }150}151152impl CheckType for ComplexValType {153 fn check(&self, value: &Val) -> Result<()> {154 match self {155 Self::Any => Ok(()),156 Self::Simple(s) => s.check(value),157 Self::Char => match value {158 Val::Str(s) if s.len() == 1 || s.chars().count() == 1 => Ok(()),159 v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),160 },161 Self::BoundedNumber(from, to) => {162 if let Val::Num(n) = value {163 if from.map(|from| from > *n).unwrap_or(false)164 || to.map(|to| to <= *n).unwrap_or(false)165 {166 return Err(TypeError::BoundsFailed(*n, *from, *to).into());167 }168 Ok(())169 } else {170 Err(TypeError::ExpectedGot(self.clone(), value.value_type()).into())171 }172 }173 Self::Array(elem_type) => match value {174 Val::Arr(a) => {175 for (i, item) in a.iter().enumerate() {176 push_type_description(177 || format!("array index {}", i),178 || ValuePathItem::Index(i as u64),179 || elem_type.check(&item.clone()?),180 )?;181 }182 Ok(())183 }184 v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),185 },186 Self::ArrayRef(elem_type) => match value {187 Val::Arr(a) => {188 for (i, item) in a.iter().enumerate() {189 push_type_description(190 || format!("array index {}", i),191 || ValuePathItem::Index(i as u64),192 || elem_type.check(&item.clone()?),193 )?;194 }195 Ok(())196 }197 v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),198 },199 Self::ObjectRef(elems) => match value {200 Val::Obj(obj) => {201 for (k, v) in elems.iter() {202 if let Some(got_v) = obj.get((*k).into())? {203 push_type_description(204 || format!("property {}", k),205 || ValuePathItem::Field((*k).into()),206 || v.check(&got_v),207 )?208 } else {209 return Err(210 TypeError::MissingProperty((*k).into(), self.clone()).into()211 );212 }213 }214 Ok(())215 }216 v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),217 },218 Self::Union(types) => {219 let mut errors = Vec::new();220 for ty in types.iter() {221 match ty.check(value) {222 Ok(()) => {223 return Ok(());224 }225 Err(e) => match e.error() {226 Error::TypeError(e) => errors.push(e.clone()),227 _ => return Err(e),228 },229 }230 }231 Err(TypeError::UnionFailed(self.clone(), TypeLocErrorList(errors)).into())232 }233 Self::UnionRef(types) => {234 let mut errors = Vec::new();235 for ty in types.iter() {236 match ty.check(value) {237 Ok(()) => {238 return Ok(());239 }240 Err(e) => match e.error() {241 Error::TypeError(e) => errors.push(e.clone()),242 _ => return Err(e),243 },244 }245 }246 Err(TypeError::UnionFailed(self.clone(), TypeLocErrorList(errors)).into())247 }248 Self::Sum(types) => {249 for ty in types.iter() {250 ty.check(value)?251 }252 Ok(())253 }254 Self::SumRef(types) => {255 for ty in types.iter() {256 ty.check(value)?257 }258 Ok(())259 }260 }261 }262}1use std::{fmt::Display, rc::Rc};23use crate::{4 error::{Error, LocError, Result},5 push_description_frame, Val,6};7use gcmodule::Trace;8use jrsonnet_types::{ComplexValType, ValType};9use thiserror::Error;1011#[macro_export]12macro_rules! unwrap_type {13 ($desc: expr, $value: expr, $typ: expr => $match: path) => {{14 use $crate::{push_stack_frame, typed::CheckType};15 push_stack_frame(None, $desc, || Ok($typ.check(&$value)?))?;16 match $value {17 $match(v) => v,18 _ => unreachable!(),19 }20 }};21}2223#[derive(Debug, Error, Clone, Trace)]24pub enum TypeError {25 #[error("expected {0}, got {1}")]26 ExpectedGot(ComplexValType, ValType),27 #[error("missing property {0} from {1:?}")]28 MissingProperty(#[skip_trace] Rc<str>, ComplexValType),29 #[error("every failed from {0}:\n{1}")]30 UnionFailed(ComplexValType, TypeLocErrorList),31 #[error(32 "number out of bounds: {0} not in {}..{}",33 .1.map(|v|v.to_string()).unwrap_or_else(|| "".to_owned()),34 .2.map(|v|v.to_string()).unwrap_or_else(|| "".to_owned()),35 )]36 BoundsFailed(f64, Option<f64>, Option<f64>),37}38impl From<TypeError> for LocError {39 fn from(e: TypeError) -> Self {40 Error::TypeError(e.into()).into()41 }42}4344#[derive(Debug, Clone, Trace)]45pub struct TypeLocError(Box<TypeError>, ValuePathStack);46impl From<TypeError> for TypeLocError {47 fn from(e: TypeError) -> Self {48 Self(Box::new(e), ValuePathStack(Vec::new()))49 }50}51impl From<TypeLocError> for LocError {52 fn from(e: TypeLocError) -> Self {53 Error::TypeError(e).into()54 }55}56impl Display for TypeLocError {57 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {58 write!(f, "{}", self.0)?;59 if !(self.1).0.is_empty() {60 write!(f, " at {}", self.1)?;61 }62 Ok(())63 }64}6566#[derive(Debug, Clone, Trace)]67pub struct TypeLocErrorList(Vec<TypeLocError>);68impl Display for TypeLocErrorList {69 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {70 use std::fmt::Write;71 let mut out = String::new();72 for (i, err) in self.0.iter().enumerate() {73 if i != 0 {74 writeln!(f)?;75 }76 out.clear();77 write!(out, "{}", err)?;7879 for (i, line) in out.lines().enumerate() {80 if line.trim().is_empty() {81 continue;82 }83 if i != 0 {84 writeln!(f)?;85 write!(f, " ")?;86 } else {87 write!(f, " - ")?;88 }89 write!(f, "{}", line)?;90 }91 }92 Ok(())93 }94}9596fn push_type_description(97 error_reason: impl Fn() -> String,98 path: impl Fn() -> ValuePathItem,99 item: impl Fn() -> Result<()>,100) -> Result<()> {101 push_description_frame(error_reason, || match item() {102 Ok(_) => Ok(()),103 Err(mut e) => {104 if let Error::TypeError(e) = &mut e.error_mut() {105 (e.1).0.push(path())106 }107 Err(e)108 }109 })110}111112// TODO: check_fast for fast path of union type checking113pub trait CheckType {114 fn check(&self, value: &Val) -> Result<()>;115}116117impl CheckType for ValType {118 fn check(&self, value: &Val) -> Result<()> {119 let got = value.value_type();120 if got != *self {121 let loc_error: TypeLocError = TypeError::ExpectedGot((*self).into(), got).into();122 return Err(loc_error.into());123 }124 Ok(())125 }126}127128#[derive(Clone, Debug, Trace)]129enum ValuePathItem {130 Field(#[skip_trace] Rc<str>),131 Index(u64),132}133impl Display for ValuePathItem {134 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {135 match self {136 Self::Field(name) => write!(f, ".{}", name)?,137 Self::Index(idx) => write!(f, "[{}]", idx)?,138 }139 Ok(())140 }141}142143#[derive(Clone, Debug, Trace)]144struct ValuePathStack(Vec<ValuePathItem>);145impl Display for ValuePathStack {146 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {147 write!(f, "self")?;148 for elem in self.0.iter().rev() {149 write!(f, "{}", elem)?;150 }151 Ok(())152 }153}154155impl CheckType for ComplexValType {156 fn check(&self, value: &Val) -> Result<()> {157 match self {158 Self::Any => Ok(()),159 Self::Simple(s) => s.check(value),160 Self::Char => match value {161 Val::Str(s) if s.len() == 1 || s.chars().count() == 1 => Ok(()),162 v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),163 },164 Self::BoundedNumber(from, to) => {165 if let Val::Num(n) = value {166 if from.map(|from| from > *n).unwrap_or(false)167 || to.map(|to| to <= *n).unwrap_or(false)168 {169 return Err(TypeError::BoundsFailed(*n, *from, *to).into());170 }171 Ok(())172 } else {173 Err(TypeError::ExpectedGot(self.clone(), value.value_type()).into())174 }175 }176 Self::Array(elem_type) => match value {177 Val::Arr(a) => {178 for (i, item) in a.iter().enumerate() {179 push_type_description(180 || format!("array index {}", i),181 || ValuePathItem::Index(i as u64),182 || elem_type.check(&item.clone()?),183 )?;184 }185 Ok(())186 }187 v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),188 },189 Self::ArrayRef(elem_type) => match value {190 Val::Arr(a) => {191 for (i, item) in a.iter().enumerate() {192 push_type_description(193 || format!("array index {}", i),194 || ValuePathItem::Index(i as u64),195 || elem_type.check(&item.clone()?),196 )?;197 }198 Ok(())199 }200 v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),201 },202 Self::ObjectRef(elems) => match value {203 Val::Obj(obj) => {204 for (k, v) in elems.iter() {205 if let Some(got_v) = obj.get((*k).into())? {206 push_type_description(207 || format!("property {}", k),208 || ValuePathItem::Field((*k).into()),209 || v.check(&got_v),210 )?211 } else {212 return Err(213 TypeError::MissingProperty((*k).into(), self.clone()).into()214 );215 }216 }217 Ok(())218 }219 v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),220 },221 Self::Union(types) => {222 let mut errors = Vec::new();223 for ty in types.iter() {224 match ty.check(value) {225 Ok(()) => {226 return Ok(());227 }228 Err(e) => match e.error() {229 Error::TypeError(e) => errors.push(e.clone()),230 _ => return Err(e),231 },232 }233 }234 Err(TypeError::UnionFailed(self.clone(), TypeLocErrorList(errors)).into())235 }236 Self::UnionRef(types) => {237 let mut errors = Vec::new();238 for ty in types.iter() {239 match ty.check(value) {240 Ok(()) => {241 return Ok(());242 }243 Err(e) => match e.error() {244 Error::TypeError(e) => errors.push(e.clone()),245 _ => return Err(e),246 },247 }248 }249 Err(TypeError::UnionFailed(self.clone(), TypeLocErrorList(errors)).into())250 }251 Self::Sum(types) => {252 for ty in types.iter() {253 ty.check(value)?254 }255 Ok(())256 }257 Self::SumRef(types) => {258 for ty in types.iter() {259 ty.check(value)?260 }261 Ok(())262 }263 }264 }265}