vize_armature 0.143.0

Armature - The structural parser framework 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
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
//! Element processing methods for the parser.
//!
//! Handles text, interpolation, open/close tags, element type determination,
//! comments, and error reporting.

use vize_carton::{Box, String, appends, directive::parse_vize_directive};
use vize_relief::{
    ast::*,
    errors::{CompilerError, ErrorCode},
};

use super::{CurrentElement, Parser, ParserStackEntry};

/// Maximum element nesting depth retained by the parser.
///
/// Elements nested deeper than this are flattened with a recoverable error
/// instead of being pushed onto the open-element stack. This keeps the depth
/// of the produced AST bounded so the recursive passes that walk it later
/// (transform, codegen, semantic analysis) stay within a predictable amount of
/// stack space regardless of the input. The limit is far beyond any realistic
/// template while still cheap to enforce.
const MAX_ELEMENT_NESTING_DEPTH: usize = 256;

/// Message attached to the recoverable error raised when the nesting limit is hit.
const NESTING_TOO_DEEP_MESSAGE: &str = "Element nesting is too deep.";

impl<'a> Parser<'a> {
    /// Process text content
    pub(super) fn on_text_impl(&mut self, start: usize, end: usize) {
        if start >= end {
            return;
        }

        let source = self.get_source(start, end).to_owned();
        self.append_or_merge_text(&source, start, end);
    }

    /// Process text entity content
    pub(super) fn on_text_entity_impl(&mut self, ch: char, start: usize, end: usize) {
        let mut content = [0_u8; 4];
        self.append_or_merge_text(ch.encode_utf8(&mut content), start, end);
    }

    /// Append or merge text node
    fn append_or_merge_text(&mut self, content: &str, start: usize, end: usize) {
        let merge_start_off = match self.stack.last().and_then(|e| e.element.children.last()) {
            Some(TemplateChildNode::Text(t)) => Some(t.loc.start.offset as usize),
            _ => None,
        };

        if let Some(merge_start) = merge_start_off {
            let end_pos = self.get_pos(end);
            let source_span = self.get_source(merge_start, end).into();
            if let Some(entry) = self.stack.last_mut()
                && let Some(TemplateChildNode::Text(text_node)) = entry.element.children.last_mut()
            {
                text_node.content.push_str(content);
                text_node.loc.end = end_pos;
                text_node.loc.source = source_span;
            }
        } else {
            let loc = self.create_loc(start, end);
            let text_node = TextNode::new(content, loc);
            let boxed = Box::new_in(text_node, self.allocator);
            self.add_child(TemplateChildNode::Text(boxed));
        }
    }

    /// Process interpolation
    pub(super) fn on_interpolation_impl(&mut self, start: usize, end: usize) {
        let raw_content = self.get_source(start, end);
        let content = raw_content.trim();

        // Calculate trimmed positions for accurate source mapping
        let leading_ws = raw_content.len() - raw_content.trim_start().len();
        let trimmed_start = start + leading_ws;
        let trimmed_end = trimmed_start + content.len();

        let delim_len = self.options.delimiters.0.len();
        let full_start = start - delim_len;
        let full_end = end + self.options.delimiters.1.len();
        let loc = self.create_loc(full_start, full_end);
        let inner_loc = self.create_loc(trimmed_start, trimmed_end);

        // Create expression node
        let expr = SimpleExpressionNode::new(content, false, inner_loc);
        let expr_boxed = Box::new_in(expr, self.allocator);

        let interp = InterpolationNode {
            content: ExpressionNode::Simple(expr_boxed),
            loc,
        };
        let boxed = Box::new_in(interp, self.allocator);
        self.add_child(TemplateChildNode::Interpolation(boxed));
    }

    /// Process open tag name
    pub(super) fn on_open_tag_name_impl(&mut self, start: usize, end: usize) {
        let tag = self.get_source(start, end);
        let ns = if self.should_force_html_namespace(tag) {
            Namespace::Html
        } else {
            (self.options.get_namespace)(tag, self.stack.last().map(|e| e.element.tag.as_str()))
        };

        self.current_element = Some(CurrentElement {
            tag: tag.into(),
            tag_start: start,
            tag_end: end,
            ns,
            is_self_closing: false,
            props: vize_carton::Vec::new_in(self.allocator),
        });
    }

