1use std::collections::BTreeMap;
5
6use super::{bool_of, embedded, str_of};
7use crate::{Error, Result, Spanned, Yaml, yaml};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum TypeName {
12 String,
14 Integer,
16 Boolean,
18 List,
20 Map,
22 Object,
24 StringOrList,
26 StringOrMap,
28 Text,
31 TextOrRule,
33 Condition,
36 BooleanOrCondition,
38}
39
40impl TypeName {
41 pub fn parse(s: &str) -> Option<Self> {
43 Some(match s {
44 "string" => TypeName::String,
45 "integer" => TypeName::Integer,
46 "boolean" => TypeName::Boolean,
47 "list" => TypeName::List,
48 "map" => TypeName::Map,
49 "object" => TypeName::Object,
50 "string-or-list" => TypeName::StringOrList,
51 "string-or-map" => TypeName::StringOrMap,
52 "text" => TypeName::Text,
53 "text-or-rule" => TypeName::TextOrRule,
54 "condition" => TypeName::Condition,
55 "boolean-or-condition" => TypeName::BooleanOrCondition,
56 _ => return None,
57 })
58 }
59}
60
61#[derive(Debug, Clone, PartialEq)]
63pub struct KeyDef {
64 pub type_: TypeName,
66 pub of: Option<String>,
69 pub required: bool,
71 pub enum_: Vec<String>,
73 pub format: Option<String>,
76 pub requires_keys: Vec<String>,
78 pub requires_kind: Vec<String>,
80 pub doc: String,
82}
83
84#[derive(Debug, Clone, PartialEq, Default)]
86pub struct RuleMap {
87 pub doc: String,
89 pub keys: Vec<(String, KeyDef)>,
91 pub exactly_one_of: Vec<String>,
93 pub at_least_one_of: Vec<String>,
95 pub common: bool,
97}
98
99impl RuleMap {
100 pub fn key(&self, key: &str) -> Option<&KeyDef> {
102 self.keys.iter().find(|(k, _)| k == key).map(|(_, d)| d)
103 }
104}
105
106#[derive(Debug, Clone, PartialEq)]
109pub struct Grammar {
110 pub name: String,
113 pub version: String,
115 pub schema: RuleMap,
117 pub rules: BTreeMap<String, RuleMap>,
119 pub rule_common: RuleMap,
121 pub sections: BTreeMap<String, Spanned>,
123}
124impl Grammar {
127 pub fn rule(&self, name: &str) -> Option<&RuleMap> {
129 if name == "schema" {
130 return Some(&self.schema);
131 }
132 self.rules.get(name)
133 }
134
135 pub fn accepts_common(&self, name: &str) -> bool {
137 self.rule(name).is_some_and(|m| m.common)
138 }
139
140 pub fn section(&self, name: &str) -> Option<&Spanned> {
143 self.sections.get(name)
145 }
146
147 pub fn base(&mut self, text: &str) -> Result<()> {
159 self.transact(|g| g.lay_base(text))
161 }
162
163 fn transact(&mut self, lay: impl FnOnce(&mut Grammar) -> Result<()>) -> Result<()> {
167 let mut next = self.clone();
168 lay(&mut next)?;
169 *self = next;
170 Ok(())
171 }
172
173 fn lay_base(&mut self, text: &str) -> Result<()> {
174 let fail = |m: String| Error::Internal(format!("format grammar: {m}"));
175 let root = yaml::parse(text, 1).map_err(|e| fail(e.to_string()))?;
176 let Some(name) = root.get("grammar").and_then(|e| e.as_str()) else {
177 return Err(fail("no `grammar` name".into()));
178 };
179 let name = name.to_string();
180 match root.get("base").and_then(|e| e.as_str()) {
182 Some(base) if base == self.name => {}
183 other => {
184 return Err(fail(format!("`base` is {other:?}, not `{}`", self.name)));
185 }
186 }
187 for (key, value) in root.as_map().unwrap_or(&[]) {
188 match key.value.as_str() {
189 "grammar" | "base" | "doc" => {}
190 "version" => {
192 if let Some(v) = value.scalar_text() {
193 self.version = v;
194 }
195 }
196 "meta" => return Err(fail("`meta` is the core grammar's".into())),
197 "schema" => self.extend_schema(value, true).map_err(fail)?,
198 other => return Err(fail(format!("unknown section `{other}`"))),
200 }
201 }
202 self.check_references().map_err(fail)?;
203 self.name = name;
205 Ok(())
206 }
207
208 pub fn extend(&mut self, text: &str) -> Result<()> {
222 self.transact(|g| g.lay_extension(text))
224 }
225
226 fn lay_extension(&mut self, text: &str) -> Result<()> {
227 let fail = |m: String| Error::Internal(format!("schema extension: {m}"));
228 let root = yaml::parse(text, 1).map_err(|e| fail(e.to_string()))?;
229 if root.get("extension").and_then(|e| e.as_str()).is_none() {
230 return Err(fail("no `extension` name".into()));
231 }
232 match root.get("extends").and_then(|e| e.as_str()) {
233 Some(name) if name == self.name => {}
234 other => {
235 return Err(fail(format!("extends {other:?}, not `{}`", self.name)));
236 }
237 }
238 for (name, value) in root.as_map().unwrap_or(&[]) {
239 match name.value.as_str() {
240 "extension" | "extends" | "version" | "doc" => {}
241 "meta" => return Err(fail("`meta` is the core grammar's".into())),
242 "schema" => self.extend_schema(value, false).map_err(fail)?,
243 other if self.sections.contains_key(other) => {
245 return Err(fail(format!("section `{other}` twice")));
246 }
247 other => {
248 self.sections.insert(other.to_string(), value.clone());
249 }
250 }
251 }
252 self.check_references().map_err(fail)
253 }
254
255 fn check_references(&self) -> std::result::Result<(), String> {
259 let maps = [("schema", &self.schema), ("rule-common", &self.rule_common)]
260 .into_iter()
261 .chain(self.rules.iter().map(|(n, m)| (n.as_str(), m)));
262 for (name, map) in maps {
263 for (key, def) in &map.keys {
264 match def.of.as_deref() {
265 None | Some("string" | "integer" | "boolean" | "string-or-list") => {}
266 Some(of) if self.rule(of).is_some() => {}
267 Some(of) => {
268 return Err(format!(
269 "`{name}.{key}` holds `{of}`, which the grammar does not define"
270 ));
271 }
272 }
273 }
274 }
275 Ok(())
276 }
277
278 fn extend_schema(&mut self, node: &Spanned, format: bool) -> std::result::Result<(), String> {
282 for (name, value) in node.as_map().unwrap_or(&[]) {
283 match name.value.as_str() {
284 "keys" => extend_keys(&mut self.schema, value, "schema")?,
285 "doc" | "exactly-one-of" | "at-least-one-of" if format => {
286 add_to_map(&mut self.schema, name.value.as_str(), value);
287 }
288 "doc" | "exactly-one-of" | "at-least-one-of" | "rule-common" => {
289 return Err(format!("`schema.{}` is the core grammar's", name.value));
290 }
291 map => {
292 if let Some(core) = self.rules.get_mut(map) {
293 for (k, v) in value.as_map().unwrap_or(&[]) {
294 match k.value.as_str() {
295 "keys" => extend_keys(core, v, map)?,
296 "doc" | "exactly-one-of" | "at-least-one-of" if format => {
297 add_to_map(core, k.value.as_str(), v);
298 }
299 other => {
300 return Err(format!("`{map}.{other}` is the core grammar's"));
301 }
302 }
303 }
304 } else {
305 let added = rule_map(value).map_err(|e| e.to_string())?;
306 self.rules.insert(map.to_string(), added);
307 }
308 }
309 }
310 }
311 Ok(())
312 }
313
314 pub fn key_def(&self, name: &str, key: &str) -> Option<&KeyDef> {
316 self.rule(name).and_then(|m| m.key(key)).or_else(|| {
317 if self.accepts_common(name) {
318 self.rule_common.key(key)
319 } else {
320 None
321 }
322 })
323 }
324}
325
326fn append_doc(doc: &mut String, more: &Spanned) {
328 let more = more.as_str().unwrap_or("").trim();
329 *doc = format!("{doc} {more}").trim().to_string();
330}
331
332fn add_to_map(map: &mut RuleMap, key: &str, value: &Spanned) {
334 match key {
335 "doc" => append_doc(&mut map.doc, value),
336 "exactly-one-of" => map.exactly_one_of.extend(string_list(Some(value))),
337 _ => map.at_least_one_of.extend(string_list(Some(value))),
338 }
339}
340
341fn extend_keys(map: &mut RuleMap, keys: &Spanned, name: &str) -> std::result::Result<(), String> {
344 for (key, def) in keys.as_map().unwrap_or(&[]) {
345 let Some(core) = map.keys.iter_mut().find(|(k, _)| *k == key.value) else {
346 map.keys
347 .push((key.value.clone(), key_def(def).map_err(|e| e.to_string())?));
348 continue;
349 };
350 let core = &mut core.1;
351 for (k, v) in def.as_map().unwrap_or(&[]) {
352 match k.value.as_str() {
353 "enum" => core.enum_.extend(
354 v.as_seq()
355 .unwrap_or(&[])
356 .iter()
357 .filter_map(Spanned::scalar_text),
358 ),
359 "requires" if matches!(v.value, Yaml::Map(_)) => core.requires_kind.extend(
360 v.get("kind")
361 .and_then(Spanned::as_str_or_list)
362 .unwrap_or_default(),
363 ),
364 "doc" => append_doc(&mut core.doc, v),
365 other => {
366 return Err(format!(
367 "`{name}.{}` changes the core grammar's `{other}`",
368 key.value
369 ));
370 }
371 }
372 }
373 }
374 Ok(())
375}
376
377pub fn load_core_grammar() -> Result<Grammar> {
381 parse_grammar(embedded::grammar_text())
382}
383pub fn parse_grammar(text: &str) -> Result<Grammar> {
390 let root = yaml::parse(text, 1).map_err(|e| Error::Internal(format!("grammar: {e}")))?;
392 let name = root
393 .get("grammar")
394 .and_then(|v| v.as_str())
395 .ok_or_else(|| Error::Internal("grammar: no `grammar` name".into()))?
396 .to_string();
397 let version = root
398 .get("version")
399 .and_then(Spanned::scalar_text)
400 .ok_or_else(|| Error::Internal("grammar: no version".into()))?;
401 let schema_node = root
402 .get("schema")
403 .ok_or_else(|| Error::Internal("grammar: no schema section".into()))?;
404 let schema = rule_map(schema_node)?;
405 let mut rules = BTreeMap::new();
406 let mut rule_common = RuleMap::default();
407 for (key, value) in schema_node.as_map().unwrap_or(&[]) {
408 match key.value.as_str() {
409 "doc" | "keys" | "exactly-one-of" | "at-least-one-of" | "common" => {}
410 "rule-common" => rule_common = rule_map(value)?,
411 name => {
412 rules.insert(name.to_string(), rule_map(value)?);
413 }
414 }
415 }
416 let grammar = Grammar {
417 name,
418 version,
419 schema,
420 rules,
421 rule_common,
422 sections: BTreeMap::new(),
423 };
424 grammar
425 .check_references()
426 .map_err(|e| Error::Internal(format!("grammar: {e}")))?;
427 Ok(grammar)
428}
429
430fn rule_map(node: &Spanned) -> Result<RuleMap> {
431 let mut map = RuleMap {
432 doc: doc_of(node),
433 ..RuleMap::default()
434 };
435 if let Some(keys) = node.get("keys") {
436 for (name, def) in keys.as_map().unwrap_or(&[]) {
437 map.keys.push((name.value.clone(), key_def(def)?));
438 }
439 }
440 map.exactly_one_of = string_list(node.get("exactly-one-of"));
441 map.at_least_one_of = string_list(node.get("at-least-one-of"));
442 map.common = bool_of(node, "common");
443 Ok(map)
444}
445
446fn key_def(node: &Spanned) -> Result<KeyDef> {
447 let type_ = match node.get("type").and_then(|t| t.as_str()) {
448 Some(t) => TypeName::parse(t)
449 .ok_or_else(|| Error::Internal(format!("grammar: unknown type `{t}`")))?,
450 None => TypeName::String,
451 };
452 let mut requires_keys = Vec::new();
453 let mut requires_kind = Vec::new();
454 if let Some(r) = node.get("requires") {
455 match &r.value {
456 Yaml::Seq(_) => requires_keys = string_list(Some(r)),
457 Yaml::Map(_) => {
458 requires_kind = r
459 .get("kind")
460 .and_then(Spanned::as_str_or_list)
461 .unwrap_or_default();
462 }
463 _ => {}
464 }
465 }
466 Ok(KeyDef {
467 type_,
468 of: str_of(node, "of"),
469 required: bool_of(node, "required"),
470 enum_: node
471 .get("enum")
472 .and_then(|e| e.as_seq())
473 .map(|items| items.iter().filter_map(Spanned::scalar_text).collect())
474 .unwrap_or_default(),
475 format: str_of(node, "format"),
476 requires_keys,
477 requires_kind,
478 doc: doc_of(node),
479 })
480}
481
482fn doc_of(node: &Spanned) -> String {
484 str_of(node, "doc").unwrap_or_default().trim().to_string()
485}
486
487fn string_list(node: Option<&Spanned>) -> Vec<String> {
488 node.and_then(Spanned::as_str_or_list).unwrap_or_default()
489}
490
491#[cfg(test)]
492mod tests {
493 use super::*;
494
495 const FORMAT: &str = "grammar: fmt\nbase: tramlines\nversion: '0.2'\ndoc: A format.\nschema:\n doc: More.\n at-least-one-of: [body]\n keys:\n body:\n type: list\n of: part\n part:\n common: true\n keys:\n text:\n type: string\n frontmatter-constraint:\n exactly-one-of: [const, enum]\n keys:\n format:\n enum: [email]\n";
496
497 #[test]
499 fn loads_the_core_grammar() {
500 let g = load_core_grammar().unwrap();
501 assert_eq!(g.name, "tramlines");
502 assert_eq!(g.version, "0.1");
503 assert!(g.schema.key("line-limit").unwrap().required);
504 assert!(g.schema.key("frontmatter").is_some());
505 assert!(g.schema.key("sections").is_none());
506 assert!(
507 g.schema.at_least_one_of.is_empty(),
508 "{:?}",
509 g.schema.at_least_one_of
510 );
511 assert!(g.rule("section").is_none());
512 assert!(g.rule("frontmatter-constraint").is_some());
513 assert!(g.rule_common.key("severity").is_some());
514 }
515
516 #[test]
519 fn a_format_grammar_adds_keys_rule_maps_and_constraint_groups() {
520 let mut g = load_core_grammar().unwrap();
521 g.base(FORMAT).unwrap();
522 assert_eq!(g.name, "fmt");
523 assert_eq!(g.version, "0.2");
524 assert!(g.schema.doc.ends_with("More."));
525 assert_eq!(g.schema.at_least_one_of, vec!["body"]);
526 assert!(g.schema.key("body").is_some());
527 assert!(g.accepts_common("part"));
528 let fm = g.rule("frontmatter-constraint").unwrap();
529 assert_eq!(fm.exactly_one_of, vec!["const", "enum"]);
530 assert!(
531 fm.key("format")
532 .unwrap()
533 .enum_
534 .contains(&"email".to_string())
535 );
536 }
537
538 #[test]
540 fn a_format_grammar_that_changes_the_core_is_refused() {
541 let base = |text: &str| load_core_grammar().unwrap().base(text);
542 assert!(base("base: tramlines\n").is_err());
543 assert!(base("grammar: fmt\nbase: other\n").is_err());
544 assert!(base("grammar: fmt\nbase: tramlines\nmeta: {}\n").is_err());
545 assert!(base("grammar: fmt\nbase: tramlines\nextra: {}\n").is_err());
546 assert!(
547 base("grammar: fmt\nbase: tramlines\nschema:\n keys:\n line-limit:\n type: string\n")
548 .is_err()
549 );
550 assert!(base("grammar: fmt\nbase: tramlines\nschema:\n rule-common: {}\n").is_err());
551 }
552
553 #[test]
558 fn a_host_extension_only_adds_to_its_format_grammar() {
559 let mut g = load_core_grammar().unwrap();
560 g.base(FORMAT).unwrap();
561 let mut h = g.clone();
562 h.extend("extension: host\nextends: fmt\nschema:\n keys:\n links:\n type: list\n part:\n keys:\n text:\n doc: Also this.\nnotes:\n a: 1\n")
563 .unwrap();
564 assert!(h.schema.key("links").is_some());
565 assert!(h.section("notes").is_some());
566 let refused = |text: &str| g.clone().extend(text);
567 assert!(refused("extends: fmt\n").is_err());
568 assert!(refused("extension: host\nextends: tramlines\n").is_err());
569 assert!(refused("extension: host\nextends: fmt\nmeta: {}\n").is_err());
570 assert!(
571 refused("extension: host\nextends: fmt\nschema:\n at-least-one-of: [links]\n")
572 .is_err()
573 );
574 assert!(
575 refused(
576 "extension: host\nextends: fmt\nschema:\n part:\n exactly-one-of: [text]\n"
577 )
578 .is_err()
579 );
580 assert!(refused("extension: host\nextends: fmt\nschema:\n part:\n keys:\n text:\n type: integer\n").is_err());
581 assert!(refused("extension: host\nextends: fmt\nnotes: {}\nnotes: {}\n").is_err());
582 }
583
584 #[test]
585 fn a_grammar_whose_of_names_nothing_is_refused() {
586 let mut g = load_core_grammar().unwrap();
587 let format = "grammar: fmt\nbase: tramlines\nversion: '0.2'\nschema:\n keys:\n body:\n type: list\n of: nothing\n";
588 let before = g.clone();
589 let e = g.base(format).unwrap_err().to_string();
590 assert!(e.contains("`schema.body` holds `nothing`"), "{e}");
591 assert_eq!(g, before);
593 let core = "grammar: x\nversion: '1'\nschema:\n keys:\n a:\n type: list\n of: nothing\n";
594 assert!(parse_grammar(core).is_err());
595 }
596
597 #[test]
598 fn refuses_a_broken_grammar() {
599 assert!(parse_grammar("grammar: x\n").is_err());
600 assert!(parse_grammar("version: '1'\nschema: {}\n").is_err());
601 assert!(
602 parse_grammar("grammar: x\nversion: '1'\nschema:\n keys:\n a:\n type: nope\n")
603 .is_err()
604 );
605 assert!(parse_grammar("a: &x 1\n").is_err());
606 let g = parse_grammar("grammar: x\nversion: '1'\nschema:\n keys:\n a: {}\n").unwrap();
607 assert_eq!(g.schema.key("a").unwrap().type_, TypeName::String);
608 assert!(TypeName::parse("nope").is_none());
609 }
610}