parser.ml 23.2 KB
Newer Older
1 2
open Cduce_loc
(* let raise = Pervasives.raise *)
3
open Ast
4
open Ident
5
open Printf
6
open Ulexer
7

8
(*
9
let ()  = Grammar.error_verbose := true
10
*)
11

12 13
let tloc (i,j) = (i,j)
let nopos = (-1,-1)
14

15
let mk loc x = Cduce_loc.mk_located (tloc loc) x
16

17
exception Error of string
18
let error (i,j) s = Cduce_loc.raise_loc i j (Error s)
19
let error loc s = error (tloc loc) s
20

21
module Gram = Camlp4.Struct.Grammar.Static.Make(Ulexer)
22

23 24
let id_dummy = U.mk "$$$"

Pietro Abate's avatar
Pietro Abate committed
25
let ident_aux s =
26 27 28 29 30 31 32 33
  let b = Buffer.create (String.length s) in
  let rec aux i =
    if (i = String.length s) then Buffer.contents b
    else match s.[i] with
      | '\\' -> assert (s.[i+1] = '.'); Buffer.add_char b '.'; aux (i+2)
      | c -> Buffer.add_char b c; aux (i+1)
  in
  aux 0
34

Pietro Abate's avatar
Pietro Abate committed
35 36
let label s = U.mk (ident_aux s)
let ident s = U.mk (ident_aux s)
37

38 39 40 41 42 43
let prog    = Gram.Entry.mk "prog"
let top_phrases   = Gram.Entry.mk "toplevel phrases"
let expr    = Gram.Entry.mk "expression"
let pat     = Gram.Entry.mk "type/pattern expression"
let regexp  = Gram.Entry.mk "type/pattern regexp"
let keyword = Gram.Entry.mk "keyword"
44

45
let lop pos = Cduce_loc.loc_of_pos (tloc pos)
46
let exp pos e = LocatedExpr (lop pos,e)
47

48 49 50 51
let rec multi_prod loc = function
  | [ x ] -> x
  | x :: l -> mk loc (Prod (x, multi_prod loc l))
  | [] -> assert false
52

53
let rec tuple = function
54
  | [ x ] -> x
55
  | x :: l -> Pair (x, tuple l)
56
  | [] -> assert false
57

58
let tuple_queue =
59
  List.fold_right (fun x q -> Pair (x, q))
60

61
let char = mknoloc (Internal (Types.char Chars.any))
62
let string_regexp = Star (Elem char)
63

64
let seq_of_string s =
65 66
  let s = Encodings.Utf8.mk s in
  let rec aux i j =
67 68
    if Encodings.Utf8.equal_index i j then []
    else let (c,i) = Encodings.Utf8.next s i in c :: (aux i j)
69
  in
70
  aux (Encodings.Utf8.start_index s) (Encodings.Utf8.end_index s)
71

72
let parse_char loc s =
73 74
  match seq_of_string s with
    | [ c ] -> c
75
    | _ -> error loc "Character litteral must have length 1"
76

77 78
let include_stack = ref []

79 80 81 82
let protect_exn f g =
  try let x = f () in g (); x
  with e -> g (); raise e

83
let localize_exn f =
84 85
  try f ()
  with
86 87 88 89 90
  | Ulexer.Loc.Exc_located (_, (Location _ as e)) -> raise e
(*  | Camlp4.PreCast.Loc.Exc_located ((i,j), e) -> raise_loc i j e *)
  | Ulexer.Loc.Exc_located (loc, e) ->
      let i, j = Ulexer.Loc.start_off loc, Ulexer.Loc.stop_off loc in
      raise_loc i j e
91

92
let is_fun_decl =
93
   Gram.Entry.of_parser "[is_fun_decl]"
94 95
     (fun strm ->
       match Stream.npeek 3 strm with
96
	 | [ KEYWORD "fun", _; IDENT _, _; KEYWORD "(", _ ]
Pietro Abate's avatar
Pietro Abate committed
97
	 | [ KEYWORD "fun", _; IDENTPAR _, _;  _ ]
98
       | [ IDENTPAR _, _; _ ; _ ]
99
	 | [ IDENT _, _; KEYWORD "(", _; _ ] -> ()
100 101 102
	 | _ -> raise Stream.Failure
     )

