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
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
//! Compiler macro analysis.
//!
//! Tracks Vue compiler macros (defineProps, defineEmits, etc.)
//! and provides a plugin interface for custom macros.

use vize_carton::{CompactString, FxHashMap};

/// How a macro participates in the script setup compilation lifecycle.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MacroLifecycle {
    /// The SFC compiler analyzes the call and emits the matching runtime code.
    AnalyzeAndErase,
    /// The SFC compiler rewrites the macro call into runtime code.
    Expand,
    /// The SFC compiler extracts the call as a separate artifact, then removes
    /// the top-level call from runtime output.
    ExtractAndErase,
}

impl MacroLifecycle {
    /// Whether calls with this lifecycle should be removed from setup runtime code.
    #[inline]
    pub const fn erases_from_runtime(self) -> bool {
        matches!(self, Self::AnalyzeAndErase | Self::ExtractAndErase)
    }

    /// Whether calls with this lifecycle produce a compiler artifact.
    #[inline]
    pub const fn produces_artifact(self) -> bool {
        matches!(self, Self::ExtractAndErase)
    }
}

/// Static metadata for a known compiler macro.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MacroDefinition {
    /// Macro call name.
    pub name: &'static str,
    /// How the macro participates in compilation.
    pub lifecycle: MacroLifecycle,
    /// Optional artifact kind emitted by the SFC compiler.
    pub artifact_kind: Option<&'static str>,
}

/// Built-in Vue compiler macros
pub static BUILTIN_MACROS: &[&str] = &[
    "defineProps",
    "defineEmits",
    "defineExpose",
    "defineOptions",
    "defineSlots",
    "defineModel",
    "withDefaults",
];

/// Known ecosystem macros that are compile-time only.
///
/// These are intentionally separate from Vue's built-in compiler macros:
/// Vize does not expand them into component runtime itself, but it may extract
/// artifacts for surrounding tooling before removing top-level calls.
pub static ECOSYSTEM_COMPILE_TIME_MACROS: &[MacroDefinition] = &[
    MacroDefinition {
        name: "definePage",
        lifecycle: MacroLifecycle::ExtractAndErase,
        artifact_kind: Some("vue-router.definePage"),
    },
    MacroDefinition {
        name: "definePageMeta",
        lifecycle: MacroLifecycle::ExtractAndErase,
        artifact_kind: Some("nuxt.definePageMeta"),
    },
    MacroDefinition {
        name: "defineRouteRules",
        lifecycle: MacroLifecycle::ExtractAndErase,
        artifact_kind: Some("nuxt.defineRouteRules"),
    },
    MacroDefinition {
        name: "defineLazyHydrationComponent",
        lifecycle: MacroLifecycle::Expand,
        artifact_kind: None,
    },
];

/// Check if a name is a built-in compiler macro
#[inline]
pub fn is_builtin_macro(name: &str) -> bool {
    BUILTIN_MACROS.contains(&name)
}

/// Return the ecosystem macro definition for a name.
#[inline]
pub fn ecosystem_macro_definition(name: &str) -> Option<&'static MacroDefinition> {
    ECOSYSTEM_COMPILE_TIME_MACROS
        .iter()
        .find(|definition| definition.name == name)
}

/// Check if a name is a known ecosystem compile-time macro.
#[inline]
pub fn is_ecosystem_compile_time_macro(name: &str) -> bool {
    ecosystem_macro_definition(name).is_some()
}

/// Return the compile-time macro lifecycle for a name.
#[inline]
pub fn macro_lifecycle(name: &str) -> Option<MacroLifecycle> {
    if is_builtin_macro(name) {
        Some(MacroLifecycle::AnalyzeAndErase)
    } else {
        ecosystem_macro_definition(name).map(|definition| definition.lifecycle)
    }
}

/// Check if a name is compile-time only in script setup.
#[inline]
pub fn is_compile_time_macro(name: &str) -> bool {
    macro_lifecycle(name).is_some()
}

