4

I created a syntax extension that allow the definition of a type as

type.yjson type_name {
  /* type_declaration */
}

to be able to build a record value directly from a json file. The syntax extension insert a module and the function necessary to do so. Until here, no problem. The syntax extension do exactly what I wanted.

I start having some issue if I want to use "yjson" at some other place in my code (i.e:function parameter).

Here what I tried:

EXTEND Gram
str_item:
    [
      [ KEYWORD "type"; KEYWORD "."; "yjson"; tdl_raw = type_declaration ->

Here the error I get when I use "yjson" as a function parameter

[fun_binding] expected after [ipatt] (in [let_binding])

I don't really understand what happen here. It doesn't seems like the rule have been match, so why do I get a parse error ?

Marc Simon
  • 5,415
  • 1
  • 19
  • 21

2 Answers2

5

I do not perfectly understand the P4's mechanism around this, but [ [ "blahblah" -> ... makes blahblah as a new keyword of the language, so you can no longer use blahblah as a function argument.

To see this, try preprocess your pa_*.ml by camlp4of and see how "blahblah" is expanded to Gram.Skeyword "blahblah". It seems that this Skeyword _ is passed to Structure.using via Insert.insert of P4 and the string is registered as a new keyword.

To keep yjson usable as a normal variable, use id = LIDENT instead of "yjson" in your rule, then check id's content is "yjson" or not in your action.

camlspotter
  • 8,990
  • 23
  • 27
4

If I can make a slightly off-topic remark, I think it's wrong to design a custom syntax for type-directed code generation, when there already exist two different syntaxes (one for type_conv and one for deriving), one of which (type-conv) is becoming a de facto standard.

type foo = {
   ...
} with json

If you pick a syntax for this, you should use this one unless you have very good reasons not to. In fact, type-conv itself is a helper utility to let you write your own type-directed code generators, so you may as well use type-conv directly for what you're trying to do.

(You probably know about Martin Jambon's Atdgen, which made a conscious choice not to use Camlp4; there is ongoing work by Alain Frisch to support annotations directly in the OCaml syntax, but that's not yet ready for consumption.)

gasche
  • 31,259
  • 3
  • 78
  • 100
  • I totally agree. I actually already re-wrote the whole thing with a deriving generator. But this error was bugging me for a while. – Marc Simon May 30 '13 at 18:06