1use std::borrow::Cow;
8use std::collections::HashMap;
9
10use kardia_core::PathSegment;
11use kardia_loader::{EXPR_KEY, expr_source};
12use saphyr_parser::{Event, Marker, Parser, ScalarStyle, Tag};
13use serde_json::{Map, Number, Value};
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub struct Position {
18 pub line: usize,
19 pub column: usize,
20}
21
22impl From<Marker> for Position {
23 fn from(marker: Marker) -> Self {
24 Self { line: marker.line(), column: marker.col() + 1 }
25 }
26}
27
28#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
29#[error("{message}")]
30pub struct ParseError {
31 pub message: String,
32 pub position: Position,
33}
34
35#[derive(Debug, Clone)]
37pub struct Syntax {
38 root: Option<Node>,
39 content: String,
40}
41
42#[derive(Debug, Clone)]
43struct Node {
44 start: Position,
45 kind: NodeKind,
46}
47
48#[derive(Debug, Clone)]
49enum NodeKind {
50 Scalar(usize, ScalarStyle),
52 Seq(Vec<Node>),
53 Map(Vec<(String, Position, Node)>),
55}
56
57impl Syntax {
58 pub fn locate(&self, path: &[PathSegment]) -> Option<Position> {
62 let mut node = self.root.as_ref()?;
63 let mut anchor = node.start;
64 for segment in path {
65 let Some((position, value)) = step(node, segment) else { break };
66 anchor = position;
67 node = value;
68 }
69 if matches!(node.kind, NodeKind::Scalar(..)) {
70 anchor = node.start;
71 }
72 Some(anchor)
73 }
74
75 pub fn locate_expr(&self, path: &[PathSegment], offset: usize) -> Option<Position> {
78 let mut node = self.root.as_ref()?;
79 for segment in path {
80 node = step(node, segment)?.1;
81 }
82 if let Some((_, value)) = step(node, &PathSegment::Key(EXPR_KEY.into())) {
83 node = value;
84 }
85 let NodeKind::Scalar(start, style) = node.kind else { return None };
86 let chars: Vec<char> = self.content.chars().collect();
87 let end = match style {
88 ScalarStyle::Plain => skip(&chars, start, offset, |_, _| None),
89 ScalarStyle::SingleQuoted => skip(&chars, start + 1, offset, |chars, i| {
90 (chars[i] == '\'' && chars.get(i + 1) == Some(&'\'')).then_some(2)
91 }),
92 ScalarStyle::DoubleQuoted => skip(&chars, start + 1, offset, |chars, i| {
93 (chars[i] == '\\').then(|| match chars.get(i + 1) {
94 Some('x') => 4,
95 Some('u') => 6,
96 Some('U') => 10,
97 _ => 2,
98 })
99 }),
100 _ => return Some(node.start),
102 };
103 Some(advance(node.start, &chars[start..end.min(chars.len())]))
104 }
105}
106
107fn step<'a>(node: &'a Node, segment: &PathSegment) -> Option<(Position, &'a Node)> {
108 match (&node.kind, segment) {
109 (NodeKind::Map(entries), PathSegment::Key(key)) => {
110 entries.iter().find(|(name, ..)| name == key).map(|(_, key, value)| (*key, value))
111 }
112 (NodeKind::Seq(items), PathSegment::Index(index)) => items.get(*index).map(|item| (item.start, item)),
113 _ => None,
114 }
115}
116
117fn skip(chars: &[char], mut index: usize, count: usize, escape: impl Fn(&[char], usize) -> Option<usize>) -> usize {
121 for _ in 0..count {
122 if index >= chars.len() {
123 break;
124 }
125 if chars[index] == '\n' {
126 index += 1;
127 while chars.get(index).is_some_and(|c| *c == ' ' || *c == '\t') {
128 index += 1;
129 }
130 } else {
131 index += escape(chars, index).unwrap_or(1);
132 }
133 }
134 index
135}
136
137fn advance(start: Position, chars: &[char]) -> Position {
139 chars.iter().fold(start, |Position { line, column }, c| match c {
140 '\n' => Position { line: line + 1, column: 1 },
141 _ => Position { line, column: column + 1 },
142 })
143}
144
145fn skip_properties(chars: &[char], mut index: usize) -> usize {
147 while chars.get(index).is_some_and(|c| *c == '&' || *c == '!') {
148 while chars.get(index).is_some_and(|c| !c.is_whitespace()) {
149 index += 1;
150 }
151 while chars.get(index).is_some_and(|c| c.is_whitespace()) {
152 index += 1;
153 }
154 }
155 index
156}
157
158enum Frame {
159 Seq {
160 anchor: usize,
161 start: Position,
162 values: Vec<Value>,
163 nodes: Vec<Node>,
164 },
165 Map {
166 anchor: usize,
167 start: Position,
168 values: Map<String, Value>,
169 nodes: Vec<(String, Position, Node)>,
170 key: Option<(String, Position)>,
171 },
172}
173
174pub fn parse(content: &str) -> Result<(Value, Syntax), ParseError> {
176 let chars: Vec<char> = content.chars().collect();
177 let mut stack: Vec<Frame> = Vec::new();
178 let mut anchors: HashMap<usize, (Value, Node)> = HashMap::new();
179 let mut result: Option<(Value, Node)> = None;
180 for event in Parser::new_from_str(content) {
181 let (event, span) = event
182 .map_err(|error| ParseError { message: error.info().to_string(), position: (*error.marker()).into() })?;
183 let start = Position::from(span.start);
184 let completed = match event {
185 Event::StreamStart | Event::DocumentStart(_) | Event::Nothing => None,
186 Event::DocumentEnd | Event::StreamEnd => break,
187 Event::Alias(id) => {
188 let (value, node) = anchors
189 .get(&id)
190 .cloned()
191 .ok_or_else(|| ParseError { message: "unknown alias".into(), position: start })?;
192 Some((value, node, 0))
193 }
194 Event::Scalar(value, style, anchor, tag) => {
195 let value =
196 scalar(&value, style, tag.as_deref()).map_err(|message| ParseError { message, position: start })?;
197 let index = skip_properties(&chars, span.start.index());
198 let start = advance(start, &chars[span.start.index()..index]);
199 let node = Node { start, kind: NodeKind::Scalar(index, style) };
200 Some((value, node, anchor))
201 }
202 Event::SequenceStart(anchor, tag) => {
203 check_collection_tag(tag.as_deref(), "seq", start)?;
204 stack.push(Frame::Seq { anchor, start, values: Vec::new(), nodes: Vec::new() });
205 None
206 }
207 Event::MappingStart(anchor, tag) => {
208 check_collection_tag(tag.as_deref(), "map", start)?;
209 stack.push(Frame::Map { anchor, start, values: Map::new(), nodes: Vec::new(), key: None });
210 None
211 }
212 Event::SequenceEnd | Event::MappingEnd => match stack.pop() {
213 Some(Frame::Seq { anchor, start, values, nodes }) => {
214 Some((Value::Array(values), Node { start, kind: NodeKind::Seq(nodes) }, anchor))
215 }
216 Some(Frame::Map { anchor, start, values, nodes, .. }) => {
217 Some((Value::Object(values), Node { start, kind: NodeKind::Map(nodes) }, anchor))
218 }
219 None => None,
220 },
221 };
222 let Some((value, node, anchor)) = completed else { continue };
223 if anchor > 0 {
224 anchors.insert(anchor, (value.clone(), node.clone()));
225 }
226 match stack.last_mut() {
227 None => {
228 result.get_or_insert((value, node));
229 }
230 Some(Frame::Seq { values, nodes, .. }) => {
231 values.push(value);
232 nodes.push(node);
233 }
234 Some(Frame::Map { values, nodes, key, .. }) => match key.take() {
235 None => {
236 let name = match value {
237 Value::String(name) => name,
238 Value::Null => "null".into(),
239 Value::Bool(_) | Value::Number(_) => value.to_string(),
240 _ => {
241 return Err(ParseError {
242 message: "complex keys are not supported".into(),
243 position: node.start,
244 });
245 }
246 };
247 *key = Some((name, node.start));
248 }
249 Some((name, position)) => {
250 values.insert(name.clone(), value);
251 nodes.push((name, position, node));
252 }
253 },
254 }
255 }
256 let (value, node) = result.unwrap_or((
257 Value::Null,
258 Node { start: Position { line: 1, column: 1 }, kind: NodeKind::Scalar(0, ScalarStyle::Plain) },
259 ));
260 Ok((value, Syntax { root: Some(node), content: content.into() }))
261}
262
263const CORE: &str = "tag:yaml.org,2002:";
264
265fn check_collection_tag(tag: Option<&Tag>, expected: &str, position: Position) -> Result<(), ParseError> {
266 match tag {
267 None => Ok(()),
268 Some(tag) if tag.handle == CORE && tag.suffix == expected => Ok(()),
269 Some(tag) => Err(ParseError { message: format!("unresolved tag: {}{}", tag.handle, tag.suffix), position }),
270 }
271}
272
273fn scalar(value: &str, style: ScalarStyle, tag: Option<&Tag>) -> Result<Value, String> {
274 if let Some(tag) = tag {
275 if tag.handle != CORE {
276 return Err(format!("unresolved tag: {}{}", tag.handle, tag.suffix));
277 }
278 return match tag.suffix.as_str() {
279 "js" => Ok(Value::Object(Map::from_iter([(EXPR_KEY.to_string(), Value::String(value.to_string()))]))),
280 "str" => Ok(Value::String(value.to_string())),
281 "null" | "bool" | "int" | "float" => resolve_plain(value)
282 .filter(|v| !v.is_string())
283 .ok_or_else(|| format!("invalid !!{} value: {value}", tag.suffix)),
284 suffix => Err(format!("unresolved tag: !!{suffix}")),
285 };
286 }
287 if style != ScalarStyle::Plain {
288 return Ok(Value::String(value.to_string()));
289 }
290 Ok(resolve_plain(value).unwrap_or_else(|| Value::String(value.to_string())))
291}
292
293fn resolve_plain(value: &str) -> Option<Value> {
295 match value {
296 "" | "~" | "null" | "Null" | "NULL" => return Some(Value::Null),
297 "true" | "True" | "TRUE" => return Some(Value::Bool(true)),
298 "false" | "False" | "FALSE" => return Some(Value::Bool(false)),
299 _ => {}
300 }
301 let digits = |s: &str, radix: u32| !s.is_empty() && s.chars().all(|c| c.is_digit(radix));
302 let unsigned = value.strip_prefix(['-', '+']).unwrap_or(value);
303 if digits(unsigned, 10) {
304 return value.parse::<i64>().ok().map(Value::from).or_else(|| value.parse::<f64>().ok().and_then(float));
305 }
306 if let Some(octal) = value.strip_prefix("0o").filter(|s| digits(s, 8)) {
307 return i64::from_str_radix(octal, 8).ok().map(Value::from);
308 }
309 if let Some(hex) = value.strip_prefix("0x").filter(|s| digits(s, 16)) {
310 return i64::from_str_radix(hex, 16).ok().map(Value::from);
311 }
312 if is_float(unsigned) {
313 return value.parse::<f64>().ok().and_then(float);
314 }
315 None
316}
317
318fn is_float(value: &str) -> bool {
320 let (mantissa, exponent) = match value.find(['e', 'E']) {
321 Some(index) => (&value[..index], Some(&value[index + 1..])),
322 None => (value, None),
323 };
324 let (int, frac) = match mantissa.split_once('.') {
325 Some((int, frac)) => (int, Some(frac)),
326 None => (mantissa, None),
327 };
328 let all_digits = |s: &str| s.chars().all(|c| c.is_ascii_digit());
329 let mantissa_ok = match frac {
330 Some(frac) => all_digits(int) && all_digits(frac) && !(int.is_empty() && frac.is_empty()),
331 None => !int.is_empty() && all_digits(int),
332 };
333 let exponent_ok = exponent.is_none_or(|e| {
334 let e = e.strip_prefix(['-', '+']).unwrap_or(e);
335 !e.is_empty() && all_digits(e)
336 });
337 mantissa_ok && exponent_ok && (frac.is_some() || exponent.is_some())
338}
339
340fn float(value: f64) -> Option<Value> {
341 Number::from_f64(value).map(Value::Number)
342}
343
344pub fn dump(value: &Value) -> String {
346 let mut output = String::new();
347 write_block(&mut output, value, 0);
348 if !output.ends_with('\n') {
349 output.push('\n');
350 }
351 output
352}
353
354fn write_block(output: &mut String, value: &Value, indent: usize) {
355 match value {
356 Value::Array(items) if !items.is_empty() => {
357 for item in items {
358 output.push_str(&" ".repeat(indent));
359 output.push('-');
360 match item {
361 Value::Object(map) if !map.is_empty() && expr_source(item).is_none() => {
362 output.push(' ');
363 write_map(output, map, indent + 2, true);
364 }
365 Value::Array(inner) if !inner.is_empty() => {
366 output.push('\n');
367 write_block(output, item, indent + 2);
368 }
369 _ => {
370 output.push(' ');
371 output.push_str(&inline(item));
372 output.push('\n');
373 }
374 }
375 }
376 }
377 Value::Object(map) if !map.is_empty() && expr_source(value).is_none() => write_map(output, map, indent, false),
378 _ => {
379 output.push_str(&" ".repeat(indent));
380 output.push_str(&inline(value));
381 output.push('\n');
382 }
383 }
384}
385
386fn write_map(output: &mut String, map: &Map<String, Value>, indent: usize, continued: bool) {
387 for (index, (key, value)) in map.iter().enumerate() {
388 if index > 0 || !continued {
389 output.push_str(&" ".repeat(indent));
390 }
391 output.push_str(&string(key));
392 output.push(':');
393 match value {
394 Value::Object(inner) if !inner.is_empty() && expr_source(value).is_none() => {
395 output.push('\n');
396 write_map(output, inner, indent + 2, false);
397 }
398 Value::Array(items) if !items.is_empty() => {
399 output.push('\n');
400 write_block(output, value, indent);
401 }
402 _ => {
403 output.push(' ');
404 output.push_str(&inline(value));
405 output.push('\n');
406 }
407 }
408 }
409}
410
411fn inline(value: &Value) -> String {
412 if let Some(source) = expr_source(value) {
413 return format!("!!js {}", quoted(source));
414 }
415 match value {
416 Value::Null => "null".into(),
417 Value::Bool(value) => value.to_string(),
418 Value::Number(number) => number.to_string(),
419 Value::String(text) => string(text),
420 Value::Array(_) => "[]".into(),
421 Value::Object(_) => "{}".into(),
422 }
423}
424
425fn string(text: &str) -> String {
427 if is_plain_safe(text) { text.to_string() } else { quoted(text) }
428}
429
430fn quoted(text: &str) -> String {
431 if text.chars().any(|c| c.is_control()) {
432 return serde_json::to_string(text).expect("strings serialize");
433 }
434 format!("'{}'", text.replace('\'', "''"))
435}
436
437fn is_plain_safe(text: &str) -> bool {
438 let Some(first) = text.chars().next() else { return false };
439 !"-?:,[]{}#&*!|>'\"%@`".contains(first)
440 && !text.starts_with(char::is_whitespace)
441 && !text.ends_with(char::is_whitespace)
442 && !text.contains(": ")
443 && !text.contains(" #")
444 && !text.ends_with(':')
445 && !text.chars().any(|c| c.is_control())
446 && resolve_plain(text).is_none()
447 && !matches!(Cow::from(text).as_ref(), ".inf" | ".nan" | "-.inf" | ".Inf" | ".NaN")
448}
449
450#[cfg(test)]
451mod tests {
452 use serde_json::json;
453
454 use super::*;
455
456 #[test]
457 fn parses_the_core_schema_with_expressions_and_aliases() {
458 let source = "- id: a\n name: foo\n disabled: !!js 'x > 1'\n config: &c { a: 1, b: [1, 2.5, ~, true, 'q', 0x1f] }\n- *c\n- !!str 12\n";
459 let (value, syntax) = parse(source).unwrap();
460 assert_eq!(
461 value,
462 json!([
463 { "id": "a", "name": "foo", "disabled": { "__jsExpr": "x > 1" }, "config": { "a": 1, "b": [1, 2.5, null, true, "q", 31] } },
464 { "a": 1, "b": [1, 2.5, null, true, "q", 31] },
465 "12",
466 ])
467 );
468 let at = |path: Vec<PathSegment>| syntax.locate(&path).unwrap();
469 let key = |key: &str| PathSegment::Key(key.into());
470 assert_eq!(at(vec![PathSegment::Index(0), key("name")]), Position { line: 2, column: 9 });
471 assert_eq!(at(vec![PathSegment::Index(0), key("config")]), Position { line: 4, column: 3 });
472 assert_eq!(at(vec![PathSegment::Index(0), key("missing")]), Position { line: 1, column: 3 });
473 assert_eq!(at(vec![PathSegment::Index(1), key("a")]), Position { line: 4, column: 19 });
475 assert_eq!(at(vec![PathSegment::Index(0), key("disabled")]), Position { line: 3, column: 18 });
476 assert_eq!(
477 syntax.locate_expr(&[PathSegment::Index(0), key("disabled")], 4),
478 Some(Position { line: 3, column: 23 })
479 );
480 }
481
482 #[test]
483 fn reports_errors_and_unknown_tags() {
484 let error = parse("a: [1, 2\nb: c").unwrap_err();
485 assert_eq!(error.position.line, 2);
486 assert!(parse("- !custom x").unwrap_err().message.contains("unresolved tag"));
487 }
488
489 #[test]
490 fn dumps_values_that_read_back_the_same() {
491 let value = json!([
492 { "id": "a", "name": "foo", "config": { "text": "it's: here", "n": "12", "empty": "", "list": [1, { "x": null }], "map": {} } },
493 { "id": "b", "name": "group", "group": true, "config": [{ "id": "c", "name": "bar", "disabled": { "__jsExpr": "a && b" } }] },
494 { "id": "d", "name": "multi", "config": "line\nbreak" },
495 ]);
496 let text = dump(&value);
497 assert_eq!(parse(&text).unwrap().0, value, "{text}");
498 assert!(text.starts_with("- id: a\n name: foo\n config:\n text: 'it''s: here'\n n: '12'\n"), "{text}");
499 assert!(text.contains("disabled: !!js 'a && b'"), "{text}");
500 }
501}