    /// Process open tag end
    pub(super) fn on_open_tag_end_impl(&mut self, end: usize) {
        if let Some(current) = self.current_element.take() {
            let tag_start = current.tag_start;
            let loc = self.create_loc(tag_start.saturating_sub(1), end + 1); // Include < and >

            let mut element = ElementNode::new(self.allocator, current.tag.clone(), loc);
            element.ns = current.ns;
            element.is_self_closing = current.is_self_closing;
            element.props = current.props;

            // Determine element type
            element.tag_type = self.determine_element_type(&element);

            // Check for pre tags
            let is_pre = (self.options.is_pre_tag)(element.tag.as_str());
            let has_v_pre = element
                .props
                .iter()
                .any(|p| matches!(p, PropNode::Directive(d) if d.name == "pre"));

            // When v-pre is on this element, convert all directives (except v-pre itself)
            // back to raw attribute nodes, since v-pre means "skip compilation"
            if has_v_pre {
                let allocator = self.allocator;
                let mut i = 0;
                while i < element.props.len() {
                    if let PropNode::Directive(dir) = &element.props[i] {
                        if dir.name == "pre" {
                            // Remove v-pre directive itself
                            element.props.remove(i);
                            continue;
                        }
                        // Convert directive back to attribute using its raw_name + arg
                        // to reconstruct the original attribute name (e.g., ":id", "@click")
                        let attr_name = {
                            let prefix = dir.raw_name.as_deref().unwrap_or(&dir.name);
                            let arg_str = dir.arg.as_ref().map(|a| match a {
                                ExpressionNode::Simple(s) => s.content.as_str(),
                                ExpressionNode::Compound(c) => c.loc.source.as_str(),
                            });
                            if let Some(arg) = arg_str {
                                let mut name =
                                    vize_carton::String::with_capacity(prefix.len() + arg.len());
                                name.push_str(prefix);
                                name.push_str(arg);
                                name
                            } else {
                                vize_carton::String::from(prefix)
                            }
                        };
                        let attr_value = dir.exp.as_ref().map(|e| {
                            let content = match e {
                                ExpressionNode::Simple(s) => s.loc.source.clone(),
                                ExpressionNode::Compound(c) => c.loc.source.clone(),
                            };
                            TextNode {
                                content,
                                loc: dir.loc.clone(),
                            }
                        });
                        let attr = PropNode::Attribute(Box::new_in(
                            AttributeNode {
                                name: attr_name,
                                name_loc: dir.loc.clone(),
                                value: attr_value,
                                loc: dir.loc.clone(),
                            },
                            allocator,
                        ));
                        element.props[i] = attr;
                    }
                    i += 1;
                }
            }

            if current.is_self_closing || (self.options.is_void_tag)(element.tag.as_str()) {
                // Self-closing or void tag, add directly
                let boxed = Box::new_in(element, self.allocator);
                self.add_child(TemplateChildNode::Element(boxed));
            } else if self.stack.len() >= MAX_ELEMENT_NESTING_DEPTH {
                // Nesting limit reached: keep the element but do not descend any
                // further, so the resulting tree depth stays bounded. The
                // element is attached at the current level as a leaf and a
                // recoverable error is recorded.
                self.errors.push(CompilerError::with_message(
                    ErrorCode::ExtendPoint,
                    NESTING_TOO_DEEP_MESSAGE,
                    Some(element.loc.clone()),
                ));
                let boxed = Box::new_in(element, self.allocator);
                self.add_child(TemplateChildNode::Element(boxed));
            } else {
                // Push to stack
                self.stack.push(ParserStackEntry {
                    element,
                    in_pre: self.in_pre,
                    in_v_pre: self.in_v_pre,
                });
                self.in_pre = is_pre || self.in_pre;
                self.in_v_pre = has_v_pre || self.in_v_pre;
            }
        }
    }

    /// Process self-closing tag
    pub(super) fn on_self_closing_tag_impl(&mut self, _end: usize) {
        if let Some(ref mut current) = self.current_element {
            current.is_self_closing = true;
        }
    }

