variable-core 0.1.4

Parser, lexer, AST, and validation for the Variable feature flag DSL
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
#![allow(unused_assignments)]

use std::collections::{HashMap, HashSet};

use miette::{Diagnostic, SourceSpan};
use thiserror::Error;

use crate::ast::{VarFile, VarType};
use crate::lexer::Span;

#[derive(Error, Debug, Diagnostic)]
pub enum ValidationError {
    #[error("duplicate feature name: `{name}`")]
    DuplicateFeature {
        name: String,
        #[label("first defined here")]
        first: SourceSpan,
        #[label("duplicate defined here")]
        duplicate: SourceSpan,
    },

    #[error("duplicate feature id `{id}`")]
    DuplicateFeatureId {
        id: u32,
        #[label("first defined here")]
        first: SourceSpan,
        #[label("duplicate defined here")]
        duplicate: SourceSpan,
    },

    #[error("duplicate variable name `{name}` in feature `{feature}`")]
    DuplicateVariable {
        feature: String,
        name: String,
        #[label("first defined here")]
        first: SourceSpan,
        #[label("duplicate defined here")]
        duplicate: SourceSpan,
    },

    #[error("duplicate variable id `{id}` in feature `{feature}`")]
    DuplicateVariableId {
        feature: String,
        id: u32,
        #[label("first defined here")]
        first: SourceSpan,
        #[label("duplicate defined here")]
        duplicate: SourceSpan,
    },

    #[error("duplicate struct name: `{name}`")]
    DuplicateStruct {
        name: String,
        #[label("first defined here")]
        first: SourceSpan,
        #[label("duplicate defined here")]
        duplicate: SourceSpan,
    },

    #[error("duplicate struct id `{id}`")]
    DuplicateStructId {
        id: u32,
        #[label("first defined here")]
        first: SourceSpan,
        #[label("duplicate defined here")]
        duplicate: SourceSpan,
    },

    #[error("duplicate field name `{name}` in struct `{struct_name}`")]
    DuplicateField {
        struct_name: String,
        name: String,
        #[label("first defined here")]
        first: SourceSpan,
        #[label("duplicate defined here")]
        duplicate: SourceSpan,
    },

    #[error("duplicate field id `{id}` in struct `{struct_name}`")]
    DuplicateFieldId {
        struct_name: String,
        id: u32,
        #[label("first defined here")]
        first: SourceSpan,
        #[label("duplicate defined here")]
        duplicate: SourceSpan,
    },

    #[error("unknown struct type `{type_name}` for variable `{variable}` in feature `{feature}`")]
    UnknownStructType {
        feature: String,
        variable: String,
        type_name: String,
        #[label("used here")]
        span: SourceSpan,
    },

    #[error("unknown field `{field}` in struct literal for type `{struct_name}`")]
    UnknownStructField {
        struct_name: String,
        field: String,
        #[label("used here")]
        span: SourceSpan,
    },
}

fn span_to_source_span(span: &Span) -> SourceSpan {
    SourceSpan::from(span.offset)
}

