facet-styx 4.0.0

Facet integration for the Styx configuration language
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
//! Validation error types.

use ariadne::{Color, Config, Label, Report, ReportKind, Source};
use styx_parse::Span;

/// Get ariadne config, respecting NO_COLOR env var.
fn ariadne_config() -> Config {
    let no_color = std::env::var("NO_COLOR").is_ok();
    if no_color {
        Config::default().with_color(false)
    } else {
        Config::default()
    }
}

/// Result of validating a document against a schema.
#[derive(Debug, Clone)]
pub struct ValidationResult {
    /// Validation errors (must be empty for validation to pass).
    pub errors: Vec<ValidationError>,
    /// Validation warnings (non-fatal issues).
    pub warnings: Vec<ValidationWarning>,
}

impl ValidationResult {
    /// Create an empty (passing) result.
    pub fn ok() -> Self {
        Self {
            errors: Vec::new(),
            warnings: Vec::new(),
        }
    }

    /// Check if validation passed (no errors).
    pub fn is_valid(&self) -> bool {
        self.errors.is_empty()
    }

    /// Add an error.
    pub fn error(&mut self, error: ValidationError) {
        self.errors.push(error);
    }

    /// Add a warning.
    pub fn warning(&mut self, warning: ValidationWarning) {
        self.warnings.push(warning);
    }

    /// Merge another result into this one.
    pub fn merge(&mut self, other: ValidationResult) {
        self.errors.extend(other.errors);
        self.warnings.extend(other.warnings);
    }

    /// Render all errors with ariadne.
    pub fn render(&self, filename: &str, source: &str) -> String {
        let mut output = Vec::new();
        self.write_report(filename, source, &mut output);
        String::from_utf8(output).unwrap_or_else(|_| {
            self.errors
                .iter()
                .map(|e| e.to_string())
                .collect::<Vec<_>>()
                .join("\n")
        })
    }

    /// Write all error reports to a writer.
    pub fn write_report<W: std::io::Write>(&self, filename: &str, source: &str, mut writer: W) {
        for error in &self.errors {
            error.write_report(filename, source, &mut writer);
        }
        for warning in &self.warnings {
            warning.write_report(filename, source, &mut writer);
        }
    }
}

/// A validation error.
#[derive(Debug, Clone)]
pub struct ValidationError {
    /// Path to the error location (e.g., "server.tls.cert").
    pub path: String,
    /// Source span in the document.
    pub span: Option<Span>,
    /// Error kind.
    pub kind: ValidationErrorKind,
    /// Human-readable message.
    pub message: String,
}

impl ValidationError {
    /// Create a new validation error.
    pub fn new(
        path: impl Into<String>,
        kind: ValidationErrorKind,
        message: impl Into<String>,
    ) -> Self {
        Self {
            path: path.into(),
            span: None,
            kind,
            message: message.into(),
        }
    }

    /// Set the span.
    pub fn with_span(mut self, span: Option<Span>) -> Self {
        self.span = span;
        self
    }

    /// Get quickfix data for LSP code actions.
    /// Returns JSON data that can be used to offer quick fixes.
    pub fn quickfix_data(&self) -> Option<serde_json::Value> {
        match &self.kind {
            ValidationErrorKind::UnknownField {
                field, suggestion, ..
            } => suggestion.as_ref().map(|suggestion| {
                serde_json::json!({
                    "type": "rename_field",
                    "from": field,
                    "to": suggestion
                })
            }),
            _ => None,
        }
    }

    /// Get a rich diagnostic message suitable for LSP.
    pub fn diagnostic_message(&self) -> String {
        match &self.kind {
            ValidationErrorKind::UnknownField {
                field,
                valid_fields,
                suggestion,
            } => {
                let mut msg = format!("unknown field '{}'", field);
                if let Some(suggestion) = suggestion {
                    msg.push_str(&format!(" — did you mean '{}'?", suggestion));
                }
                if !valid_fields.is_empty() && valid_fields.len() <= 10 {
                    msg.push_str(&format!("\nvalid: {}", valid_fields.join(", ")));
                }
                msg
            }
            ValidationErrorKind::MissingField { field } => {
                format!("missing required field '{}'", field)
            }
            ValidationErrorKind::TypeMismatch { expected, got } => {
                format!("type mismatch: expected {}, got {}", expected, got)
            }
            _ => self.message.clone(),
        }
    }