103 104 105
let if_then_else cond e1 e2 =
  Match (cond, [(mk (0,0) (Cst (Atom (ident "true")))),e1;
		(mk (0,0) (Cst (Atom (ident "false")))),e2])
106

107 108 109
let logical_and e1 e2 = if_then_else e1 e2 cst_false
let logical_or e1 e2 = if_then_else e1 cst_true e2
let logical_not e = if_then_else e cst_false cst_true
110

111
let apply_op2_noloc op e1 e2 = Apply (Apply (Var (ident op), e1), e2)
112
let apply_op2 loc op e1 e2 = exp loc (apply_op2_noloc op e1 e2)
113

114 115
let set_ref e1 e2 = Apply (Dot (e1, U.mk "set"), e2)
let get_ref e = Apply (Dot (e, U.mk "get"), cst_nil)
116 117 118
let let_in e1 p e2 =  Match (e1, [p,e2])
let seq e1 e2 = let_in e1 pat_nil e2
let concat e1 e2 = apply_op2_noloc "@" e1 e2
119

120
EXTEND Gram
121
  GLOBAL: top_phrases prog expr pat regexp keyword;
122 123

  top_phrases: [
124
    [ l = LIST0 phrase; ";;" -> List.flatten l  ]
125
  ];
126 127

  prog: [
128
    [ l = LIST0 [ p = phrase ; OPT ";;" -> p ]; `EOI -> List.flatten l ]
129 130 131
  ];

  phrase: [
132
    [ (f,p,e) = let_binding ->
133 134
	if f then [ mk _loc (FunDecl e) ] else
	  [ mk _loc (LetDecl (p,e)) ]
135
    | (_,p,e1) = let_binding; "in"; e2 = expr LEVEL "top"->
136
        [ mk _loc (EvalStatement (exp _loc (let_in e1 p e2))) ]
137
    | "type"; x = IDENTPAR; pargs = LIST1 [ x = PVAR -> ident x ] SEP ","; ")"; "="; t = pat ->
Pietro Abate's avatar
Pietro Abate committed
138 139 140
          [ mk _loc (TypeDecl ((lop _loc,ident x),pargs,t)) ]
    | "type"; x = located_ident; "="; t = pat ->
        [ mk _loc (TypeDecl (x,[],t)) ]
141
    | "using"; name = IDENT; "="; cu = [ x = IDENT -> x | x = STRING -> x ] ->
142
	[ mk _loc (Using (U.mk name, U.mk cu)) ]
143
    | "open"; ids = LIST1 ident_or_keyword SEP "." ->
144
	let ids = List.map (fun x -> ident x) ids in
145
	[ mk _loc (Open ids) ]
146
    | "schema"; name = IDENT; "="; uri = STRING ->
147
	protect_op "schema";
148
        [ mk _loc (SchemaDecl (U.mk name, uri)) ]
149 150 151 152
    | n = namespace_binding ->
	let d = match n with
	    | `Prefix (name,ns) ->  Namespace (name, ns)
	    | `Keep b -> KeepNs b in
153
	[ mk _loc d ]
154
    | n = namespace_binding; "in"; e2 = expr LEVEL "top" ->
155
	let e =
156 157 158 159
	  match n with
	    | `Prefix (name,ns) -> NamespaceIn (name, ns, e2)
	    | `Keep b -> KeepNsIn (b,e2)
	in
160 161 162 163
	[ mk _loc (EvalStatement (exp _loc e)) ]
    | "debug"; d = debug_directive -> [ mk _loc (Directive (`Debug d)) ]
    | "#"; IDENT "verbose" -> [ mk _loc (Directive `Verbose) ]
    | "#"; IDENT "silent" -> [ mk _loc (Directive `Silent) ]
164 165 166
    | "#"; IDENT "utf8" -> Ulexer.enc := Ulexing.Utf8; [ ]
    | "#"; IDENT "latin1" -> Ulexer.enc := Ulexing.Latin1; [ ]
    | "#"; IDENT "ascii" -> Ulexer.enc := Ulexing.Ascii; [ ]
