harn-kernel 0.10.135

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
411
pub struct PureCase {
    pub id: &'static str,
    pub source: &'static str,
    pub entry: &'static str,
    pub input_json: &'static str,
    pub expected_json: &'static str,
}

pub const PURE_CASES: &[PureCase] = &[
    PureCase {
        id: "typed-record-pick-preserves-nil-and-copies-values",
        source: r#"
            type Input = {name: string, age: int, absent: nil, nested: {count: int}}
            fn project(input: Input) -> {name: string, absent: nil, original: int, copied: int} {
              let selected = pick(input, ["name", "absent", "nested", "name"])
              selected.nested.count = 99
              return {name: selected.name, absent: selected.absent, original: input.nested.count, copied: selected.nested.count}
            }
        "#,
        entry: "project",
        input_json: r#"{"name":"Ada","age":37,"absent":null,"nested":{"count":1}}"#,
        expected_json: r#"{"name":"Ada","absent":null,"original":1,"copied":99}"#,
    },
    PureCase {
        id: "typed-record-pick-runtime-keys-and-missing-values",
        source: r"
            fn project(input: {data: dict<string, int>, keys: list<string>}) -> dict<string, int> {
              return pick(input.data, input.keys)
            }
        ",
        entry: "project",
        input_json: r#"{"data":{"a":1,"b":2},"keys":["b","missing","b"]}"#,
        expected_json: r#"{"b":2}"#,
    },
    PureCase {
        id: "typed-record-pick-empty",
        source: r"fn project(input: {name: string}) -> {} { return pick(input, []) }",
        entry: "project",
        input_json: r#"{"name":"Ada"}"#,
        expected_json: "{}",
    },
    PureCase {
        id: "named-record-reducer",
        source: r#"
            type State = {count: int, history: list<int>}
            type Event = {kind: string, amount: int}
            type Input = {state: State, event: Event}

            fn reduce(input: Input) -> State {
              if input.event.kind == "reset" {
                return {count: 0, history: input.state.history + [0]}
              }
              const next = input.state.count + input.event.amount
              return {count: next, history: input.state.history + [next]}
            }
        "#,
        entry: "reduce",
        input_json: r#"{"state":{"count":2,"history":[1,2]},"event":{"kind":"increment","amount":3}}"#,
        expected_json: r#"{"count":5,"history":[1,2,5]}"#,
    },
    PureCase {
        id: "closure-capture-and-control-flow",
        source: r"
            type TransformInput = {value: int, offset: int, enabled: bool}
            type TransformResult = {value: int, enabled: bool}
            fn transform(input: TransformInput) -> TransformResult {
              const offset = input.offset
              const add_offset = {value -> value + offset}
              if input.enabled {
                return {value: add_offset(input.value), enabled: true}
              }
              return {value: input.value, enabled: false}
            }
        ",
        entry: "transform",
        input_json: r#"{"value":7,"offset":4,"enabled":true}"#,
        expected_json: r#"{"enabled":true,"value":11}"#,
    },
    PureCase {
        id: "recursive-and-sibling-functions",
        source: r"
            fn fib(n: int) -> int {
              if n <= 1 { return n }
              return fib(n - 1) + fib(n - 2)
            }
            fn solve(input: int) -> int { return fib(input) }
        ",
        entry: "solve",
        input_json: "7",
        expected_json: "13",
    },
    PureCase {
        id: "forward-declared-capturing-function",
        source: r"
            fn reduce(input: int) -> int {
              const offset = 3
              return add_offset(input)
              fn add_offset(value: int) -> int { return value + offset }
            }
        ",
        entry: "reduce",
        input_json: "4",
        expected_json: "7",
    },
    PureCase {
        id: "typed-rest-and-sibling-call",
        source: r"
            fn collect(...values: int) -> list<int> { return values }
            fn reduce(input: int) -> list<int> { return collect(input, 2) }
        ",
        entry: "reduce",
        input_json: "7",
        expected_json: "[7,2]",
    },
    PureCase {
        id: "list-string-and-record-operations",
        source: r"
            type SummaryInput = {
              left: list<int>,
              right: list<int>,
              prefix: string,
              name: string,
              needle: int,
              meta: dict<string, int>,
            }
            fn summarize(input: SummaryInput) {
              return {
                items: input.left + input.right,
                title: input.prefix + input.name,
                found: input.left.contains(input.needle),
                fields: input.meta.count(),
              }
            }
        ",
        entry: "summarize",
        input_json: r#"{"left":[1,2],"right":[3],"prefix":"Harn ","name":"Kernel","needle":2,"meta":{"a":1,"b":2}}"#,
        expected_json: r#"{"fields":2,"found":true,"items":[1,2,3],"title":"Harn Kernel"}"#,
    },
    PureCase {
        id: "list-ordering-runtime-and-constant-folding",
        source: r"
            type ListComparisonInput = {left: list<int>, right: list<int>}
            fn compare_lists(input: ListComparisonInput) {
              return {
                runtime_less: input.left < input.right,
                runtime_equal: input.left <= input.left,
                constant_less: [1, 2] < [1, 3],
                constant_greater: [2] > [1, 9],
              }
            }
        ",
        entry: "compare_lists",
        input_json: r#"{"left":[1,2],"right":[1,3]}"#,
        expected_json: r#"{"constant_greater":true,"constant_less":true,"runtime_equal":true,"runtime_less":true}"#,
    },
    PureCase {
        id: "mixed-type-equality-is-structural-not-ordering",
        source: r"
            fn compare(input: {value: string}) {
              return {
                string_is_not_nil: input.value != nil,
                string_is_not_int: input.value != 7,
                nil_is_nil: nil == nil,
                numeric_cross_kind: 1 == 1.0,
              }
            }
        ",
        entry: "compare",
        input_json: r#"{"value":"ui://portable"}"#,
        expected_json: r#"{"nil_is_nil":true,"numeric_cross_kind":true,"string_is_not_int":true,"string_is_not_nil":true}"#,
    },
    PureCase {
        id: "structured-throw-catch",
        source: r#"
            fn validate(input: {value: int}) {
              try {
                if input.value < 0 {
                  throw {code: "negative", value: input.value}
                }
                return {ok: true, value: input.value}
              } catch error {
                return {ok: false, value: error.value, code: error.code}
              }
            }
        "#,
        entry: "validate",
        input_json: r#"{"value":-9}"#,
        expected_json: r#"{"code":"negative","ok":false,"value":-9}"#,
    },
    PureCase {
        id: "negative-index-and-slice",
        source: r"
            type ChoiceInput = {values: list<int>, text: string}
            fn choose(input: ChoiceInput) {
              return {
                last: input.values[-1],
                middle: input.values[-4:-1],
                suffix: input.text[-3:],
              }
            }
        ",
        entry: "choose",
        input_json: r#"{"values":[1,2,3,4,5],"text":"kernel"}"#,
        expected_json: r#"{"last":5,"middle":[2,3,4],"suffix":"nel"}"#,
    },
    PureCase {
        id: "module-capture-property-mutation",
        source: r"
            let state = {count: 0}
            fn reduce(input: {count: int}) {
              state.count = input.count
              return {count: state.count}
            }
        ",
        entry: "reduce",
        input_json: r#"{"count":9}"#,
        expected_json: r#"{"count":9}"#,
    },
    PureCase {
        id: "iteration-and-copy-on-write-mutation",
        source: r#"
            type IterationState = {count: int, tags: list<string>}
            type IterationInput = {state: IterationState, values: list<int>}
            fn reduce(input: IterationInput) -> IterationState {
              let state = input.state
              for value in input.values {
                state.count = state.count + value
              }
              state.tags[0] = "updated"
              return state
            }
        "#,
        entry: "reduce",
        input_json: r#"{"state":{"count":1,"tags":["old"]},"values":[2,3,4]}"#,
        expected_json: r#"{"count":10,"tags":["updated"]}"#,
    },
    PureCase {
        id: "renderer-string-and-option-primitives",
        source: r#"
            type RenderInput = {name: string, validation?: dict<string, bool>}
            fn reduce(input: RenderInput) {
              const options = {allow_network: false}.merging(input.validation ?? {})
              const name = trim(input.name)
              return {
                encoded: replace(json_stringify(name), "<", "\\u003c"),
                portable: starts_with(name, "Portable"),
                options: options,
              }
            }
        "#,
        entry: "reduce",
        input_json: r#"{"name":"  Portable <Harn>  ","validation":{"allow_host_bridge":true}}"#,
        expected_json: r#"{"encoded":"\"Portable \\u003cHarn>\"","options":{"allow_host_bridge":true,"allow_network":false},"portable":true}"#,
    },
    PureCase {
        id: "artifact-regex-hash-and-secret-safety-primitives",
        source: r#"
            fn inspect(input: string) {
              const captures = regex_captures("(?is)<body\\b([^>]*)>(.*?)</body>", input)
              return {
                body: captures[0].groups[1],
                scripts: regex_match("(?is)<script\\b", input),
                text: trim(regex_replace("(?is)<[^>]+>", " ", input)),
                digest: sha256("abc"),
                clean: len(secret_scan(input)) == 0,
              }
            }
        "#,
        entry: "inspect",
        input_json: r#""<body class='app'>Portable <b>Harn</b></body>""#,
        expected_json: r#"{"body":"Portable <b>Harn</b>","clean":true,"digest":"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad","scripts":null,"text":"Portable  Harn"}"#,
    },
    PureCase {
        id: "target-independent-path-joining",
        source: r#"
            fn paths(input: {root: string}) {
              return {
                host: path_join(input.root, ".harn", "state.json"),
                reset: path_join("ignored", "/absolute", "file"),
              }
            }
        "#,
        entry: "paths",
        input_json: r#"{"root":"C:\\workspace"}"#,
        expected_json: r#"{"host":"C:/workspace/.harn/state.json","reset":"/absolute/file"}"#,
    },
    PureCase {
        id: "result-enum-match-and-propagation",
        source: r#"
            fn divide(value: int, divisor: int) -> Result<int, string> {
              if divisor == 0 { return Result.Err("division by zero") }
              return Result.Ok(value / divisor)
            }
            fn halve(value: int, divisor: int) -> Result<int, string> {
              const divided: int = divide(value, divisor)?
              return Result.Ok(divided / 2)
            }
            fn reduce(input: int) {
              const result = halve(12, input)
              match result {
                Result.Ok(value) -> { return [result.variant, result.fields, value] }
                Result.Err(message) -> { return [result.variant, result.fields, message] }
              }
            }
        "#,
        entry: "reduce",
        input_json: "3",
        expected_json: r#"["Ok",[2],2]"#,
    },
    PureCase {
        // Widening: a whole int satisfies a float parameter. This is the
        // half of harn#6267 that payload schemas used to get wrong.
        id: "float-param-accepts-int",
        source: r"
            fn takes_float(x: float) -> float { return x + 0.0 }
            fn reduce(input: int) -> float { return takes_float(input) }
        ",
        entry: "reduce",
        input_json: "3",
        expected_json: "3.0",
    },
];

