use std::cell::RefCell;
use std::fmt;
use indexmap::{IndexMap, IndexSet};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct SrcSpan {
pub s: usize,
pub e: usize,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub r: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub c: Option<usize>,
}
impl SrcSpan {
pub fn new(s: usize, e: usize) -> Self {
Self {
s,
e,
r: None,
c: None,
}
}
pub fn at(s: usize, e: usize, r: usize, c: usize) -> Self {
Self {
s,
e,
r: Some(r),
c: Some(c),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Element {
#[serde(flatten)]
pub kind: Kind,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sp: Option<SrcSpan>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum Kind {
Term {
literal: String,
#[serde(
default,
rename = "caseSensitive",
skip_serializing_if = "Option::is_none"
)]
case_sensitive: Option<bool>,
#[serde(default, rename = "tokenName", skip_serializing_if = "Option::is_none")]
token_name: Option<String>,
},
Ref {
name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
debt: Option<IndexMap<String, i64>>,
},
Token { name: String },
Prose { text: String },
Regex { pattern: String, flags: String },
Opt { inner: Box<Element> },
Star {
inner: Box<Element>,
#[serde(default, rename = "debtGuard", skip_serializing_if = "Option::is_none")]
debt_guard: Option<String>,
},
Plus { inner: Box<Element> },
Rep {
min: usize,
#[serde(default, deserialize_with = "deserialize_max")]
max: Option<usize>,
inner: Box<Element>,
},
Group { alts: Vec<Sequence> },
}
fn deserialize_max<'de, D>(deserializer: D) -> Result<Option<usize>, D::Error>
where
D: serde::Deserializer<'de>,
{
let value: Option<f64> = Option::deserialize(deserializer)?;
Ok(match value {
None => None,
Some(n) if n.is_finite() && n >= 0.0 => Some(n as usize),
Some(_) => None,
})
}
pub type Sequence = Vec<Element>;
impl Element {
fn of(kind: Kind) -> Self {
Self { kind, sp: None }
}
pub fn term(literal: impl Into<String>) -> Self {
Self::of(Kind::Term {
literal: literal.into(),
case_sensitive: None,
token_name: None,
})
}
pub fn term_cs(literal: impl Into<String>, case_sensitive: bool) -> Self {
Self::of(Kind::Term {
literal: literal.into(),
case_sensitive: Some(case_sensitive),
token_name: None,
})
}
pub fn reference(name: impl Into<String>) -> Self {
Self::of(Kind::Ref {
name: name.into(),
debt: None,
})
}
pub fn token(name: impl Into<String>) -> Self {
Self::of(Kind::Token { name: name.into() })
}
pub fn prose(text: impl Into<String>) -> Self {
Self::of(Kind::Prose { text: text.into() })
}
pub fn regex(pattern: impl Into<String>, flags: impl Into<String>) -> Self {
Self::of(Kind::Regex {
pattern: pattern.into(),
flags: flags.into(),
})
}
pub fn opt(inner: Element) -> Self {
Self::of(Kind::Opt {
inner: Box::new(inner),
})
}
pub fn star(inner: Element) -> Self {
Self::of(Kind::Star {
inner: Box::new(inner),
debt_guard: None,
})
}
pub fn plus(inner: Element) -> Self {
Self::of(Kind::Plus {
inner: Box::new(inner),
})
}
pub fn rep(min: usize, max: Option<usize>, inner: Element) -> Self {
Self::of(Kind::Rep {
min,
max,
inner: Box::new(inner),
})
}
pub fn group(alts: Vec<Sequence>) -> Self {
Self::of(Kind::Group { alts })
}
pub fn with_span(mut self, sp: SrcSpan) -> Self {
self.sp = Some(sp);
self
}
pub fn ref_name(&self) -> Option<&str> {
match &self.kind {
Kind::Ref { name, .. } => Some(name),
_ => None,
}
}
pub fn is_ref(&self) -> bool {
matches!(self.kind, Kind::Ref { .. })
}
pub fn is_ref_to(&self, name: &str) -> bool {
matches!(&self.kind, Kind::Ref { name: n, .. } if n == name)
}
pub fn literal(&self) -> Option<&str> {
match &self.kind {
Kind::Term { literal, .. } => Some(literal),
_ => None,
}
}
pub fn is_terminal(&self) -> bool {
matches!(
self.kind,
Kind::Term { .. } | Kind::Token { .. } | Kind::Regex { .. }
)
}
pub(crate) fn inner(&self) -> Option<&Element> {
match &self.kind {
Kind::Opt { inner }
| Kind::Star { inner, .. }
| Kind::Plus { inner }
| Kind::Rep { inner, .. } => Some(inner),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum NodeKind {
#[default]
User,
Core,
Helper,
}
impl NodeKind {
pub fn as_str(self) -> &'static str {
match self {
NodeKind::User => "user",
NodeKind::Core => "core",
NodeKind::Helper => "helper",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ValueAnnotation {
pub kind: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub members: Vec<String>,
}
impl ValueAnnotation {
pub fn object(members: impl IntoIterator<Item = impl Into<String>>) -> Self {
Self {
kind: "object".into(),
members: members.into_iter().map(Into::into).collect(),
}
}
pub fn array() -> Self {
Self {
kind: "array".into(),
members: Vec::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProbeDispatchSpec {
#[serde(rename = "probeRule")]
pub probe_rule: String,
pub disambiguator: Element,
#[serde(rename = "withBranch")]
pub with_branch: String,
#[serde(rename = "noBranch")]
pub no_branch: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProbeHelperSpec {
#[serde(rename = "vocabElements")]
pub vocab_elements: Vec<Element>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TailRepeatSpec {
pub sep: Sequence,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Production {
pub name: String,
pub alts: Vec<Sequence>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub incremental: bool,
#[serde(default, rename = "nodeKind")]
pub node_kind: NodeKind,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub origin: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sp: Option<SrcSpan>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<ValueAnnotation>,
#[serde(
default,
rename = "tailRepeat",
skip_serializing_if = "Option::is_none"
)]
pub tail_repeat: Option<TailRepeatSpec>,
#[serde(
default,
rename = "repeatHelper",
skip_serializing_if = "std::ops::Not::not"
)]
pub repeat_helper: bool,
#[serde(default, rename = "debtGuard", skip_serializing_if = "Option::is_none")]
pub debt_guard: Option<String>,
#[serde(default, rename = "debtOwed", skip_serializing_if = "Option::is_none")]
pub debt_owed: Option<Vec<String>>,
#[serde(
default,
rename = "probeDispatch",
skip_serializing_if = "Option::is_none"
)]
pub probe_dispatch: Option<ProbeDispatchSpec>,
#[serde(
default,
rename = "probeHelper",
skip_serializing_if = "Option::is_none"
)]
pub probe_helper: Option<ProbeHelperSpec>,
}
impl Production {
pub fn new(name: impl Into<String>, alts: Vec<Sequence>) -> Self {
Self {
name: name.into(),
alts,
..Default::default()
}
}
pub(crate) fn rebuilt(&self, alts: Vec<Sequence>) -> Self {
Self {
name: self.name.clone(),
alts,
node_kind: self.node_kind,
origin: self.origin.clone(),
sp: self.sp,
value: self.value.clone(),
..Default::default()
}
}
pub(crate) fn helper(name: impl Into<String>, alts: Vec<Sequence>, origin: &str) -> Self {
Self {
name: name.into(),
alts,
node_kind: NodeKind::Helper,
origin: Some(origin.to_string()),
..Default::default()
}
}
}
pub fn origin_of(prod: &Production) -> &str {
prod.origin.as_deref().unwrap_or(&prod.name)
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AmbiguityReport {
pub rule: String,
#[serde(rename = "altIdx")]
pub alt_idx: usize,
#[serde(rename = "optIdx")]
pub opt_idx: usize,
pub reason: String,
pub resolved: bool,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Grammar {
pub productions: Vec<Production>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub ambiguities: Vec<AmbiguityReport>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub remove: Vec<String>,
#[serde(
default,
rename = "clearAll",
skip_serializing_if = "std::ops::Not::not"
)]
pub clear_all: bool,
}
impl Grammar {
pub fn new(productions: Vec<Production>) -> Self {
Self {
productions,
..Default::default()
}
}
pub(crate) fn find(&self, name: &str) -> Option<&Production> {
self.productions.iter().find(|p| p.name == name)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConvertOptions {
pub start: Option<String>,
pub tag: Option<String>,
pub builtins: bool,
pub marks: bool,
pub word_keywords: bool,
pub provenance: bool,
pub token_classes: bool,
}
impl Default for ConvertOptions {
fn default() -> Self {
Self {
start: None,
tag: None,
builtins: false,
marks: false,
word_keywords: false,
provenance: true,
token_classes: false,
}
}
}
impl ConvertOptions {
pub fn tag(tag: impl Into<String>) -> Self {
Self {
tag: Some(tag.into()),
..Default::default()
}
}
pub fn start(mut self, start: impl Into<String>) -> Self {
self.start = Some(start.into());
self
}
pub fn builtins(mut self, on: bool) -> Self {
self.builtins = on;
self
}
pub fn marks(mut self, on: bool) -> Self {
self.marks = on;
self
}
pub fn word_keywords(mut self, on: bool) -> Self {
self.word_keywords = on;
self
}
pub fn provenance(mut self, on: bool) -> Self {
self.provenance = on;
self
}
pub fn token_classes(mut self, on: bool) -> Self {
self.token_classes = on;
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EmitError {
pub message: String,
pub rule: Option<String>,
pub sp: Option<SrcSpan>,
}
impl EmitError {
pub fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
rule: None,
sp: None,
}
}
pub fn at(message: impl Into<String>, rule: &str, sp: Option<SrcSpan>) -> Self {
Self {
message: message.into(),
rule: Some(rule.to_string()),
sp,
}
}
}
impl fmt::Display for EmitError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for EmitError {}
thread_local! {
static DIAG_NAME: RefCell<String> = RefCell::new("bnf".to_string());
}
pub fn diag_name() -> String {
DIAG_NAME.with(|name| name.borrow().clone())
}
pub(crate) fn set_diag_name(tag: &str) {
DIAG_NAME.with(|name| *name.borrow_mut() = tag.to_string());
}
pub const MAX_ELEMENT_DEPTH: usize = 128;
pub(crate) fn check_element_depth(grammar: &Grammar) -> Result<(), EmitError> {
for prod in &grammar.productions {
let mut roots: Vec<&Element> = Vec::new();
for alt in &prod.alts {
roots.extend(alt.iter());
}
if let Some(tail) = &prod.tail_repeat {
roots.extend(tail.sep.iter());
}
if let Some(helper) = &prod.probe_helper {
roots.extend(helper.vocab_elements.iter());
}
let mut stack: Vec<(&Element, usize)> = roots.into_iter().map(|el| (el, 1)).collect();
while let Some((el, depth)) = stack.pop() {
if depth > MAX_ELEMENT_DEPTH {
return Err(EmitError::at(
format!(
"{}: rule '{}' nests elements more than {} deep, which is \
past what this compiler will walk. Split the \
rule into named rules.",
diag_name(),
prod.name,
MAX_ELEMENT_DEPTH
),
&prod.name,
prod.sp,
));
}
match &el.kind {
Kind::Opt { inner }
| Kind::Star { inner, .. }
| Kind::Plus { inner }
| Kind::Rep { inner, .. } => stack.push((inner, depth + 1)),
Kind::Group { alts } => {
for alt in alts {
for inner in alt.iter() {
stack.push((inner, depth + 1));
}
}
}
_ => {}
}
}
}
Ok(())
}
pub const BUILTIN_TOKENS: [(&str, &str); 4] =
[("TX", "#TX"), ("NR", "#NR"), ("ST", "#ST"), ("VL", "#VL")];
pub fn builtin_token(name: &str) -> Option<&'static str> {
BUILTIN_TOKENS
.iter()
.find(|(bare, _)| *bare == name)
.map(|(_, token)| *token)
}
pub const REMOVE_PROSE: &str = "remove";
pub const REMOVE_ALL: &str = "all";
pub fn is_prose_name(name: &str) -> bool {
name.starts_with('<') && name.ends_with('>')
}
pub fn tokens_in(alt: &[Element], out: &mut IndexSet<String>) {
for el in alt {
match &el.kind {
Kind::Token { name, .. } => {
out.insert(name.clone());
}
Kind::Opt { inner }
| Kind::Star { inner, .. }
| Kind::Plus { inner }
| Kind::Rep { inner, .. } => tokens_in(std::slice::from_ref(inner), out),
Kind::Group { alts } => {
for a in alts {
tokens_in(a, out);
}
}
_ => {}
}
}
}
pub fn refs_in(alt: &[Element], out: &mut IndexSet<String>) {
for el in alt {
match &el.kind {
Kind::Ref { name, .. } => {
out.insert(name.clone());
}
Kind::Opt { inner }
| Kind::Star { inner, .. }
| Kind::Plus { inner }
| Kind::Rep { inner, .. } => refs_in(std::slice::from_ref(inner), out),
Kind::Group { alts } => {
for a in alts {
refs_in(a, out);
}
}
_ => {}
}
}
}
pub fn is_effectively_case_sensitive(literal: &str, case_sensitive: Option<bool>) -> bool {
if case_sensitive == Some(true) {
return true;
}
!literal.bytes().any(|b| b.is_ascii_alphabetic())
}
pub fn term_key(literal: &str, case_sensitive: Option<bool>) -> String {
let prefix = if is_effectively_case_sensitive(literal, case_sensitive) {
"cs:"
} else {
"ci:"
};
format!("{prefix}{literal}")
}
pub(crate) fn term_key_of(el: &Element) -> String {
match &el.kind {
Kind::Term {
literal,
case_sensitive,
..
} => term_key(literal, *case_sensitive),
_ => unreachable!("term_key_of on a non-term element"),
}
}
pub(crate) fn regex_key(pattern: &str, flags: &str) -> String {
format!("/{pattern}/{flags}")
}
pub fn escape_regexp(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
if matches!(
c,
'\\' | '^' | '$' | '.' | '*' | '+' | '?' | '(' | ')' | '[' | ']' | '{' | '}' | '|'
) {
out.push('\\');
}
out.push(c);
}
out
}