nightjar-lang 0.1.0

A declarative, prefix-notation DSL for formal verification of structured data.
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
// Copyright 2026 Wayne Hong (h-alice) <contact@halice.art>
// Nightjar Language Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

//! Implementations of the ForAll and Exists quantifiers.
//!
//! Including the scalar-fallback rule and the vacuously-true empty-list
//! (trivially true) semantics.

use crate::context::entity::Entity;
use crate::context::verifier::apply_verifier;
use crate::error::{type_error, NightjarLanguageError, Span};
use crate::language::grammar::{QuantifierOp, UnaryCheckOp, VerifierOp};

/// A resolved predicate — the bound value in a partial verifier has already
/// been reduced to an Entity.
#[derive(Debug, Clone)]
pub enum EvalPredicate {
    /// Partial binary verifier such as `(GT 0)` with its bound argument
    /// already reduced to an [`Entity`].
    PartialVerifier {
        /// Verifier operator (e.g. `GT`, `EQ`).
        op: VerifierOp,
        /// Reduced bound value applied to each element.
        bound: Entity,
    },
    /// Unary check predicate such as `NonEmpty`.
    UnaryCheck(UnaryCheckOp),
}

/// Evaluate a quantifier (`ForAll` / `Exists`) over its operand.
///
/// - Operand must be `List`, `Map` is a `TypeError` (use `GetKeys` / `GetValues`).
/// - Scalar fallback: when the operand is a scalar or `Null`, the quantifier
///   reduces to a single predicate application.
/// - Empty list: `ForAll` is vacuously `true`, `Exists` is `false`.
pub fn apply_quantifier(
    op: QuantifierOp,
    predicate: &EvalPredicate,
    operand: &Entity,
    epsilon: f64,
    span: Span,
) -> Result<bool, NightjarLanguageError> {
    let elements: &[Entity] = match operand {
        Entity::List(v) => v,
        Entity::Map(_) => {
            return Err(type_error(
                span,
                "quantifier requires List operand; use GetKeys/GetValues for Maps",
            ));
        }
        // Scalar fallback: single predicate application.
        _scalar => {
            return apply_predicate(predicate, operand, epsilon, span);
        }
    };

    match op {
        QuantifierOp::ForAll => {
            for elem in elements {
                if !apply_predicate(predicate, elem, epsilon, span)? {
                    return Ok(false);
                }
            }
            Ok(true)
        }
        QuantifierOp::Exists => {
            for elem in elements {
                if apply_predicate(predicate, elem, epsilon, span)? {
                    return Ok(true);
                }
            }
            Ok(false)
        }
    }
}

/// Apply a unary boolean predicate to a single Entity.
///
/// For a partial verifier, the element fills the 1st operand and the bound
/// value fills the 2nd operand, i.e. `(ForAll (GT 2) [1,2,3])` means
/// `∀x. x > 2`.
pub fn apply_predicate(
    pred: &EvalPredicate,
    element: &Entity,
    epsilon: f64,
    span: Span,
) -> Result<bool, NightjarLanguageError> {
    match pred {
        EvalPredicate::PartialVerifier { op, bound } => {
            apply_verifier(*op, element, bound, epsilon, span)
        }
        EvalPredicate::UnaryCheck(UnaryCheckOp::NonEmpty) => Ok(element.is_non_empty()),
    }
}

