difftreelog
style fix formatting
in: master
31 files changed
crates/jrsonnet-evaluator/src/analyze.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/analyze.rs
+++ b/crates/jrsonnet-evaluator/src/analyze.rs
@@ -21,10 +21,10 @@
use jrsonnet_gcmodule::Acyclic;
use jrsonnet_interner::IStr;
use jrsonnet_ir::{
- function::FunctionSignature, ArgsDesc, AssertExpr, AssertStmt, BinaryOp, BinaryOpType,
- BindSpec, CompSpec, Destruct, Expr, ExprParams, FieldName, ForSpecData, IfElse, IfSpecData,
- ImportKind, LiteralType, NumValue, ObjBody, ObjComp, ObjMembers, Slice, SliceDesc, Span,
- Spanned, UnaryOpType, Visibility,
+ ArgsDesc, AssertExpr, AssertStmt, BinaryOp, BinaryOpType, BindSpec, CompSpec, Destruct, Expr,
+ ExprParams, FieldName, ForSpecData, IfElse, IfSpecData, ImportKind, LiteralType, NumValue,
+ ObjBody, ObjComp, ObjMembers, Slice, SliceDesc, Span, Spanned, UnaryOpType, Visibility,
+ function::FunctionSignature,
};
use rustc_hash::FxHashMap;
use smallvec::SmallVec;
crates/jrsonnet-evaluator/src/arr/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/mod.rs
+++ b/crates/jrsonnet-evaluator/src/arr/mod.rs
@@ -5,9 +5,9 @@
rc::Rc,
};
-use jrsonnet_gcmodule::{cc_dyn, Cc};
+use jrsonnet_gcmodule::{Cc, cc_dyn};
-use crate::{analyze::LExpr, function::NativeFn, typed::IntoUntyped, Context, Result, Thunk, Val};
+use crate::{Context, Result, Thunk, Val, analyze::LExpr, function::NativeFn, typed::IntoUntyped};
mod spec;
pub use spec::{ArrayLike, *};
crates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/spec.rs
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -11,13 +11,13 @@
use super::ArrValue;
use crate::{
+ Context, Error, ObjValue, Result, Thunk, Val,
analyze::LExpr,
error::ErrorKind::InfiniteRecursionDetected,
evaluate::evaluate,
function::NativeFn,
typed::{IntoUntyped, Typed},
val::ThunkValue,
- Context, Error, ObjValue, Result, Thunk, Val,
};
pub trait ArrayLike: Any + Trace + Debug {
crates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -4,7 +4,7 @@
use jrsonnet_gcmodule::{Cc, Trace};
use jrsonnet_interner::IStr;
-use crate::{analyze::LocalId, error, error::ErrorKind::*, Pending, Result, SupThis, Thunk, Val};
+use crate::{Pending, Result, SupThis, Thunk, Val, analyze::LocalId, error, error::ErrorKind::*};
#[derive(Debug, Trace, Clone, Educe)]
#[educe(PartialEq)]
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -9,10 +9,10 @@
use thiserror::Error;
use crate::{
+ ObjValue, ResolvePathOwned,
function::{CallLocation, FunctionSignature, ParamName},
stdlib::format::FormatError,
typed::TypeLocError,
- ObjValue, ResolvePathOwned,
};
#[derive(Debug, Clone, Acyclic)]
@@ -286,11 +286,11 @@
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- writeln!(f, "{}", self.0 .0)?;
- for el in &self.0 .1 .0 {
+ writeln!(f, "{}", self.0.0)?;
+ for el in &self.0.1.0 {
write!(f, "\t{}", el.desc)?;
if let Some(loc) = &el.location {
- write!(f, "at {}", loc.0 .0 .0)?;
+ write!(f, "at {}", loc.0.0.0)?;
loc.0.map_source_locations(&[loc.1, loc.2]);
}
writeln!(f)?;
crates/jrsonnet-evaluator/src/evaluate/compspec.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/compspec.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/compspec.rs
@@ -7,12 +7,12 @@
evaluate_field_member_static, evaluate_field_member_unbound,
};
use crate::{
+ Context, ContextBuilder, ObjValue, ObjValueBuilder, Pending, Result, Thunk, Val,
analyze::{LArrComp, LBind, LCompSpec, LDestruct, LExpr, LFieldMember, LObjComp, LocalId},
arr::ArrValue,
bail,
error::ErrorKind::*,
evaluate::evaluate,
- Context, ContextBuilder, ObjValue, ObjValueBuilder, Pending, Result, Thunk, Val,
};
trait CompCollector {
crates/jrsonnet-evaluator/src/evaluate/destructure.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
@@ -3,10 +3,10 @@
use jrsonnet_gcmodule::Trace;
use crate::{
+ Context, ContextBuilder, Pending, Result, SupThis, Thunk, Unbound, Val,
analyze::{LBind, LDestruct, LDestructField, LDestructRest, LExpr, LocalId},
bail,
evaluate::evaluate,
- Context, ContextBuilder, Pending, Result, SupThis, Thunk, Unbound, Val,
};
#[allow(dead_code, reason = "not dead in exp-destruct")]
@@ -97,7 +97,7 @@
use jrsonnet_interner::IStr;
use rustc_hash::FxHashSet;
- use crate::{bail, ObjValueBuilder};
+ use crate::{ObjValueBuilder, bail};
let captured_fields: FxHashSet<IStr> = fields.iter().map(|f| f.name.clone()).collect();
let field_names: Vec<(IStr, bool)> = fields
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -11,19 +11,20 @@
operator::evaluate_binary_op_special,
};
use crate::{
+ Context, Error, ObjValue, ObjValueBuilder, ObjectAssertion, Result, ResultExt as _, SupThis,
+ Unbound, Val,
analyze::{
LArgsDesc, LAssertStmt, LExpr, LFieldMember, LFieldName, LFunction, LIndexPart, LObjBody,
LObjMembers,
},
bail,
- error::{suggest_object_fields, ErrorKind::*},
+ error::{ErrorKind::*, suggest_object_fields},
evaluate::operator::evaluate_unary_op,
- function::{prepared::PreparedFuncVal, CallLocation, FuncDesc, FuncVal},
+ function::{CallLocation, FuncDesc, FuncVal, prepared::PreparedFuncVal},
in_frame, runtime_error,
typed::FromUntyped as _,
val::{CachedUnbound, Thunk},
- with_state, Context, Error, ObjValue, ObjValueBuilder, ObjectAssertion, Result, ResultExt as _,
- SupThis, Unbound, Val,
+ with_state,
};
pub mod compspec;
crates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -3,6 +3,7 @@
use jrsonnet_ir::{BinaryOpType, UnaryOpType};
use crate::{
+ Context, Result, Val,
analyze::LExpr,
arr::ArrValue,
bail, error,
@@ -10,8 +11,7 @@
evaluate::evaluate,
stdlib::std_format,
typed::IntoUntyped as _,
- val::{equals, StrValue},
- Context, Result, Val,
+ val::{StrValue, equals},
};
pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {
crates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -8,13 +8,13 @@
use self::{
builtin::Builtin,
- prepared::{parse_prepared_builtin_call, PreparedCall},
+ prepared::{PreparedCall, parse_prepared_builtin_call},
};
use crate::{
+ Context, ContextBuilder, Result, Thunk, Val,
analyze::{LDestruct, LExpr, LFunction},
evaluate::{destructure::destruct, ensure_sufficient_stack, evaluate, evaluate_trivial},
function::builtin::BuiltinFunc,
- Context, ContextBuilder, Result, Thunk, Val,
};
pub mod builtin;
@@ -210,8 +210,7 @@
return false;
}
#[allow(irrefutable_let_patterns, reason = "refutable with exp-destruct")]
- let LDestruct::Full(id) = ¶m.destruct
- else {
+ let LDestruct::Full(id) = ¶m.destruct else {
return false;
};
matches!(&*desc.func.body, LExpr::Local(v) if v == id)
crates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/parse.rs
+++ b/crates/jrsonnet-evaluator/src/function/parse.rs
@@ -1,9 +1,9 @@
use std::rc::Rc;
use crate::{
+ Context, ContextBuilder, Result, Thunk,
analyze::LFunction,
evaluate::{destructure::destruct, evaluate},
- Context, ContextBuilder, Result, Thunk,
};
/// Creates Context with all argument default values applied
crates/jrsonnet-evaluator/src/function/prepared.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/prepared.rs
+++ b/crates/jrsonnet-evaluator/src/function/prepared.rs
@@ -5,10 +5,7 @@
use rustc_hash::FxHashSet;
use super::{CallLocation, FuncVal};
-use crate::{
- Result, Thunk, Val, bail,
- error::ErrorKind::*,
-};
+use crate::{Result, Thunk, Val, bail, error::ErrorKind::*};
#[derive(Debug, Trace, Clone)]
pub struct PreparedFuncVal {
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -3,16 +3,16 @@
use jrsonnet_interner::{IBytes, IStr};
use jrsonnet_ir::NumValue;
use serde::{
+ Deserialize, Serialize, Serializer,
de::{self, Visitor},
ser::{
Error, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple,
SerializeTupleStruct, SerializeTupleVariant,
},
- Deserialize, Serialize, Serializer,
};
use crate::{
- in_description_frame, runtime_error, Error as JrError, ObjValue, ObjValueBuilder, Result, Val,
+ Error as JrError, ObjValue, ObjValueBuilder, Result, Val, in_description_frame, runtime_error,
};
impl<'de> Deserialize<'de> for Val {
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -39,7 +39,7 @@
pub use evaluate::ensure_sufficient_stack;
use function::CallLocation;
pub use import::*;
-use jrsonnet_gcmodule::{cc_dyn, Cc, Trace};
+use jrsonnet_gcmodule::{Cc, Trace, cc_dyn};
pub use jrsonnet_interner::{IBytes, IStr};
use jrsonnet_ir::Expr;
pub use jrsonnet_ir::{NumValue, Source, SourcePath, Span};
crates/jrsonnet-evaluator/src/manifest.rsdiffbeforeafterboth1use std::{borrow::Cow, fmt::Write, hint::black_box, ptr};23use crate::{4 bail, evaluate::ensure_sufficient_stack, in_description_frame, Error,5 Result, ResultExt, Val,6};78pub trait ManifestFormat {9 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()>;10 fn manifest(&self, val: Val) -> Result<String> {11 let mut out = String::new();12 self.manifest_buf(val, &mut out)?;13 Ok(out)14 }15 /// When outputing to file, is it safe to append a trailing newline (I.e newline won't change16 /// the meaning).17 ///18 /// Default implementation returns `true`19 fn file_trailing_newline(&self) -> bool {20 true21 }22}23impl<T> ManifestFormat for Box<T>24where25 T: ManifestFormat + ?Sized,26{27 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {28 let inner = &**self;29 inner.manifest_buf(val, buf)30 }31 fn file_trailing_newline(&self) -> bool {32 let inner = &**self;33 inner.file_trailing_newline()34 }35}36impl<T> ManifestFormat for &'_ T37where38 T: ManifestFormat + ?Sized,39{40 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {41 let inner = &**self;42 inner.manifest_buf(val, buf)43 }44 fn file_trailing_newline(&self) -> bool {45 let inner = &**self;46 inner.file_trailing_newline()47 }48}4950pub struct BlackBoxFormat;51impl ManifestFormat for BlackBoxFormat {52 #[allow(clippy::only_used_in_recursion)]53 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {54 match val {55 Val::Bool(v) => {56 black_box(v);57 }58 val @ Val::Null => {59 black_box(val);60 }61 Val::Str(str_value) => {62 black_box(format!("{str_value}"));63 }64 Val::Num(num_value) => {65 black_box(num_value);66 }67 Val::Arr(arr_value) => {68 for ele in arr_value.iter() {69 let ele = ele?;70 self.manifest_buf(ele, buf)?;71 }72 }73 Val::Obj(obj_value) => {74 for (name, value) in obj_value.iter(75 #[cfg(feature = "exp-preserve-order")]76 true,77 ) {78 black_box(name);79 let value = value?;80 self.manifest_buf(value, buf)?;81 }82 }83 Val::Func(func_val) => {84 black_box(func_val);85 bail!("tried to manifest function")86 }87 #[cfg(feature = "exp-bigint")]88 Val::BigInt(n) => {89 black_box(n);90 }91 }92 Ok(())93 }94}9596#[derive(PartialEq, Eq, Clone, Copy)]97enum JsonFormatting {98 // Applied in manifestification99 Manifest,100 /// Used for std.manifestJson101 /// Empty array/objects extends to "[\n\n]" instead of "[ ]" as in manifest102 Std,103 /// No line breaks, used in `obj+''`104 ToString,105 /// Minified json106 Minify,107}108109pub struct JsonFormat<'s> {110 padding: Cow<'s, str>,111 mtype: JsonFormatting,112 newline: &'s str,113 key_val_sep: &'s str,114 #[cfg(feature = "exp-preserve-order")]115 preserve_order: bool,116 #[cfg(feature = "exp-bigint")]117 preserve_bigints: bool,118}119120impl<'s> JsonFormat<'s> {121 // Minifying format122 pub fn minify(#[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Self {123 Self {124 padding: Cow::Borrowed(""),125 mtype: JsonFormatting::Minify,126 newline: "\n",127 key_val_sep: ":",128 #[cfg(feature = "exp-preserve-order")]129 preserve_order,130 #[cfg(feature = "exp-bigint")]131 preserve_bigints: false,132 }133 }134 /// Same format as std.toString, except does not keeps top-level string as-is135 /// To avoid confusion, the format is private in jrsonnet, use [`ToStringFormat`] instead136 const fn std_to_string_helper() -> Self {137 Self {138 padding: Cow::Borrowed(""),139 mtype: JsonFormatting::ToString,140 newline: "\n",141 key_val_sep: ": ",142 #[cfg(feature = "exp-preserve-order")]143 preserve_order: false,144 #[cfg(feature = "exp-bigint")]145 preserve_bigints: false,146 }147 }148 pub fn std_to_json(149 padding: String,150 newline: &'s str,151 key_val_sep: &'s str,152 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,153 ) -> Self {154 Self {155 padding: Cow::Owned(padding),156 mtype: JsonFormatting::Std,157 newline,158 key_val_sep,159 #[cfg(feature = "exp-preserve-order")]160 preserve_order,161 #[cfg(feature = "exp-bigint")]162 preserve_bigints: false,163 }164 }165 // Same format as CLI manifestification166 pub fn cli(167 padding: usize,168 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,169 ) -> Self {170 if padding == 0 {171 return Self::minify(172 #[cfg(feature = "exp-preserve-order")]173 preserve_order,174 );175 }176 Self {177 padding: Cow::Owned(" ".repeat(padding)),178 mtype: JsonFormatting::Manifest,179 newline: "\n",180 key_val_sep: ": ",181 #[cfg(feature = "exp-preserve-order")]182 preserve_order,183 #[cfg(feature = "exp-bigint")]184 preserve_bigints: false,185 }186 }187 // Same format as CLI manifestification188 pub fn debug() -> Self {189 Self {190 padding: Cow::Borrowed(" "),191 mtype: JsonFormatting::Manifest,192 newline: "\n",193 key_val_sep: ": ",194 #[cfg(feature = "exp-preserve-order")]195 preserve_order: true,196 #[cfg(feature = "exp-bigint")]197 preserve_bigints: true,198 }199 }200}201impl Default for JsonFormat<'static> {202 fn default() -> Self {203 Self {204 padding: Cow::Borrowed(" "),205 mtype: JsonFormatting::Manifest,206 newline: "\n",207 key_val_sep: ": ",208 #[cfg(feature = "exp-preserve-order")]209 preserve_order: false,210 #[cfg(feature = "exp-bigint")]211 preserve_bigints: false,212 }213 }214}215216pub fn manifest_json_ex(val: &Val, options: &JsonFormat<'_>) -> Result<String> {217 let mut out = String::new();218 manifest_json_ex_buf(val, &mut out, &mut String::new(), options)?;219 Ok(out)220}221222#[allow(clippy::too_many_lines)]223fn manifest_json_ex_buf(224 val: &Val,225 buf: &mut String,226 cur_padding: &mut String,227 options: &JsonFormat<'_>,228) -> Result<()> {229 use JsonFormatting::*;230231 let mtype = options.mtype;232 match val {233 Val::Bool(v) => {234 if *v {235 buf.push_str("true");236 } else {237 buf.push_str("false");238 }239 }240 Val::Null => buf.push_str("null"),241 Val::Str(s) => {242 buf.reserve(2 + s.len());243 buf.push('"');244 s.chunks(&mut |c| {245 escape_string_json_buf_raw(c, buf);246 });247 buf.push('"');248 }249 Val::Num(n) => write!(buf, "{n}").unwrap(),250 #[cfg(feature = "exp-bigint")]251 Val::BigInt(n) => {252 if options.preserve_bigints {253 write!(buf, "{n}").unwrap();254 } else {255 write!(buf, "{:?}", n.to_string()).unwrap();256 }257 }258 Val::Arr(items) => ensure_sufficient_stack(|| {259 buf.push('[');260261 let old_len = cur_padding.len();262 cur_padding.push_str(&options.padding);263264 let mut had_items = false;265 for (i, item) in items.iter().enumerate() {266 had_items = true;267 let item = item.with_description(|| format!("elem <{i}> evaluation"))?;268269 if i != 0 {270 buf.push(',');271 }272 match mtype {273 Manifest | Std => {274 buf.push_str(options.newline);275 buf.push_str(cur_padding);276 }277 ToString if i != 0 => buf.push(' '),278 Minify | ToString => {}279 }280281 in_description_frame(282 || format!("elem <{i}> manifestification"),283 || manifest_json_ex_buf(&item, buf, cur_padding, options),284 )?;285 }286287 cur_padding.truncate(old_len);288289 match mtype {290 Manifest | ToString if !had_items => {291 // Empty array as "[ ]"292 buf.push(' ');293 }294 Manifest => {295 buf.push_str(options.newline);296 buf.push_str(cur_padding);297 }298 Std => {299 if !had_items {300 // Stdlib formats empty array as "[\n\n]"301 buf.push_str(options.newline);302 }303 buf.push_str(options.newline);304 buf.push_str(cur_padding);305 }306 Minify | ToString => {}307 }308309 buf.push(']');310 Ok::<_, Error>(())311 })?,312 Val::Obj(obj) => ensure_sufficient_stack(|| {313 obj.run_assertions()?;314 buf.push('{');315316 let old_len = cur_padding.len();317 cur_padding.push_str(&options.padding);318319 let mut had_fields = false;320 for (i, (key, value)) in obj321 .iter(322 #[cfg(feature = "exp-preserve-order")]323 options.preserve_order,324 )325 .enumerate()326 {327 had_fields = true;328 let value = value.with_description(|| format!("field <{key}> evaluation"))?;329330 if i != 0 {331 buf.push(',');332 }333 match mtype {334 Manifest | Std => {335 buf.push_str(options.newline);336 buf.push_str(cur_padding);337 }338 ToString if i != 0 => buf.push(' '),339 Minify | ToString => {}340 }341342 escape_string_json_buf(&key, buf);343 buf.push_str(options.key_val_sep);344 in_description_frame(345 || format!("field <{key}> manifestification"),346 || manifest_json_ex_buf(&value, buf, cur_padding, options),347 )?;348 }349350 cur_padding.truncate(old_len);351352 match mtype {353 Manifest | ToString if !had_fields => {354 // Empty object as "{ }"355 buf.push(' ');356 }357 Manifest => {358 buf.push_str(options.newline);359 buf.push_str(cur_padding);360 }361 Std => {362 if !had_fields {363 // Stdlib formats empty object as "{\n\n}"364 buf.push_str(options.newline);365 }366 buf.push_str(options.newline);367 buf.push_str(cur_padding);368 }369 Minify | ToString => {}370 }371372 buf.push('}');373 Ok::<_, Error>(())374 })?,375 Val::Func(_) => bail!("tried to manifest function"),376 }377 Ok(())378}379380impl ManifestFormat for JsonFormat<'_> {381 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {382 manifest_json_ex_buf(&val, buf, &mut String::new(), self)383 }384}385386/// Same as [`JsonFormat`] with pre-set options, but top-level string is serialized as-is,387/// without quoting.388pub struct ToStringFormat;389impl ManifestFormat for ToStringFormat {390 fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {391 const JSON_TO_STRING: JsonFormat = JsonFormat::std_to_string_helper();392 if let Some(str) = val.as_str() {393 out.push_str(&str);394 return Ok(());395 }396 #[cfg(feature = "exp-bigint")]397 if let Some(int) = val.as_bigint() {398 out.push_str(&int.to_str_radix(10));399 return Ok(());400 }401 JSON_TO_STRING.manifest_buf(val, out)402 }403 fn file_trailing_newline(&self) -> bool {404 false405 }406}407pub struct StringFormat;408impl ManifestFormat for StringFormat {409 fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {410 let Val::Str(s) = val else {411 bail!(412 "output should be string for string manifest format, got {}",413 val.value_type()414 )415 };416 write!(out, "{s}").unwrap();417 Ok(())418 }419 fn file_trailing_newline(&self) -> bool {420 false421 }422}423424pub struct YamlStreamFormat<I> {425 inner: I,426 c_document_end: bool,427 end_newline: bool,428}429impl<I> YamlStreamFormat<I> {430 pub fn std_yaml_stream(inner: I, c_document_end: bool) -> Self {431 Self {432 inner,433 c_document_end,434 // Stdlib format always inserts useless newline at the end435 end_newline: true,436 }437 }438 pub fn cli(inner: I) -> Self {439 Self {440 inner,441 c_document_end: true,442 end_newline: false,443 }444 }445}446impl<I: ManifestFormat> ManifestFormat for YamlStreamFormat<I> {447 fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {448 let Val::Arr(arr) = val else {449 bail!(450 "output should be array for yaml stream format, got {}",451 val.value_type()452 )453 };454 for (i, v) in arr.iter().enumerate() {455 if i != 0 {456 out.push('\n');457 }458 let v = v.with_description(|| format!("elem <{i}> evaluation"))?;459 out.push_str("---\n");460 in_description_frame(461 || format!("elem <{i}> manifestification"),462 || self.inner.manifest_buf(v, out),463 )?;464 }465 if self.c_document_end {466 out.push('\n');467 out.push_str("...");468 }469 if self.end_newline {470 out.push('\n');471 }472 Ok(())473 }474}475476pub fn escape_string_json(s: &str) -> String {477 let mut buf = String::new();478 escape_string_json_buf(s, &mut buf);479 buf480}481482// Json string encoding was borrowed from https://github.com/serde-rs/json483484const BB: u8 = b'b'; // \x08485const TT: u8 = b't'; // \x09486const NN: u8 = b'n'; // \x0A487const FF: u8 = b'f'; // \x0C488const RR: u8 = b'r'; // \x0D489const QU: u8 = b'"'; // \x22490const BS: u8 = b'\\'; // \x5C491const UU: u8 = b'u'; // \x00...\x1F except the ones above492const __: u8 = 0;493494// Lookup table of escape sequences. A value of b'x' at index i means that byte495// i is escaped as "\x" in JSON. A value of 0 means that byte i is not escaped.496static ESCAPE: [u8; 256] = [497 // 1 2 3 4 5 6 7 8 9 A B C D E F498 UU, UU, UU, UU, UU, UU, UU, UU, BB, TT, NN, UU, FF, RR, UU, UU, // 0499 UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, // 1500 __, __, QU, __, __, __, __, __, __, __, __, __, __, __, __, __, // 2501 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 3502 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 4503 __, __, __, __, __, __, __, __, __, __, __, __, BS, __, __, __, // 5504 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 6505 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 7506 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 8507 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 9508 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // A509 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // B510 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // C511 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // D512 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // E513 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // F514];515516pub fn escape_string_json_buf(value: &str, buf: &mut String) {517 buf.reserve_exact(value.len() + 2);518 buf.push('"');519 escape_string_json_buf_raw(value, buf);520 buf.push('"');521}522523fn escape_string_json_buf_raw(value: &str, buf: &mut String) {524 // Safety: we only write correct utf-8 in this function525 let buf: &mut Vec<u8> = unsafe { &mut *ptr::from_mut(buf).cast::<Vec<u8>>() };526 let bytes = value.as_bytes();527528 let mut start = 0;529530 for (i, &byte) in bytes.iter().enumerate() {531 let escape = ESCAPE[byte as usize];532 if escape == __ {533 continue;534 }535536 if start < i {537 buf.extend_from_slice(&bytes[start..i]);538 }539 start = i + 1;540541 match escape {542 self::BB | self::TT | self::NN | self::FF | self::RR | self::QU | self::BS => {543 buf.extend_from_slice(&[b'\\', escape]);544 }545 self::UU => {546 static HEX_DIGITS: [u8; 16] = *b"0123456789abcdef";547 let bytes = &[548 b'\\',549 b'u',550 b'0',551 b'0',552 HEX_DIGITS[(byte >> 4) as usize],553 HEX_DIGITS[(byte & 0xF) as usize],554 ];555 buf.extend_from_slice(bytes);556 }557 _ => unreachable!(),558 }559 }560561 if start == bytes.len() {562 return;563 }564565 buf.extend_from_slice(&bytes[start..]);566}1use std::{borrow::Cow, fmt::Write, hint::black_box, ptr};23use crate::{4 Error, Result, ResultExt, Val, bail, evaluate::ensure_sufficient_stack, in_description_frame,5};67pub trait ManifestFormat {8 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()>;9 fn manifest(&self, val: Val) -> Result<String> {10 let mut out = String::new();11 self.manifest_buf(val, &mut out)?;12 Ok(out)13 }14 /// When outputing to file, is it safe to append a trailing newline (I.e newline won't change15 /// the meaning).16 ///17 /// Default implementation returns `true`18 fn file_trailing_newline(&self) -> bool {19 true20 }21}22impl<T> ManifestFormat for Box<T>23where24 T: ManifestFormat + ?Sized,25{26 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {27 let inner = &**self;28 inner.manifest_buf(val, buf)29 }30 fn file_trailing_newline(&self) -> bool {31 let inner = &**self;32 inner.file_trailing_newline()33 }34}35impl<T> ManifestFormat for &'_ T36where37 T: ManifestFormat + ?Sized,38{39 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {40 let inner = &**self;41 inner.manifest_buf(val, buf)42 }43 fn file_trailing_newline(&self) -> bool {44 let inner = &**self;45 inner.file_trailing_newline()46 }47}4849pub struct BlackBoxFormat;50impl ManifestFormat for BlackBoxFormat {51 #[allow(clippy::only_used_in_recursion)]52 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {53 match val {54 Val::Bool(v) => {55 black_box(v);56 }57 val @ Val::Null => {58 black_box(val);59 }60 Val::Str(str_value) => {61 black_box(format!("{str_value}"));62 }63 Val::Num(num_value) => {64 black_box(num_value);65 }66 Val::Arr(arr_value) => {67 for ele in arr_value.iter() {68 let ele = ele?;69 self.manifest_buf(ele, buf)?;70 }71 }72 Val::Obj(obj_value) => {73 for (name, value) in obj_value.iter(74 #[cfg(feature = "exp-preserve-order")]75 true,76 ) {77 black_box(name);78 let value = value?;79 self.manifest_buf(value, buf)?;80 }81 }82 Val::Func(func_val) => {83 black_box(func_val);84 bail!("tried to manifest function")85 }86 #[cfg(feature = "exp-bigint")]87 Val::BigInt(n) => {88 black_box(n);89 }90 }91 Ok(())92 }93}9495#[derive(PartialEq, Eq, Clone, Copy)]96enum JsonFormatting {97 // Applied in manifestification98 Manifest,99 /// Used for std.manifestJson100 /// Empty array/objects extends to "[\n\n]" instead of "[ ]" as in manifest101 Std,102 /// No line breaks, used in `obj+''`103 ToString,104 /// Minified json105 Minify,106}107108pub struct JsonFormat<'s> {109 padding: Cow<'s, str>,110 mtype: JsonFormatting,111 newline: &'s str,112 key_val_sep: &'s str,113 #[cfg(feature = "exp-preserve-order")]114 preserve_order: bool,115 #[cfg(feature = "exp-bigint")]116 preserve_bigints: bool,117}118119impl<'s> JsonFormat<'s> {120 // Minifying format121 pub fn minify(#[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Self {122 Self {123 padding: Cow::Borrowed(""),124 mtype: JsonFormatting::Minify,125 newline: "\n",126 key_val_sep: ":",127 #[cfg(feature = "exp-preserve-order")]128 preserve_order,129 #[cfg(feature = "exp-bigint")]130 preserve_bigints: false,131 }132 }133 /// Same format as std.toString, except does not keeps top-level string as-is134 /// To avoid confusion, the format is private in jrsonnet, use [`ToStringFormat`] instead135 const fn std_to_string_helper() -> Self {136 Self {137 padding: Cow::Borrowed(""),138 mtype: JsonFormatting::ToString,139 newline: "\n",140 key_val_sep: ": ",141 #[cfg(feature = "exp-preserve-order")]142 preserve_order: false,143 #[cfg(feature = "exp-bigint")]144 preserve_bigints: false,145 }146 }147 pub fn std_to_json(148 padding: String,149 newline: &'s str,150 key_val_sep: &'s str,151 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,152 ) -> Self {153 Self {154 padding: Cow::Owned(padding),155 mtype: JsonFormatting::Std,156 newline,157 key_val_sep,158 #[cfg(feature = "exp-preserve-order")]159 preserve_order,160 #[cfg(feature = "exp-bigint")]161 preserve_bigints: false,162 }163 }164 // Same format as CLI manifestification165 pub fn cli(166 padding: usize,167 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,168 ) -> Self {169 if padding == 0 {170 return Self::minify(171 #[cfg(feature = "exp-preserve-order")]172 preserve_order,173 );174 }175 Self {176 padding: Cow::Owned(" ".repeat(padding)),177 mtype: JsonFormatting::Manifest,178 newline: "\n",179 key_val_sep: ": ",180 #[cfg(feature = "exp-preserve-order")]181 preserve_order,182 #[cfg(feature = "exp-bigint")]183 preserve_bigints: false,184 }185 }186 // Same format as CLI manifestification187 pub fn debug() -> Self {188 Self {189 padding: Cow::Borrowed(" "),190 mtype: JsonFormatting::Manifest,191 newline: "\n",192 key_val_sep: ": ",193 #[cfg(feature = "exp-preserve-order")]194 preserve_order: true,195 #[cfg(feature = "exp-bigint")]196 preserve_bigints: true,197 }198 }199}200impl Default for JsonFormat<'static> {201 fn default() -> Self {202 Self {203 padding: Cow::Borrowed(" "),204 mtype: JsonFormatting::Manifest,205 newline: "\n",206 key_val_sep: ": ",207 #[cfg(feature = "exp-preserve-order")]208 preserve_order: false,209 #[cfg(feature = "exp-bigint")]210 preserve_bigints: false,211 }212 }213}214215pub fn manifest_json_ex(val: &Val, options: &JsonFormat<'_>) -> Result<String> {216 let mut out = String::new();217 manifest_json_ex_buf(val, &mut out, &mut String::new(), options)?;218 Ok(out)219}220221#[allow(clippy::too_many_lines)]222fn manifest_json_ex_buf(223 val: &Val,224 buf: &mut String,225 cur_padding: &mut String,226 options: &JsonFormat<'_>,227) -> Result<()> {228 use JsonFormatting::*;229230 let mtype = options.mtype;231 match val {232 Val::Bool(v) => {233 if *v {234 buf.push_str("true");235 } else {236 buf.push_str("false");237 }238 }239 Val::Null => buf.push_str("null"),240 Val::Str(s) => {241 buf.reserve(2 + s.len());242 buf.push('"');243 s.chunks(&mut |c| {244 escape_string_json_buf_raw(c, buf);245 });246 buf.push('"');247 }248 Val::Num(n) => write!(buf, "{n}").unwrap(),249 #[cfg(feature = "exp-bigint")]250 Val::BigInt(n) => {251 if options.preserve_bigints {252 write!(buf, "{n}").unwrap();253 } else {254 write!(buf, "{:?}", n.to_string()).unwrap();255 }256 }257 Val::Arr(items) => ensure_sufficient_stack(|| {258 buf.push('[');259260 let old_len = cur_padding.len();261 cur_padding.push_str(&options.padding);262263 let mut had_items = false;264 for (i, item) in items.iter().enumerate() {265 had_items = true;266 let item = item.with_description(|| format!("elem <{i}> evaluation"))?;267268 if i != 0 {269 buf.push(',');270 }271 match mtype {272 Manifest | Std => {273 buf.push_str(options.newline);274 buf.push_str(cur_padding);275 }276 ToString if i != 0 => buf.push(' '),277 Minify | ToString => {}278 }279280 in_description_frame(281 || format!("elem <{i}> manifestification"),282 || manifest_json_ex_buf(&item, buf, cur_padding, options),283 )?;284 }285286 cur_padding.truncate(old_len);287288 match mtype {289 Manifest | ToString if !had_items => {290 // Empty array as "[ ]"291 buf.push(' ');292 }293 Manifest => {294 buf.push_str(options.newline);295 buf.push_str(cur_padding);296 }297 Std => {298 if !had_items {299 // Stdlib formats empty array as "[\n\n]"300 buf.push_str(options.newline);301 }302 buf.push_str(options.newline);303 buf.push_str(cur_padding);304 }305 Minify | ToString => {}306 }307308 buf.push(']');309 Ok::<_, Error>(())310 })?,311 Val::Obj(obj) => ensure_sufficient_stack(|| {312 obj.run_assertions()?;313 buf.push('{');314315 let old_len = cur_padding.len();316 cur_padding.push_str(&options.padding);317318 let mut had_fields = false;319 for (i, (key, value)) in obj320 .iter(321 #[cfg(feature = "exp-preserve-order")]322 options.preserve_order,323 )324 .enumerate()325 {326 had_fields = true;327 let value = value.with_description(|| format!("field <{key}> evaluation"))?;328329 if i != 0 {330 buf.push(',');331 }332 match mtype {333 Manifest | Std => {334 buf.push_str(options.newline);335 buf.push_str(cur_padding);336 }337 ToString if i != 0 => buf.push(' '),338 Minify | ToString => {}339 }340341 escape_string_json_buf(&key, buf);342 buf.push_str(options.key_val_sep);343 in_description_frame(344 || format!("field <{key}> manifestification"),345 || manifest_json_ex_buf(&value, buf, cur_padding, options),346 )?;347 }348349 cur_padding.truncate(old_len);350351 match mtype {352 Manifest | ToString if !had_fields => {353 // Empty object as "{ }"354 buf.push(' ');355 }356 Manifest => {357 buf.push_str(options.newline);358 buf.push_str(cur_padding);359 }360 Std => {361 if !had_fields {362 // Stdlib formats empty object as "{\n\n}"363 buf.push_str(options.newline);364 }365 buf.push_str(options.newline);366 buf.push_str(cur_padding);367 }368 Minify | ToString => {}369 }370371 buf.push('}');372 Ok::<_, Error>(())373 })?,374 Val::Func(_) => bail!("tried to manifest function"),375 }376 Ok(())377}378379impl ManifestFormat for JsonFormat<'_> {380 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {381 manifest_json_ex_buf(&val, buf, &mut String::new(), self)382 }383}384385/// Same as [`JsonFormat`] with pre-set options, but top-level string is serialized as-is,386/// without quoting.387pub struct ToStringFormat;388impl ManifestFormat for ToStringFormat {389 fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {390 const JSON_TO_STRING: JsonFormat = JsonFormat::std_to_string_helper();391 if let Some(str) = val.as_str() {392 out.push_str(&str);393 return Ok(());394 }395 #[cfg(feature = "exp-bigint")]396 if let Some(int) = val.as_bigint() {397 out.push_str(&int.to_str_radix(10));398 return Ok(());399 }400 JSON_TO_STRING.manifest_buf(val, out)401 }402 fn file_trailing_newline(&self) -> bool {403 false404 }405}406pub struct StringFormat;407impl ManifestFormat for StringFormat {408 fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {409 let Val::Str(s) = val else {410 bail!(411 "output should be string for string manifest format, got {}",412 val.value_type()413 )414 };415 write!(out, "{s}").unwrap();416 Ok(())417 }418 fn file_trailing_newline(&self) -> bool {419 false420 }421}422423pub struct YamlStreamFormat<I> {424 inner: I,425 c_document_end: bool,426 end_newline: bool,427}428impl<I> YamlStreamFormat<I> {429 pub fn std_yaml_stream(inner: I, c_document_end: bool) -> Self {430 Self {431 inner,432 c_document_end,433 // Stdlib format always inserts useless newline at the end434 end_newline: true,435 }436 }437 pub fn cli(inner: I) -> Self {438 Self {439 inner,440 c_document_end: true,441 end_newline: false,442 }443 }444}445impl<I: ManifestFormat> ManifestFormat for YamlStreamFormat<I> {446 fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {447 let Val::Arr(arr) = val else {448 bail!(449 "output should be array for yaml stream format, got {}",450 val.value_type()451 )452 };453 for (i, v) in arr.iter().enumerate() {454 if i != 0 {455 out.push('\n');456 }457 let v = v.with_description(|| format!("elem <{i}> evaluation"))?;458 out.push_str("---\n");459 in_description_frame(460 || format!("elem <{i}> manifestification"),461 || self.inner.manifest_buf(v, out),462 )?;463 }464 if self.c_document_end {465 out.push('\n');466 out.push_str("...");467 }468 if self.end_newline {469 out.push('\n');470 }471 Ok(())472 }473}474475pub fn escape_string_json(s: &str) -> String {476 let mut buf = String::new();477 escape_string_json_buf(s, &mut buf);478 buf479}480481// Json string encoding was borrowed from https://github.com/serde-rs/json482483const BB: u8 = b'b'; // \x08484const TT: u8 = b't'; // \x09485const NN: u8 = b'n'; // \x0A486const FF: u8 = b'f'; // \x0C487const RR: u8 = b'r'; // \x0D488const QU: u8 = b'"'; // \x22489const BS: u8 = b'\\'; // \x5C490const UU: u8 = b'u'; // \x00...\x1F except the ones above491const __: u8 = 0;492493// Lookup table of escape sequences. A value of b'x' at index i means that byte494// i is escaped as "\x" in JSON. A value of 0 means that byte i is not escaped.495static ESCAPE: [u8; 256] = [496 // 1 2 3 4 5 6 7 8 9 A B C D E F497 UU, UU, UU, UU, UU, UU, UU, UU, BB, TT, NN, UU, FF, RR, UU, UU, // 0498 UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, // 1499 __, __, QU, __, __, __, __, __, __, __, __, __, __, __, __, __, // 2500 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 3501 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 4502 __, __, __, __, __, __, __, __, __, __, __, __, BS, __, __, __, // 5503 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 6504 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 7505 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 8506 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 9507 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // A508 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // B509 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // C510 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // D511 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // E512 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // F513];514515pub fn escape_string_json_buf(value: &str, buf: &mut String) {516 buf.reserve_exact(value.len() + 2);517 buf.push('"');518 escape_string_json_buf_raw(value, buf);519 buf.push('"');520}521522fn escape_string_json_buf_raw(value: &str, buf: &mut String) {523 // Safety: we only write correct utf-8 in this function524 let buf: &mut Vec<u8> = unsafe { &mut *ptr::from_mut(buf).cast::<Vec<u8>>() };525 let bytes = value.as_bytes();526527 let mut start = 0;528529 for (i, &byte) in bytes.iter().enumerate() {530 let escape = ESCAPE[byte as usize];531 if escape == __ {532 continue;533 }534535 if start < i {536 buf.extend_from_slice(&bytes[start..i]);537 }538 start = i + 1;539540 match escape {541 self::BB | self::TT | self::NN | self::FF | self::RR | self::QU | self::BS => {542 buf.extend_from_slice(&[b'\\', escape]);543 }544 self::UU => {545 static HEX_DIGITS: [u8; 16] = *b"0123456789abcdef";546 let bytes = &[547 b'\\',548 b'u',549 b'0',550 b'0',551 HEX_DIGITS[(byte >> 4) as usize],552 HEX_DIGITS[(byte & 0xF) as usize],553 ];554 buf.extend_from_slice(bytes);555 }556 _ => unreachable!(),557 }558 }559560 if start == bytes.len() {561 return;562 }563564 buf.extend_from_slice(&bytes[start..]);565}crates/jrsonnet-evaluator/src/obj/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj/mod.rs
+++ b/crates/jrsonnet-evaluator/src/obj/mod.rs
@@ -11,8 +11,8 @@
};
use educe::Educe;
-use im_rc::{vector, Vector};
-use jrsonnet_gcmodule::{cc_dyn, Acyclic, Cc, Trace, Weak};
+use im_rc::{Vector, vector};
+use jrsonnet_gcmodule::{Acyclic, Cc, Trace, Weak, cc_dyn};
use jrsonnet_interner::IStr;
use jrsonnet_ir::Span;
use rustc_hash::{FxHashMap, FxHashSet};
@@ -23,13 +23,13 @@
pub use oop::ObjValueBuilder;
use crate::{
+ CcUnbound, MaybeUnbound, Result, Thunk, Unbound, Val,
arr::{PickObjectKeyValues, PickObjectValues},
bail,
- error::{suggest_object_fields, ErrorKind::*},
+ error::{ErrorKind::*, suggest_object_fields},
evaluate::operator::evaluate_add_op,
identity_hash,
val::{ArrValue, ThunkValue},
- CcUnbound, MaybeUnbound, Result, Thunk, Unbound, Val,
};
#[cfg(not(feature = "exp-preserve-order"))]
crates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -10,7 +10,7 @@
#[cfg(feature = "explaining-traces")]
use jrsonnet_ir::Span;
-use crate::{error::ErrorKind, Error};
+use crate::{Error, error::ErrorKind};
/// The way paths should be displayed
#[derive(Clone, Trace)]
@@ -259,7 +259,7 @@
struct ResetData {
loc: Span,
}
- use hi_doc::{source_to_ansi, Formatting, SnippetBuilder, Text};
+ use hi_doc::{Formatting, SnippetBuilder, Text, source_to_ansi};
write!(out, "{}", error.error())?;
if let ErrorKind::ImportSyntaxError { path, error } = error.error() {
@@ -277,14 +277,15 @@
use crate::analyze::DiagLevel;
let mut builder: Option<SnippetBuilder> = None;
let mut current_src: Option<&str> = None;
- let flush =
- |builder: Option<SnippetBuilder>, out: &mut dyn std::fmt::Write| -> Result<(), std::fmt::Error> {
- if let Some(b) = builder {
- let ansi = source_to_ansi(&b.build());
- write!(out, "\n{}", ansi.trim_end())?;
- }
- Ok(())
- };
+ let flush = |builder: Option<SnippetBuilder>,
+ out: &mut dyn std::fmt::Write|
+ -> Result<(), std::fmt::Error> {
+ if let Some(b) = builder {
+ let ansi = source_to_ansi(&b.build());
+ write!(out, "\n{}", ansi.trim_end())?;
+ }
+ Ok(())
+ };
for diag in diagnostics {
if let Some(span) = &diag.span {
let src = span.0.code();
@@ -295,14 +296,12 @@
}
let b = builder.as_mut().unwrap();
let ab = match diag.level {
- DiagLevel::Error => b.error(Text::fragment(
- diag.message.clone(),
- Formatting::default(),
- )),
- DiagLevel::Warning => b.warning(Text::fragment(
- diag.message.clone(),
- Formatting::default(),
- )),
+ DiagLevel::Error => {
+ b.error(Text::fragment(diag.message.clone(), Formatting::default()))
+ }
+ DiagLevel::Warning => {
+ b.warning(Text::fragment(diag.message.clone(), Formatting::default()))
+ }
};
ab.range(span.range()).build();
} else {
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -17,7 +17,13 @@
pub use crate::arr::{ArrValue, ArrayLike};
use crate::{
- NumValue, ObjValue, Result, SupThis, Unbound, WeakSupThis, bail, error::{Error, ErrorKind::*}, evaluate::operator::{evaluate_compare_op, evaluate_mod_op}, function::FuncVal, gc::WithCapacityExt as _, manifest::{ManifestFormat, ToStringFormat}, typed::BoundedUsize
+ NumValue, ObjValue, Result, SupThis, Unbound, WeakSupThis, bail,
+ error::{Error, ErrorKind::*},
+ evaluate::operator::{evaluate_compare_op, evaluate_mod_op},
+ function::FuncVal,
+ gc::WithCapacityExt as _,
+ manifest::{ManifestFormat, ToStringFormat},
+ typed::BoundedUsize,
};
pub trait ThunkValue: Trace {
crates/jrsonnet-ir-parser/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-ir-parser/src/lib.rs
+++ b/crates/jrsonnet-ir-parser/src/lib.rs
@@ -1,11 +1,11 @@
use jrsonnet_gcmodule::Acyclic;
use jrsonnet_ir::{
- unescape, ArgsDesc, AssertExpr, AssertStmt, BinaryOp, BinaryOpType, BindSpec, CompSpec,
- Destruct, Expr, ExprParam, ExprParams, FieldMember, FieldName, ForSpecData, IStr, IfElse,
- IfSpecData, ImportKind, IndexPart, LiteralType, Member, NumValue, ObjBody, ObjComp, ObjMembers,
- Slice, SliceDesc, Source, Span, Spanned, UnaryOpType, Visibility,
+ ArgsDesc, AssertExpr, AssertStmt, BinaryOp, BinaryOpType, BindSpec, CompSpec, Destruct, Expr,
+ ExprParam, ExprParams, FieldMember, FieldName, ForSpecData, IStr, IfElse, IfSpecData,
+ ImportKind, IndexPart, LiteralType, Member, NumValue, ObjBody, ObjComp, ObjMembers, Slice,
+ SliceDesc, Source, Span, Spanned, UnaryOpType, Visibility, unescape,
};
-use jrsonnet_lexer::{collect_lexed_str_block, Lexeme, Lexer, Span as LexSpan, SyntaxKind, T};
+use jrsonnet_lexer::{Lexeme, Lexer, Span as LexSpan, SyntaxKind, T, collect_lexed_str_block};
pub struct ParserSettings {
pub source: Source,
crates/jrsonnet-ir/src/expr.rsdiffbeforeafterboth--- a/crates/jrsonnet-ir/src/expr.rs
+++ b/crates/jrsonnet-ir/src/expr.rs
@@ -7,9 +7,9 @@
use jrsonnet_interner::IStr;
use crate::{
+ NumValue,
function::{FunctionSignature, ParamDefault, ParamName, ParamParse},
source::Source,
- NumValue,
};
#[derive(Debug, PartialEq, Acyclic)]
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -3,14 +3,13 @@
use proc_macro2::TokenStream;
use quote::{quote, quote_spanned};
use syn::{
- parenthesized,
+ Attribute, DeriveInput, Error, Expr, ExprClosure, FnArg, GenericArgument, Ident, ItemFn,
+ LitStr, Meta, Pat, Path, PathArguments, Result, ReturnType, Token, Type, parenthesized,
parse::{Parse, ParseStream},
parse_macro_input,
punctuated::Punctuated,
spanned::Spanned,
token::Comma,
- Attribute, DeriveInput, Error, Expr, ExprClosure, FnArg, GenericArgument, Ident, ItemFn,
- LitStr, Meta, Pat, Path, PathArguments, Result, ReturnType, Token, Type,
};
use self::typed::{derive_from_untyped_inner, derive_into_untyped_inner, derive_typed_inner};
crates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -1,12 +1,11 @@
#![allow(non_snake_case)]
use jrsonnet_evaluator::{
- bail, error,
- function::{builtin, NativeFn},
+ Either, IStr, ObjValue, ObjValueBuilder, Result, ResultExt, Thunk, Val, bail, error,
+ function::{NativeFn, builtin},
runtime_error,
typed::{BoundedUsize, Either2, FromUntyped},
- val::{equals, ArrValue, IndexableVal},
- Either, IStr, ObjValue, ObjValueBuilder, Result, ResultExt, Thunk, Val,
+ val::{ArrValue, IndexableVal, equals},
};
pub fn eval_on_empty(on_empty: Option<Thunk<Val>>) -> Result<Val> {
crates/jrsonnet-stdlib/src/compat.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/compat.rs
+++ b/crates/jrsonnet-stdlib/src/compat.rs
@@ -1,6 +1,6 @@
use std::cmp::Ordering;
-use jrsonnet_evaluator::{function::builtin, val::ArrValue, Result, Val};
+use jrsonnet_evaluator::{Result, Val, function::builtin, val::ArrValue};
#[builtin]
#[allow(non_snake_case)]
crates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -12,7 +12,12 @@
pub use encoding::*;
pub use hash::*;
use jrsonnet_evaluator::{
- IStr, InitialContextBuilder, NumValue, ObjValue, ObjValueBuilder, Source, Thunk, Val, error::Result, function::{CallLocation, FuncVal, builtin_id}, tla::TlaArg, trace::PathResolver, typed::SerializeTypedObj as _
+ IStr, InitialContextBuilder, NumValue, ObjValue, ObjValueBuilder, Source, Thunk, Val,
+ error::Result,
+ function::{CallLocation, FuncVal, builtin_id},
+ tla::TlaArg,
+ trace::PathResolver,
+ typed::SerializeTypedObj as _,
};
use jrsonnet_gcmodule::{Acyclic, Cc, Trace};
use jrsonnet_macros::{IntoUntyped, Typed};
crates/jrsonnet-stdlib/src/manifest/toml.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/manifest/toml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/toml.rs
@@ -1,7 +1,10 @@
use std::borrow::Cow;
use jrsonnet_evaluator::{
- Error, IStr, ObjValue, Result, ResultExt, Val, bail, ensure_sufficient_stack, in_description_frame, manifest::{ManifestFormat, escape_string_json_buf}, val::ArrValue
+ Error, IStr, ObjValue, Result, ResultExt, Val, bail, ensure_sufficient_stack,
+ in_description_frame,
+ manifest::{ManifestFormat, escape_string_json_buf},
+ val::ArrValue,
};
pub struct TomlFormat<'s> {
@@ -218,14 +221,16 @@
}
first = false;
path.push(k.clone());
- ensure_sufficient_stack(|| in_description_frame(
- || format!("section <{k}> manifestification"),
- || match v {
- Val::Obj(obj) => manifest_table(&obj, path, buf, cur_padding, options),
- Val::Arr(arr) => manifest_table_array(&arr, path, buf, cur_padding, options),
- _ => unreachable!("iterating over sections"),
- },
- ))?;
+ ensure_sufficient_stack(|| {
+ in_description_frame(
+ || format!("section <{k}> manifestification"),
+ || match v {
+ Val::Obj(obj) => manifest_table(&obj, path, buf, cur_padding, options),
+ Val::Arr(arr) => manifest_table_array(&arr, path, buf, cur_padding, options),
+ _ => unreachable!("iterating over sections"),
+ },
+ )
+ })?;
path.pop();
}
Ok(())
crates/jrsonnet-stdlib/src/misc.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/misc.rs
+++ b/crates/jrsonnet-stdlib/src/misc.rs
@@ -1,13 +1,12 @@
use std::{cell::RefCell, collections::BTreeSet};
use jrsonnet_evaluator::{
- bail,
+ Either, IStr, ObjValue, ObjValueBuilder, ResultExt, Thunk, Val, bail,
error::{ErrorKind::*, Result},
- function::{builtin, CallLocation, FuncVal},
+ function::{CallLocation, FuncVal, builtin},
manifest::JsonFormat,
typed::{Either2, Either4},
- val::{equals, ArrValue},
- Either, IStr, ObjValue, ObjValueBuilder, ResultExt, Thunk, Val,
+ val::{ArrValue, equals},
};
use jrsonnet_gcmodule::Cc;
crates/jrsonnet-stdlib/src/operator.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/operator.rs
+++ b/crates/jrsonnet-stdlib/src/operator.rs
@@ -2,11 +2,11 @@
//! However, in our case we instead implement them in native, and implement native functions on top of core for backwards compatibility
use jrsonnet_evaluator::{
+ IStr, NumValue, Result, Val,
function::builtin,
stdlib::std_format,
typed::{Either, Either2},
val::{equals, primitive_equals},
- IStr, NumValue, Result, Val,
};
#[builtin]
crates/jrsonnet-stdlib/src/sets.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/sets.rs
+++ b/crates/jrsonnet-stdlib/src/sets.rs
@@ -1,6 +1,6 @@
use std::cmp::Ordering;
-use jrsonnet_evaluator::{function::builtin, val::ArrValue, Result, Thunk, Val};
+use jrsonnet_evaluator::{Result, Thunk, Val, function::builtin, val::ArrValue};
use crate::keyf::KeyF;
crates/jrsonnet-stdlib/src/sort.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/sort.rs
+++ b/crates/jrsonnet-stdlib/src/sort.rs
@@ -3,10 +3,9 @@
use std::cmp::Ordering;
use jrsonnet_evaluator::{
- bail,
+ Result, Thunk, Val, bail,
function::builtin,
- val::{equals, ArrValue},
- Result, Thunk, Val,
+ val::{ArrValue, equals},
};
use crate::{eval_on_empty, keyf::KeyF};
tests/tests/builtin.rsdiffbeforeafterboth--- a/tests/tests/builtin.rs
+++ b/tests/tests/builtin.rs
@@ -1,7 +1,11 @@
mod common;
use jrsonnet_evaluator::{
- ContextInitializer, FileImportResolver, InitialContextBuilder, Result, Source, State, Thunk, Val, function::{CallLocation, FuncVal, builtin, builtin::{Builtin}}, trace::PathResolver, typed::FromUntyped
+ ContextInitializer, FileImportResolver, InitialContextBuilder, Result, Source, State, Thunk,
+ Val,
+ function::{CallLocation, FuncVal, builtin, builtin::Builtin},
+ trace::PathResolver,
+ typed::FromUntyped,
};
use jrsonnet_gcmodule::Trace;
use jrsonnet_stdlib::ContextInitializer as StdContextInitializer;
tests/tests/common.rsdiffbeforeafterboth--- a/tests/tests/common.rs
+++ b/tests/tests/common.rs
@@ -1,5 +1,7 @@
use jrsonnet_evaluator::{
- ContextBuilder, ContextInitializer as ContextInitializerT, InitialContextBuilder, ObjValueBuilder, Result, Thunk, Val, bail, function::{FuncVal, builtin}, Source
+ ContextBuilder, ContextInitializer as ContextInitializerT, InitialContextBuilder,
+ ObjValueBuilder, Result, Source, Thunk, Val, bail,
+ function::{FuncVal, builtin},
};
use jrsonnet_gcmodule::Trace;