BlueGit

timfa posprint

Files

posprint / src / dsl / parser.rs

parser.rs

parser.rs 41.7 KiB Download Raw
1use super::{
2 Align, BarcodeMode, BarcodeSymbology, Block, Document, ImageWidth, Inline, ListItem, ParseError,
3 QrEcc, QrMode,
4};
5
6pub fn parse(source: &str) -> Result<Document, ParseError> {
7 let source = strip_comments(source);
8 let mut blocks = Vec::new();
9 let mut lines = source.lines().peekable();
10 let mut line_no = 0usize;
11 let mut current_align = Align::Left;
12
13 while let Some(raw_line) = lines.next() {
14 line_no += 1;
15 let line = raw_line.trim_end();
16
17 let (content, align_for_block) = match parse_align_line(line) {
18 Some((align, None)) => {
19 current_align = align;
20 continue;
21 }
22 Some((align, Some(rest))) => {
23 current_align = align;
24 (rest, current_align)
25 }
26 None => (line, current_align),
27 };
28
29 if is_blank_feed_line(content) {
30 blocks.push(Block::Feed(1));
31 continue;
32 }
33
34 let segments = split_aligned_segments(content, align_for_block);
35 if segments.is_empty() {
36 continue;
37 }
38
39 // Same-line multi-align plain text → one AlignedRow (space-padded at print time).
40 if segments.len() > 1
41 && segments
42 .iter()
43 .all(|(_, seg_text)| is_plain_paragraph_segment(seg_text))
44 {
45 let mut parts = Vec::with_capacity(segments.len());
46 for (seg_align, seg_text) in &segments {
47 current_align = *seg_align;
48 parts.push((*seg_align, parse_inlines(seg_text, line_no, 1)?));
49 }
50 blocks.push(Block::AlignedRow { parts });
51 continue;
52 }
53
54 for (idx, (seg_align, seg_text)) in segments.iter().enumerate() {
55 current_align = *seg_align;
56 let allow_multiline_paragraph = segments.len() == 1 && idx == segments.len() - 1;
57
58 if is_blank_feed_line(seg_text) {
59 blocks.push(Block::Feed(1));
60 continue;
61 }
62
63 if seg_text.starts_with('#') {
64 blocks.push(parse_heading(seg_text, line_no, *seg_align)?);
65 continue;
66 }
67
68 if seg_text.trim() == "---" {
69 blocks.push(Block::Rule);
70 continue;
71 }
72
73 if seg_text.trim_start().starts_with("@") {
74 blocks.push(parse_directive(seg_text.trim(), line_no, *seg_align)?);
75 continue;
76 }
77
78 if is_list_item_line(seg_text) {
79 let mut items = vec![parse_list_item(seg_text, line_no)?];
80 while let Some(&next) = lines.peek() {
81 if is_blank_feed_line(next)
82 || next.starts_with('#')
83 || next.trim() == "---"
84 || next.trim_start().starts_with('@')
85 || parse_align_line(next).is_some()
86 || !is_list_item_line(next.trim_end())
87 {
88 break;
89 }
90 line_no += 1;
91 let next_line = lines.next().unwrap().trim_end();
92 items.push(parse_list_item(next_line, line_no)?);
93 }
94 blocks.push(Block::List {
95 align: *seg_align,
96 items,
97 });
98 continue;
99 }
100
101 if allow_multiline_paragraph {
102 let mut paragraph_lines = vec![seg_text.clone()];
103 while let Some(&next) = lines.peek() {
104 if is_blank_feed_line(next)
105 || next.starts_with('#')
106 || next.trim() == "---"
107 || next.trim_start().starts_with('@')
108 || parse_align_line(next).is_some()
109 || is_list_item_line(next.trim_end())
110 {
111 break;
112 }
113 line_no += 1;
114 lines.next();
115 paragraph_lines.push(next.trim_end().to_string());
116 }
117 let text = paragraph_lines.join("\n");
118 blocks.push(Block::Paragraph {
119 align: *seg_align,
120 inlines: parse_inlines(&text, line_no, 1)?,
121 });
122 } else {
123 blocks.push(Block::Paragraph {
124 align: *seg_align,
125 inlines: parse_inlines(seg_text, line_no, 1)?,
126 });
127 }
128 }
129 }
130
131 let document = Document { blocks };
132 validate_param_kinds(&document)?;
133 Ok(document)
134}
135
136fn validate_param_kinds(document: &Document) -> Result<(), ParseError> {
137 use std::collections::BTreeSet;
138
139 let mut text_names = BTreeSet::new();
140 let mut bool_names = BTreeSet::new();
141 for block in &document.blocks {
142 collect_param_kinds_from_block(block, &mut text_names, &mut bool_names);
143 }
144 for name in text_names.intersection(&bool_names) {
145 return Err(err(
146 1,
147 1,
148 format!(
149 "parameter '{name}' cannot be both ${{{name}}} (text) and $[{name}] (checkbox)"
150 ),
151 ));
152 }
153 Ok(())
154}
155
156fn collect_param_kinds_from_block(
157 block: &Block,
158 text_names: &mut std::collections::BTreeSet<String>,
159 bool_names: &mut std::collections::BTreeSet<String>,
160) {
161 match block {
162 Block::Paragraph { inlines, .. } | Block::Heading { inlines, .. } => {
163 for inline in inlines {
164 match inline {
165 Inline::Param(name) => {
166 text_names.insert(name.clone());
167 }
168 Inline::CheckboxParam(name) => {
169 bool_names.insert(name.clone());
170 }
171 _ => {}
172 }
173 }
174 }
175 Block::AlignedRow { parts } => {
176 for (_, inlines) in parts {
177 for inline in inlines {
178 match inline {
179 Inline::Param(name) => {
180 text_names.insert(name.clone());
181 }
182 Inline::CheckboxParam(name) => {
183 bool_names.insert(name.clone());
184 }
185 _ => {}
186 }
187 }
188 }
189 }
190 Block::List { items, .. } => {
191 for item in items {
192 for inline in &item.inlines {
193 match inline {
194 Inline::Param(name) => {
195 text_names.insert(name.clone());
196 }
197 Inline::CheckboxParam(name) => {
198 bool_names.insert(name.clone());
199 }
200 _ => {}
201 }
202 }
203 }
204 }
205 Block::Image { path, .. } => collect_text_params_from_raw(path, text_names),
206 Block::Barcode { data, .. } | Block::Qr { data, .. } => {
207 collect_text_params_from_raw(data, text_names);
208 }
209 Block::Rule | Block::Feed(_) | Block::Cut | Block::Date { .. } | Block::Time { .. } => {}
210 }
211}
212
213fn collect_text_params_from_raw(text: &str, text_names: &mut std::collections::BTreeSet<String>) {
214 let chars: Vec<char> = text.chars().collect();
215 let mut i = 0;
216 while i < chars.len() {
217 if chars[i] == '$' && i + 1 < chars.len() && chars[i + 1] == '{' {
218 let start = i + 2;
219 let mut j = start;
220 while j < chars.len() && chars[j] != '}' {
221 j += 1;
222 }
223 if j < chars.len() {
224 text_names.insert(chars[start..j].iter().collect());
225 i = j + 1;
226 continue;
227 }
228 }
229 i += 1;
230 }
231}
232
233/// True when the last substantive block is `@cut` (trailing blank-line feeds are ignored).
234pub fn document_ends_with_cut(document: &Document) -> bool {
235 for block in document.blocks.iter().rev() {
236 match block {
237 Block::Feed(_) => continue,
238 Block::Cut => return true,
239 _ => return false,
240 }
241 }
242 false
243}
244
245fn strip_comments(source: &str) -> String {
246 let mut out = String::with_capacity(source.len());
247 let mut chars = source.chars().peekable();
248 while let Some(ch) = chars.next() {
249 if ch == '<' && chars.peek() == Some(&'!') {
250 let mut rest: String = chars.clone().collect();
251 if rest.starts_with('!') {
252 let _ = chars.next();
253 rest = chars.clone().collect();
254 if rest.starts_with("--") {
255 for _ in 0..3 {
256 chars.next();
257 }
258 while let Some(c) = chars.next() {
259 if c == '-' && chars.peek() == Some(&'-') {
260 chars.next();
261 if chars.peek() == Some(&'>') {
262 chars.next();
263 break;
264 }
265 }
266 }
267 continue;
268 }
269 }
270 out.push('<');
271 } else {
272 out.push(ch);
273 }
274 }
275 out
276}
277
278/// True when a segment is ordinary paragraph text (eligible for AlignedRow).
279fn is_plain_paragraph_segment(seg_text: &str) -> bool {
280 !is_blank_feed_line(seg_text)
281 && !seg_text.starts_with('#')
282 && seg_text.trim() != "---"
283 && !seg_text.trim_start().starts_with('@')
284 && !is_list_item_line(seg_text)
285}
286
287/// Parse `:left:`, `:center:`, `:centre:`, or `:right:` at line start.
288/// Returns the alignment and optional remaining content on the same line.
289fn parse_align_line(line: &str) -> Option<(Align, Option<&str>)> {
290 let trimmed = line.trim_start();
291 if let Some(rest) = trimmed.strip_prefix(":left:") {
292 let rest = rest.trim_start();
293 return Some((
294 Align::Left,
295 if rest.is_empty() { None } else { Some(rest) },
296 ));
297 }
298 if let Some(rest) = trimmed.strip_prefix(":center:") {
299 let rest = rest.trim_start();
300 return Some((
301 Align::Center,
302 if rest.is_empty() { None } else { Some(rest) },
303 ));
304 }
305 if let Some(rest) = trimmed.strip_prefix(":centre:") {
306 let rest = rest.trim_start();
307 return Some((
308 Align::Center,
309 if rest.is_empty() { None } else { Some(rest) },
310 ));
311 }
312 if let Some(rest) = trimmed.strip_prefix(":right:") {
313 let rest = rest.trim_start();
314 return Some((
315 Align::Right,
316 if rest.is_empty() { None } else { Some(rest) },
317 ));
318 }
319 None
320}
321
322/// Split line content on embedded `:left:`, `:center:`, `:centre:`, or `:right:` markers.
323/// Leading spaces in each segment are preserved (for manual indent); trailing spaces are trimmed.
324fn split_aligned_segments(content: &str, start_align: Align) -> Vec<(Align, String)> {
325 let mut segments = Vec::new();
326 let mut align = start_align;
327 let mut rest = content;
328
329 while let Some((pos, new_align, marker_len)) = find_next_align_marker(rest) {
330 let before = rest[..pos].trim_end();
331 if !before.trim().is_empty() {
332 segments.push((align, before.to_string()));
333 }
334 align = new_align;
335 rest = rest[pos + marker_len..].trim_start();
336 }
337
338 let tail = rest.trim_end();
339 if !tail.trim().is_empty() {
340 segments.push((align, tail.to_string()));
341 }
342 segments
343}
344
345fn find_next_align_marker(s: &str) -> Option<(usize, Align, usize)> {
346 const MARKERS: &[(&str, Align)] = &[
347 (":left:", Align::Left),
348 (":center:", Align::Center),
349 (":centre:", Align::Center),
350 (":right:", Align::Right),
351 ];
352
353 let mut best: Option<(usize, Align, usize)> = None;
354 for (pat, marker_align) in MARKERS {
355 if let Some(pos) = s.find(pat) {
356 if best.is_none() || pos < best.unwrap().0 {
357 best = Some((pos, *marker_align, pat.len()));
358 }
359 }
360 }
361 best
362}
363
364/// True only when a line has no visible content (empty or whitespace-only).
365/// Lines with DSL markers (`:right:`, `@feed`, `#`, etc.) are never feed lines.
366fn is_blank_feed_line(line: &str) -> bool {
367 line.chars().all(|c| c.is_whitespace())
368}
369
370fn parse_heading(line: &str, line_no: usize, align: Align) -> Result<Block, ParseError> {
371 let mut level = 0u8;
372 for ch in line.chars() {
373 if ch == '#' {
374 level += 1;
375 } else {
376 break;
377 }
378 }
379 if level == 0 || level > 2 {
380 return Err(err(line_no, 1, "heading must use # or ##"));
381 }
382 let text = line[level as usize..].trim();
383 if text.is_empty() {
384 return Err(err(line_no, 1, "heading text is empty"));
385 }
386 Ok(Block::Heading {
387 level,
388 align,
389 inlines: parse_inlines(text, line_no, level as usize + 1)?,
390 })
391}
392
393fn parse_directive(line: &str, line_no: usize, default_align: Align) -> Result<Block, ParseError> {
394 let body = line
395 .trim_start()
396 .strip_prefix('@')
397 .ok_or_else(|| err(line_no, 1, "expected directive"))?;
398 let mut parts = body.split_whitespace();
399 let name = parts.next().unwrap_or("").to_ascii_lowercase();
400 match name.as_str() {
401 "feed" => {
402 let n = parts
403 .next()
404 .ok_or_else(|| err(line_no, 1, "@feed requires line count"))?;
405 let lines: u8 = n
406 .parse()
407 .map_err(|_| err(line_no, 1, "@feed count must be 0-255"))?;
408 Ok(Block::Feed(lines))
409 }
410 "cut" => Ok(Block::Cut),
411 "image" => parse_image_directive(parts.collect(), line_no, default_align),
412 "barcode" => parse_barcode_directive(parts.collect(), line_no, default_align),
413 "qr" => parse_qr_directive(parts.collect(), line_no, default_align),
414 "date" => parse_date_directive(parts.collect(), line_no, default_align),
415 "time" => parse_time_directive(parts.collect(), line_no, default_align),
416 _ => Err(err(line_no, 1, format!("unknown directive @{name}"))),
417 }
418}
419
420fn parse_image_directive(
421 parts: Vec<&str>,
422 line_no: usize,
423 default_align: Align,
424) -> Result<Block, ParseError> {
425 if parts.is_empty() {
426 return Err(err(line_no, 1, "@image requires a path"));
427 }
428 let path = parts[0].to_string();
429 let mut width = ImageWidth::Default;
430 let mut align = default_align;
431 for attr in &parts[1..] {
432 if let Some((k, v)) = attr.split_once('=') {
433 match k.to_ascii_lowercase().as_str() {
434 "width" => {
435 width = if let Some(p) = v.strip_suffix('%') {
436 let pct: u8 = p
437 .parse()
438 .map_err(|_| err(line_no, 1, "invalid width percent"))?;
439 ImageWidth::Percent(pct.min(100))
440 } else {
441 let dots: u16 = v
442 .parse()
443 .map_err(|_| err(line_no, 1, "invalid width dots"))?;
444 ImageWidth::Dots(dots)
445 };
446 }
447 "align" => align = parse_align_value(v, line_no)?,
448 _ => return Err(err(line_no, 1, format!("unknown image attribute {k}"))),
449 }
450 }
451 }
452 Ok(Block::Image { path, width, align })
453}
454
455fn parse_barcode_directive(
456 parts: Vec<&str>,
457 line_no: usize,
458 default_align: Align,
459) -> Result<Block, ParseError> {
460 if parts.len() < 2 {
461 return Err(err(
462 line_no,
463 1,
464 "@barcode requires symbology and data (or RASTER symbology data)",
465 ));
466 }
467
468 let (mode, sym_idx, data_idx) = if parts[0].eq_ignore_ascii_case("RASTER") {
469 if parts.len() < 3 {
470 return Err(err(
471 line_no,
472 1,
473 "@barcode RASTER requires symbology and data",
474 ));
475 }
476 (BarcodeMode::Raster, 1, 2)
477 } else {
478 (BarcodeMode::Native, 0, 1)
479 };
480
481 let symbology = BarcodeSymbology::from_name(parts[sym_idx])
482 .ok_or_else(|| err(line_no, 1, format!("unknown barcode symbology {}", parts[sym_idx])))?;
483
484 if mode == BarcodeMode::Native && !symbology.supports_native() {
485 return Err(err(
486 line_no,
487 1,
488 format!(
489 "{} has no native ESC/POS support; use RASTER {}",
490 symbology.as_str(),
491 symbology.as_str()
492 ),
493 ));
494 }
495
496 let (data, attrs) = take_data_tokens(&parts, data_idx, line_no, "@barcode")?;
497 let mut height = 64u8;
498 let mut align = default_align;
499 // Default off: many printers print HRI under native barcodes otherwise.
500 let mut show_text = false;
501 for attr in attrs {
502 if let Some((k, v)) = attr.split_once('=') {
503 match k.to_ascii_lowercase().as_str() {
504 "height" => {
505 height = v
506 .parse()
507 .map_err(|_| err(line_no, 1, "invalid barcode height"))?;
508 }
509 "align" => align = parse_align_value(v, line_no)?,
510 "show_text" => show_text = v == "true",
511 _ => return Err(err(line_no, 1, format!("unknown barcode attribute {k}"))),
512 }
513 } else {
514 return Err(err(
515 line_no,
516 1,
517 format!("unexpected barcode token '{attr}' (attributes use key=value)"),
518 ));
519 }
520 }
521 Ok(Block::Barcode {
522 mode,
523 symbology,
524 data,
525 height,
526 align,
527 show_text,
528 })
529}
530
531fn parse_date_directive(
532 parts: Vec<&str>,
533 _line_no: usize,
534 default_align: Align,
535) -> Result<Block, ParseError> {
536 let pattern = parts.join(" ");
537 let format = if pattern.is_empty() {
538 None
539 } else {
540 Some(pattern)
541 };
542 Ok(Block::Date {
543 format,
544 align: default_align,
545 })
546}
547
548fn parse_time_directive(
549 parts: Vec<&str>,
550 line_no: usize,
551 default_align: Align,
552) -> Result<Block, ParseError> {
553 use super::TimeFormatSpec;
554 let spec = match parts.first().map(|s| s.to_ascii_lowercase()).as_deref() {
555 None => TimeFormatSpec::Hours24,
556 Some("12h") => TimeFormatSpec::Hours12,
557 Some("24h") => TimeFormatSpec::Hours24,
558 Some(other) => {
559 return Err(err(
560 line_no,
561 1,
562 format!("unknown @time format '{other}' (use 12h or 24h)"),
563 ));
564 }
565 };
566 if parts.len() > 1 {
567 return Err(err(
568 line_no,
569 1,
570 "@time accepts at most one format argument (12h or 24h)",
571 ));
572 }
573 Ok(Block::Time {
574 format: spec,
575 align: default_align,
576 })
577}
578
579fn parse_qr_directive(
580 parts: Vec<&str>,
581 line_no: usize,
582 default_align: Align,
583) -> Result<Block, ParseError> {
584 if parts.is_empty() {
585 return Err(err(line_no, 1, "@qr requires data"));
586 }
587
588 let (mode, data_idx) = if parts[0].eq_ignore_ascii_case("RASTER") {
589 if parts.len() < 2 {
590 return Err(err(line_no, 1, "@qr RASTER requires data"));
591 }
592 (QrMode::Raster, 1)
593 } else {
594 (QrMode::Native, 0)
595 };
596
597 let (data, attrs) = take_data_tokens(&parts, data_idx, line_no, "@qr")?;
598 let mut size = 4u8;
599 let mut ecc = QrEcc::M;
600 let mut align = default_align;
601 let mut version = None;
602 for attr in attrs {
603 if let Some((k, v)) = attr.split_once('=') {
604 match k.to_ascii_lowercase().as_str() {
605 "size" => {
606 size = v
607 .parse::<u8>()
608 .map_err(|_| err(line_no, 1, "invalid qr size"))?
609 .clamp(1, 16);
610 }
611 "scale" => {
612 size = v
613 .parse::<u8>()
614 .map_err(|_| err(line_no, 1, "invalid qr scale"))?
615 .clamp(1, 16);
616 }
617 "version" => {
618 let ver: u8 = v
619 .parse()
620 .map_err(|_| err(line_no, 1, "invalid qr version"))?;
621 if !(1..=40).contains(&ver) {
622 return Err(err(line_no, 1, "qr version must be 1-40"));
623 }
624 version = Some(ver);
625 }
626 "ecc" => {
627 ecc = QrEcc::from_name(v)
628 .ok_or_else(|| err(line_no, 1, "qr ecc must be L, M, Q, or H"))?;
629 }
630 "align" => align = parse_align_value(v, line_no)?,
631 _ => return Err(err(line_no, 1, format!("unknown qr attribute {k}"))),
632 }
633 } else {
634 return Err(err(
635 line_no,
636 1,
637 format!("unexpected qr token '{attr}' (attributes use key=value)"),
638 ));
639 }
640 }
641 Ok(Block::Qr {
642 mode,
643 data,
644 size,
645 ecc,
646 version,
647 align,
648 })
649}
650
651fn parse_align_value(value: &str, line_no: usize) -> Result<Align, ParseError> {
652 match value.to_ascii_lowercase().as_str() {
653 "left" => Ok(Align::Left),
654 "center" | "centre" => Ok(Align::Center),
655 "right" => Ok(Align::Right),
656 _ => Err(err(line_no, 1, "align must be left, center, or right")),
657 }
658}
659
660/// Collect data tokens from `data_idx` until the first `key=value` attribute.
661/// Remaining tokens are returned as attributes (must all be `key=value`).
662///
663/// Tokens that contain `=` inside a URL/query (e.g. `https://x?a=1`) are still
664/// treated as data — only simple identifier keys count as attributes.
665fn take_data_tokens<'a>(
666 parts: &'a [&str],
667 data_idx: usize,
668 line_no: usize,
669 directive: &str,
670) -> Result<(String, &'a [&'a str]), ParseError> {
671 if data_idx >= parts.len() {
672 return Err(err(line_no, 1, format!("{directive} requires data")));
673 }
674 if looks_like_attribute_token(parts[data_idx]) {
675 return Err(err(
676 line_no,
677 1,
678 format!("{directive} data cannot start with an attribute"),
679 ));
680 }
681 let mut data_end = data_idx + 1;
682 while data_end < parts.len() && !looks_like_attribute_token(parts[data_end]) {
683 data_end += 1;
684 }
685 let data = parts[data_idx..data_end].join(" ");
686 Ok((data, &parts[data_end..]))
687}
688
689/// True for tokens like `size=4` / `align=center`, false for URLs with `?a=1`.
690fn looks_like_attribute_token(token: &str) -> bool {
691 let Some((key, _value)) = token.split_once('=') else {
692 return false;
693 };
694 if key.is_empty() {
695 return false;
696 }
697 key.chars()
698 .all(|c| c.is_ascii_alphanumeric() || c == '_')
699}
700
701fn is_list_item_line(line: &str) -> bool {
702 line.trim_start().starts_with("- ")
703}
704
705/// Nesting depth from leading whitespace: two spaces (or one tab) per level.
706fn list_item_depth(line: &str) -> u8 {
707 let mut spaces = 0u32;
708 for ch in line.chars() {
709 match ch {
710 ' ' => spaces += 1,
711 '\t' => spaces += 2,
712 _ => break,
713 }
714 }
715 spaces.div_euclid(2).min(u32::from(u8::MAX)) as u8
716}
717
718fn list_item_text(line: &str) -> &str {
719 line.trim_start()
720 .strip_prefix("- ")
721 .map(str::trim_end)
722 .unwrap_or(line.trim_end())
723}
724
725fn parse_list_item(line: &str, line_no: usize) -> Result<ListItem, ParseError> {
726 Ok(ListItem {
727 depth: list_item_depth(line),
728 inlines: parse_inlines(list_item_text(line), line_no, 1)?,
729 })
730}
731
732fn parse_inlines(input: &str, line: usize, col: usize) -> Result<Vec<Inline>, ParseError> {
733 let mut out = Vec::new();
734 let mut i = 0usize;
735 let chars: Vec<char> = input.chars().collect();
736 while i < chars.len() {
737 if chars[i] == '$' && i + 1 < chars.len() {
738 match chars[i + 1] {
739 '{' => {
740 let start = i + 2;
741 let mut j = start;
742 while j < chars.len() && chars[j] != '}' {
743 j += 1;
744 }
745 if j >= chars.len() {
746 return Err(err(line, col + i, "unclosed parameter ${...}"));
747 }
748 let name: String = chars[start..j].iter().collect();
749 if !is_valid_param_name(&name) {
750 return Err(err(
751 line,
752 col + i,
753 format!("invalid parameter name '{name}'"),
754 ));
755 }
756 out.push(Inline::Param(name));
757 i = j + 1;
758 continue;
759 }
760 '[' => {
761 let start = i + 2;
762 let mut j = start;
763 while j < chars.len() && chars[j] != ']' {
764 j += 1;
765 }
766 if j >= chars.len() {
767 return Err(err(line, col + i, "unclosed parameter $[...]"));
768 }
769 let name: String = chars[start..j].iter().collect();
770 if !is_valid_param_name(&name) {
771 return Err(err(
772 line,
773 col + i,
774 format!("invalid checkbox parameter name '{name}'"),
775 ));
776 }
777 out.push(Inline::CheckboxParam(name));
778 i = j + 1;
779 continue;
780 }
781 _ => {}
782 }
783 }
784 if let Some((checked, consumed)) = try_parse_checkbox(&chars[i..]) {
785 out.push(Inline::Checkbox { checked });
786 i += consumed;
787 continue;
788 }
789 let start = i;
790 while i < chars.len() && chars[i] != '$' {
791 // Stop before a checkbox so it becomes its own inline.
792 if try_parse_checkbox(&chars[i..]).is_some() {
793 break;
794 }
795 i += 1;
796 }
797 if i == start {
798 i += 1;
799 continue;
800 }
801 out.push(Inline::Text(chars[start..i].iter().collect()));
802 }
803 Ok(out)
804}
805
806/// Parse `[]`, `[ ]`, `[x]`, or `[X]` at the start of `chars`.
807/// Returns `(checked, chars_consumed)`.
808fn try_parse_checkbox(chars: &[char]) -> Option<(bool, usize)> {
809 if chars.first() != Some(&'[') {
810 return None;
811 }
812 match chars.get(1) {
813 Some(']') => Some((false, 2)),
814 Some(' ') if chars.get(2) == Some(&']') => Some((false, 3)),
815 Some('x' | 'X') if chars.get(2) == Some(&']') => Some((true, 3)),
816 _ => None,
817 }
818}
819
820fn is_valid_param_name(name: &str) -> bool {
821 let mut chars = name.chars();
822 match chars.next() {
823 Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
824 _ => return false,
825 }
826 chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
827}
828
829fn err(line: usize, column: usize, message: impl Into<String>) -> ParseError {
830 ParseError {
831 line,
832 column,
833 message: message.into(),
834 }
835}
836
837#[cfg(test)]
838mod tests {
839 use super::*;
840 use crate::dsl::{BarcodeMode, BarcodeSymbology, Inline, TimeFormatSpec};
841
842 fn inlines_to_text(inlines: &[Inline]) -> String {
843 let mut out = String::new();
844 for inline in inlines {
845 match inline {
846 Inline::Text(t) | Inline::Param(t) | Inline::CheckboxParam(t) => out.push_str(t),
847 Inline::Checkbox { checked } => {
848 out.push_str(crate::dsl::checkbox_glyph(*checked));
849 }
850 }
851 }
852 out
853 }
854
855 #[test]
856 fn parses_inline_checkboxes() {
857 let doc = parse("[] empty\n[ ] spaced\n[x] done\n[X] also").unwrap();
858 assert_eq!(doc.blocks.len(), 1);
859 let Block::Paragraph { inlines, .. } = &doc.blocks[0] else {
860 panic!("expected paragraph");
861 };
862 let glyphs: Vec<_> = inlines
863 .iter()
864 .filter_map(|i| match i {
865 Inline::Checkbox { checked } => Some(*checked),
866 _ => None,
867 })
868 .collect();
869 assert_eq!(glyphs, vec![false, false, true, true]);
870 }
871
872 #[test]
873 fn parses_checkbox_param() {
874 let doc = parse("$[Paid] ok").unwrap();
875 let Block::Paragraph { inlines, .. } = &doc.blocks[0] else {
876 panic!("expected paragraph");
877 };
878 assert!(matches!(
879 &inlines[0],
880 Inline::CheckboxParam(name) if name == "Paid"
881 ));
882 }
883
884 #[test]
885 fn rejects_same_name_as_text_and_checkbox_param() {
886 let err = parse("${Paid}\n$[Paid]").unwrap_err();
887 assert!(
888 err.message.contains("cannot be both"),
889 "unexpected error: {}",
890 err.message
891 );
892 }
893
894 #[test]
895 fn parses_heading_and_paragraph() {
896 let doc = parse("# Store\nHello world").unwrap();
897 assert_eq!(doc.blocks.len(), 2);
898 assert!(matches!(doc.blocks[0], Block::Heading { level: 1, .. }));
899 assert!(matches!(doc.blocks[1], Block::Paragraph { .. }));
900 }
901
902 #[test]
903 fn preserves_leading_spaces_in_paragraph() {
904 let doc = parse(" hoi").unwrap();
905 let Block::Paragraph { inlines, .. } = &doc.blocks[0] else {
906 panic!("expected paragraph");
907 };
908 assert_eq!(inlines_to_text(inlines), " hoi");
909 }
910
911 #[test]
912 fn trims_trailing_but_keeps_leading_spaces() {
913 let doc = parse(" hello ").unwrap();
914 let Block::Paragraph { inlines, .. } = &doc.blocks[0] else {
915 panic!("expected paragraph");
916 };
917 assert_eq!(inlines_to_text(inlines), " hello");
918 }
919
920 #[test]
921 fn parses_bullet_list() {
922 let doc = parse("- this\n- is then\n- a list").unwrap();
923 assert_eq!(doc.blocks.len(), 1);
924 let Block::List { items, .. } = &doc.blocks[0] else {
925 panic!("expected list");
926 };
927 assert_eq!(items.len(), 3);
928 assert_eq!(inlines_to_text(&items[0].inlines), "this");
929 assert_eq!(inlines_to_text(&items[1].inlines), "is then");
930 assert_eq!(inlines_to_text(&items[2].inlines), "a list");
931 assert_eq!(items[0].depth, 0);
932 }
933
934 #[test]
935 fn parses_nested_bullet_list() {
936 let doc = parse("- Groceries\n - Milk\n - Eggs\n- Wash car").unwrap();
937 let Block::List { items, .. } = &doc.blocks[0] else {
938 panic!("expected list");
939 };
940 assert_eq!(items.len(), 4);
941 assert_eq!(items[0].depth, 0);
942 assert_eq!(inlines_to_text(&items[0].inlines), "Groceries");
943 assert_eq!(items[1].depth, 1);
944 assert_eq!(inlines_to_text(&items[1].inlines), "Milk");
945 assert_eq!(items[2].depth, 1);
946 assert_eq!(items[3].depth, 0);
947 assert_eq!(inlines_to_text(&items[3].inlines), "Wash car");
948 }
949
950 #[test]
951 fn blank_line_breaks_bullet_list() {
952 let doc = parse("- one\n\n- two").unwrap();
953 assert_eq!(doc.blocks.len(), 3);
954 assert!(matches!(doc.blocks[0], Block::List { .. }));
955 assert!(matches!(doc.blocks[1], Block::Feed(1)));
956 assert!(matches!(doc.blocks[2], Block::List { .. }));
957 }
958
959 #[test]
960 fn parses_parameters() {
961 let doc = parse("Order ${OrderId}").unwrap();
962 let Block::Paragraph { inlines, .. } = &doc.blocks[0] else {
963 panic!("expected paragraph");
964 };
965 assert!(matches!(
966 inlines.as_slice(),
967 [
968 Inline::Text(_),
969 Inline::Param(name)
970 ] if name == "OrderId"
971 ));
972 }
973
974 #[test]
975 fn dedupes_collect_is_separate_module() {
976 let doc = parse("@barcode CODE128 ${A}\n@qr ${A}").unwrap();
977 assert_eq!(doc.blocks.len(), 2);
978 }
979
980 #[test]
981 fn strips_comments() {
982 let doc = parse("<!-- hidden -->Visible").unwrap();
983 assert_eq!(doc.blocks.len(), 1);
984 let doc = parse("<!-- hidden -->\nVisible").unwrap();
985 assert!(matches!(doc.blocks[0], Block::Feed(1)));
986 }
987
988 #[test]
989 fn rejects_unknown_directive() {
990 assert!(parse("@unknown x").is_err());
991 }
992
993 #[test]
994 fn parses_alignment_prefix() {
995 let doc = parse(":center:\nCentered").unwrap();
996 let Block::Paragraph { align, .. } = &doc.blocks[0] else {
997 panic!();
998 };
999 assert_eq!(*align, Align::Center);
1000 }
1001
1002 #[test]
1003 fn persistent_center_applies_to_heading_and_directives() {
1004 let doc = parse(
1005 ":center:\n# Hello\n@qr ${Data}\n@barcode RASTER CODE128 ${Data}\n:left:\nLeft\n",
1006 )
1007 .unwrap();
1008 assert_eq!(doc.blocks.len(), 4);
1009 assert!(matches!(
1010 doc.blocks[0],
1011 Block::Heading {
1012 align: Align::Center,
1013 ..
1014 }
1015 ));
1016 assert!(matches!(
1017 doc.blocks[1],
1018 Block::Qr {
1019 align: Align::Center,
1020 ..
1021 }
1022 ));
1023 assert!(matches!(
1024 doc.blocks[2],
1025 Block::Barcode {
1026 align: Align::Center,
1027 ..
1028 }
1029 ));
1030 assert!(matches!(
1031 doc.blocks[3],
1032 Block::Paragraph {
1033 align: Align::Left,
1034 ..
1035 }
1036 ));
1037 }
1038
1039 #[test]
1040 fn persistent_center_groups_following_paragraph_lines() {
1041 let doc = parse(":center:\nLine one\nLine two").unwrap();
1042 assert_eq!(doc.blocks.len(), 1);
1043 let Block::Paragraph { align, inlines } = &doc.blocks[0] else {
1044 panic!();
1045 };
1046 assert_eq!(*align, Align::Center);
1047 assert_eq!(inlines_to_text(inlines), "Line one\nLine two");
1048 }
1049
1050 #[test]
1051 fn align_prefix_on_same_line_sets_persistent_state() {
1052 let doc = parse(":center: Inline\nNext").unwrap();
1053 assert_eq!(doc.blocks.len(), 1);
1054 let Block::Paragraph { align, inlines } = &doc.blocks[0] else {
1055 panic!();
1056 };
1057 assert_eq!(*align, Align::Center);
1058 assert_eq!(inlines_to_text(inlines), "Inline\nNext");
1059 }
1060
1061 #[test]
1062 fn multiple_align_prefixes_on_one_line() {
1063 let doc = parse(":left:left :right:right").unwrap();
1064 assert_eq!(doc.blocks.len(), 1);
1065 let Block::AlignedRow { parts } = &doc.blocks[0] else {
1066 panic!("expected AlignedRow, got {:?}", doc.blocks[0]);
1067 };
1068 assert_eq!(parts.len(), 2);
1069 assert_eq!(parts[0].0, Align::Left);
1070 assert_eq!(parts[1].0, Align::Right);
1071 assert_eq!(inlines_to_text(&parts[0].1), "left");
1072 assert_eq!(inlines_to_text(&parts[1].1), "right");
1073 }
1074
1075 #[test]
1076 fn right_before_left_keeps_source_part_order_in_ast() {
1077 let doc = parse(":right:10:left:appel").unwrap();
1078 let Block::AlignedRow { parts } = &doc.blocks[0] else {
1079 panic!();
1080 };
1081 assert_eq!(parts[0].0, Align::Right);
1082 assert_eq!(inlines_to_text(&parts[0].1), "10");
1083 assert_eq!(parts[1].0, Align::Left);
1084 assert_eq!(inlines_to_text(&parts[1].1), "appel");
1085 }
1086
1087 #[test]
1088 fn align_only_line_does_not_emit_block() {
1089 let doc = parse(":center:\n:center:").unwrap();
1090 assert!(doc.blocks.is_empty());
1091 }
1092
1093 #[test]
1094 fn parses_date_and_time_directives() {
1095 let doc = parse("@date\n@date DD-YYYY-MM\n@time\n@time 12h").unwrap();
1096 assert!(matches!(
1097 doc.blocks[0],
1098 Block::Date {
1099 format: None,
1100 ..
1101 }
1102 ));
1103 assert!(matches!(
1104 doc.blocks[1],
1105 Block::Date {
1106 format: Some(ref f),
1107 ..
1108 } if f == "DD-YYYY-MM"
1109 ));
1110 assert!(matches!(
1111 doc.blocks[2],
1112 Block::Time {
1113 format: TimeFormatSpec::Hours24,
1114 ..
1115 }
1116 ));
1117 assert!(matches!(
1118 doc.blocks[3],
1119 Block::Time {
1120 format: TimeFormatSpec::Hours12,
1121 ..
1122 }
1123 ));
1124 }
1125
1126 #[test]
1127 fn rejects_unknown_time_format() {
1128 assert!(parse("@time 24").is_err());
1129 }
1130
1131 #[test]
1132 fn blank_line_inserts_feed() {
1133 let doc = parse("A\n\nB").unwrap();
1134 assert!(matches!(doc.blocks[1], Block::Feed(1)));
1135 }
1136
1137 #[test]
1138 fn whitespace_only_line_inserts_feed() {
1139 let doc = parse("A\n \nB").unwrap();
1140 assert!(matches!(doc.blocks[1], Block::Feed(1)));
1141 }
1142
1143 #[test]
1144 fn document_ends_with_cut_ignores_trailing_blank_lines() {
1145 let doc = parse("Line\n@cut\n\n").unwrap();
1146 assert!(document_ends_with_cut(&doc));
1147 }
1148
1149 #[test]
1150 fn document_without_cut_at_end() {
1151 let doc = parse("Line\n@feed 1").unwrap();
1152 assert!(!document_ends_with_cut(&doc));
1153 }
1154
1155 #[test]
1156 fn blank_line_between_barcode_and_qr_is_feed() {
1157 let doc = parse("@barcode RASTER CODE128 X\n\n:center:@qr RASTER Y scale=4").unwrap();
1158 assert!(matches!(
1159 doc.blocks.as_slice(),
1160 [
1161 Block::Barcode { .. },
1162 Block::Feed(1),
1163 Block::Qr { .. },
1164 ]
1165 ));
1166 }
1167
1168 #[test]
1169 fn dsl_marker_lines_are_not_feed() {
1170 for src in [
1171 ":left:\nNext",
1172 ":center:\nNext",
1173 ":right:\nNext",
1174 ":centre:\nNext",
1175 "# Title\n",
1176 "---\n",
1177 "@cut\n",
1178 ] {
1179 let doc = parse(src).unwrap();
1180 assert!(
1181 !doc.blocks.iter().any(|b| matches!(b, Block::Feed(1))),
1182 "unexpected feed for {src:?}"
1183 );
1184 }
1185 }
1186
1187 #[test]
1188 fn parses_raster_barcode() {
1189 let doc = parse("@barcode RASTER CODE128 ABC").unwrap();
1190 assert!(matches!(
1191 doc.blocks[0],
1192 Block::Barcode {
1193 mode: BarcodeMode::Raster,
1194 symbology: BarcodeSymbology::Code128,
1195 ..
1196 }
1197 ));
1198 }
1199
1200 #[test]
1201 fn barcode_data_joins_words_until_attributes() {
1202 let doc = parse("@barcode RASTER CODE128 hallo wereld height=80").unwrap();
1203 match &doc.blocks[0] {
1204 Block::Barcode {
1205 data,
1206 height,
1207 show_text,
1208 ..
1209 } => {
1210 assert_eq!(data, "hallo wereld");
1211 assert_eq!(*height, 80);
1212 assert!(!*show_text);
1213 }
1214 other => panic!("expected barcode, got {other:?}"),
1215 }
1216 }
1217
1218 #[test]
1219 fn barcode_show_text_defaults_false_and_can_enable() {
1220 let off = parse("@barcode CODE128 ABC").unwrap();
1221 match &off.blocks[0] {
1222 Block::Barcode { show_text, .. } => assert!(!*show_text),
1223 other => panic!("expected barcode, got {other:?}"),
1224 }
1225 let on = parse("@barcode CODE128 ABC show_text=true").unwrap();
1226 match &on.blocks[0] {
1227 Block::Barcode { show_text, .. } => assert!(*show_text),
1228 other => panic!("expected barcode, got {other:?}"),
1229 }
1230 }
1231
1232 #[test]
1233 fn qr_data_joins_words_until_attributes() {
1234 let doc = parse("@qr hallo wereld size=6").unwrap();
1235 match &doc.blocks[0] {
1236 Block::Qr { data, size, .. } => {
1237 assert_eq!(data, "hallo wereld");
1238 assert_eq!(*size, 6);
1239 }
1240 other => panic!("expected qr, got {other:?}"),
1241 }
1242 }
1243
1244 #[test]
1245 fn qr_url_with_query_equals_is_data_not_attribute() {
1246 let doc = parse(
1247 "@qr https://sleutels.kvt.nl/moirai/index.php?t=l&d=5CD146GMCC size=4 ecc=M align=center",
1248 )
1249 .unwrap();
1250 match &doc.blocks[0] {
1251 Block::Qr {
1252 data,
1253 size,
1254 ecc,
1255 align,
1256 ..
1257 } => {
1258 assert_eq!(
1259 data,
1260 "https://sleutels.kvt.nl/moirai/index.php?t=l&d=5CD146GMCC"
1261 );
1262 assert_eq!(*size, 4);
1263 assert_eq!(*ecc, QrEcc::M);
1264 assert_eq!(*align, Align::Center);
1265 }
1266 other => panic!("expected qr, got {other:?}"),
1267 }
1268 }
1269
1270 #[test]
1271 fn barcode_url_with_query_equals_is_data() {
1272 let doc = parse("@barcode RASTER CODE128 https://example.com/x?a=1&b=2 height=40").unwrap();
1273 match &doc.blocks[0] {
1274 Block::Barcode { data, height, .. } => {
1275 assert_eq!(data, "https://example.com/x?a=1&b=2");
1276 assert_eq!(*height, 40);
1277 }
1278 other => panic!("expected barcode, got {other:?}"),
1279 }
1280 }
1281}