vize_maestro 0.0.1-alpha.26

Maestro - Language Server Protocol implementation for Vize 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
//! Template virtual code generation.
//!
//! Extracts expressions from Vue templates and generates TypeScript
//! for type checking and IntelliSense.

use vize_armature::RootNode;
use vize_relief::ast::*;

use super::{MappingData, SourceMap, SourceMapping, SourceRange, VirtualDocument, VirtualLanguage};

/// Template code generator.
pub struct TemplateCodeGenerator {
    /// Generated TypeScript output
    output: String,
    /// Source mappings
    mappings: Vec<SourceMapping>,
    /// Current position in the generated output
    gen_offset: u32,
    /// Expression counter for unique variable names
    expr_counter: u32,
    /// Block offset in the original SFC
    block_offset: u32,
}

impl TemplateCodeGenerator {
    /// Create a new template code generator.
    pub fn new() -> Self {
        Self {
            output: String::new(),
            mappings: Vec::new(),
            gen_offset: 0,
            expr_counter: 0,
            block_offset: 0,
        }
    }

    /// Set the block offset (position of <template> in SFC).
    pub fn set_block_offset(&mut self, offset: u32) {
        self.block_offset = offset;
    }

    /// Generate virtual TypeScript from a template AST.
    pub fn generate<'a>(&mut self, ast: &RootNode<'a>, _source: &str) -> VirtualDocument {
        // Reset state
        self.output.clear();
        self.mappings.clear();
        self.gen_offset = 0;
        self.expr_counter = 0;

        // Generate header
        self.write_line("// Virtual TypeScript for template type checking");
        self.write_line("// Generated by vize_maestro");
        self.write_line("");
        self.write_line("declare const __VIZE_ctx: {");
        self.write_line("  // Context bindings from <script setup>");
        self.write_line("  [key: string]: any;");
        self.write_line("};");
        self.write_line("");
        self.write_line("// Template expressions");

        // Visit all nodes and extract expressions
        self.visit_children(&ast.children);

        // Create virtual document
        let mut source_map = SourceMap::from_mappings(self.mappings.clone());
        source_map.set_block_offset(self.block_offset);

        VirtualDocument {
            uri: String::new(), // Will be set by generator
            content: self.output.clone(),
            language: VirtualLanguage::Template,
            source_map,
        }
    }

    /// Visit child nodes.
    fn visit_children(&mut self, children: &[TemplateChildNode]) {
        for child in children {
            self.visit_child(child);
        }
    }

    /// Visit a single child node.
    fn visit_child(&mut self, node: &TemplateChildNode) {
        match node {
            TemplateChildNode::Element(el) => self.visit_element(el),
            TemplateChildNode::Text(_) => {}
            TemplateChildNode::Comment(_) => {}
            TemplateChildNode::Interpolation(interp) => self.visit_interpolation(interp),
            TemplateChildNode::If(if_node) => self.visit_if(if_node),
            TemplateChildNode::For(for_node) => self.visit_for(for_node),
            TemplateChildNode::TextCall(_) => {}
            TemplateChildNode::IfBranch(branch) => {
                // Visit condition expression
                if let Some(ref condition) = branch.condition {
                    self.emit_expression_node(condition, "if");
                }
                self.visit_children(&branch.children);
            }
            TemplateChildNode::CompoundExpression(_) => {}
            TemplateChildNode::Hoisted(_) => {}
        }
    }

    /// Visit an element node.
    fn visit_element(&mut self, element: &ElementNode) {
        // Process directives
        for prop in &element.props {
            if let PropNode::Directive(dir) = prop {
                self.visit_directive(dir, &element.tag);
            }
        }

        // Process children
        self.visit_children(&element.children);
    }

    /// Visit a directive.
    fn visit_directive(&mut self, directive: &DirectiveNode, _tag: &str) {
        let dir_name = &directive.name;

        // Handle different directive types
        if let Some(ref exp) = directive.exp {
            self.emit_expression_node(exp, dir_name);
        }
    }

    /// Visit an interpolation.
    fn visit_interpolation(&mut self, interp: &InterpolationNode) {
        self.emit_expression_node(&interp.content, "interpolation");
    }

    /// Visit an if node (v-if/v-else-if/v-else).
    fn visit_if(&mut self, if_node: &IfNode) {
        for branch in &if_node.branches {
            // Visit condition expression
            if let Some(ref condition) = branch.condition {
                self.emit_expression_node(condition, "if");
            }

            // Visit children
            self.visit_children(&branch.children);
        }
    }

    /// Visit a for node.
    fn visit_for(&mut self, for_node: &ForNode) {
        // Emit the source expression
        self.emit_expression_node(&for_node.source, "for");

        // Visit children
        self.visit_children(&for_node.children);
    }

    /// Emit a TypeScript expression from an ExpressionNode with source mapping.
    fn emit_expression_node(&mut self, expr: &ExpressionNode, dir_name: &str) {
        match expr {
            ExpressionNode::Simple(simple) => {
                self.emit_simple_expression(simple, dir_name);
            }
            ExpressionNode::Compound(_compound) => {
                // For compound expressions, we just track the overall location
                // but don't emit individual parts for simplicity
                let var_name = format!("__VIZE_{}", self.expr_counter);
                self.expr_counter += 1;

                let line = format!("const {} = void 0; // compound expression\n", var_name);
                self.write(&line);
            }
        }
    }

    /// Emit a TypeScript expression with source mapping.
    fn emit_simple_expression(&mut self, expr: &SimpleExpressionNode, _dir_name: &str) {
        if expr.content.is_empty() {
            return;
        }

        let var_name = format!("__VIZE_{}", self.expr_counter);
        self.expr_counter += 1;

        // Generate TypeScript: const __VIZE_N = __VIZE_ctx.expr;
        let line = format!("const {} = __VIZE_ctx.{};\n", var_name, expr.content);

        // Calculate positions
        let expr_start_in_line = format!("const {} = __VIZE_ctx.", var_name).len() as u32;
        let gen_start = self.gen_offset + expr_start_in_line;
        let gen_end = gen_start + expr.content.len() as u32;

        let source_start = expr.loc.start.offset;
        let source_end = expr.loc.end.offset;

        // Create mapping
        let mapping = SourceMapping::with_data(
            SourceRange::new(source_start, source_end),
            SourceRange::new(gen_start, gen_end),
            MappingData::Expression {
                text: expr.content.to_string(),
            },
        );
        self.mappings.push(mapping);

        // Write the line
        self.write(&line);
    }

    /// Write a string to the output.
    fn write(&mut self, s: &str) {
        self.output.push_str(s);
        self.gen_offset += s.len() as u32;
    }

    /// Write a line to the output.
    fn write_line(&mut self, s: &str) {
        self.output.push_str(s);
        self.output.push('\n');
        self.gen_offset += s.len() as u32 + 1;
    }
}

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

