harn-kernel 0.10.136

Portable compiler, program artifact, and deterministic execution kernel for Harn
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
use std::collections::BTreeMap;
use std::sync::Arc;

use harn_parser::{SNode, TypeParam, TypedParam};

use crate::chunk::{CompiledFunction, Constant, Op};
use crate::schema;
use crate::value::VmValue;

use super::error::CompileError;
use super::yield_scan::body_contains_yield;
use super::Compiler;

impl Compiler {
    pub(super) fn compile_fn_decl(
        &mut self,
        name: &str,
        type_params: &[TypeParam],
        params: &[TypedParam],
        body: &[SNode],
        is_stream: bool,
    ) -> Result<(), CompileError> {
        let mut fn_compiler = self.nested_body();
        fn_compiler.enum_names = self.enum_names.clone();
        fn_compiler.enum_variant_owners = self.enum_variant_owners.clone();
        fn_compiler.imported_enum_candidates = self.imported_enum_candidates.clone();
        fn_compiler.imported_enum_candidates_authoritative =
            self.imported_enum_candidates_authoritative;
        fn_compiler.interface_methods = self.interface_methods.clone();
        fn_compiler.type_aliases = self.type_aliases.clone();
        fn_compiler.struct_layouts = self.struct_layouts.clone();
        fn_compiler.declare_param_slots(params);
        fn_compiler.record_param_types(params);
        fn_compiler.emit_default_preamble(params)?;
        fn_compiler.emit_type_checks(params);
        let is_gen = is_stream || body_contains_yield(body);
        fn_compiler.seed_captured_idents(body);
        fn_compiler.compile_block(body)?;
        // Run pending defers before implicit return
        fn_compiler.drain_finallys_to_floor(0)?;
        fn_compiler.chunk.emit(Op::Nil, self.line);
        fn_compiler.chunk.emit(Op::Return, self.line);

        let param_slots = fn_compiler.compile_param_slots(params);
        let has_runtime_type_checks =
            CompiledFunction::has_runtime_type_checks_for_params(&param_slots);
        super::ensure_chunk_addressable(&fn_compiler.chunk, &format!("fn `{name}`"), self.line)?;
        let func = CompiledFunction {
            name: name.to_string(),
            type_params: type_params.iter().map(|param| param.name.clone()).collect(),
            nominal_type_names: fn_compiler.nominal_type_names(),
            params: param_slots,
            default_start: TypedParam::default_start(params),
            chunk: Arc::new(fn_compiler.chunk),
            is_generator: is_gen,
            is_stream,
            has_rest_param: params.last().is_some_and(|p| p.rest),
            has_runtime_type_checks,
        };
        let fn_idx = self.chunk.functions.len();
        self.chunk.functions.push(Arc::new(func));

        self.chunk.emit_u16(Op::Closure, fn_idx as u16, self.line);
        self.emit_callable_binding(name);
        Ok(())
    }

