|
1 | | -open Migrate_parsetree.OCaml_411.Ast |
2 | | -let ocaml_version = Migrate_parsetree.Versions.ocaml_411 |
3 | | - |
4 | | -open Ast_mapper |
5 | | -open Ast_helper |
6 | | -open Asttypes |
7 | | -open Parsetree |
| 1 | +open Ppxlib |
| 2 | +open Ppxlib.Ast_helper |
8 | 3 |
|
9 | 4 | let getenv s = try Sys.getenv s with Not_found -> "" |
10 | 5 |
|
11 | | -let getenv_mapper _config _cookies = |
12 | | - (* Our getenv_mapper only overrides the handling of expressions in the default mapper. *) |
13 | | - { default_mapper with |
14 | | - expr = fun mapper expr -> |
15 | | - match expr with |
16 | | - (* Is this an extension node? *) |
17 | | - | { pexp_desc = |
18 | | - (* Should have name "getenv". *) |
19 | | - Pexp_extension ({ txt = "getenv"; loc }, pstr); _ } -> |
20 | | - begin match pstr with |
21 | | - | (* Should have a single structure item, which is evaluation of a constant string. *) |
22 | | - PStr [{ pstr_desc = |
23 | | - Pstr_eval ({ pexp_loc = loc; |
24 | | - pexp_desc = Pexp_constant (Pconst_string (sym, s_loc, None)); _ }, _); _ }] -> |
25 | | - (* Replace with a constant string with the value from the environment. *) |
26 | | - Exp.constant ~loc (Pconst_string (getenv sym, s_loc, None)) |
27 | | - | _ -> |
28 | | - raise (Location.Error ( |
29 | | - Location.error ~loc "[%getenv] accepts a string, e.g. [%getenv \"USER\"]")) |
30 | | - end |
31 | | - (* Delegate to the default mapper. *) |
32 | | - | x -> default_mapper.expr mapper x; |
33 | | - } |
| 6 | +let expander ~loc ~path:_ = function |
| 7 | + | (* Should have a single structure item, which is evaluation of a constant string. *) |
| 8 | + PStr [{ pstr_desc = |
| 9 | + Pstr_eval ({ pexp_loc = loc; |
| 10 | + pexp_desc = Pexp_constant (Pconst_string (sym, None)); _ }, _); _ }] -> |
| 11 | + (* Replace with a constant string with the value from the environment. *) |
| 12 | + Exp.constant ~loc (Pconst_string (getenv sym, None)) |
| 13 | + | _ -> |
| 14 | + Location.raise_errorf ~loc "[%%getenv] accepts a string, e.g. [%%getenv \"USER\"]" |
| 15 | + |
| 16 | +let extension = |
| 17 | + Context_free.Rule.extension |
| 18 | + (Extension.declare "getenv" Expression Ast_pattern.(__) expander) |
34 | 19 |
|
35 | | -let () = Migrate_parsetree.Driver.register ~name:"getenv" ocaml_version getenv_mapper |
| 20 | +let () = Ppxlib.Driver.register_transformation ~rules:[extension] "ppx_getenv" |
0 commit comments