vize_patina 0.3.0

Patina - The quality checker for Vize code linting
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
//! Diagnostic types for vize_patina linter.
//!
//! Uses `CompactString` for efficient small string storage.

use oxc_diagnostics::OxcDiagnostic;
use oxc_span::Span;
use serde::Serialize;
use vize_carton::CompactString;

/// Lint diagnostic severity
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
    Error,
    Warning,
}

/// Help display level for diagnostics
///
/// Controls how much help text is included in diagnostics.
/// Useful for environments where markdown rendering is unavailable
/// or CLI output where verbose help is distracting.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum HelpLevel {
    /// No help text
    None,
    /// Short help text (first line only, markdown stripped)
    Short,
    /// Full help text with markdown formatting
    #[default]
    Full,
}

impl HelpLevel {
    /// Process help text according to this level
    pub fn process(&self, help: &str) -> Option<String> {
        match self {
            HelpLevel::None => None,
            HelpLevel::Short => Some(strip_markdown_first_line(help)),
            HelpLevel::Full => Some(help.to_string()),
        }
    }
}

/// Strip markdown formatting and return the first meaningful line.
fn strip_markdown_first_line(text: &str) -> String {
    let mut in_code_block = false;
    for line in text.lines() {
        let trimmed = line.trim();
        // Track code fence blocks
        if trimmed.starts_with("```") {
            in_code_block = !in_code_block;
            continue;
        }
        // Skip lines inside code blocks
        if in_code_block {
            continue;
        }
        // Skip empty lines
        if trimmed.is_empty() {
            continue;
        }
        // Strip markdown bold/italic
        let stripped = trimmed.replace("**", "").replace("__", "").replace('`', "");
        // Skip lines that are just markdown headers
        let stripped = stripped.trim_start_matches('#').trim();
        if stripped.is_empty() {
            continue;
        }
        return stripped.to_string();
    }
    text.lines().next().unwrap_or(text).to_string()
}

// ANSI escape codes
const ANSI_BOLD: &str = "\x1b[1m";
const ANSI_BOLD_OFF: &str = "\x1b[22m";
const ANSI_UNDERLINE: &str = "\x1b[4m";
const ANSI_UNDERLINE_OFF: &str = "\x1b[24m";
const ANSI_CYAN: &str = "\x1b[36m";
const ANSI_CYAN_OFF: &str = "\x1b[39m";
const ANSI_DIM: &str = "\x1b[2m";
const ANSI_DIM_OFF: &str = "\x1b[22m";

/// Convert markdown text to ANSI-formatted text for TUI display.
///
/// Supports:
/// - `**bold**` / `__bold__` → ANSI bold
/// - `` `code` `` → cyan
/// - ```` ``` ```` code blocks → indented + dim
/// - `# Header` → bold + underline
fn render_markdown_to_ansi(text: &str) -> String {
    let mut result = String::with_capacity(text.len() + 64);
    let mut in_code_block = false;

    for line in text.lines() {
        let trimmed = line.trim();

        // Handle code fence blocks (check before pushing newline to avoid extra \n)
        if trimmed.starts_with("```") {
            in_code_block = !in_code_block;
            continue;
        }

        if !result.is_empty() {
            result.push('\n');
        }

        // Inside code block: indent + dim
        if in_code_block {
            result.push_str(ANSI_DIM);
            result.push_str("  ");
            result.push_str(line);
            result.push_str(ANSI_DIM_OFF);
            continue;
        }

        // Handle headers: # Header → bold + underline
        if let Some(header_content) = trimmed.strip_prefix("# ") {
            result.push_str(ANSI_BOLD);
            result.push_str(ANSI_UNDERLINE);
            result.push_str(header_content);
            result.push_str(ANSI_UNDERLINE_OFF);
            result.push_str(ANSI_BOLD_OFF);
            continue;
        }
        if let Some(header_content) = trimmed.strip_prefix("## ") {
            result.push_str(ANSI_BOLD);
            result.push_str(ANSI_UNDERLINE);
            result.push_str(header_content);
            result.push_str(ANSI_UNDERLINE_OFF);
            result.push_str(ANSI_BOLD_OFF);
            continue;
        }
        if let Some(header_content) = trimmed.strip_prefix("### ") {
            result.push_str(ANSI_BOLD);
            result.push_str(header_content);
            result.push_str(ANSI_BOLD_OFF);
            continue;
        }

        // Process inline formatting
        render_inline_markdown(&mut result, line);
    }

    result
}

