Skip to main content

portable_conformance_json/testdata/
portable_conformance.rs

1pub struct PureCase {
2    pub id: &'static str,
3    pub source: &'static str,
4    pub entry: &'static str,
5    pub input_json: &'static str,
6    pub expected_json: &'static str,
7}
8
9const REGEX_ERROR_SOURCE: &str = r#"
10    fn inspect(input: string) {
11      const matched = try { regex_match(input, "x"); false } catch (_) { true }
12      const replaced = try { regex_replace(input, "y", "x"); false } catch (_) { true }
13      const captured = try { regex_captures(input, "x"); false } catch (_) { true }
14      const split = try { regex_split("x", input); false } catch (_) { true }
15      return [
16        matched,
17        replaced,
18        captured,
19        split,
20      ]
21    }
22"#;
23
24pub const PURE_CASES: &[PureCase] = &[
25    PureCase {
26        id: "hex-input-errors-are-catchable",
27        source: "fn inspect(input: string) { return try { hex_decode(input); false } catch (_) { true } }",
28        entry: "inspect",
29        input_json: r#""not-hex""#,
30        expected_json: "true",
31    },
32    PureCase {
33        id: "regex-input-errors-are-catchable",
34        source: REGEX_ERROR_SOURCE,
35        entry: "inspect",
36        input_json: r#""[""#,
37        expected_json: "[true,true,true,true]",
38    },
39    PureCase {
40        id: "valid-regex-inputs-do-not-throw",
41        source: REGEX_ERROR_SOURCE,
42        entry: "inspect",
43        input_json: r#""x""#,
44        expected_json: "[false,false,false,false]",
45    },
46    PureCase {
47        id: "hashed-secret-scan-refuses-an-empty-policy",
48        source: r#"
49            fn scan(input: string) {
50              try { secret_scan(input, []) }
51              catch (error) { return to_string(error).contains("hashes must be a nonempty list") }
52              return false
53            }
54        "#,
55        entry: "scan",
56        input_json: r#""clean""#,
57        expected_json: "true",
58    },
59    PureCase {
60        id: "hashed-secret-scan-keeps-locations-without-disclosing-tokens",
61        source: r#"
62            fn scan(input: string) {
63              const findings = secret_scan(input, [sha256("synthetic.private")])
64              let output = []
65              for finding in findings {
66                output = output + [{
67                  line: finding.line,
68                  column: finding.column_start,
69                  end: finding.column_end,
70                  redacted: finding.redacted,
71                  correct_digest: finding.fingerprint == sha256("synthetic.private"),
72                }]
73              }
74              return output
75            }
76        "#,
77        entry: "scan",
78        input_json: r#""λ SYNTHETIC.PRIVATE\nsynthetic.private.invalid synthetic.private""#,
79        expected_json: r#"[{"line":1,"column":3,"end":20,"redacted":"[hash match]","correct_digest":true},{"line":2,"column":27,"end":44,"redacted":"[hash match]","correct_digest":true}]"#,
80    },
81    PureCase {
82        id: "truthiness-empty-bytes",
83        source: r"
84            fn truth(input: bytes) {
85              if input { return [!input, input ? true : false] }
86              return [!input, false]
87            }
88        ",
89        entry: "truth",
90        input_json: r#"{"$bytes":[]}"#,
91        expected_json: "[true,false]",
92    },
93    PureCase {
94        id: "truthiness-nonempty-bytes-with-zero-byte",
95        source: r"
96            fn truth(input: bytes) {
97              if input { return [!input, input ? true : false] }
98              return [!input, false]
99            }
100        ",
101        entry: "truth",
102        input_json: r#"{"$bytes":[0]}"#,
103        expected_json: "[false,true]",
104    },
105    PureCase {
106        id: "truthiness-nan-folding-and-runtime-branches",
107        source: r"
108            fn truth(input: float) {
109              let nan = input / input
110              let branch = false
111              if nan { branch = true }
112              return [!(0.0 / 0.0), !nan, (0.0 / 0.0) ? true : false,
113                nan ? true : false, (0.0 / 0.0) && true, nan && true,
114                (0.0 / 0.0) || false, nan || false, branch, !input]
115            }
116        ",
117        entry: "truth",
118        input_json: "0.0",
119        expected_json: "[false,false,true,true,true,true,true,true,true,true]",
120    },
121    PureCase {
122        id: "truthiness-duration-and-empty-values",
123        source: r"
124            fn truth(input: {zero: int, one: int, text: string, items: list<int>, record: dict<string, int>}) {
125              return [!0ms, !1ms, !input.zero, !input.one, !input.text, !input.items, !input.record,
126                !nil, !false, !true, ![], !({}), !0.0, !1.0]
127            }
128        ",
129        entry: "truth",
130        input_json: r#"{"zero":0,"one":1,"text":"","items":[],"record":{}}"#,
131        expected_json:
132            "[true,false,true,false,true,true,true,true,true,false,true,true,true,false]",
133    },
134    PureCase {
135        id: "runtime-string-repetition",
136        source: r#"
137            fn repeat(input: {text: string, count: int}) {
138              return [input.text * input.count, input.count * input.text, input.text * 0, input.text * -1, "" * input.count]
139            }
140        "#,
141        entry: "repeat",
142        input_json: r#"{"text":"λx","count":3}"#,
143        expected_json: r#"["λxλxλx","λxλxλx","","",""]"#,
144    },
145    PureCase {
146        id: "runtime-empty-string-repetition-with-huge-count",
147        source: r"fn repeat(input: {text: string, count: int}) { return input.text * input.count }",
148        entry: "repeat",
149        input_json: r#"{"text":"","count":9223372036854775807}"#,
150        expected_json: r#""""#,
151    },
152    PureCase {
153        id: "runtime-integer-exponent-promotes-beyond-u32",
154        source: r"fn power(input: int) { return [1 ** input, (-1) ** input, 2 ** -input] }",
155        entry: "power",
156        input_json: "4294967296",
157        expected_json: "[1.0,1.0,0.0]",
158    },
159    PureCase {
160        id: "runtime-float-integer-exponent-matches-folded-result",
161        source: r"
162            fn power(input: {base: float, exponent: int}) {
163              return [input.base ** input.exponent == 1.1 ** 7, input.base ** -input.exponent == 1.1 ** -7]
164            }
165        ",
166        entry: "power",
167        input_json: r#"{"base":1.1,"exponent":7}"#,
168        expected_json: "[true,true]",
169    },
170    PureCase {
171        id: "runtime-numeric-modulo-with-nonzero-divisors",
172        source: r"
173            fn modulo(input: {integer: int, floating: float}) {
174              return [input.integer % 3, input.integer % 2.5, input.floating % 3, input.floating % 2.5]
175            }
176        ",
177        entry: "modulo",
178        input_json: r#"{"integer":7,"floating":7.5}"#,
179        expected_json: "[1,2.0,1.5,0.0]",
180    },
181    PureCase {
182        id: "typed-record-pick-preserves-nil-and-copies-values",
183        source: r#"
184            type Input = {name: string, age: int, absent: nil, nested: {count: int}}
185            fn project(input: Input) -> {name: string, absent: nil, original: int, copied: int} {
186              let selected = pick(input, ["name", "absent", "nested", "name"])
187              selected.nested.count = 99
188              return {name: selected.name, absent: selected.absent, original: input.nested.count, copied: selected.nested.count}
189            }
190        "#,
191        entry: "project",
192        input_json: r#"{"name":"Ada","age":37,"absent":null,"nested":{"count":1}}"#,
193        expected_json: r#"{"name":"Ada","absent":null,"original":1,"copied":99}"#,
194    },
195    PureCase {
196        id: "typed-record-pick-runtime-keys-and-missing-values",
197        source: r"
198            fn project(input: {data: dict<string, int>, keys: list<string>}) -> dict<string, int> {
199              return pick(input.data, input.keys)
200            }
201        ",
202        entry: "project",
203        input_json: r#"{"data":{"a":1,"b":2},"keys":["b","missing","b"]}"#,
204        expected_json: r#"{"b":2}"#,
205    },
206    PureCase {
207        id: "typed-record-pick-empty",
208        source: r"fn project(input: {name: string}) -> {} { return pick(input, []) }",
209        entry: "project",
210        input_json: r#"{"name":"Ada"}"#,
211        expected_json: "{}",
212    },
213    PureCase {
214        id: "named-record-reducer",
215        source: r#"
216            type State = {count: int, history: list<int>}
217            type Event = {kind: string, amount: int}
218            type Input = {state: State, event: Event}
219
220            fn reduce(input: Input) -> State {
221              if input.event.kind == "reset" {
222                return {count: 0, history: input.state.history + [0]}
223              }
224              const next = input.state.count + input.event.amount
225              return {count: next, history: input.state.history + [next]}
226            }
227        "#,
228        entry: "reduce",
229        input_json: r#"{"state":{"count":2,"history":[1,2]},"event":{"kind":"increment","amount":3}}"#,
230        expected_json: r#"{"count":5,"history":[1,2,5]}"#,
231    },
232    PureCase {
233        id: "closure-capture-and-control-flow",
234        source: r"
235            type TransformInput = {value: int, offset: int, enabled: bool}
236            type TransformResult = {value: int, enabled: bool}
237            fn transform(input: TransformInput) -> TransformResult {
238              const offset = input.offset
239              const add_offset = {value -> value + offset}
240              if input.enabled {
241                return {value: add_offset(input.value), enabled: true}
242              }
243              return {value: input.value, enabled: false}
244            }
245        ",
246        entry: "transform",
247        input_json: r#"{"value":7,"offset":4,"enabled":true}"#,
248        expected_json: r#"{"enabled":true,"value":11}"#,
249    },
250    PureCase {
251        id: "empty-callback-preserves-pending-arguments",
252        source: r"
253            fn keep(value: int, ignored: nil) -> int { return value }
254            fn inspect(input: int) -> list<int> {
255              const empty = fn(_) {}
256              return [keep(input, empty(nil)), keep(input + 1, empty(nil))]
257            }
258        ",
259        entry: "inspect",
260        input_json: "41",
261        expected_json: "[41,42]",
262    },
263    PureCase {
264        id: "recursive-and-sibling-functions",
265        source: r"
266            fn fib(n: int) -> int {
267              if n <= 1 { return n }
268              return fib(n - 1) + fib(n - 2)
269            }
270            fn solve(input: int) -> int { return fib(input) }
271        ",
272        entry: "solve",
273        input_json: "7",
274        expected_json: "13",
275    },
276    PureCase {
277        id: "forward-declared-capturing-function",
278        source: r"
279            fn reduce(input: int) -> int {
280              const offset = 3
281              return add_offset(input)
282              fn add_offset(value: int) -> int { return value + offset }
283            }
284        ",
285        entry: "reduce",
286        input_json: "4",
287        expected_json: "7",
288    },
289    PureCase {
290        id: "typed-rest-and-sibling-call",
291        source: r"
292            fn collect(...values: int) -> list<int> { return values }
293            fn reduce(input: int) -> list<int> { return collect(input, 2) }
294        ",
295        entry: "reduce",
296        input_json: "7",
297        expected_json: "[7,2]",
298    },
299    PureCase {
300        id: "mutating-methods-rewrite-their-place",
301        source: r#"
302            type MutateInput = {items: list<int>, meta: dict<string, int>}
303            fn mutate(input: MutateInput) {
304              let items = input.items
305              const alias = items
306              items.push(4)
307              const last = items.pop()
308              items.insert(0, 0)
309              items.extend([9])
310              items.reverse()
311              let state = {stack: [1, 2], meta: input.meta}
312              const top = state.stack.pop()
313              const removed = state.meta.remove("a")
314              return {
315                items: items,
316                alias: alias,
317                last: last,
318                top: top,
319                removed: removed,
320                state: state,
321              }
322            }
323        "#,
324        entry: "mutate",
325        input_json: r#"{"items":[1,2,3],"meta":{"a":1,"b":2}}"#,
326        expected_json: r#"{"alias":[1,2,3],"items":[9,3,2,1,0],"last":4,"removed":1,"state":{"meta":{"b":2},"stack":[1]},"top":2}"#,
327    },
328    PureCase {
329        id: "list-string-and-record-operations",
330        source: r"
331            type SummaryInput = {
332              left: list<int>,
333              right: list<int>,
334              prefix: string,
335              name: string,
336              needle: int,
337              meta: dict<string, int>,
338            }
339            fn summarize(input: SummaryInput) {
340              return {
341                items: input.left + input.right,
342                title: input.prefix + input.name,
343                found: input.left.contains(input.needle),
344                fields: input.meta.len(),
345              }
346            }
347        ",
348        entry: "summarize",
349        input_json: r#"{"left":[1,2],"right":[3],"prefix":"Harn ","name":"Kernel","needle":2,"meta":{"a":1,"b":2}}"#,
350        expected_json: r#"{"fields":2,"found":true,"items":[1,2,3],"title":"Harn Kernel"}"#,
351    },
352    PureCase {
353        id: "list-ordering-runtime-and-constant-folding",
354        source: r"
355            type ListComparisonInput = {left: list<int>, right: list<int>}
356            fn compare_lists(input: ListComparisonInput) {
357              return {
358                runtime_less: input.left < input.right,
359                runtime_equal: input.left <= input.left,
360                constant_less: [1, 2] < [1, 3],
361                constant_greater: [2] > [1, 9],
362              }
363            }
364        ",
365        entry: "compare_lists",
366        input_json: r#"{"left":[1,2],"right":[1,3]}"#,
367        expected_json: r#"{"constant_greater":true,"constant_less":true,"runtime_equal":true,"runtime_less":true}"#,
368    },
369    PureCase {
370        id: "mixed-type-equality-is-structural-not-ordering",
371        source: r"
372            fn compare(input: {value: string}) {
373              return {
374                string_is_not_nil: input.value != nil,
375                string_is_not_int: input.value != 7,
376                nil_is_nil: nil == nil,
377                numeric_cross_kind: 1 == 1.0,
378              }
379            }
380        ",
381        entry: "compare",
382        input_json: r#"{"value":"ui://portable"}"#,
383        expected_json: r#"{"nil_is_nil":true,"numeric_cross_kind":true,"string_is_not_int":true,"string_is_not_nil":true}"#,
384    },
385    PureCase {
386        id: "structured-throw-catch",
387        source: r#"
388            fn validate(input: {value: int}) {
389              try {
390                if input.value < 0 {
391                  throw {code: "negative", value: input.value}
392                }
393                return {ok: true, value: input.value}
394              } catch error {
395                return {ok: false, value: error.value, code: error.code}
396              }
397            }
398        "#,
399        entry: "validate",
400        input_json: r#"{"value":-9}"#,
401        expected_json: r#"{"code":"negative","ok":false,"value":-9}"#,
402    },
403    PureCase {
404        id: "negative-index-and-slice",
405        source: r"
406            type ChoiceInput = {values: list<int>, text: string}
407            fn choose(input: ChoiceInput) {
408              return {
409                last: input.values[-1],
410                middle: input.values[-4:-1],
411                suffix: input.text[-3:],
412              }
413            }
414        ",
415        entry: "choose",
416        input_json: r#"{"values":[1,2,3,4,5],"text":"kernel"}"#,
417        expected_json: r#"{"last":5,"middle":[2,3,4],"suffix":"nel"}"#,
418    },
419    PureCase {
420        id: "module-capture-property-mutation",
421        source: r"
422            let state = {count: 0}
423            fn reduce(input: {count: int}) {
424              state.count = input.count
425              return {count: state.count}
426            }
427        ",
428        entry: "reduce",
429        input_json: r#"{"count":9}"#,
430        expected_json: r#"{"count":9}"#,
431    },
432    PureCase {
433        id: "iteration-and-copy-on-write-mutation",
434        source: r#"
435            type IterationState = {count: int, tags: list<string>}
436            type IterationInput = {state: IterationState, values: list<int>}
437            fn reduce(input: IterationInput) -> IterationState {
438              let state = input.state
439              for value in input.values {
440                state.count = state.count + value
441              }
442              state.tags[0] = "updated"
443              return state
444            }
445        "#,
446        entry: "reduce",
447        input_json: r#"{"state":{"count":1,"tags":["old"]},"values":[2,3,4]}"#,
448        expected_json: r#"{"count":10,"tags":["updated"]}"#,
449    },
450    PureCase {
451        id: "renderer-string-and-option-primitives",
452        source: r#"
453            type RenderInput = {name: string, validation?: dict<string, bool>}
454            fn reduce(input: RenderInput) {
455              const options = {allow_network: false}.merge(input.validation ?? {})
456              const name = trim(input.name)
457              return {
458                encoded: replace(json_stringify(name), "<", "\\u003c"),
459                portable: starts_with(name, "Portable"),
460                options: options,
461              }
462            }
463        "#,
464        entry: "reduce",
465        input_json: r#"{"name":"  Portable <Harn>  ","validation":{"allow_host_bridge":true}}"#,
466        expected_json: r#"{"encoded":"\"Portable \\u003cHarn>\"","options":{"allow_host_bridge":true,"allow_network":false},"portable":true}"#,
467    },
468    PureCase {
469        id: "artifact-regex-hash-and-secret-safety-primitives",
470        source: r#"
471            fn inspect(input: string) {
472              const captures = regex_captures("(?is)<body\\b([^>]*)>(.*?)</body>", input)
473              return {
474                body: captures[0].groups[1],
475                scripts: regex_match("(?is)<script\\b", input),
476                text: trim(regex_replace("(?is)<[^>]+>", " ", input)),
477                digest: sha256("abc"),
478                clean: len(secret_scan(input)) == 0,
479              }
480            }
481        "#,
482        entry: "inspect",
483        input_json: r#""<body class='app'>Portable <b>Harn</b></body>""#,
484        expected_json: r#"{"body":"Portable <b>Harn</b>","clean":true,"digest":"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad","scripts":null,"text":"Portable  Harn"}"#,
485    },
486    PureCase {
487        id: "target-independent-path-joining",
488        source: r#"
489            fn paths(input: {root: string}) {
490              return {
491                host: path_join(input.root, ".harn", "state.json"),
492                reset: path_join("ignored", "/absolute", "file"),
493              }
494            }
495        "#,
496        entry: "paths",
497        input_json: r#"{"root":"C:\\workspace"}"#,
498        expected_json: r#"{"host":"C:/workspace/.harn/state.json","reset":"/absolute/file"}"#,
499    },
500    PureCase {
501        id: "compiled-secret-pattern-catalog",
502        source: r#"
503            fn inspect(input: string) {
504              const catalog = secret_pattern_catalog()
505              let high_count = 0
506              let contextual = false
507              let detector = ""
508              let pattern = ""
509              for row in catalog {
510                if row.precision == "high" { high_count = high_count + 1 }
511                if row.precision == "heuristic" { contextual = true }
512                if row.detector == "aws-access-key-id" {
513                  detector = row.detector
514                  pattern = row.regex
515                }
516              }
517              if pattern == "" { throw "missing AWS detector" }
518              return {
519                measured: high_count >= 10,
520                contextual: contextual,
521                detector: detector,
522                accepted: regex_match(pattern, "AKIA" + input) != nil,
523                rejected: regex_match(pattern, "ordinary text") == nil,
524              }
525            }
526        "#,
527        entry: "inspect",
528        input_json: r#""ABCDEFGHIJKLMNOP""#,
529        expected_json: r#"{"accepted":true,"contextual":true,"detector":"aws-access-key-id","measured":true,"rejected":true}"#,
530    },
531    PureCase {
532        id: "result-enum-match-and-propagation",
533        source: r#"
534            fn divide(value: int, divisor: int) -> Result<int, string> {
535              if divisor == 0 { return Result.Err("division by zero") }
536              return Result.Ok(value / divisor)
537            }
538            fn halve(value: int, divisor: int) -> Result<int, string> {
539              const divided: int = divide(value, divisor)?
540              return Result.Ok(divided / 2)
541            }
542            fn reduce(input: int) {
543              const result = halve(12, input)
544              match result {
545                Result.Ok(value) -> { return [result.variant, result.fields, value] }
546                Result.Err(message) -> { return [result.variant, result.fields, message] }
547              }
548            }
549        "#,
550        entry: "reduce",
551        input_json: "3",
552        expected_json: r#"["Ok",[2],2]"#,
553    },
554    PureCase {
555        // Widening: a whole int satisfies a float parameter. This is the
556        // half of harn#6267 that payload schemas used to get wrong.
557        id: "float-param-accepts-int",
558        source: r"
559            fn takes_float(x: float) -> float { return x + 0.0 }
560            fn reduce(input: int) -> float { return takes_float(input) }
561        ",
562        entry: "reduce",
563        input_json: "3",
564        expected_json: "3.0",
565    },
566    PureCase {
567        // harn#9189: cleanup runs once for errors raised by a callee, not
568        // only for an inline `throw`. Runtime failures such as division by
569        // zero are terminal in the portable kernel, so only throws appear.
570        id: "cleanup-runs-once-for-callee-errors",
571        source: r#"
572            fn fail(message: string) -> int { throw message }
573            fn relay(message: string) -> int { return fail(message) + 1 }
574            fn reduce(input: list<string>) -> {finally_runs: int, defer_runs: int, caught: list<string>} {
575              let finally_runs = 0
576              let defer_runs = 0
577              let caught = []
578              for label in input {
579                try {
580                  defer { defer_runs = defer_runs + 1 }
581                  try {
582                    if label == "direct" {
583                      fail(label)
584                    } else {
585                      relay(label)
586                    }
587                  } finally {
588                    finally_runs = finally_runs + 1
589                  }
590                } catch (error) {
591                  caught = caught + [error]
592                }
593              }
594              return {finally_runs: finally_runs, defer_runs: defer_runs, caught: caught}
595            }
596        "#,
597        entry: "reduce",
598        input_json: r#"["direct","relayed"]"#,
599        expected_json: r#"{"finally_runs":2,"defer_runs":2,"caught":["direct","relayed"]}"#,
600    },
601    PureCase {
602        // harn#9201: `?` returns an `Err` through pending cleanup. The
603        // `finally` overrides the early return, so the result only reads
604        // `cleanup` when that cleanup ran.
605        id: "try-operator-runs-pending-finally",
606        source: r#"
607            fn check(value: int) -> Result<int, string> {
608              if value < 0 { return Result.Err("negative") }
609              return Result.Ok(value)
610            }
611            fn guarded(value: int) -> Result<int, string> {
612              try {
613                const checked = check(value)?
614                return Result.Ok(checked + 1)
615              } finally {
616                if value < 0 { return Result.Err("cleanup") }
617              }
618              return Result.Err("fell through")
619            }
620            fn reduce(input: list<int>) -> list<list<any>> {
621              let rendered = []
622              for value in input {
623                const result = guarded(value)
624                rendered = rendered + [[result.variant, result.fields]]
625              }
626              return rendered
627            }
628        "#,
629        entry: "reduce",
630        input_json: "[-1,4]",
631        expected_json: r#"[["Err",["cleanup"]],["Ok",[5]]]"#,
632    },
633];
634
635/// Runtime failures that every portable executor must agree on.
636///
637/// Unlike [`PURE_CASES`], these are expected to fail after a successful
638/// compile. The int←float case is the drift that used to slip past
639/// `browser_worker_matches_native_portable_corpus_exactly` (harn#6267).
640pub struct RuntimeFailureCase {
641    pub id: &'static str,
642    pub source: &'static str,
643    pub entry: &'static str,
644    pub input_json: &'static str,
645    pub expected_code: &'static str,
646}
647
648pub const RUNTIME_FAILURE_CASES: &[RuntimeFailureCase] = &[
649    RuntimeFailureCase {
650        id: "catch-cannot-bypass-a-value-limit",
651        source: r#"fn repeat(input: string) { try { return input * 1048577 } catch (_) { return "caught" } }"#,
652        entry: "repeat",
653        input_json: r#""x""#,
654        expected_code: "value_byte_limit",
655    },
656    RuntimeFailureCase {
657        id: "string-repetition-rejects-output-over-byte-limit",
658        source: r"fn repeat(input: {text: string, count: int}) { return input.text * input.count }",
659        entry: "repeat",
660        input_json: r#"{"text":"ab","count":524289}"#,
661        expected_code: "value_byte_limit",
662    },
663    RuntimeFailureCase {
664        id: "string-repetition-rejects-overflowing-output-length",
665        source: r"fn repeat(input: {text: string, count: int}) { return input.count * input.text }",
666        entry: "repeat",
667        input_json: r#"{"text":"abc","count":9223372036854775807}"#,
668        expected_code: "value_byte_limit",
669    },
670    RuntimeFailureCase {
671        id: "integer-modulo-by-integer-zero",
672        source: r"fn modulo(input: {left: int, right: int}) { return input.left % input.right }",
673        entry: "modulo",
674        input_json: r#"{"left":7,"right":0}"#,
675        expected_code: "division_by_zero",
676    },
677    RuntimeFailureCase {
678        id: "float-modulo-by-integer-zero",
679        source: r"fn modulo(input: {left: float, right: int}) { return input.left % input.right }",
680        entry: "modulo",
681        input_json: r#"{"left":7.5,"right":0}"#,
682        expected_code: "division_by_zero",
683    },
684    RuntimeFailureCase {
685        id: "integer-modulo-by-float-zero",
686        source: r"fn modulo(input: {left: int, right: float}) { return input.left % input.right }",
687        entry: "modulo",
688        input_json: r#"{"left":7,"right":0.0}"#,
689        expected_code: "division_by_zero",
690    },
691    RuntimeFailureCase {
692        id: "float-modulo-by-negative-float-zero",
693        source: r"fn modulo(input: {left: float, right: float}) { return input.left % input.right }",
694        entry: "modulo",
695        input_json: r#"{"left":7.5,"right":-0.0}"#,
696        expected_code: "division_by_zero",
697    },
698    RuntimeFailureCase {
699        id: "declared-error-survives-transparent-rethrows",
700        source: r"
701            fn fail(input: int) -> any throws int { throw input }
702            fn reduce(input: int) -> any throws int {
703                try { return retry 2 { try* fail(input) } }
704                finally { try { throw 8 } catch (_ignored) {} }
705            }
706        ",
707        entry: "reduce",
708        input_json: "7",
709        expected_code: "harn_declared_throw",
710    },
711    RuntimeFailureCase {
712        id: "legacy-error-stays-runtime-under-declared-wrapper",
713        source: r"
714            fn fail(input: int) -> any { throw input }
715            fn reduce(input: int) -> any throws int {
716                try { return retry 2 { try* fail(input) } }
717                finally { try { throw 8 } catch (_ignored) {} }
718            }
719        ",
720        entry: "reduce",
721        input_json: "7",
722        expected_code: "harn_throw",
723    },
724    RuntimeFailureCase {
725        id: "pick-rejects-non-record-source",
726        source: r#"fn project(input: any) { return pick(input, ["name"]) }"#,
727        entry: "project",
728        input_json: "42",
729        expected_code: "builtin_type",
730    },
731    RuntimeFailureCase {
732        id: "pick-rejects-non-string-key",
733        source: r"fn project(input: {name: string, keys: list<any>}) { return pick(input, input.keys) }",
734        entry: "project",
735        input_json: r#"{"name":"Ada","keys":[1]}"#,
736        expected_code: "builtin_type",
737    },
738    RuntimeFailureCase {
739        id: "pick-rejects-wrong-arity",
740        source: r"fn project(args: list<any>) { return pick(...args) }",
741        entry: "project",
742        input_json: r#"[{"name":"Ada"}]"#,
743        expected_code: "builtin_type",
744    },
745    RuntimeFailureCase {
746        id: "int-param-rejects-float",
747        source: r"
748            fn takes_int(n: int) -> int { return n }
749            // Deliberate unchecked host boundary: the failure belongs to the
750            // portable runtime parameter contract.
751            fn reduce(input: any) { return takes_int(input) }
752        ",
753        entry: "reduce",
754        input_json: "2.5",
755        expected_code: "argument_type",
756    },
757];
758
759pub struct InvalidCase {
760    pub id: &'static str,
761    pub source: &'static str,
762    pub entry: &'static str,
763    pub expected_code: &'static str,
764}
765
766pub const INVALID_CASES: &[InvalidCase] = &[
767    InvalidCase {
768        id: "pick-unknown-field",
769        source: r#"fn project(input: {name: string}) { return pick(input, ["nmae"]) }"#,
770        entry: "project",
771        expected_code: "compile_frontend",
772    },
773    InvalidCase {
774        id: "pick-dynamic-fields-are-not-required",
775        source: r"fn project(input: {name: string}, keys: list<string>) -> {name: string} { return pick(input, keys) }",
776        entry: "project",
777        expected_code: "compile_frontend",
778    },
779    InvalidCase {
780        id: "frontend-syntax-error",
781        source: "fn reduce( {",
782        entry: "reduce",
783        expected_code: "compile_frontend",
784    },
785    InvalidCase {
786        id: "invalid-mutable-local-program",
787        source: r"
788            fn reduce(input) {
789              var value = input
790              value = value + 1
791              return value
792            }
793        ",
794        entry: "reduce",
795        expected_code: "compile_frontend",
796    },
797];
798
799#[derive(Clone, Copy)]
800pub struct PackageCompilationCase {
801    pub id: &'static str,
802    pub source: &'static str,
803    pub entry: &'static str,
804    pub expected_ok: bool,
805}
806
807impl PackageCompilationCase {
808    pub fn package(&self) -> harn_kernel::PortableSourcePackage {
809        harn_kernel::PortableSourcePackage {
810            root_source: self.source.to_string(),
811            root_imports: Vec::new(),
812            modules: Vec::new(),
813        }
814    }
815
816    pub fn compile(&self) -> Result<harn_kernel::ProgramArtifact, Vec<harn_kernel::Diagnostic>> {
817        let result = harn_kernel::compile_source_package(
818            self.package(),
819            self.entry,
820            harn_kernel::EntryKind::Function,
821        );
822        assert_eq!(
823            result.is_ok(),
824            self.expected_ok,
825            "{} compilation decision drifted",
826            self.id
827        );
828        if let Err(diagnostics) = &result {
829            assert!(
830                !diagnostics.is_empty(),
831                "{} has no failure diagnostic",
832                self.id
833            );
834        }
835        result
836    }
837}
838
839pub fn package_compilation_cases() -> impl Iterator<Item = PackageCompilationCase> {
840    INVALID_CASES
841        .iter()
842        .map(|case| PackageCompilationCase {
843            id: case.id,
844            source: case.source,
845            entry: case.entry,
846            expected_ok: false,
847        })
848        .chain(PACKAGE_COMPILATION_CASES.iter().copied())
849}
850
851pub const PACKAGE_COMPILATION_CASES: &[PackageCompilationCase] = &[
852    PackageCompilationCase {
853        id: "removed-provider-wrapper-alias",
854        source: "fn reduce(input: string) { return with_rate_limit(input) }",
855        entry: "reduce",
856        expected_ok: false,
857    },
858    PackageCompilationCase {
859        id: "retained-provider-call-alias",
860        source: "fn reduce(input: string) { return llm_call(input) }",
861        entry: "reduce",
862        expected_ok: true,
863    },
864    PackageCompilationCase {
865        id: "retained-provider-call-method",
866        source: "fn reduce(harness: Harness, input: string) { return harness.llm.call(input) }",
867        entry: "reduce",
868        expected_ok: true,
869    },
870];