    /// Process close tag
    pub(super) fn on_close_tag_impl(&mut self, start: usize, end: usize) {
        let tag = self.get_source(start, end);

        // Find matching open tag
        let mut found = false;
        for i in (0..self.stack.len()).rev() {
            if self.stack[i].element.tag.eq_ignore_ascii_case(tag) {
                found = true;

                // Pop all elements up to and including the match
                let mut elements: vize_carton::Vec<'a, ParserStackEntry<'a>> =
                    vize_carton::Vec::new_in(self.allocator);
                while self.stack.len() > i {
                    if let Some(entry) = self.stack.pop() {
                        elements.push(entry);
                    } else {
                        break;
                    }
                }

                // Report errors for unclosed elements (except the matching one)
                for entry in elements.iter().skip(1) {
                    let loc = entry.element.loc.clone();
                    self.errors
                        .push(CompilerError::new(ErrorCode::MissingEndTag, Some(loc)));
                }

                // Add all popped elements back as children
                for entry in elements.into_iter().rev() {
                    let in_pre = entry.in_pre;
                    let in_v_pre = entry.in_v_pre;

                    let boxed = Box::new_in(entry.element, self.allocator);
                    self.add_child(TemplateChildNode::Element(boxed));

                    self.in_pre = in_pre;
                    self.in_v_pre = in_v_pre;
                }

                break;
            }
        }

        if !found {
            let loc = self.create_loc(start.saturating_sub(2), end + 1); // Include </ and >
            self.errors
                .push(CompilerError::new(ErrorCode::InvalidEndTag, Some(loc)));
        }
    }

    /// Determine element type (element, component, slot, template)
    pub(super) fn determine_element_type(&self, element: &ElementNode<'a>) -> ElementType {
        let tag = element.tag.as_str();

        // Check for slot
        if tag == "slot" {
            return ElementType::Slot;
        }

        // Check for template
        if tag == "template" {
            // Template with v-if, v-for, or v-slot is a template element
            let has_structural_directive = element.props.iter().any(|p| {
                matches!(p, PropNode::Directive(d) if matches!(d.name.as_str(), "if" | "else-if" | "else" | "for" | "slot"))
            });
            if has_structural_directive {
                return ElementType::Template;
            }
        }

        // Check if it's a component
        if self.is_component(tag) {
            return ElementType::Component;
        }

        ElementType::Element
    }

    /// Check if tag is a component
    pub(super) fn is_component(&self, tag: &str) -> bool {
        // Core built-in components
        if matches!(
            tag,
            "Teleport"
                | "Suspense"
                | "KeepAlive"
                | "BaseTransition"
                | "Transition"
                | "TransitionGroup"
        ) {
            return true;
        }

        // Custom element check
        if let Some(is_custom) = self.options.is_custom_element
            && is_custom(tag)
        {
            return false;
        }

        if self.options.custom_renderer {
            return tag.chars().next().is_some_and(|c| c.is_uppercase()) || tag.contains('-');
        }

        // Native tag check
        if let Some(is_native) = self.options.is_native_tag {
            if !is_native(tag) {
                return true;
            }
        } else {
            // Default: check if starts with uppercase
            if tag.chars().next().is_some_and(|c| c.is_uppercase()) {
                return true;
            }
        }

        false
    }

    fn should_force_html_namespace(&self, tag: &str) -> bool {
        if !self.options.custom_renderer {
            return false;
        }

        if matches!(tag, "svg" | "math") {
            return false;
        }

        if self
            .stack
            .last()
            .is_some_and(|entry| matches!(entry.element.ns, Namespace::Svg | Namespace::MathMl))
        {
            return false;
        }

        tag.chars().next().is_some_and(|c| c.is_lowercase())
            && !tag.contains('-')
            && !vize_carton::is_html_tag(tag)
    }

    /// Process comment
    pub(super) fn on_comment_impl(&mut self, start: usize, end: usize) {
        let content = self.get_source(start, end);
        let loc_start = start.saturating_sub(4);
        let loc_end = end.saturating_add(3).min(self.source.len());
        let loc = self.create_loc(loc_start, loc_end); // Include <!-- and --> when present.

        // Check for @vize: directive
        let directive = parse_vize_directive(content, loc.start.line, loc.start.offset);

        // Always preserve directive comments (even when options.comments = false)
        // so they can be explicitly handled by codegen and linter
        if directive.is_none() && !self.options.comments {
            return;
        }

        let mut comment = CommentNode::new(content, loc);
        comment.directive = directive.map(|d| d.kind);
        let boxed = Box::new_in(comment, self.allocator);
        self.add_child(TemplateChildNode::Comment(boxed));
    }

