1use crate::PortType;
10
11use super::ast::{Expr, TileHole, TileOptions, TilePiece};
12use super::lexer::{Span, lex};
13use super::parser::{for_source_from_text, parse_expression};
14
15pub fn parse_template(
18 text: &str,
19 opts: &TileOptions,
20 span: Span,
21) -> Result<Vec<TilePiece>, String> {
22 let mut p = TemplateParser {
23 chars: text.chars().collect(),
24 pos: 0,
25 opts,
26 span,
27 };
28 let pieces = p.pieces(false)?;
29 if p.pos < p.chars.len() {
30 return Err(p.err("unexpected `}` closing a block that was never opened"));
31 }
32 Ok(pieces)
33}
34
35struct TemplateParser<'a> {
36 chars: Vec<char>,
37 pos: usize,
38 opts: &'a TileOptions,
39 span: Span,
40}
41
42impl TemplateParser<'_> {
43 fn err(&self, msg: &str) -> String {
44 format!(
45 "tile at line {}, col {}: {msg} (template offset {})",
46 self.span.line, self.span.col, self.pos
47 )
48 }
49
50 fn starts_with(&self, s: &str) -> bool {
51 let sc: Vec<char> = s.chars().collect();
52 self.chars[self.pos..].starts_with(&sc)
53 }
54
55 fn take(&mut self, s: &str) {
56 self.pos += s.chars().count();
57 }
58
59 fn rest(&self) -> String {
60 self.chars[self.pos..].iter().collect()
61 }
62
63 fn pieces(&mut self, in_block: bool) -> Result<Vec<TilePiece>, String> {
66 let open = self.opts.open.clone();
67 let doubled = format!("{open}{open}");
68 let sigil = self.opts.sigil.clone();
69 let mut out: Vec<TilePiece> = Vec::new();
70 let mut static_buf = String::new();
71 let mut static_depth = 0i32;
74 let flush = |buf: &mut String, out: &mut Vec<TilePiece>| {
75 if !buf.is_empty() {
76 out.push(TilePiece::Static(std::mem::take(buf)));
77 }
78 };
79 while self.pos < self.chars.len() {
80 if self.starts_with(&doubled) {
81 self.take(&doubled);
82 static_buf.push_str(&open);
83 continue;
84 }
85 if self.starts_with(&open) {
86 flush(&mut static_buf, &mut out);
87 out.push(TilePiece::Hole(self.hole()?));
88 continue;
89 }
90 if self.starts_with(&sigil) {
91 let after: String = self.rest().chars().skip(sigil.chars().count()).collect();
92 if after.starts_with("for") && after[3..].starts_with(char::is_whitespace) {
93 flush(&mut static_buf, &mut out);
94 out.push(self.projection()?);
95 continue;
96 }
97 if after.starts_with("if") && after[2..].starts_with(char::is_whitespace) {
98 flush(&mut static_buf, &mut out);
99 out.push(self.branch()?);
100 continue;
101 }
102 }
103 let c = self.chars[self.pos];
104 if c == '{' {
105 static_depth += 1;
106 } else if c == '}' {
107 if in_block && static_depth == 0 {
108 break;
109 }
110 static_depth -= 1;
111 }
112 static_buf.push(c);
113 self.pos += 1;
114 }
115 flush(&mut static_buf, &mut out);
116 Ok(out)
117 }
118
119 fn hole(&mut self) -> Result<TileHole, String> {
121 let start = self.pos;
122 self.take(&self.opts.open.clone());
123 let inner = self.until_close()?;
124 let text = inner.trim().to_string();
125 if text.is_empty() {
126 return Err(self.err("empty hole"));
127 }
128 let (mut body, raw) = match text.strip_suffix('!') {
129 Some(b) => (b.trim().to_string(), true),
130 None => (text.clone(), false),
131 };
132 let mut format = None;
133 if let Some(idx) = rfind_top_level(&body, '|')
134 && !body[..idx].ends_with('|')
135 && body[idx + 1..]
136 .trim()
137 .chars()
138 .all(|c| c.is_ascii_alphanumeric() || ".<>^-+#0_".contains(c))
139 && !body[idx + 1..].trim().is_empty()
140 {
141 format = Some(body[idx + 1..].trim().to_string());
142 body = body[..idx].trim().to_string();
143 }
144 let mut decl_type = None;
145 if let Some(idx) = rfind_top_level(&body, ':')
146 && let Some(kw) = body.get(idx + 1..).map(str::trim)
147 && let Some(message) = PortType::retired_keyword_message(kw)
148 {
149 return Err(self.err(&format!("hole `{text}`: {message}")));
150 }
151 if let Some(idx) = rfind_top_level(&body, ':')
152 && let Some(kw) = body.get(idx + 1..).map(str::trim)
153 && PortType::from_keyword(kw).is_some()
154 {
155 decl_type = Some(kw.to_string());
156 body = body[..idx].trim().to_string();
157 }
158 if body.is_empty() {
159 return Err(self.err(&format!("hole `{text}` has no expression")));
160 }
161 let expr = parse_hole_expr(&body).map_err(|e| {
162 if let Some(idx) = rfind_top_level(&body, ':')
165 && let Some(word) = body.get(idx + 1..).map(str::trim)
166 && !word.is_empty()
167 && word.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
168 {
169 return self.err(&format!(
170 "hole `{text}`: unknown type '{word}'; types are the port-type keywords (u64, i64, f64, str, bool, json, bytes, ...)"
171 ));
172 }
173 self.err(&format!("hole `{text}`: {e}"))
174 })?;
175 let _ = start;
176 Ok(TileHole {
177 expr,
178 decl_type,
179 format,
180 raw,
181 span: self.span,
182 })
183 }
184
185 fn until_close(&mut self) -> Result<String, String> {
188 let close = self.opts.close.clone();
189 let mut depth = 0i32;
190 let mut quote: Option<char> = None;
191 let mut buf = String::new();
192 while self.pos < self.chars.len() {
193 let c = self.chars[self.pos];
194 if let Some(q) = quote {
195 buf.push(c);
196 self.pos += 1;
197 if c == '\\' && self.pos < self.chars.len() {
198 buf.push(self.chars[self.pos]);
199 self.pos += 1;
200 } else if c == q {
201 quote = None;
202 }
203 continue;
204 }
205 if depth == 0 && self.starts_with(&close) {
206 self.take(&close);
207 return Ok(buf);
208 }
209 match c {
210 '"' | '\'' => quote = Some(c),
211 '(' | '[' | '{' => depth += 1,
212 ')' | ']' | '}' => depth -= 1,
213 _ => {}
214 }
215 buf.push(c);
216 self.pos += 1;
217 }
218 Err(self.err(&format!("unterminated hole; expected `{close}`")))
219 }
220
221 fn projection(&mut self) -> Result<TilePiece, String> {
223 self.take(&self.opts.sigil.clone());
224 self.take("for");
225 let header = self.header_until_brace(HeaderKind::For)?;
226 let (source_text, sep) = split_sep(&header);
227 let source = for_source_from_text(source_text.trim(), self.span, true)
228 .map_err(|e| self.err(&format!("projection: {e}")))?;
229 let body = self.block()?;
230 Ok(TilePiece::Projection {
231 source,
232 sep,
233 body,
234 span: self.span,
235 })
236 }
237
238 fn branch(&mut self) -> Result<TilePiece, String> {
240 self.take(&self.opts.sigil.clone());
241 self.take("if");
242 let header = self.header_until_brace(HeaderKind::If)?;
243 let cond = parse_hole_expr(header.trim())
244 .map_err(|e| self.err(&format!("branch condition `{}`: {e}", header.trim())))?;
245 let then = self.block()?;
246 let save = self.pos;
247 self.skip_ws();
248 let else_kw = format!("{}else", self.opts.sigil);
249 let otherwise = if self.starts_with(&else_kw) {
250 self.take(&else_kw);
251 self.skip_ws();
252 Some(self.block()?)
253 } else {
254 self.pos = save;
255 None
256 };
257 Ok(TilePiece::Branch {
258 cond,
259 then,
260 otherwise,
261 span: self.span,
262 })
263 }
264
265 fn header_until_brace(&mut self, kind: HeaderKind) -> Result<String, String> {
270 let mut depth = 0i32;
271 let mut quote: Option<char> = None;
272 let mut buf = String::new();
273 while self.pos < self.chars.len() {
274 let c = self.chars[self.pos];
275 if let Some(q) = quote {
276 buf.push(c);
277 self.pos += 1;
278 if c == q {
279 quote = None;
280 }
281 continue;
282 }
283 if depth == 0
287 && !self.opts.open.starts_with('{')
288 && self.starts_with(&self.opts.open.clone())
289 {
290 return Err(self.err(
291 "directive has no `{` block; a hole cannot appear in a directive header",
292 ));
293 }
294 if depth == 0 && c == '{' {
295 const HEADER_PUNCT: &str = "<>=!+-*/%.,()[]&|?:";
304 let placeholder = placeholder_len(&self.chars, self.pos).is_some_and(|len| {
305 let before = buf.chars().last().is_some_and(|b| HEADER_PUNCT.contains(b));
306 let after = self
307 .chars
308 .get(self.pos + len)
309 .is_some_and(|a| HEADER_PUNCT.contains(*a));
310 if before || after {
311 return true;
312 }
313 let rest: String = self.chars[self.pos + len..].iter().collect();
314 let rest = rest.trim_start();
315 if rest.is_empty()
316 || rest.starts_with(&self.opts.sigil)
317 || rest.starts_with(&self.opts.open)
318 {
319 return false;
320 }
321 if rest.starts_with(|c: char| HEADER_PUNCT.contains(c) && !"()[]".contains(c)) {
322 return true;
323 }
324 !header_complete(kind, &buf)
329 });
330 if !placeholder {
331 return Ok(buf);
332 }
333 }
334 match c {
335 '"' | '\'' => quote = Some(c),
336 '(' | '[' => depth += 1,
337 ')' | ']' => depth -= 1,
338 _ => {}
339 }
340 buf.push(c);
341 self.pos += 1;
342 }
343 Err(self.err("directive has no `{` block"))
344 }
345
346 fn block(&mut self) -> Result<Vec<TilePiece>, String> {
348 if self.pos >= self.chars.len() || self.chars[self.pos] != '{' {
349 return Err(self.err("expected `{`"));
350 }
351 self.pos += 1;
352 let mut body = self.pieces(true)?;
353 if self.pos >= self.chars.len() || self.chars[self.pos] != '}' {
354 return Err(self.err("unterminated block; expected `}`"));
355 }
356 self.pos += 1;
357 trim_block(&mut body);
358 Ok(body)
359 }
360
361 fn skip_ws(&mut self) {
362 while self.pos < self.chars.len() && self.chars[self.pos].is_whitespace() {
363 self.pos += 1;
364 }
365 }
366}
367
368fn trim_block(body: &mut Vec<TilePiece>) {
372 if let Some(TilePiece::Static(s)) = body.first_mut() {
373 let t = s.trim_start().to_string();
374 *s = t;
375 }
376 if let Some(TilePiece::Static(s)) = body.last_mut() {
377 let t = s.trim_end().to_string();
378 *s = t;
379 }
380 body.retain(|p| !matches!(p, TilePiece::Static(s) if s.is_empty()));
381}
382
383#[derive(Clone, Copy)]
385enum HeaderKind {
386 For,
387 If,
388}
389
390fn header_complete(kind: HeaderKind, header: &str) -> bool {
394 let h = header.trim();
395 if h.is_empty() {
396 return false;
397 }
398 match kind {
399 HeaderKind::If => parse_hole_expr(h).is_ok(),
400 HeaderKind::For => {
401 let dangling = h.ends_with(|c: char| "<>=!+-*/%&|,(".contains(c))
402 || ["where", "order", "in", "&&", "||"]
403 .iter()
404 .any(|kw| h.ends_with(kw));
405 if dangling {
406 return false;
407 }
408 let (source, _) = split_sep(h);
409 for_source_from_text(source.trim(), Span { line: 0, col: 0 }, true).is_ok()
410 }
411 }
412}
413
414fn split_sep(header: &str) -> (String, Option<String>) {
418 let unescaped = header.replace("\\\"", "\"");
419 let t = unescaped.trim_end();
420 if let Some(q) = t.strip_suffix('"')
421 && let Some(open_quote) = q.rfind('"')
422 && q[..open_quote].trim_end().ends_with(" sep")
423 {
424 let sep = q[open_quote + 1..].to_string();
425 let head = q[..open_quote].trim_end();
426 let head = head[..head.len() - 3].trim_end();
427 return (head.to_string(), Some(sep));
428 }
429 (t.to_string(), None)
430}
431
432pub fn parse_hole_expr(text: &str) -> Result<Expr, String> {
433 let tokens = lex(text)?;
434 parse_expression(tokens)
435}
436
437fn rfind_top_level(s: &str, needle: char) -> Option<usize> {
439 let mut depth = 0i32;
440 let mut quote: Option<char> = None;
441 let mut found = None;
442 for (i, c) in s.char_indices() {
443 if let Some(q) = quote {
444 if c == q {
445 quote = None;
446 }
447 continue;
448 }
449 match c {
450 '"' | '\'' => quote = Some(c),
451 '(' | '[' | '{' => depth += 1,
452 ')' | ']' | '}' => depth -= 1,
453 _ if depth == 0 && c == needle => found = Some(i),
454 _ => {}
455 }
456 }
457 found
458}
459
460fn placeholder_len(chars: &[char], pos: usize) -> Option<usize> {
462 let mut i = pos + 1;
463 let first = *chars.get(i)?;
464 if !(first.is_ascii_alphabetic() || first == '_') {
465 return None;
466 }
467 while i < chars.len() && (chars[i].is_ascii_alphanumeric() || chars[i] == '_') {
468 i += 1;
469 }
470 (chars.get(i) == Some(&'}')).then_some(i + 1 - pos)
471}
472
473pub fn render_template(pieces: &[TilePiece], opts: &TileOptions) -> String {
476 let mut out = String::new();
477 for piece in pieces {
478 match piece {
479 TilePiece::Static(s) => {
480 out.push_str(&s.replace(&opts.open, &format!("{}{}", opts.open, opts.open)))
481 }
482 TilePiece::Hole(h) => {
483 out.push_str(&opts.open);
484 out.push_str(&h.to_text());
485 out.push_str(&opts.close);
486 }
487 TilePiece::Projection {
488 source, sep, body, ..
489 } => {
490 out.push_str(&opts.sigil);
491 out.push_str("for ");
492 out.push_str(&source.to_text());
493 if let Some(s) = sep {
494 out.push_str(&format!(" sep \"{s}\""));
495 }
496 out.push_str(" { ");
497 out.push_str(&render_template(body, opts));
498 out.push_str(" }");
499 }
500 TilePiece::Branch {
501 cond,
502 then,
503 otherwise,
504 ..
505 } => {
506 out.push_str(&opts.sigil);
507 out.push_str("if ");
508 out.push_str(&super::pprint::pp_expr(cond));
509 out.push_str(" { ");
510 out.push_str(&render_template(then, opts));
511 out.push_str(" }");
512 if let Some(o) = otherwise {
513 out.push(' ');
514 out.push_str(&opts.sigil);
515 out.push_str("else { ");
516 out.push_str(&render_template(o, opts));
517 out.push_str(" }");
518 }
519 }
520 }
521 }
522 out
523}