Cannot use backticks in term names as backtick quotes are being used by camlp5 (OCaml)

251 Views Asked by At

I'm using the Yojson library and one of the constructors used is called `Bool (with a backtick). I'm working with OCaml source where camlp5 is used so that text surrounded by backticks is interpreted differently (e.g. the text is converted to an OCaml data structure).

The problem I'm having is that when `Bool appears in my source code, camlp5/OCaml is seeing the backtick and thinking it is the start of the quote, causing an error. How can I make sure this is interpreted as an `Bool OCaml term instead? Is there some way to temporarily turn off what campl5 does? Some kind of escape character I can use?

1

There are 1 best solutions below

0
On BEST ANSWER

Since you are using a syntax extension that overrides the behavior of backquotes, you cannot use polymorphic variants like `Bool in the same file.

I would advise you first to change the syntax extension to use a different character than backquotes. Why not %% for example ?

The other solution is simple, but more verbose: use two different files, one where you don't use the syntax extension, and another one where you use the syntax extension.

In the first file (without the syntax extension), you define a type with normal variants that are similar to the ones use in Yojson, and functions to translate from and to polymorphic variants:

type t = 
 | Bool of ...
 | ...

let to_yojson x = 
  match x with
   | Bool v -> `Bool v
   | ...

let from_yojson x =
  match x with
   | `Bool v -> Bool v
   | ...

This way, you can manipulate this new type in your code with the syntax extension without using backquotes, and then use the translation functions to call Yojson. There is a cost to the translation, but if it is your case, you should choose to modify the syntax extension.