vize_croquis 0.76.0

Croquis - Semantic analysis layer for Vize. Quick sketches of meaning from Vue templates.
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
//! High-performance Vue SFC analyzer.
//!
//! This module provides the `Analyzer` that produces `Croquis`.
//!
//! ## Performance Considerations
//!
//! - **Lazy analysis**: Only analyze what's requested
//! - **Zero-copy**: Use borrowed strings where possible
//! - **Arena allocation**: Temporary data uses arena allocator
//! - **Efficient structures**: FxHashMap, SmallVec, phf
//! - **Incremental**: Can analyze script and template separately
//!
//! ## Usage
//!
//! ```ignore
//! let mut analyzer = Analyzer::new();
//!
//! // Analyze script (fast path if only script bindings needed)
//! analyzer.analyze_script(script_source);
//!
//! // Analyze template (requires parsed AST)
//! analyzer.analyze_template(&template_ast);
//!
//! // Get results
//! let summary = analyzer.finish();
//! ```

mod helpers;
mod template;

pub use helpers::{
    extract_identifiers_oxc, extract_inline_callback_params, extract_slot_props,
    is_builtin_directive, is_component_tag, is_keyword, parse_v_for_expression, strip_js_comments,
};

use crate::analysis::Croquis;
use vize_carton::{profile, CompactString};

/// Analysis options for controlling what gets analyzed.
///
/// Use this to skip unnecessary analysis passes for better performance.
#[derive(Debug, Clone, Copy, Default)]
pub struct AnalyzerOptions {
    /// Analyze script bindings (defineProps, defineEmits, etc.)
    pub analyze_script: bool,
    /// Analyze template scopes (v-for, v-slot variables)
    pub analyze_template_scopes: bool,
    /// Track component and directive usage
    pub track_usage: bool,
    /// Detect undefined references (requires script + template)
    pub detect_undefined: bool,
    /// Analyze hoisting opportunities
    pub analyze_hoisting: bool,
    /// Collect template expressions for type checking
    pub collect_template_expressions: bool,
}

impl AnalyzerOptions {
    /// Full analysis (all features enabled)
    #[inline]
    pub const fn full() -> Self {
        Self {
            analyze_script: true,
            analyze_template_scopes: true,
            track_usage: true,
            detect_undefined: true,
            analyze_hoisting: true,
            collect_template_expressions: true,
        }
    }

    /// Minimal analysis for linting (fast)
    #[inline]
    pub const fn for_lint() -> Self {
        Self {
            analyze_script: true,
            analyze_template_scopes: true,
            track_usage: true,
            detect_undefined: true,
            analyze_hoisting: false,
            collect_template_expressions: false,
        }
    }

    /// Analysis for compilation (needs hoisting)
    #[inline]
    pub const fn for_compile() -> Self {
        Self {
            analyze_script: true,
            analyze_template_scopes: true,
            track_usage: true,
            detect_undefined: false,
            analyze_hoisting: true,
            collect_template_expressions: false,
        }
    }
}

/// High-performance Vue SFC analyzer.
///
/// Uses lazy evaluation and efficient data structures to minimize overhead.
pub struct Analyzer {
    pub(crate) options: AnalyzerOptions,
    pub(crate) summary: Croquis,
    /// Track if script was analyzed (for undefined detection)
    pub(crate) script_analyzed: bool,
    /// Current v-if guard stack (for type narrowing in templates)
    pub(crate) vif_guard_stack: Vec<CompactString>,
}

impl Analyzer {
    /// Create a new analyzer with default options
    #[inline]
    pub fn new() -> Self {
        Self::with_options(AnalyzerOptions::default())
    }

    /// Create analyzer with specific options
    #[inline]
    pub fn with_options(options: AnalyzerOptions) -> Self {
        Self {
            options,
            summary: Croquis::new(),
            script_analyzed: false,
            vif_guard_stack: Vec::new(),
        }
    }

    /// Get the current v-if guard (combined from stack)
    pub(crate) fn current_vif_guard(&self) -> Option<CompactString> {
        if self.vif_guard_stack.is_empty() {
            None
        } else {
            Some(CompactString::new(self.vif_guard_stack.join(" && ")))
        }
    }

    /// Create analyzer for linting (optimized)
    #[inline]
    pub fn for_lint() -> Self {
        Self::with_options(AnalyzerOptions::for_lint())
    }

