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
//! Setup context propagation, queries, and markdown output.
//!
//! Provides analysis methods for the [`CallGraph`]: propagating setup context
//! through call edges, querying setup context status, and generating
//! markdown visualizations.

use super::{
    CallEdge, CallGraph, ComposableCallInfo, FunctionDef, FunctionId, SetupContextKind, SmallVec,
    VueApiCall, VueApiCategory,
};
use vize_carton::append;
use vize_carton::String;

impl CallGraph {
    /// Check if a function (or None for top-level) is in setup context.
    #[inline]
    pub fn is_in_setup_context(&self, func_id: Option<FunctionId>) -> bool {
        match func_id {
            Some(id) => self.setup_context_functions.contains(&id),
            None => {
                // Top-level in script setup is setup context
                true
            }
        }
    }

    /// Propagate setup context through call edges.
    /// Call this after all functions and edges are added.
    pub fn propagate_setup_context(&mut self) {
        if self.setup_function.is_none() {
            return;
        }

        // BFS from setup function
        let mut queue: SmallVec<[FunctionId; 16]> = SmallVec::new();
        queue.extend(self.setup_context_functions.iter().copied());

        while let Some(func_id) = queue.pop() {
            // Find all functions called by this function
            for edge in &self.call_edges {
                if edge.caller == func_id && !self.setup_context_functions.contains(&edge.callee) {
                    self.setup_context_functions.insert(edge.callee);
                    queue.push(edge.callee);

                    // Update function def
                    if let Some(func) = self.functions.get_mut(edge.callee.as_u32() as usize) {
                        func.called_in_setup = true;
                    }
                }
            }
        }

        // Update vue_api_calls in_setup_context
        // Collect updates first to avoid borrow conflict
        let vue_updates: Vec<_> = self
            .vue_api_calls
            .iter()
            .enumerate()
            .map(|(i, call)| {
                (
                    i,
                    self.setup_context_functions.contains(
                        &call
                            .containing_function
                            .unwrap_or(FunctionId::new(u32::MAX)),
                    ),
                )
            })
            .collect();
        for (i, in_setup) in vue_updates {
            // Top-level is always in setup context for script setup
            let containing = self.vue_api_calls[i].containing_function;
            self.vue_api_calls[i].in_setup_context = containing.is_none() || in_setup;
        }

        // Update composable_calls in_setup_context
        let composable_updates: Vec<_> = self
            .composable_calls
            .iter()
            .enumerate()
            .map(|(i, call)| {
                (
                    i,
                    self.setup_context_functions.contains(
                        &call
                            .containing_function
                            .unwrap_or(FunctionId::new(u32::MAX)),
                    ),
                )
            })
            .collect();
        for (i, in_setup) in composable_updates {
            let containing = self.composable_calls[i].containing_function;
            self.composable_calls[i].in_setup_context = containing.is_none() || in_setup;
        }
    }

    /// Get all Vue API calls.
    #[inline]
    pub fn vue_api_calls(&self) -> &[VueApiCall] {
        &self.vue_api_calls
    }

    /// Get Vue API calls outside setup context (potential issues).
    pub fn vue_api_calls_outside_setup(&self) -> impl Iterator<Item = &VueApiCall> {
        self.vue_api_calls.iter().filter(|c| !c.in_setup_context)
    }

    /// Get all composable calls.
    #[inline]
    pub fn composable_calls(&self) -> &[ComposableCallInfo] {
        &self.composable_calls
    }

    /// Get composable calls outside setup context (potential issues).
    pub fn composable_calls_outside_setup(&self) -> impl Iterator<Item = &ComposableCallInfo> {
        self.composable_calls.iter().filter(|c| !c.in_setup_context)
    }

    /// Get all function definitions.
    #[inline]
    pub fn functions(&self) -> &[FunctionDef] {
        &self.functions
    }

    /// Get a function by ID.
    #[inline]
    pub fn get_function(&self, id: FunctionId) -> Option<&FunctionDef> {
        self.functions.get(id.as_u32() as usize)
    }

    /// Get functions by name.
    pub fn get_functions_by_name(&self, name: &str) -> Option<&[FunctionId]> {
        self.function_by_name.get(name).map(|v| v.as_slice())
    }

    /// Get all call edges.
    #[inline]
    pub fn call_edges(&self) -> &[CallEdge] {
        &self.call_edges
    }

    /// Get the setup function ID.
    #[inline]
    pub fn setup_function(&self) -> Option<FunctionId> {
        self.setup_function
    }

