1use std::collections::{BTreeMap, HashSet};
19use std::fmt::Write;
20
21use serde_json::Value;
22
23use crate::spec::{AltSpec, GrammarSpec};
24
25#[derive(Debug, Clone, PartialEq, Eq)]
28pub enum TransducePart {
29 Part { entry: String, source: String },
33 Whole(String),
35}
36
37#[derive(Debug, Clone, Default)]
39struct Entry {
40 container: Option<&'static str>,
41 continues: bool,
43 member: Option<String>,
44 fills: Option<Fills>,
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50enum Fills {
51 Text,
52 Value,
53}
54
55const VALUE_ACTIONS: [&str; 7] = [
58 "@object$", "@array$", "@key$", "@setval$", "@push$", "@value$", "@reset$",
59];
60
61fn is_symbol(name: &str) -> bool {
65 let mut chars = name.chars();
66 let Some(first) = chars.next() else {
67 return false;
68 };
69 (first.is_ascii_alphabetic() || first == '_')
70 && chars.all(|c| c.is_ascii_alphanumeric() || "_.$-".contains(c))
71 && !matches!(name, "true" | "false" | "null")
72}
73
74fn quoted(text: &str) -> String {
78 let mut out = String::from("\"");
79 for ch in text.chars() {
80 match ch {
81 '"' | '\\' => {
82 out.push('\\');
83 out.push(ch);
84 }
85 c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
86 c => out.push(c),
87 }
88 }
89 out.push('"');
90 out
91}
92
93fn acts_of(alt: &AltSpec) -> (Vec<(String, Value)>, String) {
96 let acts: Vec<(String, Value)> = alt
97 .actions()
98 .into_iter()
99 .filter(|a| VALUE_ACTIONS.contains(&a.as_str()))
100 .map(|a| {
101 let cfg = alt
102 .k()
103 .and_then(|k| k.get(&a[1..]))
104 .cloned()
105 .unwrap_or(Value::Null);
106 (a, cfg)
107 })
108 .collect();
109 let mut signature = String::new();
110 for (a, cfg) in &acts {
111 let _ = write!(signature, "{a} {cfg};");
112 }
113 (acts, signature)
114}
115
116fn whole(why: impl Into<String>) -> TransducePart {
117 TransducePart::Whole(why.into())
118}
119
120pub fn transduce_alc(spec: &GrammarSpec, name: &str) -> TransducePart {
123 if !is_symbol(name) {
124 return whole(format!(
125 "the name {} is not one alchemy can give a definition",
126 quoted(name)
127 ));
128 }
129 let mut names: Vec<&str> = spec
130 .rule
131 .iter()
132 .filter(|(_, rs)| rs.is_some())
133 .map(|(name, _)| name.as_str())
134 .collect();
135 names.sort_unstable();
136 let rule = |name: &str| spec.rule.get(name).and_then(Option::as_ref);
137 let alts = |name: &str, side: &str| -> Vec<AltSpec> {
138 rule(name)
139 .map(|r| r.alts(side).to_vec())
140 .unwrap_or_default()
141 };
142
143 let mut entries: BTreeMap<String, Entry> = BTreeMap::new();
145 for &name in &names {
146 let mut entry = Entry::default();
147 for side in ["open", "close"] {
148 let mut first: Option<Vec<(String, Value)>> = None;
149 let mut signature = String::new();
150 for alt in alts(name, side) {
151 let (acts, sig) = acts_of(&alt);
152 match first {
153 None => {
154 first = Some(acts);
155 signature = sig;
156 }
157 Some(_) if sig != signature => {
158 return whole(format!(
159 "rule {name}'s {side} alternates build its value differently"
160 ));
161 }
162 Some(_) => {}
163 }
164 }
165 for (act, cfg) in first.unwrap_or_default() {
166 let lit = cfg.get("lit").and_then(Value::as_str);
167 match act.as_str() {
168 "@object$" | "@array$" if side == "open" && entry.container.is_none() => {
169 entry.container = Some(if act == "@object$" { "object" } else { "array" });
170 }
171 "@key$" if side == "open" && lit.is_some() && entry.member.is_none() => {
172 entry.member = lit.map(str::to_string);
173 }
174 "@setval$" | "@push$" if side == "close" && entry.fills.is_none() => {
175 entry.fills = Some(if cfg.get("src") == Some(&Value::Bool(true)) {
176 Fills::Text
177 } else {
178 Fills::Value
179 });
180 }
181 _ => {
182 return whole(format!(
183 "rule {name}'s {side} alternates use {act} as no transducer part reads it"
184 ));
185 }
186 }
187 }
188 }
189 if entry.container.is_some() || entry.member.is_some() || entry.fills.is_some() {
190 entries.insert(name.to_string(), entry);
191 }
192 }
193
194 let mut changed = true;
198 while changed {
199 changed = false;
200 for &name in &names {
201 let Some(container) = entries.get(name).and_then(|e| e.container) else {
202 continue;
203 };
204 for alt in alts(name, "close") {
205 let Some(next) = alt.r().filter(|r| !r.is_empty()) else {
206 continue;
207 };
208 if rule(next).is_none() {
209 return whole(format!(
210 "rule {name} hands its {container} on to rule {next}, which the grammar does not define"
211 ));
212 }
213 let target = entries.entry(next.to_string()).or_default();
214 match target.container {
215 None => {
216 target.container = Some(container);
217 target.continues = true;
218 changed = true;
219 }
220 Some(kind) if kind != container => {
221 let article = if kind == "object" {
222 "an object"
223 } else {
224 "an array"
225 };
226 return whole(format!(
227 "rule {name} hands its {container} on to rule {next}, a rule of {article}"
228 ));
229 }
230 Some(_) if !target.continues => {
231 return whole(format!(
232 "rule {name} hands its {container} on to rule {next}, which begins one of its own"
233 ));
234 }
235 Some(_) => {}
236 }
237 }
238 }
239 }
240
241 if let Some(bad) = entries.keys().find(|r| !is_symbol(r)) {
242 return whole(format!(
243 "rule {} has no name alchemy can write as a keyword",
244 quoted(bad)
245 ));
246 }
247
248 for (name, entry) in &entries {
251 if entry.container.is_none() && entry.fills != Some(Fills::Text) {
252 continue;
253 }
254 if alts(name, "open")
255 .iter()
256 .any(|alt| alt.r().is_some_and(|r| !r.is_empty()))
257 {
258 return whole(format!(
259 "rule {name}'s open alternate replaces it, so its close never runs"
260 ));
261 }
262 }
263
264 let beneath = |start: &str| -> Option<String> {
267 let mut seen: HashSet<String> = HashSet::new();
268 let mut stack = vec![start.to_string()];
269 while let Some(name) = stack.pop() {
270 if seen.contains(&name) || rule(&name).is_none() {
271 continue;
272 }
273 seen.insert(name.clone());
274 if entries.contains_key(&name) {
275 return Some(name);
276 }
277 let mut next: Vec<String> = Vec::new();
278 for side in ["open", "close"] {
279 for alt in alts(&name, side) {
280 for to in [alt.p(), alt.r()].into_iter().flatten() {
281 if !to.is_empty() {
282 next.push(to.to_string());
283 }
284 }
285 }
286 }
287 stack.extend(next.into_iter().rev());
288 }
289 None
290 };
291 for (name, entry) in &entries {
292 if entry.fills != Some(Fills::Text) {
293 continue;
294 }
295 for alt in alts(name, "open") {
296 let Some(pushed) = alt.p().filter(|p| !p.is_empty()) else {
297 continue;
298 };
299 if let Some(found) = beneath(pushed) {
300 return whole(format!(
301 "rule {name}'s member is the text of rule {pushed}, beneath which rule {found} builds a value of its own"
302 ));
303 }
304 }
305 }
306
307 let wrapper = spec
310 .options
311 .get("rule")
312 .and_then(|r| r.get("start"))
313 .and_then(Value::as_str);
314 let start = wrapper.filter(|w| rule(w).is_some()).and_then(|w| {
315 alts(w, "open")
316 .iter()
317 .find_map(|alt| alt.p().filter(|p| !p.is_empty()).map(str::to_string))
318 });
319 let Some(start) = start else {
320 return whole("the grammar has no start rule a wrapper pushes");
321 };
322 match entries.get(&start) {
323 Some(root) if root.container.is_some() && !root.continues => {}
324 _ => {
325 return whole(format!(
326 "the start rule {start} has no annotation, so the value is the {{rule, src, kids}} tree, \
327 whose src comes before its kids and holds the text of every node beneath it: \
328 no stream writes the root before the document has ended"
329 ));
330 }
331 }
332
333 let entry = format!("{name}-transduce");
334 let mut lines = vec![
335 format!("; The transducer part of the grammar {name}: the JSON events of the value"),
336 "; its @object and @array annotations build, from its rule passes, as".to_string(),
337 "; tabnas-bnf wrote them from the value actions those annotations attach.".to_string(),
338 format!("def {entry} [input]"),
339 " transduce-tree".to_string(),
340 " record".to_string(),
341 ];
342 for (rule, e) in &entries {
343 let mut fields: Vec<String> = Vec::new();
344 if let Some(container) = e.container {
345 fields.push(format!("(entry :container :{container})"));
346 }
347 if let Some(member) = &e.member {
348 fields.push(format!("(entry :member {})", quoted(member)));
349 }
350 if e.fills == Some(Fills::Text) {
351 fields.push("(entry :text true)".to_string());
352 }
353 if !fields.is_empty() {
354 lines.push(format!(" entry :{rule} (record {})", fields.join(" ")));
355 }
356 }
357 lines.push(" input".to_string());
358 lines.push(String::new());
359 TransducePart::Part {
360 entry,
361 source: lines.join("\n"),
362 }
363}