/// Runtime failures that every portable executor must agree on.
///
/// Unlike [`PURE_CASES`], these are expected to fail after a successful
/// compile. The int←float case is the drift that used to slip past
/// `browser_worker_matches_native_portable_corpus_exactly` (harn#6267).
pub struct RuntimeFailureCase {
    pub id: &'static str,
    pub source: &'static str,
    pub entry: &'static str,
    pub input_json: &'static str,
    pub expected_code: &'static str,
}

pub const RUNTIME_FAILURE_CASES: &[RuntimeFailureCase] = &[
    RuntimeFailureCase {
        id: "pick-rejects-non-record-source",
        source: r#"fn project(input: any) { return pick(input, ["name"]) }"#,
        entry: "project",
        input_json: "42",
        expected_code: "builtin_type",
    },
    RuntimeFailureCase {
        id: "pick-rejects-non-string-key",
        source: r"fn project(input: {name: string, keys: list<any>}) { return pick(input, input.keys) }",
        entry: "project",
        input_json: r#"{"name":"Ada","keys":[1]}"#,
        expected_code: "builtin_type",
    },
    RuntimeFailureCase {
        id: "pick-rejects-wrong-arity",
        source: r"fn project(args: list<any>) { return pick(...args) }",
        entry: "project",
        input_json: r#"[{"name":"Ada"}]"#,
        expected_code: "builtin_type",
    },
    RuntimeFailureCase {
        id: "int-param-rejects-float",
        source: r"
            fn takes_int(n: int) -> int { return n }
            // Deliberate unchecked host boundary: the failure belongs to the
            // portable runtime parameter contract.
            fn reduce(input: any) { return takes_int(input) }
        ",
        entry: "reduce",
        input_json: "2.5",
        expected_code: "argument_type",
    },
];

pub struct InvalidCase {
    pub id: &'static str,
    pub source: &'static str,
    pub entry: &'static str,
    pub expected_code: &'static str,
}

pub const INVALID_CASES: &[InvalidCase] = &[
    InvalidCase {
        id: "pick-unknown-field",
        source: r#"fn project(input: {name: string}) { return pick(input, ["nmae"]) }"#,
        entry: "project",
        expected_code: "compile_frontend",
    },
    InvalidCase {
        id: "pick-dynamic-fields-are-not-required",
        source: r"fn project(input: {name: string}, keys: list<string>) -> {name: string} { return pick(input, keys) }",
        entry: "project",
        expected_code: "compile_frontend",
    },
    InvalidCase {
        id: "frontend-syntax-error",
        source: "fn reduce( {",
        entry: "reduce",
        expected_code: "compile_frontend",
    },
    InvalidCase {
        id: "invalid-mutable-local-program",
        source: r"
            fn reduce(input) {
              var value = input
              value = value + 1
              return value
            }
        ",
        entry: "reduce",
        expected_code: "compile_frontend",
    },
];