    /// Render this error with ariadne.
    pub fn render(&self, filename: &str, source: &str) -> String {
        let mut output = Vec::new();
        self.write_report(filename, source, &mut output);
        String::from_utf8(output).unwrap_or_else(|_| format!("{}", self))
    }

    /// Write the error report to a writer.
    pub fn write_report<W: std::io::Write>(&self, filename: &str, source: &str, writer: W) {
        let report = self.build_report(filename);
        let _ = report
            .with_config(ariadne_config())
            .finish()
            .write((filename, Source::from(source)), writer);
    }

    /// Build an ariadne report for this error.
    fn build_report<'a>(
        &self,
        filename: &'a str,
    ) -> ariadne::ReportBuilder<'static, (&'a str, std::ops::Range<usize>)> {
        let range = self
            .span
            .map(|s| s.start as usize..s.end as usize)
            .unwrap_or(0..1);

        let path_info = if self.path.is_empty() {
            String::new()
        } else {
            format!(" at '{}'", self.path)
        };

        match &self.kind {
            ValidationErrorKind::MissingField { field } => {
                Report::build(ReportKind::Error, (filename, range.clone()))
                    .with_message(format!("missing required field '{}'", field))
                    .with_label(
                        Label::new((filename, range))
                            .with_message(format!("add field '{}' here", field))
                            .with_color(Color::Red),
                    )
                    .with_help(format!("{} <value>", field))
            }

            ValidationErrorKind::UnknownField {
                field,
                valid_fields,
                suggestion,
            } => {
                let mut builder = Report::build(ReportKind::Error, (filename, range.clone()))
                    .with_message(format!("unknown field '{}'", field))
                    .with_label(
                        Label::new((filename, range.clone()))
                            .with_message("not defined in schema")
                            .with_color(Color::Red),
                    );

                if let Some(suggestion) = suggestion {
                    builder = builder.with_help(format!("did you mean '{}'?", suggestion));
                }

                if !valid_fields.is_empty() {
                    builder =
                        builder.with_note(format!("valid fields: {}", valid_fields.join(", ")));
                }

                builder
            }

            ValidationErrorKind::TypeMismatch { expected, got } => {
                Report::build(ReportKind::Error, (filename, range.clone()))
                    .with_message(format!("type mismatch{}", path_info))
                    .with_label(
                        Label::new((filename, range))
                            .with_message(format!("expected {}, got {}", expected, got))
                            .with_color(Color::Red),
                    )
            }

            ValidationErrorKind::InvalidValue { reason } => {
                Report::build(ReportKind::Error, (filename, range.clone()))
                    .with_message(format!("invalid value{}", path_info))
                    .with_label(
                        Label::new((filename, range))
                            .with_message(reason)
                            .with_color(Color::Red),
                    )
            }

            ValidationErrorKind::UnknownType { name } => {
                Report::build(ReportKind::Error, (filename, range.clone()))
                    .with_message(format!("unknown type '{}'", name))
                    .with_label(
                        Label::new((filename, range))
                            .with_message("type not defined in schema")
                            .with_color(Color::Red),
                    )
            }

            ValidationErrorKind::InvalidVariant { expected, got } => {
                let expected_list = expected.join(", ");
                Report::build(ReportKind::Error, (filename, range.clone()))
                    .with_message(format!("invalid enum variant '@{}'", got))
                    .with_label(
                        Label::new((filename, range))
                            .with_message(format!("expected one of: {}", expected_list))
                            .with_color(Color::Red),
                    )
            }

            ValidationErrorKind::UnionMismatch { tried } => {
                let tried_list = tried.join(", ");
                Report::build(ReportKind::Error, (filename, range.clone()))
                    .with_message(format!(
                        "value doesn't match any union variant{}",
                        path_info
                    ))
                    .with_label(
                        Label::new((filename, range))
                            .with_message(format!("tried: {}", tried_list))
                            .with_color(Color::Red),
                    )
            }

            ValidationErrorKind::ExpectedObject => {
                Report::build(ReportKind::Error, (filename, range.clone()))
                    .with_message(format!("expected object{}", path_info))
                    .with_label(
                        Label::new((filename, range))
                            .with_message("expected { ... }")
                            .with_color(Color::Red),
                    )
            }

            ValidationErrorKind::ExpectedSequence => {
                Report::build(ReportKind::Error, (filename, range.clone()))
                    .with_message(format!("expected sequence{}", path_info))
                    .with_label(
                        Label::new((filename, range))
                            .with_message("expected ( ... )")
                            .with_color(Color::Red),
                    )
            }

            ValidationErrorKind::ExpectedScalar => {
                Report::build(ReportKind::Error, (filename, range.clone()))
                    .with_message(format!("expected scalar value{}", path_info))
                    .with_label(
                        Label::new((filename, range))
                            .with_message("expected a simple value")
                            .with_color(Color::Red),
                    )
            }

            ValidationErrorKind::ExpectedTagged => {
                Report::build(ReportKind::Error, (filename, range.clone()))
                    .with_message(format!("expected tagged value{}", path_info))
                    .with_label(
                        Label::new((filename, range))
                            .with_message("expected @tag or @tag{...}")
                            .with_color(Color::Red),
                    )
            }

            ValidationErrorKind::WrongTag { expected, got } => {
                Report::build(ReportKind::Error, (filename, range.clone()))
                    .with_message(format!("wrong tag{}", path_info))
                    .with_label(
                        Label::new((filename, range))
                            .with_message(format!("expected @{}, got @{}", expected, got))
                            .with_color(Color::Red),
                    )
            }

            ValidationErrorKind::SchemaError { reason } => {
                Report::build(ReportKind::Error, (filename, range.clone()))
                    .with_message("schema error")
                    .with_label(
                        Label::new((filename, range))
                            .with_message(reason)
                            .with_color(Color::Red),
                    )
            }
        }
    }
}