167 168
    | "#"; IDENT "quit" -> [ mk _loc (Directive `Quit) ]
    | "#"; IDENT "env" -> [ mk _loc (Directive `Env) ]
169
    | "#"; IDENT "print_type"; t = pat ->
170 171 172
        [ mk _loc (Directive (`Print_type t)) ]
    | "#"; IDENT "dump_value"; e = expr -> [ mk _loc (Directive (`Dump e)) ]
    | "#"; IDENT "reinit_ns" -> [ mk _loc (Directive `Reinit_ns) ]
173 174
    | "#"; IDENT "help" -> [ mk _loc (Directive (`Help None)) ]
    | "#"; IDENT "help"; "debug" -> [ mk _loc (Directive (`Help (Some "debug"))) ]
175
    | "#"; IDENT "builtins" -> [ mk _loc (Directive `Builtins) ]
176
    | "include"; s = STRING ->
177
	protect_op "File inclusion";
178
	let s = Cduce_loc.resolve_filename s in
179
	(* avoid looping; should issue an error ? *)
180 181
	(* it is possible to have looping with x/../x/../x/.. ....
	   Need to canonicalize filename *)
182
	if List.mem s !include_stack then []
183 184
	else (
	  include_stack := s :: !include_stack;
185
	  Cduce_loc.push_source (`File s);
186 187
	  let saved_enc = !Ulexer.enc in
	  Ulexer.enc := Ulexing.Latin1;
188 189 190
	  protect_exn
	    (fun () ->
	       let chan = open_in s in
191 192 193
	       protect_exn
		 (fun () ->
		    let input = Stream.of_channel chan in
194
		    localize_exn (fun () -> Gram.parse prog Ulexer.Loc.ghost input))
195
		 (fun () -> close_in chan))
196
	    (fun () ->
197
	       Ulexer.enc := saved_enc;
198
	       Cduce_loc.pop_source ();
199
	       include_stack := List.tl !include_stack)
200
	)
201
    ] |
202
    [ e = expr -> [ mk _loc (EvalStatement e) ]
203 204 205 206
    ]
  ];

  debug_directive: [
207 208 209 210 211
    [ IDENT "filter"; t = pat; p = pat -> `Filter(t,p)
    | IDENT "accept"; p = pat -> `Accept p
    | IDENT "compile"; t = pat; p = LIST1 pat -> `Compile (t,p)
    | IDENT "sample"; t = pat -> `Sample t
    | IDENT "subtype"; t1 = pat; t2 = pat -> `Subtype (t1,t2)
212
    | IDENT "single"; t = pat -> `Single t
213 214
    | IDENT "typed"; e = expr -> `Typed e
    | IDENT "lambda"; e = expr -> `Lambda e
215
    ]
216
  ];
217

218
  keyword: [
219
    [ a =
220 221 222
	[ "map" | "match" | "with" | "try" | "xtransform"
	| "if" | "then"	| "else"
	| "transform" | "fun" | "in"
223
	| "let" | "type" | "debug" | "include"
224
        | "and" | "or" | "validate" | "schema" | "namespace" | "ref" | "alias"
225
	| "not" | "as" | "where" | "select" | "from" | "open"
226 227 228 229 230
	]
	-> a
    ]
  ];

231 232 233 234 235
  ident_or_keyword: [
    [ s = IDENT -> s
    | s = keyword -> s ]
  ];

236 237
  expr: [
    "top" RIGHTA
238
    [ "match"; e = SELF; "with"; b = branches ->
239
	exp _loc (Match (e,b))
240
    | "try"; e = SELF; "with"; b = branches ->
241
	exp _loc (Try (e,b))
242
    | "map"; e = SELF; "with"; b = branches ->
243
	exp _loc (Map (e,b))
244
    | "xtransform"; e = SELF; "with"; b = branches ->
245
	exp _loc (Xtrans (e,b))
246 247
    | "if"; e = SELF; "then"; e1 = SELF ->
	exp _loc (if_then_else e e1 cst_nil)
248
    | "if"; e = SELF; "then"; e1 = SELF; "else"; e2 = SELF ->
249
	exp _loc (if_then_else e e1 e2)
250
    | "transform"; e = SELF; "with"; b = branches ->
251
	exp _loc (Transform (e,b))
252
    | "validate"; e = SELF; "with"; (schema, typ) = schema_ref ->
253
        exp _loc (Validate (e, [schema;typ]))
254
    | "select"; e = SELF; "from";
255
      l = LIST1 [ x = pat ; "in"; e = expr -> (x,e)] SEP "," ;
256 257
      cond = [ "where"; c = LIST1 [ expr ] SEP "and" -> c
	     | -> [] ] -> exp _loc (SelectFW (e,l,cond))
258
    | "fun"; (f,a,b) = fun_decl ->
259
	exp _loc (Abstraction { fun_name = f; fun_iface = a; fun_body = b })
260
    | (_,p,e1) = let_binding; "in"; e2 = expr LEVEL "top"->
261
        exp _loc (let_in e1 p e2)
262 263
    | n = namespace_binding; "in"; e2 = expr LEVEL "top" ->
	(match n with
264 265
	   | `Prefix (name,ns) -> exp _loc (NamespaceIn (name, ns, e2))
	   | `Keep f -> exp _loc (KeepNsIn (f,e2)))
Pietro Abate's avatar
Pietro Abate committed
266 267 268 269
    | e = expr; ":"; p = pat -> exp _loc (Forget (e,p))
    | e = expr; ":"; "?"; p = pat -> exp _loc (Check (e,p))
    | e1 = expr; ";"; e2 = expr -> exp _loc (seq e1 e2)
    | "ref"; p = pat; e = expr -> exp _loc (Ref (e,p))
270
    | "not"; e = expr -> exp _loc (logical_not e)
271
    ]
Pietro Abate's avatar
Pietro Abate committed
272 273
    | [ e1 = expr; ":="; e2 = expr -> exp _loc  (set_ref e1 e2) ]
    | [ e1 = expr; op = ["=" | "<=" | "<<" | ">>" | ">=" ]; e2 = expr ->
274 275 276
	let op = match op with
	  | "<<" -> "<"
	  | ">>" -> ">"
Pietro Abate's avatar
Pietro Abate committed
277 278
	  | s -> s
      in
279
	apply_op2 _loc op e1 e2
280
    ]
Pietro Abate's avatar
Pietro Abate committed
281
    | [ e1 = expr; op = ["+" | "-" | "@" ]; e2 = expr -> apply_op2 _loc op e1 e2
282
    | e1 = expr; ["||" | "or"]; e2 = expr -> exp _loc (logical_or e1 e2)
Pietro Abate's avatar
Pietro Abate committed
283
    | e = expr; "\\"; l = ident_or_keyword -> exp _loc (RemoveField (e, label l))
284
    ]
Pietro Abate's avatar
Pietro Abate committed
285
    | [ e1 = expr; op = ["*"]; e2 = expr -> apply_op2 _loc op e1 e2
286
    | e1 = expr; "&&"; e2 = expr -> exp _loc (logical_and e1 e2)
287
    | e = expr; op = "/"; p = pat LEVEL "simple" ->
288
	(* transform e with <(Atom)>[($$$::t|_)*] -> [$$$] *)
289
	let tag = mk _loc (Internal (Types.atom Atoms.any)) in
290 291
	let att = mk _loc (Internal Types.Record.any) in
	let any = mk _loc (Internal Types.any) in
Pietro Abate's avatar
Pietro Abate committed
292
	let re = Star(Alt(SeqCapture((noloc,id_dummy),Elem p), Elem any)) in
293
	let ct = mk _loc (Regexp re) in
Pietro Abate's avatar
Pietro Abate committed
294
      let p = mk _loc (XmlT (tag, multi_prod _loc [att;ct])) in
295
	exp _loc (Transform (e,[p, Var id_dummy]))
296
    | e = expr; "/@"; a = ident_or_keyword ->
297
	(* transform e with <(Atom) {a=$$$}>_ -> [$$$] *)
298
        let tag = mk _loc (Internal (Types.atom Atoms.any)) in
299
        let any = mk _loc (Internal Types.any) in
Pietro Abate's avatar
Pietro Abate committed
300
        let att = mk _loc (Record (true, [(label a, (mk _loc (PatVar([id_dummy],[])), None))])) in
301
        let p = mk _loc (XmlT (tag, multi_prod _loc [att;any])) in
302
        let t = (p, Pair (Var id_dummy,cst_nil)) in
303
        exp _loc (Transform (e,[t]))
304
     | e = expr; "//" ; p = pat ->
305 306
	 (* let $xstack=ref [p*] [] in
            let f  ( x : [Any*]) : [Any*] =
307 308 309
                     xtransform x with $$$ & p & <_ ..>[y::Any* ] ->  $stack := !$stack @ [$$$] ; f y
            in let _ =f e in !$stack *)

310
	 let stk = U.mk "$stack" in
311 312 313
	 let y = U.mk "y" in
	 let x = U.mk "x" in
	 let f = U.mk "f" in
314
	 let assign =
Pietro Abate's avatar
Pietro Abate committed
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
         set_ref
          (Var stk)
          (concat (get_ref (Var stk)) (Pair (Var id_dummy,cst_nil))) in
          let tag = mknoloc (Internal (Types.atom Atoms.any)) in
          let att = mknoloc (Internal Types.Record.any) in
          let any = mknoloc (Internal Types.any) in
          let re = (SeqCapture((noloc,y),Star(Elem(any)))) in
          let ct = mknoloc (Regexp re) in
          let children = mknoloc (XmlT (tag, multi_prod _loc [att;ct])) in
          let capt = mknoloc (And (mknoloc (And (mknoloc (PatVar([id_dummy],[])),p)),children)) in
          let assign = seq assign ((Apply(Var(f),Var(y)))) in
          let xt = Xtrans ((Var x),[capt,assign]) in
          let rf = Ref (cst_nil, mknoloc (Regexp (Star(Elem p)))) in
          let targ = mknoloc (Regexp(Star(Elem(any)))) in
          let tres = targ in
          let arg = mknoloc(PatVar ([x],[])) in
          let abst = {fun_name = Some (lop _loc,ident "f") ; fun_iface = [(targ, tres)] ;fun_body = [(arg,xt)] } in
          let body = 
            let_in rf (mknoloc (PatVar ([stk],[])))
            (let_in ((Abstraction abst)) (mknoloc (PatVar ([ident "f"],[])))
            (let_in ((Apply(Var(f) , e) )  ) (mknoloc (Internal Types.any)) (get_ref (Var stk))))
336
	 in
337
	 exp _loc body
338
    ]
339
    | [
Pietro Abate's avatar
Pietro Abate committed
340 341 342 343 344
      a = IDENTPAR; l = LIST1 expr SEP ","; ")" ->
        let e1 = exp _loc (Var (ident a)) in
        let e2 = exp _loc (tuple l) in
        exp _loc (Apply (e1,e2))
    | e1 = SELF; IDENT "div"; e2 = expr -> apply_op2 _loc "/" e1 e2
345 346
    | e1 = SELF; IDENT "mod"; e2 = expr -> apply_op2 _loc "mod" e1 e2
    | e1 = SELF; e2 = expr -> exp _loc (Apply (e1,e2))
347 348
    ]

Pietro Abate's avatar
Pietro Abate committed
349
    | "no_appl" [ e = expr;  "."; l = ident_or_keyword;
350 351 352
      tyargs = [ "with"; "{"; tyargs = LIST0 pat; "}" -> Some tyargs
      | -> None ] ->
	let e = Dot (e,label l) in
353
	match tyargs with None -> exp _loc e | Some tyargs ->
354
	  exp _loc (TyArgs (e,tyargs))
355 356
    ]
    | [
357
      "("; l = LIST1 expr SEP ","; ")" -> exp _loc (tuple l)
358
    | "[";  l = LIST0 seq_elem; e = OPT [ ";"; e = expr -> e ];
359
      loc_end = ["]" -> _loc] ->
360
	let e = match e with Some e -> e | None -> cst_nil in
361 362
        let e = exp loc_end e in
        let (_,loc_end) = loc_end in
363
	let l = List.fold_right
364 365
		  (fun x q ->
		     match x with
366
		       | `String (loc,i,j,s) -> exp loc (String (i,j,s,q))
367
		       | `Elems ((loc,_),x) -> exp (loc,loc_end) (Pair(x,q))
368
		       | `Explode x -> concat x q
369 370
		  ) l e
	in
371
	exp _loc l
372
    | "<"; t = [ "("; e = expr; ")" -> e
373
	       | a = tag -> exp _loc a
374
	       ];
375
	a = expr_attrib_spec; ">"; c = expr ->
376
	  exp _loc (Xml (t, Pair (a,c)))
377
    | "{"; r = expr_record_spec; "}" -> r
378
    | s = STRING ->
379
	let s = U.mk s in
380 381 382 383
	exp _loc (String (U.start_index s, U.end_index s, s, cst_nil))
    | a = IDENT -> exp _loc (Var (ident a))
    | "!"; e = expr -> exp _loc (get_ref e)
    | i = INT -> exp _loc (Integer (Intervals.V.mk i))
384
    | "`"; a = tag -> a
385
    | c = char -> exp _loc (Char c)
386 387 388
    ]

  ];
