| 1 | use super::{
|
| 2 | Align, BarcodeMode, BarcodeSymbology, Block, Document, ImageWidth, Inline, ListItem, ParseError,
|
| 3 | QrEcc, QrMode,
|
| 4 | };
|
| 5 |
|
| 6 | pub 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 |
|
| 136 | fn 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 |
|
| 156 | fn 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 |
|
| 213 | fn 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).
|
| 234 | pub 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 |
|
| 245 | fn 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).
|
| 279 | fn 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.
|
| 289 | fn 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.
|
| 324 | fn 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 |
|
| 345 | fn 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.
|
| 366 | fn is_blank_feed_line(line: &str) -> bool {
|
| 367 | line.chars().all(|c| c.is_whitespace())
|
| 368 | }
|
| 369 |
|
| 370 | fn 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 |
|
| 393 | fn 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 |
|
| 420 | fn 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 |
|
| 455 | fn 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 |
|
| 531 | fn 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 |
|
| 548 | fn 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 |
|
| 579 | fn 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 |
|
| 651 | fn 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 | fn take_data_tokens<'a>(
|
| 663 | parts: &'a [&str],
|
| 664 | data_idx: usize,
|
| 665 | line_no: usize,
|
| 666 | directive: &str,
|
| 667 | ) -> Result<(String, &'a [&'a str]), ParseError> {
|
| 668 | if data_idx >= parts.len() {
|
| 669 | return Err(err(line_no, 1, format!("{directive} requires data")));
|
| 670 | }
|
| 671 | if parts[data_idx].contains('=') {
|
| 672 | return Err(err(
|
| 673 | line_no,
|
| 674 | 1,
|
| 675 | format!("{directive} data cannot start with an attribute"),
|
| 676 | ));
|
| 677 | }
|
| 678 | let mut data_end = data_idx + 1;
|
| 679 | while data_end < parts.len() && !parts[data_end].contains('=') {
|
| 680 | data_end += 1;
|
| 681 | }
|
| 682 | let data = parts[data_idx..data_end].join(" ");
|
| 683 | Ok((data, &parts[data_end..]))
|
| 684 | }
|
| 685 |
|
| 686 | fn is_list_item_line(line: &str) -> bool {
|
| 687 | line.trim_start().starts_with("- ")
|
| 688 | }
|
| 689 |
|
| 690 | /// Nesting depth from leading whitespace: two spaces (or one tab) per level.
|
| 691 | fn list_item_depth(line: &str) -> u8 {
|
| 692 | let mut spaces = 0u32;
|
| 693 | for ch in line.chars() {
|
| 694 | match ch {
|
| 695 | ' ' => spaces += 1,
|
| 696 | '\t' => spaces += 2,
|
| 697 | _ => break,
|
| 698 | }
|
| 699 | }
|
| 700 | spaces.div_euclid(2).min(u32::from(u8::MAX)) as u8
|
| 701 | }
|
| 702 |
|
| 703 | fn list_item_text(line: &str) -> &str {
|
| 704 | line.trim_start()
|
| 705 | .strip_prefix("- ")
|
| 706 | .map(str::trim_end)
|
| 707 | .unwrap_or(line.trim_end())
|
| 708 | }
|
| 709 |
|
| 710 | fn parse_list_item(line: &str, line_no: usize) -> Result<ListItem, ParseError> {
|
| 711 | Ok(ListItem {
|
| 712 | depth: list_item_depth(line),
|
| 713 | inlines: parse_inlines(list_item_text(line), line_no, 1)?,
|
| 714 | })
|
| 715 | }
|
| 716 |
|
| 717 | fn parse_inlines(input: &str, line: usize, col: usize) -> Result<Vec<Inline>, ParseError> {
|
| 718 | let mut out = Vec::new();
|
| 719 | let mut i = 0usize;
|
| 720 | let chars: Vec<char> = input.chars().collect();
|
| 721 | while i < chars.len() {
|
| 722 | if chars[i] == '$' && i + 1 < chars.len() {
|
| 723 | match chars[i + 1] {
|
| 724 | '{' => {
|
| 725 | let start = i + 2;
|
| 726 | let mut j = start;
|
| 727 | while j < chars.len() && chars[j] != '}' {
|
| 728 | j += 1;
|
| 729 | }
|
| 730 | if j >= chars.len() {
|
| 731 | return Err(err(line, col + i, "unclosed parameter ${...}"));
|
| 732 | }
|
| 733 | let name: String = chars[start..j].iter().collect();
|
| 734 | if !is_valid_param_name(&name) {
|
| 735 | return Err(err(
|
| 736 | line,
|
| 737 | col + i,
|
| 738 | format!("invalid parameter name '{name}'"),
|
| 739 | ));
|
| 740 | }
|
| 741 | out.push(Inline::Param(name));
|
| 742 | i = j + 1;
|
| 743 | continue;
|
| 744 | }
|
| 745 | '[' => {
|
| 746 | let start = i + 2;
|
| 747 | let mut j = start;
|
| 748 | while j < chars.len() && chars[j] != ']' {
|
| 749 | j += 1;
|
| 750 | }
|
| 751 | if j >= chars.len() {
|
| 752 | return Err(err(line, col + i, "unclosed parameter $[...]"));
|
| 753 | }
|
| 754 | let name: String = chars[start..j].iter().collect();
|
| 755 | if !is_valid_param_name(&name) {
|
| 756 | return Err(err(
|
| 757 | line,
|
| 758 | col + i,
|
| 759 | format!("invalid checkbox parameter name '{name}'"),
|
| 760 | ));
|
| 761 | }
|
| 762 | out.push(Inline::CheckboxParam(name));
|
| 763 | i = j + 1;
|
| 764 | continue;
|
| 765 | }
|
| 766 | _ => {}
|
| 767 | }
|
| 768 | }
|
| 769 | if let Some((checked, consumed)) = try_parse_checkbox(&chars[i..]) {
|
| 770 | out.push(Inline::Checkbox { checked });
|
| 771 | i += consumed;
|
| 772 | continue;
|
| 773 | }
|
| 774 | let start = i;
|
| 775 | while i < chars.len() && chars[i] != '$' {
|
| 776 | // Stop before a checkbox so it becomes its own inline.
|
| 777 | if try_parse_checkbox(&chars[i..]).is_some() {
|
| 778 | break;
|
| 779 | }
|
| 780 | i += 1;
|
| 781 | }
|
| 782 | if i == start {
|
| 783 | i += 1;
|
| 784 | continue;
|
| 785 | }
|
| 786 | out.push(Inline::Text(chars[start..i].iter().collect()));
|
| 787 | }
|
| 788 | Ok(out)
|
| 789 | }
|
| 790 |
|
| 791 | /// Parse `[]`, `[ ]`, `[x]`, or `[X]` at the start of `chars`.
|
| 792 | /// Returns `(checked, chars_consumed)`.
|
| 793 | fn try_parse_checkbox(chars: &[char]) -> Option<(bool, usize)> {
|
| 794 | if chars.first() != Some(&'[') {
|
| 795 | return None;
|
| 796 | }
|
| 797 | match chars.get(1) {
|
| 798 | Some(']') => Some((false, 2)),
|
| 799 | Some(' ') if chars.get(2) == Some(&']') => Some((false, 3)),
|
| 800 | Some('x' | 'X') if chars.get(2) == Some(&']') => Some((true, 3)),
|
| 801 | _ => None,
|
| 802 | }
|
| 803 | }
|
| 804 |
|
| 805 | fn is_valid_param_name(name: &str) -> bool {
|
| 806 | let mut chars = name.chars();
|
| 807 | match chars.next() {
|
| 808 | Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
|
| 809 | _ => return false,
|
| 810 | }
|
| 811 | chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
|
| 812 | }
|
| 813 |
|
| 814 | fn err(line: usize, column: usize, message: impl Into<String>) -> ParseError {
|
| 815 | ParseError {
|
| 816 | line,
|
| 817 | column,
|
| 818 | message: message.into(),
|
| 819 | }
|
| 820 | }
|
| 821 |
|
| 822 | #[cfg(test)]
|
| 823 | mod tests {
|
| 824 | use super::*;
|
| 825 | use crate::dsl::{BarcodeMode, BarcodeSymbology, Inline, TimeFormatSpec};
|
| 826 |
|
| 827 | fn inlines_to_text(inlines: &[Inline]) -> String {
|
| 828 | let mut out = String::new();
|
| 829 | for inline in inlines {
|
| 830 | match inline {
|
| 831 | Inline::Text(t) | Inline::Param(t) | Inline::CheckboxParam(t) => out.push_str(t),
|
| 832 | Inline::Checkbox { checked } => {
|
| 833 | out.push_str(crate::dsl::checkbox_glyph(*checked));
|
| 834 | }
|
| 835 | }
|
| 836 | }
|
| 837 | out
|
| 838 | }
|
| 839 |
|
| 840 | #[test]
|
| 841 | fn parses_inline_checkboxes() {
|
| 842 | let doc = parse("[] empty\n[ ] spaced\n[x] done\n[X] also").unwrap();
|
| 843 | assert_eq!(doc.blocks.len(), 1);
|
| 844 | let Block::Paragraph { inlines, .. } = &doc.blocks[0] else {
|
| 845 | panic!("expected paragraph");
|
| 846 | };
|
| 847 | let glyphs: Vec<_> = inlines
|
| 848 | .iter()
|
| 849 | .filter_map(|i| match i {
|
| 850 | Inline::Checkbox { checked } => Some(*checked),
|
| 851 | _ => None,
|
| 852 | })
|
| 853 | .collect();
|
| 854 | assert_eq!(glyphs, vec![false, false, true, true]);
|
| 855 | }
|
| 856 |
|
| 857 | #[test]
|
| 858 | fn parses_checkbox_param() {
|
| 859 | let doc = parse("$[Paid] ok").unwrap();
|
| 860 | let Block::Paragraph { inlines, .. } = &doc.blocks[0] else {
|
| 861 | panic!("expected paragraph");
|
| 862 | };
|
| 863 | assert!(matches!(
|
| 864 | &inlines[0],
|
| 865 | Inline::CheckboxParam(name) if name == "Paid"
|
| 866 | ));
|
| 867 | }
|
| 868 |
|
| 869 | #[test]
|
| 870 | fn rejects_same_name_as_text_and_checkbox_param() {
|
| 871 | let err = parse("${Paid}\n$[Paid]").unwrap_err();
|
| 872 | assert!(
|
| 873 | err.message.contains("cannot be both"),
|
| 874 | "unexpected error: {}",
|
| 875 | err.message
|
| 876 | );
|
| 877 | }
|
| 878 |
|
| 879 | #[test]
|
| 880 | fn parses_heading_and_paragraph() {
|
| 881 | let doc = parse("# Store\nHello world").unwrap();
|
| 882 | assert_eq!(doc.blocks.len(), 2);
|
| 883 | assert!(matches!(doc.blocks[0], Block::Heading { level: 1, .. }));
|
| 884 | assert!(matches!(doc.blocks[1], Block::Paragraph { .. }));
|
| 885 | }
|
| 886 |
|
| 887 | #[test]
|
| 888 | fn preserves_leading_spaces_in_paragraph() {
|
| 889 | let doc = parse(" hoi").unwrap();
|
| 890 | let Block::Paragraph { inlines, .. } = &doc.blocks[0] else {
|
| 891 | panic!("expected paragraph");
|
| 892 | };
|
| 893 | assert_eq!(inlines_to_text(inlines), " hoi");
|
| 894 | }
|
| 895 |
|
| 896 | #[test]
|
| 897 | fn trims_trailing_but_keeps_leading_spaces() {
|
| 898 | let doc = parse(" hello ").unwrap();
|
| 899 | let Block::Paragraph { inlines, .. } = &doc.blocks[0] else {
|
| 900 | panic!("expected paragraph");
|
| 901 | };
|
| 902 | assert_eq!(inlines_to_text(inlines), " hello");
|
| 903 | }
|
| 904 |
|
| 905 | #[test]
|
| 906 | fn parses_bullet_list() {
|
| 907 | let doc = parse("- this\n- is then\n- a list").unwrap();
|
| 908 | assert_eq!(doc.blocks.len(), 1);
|
| 909 | let Block::List { items, .. } = &doc.blocks[0] else {
|
| 910 | panic!("expected list");
|
| 911 | };
|
| 912 | assert_eq!(items.len(), 3);
|
| 913 | assert_eq!(inlines_to_text(&items[0].inlines), "this");
|
| 914 | assert_eq!(inlines_to_text(&items[1].inlines), "is then");
|
| 915 | assert_eq!(inlines_to_text(&items[2].inlines), "a list");
|
| 916 | assert_eq!(items[0].depth, 0);
|
| 917 | }
|
| 918 |
|
| 919 | #[test]
|
| 920 | fn parses_nested_bullet_list() {
|
| 921 | let doc = parse("- Groceries\n - Milk\n - Eggs\n- Wash car").unwrap();
|
| 922 | let Block::List { items, .. } = &doc.blocks[0] else {
|
| 923 | panic!("expected list");
|
| 924 | };
|
| 925 | assert_eq!(items.len(), 4);
|
| 926 | assert_eq!(items[0].depth, 0);
|
| 927 | assert_eq!(inlines_to_text(&items[0].inlines), "Groceries");
|
| 928 | assert_eq!(items[1].depth, 1);
|
| 929 | assert_eq!(inlines_to_text(&items[1].inlines), "Milk");
|
| 930 | assert_eq!(items[2].depth, 1);
|
| 931 | assert_eq!(items[3].depth, 0);
|
| 932 | assert_eq!(inlines_to_text(&items[3].inlines), "Wash car");
|
| 933 | }
|
| 934 |
|
| 935 | #[test]
|
| 936 | fn blank_line_breaks_bullet_list() {
|
| 937 | let doc = parse("- one\n\n- two").unwrap();
|
| 938 | assert_eq!(doc.blocks.len(), 3);
|
| 939 | assert!(matches!(doc.blocks[0], Block::List { .. }));
|
| 940 | assert!(matches!(doc.blocks[1], Block::Feed(1)));
|
| 941 | assert!(matches!(doc.blocks[2], Block::List { .. }));
|
| 942 | }
|
| 943 |
|
| 944 | #[test]
|
| 945 | fn parses_parameters() {
|
| 946 | let doc = parse("Order ${OrderId}").unwrap();
|
| 947 | let Block::Paragraph { inlines, .. } = &doc.blocks[0] else {
|
| 948 | panic!("expected paragraph");
|
| 949 | };
|
| 950 | assert!(matches!(
|
| 951 | inlines.as_slice(),
|
| 952 | [
|
| 953 | Inline::Text(_),
|
| 954 | Inline::Param(name)
|
| 955 | ] if name == "OrderId"
|
| 956 | ));
|
| 957 | }
|
| 958 |
|
| 959 | #[test]
|
| 960 | fn dedupes_collect_is_separate_module() {
|
| 961 | let doc = parse("@barcode CODE128 ${A}\n@qr ${A}").unwrap();
|
| 962 | assert_eq!(doc.blocks.len(), 2);
|
| 963 | }
|
| 964 |
|
| 965 | #[test]
|
| 966 | fn strips_comments() {
|
| 967 | let doc = parse("<!-- hidden -->Visible").unwrap();
|
| 968 | assert_eq!(doc.blocks.len(), 1);
|
| 969 | let doc = parse("<!-- hidden -->\nVisible").unwrap();
|
| 970 | assert!(matches!(doc.blocks[0], Block::Feed(1)));
|
| 971 | }
|
| 972 |
|
| 973 | #[test]
|
| 974 | fn rejects_unknown_directive() {
|
| 975 | assert!(parse("@unknown x").is_err());
|
| 976 | }
|
| 977 |
|
| 978 | #[test]
|
| 979 | fn parses_alignment_prefix() {
|
| 980 | let doc = parse(":center:\nCentered").unwrap();
|
| 981 | let Block::Paragraph { align, .. } = &doc.blocks[0] else {
|
| 982 | panic!();
|
| 983 | };
|
| 984 | assert_eq!(*align, Align::Center);
|
| 985 | }
|
| 986 |
|
| 987 | #[test]
|
| 988 | fn persistent_center_applies_to_heading_and_directives() {
|
| 989 | let doc = parse(
|
| 990 | ":center:\n# Hello\n@qr ${Data}\n@barcode RASTER CODE128 ${Data}\n:left:\nLeft\n",
|
| 991 | )
|
| 992 | .unwrap();
|
| 993 | assert_eq!(doc.blocks.len(), 4);
|
| 994 | assert!(matches!(
|
| 995 | doc.blocks[0],
|
| 996 | Block::Heading {
|
| 997 | align: Align::Center,
|
| 998 | ..
|
| 999 | }
|
| 1000 | ));
|
| 1001 | assert!(matches!(
|
| 1002 | doc.blocks[1],
|
| 1003 | Block::Qr {
|
| 1004 | align: Align::Center,
|
| 1005 | ..
|
| 1006 | }
|
| 1007 | ));
|
| 1008 | assert!(matches!(
|
| 1009 | doc.blocks[2],
|
| 1010 | Block::Barcode {
|
| 1011 | align: Align::Center,
|
| 1012 | ..
|
| 1013 | }
|
| 1014 | ));
|
| 1015 | assert!(matches!(
|
| 1016 | doc.blocks[3],
|
| 1017 | Block::Paragraph {
|
| 1018 | align: Align::Left,
|
| 1019 | ..
|
| 1020 | }
|
| 1021 | ));
|
| 1022 | }
|
| 1023 |
|
| 1024 | #[test]
|
| 1025 | fn persistent_center_groups_following_paragraph_lines() {
|
| 1026 | let doc = parse(":center:\nLine one\nLine two").unwrap();
|
| 1027 | assert_eq!(doc.blocks.len(), 1);
|
| 1028 | let Block::Paragraph { align, inlines } = &doc.blocks[0] else {
|
| 1029 | panic!();
|
| 1030 | };
|
| 1031 | assert_eq!(*align, Align::Center);
|
| 1032 | assert_eq!(inlines_to_text(inlines), "Line one\nLine two");
|
| 1033 | }
|
| 1034 |
|
| 1035 | #[test]
|
| 1036 | fn align_prefix_on_same_line_sets_persistent_state() {
|
| 1037 | let doc = parse(":center: Inline\nNext").unwrap();
|
| 1038 | assert_eq!(doc.blocks.len(), 1);
|
| 1039 | let Block::Paragraph { align, inlines } = &doc.blocks[0] else {
|
| 1040 | panic!();
|
| 1041 | };
|
| 1042 | assert_eq!(*align, Align::Center);
|
| 1043 | assert_eq!(inlines_to_text(inlines), "Inline\nNext");
|
| 1044 | }
|
| 1045 |
|
| 1046 | #[test]
|
| 1047 | fn multiple_align_prefixes_on_one_line() {
|
| 1048 | let doc = parse(":left:left :right:right").unwrap();
|
| 1049 | assert_eq!(doc.blocks.len(), 1);
|
| 1050 | let Block::AlignedRow { parts } = &doc.blocks[0] else {
|
| 1051 | panic!("expected AlignedRow, got {:?}", doc.blocks[0]);
|
| 1052 | };
|
| 1053 | assert_eq!(parts.len(), 2);
|
| 1054 | assert_eq!(parts[0].0, Align::Left);
|
| 1055 | assert_eq!(parts[1].0, Align::Right);
|
| 1056 | assert_eq!(inlines_to_text(&parts[0].1), "left");
|
| 1057 | assert_eq!(inlines_to_text(&parts[1].1), "right");
|
| 1058 | }
|
| 1059 |
|
| 1060 | #[test]
|
| 1061 | fn right_before_left_keeps_source_part_order_in_ast() {
|
| 1062 | let doc = parse(":right:10:left:appel").unwrap();
|
| 1063 | let Block::AlignedRow { parts } = &doc.blocks[0] else {
|
| 1064 | panic!();
|
| 1065 | };
|
| 1066 | assert_eq!(parts[0].0, Align::Right);
|
| 1067 | assert_eq!(inlines_to_text(&parts[0].1), "10");
|
| 1068 | assert_eq!(parts[1].0, Align::Left);
|
| 1069 | assert_eq!(inlines_to_text(&parts[1].1), "appel");
|
| 1070 | }
|
| 1071 |
|
| 1072 | #[test]
|
| 1073 | fn align_only_line_does_not_emit_block() {
|
| 1074 | let doc = parse(":center:\n:center:").unwrap();
|
| 1075 | assert!(doc.blocks.is_empty());
|
| 1076 | }
|
| 1077 |
|
| 1078 | #[test]
|
| 1079 | fn parses_date_and_time_directives() {
|
| 1080 | let doc = parse("@date\n@date DD-YYYY-MM\n@time\n@time 12h").unwrap();
|
| 1081 | assert!(matches!(
|
| 1082 | doc.blocks[0],
|
| 1083 | Block::Date {
|
| 1084 | format: None,
|
| 1085 | ..
|
| 1086 | }
|
| 1087 | ));
|
| 1088 | assert!(matches!(
|
| 1089 | doc.blocks[1],
|
| 1090 | Block::Date {
|
| 1091 | format: Some(ref f),
|
| 1092 | ..
|
| 1093 | } if f == "DD-YYYY-MM"
|
| 1094 | ));
|
| 1095 | assert!(matches!(
|
| 1096 | doc.blocks[2],
|
| 1097 | Block::Time {
|
| 1098 | format: TimeFormatSpec::Hours24,
|
| 1099 | ..
|
| 1100 | }
|
| 1101 | ));
|
| 1102 | assert!(matches!(
|
| 1103 | doc.blocks[3],
|
| 1104 | Block::Time {
|
| 1105 | format: TimeFormatSpec::Hours12,
|
| 1106 | ..
|
| 1107 | }
|
| 1108 | ));
|
| 1109 | }
|
| 1110 |
|
| 1111 | #[test]
|
| 1112 | fn rejects_unknown_time_format() {
|
| 1113 | assert!(parse("@time 24").is_err());
|
| 1114 | }
|
| 1115 |
|
| 1116 | #[test]
|
| 1117 | fn blank_line_inserts_feed() {
|
| 1118 | let doc = parse("A\n\nB").unwrap();
|
| 1119 | assert!(matches!(doc.blocks[1], Block::Feed(1)));
|
| 1120 | }
|
| 1121 |
|
| 1122 | #[test]
|
| 1123 | fn whitespace_only_line_inserts_feed() {
|
| 1124 | let doc = parse("A\n \nB").unwrap();
|
| 1125 | assert!(matches!(doc.blocks[1], Block::Feed(1)));
|
| 1126 | }
|
| 1127 |
|
| 1128 | #[test]
|
| 1129 | fn document_ends_with_cut_ignores_trailing_blank_lines() {
|
| 1130 | let doc = parse("Line\n@cut\n\n").unwrap();
|
| 1131 | assert!(document_ends_with_cut(&doc));
|
| 1132 | }
|
| 1133 |
|
| 1134 | #[test]
|
| 1135 | fn document_without_cut_at_end() {
|
| 1136 | let doc = parse("Line\n@feed 1").unwrap();
|
| 1137 | assert!(!document_ends_with_cut(&doc));
|
| 1138 | }
|
| 1139 |
|
| 1140 | #[test]
|
| 1141 | fn blank_line_between_barcode_and_qr_is_feed() {
|
| 1142 | let doc = parse("@barcode RASTER CODE128 X\n\n:center:@qr RASTER Y scale=4").unwrap();
|
| 1143 | assert!(matches!(
|
| 1144 | doc.blocks.as_slice(),
|
| 1145 | [
|
| 1146 | Block::Barcode { .. },
|
| 1147 | Block::Feed(1),
|
| 1148 | Block::Qr { .. },
|
| 1149 | ]
|
| 1150 | ));
|
| 1151 | }
|
| 1152 |
|
| 1153 | #[test]
|
| 1154 | fn dsl_marker_lines_are_not_feed() {
|
| 1155 | for src in [
|
| 1156 | ":left:\nNext",
|
| 1157 | ":center:\nNext",
|
| 1158 | ":right:\nNext",
|
| 1159 | ":centre:\nNext",
|
| 1160 | "# Title\n",
|
| 1161 | "---\n",
|
| 1162 | "@cut\n",
|
| 1163 | ] {
|
| 1164 | let doc = parse(src).unwrap();
|
| 1165 | assert!(
|
| 1166 | !doc.blocks.iter().any(|b| matches!(b, Block::Feed(1))),
|
| 1167 | "unexpected feed for {src:?}"
|
| 1168 | );
|
| 1169 | }
|
| 1170 | }
|
| 1171 |
|
| 1172 | #[test]
|
| 1173 | fn parses_raster_barcode() {
|
| 1174 | let doc = parse("@barcode RASTER CODE128 ABC").unwrap();
|
| 1175 | assert!(matches!(
|
| 1176 | doc.blocks[0],
|
| 1177 | Block::Barcode {
|
| 1178 | mode: BarcodeMode::Raster,
|
| 1179 | symbology: BarcodeSymbology::Code128,
|
| 1180 | ..
|
| 1181 | }
|
| 1182 | ));
|
| 1183 | }
|
| 1184 |
|
| 1185 | #[test]
|
| 1186 | fn barcode_data_joins_words_until_attributes() {
|
| 1187 | let doc = parse("@barcode RASTER CODE128 hallo wereld height=80").unwrap();
|
| 1188 | match &doc.blocks[0] {
|
| 1189 | Block::Barcode {
|
| 1190 | data,
|
| 1191 | height,
|
| 1192 | show_text,
|
| 1193 | ..
|
| 1194 | } => {
|
| 1195 | assert_eq!(data, "hallo wereld");
|
| 1196 | assert_eq!(*height, 80);
|
| 1197 | assert!(!*show_text);
|
| 1198 | }
|
| 1199 | other => panic!("expected barcode, got {other:?}"),
|
| 1200 | }
|
| 1201 | }
|
| 1202 |
|
| 1203 | #[test]
|
| 1204 | fn barcode_show_text_defaults_false_and_can_enable() {
|
| 1205 | let off = parse("@barcode CODE128 ABC").unwrap();
|
| 1206 | match &off.blocks[0] {
|
| 1207 | Block::Barcode { show_text, .. } => assert!(!*show_text),
|
| 1208 | other => panic!("expected barcode, got {other:?}"),
|
| 1209 | }
|
| 1210 | let on = parse("@barcode CODE128 ABC show_text=true").unwrap();
|
| 1211 | match &on.blocks[0] {
|
| 1212 | Block::Barcode { show_text, .. } => assert!(*show_text),
|
| 1213 | other => panic!("expected barcode, got {other:?}"),
|
| 1214 | }
|
| 1215 | }
|
| 1216 |
|
| 1217 | #[test]
|
| 1218 | fn qr_data_joins_words_until_attributes() {
|
| 1219 | let doc = parse("@qr hallo wereld size=6").unwrap();
|
| 1220 | match &doc.blocks[0] {
|
| 1221 | Block::Qr { data, size, .. } => {
|
| 1222 | assert_eq!(data, "hallo wereld");
|
| 1223 | assert_eq!(*size, 6);
|
| 1224 | }
|
| 1225 | other => panic!("expected qr, got {other:?}"),
|
| 1226 | }
|
| 1227 | }
|
| 1228 | }
|