impl std::fmt::Display for ValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.path.is_empty() {
            write!(f, "{}", self.message)
        } else {
            write!(f, "{}: {}", self.path, self.message)
        }
    }
}

impl std::error::Error for ValidationError {}

/// Kinds of validation errors.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidationErrorKind {
    /// Missing required field in object.
    MissingField { field: String },
    /// Unknown field in object (when additional fields not allowed).
    UnknownField {
        field: String,
        valid_fields: Vec<String>,
        suggestion: Option<String>,
    },
    /// Type mismatch.
    TypeMismatch { expected: String, got: String },
    /// Invalid value for type.
    InvalidValue { reason: String },
    /// Unknown type reference in schema.
    UnknownType { name: String },
    /// Invalid enum variant.
    InvalidVariant { expected: Vec<String>, got: String },
    /// Union match failed (value didn't match any variant).
    UnionMismatch { tried: Vec<String> },
    /// Expected object, got something else.
    ExpectedObject,
    /// Expected sequence, got something else.
    ExpectedSequence,
    /// Expected scalar, got something else.
    ExpectedScalar,
    /// Expected tagged value.
    ExpectedTagged,
    /// Wrong tag name.
    WrongTag { expected: String, got: String },
    /// Schema error (invalid schema definition).
    SchemaError { reason: String },
}

/// A validation warning (non-fatal).
#[derive(Debug, Clone)]
pub struct ValidationWarning {
    /// Path to the warning location.
    pub path: String,
    /// Source span in the document.
    pub span: Option<Span>,
    /// Warning kind.
    pub kind: ValidationWarningKind,
    /// Human-readable message.
    pub message: String,
}

impl ValidationWarning {
    /// Create a new validation warning.
    pub fn new(
        path: impl Into<String>,
        kind: ValidationWarningKind,
        message: impl Into<String>,
    ) -> Self {
        Self {
            path: path.into(),
            span: None,
            kind,
            message: message.into(),
        }
    }

    /// Set the span.
    pub fn with_span(mut self, span: Option<Span>) -> Self {
        self.span = span;
        self
    }

