1use std::collections::BTreeMap;
16
17use indexmap::{IndexMap, IndexSet};
18use serde::Serialize;
19use tabnas::{AltSpec, RuleSpec, Tabnas, Tin, TIN_MAX};
20
21use crate::abnf::abnf;
22
23#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
27pub struct DebugTokenInfo {
28 pub tin: Tin,
30 pub name: String,
32 #[serde(skip_serializing_if = "Option::is_none")]
34 pub fixed: Option<String>,
35}
36
37#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
39pub struct DebugTokenSet {
40 pub name: String,
42 pub tins: Vec<Tin>,
44}
45
46#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
52#[serde(untagged)]
53pub enum DebugSeqItem {
54 One(String),
56 Any(Vec<String>),
58}
59
60#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
63pub struct DebugAltInfo {
64 pub seq: Vec<DebugSeqItem>,
66 #[serde(skip_serializing_if = "Option::is_none")]
68 pub push: Option<String>,
69 #[serde(skip_serializing_if = "Option::is_none")]
71 pub replace: Option<String>,
72 #[serde(skip_serializing_if = "Option::is_none")]
74 pub back: Option<usize>,
75 #[serde(skip_serializing_if = "Option::is_none")]
77 pub counters: Option<BTreeMap<String, i32>>,
78 pub groups: Vec<String>,
80 pub action: bool,
82 pub cond: bool,
84 pub modifier: bool,
86}
87
88#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
90pub struct DebugRuleInfo {
91 pub name: String,
93 pub open: Vec<DebugAltInfo>,
95 pub close: Vec<DebugAltInfo>,
97}
98
99#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
103pub struct DebugRuleEdges {
104 pub name: String,
106 #[serde(rename = "openPush")]
108 pub open_push: Vec<String>,
109 #[serde(rename = "openReplace")]
111 pub open_replace: Vec<String>,
112 #[serde(rename = "closePush")]
114 pub close_push: Vec<String>,
115 #[serde(rename = "closeReplace")]
117 pub close_replace: Vec<String>,
118}
119
120#[derive(Debug, Clone, PartialEq, Serialize)]
128pub struct DebugLexMatcher {
129 pub order: f64,
137 pub matcher: String,
139 pub make: String,
141}
142
143#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
146pub struct DebugConfigInfo {
147 pub start: String,
149 pub finish: bool,
151 #[serde(rename = "safeKey")]
153 pub safe_key: bool,
154 pub lex: IndexMap<String, bool>,
156}
157
158#[derive(Debug, Clone, PartialEq, Serialize)]
161pub struct DebugPluginInfo {
162 pub name: String,
164 #[serde(skip_serializing_if = "Option::is_none")]
166 pub options: Option<serde_json::Value>,
167}
168
169#[derive(Debug, Clone, PartialEq, Serialize)]
173pub struct DebugModel {
174 pub tag: String,
176 pub tokens: Vec<DebugTokenInfo>,
178 #[serde(rename = "tokenSets")]
180 pub token_sets: Vec<DebugTokenSet>,
181 pub rules: Vec<DebugRuleInfo>,
183 pub graph: Vec<DebugRuleEdges>,
185 pub lexer: Vec<DebugLexMatcher>,
187 pub config: DebugConfigInfo,
189 pub plugins: Vec<DebugPluginInfo>,
191 pub abnf: String,
193}
194
195pub fn model(parser: &Tabnas) -> DebugModel {
197 let specs = parser.rule_specs();
198
199 DebugModel {
200 tag: parser.options.tag.clone(),
201 tokens: tokens(parser),
202 token_sets: token_sets(parser),
203 rules: specs
204 .iter()
205 .map(|spec| DebugRuleInfo {
206 name: spec.name.clone(),
207 open: spec.open.iter().map(|alt| alt_info(parser, alt)).collect(),
208 close: spec.close.iter().map(|alt| alt_info(parser, alt)).collect(),
209 })
210 .collect(),
211 graph: specs.iter().map(|spec| rule_edges(spec)).collect(),
212 lexer: lexer(parser),
213 config: config(parser),
214 plugins: plugins(parser),
215 abnf: abnf(parser),
216 }
217}
218
219pub(crate) fn tokens(parser: &Tabnas) -> Vec<DebugTokenInfo> {
226 let mut tins: IndexSet<Tin> = (1..TIN_MAX).collect();
227 tins.extend(parser.options.fixed.tokens.values().map(|token| token.tin));
228 tins.extend(parser.options.match_tokens.values().map(|token| token.tin));
229 tins.extend(parser.options.tokens.values().copied());
230
231 let mut tins: Vec<Tin> = tins.into_iter().collect();
232 tins.sort_unstable();
233 tins.into_iter()
234 .map(|tin| DebugTokenInfo {
235 tin,
236 name: parser.token_name(tin),
237 fixed: parser.fixed_source(tin).map(str::to_string),
238 })
239 .collect()
240}
241
242pub(crate) fn token_sets(parser: &Tabnas) -> Vec<DebugTokenSet> {
248 let mut names: Vec<&String> = parser.options.token_set.keys().collect();
249 names.sort();
250 names
251 .into_iter()
252 .map(|name| {
253 let mut tins = parser.options.token_set[name].clone();
254 tins.sort_unstable();
255 DebugTokenSet {
256 name: name.clone(),
257 tins,
258 }
259 })
260 .collect()
261}
262
263pub(crate) fn alt_info(parser: &Tabnas, alt: &AltSpec) -> DebugAltInfo {
265 let seq = alt
266 .s
267 .iter()
268 .map(|position| match position.len() {
269 0 => DebugSeqItem::One(String::new()),
272 1 => DebugSeqItem::One(parser.token_name(position[0])),
273 _ => DebugSeqItem::Any(position.iter().map(|tin| parser.token_name(*tin)).collect()),
274 })
275 .collect();
276
277 DebugAltInfo {
278 seq,
279 push: target_name(
280 alt.p.as_deref(),
281 alt.p_fn.is_some() || alt.p_match.is_some(),
282 ),
283 replace: target_name(
284 alt.r.as_deref(),
285 alt.r_fn.is_some() || alt.r_match.is_some(),
286 ),
287 back: (0 != alt.b).then_some(alt.b),
290 counters: (!alt.n.is_empty()).then(|| {
291 alt.n
292 .iter()
293 .map(|(name, value)| (name.clone(), *value))
294 .collect()
295 }),
296 groups: groups(alt),
297 action: !alt.a.is_empty()
298 || !alt.action_fns.is_empty()
299 || !alt.matched_action_fns.is_empty(),
300 cond: !alt.c.is_empty()
301 || alt.c_ref.is_some()
302 || alt.c_fn.is_some()
303 || alt.c_match.is_some()
304 || alt.c_lex.is_some()
305 || alt.c_lex_match.is_some(),
306 modifier: alt.h.is_some() || alt.h_match.is_some(),
307 }
308}
309
310fn target_name(name: Option<&str>, has_fn: bool) -> Option<String> {
312 match name {
313 Some(name) => Some(name.to_string()),
314 None if has_fn => Some("<fn>".to_string()),
315 None => None,
316 }
317}
318
319pub(crate) fn groups(alt: &AltSpec) -> Vec<String> {
321 alt.g
322 .split(',')
323 .map(str::trim)
324 .filter(|tag| !tag.is_empty())
325 .map(str::to_string)
326 .collect()
327}
328
329pub(crate) fn rule_edges(spec: &RuleSpec) -> DebugRuleEdges {
331 DebugRuleEdges {
332 name: spec.name.clone(),
333 open_push: edges(&spec.open, Step::Push),
334 open_replace: edges(&spec.open, Step::Replace),
335 close_push: edges(&spec.close, Step::Push),
336 close_replace: edges(&spec.close, Step::Replace),
337 }
338}
339
340#[derive(Clone, Copy)]
341pub(crate) enum Step {
342 Push,
343 Replace,
344}
345
346pub(crate) fn edges(alts: &[AltSpec], step: Step) -> Vec<String> {
349 let mut seen: IndexSet<String> = IndexSet::new();
350 for alt in alts {
351 let (name, has_fn) = match step {
352 Step::Push => (
353 alt.p.as_deref(),
354 alt.p_fn.is_some() || alt.p_match.is_some(),
355 ),
356 Step::Replace => (
357 alt.r.as_deref(),
358 alt.r_fn.is_some() || alt.r_match.is_some(),
359 ),
360 };
361 if let Some(target) = target_name(name, has_fn) {
362 seen.insert(target);
363 }
364 }
365 seen.into_iter().collect()
366}
367
368pub(crate) fn lexer(parser: &Tabnas) -> Vec<DebugLexMatcher> {
370 let mut matchers: Vec<&tabnas::LexMatcher> = parser.options.lex.matchers.values().collect();
371 matchers.sort_by(|left, right| {
372 left.order
373 .partial_cmp(&right.order)
374 .unwrap_or(std::cmp::Ordering::Equal)
375 .then_with(|| left.name.cmp(&right.name))
376 });
377 matchers
378 .into_iter()
379 .map(|matcher| DebugLexMatcher {
380 order: matcher.order,
381 matcher: matcher.name.clone(),
382 make: String::new(),
383 })
384 .collect()
385}
386
387pub(crate) fn config(parser: &Tabnas) -> DebugConfigInfo {
389 let options = &parser.options;
390 DebugConfigInfo {
391 start: options.rule.start.clone(),
392 finish: options.rule.finish,
393 safe_key: options.safe.key,
394 lex: lex_flags(parser),
395 }
396}
397
398pub(crate) fn lex_flags(parser: &Tabnas) -> IndexMap<String, bool> {
401 let options = &parser.options;
402 [
403 ("fixed", options.fixed.lex),
404 ("space", options.space.lex),
405 ("line", options.line.lex),
406 ("text", options.text.lex),
407 ("number", options.number.lex),
408 ("comment", options.comment.lex),
409 ("string", options.string.lex),
410 ("value", options.value.lex),
411 ]
412 .into_iter()
413 .map(|(name, enabled)| (name.to_string(), enabled))
414 .collect()
415}
416
417pub(crate) fn plugins(parser: &Tabnas) -> Vec<DebugPluginInfo> {
420 parser
421 .installed_plugins()
422 .into_iter()
423 .map(|plugin| {
424 let options = parser
425 .plugin_options(&plugin.name)
426 .filter(|value| !matches!(value, tabnas::Value::Undefined))
427 .map(|value| value.to_json());
428 DebugPluginInfo {
429 name: plugin.name,
430 options,
431 }
432 })
433 .collect()
434}