184 lines
6.6 KiB
Rust
184 lines
6.6 KiB
Rust
//! `formatJson` of `packages/anatomy/src/format.ts`: Prettier 3 (parser `json`, print width
|
|
//! 80, two-space indent) over `JSON.stringify(value, null, 2)`, reproduced for the values the
|
|
//! pipeline writes. Pinned by `oracles/r5/prettier-json.json` and by every generated JSON
|
|
//! file of the seed.
|
|
//!
|
|
//! The rules, as Prettier applies them to that input:
|
|
//! - a non-empty object is always expanded (JSON.stringify put a newline after its brace),
|
|
//! and an expanded object breaks every array that holds it;
|
|
//! - an array breaks when it holds more than one element and every element is an array of
|
|
//! more than one element, when an element breaks, or when it does not fit flat on the line
|
|
//! (the trailing comma of its parent counted);
|
|
//! - a broken array of more than one number fills its lines; any other broken array puts one
|
|
//! element per line;
|
|
//! - strings print as JSON.stringify writes them, numbers as `String(number)`.
|
|
|
|
use serde_json::{Map, Value};
|
|
|
|
use super::PipelineError;
|
|
use super::text::display_width;
|
|
use crate::json::js_number;
|
|
|
|
const PRINT_WIDTH: usize = 80;
|
|
|
|
/// The file text: the formatted value and a final newline.
|
|
pub fn format_json(value: &Value) -> Result<String, PipelineError> {
|
|
let printer = Printer {
|
|
level: 0,
|
|
column: 0,
|
|
trailing: 0,
|
|
};
|
|
Ok(format!("{}\n", printer.value(value)?))
|
|
}
|
|
|
|
/// Where a value starts: its indentation level, its column, and how many characters follow
|
|
/// it on the same line (a comma, or nothing).
|
|
#[derive(Clone, Copy)]
|
|
struct Printer {
|
|
level: usize,
|
|
column: usize,
|
|
trailing: usize,
|
|
}
|
|
|
|
impl Printer {
|
|
fn value(self, value: &Value) -> Result<String, PipelineError> {
|
|
match value {
|
|
Value::Object(map) if !map.is_empty() => self.object(map),
|
|
Value::Array(items) if !items.is_empty() => self.array(items),
|
|
_ => scalar(value),
|
|
}
|
|
}
|
|
|
|
fn object(self, map: &Map<String, Value>) -> Result<String, PipelineError> {
|
|
let inner = indent(self.level + 1);
|
|
let mut lines = Vec::with_capacity(map.len());
|
|
for (index, (key, value)) in map.iter().enumerate() {
|
|
let key = string(key);
|
|
let child = Printer {
|
|
level: self.level + 1,
|
|
column: inner.len() + display_width(&key)? + 2,
|
|
trailing: usize::from(index + 1 < map.len()),
|
|
};
|
|
lines.push(format!("{inner}{key}: {}", child.value(value)?));
|
|
}
|
|
Ok(format!(
|
|
"{{\n{}\n{}}}",
|
|
lines.join(",\n"),
|
|
indent(self.level)
|
|
))
|
|
}
|
|
|
|
fn array(self, items: &[Value]) -> Result<String, PipelineError> {
|
|
if !must_break(items) {
|
|
let flat = flat(&Value::Array(items.to_vec()))?;
|
|
if self.column + display_width(&flat)? + self.trailing <= PRINT_WIDTH {
|
|
return Ok(flat);
|
|
}
|
|
}
|
|
let body = if is_concise(items) {
|
|
self.fill(items)?
|
|
} else {
|
|
self.one_per_line(items)?
|
|
};
|
|
Ok(format!("[\n{body}\n{}]", indent(self.level)))
|
|
}
|
|
|
|
/// Prettier's `fill`: an element joins the line when it and its separator still fit.
|
|
fn fill(self, items: &[Value]) -> Result<String, PipelineError> {
|
|
let inner = indent(self.level + 1);
|
|
let mut out = inner.clone();
|
|
let mut column = inner.len();
|
|
for (index, item) in items.iter().enumerate() {
|
|
let comma = if index + 1 < items.len() { "," } else { "" };
|
|
let text = format!("{}{comma}", scalar(item)?);
|
|
let width = display_width(&text)?;
|
|
if index > 0 && column + 1 + width <= PRINT_WIDTH {
|
|
out.push(' ');
|
|
column += 1;
|
|
} else if index > 0 {
|
|
out.push('\n');
|
|
out.push_str(&inner);
|
|
column = inner.len();
|
|
}
|
|
out.push_str(&text);
|
|
column += width;
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
fn one_per_line(self, items: &[Value]) -> Result<String, PipelineError> {
|
|
let inner = indent(self.level + 1);
|
|
let mut lines = Vec::with_capacity(items.len());
|
|
for (index, item) in items.iter().enumerate() {
|
|
let child = Printer {
|
|
level: self.level + 1,
|
|
column: inner.len(),
|
|
trailing: usize::from(index + 1 < items.len()),
|
|
};
|
|
lines.push(format!("{inner}{}", child.value(item)?));
|
|
}
|
|
Ok(lines.join(",\n"))
|
|
}
|
|
}
|
|
|
|
/// A group that breaks whatever the width: an expanded object inside, or Prettier's rule for
|
|
/// an array of several arrays of several elements; a breaking element breaks its parent.
|
|
fn must_break(items: &[Value]) -> bool {
|
|
let all_long_arrays = items.len() > 1
|
|
&& items
|
|
.iter()
|
|
.all(|item| matches!(item, Value::Array(inner) if inner.len() > 1));
|
|
all_long_arrays || items.iter().any(breaks)
|
|
}
|
|
|
|
fn breaks(value: &Value) -> bool {
|
|
match value {
|
|
Value::Object(map) => !map.is_empty(),
|
|
Value::Array(items) => must_break(items),
|
|
_ => false,
|
|
}
|
|
}
|
|
|
|
/// Prettier's `isConciselyPrintedArray`: more than one element, all numbers.
|
|
fn is_concise(items: &[Value]) -> bool {
|
|
items.len() > 1 && items.iter().all(Value::is_number)
|
|
}
|
|
|
|
/// The flat form of a value that does not break (arrays of scalars and arrays, `{}`).
|
|
fn flat(value: &Value) -> Result<String, PipelineError> {
|
|
match value {
|
|
Value::Array(items) if !items.is_empty() => {
|
|
let parts: Result<Vec<String>, PipelineError> = items.iter().map(flat).collect();
|
|
Ok(format!("[{}]", parts?.join(", ")))
|
|
}
|
|
_ => scalar(value),
|
|
}
|
|
}
|
|
|
|
fn scalar(value: &Value) -> Result<String, PipelineError> {
|
|
Ok(match value {
|
|
Value::Null => "null".to_owned(),
|
|
Value::Bool(flag) => flag.to_string(),
|
|
Value::Number(number) => prettier_number(number.as_f64().unwrap_or(f64::NAN)),
|
|
Value::String(text) => string(text),
|
|
Value::Array(_) => "[]".to_owned(),
|
|
Value::Object(_) => "{}".to_owned(),
|
|
})
|
|
}
|
|
|
|
/// JSON.parse reads every number as a double, JSON.stringify prints it as `String(number)`,
|
|
/// then Prettier's `printNumber` drops the `+` of an exponent (`1e+21` → `1e21`); its other
|
|
/// rewrites (case, zeros, dots) never apply to a JavaScript-printed number.
|
|
fn prettier_number(value: f64) -> String {
|
|
js_number(value).replacen("e+", "e", 1)
|
|
}
|
|
|
|
/// `JSON.stringify` of a string (serde_json escapes the same set).
|
|
fn string(text: &str) -> String {
|
|
serde_json::to_string(text).unwrap_or_default()
|
|
}
|
|
|
|
fn indent(level: usize) -> String {
|
|
" ".repeat(level)
|
|
}
|