Previous Next Contents

3.5   Examples

3.5.1   Arithmetic calculator

This is an example of a grammar of arithmetic expressions:
    let gram = Grammar.create (Plexer.make ());;
    let test = Grammar.Entry.create gram "expression";;
    let expr = Grammar.Entry.create gram "expression";;
    EXTEND
      test: [ [ e = expr; EOI -> e ] ];
      expr: [ "plus" LEFTA
              [ e1 = expr; "+"; e2 = expr -> e1 + e2
              | e1 = expr; "-"; e2 = expr -> e1 - e2 ]
            | "mult" LEFTA
              [ e1 = expr; "*"; e2 = expr -> e1 * e2
              | e1 = expr; "/"; e2 = expr -> e1 / e2 ]
            | [ e = INT -> int_of_string e
              | "("; e = expr; ")" -> e ] ];
    END;;
    let calc str =
      try Grammar.Entry.parse test (Stream.of_string str) with
        Stdpp.Exc_located (loc, e) ->
          Printf.printf "Located at (%d, %d)\n" (fst loc) (snd loc);
          raise e
    ;;
Now, an extension of the entry ``expr'' to add the modulo, could be:

    EXTEND expr:
      AFTER "mult" [ [ e1 = expr; "mod"; e2 = expr -> e1 mod e2 ] ];
    END;;

3.5.2   Camlp4 bootstrap

The Camlp4 parsers of Objective Caml and revised syntax are implemented using the present grammar system: their sources files ``pa_o.ml'' and ``pa_r.ml'', in Camlp4's distribution, hold EXTEND instructions defining the whole language parsers. This make them extensible. See chapter 4.

Moreover, the syntax extension adding the instruction ``EXTEND'' is programmed in the file ``pa_extend.ml'' in Camlp4's distribution, as a syntax extension of the language parser. It contains code looking like:

     EXTEND
       expr: [ [ "EXTEND"; g = OPT global; el = LIST0 entry; "END" -> ...
       global: [ [ "GLOBAL"; ....
       entry: [ [ e = LIDENT; ":"; p = OPT position; ....
       ...
     END
So, the Camlp4 sources use widely the Camlp4 facilities. The very first compilation of Camlp4 is done by pure Objective Caml versions of Camlp4's sources created by Camlp4.
Previous Next Contents