vize_patina 0.22.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
//! AST visitor for lint rule execution.
//!
//! High-performance visitor with minimal allocations.

use crate::context::{ElementContext, LintContext};
use crate::rule::Rule;
use vize_carton::cstr;
use vize_carton::directive::{parse_level_severity, parse_vize_directive, DirectiveKind};
use vize_carton::CompactString;
use vize_relief::ast::{
    CommentNode, ElementNode, ExpressionNode, PropNode, RootNode, TemplateChildNode,
};

/// Visit the AST and run all rules
pub struct LintVisitor<'a, 'ctx, 'rules> {
    ctx: &'ctx mut LintContext<'a>,
    rules: &'rules [Box<dyn Rule>],
    /// When true, suppress all diagnostics for the next element
    forget_next_element: bool,
}

impl<'a, 'ctx, 'rules> LintVisitor<'a, 'ctx, 'rules> {
    /// Create a new visitor
    #[inline]
    pub fn new(ctx: &'ctx mut LintContext<'a>, rules: &'rules [Box<dyn Rule>]) -> Self {
        Self {
            ctx,
            rules,
            forget_next_element: false,
        }
    }

    /// Visit the root node and traverse the AST
    #[inline]
    pub fn visit_root(&mut self, root: &RootNode<'a>) {
        // Run template-level checks
        for rule in self.rules.iter() {
            self.ctx.current_rule = rule.meta().name;
            rule.run_on_template(self.ctx, root);
        }

        // Visit children
        for child in root.children.iter() {
            self.visit_child(child);
        }
    }

    #[inline]
    fn visit_child(&mut self, node: &TemplateChildNode<'a>) {
        match node {
            TemplateChildNode::Element(el) => {
                if self.forget_next_element {
                    self.forget_next_element = false;
                    let start_line = self.ctx.offset_to_line(el.loc.start.offset);
                    let end_line = self.ctx.offset_to_line(el.loc.end.offset);
                    self.ctx.disable_all(start_line, Some(end_line));
                }
                self.visit_element(el);
            }
            TemplateChildNode::Interpolation(interp) => {
                for rule in self.rules.iter() {
                    self.ctx.current_rule = rule.meta().name;
                    rule.check_interpolation(self.ctx, interp);
                }
            }
            TemplateChildNode::If(if_node) => {
                if self.forget_next_element {
                    self.forget_next_element = false;
                    let start_line = self.ctx.offset_to_line(if_node.loc.start.offset);
                    let end_line = self.ctx.offset_to_line(if_node.loc.end.offset);
                    self.ctx.disable_all(start_line, Some(end_line));
                }
                self.visit_if(if_node);
            }
            TemplateChildNode::For(for_node) => {
                if self.forget_next_element {
                    self.forget_next_element = false;
                    let start_line = self.ctx.offset_to_line(for_node.loc.start.offset);
                    let end_line = self.ctx.offset_to_line(for_node.loc.end.offset);
                    self.ctx.disable_all(start_line, Some(end_line));
                }
                self.visit_for(for_node);
            }
            TemplateChildNode::Comment(comment) => {
                if let Some(kind) = comment.directive {
                    self.process_vize_directive(comment, kind);
                }
            }
            TemplateChildNode::Text(_) => {}
            _ => {}
        }
    }

    /// Process `@vize:` directives on comment nodes.
    fn process_vize_directive(&mut self, comment: &CommentNode, kind: DirectiveKind) {
        let line = comment.loc.start.line;
        let loc = &comment.loc;

        match kind {
            DirectiveKind::Todo => {
                // Parse the payload from the comment content
                if let Some(d) = parse_vize_directive(&comment.content, line, loc.start.offset) {
                    let msg = if d.payload.is_empty() {
                        CompactString::from("TODO")
                    } else {
                        cstr!("TODO: {}", d.payload)
                    };
                    self.ctx.current_rule = "vize/todo";
                    self.ctx.warn(msg, loc);
                }
            }
            DirectiveKind::Fixme => {
                if let Some(d) = parse_vize_directive(&comment.content, line, loc.start.offset) {
                    let msg = if d.payload.is_empty() {
                        CompactString::from("FIXME")
                    } else {
                        cstr!("FIXME: {}", d.payload)
                    };
                    self.ctx.current_rule = "vize/fixme";
                    self.ctx.error(msg, loc);
                }
            }
            DirectiveKind::Expected => {
                self.ctx.expect_error_next_line(line);
            }
            DirectiveKind::IgnoreStart => {
                self.ctx.push_ignore_region(line);
            }
            DirectiveKind::IgnoreEnd => {
                self.ctx.pop_ignore_region(line);
            }
            DirectiveKind::Level => {
                if let Some(d) = parse_vize_directive(&comment.content, line, loc.start.offset) {
                    if let Some(severity) = parse_level_severity(&d.payload) {
                        self.ctx.set_severity_override_next_line(line, severity);
                    }
                }
            }
            DirectiveKind::Deprecated => {
                if let Some(d) = parse_vize_directive(&comment.content, line, loc.start.offset) {
                    let msg = if d.payload.is_empty() {
                        CompactString::from("Deprecated")
                    } else {
                        cstr!("Deprecated: {}", d.payload)
                    };
                    self.ctx.current_rule = "vize/deprecated";
                    self.ctx.warn(msg, loc);
                }
            }
            DirectiveKind::Forget => {
                if let Some(d) = parse_vize_directive(&comment.content, line, loc.start.offset) {
                    if d.payload.is_empty() {
                        self.ctx.current_rule = "vize/forget";
                        self.ctx
                            .warn(CompactString::from("@vize:forget requires a reason"), loc);
                    }
                    self.forget_next_element = true;
                }
            }
            // Docs, DevOnly, Unknown: no lint action needed
            _ => {}
        }
    }

