File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ ---
2
+ layout : post
3
+ title : Query compilers
4
+ published : false
5
+ ---
6
+
7
+ ## OCaml Meta programming
8
+
9
+ My simplest code generator. There is a scarcity of tutorials that explain OCaml PPX and its variants.
10
+ It is a pity as I believe there exist some good code generation usecases.
11
+
12
+ {% highlight ocaml%}
13
+
14
+ let function_generator ~ ctxt _ input _ is_private =
15
+ let loc = Expansion_context.Deriver.derived_item_loc ctxt in
16
+ let expr = [ %expr [ 1; 2; 3]] in
17
+ let pattern = ppat_var ~ loc { txt = "Pattern_test"; loc } in
18
+ let match_expr =
19
+ [ %expr
20
+ match [ %e expr] with
21
+ | [ %p pattern] -> [ %e evar ~ loc "Pattern_test"]
22
+ ]
23
+ in
24
+ let code =
25
+ [[ Ast_builder.Default.value_binding ~ loc ~ pat: pattern ~ expr: match_expr ] |> pstr_value ~ loc Nonrecursive ]
26
+ in
27
+ List.iter (fun item ->
28
+ Format.printf "Generated Code: %a@." Pprintast.structure_item item
29
+ ) code;
30
+ code
31
+
32
+ let generator () = Deriving.Generator.V2.make (args ()) function_generator
33
+ let _ = Deriving.add "name" ~ str_type_decl:(generator ())
34
+
35
+ {% endhighlight %}
You can’t perform that action at this time.
0 commit comments