    /// Write the warning report to a writer.
    pub fn write_report<W: std::io::Write>(&self, filename: &str, source: &str, writer: W) {
        let range = self
            .span
            .map(|s| s.start as usize..s.end as usize)
            .unwrap_or(0..1);

        let report = match &self.kind {
            ValidationWarningKind::Deprecated { reason } => {
                Report::build(ReportKind::Warning, (filename, range.clone()))
                    .with_message("deprecated")
                    .with_label(
                        Label::new((filename, range))
                            .with_message(reason)
                            .with_color(Color::Yellow),
                    )
            }
            ValidationWarningKind::IgnoredField { field } => {
                Report::build(ReportKind::Warning, (filename, range.clone()))
                    .with_message(format!("field '{}' will be ignored", field))
                    .with_label(
                        Label::new((filename, range))
                            .with_message("ignored")
                            .with_color(Color::Yellow),
                    )
            }
        };

        let _ = report
            .with_config(ariadne_config())
            .finish()
            .write((filename, Source::from(source)), writer);
    }
}

/// Kinds of validation warnings.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidationWarningKind {
    /// Deprecated field or type.
    Deprecated { reason: String },
    /// Field will be ignored.
    IgnoredField { field: String },
}

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

    #[test]
    fn test_missing_field_diagnostic() {
        let source = "name Alice";
        let error = ValidationError::new(
            "",
            ValidationErrorKind::MissingField {
                field: "age".into(),
            },
            "missing required field 'age'",
        )
        .with_span(Some(Span { start: 0, end: 10 }));

        assert_snapshot_stripped!(error.render("test.styx", source));
    }

    #[test]
    fn test_unknown_field_diagnostic() {
        let source = "name Alice\nunknwon_field value";
        let error = ValidationError::new(
            "",
            ValidationErrorKind::UnknownField {
                field: "unknwon_field".into(),
                valid_fields: vec!["name".into(), "age".into(), "email".into()],
                suggestion: Some("unknown_field".into()),
            },
            "unknown field 'unknwon_field'",
        )
        .with_span(Some(Span { start: 11, end: 24 }));

        assert_snapshot_stripped!(error.render("test.styx", source));
    }

    #[test]
    fn test_type_mismatch_diagnostic() {
        let source = "age notanumber";
        let error = ValidationError::new(
            "age",
            ValidationErrorKind::TypeMismatch {
                expected: "int".into(),
                got: "string".into(),
            },
            "expected int, got string",
        )
        .with_span(Some(Span { start: 4, end: 14 }));

        assert_snapshot_stripped!(error.render("test.styx", source));
    }

    #[test]
    fn test_invalid_variant_diagnostic() {
        let source = "status @unknown";
        let error = ValidationError::new(
            "status",
            ValidationErrorKind::InvalidVariant {
                expected: vec!["active".into(), "inactive".into(), "pending".into()],
                got: "unknown".into(),
            },
            "invalid enum variant",
        )
        .with_span(Some(Span { start: 7, end: 15 }));

        assert_snapshot_stripped!(error.render("test.styx", source));
    }

    #[test]
    fn test_expected_object_diagnostic() {
        let source = "config simple_value";
        let error = ValidationError::new(
            "config",
            ValidationErrorKind::ExpectedObject,
            "expected object",
        )
        .with_span(Some(Span { start: 7, end: 19 }));

        assert_snapshot_stripped!(error.render("test.styx", source));
    }

    #[test]
    fn test_warning_deprecated_diagnostic() {
        let source = "old_setting value";
        let warning = ValidationWarning::new(
            "old_setting",
            ValidationWarningKind::Deprecated {
                reason: "use 'new_setting' instead".into(),
            },
            "deprecated field",
        )
        .with_span(Some(Span { start: 0, end: 11 }));

        let mut output = Vec::new();
        warning.write_report("test.styx", source, &mut output);
        assert_snapshot_stripped!(String::from_utf8(output).unwrap());
    }

    #[test]
    fn test_validation_result_multiple_errors() {
        let source = "name 123\nunknown_field value";
        let mut result = ValidationResult::ok();

        result.error(
            ValidationError::new(
                "name",
                ValidationErrorKind::TypeMismatch {
                    expected: "string".into(),
                    got: "int".into(),
                },
                "expected string, got int",
            )
            .with_span(Some(Span { start: 5, end: 8 })),
        );

        result.error(
            ValidationError::new(
                "",
                ValidationErrorKind::UnknownField {
                    field: "unknown_field".into(),
                    valid_fields: vec!["name".into(), "age".into()],
                    suggestion: None,
                },
                "unknown field",
            )
            .with_span(Some(Span { start: 9, end: 22 })),
        );

        assert_snapshot_stripped!(result.render("test.styx", source));
    }
}