BlueGit

timfa posprint

Files

posprint / src / dsl / parser.rs

parser.rs

parser.rs 33.7 KiB Download Raw
1use super::{
2 Align, BarcodeMode, BarcodeSymbology, Block, Document, ImageWidth, Inline, ParseError, QrEcc,
3 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_inlines(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_inlines(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 {
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
613fn list_item_text(line: &str) -> &str {
614 line.trim_start()
615 .strip_prefix("- ")
616 .map(str::trim_end)
617 .unwrap_or(line.trim_end())
618}
619
620fn parse_list_item_inlines(line: &str, line_no: usize) -> Result<Vec<Inline>, ParseError> {
621 parse_inlines(list_item_text(line), line_no, 1)
622}
623
624fn parse_inlines(input: &str, line: usize, col: usize) -> Result<Vec<Inline>, ParseError> {
625 let mut out = Vec::new();
626 let mut i = 0usize;
627 let chars: Vec<char> = input.chars().collect();
628 while i < chars.len() {
629 if chars[i] == '$' && i + 1 < chars.len() {
630 match chars[i + 1] {
631 '{' => {
632 let start = i + 2;
633 let mut j = start;
634 while j < chars.len() && chars[j] != '}' {
635 j += 1;
636 }
637 if j >= chars.len() {
638 return Err(err(line, col + i, "unclosed parameter ${...}"));
639 }
640 let name: String = chars[start..j].iter().collect();
641 if !is_valid_param_name(&name) {
642 return Err(err(
643 line,
644 col + i,
645 format!("invalid parameter name '{name}'"),
646 ));
647 }
648 out.push(Inline::Param(name));
649 i = j + 1;
650 continue;
651 }
652 '[' => {
653 let start = i + 2;
654 let mut j = start;
655 while j < chars.len() && chars[j] != ']' {
656 j += 1;
657 }
658 if j >= chars.len() {
659 return Err(err(line, col + i, "unclosed parameter $[...]"));
660 }
661 let name: String = chars[start..j].iter().collect();
662 if !is_valid_param_name(&name) {
663 return Err(err(
664 line,
665 col + i,
666 format!("invalid checkbox parameter name '{name}'"),
667 ));
668 }
669 out.push(Inline::CheckboxParam(name));
670 i = j + 1;
671 continue;
672 }
673 _ => {}
674 }
675 }
676 if let Some((checked, consumed)) = try_parse_checkbox(&chars[i..]) {
677 out.push(Inline::Checkbox { checked });
678 i += consumed;
679 continue;
680 }
681 let start = i;
682 while i < chars.len() && chars[i] != '$' {
683 // Stop before a checkbox so it becomes its own inline.
684 if try_parse_checkbox(&chars[i..]).is_some() {
685 break;
686 }
687 i += 1;
688 }
689 if i == start {
690 i += 1;
691 continue;
692 }
693 out.push(Inline::Text(chars[start..i].iter().collect()));
694 }
695 Ok(out)
696}
697
698/// Parse `[]`, `[ ]`, `[x]`, `[X]`, or `[√]` at the start of `chars`.
699/// Returns `(checked, chars_consumed)`.
700fn try_parse_checkbox(chars: &[char]) -> Option<(bool, usize)> {
701 if chars.first() != Some(&'[') {
702 return None;
703 }
704 match chars.get(1) {
705 Some(']') => Some((false, 2)),
706 Some(' ') if chars.get(2) == Some(&']') => Some((false, 3)),
707 Some('x' | 'X' | '\u{221A}') if chars.get(2) == Some(&']') => Some((true, 3)),
708 _ => None,
709 }
710}
711
712fn is_valid_param_name(name: &str) -> bool {
713 let mut chars = name.chars();
714 match chars.next() {
715 Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
716 _ => return false,
717 }
718 chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
719}
720
721fn err(line: usize, column: usize, message: impl Into<String>) -> ParseError {
722 ParseError {
723 line,
724 column,
725 message: message.into(),
726 }
727}
728
729#[cfg(test)]
730mod tests {
731 use super::*;
732 use crate::dsl::{BarcodeMode, BarcodeSymbology, Inline, TimeFormatSpec};
733
734 fn inlines_to_text(inlines: &[Inline]) -> String {
735 let mut out = String::new();
736 for inline in inlines {
737 match inline {
738 Inline::Text(t) | Inline::Param(t) | Inline::CheckboxParam(t) => out.push_str(t),
739 Inline::Checkbox { checked } => {
740 out.push_str(crate::dsl::checkbox_glyph(*checked));
741 }
742 }
743 }
744 out
745 }
746
747 #[test]
748 fn parses_inline_checkboxes() {
749 let doc = parse("[] empty\n[ ] spaced\n[x] done\n[X] also").unwrap();
750 assert_eq!(doc.blocks.len(), 1);
751 let Block::Paragraph { inlines, .. } = &doc.blocks[0] else {
752 panic!("expected paragraph");
753 };
754 let glyphs: Vec<_> = inlines
755 .iter()
756 .filter_map(|i| match i {
757 Inline::Checkbox { checked } => Some(*checked),
758 _ => None,
759 })
760 .collect();
761 assert_eq!(glyphs, vec![false, false, true, true]);
762 }
763
764 #[test]
765 fn parses_checkbox_param() {
766 let doc = parse("$[Paid] ok").unwrap();
767 let Block::Paragraph { inlines, .. } = &doc.blocks[0] else {
768 panic!("expected paragraph");
769 };
770 assert!(matches!(
771 &inlines[0],
772 Inline::CheckboxParam(name) if name == "Paid"
773 ));
774 }
775
776 #[test]
777 fn rejects_same_name_as_text_and_checkbox_param() {
778 let err = parse("${Paid}\n$[Paid]").unwrap_err();
779 assert!(
780 err.message.contains("cannot be both"),
781 "unexpected error: {}",
782 err.message
783 );
784 }
785
786 #[test]
787 fn parses_heading_and_paragraph() {
788 let doc = parse("# Store\nHello world").unwrap();
789 assert_eq!(doc.blocks.len(), 2);
790 assert!(matches!(doc.blocks[0], Block::Heading { level: 1, .. }));
791 assert!(matches!(doc.blocks[1], Block::Paragraph { .. }));
792 }
793
794 #[test]
795 fn parses_bullet_list() {
796 let doc = parse("- this\n- is then\n- a list").unwrap();
797 assert_eq!(doc.blocks.len(), 1);
798 let Block::List { items, .. } = &doc.blocks[0] else {
799 panic!("expected list");
800 };
801 assert_eq!(items.len(), 3);
802 assert_eq!(inlines_to_text(&items[0]), "this");
803 assert_eq!(inlines_to_text(&items[1]), "is then");
804 assert_eq!(inlines_to_text(&items[2]), "a list");
805 }
806
807 #[test]
808 fn blank_line_breaks_bullet_list() {
809 let doc = parse("- one\n\n- two").unwrap();
810 assert_eq!(doc.blocks.len(), 3);
811 assert!(matches!(doc.blocks[0], Block::List { .. }));
812 assert!(matches!(doc.blocks[1], Block::Feed(1)));
813 assert!(matches!(doc.blocks[2], Block::List { .. }));
814 }
815
816 #[test]
817 fn parses_parameters() {
818 let doc = parse("Order ${OrderId}").unwrap();
819 let Block::Paragraph { inlines, .. } = &doc.blocks[0] else {
820 panic!("expected paragraph");
821 };
822 assert!(matches!(
823 inlines.as_slice(),
824 [
825 Inline::Text(_),
826 Inline::Param(name)
827 ] if name == "OrderId"
828 ));
829 }
830
831 #[test]
832 fn dedupes_collect_is_separate_module() {
833 let doc = parse("@barcode CODE128 ${A}\n@qr ${A}").unwrap();
834 assert_eq!(doc.blocks.len(), 2);
835 }
836
837 #[test]
838 fn strips_comments() {
839 let doc = parse("<!-- hidden -->Visible").unwrap();
840 assert_eq!(doc.blocks.len(), 1);
841 let doc = parse("<!-- hidden -->\nVisible").unwrap();
842 assert!(matches!(doc.blocks[0], Block::Feed(1)));
843 }
844
845 #[test]
846 fn rejects_unknown_directive() {
847 assert!(parse("@unknown x").is_err());
848 }
849
850 #[test]
851 fn parses_alignment_prefix() {
852 let doc = parse(":center:\nCentered").unwrap();
853 let Block::Paragraph { align, .. } = &doc.blocks[0] else {
854 panic!();
855 };
856 assert_eq!(*align, Align::Center);
857 }
858
859 #[test]
860 fn persistent_center_applies_to_heading_and_directives() {
861 let doc = parse(
862 ":center:\n# Hello\n@qr ${Data}\n@barcode RASTER CODE128 ${Data}\n:left:\nLeft\n",
863 )
864 .unwrap();
865 assert_eq!(doc.blocks.len(), 4);
866 assert!(matches!(
867 doc.blocks[0],
868 Block::Heading {
869 align: Align::Center,
870 ..
871 }
872 ));
873 assert!(matches!(
874 doc.blocks[1],
875 Block::Qr {
876 align: Align::Center,
877 ..
878 }
879 ));
880 assert!(matches!(
881 doc.blocks[2],
882 Block::Barcode {
883 align: Align::Center,
884 ..
885 }
886 ));
887 assert!(matches!(
888 doc.blocks[3],
889 Block::Paragraph {
890 align: Align::Left,
891 ..
892 }
893 ));
894 }
895
896 #[test]
897 fn persistent_center_groups_following_paragraph_lines() {
898 let doc = parse(":center:\nLine one\nLine two").unwrap();
899 assert_eq!(doc.blocks.len(), 1);
900 let Block::Paragraph { align, inlines } = &doc.blocks[0] else {
901 panic!();
902 };
903 assert_eq!(*align, Align::Center);
904 assert_eq!(inlines_to_text(inlines), "Line one\nLine two");
905 }
906
907 #[test]
908 fn align_prefix_on_same_line_sets_persistent_state() {
909 let doc = parse(":center: Inline\nNext").unwrap();
910 assert_eq!(doc.blocks.len(), 1);
911 let Block::Paragraph { align, inlines } = &doc.blocks[0] else {
912 panic!();
913 };
914 assert_eq!(*align, Align::Center);
915 assert_eq!(inlines_to_text(inlines), "Inline\nNext");
916 }
917
918 #[test]
919 fn multiple_align_prefixes_on_one_line() {
920 let doc = parse(":left:left :right:right").unwrap();
921 assert_eq!(doc.blocks.len(), 2);
922 assert!(matches!(
923 doc.blocks[0],
924 Block::Paragraph {
925 align: Align::Left,
926 ..
927 }
928 ));
929 assert!(matches!(
930 doc.blocks[1],
931 Block::Paragraph {
932 align: Align::Right,
933 ..
934 }
935 ));
936 let Block::Paragraph { inlines: left, .. } = &doc.blocks[0] else {
937 panic!();
938 };
939 let Block::Paragraph { inlines: right, .. } = &doc.blocks[1] else {
940 panic!();
941 };
942 assert_eq!(inlines_to_text(left), "left");
943 assert_eq!(inlines_to_text(right), "right");
944 }
945
946 #[test]
947 fn align_only_line_does_not_emit_block() {
948 let doc = parse(":center:\n:center:").unwrap();
949 assert!(doc.blocks.is_empty());
950 }
951
952 #[test]
953 fn parses_date_and_time_directives() {
954 let doc = parse("@date\n@date DD-YYYY-MM\n@time\n@time 12h").unwrap();
955 assert!(matches!(
956 doc.blocks[0],
957 Block::Date {
958 format: None,
959 ..
960 }
961 ));
962 assert!(matches!(
963 doc.blocks[1],
964 Block::Date {
965 format: Some(ref f),
966 ..
967 } if f == "DD-YYYY-MM"
968 ));
969 assert!(matches!(
970 doc.blocks[2],
971 Block::Time {
972 format: TimeFormatSpec::Hours24,
973 ..
974 }
975 ));
976 assert!(matches!(
977 doc.blocks[3],
978 Block::Time {
979 format: TimeFormatSpec::Hours12,
980 ..
981 }
982 ));
983 }
984
985 #[test]
986 fn rejects_unknown_time_format() {
987 assert!(parse("@time 24").is_err());
988 }
989
990 #[test]
991 fn blank_line_inserts_feed() {
992 let doc = parse("A\n\nB").unwrap();
993 assert!(matches!(doc.blocks[1], Block::Feed(1)));
994 }
995
996 #[test]
997 fn whitespace_only_line_inserts_feed() {
998 let doc = parse("A\n \nB").unwrap();
999 assert!(matches!(doc.blocks[1], Block::Feed(1)));
1000 }
1001
1002 #[test]
1003 fn document_ends_with_cut_ignores_trailing_blank_lines() {
1004 let doc = parse("Line\n@cut\n\n").unwrap();
1005 assert!(document_ends_with_cut(&doc));
1006 }
1007
1008 #[test]
1009 fn document_without_cut_at_end() {
1010 let doc = parse("Line\n@feed 1").unwrap();
1011 assert!(!document_ends_with_cut(&doc));
1012 }
1013
1014 #[test]
1015 fn blank_line_between_barcode_and_qr_is_feed() {
1016 let doc = parse("@barcode RASTER CODE128 X\n\n:center:@qr RASTER Y scale=4").unwrap();
1017 assert!(matches!(
1018 doc.blocks.as_slice(),
1019 [
1020 Block::Barcode { .. },
1021 Block::Feed(1),
1022 Block::Qr { .. },
1023 ]
1024 ));
1025 }
1026
1027 #[test]
1028 fn dsl_marker_lines_are_not_feed() {
1029 for src in [
1030 ":left:\nNext",
1031 ":center:\nNext",
1032 ":right:\nNext",
1033 ":centre:\nNext",
1034 "# Title\n",
1035 "---\n",
1036 "@cut\n",
1037 ] {
1038 let doc = parse(src).unwrap();
1039 assert!(
1040 !doc.blocks.iter().any(|b| matches!(b, Block::Feed(1))),
1041 "unexpected feed for {src:?}"
1042 );
1043 }
1044 }
1045
1046 #[test]
1047 fn parses_raster_barcode() {
1048 let doc = parse("@barcode RASTER CODE128 ABC").unwrap();
1049 assert!(matches!(
1050 doc.blocks[0],
1051 Block::Barcode {
1052 mode: BarcodeMode::Raster,
1053 symbology: BarcodeSymbology::Code128,
1054 ..
1055 }
1056 ));
1057 }
1058}