    pub(super) fn compile_tool_decl(
        &mut self,
        name: &str,
        description: &Option<String>,
        params: &[TypedParam],
        return_type: &Option<harn_parser::TypeExpr>,
        body: &[SNode],
    ) -> Result<(), CompileError> {
        // Compile the body as a closure, then call `tool_define(registry, name, description, config)`.
        let mut fn_compiler = self.nested_body();
        fn_compiler.enum_names = self.enum_names.clone();
        fn_compiler.enum_variant_owners = self.enum_variant_owners.clone();
        fn_compiler.imported_enum_candidates = self.imported_enum_candidates.clone();
        fn_compiler.imported_enum_candidates_authoritative =
            self.imported_enum_candidates_authoritative;
        fn_compiler.interface_methods = self.interface_methods.clone();
        fn_compiler.type_aliases = self.type_aliases.clone();
        fn_compiler.struct_layouts = self.struct_layouts.clone();
        fn_compiler.declare_param_slots(params);
        fn_compiler.record_param_types(params);
        fn_compiler.emit_default_preamble(params)?;
        fn_compiler.emit_type_checks(params);
        fn_compiler.seed_captured_idents(body);
        fn_compiler.compile_block(body)?;
        // Run pending defers before implicit return
        fn_compiler.drain_finallys_to_floor(0)?;
        fn_compiler.chunk.emit(Op::Return, self.line);

        let param_slots = fn_compiler.compile_param_slots(params);
        let has_runtime_type_checks =
            CompiledFunction::has_runtime_type_checks_for_params(&param_slots);
        super::ensure_chunk_addressable(&fn_compiler.chunk, &format!("fn `{name}`"), self.line)?;
        let func = CompiledFunction {
            name: name.to_string(),
            type_params: Vec::new(),
            nominal_type_names: fn_compiler.nominal_type_names(),
            params: param_slots,
            default_start: TypedParam::default_start(params),
            chunk: Arc::new(fn_compiler.chunk),
            is_generator: false,
            is_stream: false,
            has_rest_param: params.last().is_some_and(|p| p.rest),
            has_runtime_type_checks,
        };
        let body = Arc::new(func);
        let handler = self.compile_tool_argument_adapter(name, params, Arc::clone(&body))?;
        let body_idx = self.chunk.functions.len();
        self.chunk.functions.push(body);
        let fn_idx = self.chunk.functions.len();
        self.chunk.functions.push(handler);

        let define_name = self.string_constant("tool_define");
        self.chunk.emit_u16(Op::Constant, define_name, self.line);

        let reg_name = self.string_constant("tool_registry");
        self.chunk.emit_u16(Op::Constant, reg_name, self.line);
        self.chunk.emit_u8(Op::Call, 0, self.line);

        let tool_name_idx = self.string_constant(name);
        self.chunk.emit_u16(Op::Constant, tool_name_idx, self.line);

        let desc = description.as_deref().unwrap_or("");
        let desc_idx = self.string_constant(desc);
        self.chunk.emit_u16(Op::Constant, desc_idx, self.line);

        // Build parameters dict using the same schema lowering as
        // runtime param validation so tools expose nested shapes,
        // unions, item schemas, defaults, and dict value schemas.
        let mut param_count: u16 = 0;
        for p in params {
            let pn_idx = self.string_constant(&p.name);
            self.chunk.emit_u16(Op::Constant, pn_idx, self.line);

            let value_type = if p.rest {
                Some(harn_parser::TypeExpr::List(Box::new(
                    p.type_expr
                        .clone()
                        .unwrap_or_else(|| harn_parser::TypeExpr::Named("unknown".into())),
                )))
            } else {
                p.type_expr.clone()
            };
            let base_schema = value_type
                .as_ref()
                .and_then(Self::type_expr_to_schema_value)
                .unwrap_or_else(|| {
                    VmValue::dict(BTreeMap::from([(
                        "type".to_string(),
                        VmValue::String(arcstr::ArcStr::from("any")),
                    )]))
                });
            let public_schema =
                schema::schema_to_json_schema_value(&base_schema).map_err(|error| {
                    CompileError {
                        message: format!(
                            "failed to lower tool parameter schema for '{}': {}",
                            p.name, error
                        ),
                        line: self.line,
                    }
                })?;
            let mut param_schema = match public_schema {
                VmValue::Dict(map) => (*map).clone(),
                _ => crate::value::DictMap::new(),
            };

            if p.default_value.is_some() || p.rest {
                param_schema.insert(crate::value::intern_key("required"), VmValue::Bool(false));
            }

            self.emit_vm_value_literal(&VmValue::dict(param_schema));

            // Schema metadata must not execute a default expression at
            // declaration time. Nonconstant defaults can capture capabilities
            // or refer to earlier arguments, and belong to handler invocation.
            if let Some(default_value) = p
                .default_value
                .as_deref()
                .and_then(super::optimizer::constant_value)
            {
                let default_key = self.string_constant("default");
                self.chunk.emit_u16(Op::Constant, default_key, self.line);
                self.emit_vm_value_literal(&default_value);
                self.chunk.emit_u16(Op::BuildDict, 1, self.line);
                self.chunk.emit(Op::Add, self.line);
            }

            param_count += 1;
        }
        self.chunk.emit_u16(Op::BuildDict, param_count, self.line);

        let params_key = self.string_constant("parameters");
        self.chunk.emit_u16(Op::Constant, params_key, self.line);
        self.chunk.emit(Op::Swap, self.line);

        let handler_key = self.string_constant("handler");
        self.chunk.emit_u16(Op::Constant, handler_key, self.line);
        self.chunk.emit_u16(Op::Closure, fn_idx as u16, self.line);

        // The registry dispatches named arguments. Calling the tool value in
        // Harn keeps ordinary positional function semantics around the same body.
        let call_handler_key = self.string_constant("_call_handler");
        self.chunk
            .emit_u16(Op::Constant, call_handler_key, self.line);
        self.chunk.emit_u16(Op::Closure, body_idx as u16, self.line);

        let mut config_entries = 3u16;
        if let Some(return_type) = return_type
            .as_ref()
            .and_then(Self::type_expr_to_schema_value)
        {
            let return_type =
                schema::schema_to_json_schema_value(&return_type).map_err(|error| {
                    CompileError {
                        message: format!(
                            "failed to lower tool return schema for '{name}': {error}"
                        ),
                        line: self.line,
                    }
                })?;
            let returns_key = self.string_constant("returns");
            self.chunk.emit_u16(Op::Constant, returns_key, self.line);
            self.emit_vm_value_literal(&return_type);
            config_entries += 1;
        }

        self.chunk
            .emit_u16(Op::BuildDict, config_entries, self.line);

        self.chunk.emit_u8(Op::Call, 4, self.line);

        self.emit_define_binding(name, false);
        Ok(())
    }

