vize_relief 0.211.0

Relief - The sculptured AST surface 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
//! Compiler error types and codes.

use crate::SourceLocation;
use thiserror::Error;
use vize_carton::{CompactString, ToCompactString};

/// Compiler error
#[derive(Debug, Clone, Error)]
#[error("{message}")]
pub struct CompilerError {
    pub code: ErrorCode,
    pub message: CompactString,
    pub loc: Option<SourceLocation>,
}

impl CompilerError {
    pub fn new(code: ErrorCode, loc: Option<SourceLocation>) -> Self {
        Self {
            message: code.message().to_compact_string(),
            code,
            loc,
        }
    }

    pub fn with_message(
        code: ErrorCode,
        message: impl Into<CompactString>,
        loc: Option<SourceLocation>,
    ) -> Self {
        Self {
            code,
            message: message.into(),
            loc,
        }
    }

    /// Returns true when this diagnostic is a parser-level warning that
    /// downstream codegen can recover from. Mirrors `@vue/compiler-sfc`'s
    /// classification: a duplicate attribute is reported but does not
    /// gate render emission (#958).
    #[must_use]
    pub fn is_recoverable(&self) -> bool {
        matches!(self.code, ErrorCode::DuplicateAttribute)
            || (self.code == ErrorCode::ExtendPoint
                && self
                    .message
                    .starts_with("Invalid self-closing syntax on non-void HTML element"))
    }
}

/// Error codes for compiler errors
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u16)]
pub enum ErrorCode {
    // Parse errors
    AbruptClosingOfEmptyComment = 0,
    CdataInHtmlContent = 1,
    DuplicateAttribute = 2,
    EndTagWithAttributes = 3,
    EndTagWithTrailingSolidus = 4,
    EofBeforeTagName = 5,
    EofInCdata = 6,
    EofInComment = 7,
    EofInScriptHtmlCommentLikeText = 8,
    EofInTag = 9,
    IncorrectlyClosedComment = 10,
    IncorrectlyOpenedComment = 11,
    InvalidFirstCharacterOfTagName = 12,
    MissingAttributeValue = 13,
    MissingEndTagName = 14,
    MissingWhitespaceBetweenAttributes = 15,
    NestedComment = 16,
    UnexpectedCharacterInAttributeName = 17,
    UnexpectedCharacterInUnquotedAttributeValue = 18,
    UnexpectedEqualsSignBeforeAttributeName = 19,
    UnexpectedNullCharacter = 20,
    UnexpectedQuestionMarkInsteadOfTagName = 21,
    UnexpectedSolidusInTag = 22,

    // Vue-specific parse errors
    InvalidEndTag = 23,
    MissingEndTag = 24,
    MissingInterpolationEnd = 25,
    MissingDynamicDirectiveArgumentEnd = 26,
    MissingDirectiveName = 27,
    MissingDirectiveModifier = 28,

    // Transform errors
    VIfNoExpression = 29,
    VIfSameKey = 30,
    VElseNoAdjacentIf = 31,
    VForNoExpression = 32,
    VForMalformedExpression = 33,
    VForTemplateKeyPlacement = 34,
    VBindNoExpression = 35,
    VBindSameNameShorthand = 36,
    VOnNoExpression = 37,
    VSlotUnexpectedDirectiveOnSlotOutlet = 38,
    VSlotMixedSlotUsage = 39,
    VSlotDuplicateSlotNames = 40,
    VSlotExtraneousDefaultSlotChildren = 41,
    VSlotMisplaced = 42,
    VModelNoExpression = 43,
    VModelMalformedExpression = 44,
    VModelOnScope = 45,
    VModelOnProps = 46,
    VModelArgOnElement = 47,
    VShowNoExpression = 48,
    /// A template expression failed to parse as JavaScript/TypeScript.
    /// Mirrors `@vue/compiler-core`'s `X_INVALID_EXPRESSION`.
    InvalidExpression = 49,

    // Generic errors
    PrefixIdNotSupported = 50,
    ModuleModeNotSupported = 51,
    CacheHandlerNotSupported = 52,
    ScopeIdNotSupported = 53,

    // Extended errors
    UnhandledCodePath = 100,
    ExtendPoint = 1000,
}