    fn visit_element(&mut self, el: &ElementNode<'a>) {
        // Check for v-for and v-if directives using iterators (no allocation)
        let has_v_for = el
            .props
            .iter()
            .any(|p| matches!(p, PropNode::Directive(d) if d.name.as_str() == "for"));
        let has_v_if = el
            .props
            .iter()
            .any(|p| matches!(p, PropNode::Directive(d) if d.name.as_str() == "if" || d.name.as_str() == "else-if"));

        // Extract v-for variables (only allocates if v-for exists)
        let v_for_vars = if has_v_for {
            self.extract_v_for_vars(el)
        } else {
            Vec::new()
        };

        // Build element context with CompactString tag (efficient for small strings)
        let elem_ctx = ElementContext {
            tag: CompactString::from(el.tag.as_str()),
            has_v_for,
            has_v_if,
            v_for_vars,
        };

        self.ctx.push_element(elem_ctx);

        // Enter element - run rules
        for rule in self.rules.iter() {
            self.ctx.current_rule = rule.meta().name;
            rule.enter_element(self.ctx, el);
        }

        // Check directives
        for prop in el.props.iter() {
            if let PropNode::Directive(dir) = prop {
                for rule in self.rules.iter() {
                    self.ctx.current_rule = rule.meta().name;
                    rule.check_directive(self.ctx, el, dir);
                }
            }
        }

        // Visit children
        for child in el.children.iter() {
            self.visit_child(child);
        }

        // Exit element - run rules
        for rule in self.rules.iter() {
            self.ctx.current_rule = rule.meta().name;
            rule.exit_element(self.ctx, el);
        }

        self.ctx.pop_element();
    }

    #[inline]
    fn visit_if(&mut self, if_node: &vize_relief::ast::IfNode<'a>) {
        // Run if checks
        for rule in self.rules.iter() {
            self.ctx.current_rule = rule.meta().name;
            rule.check_if(self.ctx, if_node);
        }

        // Visit branches
        for branch in if_node.branches.iter() {
            for child in branch.children.iter() {
                self.visit_child(child);
            }
        }
    }

    #[inline]
    fn visit_for(&mut self, for_node: &vize_relief::ast::ForNode<'a>) {
        // Run for checks
        for rule in self.rules.iter() {
            self.ctx.current_rule = rule.meta().name;
            rule.check_for(self.ctx, for_node);
        }

        // Visit children
        for child in for_node.children.iter() {
            self.visit_child(child);
        }
    }

    /// Extract variable names from v-for directive on an element
    #[inline]
    fn extract_v_for_vars(&self, el: &ElementNode<'a>) -> Vec<CompactString> {
        for prop in el.props.iter() {
            if let PropNode::Directive(dir) = prop {
                if dir.name.as_str() == "for" {
                    if let Some(exp) = &dir.exp {
                        return parse_v_for_variables(exp);
                    }
                }
            }
        }
        Vec::new()
    }
}

