]> matita.cs.unibo.it Git - helm.git/blobdiff - helm/ocaml/cic_notation/cicNotationParser.ml
snapshot (first version in which some extensions work, e.g. infix +)
[helm.git] / helm / ocaml / cic_notation / cicNotationParser.ml
index 5e94d20a08f0510ba0645c3d4141cf76d5aa10cb..09fd55b0d4bae7c890c6eb98599fbf6d3e9aa034 100644 (file)
 open Printf
 
 exception Parse_error of Token.flocation * string
+exception Level_not_found of int
 
-module Level1Lexer =
-struct
-  type te = string * string
-  let lexer = CicNotationLexer.syntax_pattern_lexer
-end
-module Level1Parser = Grammar.GMake (Level1Lexer)
-
-module Level2Lexer =
-struct
-  type te = string * string
-  let lexer = CicNotationLexer.ast_pattern_lexer
-end
-module Level2Parser = Grammar.GMake (Level2Lexer)
-
-module Level3Lexer =
-struct
-  type te = string * string
-  let lexer = CicNotationLexer.ast_pattern_lexer
-end
-module Level3Parser = Grammar.GMake (Level3Lexer)
-
-let level1_pattern = Level1Parser.Entry.create "level1_pattern"
-let level2_pattern = Level2Parser.Entry.create "level2_pattern"
-let level3_interpretation = Level3Parser.Entry.create "level3_interpretation"
+let grammar = Grammar.gcreate CicNotationLexer.notation_lexer
+
+let level1_pattern = Grammar.Entry.create grammar "level1_pattern"
+let level2_pattern = Grammar.Entry.create grammar "level2_pattern"
+let level3_term = Grammar.Entry.create grammar "level3_term"
+let l2_pattern = Grammar.Entry.create grammar "l2_pattern"
+let notation = Grammar.Entry.create grammar "notation" (* level1 <-> level 2 *)
+let interpretation =
+  Grammar.Entry.create grammar "interpretation" (* level2 <-> level 3 *)
 
 let return_term loc term = ()
 
-(*let fail floc msg =*)
-(*  let (x, y) = CicAst.loc_of_floc floc in*)
-(*  failwith (sprintf "Error at characters %d - %d: %s" x y msg)*)
+let loc_of_floc = function
+  | { Lexing.pos_cnum = loc_begin }, { Lexing.pos_cnum = loc_end } ->
+      (loc_begin, loc_end)
+
+let fail floc msg =
+  let (x, y) = loc_of_floc floc in
+  failwith (sprintf "Error at characters %d - %d: %s" x y msg)
 
 let int_of_string s =
   try
@@ -64,72 +54,99 @@ let int_of_string s =
   with Failure _ ->
     failwith (sprintf "Lexer failure: string_of_int \"%s\" failed" s)
 
+open CicNotationPt
+
+let boxify = function
+  | [ a ] -> a
+  | l -> Layout (Box (H, l))
+
+let fold_binder binder pt_names body =
+  let fold_cluster binder names ty body =
+    List.fold_right
+      (fun name body -> Binder (binder, (Cic.Name name, ty), body))
+      names body
+  in
+  List.fold_right
+    (fun (names, ty) body -> fold_cluster binder names ty body)
+    pt_names body
+
+let return_term loc term = AttributedTerm (`Loc loc, term)
+
+EXTEND
+  GLOBAL: level1_pattern level2_pattern level3_term
+          l2_pattern
+          notation interpretation;
 (* {{{ Grammar for concrete syntax patterns, notation level 1 *)
-GEXTEND Level1Parser
-  GLOBAL: level1_pattern;
-  level1_pattern: [ [ p = pattern -> () ] ];
-  pattern: [ [ p = LIST1 simple_pattern -> () ] ];
+  level1_pattern: [ [ p = l1_pattern; EOI -> boxify p ] ];
+  l1_pattern: [ [ p = LIST0 l1_simple_pattern -> p ] ];
   literal: [
-    [ s = SYMBOL -> ()
-    | k = KEYWORD -> ()
+    [ s = SYMBOL -> `Symbol s
+    | k = KEYWORD -> `Keyword k
+    | n = NUMBER -> `Number n
     ]
   ];