impl ErrorCode {
    pub fn message(&self) -> &'static str {
        match self {
            Self::AbruptClosingOfEmptyComment => "Illegal comment.",
            Self::CdataInHtmlContent => "CDATA section is allowed only in XML context.",
            Self::DuplicateAttribute => "Duplicate attribute.",
            Self::EndTagWithAttributes => "End tag cannot have attributes.",
            Self::EndTagWithTrailingSolidus => "Trailing solidus not allowed in end tags.",
            Self::EofBeforeTagName => "Unexpected EOF in tag.",
            Self::EofInCdata => "EOF in CDATA section.",
            Self::EofInComment => "EOF in comment.",
            Self::EofInScriptHtmlCommentLikeText => "EOF in script.",
            Self::EofInTag => "EOF in tag.",
            Self::IncorrectlyClosedComment => "Incorrectly closed comment.",
            Self::IncorrectlyOpenedComment => "Incorrectly opened comment.",
            Self::InvalidFirstCharacterOfTagName => "Invalid first character of tag name.",
            Self::MissingAttributeValue => "Attribute value expected.",
            Self::MissingEndTagName => "End tag name expected.",
            Self::MissingWhitespaceBetweenAttributes => "Whitespace expected between attributes.",
            Self::NestedComment => "Nested comments are not allowed.",
            Self::UnexpectedCharacterInAttributeName => "Unexpected character in attribute name.",
            Self::UnexpectedCharacterInUnquotedAttributeValue => {
                "Unexpected character in unquoted attribute value."
            }
            Self::UnexpectedEqualsSignBeforeAttributeName => {
                "Unexpected equals sign before attribute name."
            }
            Self::UnexpectedNullCharacter => "Unexpected null character.",
            Self::UnexpectedQuestionMarkInsteadOfTagName => "Invalid tag name.",
            Self::UnexpectedSolidusInTag => "Unexpected solidus in tag.",

            Self::InvalidEndTag => "Invalid end tag.",
            Self::MissingEndTag => "Element is missing end tag.",
            Self::MissingInterpolationEnd => "Interpolation end sign was not found.",
            Self::MissingDynamicDirectiveArgumentEnd => {
                "End bracket for dynamic directive argument was not found."
            }
            Self::MissingDirectiveName => "Directive name is missing.",
            Self::MissingDirectiveModifier => "Directive modifier is expected.",

            Self::VIfNoExpression => "v-if/v-else-if is missing expression.",
            Self::VIfSameKey => "v-if/v-else-if branches must use unique keys.",
            Self::VElseNoAdjacentIf => "v-else/v-else-if has no adjacent v-if.",
            Self::VForNoExpression => "v-for is missing expression.",
            Self::VForMalformedExpression => "v-for has invalid expression.",
            Self::VForTemplateKeyPlacement => {
                "<template v-for> key should be placed on the <template> tag."
            }
            Self::VBindNoExpression => "v-bind is missing expression.",
            Self::VBindSameNameShorthand => "v-bind shorthand requires prop name.",
            Self::VOnNoExpression => "v-on is missing expression.",
            Self::VSlotUnexpectedDirectiveOnSlotOutlet => {
                "Unexpected custom directive on <slot> outlet."
            }
            Self::VSlotMixedSlotUsage => "Mixed v-slot usage with named slots detected.",
            Self::VSlotDuplicateSlotNames => "Duplicate slot names detected.",
            Self::VSlotExtraneousDefaultSlotChildren => {
                "Extraneous children found when component already has an explicit default slot."
            }
            Self::VSlotMisplaced => "v-slot can only be used on components or <template> tags.",
            Self::VModelNoExpression => "v-model is missing expression.",
            Self::VModelMalformedExpression => {
                "v-model value must be a valid JavaScript member expression."
            }
            Self::VModelOnScope => "v-model cannot be used on v-for or v-slot scope variables.",
            Self::VModelOnProps => "v-model cannot be used on props.",
            Self::VModelArgOnElement => "v-model argument is not supported on plain elements.",
            Self::VShowNoExpression => "v-show is missing expression.",
            Self::InvalidExpression => "Error parsing JavaScript expression.",

            Self::PrefixIdNotSupported => "prefixIdentifiers option is not supported in this mode.",
            Self::ModuleModeNotSupported => "ES module mode is not supported in this mode.",
            Self::CacheHandlerNotSupported => "cacheHandlers option is not supported in this mode.",
            Self::ScopeIdNotSupported => "scopeId option is not supported in this mode.",

            Self::UnhandledCodePath => "Unhandled code path.",
            Self::ExtendPoint => "Extension point.",
        }
    }

    pub fn is_parse_error(&self) -> bool {
        (*self as u16) < (Self::VIfNoExpression as u16)
    }

    pub fn is_transform_error(&self) -> bool {
        let code = *self as u16;
        code >= (Self::VIfNoExpression as u16) && code < (Self::PrefixIdNotSupported as u16)
    }

    /// Returns true when this code is a recovery-level diagnostic (a warning)
    /// rather than a hard error. `ExtendPoint` is the code the parser uses for
    /// HTML tree-construction recovery notes (e.g. self-closing rewrites,
    /// fostered elements, auto-closed `<p>`). These describe spec-compliant
    /// repairs the parser already applied, so downstream consumers — notably
    /// the `vize_canon` virtual-TS codegen — must NOT treat them as a reason to
    /// abort and fall back to a stub component.
    #[must_use]
    pub fn is_recovery(&self) -> bool {
        matches!(self, Self::ExtendPoint)
    }
}

