open Camlp4.PreCast
module Caml_syntax = Syntax

let symbols = ref []

let define s =
  let i = 
    try String.index s '=' 
    with Not_found -> failwith ("Invalid symbol definition :" ^ s) in
  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

EXTEND Caml_syntax.Gram
  GLOBAL: Caml_syntax.str_item;

  Caml_syntax.str_item: FIRST
    [ [ "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 ->
          if List.mem_assoc c !symbols then e1 else <:str_item<>>
      | "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 ->
          if List.mem_assoc c !symbols then <:str_item<>> else e1
      ] ];
END

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

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