package catala
Compiler and library for the literate programming language for tax code specification
Install
Dune Dependency
Authors
Maintainers
Sources
0.9.0.tar.gz
md5=8f891209d18b6540df9c34b2d1a6a783
sha512=737770b87a057674bceefe77e8526720732552f51f424afcebcb6a628267eab522c4fd993caca1ae8ed7ace65a4a87e485af10c1676e51ca5939509a1b841ac2
doc/src/catala.shared_ast/optimizations.ml.html
Source file optimizations.ml
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
(* This file is part of the Catala compiler, a specification language for tax and social benefits computation rules. Copyright (C) 2022 Inria, contributors: Alain Delaët <alain.delaet--tixeuil@inria.fr>, Denis Merigoux <denis.merigoux@inria.fr> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) open Catala_utils open Definitions type ('a, 'b, 'm) optimizations_ctx = { var_values : ( (('a, 'b) dcalc_lcalc, 'm) gexpr, (('a, 'b) dcalc_lcalc, 'm) gexpr ) Var.Map.t; decl_ctx : decl_ctx; } let all_match_cases_are_id_fun cases n = EnumConstructor.Map.for_all (fun i case -> match Mark.remove case with | EAbs { binder; _ } -> ( let var, body = Bindlib.unmbind binder in (* because of invariant [invariant_match], the arity is always one. *) let[@warning "-8"] [| var |] = var in match Mark.remove body with | EInj { cons = i'; name = n'; e = EVar x, _ } -> EnumConstructor.equal i i' && EnumName.equal n n' && Bindlib.eq_vars x var | EInj { cons = i'; name = n'; e = ELit LUnit, _ } -> (* since unit is the only value of type unit. We don't need to check the equality. *) EnumConstructor.equal i i' && EnumName.equal n n' | _ -> false) | _ -> (* because of invariant [invariant_match], there is always some EAbs in each cases. *) assert false) cases let all_match_cases_map_to_same_constructor cases n = EnumConstructor.Map.for_all (fun i case -> match Mark.remove case with | EAbs { binder; _ } -> ( let _, body = Bindlib.unmbind binder in match Mark.remove body with | EInj { cons = i'; name = n'; _ } -> EnumConstructor.equal i i' && EnumName.equal n n' | _ -> false) | _ -> assert false) cases let binder_vars_used_at_most_once (binder : ( (('a, 'b) dcalc_lcalc, ('a, 'b) dcalc_lcalc, 'm) base_gexpr, (('a, 'b) dcalc_lcalc, 'm) gexpr ) Bindlib.mbinder) : bool = (* fast path: variables not used at all *) (not (Array.exists Fun.id (Bindlib.mbinder_occurs binder))) || let vars, body = Bindlib.unmbind binder in let rec vars_count (e : (('a, 'b) dcalc_lcalc, 'm) gexpr) : int array = match e with | EVar v, _ -> Array.map (fun i -> if Bindlib.eq_vars v (Array.get vars i) then 1 else 0) (Array.make (Array.length vars) 0) | e -> Expr.shallow_fold (fun e' acc -> Array.map2 (fun x y -> x + y) (vars_count e') acc) e (Array.make (Array.length vars) 0) in not (Array.exists (fun c -> c > 1) (vars_count body)) let rec : type a b. (a, b, 'm) optimizations_ctx -> ((a, b) dcalc_lcalc, 'm) gexpr -> ((a, b) dcalc_lcalc, 'm) boxed_gexpr = fun ctx e -> (* We proceed bottom-up, first apply on the subterms *) let e = Expr.map ~f:(optimize_expr ctx) e in let mark = Mark.get e in (* Then reduce the parent node *) let reduce (e : ((a, b) dcalc_lcalc, 'm) gexpr) = (* Todo: improve the handling of eapp(log,elit) cases here, it obfuscates the matches and the log calls are not preserved, which would be a good property *) match Mark.remove e with | EAppOp { op = Not; args = [(ELit (LBool b), _)]; _ } -> (* reduction of logical not *) ELit (LBool (not b)) | EAppOp { op = Or; args = [(ELit (LBool b), _); (e, _)]; _ } | EAppOp { op = Or; args = [(e, _); (ELit (LBool b), _)]; _ } -> (* reduction of logical or *) if b then ELit (LBool true) else e | EAppOp { op = And; args = [(ELit (LBool b), _); (e, _)]; _ } | EAppOp { op = And; args = [(e, _); (ELit (LBool b), _)]; _ } -> (* reduction of logical and *) if b then e else ELit (LBool false) | EMatch { e = EInj { e = e'; cons; name = n' }, _; cases; name = n } (* iota-reduction *) when EnumName.equal n n' -> ( (* match E x with | E y -> e1 = e1[y |-> x]*) match Mark.remove @@ EnumConstructor.Map.find cons cases with (* holds because of invariant_match_inversion *) | EAbs { binder; _ } -> Mark.remove (Bindlib.msubst binder ([e'] |> List.map fst |> Array.of_list)) | _ -> assert false) | EMatch { e = e'; cases; name = n } when all_match_cases_are_id_fun cases n -> (* iota-reduction when the match is equivalent to an identity function *) Mark.remove e' | EMatch { e = EMatch { e = arg; cases = cases1; name = n1 }, _; cases = cases2; name = n2; } when false (* TODO: this case is buggy because of the box/unbox manipulation, it should be fixed before removing this [false] value*) && EnumName.equal n1 n2 && all_match_cases_map_to_same_constructor cases1 n1 -> (* iota-reduction when the matched expression is itself a match of the same enum mapping all constructors to themselves *) let cases = EnumConstructor.Map.merge (fun _i o1 o2 -> match o1, o2 with | Some b1, Some e2 -> ( match Mark.remove b1, Mark.remove e2 with | EAbs { binder = b1; _ }, EAbs { binder = b2; tys } -> ( let v1, e1 = Bindlib.unmbind b1 in let[@warning "-8"] [| v1 |] = v1 in match Mark.remove e1 with | EInj { e = e1; _ } -> Some (Expr.unbox (Expr.make_abs [| v1 |] (Expr.box (Bindlib.msubst b2 ([e1] |> List.map fst |> Array.of_list))) tys (Expr.pos e2))) | _ -> assert false) | _ -> assert false) | _ -> assert false) cases1 cases2 in EMatch { e = arg; cases; name = n1 } | EApp { f = EAbs { binder; _ }, _; args; _ } when binder_vars_used_at_most_once binder || List.for_all (function EVar _, _ -> true | _ -> false) args -> (* beta reduction when variables not used, and for variable aliases *) Mark.remove (Bindlib.msubst binder (List.map fst args |> Array.of_list)) | EStructAccess { name; field; e = EStruct { name = name1; fields }, _ } when StructName.equal name name1 -> Mark.remove (StructField.Map.find field fields) | EErrorOnEmpty ( EDefault { excepts = []; just = ELit (LBool true), _; cons = EPureDefault e, _; }, _ ) -> (* No exceptions, always true *) Mark.remove e | EErrorOnEmpty ( EDefault { excepts = [ ( EDefault { excepts = []; just = ELit (LBool true), _; cons }, _ ); ]; _; }, _ ) -> (* Single, always true exception *) Mark.remove cons | EDefault { excepts; just; cons } -> ( (* TODO: mechanically prove each of these optimizations correct *) let excepts = List.filter (fun except -> Mark.remove except <> EEmptyError) excepts (* we can discard the exceptions that are always empty error *) in let value_except_count = List.fold_left (fun nb except -> if Expr.is_value except then nb + 1 else nb) 0 excepts in if value_except_count > 1 then (* at this point we know a conflict error will be triggered so we just feed the expression to the interpreter that will print the beautiful right error message *) let (_ : _ gexpr) = Interpreter.evaluate_expr ctx.decl_ctx Cli.En (* Default language to English, no errors should be raised normally so we don't care *) e in assert false else match excepts, just with | ( [ ( (EDefault { excepts = []; just = ELit (LBool true), _; _ } as dft), _ ); ], _ ) -> (* Single exception with condition [true] *) dft | ( [], ( ( ELit (LBool false) | EAppOp { op = Log _; args = [(ELit (LBool false), _)]; _ } ), _ ) ) -> (* No exceptions and condition false *) EEmptyError | excepts, just -> EDefault { excepts; just; cons }) | EIfThenElse { cond = ( ELit (LBool true), _ | EAppOp { op = Log _; args = [(ELit (LBool true), _)]; _ }, _ ); etrue; _; } -> Mark.remove etrue | EIfThenElse { cond = ( ( ELit (LBool false) | EAppOp { op = Log _; args = [(ELit (LBool false), _)]; _ } ), _ ); efalse; _; } -> Mark.remove efalse | EIfThenElse { cond; etrue = ( ( ELit (LBool btrue) | EAppOp { op = Log _; args = [(ELit (LBool btrue), _)]; _ } ), _ ); efalse = ( ( ELit (LBool bfalse) | EAppOp { op = Log _; args = [(ELit (LBool bfalse), _)]; _ } ), _ ); } -> if btrue && not bfalse then Mark.remove cond else if (not btrue) && bfalse then EAppOp { op = Not; tys = [TLit TBool, Expr.mark_pos mark]; args = [cond] } (* note: this last call eliminates the condition & might skip log calls as well *) else (* btrue = bfalse *) ELit (LBool btrue) | EAppOp { op = Op.Fold; args = [_f; init; (EArray [], _)]; _ } -> (*reduces a fold with an empty list *) Mark.remove init | EAppOp { op = Op.Fold; args = [f; init; (EArray [e'], _)]; tys = [_; tinit; (TArray tx, _)]; } -> (* reduces a fold with one element *) EApp { f; args = [init; e']; tys = [tinit; tx] } | ECatch { body; exn; handler } -> ( (* peephole exception catching reductions *) match Mark.remove body, Mark.remove handler with | ERaise exn', ERaise exn'' when exn' = exn && exn = exn'' -> ERaise exn | ERaise exn', _ when exn' = exn -> Mark.remove handler | _, ERaise exn' when exn' = exn -> Mark.remove body | _ -> ECatch { body; exn; handler }) | e -> e in Expr.Box.app1 e reduce mark let optimize_expr : 'm. decl_ctx -> (('a, 'b) dcalc_lcalc, 'm) gexpr -> (('a, 'b) dcalc_lcalc, 'm) boxed_gexpr = fun (decl_ctx : decl_ctx) (e : (('a, 'b) dcalc_lcalc, 'm) gexpr) -> optimize_expr { var_values = Var.Map.empty; decl_ctx } e let optimize_program (p : 'm program) : 'm program = Bindlib.unbox (Program.map_exprs ~f:(optimize_expr p.decl_ctx) ~varf:(fun v -> v) p) let test_iota_reduction_1 () = let x = Var.make "x" in let enumT = EnumName.fresh [] ("t", Pos.no_pos) in let consA = EnumConstructor.fresh ("A", Pos.no_pos) in let consB = EnumConstructor.fresh ("B", Pos.no_pos) in let consC = EnumConstructor.fresh ("C", Pos.no_pos) in let consD = EnumConstructor.fresh ("D", Pos.no_pos) in let nomark = Untyped { pos = Pos.no_pos } in let injA = Expr.einj ~e:(Expr.evar x nomark) ~cons:consA ~name:enumT nomark in let injC = Expr.einj ~e:(Expr.evar x nomark) ~cons:consC ~name:enumT nomark in let injD = Expr.einj ~e:(Expr.evar x nomark) ~cons:consD ~name:enumT nomark in let cases : ('a, 't) boxed_gexpr EnumConstructor.Map.t = EnumConstructor.Map.of_list [ consA, Expr.eabs (Expr.bind [| x |] injC) [TAny, Pos.no_pos] nomark; consB, Expr.eabs (Expr.bind [| x |] injD) [TAny, Pos.no_pos] nomark; ] in let matchA = Expr.ematch ~e:injA ~name:enumT ~cases nomark in Alcotest.(check string) "same string" begin[@ocamlformat "disable"] "before=match (A x) with\n\ \ | A x → C x\n\ \ | B x → D x\n\ after=C x" end (Format.asprintf "before=%a\nafter=%a" Expr.format (Expr.unbox matchA) Expr.format (Expr.unbox (optimize_expr Program.empty_ctx (Expr.unbox matchA)))) let cases_of_list l : ('a, 't) boxed_gexpr EnumConstructor.Map.t = EnumConstructor.Map.of_list @@ ListLabels.map l ~f:(fun (cons, f) -> let var = Var.make "x" in ( cons, Expr.eabs (Expr.bind [| var |] (f var)) [TAny, Pos.no_pos] (Untyped { pos = Pos.no_pos }) )) let test_iota_reduction_2 () = let enumT = EnumName.fresh [] ("t", Pos.no_pos) in let consA = EnumConstructor.fresh ("A", Pos.no_pos) in let consB = EnumConstructor.fresh ("B", Pos.no_pos) in let consC = EnumConstructor.fresh ("C", Pos.no_pos) in let consD = EnumConstructor.fresh ("D", Pos.no_pos) in let nomark = Untyped { pos = Pos.no_pos } in let num n = Expr.elit (LInt (Runtime.integer_of_int n)) nomark in let injAe e = Expr.einj ~e ~cons:consA ~name:enumT nomark in let injBe e = Expr.einj ~e ~cons:consB ~name:enumT nomark in let injCe e = Expr.einj ~e ~cons:consC ~name:enumT nomark in let injDe e = Expr.einj ~e ~cons:consD ~name:enumT nomark in (* let injA x = injAe (Expr.evar x nomark) in *) let injB x = injBe (Expr.evar x nomark) in let injC x = injCe (Expr.evar x nomark) in let injD x = injDe (Expr.evar x nomark) in let matchA = Expr.ematch ~e: (Expr.ematch ~e:(num 1) ~name:enumT ~cases: (cases_of_list [ (consB, fun x -> injBe (injB x)); (consA, fun _x -> injAe (num 20)); ]) nomark) ~name:enumT ~cases:(cases_of_list [consA, injC; consB, injD]) nomark in Alcotest.(check string) "same string " begin[@ocamlformat "disable"] "before=match (match 1 with\n\ \ | A x → A 20\n\ \ | B x → B (B x)) with\n\ \ | A x → C x\n\ \ | B x → D x\n\ after=match 1 with\n\ \ | A x → C 20\n\ \ | B x → D B x" end (Format.asprintf "before=@[%a@]@.after=%a@." Expr.format (Expr.unbox matchA) Expr.format (Expr.unbox (optimize_expr Program.empty_ctx (Expr.unbox matchA))))
sectionYPositions = computeSectionYPositions($el), 10)"
x-init="setTimeout(() => sectionYPositions = computeSectionYPositions($el), 10)"
>