Skip to content

Commit e449daf

Browse files
authored
Create 2025-03-04-Query_compiler.md
1 parent 8f3c5e5 commit e449daf

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

_posts/2025-03-04-Query_compiler.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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 %}

0 commit comments

Comments
 (0)