    /// Create analyzer for compilation
    #[inline]
    pub fn for_compile() -> Self {
        Self::with_options(AnalyzerOptions::for_compile())
    }

    /// Analyze script setup source code.
    ///
    /// This uses OXC parser to extract:
    /// - defineProps/defineEmits/defineModel calls
    /// - Top-level bindings (const, let, function, class)
    /// - Import statements
    /// - Reactivity wrappers (ref, reactive, computed)
    ///
    /// Performance: OXC provides high-performance AST parsing with accurate span tracking.
    pub fn analyze_script(&mut self, source: &str) -> &mut Self {
        self.analyze_script_setup(source)
    }

    /// Analyze script setup source code.
    pub fn analyze_script_setup(&mut self, source: &str) -> &mut Self {
        self.analyze_script_setup_with_generic(source, None)
    }

    /// Analyze script setup source code with an optional generic parameter.
    ///
    /// `generic` is the value from `<script setup generic="T">` attribute, if present.
    pub fn analyze_script_setup_with_generic(
        &mut self,
        source: &str,
        generic: Option<&str>,
    ) -> &mut Self {
        if !self.options.analyze_script {
            return self;
        }

        self.script_analyzed = true;

        // Use OXC-based parser for accurate AST analysis
        let result = profile!(
            "croquis.analyzer.script_setup",
            crate::script_parser::parse_script_setup_with_generic(source, generic)
        );

        // Merge results into summary
        self.summary.bindings = result.bindings;
        self.summary.macros = result.macros;
        self.summary.reactivity = result.reactivity;
        self.summary.type_exports = result.type_exports;
        self.summary.invalid_exports = result.invalid_exports;
        self.summary.scopes = result.scopes;
        self.summary.provide_inject = result.provide_inject;
        self.summary.import_statements = result.import_statements;
        self.summary.re_exports = result.re_exports;
        self.summary.binding_spans = result.binding_spans;
        self.summary.setup_context = result.setup_context;

        self
    }

    /// Analyze non-script-setup (Options API) source code.
    pub fn analyze_script_plain(&mut self, source: &str) -> &mut Self {
        if !self.options.analyze_script {
            return self;
        }

        self.script_analyzed = true;

        // Use OXC-based parser for non-script-setup
        let result = profile!(
            "croquis.analyzer.script_plain",
            crate::script_parser::parse_script(source)
        );

        // Merge results into summary
        self.summary.bindings = result.bindings;
        self.summary.macros = result.macros;
        self.summary.reactivity = result.reactivity;
        self.summary.type_exports = result.type_exports;
        self.summary.invalid_exports = result.invalid_exports;
        self.summary.scopes = result.scopes;
        self.summary.provide_inject = result.provide_inject;
        self.summary.import_statements = result.import_statements;
        self.summary.re_exports = result.re_exports;
        self.summary.binding_spans = result.binding_spans;
        self.summary.setup_context = result.setup_context;

        self
    }

    /// Finish analysis and return the summary.
    ///
    /// Consumes the analyzer.
    #[inline]
    pub fn finish(self) -> Croquis {
        profile!("croquis.analyzer.finish", self.summary)
    }

    /// Get a reference to the current summary (without consuming).
    #[inline]
    pub fn summary(&self) -> &Croquis {
        &self.summary
    }

    /// Get a mutable reference to the current croquis (analysis result).
    ///
    /// This is primarily used for testing and advanced scenarios where
    /// the caller needs to inject data (e.g., used_components from template parsing).
    #[inline]
    pub fn croquis_mut(&mut self) -> &mut Croquis {
        &mut self.summary
    }
}

impl Default for Analyzer {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::{Analyzer, AnalyzerOptions};
    use crate::analysis::{InvalidExportKind, TypeExportKind};
    use vize_carton::append;

    #[test]
    fn test_analyzer_script_bindings() {
        let mut analyzer = Analyzer::for_lint();
        analyzer.analyze_script(
            r#"
            const count = ref(0)
            const name = 'hello'
            let flag = true
            function handleClick() {}
        "#,
        );

        let summary = analyzer.finish();
        assert!(summary.reactivity.is_reactive("count"));
        assert!(summary.reactivity.needs_value_access("count"));
        insta::assert_debug_snapshot!(summary);
    }

