synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-crumb / src / yaml.rs
| 1 | //! Strict line reader for the D3 YAML-like `schema: "crumb/v1"` dialect. |
| 2 | //! |
| 3 | //! This is not a YAML parser. It accepts exactly the shape found in the |
| 4 | //! Synapse repository root `.crumb` (the only known instance; no writer tool is |
| 5 | //! known): top-level `key: "string"` lines and one `components:` list whose |
| 6 | //! items carry exactly `name`, `path`, and `role` as quoted strings. Blank lines |
| 7 | //! and `#` comment lines at column 0 are allowed. Everything else is refused. |
| 8 | |
| 9 | use std::collections::BTreeMap; |
| 10 | |
| 11 | /// Required value of the `schema` key for this dialect. |
| 12 | pub const YAML_V1_SCHEMA: &str = "crumb/v1"; |
| 13 | |
| 14 | /// One entry of the `components:` list. |
| 15 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 16 | pub struct YamlComponent { |
| 17 | pub name: String, |
| 18 | pub path: String, |
| 19 | pub role: String, |
| 20 | } |
| 21 | |
| 22 | /// A parsed D3 document. |
| 23 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 24 | pub struct YamlCrumbV1 { |
| 25 | /// Top-level scalar keys other than `schema`, in key order. |
| 26 | pub fields: BTreeMap<String, String>, |
| 27 | pub components: Vec<YamlComponent>, |
| 28 | } |
| 29 | |
| 30 | impl YamlCrumbV1 { |
| 31 | pub fn summary(&self) -> Option<&str> { |
| 32 | self.fields.get("summary").map(String::as_str) |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | /// Why a D3 document was refused. `line` is 1-based. |
| 37 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 38 | pub enum YamlError { |
| 39 | /// A line does not match the accepted shape. |
| 40 | Syntax { line: usize }, |
| 41 | /// A key appears twice at the same level. |
| 42 | DuplicateKey { line: usize }, |
| 43 | /// A component item lacks one of `name`, `path`, `role`. |
| 44 | ComponentIncomplete { line: usize }, |
| 45 | /// `schema` is present but is not `"crumb/v1"`. |
| 46 | UnsupportedSchema, |
| 47 | } |
| 48 | |
| 49 | /// Does the first meaningful line start a D3 document (`schema:` at column 0)? |
| 50 | /// Lines end at `\n` or `\r\n`, as in [`parse`]. |
| 51 | pub fn looks_like_yaml_v1(text: &str) -> bool { |
| 52 | text.lines() |
| 53 | .find(|l| !is_blank_or_comment(l)) |
| 54 | .is_some_and(|l| l.starts_with("schema:")) |
| 55 | } |
| 56 | |
| 57 | fn is_blank_or_comment(line: &str) -> bool { |
| 58 | line.trim_matches(' ').is_empty() || line.starts_with('#') |
| 59 | } |
| 60 | |
| 61 | fn is_key(k: &str) -> bool { |
| 62 | let mut cs = k.chars(); |
| 63 | matches!(cs.next(), Some('a'..='z' | '_')) |
| 64 | && cs.all(|c| matches!(c, 'a'..='z' | '0'..='9' | '_')) |
| 65 | } |
| 66 | |
| 67 | /// Parse `"..."` occupying the whole of `s`; only `\"` and `\\` escapes. |
| 68 | fn quoted(s: &str) -> Option<String> { |
| 69 | let inner = s.strip_prefix('"')?.strip_suffix('"')?; |
| 70 | let mut out = String::with_capacity(inner.len()); |
| 71 | let mut chars = inner.chars(); |
| 72 | while let Some(c) = chars.next() { |
| 73 | match c { |
| 74 | '\\' => match chars.next()? { |
| 75 | '"' => out.push('"'), |
| 76 | '\\' => out.push('\\'), |
| 77 | _ => return None, |
| 78 | }, |
| 79 | '"' => return None, |
| 80 | c if c.is_control() => return None, |
| 81 | c => out.push(c), |
| 82 | } |
| 83 | } |
| 84 | Some(out) |
| 85 | } |
| 86 | |
| 87 | /// Split `key: "value"` (exact single space after the colon). |
| 88 | fn key_value(s: &str) -> Option<(&str, String)> { |
| 89 | let (k, rest) = s.split_once(": ")?; |
| 90 | if !is_key(k) { |
| 91 | return None; |
| 92 | } |
| 93 | Some((k, quoted(rest)?)) |
| 94 | } |
| 95 | |
| 96 | #[derive(Default)] |
| 97 | struct Partial { |
| 98 | name: Option<String>, |
| 99 | path: Option<String>, |
| 100 | role: Option<String>, |
| 101 | line: usize, |
| 102 | } |
| 103 | |
| 104 | impl Partial { |
| 105 | fn set(&mut self, k: &str, v: String, line: usize) -> Result<(), YamlError> { |
| 106 | let slot = match k { |
| 107 | "name" => &mut self.name, |
| 108 | "path" => &mut self.path, |
| 109 | "role" => &mut self.role, |
| 110 | _ => return Err(YamlError::Syntax { line }), |
| 111 | }; |
| 112 | if slot.is_some() { |
| 113 | return Err(YamlError::DuplicateKey { line }); |
| 114 | } |
| 115 | *slot = Some(v); |
| 116 | Ok(()) |
| 117 | } |
| 118 | |
| 119 | fn finish(self) -> Result<YamlComponent, YamlError> { |
| 120 | match (self.name, self.path, self.role) { |
| 121 | (Some(name), Some(path), Some(role)) => Ok(YamlComponent { name, path, role }), |
| 122 | _ => Err(YamlError::ComponentIncomplete { line: self.line }), |
| 123 | } |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | /// Parse a D3 document. The caller has already checked [`looks_like_yaml_v1`]. |
| 128 | pub fn parse(text: &str) -> Result<YamlCrumbV1, YamlError> { |
| 129 | let mut fields = BTreeMap::new(); |
| 130 | let mut schema: Option<String> = None; |
| 131 | let mut components: Option<Vec<YamlComponent>> = None; |
| 132 | let mut in_components = false; |
| 133 | let mut current: Option<Partial> = None; |
| 134 | |
| 135 | // Same line splitting as [`looks_like_yaml_v1`]: `\n` or `\r\n` ends a line, so a CRLF file |
| 136 | // parses exactly like its LF form. A bare `\r` elsewhere stays in the line and is refused. |
| 137 | for (idx, line) in text.lines().enumerate() { |
| 138 | let n = idx + 1; |
| 139 | if is_blank_or_comment(line) { |
| 140 | continue; |
| 141 | } |
| 142 | if let Some(item) = line.strip_prefix(" - ") { |
| 143 | if !in_components { |
| 144 | return Err(YamlError::Syntax { line: n }); |
| 145 | } |
| 146 | if let Some(done) = current.take() { |
| 147 | components.get_or_insert_with(Vec::new).push(done.finish()?); |
| 148 | } |
| 149 | let (k, v) = key_value(item).ok_or(YamlError::Syntax { line: n })?; |
| 150 | let mut p = Partial { |
| 151 | line: n, |
| 152 | ..Partial::default() |
| 153 | }; |
| 154 | p.set(k, v, n)?; |
| 155 | current = Some(p); |
| 156 | continue; |
| 157 | } |
| 158 | if let Some(cont) = line.strip_prefix(" ") { |
| 159 | let p = current.as_mut().ok_or(YamlError::Syntax { line: n })?; |
| 160 | let (k, v) = key_value(cont).ok_or(YamlError::Syntax { line: n })?; |
| 161 | p.set(k, v, n)?; |
| 162 | continue; |
| 163 | } |
| 164 | // Top-level line ends any open component list. |
| 165 | if let Some(done) = current.take() { |
| 166 | components.get_or_insert_with(Vec::new).push(done.finish()?); |
| 167 | } |
| 168 | in_components = false; |
| 169 | if line == "components:" { |
| 170 | if components.is_some() { |
| 171 | return Err(YamlError::DuplicateKey { line: n }); |
| 172 | } |
| 173 | components = Some(Vec::new()); |
| 174 | in_components = true; |
| 175 | continue; |
| 176 | } |
| 177 | let (k, v) = key_value(line).ok_or(YamlError::Syntax { line: n })?; |
| 178 | if k == "components" { |
| 179 | return Err(YamlError::Syntax { line: n }); |
| 180 | } |
| 181 | if k == "schema" { |
| 182 | if schema.is_some() { |
| 183 | return Err(YamlError::DuplicateKey { line: n }); |
| 184 | } |
| 185 | schema = Some(v); |
| 186 | } else if fields.insert(k.to_string(), v).is_some() { |
| 187 | return Err(YamlError::DuplicateKey { line: n }); |
| 188 | } |
| 189 | } |
| 190 | if let Some(done) = current.take() { |
| 191 | components.get_or_insert_with(Vec::new).push(done.finish()?); |
| 192 | } |
| 193 | match schema.as_deref() { |
| 194 | Some(YAML_V1_SCHEMA) => Ok(YamlCrumbV1 { |
| 195 | fields, |
| 196 | components: components.unwrap_or_default(), |
| 197 | }), |
| 198 | Some(_) => Err(YamlError::UnsupportedSchema), |
| 199 | None => Err(YamlError::Syntax { line: 1 }), |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | #[cfg(test)] |
| 204 | mod tests { |
| 205 | use super::*; |
| 206 | |
| 207 | #[test] |
| 208 | fn parses_synapse_root_shape() { |
| 209 | let doc = "schema: \"crumb/v1\"\nrepository: \"aien-spark/synapse\"\nsummary: \"S \\\"q\\\"\"\ncomponents:\n - name: \"a\"\n path: \"crates/a\"\n role: \"A\"\n - name: \"b\"\n path: \"crates/b\"\n role: \"B\"\n"; |
| 210 | assert!(looks_like_yaml_v1(doc)); |
| 211 | let y = parse(doc).unwrap(); |
| 212 | assert_eq!(y.summary(), Some("S \"q\"")); |
| 213 | assert_eq!(y.fields.get("repository").unwrap(), "aien-spark/synapse"); |
| 214 | assert_eq!(y.components.len(), 2); |
| 215 | assert_eq!(y.components[1].path, "crates/b"); |
| 216 | } |
| 217 | |
| 218 | #[test] |
| 219 | fn refuses_off_shape_documents() { |
| 220 | let cases: [(&str, YamlError); 6] = [ |
| 221 | ("schema: \"crumb/v2\"\n", YamlError::UnsupportedSchema), |
| 222 | ( |
| 223 | "schema: \"crumb/v1\"\nsummary: bare\n", |
| 224 | YamlError::Syntax { line: 2 }, |
| 225 | ), |
| 226 | ( |
| 227 | "schema: \"crumb/v1\"\nsummary: \"a\"\nsummary: \"b\"\n", |
| 228 | YamlError::DuplicateKey { line: 3 }, |
| 229 | ), |
| 230 | ( |
| 231 | "schema: \"crumb/v1\"\ncomponents:\n - name: \"a\"\n path: \"p\"\n", |
| 232 | YamlError::ComponentIncomplete { line: 3 }, |
| 233 | ), |
| 234 | ( |
| 235 | "schema: \"crumb/v1\"\ncomponents:\n - name: \"a\"\n owner: \"x\"\n", |
| 236 | YamlError::Syntax { line: 4 }, |
| 237 | ), |
| 238 | ( |
| 239 | "schema: \"crumb/v1\"\n - name: \"a\"\n", |
| 240 | YamlError::Syntax { line: 2 }, |
| 241 | ), |
| 242 | ]; |
| 243 | for (doc, want) in cases { |
| 244 | assert_eq!(parse(doc), Err(want), "{doc:?}"); |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | #[test] |
| 249 | fn crlf_parses_like_lf_and_bare_cr_is_refused() { |
| 250 | let lf = "schema: \"crumb/v1\"\nsummary: \"s\"\ncomponents:\n - name: \"a\"\n path: \"p\"\n role: \"r\"\n"; |
| 251 | let crlf = lf.replace('\n', "\r\n"); |
| 252 | assert!(looks_like_yaml_v1(&crlf)); |
| 253 | assert_eq!(parse(&crlf), parse(lf)); |
| 254 | assert!(parse(lf).is_ok()); |
| 255 | let bare_cr = "schema: \"crumb/v1\"\nsummary: \"s\"\r\rnext: \"x\"\n"; |
| 256 | assert!(looks_like_yaml_v1(bare_cr)); |
| 257 | assert_eq!(parse(bare_cr), Err(YamlError::Syntax { line: 2 })); |
| 258 | } |
| 259 | } |