389

390
  tag: [ [ a = ident_or_keyword -> exp _loc (Atom (ident a)) ] ];
391 392

  tag_type: [
393
    [ "_" ->  mk _loc (Internal (Types.atom Atoms.any))
394
    | a = ident_or_keyword -> mk _loc (Cst (Atom (ident a)))
395
    | t = ANY_IN_NS -> mk _loc (NsT (ident t))
396 397 398
    ]
  ];

399
  seq_elem: [
400
    [ x = STRING2 ->
401 402
      let s = U.mk x in
      `String (_loc, U.start_index s, U.end_index s, s)
403
    | e = expr LEVEL "no_appl" -> `Elems (_loc,e)
404
    | "!"; e = expr LEVEL "no_appl" -> `Explode e
405 406
    ]
  ];
407

408
  namespace_binding: [
409
    [ "namespace"; r = [
410
	[ name =
411
	    [ name = ident_or_keyword; "=" -> ident name
412
	    | -> U.mk "" ];
413
	  ns = ns_expr -> `Prefix (name,ns)
414 415 416
	| IDENT "on" -> `Keep true
	| IDENT "off" -> `Keep false ]
      ] -> r ]
417 418
  ];

419
  ns_expr: [
420 421
    [ uri = STRING -> `Uri (Ns.Uri.mk (ident uri))
    | ids = LIST1 ident_or_keyword SEP "." ->
422 423 424 425
	let ids = List.map (fun x -> ident x) ids in
	`Path ids ]
  ];

