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
//! Declaration TypeScript generation from Croquis analysis.
//!
//! This module turns the semantic sketch that Croquis already collected from an
//! SFC script into a lightweight `.d.ts` surface for Vue component consumers.

use crate::{Croquis, ScopeData, ScopeKind};
use vize_carton::{append, cstr, SmallVec, String};

/// Result of declaration generation.
#[derive(Debug, Clone, Default)]
pub struct DeclarationTsOutput {
    /// Generated `.d.ts` content.
    pub content: String,
}

/// Generate component declarations from Croquis analysis and the analyzed
/// script content.
pub fn generate_declaration_ts(
    summary: &Croquis,
    script_content: Option<&str>,
) -> DeclarationTsOutput {
    generate_declaration_ts_inner(summary, script_content.map(ScriptContent::Single))
}

/// Generate component declarations from Croquis analysis when plain `<script>`
/// and `<script setup>` were analyzed as a virtual concatenation.
///
/// This avoids allocating that concatenated script just to slice module-level
/// statements back out during declaration generation.
pub fn generate_declaration_ts_with_split_scripts(
    summary: &Croquis,
    plain_script: &str,
    setup_script: &str,
) -> DeclarationTsOutput {
    generate_declaration_ts_inner(
        summary,
        Some(ScriptContent::Split {
            first: plain_script,
            second: setup_script,
            second_start: plain_script.len() as u32 + 1,
        }),
    )
}

fn generate_declaration_ts_inner(
    summary: &Croquis,
    script_content: Option<ScriptContent<'_>>,
) -> DeclarationTsOutput {
    let mut ts = String::default();
    let generic_param = generic_param(summary);
    let generic_decl = generic_param
        .map(|generic| cstr!("<{}>", add_generic_defaults(generic)))
        .unwrap_or_default();
    let generic_ref = generic_param
        .map(|generic| cstr!("<{}>", extract_generic_names(generic)))
        .unwrap_or_default();

    if let Some(script) = script_content.as_ref() {
        emit_module_statements(&mut ts, summary, script);
    }

    emit_props_type(&mut ts, summary, generic_decl.as_str());
    emit_emits_type(&mut ts, summary, generic_decl.as_str());
    emit_slots_type(&mut ts, summary, generic_decl.as_str());
    emit_default_component(&mut ts, generic_decl.as_str(), generic_ref.as_str());

    DeclarationTsOutput { content: ts }
}

enum ScriptContent<'a> {
    Single(&'a str),
    Split {
        first: &'a str,
        second: &'a str,
        second_start: u32,
    },
}

impl<'a> ScriptContent<'a> {
    fn get(&self, start: u32, end: u32) -> Option<&'a str> {
        match self {
            Self::Single(script) => script.get(start as usize..end as usize),
            Self::Split {
                first,
                second,
                second_start,
            } => {
                if end <= *second_start {
                    return first.get(start as usize..end as usize);
                }
                if start >= *second_start {
                    let start = (start - *second_start) as usize;
                    let end = (end - *second_start) as usize;
                    return second.get(start..end);
                }
                None
            }
        }
    }
}