    #[test]
    fn test_analyzer_define_props() {
        let mut analyzer = Analyzer::for_lint();
        analyzer.analyze_script(
            r#"
            const props = defineProps<{
                msg: string
                count?: number
            }>()
        "#,
        );

        let summary = analyzer.finish();
        assert_eq!(summary.macros.props().len(), 2);

        let prop_names: Vec<_> = summary
            .macros
            .props()
            .iter()
            .map(|p| p.name.as_str())
            .collect();
        assert!(prop_names.contains(&"msg"));
        assert!(prop_names.contains(&"count"));
    }

    #[test]
    fn test_type_exports() {
        let mut analyzer = Analyzer::for_lint();
        analyzer.analyze_script(
            r#"
export type Props = {
    msg: string
}
export interface Emits {
    (e: 'update', value: string): void
}
const count = ref(0)
        "#,
        );

        let summary = analyzer.finish();
        assert_eq!(summary.type_exports.len(), 2);

        let type_export = &summary.type_exports[0];
        assert_eq!(type_export.name.as_str(), "Props");
        assert_eq!(type_export.kind, TypeExportKind::Type);
        assert!(type_export.hoisted);

        let interface_export = &summary.type_exports[1];
        assert_eq!(interface_export.name.as_str(), "Emits");
        assert_eq!(interface_export.kind, TypeExportKind::Interface);
        assert!(interface_export.hoisted);
    }

    #[test]
    fn test_invalid_exports() {
        let mut analyzer = Analyzer::for_lint();
        analyzer.analyze_script(
            r#"
export const foo = 'bar'
export let count = 0
export function hello() {}
export class MyClass {}
export default { foo: 'bar' }
const valid = ref(0)
        "#,
        );

        let summary = analyzer.finish();
        assert_eq!(summary.invalid_exports.len(), 5);

        let kinds: Vec<_> = summary.invalid_exports.iter().map(|e| e.kind).collect();
        assert!(kinds.contains(&InvalidExportKind::Const));
        assert!(kinds.contains(&InvalidExportKind::Let));
        assert!(kinds.contains(&InvalidExportKind::Function));
        assert!(kinds.contains(&InvalidExportKind::Class));
        assert!(kinds.contains(&InvalidExportKind::Default));

        let names: Vec<_> = summary
            .invalid_exports
            .iter()
            .map(|e| e.name.as_str())
            .collect();
        assert!(names.contains(&"foo"));
        assert!(names.contains(&"count"));
        assert!(names.contains(&"hello"));
        assert!(names.contains(&"MyClass"));
    }

    #[test]
    fn test_mixed_exports() {
        let mut analyzer = Analyzer::for_lint();
        analyzer.analyze_script(
            r#"
export type MyType = string
export const invalid = 123
export interface MyInterface { name: string }
        "#,
        );

        let summary = analyzer.finish();
        assert_eq!(summary.type_exports.len(), 2);
        assert_eq!(summary.invalid_exports.len(), 1);
        assert_eq!(summary.invalid_exports[0].name.as_str(), "invalid");
    }

    #[test]
    fn test_inject_detection_in_script_setup() {
        let mut analyzer = Analyzer::with_options(AnalyzerOptions::full());
        analyzer.analyze_script_setup(
            r#"import { inject } from 'vue'

const theme = inject('theme')
const { name } = inject('user') as { name: string; id: number }"#,
        );

        let summary = analyzer.finish();
        let injects = summary.provide_inject.injects();

        assert_eq!(injects.len(), 2, "Should detect 2 inject calls");

        assert_eq!(
            injects[0].key,
            crate::provide::ProvideKey::String(vize_carton::CompactString::new("theme"))
        );

        assert_eq!(
            injects[1].key,
            crate::provide::ProvideKey::String(vize_carton::CompactString::new("user"))
        );
        assert!(
            matches!(
                &injects[1].pattern,
                crate::provide::InjectPattern::ObjectDestructure(_)
            ),
            "Should detect object destructure pattern"
        );
    }

    // ========== Snapshot Tests ==========

