use std::fmt::Write as _;
use crate::codes::{
SYNTAX_BYTE_ORDER_MARK, SYNTAX_CODE_FENCE, SYNTAX_COMMENT, SYNTAX_CONTROL_CHARACTER,
SYNTAX_CUT, SYNTAX_FOREIGN_LITERAL, SYNTAX_INVALID_ESCAPE, SYNTAX_LONE_SURROGATE,
SYNTAX_MISSING_COMMA, SYNTAX_NOT_FINITE, SYNTAX_NUMBER_SPELLING, SYNTAX_SINGLE_QUOTES,
SYNTAX_SURROUNDING_TEXT, SYNTAX_TOO_DEEP, SYNTAX_TRAILING_COMMA, SYNTAX_UNQUOTED_KEY,
SYNTAX_UNREADABLE,
};
use crate::diagnostic::{Diagnostic, Edit, Fix};
use crate::path::{Path, Segment};
use crate::tree::{Entry, Node, Number, Span, Value};
use crate::write::quote;
use super::Read;
const LITERALS: [&str; 9] = [
"true",
"false",
"null",
"True",
"False",
"None",
"NaN",
"Infinity",
"undefined",
];
pub const MAX_DEPTH: usize = 127;
#[must_use]
pub fn json(text: &str, root: &Path) -> Read {
let mut reader = Reader {
text,
bytes: text.as_bytes(),
at: 0,
line: 1,
column: 1,
start: 0,
end: text.len(),
diagnostics: Vec::new(),
incomplete: Vec::new(),
};
let tree = reader.document(root);
let mut diagnostics = reader.diagnostics;
if let Some(tree) = &tree {
for diagnostic in &mut diagnostics {
while tree.at(&diagnostic.path).is_none() {
let Some(parent) = diagnostic.path.parent() else {
break;
};
diagnostic.path = parent;
}
}
}
Read {
tree,
diagnostics,
incomplete: reader.incomplete,
}
}
enum Hex {
End,
Invalid,
Value(u32),
}
enum Parsed {
Done(Node),
Stopped(Option<Node>),
}
#[derive(Clone, Copy)]
struct Mark {
at: usize,
line: u32,
column: u32,
}
struct Reader<'a> {
text: &'a str,
bytes: &'a [u8],
at: usize,
line: u32,
column: u32,
start: usize,
end: usize,
diagnostics: Vec<Diagnostic>,
incomplete: Vec<Path>,
}
fn is_identifier_start(byte: u8) -> bool {
byte.is_ascii_alphabetic() || byte == b'_' || byte == b'$'
}
fn is_identifier(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$'
}
fn is_delimiter(byte: Option<u8>) -> bool {
byte.is_none_or(|byte| {
matches!(
byte,
b' ' | b'\t' | b'\n' | b'\r' | b',' | b']' | b'}' | b':' | b'/'
)
})
}
impl Reader<'_> {
fn peek(&self) -> Option<u8> {
(self.at < self.end).then(|| self.bytes[self.at])
}
fn peek_at(&self, ahead: usize) -> Option<u8> {
let at = self.at + ahead;
(at < self.end).then(|| self.bytes[at])
}
fn bump(&mut self) {
let byte = self.bytes[self.at];
self.at += 1;
if byte == b'\n' {
self.line += 1;
self.column = 1;
} else if byte & 0xC0 != 0x80 {
self.column += 1;
}
}
fn bump_n(&mut self, count: usize) {
for _ in 0..count {
self.bump();
}
}
const fn mark(&self) -> Mark {
Mark {
at: self.at,
line: self.line,
column: self.column,
}
}
fn reset(&mut self, mark: Mark) {
self.at = mark.at;
self.line = mark.line;
self.column = mark.column;
}
fn span_from(&self, mark: Mark) -> Span {
Span {
offset: mark.at,
length: self.at - mark.at,
line: mark.line,
column: mark.column,
}
}
const fn here(&self) -> Span {
Span {
offset: self.at,
length: 0,
line: self.line,
column: self.column,
}
}
fn report(&mut self, diagnostic: Diagnostic) {
self.diagnostics.push(diagnostic);
}
fn document(&mut self, root: &Path) -> Option<Node> {
if self.text.starts_with('\u{feff}') {
let span = Span {
offset: 0,
length: 3,
line: 1,
column: 1,
};
self.report(
Diagnostic::new(
&SYNTAX_BYTE_ORDER_MARK,
root.clone(),
"The text starts with a byte-order mark, which JSON readers refuse.",
)
.at(Some(span))
.fix(Fix::certain(
"remove the byte-order mark",
vec![remove(0, 3)],
)),
);
self.bump_n(3);
self.column = 1;
self.start = 3;
}
self.skip_space();
if !self.at_value_start() {
self.surroundings(root);
}
self.skip_space_and_comments(root);
if self.peek().is_none() {
let span = self.here();
self.report(
Diagnostic::new(
&SYNTAX_UNREADABLE,
root.clone(),
"The text holds no document.",
)
.at(Some(span))
.data(Node::map([("expected", Node::text("a value"))])),
);
return None;
}
let parsed = self.value(&mut root.clone(), 0);
let tree = match parsed {
Parsed::Done(node) => Some(node),
Parsed::Stopped(node) => return node,
};
self.skip_space_and_comments(root);
if self.at < self.end {
self.trailing_text(root);
}
tree
}
fn at_value_start(&self) -> bool {
match self.peek() {
Some(b'{' | b'[' | b'"' | b'\'' | b'-' | b'+' | b'.' | b'0'..=b'9') => true,
Some(byte) if is_identifier_start(byte) => {
let start = self.at;
let mut end = start;
while end < self.end && is_identifier(self.bytes[end]) {
end += 1;
}
let word = &self.text[start..end];
if end == self.end {
return LITERALS.iter().any(|literal| literal.starts_with(word));
}
LITERALS.contains(&word) && is_delimiter(self.bytes.get(end).copied())
}
_ => false,
}
}
fn surroundings(&mut self, root: &Path) {
let rest = &self.text[self.at..self.end];
let fence = rest
.match_indices("```")
.map(|(offset, _)| self.at + offset)
.find(|&offset| offset == 0 || self.bytes[offset - 1] == b'\n');
let first_bracket = rest.find(['{', '[']).map(|offset| self.at + offset);
if let Some(open) = fence
&& first_bracket.is_none_or(|bracket| open < bracket)
{
let content = self.text[open..]
.find('\n')
.map_or(self.end, |line_end| open + line_end + 1);
let close = self.text[content..self.end]
.match_indices("```")
.map(|(offset, _)| content + offset)
.find(|&offset| self.bytes[offset - 1] == b'\n')
.unwrap_or(self.end);
self.bump_n(open - self.at);
let fence_start = self.mark();
self.report(
Diagnostic::new(
&SYNTAX_CODE_FENCE,
root.clone(),
"The document is wrapped in a Markdown code fence; send the JSON alone.",
)
.at(Some(Span {
offset: open,
length: content - open,
line: fence_start.line,
column: fence_start.column,
}))
.fix(Fix::certain(
"remove the code fence and the text around it",
vec![
remove(close, self.text.len() - close),
remove(self.start, content - self.start),
],
)),
);
self.bump_n(content - self.at);
self.end = close;
return;
}
let Some(start) = first_bracket else {
return;
};
let mark = self.mark();
self.report(
Diagnostic::new(
&SYNTAX_SURROUNDING_TEXT,
root.clone(),
"Text that is not JSON comes before the document.",
)
.at(Some(Span {
offset: mark.at,
length: start - mark.at,
line: mark.line,
column: mark.column,
}))
.fix(Fix::certain(
"remove the text before the document",
vec![remove(self.start, start - self.start)],
)),
);
self.bump_n(start - self.at);
}
fn trailing_text(&mut self, root: &Path) {
let mark = self.mark();
let length = self.end - self.at;
self.report(
Diagnostic::new(
&SYNTAX_SURROUNDING_TEXT,
root.clone(),
"Text that is not part of the document follows it.",
)
.at(Some(Span {
offset: mark.at,
length,
line: mark.line,
column: mark.column,
}))
.fix(Fix::certain(
"remove the text after the document",
vec![remove(mark.at, length)],
)),
);
self.at = self.end;
}
fn skip_space(&mut self) {
while let Some(b' ' | b'\t' | b'\n' | b'\r') = self.peek() {
self.bump();
}
}
fn skip_space_and_comments(&mut self, path: &Path) -> bool {
loop {
self.skip_space();
match (self.peek(), self.peek_at(1)) {
(Some(b'/'), Some(b'/')) => {
let mark = self.mark();
while self.peek().is_some_and(|byte| byte != b'\n') {
self.bump();
}
self.comment(path, mark);
}
(Some(b'/'), Some(b'*')) => {
let mark = self.mark();
self.bump_n(2);
let closed = loop {
match (self.peek(), self.peek_at(1)) {
(Some(b'*'), Some(b'/')) => {
self.bump_n(2);
break true;
}
(Some(_), _) => self.bump(),
(None, _) => break false,
}
};
if !closed {
return false;
}
self.comment(path, mark);
}
_ => return true,
}
}
}
fn comment(&mut self, path: &Path, mark: Mark) {
let span = self.span_from(mark);
self.report(
Diagnostic::new(
&SYNTAX_COMMENT,
path.clone(),
"JSON has no comments; this one has to go.",
)
.at(Some(span))
.fix(Fix::certain(
"remove the comment",
vec![remove(span.offset, span.length)],
)),
);
}
fn cut(&mut self, path: &Path, dropped: Option<&str>) {
let span = self.here();
let mut message = format!("The text ends inside {path}");
if let Some(dropped) = dropped {
let _ = write!(message, ", in the middle of {dropped}");
}
message.push_str("; what was open is closed here to check the rest.");
let mut data = vec![("open", Node::text(path.to_string()))];
if let Some(dropped) = dropped {
data.push(("dropped", Node::text(dropped)));
}
self.report(
Diagnostic::new(&SYNTAX_CUT, path.clone(), message)
.at(Some(span))
.data(Node::map(data)),
);
}
fn unreadable(&mut self, path: &Path, expected: &str) {
let mut span = self.here();
let found = match self.text[self.at..self.end].chars().next() {
Some(char) => {
span.length = char.len_utf8();
format!("{char:?}")
}
None => "the end of the text".to_owned(),
};
self.report(
Diagnostic::new(
&SYNTAX_UNREADABLE,
path.clone(),
format!(
"Expected {expected} but found {found}; the text cannot be read from here on."
),
)
.at(Some(span))
.data(Node::map([
("expected", Node::text(expected)),
("found", Node::text(found)),
])),
);
}
fn value(&mut self, path: &mut Path, depth: usize) -> Parsed {
let mark = self.mark();
match self.peek() {
None => {
self.cut(path, None);
Parsed::Stopped(None)
}
Some(b'{') => self.object(path, depth + 1),
Some(b'[') => self.array(path, depth + 1),
Some(quote @ (b'"' | b'\'')) => {
let text = if quote == b'"' {
self.string(path, b'"')
} else {
self.single_quoted(path, mark)
};
if let Some(text) = text {
Parsed::Done(spanned(Value::Text(text), self.span_from(mark)))
} else {
self.cut(path, Some("a string"));
Parsed::Stopped(None)
}
}
Some(b'-' | b'+' | b'.' | b'0'..=b'9') => self.number(path),
Some(byte) if is_identifier_start(byte) => self.literal(path),
Some(_) => {
self.unreadable(path, "a value");
Parsed::Stopped(None)
}
}
}
fn object(&mut self, path: &mut Path, depth: usize) -> Parsed {
let mark = self.mark();
if depth > MAX_DEPTH {
self.too_deep(path);
return Parsed::Stopped(None);
}
self.bump();
let mut entries: Vec<Entry> = Vec::new();
let mut previous_end: Option<usize> = None;
let stopped = loop {
if !self.space(path) {
break true;
}
match self.peek() {
None => {
self.cut(path, None);
break true;
}
Some(b'}') => {
self.bump();
break false;
}
Some(b'"' | b'\'') => {}
Some(byte) if is_identifier_start(byte) => {}
Some(_) => {
self.unreadable(path, "a key or `}`");
break true;
}
}
if let Some(end) = previous_end.take() {
self.missing_comma(path, end);
}
let key_mark = self.mark();
let Some(key) = self.key(path) else {
self.cut(path, Some("a key"));
break true;
};
let key_span = self.span_from(key_mark);
if !self.space(path) {
break true;
}
match self.peek() {
Some(b':') => self.bump(),
None => {
self.cut(path, Some(&format!("the entry {}", quote(&key))));
break true;
}
Some(_) => {
self.unreadable(path, "`:` after the key");
break true;
}
}
if !self.space(path) {
break true;
}
path.push(Segment::Key(key.clone()));
let parsed = self.value(path, depth);
path.pop();
match parsed {
Parsed::Done(value) => {
previous_end = value.span.map(|span| span.end());
entries.push(Entry {
key,
key_span: Some(key_span),
value,
});
}
Parsed::Stopped(value) => {
if let Some(value) = value {
entries.push(Entry {
key,
key_span: Some(key_span),
value,
});
}
break true;
}
}
if !self.separator(path, b'}', &mut previous_end) {
break true;
}
};
let node = Node {
value: Value::Map(entries),
span: Some(self.span_from(mark)),
};
if stopped {
self.incomplete.push(path.clone());
Parsed::Stopped(Some(node))
} else {
Parsed::Done(node)
}
}
fn array(&mut self, path: &mut Path, depth: usize) -> Parsed {
let mark = self.mark();
if depth > MAX_DEPTH {
self.too_deep(path);
return Parsed::Stopped(None);
}
self.bump();
let mut items: Vec<Node> = Vec::new();
let mut previous_end: Option<usize> = None;
let stopped = loop {
if !self.space(path) {
break true;
}
match self.peek() {
None => {
self.cut(path, None);
break true;
}
Some(b']') => {
self.bump();
break false;
}
Some(_) if self.at_value_start() => {}
Some(_) => {
self.unreadable(path, "a value or `]`");
break true;
}
}
if let Some(end) = previous_end.take() {
self.missing_comma(path, end);
}
path.push(Segment::Index(items.len()));
let parsed = self.value(path, depth);
path.pop();
match parsed {
Parsed::Done(value) => {
previous_end = value.span.map(|span| span.end());
items.push(value);
}
Parsed::Stopped(value) => {
items.extend(value);
break true;
}
}
if !self.separator(path, b']', &mut previous_end) {
break true;
}
};
let node = Node {
value: Value::List(items),
span: Some(self.span_from(mark)),
};
if stopped {
self.incomplete.push(path.clone());
Parsed::Stopped(Some(node))
} else {
Parsed::Done(node)
}
}
fn space(&mut self, path: &Path) -> bool {
let closed = self.skip_space_and_comments(path);
if !closed {
self.cut(path, Some("a comment"));
}
closed
}
fn separator(&mut self, path: &Path, close: u8, previous_end: &mut Option<usize>) -> bool {
if !self.space(path) {
return false;
}
if self.peek() == Some(b',') {
*previous_end = None;
let comma = self.mark();
self.bump();
if !self.space(path) {
return false;
}
if self.peek() == Some(close) {
self.trailing_comma(path, comma);
}
}
true
}
fn too_deep(&mut self, path: &Path) {
let mut span = self.here();
span.length = 1;
self.report(
Diagnostic::new(
&SYNTAX_TOO_DEEP,
path.clone(),
format!("Arrays and objects nest deeper than {MAX_DEPTH} levels here."),
)
.at(Some(span))
.data(Node::map([("maximum", Node::from(MAX_DEPTH))])),
);
}
fn trailing_comma(&mut self, path: &Path, comma: Mark) {
let span = Span {
offset: comma.at,
length: 1,
line: comma.line,
column: comma.column,
};
self.report(
Diagnostic::new(
&SYNTAX_TRAILING_COMMA,
path.clone(),
"A comma follows the last entry; JSON allows none there.",
)
.at(Some(span))
.fix(Fix::certain("remove the comma", vec![remove(comma.at, 1)])),
);
}
fn missing_comma(&mut self, path: &Path, previous_end: usize) {
let span = self.here();
self.report(
Diagnostic::new(
&SYNTAX_MISSING_COMMA,
path.clone(),
"A comma is missing between two entries.",
)
.at(Some(span))
.fix(Fix::certain(
"add a comma",
vec![Edit::Text {
offset: previous_end,
length: 0,
replacement: ",".into(),
}],
)),
);
}
fn key(&mut self, path: &Path) -> Option<String> {
let mark = self.mark();
match self.peek()? {
b'"' => self.string(path, b'"'),
b'\'' => self.single_quoted(path, mark),
_ => {
while self.peek().is_some_and(is_identifier) {
self.bump();
}
let key = self.text[mark.at..self.at].to_owned();
let span = self.span_from(mark);
self.report(
Diagnostic::new(
&SYNTAX_UNQUOTED_KEY,
path.clone(),
format!("The key {key} has no quotes; JSON keys are strings."),
)
.at(Some(span))
.fix(Fix::certain(
format!("write the key as {}", quote(&key)),
vec![replace_text(span, quote(&key))],
)),
);
Some(key)
}
}
}
fn single_quoted(&mut self, path: &Path, mark: Mark) -> Option<String> {
let text = self.string(path, b'\'')?;
let span = self.span_from(mark);
self.report(
Diagnostic::new(
&SYNTAX_SINGLE_QUOTES,
path.clone(),
"A string is in single quotes; JSON strings use double quotes.",
)
.at(Some(span))
.fix(Fix::certain(
"use double quotes",
vec![replace_text(span, quote(&text))],
)),
);
Some(text)
}
fn string(&mut self, path: &Path, close: u8) -> Option<String> {
let open = self.mark();
self.bump();
let mut text = String::new();
let mut controls = Vec::new();
let mut escapes = Vec::new();
let mut surrogates = Vec::new();
loop {
let byte = self.peek()?;
if byte == close {
self.bump();
break;
}
match byte {
b'\\' => {
let mark = self.mark();
self.bump();
self.escape(&mut text, mark, close, &mut escapes, &mut surrogates)?;
}
0x00..=0x1F => {
let mark = self.mark();
self.bump();
let span = self.span_from(mark);
controls.push(replace_text(
span,
quote(&char::from(byte).to_string())
.trim_matches('"')
.to_owned(),
));
text.push(char::from(byte));
}
_ => {
let start = self.at;
while self
.peek()
.is_some_and(|byte| byte != close && byte != b'\\' && byte >= 0x20)
{
self.bump();
}
text.push_str(&self.text[start..self.at]);
}
}
}
let span = self.span_from(open);
if !controls.is_empty() {
self.report(
Diagnostic::new(
&SYNTAX_CONTROL_CHARACTER,
path.clone(),
"A string holds a raw control character, such as a line break; JSON writes it escaped.",
)
.at(Some(span))
.fix(Fix::certain("escape the control characters", controls)),
);
}
if !escapes.is_empty() {
let diagnostic = Diagnostic::new(
&SYNTAX_INVALID_ESCAPE,
path.clone(),
"A string holds an escape JSON does not define; the character after the backslash is kept.",
)
.at(Some(span));
let all_quotes = escapes.iter().all(|(_, quote)| *quote);
let edits = escapes.into_iter().map(|(edit, _)| edit).collect();
self.report(if all_quotes {
diagnostic.fix(Fix::certain("remove the backslashes", edits))
} else {
diagnostic
});
}
if !surrogates.is_empty() {
self.report(
Diagnostic::new(
&SYNTAX_LONE_SURROGATE,
path.clone(),
"A string escapes half of a UTF-16 surrogate pair, which is no character.",
)
.at(Some(span)),
);
}
Some(text)
}
fn escape(
&mut self,
text: &mut String,
mark: Mark,
close: u8,
escapes: &mut Vec<(Edit, bool)>,
surrogates: &mut Vec<Span>,
) -> Option<()> {
let byte = self.peek()?;
let simple = match byte {
b'"' => Some('"'),
b'\\' => Some('\\'),
b'/' => Some('/'),
b'b' => Some('\u{8}'),
b'f' => Some('\u{c}'),
b'n' => Some('\n'),
b'r' => Some('\r'),
b't' => Some('\t'),
_ => None,
};
if let Some(char) = simple {
self.bump();
text.push(char);
return Some(());
}
if byte == b'u' {
self.bump();
let first = match self.hex4() {
Hex::End => return None,
Hex::Value(value) => value,
Hex::Invalid => {
escapes.push((
Edit::Text {
offset: mark.at,
length: 1,
replacement: String::new(),
},
false,
));
text.push('u');
return Some(());
}
};
if (0xD800..0xDC00).contains(&first) {
if self.peek() == Some(b'\\') && self.peek_at(1) == Some(b'u') {
let resume = self.mark();
self.bump_n(2);
if let Hex::Value(second) = self.hex4()
&& (0xDC00..0xE000).contains(&second)
{
let code = 0x10000 + ((first - 0xD800) << 10) + (second - 0xDC00);
text.push(char::from_u32(code).unwrap_or('\u{fffd}'));
return Some(());
}
self.reset(resume);
}
surrogates.push(self.span_from(mark));
text.push('\u{fffd}');
} else if (0xDC00..0xE000).contains(&first) {
surrogates.push(self.span_from(mark));
text.push('\u{fffd}');
} else {
text.push(char::from_u32(first).unwrap_or('\u{fffd}'));
}
return Some(());
}
let char = self.text[self.at..].chars().next()?;
self.bump_n(char.len_utf8());
escapes.push((
Edit::Text {
offset: mark.at,
length: 1,
replacement: String::new(),
},
close == b'"' && char == '\'',
));
text.push(char);
Some(())
}
fn hex4(&mut self) -> Hex {
let mut value = 0;
for _ in 0..4 {
let Some(byte) = self.peek() else {
return Hex::End;
};
let Some(digit) = char::from(byte).to_digit(16) else {
return Hex::Invalid;
};
self.bump();
value = value * 16 + digit;
}
Hex::Value(value)
}
fn number(&mut self, path: &Path) -> Parsed {
let mark = self.mark();
let mut sign = "";
match self.peek() {
Some(b'-') => {
sign = "-";
self.bump();
}
Some(b'+') => self.bump(),
_ => {}
}
if self.peek().is_some_and(is_identifier_start) {
let word_start = self.at;
while self.peek().is_some_and(is_identifier) {
self.bump();
}
if &self.text[word_start..self.at] == "Infinity" && is_delimiter(self.peek()) {
return Parsed::Done(self.not_finite(path, mark, &format!("{sign}Infinity")));
}
self.reset(mark);
self.unreadable(path, "a number");
return Parsed::Stopped(None);
}
let digits_start = self.at;
while self.peek().is_some_and(|byte| byte.is_ascii_digit()) {
self.bump();
}
let integer = &self.text[digits_start..self.at];
let mut fraction = None;
if self.peek() == Some(b'.') {
self.bump();
let start = self.at;
while self.peek().is_some_and(|byte| byte.is_ascii_digit()) {
self.bump();
}
fraction = Some(&self.text[start..self.at]);
}
let mut exponent = None;
if matches!(self.peek(), Some(b'e' | b'E')) {
let before = self.mark();
self.bump();
let mut exponent_sign = "";
if let Some(byte @ (b'+' | b'-')) = self.peek() {
exponent_sign = if byte == b'-' { "-" } else { "+" };
self.bump();
}
let start = self.at;
while self.peek().is_some_and(|byte| byte.is_ascii_digit()) {
self.bump();
}
if self.at == start {
self.reset(before);
} else {
exponent = Some((exponent_sign, &self.text[start..self.at]));
}
}
if (integer.is_empty() && fraction.is_none_or(str::is_empty)) || !is_delimiter(self.peek())
{
self.reset(mark);
self.unreadable(path, "a number");
return Parsed::Stopped(None);
}
self.finish_number(path, mark, sign, integer, fraction, exponent)
}
fn finish_number(
&mut self,
path: &Path,
mark: Mark,
sign: &str,
integer: &str,
fraction: Option<&str>,
exponent: Option<(&str, &str)>,
) -> Parsed {
let span = self.span_from(mark);
let written = &self.text[span.offset..span.end()];
let trimmed = integer.trim_start_matches('0');
let mut spelling = format!("{sign}{}", if trimmed.is_empty() { "0" } else { trimmed });
if let Some(fraction) = fraction {
spelling.push('.');
spelling.push_str(if fraction.is_empty() { "0" } else { fraction });
}
if let Some((exponent_sign, digits)) = exponent {
spelling.push('e');
spelling.push_str(exponent_sign);
spelling.push_str(digits);
}
let number = if let Some(number) = Number::parse(written) {
number
} else {
let number = Number::parse(&spelling).unwrap_or_else(|| Number::integer(0));
self.report(
Diagnostic::new(
&SYNTAX_NUMBER_SPELLING,
path.clone(),
format!("The number {written} is not spelt as JSON spells numbers."),
)
.at(Some(span))
.fix(Fix::certain(
format!("write it as {spelling}"),
vec![replace_text(span, spelling.clone())],
)),
);
number
};
Parsed::Done(Node {
value: Value::Number(number),
span: Some(span),
})
}
fn not_finite(&mut self, path: &Path, mark: Mark, word: &str) -> Node {
let span = self.span_from(mark);
self.report(
Diagnostic::new(
&SYNTAX_NOT_FINITE,
path.clone(),
format!("{word} is not a number JSON can write."),
)
.at(Some(span))
.help("write a finite number, or leave the field out if it has a default"),
);
Node {
value: Value::Number(Number::not_finite(word.trim_start_matches('+'))),
span: Some(span),
}
}
fn literal(&mut self, path: &Path) -> Parsed {
let mark = self.mark();
while self.peek().is_some_and(is_identifier) {
self.bump();
}
let word = &self.text[mark.at..self.at];
if self.peek().is_none() && !matches!(word, "true" | "false" | "null") {
let complete = matches!(word, "True" | "False" | "None" | "NaN" | "Infinity");
if !complete {
self.cut(path, Some("a literal"));
return Parsed::Stopped(None);
}
}
if !is_delimiter(self.peek()) {
self.reset(mark);
self.unreadable(path, "a value");
return Parsed::Stopped(None);
}
let span = self.span_from(mark);
let (value, json) = match word {
"true" => return Parsed::Done(spanned(Value::Bool(true), span)),
"false" => return Parsed::Done(spanned(Value::Bool(false), span)),
"null" => return Parsed::Done(spanned(Value::Null, span)),
"True" => (Value::Bool(true), Some("true")),
"False" => (Value::Bool(false), Some("false")),
"None" => (Value::Null, Some("null")),
"undefined" => (Value::Null, None),
"NaN" | "Infinity" => {
let word = word.to_owned();
return Parsed::Done(self.not_finite(path, mark, &word));
}
_ => {
self.reset(mark);
self.unreadable(path, "a value");
return Parsed::Stopped(None);
}
};
let mut diagnostic = Diagnostic::new(
&SYNTAX_FOREIGN_LITERAL,
path.clone(),
format!("{word} is not a JSON literal."),
)
.at(Some(span));
diagnostic = match json {
Some(json) => diagnostic.fix(Fix::certain(
format!("write {json}"),
vec![replace_text(span, json.to_owned())],
)),
None => diagnostic.help("JSON has no undefined; leave the entry out or write null"),
};
self.report(diagnostic);
Parsed::Done(spanned(value, span))
}
}
const fn spanned(value: Value, span: Span) -> Node {
Node {
value,
span: Some(span),
}
}
const fn remove(offset: usize, length: usize) -> Edit {
Edit::Text {
offset,
length,
replacement: String::new(),
}
}
const fn replace_text(span: Span, replacement: String) -> Edit {
Edit::Text {
offset: span.offset,
length: span.length,
replacement,
}
}