q_symbol.ml 1.24 KB
Newer Older
1 2 3
open Camlp4.PreCast
module Caml_syntax = Syntax

4 5 6
let symbols = ref []

let define s =
7 8 9
  let i = 
    try String.index s '=' 
    with Not_found -> failwith ("Invalid symbol definition :" ^ s) in
10 11 12 13 14 15
  let symbol = String.sub s 0 i in
  let value =
    Gram.parse_string
      Caml_syntax.expr (Loc.mk "<from-string>") (String.sub s (i + 1) (String.length s - i - 1))
  in
  symbols := (symbol, value) :: !symbols
16

17 18
EXTEND Caml_syntax.Gram
  GLOBAL: Caml_syntax.str_item;
19

20
  Caml_syntax.str_item: FIRST
21 22 23 24
    [ [ "ifdef"; c = UIDENT; "then"; e1 = SELF;
        "else"; e2 = SELF ->
          if List.mem_assoc c !symbols then e1 else e2
      | "ifdef"; c = UIDENT; "then"; e1 = SELF ->
25
          if List.mem_assoc c !symbols then e1 else <:str_item<>>
26 27 28 29
      | "ifndef"; c = UIDENT; "then"; e1 = SELF;
        "else"; e2 = SELF ->
          if List.mem_assoc c !symbols then e2 else e1
      | "ifndef"; c = UIDENT; "then"; e1 = SELF ->
30
          if List.mem_assoc c !symbols then <:str_item<>> else e1
31 32 33
      ] ];
END

34
let expr _ _ s =
35
  try List.assoc s !symbols
36
  with Not_found -> failwith ("No definition for symbol " ^ s)
37 38

let _ =
39 40
  Quotation.add "symbol" Quotation.DynAst.expr_tag expr;
  Camlp4.Options.add "-symbol" (Arg.String define) 
41
    "<symbol=value> Define a symbol"