This commit is contained in:
swrup 2025-11-11 02:07:51 +01:00
parent aa2ff7b2f0
commit 2f3113f55d
11742 changed files with 1223940 additions and 0 deletions

View file

@ -0,0 +1,7 @@
(executable
(name print_stuff)
(libraries ppxlib))
(cram
(package ppxlib)
(deps print_stuff.exe))

View file

@ -0,0 +1,45 @@
open Ppxlib
let mk_expression ~loc pexp_desc =
{ pexp_desc; pexp_loc_stack = []; pexp_loc = loc; pexp_attributes = [] }
let print_string s ~loc =
let print_exp =
mk_expression ~loc (Pexp_ident { txt = Lident "print_endline"; loc })
in
let string_exp =
mk_expression ~loc (Pexp_constant (Pconst_string (s, loc, None)))
in
mk_expression ~loc (Pexp_apply (print_exp, [ (Nolabel, string_exp) ]))
let hi_rule =
let expand ~loc ~path:_ = print_string "hi" ~loc in
Extension.declare "print_hi" Extension.Context.expression
Ast_pattern.(pstr nil)
expand
|> Context_free.Rule.extension
let tool_name_rule =
let expand ~ctxt =
let loc = Expansion_context.Extension.extension_point_loc ctxt in
let tool_name = Expansion_context.Extension.tool_name ctxt in
print_string tool_name ~loc
in
Extension.V3.declare "print_tool_name" Extension.Context.expression
Ast_pattern.(pstr nil)
expand
|> Context_free.Rule.extension
let fname_rule =
let expand ~loc ~path:_ = print_string ~loc loc.loc_start.pos_fname in
Extension.declare "print_fname" Extension.Context.expression
Ast_pattern.(pstr nil)
expand
|> Context_free.Rule.extension
let () =
Driver.register_transformation
~rules:[ hi_rule; tool_name_rule; fname_rule ]
"test"
let () = Ppxlib.Driver.standalone ()

View file

@ -0,0 +1,37 @@
Keep the error output short in order to avoid different error output between different compiler versions in the subsequent tests
$ export OCAML_ERROR_STYLE=short
The rewriter gets applied when using `--as-ppx`
$ echo "let _ = [%print_hi]" > impl.ml
$ ocaml -ppx './print_stuff.exe --as-ppx' impl.ml
hi
If a non-compatible file gets fed, the file name is reported correctly
$ touch no_binary_ast.ml
$ ./print_stuff.exe --as-ppx no_binary_ast.ml some_output
File "no_binary_ast.ml", line 1:
Error: Expected a binary AST as input
[1]
The ocaml.ppx.context attribute gets parsed correctly; in particular, the tool name gets set correctly
$ echo "let _ = [%print_tool_name]" > impl.ml
$ ocaml -ppx './print_stuff.exe --as-ppx' impl.ml
ocaml
The driver's `shared_args` arguments are taken into account. For example, `-loc-filename`
$ echo "let _ = [%print_fname]" > impl.ml
$ ocaml -ppx './print_stuff.exe --as-ppx -loc-filename new_fn.ml' impl.ml
new_fn.ml
or `dont-apply`
$ echo "let _ = [%print_hi]" > impl.ml
$ ocaml -ppx './print_stuff.exe --as-ppx -dont-apply test' impl.ml
File "./impl.ml", line 1, characters 10-18:
Error: Uninterpreted extension 'print_hi'.
[2]