1use std::fmt::Write as _;
16
17use tabnas::{AltSpec, RuleSpec, Tabnas};
18
19use crate::abnf::abnf;
20use crate::model;
21
22pub const SECTIONS: [&str; 8] = [
25 "========= INSTANCE ========",
26 "========= TOKENS ========",
27 "========= RULES =========",
28 "========= ALTS =========",
29 "========= LEXER =========",
30 "========= CONFIG ========",
31 "========= PLUGIN =========",
32 "========= ABNF =========",
33];
34
35pub fn describe(parser: &Tabnas) -> String {
37 let mut parts: Vec<String> = Vec::new();
38
39 parts.push(SECTIONS[0].to_string());
40 parts.push(format!(" tag: {}", parser.options.tag));
41 parts.push("\n".to_string());
42
43 parts.push(SECTIONS[1].to_string());
44 parts.push(
45 model::tokens(parser)
46 .into_iter()
47 .map(|token| {
48 let fixed = token
49 .fixed
50 .map(|source| format!("\"{source}\""))
51 .unwrap_or_default();
52 format!(" {}\t{}\t{}", token.tin, token.name, fixed)
53 })
54 .collect::<Vec<_>>()
55 .join("\n"),
56 );
57 parts.push("\n".to_string());
58
59 parts.push(
60 model::token_sets(parser)
61 .into_iter()
62 .map(|set| {
63 let tins = set
64 .tins
65 .iter()
66 .map(|tin| tin.to_string())
67 .collect::<Vec<_>>()
68 .join(",");
69 format!(" {}\t{}", set.name, tins)
70 })
71 .collect::<Vec<_>>()
72 .join("\n"),
73 );
74 parts.push("\n".to_string());
75
76 let specs = parser.rule_specs();
77
78 parts.push(SECTIONS[2].to_string());
79 parts.push(rule_tree(&specs));
80 parts.push("\n".to_string());
81
82 parts.push(SECTIONS[3].to_string());
83 parts.push(
84 specs
85 .iter()
86 .map(|spec| {
87 format!(
88 " {}:\n{}{}",
89 spec.name,
90 describe_alts(parser, &spec.open, "OPEN"),
91 describe_alts(parser, &spec.close, "CLOSE"),
92 )
93 })
94 .collect::<Vec<_>>()
95 .join("\n\n"),
96 );
97 parts.push("\n".to_string());
98
99 parts.push(SECTIONS[4].to_string());
100 parts.push(format!(
101 " {}",
102 model::lexer(parser)
103 .into_iter()
104 .map(|matcher| format!("{}: {} ({})", matcher.order, matcher.matcher, matcher.make))
105 .collect::<Vec<_>>()
106 .join("\n ")
107 ));
108 parts.push("\n".to_string());
109
110 parts.push(SECTIONS[5].to_string());
111 let config = model::config(parser);
112 let mut config_lines = vec![
113 format!(" start: {}", config.start),
114 format!(" finish: {}", config.finish),
115 format!(" safeKey: {}", config.safe_key),
116 ];
117 for (name, enabled) in &config.lex {
118 config_lines.push(format!(" lex.{name}: {enabled}"));
119 }
120 parts.push(config_lines.join("\n"));
121 parts.push("\n".to_string());
122
123 parts.push("\n".to_string());
124 parts.push(SECTIONS[6].to_string());
125 parts.push(format!(
126 " {}",
127 model::plugins(parser)
128 .into_iter()
129 .map(|plugin| {
130 let mut line = plugin.name;
131 if let Some(serde_json::Value::Object(options)) = plugin.options {
132 for (key, value) in options {
133 let _ = write!(line, "\n {key}: {value}");
134 }
135 }
136 line
137 })
138 .collect::<Vec<_>>()
139 .join("\n ")
140 ));
141 parts.push("\n".to_string());
142
143 parts.push(SECTIONS[7].to_string());
144 parts.push(abnf(parser));
145 parts.push("\n".to_string());
146
147 parts.join("\n")
148}
149
150fn rule_tree(specs: &[&RuleSpec]) -> String {
153 let mut out = String::new();
154 for spec in specs {
155 let categories = [
156 ("op", model::edges(&spec.open, model::Step::Push)),
157 ("or", model::edges(&spec.open, model::Step::Replace)),
158 ("cp", model::edges(&spec.close, model::Step::Push)),
159 ("cr", model::edges(&spec.close, model::Step::Replace)),
160 ];
161 let lines: Vec<String> = categories
162 .into_iter()
163 .filter(|(_, targets)| !targets.is_empty())
164 .map(|(label, targets)| format!("{label}: {}", targets.join(" ")))
165 .collect();
166 let _ = write!(out, " {}:\n {}\n", spec.name, lines.join("\n "));
167 }
168 out
169}
170
171fn describe_alts(parser: &Tabnas, alts: &[AltSpec], kind: &str) -> String {
173 if alts.is_empty() {
174 return String::new();
175 }
176 let mut out = format!(" {kind}:\n");
177 let rendered: Vec<String> = alts
178 .iter()
179 .enumerate()
180 .map(|(index, alt)| describe_alt(parser, alt, index))
181 .collect();
182 out.push_str(&rendered.join("\n"));
183 out.push('\n');
184 out
185}
186
187fn describe_alt(parser: &Tabnas, alt: &AltSpec, index: usize) -> String {
188 let sequence = alt
189 .s
190 .iter()
191 .map(|position| match position.len() {
192 0 => String::new(),
193 1 => parser.token_name(position[0]),
194 _ => format!(
195 "[{}]",
196 position
197 .iter()
198 .map(|tin| parser.token_name(*tin))
199 .collect::<Vec<_>>()
200 .join(",")
201 ),
202 })
203 .collect::<Vec<_>>()
204 .join(" ");
205 let sequence = format!("[{sequence}] ");
206
207 let replace = match (&alt.r, alt.r_fn.is_some() || alt.r_match.is_some()) {
208 (Some(name), _) => format!(" r={name}"),
209 (None, true) => " r=<F>".to_string(),
210 (None, false) => String::new(),
211 };
212 let push = match (&alt.p, alt.p_fn.is_some() || alt.p_match.is_some()) {
213 (Some(name), _) => format!(" p={name}"),
214 (None, true) => " p=<F>".to_string(),
215 (None, false) => String::new(),
216 };
217 let no_target = if replace.is_empty() && push.is_empty() {
218 "\t"
219 } else {
220 ""
221 };
222
223 let back = if 0 == alt.b {
224 String::new()
225 } else {
226 format!("b={}", alt.b)
227 };
228
229 let counters = if alt.n.is_empty() {
232 String::new()
233 } else {
234 let mut pairs: Vec<String> = alt
235 .n
236 .iter()
237 .map(|(name, value)| format!("{name}:{value}"))
238 .collect();
239 pairs.sort();
240 format!("n={}", pairs.join(","))
241 };
242
243 let info = model::alt_info(parser, alt);
244 let mut flags = String::new();
245 if info.action {
246 flags.push('A');
247 }
248 if info.cond {
249 flags.push('C');
250 }
251 if info.modifier {
252 flags.push('H');
253 }
254
255 let declarative = if alt.c.is_empty() {
261 "\t".to_string()
262 } else {
263 let rendered: Vec<String> = alt
264 .c
265 .iter()
266 .map(|condition| {
267 format!(
268 "{}{:?}{}",
269 condition.path.join("."),
270 condition.op,
271 condition.value
272 )
273 })
274 .collect();
275 format!(" CD={}", rendered.join(","))
276 };
277
278 let groups = model::groups(alt);
279 let groups = if groups.is_empty() {
280 String::new()
281 } else {
282 format!("\tg={}", groups.join(","))
283 };
284
285 format!(
286 " {index:>5} {sequence:<32}{replace}{push}{no_target}\t{back}\t{counters}\t{flags}\t{declarative}{groups}"
287 )
288}