    /// Check if a function is a composable.
    #[inline]
    pub fn is_composable(&self, id: FunctionId) -> bool {
        self.get_function(id)
            .map(|f| f.is_composable)
            .unwrap_or(false)
    }

    /// Get the setup context kind for a given location.
    pub fn get_setup_context_kind(&self, func_id: Option<FunctionId>) -> SetupContextKind {
        match func_id {
            None => {
                // Top-level - check if we have a setup function
                if self.setup_function.is_some() {
                    SetupContextKind::SetupBody
                } else {
                    SetupContextKind::None
                }
            }
            Some(id) => {
                if Some(id) == self.setup_function {
                    SetupContextKind::SetupBody
                } else if self.setup_context_functions.contains(&id) {
                    // Check if this function is a composable
                    if self.is_composable(id) {
                        SetupContextKind::Composable
                    } else {
                        // It's a callback or nested function in setup context
                        SetupContextKind::ComposableCallback
                    }
                } else {
                    SetupContextKind::None
                }
            }
        }
    }

    /// Generate a markdown visualization of the call graph.
    pub fn to_markdown(&self) -> String {
        let mut out = String::with_capacity(2048);

        out.push_str("## Function Call Graph\n\n");

        // Setup function
        if let Some(setup_id) = self.setup_function {
            if let Some(func) = self.get_function(setup_id) {
                append!(
                    out,
                    "**Setup Function**: `{}` (offset: {}..{})\n\n",
                    func.name.as_deref().unwrap_or("<anonymous>"),
                    func.start,
                    func.end
                );
            }
        }

        // Functions in setup context
        out.push_str("### Functions in Setup Context\n\n");
        for func in &self.functions {
            if func.called_in_setup || Some(func.id) == self.setup_function {
                let marker = if func.is_composable {
                    "🔧"
                } else if func.uses_vue_apis {
                    ""
                } else {
                    "📦"
                };
                append!(
                    out,
                    "- {} `{}` ({}..{})\n",
                    marker,
                    func.name.as_deref().unwrap_or("<anonymous>"),
                    func.start,
                    func.end
                );
            }
        }

        // Vue API calls
        out.push_str("\n### Vue API Calls\n\n");
        out.push_str("| API | Category | In Setup | Offset |\n");
        out.push_str("|-----|----------|----------|--------|\n");
        for call in &self.vue_api_calls {
            let in_setup = if call.in_setup_context { "" } else { "" };
            append!(
                out,
                "| `{}` | {:?} | {} | {}..{} |\n",
                call.name,
                call.category,
                in_setup,
                call.start,
                call.end
            );
        }

        // Composable calls
        if !self.composable_calls.is_empty() {
            out.push_str("\n### Composable Calls\n\n");
            out.push_str("| Composable | Source | In Setup | Offset |\n");
            out.push_str("|------------|--------|----------|--------|\n");
            for call in &self.composable_calls {
                let in_setup = if call.in_setup_context { "" } else { "" };
                let source = call.source.as_deref().unwrap_or("-");
                append!(
                    out,
                    "| `{}` | `{}` | {} | {}..{} |\n",
                    call.name,
                    source,
                    in_setup,
                    call.start,
                    call.end
                );
            }
        }

        // Issues (Vue APIs outside setup)
        let issues: Vec<_> = self.vue_api_calls_outside_setup().collect();
        if !issues.is_empty() {
            out.push_str("\n### ⚠️ Issues: Vue APIs Outside Setup Context\n\n");
            for call in issues {
                append!(
                    out,
                    "- `{}` at {}..{} - Vue {} API called outside setup context\n",
                    call.name,
                    call.start,
                    call.end,
                    match call.category {
                        VueApiCategory::Reactivity => "reactivity",
                        VueApiCategory::Lifecycle => "lifecycle",
                        VueApiCategory::DependencyInjection => "dependency injection",
                        VueApiCategory::Watcher => "watcher",
                        VueApiCategory::TemplateRef => "template ref",
                        VueApiCategory::Other => "",
                    }
                );
            }
        }

        out
    }
}

#[cfg(test)]
mod tests {
    use super::{CallGraph, SetupContextKind, VueApiCategory};
    use crate::call_graph::builder::{categorize_vue_api, is_composable_name, is_vue_api};
    use crate::scope::ScopeId;
    use vize_carton::CompactString;