    /// Process CDATA
    pub(super) fn on_cdata_impl(&mut self, start: usize, end: usize) {
        let is_html_ns = self
            .stack
            .last()
            .map(|e| e.element.ns)
            .unwrap_or(Namespace::Html)
            == Namespace::Html;
        if is_html_ns {
            self.on_error_impl(ErrorCode::CdataInHtmlContent, start.saturating_sub(9));
        } else {
            self.on_text_impl(start, end);
        }
    }

    /// Handle error
    pub(super) fn on_error_impl(&mut self, code: ErrorCode, index: usize) {
        let len = self.source.len();
        let start = index.min(len);
        let end = (index + 1).min(len);
        let loc = self.create_loc(start, end);
        let error = if let Some(message) = self.recovery_error_message(code) {
            CompilerError::with_message(code, message, Some(loc))
        } else {
            CompilerError::new(code, Some(loc))
        };
        self.errors.push(error);
    }

    fn recovery_error_message(&self, code: ErrorCode) -> Option<String> {
        match code {
            ErrorCode::EofBeforeTagName => Some(
                "Unexpected end of input after `<`; treating it as text so parsing can continue."
                    .into(),
            ),
            ErrorCode::EofInTag => Some(
                "Unexpected end of input inside a tag; inferred the missing tag close so parsing can continue."
                    .into(),
            ),
            ErrorCode::EofInComment => Some(
                "Comment is missing its closing `-->`; preserving the unfinished comment so parsing can finish."
                    .into(),
            ),
            ErrorCode::InvalidFirstCharacterOfTagName => Some(
                "Tag name starts with an invalid character; treating the malformed tag as text.".into(),
            ),
            ErrorCode::MissingAttributeValue => {
                let name = self
                    .current_attr
                    .as_ref()
                    .map(|attr| attr.name.as_str())
                    .or_else(|| self.current_dir.as_ref().map(|dir| dir.raw_name.as_str()))
                    .unwrap_or("attribute");
                let mut message = String::with_capacity(name.len() + 70);
                appends!(
                    message,
                    "Attribute `",
                    name,
                    "` is missing a value after `=`; continuing without the value."
                );
                Some(message)
            }
            ErrorCode::MissingDynamicDirectiveArgumentEnd => Some(
                "Dynamic directive argument is missing its closing `]`; inferred the argument end at the next tag boundary."
                    .into(),
            ),
            ErrorCode::MissingInterpolationEnd => {
                let delimiter = self.options.delimiters.1.as_str();
                let mut message = String::with_capacity(delimiter.len() + 97);
                appends!(
                    message,
                    "Interpolation is missing its closing delimiter `",
                    delimiter,
                    "`; treating the unfinished interpolation as text."
                );
                Some(message)
            }
            ErrorCode::UnexpectedCharacterInAttributeName => Some(
                "Attribute name contains an invalid character; inferred the nearest attribute boundary and continued."
                    .into(),
            ),
            ErrorCode::UnexpectedCharacterInUnquotedAttributeValue => Some(
                "Unquoted attribute value contains a character that should be quoted; keeping it in the value and continuing."
                    .into(),
            ),
            ErrorCode::UnexpectedEqualsSignBeforeAttributeName => Some(
                "Unexpected `=` before an attribute name; skipping it and continuing with the next attribute."
                    .into(),
            ),
            ErrorCode::MissingWhitespaceBetweenAttributes => Some(
                "Missing whitespace between attributes; inferred a new attribute boundary.".into(),
            ),
            ErrorCode::IncorrectlyClosedComment => Some(
                "Comment was closed as `--!>`; treating it as `-->` so parsing can continue."
                    .into(),
            ),
            ErrorCode::IncorrectlyOpenedComment => Some(
                "Declaration or comment syntax is malformed; skipping it until the next `>`.".into(),
            ),
            _ => None,
        }
    }
}