pvg 0.2.0

Deterministic Procedural Vector Graphics (PVG) core engine with microsecond CPU evaluation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
use crate::ast::Color;
use crate::error::PvgError;

#[derive(Debug, Clone, PartialEq)]
pub enum TokenKind {
    Indent,
    Dedent,
    Newline,
    Eof,

    // Literals
    Number(f64),
    String(String),
    Color(Color),
    Ident(String),

    // Keywords
    Pvg,
    Canvas,
    Background,
    Snap,
    Filter,
    Param,
    Pattern,
    Sprite,
    Spline,
    Palette,
    Data,
    Row,
    Set,
    Def,
    Return,
    For,
    From,
    To,
    Step,
    While,
    If,
    Else,
    Seed,

    // Shapes & Elements
    Circle,
    Ellipse,
    Rectangle,
    Line,
    Polygon,
    Path,
    Text,
    Group,
    Clip,

    // Properties
    Center,
    Radius,
    Pos,
    Size,
    Points,
    Content,
    Font,
    Align,
    Fill,
    Stroke,
    Width,
    Opacity,
    Rot,
    Scale,
    Cap,
    Join,
    Miter,
    Dash,
    Blend,
    Blur,
    Shadow,
    Glow,

    // Gradient keywords (PVG 0.2)
    Linear,
    Radial,
    Angular,
    Stop,

    // Path commands
    Start,
    Quad,
    Curve,
    Arc,
    Close,

    // Symbols & Operators
    LBracket,
    RBracket,
    LParen,
    RParen,
    Comma,
    Question,
    Colon,
    Plus,
    Minus,
    Star,
    Slash,
    Percent,
    Caret,
    Equal,
    EqualEqual,
    NotEqual,
    Less,
    LessEqual,
    Greater,
    GreaterEqual,
    And,
    Or,
    Not,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Token {
    pub kind: TokenKind,
    pub line: usize,
    pub col: usize,
}

pub struct Lexer<'a> {
    source: &'a str,
    indent_stack: Vec<usize>,
}

impl<'a> Lexer<'a> {
    pub fn new(source: &'a str) -> Self {
        Self {
            source,
            indent_stack: vec![0],
        }
    }

    pub fn tokenize_all(&mut self) -> Result<Vec<Token>, PvgError> {
        let lines: Vec<&str> = self.source.lines().collect();
        let mut tokens = Vec::new();
        let mut li: usize = 0;

        while li < lines.len() {
            let line_num = li + 1;
            let raw_line = lines[li];

            let bytes = raw_line.as_bytes();
            let mut spaces = 0;
            while spaces < bytes.len() && bytes[spaces] == b' ' {
                spaces += 1;
            }

            if spaces < bytes.len() && bytes[spaces] == b'\t' {
                return Err(PvgError::lex(
                    line_num,
                    spaces + 1,
                    "Tabs are forbidden. Use 2 spaces for indentation.",
                ));
            }

            if spaces == bytes.len() || bytes[spaces] == b'#' {
                li += 1;
                continue;
            }

            let current_indent = *self.indent_stack.last().unwrap();
            if spaces > current_indent {
                self.indent_stack.push(spaces);
                tokens.push(Token {
                    kind: TokenKind::Indent,
                    line: line_num,
                    col: spaces + 1,
                });
            } else if spaces < current_indent {
                while let Some(&last) = self.indent_stack.last() {
                    if spaces < last {
                        self.indent_stack.pop();
                        tokens.push(Token {
                            kind: TokenKind::Dedent,
                            line: line_num,
                            col: spaces + 1,
                        });
                    } else if spaces == last {
                        break;
                    } else {
                        return Err(PvgError::lex(
                            line_num,
                            spaces + 1,
                            "Inconsistent indentation level.",
                        ));
                    }
                }
            }

            let content = &raw_line[spaces..];
            // Triple-quoted strings (`"""`) may span lines (sprite art, text
            // blocks). They consume whole following lines as raw content.
            let extra = if triple_opener_before_comment(content) {
                self.tokenize_line_with_triple(
                    content, &lines, &mut li, line_num, spaces + 1, spaces, &mut tokens,
                )?
            } else {
                self.tokenize_line(content, line_num, spaces + 1, &mut tokens)?;
                0
            };
            tokens.push(Token {
                kind: TokenKind::Newline,
                line: line_num,
                col: raw_line.len() + 1,
            });
            li += 1 + extra;
        }

        let last_line = lines.len().max(1);
        while self.indent_stack.len() > 1 {
            self.indent_stack.pop();
            tokens.push(Token {
                kind: TokenKind::Dedent,
                line: last_line,
                col: 1,
            });
        }

        tokens.push(Token {
            kind: TokenKind::Eof,
            line: last_line,
            col: 1,
        });

        Ok(tokens)
    }

