clove/code4dyslexia
src/json_source.rs
// src/json_source.rs
use std::borrow::Cow;
use std::ops::Range;
use serde::de::IgnoredAny;
use crate::config::Effective;
use crate::language::{Analysis, Diagnostic};
#[derive(Clone, Copy, PartialEq, Eq)]
enum Kind {
Open,
Close,
Comma,
Colon,
Value,
}
struct Token {
kind: Kind,
span: Range<usize>,
}
fn syntax(offset: usize, message: impl Into<String>) -> Diagnostic {
Diagnostic {
offset,
rule: "syntax",
message: message.into(),
}
}
fn lex(source: &str, comments: bool) -> Result<(Vec<Token>, Vec<Range<usize>>), Diagnostic> {
let bytes = source.as_bytes();
let mut offset = 0;
let mut tokens = Vec::new();
let mut masks = Vec::new();
while offset < bytes.len() {
let start = offset;
offset += 1;
let kind = match bytes[start] {
b' ' | b'\t' | b'\r' | b'\n' => continue,
b'{' | b'[' => Kind::Open,
b'}' | b']' => Kind::Close,
b',' => Kind::Comma,
b':' => Kind::Colon,
b'"' => {
while offset < bytes.len() {
let byte = bytes[offset];
offset += 1;
if byte == b'"' {
break;
}
if byte == b'\\' && offset < bytes.len() {
offset += 1;
}
}
Kind::Value
}
b'/' if comments && bytes.get(offset) == Some(&b'/') => {
offset = source[start..].find(['\r', '\n']).map_or(bytes.len(), |end| start + end);
masks.push(start..offset);
continue;
}
b'/' if comments && bytes.get(offset) == Some(&b'*') => {
offset = source[offset + 1..]
.find("*/")
.map(|end| offset + 1 + end + 2)
.ok_or_else(|| syntax(start, "Unterminated block comment"))?;
masks.push(start..offset);
continue;
}
_ => {
while bytes.get(offset).is_some_and(|&byte| {
!matches!(byte, b' ' | b'\t' | b'\r' | b'\n' | b'{' | b'[' | b'}' | b']' | b':' | b',' | b'"' | b'/')
}) {
offset += 1;
}
Kind::Value
}
};
tokens.push(Token {
kind,
span: start..offset,
});
}
Ok((tokens, masks))
}
fn validate(
source: &str,
tokens: &[Token],
mut masks: Vec<Range<usize>>,
comments: bool,
lines: &[usize],
) -> Result<(), Diagnostic> {
if comments {
// Mask commas only after a value and immediately before a closing delimiter.
for triple in tokens.windows(3) {
if matches!(triple[0].kind, Kind::Value | Kind::Close)
&& triple[1].kind == Kind::Comma && triple[2].kind == Kind::Close
{
masks.push(triple[1].span.clone());
}
}
}
let mut masked;
let input = if masks.is_empty() {
source.as_bytes()
} else {
masked = source.as_bytes().to_vec();
for range in masks {
for byte in &mut masked[range] {
if !matches!(*byte, b'\r' | b'\n') {
*byte = b' ';
}
}
}
&masked
};
serde_json::from_slice::<IgnoredAny>(input).map_err(|error| {
let line = lines[error.line().saturating_sub(1).min(lines.len() - 1)];
let mut offset = (line + error.column().saturating_sub(1)).min(source.len());
while !source.is_char_boundary(offset) {
offset -= 1;
}
syntax(offset, error.to_string())
})?;
Ok(())
}
struct Edit {
span: Range<usize>,
replacement: String,
issue: Diagnostic,
}
fn edit(span: Range<usize>, replacement: String, rule: &'static str, message: String) -> Edit {
Edit {
issue: Diagnostic {
offset: span.start,
rule,
message,
},
span,
replacement,
}
}
pub fn analyze<'source, const COMMENTS: bool>(
source: &'source str,
_: &str,
settings: &Effective,
_: bool,
) -> Result<Analysis<'source>, Diagnostic> {
let code = source.strip_prefix('\u{feff}').unwrap_or(source);
let header = source.len() - code.len();
let lines: Vec<_> = std::iter::once(0)
.chain(code.match_indices('\n').map(|(offset, _)| offset + 1))
.collect();
let result = lex(code, COMMENTS).and_then(|(tokens, masks)| {
validate(code, &tokens, masks, COMMENTS, &lines)?;
Ok(tokens)
});
let tokens = result.map_err(|mut issue| {
issue.offset += header;
issue
})?;
let mut edits = Vec::new();
let mut depth: usize = 0;
let mut previous_line = None;
for (index, token) in tokens.iter().enumerate() {
let line = lines.partition_point(|offset| *offset <= token.span.start) - 1;
if token.kind == Kind::Close {
depth = depth.saturating_sub(1);
}
let indent = settings.indent_size();
if indent != 0 && previous_line != Some(line) {
let prefix = &code.as_bytes()[lines[line]..token.span.start];
let width = depth * indent;
if prefix.iter().all(|byte| matches!(byte, b' ' | b'\t'))
&& (prefix.len() != width || prefix.contains(&b'\t'))
{
edits.push(edit(
lines[line]..token.span.start,
" ".repeat(width),
"formatting.indentSize",
format!("Expected {width} space(s) of indentation"),
));
}
}
previous_line = Some(line);
if token.kind == Kind::Open {
depth += 1;
}
let newlines = settings.newline_size();
if newlines == 0 || token.kind != Kind::Comma || index == 0 {
continue;
}
let Some(right) = tokens.get(index + 1).filter(|next| next.kind != Kind::Close) else {
continue;
};
let nested_right = right.kind == Kind::Open
|| (tokens.get(index + 2).is_some_and(|next| next.kind == Kind::Colon)
&& tokens.get(index + 3).is_some_and(|next| next.kind == Kind::Open));
if tokens[index - 1].kind != Kind::Close && !nested_right {
continue;
}
let between = &code[token.span.end..right.span.start];
if !between.bytes().all(|byte| matches!(byte, b' ' | b'\t' | b'\r' | b'\n')) {
continue;
}
let count = between.bytes().filter(|&byte| byte == b'\n').count();
if count != 0 && count != newlines {
let first = between.find('\n').unwrap();
let last = between.rfind('\n').unwrap();
let ending = if between[..first].ends_with('\r') { "\r\n" } else { "\n" };
edits.push(edit(
token.span.end..token.span.end + last + 1,
ending.repeat(newlines),
"formatting.newLineSize",
format!("Expected {newlines} newline character(s) between structured values"),
));
}
}
if edits.is_empty() {
return Ok(Analysis {
formatted: Cow::Borrowed(source),
issues: Vec::new(),
});
}
let mut output = String::with_capacity(source.len());
let mut issues = Vec::with_capacity(edits.len());
output.push_str(&source[..header]);
let mut cursor = 0;
for Edit { span, replacement, mut issue } in edits {
output.push_str(&code[cursor..span.start]);
output.push_str(&replacement);
cursor = span.end;
issue.offset += header;
issues.push(issue);
}
output.push_str(&code[cursor..]);
Ok(Analysis {
formatted: Cow::Owned(output),
issues,
})
}