    #[test]
    fn test_full_analysis_snapshot() {
        use insta::assert_snapshot;

        let mut analyzer = Analyzer::with_options(AnalyzerOptions::full());
        analyzer.analyze_script(
            r#"import { ref, computed, inject, provide } from 'vue'
import MyComponent from './MyComponent.vue'

const props = defineProps<{
    msg: string
    count?: number
}>()

const emit = defineEmits<{
    (e: 'update', value: string): void
    (e: 'delete'): void
}>()

const model = defineModel<string>()

const counter = ref(0)
const doubled = computed(() => counter.value * 2)
const theme = inject('theme')

provide('counter', counter)

function increment() {
    counter.value++
    emit('update', String(counter.value))
}

export type UserProps = { name: string }
"#,
        );

        let summary = analyzer.finish();

        // Build a readable snapshot
        let mut output = String::new();
        output.push_str("=== Bindings ===\n");
        for (name, ty) in summary.bindings.iter() {
            append!(output, "  {name}: {:?}\n", ty);
        }

        output.push_str("\n=== Macros ===\n");
        append!(output, "  props: {}\n", summary.macros.props().len());
        append!(output, "  emits: {}\n", summary.macros.emits().len());
        append!(output, "  models: {}\n", summary.macros.models().len());

        output.push_str("\n=== Reactivity ===\n");
        for source in summary.reactivity.sources() {
            append!(
                output,
                "  {}: kind={:?}, needs_value={}\n",
                source.name,
                source.kind,
                source.kind.needs_value_access()
            );
        }

        output.push_str("\n=== Provide/Inject ===\n");
        append!(
            output,
            "  provides: {}\n",
            summary.provide_inject.provides().len()
        );
        append!(
            output,
            "  injects: {}\n",
            summary.provide_inject.injects().len()
        );

        output.push_str("\n=== Type Exports ===\n");
        for te in &summary.type_exports {
            append!(output, "  {}: {:?}\n", te.name, te.kind);
        }

        assert_snapshot!(output);
    }

    #[test]
    fn test_props_emits_snapshot() {
        use insta::assert_snapshot;

        let mut analyzer = Analyzer::for_lint();
        analyzer.analyze_script(
            r#"
const props = defineProps({
    title: String,
    count: { type: Number, required: true },
    items: { type: Array, default: () => [] }
})

const emit = defineEmits(['update', 'delete', 'select'])
"#,
        );

        let summary = analyzer.finish();

        let mut output = String::new();
        output.push_str("=== Props ===\n");
        for prop in summary.macros.props() {
            append!(
                output,
                "  {}: required={}, has_default={}\n",
                prop.name,
                prop.required,
                prop.default_value.is_some()
            );
        }

        output.push_str("\n=== Emits ===\n");
        for emit in summary.macros.emits() {
            append!(output, "  {}\n", emit.name);
        }

        assert_snapshot!(output);
    }

    #[test]
    fn test_provide_inject_snapshot() {
        use insta::assert_snapshot;

        let mut analyzer = Analyzer::with_options(AnalyzerOptions::full());
        analyzer.analyze_script(
            r#"import { provide, inject } from 'vue'

// Simple provide
provide('theme', 'dark')

// Provide with ref
const counter = ref(0)
provide('counter', counter)

// Provide with Symbol key
const KEY = Symbol('key')
provide(KEY, { value: 42 })

// Simple inject
const theme = inject('theme')

// Inject with default
const locale = inject('locale', 'en')

// Inject with destructure
const { name, id } = inject('user') as { name: string; id: number }
"#,
        );

        let summary = analyzer.finish();

        let mut output = String::new();
        output.push_str("=== Provides ===\n");
        for p in summary.provide_inject.provides() {
            append!(output, "  key: {:?}\n", p.key);
        }

        output.push_str("\n=== Injects ===\n");
        for i in summary.provide_inject.injects() {
            append!(
                output,
                "  key: {:?}, has_default: {}, pattern: {:?}\n",
                i.key,
                i.default_value.is_some(),
                i.pattern
            );
        }

        assert_snapshot!(output);
    }

    #[test]
    fn test_vif_guard_in_template() {
        use vize_armature::parse;
        use vize_carton::Bump;

        let allocator = Bump::new();
        let template = r#"<div>
            <p v-if="todo.description">{{ unwrapDescription(todo.description) }}</p>
            <span>{{ todo.title }}</span>
        </div>"#;

        let (root, errors) = parse(&allocator, template);
        assert!(errors.is_empty(), "Template should parse without errors");

        let mut analyzer = Analyzer::with_options(AnalyzerOptions::full());
        analyzer.analyze_template(&root);
        let summary = analyzer.finish();

        // Find the interpolation expressions
        let expressions: Vec<_> = summary
            .template_expressions
            .iter()
            .filter(|e| {
                matches!(
                    e.kind,
                    crate::analysis::TemplateExpressionKind::Interpolation
                )
            })
            .collect();

        insta::assert_debug_snapshot!(expressions);
    }
}