BlueGit

timfa posprint

Files

posprint / src / dsl / parser.rs

parser.rs

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