pub fn validate(var_file: &VarFile) -> Result<(), Vec<ValidationError>> {
    let mut errors = Vec::new();

    // Collect known struct names for type reference validation
    let mut struct_names_set: HashSet<&str> = HashSet::new();

    // Check for duplicate struct names and IDs
    let mut struct_names: HashMap<&str, &Span> = HashMap::new();
    let mut struct_ids: HashMap<u32, &Span> = HashMap::new();
    for struct_def in &var_file.structs {
        struct_names_set.insert(&struct_def.name);

        if let Some(first_span) = struct_names.get(struct_def.name.as_str()) {
            errors.push(ValidationError::DuplicateStruct {
                name: struct_def.name.clone(),
                first: span_to_source_span(first_span),
                duplicate: span_to_source_span(&struct_def.span),
            });
        } else {
            struct_names.insert(&struct_def.name, &struct_def.span);
        }

        if let Some(first_span) = struct_ids.get(&struct_def.id) {
            errors.push(ValidationError::DuplicateStructId {
                id: struct_def.id,
                first: span_to_source_span(first_span),
                duplicate: span_to_source_span(&struct_def.span),
            });
        } else {
            struct_ids.insert(struct_def.id, &struct_def.span);
        }

        // Check for duplicate field names and IDs within struct
        let mut field_names: HashMap<&str, &Span> = HashMap::new();
        let mut field_ids: HashMap<u32, &Span> = HashMap::new();
        for field in &struct_def.fields {
            if let Some(first_span) = field_names.get(field.name.as_str()) {
                errors.push(ValidationError::DuplicateField {
                    struct_name: struct_def.name.clone(),
                    name: field.name.clone(),
                    first: span_to_source_span(first_span),
                    duplicate: span_to_source_span(&field.span),
                });
            } else {
                field_names.insert(&field.name, &field.span);
            }

            if let Some(first_span) = field_ids.get(&field.id) {
                errors.push(ValidationError::DuplicateFieldId {
                    struct_name: struct_def.name.clone(),
                    id: field.id,
                    first: span_to_source_span(first_span),
                    duplicate: span_to_source_span(&field.span),
                });
            } else {
                field_ids.insert(field.id, &field.span);
            }
        }
    }

    // Build a map of struct field names for literal validation
    let struct_field_names: HashMap<&str, HashSet<&str>> = var_file
        .structs
        .iter()
        .map(|s| {
            let fields: HashSet<&str> = s.fields.iter().map(|f| f.name.as_str()).collect();
            (s.name.as_str(), fields)
        })
        .collect();

    // Check for duplicate feature names and IDs
    let mut feature_names: HashMap<&str, &Span> = HashMap::new();
    let mut feature_ids: HashMap<u32, &Span> = HashMap::new();
    for feature in &var_file.features {
        if let Some(first_span) = feature_names.get(feature.name.as_str()) {
            errors.push(ValidationError::DuplicateFeature {
                name: feature.name.clone(),
                first: span_to_source_span(first_span),
                duplicate: span_to_source_span(&feature.span),
            });
        } else {
            feature_names.insert(&feature.name, &feature.span);
        }

        if let Some(first_span) = feature_ids.get(&feature.id) {
            errors.push(ValidationError::DuplicateFeatureId {
                id: feature.id,
                first: span_to_source_span(first_span),
                duplicate: span_to_source_span(&feature.span),
            });
        } else {
            feature_ids.insert(feature.id, &feature.span);
        }
    }

    // Check for duplicate variable names and IDs within each feature,
    // and validate struct type references
    for feature in &var_file.features {
        let mut var_names: HashMap<&str, &Span> = HashMap::new();
        let mut var_ids: HashMap<u32, &Span> = HashMap::new();
        for variable in &feature.variables {
            if let Some(first_span) = var_names.get(variable.name.as_str()) {
                errors.push(ValidationError::DuplicateVariable {
                    feature: feature.name.clone(),
                    name: variable.name.clone(),
                    first: span_to_source_span(first_span),
                    duplicate: span_to_source_span(&variable.span),
                });
            } else {
                var_names.insert(&variable.name, &variable.span);
            }

            if let Some(first_span) = var_ids.get(&variable.id) {
                errors.push(ValidationError::DuplicateVariableId {
                    feature: feature.name.clone(),
                    id: variable.id,
                    first: span_to_source_span(first_span),
                    duplicate: span_to_source_span(&variable.span),
                });
            } else {
                var_ids.insert(variable.id, &variable.span);
            }

            // Validate struct type references resolve to a defined struct
            if let VarType::Struct(ref struct_name) = variable.var_type {
                if !struct_names_set.contains(struct_name.as_str()) {
                    errors.push(ValidationError::UnknownStructType {
                        feature: feature.name.clone(),
                        variable: variable.name.clone(),
                        type_name: struct_name.clone(),
                        span: span_to_source_span(&variable.span),
                    });
                }

                // Validate struct literal fields exist in the struct definition
                if let crate::ast::Value::Struct { fields, .. } = &variable.default {
                    if let Some(valid_fields) = struct_field_names.get(struct_name.as_str()) {
                        for field_name in fields.keys() {
                            if !valid_fields.contains(field_name.as_str()) {
                                errors.push(ValidationError::UnknownStructField {
                                    struct_name: struct_name.clone(),
                                    field: field_name.clone(),
                                    span: span_to_source_span(&variable.span),
                                });
                            }
                        }
                    }
                }
            }
        }
    }

    if errors.is_empty() {
        Ok(())
    } else {
        Err(errors)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lexer::lex;
    use crate::parser::parse;

    fn parse_and_validate(input: &str) -> Result<VarFile, Vec<ValidationError>> {
        let tokens = lex(input).expect("lex failed");
        let var_file = parse(tokens).expect("parse failed");
        validate(&var_file)?;
        Ok(var_file)
    }

    #[test]
    fn valid_file_passes() {
        let input = r#"1: Feature Checkout = {
    1: enabled Boolean = true
    2: max_items Integer = 50
}

2: Feature Search = {
    1: query String = "default"
}"#;
        assert!(parse_and_validate(input).is_ok());
    }

    #[test]
    fn duplicate_feature_name_error() {
        let input = r#"1: Feature Checkout = {
    1: enabled Boolean = true
}

2: Feature Checkout = {
    1: max_items Integer = 50
}"#;
        let err = parse_and_validate(input).unwrap_err();
        assert_eq!(err.len(), 1);
        match &err[0] {
            ValidationError::DuplicateFeature { name, .. } => {
                assert_eq!(name, "Checkout");
            }
            _ => panic!("expected DuplicateFeature error"),
        }
    }

    #[test]
    fn duplicate_variable_name_error() {
        let input = r#"1: Feature Checkout = {
    1: enabled Boolean = true
    2: enabled Boolean = false
}"#;
        let err = parse_and_validate(input).unwrap_err();
        assert_eq!(err.len(), 1);
        match &err[0] {
            ValidationError::DuplicateVariable { feature, name, .. } => {
                assert_eq!(feature, "Checkout");
                assert_eq!(name, "enabled");
            }
            _ => panic!("expected DuplicateVariable error"),
        }
    }

    #[test]
    fn error_has_correct_line_info() {
        let input = r#"1: Feature Checkout = {
    1: enabled Boolean = true
}

