difftreelog
style enforce import style
in: master
38 files changed
.rustfmt.tomldiffbeforeafterboth--- a/.rustfmt.toml
+++ b/.rustfmt.toml
@@ -1 +1,3 @@
hard_tabs = true
+imports_granularity = "crate"
+group_imports = "stdexternalcrate"
bindings/jsonnet/src/import.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/import.rs
+++ b/bindings/jsonnet/src/import.rs
@@ -1,9 +1,5 @@
//! Import resolution manipulation utilities
-use jrsonnet_evaluator::{
- error::{Error::*, Result},
- throw, EvaluationState, ImportResolver,
-};
use std::{
any::Any,
cell::RefCell,
@@ -17,6 +13,11 @@
rc::Rc,
};
+use jrsonnet_evaluator::{
+ error::{Error::*, Result},
+ throw, EvaluationState, ImportResolver,
+};
+
pub type JsonnetImportCallback = unsafe extern "C" fn(
ctx: *mut c_void,
base: *const c_char,
bindings/jsonnet/src/interop.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/interop.rs
+++ b/bindings/jsonnet/src/interop.rs
@@ -1,12 +1,14 @@
//! Jrsonnet specific additional binding helpers
-use crate::{import::jsonnet_import_callback, native::jsonnet_native_callback};
-use jrsonnet_evaluator::{EvaluationState, Val};
use std::{
ffi::c_void,
os::raw::{c_char, c_int},
};
+use jrsonnet_evaluator::{EvaluationState, Val};
+
+use crate::{import::jsonnet_import_callback, native::jsonnet_native_callback};
+
extern "C" {
pub fn _jrsonnet_static_import_callback(
ctx: *mut c_void,
bindings/jsonnet/src/lib.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -8,8 +8,6 @@
pub mod val_modify;
pub mod vars_tlas;
-use import::NativeImportResolver;
-use jrsonnet_evaluator::{EvaluationState, IStr, ManifestFormat, Val};
use std::{
alloc::Layout,
ffi::{CStr, CString},
@@ -17,6 +15,9 @@
path::PathBuf,
};
+use import::NativeImportResolver;
+use jrsonnet_evaluator::{EvaluationState, IStr, ManifestFormat, Val};
+
/// WASM stub
#[cfg(target_arch = "wasm32")]
#[no_mangle]
bindings/jsonnet/src/native.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/native.rs
+++ b/bindings/jsonnet/src/native.rs
@@ -1,3 +1,11 @@
+use std::{
+ convert::TryFrom,
+ ffi::{c_void, CStr},
+ os::raw::{c_char, c_int},
+ path::Path,
+ rc::Rc,
+};
+
use gcmodule::Cc;
use jrsonnet_evaluator::{
error::{Error, LocError},
@@ -5,13 +13,6 @@
gc::TraceBox,
native::{NativeCallback, NativeCallbackHandler},
EvaluationState, IStr, Val,
-};
-use std::{
- convert::TryFrom,
- ffi::{c_void, CStr},
- os::raw::{c_char, c_int},
- path::Path,
- rc::Rc,
};
type JsonnetNativeCallback = unsafe extern "C" fn(
bindings/jsonnet/src/val_extract.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/val_extract.rs
+++ b/bindings/jsonnet/src/val_extract.rs
@@ -1,12 +1,12 @@
//! Extract values from VM
-use jrsonnet_evaluator::{EvaluationState, Val};
-
use std::{
ffi::CString,
os::raw::{c_char, c_double, c_int},
};
+use jrsonnet_evaluator::{EvaluationState, Val};
+
#[no_mangle]
pub extern "C" fn jsonnet_json_extract_string(_vm: &EvaluationState, v: &Val) -> *mut c_char {
match v {
bindings/jsonnet/src/val_make.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/val_make.rs
+++ b/bindings/jsonnet/src/val_make.rs
@@ -1,12 +1,13 @@
//! Create values in VM
-use gcmodule::Cc;
-use jrsonnet_evaluator::{ArrValue, EvaluationState, ObjValue, Val};
use std::{
ffi::CStr,
os::raw::{c_char, c_double, c_int},
};
+use gcmodule::Cc;
+use jrsonnet_evaluator::{val::ArrValue, EvaluationState, ObjValue, Val};
+
/// # Safety
///
/// This function is safe, if received v is a pointer to normal C string
bindings/jsonnet/src/val_modify.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/val_modify.rs
+++ b/bindings/jsonnet/src/val_modify.rs
@@ -2,10 +2,11 @@
//! Only tested with variables, which haven't altered by code before appearing here
//! In jrsonnet every value is immutable, and this code is probally broken
+use std::{ffi::CStr, os::raw::c_char};
+
use gcmodule::Cc;
-use jrsonnet_evaluator::{ArrValue, EvaluationState, LazyBinding, LazyVal, ObjMember, Val};
+use jrsonnet_evaluator::{val::ArrValue, EvaluationState, LazyBinding, LazyVal, ObjMember, Val};
use jrsonnet_parser::Visibility;
-use std::{ffi::CStr, os::raw::c_char};
/// # Safety
///
bindings/jsonnet/src/vars_tlas.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/vars_tlas.rs
+++ b/bindings/jsonnet/src/vars_tlas.rs
@@ -1,8 +1,9 @@
//! Manipulate external variables and top level arguments
-use jrsonnet_evaluator::EvaluationState;
use std::{ffi::CStr, os::raw::c_char};
+use jrsonnet_evaluator::EvaluationState;
+
/// # Safety
#[no_mangle]
pub unsafe extern "C" fn jsonnet_ext_var(
cmds/jrsonnet/src/main.rsdiffbeforeafterboth--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -1,13 +1,13 @@
+use std::{
+ fs::{create_dir_all, File},
+ io::{Read, Write},
+ path::PathBuf,
+};
+
use clap::{AppSettings, IntoApp, Parser};
use clap_complete::Shell;
use jrsonnet_cli::{ConfigureState, GcOpts, GeneralOpts, InputOpts, ManifestOpts, OutputOpts};
use jrsonnet_evaluator::{error::LocError, EvaluationState};
-use std::{
- fs::{create_dir_all, File},
- io::Read,
- io::Write,
- path::PathBuf,
-};
#[cfg(feature = "mimalloc")]
#[global_allocator]
crates/jrsonnet-cli/src/ext.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/ext.rs
+++ b/crates/jrsonnet-cli/src/ext.rs
@@ -1,8 +1,10 @@
-use crate::ConfigureState;
+use std::{fs::read_to_string, str::FromStr};
+
use clap::Parser;
use jrsonnet_evaluator::{error::Result, EvaluationState};
-use std::{fs::read_to_string, str::FromStr};
+use crate::ConfigureState;
+
#[derive(Clone)]
pub struct ExtStr {
pub name: String,
crates/jrsonnet-cli/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/lib.rs
+++ b/crates/jrsonnet-cli/src/lib.rs
@@ -3,14 +3,14 @@
mod tla;
mod trace;
+use std::{env, path::PathBuf};
+
+use clap::Parser;
pub use ext::*;
+use jrsonnet_evaluator::{error::Result, EvaluationState, FileImportResolver};
pub use manifest::*;
pub use tla::*;
pub use trace::*;
-
-use clap::Parser;
-use jrsonnet_evaluator::{error::Result, EvaluationState, FileImportResolver};
-use std::{env, path::PathBuf};
pub trait ConfigureState {
fn configure(&self, state: &EvaluationState) -> Result<()>;
crates/jrsonnet-cli/src/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/manifest.rs
+++ b/crates/jrsonnet-cli/src/manifest.rs
@@ -1,8 +1,10 @@
-use crate::ConfigureState;
+use std::{path::PathBuf, str::FromStr};
+
use clap::Parser;
use jrsonnet_evaluator::{error::Result, EvaluationState, ManifestFormat};
-use std::{path::PathBuf, str::FromStr};
+use crate::ConfigureState;
+
pub enum ManifestFormatName {
/// Expect string as output, and write them directly
String,
crates/jrsonnet-cli/src/tla.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/tla.rs
+++ b/crates/jrsonnet-cli/src/tla.rs
@@ -1,7 +1,8 @@
-use crate::{ConfigureState, ExtFile, ExtStr};
use clap::Parser;
use jrsonnet_evaluator::{error::Result, EvaluationState};
+use crate::{ConfigureState, ExtFile, ExtStr};
+
#[derive(Parser)]
#[clap(next_help_heading = "TOP LEVEL ARGUMENTS")]
pub struct TLAOpts {
crates/jrsonnet-cli/src/trace.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/trace.rs
+++ b/crates/jrsonnet-cli/src/trace.rs
@@ -1,12 +1,14 @@
-use crate::ConfigureState;
+use std::str::FromStr;
+
use clap::Parser;
use jrsonnet_evaluator::{
error::Result,
trace::{CompactFormat, ExplainingFormat, PathResolver},
EvaluationState,
};
-use std::str::FromStr;
+use crate::ConfigureState;
+
#[derive(PartialEq)]
pub enum TraceFormatName {
Compact,
crates/jrsonnet-evaluator/build.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/build.rs
+++ b/crates/jrsonnet-evaluator/build.rs
@@ -1,6 +1,3 @@
-use bincode::serialize;
-use jrsonnet_parser::{parse, ParserSettings};
-use jrsonnet_stdlib::STDLIB_STR;
use std::{
env,
fs::File,
@@ -8,6 +5,10 @@
path::{Path, PathBuf},
};
+use bincode::serialize;
+use jrsonnet_parser::{parse, ParserSettings};
+use jrsonnet_stdlib::STDLIB_STR;
+
fn main() {
let parsed = parse(
STDLIB_STR,
crates/jrsonnet-evaluator/src/builtin/format.rsdiffbeforeafterboth1//! faster std.format impl2#![allow(clippy::too_many_arguments)]34use crate::{error::Error::*, throw, LocError, ObjValue, Result, Val};5use gcmodule::Trace;6use jrsonnet_interner::IStr;7use jrsonnet_types::ValType;8use std::convert::TryFrom;9use thiserror::Error;1011#[derive(Debug, Clone, Error, Trace)]12pub enum FormatError {13 #[error("truncated format code")]14 TruncatedFormatCode,15 #[error("unrecognized conversion type: {0}")]16 UnrecognizedConversionType(char),1718 #[error("not enough values")]19 NotEnoughValues,2021 #[error("cannot use * width with object")]22 CannotUseStarWidthWithObject,23 #[error("mapping keys required")]24 MappingKeysRequired,25 #[error("no such format field: {0}")]26 NoSuchFormatField(IStr),27}2829impl From<FormatError> for LocError {30 fn from(e: FormatError) -> Self {31 Self::new(Format(e))32 }33}3435use FormatError::*;3637type ParseResult<'t, T> = std::result::Result<(T, &'t str), FormatError>;3839pub fn try_parse_mapping_key(str: &str) -> ParseResult<&str> {40 if str.is_empty() {41 return Err(TruncatedFormatCode);42 }43 let bytes = str.as_bytes();44 if bytes[0] == b'(' {45 let mut i = 1;46 while i < bytes.len() {47 if bytes[i] == b')' {48 return Ok((&str[1..i as usize], &str[i as usize + 1..]));49 }50 i += 1;51 }52 Err(TruncatedFormatCode)53 } else {54 Ok(("", str))55 }56}5758#[cfg(test)]59pub mod tests_key {60 use super::*;6162 #[test]63 fn parse_key() {64 assert_eq!(65 try_parse_mapping_key("(hello ) world").unwrap(),66 ("hello ", " world")67 );68 assert_eq!(try_parse_mapping_key("() world").unwrap(), ("", " world"));69 assert_eq!(try_parse_mapping_key(" world").unwrap(), ("", " world"));70 assert_eq!(71 try_parse_mapping_key(" () world").unwrap(),72 ("", " () world")73 );74 }7576 #[test]77 #[should_panic]78 fn parse_key_missing_start() {79 try_parse_mapping_key("").unwrap();80 }8182 #[test]83 #[should_panic]84 fn parse_key_missing_end() {85 try_parse_mapping_key("( ").unwrap();86 }87}8889#[derive(Default, Debug)]90pub struct CFlags {91 pub alt: bool,92 pub zero: bool,93 pub left: bool,94 pub blank: bool,95 pub sign: bool,96}9798pub fn try_parse_cflags(str: &str) -> ParseResult<CFlags> {99 if str.is_empty() {100 return Err(TruncatedFormatCode);101 }102 let bytes = str.as_bytes();103 let mut i = 0;104 let mut out = CFlags::default();105 loop {106 if bytes.len() == i {107 return Err(TruncatedFormatCode);108 }109 match bytes[i] {110 b'#' => out.alt = true,111 b'0' => out.zero = true,112 b'-' => out.left = true,113 b' ' => out.blank = true,114 b'+' => out.sign = true,115 _ => break,116 }117 i += 1;118 }119 Ok((out, &str[i..]))120}121122#[derive(Debug, PartialEq)]123pub enum Width {124 Star,125 Fixed(usize),126}127pub fn try_parse_field_width(str: &str) -> ParseResult<Width> {128 if str.is_empty() {129 return Err(TruncatedFormatCode);130 }131 let bytes = str.as_bytes();132 if bytes[0] == b'*' {133 return Ok((Width::Star, &str[1..]));134 }135 let mut out: usize = 0;136 let mut digits = 0;137 while let Some(digit) = (bytes[digits] as char).to_digit(10) {138 out *= 10;139 out += digit as usize;140 digits += 1;141 if digits == bytes.len() {142 return Err(TruncatedFormatCode);143 }144 }145 Ok((Width::Fixed(out), &str[digits..]))146}147148pub fn try_parse_precision(str: &str) -> ParseResult<Option<Width>> {149 if str.is_empty() {150 return Err(TruncatedFormatCode);151 }152 let bytes = str.as_bytes();153 if bytes[0] == b'.' {154 try_parse_field_width(&str[1..]).map(|(r, s)| (Some(r), s))155 } else {156 Ok((None, str))157 }158}159160// Only skips161pub fn try_parse_length_modifier(str: &str) -> ParseResult<()> {162 if str.is_empty() {163 return Err(TruncatedFormatCode);164 }165 let bytes = str.as_bytes();166 let mut idx = 0;167 while bytes[idx] == b'h' || bytes[idx] == b'l' || bytes[idx] == b'L' {168 idx += 1;169 if bytes.len() == idx {170 return Err(TruncatedFormatCode);171 }172 }173 Ok(((), &str[idx..]))174}175176#[derive(Debug, PartialEq)]177pub enum ConvTypeV {178 Decimal,179 Octal,180 Hexadecimal,181 Scientific,182 Float,183 Shorter,184 Char,185 String,186 Percent,187}188pub struct ConvType {189 v: ConvTypeV,190 caps: bool,191}192193pub fn parse_conversion_type(str: &str) -> ParseResult<ConvType> {194 if str.is_empty() {195 return Err(TruncatedFormatCode);196 }197198 let code = str.as_bytes()[0];199 let v: (ConvTypeV, bool) = match code {200 b'd' | b'i' | b'u' => (ConvTypeV::Decimal, false),201 b'o' => (ConvTypeV::Octal, false),202 b'x' => (ConvTypeV::Hexadecimal, false),203 b'X' => (ConvTypeV::Hexadecimal, true),204 b'e' => (ConvTypeV::Scientific, false),205 b'E' => (ConvTypeV::Scientific, true),206 b'f' => (ConvTypeV::Float, false),207 b'F' => (ConvTypeV::Float, true),208 b'g' => (ConvTypeV::Shorter, false),209 b'G' => (ConvTypeV::Shorter, true),210 b'c' => (ConvTypeV::Char, false),211 b's' => (ConvTypeV::String, false),212 b'%' => (ConvTypeV::Percent, false),213 c => return Err(UnrecognizedConversionType(c as char)),214 };215216 Ok((ConvType { v: v.0, caps: v.1 }, &str[1..]))217}218219#[derive(Debug)]220pub struct Code<'s> {221 mkey: &'s str,222 cflags: CFlags,223 width: Width,224 precision: Option<Width>,225 convtype: ConvTypeV,226 caps: bool,227}228pub fn parse_code(str: &str) -> ParseResult<Code> {229 if str.is_empty() {230 return Err(TruncatedFormatCode);231 }232 let (mkey, str) = try_parse_mapping_key(str)?;233 let (cflags, str) = try_parse_cflags(str)?;234 let (width, str) = try_parse_field_width(str)?;235 let (precision, str) = try_parse_precision(str)?;236 let (_, str) = try_parse_length_modifier(str)?;237 let (convtype, str) = parse_conversion_type(str)?;238239 Ok((240 Code {241 mkey,242 cflags,243 width,244 precision,245 convtype: convtype.v,246 caps: convtype.caps,247 },248 str,249 ))250}251252#[derive(Debug)]253pub enum Element<'s> {254 String(&'s str),255 Code(Code<'s>),256}257pub fn parse_codes(mut str: &str) -> Result<Vec<Element>> {258 let mut bytes = str.as_bytes();259 let mut out = vec![];260 let mut offset = 0;261262 loop {263 while offset != bytes.len() && bytes[offset] != b'%' {264 offset += 1;265 }266 if offset != 0 {267 out.push(Element::String(&str[0..offset]));268 }269 if offset == bytes.len() {270 return Ok(out);271 }272 str = &str[offset + 1..];273 let (code, nstr) = parse_code(str)?;274 str = nstr;275 bytes = str.as_bytes();276 offset = 0;277278 out.push(Element::Code(code))279 }280}281282const NUMBERS: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";283284#[inline]285pub fn render_integer(286 out: &mut String,287 iv: i64,288 padding: usize,289 precision: usize,290 blank: bool,291 sign: bool,292 radix: i64,293 prefix: &str,294 caps: bool,295) {296 // Digit char indexes in reverse order, i.e297 // for radix = 16 and n = 12f: [15, 2, 1]298 let digits = if iv == 0 {299 vec![0u8]300 } else {301 let mut v = iv.abs();302 let mut nums = Vec::with_capacity(1);303 while v > 0 {304 nums.push((v % radix) as u8);305 v /= radix;306 }307 nums308 };309 let neg = iv < 0;310 let zp = padding.saturating_sub(if neg || blank || sign { 1 } else { 0 });311 let zp2 = zp312 .max(precision)313 .saturating_sub(prefix.len() + digits.len());314315 if neg {316 out.push('-')317 } else if sign {318 out.push('+');319 } else if blank {320 out.push(' ');321 }322323 out.reserve(zp2);324 for _ in 0..zp2 {325 out.push('0');326 }327 out.push_str(prefix);328329 for digit in digits.into_iter().rev() {330 let ch = NUMBERS[digit as usize] as char;331 out.push(if caps { ch.to_ascii_uppercase() } else { ch });332 }333}334335pub fn render_decimal(336 out: &mut String,337 iv: i64,338 padding: usize,339 precision: usize,340 blank: bool,341 sign: bool,342) {343 render_integer(out, iv, padding, precision, blank, sign, 10, "", false)344}345pub fn render_octal(346 out: &mut String,347 iv: i64,348 padding: usize,349 precision: usize,350 alt: bool,351 blank: bool,352 sign: bool,353) {354 render_integer(355 out,356 iv,357 padding,358 precision,359 blank,360 sign,361 8,362 if alt && iv != 0 { "0" } else { "" },363 false,364 )365}366pub fn render_hexadecimal(367 out: &mut String,368 iv: i64,369 padding: usize,370 precision: usize,371 alt: bool,372 blank: bool,373 sign: bool,374 caps: bool,375) {376 render_integer(377 out,378 iv,379 padding,380 precision,381 blank,382 sign,383 16,384 match (alt, caps) {385 (true, true) => "0X",386 (true, false) => "0x",387 (false, _) => "",388 },389 caps,390 )391}392393pub fn render_float(394 out: &mut String,395 n: f64,396 mut padding: usize,397 precision: usize,398 blank: bool,399 sign: bool,400 ensure_pt: bool,401 trailing: bool,402) {403 let dot_size = if precision == 0 && !ensure_pt { 0 } else { 1 };404 padding = padding.saturating_sub(dot_size + precision);405 render_decimal(out, n.floor() as i64, padding, 0, blank, sign);406 if precision == 0 {407 if ensure_pt {408 out.push('.');409 }410 return;411 }412 let frac = n413 .fract()414 .mul_add(10.0_f64.powf(precision as f64), 0.5)415 .floor();416 if trailing || frac > 0.0 {417 out.push('.');418 let mut frac_str = String::new();419 render_decimal(&mut frac_str, frac as i64, precision, 0, false, false);420 let mut trim = frac_str.len();421 if !trailing {422 for b in frac_str.as_bytes().iter().rev() {423 if *b == b'0' {424 trim -= 1;425 }426 }427 }428 out.push_str(&frac_str[..trim]);429 } else if ensure_pt {430 out.push('.');431 }432}433434pub fn render_float_sci(435 out: &mut String,436 n: f64,437 mut padding: usize,438 precision: usize,439 blank: bool,440 sign: bool,441 ensure_pt: bool,442 trailing: bool,443 caps: bool,444) {445 let exponent = n.log10().floor();446 let mantissa = if exponent as i16 == -324 {447 n * 10.0 / 10.0_f64.powf(exponent + 1.0)448 } else {449 n / 10.0_f64.powf(exponent)450 };451 let mut exponent_str = String::new();452 render_decimal(&mut exponent_str, exponent as i64, 3, 0, false, true);453454 // +1 for e455 padding = padding.saturating_sub(exponent_str.len() + 1);456457 render_float(458 out, mantissa, padding, precision, blank, sign, ensure_pt, trailing,459 );460 out.push(if caps { 'E' } else { 'e' });461 out.push_str(&exponent_str);462}463464pub fn format_code(465 out: &mut String,466 value: &Val,467 code: &Code,468 width: usize,469 precision: Option<usize>,470) -> Result<()> {471 let clfags = &code.cflags;472 let (fpprec, iprec) = match precision {473 Some(v) => (v, v),474 None => (6, 0),475 };476 let padding = if clfags.zero && !clfags.left {477 width478 } else {479 0480 };481482 // TODO: If left padded, can optimize by writing directly to out483 let mut tmp_out = String::new();484485 match code.convtype {486 ConvTypeV::String => tmp_out.push_str(&value.clone().to_string()?),487 ConvTypeV::Decimal => {488 let value = f64::try_from(value.clone())?;489 render_decimal(490 &mut tmp_out,491 value as i64,492 padding,493 iprec,494 clfags.blank,495 clfags.sign,496 );497 }498 ConvTypeV::Octal => {499 let value = f64::try_from(value.clone())?;500 render_octal(501 &mut tmp_out,502 value as i64,503 padding,504 iprec,505 clfags.alt,506 clfags.blank,507 clfags.sign,508 );509 }510 ConvTypeV::Hexadecimal => {511 let value = f64::try_from(value.clone())?;512 render_hexadecimal(513 &mut tmp_out,514 value as i64,515 padding,516 iprec,517 clfags.alt,518 clfags.blank,519 clfags.sign,520 code.caps,521 );522 }523 ConvTypeV::Scientific => {524 let value = f64::try_from(value.clone())?;525 render_float_sci(526 &mut tmp_out,527 value,528 padding,529 fpprec,530 clfags.blank,531 clfags.sign,532 clfags.alt,533 true,534 code.caps,535 );536 }537 ConvTypeV::Float => {538 let value = f64::try_from(value.clone())?;539 render_float(540 &mut tmp_out,541 value,542 padding,543 fpprec,544 clfags.blank,545 clfags.sign,546 clfags.alt,547 true,548 );549 }550 ConvTypeV::Shorter => {551 let value = f64::try_from(value.clone())?;552 let exponent = value.log10().floor();553 if exponent < -4.0 || exponent >= fpprec as f64 {554 render_float_sci(555 &mut tmp_out,556 value,557 padding,558 fpprec - 1,559 clfags.blank,560 clfags.sign,561 clfags.alt,562 clfags.alt,563 code.caps,564 );565 } else {566 let digits_before_pt = 1.max(exponent as usize + 1);567 render_float(568 &mut tmp_out,569 value,570 padding,571 fpprec - digits_before_pt,572 clfags.blank,573 clfags.sign,574 clfags.alt,575 clfags.alt,576 );577 }578 }579 ConvTypeV::Char => match value.clone() {580 Val::Num(n) => tmp_out581 .push(std::char::from_u32(n as u32).ok_or(InvalidUnicodeCodepointGot(n as u32))?),582 Val::Str(s) => {583 if s.chars().count() != 1 {584 throw!(RuntimeError(585 format!("%c expected 1 char string, got {}", s.chars().count()).into(),586 ));587 }588 tmp_out.push_str(&s);589 }590 _ => {591 throw!(TypeMismatch(592 "%c requires number/string",593 vec![ValType::Num, ValType::Str],594 value.value_type(),595 ));596 }597 },598 ConvTypeV::Percent => tmp_out.push('%'),599 };600601 let padding = width.saturating_sub(tmp_out.len());602603 if !clfags.left {604 for _ in 0..padding {605 out.push(' ');606 }607 }608 out.push_str(&tmp_out);609 if clfags.left {610 for _ in 0..padding {611 out.push(' ');612 }613 }614615 Ok(())616}617618pub fn format_arr(str: &str, mut values: &[Val]) -> Result<String> {619 let codes = parse_codes(str)?;620 let mut out = String::new();621622 for code in codes {623 match code {624 Element::String(s) => {625 out.push_str(s);626 }627 Element::Code(c) => {628 let width = match c.width {629 Width::Star => {630 if values.is_empty() {631 throw!(NotEnoughValues);632 }633 let value = &values[0];634 values = &values[1..];635 usize::try_from(value.clone())?636 }637 Width::Fixed(n) => n,638 };639 let precision = match c.precision {640 Some(Width::Star) => {641 if values.is_empty() {642 throw!(NotEnoughValues);643 }644 let value = &values[0];645 values = &values[1..];646 Some(usize::try_from(value.clone())?)647 }648 Some(Width::Fixed(n)) => Some(n),649 None => None,650 };651652 // %% should not consume a value653 let value = if c.convtype == ConvTypeV::Percent {654 &Val::Null655 } else {656 if values.is_empty() {657 throw!(NotEnoughValues);658 }659 let value = &values[0];660 values = &values[1..];661 value662 };663664 format_code(&mut out, value, &c, width, precision)?;665 }666 }667 }668669 Ok(out)670}671672pub fn format_obj(str: &str, values: &ObjValue) -> Result<String> {673 let codes = parse_codes(str)?;674 let mut out = String::new();675676 for code in codes {677 match code {678 Element::String(s) => {679 out.push_str(s);680 }681 Element::Code(c) => {682 // TODO: Operate on ref683 let f: IStr = c.mkey.into();684 let width = match c.width {685 Width::Star => {686 throw!(CannotUseStarWidthWithObject);687 }688 Width::Fixed(n) => n,689 };690 let precision = match c.precision {691 Some(Width::Star) => {692 throw!(CannotUseStarWidthWithObject);693 }694 Some(Width::Fixed(n)) => Some(n),695 None => None,696 };697698 let value = if c.convtype == ConvTypeV::Percent {699 Val::Null700 } else {701 if f.is_empty() {702 throw!(MappingKeysRequired);703 }704 if let Some(v) = values.get(f.clone())? {705 v706 } else {707 throw!(NoSuchFormatField(f));708 }709 };710711 format_code(&mut out, &value, &c, width, precision)?;712 }713 }714 }715716 Ok(out)717}718719#[cfg(test)]720pub mod test_format {721 use super::*;722723 #[test]724 fn parse() {725 assert_eq!(726 parse_codes(727 "How much error budget is left looking at our %.3f%% availability gurantees?"728 )729 .unwrap()730 .len(),731 4732 );733 }734735 #[test]736 fn octals() {737 assert_eq!(format_arr("%#o", &[Val::Num(8.0)]).unwrap(), "010");738 assert_eq!(format_arr("%#4o", &[Val::Num(8.0)]).unwrap(), " 010");739 assert_eq!(format_arr("%4o", &[Val::Num(8.0)]).unwrap(), " 10");740 assert_eq!(format_arr("%04o", &[Val::Num(8.0)]).unwrap(), "0010");741 assert_eq!(format_arr("%+4o", &[Val::Num(8.0)]).unwrap(), " +10");742 assert_eq!(format_arr("%+04o", &[Val::Num(8.0)]).unwrap(), "+010");743 assert_eq!(format_arr("%-4o", &[Val::Num(8.0)]).unwrap(), "10 ");744 assert_eq!(format_arr("%+-4o", &[Val::Num(8.0)]).unwrap(), "+10 ");745 assert_eq!(format_arr("%+-04o", &[Val::Num(8.0)]).unwrap(), "+10 ");746 }747748 #[test]749 fn percent_doesnt_consumes_values() {750 assert_eq!(751 format_arr(752 "How much error budget is left looking at our %.3f%% availability gurantees?",753 &[Val::Num(4.0)]754 )755 .unwrap(),756 "How much error budget is left looking at our 4.000% availability gurantees?"757 );758 }759}1//! faster std.format impl2#![allow(clippy::too_many_arguments)]34use std::convert::TryFrom;56use gcmodule::Trace;7use jrsonnet_interner::IStr;8use jrsonnet_types::ValType;9use thiserror::Error;1011use crate::{error::Error::*, throw, LocError, ObjValue, Result, Val};1213#[derive(Debug, Clone, Error, Trace)]14pub enum FormatError {15 #[error("truncated format code")]16 TruncatedFormatCode,17 #[error("unrecognized conversion type: {0}")]18 UnrecognizedConversionType(char),1920 #[error("not enough values")]21 NotEnoughValues,2223 #[error("cannot use * width with object")]24 CannotUseStarWidthWithObject,25 #[error("mapping keys required")]26 MappingKeysRequired,27 #[error("no such format field: {0}")]28 NoSuchFormatField(IStr),29}3031impl From<FormatError> for LocError {32 fn from(e: FormatError) -> Self {33 Self::new(Format(e))34 }35}3637use FormatError::*;3839type ParseResult<'t, T> = std::result::Result<(T, &'t str), FormatError>;4041pub fn try_parse_mapping_key(str: &str) -> ParseResult<&str> {42 if str.is_empty() {43 return Err(TruncatedFormatCode);44 }45 let bytes = str.as_bytes();46 if bytes[0] == b'(' {47 let mut i = 1;48 while i < bytes.len() {49 if bytes[i] == b')' {50 return Ok((&str[1..i as usize], &str[i as usize + 1..]));51 }52 i += 1;53 }54 Err(TruncatedFormatCode)55 } else {56 Ok(("", str))57 }58}5960#[cfg(test)]61pub mod tests_key {62 use super::*;6364 #[test]65 fn parse_key() {66 assert_eq!(67 try_parse_mapping_key("(hello ) world").unwrap(),68 ("hello ", " world")69 );70 assert_eq!(try_parse_mapping_key("() world").unwrap(), ("", " world"));71 assert_eq!(try_parse_mapping_key(" world").unwrap(), ("", " world"));72 assert_eq!(73 try_parse_mapping_key(" () world").unwrap(),74 ("", " () world")75 );76 }7778 #[test]79 #[should_panic]80 fn parse_key_missing_start() {81 try_parse_mapping_key("").unwrap();82 }8384 #[test]85 #[should_panic]86 fn parse_key_missing_end() {87 try_parse_mapping_key("( ").unwrap();88 }89}9091#[derive(Default, Debug)]92pub struct CFlags {93 pub alt: bool,94 pub zero: bool,95 pub left: bool,96 pub blank: bool,97 pub sign: bool,98}99100pub fn try_parse_cflags(str: &str) -> ParseResult<CFlags> {101 if str.is_empty() {102 return Err(TruncatedFormatCode);103 }104 let bytes = str.as_bytes();105 let mut i = 0;106 let mut out = CFlags::default();107 loop {108 if bytes.len() == i {109 return Err(TruncatedFormatCode);110 }111 match bytes[i] {112 b'#' => out.alt = true,113 b'0' => out.zero = true,114 b'-' => out.left = true,115 b' ' => out.blank = true,116 b'+' => out.sign = true,117 _ => break,118 }119 i += 1;120 }121 Ok((out, &str[i..]))122}123124#[derive(Debug, PartialEq)]125pub enum Width {126 Star,127 Fixed(usize),128}129pub fn try_parse_field_width(str: &str) -> ParseResult<Width> {130 if str.is_empty() {131 return Err(TruncatedFormatCode);132 }133 let bytes = str.as_bytes();134 if bytes[0] == b'*' {135 return Ok((Width::Star, &str[1..]));136 }137 let mut out: usize = 0;138 let mut digits = 0;139 while let Some(digit) = (bytes[digits] as char).to_digit(10) {140 out *= 10;141 out += digit as usize;142 digits += 1;143 if digits == bytes.len() {144 return Err(TruncatedFormatCode);145 }146 }147 Ok((Width::Fixed(out), &str[digits..]))148}149150pub fn try_parse_precision(str: &str) -> ParseResult<Option<Width>> {151 if str.is_empty() {152 return Err(TruncatedFormatCode);153 }154 let bytes = str.as_bytes();155 if bytes[0] == b'.' {156 try_parse_field_width(&str[1..]).map(|(r, s)| (Some(r), s))157 } else {158 Ok((None, str))159 }160}161162// Only skips163pub fn try_parse_length_modifier(str: &str) -> ParseResult<()> {164 if str.is_empty() {165 return Err(TruncatedFormatCode);166 }167 let bytes = str.as_bytes();168 let mut idx = 0;169 while bytes[idx] == b'h' || bytes[idx] == b'l' || bytes[idx] == b'L' {170 idx += 1;171 if bytes.len() == idx {172 return Err(TruncatedFormatCode);173 }174 }175 Ok(((), &str[idx..]))176}177178#[derive(Debug, PartialEq)]179pub enum ConvTypeV {180 Decimal,181 Octal,182 Hexadecimal,183 Scientific,184 Float,185 Shorter,186 Char,187 String,188 Percent,189}190pub struct ConvType {191 v: ConvTypeV,192 caps: bool,193}194195pub fn parse_conversion_type(str: &str) -> ParseResult<ConvType> {196 if str.is_empty() {197 return Err(TruncatedFormatCode);198 }199200 let code = str.as_bytes()[0];201 let v: (ConvTypeV, bool) = match code {202 b'd' | b'i' | b'u' => (ConvTypeV::Decimal, false),203 b'o' => (ConvTypeV::Octal, false),204 b'x' => (ConvTypeV::Hexadecimal, false),205 b'X' => (ConvTypeV::Hexadecimal, true),206 b'e' => (ConvTypeV::Scientific, false),207 b'E' => (ConvTypeV::Scientific, true),208 b'f' => (ConvTypeV::Float, false),209 b'F' => (ConvTypeV::Float, true),210 b'g' => (ConvTypeV::Shorter, false),211 b'G' => (ConvTypeV::Shorter, true),212 b'c' => (ConvTypeV::Char, false),213 b's' => (ConvTypeV::String, false),214 b'%' => (ConvTypeV::Percent, false),215 c => return Err(UnrecognizedConversionType(c as char)),216 };217218 Ok((ConvType { v: v.0, caps: v.1 }, &str[1..]))219}220221#[derive(Debug)]222pub struct Code<'s> {223 mkey: &'s str,224 cflags: CFlags,225 width: Width,226 precision: Option<Width>,227 convtype: ConvTypeV,228 caps: bool,229}230pub fn parse_code(str: &str) -> ParseResult<Code> {231 if str.is_empty() {232 return Err(TruncatedFormatCode);233 }234 let (mkey, str) = try_parse_mapping_key(str)?;235 let (cflags, str) = try_parse_cflags(str)?;236 let (width, str) = try_parse_field_width(str)?;237 let (precision, str) = try_parse_precision(str)?;238 let (_, str) = try_parse_length_modifier(str)?;239 let (convtype, str) = parse_conversion_type(str)?;240241 Ok((242 Code {243 mkey,244 cflags,245 width,246 precision,247 convtype: convtype.v,248 caps: convtype.caps,249 },250 str,251 ))252}253254#[derive(Debug)]255pub enum Element<'s> {256 String(&'s str),257 Code(Code<'s>),258}259pub fn parse_codes(mut str: &str) -> Result<Vec<Element>> {260 let mut bytes = str.as_bytes();261 let mut out = vec![];262 let mut offset = 0;263264 loop {265 while offset != bytes.len() && bytes[offset] != b'%' {266 offset += 1;267 }268 if offset != 0 {269 out.push(Element::String(&str[0..offset]));270 }271 if offset == bytes.len() {272 return Ok(out);273 }274 str = &str[offset + 1..];275 let (code, nstr) = parse_code(str)?;276 str = nstr;277 bytes = str.as_bytes();278 offset = 0;279280 out.push(Element::Code(code))281 }282}283284const NUMBERS: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";285286#[inline]287pub fn render_integer(288 out: &mut String,289 iv: i64,290 padding: usize,291 precision: usize,292 blank: bool,293 sign: bool,294 radix: i64,295 prefix: &str,296 caps: bool,297) {298 // Digit char indexes in reverse order, i.e299 // for radix = 16 and n = 12f: [15, 2, 1]300 let digits = if iv == 0 {301 vec![0u8]302 } else {303 let mut v = iv.abs();304 let mut nums = Vec::with_capacity(1);305 while v > 0 {306 nums.push((v % radix) as u8);307 v /= radix;308 }309 nums310 };311 let neg = iv < 0;312 let zp = padding.saturating_sub(if neg || blank || sign { 1 } else { 0 });313 let zp2 = zp314 .max(precision)315 .saturating_sub(prefix.len() + digits.len());316317 if neg {318 out.push('-')319 } else if sign {320 out.push('+');321 } else if blank {322 out.push(' ');323 }324325 out.reserve(zp2);326 for _ in 0..zp2 {327 out.push('0');328 }329 out.push_str(prefix);330331 for digit in digits.into_iter().rev() {332 let ch = NUMBERS[digit as usize] as char;333 out.push(if caps { ch.to_ascii_uppercase() } else { ch });334 }335}336337pub fn render_decimal(338 out: &mut String,339 iv: i64,340 padding: usize,341 precision: usize,342 blank: bool,343 sign: bool,344) {345 render_integer(out, iv, padding, precision, blank, sign, 10, "", false)346}347pub fn render_octal(348 out: &mut String,349 iv: i64,350 padding: usize,351 precision: usize,352 alt: bool,353 blank: bool,354 sign: bool,355) {356 render_integer(357 out,358 iv,359 padding,360 precision,361 blank,362 sign,363 8,364 if alt && iv != 0 { "0" } else { "" },365 false,366 )367}368pub fn render_hexadecimal(369 out: &mut String,370 iv: i64,371 padding: usize,372 precision: usize,373 alt: bool,374 blank: bool,375 sign: bool,376 caps: bool,377) {378 render_integer(379 out,380 iv,381 padding,382 precision,383 blank,384 sign,385 16,386 match (alt, caps) {387 (true, true) => "0X",388 (true, false) => "0x",389 (false, _) => "",390 },391 caps,392 )393}394395pub fn render_float(396 out: &mut String,397 n: f64,398 mut padding: usize,399 precision: usize,400 blank: bool,401 sign: bool,402 ensure_pt: bool,403 trailing: bool,404) {405 let dot_size = if precision == 0 && !ensure_pt { 0 } else { 1 };406 padding = padding.saturating_sub(dot_size + precision);407 render_decimal(out, n.floor() as i64, padding, 0, blank, sign);408 if precision == 0 {409 if ensure_pt {410 out.push('.');411 }412 return;413 }414 let frac = n415 .fract()416 .mul_add(10.0_f64.powf(precision as f64), 0.5)417 .floor();418 if trailing || frac > 0.0 {419 out.push('.');420 let mut frac_str = String::new();421 render_decimal(&mut frac_str, frac as i64, precision, 0, false, false);422 let mut trim = frac_str.len();423 if !trailing {424 for b in frac_str.as_bytes().iter().rev() {425 if *b == b'0' {426 trim -= 1;427 }428 }429 }430 out.push_str(&frac_str[..trim]);431 } else if ensure_pt {432 out.push('.');433 }434}435436pub fn render_float_sci(437 out: &mut String,438 n: f64,439 mut padding: usize,440 precision: usize,441 blank: bool,442 sign: bool,443 ensure_pt: bool,444 trailing: bool,445 caps: bool,446) {447 let exponent = n.log10().floor();448 let mantissa = if exponent as i16 == -324 {449 n * 10.0 / 10.0_f64.powf(exponent + 1.0)450 } else {451 n / 10.0_f64.powf(exponent)452 };453 let mut exponent_str = String::new();454 render_decimal(&mut exponent_str, exponent as i64, 3, 0, false, true);455456 // +1 for e457 padding = padding.saturating_sub(exponent_str.len() + 1);458459 render_float(460 out, mantissa, padding, precision, blank, sign, ensure_pt, trailing,461 );462 out.push(if caps { 'E' } else { 'e' });463 out.push_str(&exponent_str);464}465466pub fn format_code(467 out: &mut String,468 value: &Val,469 code: &Code,470 width: usize,471 precision: Option<usize>,472) -> Result<()> {473 let clfags = &code.cflags;474 let (fpprec, iprec) = match precision {475 Some(v) => (v, v),476 None => (6, 0),477 };478 let padding = if clfags.zero && !clfags.left {479 width480 } else {481 0482 };483484 // TODO: If left padded, can optimize by writing directly to out485 let mut tmp_out = String::new();486487 match code.convtype {488 ConvTypeV::String => tmp_out.push_str(&value.clone().to_string()?),489 ConvTypeV::Decimal => {490 let value = f64::try_from(value.clone())?;491 render_decimal(492 &mut tmp_out,493 value as i64,494 padding,495 iprec,496 clfags.blank,497 clfags.sign,498 );499 }500 ConvTypeV::Octal => {501 let value = f64::try_from(value.clone())?;502 render_octal(503 &mut tmp_out,504 value as i64,505 padding,506 iprec,507 clfags.alt,508 clfags.blank,509 clfags.sign,510 );511 }512 ConvTypeV::Hexadecimal => {513 let value = f64::try_from(value.clone())?;514 render_hexadecimal(515 &mut tmp_out,516 value as i64,517 padding,518 iprec,519 clfags.alt,520 clfags.blank,521 clfags.sign,522 code.caps,523 );524 }525 ConvTypeV::Scientific => {526 let value = f64::try_from(value.clone())?;527 render_float_sci(528 &mut tmp_out,529 value,530 padding,531 fpprec,532 clfags.blank,533 clfags.sign,534 clfags.alt,535 true,536 code.caps,537 );538 }539 ConvTypeV::Float => {540 let value = f64::try_from(value.clone())?;541 render_float(542 &mut tmp_out,543 value,544 padding,545 fpprec,546 clfags.blank,547 clfags.sign,548 clfags.alt,549 true,550 );551 }552 ConvTypeV::Shorter => {553 let value = f64::try_from(value.clone())?;554 let exponent = value.log10().floor();555 if exponent < -4.0 || exponent >= fpprec as f64 {556 render_float_sci(557 &mut tmp_out,558 value,559 padding,560 fpprec - 1,561 clfags.blank,562 clfags.sign,563 clfags.alt,564 clfags.alt,565 code.caps,566 );567 } else {568 let digits_before_pt = 1.max(exponent as usize + 1);569 render_float(570 &mut tmp_out,571 value,572 padding,573 fpprec - digits_before_pt,574 clfags.blank,575 clfags.sign,576 clfags.alt,577 clfags.alt,578 );579 }580 }581 ConvTypeV::Char => match value.clone() {582 Val::Num(n) => tmp_out583 .push(std::char::from_u32(n as u32).ok_or(InvalidUnicodeCodepointGot(n as u32))?),584 Val::Str(s) => {585 if s.chars().count() != 1 {586 throw!(RuntimeError(587 format!("%c expected 1 char string, got {}", s.chars().count()).into(),588 ));589 }590 tmp_out.push_str(&s);591 }592 _ => {593 throw!(TypeMismatch(594 "%c requires number/string",595 vec![ValType::Num, ValType::Str],596 value.value_type(),597 ));598 }599 },600 ConvTypeV::Percent => tmp_out.push('%'),601 };602603 let padding = width.saturating_sub(tmp_out.len());604605 if !clfags.left {606 for _ in 0..padding {607 out.push(' ');608 }609 }610 out.push_str(&tmp_out);611 if clfags.left {612 for _ in 0..padding {613 out.push(' ');614 }615 }616617 Ok(())618}619620pub fn format_arr(str: &str, mut values: &[Val]) -> Result<String> {621 let codes = parse_codes(str)?;622 let mut out = String::new();623624 for code in codes {625 match code {626 Element::String(s) => {627 out.push_str(s);628 }629 Element::Code(c) => {630 let width = match c.width {631 Width::Star => {632 if values.is_empty() {633 throw!(NotEnoughValues);634 }635 let value = &values[0];636 values = &values[1..];637 usize::try_from(value.clone())?638 }639 Width::Fixed(n) => n,640 };641 let precision = match c.precision {642 Some(Width::Star) => {643 if values.is_empty() {644 throw!(NotEnoughValues);645 }646 let value = &values[0];647 values = &values[1..];648 Some(usize::try_from(value.clone())?)649 }650 Some(Width::Fixed(n)) => Some(n),651 None => None,652 };653654 // %% should not consume a value655 let value = if c.convtype == ConvTypeV::Percent {656 &Val::Null657 } else {658 if values.is_empty() {659 throw!(NotEnoughValues);660 }661 let value = &values[0];662 values = &values[1..];663 value664 };665666 format_code(&mut out, value, &c, width, precision)?;667 }668 }669 }670671 Ok(out)672}673674pub fn format_obj(str: &str, values: &ObjValue) -> Result<String> {675 let codes = parse_codes(str)?;676 let mut out = String::new();677678 for code in codes {679 match code {680 Element::String(s) => {681 out.push_str(s);682 }683 Element::Code(c) => {684 // TODO: Operate on ref685 let f: IStr = c.mkey.into();686 let width = match c.width {687 Width::Star => {688 throw!(CannotUseStarWidthWithObject);689 }690 Width::Fixed(n) => n,691 };692 let precision = match c.precision {693 Some(Width::Star) => {694 throw!(CannotUseStarWidthWithObject);695 }696 Some(Width::Fixed(n)) => Some(n),697 None => None,698 };699700 let value = if c.convtype == ConvTypeV::Percent {701 Val::Null702 } else {703 if f.is_empty() {704 throw!(MappingKeysRequired);705 }706 if let Some(v) = values.get(f.clone())? {707 v708 } else {709 throw!(NoSuchFormatField(f));710 }711 };712713 format_code(&mut out, &value, &c, width, precision)?;714 }715 }716 }717718 Ok(out)719}720721#[cfg(test)]722pub mod test_format {723 use super::*;724725 #[test]726 fn parse() {727 assert_eq!(728 parse_codes(729 "How much error budget is left looking at our %.3f%% availability gurantees?"730 )731 .unwrap()732 .len(),733 4734 );735 }736737 #[test]738 fn octals() {739 assert_eq!(format_arr("%#o", &[Val::Num(8.0)]).unwrap(), "010");740 assert_eq!(format_arr("%#4o", &[Val::Num(8.0)]).unwrap(), " 010");741 assert_eq!(format_arr("%4o", &[Val::Num(8.0)]).unwrap(), " 10");742 assert_eq!(format_arr("%04o", &[Val::Num(8.0)]).unwrap(), "0010");743 assert_eq!(format_arr("%+4o", &[Val::Num(8.0)]).unwrap(), " +10");744 assert_eq!(format_arr("%+04o", &[Val::Num(8.0)]).unwrap(), "+010");745 assert_eq!(format_arr("%-4o", &[Val::Num(8.0)]).unwrap(), "10 ");746 assert_eq!(format_arr("%+-4o", &[Val::Num(8.0)]).unwrap(), "+10 ");747 assert_eq!(format_arr("%+-04o", &[Val::Num(8.0)]).unwrap(), "+10 ");748 }749750 #[test]751 fn percent_doesnt_consumes_values() {752 assert_eq!(753 format_arr(754 "How much error budget is left looking at our %.3f%% availability gurantees?",755 &[Val::Num(4.0)]756 )757 .unwrap(),758 "How much error budget is left looking at our 4.000% availability gurantees?"759 );760 }761}crates/jrsonnet-evaluator/src/builtin/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/manifest.rs
@@ -1,7 +1,7 @@
-use crate::error::Error::*;
-use crate::error::Result;
-use crate::push_description_frame;
-use crate::{throw, Val};
+use crate::{
+ error::{Error::*, Result},
+ push_description_frame, throw, Val,
+};
#[derive(PartialEq, Clone, Copy)]
pub enum ManifestType {
crates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -1,23 +1,25 @@
-use crate::function::{CallLocation, StaticBuiltin};
-use crate::typed::{Any, Bytes, PositiveF64, VecVal, M1};
-use crate::{
- builtin::manifest::{manifest_yaml_ex, ManifestYamlOptions},
- equals,
- error::{Error::*, Result},
- operator::evaluate_mod_op,
- primitive_equals, push_frame, throw,
- typed::{Either2, Either4},
- with_state, ArrValue, FuncVal, IndexableVal, Val,
+use std::{
+ collections::HashMap,
+ convert::{TryFrom, TryInto},
};
-use crate::{Either, ObjValue};
+
use format::{format_arr, format_obj};
use gcmodule::Cc;
use jrsonnet_interner::IStr;
use serde::Deserialize;
use serde_yaml::DeserializingQuirks;
-use std::collections::HashMap;
-use std::convert::{TryFrom, TryInto};
+use crate::{
+ builtin::manifest::{manifest_yaml_ex, ManifestYamlOptions},
+ error::{Error::*, Result},
+ function::{CallLocation, StaticBuiltin},
+ operator::evaluate_mod_op,
+ push_frame, throw,
+ typed::{Any, BoundedUsize, Bytes, Either2, Either4, PositiveF64, VecVal, M1},
+ val::{equals, primitive_equals, ArrValue, FuncVal, IndexableVal, Slice},
+ with_state, Either, ObjValue, Val,
+};
+
pub mod stdlib;
pub use stdlib::*;
@@ -58,12 +60,12 @@
}
Ok(Val::Str(
- (s.chars()
- .skip(index)
- .take(end - index)
- .step_by(step)
- .collect::<String>())
- .into(),
+ (s.chars()
+ .skip(index)
+ .take(end - index)
+ .step_by(step)
+ .collect::<String>())
+ .into(),
))
}
IndexableVal::Arr(arr) => {
crates/jrsonnet-evaluator/src/builtin/sort.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/sort.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/sort.rs
@@ -1,10 +1,12 @@
+use gcmodule::{Cc, Trace};
+
use crate::{
error::{Error, LocError, Result},
throw,
typed::Any,
- FuncVal, Val,
+ val::FuncVal,
+ Val,
};
-use gcmodule::{Cc, Trace};
#[derive(Debug, Clone, thiserror::Error, Trace)]
pub enum SortError {
crates/jrsonnet-evaluator/src/builtin/stdlib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/stdlib.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/stdlib.rs
@@ -1,6 +1,7 @@
-use jrsonnet_parser::{LocExpr, ParserSettings};
use std::path::PathBuf;
+use jrsonnet_parser::{LocExpr, ParserSettings};
+
thread_local! {
/// To avoid parsing again when issued from the same thread
#[allow(unreachable_code)]
crates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -1,12 +1,12 @@
-use crate::cc_ptr_eq;
-use crate::gc::GcHashMap;
+use std::fmt::Debug;
+
+use gcmodule::{Cc, Trace};
+use jrsonnet_interner::IStr;
+
use crate::{
- error::Error::*, map::LayeredHashMap, FutureWrapper, LazyBinding, LazyVal, ObjValue, Result,
- Val,
+ cc_ptr_eq, error::Error::*, gc::GcHashMap, map::LayeredHashMap, FutureWrapper, LazyBinding,
+ LazyVal, ObjValue, Result, Val,
};
-use gcmodule::{Cc, Trace};
-use jrsonnet_interner::IStr;
-use std::fmt::Debug;
#[derive(Clone, Trace)]
pub struct ContextCreator(pub Context, pub FutureWrapper<GcHashMap<IStr, LazyBinding>>);
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -1,16 +1,18 @@
-use crate::{
- builtin::{format::FormatError, sort::SortError},
- typed::TypeLocError,
+use std::{
+ path::{Path, PathBuf},
+ rc::Rc,
};
+
use gcmodule::Trace;
use jrsonnet_interner::IStr;
use jrsonnet_parser::{BinaryOpType, ExprLocation, UnaryOpType};
use jrsonnet_types::ValType;
-use std::{
- path::{Path, PathBuf},
- rc::Rc,
+use thiserror::Error;
+
+use crate::{
+ builtin::{format::FormatError, sort::SortError},
+ typed::TypeLocError,
};
-use thiserror::Error;
#[derive(Error, Debug, Clone, Trace)]
pub enum Error {
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -1,15 +1,5 @@
use std::convert::TryFrom;
-use crate::{
- builtin::{std_slice, BUILTINS},
- error::Error::*,
- evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},
- function::CallLocation,
- gc::TraceBox,
- push_frame, throw, with_state, ArrValue, Bindable, Context, ContextCreator, FuncDesc, FuncVal,
- FutureWrapper, GcHashMap, LazyBinding, LazyVal, LazyValValue, ObjValue, ObjValueBuilder,
- ObjectAssertion, Result, Val,
-};
use gcmodule::{Cc, Trace};
use jrsonnet_interner::IStr;
use jrsonnet_parser::{
@@ -17,6 +7,19 @@
LiteralType, LocExpr, Member, ObjBody, ParamsDesc,
};
use jrsonnet_types::ValType;
+
+use crate::{
+ builtin::{std_slice, BUILTINS},
+ error::Error::*,
+ evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},
+ function::CallLocation,
+ gc::TraceBox,
+ push_frame, throw,
+ typed::BoundedUsize,
+ val::{ArrValue, FuncDesc, FuncVal, LazyValValue},
+ with_state, Bindable, Context, ContextCreator, FutureWrapper, GcHashMap, LazyBinding, LazyVal,
+ ObjValue, ObjValueBuilder, ObjectAssertion, Result, Val,
+};
pub mod operator;
pub fn evaluate_binding_in_future(
crates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -1,10 +1,11 @@
use std::convert::TryInto;
-use crate::builtin::std_format;
-use crate::{equals, evaluate, Context, Val};
-use crate::{error::Error::*, throw, Result};
use jrsonnet_parser::{BinaryOpType, LocExpr, UnaryOpType};
+use crate::{
+ builtin::std_format, error::Error::*, evaluate, throw, val::equals, Context, Result, Val,
+};
+
pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {
use UnaryOpType::*;
use Val::*;
crates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function.rs
+++ b/crates/jrsonnet-evaluator/src/function.rs
@@ -1,16 +1,19 @@
+use std::{borrow::Cow, collections::HashMap, convert::TryFrom};
+
+use gcmodule::Trace;
+use jrsonnet_interner::IStr;
+pub use jrsonnet_macros::builtin;
+use jrsonnet_parser::{ArgsDesc, ExprLocation, LocExpr, ParamsDesc};
+
use crate::{
error::{Error::*, LocError},
evaluate, evaluate_named,
gc::TraceBox,
throw,
typed::Typed,
- Context, FutureWrapper, GcHashMap, LazyVal, LazyValValue, Result, Val,
+ val::LazyValValue,
+ Context, FutureWrapper, GcHashMap, LazyVal, Result, Val,
};
-use gcmodule::Trace;
-use jrsonnet_interner::IStr;
-pub use jrsonnet_macros::builtin;
-use jrsonnet_parser::{ArgsDesc, ExprLocation, LocExpr, ParamsDesc};
-use std::{borrow::Cow, collections::HashMap, convert::TryFrom};
#[derive(Clone, Copy)]
pub struct CallLocation<'l>(pub Option<&'l ExprLocation>);
crates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/import.rs
+++ b/crates/jrsonnet-evaluator/src/import.rs
@@ -1,17 +1,20 @@
-use crate::{
- error::{Error::*, Result},
- throw,
-};
-use fs::File;
-use jrsonnet_interner::IStr;
-use std::fs;
use std::{
any::Any,
+ convert::TryFrom,
+ fs,
+ io::Read,
path::{Path, PathBuf},
rc::Rc,
};
-use std::{convert::TryFrom, io::Read};
+use fs::File;
+use jrsonnet_interner::IStr;
+
+use crate::{
+ error::{Error::*, Result},
+ throw,
+};
+
/// Implements file resolution logic for `import` and `importStr`
pub trait ImportResolver {
/// Resolves real file path, e.g. `(/home/user/manifests, b.libjsonnet)` can correspond
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -1,9 +1,11 @@
+use std::convert::{TryFrom, TryInto};
+
+use serde_json::{Map, Number, Value};
+
use crate::{
error::{Error::*, LocError, Result},
throw, ObjValueBuilder, Val,
};
-use serde_json::{Map, Number, Value};
-use std::convert::{TryFrom, TryInto};
impl TryFrom<&Val> for Value {
type Error = LocError;
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -13,6 +13,7 @@
pub mod error;
mod evaluate;
pub mod function;
+pub mod gc;
mod import;
mod integrations;
mod map;
@@ -20,9 +21,15 @@
mod obj;
pub mod trace;
pub mod typed;
-mod val;
+pub mod val;
-pub use jrsonnet_parser as parser;
+use std::{
+ cell::{Ref, RefCell, RefMut},
+ collections::HashMap,
+ fmt::Debug,
+ path::{Path, PathBuf},
+ rc::Rc,
+};
pub use ctx::*;
pub use dynamic::*;
@@ -33,18 +40,11 @@
use gcmodule::{Cc, Trace, Weak};
pub use import::*;
pub use jrsonnet_interner::IStr;
+pub use jrsonnet_parser as parser;
use jrsonnet_parser::*;
pub use obj::*;
-use std::{
- cell::{Ref, RefCell, RefMut},
- collections::HashMap,
- fmt::Debug,
- path::{Path, PathBuf},
- rc::Rc,
-};
use trace::{location_to_offset, offset_to_location, CodeLocation, CompactFormat, TraceFormat};
-pub use val::*;
-pub mod gc;
+pub use val::{LazyVal, ManifestFormat, Val};
pub trait Bindable: Trace + 'static {
fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal>;
@@ -693,18 +693,24 @@
#[cfg(test)]
pub mod tests {
- use super::Val;
- use crate::{
- error::Error::*, function::BuiltinParam, gc::TraceBox, native::NativeCallbackHandler,
- primitive_equals, EvaluationState,
- };
- use gcmodule::{Cc, Trace};
- use jrsonnet_parser::*;
use std::{
path::{Path, PathBuf},
rc::Rc,
};
+ use gcmodule::{Cc, Trace};
+ use jrsonnet_parser::*;
+
+ use super::Val;
+ use crate::{
+ error::Error::*,
+ function::{BuiltinParam, CallLocation},
+ gc::TraceBox,
+ native::NativeCallbackHandler,
+ val::primitive_equals,
+ EvaluationState,
+ };
+
#[test]
#[should_panic]
fn eval_state_stacktrace() {
@@ -712,11 +718,15 @@
state.run_in_state(|| {
state
.push(
- Some(&ExprLocation(PathBuf::from("test1.jsonnet").into(), 10, 20)),
+ CallLocation::new(&ExprLocation(PathBuf::from("test1.jsonnet").into(), 10, 20)),
|| "outer".to_owned(),
|| {
state.push(
- Some(&ExprLocation(PathBuf::from("test2.jsonnet").into(), 30, 40)),
+ CallLocation::new(&ExprLocation(
+ PathBuf::from("test2.jsonnet").into(),
+ 30,
+ 40,
+ )),
|| "inner".to_owned(),
|| Err(RuntimeError("".into()).into()),
)?;
@@ -1290,10 +1300,11 @@
}
mod derive_typed {
+ use std::path::PathBuf;
+
use crate::{typed::Typed, EvaluationState};
- use std::path::PathBuf;
- #[derive(Typed, PartialEq, Debug)]
+ #[derive(PartialEq, Debug, Typed)]
struct MyTyped {
a: u32,
#[typed(rename = "b")]
crates/jrsonnet-evaluator/src/native.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/native.rs
+++ b/crates/jrsonnet-evaluator/src/native.rs
@@ -1,13 +1,16 @@
#![allow(clippy::type_complexity)]
-use crate::function::{parse_builtin_call, ArgsLike, Builtin, BuiltinParam, CallLocation};
-use crate::gc::TraceBox;
-use crate::Context;
-use crate::{error::Result, Val};
+use std::{path::Path, rc::Rc};
+
use gcmodule::Trace;
-use std::path::Path;
-use std::rc::Rc;
+use crate::{
+ error::Result,
+ function::{parse_builtin_call, ArgsLike, Builtin, BuiltinParam, CallLocation},
+ gc::TraceBox,
+ Context, Val,
+};
+
#[derive(Trace)]
pub struct NativeCallback {
pub(crate) params: Vec<BuiltinParam>,
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -1,20 +1,23 @@
-use crate::error::LocError;
-use crate::function::CallLocation;
-use crate::gc::{GcHashMap, GcHashSet, TraceBox};
-use crate::operator::evaluate_add_op;
-use crate::push_frame;
-use crate::{
- cc_ptr_eq, error::Error::*, throw, weak_ptr_eq, weak_raw, Bindable, LazyBinding, LazyVal,
- Result, Val,
+use std::{
+ cell::RefCell,
+ fmt::Debug,
+ hash::{Hash, Hasher},
};
+
use gcmodule::{Cc, Trace, Weak};
use jrsonnet_interner::IStr;
use jrsonnet_parser::{ExprLocation, Visibility};
use rustc_hash::FxHashMap;
-use std::cell::RefCell;
-use std::fmt::Debug;
-use std::hash::{Hash, Hasher};
+use crate::{
+ cc_ptr_eq,
+ error::{Error::*, LocError},
+ function::CallLocation,
+ gc::{GcHashMap, GcHashSet, TraceBox},
+ operator::evaluate_add_op,
+ push_frame, throw, weak_ptr_eq, weak_raw, Bindable, LazyBinding, LazyVal, Result, Val,
+};
+
#[derive(Debug, Trace)]
pub struct ObjMember {
pub add: bool,
crates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -1,8 +1,10 @@
mod location;
+use std::path::{Path, PathBuf};
+
+pub use location::*;
+
use crate::{error::Error, EvaluationState, LocError};
-pub use location::*;
-use std::path::{Path, PathBuf};
/// The way paths should be displayed
pub enum PathResolver {
crates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/mod.rs
+++ b/crates/jrsonnet-evaluator/src/typed/mod.rs
@@ -2,14 +2,14 @@
mod conversions;
pub use conversions::*;
+use gcmodule::Trace;
+pub use jrsonnet_types::{ComplexValType, ValType};
+use thiserror::Error;
use crate::{
error::{Error, LocError, Result},
push_description_frame, Val,
};
-use gcmodule::Trace;
-pub use jrsonnet_types::{ComplexValType, ValType};
-use thiserror::Error;
#[derive(Debug, Error, Clone, Trace)]
pub enum TypeError {
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -1,3 +1,10 @@
+use std::{cell::RefCell, fmt::Debug, rc::Rc};
+
+use gcmodule::{Cc, Trace};
+use jrsonnet_interner::IStr;
+use jrsonnet_parser::{LocExpr, ParamsDesc};
+use jrsonnet_types::ValType;
+
use crate::{
builtin::manifest::{
manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType, ManifestYamlOptions,
@@ -12,11 +19,6 @@
gc::TraceBox,
throw, Context, ObjValue, Result,
};
-use gcmodule::{Cc, Trace};
-use jrsonnet_interner::IStr;
-use jrsonnet_parser::{LocExpr, ParamsDesc};
-use jrsonnet_types::ValType;
-use std::{cell::RefCell, fmt::Debug, rc::Rc};
pub trait LazyValValue: Trace {
fn get(self: Box<Self>) -> Result<Val>;
crates/jrsonnet-interner/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-interner/src/lib.rs
+++ b/crates/jrsonnet-interner/src/lib.rs
@@ -1,6 +1,3 @@
-use gcmodule::Trace;
-use rustc_hash::FxHashMap;
-use serde::{Deserialize, Serialize};
use std::{
borrow::Cow,
cell::RefCell,
@@ -12,6 +9,10 @@
str::Utf8Error,
};
+use gcmodule::Trace;
+use rustc_hash::FxHashMap;
+use serde::{Deserialize, Serialize};
+
#[derive(Clone, PartialOrd, Ord, Eq)]
pub struct IStr(Rc<str>);
impl Trace for IStr {
crates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/expr.rs
+++ b/crates/jrsonnet-parser/src/expr.rs
@@ -1,7 +1,3 @@
-use gcmodule::Trace;
-use jrsonnet_interner::IStr;
-#[cfg(feature = "serde")]
-use serde::{Deserialize, Serialize};
use std::{
fmt::{Debug, Display},
ops::Deref,
@@ -9,6 +5,11 @@
rc::Rc,
};
+use gcmodule::Trace;
+use jrsonnet_interner::IStr;
+#[cfg(feature = "serde")]
+use serde::{Deserialize, Serialize};
+
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, PartialEq, Trace)]
pub enum FieldName {
crates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/lib.rs
+++ b/crates/jrsonnet-parser/src/lib.rs
@@ -1,10 +1,11 @@
#![allow(clippy::redundant_closure_call)]
-use peg::parser;
use std::{
path::{Path, PathBuf},
rc::Rc,
};
+
+use peg::parser;
mod expr;
pub use expr::*;
pub use jrsonnet_interner::IStr;
@@ -317,11 +318,13 @@
#[cfg(test)]
pub mod tests {
- use super::{expr::*, parse};
- use crate::ParserSettings;
use std::path::PathBuf;
+
use BinaryOpType::*;
+ use super::{expr::*, parse};
+ use crate::ParserSettings;
+
macro_rules! parse {
($s:expr) => {
parse(
crates/jrsonnet-types/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-types/src/lib.rs
+++ b/crates/jrsonnet-types/src/lib.rs
@@ -1,8 +1,9 @@
#![allow(clippy::redundant_closure_call)]
-use gcmodule::Trace;
use std::fmt::Display;
+use gcmodule::Trace;
+
#[macro_export]
macro_rules! ty {
((Array<number>)) => {{