/// Extract expressions from a template for quick analysis.
#[derive(Debug, Clone)]
pub struct TemplateExpression {
    /// Expression text
    pub text: String,
    /// Source range in template
    pub range: SourceRange,
    /// Expression kind
    pub kind: ExpressionKind,
}

/// Kind of template expression.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExpressionKind {
    /// Interpolation {{ expr }}
    Interpolation,
    /// v-bind expression
    VBind,
    /// v-on expression
    VOn,
    /// v-if/v-else-if condition
    VIf,
    /// v-for source
    VFor,
    /// v-model value
    VModel,
    /// v-show condition
    VShow,
    /// v-slot binding
    VSlot,
    /// Other directive expression
    Other,
}

/// Quick extraction of expressions from template.
pub fn extract_expressions<'a>(ast: &'a RootNode<'a>) -> Vec<TemplateExpression> {
    let mut expressions = Vec::new();
    extract_from_children(&ast.children, &mut expressions);
    expressions
}

fn extract_from_children<'a>(
    children: &'a [TemplateChildNode<'a>],
    expressions: &mut Vec<TemplateExpression>,
) {
    for child in children {
        extract_from_child(child, expressions);
    }
}

fn extract_from_child<'a>(
    node: &'a TemplateChildNode<'a>,
    expressions: &mut Vec<TemplateExpression>,
) {
    match node {
        TemplateChildNode::Element(el) => {
            for prop in &el.props {
                if let PropNode::Directive(dir) = prop {
                    extract_from_directive(dir, expressions);
                }
            }
            extract_from_children(&el.children, expressions);
        }
        TemplateChildNode::Interpolation(interp) => {
            if let Some((text, loc)) = get_expression_content(&interp.content) {
                expressions.push(TemplateExpression {
                    text,
                    range: SourceRange::from(loc),
                    kind: ExpressionKind::Interpolation,
                });
            }
        }
        TemplateChildNode::If(if_node) => {
            for branch in &if_node.branches {
                if let Some(ref cond) = branch.condition {
                    if let Some((text, loc)) = get_expression_content(cond) {
                        expressions.push(TemplateExpression {
                            text,
                            range: SourceRange::from(loc),
                            kind: ExpressionKind::VIf,
                        });
                    }
                }
                extract_from_children(&branch.children, expressions);
            }
        }
        TemplateChildNode::For(for_node) => {
            if let Some((text, loc)) = get_expression_content(&for_node.source) {
                expressions.push(TemplateExpression {
                    text,
                    range: SourceRange::from(loc),
                    kind: ExpressionKind::VFor,
                });
            }
            extract_from_children(&for_node.children, expressions);
        }
        TemplateChildNode::IfBranch(branch) => {
            if let Some(ref cond) = branch.condition {
                if let Some((text, loc)) = get_expression_content(cond) {
                    expressions.push(TemplateExpression {
                        text,
                        range: SourceRange::from(loc),
                        kind: ExpressionKind::VIf,
                    });
                }
            }
            extract_from_children(&branch.children, expressions);
        }
        _ => {}
    }
}