/// Check if a macro call should be removed from setup runtime output.
#[inline]
pub fn is_runtime_erased_macro(name: &str) -> bool {
    macro_lifecycle(name).is_some_and(MacroLifecycle::erases_from_runtime)
}

/// Return the artifact kind emitted for a macro name, when any.
#[inline]
pub fn macro_artifact_kind(name: &str) -> Option<&'static str> {
    ecosystem_macro_definition(name).and_then(|definition| definition.artifact_kind)
}

/// Check if a macro call should produce a compiler artifact.
#[inline]
pub fn is_artifact_macro(name: &str) -> bool {
    macro_lifecycle(name).is_some_and(MacroLifecycle::produces_artifact)
}

/// Names of macros that should not remain in setup runtime code.
#[inline]
pub fn runtime_erased_macro_names() -> impl Iterator<Item = &'static str> {
    BUILTIN_MACROS.iter().copied().chain(
        ECOSYSTEM_COMPILE_TIME_MACROS
            .iter()
            .filter(|definition| definition.lifecycle.erases_from_runtime())
            .map(|definition| definition.name),
    )
}

/// Names of macros that should produce compiler artifacts.
#[inline]
pub fn artifact_macro_names() -> impl Iterator<Item = &'static str> {
    ECOSYSTEM_COMPILE_TIME_MACROS
        .iter()
        .filter(|definition| definition.lifecycle.produces_artifact())
        .map(|definition| definition.name)
}

/// Unique identifier for a macro call
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct MacroCallId(u32);

impl MacroCallId {
    #[inline(always)]
    pub const fn new(id: u32) -> Self {
        Self(id)
    }

    #[inline(always)]
    pub const fn as_u32(self) -> u32 {
        self.0
    }
}

/// Kind of macro
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum MacroKind {
    DefineProps = 0,
    DefineEmits = 1,
    DefineExpose = 2,
    DefineOptions = 3,
    DefineSlots = 4,
    DefineModel = 5,
    WithDefaults = 6,
    Custom = 255,
}

impl MacroKind {
    #[inline]
    pub fn from_name(name: &str) -> Option<Self> {
        match name {
            "defineProps" => Some(Self::DefineProps),
            "defineEmits" => Some(Self::DefineEmits),
            "defineExpose" => Some(Self::DefineExpose),
            "defineOptions" => Some(Self::DefineOptions),
            "defineSlots" => Some(Self::DefineSlots),
            "defineModel" => Some(Self::DefineModel),
            "withDefaults" => Some(Self::WithDefaults),
            _ => None,
        }
    }
}

/// A compiler macro call
#[derive(Debug, Clone)]
pub struct MacroCall {
    pub id: MacroCallId,
    pub name: CompactString,
    pub kind: MacroKind,
    pub start: u32,
    pub end: u32,
    pub runtime_args: Option<CompactString>,
    pub type_args: Option<CompactString>,
}

/// Props destructure binding info
#[derive(Debug, Clone)]
pub struct PropsDestructureBinding {
    pub local: CompactString,
    pub default: Option<CompactString>,
}

/// Props destructure bindings data
#[derive(Debug, Clone, Default)]
pub struct PropsDestructuredBindings {
    pub bindings: FxHashMap<CompactString, PropsDestructureBinding>,
    pub rest_id: Option<CompactString>,
}

impl PropsDestructuredBindings {
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.bindings.is_empty() && self.rest_id.is_none()
    }

    #[inline]
    pub fn insert(
        &mut self,
        key: CompactString,
        local: CompactString,
        default: Option<CompactString>,
    ) {
        self.bindings
            .insert(key, PropsDestructureBinding { local, default });
    }

    #[inline]
    pub fn get(&self, key: &str) -> Option<&PropsDestructureBinding> {
        self.bindings.get(key)
    }
}

/// Prop definition from defineProps
#[derive(Debug, Clone)]
pub struct PropDefinition {
    pub name: CompactString,
    pub prop_type: Option<CompactString>,
    pub required: bool,
    pub default_value: Option<CompactString>,
}

/// Emit definition from defineEmits
#[derive(Debug, Clone)]
pub struct EmitDefinition {
    pub name: CompactString,
    pub payload_type: Option<CompactString>,
}