/// Process inline markdown formatting: **bold**, __bold__, `code`
fn render_inline_markdown(out: &mut String, line: &str) {
    let bytes = line.as_bytes();
    let len = bytes.len();
    let mut i = 0;

    while i < len {
        // Inline code: `code`
        if bytes[i] == b'`' {
            if let Some(end) = find_closing_backtick(bytes, i + 1) {
                out.push_str(ANSI_CYAN);
                out.push_str(&line[i + 1..end]);
                out.push_str(ANSI_CYAN_OFF);
                i = end + 1;
                continue;
            }
        }

        // Bold: **text** or __text__
        if i + 1 < len && bytes[i] == b'*' && bytes[i + 1] == b'*' {
            if let Some(end) = find_closing_double(bytes, i + 2, b'*') {
                out.push_str(ANSI_BOLD);
                // Recursively process inline content within bold
                render_inline_markdown(out, &line[i + 2..end]);
                out.push_str(ANSI_BOLD_OFF);
                i = end + 2;
                continue;
            }
        }
        if i + 1 < len && bytes[i] == b'_' && bytes[i + 1] == b'_' {
            if let Some(end) = find_closing_double(bytes, i + 2, b'_') {
                out.push_str(ANSI_BOLD);
                render_inline_markdown(out, &line[i + 2..end]);
                out.push_str(ANSI_BOLD_OFF);
                i = end + 2;
                continue;
            }
        }

        out.push(bytes[i] as char);
        i += 1;
    }
}

/// Find closing backtick for inline code
fn find_closing_backtick(bytes: &[u8], start: usize) -> Option<usize> {
    (start..bytes.len()).find(|&i| bytes[i] == b'`')
}

/// Find closing double delimiter (** or __)
fn find_closing_double(bytes: &[u8], start: usize, ch: u8) -> Option<usize> {
    let mut i = start;
    while i + 1 < bytes.len() {
        if bytes[i] == ch && bytes[i + 1] == ch {
            return Some(i);
        }
        i += 1;
    }
    None
}

/// Render target for help text conversion at output boundaries.
///
/// Help text is stored as raw markdown in `LintDiagnostic.help`.
/// Use this enum with [`render_help`] to convert at the output boundary.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HelpRenderTarget {
    /// CLI/TUI: Convert markdown to ANSI escape codes
    Ansi,
    /// LSP, JSON: Strip markdown syntax for clean text
    PlainText,
    /// WASM/Playground: Pass through as-is (raw markdown)
    Markdown,
}

/// Render help text (raw markdown) for the given target.
///
/// This function should be called at output boundaries, not when creating diagnostics.
pub fn render_help(markdown: &str, target: HelpRenderTarget) -> String {
    match target {
        HelpRenderTarget::Ansi => render_markdown_to_ansi(markdown),
        HelpRenderTarget::PlainText => strip_markdown(markdown),
        HelpRenderTarget::Markdown => markdown.to_string(),
    }
}

