Skip to content

Instantly share code, notes, and snippets.

@zehnpaard
Created March 1, 2021 02:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zehnpaard/817e0ae7eeffdec7a9d209ea86437a05 to your computer and use it in GitHub Desktop.
Save zehnpaard/817e0ae7eeffdec7a9d209ea86437a05 to your computer and use it in GitHub Desktop.
Minimal example using ocamllex/menhir with js_of_ocaml : compile to JS with the command `dune build ./main.bc.js`
(menhir
(modules parser))
(ocamllex lexer)
(executable
(name main)
(modes js))
type t =
| Var of string
| Call of t list
let rec to_string = function
| Var s -> "Var(" ^ s ^ ")"
| Call xs ->
let s = List.map to_string xs |> String.concat " " in
"Call(" ^ s ^ ")"
let whitespace = [' ' '\t' '\n']
let char = ['a'-'z' 'A'-'Z' '+' '-' '*' '/' '<' '>' '=' '!' '?' '_']
let variable = char+
rule f = parse
| whitespace* { f lexbuf }
| "(" { Parser.LPAREN }
| ")" { Parser.RPAREN }
| variable as s { Parser.VAR s }
| eof { EOF }
<html>
<head>
<script type="text/javascript" src="_build/default/main.bc.js"></script>
</head>
<body></body>
</html>
let () =
"(test a b c)"
|> Lexing.from_string
|> Parser.f Lexer.f
|> Exp.to_string
|> print_endline
%token <string> VAR
%token LPAREN
%token RPAREN
%token EOF
%start <Exp.t> f
%%
f : e = expr; EOF { e }
expr :
| s = VAR; { Exp.Var s }
| LPAREN; es = list (expr); RPAREN { Exp.Call es }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment