use std::collections::BTreeMap;
use indexmap::{IndexMap, IndexSet};
use serde::Serialize;
use tabnas::{AltSpec, RuleSpec, Tabnas, Tin, TIN_MAX};
use crate::abnf::abnf;
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct DebugTokenInfo {
pub tin: Tin,
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub fixed: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct DebugTokenSet {
pub name: String,
pub tins: Vec<Tin>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(untagged)]
pub enum DebugSeqItem {
One(String),
Any(Vec<String>),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct DebugAltInfo {
pub seq: Vec<DebugSeqItem>,
#[serde(skip_serializing_if = "Option::is_none")]
pub push: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub replace: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub back: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub counters: Option<BTreeMap<String, i32>>,
pub groups: Vec<String>,
pub action: bool,
pub cond: bool,
pub modifier: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct DebugRuleInfo {
pub name: String,
pub open: Vec<DebugAltInfo>,
pub close: Vec<DebugAltInfo>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct DebugRuleEdges {
pub name: String,
#[serde(rename = "openPush")]
pub open_push: Vec<String>,
#[serde(rename = "openReplace")]
pub open_replace: Vec<String>,
#[serde(rename = "closePush")]
pub close_push: Vec<String>,
#[serde(rename = "closeReplace")]
pub close_replace: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct DebugLexMatcher {
pub order: f64,
pub matcher: String,
pub make: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct DebugConfigInfo {
pub start: String,
pub finish: bool,
#[serde(rename = "safeKey")]
pub safe_key: bool,
pub lex: IndexMap<String, bool>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct DebugPluginInfo {
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub options: Option<serde_json::Value>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct DebugModel {
pub tag: String,
pub tokens: Vec<DebugTokenInfo>,
#[serde(rename = "tokenSets")]
pub token_sets: Vec<DebugTokenSet>,
pub rules: Vec<DebugRuleInfo>,
pub graph: Vec<DebugRuleEdges>,
pub lexer: Vec<DebugLexMatcher>,
pub config: DebugConfigInfo,
pub plugins: Vec<DebugPluginInfo>,
pub abnf: String,
}
pub fn model(parser: &Tabnas) -> DebugModel {
let specs = parser.rule_specs();
DebugModel {
tag: parser.options.tag.clone(),
tokens: tokens(parser),
token_sets: token_sets(parser),
rules: specs
.iter()
.map(|spec| DebugRuleInfo {
name: spec.name.clone(),
open: spec.open.iter().map(|alt| alt_info(parser, alt)).collect(),
close: spec.close.iter().map(|alt| alt_info(parser, alt)).collect(),
})
.collect(),
graph: specs.iter().map(|spec| rule_edges(spec)).collect(),
lexer: lexer(parser),
config: config(parser),
plugins: plugins(parser),
abnf: abnf(parser),
}
}
pub(crate) fn tokens(parser: &Tabnas) -> Vec<DebugTokenInfo> {
let mut tins: IndexSet<Tin> = (1..TIN_MAX).collect();
tins.extend(parser.options.fixed.tokens.values().map(|token| token.tin));
tins.extend(parser.options.match_tokens.values().map(|token| token.tin));
tins.extend(parser.options.tokens.values().copied());
let mut tins: Vec<Tin> = tins.into_iter().collect();
tins.sort_unstable();
tins.into_iter()
.map(|tin| DebugTokenInfo {
tin,
name: parser.token_name(tin),
fixed: parser.fixed_source(tin).map(str::to_string),
})
.collect()
}
pub(crate) fn token_sets(parser: &Tabnas) -> Vec<DebugTokenSet> {
let mut names: Vec<&String> = parser.options.token_set.keys().collect();
names.sort();
names
.into_iter()
.map(|name| {
let mut tins = parser.options.token_set[name].clone();
tins.sort_unstable();
DebugTokenSet {
name: name.clone(),
tins,
}
})
.collect()
}
pub(crate) fn alt_info(parser: &Tabnas, alt: &AltSpec) -> DebugAltInfo {
let seq = alt
.s
.iter()
.map(|position| match position.len() {
0 => DebugSeqItem::One(String::new()),
1 => DebugSeqItem::One(parser.token_name(position[0])),
_ => DebugSeqItem::Any(position.iter().map(|tin| parser.token_name(*tin)).collect()),
})
.collect();
DebugAltInfo {
seq,
push: target_name(
alt.p.as_deref(),
alt.p_fn.is_some() || alt.p_match.is_some(),
),
replace: target_name(
alt.r.as_deref(),
alt.r_fn.is_some() || alt.r_match.is_some(),
),
back: (0 != alt.b).then_some(alt.b),
counters: (!alt.n.is_empty()).then(|| {
alt.n
.iter()
.map(|(name, value)| (name.clone(), *value))
.collect()
}),
groups: groups(alt),
action: !alt.a.is_empty()
|| !alt.action_fns.is_empty()
|| !alt.matched_action_fns.is_empty(),
cond: !alt.c.is_empty()
|| alt.c_ref.is_some()
|| alt.c_fn.is_some()
|| alt.c_match.is_some()
|| alt.c_lex.is_some()
|| alt.c_lex_match.is_some(),
modifier: alt.h.is_some() || alt.h_match.is_some(),
}
}
fn target_name(name: Option<&str>, has_fn: bool) -> Option<String> {
match name {
Some(name) => Some(name.to_string()),
None if has_fn => Some("<fn>".to_string()),
None => None,
}
}
pub(crate) fn groups(alt: &AltSpec) -> Vec<String> {
alt.g
.split(',')
.map(str::trim)
.filter(|tag| !tag.is_empty())
.map(str::to_string)
.collect()
}
pub(crate) fn rule_edges(spec: &RuleSpec) -> DebugRuleEdges {
DebugRuleEdges {
name: spec.name.clone(),
open_push: edges(&spec.open, Step::Push),
open_replace: edges(&spec.open, Step::Replace),
close_push: edges(&spec.close, Step::Push),
close_replace: edges(&spec.close, Step::Replace),
}
}
#[derive(Clone, Copy)]
pub(crate) enum Step {
Push,
Replace,
}
pub(crate) fn edges(alts: &[AltSpec], step: Step) -> Vec<String> {
let mut seen: IndexSet<String> = IndexSet::new();
for alt in alts {
let (name, has_fn) = match step {
Step::Push => (
alt.p.as_deref(),
alt.p_fn.is_some() || alt.p_match.is_some(),
),
Step::Replace => (
alt.r.as_deref(),
alt.r_fn.is_some() || alt.r_match.is_some(),
),
};
if let Some(target) = target_name(name, has_fn) {
seen.insert(target);
}
}
seen.into_iter().collect()
}
pub(crate) fn lexer(parser: &Tabnas) -> Vec<DebugLexMatcher> {
let mut matchers: Vec<&tabnas::LexMatcher> = parser.options.lex.matchers.values().collect();
matchers.sort_by(|left, right| {
left.order
.partial_cmp(&right.order)
.unwrap_or(std::cmp::Ordering::Equal)
.then_with(|| left.name.cmp(&right.name))
});
matchers
.into_iter()
.map(|matcher| DebugLexMatcher {
order: matcher.order,
matcher: matcher.name.clone(),
make: String::new(),
})
.collect()
}
pub(crate) fn config(parser: &Tabnas) -> DebugConfigInfo {
let options = &parser.options;
DebugConfigInfo {
start: options.rule.start.clone(),
finish: options.rule.finish,
safe_key: options.safe.key,
lex: lex_flags(parser),
}
}
pub(crate) fn lex_flags(parser: &Tabnas) -> IndexMap<String, bool> {
let options = &parser.options;
[
("fixed", options.fixed.lex),
("space", options.space.lex),
("line", options.line.lex),
("text", options.text.lex),
("number", options.number.lex),
("comment", options.comment.lex),
("string", options.string.lex),
("value", options.value.lex),
]
.into_iter()
.map(|(name, enabled)| (name.to_string(), enabled))
.collect()
}
pub(crate) fn plugins(parser: &Tabnas) -> Vec<DebugPluginInfo> {
parser
.installed_plugins()
.into_iter()
.map(|plugin| {
let options = parser
.plugin_options(&plugin.name)
.filter(|value| !matches!(value, tabnas::Value::Undefined))
.map(|value| value.to_json());
DebugPluginInfo {
name: plugin.name,
options,
}
})
.collect()
}