    #[test]
    fn test_categorize_vue_api() {
        assert_eq!(categorize_vue_api("ref"), VueApiCategory::Reactivity);
        assert_eq!(categorize_vue_api("computed"), VueApiCategory::Reactivity);
        assert_eq!(categorize_vue_api("onMounted"), VueApiCategory::Lifecycle);
        assert_eq!(
            categorize_vue_api("provide"),
            VueApiCategory::DependencyInjection
        );
        assert_eq!(categorize_vue_api("watch"), VueApiCategory::Watcher);
        assert_eq!(
            categorize_vue_api("useTemplateRef"),
            VueApiCategory::TemplateRef
        );
        assert_eq!(categorize_vue_api("nextTick"), VueApiCategory::Other);
    }

    #[test]
    fn test_is_composable_name() {
        assert!(is_composable_name("useCounter"));
        assert!(is_composable_name("useAuth"));
        assert!(is_composable_name("useFetch"));
        assert!(!is_composable_name("use")); // Too short
        assert!(!is_composable_name("usecounter")); // Lowercase after use
        assert!(!is_composable_name("counter")); // Doesn't start with use
    }

    #[test]
    fn test_is_vue_api() {
        assert!(is_vue_api("ref"));
        assert!(is_vue_api("reactive"));
        assert!(is_vue_api("computed"));
        assert!(is_vue_api("onMounted"));
        assert!(is_vue_api("provide"));
        assert!(is_vue_api("inject"));
        assert!(is_vue_api("watch"));
        assert!(!is_vue_api("myFunction"));
        assert!(!is_vue_api("useState")); // React API, not Vue
    }

    #[test]
    fn test_call_graph_basic() {
        let mut graph = CallGraph::new();

        // Add setup function
        let setup_id = graph.add_function(
            Some(CompactString::new("setup")),
            ScopeId::new(1),
            None,
            false,
            0,
            100,
        );
        graph.set_setup_function(setup_id);

        // Add a helper function
        let helper_id = graph.add_function(
            Some(CompactString::new("useCounter")),
            ScopeId::new(2),
            None,
            false,
            110,
            200,
        );

        // Add call edge: setup -> useCounter
        graph.add_call_edge(setup_id, helper_id, 50);

        // Add Vue API call in helper
        graph.add_vue_api_call(
            CompactString::new("ref"),
            ScopeId::new(2),
            Some(helper_id),
            150,
            155,
        );

        // Propagate setup context
        graph.propagate_setup_context();

        // Verify
        assert!(graph.is_in_setup_context(Some(setup_id)));
        assert!(graph.is_in_setup_context(Some(helper_id)));

        let func = graph.get_function(helper_id).unwrap();
        assert!(func.called_in_setup);
        assert!(func.uses_vue_apis);
        assert!(func.is_composable);
    }

    #[test]
    fn test_vue_api_outside_setup() {
        let mut graph = CallGraph::new();

        // Add setup function
        let setup_id = graph.add_function(
            Some(CompactString::new("setup")),
            ScopeId::new(1),
            None,
            false,
            0,
            100,
        );
        graph.set_setup_function(setup_id);

        // Add a function NOT called from setup
        let outside_id = graph.add_function(
            Some(CompactString::new("outsideFunction")),
            ScopeId::new(2),
            None,
            false,
            200,
            300,
        );

        // Add Vue API call in the outside function
        graph.add_vue_api_call(
            CompactString::new("ref"),
            ScopeId::new(2),
            Some(outside_id),
            250,
            255,
        );

        // Propagate
        graph.propagate_setup_context();

        // Verify the issue is detected
        let issues: Vec<_> = graph.vue_api_calls_outside_setup().collect();
        assert_eq!(issues.len(), 1);
        assert_eq!(issues[0].name.as_str(), "ref");
    }

    #[test]
    fn test_setup_context_kind() {
        let mut graph = CallGraph::new();

        let setup_id = graph.add_function(
            Some(CompactString::new("setup")),
            ScopeId::new(1),
            None,
            false,
            0,
            100,
        );
        graph.set_setup_function(setup_id);

        let composable_id = graph.add_function(
            Some(CompactString::new("useAuth")),
            ScopeId::new(2),
            None,
            false,
            110,
            200,
        );
        graph.add_call_edge(setup_id, composable_id, 50);

        let callback_id =
            graph.add_function(None, ScopeId::new(3), Some(composable_id), true, 150, 180);
        graph.add_call_edge(composable_id, callback_id, 160);

        graph.propagate_setup_context();

        assert_eq!(
            graph.get_setup_context_kind(Some(setup_id)),
            SetupContextKind::SetupBody
        );
        assert_eq!(
            graph.get_setup_context_kind(Some(composable_id)),
            SetupContextKind::Composable
        );
        assert_eq!(
            graph.get_setup_context_kind(Some(callback_id)),
            SetupContextKind::ComposableCallback
        );
    }
}