/// Result type for compiler operations
pub type CompilerResult<T> = Result<T, CompilerError>;

#[cfg(test)]
mod tests {
    use super::{CompilerError, ErrorCode};

    #[test]
    fn compiler_error_new() {
        let err = CompilerError::new(ErrorCode::EofInTag, None);
        assert_eq!(err.code, ErrorCode::EofInTag);
        assert_eq!(err.message, "EOF in tag.");
        assert!(err.loc.is_none());
    }

    #[test]
    fn compiler_error_with_message() {
        let err =
            CompilerError::with_message(ErrorCode::UnhandledCodePath, "custom error message", None);
        assert_eq!(err.code, ErrorCode::UnhandledCodePath);
        assert_eq!(err.message, "custom error message");
    }

    #[test]
    fn error_code_messages_not_empty() {
        let codes = [
            ErrorCode::AbruptClosingOfEmptyComment,
            ErrorCode::CdataInHtmlContent,
            ErrorCode::DuplicateAttribute,
            ErrorCode::EndTagWithAttributes,
            ErrorCode::EofInTag,
            ErrorCode::InvalidEndTag,
            ErrorCode::MissingEndTag,
            ErrorCode::MissingInterpolationEnd,
            ErrorCode::MissingDirectiveName,
            ErrorCode::MissingDirectiveModifier,
            ErrorCode::VIfNoExpression,
            ErrorCode::VForNoExpression,
            ErrorCode::VBindNoExpression,
            ErrorCode::VOnNoExpression,
            ErrorCode::VModelNoExpression,
            ErrorCode::VShowNoExpression,
            ErrorCode::PrefixIdNotSupported,
            ErrorCode::UnhandledCodePath,
            ErrorCode::ExtendPoint,
        ];
        for code in &codes {
            assert!(!code.message().is_empty(), "{:?} has empty message", code);
        }
    }

    #[test]
    fn is_recovery_only_for_extend_point() {
        assert!(ErrorCode::ExtendPoint.is_recovery());
        assert!(!ErrorCode::InvalidEndTag.is_recovery());
        assert!(!ErrorCode::UnexpectedSolidusInTag.is_recovery());
        assert!(!ErrorCode::DuplicateAttribute.is_recovery());
        assert!(!ErrorCode::UnhandledCodePath.is_recovery());
    }

    #[test]
    fn is_parse_error_true() {
        let parse_errors = [
            ErrorCode::AbruptClosingOfEmptyComment,
            ErrorCode::CdataInHtmlContent,
            ErrorCode::DuplicateAttribute,
            ErrorCode::EofInTag,
            ErrorCode::InvalidEndTag,
            ErrorCode::MissingEndTag,
            ErrorCode::MissingInterpolationEnd,
            ErrorCode::MissingDirectiveName,
            ErrorCode::MissingDirectiveModifier,
        ];
        for code in &parse_errors {
            assert!(code.is_parse_error(), "{:?} should be parse error", code);
        }
    }

    #[test]
    fn is_parse_error_false_for_transform() {
        assert!(!ErrorCode::VIfNoExpression.is_parse_error());
        assert!(!ErrorCode::VShowNoExpression.is_parse_error());
        assert!(!ErrorCode::PrefixIdNotSupported.is_parse_error());
    }

    #[test]
    fn is_transform_error_true() {
        let transform_errors = [
            ErrorCode::VIfNoExpression,
            ErrorCode::VIfSameKey,
            ErrorCode::VElseNoAdjacentIf,
            ErrorCode::VForNoExpression,
            ErrorCode::VBindNoExpression,
            ErrorCode::VOnNoExpression,
            ErrorCode::VModelNoExpression,
            ErrorCode::VShowNoExpression,
            ErrorCode::InvalidExpression,
        ];
        for code in &transform_errors {
            assert!(
                code.is_transform_error(),
                "{:?} should be transform error",
                code
            );
        }
    }