/// Iterate a quantifier over `operand`, invoking `eval_on_element` once per
/// element with the element bound in scope.
///
/// Shares the list/scalar/map dispatch with [`apply_quantifier`].
///
/// Used for `Predicate::Full` where the predicate body is a general `BoolExpr`
/// re-evaluated per element.
pub fn apply_quantifier_full<F>(
    op: QuantifierOp,
    operand: &Entity,
    span: Span,
    mut eval_on_element: F, // A lambda that evaluates the predicate body with the element bound in scope.
) -> Result<bool, NightjarLanguageError>
where
    F: FnMut(&Entity) -> Result<bool, NightjarLanguageError>,
{
    let elements: &[Entity] = match operand {
        Entity::List(v) => v,
        Entity::Map(_) => {
            return Err(type_error(
                span,
                "quantifier requires List operand; use GetKeys/GetValues for Maps",
            ));
        }
        // Scalar fallback: single predicate application.
        scalar => return eval_on_element(scalar),
    };

    match op {
        QuantifierOp::ForAll => {
            for elem in elements {
                if !eval_on_element(elem)? {
                    return Ok(false);
                }
            }
            Ok(true)
        }
        QuantifierOp::Exists => {
            for elem in elements {
                if eval_on_element(elem)? {
                    return Ok(true);
                }
            }
            Ok(false)
        }
    }
}

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

    const EPS: f64 = 1e-10;

    fn gt(bound: i64) -> EvalPredicate {
        EvalPredicate::PartialVerifier {
            op: VerifierOp::GT,
            bound: Entity::Int(bound),
        }
    }

    fn eq_str(bound: &str) -> EvalPredicate {
        EvalPredicate::PartialVerifier {
            op: VerifierOp::EQ,
            bound: Entity::String(bound.to_string()),
        }
    }

    fn non_empty() -> EvalPredicate {
        EvalPredicate::UnaryCheck(UnaryCheckOp::NonEmpty)
    }

    fn list_of_ints(xs: &[i64]) -> Entity {
        Entity::List(xs.iter().copied().map(Entity::Int).collect())
    }

    // ── ForAll ───────────────────────────────────────────────

    #[test]
    fn forall_all_greater_than_zero() {
        let r = apply_quantifier(
            QuantifierOp::ForAll,
            &gt(0),
            &list_of_ints(&[1, 2, 3]),
            EPS,
            Span::new(0, 0),
        )
        .unwrap();
        assert!(r);
    }

    #[test]
    fn forall_fails_when_zero_included() {
        let r = apply_quantifier(
            QuantifierOp::ForAll,
            &gt(0),
            &list_of_ints(&[0, 1, 2]),
            EPS,
            Span::new(0, 0),
        )
        .unwrap();
        assert!(!r);
    }

    #[test]
    fn forall_empty_list_is_vacuously_true() {
        let r = apply_quantifier(
            QuantifierOp::ForAll,
            &gt(0),
            &list_of_ints(&[]),
            EPS,
            Span::new(0, 0),
        )
        .unwrap();
        assert!(r);
    }

    // ── Exists ───────────────────────────────────────────────

    #[test]
    fn exists_finds_matching_value() {
        let r = apply_quantifier(
            QuantifierOp::Exists,
            &EvalPredicate::PartialVerifier {
                op: VerifierOp::EQ,
                bound: Entity::Int(2),
            },
            &list_of_ints(&[1, 2, 3]),
            EPS,
            Span::new(0, 0),
        )
        .unwrap();
        assert!(r);
    }

    #[test]
    fn exists_returns_false_when_no_match() {
        let r = apply_quantifier(
            QuantifierOp::Exists,
            &gt(10),
            &list_of_ints(&[1, 2, 3]),
            EPS,
            Span::new(0, 0),
        )
        .unwrap();
        assert!(!r);
    }

    #[test]
    fn exists_empty_list_is_false() {
        let r = apply_quantifier(
            QuantifierOp::Exists,
            &gt(0),
            &list_of_ints(&[]),
            EPS,
            Span::new(0, 0),
        )
        .unwrap();
        assert!(!r);
    }

    // ── Predicates ───────────────────────────────────────────

    #[test]
    fn exists_admin_role_in_string_list() {
        let list = Entity::List(vec![
            Entity::String("user".into()),
            Entity::String("admin".into()),
        ]);
        let r = apply_quantifier(
            QuantifierOp::Exists,
            &eq_str("admin"),
            &list,
            EPS,
            Span::new(0, 0),
        )
        .unwrap();
        assert!(r);
    }

    #[test]
    fn forall_nonempty_strings() {
        let bad = Entity::List(vec![
            Entity::String("a".into()),
            Entity::String("".into()),
            Entity::String("b".into()),
        ]);
        assert!(!apply_quantifier(
            QuantifierOp::ForAll,
            &non_empty(),
            &bad,
            EPS,
            Span::new(0, 0),
        )
        .unwrap());

        let good = Entity::List(vec![Entity::String("a".into()), Entity::String("b".into())]);
        assert!(apply_quantifier(
            QuantifierOp::ForAll,
            &non_empty(),
            &good,
            EPS,
            Span::new(0, 0),
        )
        .unwrap());
    }

    #[test]
    fn exists_nonempty_in_all_empty_strings_is_false() {
        let all_empty = Entity::List(vec![Entity::String("".into()), Entity::String("".into())]);
        assert!(!apply_quantifier(
            QuantifierOp::Exists,
            &non_empty(),
            &all_empty,
            EPS,
            Span::new(0, 0),
        )
        .unwrap());
    }

    // ── Fallback / errors ────────────────────────────────────

    #[test]
    fn scalar_fallback_reduces_to_predicate() {
        // (ForAll (GT 0) 5) → True
        let r = apply_quantifier(
            QuantifierOp::ForAll,
            &gt(0),
            &Entity::Int(5),
            EPS,
            Span::new(0, 0),
        )
        .unwrap();
        assert!(r);

        // (ForAll (GT 0) -1) → False
        let r = apply_quantifier(
            QuantifierOp::ForAll,
            &gt(0),
            &Entity::Int(-1),
            EPS,
            Span::new(0, 0),
        )
        .unwrap();
        assert!(!r);
    }

    #[test]
    fn map_operand_is_type_error() {
        let m = Entity::Map(std::collections::HashMap::new());
        let err =
            apply_quantifier(QuantifierOp::ForAll, &gt(0), &m, EPS, Span::new(0, 0)).unwrap_err();
        assert!(matches!(err, NightjarLanguageError::TypeError { .. }));
    }

    #[test]
    fn predicate_type_error_propagates() {
        // Comparing Int > String is a type error — when iterating, the first
        // element to hit that should surface the error up.
        let bad = Entity::List(vec![Entity::String("a".into())]);
        let err =
            apply_quantifier(QuantifierOp::ForAll, &gt(0), &bad, EPS, Span::new(0, 0)).unwrap_err();
        assert!(matches!(err, NightjarLanguageError::TypeError { .. }));
    }

    // ── apply_quantifier_full ────────────────────────────────

    #[test]
    fn full_forall_all_true() {
        let r = apply_quantifier_full(
            QuantifierOp::ForAll,
            &list_of_ints(&[1, 2, 3]),
            Span::new(0, 0),
            |e| Ok(matches!(e, Entity::Int(i) if *i > 0)),
        )
        .unwrap();
        assert!(r);
    }

    #[test]
    fn full_forall_short_circuits_on_false() {
        let mut calls = 0;
        let r = apply_quantifier_full(
            QuantifierOp::ForAll,
            &list_of_ints(&[1, 0, 2]),
            Span::new(0, 0),
            |e| {
                calls += 1;
                Ok(matches!(e, Entity::Int(i) if *i > 0))
            },
        )
        .unwrap();
        assert!(!r);
        assert_eq!(calls, 2, "ForAll should short-circuit at first false");
    }

    #[test]
    fn full_exists_short_circuits_on_true() {
        let mut calls = 0;
        let r = apply_quantifier_full(
            QuantifierOp::Exists,
            &list_of_ints(&[0, 1, 2]),
            Span::new(0, 0),
            |e| {
                calls += 1;
                Ok(matches!(e, Entity::Int(i) if *i > 0))
            },
        )
        .unwrap();
        assert!(r);
        assert_eq!(calls, 2, "Exists should short-circuit at first true");
    }

    #[test]
    fn full_empty_list_semantics() {
        let empty = list_of_ints(&[]);
        assert!(
            apply_quantifier_full(QuantifierOp::ForAll, &empty, Span::new(0, 0), |_| Ok(false))
                .unwrap()
        );
        assert!(
            !apply_quantifier_full(QuantifierOp::Exists, &empty, Span::new(0, 0), |_| Ok(true))
                .unwrap()
        );
    }

    #[test]
    fn full_scalar_fallback_invokes_once() {
        let mut calls = 0;
        let r = apply_quantifier_full(
            QuantifierOp::ForAll,
            &Entity::Int(5),
            Span::new(0, 0),
            |e| {
                calls += 1;
                Ok(matches!(e, Entity::Int(i) if *i > 0))
            },
        )
        .unwrap();
        assert!(r);
        assert_eq!(calls, 1);
    }

    #[test]
    fn full_map_operand_is_type_error() {
        let err = apply_quantifier_full(
            QuantifierOp::ForAll,
            &Entity::Map(std::collections::HashMap::new()),
            Span::new(0, 0),
            |_| Ok(true),
        )
        .unwrap_err();
        assert!(matches!(err, NightjarLanguageError::TypeError { .. }));
    }
}