2: Feature Checkout = {
    1: max_items Integer = 50
}"#;
        let err = parse_and_validate(input).unwrap_err();
        match &err[0] {
            ValidationError::DuplicateFeature {
                first, duplicate, ..
            } => {
                // First "Feature" is at offset 0
                assert_eq!(first.offset(), 0);
                // Duplicate "Feature" is on line 5
                assert!(duplicate.offset() > 0);
            }
            _ => panic!("expected DuplicateFeature error"),
        }
    }

    #[test]
    fn duplicate_feature_id_error() {
        let input = r#"1: Feature Checkout = {
    1: enabled Boolean = true
}

1: Feature Search = {
    1: query String = "default"
}"#;
        let err = parse_and_validate(input).unwrap_err();
        assert_eq!(err.len(), 1);
        match &err[0] {
            ValidationError::DuplicateFeatureId { id, .. } => {
                assert_eq!(*id, 1);
            }
            _ => panic!("expected DuplicateFeatureId error"),
        }
    }

    #[test]
    fn duplicate_variable_id_error() {
        let input = r#"1: Feature Checkout = {
    1: enabled Boolean = true
    1: max_items Integer = 50
}"#;
        let err = parse_and_validate(input).unwrap_err();
        assert_eq!(err.len(), 1);
        match &err[0] {
            ValidationError::DuplicateVariableId { feature, id, .. } => {
                assert_eq!(feature, "Checkout");
                assert_eq!(*id, 1);
            }
            _ => panic!("expected DuplicateVariableId error"),
        }
    }

    #[test]
    fn valid_file_with_struct_passes() {
        let input = r#"1: Struct Theme = {
    1: dark_mode Boolean = false
    2: font_size Integer = 14
}