426
  let_binding: [
427 428
    [ "let"; is_fun_decl; OPT "fun"; (f,a,b) = fun_decl ->
	let f = match f with Some x -> x | None -> assert false in
Pietro Abate's avatar
Pietro Abate committed
429
      let p = mk _loc (PatVar([snd f],[])) in
430
	let abst = { fun_name = Some f; fun_iface = a; fun_body = b } in
431
        let e = exp _loc (Abstraction abst) in
432
        (true,p,e)
433 434
    | "let"; p = pat; "="; e = expr -> (false,p,e)
    | "let"; p = pat; ":"; t = pat; "="; e = expr -> (false,p, Forget (e,t))
435
    | "let"; p = pat; ":"; "?"; t = pat; "="; e = expr ->
436
	(false,p, Check (e,t))
437
    ]
438 439
  ];

440
 fun_decl_after_lparen: [
Pietro Abate's avatar
Pietro Abate committed
441
  (* need an hack to do this, because both productions would
442
   match   [ OPT IDENT; "("; pat ] .... *)
443 444 445 446 447
   [ p1 = pat LEVEL "no_arrow";
     res = [ "->"; p2 = pat;
	     a = [ ";"; a = LIST0 arrow SEP ";" -> a | -> [] ];
	     ")"; b = branches -> `Classic (p2,a,b)
	   | ":"; targ1 = pat;
448
	     args = LIST0 [ ","; arg = pat; ":"; targ = pat -> (arg,targ) ];
449
	     ")";
450
	     others = LIST0
451
			[ "(";
452 453
			  args =
			    LIST1
454 455 456
			      [ arg = pat; ":"; targ = pat -> (arg,targ) ]
			      SEP ",";
			  ")" -> args ];
457
	     ":"; tres = pat ;
458
	     "="; body = expr ->
459
	       `Compact (targ1,args,others,tres,body)
Pietro Abate's avatar
Pietro Abate committed
460
     ] ->
461 462
       match res with
	 | `Classic (p2,a,b) -> (p1,p2)::a,b
463 464 465 466 467 468 469 470 471
	 | `Compact (targ1,args,others,tres,body) ->
	     let mkfun args =
	       multi_prod nopos (List.map snd args),
	       multi_prod nopos (List.map fst args)
	     in
	     let (tres,body) =
	       List.fold_right
		 (fun args (tres,body) ->
		    let (targ,arg) = mkfun args in
472 473
		    let e = Abstraction
			      { fun_name = None; fun_iface = [targ,tres];
474 475 476 477 478 479 480
				fun_body = [arg,body] } in
		    let t = mknoloc (Arrow (targ,tres)) in
		    (t,e)
		 )
		 others (tres,body) in
	     let (targ,arg) = mkfun ((p1,targ1) :: args) in
	     [(targ,tres)],[(arg,body)]
Pietro Abate's avatar
Pietro Abate committed
481 482
    ]
  ];
