use alloc::{borrow::Cow, string::String, vec::Vec};
use syntax_lang::Node;
use crate::{Error, Rule, check, js, json, rule::Text, sexp};
#[derive(Clone, Debug)]
pub struct Grammar {
pub(crate) name: Text,
pub(crate) rules: Vec<(Text, Rule)>,
pub(crate) extras: Option<Vec<Rule>>,
pub(crate) externals: Vec<Text>,
pub(crate) supertypes: Vec<Text>,
pub(crate) inline: Vec<Text>,
pub(crate) conflicts: Vec<Vec<Text>>,
pub(crate) word: Option<Text>,
}
impl Grammar {
#[must_use]
pub fn new(name: impl Into<Cow<'static, str>>) -> Grammar {
Grammar {
name: name.into(),
rules: Vec::new(),
extras: None,
externals: Vec::new(),
supertypes: Vec::new(),
inline: Vec::new(),
conflicts: Vec::new(),
word: None,
}
}
#[must_use]
pub fn rule(mut self, name: impl Into<Cow<'static, str>>, rule: Rule) -> Grammar {
self.rules.push((name.into(), rule));
self
}
#[must_use]
pub fn extra(mut self, rule: Rule) -> Grammar {
self.extras.get_or_insert_with(Vec::new).push(rule);
self
}
#[must_use]
pub fn external(mut self, name: impl Into<Cow<'static, str>>) -> Grammar {
self.externals.push(name.into());
self
}
#[must_use]
pub fn supertype(mut self, name: impl Into<Cow<'static, str>>) -> Grammar {
self.supertypes.push(name.into());
self
}
#[must_use]
pub fn inline(mut self, name: impl Into<Cow<'static, str>>) -> Grammar {
self.inline.push(name.into());
self
}
#[must_use]
pub fn conflict<N>(mut self, names: impl IntoIterator<Item = N>) -> Grammar
where
N: Into<Cow<'static, str>>,
{
self.conflicts
.push(names.into_iter().map(Into::into).collect());
self
}
#[must_use]
pub fn word(mut self, name: impl Into<Cow<'static, str>>) -> Grammar {
self.word = Some(name.into());
self
}
pub fn to_js(&self) -> Result<String, Error> {
let mut out = String::new();
self.write_js(&mut out)?;
Ok(out)
}
pub fn write_js(&self, out: &mut String) -> Result<(), Error> {
check::validate(self)?;
js::write(self, out);
Ok(())
}
pub fn to_json(&self) -> Result<String, Error> {
let mut out = String::new();
self.write_json(&mut out)?;
Ok(out)
}
pub fn write_json(&self, out: &mut String) -> Result<(), Error> {
check::validate(self)?;
json::write(self, out);
Ok(())
}
pub fn sexp<'n, K>(
&self,
tree: &Node<K>,
name: impl Fn(&K) -> &'n str,
) -> Result<String, Error> {
let mut out = String::new();
self.write_sexp(tree, name, &mut out)?;
Ok(out)
}
pub fn write_sexp<'n, K>(
&self,
tree: &Node<K>,
name: impl Fn(&K) -> &'n str,
out: &mut String,
) -> Result<(), Error> {
let start = out.len();
let result = sexp::write(self, tree, &name, out);
if result.is_err() {
out.truncate(start);
}
result
}
}
impl Grammar {
pub(crate) fn inline_names(&self) -> impl Iterator<Item = &Text> {
self.inline
.iter()
.enumerate()
.filter(|&(i, name)| !self.inline[..i].contains(name))
.map(|(_, name)| name)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_builder_records_settings_in_order() {
let g = Grammar::new("demo")
.rule("a", Rule::string("a"))
.rule("b", Rule::string("b"))
.extra(Rule::pattern(r"\s"))
.external("ext")
.supertype("_s")
.inline("_i")
.conflict(["a", "b"])
.word("b")
.word("a");
let names: Vec<&str> = g.rules.iter().map(|(n, _)| &**n).collect();
assert_eq!(names, ["a", "b"]);
assert_eq!(g.extras.as_ref().map(Vec::len), Some(1));
assert_eq!(g.externals, ["ext"]);
assert_eq!(g.supertypes, ["_s"]);
assert_eq!(g.inline, ["_i"]);
assert_eq!(g.conflicts, [["a", "b"]]);
assert_eq!(g.word.as_deref(), Some("a"));
}
#[test]
fn test_public_types_are_send_and_sync() {
fn shareable<T: Send + Sync>() {}
shareable::<Grammar>();
shareable::<Rule>();
shareable::<Error>();
}
#[test]
fn test_extras_default_to_none_until_added() {
assert!(Grammar::new("x").extras.is_none());
}
#[test]
fn test_write_js_leaves_buffer_untouched_on_error() {
let mut out = String::from("keep");
let result = Grammar::new("x").write_js(&mut out);
assert_eq!(result, Err(Error::NoRules));
assert_eq!(out, "keep");
}
}