harn-parser 0.10.141

Parser, AST, and type checker for the Harn programming 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
//! Static obligations of the registered predicate capability. Ordinary method
//! syntax preserves lexical capability resolution and existing editor tooling.

use super::{scope::TypeScope, TypeChecker};
use crate::{ast::*, builtin_signatures::TyExt, diagnostic_codes::Code};
use harn_lexer::Span;

/// Which entry point declared a site. Both evaluate one question set through
/// one evaluator; they differ only in the outcome they project.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PredicateSiteKind {
    /// `harness.llm.evaluate_predicate`: one boolean question.
    Predicate,
    /// `harness.llm.evaluate`: a declared question set over one state.
    Evaluation,
}

impl PredicateSiteKind {
    /// The outcome schema a site of this kind returns.
    pub fn outcome_schema(self) -> &'static str {
        match self {
            Self::Predicate => "harn.predicate.outcome.v1",
            Self::Evaluation => "harn.evaluation.outcome.v1",
        }
    }
}

/// A checked source site. Consumers hash the canonical type and question set at
/// their artifact boundary; this record never contains runtime input values.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PredicateSite {
    pub id: String,
    pub kind: PredicateSiteKind,
    /// Every question this site asks. A predicate site holds exactly one
    /// boolean question, so both kinds project the same manifest census.
    pub questions: Vec<super::PredicateQuestionSpec>,
    pub input_type: TypeExpr,
    pub line: usize,
    pub column: usize,
    pub start: usize,
    pub end: usize,
    /// The declaration-time route, before catalog admission. An unknown route
    /// remains explicit so consumers cannot confuse no measurement with support.
    #[serde(default)]
    pub model_route: Option<PredicateModelRoute>,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PredicateModelRoute {
    pub provider: String,
    pub model: String,
}

fn model_route(policy: &SNode, scope: &TypeScope) -> Option<PredicateModelRoute> {
    let crate::const_eval::ConstValue::Dict(fields) = scope.const_value(policy)? else {
        return None;
    };
    let string = |name: &str| {
        fields.iter().find_map(|(key, value)| {
            if key != name {
                return None;
            }
            match value {
                crate::const_eval::ConstValue::String(value) => Some(value.clone()),
                _ => None,
            }
        })
    };
    Some(PredicateModelRoute {
        provider: string("provider")?,
        model: string("model")?,
    })
}

/// A deterministic structural identity, independent of field/union ordering
/// and source spans. This is material for an artifact/cache digest, not a hash.
pub fn canonical_type(ty: &TypeExpr) -> String {
    fn normalize(value: &mut serde_json::Value) {
        match value {
            serde_json::Value::Object(fields) => {
                for (name, value) in fields {
                    normalize(value);
                    if matches!(name.as_str(), "Shape" | "Union" | "Intersection") {
                        if let serde_json::Value::Array(items) = value {
                            items.sort_by_key(serde_json::Value::to_string);
                        }
                    }
                }
            }
            serde_json::Value::Array(items) => items.iter_mut().for_each(normalize),
            _ => {}
        }
    }
    let mut value = serde_json::to_value(ty).expect("type expression serializes");
    normalize(&mut value);
    value.to_string()
}

/// Undo the site-specific narrowing of a batched outcome's answer map, so an
/// arm recognizes as the contract arm it is. Without this, every evaluation
/// whose answers were typed from its own questions would stop counting as an
/// outcome and would escape the unused, boolean-use, and narrowing checks.
fn declared_answer_map(mut variant: TypeExpr) -> TypeExpr {
    let TypeExpr::Shape(fields) = &mut variant else {
        return variant;
    };
    let answered = fields.iter().any(|field| {
        field.name == "kind"
            && matches!(&field.type_expr, TypeExpr::LitString(kind)
                if kind == "answered" || kind == "low_confidence")
    });
    if !answered {
        return variant;
    }
    for field in fields.iter_mut() {
        if matches!(field.name.as_str(), "value" | "candidates") {
            field.type_expr = declared_answer_map_type().clone();
        }
    }
    variant
}

/// The contract's own `dict<string, EvaluationAnswer>`, read out of the
/// `answered` arm rather than rebuilt, so the two spellings cannot drift.
fn declared_answer_map_type() -> &'static TypeExpr {
    static DECLARED: std::sync::OnceLock<TypeExpr> = std::sync::OnceLock::new();
    DECLARED.get_or_init(|| {
        let TypeExpr::Union(variants) =
            harn_builtin_meta::predicate::EVALUATION_OUTCOME.to_type_expr()
        else {
            unreachable!("an evaluation outcome is a closed union");
        };
        variants
            .into_iter()
            .find_map(|variant| {
                let TypeExpr::Shape(fields) = variant else {
                    return None;
                };
                fields.iter().any(|field| {
                    field.name == "kind"
                        && matches!(&field.type_expr, TypeExpr::LitString(kind) if kind == "answered")
                }).then(|| {
                    fields
                        .into_iter()
                        .find(|field| field.name == "value")
                        .expect("the answered arm carries its answers")
                        .type_expr
                })
            })
            .expect("the evaluation outcome declares an answered arm")
    })
}