    /// Lexes a line containing a `"""` opener. Emits the prefix tokens, one
    /// raw multi-line `String` token, and any same-line tail. Returns how many
    /// *extra* source lines were consumed (continuation + closer lines).
    #[allow(clippy::too_many_arguments)]
    fn tokenize_line_with_triple(
        &self,
        content: &str,
        lines: &[&str],
        li: &mut usize,
        line_num: usize,
        col_offset: usize,
        base_spaces: usize,
        tokens: &mut Vec<Token>,
    ) -> Result<usize, PvgError> {
        let open = content.find("\"\"\"").unwrap();
        let (prefix, rest) = content.split_at(open);
        if !prefix.trim().is_empty() {
            self.tokenize_line(prefix, line_num, col_offset, tokens)?;
        }
        let open_col = col_offset + open;
        let after_open = &rest[3..];

        // Opener and closer on the same line: `data """..11.."""`.
        if let Some(close) = after_open.find("\"\"\"") {
            tokens.push(Token {
                kind: TokenKind::String(after_open[..close].to_string()),
                line: line_num,
                col: open_col,
            });
            let tail = &after_open[close + 3..];
            if !tail.trim().is_empty() {
                self.tokenize_line(tail, line_num, open_col + 3 + close + 3, tokens)?;
            }
            return Ok(0);
        }

        // Multi-line form: the opener must end the line (a trailing
        // `# comment` is allowed).
        {
            let tail = after_open.trim_start();
            if !(tail.is_empty() || tail.starts_with('#')) {
                return Err(PvgError::lex(
                    line_num,
                    open_col,
                    "Multi-line \"\"\" strings must start at the end of the line (e.g. `data \"\"\"`).",
                ));
            }
        }

        let mut body: Vec<String> = Vec::new();
        let mut extra = 0usize;
        loop {
            let nli = *li + 1 + extra;
            if nli >= lines.len() {
                return Err(PvgError::lex(line_num, open_col, "Unclosed triple-quoted string."));
            }
            let l = lines[nli];
            let lb = l.as_bytes();
            let mut sp = 0;
            while sp < lb.len() && lb[sp] == b' ' {
                sp += 1;
            }
            if l[sp..].starts_with("\"\"\"") {
                let tail = &l[sp + 3..];
                // A trailing `# comment` after the closer is allowed.
                let tail_trim = tail.trim_start();
                if !(tail_trim.is_empty() || tail_trim.starts_with('#')) {
                    return Err(PvgError::lex(
                        nli + 1,
                        sp + 4,
                        "Unexpected content after closing \"\"\".",
                    ));
                }
                extra += 1; // consume the closer line itself
                break;
            }
            // Dedent continuation lines by the opener's block indent so art
            // and text blocks read naturally (leading spaces are transparent
            // in sprites anyway).
            let mut cut = 0;
            while cut < base_spaces && cut < lb.len() && lb[cut] == b' ' {
                cut += 1;
            }
            body.push(l[cut..].to_string());
            extra += 1;
        }

        tokens.push(Token {
            kind: TokenKind::String(body.join("\n")),
            line: line_num,
            col: open_col,
        });
        Ok(extra)
    }

