caml-list - the Caml user's mailing list
 help / Atom feed
* [Caml-list] Implementing include "file" statement in menhir
@ 2020-01-21  6:48 Richard W.M. Jones
  2020-01-21  7:15 ` Yann Régis-Gianas
                   ` (2 more replies)
  0 siblings, 3 replies; 4+ messages in thread
From: Richard W.M. Jones @ 2020-01-21  6:48 UTC (permalink / raw)
  To: caml-list, Francois.Pottier, Yann.Regis-Gianas

[Resend, apologies if you get this twice, but I sent it
earlier and that seems to have disappeared.]

I'm writing a parser which needs to have a C-like include directive.
There's an old thread on this describing a rather complicated way to
do this for ocamllex:!topic/fa.caml/_v_k4WTQV_Q

I thought I'd have a go at writing an include statement in menhir, and
I did come up with something which works but it's quite a large hack.
What I did is documented below, but I wonder if someone can think of a
simpler way to do this?  Also two related questions:

How do you pass extra parameters to menhir's generated parser

Is there a nice way to export values into menhir's generated
parser.mli file?


The concept behind my include statement uses the following grammar:

  %token INCLUDE
  %token <string> STRING
  %start file
  file: list(stmt) ;

        let filename = $2 in
        let fp = open_in filename in
        let lexbuf = Lexing.from_channel fp in
        lexbuf.lex_curr_p <- { lexbuf.lex_curr_p with pos_fname = filename };
	(* Recursively call Parser.file: *)
        file lexbuf;
        close_in fp;
      | ... other statements ...

Unfortunately as written the above code cannot work because it
introduces a circular dependency between the Parser and the Lexer
modules (normally the Lexer module depends on the Parser, and so the
Parser cannot use any functions from the Lexer module).

To break the cycle we have to add:

  let lexer_read = ref None

and replace with:

  let reader =
     match !lexer_read with None -> assert false | Some r -> r in
  file reader lexbuf;

Then to initialize lexer_read, we have to export it by doing this

  menhir parser.mly
  echo 'val lexer_read : (Lexing.lexbuf -> token) option ref' >> parser.mli

and we can set it from the main program.


^ permalink raw reply	[flat|nested] 4+ messages in thread

end of thread, back to index

Thread overview: 4+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2020-01-21  6:48 [Caml-list] Implementing include "file" statement in menhir Richard W.M. Jones
2020-01-21  7:15 ` Yann Régis-Gianas
2020-01-21  8:55 ` François Pottier
2020-01-21 13:04 ` Jocelyn Sérot

caml-list - the Caml user's mailing list

Archives are clonable: git clone --mirror

AGPL code for this site: git clone public-inbox