/// An actual emit() call in the code
#[derive(Debug, Clone)]
pub struct EmitCall {
    /// Event name being emitted
    pub event_name: CompactString,
    /// Whether this is a dynamic emit (variable event name)
    pub is_dynamic: bool,
    /// Source start offset
    pub start: u32,
    /// Source end offset
    pub end: u32,
}

/// Model definition from defineModel
#[derive(Debug, Clone)]
pub struct ModelDefinition {
    pub name: CompactString,
    pub local_name: CompactString,
    pub model_type: Option<CompactString>,
    pub required: bool,
    pub default_value: Option<CompactString>,
}

/// Top-level await in script setup
#[derive(Debug, Clone)]
pub struct TopLevelAwait {
    pub start: u32,
    pub end: u32,
    pub expression: CompactString,
}

/// Expose definition from defineExpose
#[derive(Debug, Clone)]
pub struct ExposeDefinition {
    /// Exposed property name
    pub name: CompactString,
    /// Type of the exposed property (if known)
    pub expose_type: Option<CompactString>,
}

/// Slots definition from defineSlots
#[derive(Debug, Clone)]
pub struct SlotsDefinition {
    /// Slot name
    pub name: CompactString,
    /// Slot props type (if known)
    pub props_type: Option<CompactString>,
}

/// Macro binding kind for props destructure
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MacroBindingKind {
    /// Direct prop access
    Prop,
    /// Aliased prop
    PropAliased,
    /// Rest spread
    Rest,
}

/// Tracks compiler macros during analysis
#[derive(Debug, Default)]
pub struct MacroTracker {
    calls: Vec<MacroCall>,
    props: Vec<PropDefinition>,
    emits: Vec<EmitDefinition>,
    /// Actual emit() calls in the code (not declarations)
    emit_calls: Vec<EmitCall>,
    models: Vec<ModelDefinition>,
    /// Exposed properties from defineExpose
    exposes: Vec<ExposeDefinition>,
    /// Slots from defineSlots
    slots: Vec<SlotsDefinition>,
    props_destructure: Option<PropsDestructuredBindings>,
    top_level_awaits: Vec<TopLevelAwait>,
    next_id: u32,
    /// Cached indices for quick lookup
    define_props_idx: Option<usize>,
    define_emits_idx: Option<usize>,
    define_expose_idx: Option<usize>,
    define_slots_idx: Option<usize>,
}

impl MacroTracker {
    #[inline]
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a macro call
    pub fn add_call(
        &mut self,
        name: impl Into<CompactString>,
        kind: MacroKind,
        start: u32,
        end: u32,
        runtime_args: Option<CompactString>,
        type_args: Option<CompactString>,
    ) -> MacroCallId {
        let id = MacroCallId::new(self.next_id);
        self.next_id += 1;

        let idx = self.calls.len();

        // Cache macro indices for quick lookup
        match kind {
            MacroKind::DefineProps => self.define_props_idx = Some(idx),
            MacroKind::DefineEmits => self.define_emits_idx = Some(idx),
            MacroKind::DefineExpose => self.define_expose_idx = Some(idx),
            MacroKind::DefineSlots => self.define_slots_idx = Some(idx),
            _ => {}
        }

        self.calls.push(MacroCall {
            id,
            name: name.into(),
            kind,
            start,
            end,
            runtime_args,
            type_args,
        });

        id
    }

    /// Get all macro calls
    #[inline]
    pub fn all_calls(&self) -> &[MacroCall] {
        &self.calls
    }

    /// Get defineProps call (cached lookup)
    #[inline]
    pub fn define_props(&self) -> Option<&MacroCall> {
        self.define_props_idx.map(|idx| &self.calls[idx])
    }

    /// Get defineEmits call (cached lookup)
    #[inline]
    pub fn define_emits(&self) -> Option<&MacroCall> {
        self.define_emits_idx.map(|idx| &self.calls[idx])
    }

