difftreelog
style increase clippy linting level
in: master
15 files changed
crates/jrsonnet-evaluator/src/builtin/format.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/format.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/format.rs
@@ -314,7 +314,7 @@
for _ in 0..zp2 {
out.push('0');
}
- out.push_str(&prefix);
+ out.push_str(prefix);
for digit in digits.into_iter().rev() {
let ch = NUMBERS[digit as usize] as char;
@@ -399,7 +399,10 @@
}
return;
}
- let frac = (n.fract() * 10.0_f64.powf(precision as f64) + 0.5).floor();
+ let frac = n
+ .fract()
+ .mul_add(10.0_f64.powf(precision as f64), 0.5)
+ .floor();
if trailing || frac > 0.0 {
out.push('.');
let mut frac_str = String::new();
@@ -605,7 +608,7 @@
}
pub fn format_arr(str: &str, mut values: &[Val]) -> Result<String> {
- let codes = parse_codes(&str)?;
+ let codes = parse_codes(str)?;
let mut out = String::new();
for code in codes {
@@ -659,7 +662,7 @@
}
pub fn format_obj(str: &str, values: &ObjValue) -> Result<String> {
- let codes = parse_codes(&str)?;
+ let codes = parse_codes(str)?;
let mut out = String::new();
for code in codes {
crates/jrsonnet-evaluator/src/builtin/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/manifest.rs
@@ -20,7 +20,7 @@
pub mtype: ManifestType,
}
-pub(crate) fn manifest_json_ex(val: &Val, options: &ManifestJsonOptions<'_>) -> Result<String> {
+pub fn manifest_json_ex(val: &Val, options: &ManifestJsonOptions<'_>) -> Result<String> {
let mut out = String::new();
manifest_json_ex_buf(val, &mut out, &mut String::new(), options)?;
Ok(out)
crates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -16,6 +16,7 @@
pub mod manifest;
pub mod sort;
+#[allow(clippy::cognitive_complexity)]
pub fn call_builtin(
context: Context,
loc: &Option<ExprLocation>,
@@ -23,7 +24,7 @@
name: &str,
args: &ArgsDesc,
) -> Result<Val> {
- Ok(match (ns, &name as &str) {
+ Ok(match (ns, name as &str) {
// arr/string/function
("std", "length") => parse_args!(context, "std.length", args, 1, [
0, x: [Val::Str|Val::Arr|Val::Obj], vec![ValType::Str, ValType::Arr, ValType::Obj];
crates/jrsonnet-evaluator/src/builtin/stdlib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/stdlib.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/stdlib.rs
@@ -22,7 +22,7 @@
}
jrsonnet_parser::parse(
- &jrsonnet_stdlib::STDLIB_STR,
+ jrsonnet_stdlib::STDLIB_STR,
&ParserSettings {
loc_data: true,
file_name: Rc::new(PathBuf::from("std.jsonnet")),
crates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -48,8 +48,8 @@
&self.0.super_obj
}
- pub fn new() -> Context {
- Context(Rc::new(ContextInternals {
+ pub fn new() -> Self {
+ Self(Rc::new(ContextInternals {
dollar: None,
this: None,
super_obj: None,
@@ -65,14 +65,14 @@
.cloned()
.ok_or_else(|| UnknownVariable(name))?)
}
- pub fn into_future(self, ctx: FutureContext) -> Context {
+ pub fn into_future(self, ctx: FutureContext) -> Self {
{
ctx.0.borrow_mut().replace(self);
}
ctx.unwrap()
}
- pub fn with_var(self, name: Rc<str>, value: Val) -> Context {
+ pub fn with_var(self, name: Rc<str>, value: Val) -> Self {
let mut new_bindings =
FxHashMap::with_capacity_and_hasher(1, BuildHasherDefault::default());
new_bindings.insert(name, resolved_lazy_val!(value));
@@ -85,7 +85,7 @@
new_dollar: Option<ObjValue>,
new_this: Option<ObjValue>,
new_super_obj: Option<ObjValue>,
- ) -> Context {
+ ) -> Self {
match Rc::try_unwrap(self.0) {
Ok(mut ctx) => {
// Extended context aren't used by anything else, we can freely mutate it without cloning
@@ -101,7 +101,7 @@
if !new_bindings.is_empty() {
ctx.bindings = ctx.bindings.extend(new_bindings);
}
- Context(Rc::new(ctx))
+ Self(Rc::new(ctx))
}
Err(ctx) => {
let dollar = new_dollar.or_else(|| ctx.dollar.clone());
@@ -112,7 +112,7 @@
} else {
ctx.bindings.clone().extend(new_bindings)
};
- Context(Rc::new(ContextInternals {
+ Self(Rc::new(ContextInternals {
dollar,
this,
super_obj,
@@ -127,7 +127,7 @@
new_dollar: Option<ObjValue>,
new_this: Option<ObjValue>,
new_super_obj: Option<ObjValue>,
- ) -> Result<Context> {
+ ) -> Result<Self> {
let this = new_this.or_else(|| self.0.this.clone());
let super_obj = new_super_obj.or_else(|| self.0.super_obj.clone());
let mut new =
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -95,10 +95,10 @@
Self(Box::new((e, StackTrace(vec![]))))
}
- pub fn error(&self) -> &Error {
+ pub const fn error(&self) -> &Error {
&(self.0).0
}
- pub fn trace(&self) -> &StackTrace {
+ pub const fn trace(&self) -> &StackTrace {
&(self.0).1
}
pub fn trace_mut(&mut self) -> &mut StackTrace {
crates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate.rs
@@ -82,9 +82,9 @@
})
}
-pub(crate) fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {
+pub fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {
Ok(match (a, b) {
- (Val::Str(v1), Val::Str(v2)) => Val::Str(((**v1).to_owned() + &v2).into()),
+ (Val::Str(v1), Val::Str(v2)) => Val::Str(((**v1).to_owned() + v2).into()),
// Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)
(Val::Num(n), Val::Str(o)) => Val::Str(format!("{}{}", n, o).into()),
@@ -111,7 +111,7 @@
b: &LocExpr,
) -> Result<Val> {
Ok(
- match (evaluate(context.clone(), &a)?.unwrap_if_lazy()?, op, b) {
+ match (evaluate(context.clone(), a)?.unwrap_if_lazy()?, op, b) {
(Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),
(Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),
(a, op, eb) => {
@@ -194,14 +194,14 @@
Ok(match specs.get(0) {
None => Some(vec![value(context)?]),
Some(CompSpec::IfSpec(IfSpecData(cond))) => {
- if evaluate(context.clone(), &cond)?.try_cast_bool("if spec")? {
+ if evaluate(context.clone(), cond)?.try_cast_bool("if spec")? {
evaluate_comp(context, value, &specs[1..])?
} else {
None
}
}
Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {
- match evaluate(context.clone(), &expr)?.unwrap_if_lazy()? {
+ match evaluate(context.clone(), expr)?.unwrap_if_lazy()? {
Val::Arr(list) => {
let mut out = Vec::new();
for item in list.iter() {
@@ -258,7 +258,7 @@
visibility,
value,
}) => {
- let name = evaluate_field_name(context.clone(), &name)?;
+ let name = evaluate_field_name(context.clone(), name)?;
if name.is_none() {
continue;
}
@@ -286,7 +286,7 @@
value,
..
}) => {
- let name = evaluate_field_name(context.clone(), &name)?;
+ let name = evaluate_field_name(context.clone(), name)?;
if name.is_none() {
continue;
}
@@ -320,7 +320,7 @@
pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {
Ok(match object {
- ObjBody::MemberList(members) => evaluate_member_list_object(context, &members)?,
+ ObjBody::MemberList(members) => evaluate_member_list_object(context, members)?,
ObjBody::ObjComp(obj) => {
let future_this = FutureObjValue::new();
let mut new_members = HashMap::new();
@@ -437,7 +437,7 @@
Parened(e) => evaluate(context, e)?,
Str(v) => Val::Str(v.clone()),
Num(v) => Val::new_checked_num(*v)?,
- BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, &v1, *o, &v2)?,
+ BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, v1, *o, v2)?,
UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,
Var(name) => push(
loc,
@@ -461,7 +461,7 @@
(Val::Obj(v), Val::Str(s)) => {
let sn = s.clone();
push(
- &loc,
+ loc,
|| format!("field <{}> access", sn),
|| {
if let Some(v) = v.get(s.clone())? {
@@ -563,7 +563,7 @@
&value.1,
|| "assertion condition".to_owned(),
|| {
- evaluate(context.clone(), &value)?
+ evaluate(context.clone(), value)?
.try_cast_bool("assertion condition should be of type `boolean`")
},
)?;
@@ -576,7 +576,7 @@
}
}
ErrorStmt(e) => push(
- &loc,
+ loc,
|| "error statement".to_owned(),
|| {
throw!(RuntimeError(
@@ -610,7 +610,7 @@
push(
loc,
|| format!("import {:?}", path),
- || with_state(|s| s.import_file(&import_location, path)),
+ || with_state(|s| s.import_file(import_location, path)),
)?
}
ImportStr(path) => {
@@ -620,7 +620,7 @@
.0;
let import_location = Rc::make_mut(&mut tmp);
import_location.pop();
- Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)
+ Val::Str(with_state(|s| s.import_file_str(import_location, path))?)
}
Literal(LiteralType::Super) => throw!(StandaloneSuper),
})
crates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function.rs
+++ b/crates/jrsonnet-evaluator/src/function.rs
@@ -75,7 +75,7 @@
let idx = params
.iter()
.position(|p| *p.0 == **name)
- .ok_or_else(|| UnknownFunctionParameter((&name as &str).to_owned()))?;
+ .ok_or_else(|| UnknownFunctionParameter((name as &str).to_owned()))?;
if idx >= params.len() {
throw!(TooManyArgsFunctionHas(params.len()));
@@ -111,7 +111,7 @@
Ok(body_ctx.unwrap_or(ctx).extend(out, None, None, None))
}
-pub(crate) fn place_args(
+pub fn place_args(
ctx: Context,
body_ctx: Option<Context>,
params: &ParamsDesc,
crates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/import.rs
+++ b/crates/jrsonnet-evaluator/src/import.rs
@@ -41,6 +41,7 @@
panic!("`as_any($self)` is not supported by dummy resolver")
}
}
+#[allow(clippy::use_self)]
impl Default for Box<dyn ImportResolver> {
fn default() -> Self {
Box::new(DummyImportResolver)
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -14,10 +14,10 @@
type Error = LocError;
fn try_from(v: &Val) -> Result<Self> {
Ok(match v {
- Val::Bool(b) => Value::Bool(*b),
- Val::Null => Value::Null,
- Val::Str(s) => Value::String((&s as &str).into()),
- Val::Num(n) => Value::Number(if n.fract() <= f64::EPSILON {
+ Val::Bool(b) => Self::Bool(*b),
+ Val::Null => Self::Null,
+ Val::Str(s) => Self::String((s as &str).into()),
+ Val::Num(n) => Self::Number(if n.fract() <= f64::EPSILON {
(*n as i64).into()
} else {
Number::from_f64(*n).expect("to json number")
@@ -28,7 +28,7 @@
for item in a.iter() {
out.push(item.try_into()?);
}
- Value::Array(out)
+ Self::Array(out)
}
Val::Obj(o) => {
let mut out = Map::new();
@@ -38,7 +38,7 @@
(&o.get(key)?.expect("field exists")).try_into()?,
);
}
- Value::Object(out)
+ Self::Object(out)
}
Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),
})
@@ -48,16 +48,16 @@
impl From<&Value> for Val {
fn from(v: &Value) -> Self {
match v {
- Value::Null => Val::Null,
- Value::Bool(v) => Val::Bool(*v),
- Value::Number(n) => Val::Num(n.as_f64().expect("as f64")),
- Value::String(s) => Val::Str((s as &str).into()),
+ Value::Null => Self::Null,
+ Value::Bool(v) => Self::Bool(*v),
+ Value::Number(n) => Self::Num(n.as_f64().expect("as f64")),
+ Value::String(s) => Self::Str((s as &str).into()),
Value::Array(a) => {
let mut out = Vec::with_capacity(a.len());
for v in a {
out.push(v.into());
}
- Val::Arr(Rc::new(out))
+ Self::Arr(Rc::new(out))
}
Value::Object(o) => {
let mut entries = HashMap::with_capacity(o.len());
@@ -72,7 +72,7 @@
},
);
}
- Val::Obj(ObjValue::new(None, Rc::new(entries)))
+ Self::Obj(ObjValue::new(None, Rc::new(entries)))
}
}
}
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -1,5 +1,6 @@
#![cfg_attr(feature = "unstable", feature(stmt_expr_attributes))]
#![allow(macro_expanded_macro_exports_accessed_by_absolute_paths)]
+#![warn(clippy::all, clippy::nursery)]
mod builtin;
mod ctx;
@@ -49,8 +50,8 @@
impl LazyBinding {
pub fn evaluate(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {
match self {
- LazyBinding::Bindable(v) => v(this, super_obj),
- LazyBinding::Bound(v) => Ok(v.clone()),
+ Self::Bindable(v) => v(this, super_obj),
+ Self::Bound(v) => Ok(v.clone()),
}
}
}
@@ -77,7 +78,7 @@
}
impl Default for EvaluationSettings {
fn default() -> Self {
- EvaluationSettings {
+ Self {
max_stack: 200,
max_trace: 20,
globals: Default::default(),
@@ -130,7 +131,7 @@
f: impl FnOnce() -> Result<T>,
) -> Result<T> {
if let Some(v) = e {
- with_state(|s| s.push(&v, frame_desc, f))
+ with_state(|s| s.push(v, frame_desc, f))
} else {
f()
}
@@ -359,10 +360,10 @@
/// Raw methods evaluate passed values but don't perform TLA execution
impl EvaluationState {
pub fn evaluate_file_raw(&self, name: &PathBuf) -> Result<Val> {
- self.run_in_state(|| self.import_file(&std::env::current_dir().expect("cwd"), &name))
+ self.run_in_state(|| self.import_file(&std::env::current_dir().expect("cwd"), name))
}
pub fn evaluate_file_raw_nocwd(&self, name: &PathBuf) -> Result<Val> {
- self.run_in_state(|| self.import_file(&PathBuf::from("."), &name))
+ self.run_in_state(|| self.import_file(&PathBuf::from("."), name))
}
/// Parses and evaluates the given snippet
pub fn evaluate_snippet_raw(&self, source: Rc<PathBuf>, code: Rc<str>) -> Result<Val> {
crates/jrsonnet-evaluator/src/map.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/map.rs
+++ b/crates/jrsonnet-evaluator/src/map.rs
@@ -15,10 +15,10 @@
match Rc::try_unwrap(self.0) {
Ok(mut map) => {
map.current.extend(new_layer);
- LayeredHashMap(Rc::new(map))
+ Self(Rc::new(map))
}
- Err(this) => LayeredHashMap(Rc::new(LayeredHashMapInternals {
- parent: Some(LayeredHashMap(this)),
+ Err(this) => Self(Rc::new(LayeredHashMapInternals {
+ parent: Some(Self(this)),
current: new_layer,
})),
}
@@ -31,20 +31,20 @@
{
(self.0)
.current
- .get(&key)
+ .get(key)
.or_else(|| self.0.parent.as_ref().and_then(|p| p.get(key)))
}
}
impl<K: Hash, V> Clone for LayeredHashMap<K, V> {
fn clone(&self) -> Self {
- LayeredHashMap(self.0.clone())
+ Self(self.0.clone())
}
}
impl<K: Hash + Eq, V> Default for LayeredHashMap<K, V> {
fn default() -> Self {
- LayeredHashMap(Rc::new(LayeredHashMapInternals {
+ Self(Rc::new(LayeredHashMapInternals {
parent: None,
current: FxHashMap::default(),
}))
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -47,23 +47,20 @@
}
impl ObjValue {
- pub fn new(
- super_obj: Option<ObjValue>,
- this_entries: Rc<HashMap<Rc<str>, ObjMember>>,
- ) -> ObjValue {
- ObjValue(Rc::new(ObjValueInternals {
+ pub fn new(super_obj: Option<Self>, this_entries: Rc<HashMap<Rc<str>, ObjMember>>) -> Self {
+ Self(Rc::new(ObjValueInternals {
super_obj,
this_entries,
value_cache: RefCell::new(HashMap::new()),
}))
}
- pub fn new_empty() -> ObjValue {
+ pub fn new_empty() -> Self {
Self::new(None, Rc::new(HashMap::new()))
}
- pub fn with_super(&self, super_obj: ObjValue) -> ObjValue {
+ pub fn with_super(&self, super_obj: Self) -> Self {
match &self.0.super_obj {
- None => ObjValue::new(Some(super_obj), self.0.this_entries.clone()),
- Some(v) => ObjValue::new(Some(v.with_super(super_obj)), self.0.this_entries.clone()),
+ None => Self::new(Some(super_obj), self.0.this_entries.clone()),
+ Some(v) => Self::new(Some(v.with_super(super_obj)), self.0.this_entries.clone()),
}
}
pub fn enum_fields(&self, handler: &impl Fn(&Rc<str>, &Visibility)) {
@@ -71,7 +68,7 @@
s.enum_fields(handler);
}
for (name, member) in self.0.this_entries.iter() {
- handler(&name, &member.visibility);
+ handler(name, &member.visibility);
}
}
pub fn fields_visibility(&self) -> IndexMap<Rc<str>, bool> {
@@ -107,7 +104,7 @@
pub fn get(&self, key: Rc<str>) -> Result<Option<Val>> {
Ok(self.get_raw(key, self)?)
}
- pub(crate) fn get_raw(&self, key: Rc<str>, real_this: &ObjValue) -> Result<Option<Val>> {
+ pub(crate) fn get_raw(&self, key: Rc<str>, real_this: &Self) -> Result<Option<Val>> {
let cache_key = (key.clone(), Rc::as_ptr(&real_this.0) as usize);
if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {
@@ -135,7 +132,7 @@
.insert(cache_key, value.clone());
Ok(value)
}
- fn evaluate_this(&self, v: &ObjMember, real_this: &ObjValue) -> Result<Val> {
+ fn evaluate_this(&self, v: &ObjMember, real_this: &Self) -> Result<Val> {
Ok(v.invoke
.evaluate(Some(real_this.clone()), self.0.super_obj.clone())?
.evaluate()?)
crates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth1mod location;23use crate::{EvaluationState, LocError};4pub use location::*;5use std::path::PathBuf;67/// The way paths should be displayed8pub enum PathResolver {9 /// Only filename10 FileName,11 /// Absolute path12 Absolute,13 /// Path relative to base directory14 Relative(PathBuf),15}1617impl PathResolver {18 pub fn resolve(&self, from: &PathBuf) -> String {19 match self {20 PathResolver::FileName => from.file_name().unwrap().to_string_lossy().into_owned(),21 PathResolver::Absolute => from.to_string_lossy().into_owned(),22 PathResolver::Relative(base) => {23 if from.is_relative() {24 return from.to_string_lossy().into_owned();25 }26 pathdiff::diff_paths(from, base)27 .unwrap()28 .to_string_lossy()29 .into_owned()30 }31 }32 }33}3435/// Implements pretty-printing of traces36pub trait TraceFormat {37 fn write_trace(38 &self,39 out: &mut dyn std::fmt::Write,40 evaluation_state: &EvaluationState,41 error: &LocError,42 ) -> Result<(), std::fmt::Error>;43 // fn print_trace(44 // &self,45 // evaluation_state: &EvaluationState,46 // error: &LocError,47 // ) -> Result<(), std::fmt::Error> {48 // self.write_trace(&mut std::fmt::stdout(), evaluation_state, error)49 // }50}5152fn print_code_location(53 out: &mut impl std::fmt::Write,54 start: &CodeLocation,55 end: &CodeLocation,56) -> Result<(), std::fmt::Error> {57 if start.line == end.line {58 if start.column == end.column {59 write!(out, "{}:{}", start.line, end.column - 1)?;60 } else {61 write!(out, "{}:{}-{}", start.line, start.column - 1, end.column)?;62 }63 } else {64 write!(65 out,66 "{}:{}-{}:{}",67 start.line,68 end.column - 1,69 start.line,70 end.column71 )?;72 }73 Ok(())74}7576/// vanilla-like jsonnet formatting77pub struct CompactFormat {78 pub resolver: PathResolver,79 pub padding: usize,80}8182impl TraceFormat for CompactFormat {83 fn write_trace(84 &self,85 out: &mut dyn std::fmt::Write,86 evaluation_state: &EvaluationState,87 error: &LocError,88 ) -> Result<(), std::fmt::Error> {89 writeln!(out, "{:?}", error.error())?;90 let file_names = error91 .trace()92 .093 .iter()94 .map(|el| {95 let resolved_path = self.resolver.resolve(&el.location.0);96 // TODO: Process all trace elements first97 let location = evaluation_state98 .map_source_locations(&el.location.0, &[el.location.1, el.location.2]);99 (resolved_path, location)100 })101 .map(|(mut n, location)| {102 use std::fmt::Write;103 write!(n, ":").unwrap();104 print_code_location(&mut n, &location[0], &location[1]).unwrap();105 n106 })107 .collect::<Vec<_>>();108 let align = file_names.iter().map(|e| e.len()).max().unwrap_or(0);109 for (i, (el, file)) in error.trace().0.iter().zip(file_names).enumerate() {110 if i != 0 {111 writeln!(out)?;112 }113 write!(114 out,115 "{:<p$}{:<w$}: {}",116 "",117 file,118 el.desc,119 p = self.padding,120 w = align121 )?;122 }123 Ok(())124 }125}126127pub struct JSFormat;128impl TraceFormat for JSFormat {129 fn write_trace(130 &self,131 out: &mut dyn std::fmt::Write,132 evaluation_state: &EvaluationState,133 error: &LocError,134 ) -> Result<(), std::fmt::Error> {135 writeln!(out, "{:?}", error.error())?;136 for (i, item) in error.trace().0.iter().enumerate() {137 if i != 0 {138 writeln!(out)?;139 }140 let desc = &item.desc;141 let source = item.location.clone();142 let start_end = evaluation_state.map_source_locations(&source.0, &[source.1, source.2]);143144 write!(145 out,146 " at {} ({}:{}:{})",147 desc,148 source.0.to_str().unwrap(),149 start_end[0].line,150 start_end[0].column,151 )?;152 }153 Ok(())154 }155}156157/// rustc-like trace displaying158#[cfg(feature = "explaining-traces")]159pub struct ExplainingFormat {160 pub resolver: PathResolver,161}162#[cfg(feature = "explaining-traces")]163impl TraceFormat for ExplainingFormat {164 fn write_trace(165 &self,166 out: &mut dyn std::fmt::Write,167 evaluation_state: &EvaluationState,168 error: &LocError,169 ) -> Result<(), std::fmt::Error> {170 use annotate_snippets::{171 display_list::{DisplayList, FormatOptions},172 snippet::{AnnotationType, Slice, Snippet, SourceAnnotation},173 };174 writeln!(out, "{:?}", error.error())?;175 let trace = &error.trace();176 for item in trace.0.iter() {177 let desc = &item.desc;178 let source = item.location.clone();179 let start_end = evaluation_state.map_source_locations(&source.0, &[source.1, source.2]);180181 let source_fragment: String = evaluation_state182 .get_source(&source.0)183 .unwrap()184 .chars()185 .skip(start_end[0].line_start_offset)186 .take(start_end[1].line_end_offset - start_end[0].line_start_offset)187 .collect();188189 let origin = self.resolver.resolve(&source.0);190 let snippet = Snippet {191 opt: FormatOptions {192 color: true,193 ..Default::default()194 },195 title: None,196 footer: vec![],197 slices: vec![Slice {198 source: &source_fragment,199 line_start: start_end[0].line,200 origin: Some(&origin),201 fold: false,202 annotations: vec![SourceAnnotation {203 label: desc,204 annotation_type: AnnotationType::Error,205 range: (206 source.1 - start_end[0].line_start_offset,207 source.2 - start_end[0].line_start_offset,208 ),209 }],210 }],211 };212213 let dl = DisplayList::from(snippet);214 writeln!(out, "{}", dl)?;215 }216 Ok(())217 }218}1mod location;23use crate::{EvaluationState, LocError};4pub use location::*;5use std::path::PathBuf;67/// The way paths should be displayed8pub enum PathResolver {9 /// Only filename10 FileName,11 /// Absolute path12 Absolute,13 /// Path relative to base directory14 Relative(PathBuf),15}1617impl PathResolver {18 pub fn resolve(&self, from: &PathBuf) -> String {19 match self {20 Self::FileName => from.file_name().unwrap().to_string_lossy().into_owned(),21 Self::Absolute => from.to_string_lossy().into_owned(),22 Self::Relative(base) => {23 if from.is_relative() {24 return from.to_string_lossy().into_owned();25 }26 pathdiff::diff_paths(from, base)27 .unwrap()28 .to_string_lossy()29 .into_owned()30 }31 }32 }33}3435/// Implements pretty-printing of traces36pub trait TraceFormat {37 fn write_trace(38 &self,39 out: &mut dyn std::fmt::Write,40 evaluation_state: &EvaluationState,41 error: &LocError,42 ) -> Result<(), std::fmt::Error>;43 // fn print_trace(44 // &self,45 // evaluation_state: &EvaluationState,46 // error: &LocError,47 // ) -> Result<(), std::fmt::Error> {48 // self.write_trace(&mut std::fmt::stdout(), evaluation_state, error)49 // }50}5152fn print_code_location(53 out: &mut impl std::fmt::Write,54 start: &CodeLocation,55 end: &CodeLocation,56) -> Result<(), std::fmt::Error> {57 if start.line == end.line {58 if start.column == end.column {59 write!(out, "{}:{}", start.line, end.column - 1)?;60 } else {61 write!(out, "{}:{}-{}", start.line, start.column - 1, end.column)?;62 }63 } else {64 write!(65 out,66 "{}:{}-{}:{}",67 start.line,68 end.column - 1,69 start.line,70 end.column71 )?;72 }73 Ok(())74}7576/// vanilla-like jsonnet formatting77pub struct CompactFormat {78 pub resolver: PathResolver,79 pub padding: usize,80}8182impl TraceFormat for CompactFormat {83 fn write_trace(84 &self,85 out: &mut dyn std::fmt::Write,86 evaluation_state: &EvaluationState,87 error: &LocError,88 ) -> Result<(), std::fmt::Error> {89 writeln!(out, "{:?}", error.error())?;90 let file_names = error91 .trace()92 .093 .iter()94 .map(|el| {95 let resolved_path = self.resolver.resolve(&el.location.0);96 // TODO: Process all trace elements first97 let location = evaluation_state98 .map_source_locations(&el.location.0, &[el.location.1, el.location.2]);99 (resolved_path, location)100 })101 .map(|(mut n, location)| {102 use std::fmt::Write;103 write!(n, ":").unwrap();104 print_code_location(&mut n, &location[0], &location[1]).unwrap();105 n106 })107 .collect::<Vec<_>>();108 let align = file_names.iter().map(|e| e.len()).max().unwrap_or(0);109 for (i, (el, file)) in error.trace().0.iter().zip(file_names).enumerate() {110 if i != 0 {111 writeln!(out)?;112 }113 write!(114 out,115 "{:<p$}{:<w$}: {}",116 "",117 file,118 el.desc,119 p = self.padding,120 w = align121 )?;122 }123 Ok(())124 }125}126127pub struct JSFormat;128impl TraceFormat for JSFormat {129 fn write_trace(130 &self,131 out: &mut dyn std::fmt::Write,132 evaluation_state: &EvaluationState,133 error: &LocError,134 ) -> Result<(), std::fmt::Error> {135 writeln!(out, "{:?}", error.error())?;136 for (i, item) in error.trace().0.iter().enumerate() {137 if i != 0 {138 writeln!(out)?;139 }140 let desc = &item.desc;141 let source = item.location.clone();142 let start_end = evaluation_state.map_source_locations(&source.0, &[source.1, source.2]);143144 write!(145 out,146 " at {} ({}:{}:{})",147 desc,148 source.0.to_str().unwrap(),149 start_end[0].line,150 start_end[0].column,151 )?;152 }153 Ok(())154 }155}156157/// rustc-like trace displaying158#[cfg(feature = "explaining-traces")]159pub struct ExplainingFormat {160 pub resolver: PathResolver,161}162#[cfg(feature = "explaining-traces")]163impl TraceFormat for ExplainingFormat {164 fn write_trace(165 &self,166 out: &mut dyn std::fmt::Write,167 evaluation_state: &EvaluationState,168 error: &LocError,169 ) -> Result<(), std::fmt::Error> {170 use annotate_snippets::{171 display_list::{DisplayList, FormatOptions},172 snippet::{AnnotationType, Slice, Snippet, SourceAnnotation},173 };174 writeln!(out, "{:?}", error.error())?;175 let trace = &error.trace();176 for item in trace.0.iter() {177 let desc = &item.desc;178 let source = item.location.clone();179 let start_end = evaluation_state.map_source_locations(&source.0, &[source.1, source.2]);180181 let source_fragment: String = evaluation_state182 .get_source(&source.0)183 .unwrap()184 .chars()185 .skip(start_end[0].line_start_offset)186 .take(start_end[1].line_end_offset - start_end[0].line_start_offset)187 .collect();188189 let origin = self.resolver.resolve(&source.0);190 let snippet = Snippet {191 opt: FormatOptions {192 color: true,193 ..Default::default()194 },195 title: None,196 footer: vec![],197 slices: vec![Slice {198 source: &source_fragment,199 line_start: start_end[0].line,200 origin: Some(&origin),201 fold: false,202 annotations: vec![SourceAnnotation {203 label: desc,204 annotation_type: AnnotationType::Error,205 range: (206 source.1 - start_end[0].line_start_offset,207 source.2 - start_end[0].line_start_offset,208 ),209 }],210 }],211 };212213 let dl = DisplayList::from(snippet);214 writeln!(out, "{}", dl)?;215 }216 Ok(())217 }218}crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -25,10 +25,10 @@
pub struct LazyVal(Rc<RefCell<LazyValInternals>>);
impl LazyVal {
pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {
- LazyVal(Rc::new(RefCell::new(LazyValInternals::Waiting(f))))
+ Self(Rc::new(RefCell::new(LazyValInternals::Waiting(f))))
}
pub fn new_resolved(val: Val) -> Self {
- LazyVal(Rc::new(RefCell::new(LazyValInternals::Computed(val))))
+ Self(Rc::new(RefCell::new(LazyValInternals::Computed(val))))
}
pub fn evaluate(&self) -> Result<Val> {
let new_value = match &*self.0.borrow() {
@@ -84,22 +84,22 @@
impl PartialEq for FuncVal {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
- (FuncVal::Normal(a), FuncVal::Normal(b)) => a == b,
- (FuncVal::Intrinsic(ans, an), FuncVal::Intrinsic(bns, bn)) => ans == bns && an == bn,
- (FuncVal::NativeExt(an, _), FuncVal::NativeExt(bn, _)) => an == bn,
+ (Self::Normal(a), Self::Normal(b)) => a == b,
+ (Self::Intrinsic(ans, an), Self::Intrinsic(bns, bn)) => ans == bns && an == bn,
+ (Self::NativeExt(an, _), Self::NativeExt(bn, _)) => an == bn,
(..) => false,
}
}
}
impl FuncVal {
pub fn is_ident(&self) -> bool {
- matches!(&self, FuncVal::Intrinsic(ns, n) if ns as &str == "std" && n as &str == "id")
+ matches!(&self, Self::Intrinsic(ns, n) if ns as &str == "std" && n as &str == "id")
}
pub fn name(&self) -> Rc<str> {
match self {
- FuncVal::Normal(normal) => normal.name.clone(),
- FuncVal::Intrinsic(ns, name) => format!("intrinsic.{}.{}", ns, name).into(),
- FuncVal::NativeExt(n, _) => format!("native.{}", n).into(),
+ Self::Normal(normal) => normal.name.clone(),
+ Self::Intrinsic(ns, name) => format!("intrinsic.{}.{}", ns, name).into(),
+ Self::NativeExt(n, _) => format!("native.{}", n).into(),
}
}
pub fn evaluate(
@@ -110,7 +110,7 @@
tailstrict: bool,
) -> Result<Val> {
match self {
- FuncVal::Normal(func) => {
+ Self::Normal(func) => {
let ctx = parse_function_call(
call_ctx,
Some(func.ctx.clone()),
@@ -120,8 +120,8 @@
)?;
evaluate(ctx, &func.body)
}
- FuncVal::Intrinsic(ns, name) => call_builtin(call_ctx, loc, &ns, &name, args),
- FuncVal::NativeExt(_name, handler) => {
+ Self::Intrinsic(ns, name) => call_builtin(call_ctx, loc, ns, name, args),
+ Self::NativeExt(_name, handler) => {
let args = parse_function_call(call_ctx, None, &handler.params, args, true)?;
let mut out_args = Vec::with_capacity(handler.params.len());
for p in handler.params.0.iter() {
@@ -139,7 +139,7 @@
tailstrict: bool,
) -> Result<Val> {
match self {
- FuncVal::Normal(func) => {
+ Self::Normal(func) => {
let ctx = parse_function_call_map(
call_ctx,
Some(func.ctx.clone()),
@@ -149,19 +149,19 @@
)?;
evaluate(ctx, &func.body)
}
- FuncVal::Intrinsic(_, _) => todo!(),
- FuncVal::NativeExt(_, _) => todo!(),
+ Self::Intrinsic(_, _) => todo!(),
+ Self::NativeExt(_, _) => todo!(),
}
}
pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {
match self {
- FuncVal::Normal(func) => {
+ Self::Normal(func) => {
let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;
evaluate(ctx, &func.body)
}
- FuncVal::Intrinsic(_, _) => todo!(),
- FuncVal::NativeExt(_, _) => todo!(),
+ Self::Intrinsic(_, _) => todo!(),
+ Self::NativeExt(_, _) => todo!(),
}
}
}
@@ -177,7 +177,7 @@
Func,
}
impl ValType {
- pub fn name(&self) -> &'static str {
+ pub const fn name(&self) -> &'static str {
use ValType::*;
match self {
Bool => "boolean",
@@ -227,9 +227,9 @@
impl Val {
/// Creates `Val::Num` after checking for numeric overflow.
/// As numbers are `f64`, we can just check for their finity.
- pub fn new_checked_num(num: f64) -> Result<Val> {
+ pub fn new_checked_num(num: f64) -> Result<Self> {
if num.is_finite() {
- Ok(Val::Num(num))
+ Ok(Self::Num(num))
} else {
throw!(RuntimeError("overflow".into()))
}
@@ -245,24 +245,24 @@
}
pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {
self.assert_type(context, ValType::Bool)?;
- Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Bool(v), v))
+ Ok(matches_unwrap!(self.unwrap_if_lazy()?, Self::Bool(v), v))
}
pub fn try_cast_str(self, context: &'static str) -> Result<Rc<str>> {
self.assert_type(context, ValType::Str)?;
- Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Str(v), v))
+ Ok(matches_unwrap!(self.unwrap_if_lazy()?, Self::Str(v), v))
}
pub fn try_cast_num(self, context: &'static str) -> Result<f64> {
self.assert_type(context, ValType::Num)?;
- Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Num(v), v))
+ Ok(matches_unwrap!(self.unwrap_if_lazy()?, Self::Num(v), v))
}
pub fn inplace_unwrap(&mut self) -> Result<()> {
- while let Val::Lazy(lazy) = self {
+ while let Self::Lazy(lazy) = self {
*self = lazy.evaluate()?;
}
Ok(())
}
pub fn unwrap_if_lazy(&self) -> Result<Self> {
- Ok(if let Val::Lazy(v) = self {
+ Ok(if let Self::Lazy(v) = self {
v.evaluate()?.unwrap_if_lazy()?
} else {
self.clone()
@@ -270,27 +270,27 @@
}
pub fn value_type(&self) -> Result<ValType> {
Ok(match self {
- Val::Str(..) => ValType::Str,
- Val::Num(..) => ValType::Num,
- Val::Arr(..) => ValType::Arr,
- Val::Obj(..) => ValType::Obj,
- Val::Bool(_) => ValType::Bool,
- Val::Null => ValType::Null,
- Val::Func(..) => ValType::Func,
- Val::Lazy(_) => self.clone().unwrap_if_lazy()?.value_type()?,
+ Self::Str(..) => ValType::Str,
+ Self::Num(..) => ValType::Num,
+ Self::Arr(..) => ValType::Arr,
+ Self::Obj(..) => ValType::Obj,
+ Self::Bool(_) => ValType::Bool,
+ Self::Null => ValType::Null,
+ Self::Func(..) => ValType::Func,
+ Self::Lazy(_) => self.clone().unwrap_if_lazy()?.value_type()?,
})
}
pub fn to_string(&self) -> Result<Rc<str>> {
Ok(match self.unwrap_if_lazy()? {
- Val::Bool(true) => "true".into(),
- Val::Bool(false) => "false".into(),
- Val::Null => "null".into(),
- Val::Str(s) => s,
+ Self::Bool(true) => "true".into(),
+ Self::Bool(false) => "false".into(),
+ Self::Null => "null".into(),
+ Self::Str(s) => s,
v => manifest_json_ex(
&v,
&ManifestJsonOptions {
- padding: &"",
+ padding: "",
mtype: ManifestType::ToString,
},
)?
@@ -301,7 +301,7 @@
/// Expects value to be object, outputs (key, manifested value) pairs
pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(Rc<str>, Rc<str>)>> {
let obj = match self {
- Val::Obj(obj) => obj,
+ Self::Obj(obj) => obj,
_ => throw!(MultiManifestOutputIsNotAObject),
};
let keys = obj.visible_fields();
@@ -319,7 +319,7 @@
/// Expects value to be array, outputs manifested values
pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<Rc<str>>> {
let arr = match self {
- Val::Arr(a) => a,
+ Self::Arr(a) => a,
_ => throw!(StreamManifestOutputIsNotAArray),
};
let mut out = Vec::with_capacity(arr.len());
@@ -333,7 +333,7 @@
Ok(match ty {
ManifestFormat::YamlStream(format) => {
let arr = match self {
- Val::Arr(a) => a,
+ Self::Arr(a) => a,
_ => throw!(StreamManifestOutputIsNotAArray),
};
let mut out = String::new();
@@ -358,7 +358,7 @@
ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,
ManifestFormat::Json(padding) => self.to_json(*padding)?,
ManifestFormat::String => match self {
- Val::Str(s) => s.clone(),
+ Self::Str(s) => s.clone(),
_ => throw!(StringManifestOutputIsNotAString),
},
})
@@ -384,7 +384,7 @@
#[cfg(feature = "faster")]
pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {
manifest_json_ex(
- &self,
+ self,
&ManifestJsonOptions {
padding: &" ".repeat(padding),
mtype: ManifestType::Std,
@@ -441,7 +441,7 @@
}
}
-fn is_function_like(val: &Val) -> bool {
+const fn is_function_like(val: &Val) -> bool {
matches!(val, Val::Func(_))
}