483 484 485


 fun_decl: [
486
   [ f = OPT located_ident; "("; (a,b) = fun_decl_after_lparen -> (f,a,b)
487
   | f = IDENTPAR; (a,b) = fun_decl_after_lparen -> (Some (lop _loc,ident f),a,b)
488
   ]
489 490
 ];

491
 arrow: [
492
    [ t1 = pat LEVEL "no_arrow"; "->"; t2 = pat -> (t1,t2)]
493 494 495
  ];

  branches: [
496
    [ OPT "|"; l = LIST1 branch SEP "|" -> l ]
497 498 499
  ];

  branch: [
500
    [ p = pat LEVEL "no_arrow"; "->"; e = expr -> (p,e) ]
501 502
  ];

503 504
  regexp: [
    [ x = regexp; "|"; y = regexp ->
505
	match (x,y) with
506
	  | Elem x, Elem y -> Elem (mk _loc (Or (x,y)))
507
	  | _ -> Alt (x,y)
508
    ]
509
  | [ x = regexp; y = regexp -> Seq (x,y) ]
510 511
  | [ x = regexp; "&"; y = regexp ->
	match (x,y) with
512 513
	  | Elem x, Elem y -> Elem (mk _loc (And (x,y)))
	  | _ -> error _loc "Conjunction not allowed in regular expression"
514
    ]
Pietro Abate's avatar
Pietro Abate committed
515
  | [ a = IDENT; "::"; x = regexp -> SeqCapture ((lop _loc,ident a),x) ]
516 517 518 519
  | [ x = regexp; "*" -> Star x
    | x = regexp; "*?" -> WeakStar x
    | x = regexp; "+" -> Seq (x, Star x)
    | x = regexp; "+?" -> Seq (x, WeakStar x)
520
    | x = regexp; "?" ->  Alt (x, Epsilon)
521
    | x = regexp; "??" -> Alt (Epsilon, x)
522 523 524 525 526
    | x = regexp; "**"; i = INT ->
	let rec aux i accu =
	  if (i = 0) then accu
	  else aux (pred i) (Seq (x, accu))
	in
527 528
	let i =
	  try
529 530 531
	    let i = int_of_string i in
	    if (i > 1024) then raise Exit else i
	      (* We cannot handle type that huge... *)
532
	  with Failure _ | Exit -> error _loc "Repetition number too large"
533
	in
534
	if (i <= 0) then
535
	  error _loc "Repetition number must be a positive integer";
536 537
	aux i Epsilon
    ]
538
  | [ "("; x = LIST1 regexp SEP ","; ")" ->
539 540 541
	(match x with
	  | [ x ] -> x
	  | _ ->
542 543
	      let x =
		List.map
544 545
		  (function
		     | Elem x -> x
546
		     | _ -> error _loc
547 548
			 "Mixing regular expressions and products")
		  x in
549
	      Elem (multi_prod _loc x))
550
    | "("; a = IDENT; ":="; c = expr; ")" ->
551
	Elem (mk _loc (Constant ((ident a,c))))
552
    | "/"; p = pat LEVEL "simple" -> Guard p
553
    | IDENT "PCDATA" -> string_regexp
554
    | i = STRING2; "--"; j = STRING2 ->
555 556 557
      let i = Chars.V.mk_int (parse_char _loc i)
      and j = Chars.V.mk_int (parse_char _loc j) in
      Elem (mk _loc (Internal (Types.char (Chars.char_class i j))))
558
    | s = STRING2 ->
559
	List.fold_right
560
	  (fun c accu ->
561
	     let c = Chars.V.mk_int c in
562
	     let c = Chars.atom c in
563
	     Seq (Elem (mknoloc (Internal (Types.char c))), accu))
564
	  (seq_of_string s)
565
	  Epsilon ]
Pietro Abate's avatar
Pietro Abate committed
566
    | [ e = pat LEVEL "simple" -> Elem e ]
567 568
  ];