fn literal_text(node: &SNode) -> Option<String> {
    match &node.node {
        Node::StringLiteral(text) | Node::RawStringLiteral(text) if !text.is_empty() => {
            Some(text.clone())
        }
        _ => None,
    }
}

fn serializable(ty: &TypeExpr) -> bool {
    match ty {
        TypeExpr::Named(name) => {
            matches!(name.as_str(), "string" | "bool" | "int" | "float" | "nil")
        }
        TypeExpr::LitString(_) | TypeExpr::LitInt(_) => true,
        TypeExpr::Shape(fields) => fields.iter().all(|field| serializable(&field.type_expr)),
        TypeExpr::List(item) => serializable(item),
        TypeExpr::Tuple(items) | TypeExpr::Union(items) => {
            !items.is_empty() && items.iter().all(serializable)
        }
        TypeExpr::DictType(key, value) => {
            matches!(key.as_ref(), TypeExpr::Named(name) if name == "string") && serializable(value)
        }
        _ => false,
    }
}

impl TypeChecker {
    fn predicate_method_name(method: &str) -> bool {
        crate::builtin_signatures::lookup_capability_method(
            harn_builtin_meta::CapabilityId::Llm,
            method,
        )
        .is_some_and(|signature| {
            signature.name == harn_builtin_meta::predicate::EVALUATE.name
                || signature.name == harn_builtin_meta::predicate::EVALUATE_PREDICATE.name
        })
    }

    fn is_predicate_method(&self, object: &SNode, method: &str, scope: &TypeScope) -> bool {
        if !Self::predicate_method_name(method) {
            return false;
        }
        let Some(ty) = self.infer_type(object, scope) else {
            return false;
        };
        let ty = self.resolve_alias(&ty, scope);
        let Some(TypeExpr::Named(name)) = super::union::without_nil(&ty) else {
            return false;
        };
        harn_builtin_meta::CapabilityId::from_type_name(&name)
            == Some(harn_builtin_meta::CapabilityId::Llm)
    }

    pub(super) fn check_predicate_node(&mut self, node: &SNode, scope: &TypeScope) {
        let projection = match &node.node {
            Node::PropertyAccess { object, property }
            | Node::OptionalPropertyAccess { object, property } => {
                Some((object, Some(property.as_str())))
            }
            Node::SubscriptAccess { object, index }
            | Node::OptionalSubscriptAccess { object, index } => {
                let field = match &index.node {
                    Node::StringLiteral(name) | Node::RawStringLiteral(name) => Some(name.as_str()),
                    _ => None,
                };
                Some((object, field))
            }
            _ => None,
        };
        if let Some((object, field)) = projection {
            if let Some(ty) = self.infer_type(object, scope) {
                self.check_predicate_field(&ty, field, node.span, scope);
            }
        }
        // Only a call. `evaluate` is an ordinary field name, and reading
        // `config?.evaluate` off an untyped record is data, not an erased
        // capability. An erased receiver still has to call the method to
        // evaluate anything, and runtime admission refuses a call that no
        // checked site in the artifact owns.
        let named_receiver = match &node.node {
            Node::MethodCall { object, method, .. }
            | Node::OptionalMethodCall { object, method, .. } => Some((object, method)),
            _ => None,
        };
        if let Some((object, method)) = named_receiver {
            if Self::predicate_method_name(method)
                && self.infer_type(object, scope).is_none_or(|ty| {
                    matches!(self.resolve_alias(&ty, scope), TypeExpr::Named(name)
                        if matches!(name.as_str(), "any" | "unknown" | "dict" | "_"))
                })
            {
                self.error_at_with_help(
                    Code::PredicateSiteInvalid,
                    "predicate method receiver has no statically resolved type".into(),
                    node.span,
                    "retain HarnessLlm in the helper signature instead of erasing it to an unvalidated value".into(),
                );
            }
        }
        match &node.node {
            Node::IfElse { condition, .. }
            | Node::WhileLoop { condition, .. }
            | Node::GuardStmt { condition, .. }
            | Node::RequireStmt { condition, .. }
            | Node::Ternary { condition, .. } => self.check_predicate_boolean(condition, scope),
            Node::UnaryOp { op, operand } if op == "!" => {
                self.check_predicate_boolean(operand, scope);
            }
            Node::BinaryOp { op, left, right } if op == "&&" || op == "||" => {
                self.check_predicate_boolean(left, scope);
                self.check_predicate_boolean(right, scope);
            }
            Node::PropertyAccess { object, property }
            | Node::OptionalPropertyAccess { object, property }
                if self.is_predicate_method(object, property, scope) =>
            {
                self.error_at(Code::PredicateSiteInvalid,
                    "predicate evaluation cannot be captured as a function value; use a typed helper with a literal site".into(), node.span);
            }
            Node::OptionalMethodCall { object, method, .. }
                if self.is_predicate_method(object, method, scope) =>
            {
                self.error_at(Code::PredicateSiteInvalid,
                    "predicate evaluation requires an unconditional capability call; handle capability absence explicitly".into(), node.span);
            }
            _ => {}
        }
    }