    fn tokenize_line(
        &self,
        text: &str,
        line_num: usize,
        col_offset: usize,
        tokens: &mut Vec<Token>,
    ) -> Result<(), PvgError> {
        let bytes = text.as_bytes();
        let len = bytes.len();
        let mut i = 0;

        while i < len {
            let b = bytes[i];
            if b == b' ' || b == b'\t' || b == b'\r' {
                i += 1;
                continue;
            }

            let col = col_offset + i;

            if b == b'#' {
                let mut hex_end = i + 1;
                while hex_end < len && bytes[hex_end].is_ascii_hexdigit() {
                    hex_end += 1;
                }
                let hex_len = hex_end - (i + 1);
                if hex_len == 3 || hex_len == 6 || hex_len == 8 {
                    let is_delim = hex_end == len
                        || bytes[hex_end].is_ascii_whitespace()
                        || bytes[hex_end] == b']'
                        || bytes[hex_end] == b')'
                        || bytes[hex_end] == b','
                        || bytes[hex_end] == b':';
                    if is_delim {
                        let hex_str = std::str::from_utf8(&bytes[i..hex_end]).unwrap();
                        if let Some(col_val) = Color::from_hex(hex_str) {
                            tokens.push(Token {
                                kind: TokenKind::Color(col_val),
                                line: line_num,
                                col,
                            });
                            i = hex_end;
                            continue;
                        }
                    }
                }
                break;
            }

            if b == b'[' { tokens.push(Token { kind: TokenKind::LBracket, line: line_num, col }); i += 1; continue; }
            if b == b']' { tokens.push(Token { kind: TokenKind::RBracket, line: line_num, col }); i += 1; continue; }
            if b == b'(' { tokens.push(Token { kind: TokenKind::LParen, line: line_num, col }); i += 1; continue; }
            if b == b')' { tokens.push(Token { kind: TokenKind::RParen, line: line_num, col }); i += 1; continue; }
            if b == b',' { tokens.push(Token { kind: TokenKind::Comma, line: line_num, col }); i += 1; continue; }
            if b == b'?' { tokens.push(Token { kind: TokenKind::Question, line: line_num, col }); i += 1; continue; }
            if b == b':' { tokens.push(Token { kind: TokenKind::Colon, line: line_num, col }); i += 1; continue; }
            if b == b'^' { tokens.push(Token { kind: TokenKind::Caret, line: line_num, col }); i += 1; continue; }

            if b == b'=' {
                if i + 1 < len && bytes[i + 1] == b'=' {
                    tokens.push(Token { kind: TokenKind::EqualEqual, line: line_num, col });
                    i += 2;
                } else {
                    tokens.push(Token { kind: TokenKind::Equal, line: line_num, col });
                    i += 1;
                }
                continue;
            }

            if b == b'!' {
                if i + 1 < len && bytes[i + 1] == b'=' {
                    tokens.push(Token { kind: TokenKind::NotEqual, line: line_num, col });
                    i += 2;
                } else {
                    tokens.push(Token { kind: TokenKind::Not, line: line_num, col });
                    i += 1;
                }
                continue;
            }

            if b == b'<' {
                if i + 1 < len && bytes[i + 1] == b'=' {
                    tokens.push(Token { kind: TokenKind::LessEqual, line: line_num, col });
                    i += 2;
                } else {
                    tokens.push(Token { kind: TokenKind::Less, line: line_num, col });
                    i += 1;
                }
                continue;
            }

            if b == b'>' {
                if i + 1 < len && bytes[i + 1] == b'=' {
                    tokens.push(Token { kind: TokenKind::GreaterEqual, line: line_num, col });
                    i += 2;
                } else {
                    tokens.push(Token { kind: TokenKind::Greater, line: line_num, col });
                    i += 1;
                }
                continue;
            }

            if b == b'&' && i + 1 < len && bytes[i + 1] == b'&' {
                tokens.push(Token { kind: TokenKind::And, line: line_num, col });
                i += 2;
                continue;
            }
            if b == b'|' && i + 1 < len && bytes[i + 1] == b'|' {
                tokens.push(Token { kind: TokenKind::Or, line: line_num, col });
                i += 2;
                continue;
            }

            if b == b'+' { tokens.push(Token { kind: TokenKind::Plus, line: line_num, col }); i += 1; continue; }
            if b == b'-' { tokens.push(Token { kind: TokenKind::Minus, line: line_num, col }); i += 1; continue; }
            if b == b'*' { tokens.push(Token { kind: TokenKind::Star, line: line_num, col }); i += 1; continue; }
            if b == b'/' { tokens.push(Token { kind: TokenKind::Slash, line: line_num, col }); i += 1; continue; }
            if b == b'%' { tokens.push(Token { kind: TokenKind::Percent, line: line_num, col }); i += 1; continue; }

            // UTF-8 Clean String Tokenizer
            if b == b'"' {
                i += 1;
                let mut s = String::new();
                let mut closed = false;
                let remaining = &text[i..];
                let mut chars = remaining.char_indices();

                while let Some((c_idx, ch)) = chars.next() {
                    if ch == '\\' {
                        if let Some((_, next_ch)) = chars.next() {
                            match next_ch {
                                'n' => s.push('\n'),
                                't' => s.push('\t'),
                                'r' => s.push('\r'),
                                '"' => s.push('"'),
                                '\\' => s.push('\\'),
                                other => s.push(other),
                            }
                        } else {
                            break;
                        }
                    } else if ch == '"' {
                        closed = true;
                        i += c_idx + 1;
                        break;
                    } else {
                        s.push(ch);
                    }
                }

                if !closed {
                    return Err(PvgError::lex(line_num, col, "Unclosed string literal."));
                }
                tokens.push(Token { kind: TokenKind::String(s), line: line_num, col });
                continue;
            }

            if b.is_ascii_digit() || (b == b'.' && i + 1 < len && bytes[i + 1].is_ascii_digit()) {
                let start = i;
                let mut has_dot = false;
                while i < len && (bytes[i].is_ascii_digit() || (!has_dot && bytes[i] == b'.')) {
                    if bytes[i] == b'.' {
                        has_dot = true;
                    }
                    i += 1;
                }
                let num_str = std::str::from_utf8(&bytes[start..i]).unwrap();
                let mut val = num_str
                    .parse::<f64>()
                    .map_err(|e| PvgError::lex(line_num, col, format!("Invalid number: {}", e)))?;

                if i + 3 <= len && &bytes[i..i + 3] == b"deg" {
                    val = val.to_radians();
                    i += 3;
                } else if i + 3 <= len && &bytes[i..i + 3] == b"rad" {
                    i += 3;
                }

                tokens.push(Token { kind: TokenKind::Number(val), line: line_num, col });
                continue;
            }

            if b.is_ascii_alphabetic() || b == b'_' {
                let start = i;
                while i < len && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_' || bytes[i] == b'-') {
                    i += 1;
                }
                let ident = std::str::from_utf8(&bytes[start..i]).unwrap();
                let kind = match ident {
                    "PVG" | "CPSVG" => TokenKind::Pvg,
                    "canvas" => TokenKind::Canvas,
                    "background" => TokenKind::Background,
                    "snap" => TokenKind::Snap,
                    "filter" => TokenKind::Filter,
                    "param" => TokenKind::Param,
                    "pattern" => TokenKind::Pattern,
                    "sprite" => TokenKind::Sprite,
                    "spline" => TokenKind::Spline,
                    "palette" => TokenKind::Palette,
                    "data" => TokenKind::Data,
                    "row" => TokenKind::Row,
                    "set" => TokenKind::Set,
                    "def" => TokenKind::Def,
                    "return" => TokenKind::Return,
                    "for" => TokenKind::For,
                    "from" => TokenKind::From,
                    "to" => TokenKind::To,
                    "step" => TokenKind::Step,
                    "while" => TokenKind::While,
                    "if" => TokenKind::If,
                    "else" => TokenKind::Else,
                    "seed" => TokenKind::Seed,
                    "circle" => TokenKind::Circle,
                    "ellipse" => TokenKind::Ellipse,
                    "rectangle" | "rect" => TokenKind::Rectangle,
                    "line" => TokenKind::Line,
                    "polygon" => TokenKind::Polygon,
                    "path" => TokenKind::Path,
                    "text" => TokenKind::Text,
                    "group" => TokenKind::Group,
                    "clip" => TokenKind::Clip,
                    "center" => TokenKind::Center,
                    "radius" => TokenKind::Radius,
                    "pos" => TokenKind::Pos,
                    "size" => TokenKind::Size,
                    "points" => TokenKind::Points,
                    "content" => TokenKind::Content,
                    "font" => TokenKind::Font,
                    "align" => TokenKind::Align,
                    "fill" => TokenKind::Fill,
                    "stroke" => TokenKind::Stroke,
                    "width" => TokenKind::Width,
                    "opacity" => TokenKind::Opacity,
                    "rot" => TokenKind::Rot,
                    "scale" => TokenKind::Scale,
                    "cap" => TokenKind::Cap,
                    "join" => TokenKind::Join,
                    "miter" => TokenKind::Miter,
                    "dash" => TokenKind::Dash,
                    "blend" => TokenKind::Blend,
                    "blur" => TokenKind::Blur,
                    "shadow" => TokenKind::Shadow,
                    "glow" => TokenKind::Glow,
                    "linear" => TokenKind::Linear,
                    "radial" => TokenKind::Radial,
                    "angular" | "conic" => TokenKind::Angular,
                    "stop" => TokenKind::Stop,
                    "start" => TokenKind::Start,
                    "quad" => TokenKind::Quad,
                    "curve" => TokenKind::Curve,
                    "arc" => TokenKind::Arc,
                    "close" => TokenKind::Close,
                    "and" => TokenKind::And,
                    "or" => TokenKind::Or,
                    "not" => TokenKind::Not,
                    "black" => TokenKind::Color(Color::BLACK),
                    "white" => TokenKind::Color(Color::WHITE),
                    "red" => TokenKind::Color(Color::RED),
                    "green" => TokenKind::Color(Color::GREEN),
                    "blue" => TokenKind::Color(Color::BLUE),
                    "yellow" => TokenKind::Color(Color::YELLOW),
                    "cyan" => TokenKind::Color(Color::CYAN),
                    "magenta" => TokenKind::Color(Color::MAGENTA),
                    "none" | "transparent" => TokenKind::Color(Color::None),
                    "true" => TokenKind::Ident("true".into()),
                    "false" => TokenKind::Ident("false".into()),
                    _ => TokenKind::Ident(ident.to_string()),
                };
                tokens.push(Token { kind, line: line_num, col });
                continue;
            }

            return Err(PvgError::lex(
                line_num,
                col,
                format!("Unexpected character '{}'.", b as char),
            ));
        }

        Ok(())
    }
}

/// Reports whether a `"""` opener appears on this line *before* any real `#`
/// comment start (mirroring `tokenize_line`'s hex-color rule so `#fff`-style
/// colors don't count as comments).
fn triple_opener_before_comment(content: &str) -> bool {
    let bytes = content.as_bytes();
    let open = match content.find("\"\"\"") {
        Some(i) => i,
        None => return false,
    };
    let mut i = 0;
    while i < open {
        if bytes[i] == b'#' {
            let mut hex_end = i + 1;
            while hex_end < bytes.len() && bytes[hex_end].is_ascii_hexdigit() {
                hex_end += 1;
            }
            let hex_len = hex_end - (i + 1);
            if hex_len == 3 || hex_len == 6 || hex_len == 8 {
                let is_delim = hex_end == bytes.len()
                    || bytes[hex_end].is_ascii_whitespace()
                    || matches!(bytes[hex_end], b']' | b')' | b',' | b':' | b'"');
                if is_delim {
                    i = hex_end;
                    continue;
                }
            }
            // A real comment starts here; the `"""` is inside it.
            return false;
        }
        i += 1;
    }
    true
}