    #[test]
    fn is_transform_error_false() {
        // Parse errors should not be transform errors
        assert!(!ErrorCode::EofInTag.is_transform_error());
        assert!(!ErrorCode::MissingDirectiveModifier.is_transform_error());
        // Generic errors should not be transform errors
        assert!(!ErrorCode::PrefixIdNotSupported.is_transform_error());
    }

    #[test]
    fn boundary_error_codes() {
        // MissingDirectiveModifier (28) is the last parse error
        assert!(ErrorCode::MissingDirectiveModifier.is_parse_error());
        assert!(!ErrorCode::MissingDirectiveModifier.is_transform_error());

        // VIfNoExpression (29) is the first transform error
        assert!(!ErrorCode::VIfNoExpression.is_parse_error());
        assert!(ErrorCode::VIfNoExpression.is_transform_error());

        // InvalidExpression (49) is the last transform error
        assert!(ErrorCode::InvalidExpression.is_transform_error());
        assert!(!ErrorCode::InvalidExpression.is_parse_error());

        // PrefixIdNotSupported (50) is neither
        assert!(!ErrorCode::PrefixIdNotSupported.is_parse_error());
        assert!(!ErrorCode::PrefixIdNotSupported.is_transform_error());
    }

    #[test]
    fn mutual_exclusion() {
        let all_codes = [
            ErrorCode::AbruptClosingOfEmptyComment,
            ErrorCode::CdataInHtmlContent,
            ErrorCode::DuplicateAttribute,
            ErrorCode::EndTagWithAttributes,
            ErrorCode::EndTagWithTrailingSolidus,
            ErrorCode::EofBeforeTagName,
            ErrorCode::EofInCdata,
            ErrorCode::EofInComment,
            ErrorCode::EofInScriptHtmlCommentLikeText,
            ErrorCode::EofInTag,
            ErrorCode::IncorrectlyClosedComment,
            ErrorCode::IncorrectlyOpenedComment,
            ErrorCode::InvalidFirstCharacterOfTagName,
            ErrorCode::MissingAttributeValue,
            ErrorCode::MissingEndTagName,
            ErrorCode::MissingWhitespaceBetweenAttributes,
            ErrorCode::NestedComment,
            ErrorCode::UnexpectedCharacterInAttributeName,
            ErrorCode::UnexpectedCharacterInUnquotedAttributeValue,
            ErrorCode::UnexpectedEqualsSignBeforeAttributeName,
            ErrorCode::UnexpectedNullCharacter,
            ErrorCode::UnexpectedQuestionMarkInsteadOfTagName,
            ErrorCode::UnexpectedSolidusInTag,
            ErrorCode::InvalidEndTag,
            ErrorCode::MissingEndTag,
            ErrorCode::MissingInterpolationEnd,
            ErrorCode::MissingDynamicDirectiveArgumentEnd,
            ErrorCode::MissingDirectiveName,
            ErrorCode::MissingDirectiveModifier,
            ErrorCode::VIfNoExpression,
            ErrorCode::VIfSameKey,
            ErrorCode::VElseNoAdjacentIf,
            ErrorCode::VForNoExpression,
            ErrorCode::VForMalformedExpression,
            ErrorCode::VForTemplateKeyPlacement,
            ErrorCode::VBindNoExpression,
            ErrorCode::VBindSameNameShorthand,
            ErrorCode::VOnNoExpression,
            ErrorCode::VSlotUnexpectedDirectiveOnSlotOutlet,
            ErrorCode::VSlotMixedSlotUsage,
            ErrorCode::VSlotDuplicateSlotNames,
            ErrorCode::VSlotExtraneousDefaultSlotChildren,
            ErrorCode::VSlotMisplaced,
            ErrorCode::VModelNoExpression,
            ErrorCode::VModelMalformedExpression,
            ErrorCode::VModelOnScope,
            ErrorCode::VModelOnProps,
            ErrorCode::VModelArgOnElement,
            ErrorCode::VShowNoExpression,
            ErrorCode::InvalidExpression,
            ErrorCode::PrefixIdNotSupported,
            ErrorCode::ModuleModeNotSupported,
            ErrorCode::CacheHandlerNotSupported,
            ErrorCode::ScopeIdNotSupported,
            ErrorCode::UnhandledCodePath,
            ErrorCode::ExtendPoint,
        ];
        for code in &all_codes {
            assert!(
                !(code.is_parse_error() && code.is_transform_error()),
                "{:?} should not be both parse and transform error",
                code
            );
        }
    }
}