use std::rc::Rc;
use yaml_rust2::parser::{Event, Parser};
use yaml_rust2::scanner::{Marker, TScalarStyle};
use crate::mark::Mark;
use crate::names::same_name;
use crate::path::Path;
use crate::problems::{Kind, Problems};
use crate::raw::{Raw, RawKey};
#[derive(Debug, PartialEq)]
pub(crate) enum Parsed {
Tree(Raw),
Empty,
Failed,
}
pub(crate) fn read(text: &str, name: &Rc<str>, problems: &mut Problems) -> Parsed {
let mut parser = Parser::new_from_str(text).keep_tags(true);
let mut events: Vec<(Event, Marker)> = Vec::new();
loop {
match parser.next_token() {
Ok((event, marker)) => {
let ended = event == Event::StreamEnd;
events.push((event, marker));
if ended {
break;
}
}
Err(error) => {
let message = format!("invalid YAML: {}", error.info());
report(problems, name, error.marker().line(), &message);
return Parsed::Failed;
}
}
}
match document(Cursor::new(&events), name) {
Ok(Some(raw)) => Parsed::Tree(raw),
Ok(None) => Parsed::Empty,
Err((line, message)) => {
report(problems, name, line, &message);
Parsed::Failed
}
}
}
fn report(problems: &mut Problems, name: &Rc<str>, line: usize, message: &str) {
problems.error(
Kind::Source,
&Mark::File(name.clone(), line),
Path::new(),
message.to_owned(),
);
}
type Syntax = (usize, String);
struct Cursor<'a> {
events: &'a [(Event, Marker)],
position: usize,
}
impl<'a> Cursor<'a> {
fn new(events: &'a [(Event, Marker)]) -> Self {
Self {
events,
position: 0,
}
}
fn peek(&self) -> Option<(&Event, usize)> {
let next = self.events.get(self.position)?;
Some((&next.0, next.1.line()))
}
fn next(&mut self) -> Option<(&Event, usize)> {
let next = self.events.get(self.position)?;
self.position += 1;
Some((&next.0, next.1.line()))
}
}
fn document(mut cursor: Cursor<'_>, name: &Rc<str>) -> Result<Option<Raw>, Syntax> {
match cursor.next() {
Some((Event::StreamStart, _)) => {}
_ => return Err((1, "the stream does not start".to_owned())),
}
match cursor.next() {
Some((Event::StreamEnd, _)) => return Ok(None),
Some((Event::DocumentStart, _)) => {}
_ => return Err((1, "the document does not start".to_owned())),
}
let mut anchors: Vec<(usize, Raw)> = Vec::new();
let closed_at = match cursor.peek() {
Some((Event::DocumentEnd, line)) => Some(line),
_ => None,
};
let raw = match closed_at {
Some(line) => Raw::null(Mark::File(name.clone(), line)),
None => node(&mut cursor, &mut anchors, name)?,
};
match cursor.next() {
Some((Event::DocumentEnd, _)) => {}
Some((_, line)) => return Err((line, "the document is not closed".to_owned())),
None => return Err((1, "the document is not closed".to_owned())),
}
match cursor.next() {
Some((Event::StreamEnd, _)) => Ok(Some(raw)),
Some((_, line)) => Err((line, "expected a single document".to_owned())),
None => Err((1, "the stream is not closed".to_owned())),
}
}
fn node(
cursor: &mut Cursor<'_>,
anchors: &mut Vec<(usize, Raw)>,
name: &Rc<str>,
) -> Result<Raw, Syntax> {
let Some((event, line)) = cursor.next().map(|(event, line)| (event.clone(), line)) else {
return Err((1, "the document ends too early".to_owned()));
};
let mark = || Mark::File(name.clone(), line);
let (anchor, tag, raw) = match event {
Event::Scalar(text, style, anchor, tag) => {
let raw = if is_null(&text, style) {
Raw::null(mark())
} else {
Raw::scalar(text, mark())
};
(anchor, tag, raw)
}
Event::SequenceStart(anchor, tag) => (anchor, tag, sequence(cursor, anchors, name, mark)?),
Event::MappingStart(anchor, tag) => (anchor, tag, mapping(cursor, anchors, name, mark)?),
Event::Alias(id) => {
return anchors
.iter()
.find(|(known, _)| *known == id)
.map(|(_, raw)| raw.clone())
.ok_or_else(|| (line, format!("unknown anchor {id}")));
}
other => return Err((line, format!("unexpected {}", describe(&other)))),
};
if let Some(tag) = tag {
return Err((
line,
format!("tags are not supported: {}{}", tag.handle, tag.suffix),
));
}
if anchor != 0 {
anchors.push((anchor, raw.clone()));
}
Ok(raw)
}
enum Ahead {
Closed,
Scalar(String, usize),
Other(usize),
End,
}
fn ahead(cursor: &Cursor<'_>) -> Ahead {
match cursor.peek() {
None => Ahead::End,
Some((Event::SequenceEnd | Event::MappingEnd, _)) => Ahead::Closed,
Some((Event::Scalar(text, _, _, _), line)) => Ahead::Scalar(text.clone(), line),
Some((_, line)) => Ahead::Other(line),
}
}
fn sequence(
cursor: &mut Cursor<'_>,
anchors: &mut Vec<(usize, Raw)>,
name: &Rc<str>,
mark: impl Fn() -> Mark,
) -> Result<Raw, Syntax> {
let mut items: Vec<Raw> = Vec::new();
loop {
match ahead(cursor) {
Ahead::Closed => {
cursor.next();
break;
}
Ahead::Scalar(_, _) | Ahead::Other(_) => items.push(node(cursor, anchors, name)?),
Ahead::End => return Err((1, "the sequence is not closed".to_owned())),
}
}
Ok(if items.is_empty() {
Raw::empty_sequence(mark())
} else {
Raw::sequence(items, mark())
})
}
fn mapping(
cursor: &mut Cursor<'_>,
anchors: &mut Vec<(usize, Raw)>,
name: &Rc<str>,
mark: impl Fn() -> Mark,
) -> Result<Raw, Syntax> {
let mut entries: Vec<(RawKey, Raw)> = Vec::new();
loop {
let (text, line) = match ahead(cursor) {
Ahead::Closed => {
cursor.next();
break;
}
Ahead::Scalar(text, line) => (text, line),
Ahead::Other(line) => {
return Err((line, "a key of a mapping must be a scalar".to_owned()));
}
Ahead::End => return Err((1, "the mapping is not closed".to_owned())),
};
if let Some((Event::Scalar(_, _, _, Some(tag)), _)) = cursor.next() {
return Err((
line,
format!("tags are not supported: {}{}", tag.handle, tag.suffix),
));
}
let key = RawKey::new(text, Mark::File(name.clone(), line));
let value = node(cursor, anchors, name)?;
if entries
.iter()
.any(|(known, _)| same_name(known.text(), key.text()))
{
return Err((line, format!("duplicate name {:?}", key.text())));
}
entries.push((key, value));
}
Ok(if entries.is_empty() {
Raw::empty_mapping(mark())
} else {
Raw::mapping(entries, mark())
})
}
fn is_null(text: &str, style: TScalarStyle) -> bool {
style == TScalarStyle::Plain
&& (text.is_empty() || text == "~" || text.eq_ignore_ascii_case("null"))
}
fn describe(event: &Event) -> &'static str {
match event {
Event::StreamStart | Event::StreamEnd => "end of the stream",
Event::DocumentStart | Event::DocumentEnd => "end of the document",
Event::SequenceEnd | Event::MappingEnd => "end of a collection",
Event::Nothing => "nothing",
_ => "node",
}
}
#[cfg(test)]
mod tests {
use super::{Parsed, read};
use crate::mark::Mark;
use crate::problems::{Origin, Problems};
use crate::raw::Raw;
fn file(text: &str) -> (Option<Raw>, Problems) {
let mut problems = Problems::new();
let raw = match read(text, &"config.yaml".into(), &mut problems) {
Parsed::Tree(raw) => Some(raw),
Parsed::Empty | Parsed::Failed => None,
};
(raw, problems)
}
fn entries(raw: &Raw) -> Vec<(String, String, bool)> {
raw.entries()
.unwrap_or_default()
.iter()
.map(|(key, value)| {
(
key.text().to_owned(),
value.text().unwrap_or("").to_owned(),
value.is_null(),
)
})
.collect()
}
#[test]
fn section_sequence_and_scalars_keep_their_shape() {
let (raw, problems) =
file("host: localhost\nports:\n - 4200\n - 443\nempty: {}\nnone: []\n");
assert!(problems.is_empty(), "{problems}");
let raw = raw.expect("the document is read");
assert_eq!(
entries(&raw),
[
("host".to_owned(), "localhost".to_owned(), false),
("ports".to_owned(), String::new(), false),
("empty".to_owned(), String::new(), false),
("none".to_owned(), String::new(), false),
]
);
let items = raw
.entries()
.and_then(|entries| entries.get(1))
.and_then(|(_, value)| value.items());
assert_eq!(items.map(<[Raw]>::len), Some(2));
let empty = raw
.entries()
.and_then(|entries| entries.get(2))
.map(|(_, value)| value.is_empty());
assert_eq!(empty, Some(true));
}
#[test]
fn null_has_several_spellings_and_quotes_keep_the_text() {
let text =
"a:\nb: ~\nc: null\nd: Null\ne: '~'\nf: \"null\"\ng: ''\nh: |\n first\n second\n";
let (raw, problems) = file(text);
assert!(problems.is_empty(), "{problems}");
let raw = raw.expect("the document is read");
let (texts, nulls): (Vec<String>, Vec<bool>) = entries(&raw)
.into_iter()
.map(|(_, text, null)| (text, null))
.unzip();
assert_eq!(nulls, [true, true, true, true, false, false, false, false]);
assert_eq!(
texts,
["", "", "", "", "~", "null", "", "first\nsecond\n"].map(String::from)
);
}
#[test]
fn empty_file_gives_no_document() {
let (raw, problems) = file("");
assert!(raw.is_none());
assert!(problems.is_empty());
let (raw, problems) = file("# only a comment\n\n");
assert!(raw.is_none());
assert!(problems.is_empty(), "{problems}");
}
#[test]
fn anchors_repeat_a_node_and_tags_are_rejected() {
let (raw, problems) = file("base: &base\n host: a\nsame: *base\n");
assert!(problems.is_empty(), "{problems}");
let raw = raw.expect("the document is read");
let read = raw.entries().unwrap_or_default();
assert_eq!(read.len(), 2);
assert_eq!(read[0].1, read[1].1);
let (raw, problems) = file("value: !!str 12\n");
assert!(raw.is_none());
assert_eq!(problems.len(), 1);
assert!(
problems
.iter()
.next()
.unwrap()
.message
.contains("tags are not supported")
);
}
#[test]
fn duplicates_and_second_document_are_errors_with_lines() {
let (raw, problems) = file("host: a\nHost: b\n");
assert!(raw.is_none());
let problem = problems.iter().next().unwrap();
assert_eq!(
problem.origin,
Origin::File {
name: "config.yaml".into(),
line: 2
}
);
assert_eq!(problem.message, "duplicate name \"Host\"");
let (raw, problems) = file("a: 1\n---\nb: 2\n");
assert!(raw.is_none());
assert!(
problems
.iter()
.next()
.unwrap()
.message
.contains("single document")
);
let (raw, problems) = file("a: [1, 2\n");
assert!(raw.is_none());
assert!(
problems
.iter()
.next()
.unwrap()
.message
.starts_with("invalid YAML")
);
}
#[test]
fn keys_remember_their_lines() {
let (raw, _) = file("# комментарий\n\nhost: a\n\nports:\n - 1\n");
let raw = raw.expect("the document is read");
let lines: Vec<usize> = raw
.entries()
.unwrap_or_default()
.iter()
.map(|(key, _)| match key.mark() {
Mark::File(_, line) => *line,
other => unreachable!("ключ не из файла: {other:?}"),
})
.collect();
assert_eq!(lines, [3, 5]);
assert_ne!(Mark::File("a".into(), 1), Mark::File("a".into(), 2));
}
}