1: Feature Dashboard = {
    1: enabled Boolean = true
    2: theme Theme = Theme {}
}"#;
        assert!(parse_and_validate(input).is_ok());
    }

    #[test]
    fn duplicate_struct_name_error() {
        let input = r#"1: Struct Theme = {
    1: dark_mode Boolean = false
}

2: Struct Theme = {
    1: font_size Integer = 14
}"#;
        let err = parse_and_validate(input).unwrap_err();
        assert_eq!(err.len(), 1);
        match &err[0] {
            ValidationError::DuplicateStruct { name, .. } => {
                assert_eq!(name, "Theme");
            }
            _ => panic!("expected DuplicateStruct error"),
        }
    }

    #[test]
    fn duplicate_struct_id_error() {
        let input = r#"1: Struct Theme = {
    1: dark_mode Boolean = false
}

1: Struct Config = {
    1: retries Integer = 3
}"#;
        let err = parse_and_validate(input).unwrap_err();
        assert_eq!(err.len(), 1);
        match &err[0] {
            ValidationError::DuplicateStructId { id, .. } => {
                assert_eq!(*id, 1);
            }
            _ => panic!("expected DuplicateStructId error"),
        }
    }

    #[test]
    fn duplicate_field_name_error() {
        let input = r#"1: Struct Theme = {
    1: dark_mode Boolean = false
    2: dark_mode Boolean = true
}"#;
        let err = parse_and_validate(input).unwrap_err();
        assert_eq!(err.len(), 1);
        match &err[0] {
            ValidationError::DuplicateField {
                struct_name, name, ..
            } => {
                assert_eq!(struct_name, "Theme");
                assert_eq!(name, "dark_mode");
            }
            _ => panic!("expected DuplicateField error"),
        }
    }

    #[test]
    fn duplicate_field_id_error() {
        let input = r#"1: Struct Theme = {
    1: dark_mode Boolean = false
    1: font_size Integer = 14
}"#;
        let err = parse_and_validate(input).unwrap_err();
        assert_eq!(err.len(), 1);
        match &err[0] {
            ValidationError::DuplicateFieldId {
                struct_name, id, ..
            } => {
                assert_eq!(struct_name, "Theme");
                assert_eq!(*id, 1);
            }
            _ => panic!("expected DuplicateFieldId error"),
        }
    }

    #[test]
    fn unknown_struct_type_error() {
        let input = r#"1: Feature Dashboard = {
    1: theme UnknownType = UnknownType {}
}"#;
        let err = parse_and_validate(input).unwrap_err();
        assert_eq!(err.len(), 1);
        match &err[0] {
            ValidationError::UnknownStructType {
                feature,
                variable,
                type_name,
                ..
            } => {
                assert_eq!(feature, "Dashboard");
                assert_eq!(variable, "theme");
                assert_eq!(type_name, "UnknownType");
            }
            _ => panic!("expected UnknownStructType error"),
        }
    }

    #[test]
    fn unknown_struct_field_in_literal_error() {
        let input = r#"1: Struct Theme = {
    1: dark_mode Boolean = false
}

1: Feature Dashboard = {
    1: theme Theme = Theme { nonexistent = true }
}"#;
        let err = parse_and_validate(input).unwrap_err();
        assert_eq!(err.len(), 1);
        match &err[0] {
            ValidationError::UnknownStructField {
                struct_name, field, ..
            } => {
                assert_eq!(struct_name, "Theme");
                assert_eq!(field, "nonexistent");
            }
            _ => panic!("expected UnknownStructField error"),
        }
    }
}