//! The strict YAML subset of road headers: Pensum's header subset (Fabrica `core/docs/FORMATS.md`, "The header //! subset"). Every header this accepts is valid YAML; most of YAML is refused, each refusal naming the line and //! the field. use crate::rules; /// A field's value. Plain scalars are always strings: `true` is text, the field's reader decides. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Value { /// `key:` with nothing after it: the field is not set. Absent, Str(String), List(Vec), } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Field { pub key: String, /// 1-based line in the file. pub line: usize, pub value: Value, } /// The first problem in a header: line (1-based in the file), field, rule code, message. #[derive(Debug, Clone, PartialEq, Eq)] pub struct HeaderError { pub line: usize, pub field: Option, pub code: &'static str, pub message: String, } fn refused(line: usize, field: Option<&str>, message: impl Into) -> HeaderError { HeaderError { line, field: field.map(String::from), code: rules::YAML_REFUSED, message: message.into(), } } fn syntax(line: usize, field: Option<&str>, message: impl Into) -> HeaderError { HeaderError { line, field: field.map(String::from), code: rules::YAML_SYNTAX, message: message.into(), } } /// Parses header lines (without their line endings). `first_line` is the file line of `lines[0]`. pub fn parse(lines: &[&str], first_line: usize) -> Result, HeaderError> { let mut fields: Vec = Vec::new(); let mut i = 0; while i < lines.len() { let line = lines[i]; let no = first_line + i; if line.starts_with('\t') { return Err(refused(no, None, "tab indentation is not allowed")); } let trimmed = line.trim_start_matches(' '); if trimmed.is_empty() || trimmed.starts_with('#') { i += 1; continue; } if line.starts_with(' ') { return Err(refused( no, None, "unexpected indentation: keys start at column 0", )); } if line.starts_with('%') { return Err(refused(no, None, "YAML directives are not allowed")); } if line == "..." { return Err(refused( no, None, "the document end marker `...` is not allowed", )); } let Some((key, rest)) = split_key(line) else { return Err(syntax( no, None, format!("expected `key: value`, found `{}`", crate::ids::clip(line)), )); }; if fields.iter().any(|f| f.key == key) { return Err(HeaderError { line: no, field: Some(key.to_string()), code: rules::KEY_DUPLICATE, message: "duplicate key".into(), }); } let rest = rest.trim_start_matches(' '); let value = if rest.is_empty() || rest.starts_with('#') { let mut list = Vec::new(); while i + 1 < lines.len() { let next = lines[i + 1]; if next.starts_with('\t') { return Err(refused(no + 1, Some(key), "tab indentation is not allowed")); } let t = next.trim_start_matches(' '); if t.len() == next.len() || !(t == "-" || t.starts_with("- ")) { break; } let item_line = first_line + i + 1; let item = t[1..].trim_start_matches(' '); if item.starts_with('[') || item.starts_with('-') || item.starts_with('{') { return Err(refused( item_line, Some(key), "nested lists and mappings are not allowed", )); } let (s, after) = scalar(item, false, item_line, key)?; end_of_value(after, item_line, key)?; list.push(s); i += 1; } if list.is_empty() { Value::Absent } else { Value::List(list) } } else { inline(rest, no, key)? }; fields.push(Field { key: key.to_string(), line: no, value, }); i += 1; } Ok(fields) } /// `key: rest` with `key` = `[A-Za-z][A-Za-z0-9]*`, the colon followed by a space or the end of the line. fn split_key(line: &str) -> Option<(&str, &str)> { let colon = line.find(':')?; let key = &line[..colon]; let rest = &line[colon + 1..]; let mut b = key.bytes(); let ok = b.next().is_some_and(|c| c.is_ascii_alphabetic()) && b.all(|c| c.is_ascii_alphanumeric()); (ok && (rest.is_empty() || rest.starts_with(' '))).then_some((key, rest)) } fn inline(rest: &str, line: usize, key: &str) -> Result { if let Some(mut s) = rest.strip_prefix('[') { let mut items = Vec::new(); loop { s = s.trim_start_matches(' '); if let Some(after) = s.strip_prefix(']') { if !items.is_empty() { return Err(syntax(line, Some(key), "an empty item in a list")); } end_of_value(after, line, key)?; return Ok(Value::List(items)); } if s.starts_with('[') || s.starts_with('{') { return Err(refused( line, Some(key), "nested lists and mappings are not allowed", )); } let (item, after) = scalar(s, true, line, key)?; items.push(item); let after = after.trim_start_matches(' '); if let Some(a) = after.strip_prefix(',') { s = a; } else if let Some(a) = after.strip_prefix(']') { end_of_value(a, line, key)?; return Ok(Value::List(items)); } else { return Err(syntax( line, Some(key), "a list is `[a, b]`, closed on the same line", )); } } } let (s, after) = scalar(rest, false, line, key)?; end_of_value(after, line, key)?; Ok(Value::Str(s)) } /// After a value: nothing, or spaces and a ` # comment`. fn end_of_value(after: &str, line: usize, key: &str) -> Result<(), HeaderError> { let t = after.trim_start_matches(' '); if t.is_empty() || (t.starts_with('#') && t.len() < after.len()) { Ok(()) } else { Err(syntax( line, Some(key), format!("unexpected `{}` after the value", crate::ids::clip(t)), )) } } /// One scalar at the start of `s`; returns it and what follows. fn scalar<'a>( s: &'a str, in_flow: bool, line: usize, key: &str, ) -> Result<(String, &'a str), HeaderError> { match s.chars().next() { Some('&') => Err(refused(line, Some(key), "anchors (`&`) are not allowed")), Some('*') => Err(refused(line, Some(key), "aliases (`*`) are not allowed")), Some('!') => Err(refused(line, Some(key), "tags (`!`) are not allowed")), Some('|') | Some('>') => Err(refused( line, Some(key), "block scalars (`|`, `>`) are not allowed", )), Some('{') => Err(refused( line, Some(key), "flow mappings (`{}`) are not allowed", )), Some('%') | Some('@') | Some('`') | Some('?') | Some(',') | Some(']') | Some('}') => { Err(syntax( line, Some(key), "a value may not start with this character; quote it", )) } Some('"') => double_quoted(&s[1..], line, key), Some('\'') => single_quoted(&s[1..], line, key), _ => { let mut end = s.len(); for (i, c) in s.char_indices() { if in_flow && matches!(c, ',' | ']') { end = i; break; } if in_flow && matches!(c, '[' | '{' | '}') { return Err(syntax( line, Some(key), "quote a list item that holds brackets", )); } if c == '#' && i > 0 && s.as_bytes()[i - 1] == b' ' { end = i; break; } } let v = s[..end].trim_end_matches(' '); if v.contains(": ") || v.ends_with(':') { return Err(syntax( line, Some(key), "a plain value may not contain `: `; quote it", )); } if v.is_empty() && in_flow { return Err(syntax(line, Some(key), "an empty item in a list")); } Ok((v.to_string(), &s[v.len()..])) } } } fn double_quoted<'a>(s: &'a str, line: usize, key: &str) -> Result<(String, &'a str), HeaderError> { let mut out = String::new(); let mut chars = s.char_indices(); while let Some((i, c)) = chars.next() { match c { '"' => return Ok((out, &s[i + 1..])), '\\' => match chars.next().map(|(_, c)| c) { Some('"') => out.push('"'), Some('\\') => out.push('\\'), Some('n') => out.push('\n'), Some('t') => out.push('\t'), Some('r') => out.push('\r'), Some('u') => { let hex: String = (0..4) .filter_map(|_| chars.next().map(|(_, c)| c)) .collect(); let ch = (hex.len() == 4 && hex.bytes().all(|b| b.is_ascii_hexdigit())) .then(|| u32::from_str_radix(&hex, 16).ok()) .flatten() .and_then(char::from_u32); match ch { Some(ch) => out.push(ch), None => { return Err(syntax( line, Some(key), "`\\u` takes 4 hex digits of a character", )); } } } _ => { return Err(syntax( line, Some(key), "unknown escape; use \\\" \\\\ \\n \\t \\r \\uXXXX", )); } }, c => out.push(c), } } Err(syntax(line, Some(key), "unclosed double-quoted string")) } fn single_quoted<'a>(s: &'a str, line: usize, key: &str) -> Result<(String, &'a str), HeaderError> { let mut out = String::new(); let b = s.as_bytes(); let mut i = 0; let mut start = 0; while i < b.len() { if b[i] == b'\'' { out.push_str(&s[start..i]); if b.get(i + 1) == Some(&b'\'') { out.push('\''); i += 2; start = i; continue; } return Ok((out, &s[i + 1..])); } i += 1; } Err(syntax(line, Some(key), "unclosed single-quoted string")) } /// Whether `s` reads back unchanged as a plain scalar in a header value or flow list item. pub fn is_plain_safe(s: &str, in_flow: bool) -> bool { let Some(first) = s.chars().next() else { return false; }; if "&*!|>{}[]%@`?,#'\"-:".contains(first) || s.ends_with(' ') || s.ends_with(':') { return false; } if s.contains(": ") || s.contains(" #") || s.chars().any(|c| c.is_control()) { return false; } if in_flow && s.contains([',', '[', ']', '{', '}']) { return false; } true } /// `s` as a double-quoted scalar. pub fn quote(s: &str) -> String { let mut out = String::from("\""); for c in s.chars() { match c { '"' => out.push_str("\\\""), '\\' => out.push_str("\\\\"), '\n' => out.push_str("\\n"), '\t' => out.push_str("\\t"), '\r' => out.push_str("\\r"), c if c.is_control() => out.push_str(&format!("\\u{:04x}", c as u32)), c => out.push(c), } } out.push('"'); out } #[cfg(test)] mod tests { use super::*; fn one(line: &str) -> Result { parse(&[line], 1).map(|f| f[0].value.clone()) } #[test] fn values() { assert_eq!(one("a: b"), Ok(Value::Str("b".into()))); assert_eq!(one("a: b # note"), Ok(Value::Str("b".into()))); assert_eq!(one("a: b#c"), Ok(Value::Str("b#c".into()))); assert_eq!(one("a: \"x: y\""), Ok(Value::Str("x: y".into()))); assert_eq!(one("a: 'it''s'"), Ok(Value::Str("it's".into()))); assert_eq!( one("a: [tcp/443, \"udp/53\"] # c"), Ok(Value::List(vec!["tcp/443".into(), "udp/53".into()])) ); assert_eq!(one("a: []"), Ok(Value::List(vec![]))); assert_eq!(one("a:"), Ok(Value::Absent)); assert_eq!( one("a: subnet:fd00::/64"), Ok(Value::Str("subnet:fd00::/64".into())) ); assert_eq!( parse(&["a:", " - x", " - 'y'", "b: c"], 1).unwrap()[0].value, Value::List(vec!["x".into(), "y".into()]) ); } #[test] fn refusals_name_the_line_and_field() { for (line, code) in [ ("a: &x b", rules::YAML_REFUSED), ("a: *x", rules::YAML_REFUSED), ("a: !tag b", rules::YAML_REFUSED), ("a: |", rules::YAML_REFUSED), ("a: >", rules::YAML_REFUSED), ("a: {b: c}", rules::YAML_REFUSED), ("a: [[b]]", rules::YAML_REFUSED), ("a: x: y", rules::YAML_SYNTAX), ("a: \"open", rules::YAML_SYNTAX), ("a: \"\\q\"", rules::YAML_SYNTAX), ("a: [b, ]", rules::YAML_SYNTAX), ("a: [b", rules::YAML_SYNTAX), ("a: \"b\" c", rules::YAML_SYNTAX), ] { let e = one(line).unwrap_err(); assert_eq!( (e.code, e.field.as_deref(), e.line), (code, Some("a"), 1), "{line}" ); } for (lines, code) in [ (&["\ta: b"][..], rules::YAML_REFUSED), (&[" a: b"][..], rules::YAML_REFUSED), (&["%YAML 1.2"][..], rules::YAML_REFUSED), (&["..."][..], rules::YAML_REFUSED), (&["a: b", "a: c"][..], rules::KEY_DUPLICATE), (&["a:", " - - b"][..], rules::YAML_REFUSED), (&["just text"][..], rules::YAML_SYNTAX), (&["a:b"][..], rules::YAML_SYNTAX), ] { assert_eq!(parse(lines, 1).unwrap_err().code, code, "{lines:?}"); } } #[test] fn plain_safety_round_trips() { for s in [ "person:jana", "tcp/443", "2026-11-29T23:59:59+01:00", "subnet:fd00::/64", "true", ] { assert!(is_plain_safe(s, true), "{s}"); assert_eq!(one(&format!("a: {s}")), Ok(Value::Str(s.into()))); } for s in ["", "-x", "a: b", "a #b", "[x", "x ", "'q"] { assert!(!is_plain_safe(s, false), "{s}"); assert_eq!( one(&format!("a: {}", quote(s))), Ok(Value::Str(s.into())), "{s}" ); } } }