/// Strip all markdown formatting from text, producing clean plain text.
fn strip_markdown(text: &str) -> String {
    let mut result = String::with_capacity(text.len());
    let mut in_code_block = false;

    for line in text.lines() {
        let trimmed = line.trim();

        // Handle code fence blocks
        if trimmed.starts_with("```") {
            in_code_block = !in_code_block;
            continue;
        }

        // Inside code block: keep content with indent
        if in_code_block {
            if !result.is_empty() {
                result.push('\n');
            }
            result.push_str("  ");
            result.push_str(trimmed);
            continue;
        }

        // Skip empty lines (but preserve paragraph breaks)
        if trimmed.is_empty() {
            if !result.is_empty() && !result.ends_with('\n') {
                result.push('\n');
            }
            continue;
        }

        if !result.is_empty() && !result.ends_with('\n') {
            result.push('\n');
        }

        // Strip markdown headers
        let content = trimmed
            .strip_prefix("### ")
            .or_else(|| trimmed.strip_prefix("## "))
            .or_else(|| trimmed.strip_prefix("# "))
            .unwrap_or(trimmed);

        // Strip bold/italic markers and inline code backticks
        let content = content.replace("**", "").replace("__", "").replace('`', "");
        result.push_str(content.trim());
    }

    // Trim trailing whitespace/newlines
    let trimmed = result.trim_end();
    trimmed.to_string()
}

/// A text edit for auto-fixing a diagnostic.
///
/// Represents a single text replacement in the source code.
#[derive(Debug, Clone, Serialize)]
pub struct TextEdit {
    /// Start byte offset
    pub start: u32,
    /// End byte offset
    pub end: u32,
    /// Replacement text
    pub new_text: String,
}

impl TextEdit {
    /// Create a new text edit
    #[inline]
    pub fn new(start: u32, end: u32, new_text: impl Into<String>) -> Self {
        Self {
            start,
            end,
            new_text: new_text.into(),
        }
    }

    /// Create an insertion edit
    #[inline]
    pub fn insert(offset: u32, text: impl Into<String>) -> Self {
        Self::new(offset, offset, text)
    }

    /// Create a deletion edit
    #[inline]
    pub fn delete(start: u32, end: u32) -> Self {
        Self::new(start, end, "")
    }

    /// Create a replacement edit
    #[inline]
    pub fn replace(start: u32, end: u32, text: impl Into<String>) -> Self {
        Self::new(start, end, text)
    }
}

/// A fix for a diagnostic, containing one or more text edits.
#[derive(Debug, Clone, Serialize)]
pub struct Fix {
    /// Description of the fix
    pub message: String,
    /// Text edits to apply
    pub edits: Vec<TextEdit>,
}

impl Fix {
    /// Create a new fix with a single edit
    #[inline]
    pub fn new(message: impl Into<String>, edit: TextEdit) -> Self {
        Self {
            message: message.into(),
            edits: vec![edit],
        }
    }

    /// Create a new fix with multiple edits
    #[inline]
    pub fn with_edits(message: impl Into<String>, edits: Vec<TextEdit>) -> Self {
        Self {
            message: message.into(),
            edits,
        }
    }

    /// Apply the fix to a source string
    #[inline]
    pub fn apply(&self, source: &str) -> String {
        let mut result = source.to_string();
        // Apply edits in reverse order to preserve offsets
        let mut edits = self.edits.clone();
        edits.sort_by(|a, b| b.start.cmp(&a.start));

        for edit in edits {
            let start = edit.start as usize;
            let end = edit.end as usize;
            if start <= result.len() && end <= result.len() {
                result.replace_range(start..end, &edit.new_text);
            }
        }
        result
    }
}

/// A lint diagnostic with rich information for display.
///
/// Uses `CompactString` for message storage - strings up to 24 bytes
/// are stored inline without heap allocation.
#[derive(Debug, Clone)]
pub struct LintDiagnostic {
    /// Rule that triggered this diagnostic
    pub rule_name: &'static str,
    /// Severity level
    pub severity: Severity,
    /// Primary message (CompactString for efficiency)
    pub message: CompactString,
    /// Start byte offset in source
    pub start: u32,
    /// End byte offset in source
    pub end: u32,
    /// Help message for fixing (optional, CompactString)
    pub help: Option<CompactString>,
    /// Related diagnostic information
    pub labels: Vec<Label>,
    /// Auto-fix for this diagnostic (optional)
    pub fix: Option<Fix>,
}

/// Additional label for a diagnostic
#[derive(Debug, Clone)]
pub struct Label {
    /// Message for this label (CompactString for efficiency)
    pub message: CompactString,
    /// Start byte offset
    pub start: u32,
    /// End byte offset
    pub end: u32,
}