    /// Get defineExpose call (cached lookup)
    #[inline]
    pub fn define_expose(&self) -> Option<&MacroCall> {
        self.define_expose_idx.map(|idx| &self.calls[idx])
    }

    /// Get defineSlots call (cached lookup)
    #[inline]
    pub fn define_slots(&self) -> Option<&MacroCall> {
        self.define_slots_idx.map(|idx| &self.calls[idx])
    }

    /// Add a prop definition
    #[inline]
    pub fn add_prop(&mut self, prop: PropDefinition) {
        self.props.push(prop);
    }

    /// Get all props
    #[inline]
    pub fn props(&self) -> &[PropDefinition] {
        &self.props
    }

    /// Add an emit definition
    #[inline]
    pub fn add_emit(&mut self, emit: EmitDefinition) {
        self.emits.push(emit);
    }

    /// Get all emits
    #[inline]
    pub fn emits(&self) -> &[EmitDefinition] {
        &self.emits
    }

    /// Add an emit call (actual emit() invocation in code)
    #[inline]
    pub fn add_emit_call(
        &mut self,
        event_name: CompactString,
        is_dynamic: bool,
        start: u32,
        end: u32,
    ) {
        self.emit_calls.push(EmitCall {
            event_name,
            is_dynamic,
            start,
            end,
        });
    }

    /// Get all emit calls
    #[inline]
    pub fn emit_calls(&self) -> &[EmitCall] {
        &self.emit_calls
    }

    /// Check if an event is actually emitted (called)
    #[inline]
    pub fn is_event_emitted(&self, event_name: &str) -> bool {
        self.emit_calls
            .iter()
            .any(|c| c.event_name.as_str() == event_name && !c.is_dynamic)
    }

    /// Get emit calls for a specific event
    pub fn emit_calls_for_event<'a>(
        &'a self,
        event_name: &'a str,
    ) -> impl Iterator<Item = &'a EmitCall> + 'a {
        self.emit_calls
            .iter()
            .filter(move |c| c.event_name.as_str() == event_name)
    }

    /// Add a model definition
    #[inline]
    pub fn add_model(&mut self, model: ModelDefinition) {
        self.models.push(model);
    }

    /// Get all models
    #[inline]
    pub fn models(&self) -> &[ModelDefinition] {
        &self.models
    }

    /// Add an expose definition
    #[inline]
    pub fn add_expose(&mut self, expose: ExposeDefinition) {
        self.exposes.push(expose);
    }

    /// Get all exposes
    #[inline]
    pub fn exposes(&self) -> &[ExposeDefinition] {
        &self.exposes
    }

    /// Add a slot definition
    #[inline]
    pub fn add_slot(&mut self, slot: SlotsDefinition) {
        self.slots.push(slot);
    }

    /// Get all slots
    #[inline]
    pub fn slots(&self) -> &[SlotsDefinition] {
        &self.slots
    }

    /// Set props destructure
    #[inline]
    pub fn set_props_destructure(&mut self, destructure: PropsDestructuredBindings) {
        self.props_destructure = Some(destructure);
    }

    /// Get props destructure
    #[inline]
    pub fn props_destructure(&self) -> Option<&PropsDestructuredBindings> {
        self.props_destructure.as_ref()
    }

    /// Add top-level await
    #[inline]
    pub fn add_top_level_await(&mut self, expression: CompactString, start: u32, end: u32) {
        self.top_level_awaits.push(TopLevelAwait {
            start,
            end,
            expression,
        });
    }

    /// Check if there are top-level awaits
    #[inline]
    pub fn has_top_level_await(&self) -> bool {
        !self.top_level_awaits.is_empty()
    }

    /// Get all top-level awaits
    #[inline]
    pub fn top_level_awaits(&self) -> &[TopLevelAwait] {
        &self.top_level_awaits
    }

    /// Check if script is async (has top-level await)
    #[inline]
    pub fn is_async(&self) -> bool {
        self.has_top_level_await()
    }
}