    pub(super) fn check_predicate_call(&mut self, args: &[SNode], scope: &TypeScope, span: Span) {
        let [id, question, input, policy] = args else {
            return; // Ordinary signature checking owns arity.
        };
        let (Some(id), Some(question)) = (literal_text(id), literal_text(question)) else {
            self.error_at(
                Code::PredicateSiteInvalid,
                "predicate id and question must be nonempty string literals".into(),
                span,
            );
            return;
        };
        // The boolean projection asks one question, named by the site, so both
        // entry points record the same question census.
        let questions = vec![super::PredicateQuestionSpec {
            id: id.clone(),
            kind: super::PredicateQuestionKind::Boolean,
            instructions: question,
            labels: Vec::new(),
        }];
        self.record_predicate_site(
            PredicateSiteKind::Predicate,
            id,
            questions,
            input,
            policy,
            scope,
            span,
        );
    }

    pub(super) fn check_evaluation_call(&mut self, args: &[SNode], scope: &TypeScope, span: Span) {
        let [id, state, questions, policy] = args else {
            return; // Ordinary signature checking owns arity.
        };
        let Some(id) = literal_text(id) else {
            self.error_at(
                Code::PredicateSiteInvalid,
                "evaluation id must be a nonempty string literal".into(),
                span,
            );
            return;
        };
        let questions = match self.question_set(questions, scope) {
            Ok(questions) => questions,
            Err(error) => {
                self.error_at_with_help(
                    Code::PredicateQuestionSetInvalid,
                    error.message(),
                    questions.span,
                    error.help(),
                );
                return;
            }
        };
        self.record_predicate_site(
            PredicateSiteKind::Evaluation,
            id,
            questions,
            state,
            policy,
            scope,
            span,
        );
    }

    #[allow(clippy::too_many_arguments)]
    fn record_predicate_site(
        &mut self,
        kind: PredicateSiteKind,
        id: String,
        questions: Vec<super::PredicateQuestionSpec>,
        input: &SNode,
        policy: &SNode,
        scope: &TypeScope,
        span: Span,
    ) {
        let Some(input_type) = self.infer_type(input, scope) else {
            self.predicate_input_error(input.span);
            return;
        };
        let input_type = self.resolve_alias(&input_type, scope);
        if !serializable(&input_type) {
            self.predicate_input_error(input.span);
            return;
        }
        // Gradual typing ordinarily allows `any` at a typed call boundary.
        // Predicate admission must not accept an opaque policy that way.
        let policy_is_closed = self
            .infer_type(policy, scope)
            .is_some_and(|ty| serializable(&self.resolve_alias(&ty, scope)));
        if !policy_is_closed {
            self.error_at(
                Code::PredicateInputInvalid,
                "predicate policy must have a closed typed record".into(),
                policy.span,
            );
        }
        if self
            .predicate_sites
            .iter()
            .any(|site| site.id == id && (site.start != span.start || site.end != span.end))
        {
            self.error_at(
                Code::PredicateSiteInvalid,
                format!("predicate id `{id}` is declared by more than one source site"),
                span,
            );
            return;
        }
        if !self
            .predicate_sites
            .iter()
            .any(|site| site.start == span.start && site.end == span.end)
        {
            self.predicate_sites.push(PredicateSite {
                model_route: model_route(policy, scope),
                id,
                kind,
                questions,
                input_type,
                line: span.line,
                column: span.column,
                start: span.start,
                end: span.end,
            });
        }
    }

    fn predicate_input_error(&mut self, span: Span) {
        self.error_at(
            Code::PredicateInputInvalid,
            "predicate input must have a closed serializable type; functions, handles, open records and unvalidated values are not accepted".into(),
            span,
        );
    }