impl LintDiagnostic {
    /// Create a new error diagnostic
    #[inline]
    pub fn error(
        rule_name: &'static str,
        message: impl Into<CompactString>,
        start: u32,
        end: u32,
    ) -> Self {
        Self {
            rule_name,
            severity: Severity::Error,
            message: message.into(),
            start,
            end,
            help: None,
            labels: Vec::new(),
            fix: None,
        }
    }

    /// Create a new warning diagnostic
    #[inline]
    pub fn warn(
        rule_name: &'static str,
        message: impl Into<CompactString>,
        start: u32,
        end: u32,
    ) -> Self {
        Self {
            rule_name,
            severity: Severity::Warning,
            message: message.into(),
            start,
            end,
            help: None,
            labels: Vec::new(),
            fix: None,
        }
    }

    /// Add a help message
    #[inline]
    pub fn with_help(mut self, help: impl Into<CompactString>) -> Self {
        self.help = Some(help.into());
        self
    }

    /// Add a related label
    #[inline]
    pub fn with_label(mut self, message: impl Into<CompactString>, start: u32, end: u32) -> Self {
        self.labels.push(Label {
            message: message.into(),
            start,
            end,
        });
        self
    }

    /// Add a fix for this diagnostic
    #[inline]
    pub fn with_fix(mut self, fix: Fix) -> Self {
        self.fix = Some(fix);
        self
    }

    /// Check if this diagnostic has a fix
    #[inline]
    pub fn has_fix(&self) -> bool {
        self.fix.is_some()
    }

    /// Get the formatted message with `[vize:RULE]` prefix.
    #[inline]
    pub fn formatted_message(&self) -> String {
        format!("[vize:{}] {}", self.rule_name, self.message)
    }

    /// Convert to OxcDiagnostic for rich rendering
    #[inline]
    pub fn into_oxc_diagnostic(self) -> OxcDiagnostic {
        // Format message with [vize:RULE] prefix
        let formatted_msg = format!("[vize:{}] {}", self.rule_name, self.message);

        let mut diag = match self.severity {
            Severity::Error => OxcDiagnostic::error(formatted_msg),
            Severity::Warning => OxcDiagnostic::warn(formatted_msg),
        };

        // Add primary label
        diag = diag.with_label(Span::new(self.start, self.end));

        // Add help if present (render as plain text for OxcDiagnostic)
        if let Some(help) = self.help {
            diag = diag.with_help(render_help(&help, HelpRenderTarget::PlainText));
        }

        // Add additional labels
        for label in self.labels {
            diag =
                diag.and_label(Span::new(label.start, label.end).label(label.message.to_string()));
        }

        diag
    }
}

/// Summary of lint results
#[derive(Debug, Clone, Default, Serialize)]
pub struct LintSummary {
    pub error_count: usize,
    pub warning_count: usize,
    pub file_count: usize,
}

impl LintSummary {
    #[inline]
    pub fn add(&mut self, diagnostic: &LintDiagnostic) {
        match diagnostic.severity {
            Severity::Error => self.error_count += 1,
            Severity::Warning => self.warning_count += 1,
        }
    }