#[cfg(test)]
mod tests {
    use super::{
        artifact_macro_names, is_artifact_macro, is_compile_time_macro,
        is_ecosystem_compile_time_macro, is_runtime_erased_macro, macro_artifact_kind,
        macro_lifecycle, runtime_erased_macro_names, MacroKind, MacroLifecycle, MacroTracker,
    };
    use vize_carton::CompactString;

    #[test]
    fn test_macro_lifecycle_classifies_builtin_and_ecosystem_macros() {
        assert_eq!(
            macro_lifecycle("defineProps"),
            Some(MacroLifecycle::AnalyzeAndErase)
        );
        assert_eq!(
            macro_lifecycle("definePage"),
            Some(MacroLifecycle::ExtractAndErase)
        );
        assert_eq!(
            macro_lifecycle("definePageMeta"),
            Some(MacroLifecycle::ExtractAndErase)
        );
        assert_eq!(
            macro_lifecycle("defineRouteRules"),
            Some(MacroLifecycle::ExtractAndErase)
        );
        assert_eq!(
            macro_lifecycle("defineLazyHydrationComponent"),
            Some(MacroLifecycle::Expand)
        );
        assert_eq!(macro_lifecycle("notAMacro"), None);

        assert!(is_compile_time_macro("definePage"));
        assert!(is_ecosystem_compile_time_macro("definePage"));
        assert!(is_runtime_erased_macro("definePage"));
        assert!(is_artifact_macro("definePage"));
        assert_eq!(
            macro_artifact_kind("definePage"),
            Some("vue-router.definePage")
        );
        assert!(is_compile_time_macro("definePageMeta"));
        assert!(is_ecosystem_compile_time_macro("definePageMeta"));
        assert!(is_runtime_erased_macro("definePageMeta"));
        assert!(is_artifact_macro("definePageMeta"));
        assert_eq!(
            macro_artifact_kind("definePageMeta"),
            Some("nuxt.definePageMeta")
        );
        assert!(is_compile_time_macro("defineRouteRules"));
        assert!(is_ecosystem_compile_time_macro("defineRouteRules"));
        assert!(is_runtime_erased_macro("defineRouteRules"));
        assert!(is_artifact_macro("defineRouteRules"));
        assert_eq!(
            macro_artifact_kind("defineRouteRules"),
            Some("nuxt.defineRouteRules")
        );
        assert!(is_compile_time_macro("defineLazyHydrationComponent"));
        assert!(is_ecosystem_compile_time_macro(
            "defineLazyHydrationComponent"
        ));
        assert!(!is_runtime_erased_macro("defineLazyHydrationComponent"));
        assert!(!is_artifact_macro("defineLazyHydrationComponent"));
        assert_eq!(macro_artifact_kind("defineLazyHydrationComponent"), None);
        assert!(runtime_erased_macro_names().any(|name| name == "definePage"));
        assert!(runtime_erased_macro_names().any(|name| name == "definePageMeta"));
        assert!(runtime_erased_macro_names().any(|name| name == "defineRouteRules"));
        assert!(!runtime_erased_macro_names().any(|name| name == "defineLazyHydrationComponent"));
        assert!(artifact_macro_names().any(|name| name == "definePage"));
        assert!(artifact_macro_names().any(|name| name == "definePageMeta"));
        assert!(artifact_macro_names().any(|name| name == "defineRouteRules"));
        assert!(!artifact_macro_names().any(|name| name == "defineLazyHydrationComponent"));
    }

    #[test]
    fn test_macro_tracker() {
        let mut tracker = MacroTracker::new();

        let id = tracker.add_call(
            "defineProps",
            MacroKind::DefineProps,
            0,
            20,
            None,
            Some(CompactString::new("{ msg: string }")),
        );

        assert_eq!(id.as_u32(), 0);
        assert!(tracker.define_props().is_some());
        assert!(tracker.define_emits().is_none());
    }

    #[test]
    fn test_top_level_await() {
        let mut tracker = MacroTracker::new();
        assert!(!tracker.is_async());

        tracker.add_top_level_await(CompactString::new("fetch('/api')"), 10, 30);
        assert!(tracker.is_async());
        assert_eq!(tracker.top_level_awaits().len(), 1);
    }
}