fn emit_module_statements(ts: &mut String, summary: &Croquis, script: &ScriptContent<'_>) {
    let mut spans: SmallVec<[(u32, u32); 8]> = SmallVec::new();
    for import in &summary.import_statements {
        spans.push((import.start, import.end));
    }
    for re_export in &summary.re_exports {
        spans.push((re_export.start, re_export.end));
    }
    for type_export in &summary.type_exports {
        spans.push((type_export.start, type_export.end));
    }

    spans.sort_unstable();
    spans.dedup();

    for (start, end) in spans {
        let Some(text) = script.get(start, end) else {
            continue;
        };
        let text = text.trim();
        if text.is_empty() {
            continue;
        }
        ts.push_str(text);
        ts.push('\n');
    }

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

fn emit_props_type(ts: &mut String, summary: &Croquis, generic_decl: &str) {
    if type_exists(summary, "Props") {
        return;
    }

    if let Some(type_args) = summary
        .macros
        .define_props()
        .and_then(|call| call.type_args.as_ref())
    {
        let inner = strip_outer_angle_brackets(type_args.as_str());
        append!(*ts, "export type Props{generic_decl} = {inner};\n");
        return;
    }

    if !summary.macros.props().is_empty() {
        append!(*ts, "export type Props{generic_decl} = {{\n");
        for prop in summary.macros.props() {
            let key = property_key(prop.name.as_str());
            let optional = if prop.required { "" } else { "?" };
            let prop_type = prop.prop_type.as_deref().unwrap_or("unknown");
            append!(*ts, "  {key}{optional}: {prop_type};\n");
        }
        ts.push_str("};\n");
        return;
    }

    append!(*ts, "export type Props{generic_decl} = {{}};\n");
}

fn emit_emits_type(ts: &mut String, summary: &Croquis, generic_decl: &str) {
    if type_exists(summary, "Emits") {
        return;
    }

    if let Some(type_args) = summary
        .macros
        .define_emits()
        .and_then(|call| call.type_args.as_ref())
    {
        let inner = strip_outer_angle_brackets(type_args.as_str());
        append!(*ts, "export type Emits{generic_decl} = {inner};\n");
        return;
    }

    if !summary.macros.emits().is_empty() {
        append!(*ts, "export type Emits{generic_decl} = {{\n");
        for emit in summary.macros.emits() {
            let key = string_literal(emit.name.as_str());
            let payload = emit.payload_type.as_deref().unwrap_or("any[]");
            append!(*ts, "  {key}: {payload};\n");
        }
        ts.push_str("};\n");
        return;
    }

    append!(*ts, "export type Emits{generic_decl} = {{}};\n");
}

fn emit_slots_type(ts: &mut String, summary: &Croquis, generic_decl: &str) {
    if type_exists(summary, "Slots") {
        return;
    }

    if let Some(type_args) = summary
        .macros
        .define_slots()
        .and_then(|call| call.type_args.as_ref())
    {
        let inner = strip_outer_angle_brackets(type_args.as_str());
        append!(*ts, "export type Slots{generic_decl} = {inner};\n");
        return;
    }

    append!(*ts, "export type Slots{generic_decl} = {{}};\n");
}

fn emit_default_component(ts: &mut String, generic_decl: &str, generic_ref: &str) {
    let props_ref = cstr!("Props{generic_ref}");
    let emits_ref = cstr!("Emits{generic_ref}");
    let slots_ref = cstr!("Slots{generic_ref}");

    ts.push_str("type __EmitShape<T> = T extends (...args: any[]) => any ? T : T extends Record<string, any> ? {\n");
    ts.push_str("  [K in keyof T]: T[K] extends (...args: infer A) => any ? A : T[K] extends any[] ? T[K] : any[];\n");
    ts.push_str("} : Record<string, any[]>;\n");
    ts.push_str("type __EmitArgs<T, K extends keyof T> = T[K] extends any[] ? T[K] : any[];\n");
    ts.push_str("type __EmitFn<T> = __EmitShape<T> extends (...args: any[]) => any ? __EmitShape<T> : (<K extends keyof __EmitShape<T>>(event: K, ...args: __EmitArgs<__EmitShape<T>, K>) => void);\n");
    append!(*ts, "type __VizeComponentInstance{generic_decl} = {{\n");
    append!(*ts, "  $props: {props_ref};\n");
    append!(*ts, "  $emit: __EmitFn<{emits_ref}>;\n");
    append!(*ts, "  $slots: {slots_ref};\n");
    ts.push_str("};\n");
    append!(
        *ts,
        "declare const __vize_component__: new {generic_decl}(...args: any[]) => __VizeComponentInstance{generic_ref};\n"
    );
    ts.push_str("export default __vize_component__;\n");
}

fn generic_param(summary: &Croquis) -> Option<&str> {
    summary
        .scopes
        .iter()
        .find_map(|scope| match (scope.kind, scope.data()) {
            (ScopeKind::ScriptSetup, ScopeData::ScriptSetup(data)) => {
                data.generic.as_ref().map(|generic| generic.as_str())
            }
            _ => None,
        })
}

fn type_exists(summary: &Croquis, name: &str) -> bool {
    summary
        .type_exports
        .iter()
        .any(|type_export| type_export.name.as_str() == name)
}

fn property_key(name: &str) -> String {
    if is_identifier_name(name) {
        return name.into();
    }
    string_literal(name)
}

fn is_identifier_name(name: &str) -> bool {
    let mut chars = name.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    if !(first == '_' || first == '$' || first.is_ascii_alphabetic()) {
        return false;
    }
    chars.all(|ch| ch == '_' || ch == '$' || ch.is_ascii_alphanumeric())
}

fn string_literal(value: &str) -> String {
    let escaped = value.replace('\\', "\\\\").replace('\'', "\\'");
    cstr!("'{escaped}'")
}

fn strip_outer_angle_brackets(value: &str) -> &str {
    let value = value.trim();
    if !value.starts_with('<') {
        return value;
    }

    let mut depth = 0i32;
    for (index, ch) in value.char_indices() {
        match ch {
            '<' => depth += 1,
            '>' => {
                depth -= 1;
                if depth == 0 && index == value.len() - 1 {
                    return &value[1..index];
                }
            }
            _ => {}
        }
    }

    value
}

fn extract_generic_names(generic_param: &str) -> String {
    let mut names = String::default();
    let mut depth = 0i32;
    let mut current = String::default();

    for ch in generic_param.chars() {
        match ch {
            '<' => {
                depth += 1;
                current.push(ch);
            }
            '>' => {
                depth -= 1;
                current.push(ch);
            }
            ',' if depth == 0 => {
                append_generic_name(&mut names, current.trim());
                current.clear();
            }
            _ => current.push(ch),
        }
    }

    append_generic_name(&mut names, current.trim());
    names
}

fn append_generic_name(names: &mut String, param: &str) {
    if param.is_empty() {
        return;
    }
    let name = param.split_whitespace().next().unwrap_or(param);
    if !names.is_empty() {
        names.push_str(", ");
    }
    names.push_str(name);
}

fn add_generic_defaults(generic_param: &str) -> String {
    let mut result = String::default();
    let mut depth = 0i32;
    let mut current = String::default();

    for ch in generic_param.chars() {
        match ch {
            '<' => {
                depth += 1;
                current.push(ch);
            }
            '>' => {
                depth -= 1;
                current.push(ch);
            }
            ',' if depth == 0 => {
                append_param_with_default(&mut result, current.trim());
                result.push_str(", ");
                current.clear();
            }
            _ => current.push(ch),
        }
    }

    append_param_with_default(&mut result, current.trim());
    result
}

fn append_param_with_default(result: &mut String, param: &str) {
    if param.is_empty() {
        return;
    }
    result.push_str(param);

    let mut depth = 0i32;
    let has_default = param.chars().any(|ch| {
        match ch {
            '<' => depth += 1,
            '>' => depth -= 1,
            '=' if depth == 0 => return true,
            _ => {}
        }
        false
    });
    if !has_default {
        result.push_str(" = any");
    }
}

#[cfg(test)]
mod tests {
    use super::generate_declaration_ts;
    use crate::{Analyzer, AnalyzerOptions};

    #[test]
    fn generates_type_macro_declaration() {
        let script = r#"import type { User } from './types'

interface PublicProps {
  user: User
  active?: boolean
}

const props = defineProps<PublicProps>()
const emit = defineEmits<{
  (event: 'select', user: User): void
}>()
const slots = defineSlots<{
  default(props: { user: User }): any
}>()
"#;

        let mut analyzer = Analyzer::with_options(AnalyzerOptions::full());
        analyzer.analyze_script_setup(script);
        let summary = analyzer.finish();
        let output = generate_declaration_ts(&summary, Some(script));

        assert!(output
            .content
            .contains("import type { User } from './types'"));
        assert!(output.content.contains("interface PublicProps"));
        assert!(output.content.contains("export type Props = PublicProps;"));
        assert!(output.content.contains("export type Emits = {"));
        assert!(output.content.contains("export type Slots = {"));
        assert!(output
            .content
            .contains("export default __vize_component__;"));
    }

    #[test]
    fn generates_runtime_macro_declaration() {
        let script = r#"const props = defineProps({
  title: String,
  count: { type: Number, required: true },
  'data-id': String,
})
const emit = defineEmits(['save'])
"#;

        let mut analyzer = Analyzer::with_options(AnalyzerOptions::full());
        analyzer.analyze_script_setup(script);
        let summary = analyzer.finish();
        let output = generate_declaration_ts(&summary, Some(script));

        assert!(output.content.contains("title?: string;"));
        assert!(output.content.contains("count: number;"));
        assert!(output.content.contains("'data-id'?: string;"));
        assert!(output.content.contains("'save': any[];"));
    }
}