#[cfg(test)]
mod bootstrap;
pub mod builder;
pub(crate) mod link;
pub use link::{ModuleFiles, Modules};
#[rustfmt::skip]
mod meta;
pub(crate) mod print;
mod text;
pub const BUILT_IN_BUILDERS: [&str; 7] =
["int", "float", "text", "unquote", "list", "tuple", "dict"];
pub const MAX_EXPRESSION_DEPTH: usize = 100;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Span {
pub start: u32,
pub end: u32,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Name {
pub text: String,
pub span: Span,
}
impl Name {
pub fn new(text: impl Into<String>) -> Name {
Name {
text: text.into(),
span: Span::default(),
}
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Grammar {
pub rules: Vec<Rule>,
pub ignore: Vec<Expr>,
pub word: Option<Expr>,
pub flags: Vec<Name>,
pub tabs: Option<Count>,
pub soft_keywords: Vec<Text>,
pub imports: Vec<Import>,
pub extends: Option<Text>,
pub recovers: Vec<Recover>,
pub(crate) sources: Vec<link::Source>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Count {
pub value: u32,
pub span: Span,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Text {
pub value: String,
pub span: Span,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RuleKind {
Syntactic,
Terminal,
Lexical,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Rule {
pub name: Name,
pub transparent: bool,
pub params: Vec<Name>,
pub display: Option<Text>,
pub attributes: Vec<Name>,
pub body: RuleBody,
pub span: Span,
}
impl Rule {
pub fn kind(&self) -> RuleKind {
let first = self.own_name().trim_start_matches('_').chars().next();
if first.is_some_and(|c| c.is_ascii_uppercase()) {
RuleKind::Terminal
} else if self.has_attribute("lexical") {
RuleKind::Lexical
} else {
RuleKind::Syntactic
}
}
pub fn is_underscored(&self) -> bool {
self.own_name().starts_with('_')
}
fn own_name(&self) -> &str {
self.name
.text
.rsplit_once('.')
.map_or(&self.name.text, |(_, own)| own)
}
pub fn has_attribute(&self, name: &str) -> bool {
self.attributes.iter().any(|a| a.text == name)
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum RuleBody {
Alternatives(Vec<Alternative>),
Precedence(Vec<Level>),
}
impl RuleBody {
pub(crate) fn alternatives(&self) -> impl Iterator<Item = &Alternative> {
let (alternatives, levels) = match self {
RuleBody::Alternatives(alternatives) => (alternatives.as_slice(), &[][..]),
RuleBody::Precedence(levels) => (&[][..], levels.as_slice()),
};
(alternatives.iter()).chain(levels.iter().flat_map(|level| &level.alternatives))
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Level {
pub name: Name,
pub alternatives: Vec<Alternative>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Alternative {
pub expr: Expr,
pub alias: Option<Name>,
pub builder: Option<ValueBuilder>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Expr {
pub kind: ExprKind,
pub span: Span,
}
impl Expr {
pub fn new(kind: ExprKind) -> Expr {
Expr {
kind,
span: Span::default(),
}
}
pub fn children(&self) -> Vec<&Expr> {
match &self.kind {
ExprKind::Reference { args, .. } => args.iter().collect(),
ExprKind::Sequence(items) | ExprKind::Choice(items) => items.iter().collect(),
ExprKind::Separated {
item, separator, ..
} => vec![item, separator],
ExprKind::Repeat { expr, .. }
| ExprKind::And(expr)
| ExprKind::Not(expr)
| ExprKind::Field { expr, .. }
| ExprKind::Label { expr, .. }
| ExprKind::FlagOn { expr, .. }
| ExprKind::FlagOff { expr, .. }
| ExprKind::Indent(expr)
| ExprKind::Def { expr, .. } => vec![expr],
_ => Vec::new(),
}
}
pub fn map_children(&self, f: &mut dyn FnMut(&Expr) -> Expr) -> Expr {
let mut each = |items: &[Expr]| items.iter().map(&mut *f).collect::<Vec<_>>();
let kind = match &self.kind {
ExprKind::Reference { name, args } => ExprKind::Reference {
name: name.clone(),
args: each(args),
},
ExprKind::Sequence(items) => ExprKind::Sequence(each(items)),
ExprKind::Choice(items) => ExprKind::Choice(each(items)),
ExprKind::Separated {
item,
separator,
at_least_one,
} => ExprKind::Separated {
item: Box::new(f(item)),
separator: Box::new(f(separator)),
at_least_one: *at_least_one,
},
ExprKind::Repeat { expr, min, max } => ExprKind::Repeat {
expr: Box::new(f(expr)),
min: *min,
max: *max,
},
ExprKind::And(expr) => ExprKind::And(Box::new(f(expr))),
ExprKind::Not(expr) => ExprKind::Not(Box::new(f(expr))),
ExprKind::Field { name, expr } => ExprKind::Field {
name: name.clone(),
expr: Box::new(f(expr)),
},
ExprKind::Label { expr, label } => ExprKind::Label {
expr: Box::new(f(expr)),
label: label.clone(),
},
ExprKind::FlagOn { flag, expr } => ExprKind::FlagOn {
flag: flag.clone(),
expr: Box::new(f(expr)),
},
ExprKind::FlagOff { flag, expr } => ExprKind::FlagOff {
flag: flag.clone(),
expr: Box::new(f(expr)),
},
ExprKind::Indent(expr) => ExprKind::Indent(Box::new(f(expr))),
ExprKind::Def { name, expr } => ExprKind::Def {
name: name.clone(),
expr: Box::new(f(expr)),
},
other => other.clone(),
};
Expr {
kind,
span: self.span,
}
}
pub fn contains_field(&self) -> bool {
matches!(self.kind, ExprKind::Field { .. })
|| self.children().into_iter().any(Expr::contains_field)
}
pub(crate) fn measure(&self) -> (usize, usize) {
let mut pending = vec![(self, 1)];
let (mut size, mut depth) = (0, 0);
while let Some((expr, level)) = pending.pop() {
size += 1;
depth = depth.max(level);
pending.extend(expr.children().into_iter().map(|child| (child, level + 1)));
}
(size, depth)
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum ExprKind {
Empty,
Literal {
text: String,
case_insensitive: bool,
},
Class(Class),
Any,
Reference {
name: Name,
args: Vec<Expr>,
},
Sequence(Vec<Expr>),
Choice(Vec<Expr>),
Repeat {
expr: Box<Expr>,
min: u32,
max: Option<u32>,
},
Separated {
item: Box<Expr>,
separator: Box<Expr>,
at_least_one: bool,
},
And(Box<Expr>),
Not(Box<Expr>),
Field {
name: Name,
expr: Box<Expr>,
},
Cut,
Label {
expr: Box<Expr>,
label: ErrorLabel,
},
FlagOn {
flag: Name,
expr: Box<Expr>,
},
FlagOff {
flag: Name,
expr: Box<Expr>,
},
FlagTest {
flag: Name,
negated: bool,
},
Indent(Box<Expr>),
Same,
Def {
name: Name,
expr: Box<Expr>,
},
Ref {
name: Name,
},
Error {
message: Text,
},
Inherited,
}
#[derive(Clone, Debug, PartialEq)]
pub enum ErrorLabel {
Message(Text),
Named(Name),
}
#[derive(Clone, Debug, PartialEq)]
pub struct Class {
pub negated: bool,
pub items: Vec<ClassItem>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ClassItem {
Range(char, char),
Property {
property: Property,
negated: bool,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Property {
XidStart,
XidContinue,
Alphabetic,
WhiteSpace,
Uppercase,
Lowercase,
}
impl Property {
pub const ALL: [(Property, &'static str); 6] = [
(Property::XidStart, "XID_Start"),
(Property::XidContinue, "XID_Continue"),
(Property::Alphabetic, "Alphabetic"),
(Property::WhiteSpace, "White_Space"),
(Property::Uppercase, "Uppercase"),
(Property::Lowercase, "Lowercase"),
];
pub fn from_name(name: &str) -> Option<Property> {
Property::ALL
.iter()
.find(|(_, n)| *n == name)
.map(|(p, _)| *p)
}
pub fn name(self) -> &'static str {
Property::ALL
.iter()
.find(|(p, _)| *p == self)
.map_or("", |(_, n)| n)
}
pub fn contains(self, c: char) -> bool {
match self {
Property::XidStart => unicode_ident::is_xid_start(c),
Property::XidContinue => unicode_ident::is_xid_continue(c),
Property::Alphabetic => c.is_alphabetic(),
Property::WhiteSpace => c.is_whitespace(),
Property::Uppercase => c.is_uppercase(),
Property::Lowercase => c.is_lowercase(),
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum ValueBuilder {
Name(Name),
Constant(Constant),
Call {
name: Name,
args: Vec<BuilderArg>,
},
}
#[derive(Clone, Debug, PartialEq)]
pub enum Constant {
None,
Bool(bool),
Number(String),
String(String),
}
#[derive(Clone, Debug, PartialEq)]
pub struct BuilderArg {
pub key: Option<Name>,
pub value: BuilderValue,
}
#[derive(Clone, Debug, PartialEq)]
pub enum BuilderValue {
Field(Name),
Constant(Constant),
All,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Import {
pub module: Text,
pub names: Vec<Name>,
pub prefix: Option<Name>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Recover {
pub label: Name,
pub expr: Expr,
}