fn extract_from_directive<'a>(
    dir: &'a DirectiveNode<'a>,
    expressions: &mut Vec<TemplateExpression>,
) {
    if let Some(ref exp) = dir.exp {
        let kind = match dir.name.as_str() {
            "bind" => ExpressionKind::VBind,
            "on" => ExpressionKind::VOn,
            "if" | "else-if" => ExpressionKind::VIf,
            "for" => ExpressionKind::VFor,
            "model" => ExpressionKind::VModel,
            "show" => ExpressionKind::VShow,
            "slot" => ExpressionKind::VSlot,
            _ => ExpressionKind::Other,
        };
        if let Some((text, loc)) = get_expression_content(exp) {
            expressions.push(TemplateExpression {
                text,
                range: SourceRange::from(loc),
                kind,
            });
        }
    }
}

/// Helper to get content and location from an ExpressionNode.
fn get_expression_content<'a>(
    expr: &'a ExpressionNode<'a>,
) -> Option<(String, &'a SourceLocation)> {
    match expr {
        ExpressionNode::Simple(simple) => {
            if simple.content.is_empty() {
                None
            } else {
                Some((simple.content.to_string(), &simple.loc))
            }
        }
        ExpressionNode::Compound(compound) => {
            // For compound expressions, we return the full location
            // but can't easily get a single content string
            Some(("<compound>".to_string(), &compound.loc))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_template_code_generator() {
        let source = r#"<div>{{ message }}</div>"#;
        let allocator = vize_carton::Bump::new();
        let (ast, _) = vize_armature::parse(&allocator, source);

        let mut gen = TemplateCodeGenerator::new();
        let doc = gen.generate(&ast, source);

        // Should contain the expression
        assert!(doc.content.contains("__VIZE_ctx.message"));
        assert!(!doc.source_map.is_empty());
    }

    #[test]
    fn test_generator_with_directives() {
        let source = r#"<div v-if="show">test</div>"#;
        let allocator = vize_carton::Bump::new();
        let (ast, _) = vize_armature::parse(&allocator, source);

        let mut gen = TemplateCodeGenerator::new();
        let doc = gen.generate(&ast, source);

        // Should have generated some TypeScript
        assert!(doc.content.contains("__VIZE_"));
    }
}