    /// Lower a `skill NAME { key value ... }` declaration to
    /// `let NAME = skill_define(skill_registry(), NAME, { key: value, ... })`.
    ///
    /// Each `(field_name, expr)` pair becomes a dict entry. Lifecycle hook
    /// expressions (e.g. `on_activate fn() { ... }`) lower to closure
    /// values just like any other `fn(...) { ... }` literal.
    pub(super) fn compile_skill_decl(
        &mut self,
        name: &str,
        fields: &[(String, SNode)],
    ) -> Result<(), CompileError> {
        // Push skill_define
        let define_idx = self.string_constant("skill_define");
        self.chunk.emit_u16(Op::Constant, define_idx, self.line);

        // Push skill_registry()
        let reg_idx = self.string_constant("skill_registry");
        self.chunk.emit_u16(Op::Constant, reg_idx, self.line);
        self.chunk.emit_u8(Op::Call, 0, self.line);

        // Push skill name
        let name_const = self.string_constant(name);
        self.chunk.emit_u16(Op::Constant, name_const, self.line);

        // Build config dict from fields.
        let mut field_count: u16 = 0;
        for (key, value) in fields {
            let key_idx = self.string_constant(key);
            self.chunk.emit_u16(Op::Constant, key_idx, self.line);
            self.compile_node(value)?;
            field_count += 1;
        }
        self.chunk.emit_u16(Op::BuildDict, field_count, self.line);

        // Call skill_define(registry, name, config) — 3 args.
        self.chunk.emit_u8(Op::Call, 3, self.line);

        // Bind result to skill name as a variable.
        self.emit_define_binding(name, false);
        Ok(())
    }

    pub(super) fn compile_eval_pack_decl(
        &mut self,
        binding_name: &str,
        pack_id: &str,
        fields: &[(String, SNode)],
        body: &[SNode],
        summarize: &Option<Vec<SNode>>,
        run_body: bool,
    ) -> Result<(), CompileError> {
        self.emit_eval_pack_manifest_value(pack_id, fields)?;
        self.emit_define_binding(binding_name, false);

        if run_body && (!body.is_empty() || summarize.is_some()) {
            self.begin_scope();
            let finally_floor = self.finally_bodies.len();

            let mut visible_fields = vec!["id".to_string(), "version".to_string()];
            for (field_name, _) in fields {
                if !visible_fields.iter().any(|name| name == field_name) {
                    visible_fields.push(field_name.clone());
                }
            }
            for field_name in visible_fields {
                self.emit_get_binding(binding_name);
                let field_idx = self.string_constant(&field_name);
                self.chunk.emit_u16(Op::GetProperty, field_idx, self.line);
                self.emit_define_binding(&field_name, false);
            }

            for sn in body {
                self.compile_discarded_stmt(sn)?;
            }
            if let Some(summary_body) = summarize {
                for sn in summary_body {
                    self.compile_discarded_stmt(sn)?;
                }
            }
            self.drain_finallys_to_floor(finally_floor)?;
            self.end_scope();
        }
        Ok(())
    }