569
  schema_ref: [
570
    [ schema = IDENT; "."; typ = ident_or_keyword -> (U.mk schema, ident typ)
571 572 573
    ]
  ];

574
  located_ident: [ [ a = ident_or_keyword -> (lop _loc,ident a) ] ];
575

576
  pat: [
Pietro Abate's avatar
Pietro Abate committed
577
    [ x = pat; "where";
Pietro Abate's avatar
Pietro Abate committed
578
      b = LIST1 [ x = located_ident; "="; y = pat -> (x,[],y) ] SEP "and" -> 
Pietro Abate's avatar
Pietro Abate committed
579
        mk _loc (Recurs (x,b)) ]
580 581 582
    | RIGHTA [ x = pat; "->"; y = pat -> mk _loc (Arrow (x,y))
             | x = pat; "@"; y = pat -> mk _loc (Concat (x,y))
             | x = pat; "+"; y = pat -> mk _loc (Merge (x,y)) ]
583 584
    | "no_arrow" [ x = pat; "|"; y = pat -> mk _loc (Or (x,y)) ]
    | "simple" [ x = pat; "&"; y = pat -> mk _loc (And (x,y))
Pietro Abate's avatar
Pietro Abate committed
585
	         | x = pat; "\\"; y = pat -> mk _loc (Diff (x,y)) ]
Pietro Abate's avatar
Pietro Abate committed
586
    | "var" [ x = PVAR -> 
Pietro Abate's avatar
Pietro Abate committed
587
        mk _loc (Internal (Types.var (Var.mk (ident_aux x)))) ]
588
    |
589
      [ "{"; r = record_spec; "}" -> r
590
      | "ref"; p = pat ->
591
	  let get_fun = mk _loc (Arrow (pat_nil, p))
592
	  and set_fun = mk _loc (Arrow (p, pat_nil))in
593
	  let fields =
594
	    [ label "get", (get_fun, None); label "set", (set_fun, None) ] in
595 596
	  mk _loc (Record (false, fields))
      | "_" -> mk _loc (Internal Types.any)
597
      | "("; a = IDENT; ":="; c = expr; ")" ->
598
	  mk _loc (Constant (ident a,c))
599
      | "!"; a = IDENT ->
600
	  mk _loc (Internal (Types.abstract (Types.Abstracts.atom a)))
601
      | id = IDENTPAR; pargs = LIST1 pat SEP ","; ")" ->
Pietro Abate's avatar
Pietro Abate committed
602 603 604
            mk _loc (PatVar ([ident id],pargs))
      | ids = LIST1 ident_or_keyword SEP "." ->
          mk _loc (PatVar (List.map ident ids,[]))
605 606
      | i = INT ; "--"; j = INT ->
          let i =  Intervals.V.mk i
607
	  and j =  Intervals.V.mk j in
608
          mk _loc (Internal (Types.interval (Intervals.bounded i j)))
609
      | i = INT ->
610
          let i =  Intervals.V.mk i  in
611
          mk _loc (Internal (Types.interval (Intervals.atom i)))
612
      | "*"; "--"; j = INT ->
613
	  let j =  Intervals.V.mk j in
614
          mk _loc (Internal (Types.interval (Intervals.left j)))
615
      | i = INT; "--"; "*" ->
616
	  let i = Intervals.V.mk i in
617
          mk _loc (Internal (Types.interval (Intervals.right i)))