-  sep:       [ [ SYMBOL "\\SEP";      sep = literal -> () ] ];
-  row_sep:   [ [ SYMBOL "\\ROWSEP";   sep = literal -> () ] ];
-  field_sep: [ [ SYMBOL "\\FIELDSEP"; sep = literal -> () ] ];
-  box_pattern: [
-    [ SYMBOL "\\HBOX"; p = simple_pattern -> ()
-    | SYMBOL "\\VBOX"; p = simple_pattern -> ()
-    | SYMBOL "\\BREAK" -> ()
+  sep:       [ [ SYMBOL "\\SEP";      sep = literal -> sep ] ];
+(*   row_sep:   [ [ SYMBOL "\\ROWSEP";   sep = literal -> sep ] ];
+  field_sep: [ [ SYMBOL "\\FIELDSEP"; sep = literal -> sep ] ]; *)
+  l1_magic_pattern: [
+    [ SYMBOL "\\LIST0"; p = l1_simple_pattern; sep = OPT sep -> List0 (p, sep)
+    | SYMBOL "\\LIST1"; p = l1_simple_pattern; sep = OPT sep -> List1 (p, sep)
+    | SYMBOL "\\OPT";   p = l1_simple_pattern -> Opt p
     ]
   ];
-  magic_pattern: [
-    [ SYMBOL "\\LIST0"; p = simple_pattern; sep = OPT sep -> ()
-    | SYMBOL "\\LIST1"; p = simple_pattern; sep = OPT sep -> ()
-    | SYMBOL "\\OPT"; p = simple_pattern -> ()
+  l1_pattern_variable: [
+    [ id = IDENT -> TermVar id
+    | SYMBOL "\\TERM"; id = IDENT -> TermVar id
+    | SYMBOL "\\NUM"; id = IDENT -> NumVar id
+    | SYMBOL "\\IDENT"; id = IDENT -> IdentVar id
     ]
   ];
-  pattern_variable: [
-    [ id = IDENT -> ()
-    | SYMBOL "\\NUM"; id = IDENT -> ()
-    | SYMBOL "\\IDENT"; id = IDENT -> ()
-    ]
-  ];
-  simple_pattern:
+  l1_simple_pattern:
     [ "layout" LEFTA
-      [ p1 = SELF; SYMBOL "\\SUB"; p2 = SELF -> ()
-      | p1 = SELF; SYMBOL "\\SUP"; p2 = SELF -> ()
-      | p1 = SELF; SYMBOL "\\BELOW"; p2 = SELF -> ()
-      | p1 = SELF; SYMBOL "\\ABOVE"; p2 = SELF -> ()
-      | SYMBOL "["; p1 = pattern; SYMBOL "\\OVER"; p2 = pattern; SYMBOL "]" ->
-          ()
-      | SYMBOL "["; p1 = pattern; SYMBOL "\\ATOP"; p2 = pattern; SYMBOL "]" ->
-          ()
-      | SYMBOL "\\ARRAY"; p = SELF; fsep = OPT field_sep; rsep = OPT row_sep ->
-          ()
-      | SYMBOL "\\FRAC"; p1 = SELF; p2 = SELF -> ()
-      | SYMBOL "\\SQRT"; p = SELF -> ()
-      | SYMBOL "\\ROOT"; arg = pattern; SYMBOL "\\OF"; index = SELF -> ()
+      [ p1 = SELF; SYMBOL "\\SUB"; p2 = SELF ->
+          return_term loc (Layout (Sub (p1, p2)))
+      | p1 = SELF; SYMBOL "\\SUP"; p2 = SELF ->
+          return_term loc (Layout (Sup (p1, p2)))
+      | p1 = SELF; SYMBOL "\\BELOW"; p2 = SELF ->
+          return_term loc (Layout (Below (p1, p2)))
+      | p1 = SELF; SYMBOL "\\ABOVE"; p2 = SELF ->
+          return_term loc (Layout (Above (p1, p2)))
+      | SYMBOL "["; p1 = l1_pattern; SYMBOL "\\OVER"; p2 = l1_pattern;
+        SYMBOL "]" ->
+          return_term loc (Layout (Over (boxify p1, boxify p2)))
+      | SYMBOL "["; p1 = l1_pattern; SYMBOL "\\ATOP"; p2 = l1_pattern;
+        SYMBOL "]" ->
+          return_term loc (Layout (Atop (boxify p1, boxify p2)))
+(*       | SYMBOL "\\ARRAY"; p = SELF; csep = OPT field_sep; rsep = OPT row_sep ->
+          return_term loc (Array (p, csep, rsep)) *)
+      | SYMBOL "\\FRAC"; p1 = SELF; p2 = SELF ->
+          return_term loc (Layout (Frac (p1, p2)))
+      | SYMBOL "\\SQRT"; p = SELF -> return_term loc (Layout (Sqrt p))
+      | SYMBOL "\\ROOT"; index = l1_pattern; SYMBOL "\\OF"; arg = SELF ->
+          return_term loc (Layout (Root (arg, Layout (Box (H, index)))))
+      | SYMBOL "\\HBOX"; SYMBOL "["; p = l1_pattern; SYMBOL "]" ->
+          return_term loc (Layout (Box (H, p)))
+      | SYMBOL "\\VBOX"; SYMBOL "["; p = l1_pattern; SYMBOL "]" ->
+          return_term loc (Layout (Box (V, p)))
+      | SYMBOL "\\BREAK" -> return_term loc (Layout Break)
+      | SYMBOL "["; p = l1_pattern; SYMBOL "]" ->
+          return_term loc (boxify p)
+      | SYMBOL "["; p = l1_pattern; SYMBOL "\\AS"; id = IDENT; SYMBOL "]" ->
+          return_term loc (Variable (Ascription (Layout (Box (H, p)), id)))
       ]
     | "simple" NONA
-      [ m = magic_pattern -> ()
-      | v = pattern_variable -> ()
-      | b = box_pattern -> ()
-      | n = NUMBER -> ()
-      | SYMBOL "["; p = pattern; SYMBOL "]" -> ()
+      [ m = l1_magic_pattern -> return_term loc (Magic m)
+      | v = l1_pattern_variable -> return_term loc (Variable v)
+      | l = literal -> return_term loc (Literal l)
       ]
     ];
-END
 (* }}} *)
-
 (* {{{ Grammar for ast patterns, notation level 2 *)
-GEXTEND Level2Parser
-  GLOBAL: level2_pattern;
-  level2_pattern: [ [ p = pattern -> () ] ];
+  level2_pattern: [ [ p = l2_pattern; EOI -> p ] ];
   sort: [
-    [ SYMBOL "\\PROP" -> ()
-    | SYMBOL "\\SET" -> ()
-    | SYMBOL "\\TYPE" -> ()
+    [ SYMBOL "\\PROP" -> `Prop
+    | SYMBOL "\\SET" -> `Set
+    | SYMBOL "\\TYPE" -> `Type
     ]
   ];
   explicit_subst: [
@@ -141,132 +158,191 @@ GEXTEND Level2Parser
     ]
   ];
   possibly_typed_name: [
-    [ SYMBOL "("; i = IDENT; SYMBOL ":"; typ = pattern; SYMBOL ")" -> ()
-    | i = IDENT -> ()
+    [ SYMBOL "("; id = IDENT; SYMBOL ":"; typ = l2_pattern; SYMBOL ")" ->
+        Cic.Name id, Some typ
+    | id = IDENT -> Cic.Name id, None
     ]
   ];
   match_pattern: [
-    [ n = IDENT -> ()
-    | SYMBOL "("; head = IDENT; vars = LIST1 possibly_typed_name; SYMBOL ")" ->
-        ()
+    [ id = IDENT -> id, []
+    | SYMBOL "("; id = IDENT; vars = LIST1 possibly_typed_name; SYMBOL ")" ->
+        id, vars
     ]
   ];
   binder: [
-    [ SYMBOL <:unicode<Pi>>     (* Π *) -> ()
-    | SYMBOL <:unicode<exists>> (* ∃ *) -> ()
-    | SYMBOL <:unicode<forall>> (* ∀ *) -> ()
-    | SYMBOL <:unicode<lambda>> (* λ *) -> ()
+    [ SYMBOL <:unicode<Pi>>     (* Π *) -> `Pi
+    | SYMBOL <:unicode<exists>> (* ∃ *) -> `Exists
+    | SYMBOL <:unicode<forall>> (* ∀ *) -> `Forall
+    | SYMBOL <:unicode<lambda>> (* λ *) -> `Lambda
     ]
   ];
   bound_names: [
     [ vars = LIST1 IDENT SEP SYMBOL ",";
-      typ = OPT [ SYMBOL ":"; p = pattern -> () ] -> ()
-    | LIST1 [
-        SYMBOL "("; vars = LIST1 IDENT SEP SYMBOL ",";
-        typ = OPT [ SYMBOL ":"; p = pattern -> () ]; SYMBOL ")" -> ()
+      ty = OPT [ SYMBOL ":"; p = l2_pattern -> p ] ->
+        [ vars, ty ]
+    | clusters = LIST1 [
+        SYMBOL "(";
+        vars = LIST1 IDENT SEP SYMBOL ",";
+        ty = OPT [ SYMBOL ":"; p = l2_pattern -> p ];
+        SYMBOL ")" ->
+          vars, ty
       ] ->
-        ()
+        clusters
     ]
   ];
   induction_kind: [
-    [ IDENT "rec" -> ()
-    | IDENT "corec" -> ()
+    [ IDENT "rec" -> `Inductive
+    | IDENT "corec" -> `CoInductive
     ]
   ];
   let_defs: [
     [ defs = LIST1 [
         name = IDENT; args = bound_names;
-        index_name = OPT [ IDENT "on"; idx = IDENT -> () ];
-        ty = OPT [ SYMBOL ":" ; p = pattern -> () ];
-        SYMBOL <:unicode<def>> (* ≝ *); body = pattern ->
-          ()
+        index_name = OPT [ IDENT "on"; id = IDENT -> id ];
+        ty = OPT [ SYMBOL ":" ; p = l2_pattern -> p ];
+        SYMBOL <:unicode<def>> (* ≝ *); body = l2_pattern ->
+          let body = fold_binder `Lambda args body in
+          let ty = 
+            match ty with 
+            | None -> None
+            | Some ty -> Some (fold_binder `Pi args ty)
+          in
+          let rec position_of name p = function 
+            | [] -> None, p
+            | n :: _ when n = name -> Some p, p
+            | _ :: tl -> position_of name (p + 1) tl
+          in
+          let rec find_arg name n = function 
+            | [] -> fail loc (sprintf "Argument %s not found" name)
+            | (l,_) :: tl -> 
+                (match position_of name 0 l with
+                | None, len -> find_arg name (n + len) tl
+                | Some where, len -> n + where)
+          in
+          let index = 
+            match index_name with 
+            | None -> 0 
+            | Some name -> find_arg name 0 args
+          in
+          (Cic.Name name, ty), body, index
       ] SEP IDENT "and" ->
-        ()
+        defs
     ]
   ];
-  pattern_variable: [
-    [ SYMBOL "\\NUM"; id = IDENT -> ()
-    | SYMBOL "\\IDENT"; id = IDENT -> ()
-    | SYMBOL "\\FRESH"; id = IDENT -> ()
+  l2_pattern_variable: [
+    [ SYMBOL "\\NUM"; id = IDENT -> NumVar id
+    | SYMBOL "\\IDENT"; id = IDENT -> IdentVar id
+    | SYMBOL "\\FRESH"; id = IDENT -> FreshVar id
     ]
   ];
-  magic_pattern: [
-    [ SYMBOL "\\FOLD"; n = OPT NUMBER; [ IDENT "left" | IDENT "right" ];
-      LIST1 IDENT; SYMBOL "."; p1 = pattern;
-      OPT [ SYMBOL "\\LAMBDA"; LIST1 IDENT ]; p2 = pattern ->
-        ()
-    | SYMBOL "\\DEFAULT"; id = IDENT; p1 = pattern; p2 = pattern -> ()
+  l2_magic_pattern: [
+    [ SYMBOL "\\FOLD";
+      kind = [ IDENT "left" -> `Left | IDENT "right" -> `Right ];
+      base = l2_pattern;
+      SYMBOL "\\LAMBDA"; id = IDENT; recursive = l2_pattern ->
+        Fold (kind, base, [id], recursive)
+    | SYMBOL "\\DEFAULT"; some = l2_pattern; none = l2_pattern ->
+        Default (some, none)
     ]
   ];
-  pattern:
-    [ "letin" NONA
+  l2_pattern:
+    [ "0" [ ]
+    | "10" NONA (* let in *)
       [ IDENT "let"; var = possibly_typed_name; SYMBOL <:unicode<def>> (* ≝ *);
-        p1 = pattern; "in"; p2 = pattern ->
-          ()
+        p1 = l2_pattern; "in"; p2 = l2_pattern ->
+          return_term loc (LetIn (var, p1, p2))
       | IDENT "let"; k = induction_kind; defs = let_defs; IDENT "in";
-        body = pattern ->
-          ()
+        body = l2_pattern ->
+          return_term loc (LetRec (k, defs, body))
       ]
-    | "binder" RIGHTA
-      [ b = binder; bound_names; SYMBOL "."; body = pattern -> () ]
-    | "extension"
-      [ ]
-    | "apply" LEFTA
-      [ p1 = pattern; p2 = pattern -> () ]
-    | "simple" NONA
-      [ i = IDENT -> ()
-      | i = IDENT; s = explicit_subst -> ()
-      | n = NUMBER -> ()
-      | IMPLICIT -> ()
-      | m = META -> ()
-      | m = META; s = meta_subst -> ()
-      | s = sort -> ()
-      | s = SYMBOL -> ()
-      | u = URI -> ()
-      | outtyp = OPT [ SYMBOL "["; typ = pattern; SYMBOL "]" ];
-        IDENT "match"; t = pattern;
-        indty_ident = OPT [ SYMBOL ":"; id = IDENT ];
+    | "20" RIGHTA (* binder *)
+      [ b = binder; names = bound_names; SYMBOL "."; body = l2_pattern ->
+          return_term loc (fold_binder b names body)
+      ]
+    | "30" [ ]
+    | "40" [ ]
+    | "50" [ ]
+    | "60" [ ]
+    | "70" LEFTA (* apply *)
+      [ p1 = l2_pattern; p2 = l2_pattern ->
+          let rec aux = function
+            | Appl (hd :: tl)
+            | AttributedTerm (_, Appl (hd :: tl)) ->
+                aux hd @ tl
+            | term -> [term]
+          in
+          return_term loc (Appl (aux p1 @ [p2]))
+      ]
+    | "80" [ ]
+    | "90" NONA (* simple *)
+      [ id = IDENT -> return_term loc (Ident (id, None))
+      | id = IDENT; s = explicit_subst -> return_term loc (Ident (id, Some s))
+      | u = URI -> return_term loc (Uri (u, None))
+      | n = NUMBER -> prerr_endline "number"; return_term loc (Num (n, 0))
+      | IMPLICIT -> return_term loc (Implicit)
+      | m = META -> return_term loc (Meta (int_of_string m, []))
+      | m = META; s = meta_subst -> return_term loc (Meta (int_of_string m, s))
+      | s = sort -> return_term loc (Sort s)
+      | outtyp = OPT [ SYMBOL "["; ty = l2_pattern; SYMBOL "]" -> ty ];
+        IDENT "match"; t = l2_pattern;
+        indty_ident = OPT [ SYMBOL ":"; id = IDENT -> id ];
         IDENT "with"; SYMBOL "[";
         patterns = LIST0 [
           lhs = match_pattern; SYMBOL <:unicode<Rightarrow>> (* ⇒ *);
-          rhs = pattern ->
-            ()
+          rhs = l2_pattern ->
+            lhs, rhs
         ] SEP SYMBOL "|";
         SYMBOL "]" ->
-          ()
-      | SYMBOL "("; p1 = pattern; SYMBOL ":"; p2 = pattern; SYMBOL ")" -> ()
-      | SYMBOL "("; p = pattern; SYMBOL ")" -> ()
-      | v = pattern_variable -> ()
-      | m = magic_pattern -> ()
+          return_term loc (Case (t, indty_ident, outtyp, patterns))
+      | SYMBOL "("; p1 = l2_pattern; SYMBOL ":"; p2 = l2_pattern; SYMBOL ")" ->
+          return_term loc (Appl [ Symbol ("cast", 0); p1; p2 ])
+      | SYMBOL "("; p = l2_pattern; SYMBOL ")" -> p
+      | v = l2_pattern_variable -> return_term loc (Variable v)
+      | m = l2_magic_pattern -> return_term loc (Magic m)
       ]
+    | "100" [ ]
     ];
-END
 (* }}} *)
-
 (* {{{ Grammar for interpretation, notation level 3 *)
-GEXTEND Level3Parser
-  GLOBAL: level3_interpretation;
-  level3_interpretation: [ [ i = interpretation -> () ] ];
   argument: [
-    [ i = IDENT -> ()
-    | SYMBOL <:unicode<eta>> (* η *); SYMBOL "."; a = SELF -> ()
-    | SYMBOL <:unicode<eta>> (* η *); i = IDENT; SYMBOL "."; a = SELF -> ()
+    [ id = IDENT -> IdentArg id
+    | SYMBOL <:unicode<eta>> (* η *); SYMBOL "."; a = SELF -> EtaArg (None, a)
+    | SYMBOL <:unicode<eta>> (* η *); id = IDENT; SYMBOL "."; a = SELF ->
+        EtaArg (Some id, a)
+    ]
+  ];
+  level3_term: [
+    [ u = URI -> UriPattern u
+    | a = argument -> ArgPattern a
+    | SYMBOL "("; terms = LIST1 SELF; SYMBOL ")" ->
+        (match terms with
+        | [] -> assert false
+        | [term] -> term
+        | terms -> ApplPattern terms)
+    ]
+  ];
+(* }}} *)
+(* {{{ Notation glues *)
+  associativity: [
+    [ IDENT "left";  IDENT "associative" -> `Left
+    | IDENT "right"; IDENT "associative" -> `Right
     ]
   ];
-  term: [
-    [ u = URI -> ()
-    | a = argument -> ()
-    | SYMBOL "("; terms = LIST1 SELF; SYMBOL ")" -> ()
+  precedence: [ [ IDENT "at"; IDENT "precedence"; n = NUMBER -> n ] ];
+  notation: [
+    [ IDENT "notation"; p1 = level1_pattern; IDENT "for"; p2 = level2_pattern;
+      assoc = OPT associativity; prec = OPT precedence ->
+        ()
     ]
   ];
   interpretation: [
     [ IDENT "interpretation"; s = SYMBOL; args = LIST1 argument; IDENT "as";
-      t = term ->
+      t = level3_term ->
         ()
     ]
   ];
-END
 (* }}} *)
+END
 
 let exc_located_wrapper f =
   try
@@ -278,19 +354,192 @@ let exc_located_wrapper f =
       raise (Parse_error (floc, (Printexc.to_string exn)))
 
 let parse_syntax_pattern stream =
-  exc_located_wrapper
-    (fun () ->
-      (Level1Parser.Entry.parse level1_pattern (Level1Parser.parsable stream)))
+  exc_located_wrapper (fun () -> Grammar.Entry.parse level1_pattern stream)
 
 let parse_ast_pattern stream =
-  exc_located_wrapper
-    (fun () ->
-      (Level2Parser.Entry.parse level2_pattern (Level2Parser.parsable stream)))
+  exc_located_wrapper (fun () -> Grammar.Entry.parse level2_pattern stream)
 
 let parse_interpretation stream =
-  exc_located_wrapper
-    (fun () ->
-      (Level3Parser.Entry.parse level3_interpretation
-        (Level3Parser.parsable stream)))
+  exc_located_wrapper (fun () -> Grammar.Entry.parse level3_term stream)
+
+(** {2 Grammar extension} *)
+
+type associativity_kind = [ `Left | `Right | `None ]
+
+let symbol s = Gramext.Stoken ("SYMBOL", s)
+let ident s = Gramext.Stoken ("IDENT", s)
+let number s = Gramext.Stoken ("NUMBER", s)
+let term = Gramext.Sself
+
+type env_type = (string * (value_type * value)) list
+
+let rec pp_value =
+  function
+  | TermValue _ -> "@TERM@"
+  | StringValue s -> sprintf "\"%s\"" s
+  | NumValue n -> n
+  | OptValue (Some v) -> "Some " ^ pp_value v
+  | OptValue None -> "None"
+  | ListValue l -> sprintf "[%s]" (String.concat "; " (List.map pp_value l))
+
+let rec pp_value_type =
+  function
+  | TermType -> "Term"
+  | StringType -> "String"
+  | NumType -> "Number"
+  | OptType t -> "Maybe " ^ pp_value_type t
+  | ListType l -> "List " ^ pp_value_type l
+
+let pp_env env =
+  String.concat "; "
+    (List.map
+      (fun (name, (ty, value)) ->
+        sprintf "%s : %s = %s" name (pp_value_type ty) (pp_value value))
+      env)
+
+let make_action action bindings =
+  let rec aux (vl : env_type) =
+    function
+      [] ->
+        prerr_endline "aux: make_action";
+        Gramext.action (fun (loc: location) -> action vl loc)
+    | None :: tl ->
+        prerr_endline "aux: none";
+        Gramext.action (fun _ -> aux vl tl)
+    (* LUCA: DEFCON 3 BEGIN *)
+    | Some (name, TermType) :: tl ->
+        prerr_endline "aux: term";
+        Gramext.action
+          (fun (v:term) -> aux ((name, (TermType, (TermValue v)))::vl) tl)
+    | Some (name, StringType) :: tl ->
+        prerr_endline "aux: string";
+        Gramext.action
+          (fun (v:string) ->
+            aux ((name, (StringType, (StringValue v))) :: vl) tl)
+    | Some (name, NumType) :: tl ->
+        prerr_endline "aux: num";
+        Gramext.action
+          (fun (v:string) -> aux ((name, (NumType, (NumValue v))) :: vl) tl)
+    | Some (name, OptType t) :: tl ->
+        prerr_endline "aux: opt";
+        Gramext.action
+          (fun (v:'a option) ->
+            aux ((name, (OptType t, (OptValue v))) :: vl) tl)
+    | Some (name, ListType t) :: tl ->
+        prerr_endline "aux: list";
+        Gramext.action
+          (fun (v:'a list) ->
+            aux ((name, (ListType t, (ListValue v))) :: vl) tl)
+    (* LUCA: DEFCON 3 END *)
+  in
+    aux [] (List.rev bindings)
+
+let flatten_opt =
+  let rec aux acc =
+    function
+      [] -> List.rev acc
+    | None::tl -> aux acc tl
+    | Some hd::tl -> aux (hd::acc) tl
+  in
+  aux []
+
+  (* given a level 1 pattern computes the new RHS of "term" grammar entry *)
+let extract_term_production pattern =
+  let rec aux = function
+    | Literal l -> aux_literal l
+    | Layout l -> aux_layout l
+    | Magic m -> aux_magic m
+    | Variable v -> aux_variable v
+    | _ -> assert false
+  and aux_literal = function
+    | `Symbol s -> [None, symbol s]
+    | `Keyword s -> [None, ident s]
+    | `Number s -> [None, number s]
+  and aux_layout = function
+    | Sub (p1, p2) -> aux p1 @ [None, symbol "\\SUB"] @ aux p2
+    | Sup (p1, p2) -> aux p1 @ [None, symbol "\\SUP"] @ aux p2
+    | Below (p1, p2) -> aux p1 @ [None, symbol "\\BELOW"] @ aux p2
+    | Above (p1, p2) -> aux p1 @ [None, symbol "\\ABOVE"] @ aux p2
+    | Frac (p1, p2) -> aux p1 @ [None, symbol "\\FRAC"] @ aux p2
+    | Atop (p1, p2) -> aux p1 @ [None, symbol "\\ATOP"] @ aux p2
+    | Over (p1, p2) -> aux p1 @ [None, symbol "\\OVER"] @ aux p2
+    | Root (p1, p2) ->
+        [None, symbol "\\ROOT"] @ aux p2 @ [None, symbol "\\OF"] @ aux p1
+    | Sqrt p -> [None, symbol "\\SQRT"] @ aux p
+    | Break -> []
+    | Box (_, pl) -> List.flatten (List.map aux pl)
+  and aux_magic = function
+    | Opt p ->
+        let p_bindings, p_atoms = List.split (aux p) in
+        let p_names = flatten_opt p_bindings in
+        [ None,
+          Gramext.srules
+            [ [ Gramext.Sopt
+                  (Gramext.srules
+                    [ p_atoms,
+                      (make_action
+                        (fun (env : env_type) (loc : location) ->
+                          prerr_endline "inner opt action";
+                          env)
+                        p_bindings)])],
+              Gramext.action
+                (fun (env_opt : env_type option) (loc : location) ->
+                  match env_opt with
+                    Some env ->
+                      prerr_endline "opt action (Some _)";
+                      List.map
+                        (fun (name, (typ, v)) ->
+                          (name, (OptType typ, OptValue (Some v))))
+                        env
+                  | None -> 
+                      prerr_endline "opt action (None)";
+                      List.map
+                        (fun (name, typ) ->
+                          (name, (OptType typ, OptValue None)))
+                        p_names) ]]
+    | _ -> assert false
+  and aux_variable = function
+    | NumVar s -> [Some (s, NumType), number ""]
+    | TermVar s -> [Some (s, TermType), term]
+    | IdentVar s -> [Some (s, StringType), ident ""]
+    | Ascription (p, s) -> assert false (* TODO *)
+    | FreshVar _ -> assert false
+  in
+  aux pattern
+
+let level_of_int precedence =
+  (* TODO "mod" test to be removed as soon as we add all 100 levels *)
+  if precedence mod 10 <> 0 || precedence < 0 || precedence > 100 then
+    raise (Level_not_found precedence);
+  string_of_int precedence
+
+type rule_id = Token.t Gramext.g_symbol list
+
+let extend level1_pattern ?(precedence = 0) ?associativity action =
+  let p_bindings, p_atoms =
+    List.split (extract_term_production level1_pattern)
+  in
+  let level = level_of_int precedence in
+  let p_names = flatten_opt p_bindings in
+  let entry = Grammar.Entry.obj (l2_pattern: 'a Grammar.Entry.e) in
+  let _ =
+    prerr_endline (string_of_int (List.length p_bindings));
+    Grammar.extend
+      [ entry, Some (Gramext.Level level),
+        [ Some level,  (* TODO should we put None here? *)
+          associativity,
+          [ p_atoms, 
+            (make_action
+              (fun (env: env_type) (loc: location) -> (action env loc))
+              p_bindings) ]]]
+  in
+  p_atoms
+
+let delete atoms = Grammar.delete_rule l2_pattern atoms
+
+let print_l2_pattern () =
+  Grammar.print_entry Format.std_formatter (Grammar.Entry.obj l2_pattern);
+  Format.pp_print_flush Format.std_formatter ();
+  flush stdout
 
 (* vim:set encoding=utf8 foldmethod=marker: *)