/// Parse v-for expression to extract variable names.
///
/// Uses CompactString for efficient small string storage.
///
/// Handles formats like:
/// - `item in items`
/// - `(item, index) in items`
/// - `(value, key, index) in object`
#[inline]
pub fn parse_v_for_variables(exp: &ExpressionNode) -> Vec<CompactString> {
    let content = match exp {
        ExpressionNode::Simple(s) => s.content.as_str(),
        ExpressionNode::Compound(_) => return Vec::new(),
    };

    // Split on " in " or " of " - use byte search for speed
    let bytes = content.as_bytes();
    let (alias_part, _) = if let Some(idx) = find_pattern(bytes, b" in ") {
        (&content[..idx], &content[idx + 4..])
    } else if let Some(idx) = find_pattern(bytes, b" of ") {
        (&content[..idx], &content[idx + 4..])
    } else {
        return Vec::new();
    };

    let alias_str = alias_part.trim();

    // Handle destructuring: (item, index), { id, name }, or [first, second]
    let is_tuple = alias_str.starts_with('(') && alias_str.ends_with(')');
    let is_object = alias_str.starts_with('{') && alias_str.ends_with('}');
    let is_array = alias_str.starts_with('[') && alias_str.ends_with(']');

    if is_tuple || is_object || is_array {
        let inner = &alias_str[1..alias_str.len() - 1];
        // Pre-allocate with estimated capacity
        let mut vars = Vec::with_capacity(3);
        for s in inner.split(',') {
            let trimmed = s.trim();
            if trimmed.is_empty() {
                continue;
            }
            // Handle object shorthand: { id } -> id, { id: itemId } -> itemId
            if is_object {
                if let Some(colon_idx) = trimmed.find(':') {
                    // { id: itemId } -> itemId
                    let value_part = trimmed[colon_idx + 1..].trim();
                    if !value_part.is_empty() {
                        vars.push(CompactString::from(value_part));
                    }
                } else {
                    // { id } -> id (shorthand)
                    vars.push(CompactString::from(trimmed));
                }
            } else {
                vars.push(CompactString::from(trimmed));
            }
        }
        vars
    } else {
        // Single variable - avoid allocation if possible
        vec![CompactString::from(alias_str)]
    }
}

/// Fast byte pattern search
#[inline]
fn find_pattern(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    if needle.is_empty() || haystack.len() < needle.len() {
        return None;
    }

    haystack
        .windows(needle.len())
        .position(|window| window == needle)
}

#[cfg(test)]
mod tests {
    use super::{parse_v_for_variables, CompactString, ExpressionNode};
    use vize_carton::Bump;
    use vize_relief::ast::SimpleExpressionNode;

    fn make_simple_exp<'a>(allocator: &'a Bump, content: &str) -> ExpressionNode<'a> {
        ExpressionNode::Simple(vize_carton::Box::new_in(
            SimpleExpressionNode::new(
                vize_carton::String::from(content),
                false,
                vize_relief::ast::SourceLocation::STUB,
            ),
            allocator,
        ))
    }

    #[test]
    fn test_parse_v_for_simple() {
        let allocator = Bump::new();
        let exp = make_simple_exp(&allocator, "item in items");
        let vars = parse_v_for_variables(&exp);
        assert_eq!(vars, vec![CompactString::from("item")]);
    }

    #[test]
    fn test_parse_v_for_with_index() {
        let allocator = Bump::new();
        let exp = make_simple_exp(&allocator, "(item, index) in items");
        let vars = parse_v_for_variables(&exp);
        assert_eq!(
            vars,
            vec![CompactString::from("item"), CompactString::from("index")]
        );
    }

    #[test]
    fn test_parse_v_for_object() {
        let allocator = Bump::new();
        let exp = make_simple_exp(&allocator, "(value, key, index) in object");
        let vars = parse_v_for_variables(&exp);
        assert_eq!(
            vars,
            vec![
                CompactString::from("value"),
                CompactString::from("key"),
                CompactString::from("index"),
            ]
        );
    }

    #[test]
    fn test_parse_v_for_object_destructuring() {
        let allocator = Bump::new();
        let exp = make_simple_exp(&allocator, "{ id } in items");
        let vars = parse_v_for_variables(&exp);
        assert_eq!(vars, vec![CompactString::from("id")]);
    }

    #[test]
    fn test_parse_v_for_object_destructuring_multiple() {
        let allocator = Bump::new();
        let exp = make_simple_exp(&allocator, "{ id, name } in items");
        let vars = parse_v_for_variables(&exp);
        assert_eq!(
            vars,
            vec![CompactString::from("id"), CompactString::from("name")]
        );
    }

    #[test]
    fn test_parse_v_for_object_destructuring_with_rename() {
        let allocator = Bump::new();
        let exp = make_simple_exp(&allocator, "{ id: itemId, name: itemName } in items");
        let vars = parse_v_for_variables(&exp);
        assert_eq!(
            vars,
            vec![
                CompactString::from("itemId"),
                CompactString::from("itemName")
            ]
        );
    }

    #[test]
    fn test_parse_v_for_array_destructuring() {
        let allocator = Bump::new();
        let exp = make_simple_exp(&allocator, "[first, second] in items");
        let vars = parse_v_for_variables(&exp);
        assert_eq!(
            vars,
            vec![CompactString::from("first"), CompactString::from("second")]
        );
    }
}