/// The differential fuzzer's program generator (issue #352; see /// fuzz/README.md): draws a small, deterministic, well-typed Louise /// program from LOUISE_FUZZ_SEED and prints it. /// crates/louise_codegen_c/tests/fuzz.rs runs each program interpreted /// and natively and compares stdout, exit code and the leak oracle. /// /// Generated programs are deterministic: every random choice happens /// here, at generation time (the one exception reaches `std/random` /// through `random.with_seed`, which is deterministic too). They /// terminate by construction: recursion decreases an Int bounded at the /// call site, and list sizes are bounded. import gen import std/io import std/list import std/os import std/random.{type random} import std/ref.{type Ref, type st} import std/result import std/string /// The types expressions are generated at. `TChoice` is the program's /// generated enum and `TRec` its generated record; a program declares /// them at the top when it uses them. type Ty { TInt, TBool, TString, TList(Ty), TOpt(Ty), TPair(Ty, Ty), TChoice, TRec } /// Generation state: a fresh-name counter, the imports the program /// needs, and the declarations, helpers and effects its statements and /// expressions may use. type Ctx { Ctx( ctr: Ref , imports: Ref> , helpers: Ref, Ty)>> , decls: Ref> , effects: Ref> , handler_fns: Ref> , recursive: Ref> , fields: List<(String, Ty)> , choice: Bool ) } fn fresh :: c: Ctx prefix: String -> String / > { let n = ref.get c.ctr ref.set c.ctr (n + 1) prefix <> show n } /// Records that the program must import `module`. fn need :: c: Ctx module: String -> () / > { if list.any (ref.get c.imports) fn m { m == module } { () } else { ref.set c.imports [module, ..ref.get c.imports] } } fn ty_src :: ty: Ty -> String { match ty { TInt -> "Int" , TBool -> "Bool" , TString -> "String" , TList(t) -> "List<" <> ty_src t <> ">" , TOpt(t) -> "Option<" <> ty_src t <> ">" , TPair(a, b) -> "(" <> ty_src a <> ", " <> ty_src b <> ")" , TChoice -> "Choice" , TRec -> "R" } } fn ty_eq :: a: Ty b: Ty -> Bool { match (a, b) { (TInt, TInt) -> True , (TBool, TBool) -> True , (TString, TString) -> True , (TChoice, TChoice) -> True , (TRec, TRec) -> True , (TList(x), TList(y)) -> ty_eq x y , (TOpt(x), TOpt(y)) -> ty_eq x y , (TPair(x1, y1), TPair(x2, y2)) -> ty_eq x1 x2 && ty_eq y1 y2 , _ -> False } } /// Whether the generated program may `show` a value of `ty`: the /// generated `Choice` and `R` derive nothing. fn showable :: ty: Ty -> Bool { match ty { TChoice -> False, TRec -> False, _ -> True } } /// A scalar type: Int, Bool or String. fn scalar :: -> Ty / { gen.weighted [(4, TInt), (2, TBool), (2, TString)] } /// A type for a `let`; compound types hold scalars, so programs stay /// small. fn any_ty :: c: Ctx -> Ty / { let compound = [ (3, TList(TInt)) , (2, TList(TString)) , (1, TOpt(TInt)) , (1, TPair(TInt, TString)) ] let user = list.append (if c.choice { [(2, TChoice)] } else { [] }) (if list.length c.fields == 0 { [] } else { [(2, TRec)] }) gen.weighted ( list.append [(5, TInt), (2, TBool), (2, TString)] (list.append compound user) ) } /// The names in `env` with type `ty`. fn vars_of :: env: List<(String, Ty)> ty: Ty -> List { list.map (list.filter env fn v { ty_eq v.1 ty }) fn v { v.0 } } /// `text`, an expression of type `ty`, made to pin `ty` down in the /// source: a bare `[]` or `None` leaves the element type unknown /// (E0403 where a trait needs it), so it becomes a one-element literal. fn pin :: c: Ctx ty: Ty text: String -> String / , random> { match ty { TList ( t ) -> if string.contains text "[]" { "[" <> literal c t <> "]" } else { text } , TOpt ( t ) -> if string.contains text "None" { "Some(" <> literal c t <> ")" } else { text } , _ -> text } } /// A string literal of lowercase letters (no escapes needed). fn word :: -> String / { "\"" <> gen.string ~alphabet: (gen.lower ()) ~min: 1 ~max: 8 <> "\"" } fn literal :: c: Ctx ty: Ty -> String / , random> { match ty { TInt -> show (gen.int ~low: (0 - 20) ~high: 99) , TBool -> if gen.bool () { "True" } else { "False" } , TString -> word () , TList(t) -> list_lit c t , TOpt(t) -> if gen.bool () { "None" } else { "Some(" <> literal c t <> ")" } , TPair(a, b) -> "(" <> literal c a <> ", " <> literal c b <> ")" , TChoice -> choice_lit () , TRec -> rec_lit c } } fn list_lit :: c: Ctx t: Ty -> String / , random> { let n = gen.int ~low: 0 ~high: 3 "[" <> string.join (list.map (list.range 1 n) fn _ { literal c t }) ", " <> "]" } fn choice_lit :: -> String / { match gen.int ~low: 0 ~high: 2 { 0 -> "A" , 1 -> "B(" <> show (gen.int ~low: 0 ~high: 9) <> ")" , _ -> "C(" <> word () <> ")" } } fn rec_lit :: c: Ctx -> String / , random> { "R(" <> string.join (list.map c.fields fn f { f.0 <> ": " <> literal c f.1 }) ", " <> ")" } /// Flatten lists of lines. fn concat :: xss: List> -> List { list.flat_map xss fn xs { xs } } // --- Expressions ------------------------------------------------------- /// An expression of type `ty`; `depth` bounds its size. Expressions are /// pure: effects happen in statements, so a value can travel anywhere. fn expr :: c: Ctx env: List<(String, Ty)> ty: Ty depth: Int -> String / , random> { let vars = vars_of env ty if depth <= 0 { match vars { [] -> literal c ty , _ -> gen.weighted [(1, literal c ty), (3, gen.pick vars)] } } else { match gen.weighted (expr_choices c env ty) { 0 -> literal c ty , 1 -> if_expr c env ty depth , 2 -> match_expr c env ty depth , 3 -> gen.pick vars , 4 -> call c env ty depth , 5 -> gen.pick (projectable env ty) , 6 -> gen.pick (fieldable c env ty) , tag -> typed_expr c env ty depth tag } } } /// (weight, tag) choices for `expr`; tags below 10 are generic, the /// rest are per type (`typed_expr`). fn expr_choices :: c: Ctx env: List<(String, Ty)> ty: Ty -> List<(Int, Int)> / > { let base = [(1, 0), (2, 1), (2, 2)] let with_var = match vars_of env ty { [] -> base, _ -> [(3, 3), ..base] } let with_call = match helpers_to c ty { [] -> with_var, _ -> [(2, 4), ..with_var] } let with_proj = match projectable env ty { [] -> with_call, _ -> [(1, 5), ..with_call] } let with_field = match fieldable c env ty { [] -> with_proj, _ -> [(1, 6), ..with_proj] } list.append with_field (typed_choices c env ty) } /// The helpers whose result type is `ty`: (name, parameter types, /// result type). fn helpers_to :: c: Ctx ty: Ty -> List<(String, List, Ty)> / > { list.filter (ref.get c.helpers) fn h { ty_eq h.2 ty } } /// Projections of `ty` out of pairs in scope: "v.0" / "v.1". fn projectable :: env: List<(String, Ty)> ty: Ty -> List { list.flat_map env fn v { match v.1 { TPair(a, b) -> list.append (if ty_eq a ty { [v.0 <> ".0"] } else { [] }) (if ty_eq b ty { [v.0 <> ".1"] } else { [] }) , _ -> [] } } } /// Field accesses of `ty` on records in scope: "v.a". fn fieldable :: c: Ctx env: List<(String, Ty)> ty: Ty -> List { list.flat_map env fn v { match v.1 { TRec -> list.map (list.filter c.fields fn f { ty_eq f.1 ty }) fn f { v.0 <> "." <> f.0 } , _ -> [] } } } /// The per-type (weight, tag) choices. fn typed_choices :: c: Ctx env: List<(String, Ty)> ty: Ty -> List<(Int, Int)> { match ty { TInt -> [(3, 10), (1, 11), (1, 12), (1, 13), (1, 14)] , TBool -> [(3, 10), (1, 11), (1, 12), (1, 13)] , TString -> [(3, 10), (1, 11), (2, 12)] , TList(t) -> list.append [(2, 10), (2, 11), (2, 12), (1, 13), (1, 14), (1, 15), (1, 16), (1, 17)] (if ty_eq t TInt { [(1, 18)] } else { [] }) , TOpt(_) -> [(2, 10)] , TPair(_, _) -> [(2, 10)] , TChoice -> [(2, 10)] , TRec -> match list.find env fn v { ty_eq v.1 TRec } { None -> [(2, 10)], Some(_) -> [(2, 10), (1, 11)] } } } /// A tag of `typed_choices`: an expression of `ty` specific to `ty`. fn typed_expr :: c: Ctx env: List<(String, Ty)> ty: Ty depth: Int tag: Int -> String / , random> { let at = fn t { expr c env t (depth - 1) } match ty { TInt -> match tag { 10 -> "(" <> at TInt <> " " <> gen.pick ["+", "-", "*"] <> " " <> at TInt <> ")" , 11 -> // Division and remainder panic on zero; usually the divisor is // kept nonzero, sometimes it is not (the panic path is part of // the oracle). { let divisor = gen.weighted [(7, "((" <> at TInt <> " % 5) + 6)"), (3, at TInt)] "(" <> at TInt <> " " <> gen.pick ["/", "%"] <> " " <> divisor <> ")" } , 12 -> { need c "std/list" let u = scalar () "list.length (" <> pin c (TList(u)) (at (TList(u))) <> ")" } , 13 -> { need c "std/string" "string.length (" <> at TString <> ")" } , _ -> { need c "std/list" "list.fold (" <> pin c (TList(TInt)) (at (TList(TInt))) <> ") 0 fn a x \{ a + x \}" } } , TBool -> match tag { 10 -> "(" <> at TInt <> " " <> gen.pick ["<", "<=", ">", ">=", "==", "!="] <> " " <> at TInt <> ")" , 11 -> "(" <> at TString <> " == " <> at TString <> ")" , 12 -> "(" <> at TBool <> " == " <> at TBool <> ")" , _ -> { need c "std/list" let u = scalar () let x = fresh c "x" "list.any (" <> pin c (TList(u)) (at (TList(u))) <> ") fn " <> x <> " \{ " <> expr c [(x, u), ..env] TBool (depth - 1) <> " \}" } } , TString -> match tag { 10 -> "(" <> at TString <> " <> " <> at TString <> ")" , 11 -> match vars_of env TInt { [] -> "(" <> at TString <> " <> " <> at TString <> ")" , vars -> "\"" <> gen.string ~alphabet: (gen.lower ()) ~min: 0 ~max: 4 <> "\{" <> gen.pick vars <> "\}" <> gen.string ~alphabet: (gen.lower ()) ~min: 0 ~max: 4 <> "\"" } , _ -> { let t = showable_ty () let arg = match vars_of env t { [] -> pin c t (literal c t) , vars -> gen.weighted [(2, gen.pick vars), (1, pin c t (literal c t))] } "show (" <> arg <> ")" } } , TList(t) -> { need c "std/list" match tag { 10 -> { let n = gen.int ~low: 0 ~high: 3 "[" <> string.join (list.map (list.range 1 n) fn _ { at t }) ", " <> "]" } , 11 -> "[" <> at t <> ", .." <> at (TList(t)) <> "]" , 12 -> { let u = scalar () let x = fresh c "x" "list.map (" <> pin c (TList(u)) (at (TList(u))) <> ") fn " <> x <> " \{ " <> expr c [(x, u), ..env] t (depth - 1) <> " \}" } , 13 -> { let x = fresh c "x" "list.filter (" <> pin c (TList(t)) (at (TList(t))) <> ") fn " <> x <> " \{ " <> expr c [(x, t), ..env] TBool (depth - 1) <> " \}" } , 14 -> "list.append (" <> pin c (TList(t)) (at (TList(t))) <> ") (" <> pin c (TList(t)) (at (TList(t))) <> ")" , 15 -> "list.reverse (" <> pin c (TList(t)) (at (TList(t))) <> ")" , 16 -> "list.take (" <> pin c (TList(t)) (at (TList(t))) <> ") (" <> at TInt <> ")" , 17 -> "list.drop (" <> pin c (TList(t)) (at (TList(t))) <> ") (" <> at TInt <> ")" , _ -> "list.range 1 ((" <> at TInt <> " % 5) + 1)" } } , TOpt(t) -> "Some(" <> at t <> ")" , TPair(a, b) -> "(" <> at a <> ", " <> at b <> ")" , TChoice -> match gen.int ~low: 0 ~high: 2 { 0 -> "A", 1 -> "B(" <> at TInt <> ")", _ -> "C(" <> at TString <> ")" } , TRec -> if tag == 11 { match list.find env fn v { ty_eq v.1 TRec } { None -> rec_lit c , Some(v) -> { let f = gen.pick c.fields "R(.." <> v.0 <> ", " <> f.0 <> ": " <> expr c env f.1 (depth - 1) <> ")" } } } else { "R(" <> string.join (list.map c.fields fn f { f.0 <> ": " <> expr c env f.1 (depth - 1) }) ", " <> ")" } } } /// A showable type, for `show`. fn showable_ty :: -> Ty / { gen.weighted [ (3, TInt) , (2, TBool) , (1, TList(TInt)) , (1, TOpt(TInt)) , (1, TPair(TInt, TString)) ] } fn if_expr :: c: Ctx env: List<(String, Ty)> ty: Ty depth: Int -> String / , random> { "if " <> expr c env TBool (depth - 1) <> " \{ " <> expr c env ty (depth - 1) <> " \} else \{ " <> expr c env ty (depth - 1) <> " \}" } /// A single-line `match` expression of type `ty`. fn match_expr :: c: Ctx env: List<(String, Ty)> ty: Ty depth: Int -> String / , random> { let kinds = list.append [(2, "opt"), (2, "list"), (1, "int")] ( list.append (if c.choice { [(2, "choice")] } else { [] }) (if list.length c.fields == 0 { [] } else { [(1, "rec")] }) ) let at = fn t { expr c env t (depth - 1) } match gen.weighted kinds { "opt" -> { let u = scalar () let x = fresh c "m" "match " <> pin c (TOpt(u)) (at (TOpt(u))) <> " \{ None -> " <> at ty <> ", Some(" <> x <> ") -> " <> expr c [(x, u), ..env] ty (depth - 1) <> " \}" } , "list" -> { let u = scalar () let x = fresh c "m" let rest = fresh c "m" "match " <> pin c (TList(u)) (at (TList(u))) <> " \{ [] -> " <> at ty <> ", [" <> x <> ", .." <> rest <> "] -> " <> expr c [(x, u), (rest, TList(u)), ..env] ty (depth - 1) <> " \}" } , "choice" -> { let n = fresh c "m" let s = fresh c "m" "match " <> at TChoice <> " \{ A -> " <> at ty <> ", B(" <> n <> ") -> " <> expr c [(n, TInt), ..env] ty (depth - 1) <> ", C(" <> s <> ") -> " <> expr c [(s, TString), ..env] ty (depth - 1) <> " \}" } , "rec" -> { let names = list.map c.fields fn _ { fresh c "m" } let binds = list.zip names (list.map c.fields fn f { f.1 }) "match " <> at TRec <> " \{ R(" <> string.join names ", " <> ") -> " <> expr c (list.append binds env) ty (depth - 1) <> " \}" } , _ -> "match " <> at TInt <> " \{ 0 -> " <> at ty <> ", _ if " <> expr c env TBool (depth - 1) <> " -> " <> at ty <> ", _ -> " <> at ty <> " \}" } } /// A call of a helper returning `ty`. Recursive helpers take Int, and /// their argument is clamped so the recursion is short. fn call :: c: Ctx env: List<(String, Ty)> ty: Ty depth: Int -> String / , random> { let h = gen.pick (helpers_to c ty) let args = list.map h.1 fn p { if ty_eq h.2 TInt && ty_eq p TInt && is_recursive c h.0 { "((" <> expr c env TInt (depth - 1) <> " % 7))" } else { expr c env p (depth - 1) } } "(" <> h.0 <> " " <> string.join (list.map args fn a { "(" <> a <> ")" }) " " <> ")" } /// Whether `name` is a recursive helper (its argument is clamped at /// call sites). fn is_recursive :: c: Ctx name: String -> Bool / > { list.any (ref.get c.recursive) fn n { n == name } } // --- Statements -------------------------------------------------------- /// `count` statements at `indent`, extending `env` with what they /// bind. Returns the lines and the extended environment. fn stmts :: c: Ctx env: List<(String, Ty)> depth: Int indent: String count: Int -> (List, List<(String, Ty)>) / , random> { if count <= 0 { ([], env) } else { let (first, env2) = stmt c env depth indent let (rest, env3) = stmts c env2 depth indent (count - 1) (list.append first rest, env3) } } fn stmt :: c: Ctx env: List<(String, Ty)> depth: Int indent: String -> (List, List<(String, Ty)>) / , random> { let choices = if depth > 0 { [(4, 0), (3, 1), (2, 2), (1, 3), (2, 4), (1, 5), (2, 6), (1, 7), (1, 8)] } else { [(4, 0), (3, 1), (2, 4)] } match gen.weighted choices { 0 -> { let ty = any_ty c let name = fresh c "v" ( [ indent <> "let " <> name <> ": " <> ty_src ty <> " = " <> expr c env ty 2 ] , [(name, ty), ..env] ) } , 1 -> ([indent <> "io.println (" <> expr c env TString 2 <> ")"], env) , 2 -> { let cond = expr c env TBool 1 let (then_ls, _) = stmts c env (depth - 1) (indent <> " ") (gen.int ~low: 1 ~high: 2) let (else_ls, _) = stmts c env (depth - 1) (indent <> " ") (gen.int ~low: 1 ~high: 2) ( concat [ [indent <> "if " <> cond, indent <> "\{"] , then_ls , [indent <> "\}", indent <> "else", indent <> "\{"] , else_ls , [indent <> "\}"] ] , env ) } , 3 -> (match_stmt c env (depth - 1) indent, env) , 4 -> { let d = fresh c "d" ([indent <> "defer io.println \"" <> d <> "\""], env) } , 5 -> (region_stmt c env indent, env) , 6 -> handle_stmt c env indent , 7 -> ( [ indent <> "io.println (match " <> try_decl c <> " () \{ Ok(v) -> \"ok \" <> show v, Error(e) -> \"err \" <> e \})" ] , env ) , _ -> { need c "std/random" let v = fresh c "v" ( [ indent <> "let " <> v <> " = random.with_seed " <> show (gen.int ~low: 1 ~high: 1000) <> " fn \{ random.range 1 6 + random.range 1 6 \}" , indent <> "io.println (show " <> v <> ")" ] , env ) } } } /// A `match` statement whose arms print. fn match_stmt :: c: Ctx env: List<(String, Ty)> depth: Int indent: String -> List / , random> { let kinds = list.append [(2, "opt"), (2, "list"), (1, "int")] (if c.choice { [(2, "choice")] } else { [] }) match gen.weighted kinds { "opt" -> { let u = scalar () let x = fresh c "m" [ indent <> "match " <> pin c (TOpt(u)) (expr c env (TOpt(u)) depth) , indent <> "\{ None -> io.println \"none\"" , indent <> ", Some(" <> x <> ") -> io.println (\"some \" <> show " <> x <> ")" , indent <> "\}" ] } , "list" -> { let u = scalar () let x = fresh c "m" [ indent <> "match " <> pin c (TList(u)) (expr c env (TList(u)) depth) , indent <> "\{ [] -> io.println \"empty\"" , indent <> ", [" <> x <> ", ..] -> io.println (\"head \" <> show " <> x <> ")" , indent <> "\}" ] } , "choice" -> { let n = fresh c "m" let s = fresh c "m" [ indent <> "match " <> expr c env TChoice depth , indent <> "\{ A -> io.println \"ca\"" , indent <> ", B(" <> n <> ") -> io.println (\"cb \" <> show " <> n <> ")" , indent <> ", C(" <> s <> ") -> io.println (\"cc \" <> " <> s <> ")" , indent <> "\}" ] } , _ -> [ indent <> "match " <> expr c env TInt depth , indent <> "\{ 0 -> io.println \"zero\"" , indent <> ", _ -> io.println (\"other \" <> show (" <> expr c env TInt depth <> "))" , indent <> "\}" ] } } /// A `region` with a reference: ends by reading it (an Int), or uses /// `use n <- ref.update` for the update-in-the-rest form. fn region_stmt :: c: Ctx env: List<(String, Ty)> indent: String -> List / , random> { need c "std/ref" let rx = fresh c "rx" let inner = indent <> " " if gen.bool () { let v = fresh c "v" [ indent <> "let " <> v <> " = region" , indent <> "\{" , inner <> "let " <> rx <> " = ref.new " <> show (gen.int ~low: 0 ~high: 20) , inner <> "ref.set " <> rx <> " (ref.get " <> rx <> " + " <> expr c env TInt 1 <> ")" , inner <> "ref.get " <> rx , indent <> "\}" , indent <> "io.println (show " <> v <> ")" ] } else { [ indent <> "region" , indent <> "\{" , inner <> "let " <> rx <> " = ref.new " <> show (gen.int ~low: 0 ~high: 20) , inner <> "use n <- ref.update " <> rx , inner <> "io.println (\"upd \" <> show n)" , inner <> "n + (" <> expr c env TInt 1 <> ")" , indent <> "\}" ] } } /// The effect named for `kind`, declaring it first if need be; at most /// two effects per program ("", "" when the budget is spent). fn effect_for :: c: Ctx kind: String -> (String, String) / > { match list.find (ref.get c.effects) fn e { e.0 == kind } { Some(e) -> (e.1, e.2) , None -> if list.length (ref.get c.effects) >= 2 { ("", "") } else { let k = list.length (ref.get c.effects) let en = "F" <> show k let on = "op" <> show k ref.set c.effects [(kind, en, on), ..ref.get c.effects] (en, on) } } } /// A `handle` statement: one of the effect templates (issue #352's /// "effects + handlers"). fn handle_stmt :: c: Ctx env: List<(String, Ty)> indent: String -> (List, List<(String, Ty)>) / , random> { let inner = indent <> " " match gen.weighted [(3, "ask"), (2, "collect"), (1, "cancel"), (2, "fail"), (1, "install")] { "ask" -> match effect_for c "ask" { ("", _) -> ([indent <> "io.println " <> word ()], env) , (_, on) -> { let v = fresh c "v" ( [ indent <> "let " <> v <> " = handle" , indent <> "\{" , inner <> on <> " () + (" <> expr c env TInt 1 <> ")" , indent <> "\}" , indent <> "with" , indent <> "\{ " <> on <> " -> " <> show (gen.int ~low: 20 ~high: 60) <> " \}" , indent <> "io.println (show " <> v <> ")" ] , env ) } } , "collect" -> match effect_for c "yield" { ("", _) -> ([indent <> "io.println " <> word ()], env) , (_, on) -> { let v = fresh c "v" let yields = list.map (list.range 1 (gen.int ~low: 1 ~high: 3)) fn _ { inner <> on <> " (" <> expr c env TInt 1 <> ")" } ( concat [ [indent <> "let " <> v <> " = handle", indent <> "\{"] , yields , [ indent <> "\}" , indent <> "with" , indent <> "\{ " <> on <> " x -> [x, ..resume ()], return _ -> [] \}" , indent <> "io.println (show " <> v <> ")" ] ] , env ) } } , "cancel" -> match effect_for c "yield" { ("", _) -> ([indent <> "io.println " <> word ()], env) , (_, on) -> { let v = fresh c "v" ( [ indent <> "let " <> v <> " = handle" , indent <> "\{" , inner <> "defer io.println \"cgone\"" , inner <> on <> " (" <> expr c env TInt 1 <> ")" , inner <> on <> " (" <> expr c env TInt 1 <> ")" , indent <> "\}" , indent <> "with" , indent <> "\{ " <> on <> " x -> x, return _ -> 0 - 1 \}" , indent <> "io.println (show " <> v <> ")" ] , env ) } } , "fail" -> match effect_for c "fail" { ("", _) -> ([indent <> "io.println " <> word ()], env) , (_, on) -> { let v = fresh c "v" ( [ indent <> "let " <> v <> ": Result = handle" , indent <> "\{" , inner <> "Ok(if " <> expr c env TBool 1 <> " \{ " <> on <> " \"f" <> show (gen.int ~low: 0 ~high: 9) <> "\" \} else \{ " <> expr c env TInt 1 <> " \})" , indent <> "\}" , indent <> "with" , indent <> "\{ " <> on <> " r -> Error(r) \}" , indent <> "io.println (match " <> v <> " \{ Ok(x) -> \"ok \" <> show x, Error(e) -> \"err \" <> e \})" ] , env ) } } , _ -> // `use <- h` installs the ask effect's handler for the rest of // the block. match effect_for c "ask" { ("", _) -> ([indent <> "io.println " <> word ()], env) , (en, on) -> { let hn = handler_fn c en on ( [ indent <> "\{" , inner <> "use <- " <> hn , inner <> "io.println (show (" <> on <> " () + (" <> expr c env TInt 1 <> ")))" , indent <> "\}" ] , env ) } } } } /// The handler-installing function for the ask effect `en` (declared /// once): `fn h0 :: action: fn() -> a / -> a / `. fn handler_fn :: c: Ctx en: String on: String -> String / , random> { let hn = "h" <> string.slice en 1 (string.length en) if list.any (ref.get c.handler_fns) fn h { h == en } { hn } else { ref.set c.handler_fns [en, ..ref.get c.handler_fns] ref.set c.decls [ ..ref.get c.decls , "fn " <> hn <> " :: action: fn() -> a / <" <> en <> " | e> -> a / " , "\{ handle" , " \{ action () \}" , " with" , " \{ " <> on <> " -> " <> show (gen.int ~low: 1 ~high: 40) <> " \}" , "\}" ] hn } } /// A `use x <- result.try` helper (declared) and its name. fn try_decl :: c: Ctx -> String / , random> { need c "std/result" need c "std/string" let t = fresh c "t" let digits = fn { if gen.weighted [(3, True), (1, False)] { show (gen.int ~low: 0 ~high: 99) } else { "x" } } ref.set c.decls [ ..ref.get c.decls , "fn " <> t <> " :: -> Result" , "\{ use a <- result.try (string.to_int \"" <> digits () <> "\")" , " use b <- result.try (string.to_int \"" <> digits () <> "\")" , " Ok(a + b)" , "\}" ] t } // --- Declarations ------------------------------------------------------ /// The small helper functions a program starts with; expressions may /// call them. fn gen_helpers :: c: Ctx -> () / , random> { let count = gen.int ~low: 0 ~high: 2 list.each (list.range 1 count) fn i { gen_helper c (i - 1) } } fn gen_helper :: c: Ctx i: Int -> () / , random> { let name = "f" <> show i if gen.bool () { // Recursive: Int in, Int out, decreasing; call sites clamp the // argument, so the recursion is short. let op = gen.pick ["+", "*"] ref.set c.decls [ ..ref.get c.decls , "fn " <> name <> " :: n: Int -> Int" , "\{ if n <= 0" , " \{ " <> show (gen.int ~low: 0 ~high: 9) <> " \}" , " else" , " \{ (" <> name <> " (n - 1)) " <> op <> " " <> show (gen.int ~low: 1 ~high: 9) <> " \}" , "\}" ] ref.set c.helpers [(name, [TInt], TInt), ..ref.get c.helpers] ref.set c.recursive [name, ..ref.get c.recursive] } else { let pt = scalar () let rt = scalar () let body = expr c [("a", pt)] rt 2 ref.set c.decls [ ..ref.get c.decls , "fn " <> name <> " :: a: " <> ty_src pt <> " -> " <> ty_src rt , "\{ " <> body <> " \}" ] ref.set c.helpers [(name, [pt], rt), ..ref.get c.helpers] } } /// The record type's fields: none (no record in this program), or two /// to three named scalar fields. fn record_fields :: -> List<(String, Ty)> / { match gen.weighted [(2, 0), (2, 2), (1, 3)] { 0 -> [] , 2 -> [("a", scalar ()), ("b", scalar ())] , _ -> [("a", scalar ()), ("b", scalar ()), ("c", scalar ())] } } /// A final `use x <- list.each` over a list in scope: the rest of the /// block runs per element. fn use_tail :: c: Ctx env: List<(String, Ty)> indent: String -> List / , random> { match list.find env fn v { match v.1 { TList(t) -> showable t, _ -> False } } { None -> [] , Some(v) -> if gen.weighted [(1, True), (3, False)] { need c "std/list" [ indent <> "use x <- list.each " <> v.0 , indent <> "io.println (\"each \" <> show x)" ] } else { [] } } } /// The declaration text of an effect. fn effect_decl :: kind: String en: String on: String -> String { if kind == "ask" { "effect " <> en <> " \{ fn " <> on <> " :: -> Int \}" } else { if kind == "yield" { "effect " <> en <> " \{ ctl " <> on <> " :: x: Int -> () \}" } else { "effect " <> en <> " \{ final ctl " <> on <> " :: reason: String -> Never \}" } } } /// A whole program. fn program :: -> String / { region { let fields = record_fields () let c = Ctx( ctr: ref.new 0 , imports: ref.new [] , helpers: ref.new [] , decls: ref.new [] , effects: ref.new [] , handler_fns: ref.new [] , recursive: ref.new [] , fields: fields , choice: gen.weighted [(2, True), (1, False)] ) gen_helpers c let (body, env) = stmts c [] 2 " " (gen.int ~low: 4 ~high: 9) let tail = use_tail c env " " let imports = list.map (list.sort ["std/io", ..ref.get c.imports]) fn m { "import " <> m } let types = list.append (if c.choice { ["type Choice \{ A, B(Int), C(String) \}"] } else { [] }) ( match fields { [] -> [] , _ -> [ "type R \{ R(" <> string.join (list.map fields fn f { f.0 <> ": " <> ty_src f.1 }) ", " <> ") \}" ] } ) let effects = list.map (list.reverse (ref.get c.effects)) fn e { effect_decl e.0 e.1 e.2 } string.join ( concat [ imports , [""] , types , effects , ref.get c.decls , ["", "pub fn main :: -> () / ", "\{"] , list.append body tail , ["\}"] ] ) "\n" <> "\n" } } pub fn main :: -> () / { let seed = match os.env "LOUISE_FUZZ_SEED" { Some(s) -> result.unwrap_or (string.to_int s) 1, None -> 1 } io.print (random.with_seed seed fn { program () }) }