    #[inline]
    pub fn has_errors(&self) -> bool {
        self.error_count > 0
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_help_level_full() {
        let level = HelpLevel::Full;
        let help = "**Why:** Use `:key` for tracking.\n\n```vue\n<li :key=\"id\">\n```";
        let result = level.process(help);
        // Full mode preserves raw markdown
        assert_eq!(result, Some(help.to_string()));
    }

    #[test]
    fn test_help_level_none() {
        let level = HelpLevel::None;
        let result = level.process("Any help text");
        assert_eq!(result, None);
    }

    #[test]
    fn test_help_level_short_strips_markdown() {
        let level = HelpLevel::Short;
        let help = "**Why:** The `:key` attribute helps Vue track items.\n\n**Fix:**\n```vue\n<li :key=\"id\">\n```";
        let result = level.process(help);
        assert_eq!(
            result,
            Some("Why: The :key attribute helps Vue track items.".to_string())
        );
    }

    #[test]
    fn test_help_level_short_skips_code_blocks() {
        let level = HelpLevel::Short;
        let help = "```vue\n<li :key=\"id\">\n```\nUse unique keys";
        let result = level.process(help);
        assert_eq!(result, Some("Use unique keys".to_string()));
    }

    #[test]
    fn test_help_level_short_simple_text() {
        let level = HelpLevel::Short;
        let help = "Add a key attribute to the element";
        let result = level.process(help);
        assert_eq!(
            result,
            Some("Add a key attribute to the element".to_string())
        );
    }

    #[test]
    fn test_strip_markdown_first_line_with_backticks() {
        let result = strip_markdown_first_line("Use `v-model` instead of `{{ }}`");
        assert_eq!(result, "Use v-model instead of {{ }}");
    }

    #[test]
    fn test_render_markdown_bold() {
        let result = render_markdown_to_ansi("**bold** text");
        assert_eq!(result, format!("{ANSI_BOLD}bold{ANSI_BOLD_OFF} text"));
    }

    #[test]
    fn test_render_markdown_inline_code() {
        let result = render_markdown_to_ansi("Use `v-model` directive");
        assert_eq!(
            result,
            format!("Use {ANSI_CYAN}v-model{ANSI_CYAN_OFF} directive")
        );
    }

    #[test]
    fn test_render_markdown_header() {
        let result = render_markdown_to_ansi("# Why");
        assert_eq!(
            result,
            format!("{ANSI_BOLD}{ANSI_UNDERLINE}Why{ANSI_UNDERLINE_OFF}{ANSI_BOLD_OFF}")
        );
    }

    #[test]
    fn test_render_markdown_code_block() {
        let result = render_markdown_to_ansi("```vue\n<li :key=\"id\">\n```");
        assert_eq!(
            result,
            format!("{ANSI_DIM}  <li :key=\"id\">{ANSI_DIM_OFF}")
        );
    }

    #[test]
    fn test_render_markdown_plain_text() {
        let result = render_markdown_to_ansi("plain text");
        assert_eq!(result, "plain text");
    }

    #[test]
    fn test_render_markdown_underscore_bold() {
        let result = render_markdown_to_ansi("__bold__ text");
        assert_eq!(result, format!("{ANSI_BOLD}bold{ANSI_BOLD_OFF} text"));
    }

    // render_help tests

    #[test]
    fn test_render_help_ansi() {
        let md = "**bold** and `code`";
        let result = render_help(md, HelpRenderTarget::Ansi);
        assert_eq!(
            result,
            format!("{ANSI_BOLD}bold{ANSI_BOLD_OFF} and {ANSI_CYAN}code{ANSI_CYAN_OFF}")
        );
    }

    #[test]
    fn test_render_help_plain_text() {
        let md = "**Why:** Use `:key` for tracking.\n\n```vue\n<li :key=\"id\">\n```";
        let result = render_help(md, HelpRenderTarget::PlainText);
        assert_eq!(result, "Why: Use :key for tracking.\n\n  <li :key=\"id\">");
    }

    #[test]
    fn test_render_help_markdown_passthrough() {
        let md = "**bold** and `code`";
        let result = render_help(md, HelpRenderTarget::Markdown);
        assert_eq!(result, md);
    }

    // strip_markdown tests

    #[test]
    fn test_strip_markdown_bold_and_code() {
        let result = strip_markdown("**bold** and `code`");
        assert_eq!(result, "bold and code");
    }

    #[test]
    fn test_strip_markdown_headers() {
        let result = strip_markdown("# Title\n## Subtitle\nBody text");
        assert_eq!(result, "Title\nSubtitle\nBody text");
    }

    #[test]
    fn test_strip_markdown_code_block() {
        let result = strip_markdown("Before\n```vue\n<div>code</div>\n```\nAfter");
        assert_eq!(result, "Before\n  <div>code</div>\nAfter");
    }

    #[test]
    fn test_strip_markdown_plain_text() {
        let result = strip_markdown("plain text");
        assert_eq!(result, "plain text");
    }
}