ocaml-ppx / ppxlib

Base library and tools for ppx rewriters
MIT License
246 stars 97 forks source link

Context_free.Rule.special_function and partial application? #170

Open jberdine opened 4 years ago

jberdine commented 4 years ago

What is the intended behavior for Context_free.Rule.special_function regarding partial application? For example, it seems to me that it would be helpful to (optionally?) expand (my_special_function x) y the same as my_special_function x y, and likewise for my_special_function x @@ y and y |> my_special_function x.

NathanReb commented 4 years ago

For now there's no special support for those cases and the expansion function will only receive the partial application arguments indeed.

We could eventually support the (f x) y case without it causing too much troubles but the other two cases are a bit different since they rely on operators which can be overridden and therefore have a different semantic than the one we expect, potentially resulting in very strange errors for users in some context. I admit this is probably quite unlikely but we do have to take this into account. I have a feeling that it's okay for a ppx rewriter to document this behaviour as working with "regular" applications only and make this part of its syntax.

Do you have a concrete example of how you'd like to be use special functions rewriting in such cases?

jberdine commented 4 years ago

One example could be something like:

let inc x =
  trace
    ~call:(fun {pf} -> pf "%d" x)
    ~retn:(fun {pf} -> pf "%d")
  @@ fun () ->
  x + 1

where trace is a "special function" that the rewriter expands either to x + 1 when tracing is disabled, or else to a call to some other function such as:

val trace :
     ?call:(pf -> unit)
  -> ?retn:(pf -> 'a -> unit)
  -> ?exn:(pf -> exn -> unit)
  -> string
  -> string
  -> (unit -> 'a)
  -> 'a

where the rewriter also adds string arguments corresponding to the module and function name of the call site.

If the rewriter is meant to replace the entire call with the body of the fun () -> ..., then not handling things like @@ will lead to surprising cases where the above example does not expand to the same code as the (equivalent-as-OCaml):

let inc x =
  trace
    ~call:(fun {pf} -> pf "%d" x)
    (fun () -> x + 1)
    ~retn:(fun {pf} -> pf "%d")