mirror of
https://github.com/nushell/nushell.git
synced 2026-12-03 18:46:44 +08:00
Speed up JSON, CSV, YAML and TOML conversion on big inputs (#19666)
## Description This is the first easy stab at making formats a bit faster. There's still lots of room for better perf. Most of the time spent loading and saving big files went into copying and converting data around the parsers, not into parsing. This PR removes that work: - `from json` parsed into a JSON value tree, with a hash map for every object, and then converted the tree into nushell values. Before that it copied the whole input once more. It now builds nushell values straight from the parser, in both default and `--strict` mode. `to json` no longer copies the value into a JSON tree before writing it. - `to csv` and `to tsv` built a new CSV writer with an 8 KiB buffer for every row and handed out one row per chunk, so `save` made one `write` call per row. For a table that is already in memory, they now fill the writer's buffer before handing out a chunk. String cells are borrowed instead of copied. - `from yaml` ran the int, float and timestamp regexes on every plain scalar. Each of those patterns starts with a sign, a digit or a dot, so scalars that start with anything else now skip them. Plain decimal ints are read without the capture regex. A mapping without `<<` is no longer merged into an empty record one key at a time. `to yaml` no longer formats a tag string for values that have no tag. - `from toml` moves strings and keys out of the parsed TOML instead of cloning them. Apart from the fixes below, the output is the same as on main. I compared 293 cases against main, covering Hjson, duplicate keys, number edge cases, BOMs, error messages, CSV errors after several chunks, YAML 1.1 and 1 ### Before and after The table has 500k rows and 10 columns of ints, floats, bools, strings and nulls, which is 139 MB as JSON. Times are from an idle M-series Mac. "Before" is main. Write times include loading the table from msgpack, which takes about 0.55 s and 848 MB on both. | command | before | after | |---|---|---| | `open fixture.json` | 1.50 s, 1456 MB | 1.19 s, 979 MB | | `save fixture.json` | 1.81 s, 1760 MB | 1.00 s, 981 MB | | `save fixture.csv` | 2.13 s | 1.05 s | | `save fixture.tsv` | 2.13 s | 1.05 s | | `open fixture.yaml` | 4.80 s | 3.27 s | | `save fixture.yaml` | 1.50 s | 1.41 s | | `open fixture.toml` | 2.20 s, 2902 MB | 2.07 s, 2799 MB | ## User-facing changes (Release notes) - `from json` and `open` on `.json` files are faster and use a third less memory on large inputs. - `to json` and `save` to `.json` are about twice as fast on large tables and use less memory. - `to csv`, `to tsv` and `save` to `.csv` or `.tsv` are about twice as fast on large tables. - `from yaml` is about a third faster. `to yaml` and `from toml` are a little faster. - `from json` reports an error for a `/*` comment with no closing `*/`, which used to crash nu. - `from json` without `--strict` reports an error for lists and objects nested more than 1024 deep, where deeper input used to crash nu with a stack overflow. Input nested 1025 to about 11,000 levels deep parsed in a release build before and now gets the error. - `from yaml` reads -9223372036854775808, the smallest int. ## Additional notes <!-- Optional. Examples: - fixes #123 - closes #456 - related #789 Anything else reviewers should know. Remove this section if not needed. -->
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
use std::io::{BufRead, Cursor};
|
||||
|
||||
use serde::de::DeserializeSeed;
|
||||
|
||||
use nu_engine::command_prelude::*;
|
||||
use nu_protocol::{
|
||||
DEFAULT_ERROR_CONTEXT, ListStream, Signals,
|
||||
@@ -171,18 +173,30 @@ pub fn try_str_to_value(
|
||||
// Windows editors and PowerShell's `Out-File` write a UTF-8 BOM, which RFC 8259 lets a
|
||||
// parser ignore. Strip exactly one leading one: `U+FEFF` anywhere else is content.
|
||||
let input = input.strip_prefix('\u{feff}').unwrap_or(input);
|
||||
// Both parsers build nushell values directly, with no JSON value tree in between.
|
||||
let seed = nu_json::NuValueSeed { span };
|
||||
match strict {
|
||||
true => try_str_to_value_impl(
|
||||
input,
|
||||
span,
|
||||
signals,
|
||||
|s| serde_json::from_str(s),
|
||||
|s| {
|
||||
let mut de = serde_json::Deserializer::from_str(s);
|
||||
let value = seed.deserialize(&mut de)?;
|
||||
de.end().map(|()| value)
|
||||
},
|
||||
|err| err.is_syntax().then_some((err.line(), err.column())),
|
||||
),
|
||||
false => try_str_to_value_impl(input, span, signals, nu_json::from_str, |err| match err {
|
||||
nu_json::Error::Syntax(_, row, col) => Some((*row, *col)),
|
||||
_ => None,
|
||||
}),
|
||||
false => try_str_to_value_impl(
|
||||
input,
|
||||
span,
|
||||
signals,
|
||||
|s| nu_json::from_slice_seed(s.as_bytes(), seed),
|
||||
|err| match err {
|
||||
nu_json::Error::Syntax(_, row, col) => Some((*row, *col)),
|
||||
_ => None,
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,11 +205,11 @@ fn try_str_to_value_impl<E: std::error::Error>(
|
||||
input: &str,
|
||||
span: Span,
|
||||
signals: &Signals,
|
||||
parser: impl Fn(&str) -> Result<nu_json::Value, E>,
|
||||
parser: impl Fn(&str) -> Result<Value, E>,
|
||||
on_syntax_err: impl Fn(&E) -> Option<(usize, usize)>,
|
||||
) -> Result<Value, ShellError> {
|
||||
match parser(input) {
|
||||
Ok(value) => Ok(value.into_value(span)),
|
||||
Ok(value) => Ok(value),
|
||||
Err(err) => match on_syntax_err(&err) {
|
||||
Some((row, col)) => {
|
||||
let label = err.to_string();
|
||||
|
||||
@@ -106,27 +106,27 @@ pub(crate) fn convert_toml_datetime_to_value(dt: &Datetime, span: Span) -> Value
|
||||
}
|
||||
}
|
||||
|
||||
fn convert_toml_to_value(value: &toml::Value, span: Span) -> Value {
|
||||
/// Converts a parsed TOML value, moving its strings and keys instead of copying them.
|
||||
fn convert_toml_to_value(value: toml::Value, span: Span) -> Value {
|
||||
match value {
|
||||
toml::Value::Array(array) => {
|
||||
let v: Vec<Value> = array
|
||||
.iter()
|
||||
toml::Value::Array(array) => Value::list(
|
||||
array
|
||||
.into_iter()
|
||||
.map(|x| convert_toml_to_value(x, span))
|
||||
.collect();
|
||||
|
||||
Value::list(v, span)
|
||||
}
|
||||
toml::Value::Boolean(b) => Value::bool(*b, span),
|
||||
toml::Value::Float(f) => Value::float(*f, span),
|
||||
toml::Value::Integer(i) => Value::int(*i, span),
|
||||
toml::Value::Table(k) => Value::record(
|
||||
k.iter()
|
||||
.map(|(k, v)| (k.clone(), convert_toml_to_value(v, span)))
|
||||
.collect(),
|
||||
span,
|
||||
),
|
||||
toml::Value::String(s) => Value::string(s.clone(), span),
|
||||
toml::Value::Datetime(dt) => convert_toml_datetime_to_value(dt, span),
|
||||
toml::Value::Boolean(b) => Value::bool(b, span),
|
||||
toml::Value::Float(f) => Value::float(f, span),
|
||||
toml::Value::Integer(i) => Value::int(i, span),
|
||||
toml::Value::Table(k) => Value::record(
|
||||
k.into_iter()
|
||||
.map(|(k, v)| (k, convert_toml_to_value(v, span)))
|
||||
.collect(),
|
||||
span,
|
||||
),
|
||||
toml::Value::String(s) => Value::string(s, span),
|
||||
toml::Value::Datetime(dt) => convert_toml_datetime_to_value(&dt, span),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,7 +136,7 @@ pub(crate) fn convert_string_to_value(
|
||||
) -> Result<Value, ShellError> {
|
||||
let result: Result<toml::Value, toml::de::Error> = toml::from_str(&string_input);
|
||||
match result {
|
||||
Ok(value) => Ok(convert_toml_to_value(&value, span)),
|
||||
Ok(value) => Ok(convert_toml_to_value(value, span)),
|
||||
|
||||
Err(err) => Err(ShellError::CantConvert {
|
||||
to_type: "structured toml data".into(),
|
||||
@@ -184,7 +184,7 @@ mod tests {
|
||||
Span::test_data(),
|
||||
);
|
||||
|
||||
let result = convert_toml_to_value(&toml_date, span);
|
||||
let result = convert_toml_to_value(toml_date, span);
|
||||
|
||||
//positive test (from toml returns a nushell date)
|
||||
assert_eq!(result, reference_date);
|
||||
|
||||
@@ -18,14 +18,15 @@ fn make_csv_error(error: csv::Error, format_name: &str, head: Span) -> ShellErro
|
||||
}
|
||||
}
|
||||
|
||||
fn to_string_tagged_value(
|
||||
v: &Value,
|
||||
/// The text of one cell. Strings are borrowed, so most cells cost no allocation.
|
||||
fn to_string_tagged_value<'a>(
|
||||
v: &'a Value,
|
||||
config: &Config,
|
||||
format_name: &'static str,
|
||||
) -> Result<String, ShellError> {
|
||||
) -> Result<Cow<'a, str>, ShellError> {
|
||||
match &v {
|
||||
Value::String { .. }
|
||||
| Value::Bool { .. }
|
||||
Value::String { val, .. } => Ok(Cow::Borrowed(val)),
|
||||
Value::Bool { .. }
|
||||
| Value::Int { .. }
|
||||
| Value::Duration { .. }
|
||||
| Value::Binary { .. }
|
||||
@@ -33,8 +34,8 @@ fn to_string_tagged_value(
|
||||
| Value::Filesize { .. }
|
||||
| Value::CellPath { .. }
|
||||
| Value::Float { .. }
|
||||
| Value::Date { .. } => Ok(v.to_expanded_string(", ", config)),
|
||||
Value::Nothing { .. } => Ok(String::new()),
|
||||
| Value::Date { .. } => Ok(Cow::Owned(v.to_expanded_string(", ", config))),
|
||||
Value::Nothing { .. } => Ok(Cow::Borrowed("")),
|
||||
// Propagate existing errors
|
||||
Value::Error { error, .. } => Err(*error.clone()),
|
||||
_ => Err(make_cant_convert_error(v, format_name)),
|
||||
@@ -172,7 +173,10 @@ fn current_stream_columns<'a>(
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper function to write a single row to CSV
|
||||
/// Helper function to write a single row to CSV.
|
||||
///
|
||||
/// Every cell is converted before the first one is written, so a cell that can't be converted
|
||||
/// leaves no partial row behind in the writer's buffer.
|
||||
fn write_csv_row(
|
||||
wtr: &mut csv::Writer<&mut Vec<u8>>,
|
||||
record: &nu_protocol::Record,
|
||||
@@ -182,12 +186,15 @@ fn write_csv_row(
|
||||
head: Span,
|
||||
escape: Option<u8>,
|
||||
) -> Result<(), ShellError> {
|
||||
for column in columns {
|
||||
let field = record
|
||||
.get(column)
|
||||
.map(|v| to_string_tagged_value(v, config, format_name))
|
||||
.unwrap_or(Ok(String::new()))?;
|
||||
wtr.write_field(escape_delimited_field(&field, escape).as_bytes())
|
||||
let fields = columns
|
||||
.iter()
|
||||
.map(|column| match record.get(column) {
|
||||
Some(v) => to_string_tagged_value(v, config, format_name),
|
||||
None => Ok(Cow::Borrowed("")),
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
for field in &fields {
|
||||
wtr.write_field(escape_delimited_field(field, escape).as_bytes())
|
||||
.map_err(|err| make_csv_error(err, format_name, head))?;
|
||||
}
|
||||
wtr.write_record(iter::empty::<String>())
|
||||
@@ -298,12 +305,17 @@ pub fn to_delimited_data(
|
||||
};
|
||||
let mut iter = input.into_iter();
|
||||
let mut header_written = noheaders; // If noheaders is true, consider it already written
|
||||
// A row that fails after other rows of its chunk were written, reported on the next call.
|
||||
let mut pending_error = None;
|
||||
|
||||
let stream = ByteStream::from_fn(
|
||||
head,
|
||||
Signals::empty(),
|
||||
ByteStreamType::String,
|
||||
move |buffer| {
|
||||
if let Some(err) = pending_error.take() {
|
||||
return Err(err);
|
||||
}
|
||||
let mut wtr = builder.from_writer(buffer);
|
||||
|
||||
// Write header once if not already written
|
||||
@@ -312,24 +324,39 @@ pub fn to_delimited_data(
|
||||
header_written = true;
|
||||
}
|
||||
|
||||
if let Some(row) = iter.next() {
|
||||
if let Value::Error { error, .. } = &row {
|
||||
return Err(*error.clone());
|
||||
// The rows are already in memory, so keep writing until the csv writer's own
|
||||
// buffer spills into `buffer`. A chunk per row would cost a write (a syscall in
|
||||
// `save`) per row.
|
||||
let mut wrote_row = false;
|
||||
for row in iter.by_ref() {
|
||||
let written = match row {
|
||||
Value::Error { error, .. } => Err(*error),
|
||||
row => row.into_record().and_then(|record| {
|
||||
write_csv_row(
|
||||
&mut wtr,
|
||||
&record,
|
||||
&columns,
|
||||
&config,
|
||||
format_name,
|
||||
head,
|
||||
escape,
|
||||
)
|
||||
}),
|
||||
};
|
||||
match written {
|
||||
Ok(()) => wrote_row = true,
|
||||
// Hand out the rows before it first, as when each row was its own chunk.
|
||||
Err(err) if wrote_row => {
|
||||
pending_error = Some(err);
|
||||
break;
|
||||
}
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
if !wtr.get_ref().is_empty() {
|
||||
break;
|
||||
}
|
||||
let record = row.into_record()?;
|
||||
write_csv_row(
|
||||
&mut wtr,
|
||||
&record,
|
||||
&columns,
|
||||
&config,
|
||||
format_name,
|
||||
head,
|
||||
escape,
|
||||
)?;
|
||||
Ok(true)
|
||||
} else {
|
||||
Ok(false)
|
||||
}
|
||||
Ok(wrote_row)
|
||||
},
|
||||
);
|
||||
return Ok(PipelineData::byte_stream(stream, metadata));
|
||||
@@ -432,3 +459,65 @@ pub fn to_delimited_data(
|
||||
|
||||
Ok(PipelineData::byte_stream(stream, metadata))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use nu_protocol::{Record, shell_error::bridge::ShellErrorBridge};
|
||||
use std::io::Read;
|
||||
|
||||
fn to_csv(rows: Vec<Value>) -> nu_protocol::ByteStream {
|
||||
let span = Span::test_data();
|
||||
let args = ToDelimitedDataArgs {
|
||||
noheaders: false,
|
||||
separator: Spanned { item: ',', span },
|
||||
quote: Spanned { item: '"', span },
|
||||
escape: None,
|
||||
columns: None,
|
||||
format_name: "CSV",
|
||||
input: PipelineData::value(Value::test_list(rows), None),
|
||||
head: span,
|
||||
content_type: None,
|
||||
};
|
||||
match to_delimited_data(args, Arc::new(Config::default())) {
|
||||
Ok(PipelineData::ByteStream(stream, ..)) => stream,
|
||||
_ => panic!("to csv makes a byte stream"),
|
||||
}
|
||||
}
|
||||
|
||||
fn row(i: i64) -> Value {
|
||||
let mut record = Record::new();
|
||||
record.push("a", Value::test_int(i));
|
||||
record.push("b", Value::test_string("some text to fill the chunks"));
|
||||
Value::test_record(record)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_before_a_bad_row_are_still_written() {
|
||||
// Enough rows for several chunks, so the bad row lands in a later one.
|
||||
let good: Vec<Value> = (0..2000).map(row).collect();
|
||||
let mut bad = Record::new();
|
||||
bad.push("a", Value::test_list(vec![Value::test_int(1)]));
|
||||
let mut rows = good.clone();
|
||||
rows.push(Value::test_record(bad));
|
||||
|
||||
let mut expected = String::new();
|
||||
to_csv(good)
|
||||
.reader()
|
||||
.expect("has a reader")
|
||||
.read_to_string(&mut expected)
|
||||
.expect("good rows write");
|
||||
|
||||
let mut written = Vec::new();
|
||||
let err = to_csv(rows)
|
||||
.reader()
|
||||
.expect("has a reader")
|
||||
.read_to_end(&mut written)
|
||||
.expect_err("the bad row fails");
|
||||
assert_eq!(String::from_utf8_lossy(&written), expected);
|
||||
assert!(matches!(
|
||||
ShellErrorBridge::try_from(err),
|
||||
Ok(ShellErrorBridge(ShellError::CantConvert { .. }))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,18 +57,20 @@ impl Command for ToJson {
|
||||
// allow ranges to expand and turn into array
|
||||
let input = input.try_expand_range()?;
|
||||
let value = input.into_value(span)?;
|
||||
let ty = value.get_type();
|
||||
let json_value = value_to_json_value(engine_state, value, span, serialize_types)?;
|
||||
|
||||
let json_result = if raw {
|
||||
nu_json::to_string_raw(&json_value)
|
||||
} else if let Some(tab_count) = use_tabs {
|
||||
nu_json::to_string_with_tab_indentation(&json_value, tab_count)
|
||||
} else if let Some(indent) = indent {
|
||||
nu_json::to_string_with_indent(&json_value, indent)
|
||||
} else {
|
||||
nu_json::to_string(&json_value)
|
||||
};
|
||||
// Serialize straight from the nushell value, without a JSON value tree in between.
|
||||
let json_result =
|
||||
nu_json::write_nu_value(&value, serialize_types.then_some(engine_state), |json| {
|
||||
if raw {
|
||||
nu_json::to_string_raw(json)
|
||||
} else if let Some(tab_count) = use_tabs {
|
||||
nu_json::to_string_with_tab_indentation(json, tab_count)
|
||||
} else if let Some(indent) = indent {
|
||||
nu_json::to_string_with_indent(json, indent)
|
||||
} else {
|
||||
nu_json::to_string(json)
|
||||
}
|
||||
})
|
||||
.map_err(|err| closure_error(err, span, value.span()))?;
|
||||
|
||||
match json_result {
|
||||
Ok(serde_json_string) => {
|
||||
@@ -82,7 +84,7 @@ impl Command for ToJson {
|
||||
}
|
||||
_ => Err(ShellError::CantConvert {
|
||||
to_type: "JSON".into(),
|
||||
from_type: ty.to_string(),
|
||||
from_type: value.get_type().to_string(),
|
||||
span,
|
||||
help: None,
|
||||
}),
|
||||
@@ -121,16 +123,24 @@ pub fn value_to_json_value(
|
||||
let value_span = v.span();
|
||||
match serialize_types {
|
||||
false => nu_json::Value::from_value(v),
|
||||
true => nu_json::Value::from_value_serialized(v, engine_state)
|
||||
}.map_err(|err| match err {
|
||||
ShellError::CantConvert { from_type, .. } if from_type == "closure" => ShellError::UnsupportedInput {
|
||||
msg: "closures are currently not deserializable (use --serialize to serialize as a string)".into(),
|
||||
input: "value originates from here".into(),
|
||||
msg_span: call_span,
|
||||
input_span: value_span,
|
||||
},
|
||||
err => err
|
||||
})
|
||||
true => nu_json::Value::from_value_serialized(v, engine_state),
|
||||
}
|
||||
.map_err(|err| closure_error(err, call_span, value_span))
|
||||
}
|
||||
|
||||
/// Explains the error for a closure met without `--serialize`; other errors pass through.
|
||||
fn closure_error(err: ShellError, call_span: Span, value_span: Span) -> ShellError {
|
||||
match err {
|
||||
ShellError::CantConvert { from_type, .. } if from_type == "closure" => {
|
||||
ShellError::UnsupportedInput {
|
||||
msg: "closures are currently not deserializable (use --serialize to serialize as a string)".into(),
|
||||
input: "value originates from here".into(),
|
||||
msg_span: call_span,
|
||||
input_span: value_span,
|
||||
}
|
||||
}
|
||||
err => err,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -726,7 +726,12 @@ fn parse_mapping<'i>(
|
||||
}
|
||||
Event::MappingEnd => {
|
||||
let record = Record::from_iter(values);
|
||||
break 'record merge.merge(record, merge_strategy, ctx.parser_span)?;
|
||||
// Without `<<` there is nothing to merge into, and the keys are already
|
||||
// unique, so merging into the empty record would only copy it key by key.
|
||||
break 'record match merge.is_empty() {
|
||||
true => record,
|
||||
false => merge.merge(record, merge_strategy, ctx.parser_span)?,
|
||||
};
|
||||
}
|
||||
Event::MappingStart(..) => {
|
||||
return Err(ShellError::from(ParseError::UnsupportedKey {
|
||||
@@ -923,16 +928,14 @@ macro_rules! parse_int {
|
||||
input: &str,
|
||||
caps: ::regex::Captures<'_>
|
||||
) -> Result<i64, crate::yaml::error::ParseError<'i>> {
|
||||
let sign = match caps.name("sign").map(|m| m.as_str()) {
|
||||
Some("+" | "") | None => 1,
|
||||
Some("-") => -1,
|
||||
_ => unreachable!(r#"regex only matches "+", "-" or "" here"#)
|
||||
};
|
||||
let negative = caps.name("sign").is_some_and(|m| m.as_str() == "-");
|
||||
|
||||
// Parse the sign with the digits: the digits of `i64::MIN` alone overflow `i64`.
|
||||
let digits = &caps["digits"];
|
||||
let digits = match digits.contains("_") {
|
||||
false => ::std::borrow::Cow::Borrowed(digits),
|
||||
true => ::std::borrow::Cow::Owned(digits.replace("_", ""))
|
||||
let digits = match (negative, digits.contains("_")) {
|
||||
(false, false) => ::std::borrow::Cow::Borrowed(digits),
|
||||
(false, true) => ::std::borrow::Cow::Owned(digits.replace("_", "")),
|
||||
(true, _) => ::std::borrow::Cow::Owned(format!("-{}", digits.replace("_", ""))),
|
||||
};
|
||||
|
||||
i64::from_str_radix(&digits, $base)
|
||||
@@ -941,7 +944,6 @@ macro_rules! parse_int {
|
||||
base_and_err: Some(($base, err)),
|
||||
span: ctx.yaml_span,
|
||||
})
|
||||
.map(|num| num * sign)
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -958,6 +960,16 @@ mod v1_x {
|
||||
pub static NAN: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"^\.(nan|NaN|NAN)$").expect("valid NaN regex for spec v1.x"));
|
||||
|
||||
/// Whether `input` could be an int, float or timestamp. Every pattern for those in both specs
|
||||
/// is anchored at the start and begins with a sign, a digit or a dot, so a scalar starting
|
||||
/// with anything else (most strings and keys) skips the regexes.
|
||||
pub fn may_be_number(input: &str) -> bool {
|
||||
matches!(
|
||||
input.as_bytes().first(),
|
||||
Some(b'0'..=b'9' | b'+' | b'-' | b'.')
|
||||
)
|
||||
}
|
||||
|
||||
pub fn maybe_parse_null<'i>(_: &mut ParseCtx<'i>, input: &str) -> Option<()> {
|
||||
match input {
|
||||
"null" | "Null" | "NULL" | "~" | "" => Some(()),
|
||||
@@ -1092,6 +1104,9 @@ mod v1_x {
|
||||
ctx: &mut ParseCtx<'i>,
|
||||
input: &str,
|
||||
) -> Result<Option<DateTime>, ParseError<'i>> {
|
||||
if !may_be_number(input) {
|
||||
return Ok(None);
|
||||
}
|
||||
if let Some(caps) = TIMESTAMP.captures(input) {
|
||||
return parse_timestamp(ctx, input, caps).map(Some);
|
||||
}
|
||||
@@ -1099,6 +1114,93 @@ mod v1_x {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Inputs around the edges of the number patterns, for the tests of the shortcuts that skip
|
||||
/// them ([`may_be_number`] and `v1_2::plain_decimal`).
|
||||
#[cfg(test)]
|
||||
pub const NUMBER_EDGES: &[&str] = &[
|
||||
"",
|
||||
" 1",
|
||||
"\t1",
|
||||
"1 ",
|
||||
"a1",
|
||||
"_1",
|
||||
"~1",
|
||||
"(1)",
|
||||
"e5",
|
||||
"E5",
|
||||
"x1",
|
||||
"inf",
|
||||
"nan",
|
||||
"Inf",
|
||||
"0",
|
||||
"00",
|
||||
"007",
|
||||
"-0",
|
||||
"+0",
|
||||
"-",
|
||||
"+",
|
||||
".",
|
||||
"..",
|
||||
"-.",
|
||||
"+.",
|
||||
"1.",
|
||||
".5",
|
||||
"-.5",
|
||||
"1e5",
|
||||
"1e+5",
|
||||
"1.0e-5",
|
||||
"1_000",
|
||||
"+1_0",
|
||||
"1_0.5",
|
||||
"0b101",
|
||||
"-0b11",
|
||||
"0o17",
|
||||
"-0o17",
|
||||
"017",
|
||||
"0x1F",
|
||||
"-0x1f",
|
||||
"0x",
|
||||
"0o",
|
||||
"0b",
|
||||
".inf",
|
||||
"-.Inf",
|
||||
"+.INF",
|
||||
".nan",
|
||||
".NaN",
|
||||
"+.nan",
|
||||
"1:2",
|
||||
"190:20:30",
|
||||
"-1:30",
|
||||
"190:20:30.15",
|
||||
"2002-12-14",
|
||||
"2001-12-14t21:59:43.10-05:00",
|
||||
"9223372036854775807",
|
||||
"9223372036854775808",
|
||||
"-9223372036854775808",
|
||||
"1 2",
|
||||
"12abc",
|
||||
"\u{661}\u{662}",
|
||||
"\u{2212}12",
|
||||
"\u{ff11}\u{ff12}",
|
||||
"12\n",
|
||||
"--5",
|
||||
"+-5",
|
||||
"-+5",
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn may_be_number_only_skips_what_no_pattern_matches() {
|
||||
let patterns: [&Regex; 3] = [&INFINITY, &NAN, &TIMESTAMP];
|
||||
for input in NUMBER_EDGES {
|
||||
if !may_be_number(input) {
|
||||
for re in patterns {
|
||||
assert!(!re.is_match(input), "{re} matches {input:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[rstest::rstest]
|
||||
#[case::infinity(&INFINITY)]
|
||||
@@ -1155,6 +1257,9 @@ mod v1_1 {
|
||||
ctx: &mut ParseCtx<'i>,
|
||||
input: &str,
|
||||
) -> Result<Option<i64>, ParseError<'i>> {
|
||||
if !v1_x::may_be_number(input) {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(match input {
|
||||
s if let Some(caps) = INT_BASE2.captures(s) => parse_int_base2(ctx, s, caps)?,
|
||||
s if let Some(caps) = INT_BASE8.captures(s) => parse_int_base8(ctx, input, caps)?,
|
||||
@@ -1220,6 +1325,9 @@ mod v1_1 {
|
||||
ctx: &mut ParseCtx<'i>,
|
||||
input: &str,
|
||||
) -> Result<Option<f64>, ParseError<'i>> {
|
||||
if !v1_x::may_be_number(input) {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(match input {
|
||||
s if FLOAT_BASE10.is_match(s) => parse_float_base10(ctx, s)?,
|
||||
s if let Some(caps) = FLOAT_BASE60.captures(s) => parse_float_base60(ctx, input, caps)?,
|
||||
@@ -1256,6 +1364,27 @@ mod v1_1 {
|
||||
fn regex_valid(#[case] re: &LazyLock<Regex>) {
|
||||
LazyLock::force(re);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn may_be_number_only_skips_what_no_pattern_matches() {
|
||||
let patterns: [&Regex; 7] = [
|
||||
&INT_BASE2,
|
||||
&INT_BASE8,
|
||||
&INT_BASE10,
|
||||
&INT_BASE16,
|
||||
&INT_BASE60,
|
||||
&FLOAT_BASE10,
|
||||
&FLOAT_BASE60,
|
||||
];
|
||||
for input in v1_x::NUMBER_EDGES {
|
||||
if !v1_x::may_be_number(input) {
|
||||
for re in patterns {
|
||||
assert!(!re.is_match(input), "{re} matches {input:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mod v1_2 {
|
||||
@@ -1269,6 +1398,21 @@ mod v1_2 {
|
||||
ctx: &mut ParseCtx<'i>,
|
||||
input: &str,
|
||||
) -> Result<Option<i64>, ParseError<'i>> {
|
||||
if !v1_x::may_be_number(input) {
|
||||
return Ok(None);
|
||||
}
|
||||
// Most ints are plain decimals: match `INT_BASE10` by hand and skip the capture regexes.
|
||||
// Nothing else here matches a sign and digits only, so trying it first is safe.
|
||||
if is_plain_decimal(input) {
|
||||
return input
|
||||
.parse::<i64>()
|
||||
.map(Some)
|
||||
.map_err(|err| ParseError::Int {
|
||||
attempted: input.to_owned(),
|
||||
base_and_err: Some((10, err)),
|
||||
span: ctx.yaml_span,
|
||||
});
|
||||
}
|
||||
Ok(Some(match input {
|
||||
s if let Some(caps) = INT_BASE8.captures(s) => parse_int_base8(ctx, input, caps)?,
|
||||
s if let Some(caps) = INT_BASE10.captures(s) => parse_int_base10(ctx, input, caps)?,
|
||||
@@ -1277,6 +1421,12 @@ mod v1_2 {
|
||||
}))
|
||||
}
|
||||
|
||||
/// Whether `input` matches `INT_BASE10` (`[-+]?[0-9]+`), which `str::parse::<i64>` reads as is.
|
||||
fn is_plain_decimal(input: &str) -> bool {
|
||||
let digits = input.strip_prefix(['-', '+']).unwrap_or(input);
|
||||
!digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit())
|
||||
}
|
||||
|
||||
static FLOAT: LazyLock<Regex> = LazyLock::new(|| {
|
||||
Regex::new(r"^[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?$")
|
||||
.expect("valid float regex for spec v1.2")
|
||||
@@ -1293,6 +1443,9 @@ mod v1_2 {
|
||||
ctx: &mut ParseCtx<'i>,
|
||||
input: &str,
|
||||
) -> Result<Option<f64>, ParseError<'i>> {
|
||||
if !v1_x::may_be_number(input) {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(match input {
|
||||
s if FLOAT.is_match(s) => parse_float(ctx, s)?,
|
||||
s if v1_x::INFINITY.is_match(s) => match s.starts_with("-") {
|
||||
@@ -1321,6 +1474,31 @@ mod v1_2 {
|
||||
fn regex_valid(#[case] re: &LazyLock<Regex>) {
|
||||
LazyLock::force(re);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn may_be_number_only_skips_what_no_pattern_matches() {
|
||||
let patterns: [&Regex; 4] = [&INT_BASE8, &INT_BASE10, &INT_BASE16, &FLOAT];
|
||||
for input in v1_x::NUMBER_EDGES {
|
||||
if !v1_x::may_be_number(input) {
|
||||
for re in patterns {
|
||||
assert!(!re.is_match(input), "{re} matches {input:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn is_plain_decimal_matches_int_base10() {
|
||||
for input in v1_x::NUMBER_EDGES {
|
||||
assert_eq!(
|
||||
is_plain_decimal(input),
|
||||
INT_BASE10.is_match(input),
|
||||
"{input:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -1485,6 +1663,19 @@ mod tests {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[case::yaml_1_1_decimal(Spec::V1_1, "-9223372036854775808")]
|
||||
#[case::yaml_1_1_underscores(Spec::V1_1, "-9_223_372_036_854_775_808")]
|
||||
#[case::yaml_1_1_hex(Spec::V1_1, "-0x8000000000000000")]
|
||||
#[case::yaml_1_1_binary(Spec::V1_1, &format!("-0b1{}", "0".repeat(63)))]
|
||||
#[case::yaml_1_2_decimal(Spec::V1_2, "-9223372036854775808")]
|
||||
fn parse_smallest_int(#[case] spec: Spec, #[case] input: &str) -> Result {
|
||||
let options = ParseOptions::default().with_spec(spec);
|
||||
let parsed = parse(input.into_spanned(SPAN), SPAN, options)?;
|
||||
assert_eq!(parsed, i64::MIN.into_value(SPAN));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_unknown_tags_are_rejected_by_default() {
|
||||
let yaml = "key: !Unknown value".into_spanned(SPAN);
|
||||
|
||||
@@ -365,11 +365,11 @@ impl Serialize for YamlValue<'_> {
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
let tag = self.tag().to_string();
|
||||
let tag = tag.as_str();
|
||||
// Formatted only by the tagged variants below; most values have no tag to write.
|
||||
let tag = self.tag();
|
||||
fn serialize_with_tag<S: serde::Serializer>(
|
||||
serializer: S,
|
||||
tag: &str,
|
||||
tag: KnownTag,
|
||||
value: impl Serialize,
|
||||
) -> Result<S::Ok, S::Error> {
|
||||
WRITER.with_borrow_mut(|writer| {
|
||||
@@ -383,9 +383,7 @@ impl Serialize for YamlValue<'_> {
|
||||
.expect("infallible for writes to string");
|
||||
}
|
||||
|
||||
writer
|
||||
.write_str(tag)
|
||||
.expect("infallible for writes to string");
|
||||
write!(writer, "{tag}").expect("infallible for writes to string");
|
||||
|
||||
if Container::current() != Some(Container::Map) {
|
||||
writer
|
||||
|
||||
+129
-46
@@ -19,11 +19,17 @@ enum State {
|
||||
Keyname,
|
||||
}
|
||||
|
||||
/// How deep lists and objects may nest. Each level is a few recursive calls, so deeper input
|
||||
/// gets an error here instead of overflowing the stack.
|
||||
const MAX_DEPTH: usize = 1024;
|
||||
|
||||
/// A structure that deserializes Hjson into Rust values.
|
||||
pub struct Deserializer<Iter: Iterator<Item = u8>> {
|
||||
rdr: StringReader<Iter>,
|
||||
str_buf: Vec<u8>,
|
||||
state: State,
|
||||
/// How many more lists and objects may open inside the current one.
|
||||
remaining_depth: usize,
|
||||
}
|
||||
|
||||
impl<Iter> Deserializer<Iter>
|
||||
@@ -37,6 +43,7 @@ where
|
||||
rdr: StringReader::new(rdr),
|
||||
str_buf: Vec::with_capacity(128),
|
||||
state: State::Normal,
|
||||
remaining_depth: MAX_DEPTH,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,25 +153,38 @@ where
|
||||
let s = str::from_utf8(&self.str_buf).expect("Internal error: json parsing");
|
||||
visitor.visit_str(s)
|
||||
}
|
||||
b'[' => {
|
||||
self.rdr.eat_char();
|
||||
let ret = visitor.visit_seq(SeqVisitor::new(self))?;
|
||||
self.rdr.parse_whitespace()?;
|
||||
match self.rdr.next_char()? {
|
||||
b'[' => self.nested(|de| {
|
||||
de.rdr.eat_char();
|
||||
let ret = visitor.visit_seq(SeqVisitor::new(de))?;
|
||||
de.rdr.parse_whitespace()?;
|
||||
match de.rdr.next_char()? {
|
||||
Some(b']') => Ok(ret),
|
||||
Some(_) => Err(self.rdr.error(ErrorCode::TrailingCharacters)),
|
||||
None => Err(self.rdr.error(ErrorCode::EofWhileParsingList)),
|
||||
Some(_) => Err(de.rdr.error(ErrorCode::TrailingCharacters)),
|
||||
None => Err(de.rdr.error(ErrorCode::EofWhileParsingList)),
|
||||
}
|
||||
}
|
||||
b'{' => {
|
||||
self.rdr.eat_char();
|
||||
self.visit_map(false, visitor)
|
||||
}
|
||||
}),
|
||||
b'{' => self.nested(|de| {
|
||||
de.rdr.eat_char();
|
||||
de.visit_map(false, visitor)
|
||||
}),
|
||||
b'\x00' => Err(self.rdr.error(ErrorCode::ExpectedSomeValue)),
|
||||
_ => self.parse_tfnns(visitor),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `parse` on a list or object one level deeper, or fails past [`MAX_DEPTH`].
|
||||
fn nested<T>(&mut self, parse: impl FnOnce(&mut Self) -> Result<T>) -> Result<T> {
|
||||
if self.remaining_depth == 0 {
|
||||
return Err(self.rdr.error(ErrorCode::Custom(format!(
|
||||
"Found lists and objects nested more than {MAX_DEPTH} deep"
|
||||
))));
|
||||
}
|
||||
self.remaining_depth -= 1;
|
||||
let result = parse(self);
|
||||
self.remaining_depth += 1;
|
||||
result
|
||||
}
|
||||
|
||||
fn visit_map<'de, V>(&mut self, root: bool, visitor: V) -> Result<V::Value>
|
||||
where
|
||||
V: de::Visitor<'de>,
|
||||
@@ -351,9 +371,12 @@ where
|
||||
// Parse a multiline string value.
|
||||
let mut triple = 0;
|
||||
|
||||
// we are at ''' +1 - get indent
|
||||
// `col` is the column of the third quote, so the opening ''' starts `col - 3` bytes into
|
||||
// its line. `ml_skip_indent` skips one byte more than it is asked to, hence the `- 4`.
|
||||
// When ''' starts the line there is nothing to subtract from. Release builds have always
|
||||
// wrapped to `usize::MAX` there, which strips all leading whitespace, so keep that.
|
||||
let (_, col) = self.rdr.pos();
|
||||
let indent = col - 4;
|
||||
let indent = col.checked_sub(4).unwrap_or(usize::MAX);
|
||||
|
||||
// skip white/to (newline)
|
||||
while self.ml_skip_white()? {}
|
||||
@@ -765,37 +788,8 @@ where
|
||||
I: Iterator<Item = io::Result<u8>>,
|
||||
T: de::DeserializeOwned,
|
||||
{
|
||||
let fold: io::Result<Vec<_>> = iter.collect();
|
||||
|
||||
if let Err(e) = fold {
|
||||
return Err(Error::Io(e));
|
||||
}
|
||||
|
||||
let bytes = fold.expect("Internal error: json parsing");
|
||||
|
||||
// deserialize tries first to decode with legacy support (new_for_root)
|
||||
// and then with the standard method if this fails.
|
||||
// todo: add compile switch
|
||||
|
||||
// deserialize and make sure the whole stream has been consumed
|
||||
let mut de = Deserializer::new_for_root(bytes.iter().copied());
|
||||
de::Deserialize::deserialize(&mut de)
|
||||
.and_then(|x| de.end().map(|()| x))
|
||||
.or_else(|_| {
|
||||
let mut de2 = Deserializer::new(bytes.iter().copied());
|
||||
de::Deserialize::deserialize(&mut de2).and_then(|x| de2.end().map(|()| x))
|
||||
})
|
||||
|
||||
/* without legacy support:
|
||||
// deserialize and make sure the whole stream has been consumed
|
||||
let mut de = Deserializer::new(bytes.iter().map(|b| *b));
|
||||
let value = match de::Deserialize::deserialize(&mut de)
|
||||
.and_then(|x| { try!(de.end()); Ok(x) })
|
||||
{
|
||||
Ok(v) => Ok(v),
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
*/
|
||||
let bytes = iter.collect::<io::Result<Vec<_>>>().map_err(Error::Io)?;
|
||||
from_slice(&bytes)
|
||||
}
|
||||
|
||||
/// Decodes a Hjson value from a `std::io::Read`.
|
||||
@@ -815,7 +809,27 @@ pub fn from_slice<T>(v: &[u8]) -> Result<T>
|
||||
where
|
||||
T: de::DeserializeOwned,
|
||||
{
|
||||
from_iter(v.iter().map(|&byte| Ok(byte)))
|
||||
from_slice_seed(v, PhantomData::<T>)
|
||||
}
|
||||
|
||||
/// Decodes a Hjson value from a byte slice with `seed`, which decides what the value is built
|
||||
/// into (see [`de::DeserializeSeed`]).
|
||||
///
|
||||
/// Like [`from_slice`], this first reads the input as a root object without braces (legacy Hjson)
|
||||
/// and, if that fails, as a plain value. Either way the whole input must be consumed.
|
||||
pub fn from_slice_seed<S, T>(v: &[u8], seed: S) -> Result<T>
|
||||
where
|
||||
S: for<'de> de::DeserializeSeed<'de, Value = T> + Clone,
|
||||
{
|
||||
let mut de = Deserializer::new_for_root(v.iter().copied());
|
||||
seed.clone()
|
||||
.deserialize(&mut de)
|
||||
.and_then(|x| de.end().map(|()| x))
|
||||
.or_else(|_| {
|
||||
let mut de2 = Deserializer::new(v.iter().copied());
|
||||
seed.deserialize(&mut de2)
|
||||
.and_then(|x| de2.end().map(|()| x))
|
||||
})
|
||||
}
|
||||
|
||||
/// Decodes a Hjson value from a `&str`.
|
||||
@@ -825,3 +839,72 @@ where
|
||||
{
|
||||
from_slice(s.as_bytes())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::Value;
|
||||
|
||||
#[test]
|
||||
fn unclosed_block_comment_is_an_error() {
|
||||
for input in ["[1, 2] /* x", "[1, 2] /* x *", "[1, /* x", "/*/"] {
|
||||
let err = from_str::<Value>(input).expect_err(input);
|
||||
assert!(
|
||||
err.to_string().contains("no closing */"),
|
||||
"{input:?}: {err}"
|
||||
);
|
||||
}
|
||||
let expected = from_str::<Value>("[1, 2]").expect("valid input parses");
|
||||
for input in [
|
||||
"[1, 2] /* x */",
|
||||
"[1, /**/ 2]",
|
||||
"/***/ [1, 2]",
|
||||
"[1, 2 /* * / */]",
|
||||
] {
|
||||
assert_eq!(
|
||||
from_str::<Value>(input).expect(input),
|
||||
expected,
|
||||
"{input:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiline_string_indent() {
|
||||
// The column of the opening ''' sets how much indent each line loses.
|
||||
let value: Value = from_str("[\n '''\n abc\n def\n '''\n]").expect("parses");
|
||||
assert_eq!(
|
||||
value,
|
||||
Value::Array(vec![Value::String(" abc\n def".into())])
|
||||
);
|
||||
// At the start of a line it strips all leading whitespace, as release builds always did.
|
||||
let value: Value = from_str("'''\n abc\n def\n'''").expect("parses");
|
||||
assert_eq!(value, Value::String("abc\ndef".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nesting_past_max_depth_is_an_error() {
|
||||
// Debug builds use far more stack per level than release builds, and the default test
|
||||
// thread is too small for `MAX_DEPTH` levels there.
|
||||
std::thread::Builder::new()
|
||||
.stack_size(64 * 1024 * 1024)
|
||||
.spawn(|| {
|
||||
let nest = |open: &str, inner: &str, close: &str, depth: usize| {
|
||||
format!("{}{inner}{}", open.repeat(depth), close.repeat(depth))
|
||||
};
|
||||
for (open, inner, close) in [("[", "", "]"), (r#"{"a":"#, "1", "}")] {
|
||||
let input = nest(open, inner, close, MAX_DEPTH);
|
||||
assert!(from_str::<Value>(&input).is_ok(), "{open} at the limit");
|
||||
let input = nest(open, inner, close, MAX_DEPTH + 1);
|
||||
let err = from_str::<Value>(&input).expect_err("past the limit");
|
||||
assert!(
|
||||
err.to_string().contains("nested more than"),
|
||||
"{open}: {err}"
|
||||
);
|
||||
}
|
||||
})
|
||||
.expect("test thread starts")
|
||||
.join()
|
||||
.expect("test thread does not panic");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#![doc = include_str!("../README.md")]
|
||||
pub use self::de::{
|
||||
Deserializer, StreamDeserializer, from_iter, from_reader, from_slice, from_str,
|
||||
Deserializer, StreamDeserializer, from_iter, from_reader, from_slice, from_slice_seed, from_str,
|
||||
};
|
||||
pub use self::error::{Error, ErrorCode, Result};
|
||||
pub use self::ser::{
|
||||
@@ -18,3 +18,5 @@ pub mod value;
|
||||
|
||||
#[cfg(feature = "nu-protocol")]
|
||||
mod nu_value;
|
||||
#[cfg(feature = "nu-protocol")]
|
||||
pub use self::nu_value::{NuValueJson, NuValueSeed, write_nu_value};
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
use std::{cell::RefCell, collections::HashSet, fmt, marker::PhantomData};
|
||||
|
||||
use nu_protocol::{
|
||||
CustomValue, FromValue, IntoValue, Record, ShellError, Span, Type,
|
||||
engine::{Closure, EngineState},
|
||||
};
|
||||
use serde::{
|
||||
Serialize, Serializer,
|
||||
de::{DeserializeSeed, Deserializer, MapAccess, SeqAccess, Visitor},
|
||||
ser::{self, SerializeMap, SerializeSeq},
|
||||
};
|
||||
|
||||
use crate::Value as JsonValue;
|
||||
use nu_protocol::Value as NuValue;
|
||||
@@ -32,12 +39,238 @@ impl IntoValue for JsonValue {
|
||||
}
|
||||
}
|
||||
|
||||
/// Deserializes JSON or Hjson straight into a nushell [`NuValue`] with `span`.
|
||||
///
|
||||
/// The result is the same as deserializing a [`JsonValue`] (with the `preserve_order` feature,
|
||||
/// which keeps keys in input order) and calling [`IntoValue::into_value`] on it, without building
|
||||
/// the [`JsonValue`] tree in between. Use it with [`from_slice_seed`](crate::from_slice_seed) or
|
||||
/// any other serde deserializer.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct NuValueSeed {
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
impl<'de> DeserializeSeed<'de> for NuValueSeed {
|
||||
type Value = NuValue;
|
||||
|
||||
fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<NuValue, D::Error> {
|
||||
deserializer.deserialize_any(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Visitor<'de> for NuValueSeed {
|
||||
type Value = NuValue;
|
||||
|
||||
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
f.write_str("a json value")
|
||||
}
|
||||
|
||||
fn visit_bool<E>(self, value: bool) -> Result<NuValue, E> {
|
||||
Ok(NuValue::bool(value, self.span))
|
||||
}
|
||||
|
||||
fn visit_i64<E>(self, value: i64) -> Result<NuValue, E> {
|
||||
Ok(NuValue::int(value, self.span))
|
||||
}
|
||||
|
||||
fn visit_u64<E>(self, value: u64) -> Result<NuValue, E> {
|
||||
Ok(JsonValue::U64(value).into_value(self.span))
|
||||
}
|
||||
|
||||
fn visit_f64<E>(self, value: f64) -> Result<NuValue, E> {
|
||||
Ok(NuValue::float(value, self.span))
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, value: &str) -> Result<NuValue, E> {
|
||||
Ok(NuValue::string(value, self.span))
|
||||
}
|
||||
|
||||
fn visit_string<E>(self, value: String) -> Result<NuValue, E> {
|
||||
Ok(NuValue::string(value, self.span))
|
||||
}
|
||||
|
||||
fn visit_none<E>(self) -> Result<NuValue, E> {
|
||||
Ok(NuValue::nothing(self.span))
|
||||
}
|
||||
|
||||
fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<NuValue, D::Error> {
|
||||
self.deserialize(deserializer)
|
||||
}
|
||||
|
||||
fn visit_unit<E>(self) -> Result<NuValue, E> {
|
||||
Ok(NuValue::nothing(self.span))
|
||||
}
|
||||
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<NuValue, A::Error> {
|
||||
let mut vals = Vec::with_capacity(seq.size_hint().unwrap_or(0));
|
||||
while let Some(val) = seq.next_element_seed(self)? {
|
||||
vals.push(val);
|
||||
}
|
||||
Ok(NuValue::list(vals, self.span))
|
||||
}
|
||||
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<NuValue, A::Error> {
|
||||
let mut pairs = Vec::with_capacity(map.size_hint().unwrap_or(0));
|
||||
while let Some(pair) = map.next_entry_seed(PhantomData::<String>, self)? {
|
||||
pairs.push(pair);
|
||||
}
|
||||
if has_duplicate_keys(pairs.iter().map(|(key, _)| key.as_str())) {
|
||||
pairs = keep_last_of_each_key(pairs);
|
||||
}
|
||||
Ok(NuValue::record(Record::from_iter(pairs), self.span))
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether any key appears twice, in O(n log n) so wide objects stay cheap.
|
||||
fn has_duplicate_keys<'a>(keys: impl ExactSizeIterator<Item = &'a str>) -> bool {
|
||||
if keys.len() < 2 {
|
||||
return false;
|
||||
}
|
||||
let mut keys: Vec<&str> = keys.collect();
|
||||
keys.sort_unstable();
|
||||
keys.windows(2).any(|w| w[0] == w[1])
|
||||
}
|
||||
|
||||
/// Drops repeated keys the way the [`Map`](crate::Map) behind [`JsonValue::Object`] does: a key
|
||||
/// keeps its last value and sits where it last appeared (`{a: 1, b: 2, a: 3}` gives `{b: 2, a: 3}`).
|
||||
fn keep_last_of_each_key(pairs: Vec<(String, NuValue)>) -> Vec<(String, NuValue)> {
|
||||
let keep: Vec<bool> = {
|
||||
let mut seen = HashSet::with_capacity(pairs.len());
|
||||
let mut keep: Vec<bool> = pairs
|
||||
.iter()
|
||||
.rev()
|
||||
.map(|(key, _)| seen.insert(key.as_str()))
|
||||
.collect();
|
||||
keep.reverse();
|
||||
keep
|
||||
};
|
||||
pairs
|
||||
.into_iter()
|
||||
.zip(keep)
|
||||
.filter_map(|(pair, keep)| keep.then_some(pair))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum SerializeMode<'e> {
|
||||
Simple,
|
||||
Coercing { engine_state: &'e EngineState },
|
||||
}
|
||||
|
||||
/// Writes `value` as JSON with `write` (such as [`to_string`](crate::to_string) or
|
||||
/// [`to_string_with_indent`](crate::to_string_with_indent)) without building a [`JsonValue`]
|
||||
/// first.
|
||||
///
|
||||
/// The output and errors are the same as converting with [`JsonValue::from_value`] (or
|
||||
/// [`JsonValue::from_value_serialized`] when `engine_state` is given, which turns closures into
|
||||
/// their source) and then writing that. The outer error is the conversion error, the inner one
|
||||
/// the serializer's.
|
||||
pub fn write_nu_value<T>(
|
||||
value: &NuValue,
|
||||
engine_state: Option<&EngineState>,
|
||||
write: impl FnOnce(&NuValueJson<'_>) -> crate::Result<T>,
|
||||
) -> Result<crate::Result<T>, ShellError> {
|
||||
let mode = match engine_state {
|
||||
Some(engine_state) => SerializeMode::Coercing { engine_state },
|
||||
None => SerializeMode::Simple,
|
||||
};
|
||||
let error = RefCell::new(None);
|
||||
let written = write(&NuValueJson {
|
||||
value,
|
||||
mode,
|
||||
error: &error,
|
||||
});
|
||||
match error.into_inner() {
|
||||
Some(err) => Err(err),
|
||||
None => Ok(written),
|
||||
}
|
||||
}
|
||||
|
||||
/// A borrowed nushell value that serializes as JSON; see [`write_nu_value`].
|
||||
pub struct NuValueJson<'a> {
|
||||
value: &'a NuValue,
|
||||
mode: SerializeMode<'a>,
|
||||
/// The first conversion error. The serializer only carries a message, so the error itself
|
||||
/// waits here for [`write_nu_value`].
|
||||
error: &'a RefCell<Option<ShellError>>,
|
||||
}
|
||||
|
||||
impl NuValueJson<'_> {
|
||||
fn child<'b>(&'b self, value: &'b NuValue) -> NuValueJson<'b> {
|
||||
NuValueJson {
|
||||
value,
|
||||
mode: self.mode,
|
||||
error: self.error,
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps `err` for [`write_nu_value`] and stops the serializer.
|
||||
fn fail<E: ser::Error>(&self, err: ShellError) -> E {
|
||||
let msg = err.to_string();
|
||||
self.error.borrow_mut().get_or_insert(err);
|
||||
E::custom(msg)
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for NuValueJson<'_> {
|
||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
let span = self.value.span();
|
||||
match self.value {
|
||||
NuValue::Bool { val, .. } => serializer.serialize_bool(*val),
|
||||
NuValue::Int { val, .. } => serializer.serialize_i64(*val),
|
||||
NuValue::Float { val, .. } => serializer.serialize_f64(*val),
|
||||
NuValue::String { val, .. } => serializer.serialize_str(val),
|
||||
NuValue::Glob { val, .. } => serializer.serialize_str(&val.to_string()),
|
||||
NuValue::Filesize { val, .. } => serializer.serialize_i64(val.get()),
|
||||
NuValue::Duration { val, .. } => serializer.serialize_i64(*val),
|
||||
NuValue::Date { val, .. } => serializer.serialize_str(&val.to_rfc3339()),
|
||||
NuValue::Range { val, .. } => serializer.serialize_str(&val.to_string()),
|
||||
NuValue::Record { val, .. } => {
|
||||
if has_duplicate_keys(val.columns().map(String::as_str)) {
|
||||
// Rare: let the map behind `JsonValue::Object` pick which keys stay.
|
||||
return match JsonValue::from_value_impl(self.value.clone(), self.mode) {
|
||||
Ok(json) => json.serialize(serializer),
|
||||
Err(err) => Err(self.fail(err)),
|
||||
};
|
||||
}
|
||||
let mut map = serializer.serialize_map(Some(val.len()))?;
|
||||
for (key, value) in val.iter() {
|
||||
map.serialize_key(key)?;
|
||||
map.serialize_value(&self.child(value))?;
|
||||
}
|
||||
map.end()
|
||||
}
|
||||
NuValue::List { vals, .. } => {
|
||||
let mut seq = serializer.serialize_seq(Some(vals.len()))?;
|
||||
for value in vals.iter() {
|
||||
seq.serialize_element(&self.child(value))?;
|
||||
}
|
||||
seq.end()
|
||||
}
|
||||
NuValue::Closure { val, .. } => {
|
||||
match closure_into_json_value((**val).clone(), self.mode, span) {
|
||||
Ok(json) => json.serialize(serializer),
|
||||
Err(err) => Err(self.fail(err)),
|
||||
}
|
||||
}
|
||||
NuValue::Error { error, .. } => Err(self.fail((**error).clone())),
|
||||
NuValue::Binary { val, .. } => {
|
||||
let mut seq = serializer.serialize_seq(Some(val.len()))?;
|
||||
for byte in val {
|
||||
seq.serialize_element(&u64::from(*byte))?;
|
||||
}
|
||||
seq.end()
|
||||
}
|
||||
NuValue::CellPath { val, .. } => serializer.serialize_str(&val.to_string()),
|
||||
NuValue::Custom { val, .. } => match val.to_base_value(span) {
|
||||
Ok(base) => self.child(&base).serialize(serializer),
|
||||
Err(err) => Err(self.fail(err)),
|
||||
},
|
||||
NuValue::Nothing { .. } => serializer.serialize_unit(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FromValue for JsonValue {
|
||||
fn from_value(v: NuValue) -> Result<Self, ShellError> {
|
||||
Self::from_value_impl(v, SerializeMode::Simple)
|
||||
@@ -133,3 +366,114 @@ fn custom_into_json_value(
|
||||
) -> Result<JsonValue, ShellError> {
|
||||
JsonValue::from_value_impl(val.to_base_value(span)?, mode)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{from_slice, from_slice_seed, to_string, to_string_raw};
|
||||
use nu_protocol::record;
|
||||
|
||||
/// Debug output keeps record key order, which `==` on records ignores.
|
||||
fn same(a: &NuValue, b: &NuValue) {
|
||||
assert_eq!(format!("{a:?}"), format!("{b:?}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seed_matches_json_value_tree() {
|
||||
let span = Span::test_data();
|
||||
let inputs = [
|
||||
r#"{"a": 1, "b": [true, null, "x"], "c": {"d": -0, "e": 1.5e3}}"#,
|
||||
"[0, -1, 9223372036854775807, 9223372036854775808, 18446744073709551616, -9223372036854775809]",
|
||||
r#"{"a": 1, "b": 2, "a": 3, "b": 4, "a": 5, "c": {"x": 1, "x": 2}}"#,
|
||||
"// comment\n{\n key: quoteless value\n list: [1, 2,]\n}",
|
||||
"braceless: 1\nother: two",
|
||||
r#""é😀""#,
|
||||
"[]",
|
||||
"{}",
|
||||
];
|
||||
for input in inputs {
|
||||
let direct = from_slice_seed(input.as_bytes(), NuValueSeed { span })
|
||||
.expect("valid input parses");
|
||||
let tree = from_slice::<JsonValue>(input.as_bytes())
|
||||
.expect("valid input parses")
|
||||
.into_value(span);
|
||||
same(&direct, &tree);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seed_keeps_last_duplicate_at_its_last_position() {
|
||||
let span = Span::test_data();
|
||||
let value = from_slice_seed(br#"{"a": 1, "b": 2, "a": 3}"#, NuValueSeed { span })
|
||||
.expect("valid input parses");
|
||||
same(
|
||||
&value,
|
||||
&NuValue::test_record(record! {
|
||||
"b" => NuValue::test_int(2),
|
||||
"a" => NuValue::test_int(3),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seed_reports_the_same_error() {
|
||||
let span = Span::test_data();
|
||||
for input in ["[1, 2", r#"{"a" 1}"#, "[1] x"] {
|
||||
let direct = from_slice_seed(input.as_bytes(), NuValueSeed { span })
|
||||
.expect_err("invalid input fails");
|
||||
let tree = from_slice::<JsonValue>(input.as_bytes()).expect_err("invalid input fails");
|
||||
assert_eq!(direct.to_string(), tree.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_matches_json_value_tree() {
|
||||
let span = Span::test_data();
|
||||
let mut with_duplicates = Record::new();
|
||||
with_duplicates.push("a", NuValue::test_int(1));
|
||||
with_duplicates.push("b", NuValue::test_int(2));
|
||||
with_duplicates.push("a", NuValue::test_int(3));
|
||||
let values = [
|
||||
NuValue::test_record(record! {
|
||||
"a" => NuValue::test_int(1),
|
||||
"b" => NuValue::test_list(vec![NuValue::test_float(-0.0), NuValue::test_nothing()]),
|
||||
"c" => NuValue::test_string("é\n\"😀"),
|
||||
}),
|
||||
NuValue::test_binary(vec![0, 255, 16]),
|
||||
NuValue::test_filesize(1024),
|
||||
NuValue::test_duration(-5),
|
||||
NuValue::test_glob("*.rs"),
|
||||
NuValue::test_list(vec![NuValue::record(with_duplicates, span)]),
|
||||
NuValue::test_list(vec![]),
|
||||
NuValue::test_record(Record::new()),
|
||||
];
|
||||
for value in values {
|
||||
let direct = write_nu_value(&value, None, |json| to_string(json))
|
||||
.expect("converts")
|
||||
.expect("serializes");
|
||||
let tree = to_string(&JsonValue::from_value(value.clone()).expect("converts"))
|
||||
.expect("serializes");
|
||||
assert_eq!(direct, tree);
|
||||
let direct = write_nu_value(&value, None, |json| to_string_raw(json))
|
||||
.expect("converts")
|
||||
.expect("serializes");
|
||||
let tree = to_string_raw(&JsonValue::from_value(value).expect("converts"))
|
||||
.expect("serializes");
|
||||
assert_eq!(direct, tree);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_returns_the_conversion_error() {
|
||||
let span = Span::test_data();
|
||||
let error = ShellError::NushellFailed { msg: "boom".into() };
|
||||
let value = NuValue::test_list(vec![
|
||||
NuValue::test_int(1),
|
||||
NuValue::error(error.clone(), span),
|
||||
]);
|
||||
let direct = write_nu_value(&value, None, |json| to_string(json))
|
||||
.expect_err("the error value is returned");
|
||||
let tree = JsonValue::from_value(value).expect_err("the error value is returned");
|
||||
assert_eq!(format!("{direct:?}"), format!("{tree:?}"));
|
||||
}
|
||||
}
|
||||
|
||||
+21
-10
@@ -1,3 +1,4 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::io;
|
||||
use std::str;
|
||||
|
||||
@@ -7,7 +8,8 @@ pub struct StringReader<Iter: Iterator<Item = u8>> {
|
||||
iter: Iter,
|
||||
line: usize,
|
||||
col: usize,
|
||||
ch: Vec<u8>,
|
||||
/// Bytes peeked but not eaten yet, front first.
|
||||
ch: VecDeque<u8>,
|
||||
}
|
||||
|
||||
impl<Iter> StringReader<Iter>
|
||||
@@ -20,7 +22,7 @@ where
|
||||
iter,
|
||||
line: 1,
|
||||
col: 0,
|
||||
ch: Vec::new(),
|
||||
ch: VecDeque::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,7 +54,7 @@ where
|
||||
while self.ch.len() <= idx {
|
||||
match self.next() {
|
||||
Some(Err(err)) => return Err(Error::Io(err)),
|
||||
Some(Ok(ch)) => self.ch.push(ch),
|
||||
Some(Ok(ch)) => self.ch.push_back(ch),
|
||||
None => return Ok(None),
|
||||
}
|
||||
}
|
||||
@@ -68,15 +70,16 @@ where
|
||||
}
|
||||
|
||||
pub fn eat_char(&mut self) -> u8 {
|
||||
self.ch.remove(0)
|
||||
// Every caller peeks the byte it eats, so the buffer is not empty here.
|
||||
self.ch.pop_front().unwrap_or(b'\x00')
|
||||
}
|
||||
|
||||
pub fn uneat_char(&mut self, ch: u8) {
|
||||
self.ch.insert(0, ch);
|
||||
self.ch.push_front(ch);
|
||||
}
|
||||
|
||||
pub fn next_char(&mut self) -> Result<Option<u8>> {
|
||||
match self.ch.first() {
|
||||
match self.ch.front() {
|
||||
Some(&ch) => {
|
||||
self.eat_char();
|
||||
Ok(Some(ch))
|
||||
@@ -116,10 +119,18 @@ where
|
||||
Some(b'*') => {
|
||||
self.eat_char();
|
||||
self.eat_char();
|
||||
while !(self.peek()?.unwrap_or(b'*') == b'*'
|
||||
&& self.peek_next(1)?.unwrap_or(b'/') == b'/')
|
||||
{
|
||||
self.eat_char();
|
||||
loop {
|
||||
match self.peek()? {
|
||||
None => {
|
||||
return Err(self.error(ErrorCode::Custom(
|
||||
"Found a /* comment with no closing */".to_string(),
|
||||
)));
|
||||
}
|
||||
Some(b'*') if self.peek_next(1)? == Some(b'/') => break,
|
||||
Some(_) => {
|
||||
self.eat_char();
|
||||
}
|
||||
}
|
||||
}
|
||||
self.eat_char();
|
||||
self.eat_char();
|
||||
|
||||
Reference in New Issue
Block a user