    fn emit_eval_pack_manifest_value(
        &mut self,
        pack_id: &str,
        fields: &[(String, SNode)],
    ) -> Result<(), CompileError> {
        let manifest_idx = self.string_constant("eval_pack_manifest");
        self.chunk.emit_u16(Op::Constant, manifest_idx, self.line);

        let has_id = fields.iter().any(|(key, _)| key == "id");
        let has_version = fields.iter().any(|(key, _)| key == "version");
        let mut entry_count = fields.len() as u16;
        if !has_version {
            let key_idx = self.string_constant("version");
            self.chunk.emit_u16(Op::Constant, key_idx, self.line);
            let value_idx = self.chunk.add_constant(Constant::Int(1));
            self.chunk.emit_u16(Op::Constant, value_idx, self.line);
            entry_count += 1;
        }
        if !has_id {
            let key_idx = self.string_constant("id");
            self.chunk.emit_u16(Op::Constant, key_idx, self.line);
            let value_idx = self.string_constant(pack_id);
            self.chunk.emit_u16(Op::Constant, value_idx, self.line);
            entry_count += 1;
        }
        for (key, value) in fields {
            let key_idx = self.string_constant(key);
            self.chunk.emit_u16(Op::Constant, key_idx, self.line);
            self.compile_node(value)?;
        }
        self.chunk.emit_u16(Op::BuildDict, entry_count, self.line);
        self.chunk.emit_u8(Op::Call, 1, self.line);
        Ok(())
    }

    pub(super) fn compile_closure(
        &mut self,
        params: &[TypedParam],
        body: &[SNode],
    ) -> Result<(), CompileError> {
        let mut fn_compiler = self.nested_body();
        fn_compiler.enum_names = self.enum_names.clone();
        fn_compiler.enum_variant_owners = self.enum_variant_owners.clone();
        fn_compiler.imported_enum_candidates = self.imported_enum_candidates.clone();
        fn_compiler.imported_enum_candidates_authoritative =
            self.imported_enum_candidates_authoritative;
        fn_compiler.interface_methods = self.interface_methods.clone();
        fn_compiler.type_aliases = self.type_aliases.clone();
        fn_compiler.struct_layouts = self.struct_layouts.clone();
        fn_compiler.declare_param_slots(params);
        fn_compiler.record_param_types(params);
        fn_compiler.emit_default_preamble(params)?;
        fn_compiler.emit_type_checks(params);
        let is_gen = body_contains_yield(body);
        fn_compiler.seed_captured_idents(body);
        fn_compiler.compile_block(body)?;
        // Run pending defers before implicit return
        fn_compiler.drain_finallys_to_floor(0)?;
        fn_compiler.chunk.emit(Op::Return, self.line);

        let param_slots = fn_compiler.compile_param_slots(params);
        let has_runtime_type_checks =
            CompiledFunction::has_runtime_type_checks_for_params(&param_slots);
        super::ensure_chunk_addressable(&fn_compiler.chunk, "closure", self.line)?;
        let func = CompiledFunction {
            name: "<closure>".to_string(),
            type_params: Vec::new(),
            nominal_type_names: fn_compiler.nominal_type_names(),
            params: param_slots,
            default_start: TypedParam::default_start(params),
            chunk: Arc::new(fn_compiler.chunk),
            is_generator: is_gen,
            is_stream: false,
            has_rest_param: false,
            has_runtime_type_checks,
        };
        let fn_idx = self.chunk.functions.len();
        self.chunk.functions.push(Arc::new(func));

        self.chunk.emit_u16(Op::Closure, fn_idx as u16, self.line);
        Ok(())
    }
}