    pub(super) fn is_predicate_outcome(&self, ty: &TypeExpr, scope: &TypeScope) -> bool {
        let ty = self.resolve_alias(ty, scope);
        let Some(ty) = super::union::without_nil(&ty) else {
            return false;
        };
        let members = match &ty {
            TypeExpr::Union(members) => members.as_slice(),
            other => std::slice::from_ref(other),
        };
        if members.is_empty()
            || !members.iter().all(|member| {
                matches!(member, TypeExpr::Shape(fields) if fields.iter().any(|field| field.name == "receipt"))
            })
        {
            return false;
        }
        static VARIANTS: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
        let variants = VARIANTS.get_or_init(|| {
            // Both entry points return a closed outcome, and both must be
            // recognized here: a batched outcome discarded, used as a boolean,
            // or projected without narrowing is the same defect.
            [
                harn_builtin_meta::predicate::OUTCOME,
                harn_builtin_meta::predicate::EVALUATION_OUTCOME,
            ]
            .into_iter()
            .flat_map(|outcome| {
                let TypeExpr::Union(variants) = outcome.to_type_expr() else {
                    unreachable!("an evaluation outcome is a closed union");
                };
                variants
            })
            .map(|variant| canonical_type(&declared_answer_map(variant)))
            .collect()
        });
        members
            .iter()
            .all(|member| variants.contains(&canonical_type(&declared_answer_map(member.clone()))))
    }

    fn check_predicate_field(
        &mut self,
        ty: &TypeExpr,
        field: Option<&str>,
        span: Span,
        scope: &TypeScope,
    ) {
        if !self.is_predicate_outcome(ty, scope) {
            return;
        }
        let ty = self.resolve_alias(ty, scope);
        let Some(ty) = super::union::without_nil(&ty) else {
            return;
        };
        let members = match &ty {
            TypeExpr::Union(members) => members.as_slice(),
            other => std::slice::from_ref(other),
        };
        if field.is_some_and(|name| members.iter().all(|member| {
            matches!(member, TypeExpr::Shape(fields) if fields.iter().any(|field| field.name == name))
        })) { return; }
        self.error_at_with_help(
            Code::PredicateOutcomeUnnarrowed,
            "predicate variant field is not available on every remaining outcome".into(),
            span,
            "match outcome.kind before accessing a variant field; use a named field rather than a dynamic index".into(),
        );
    }

    pub(super) fn check_predicate_boolean(&mut self, node: &SNode, scope: &TypeScope) {
        if self
            .infer_type(node, scope)
            .is_some_and(|ty| self.is_predicate_outcome(&ty, scope))
        {
            self.error_at_with_help(
                Code::PredicateBooleanUse,
                "a predicate outcome is not a boolean".into(),
                node.span,
                "match outcome.kind, then branch on outcome.value.verdict only in the verdict arm"
                    .into(),
            );
        }
    }

    pub(super) fn record_predicate_binding(
        &mut self,
        pattern: &BindingPattern,
        inferred: Option<&TypeExpr>,
        span: Span,
        scope: &TypeScope,
    ) {
        if !inferred.is_some_and(|ty| self.is_predicate_outcome(ty, scope)) {
            return;
        }
        if let (BindingPattern::Dict(fields), Some(ty)) = (pattern, inferred) {
            for field in fields {
                if !field.is_rest {
                    self.check_predicate_field(ty, Some(&field.key), span, scope);
                }
            }
        }
        if let BindingPattern::Identifier(name) = pattern {
            if is_discard_name(name) {
                self.unused_predicate_error(span);
            } else {
                let binding = crate::lexical::BindingId {
                    name: name.clone(),
                    declaration_start: span.start,
                    declaration_end: span.end,
                };
                if !self
                    .predicate_bindings
                    .iter()
                    .any(|(existing, _)| *existing == binding)
                {
                    self.predicate_bindings.push((binding, span));
                }
            }
        }
    }

    pub(super) fn unused_predicate_error(&mut self, span: Span) {
        self.error_at_with_help(
            Code::PredicateOutcomeUnused,
            "predicate outcome is discarded without a disposition".into(),
            span,
            "match the outcome or pass it to a typed outcome policy".into(),
        );
    }

    pub(super) fn check_unused_predicate_bindings(&mut self, program: &[SNode]) {
        let patterns = crate::lexical::module_match_pattern_catalog_with_visible(
            program,
            &self.imported_type_decls,
        );
        let used = crate::lexical::resolved_identifier_bindings_with_source(
            &[],
            program,
            self.source.as_deref(),
            &patterns,
        );
        let unused: Vec<_> = self
            .predicate_bindings
            .iter()
            .filter(|(binding, _)| !used.values().any(|used| used == binding))
            .map(|(_, span)| *span)
            .collect();
        for span in unused {
            self.unused_predicate_error(span);
        }
    }
}