use std::cell::RefCell;
use std::collections::BTreeMap;
use std::fmt;
use std::rc::Rc;
use std::sync::Arc;
use indexmap::IndexMap;
use serde_json::{json, Map as JsonMap, Value as JsonValue};
use tabnas::{
ActionError, Context, GrammarSetting, GrammarSpec, Plugin, PluginError, Rule, RuleSnapshot,
Tabnas, Tin, Token, Value,
};
pub const VERSION: &str = "0.5.10";
const DEFAULT_OPEN_RULES: &str = "val";
const DEFAULT_CLOSE_RULES: &str = "list,elem,map,pair";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DirectiveError(pub String);
impl fmt::Display for DirectiveError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
impl std::error::Error for DirectiveError {}
impl From<PluginError> for DirectiveError {
fn from(error: PluginError) -> Self {
Self(error.0)
}
}
impl From<DirectiveError> for PluginError {
fn from(error: DirectiveError) -> Self {
Self(error.0)
}
}
pub type ActionFn = Arc<dyn Fn(&mut Rule, &mut Context) -> Result<(), ActionError> + Send + Sync>;
pub type TokenActionFn =
Arc<dyn Fn(&mut Rule, &mut Context) -> Result<Option<Token>, ActionError> + Send + Sync>;
pub type ConditionFn = Arc<dyn Fn(&mut Rule, &mut Context) -> bool + Send + Sync>;
pub type CustomFn = Arc<dyn Fn(&mut Tabnas, &DirectiveConfig) + Send + Sync>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DirectiveConfig {
pub open: Tin,
pub close: Option<Tin>,
pub name: String,
}
pub fn set_node(rule: &mut Rule, value: Value) {
rule.node = Rc::new(RefCell::new(value));
}
#[derive(Clone, Default)]
pub enum DirectiveAction {
#[default]
None,
Call(ActionFn),
Token(TokenActionFn),
Path(String),
}
impl fmt::Debug for DirectiveAction {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::None => formatter.write_str("DirectiveAction::None"),
Self::Call(_) => formatter.write_str("DirectiveAction::Call(<function>)"),
Self::Token(_) => formatter.write_str("DirectiveAction::Token(<function>)"),
Self::Path(path) => write!(formatter, "DirectiveAction::Path({path:?})"),
}
}
}
impl DirectiveAction {
fn run(&self, rule: &mut Rule, context: &mut Context) -> Result<Option<Token>, ActionError> {
match self {
Self::None => Ok(None),
Self::Call(action) => action(rule, context).map(|()| None),
Self::Token(action) => action(rule, context),
Self::Path(path) => {
let value = option_prop(context, path);
set_node(rule, value);
Ok(None)
}
}
}
}
fn option_prop(context: &Context, path: &str) -> Value {
let mut parts = path.split('.');
let Some(head) = parts.next() else {
return Value::Undefined;
};
let mut current = match context.options.plugin.get(&head.to_lowercase()) {
Some(value) => value.clone(),
None => return Value::Undefined,
};
for part in parts {
let Value::Object(map) = current else {
return Value::Undefined;
};
current = match map.get(part) {
Some(value) => value.clone(),
None => return Value::Undefined,
};
}
current
}
#[derive(Clone, Default)]
pub struct RuleMod {
pub c: Option<ConditionFn>,
}
impl RuleMod {
pub fn new() -> Self {
Self::default()
}
pub fn when(
condition: impl Fn(&mut Rule, &mut Context) -> bool + Send + Sync + 'static,
) -> Self {
Self {
c: Some(Arc::new(condition)),
}
}
}
impl fmt::Debug for RuleMod {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("RuleMod")
.field("c", &self.c.as_ref().map(|_| "<function>"))
.finish()
}
}
#[derive(Clone, Debug, Default)]
pub struct RulesOption {
pub open: BTreeMap<String, RuleMod>,
pub close: BTreeMap<String, RuleMod>,
}
impl RulesOption {
pub fn new() -> Self {
Self::default()
}
pub fn open_rules(mut self, rules: &str) -> Self {
self.open = parse_rule_list(rules);
self
}
pub fn close_rules(mut self, rules: &str) -> Self {
self.close = parse_rule_list(rules);
self
}
pub fn open_rule(mut self, name: impl Into<String>, modification: RuleMod) -> Self {
self.open.insert(name.into(), modification);
self
}
pub fn close_rule(mut self, name: impl Into<String>, modification: RuleMod) -> Self {
self.close.insert(name.into(), modification);
self
}
}
fn parse_rule_list(rules: &str) -> BTreeMap<String, RuleMod> {
rules
.split(',')
.map(str::trim)
.filter(|name| !name.is_empty())
.map(|name| (name.to_string(), RuleMod::new()))
.collect()
}
#[derive(Clone)]
pub struct DirectiveOptions {
pub name: String,
pub open: String,
pub close: Option<String>,
pub action: DirectiveAction,
pub rules: Option<RulesOption>,
pub custom: Option<CustomFn>,
}
impl fmt::Debug for DirectiveOptions {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("DirectiveOptions")
.field("name", &self.name)
.field("open", &self.open)
.field("close", &self.close)
.field("action", &self.action)
.field("rules", &self.rules)
.field("custom", &self.custom.as_ref().map(|_| "<function>"))
.finish()
}
}
impl DirectiveOptions {
pub fn new(name: impl Into<String>, open: impl Into<String>) -> Self {
Self {
name: name.into(),
open: open.into(),
close: None,
action: DirectiveAction::None,
rules: None,
custom: None,
}
}
pub fn with_close(mut self, close: impl Into<String>) -> Self {
self.close = Some(close.into());
self
}
pub fn with_action(
mut self,
action: impl Fn(&mut Rule, &mut Context) -> Result<(), ActionError> + Send + Sync + 'static,
) -> Self {
self.action = DirectiveAction::Call(Arc::new(action));
self
}
pub fn with_token_action(
mut self,
action: impl Fn(&mut Rule, &mut Context) -> Result<Option<Token>, ActionError>
+ Send
+ Sync
+ 'static,
) -> Self {
self.action = DirectiveAction::Token(Arc::new(action));
self
}
pub fn with_action_path(mut self, path: impl Into<String>) -> Self {
self.action = DirectiveAction::Path(path.into());
self
}
pub fn with_rules(mut self, rules: RulesOption) -> Self {
self.rules = Some(rules);
self
}
pub fn with_custom(
mut self,
custom: impl Fn(&mut Tabnas, &DirectiveConfig) + Send + Sync + 'static,
) -> Self {
self.custom = Some(Arc::new(custom));
self
}
fn close_source(&self) -> Option<&str> {
self.close.as_deref().filter(|close| !close.is_empty())
}
fn resolved_rules(&self) -> (BTreeMap<String, RuleMod>, BTreeMap<String, RuleMod>) {
match &self.rules {
Some(rules) => (rules.open.clone(), rules.close.clone()),
None => (
parse_rule_list(DEFAULT_OPEN_RULES),
parse_rule_list(DEFAULT_CLOSE_RULES),
),
}
}
}
pub fn plugin(options: DirectiveOptions) -> Plugin {
Plugin::new("Directive", move |parser, _plugin_options| {
install(parser, &options).map_err(PluginError::from)
})
}
pub fn apply(parser: &mut Tabnas, options: DirectiveOptions) -> Result<(), DirectiveError> {
parser
.use_plugin(plugin(options), None)
.map(|_| ())
.map_err(DirectiveError::from)
}
fn install(parser: &mut Tabnas, options: &DirectiveOptions) -> Result<(), DirectiveError> {
let name = options.name.clone();
let open = options.open.clone();
let close = options.close_source().map(str::to_string);
let (open_rules, close_rules) = options.resolved_rules();
if name.is_empty() || name.chars().any(char::is_whitespace) {
return Err(DirectiveError(format!(
"Directive name must be non-empty and contain no whitespace: {name:?}"
)));
}
if parser.fixed(&open).is_some() {
return Err(DirectiveError(format!(
"Directive open token already in use: {open}"
)));
}
let open_tn = format!("#OD_{name}");
let open_tin = parser.token_with_source(&open_tn, &open);
let mut close_tin = None;
let mut close_tn = None;
if let Some(close) = close.as_deref() {
if let Some(existing) = parser.fixed(close) {
close_tin = Some(existing);
close_tn = Some(parser.token_name(existing));
} else {
let token_name = format!("#CD_{name}");
close_tin = Some(parser.token_with_source(&token_name, close));
close_tn = Some(token_name);
}
}
register_lifecycle_refs(parser, &name, options.action.clone());
let document = build_grammar(
parser,
&name,
&open_tn,
close_tn.as_deref(),
&open_rules,
&close_rules,
);
parser.define_rule(name.clone(), |spec| {
spec.clear();
});
let spec =
GrammarSpec::from_value(document).map_err(|error| DirectiveError(error.to_string()))?;
parser
.grammar_with_setting(&spec, &GrammarSetting::groups("directive"))
.map_err(|error| DirectiveError(error.to_string()))?;
if let Some(custom) = options.custom.clone() {
let config = DirectiveConfig {
open: open_tin,
close: close_tin,
name: name.clone(),
};
custom(parser, &config);
}
Ok(())
}
fn register_lifecycle_refs(parser: &mut Tabnas, name: &str, action: DirectiveAction) {
parser.state_action_with_next_ref(format!("@{name}-bo"), |rule, _context, _next, _out| {
set_node(rule, Value::object(IndexMap::new()));
Ok(None)
});
parser.state_action_with_next_ref(
format!("@{name}-bc"),
move |rule: &mut Rule,
context: &mut Context,
_next: Option<&RuleSnapshot>,
_out: Option<Token>| { action.run(rule, context) },
);
}
fn build_grammar(
parser: &mut Tabnas,
name: &str,
open_tn: &str,
close_tn: Option<&str>,
open_rules: &BTreeMap<String, RuleMod>,
close_rules: &BTreeMap<String, RuleMod>,
) -> JsonValue {
let counter = format!("dr_{name}");
let mut rules = JsonMap::new();
for (rule_name, modification) in open_rules {
let mut open_alts: Vec<JsonValue> = Vec::new();
let mut close_alts: Vec<JsonValue> = Vec::new();
if let Some(close_tn) = close_tn {
open_alts.push(json!({
"s": format!("{open_tn} {close_tn}"),
"b": 1,
"p": name,
"n": { counter.clone(): 1 },
"g": "start,end",
}));
close_alts.push(json!({ "s": close_tn, "b": 1, "g": "end" }));
}
let mut open_alt = json!({
"s": open_tn,
"p": name,
"n": { counter.clone(): 1 },
"g": "start",
});
if let Some(condition) = modification.c.clone() {
let reference = format!("@dr-open-c-{name}-{rule_name}");
parser.alt_condition(reference.clone(), move |rule, context| {
condition(rule, context)
});
insert_field(&mut open_alt, "c", JsonValue::String(reference));
}
open_alts.push(open_alt);
let entry = rule_entry(&mut rules, rule_name);
insert_field(entry, "open", JsonValue::Array(open_alts));
if !close_alts.is_empty() {
insert_field(entry, "close", JsonValue::Array(close_alts));
}
}
if let Some(close_tn) = close_tn {
for (rule_name, modification) in close_rules {
let close_reference = format!("@dr-close-c-{name}-{rule_name}");
let condition = modification.c.clone();
let close_counter = counter.clone();
parser.alt_condition(close_reference.clone(), move |rule, context| {
if rule.n.get(&close_counter).copied().unwrap_or(0) != 1 {
return false;
}
match &condition {
Some(condition) => condition(rule, context),
None => true,
}
});
let comma_reference = format!("@dr-close-ca-c-{name}-{rule_name}");
let comma_counter = counter.clone();
parser.alt_condition(comma_reference.clone(), move |rule, _context| {
rule.n.get(&comma_counter).copied().unwrap_or(0) == 1
});
let entry = rule_entry(&mut rules, rule_name);
insert_field(
entry,
"close",
json!([
{ "s": close_tn, "c": close_reference, "b": 1, "g": "end" },
{
"s": format!("#CA {close_tn}"),
"c": comma_reference,
"b": 1,
"g": "end,comma",
},
]),
);
}
}
let mut directive_open: Vec<JsonValue> = Vec::new();
if let Some(close_tn) = close_tn {
directive_open.push(json!({ "s": close_tn, "b": 1 }));
}
let counters = if close_tn.is_some() {
json!({ "dlist": 0, "dmap": 0 })
} else {
json!({ "dlist": 1, "dmap": 1 })
};
directive_open.push(json!({ "p": "val", "n": counters }));
let entry = rule_entry(&mut rules, name);
insert_field(entry, "open", JsonValue::Array(directive_open));
if let Some(close_tn) = close_tn {
insert_field(
entry,
"close",
json!([{ "s": close_tn }, { "s": format!("#CA {close_tn}") }]),
);
}
json!({ "rule": JsonValue::Object(rules) })
}
fn rule_entry<'a>(rules: &'a mut JsonMap<String, JsonValue>, name: &str) -> &'a mut JsonValue {
rules
.entry(name.to_string())
.or_insert_with(|| JsonValue::Object(JsonMap::new()))
}
fn insert_field(target: &mut JsonValue, key: &str, value: JsonValue) {
if let Some(object) = target.as_object_mut() {
object.insert(key.to_string(), value);
}
}