parser.ml 22.5 KB
Newer Older
1 2
#load "pa_extend.cmo";;

3 4
open Location
open Ast
5
open Ident
6
open Printf
7

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

12 13 14 15 16 17
let tloc (i,j) = (i.Lexing.pos_cnum,j.Lexing.pos_cnum)
let nopos = (Lexing.dummy_pos, Lexing.dummy_pos)


let mk loc x = Location.mk (tloc loc) x

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

22
let gram    = Grammar.gcreate Ulexer.lex
23

24 25 26 27 28 29 30 31 32 33 34
let id_dummy = U.mk "$$$"

let ident s =
  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
35

36 37
let label s = U.mk (ident s)
let ident s = U.mk (ident s)
38

39
let prog    = Grammar.Entry.create gram "prog"
40
let top_phrases   = Grammar.Entry.create gram "toplevel phrases"
41 42 43
let expr    = Grammar.Entry.create gram "expression"
let pat     = Grammar.Entry.create gram "type/pattern expression"
let regexp  = Grammar.Entry.create gram "type/pattern regexp"
44
let keyword = Grammar.Entry.create gram "keyword"
45
		
46 47
let lop pos = loc_of_pos (tloc pos)
let exp pos e = LocatedExpr (lop pos,e)
48

49 50 51 52 53
let rec multi_prod loc = function
  | [ x ] -> x
  | x :: l -> mk loc (Prod (x, multi_prod loc l))
  | [] -> assert false
      
54
let rec tuple = function
55
  | [ x ] -> x
56
  | x :: l -> Pair (x, tuple l)
57
  | [] -> assert false
58 59

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


63
let char = mknoloc (Internal (Types.char Chars.any))
64
let string_regexp = Star (Elem char)
65
	       
66
let seq_of_string s =
67 68
  let s = Encodings.Utf8.mk s in
  let rec aux i j =
69 70
    if Encodings.Utf8.equal_index i j then []
    else let (c,i) = Encodings.Utf8.next s i in c :: (aux i j)
71
  in
72
  aux (Encodings.Utf8.start_index s) (Encodings.Utf8.end_index s)
73

74

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

80 81
let include_stack = ref []

82 83 84 85
let protect_exn f g =
  try let x = f () in g (); x
  with e -> g (); raise e

86 87 88 89
let localize_exn f = 
  try f ()
  with
  | Stdpp.Exc_located (_, (Location _ as e)) -> raise e
90 91
(*  | Stdpp.Exc_located ((i,j), e) -> raise_loc i j e *)
  | Stdpp.Exc_located ((i,j), e) -> raise_loc i.Lexing.pos_cnum j.Lexing.pos_cnum e
92

93 94 95 96
let is_fun_decl =
   Grammar.Entry.of_parser gram "[is_fun_decl]"
     (fun strm ->
       match Stream.npeek 3 strm with
97 98
	 | [ ("", "fun"); ("IDENT", _); ("", "(") ]
	 | [ ("IDENT", _) ; ("", "(") ; _ ] -> ()
99 100 101
	 | _ -> raise Stream.Failure
     )

102 103 104 105 106 107 108 109 110
let is_capture =
   Grammar.Entry.of_parser gram "[is_capture]"
     (fun strm ->
       match Stream.npeek 2 strm with
	 | [ ("IDENT", _) ; ("", "::") ; _ ] -> ()
	 | _ -> raise Stream.Failure
     )


111 112 113 114 115
let if_then_else cond e1 e2 = Match (cond, [pat_true,e1; pat_false,e2])
 
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
116

117
let apply_op2_noloc op e1 e2 = Apply (Apply (Var (ident op), e1), e2)
118
let apply_op2 loc op e1 e2 = exp loc (apply_op2_noloc op e1 e2)
119
 
120 121
let set_ref e1 e2 = Apply (Dot (e1, U.mk "set"), e2)
let get_ref e = Apply (Dot (e, U.mk "get"), cst_nil)
122 123 124
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
125

126
EXTEND
127
  GLOBAL: top_phrases prog expr pat regexp keyword;
128 129

  top_phrases: [
130
    [ l = LIST0 phrase; ";;" -> List.flatten l  ]
131
  ];
132 133

  prog: [
134
    [ l = LIST0 [ p = phrase ; OPT ";;" -> p ]; EOI -> List.flatten l ]
135 136 137
  ];

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

  debug_directive: [
209 210 211 212 213
    [ 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)
214
    | IDENT "single"; t = pat -> `Single t
215
    ]
216
  ];
217

218 219 220 221 222
  keyword: [
    [ a = 
	[ "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
  expr: [
    "top" RIGHTA
233
    [ "match"; e = SELF; "with"; b = branches -> 
234
	exp _loc (Match (e,b))
235
    | "try"; e = SELF; "with"; b = branches -> 
236
	exp _loc (Try (e,b))
237
    | "map"; e = SELF; "with"; b = branches -> 
238
	exp _loc (Map (e,b))
239
    | "xtransform"; e = SELF; "with"; b = branches -> 
240
	exp _loc (Xtrans (e,b))
241
    | "if"; e = SELF; "then"; e1 = SELF; "else"; e2 = SELF ->
242
	exp _loc (if_then_else e e1 e2)
243
    | "transform"; e = SELF; "with"; b = branches -> 
244
	exp _loc (Transform (e,b))
245
    | "validate"; e = SELF; "with"; (schema, typ) = schema_ref ->
246
        exp _loc (Validate (e, [schema;typ]))
247 248 249
    | "select"; e = SELF; "from"; 
      l = LIST1 [ x = pat ; "in"; e = expr -> (x,e)] SEP "," ;
      cond = [ "where"; c = LIST1 [ expr ] SEP "and" -> c 
250
	     | -> [] ] -> exp _loc (SelectFW (e,l,cond)) 
251
    | "fun"; (f,a,b) = fun_decl ->
252
	exp _loc (Abstraction { fun_name = f; fun_iface = a; fun_body = b })
253
    | (_,p,e1) = let_binding; "in"; e2 = expr LEVEL "top"->
254
        exp _loc (let_in e1 p e2)
255 256
    | n = namespace_binding; "in"; e2 = expr LEVEL "top" ->
	(match n with
257 258
	   | `Prefix (name,ns) -> exp _loc (NamespaceIn (name, ns, e2))
	   | `Keep f -> exp _loc (KeepNsIn (f,e2)))
259
    | e = expr; ":"; p = pat ->
260
	exp _loc (Forget (e,p))
261
    | e = expr; ":"; "?"; p = pat ->
262
	exp _loc (Check (e,p))
263
    | e1 = expr; ";"; e2 = expr ->
264
	exp _loc (seq e1 e2) 
265
    | "ref"; p = pat; e = expr ->
266 267
	exp _loc (Ref (e,p))
    | "not"; e = expr -> exp _loc (logical_not e)
268 269
    ]
    |
270
    [ e1 = expr; ":="; e2 = expr -> exp _loc  (set_ref e1 e2)
271
    ]
272 273 274 275 276 277
    | 
    [ e1 = expr; op = ["=" | "<=" | "<<" | ">>" | ">=" ]; e2 = expr -> 
	let op = match op with
	  | "<<" -> "<"
	  | ">>" -> ">"
	  | s -> s in
278
	apply_op2 _loc op e1 e2
279 280
    ]

281
    | 
282 283
    [ e1 = expr; op = ["+" | "-" | "@" ]; e2 = expr -> apply_op2 _loc op e1 e2
    | e1 = expr; ["||" | "or"]; e2 = expr -> exp _loc (logical_or e1 e2)
284
    | e = expr; "\\"; l = [IDENT | keyword ] -> 
285
	exp _loc (RemoveField (e, label l)) 
286 287
    ]
    |
288 289
    [ e1 = expr; op = ["*"]; e2 = expr -> apply_op2 _loc op e1 e2
    | e1 = expr; "&&"; e2 = expr -> exp _loc (logical_and e1 e2)
290
    | e = expr; op = "/"; p = pat LEVEL "simple" ->
291
	(* transform e with <(Atom)>[($$$::t|_)*] -> [$$$] *)
292 293 294
	let tag = mk _loc (Internal (Types.atom (Atoms.any))) in
	let att = mk _loc (Internal Types.Record.any) in
	let any = mk _loc (Internal Types.any) in
295
	let re = Star(Alt(SeqCapture(noloc,id_dummy,Elem p), Elem any)) in
296 297 298
	let ct = mk _loc (Regexp re) in
        let p = mk _loc (XmlT (tag, multi_prod _loc [att;ct])) in
	exp _loc (Transform (e,[p, Var id_dummy]))
299 300
    | e = expr; "/@"; a = [IDENT|keyword] ->
	(* transform e with <(Atom) {a=$$$}>_ -> [$$$] *)
301 302 303
        let tag = mk _loc (Internal (Types.atom Atoms.any)) in
        let any = mk _loc (Internal Types.any) in
        let att = mk _loc (Record
304
			    (true, [(label a,
305
				     (mk _loc (PatVar [id_dummy]),
306
				      None))])) in
307
        let p = mk _loc (XmlT (tag, multi_prod _loc [att;any])) in
308
        let t = (p, Pair (Var id_dummy,cst_nil)) in
309
        exp _loc (Transform (e,[t]))
310
     | e = expr; "//" ; p = pat ->
311 312 313 314 315 316 317 318 319
	 (* let $xstack=ref [p*] [] in                  
            let f  ( x : [Any*]) : [Any*] = 
                     xtransform x with $$$ & p & <_ ..>[y::Any* ] ->  $stack := !$stack @ [$$$] ; f y
            in let _ =f e in !$stack *)

	 let stk = U.mk "$stack" in 
	 let y = U.mk "y" in
	 let x = U.mk "x" in
	 let f = U.mk "f" in
320 321 322
	 let assign = 
	   set_ref 
	     (Var stk)
323
	     (concat (get_ref (Var stk)) (Pair (Var id_dummy,cst_nil))) in  
324 325 326
        	let tag = mknoloc (Internal (Types.atom (Atoms.any))) in
	        let att = mknoloc (Internal Types.Record.any) in
	        let any = mknoloc (Internal Types.any) in
327
	        let re = (SeqCapture(noloc,y,Star(Elem(any)))) in
328 329 330 331
	        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
332
	 let xt = Xtrans ((Var x),[capt,assign]) in 
333 334
	 let rf = Ref (cst_nil, mknoloc (Regexp (Star(Elem p)))) in 
         let targ = mknoloc (Regexp(Star(Elem(any)))) in
335
	 let tres = targ in
336
	 let arg = mknoloc(PatVar [x]) in
337
         let abst = {fun_name = Some (lop _loc,ident "f") ; fun_iface = [(targ, tres)] ;fun_body = [(arg,xt)] } in
338
	 let body = 
339 340 341
	   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))))
342
	 in
343
	 exp _loc body
344
    ]
345
    | [ 
346 347 348
      e1 = SELF; IDENT "div"; e2 = expr -> apply_op2 _loc "/" e1 e2
    | e1 = SELF; IDENT "mod"; e2 = expr -> apply_op2 _loc "mod" e1 e2
    | e1 = SELF; e2 = expr -> exp _loc (Apply (e1,e2))
349 350
    ]

351
    | "no_appl" 
352

353 354 355 356
    [ e = expr;  "."; l = [IDENT | keyword ]; 
      tyargs = [ "with"; "{"; tyargs = LIST0 pat; "}" -> Some tyargs
      | -> None ] ->
	let e = Dot (e,label l) in
357 358
	match tyargs with None -> exp _loc e | Some tyargs -> 
	  exp _loc (TyArgs (e,tyargs))
359 360
    ]  
    | [ 
361
      "("; l = LIST1 expr SEP ","; ")" -> exp _loc (tuple l)
362
    | "[";  l = LIST0 seq_elem; e = OPT [ ";"; e = expr -> e ]; 
363
      loc_end = ["]" -> _loc] ->
364
	let e = match e with Some e -> e | None -> cst_nil in
365 366
        let e = exp loc_end e in
        let (_,loc_end) = loc_end in
367 368 369
	let l = List.fold_right 
		  (fun x q ->
		     match x with
370
		       | `String (loc,i,j,s) -> exp loc (String (i,j,s,q))
371
		       | `Elems ((loc,_),x) -> exp (loc,loc_end) (Pair(x,q))
372
		       | `Explode x -> concat x q
373 374
		  ) l e
	in
375
	exp _loc l
376
    | "<"; t = [ "("; e = expr; ")" -> e
377
	       | a = tag -> exp _loc a
378
	       ];
379
	a = expr_attrib_spec; ">"; c = expr ->
380
	  exp _loc (Xml (t, Pair (a,c)))
381
    | "{"; r = expr_record_spec; "}" -> r
382
    | s = STRING2 ->
383
	let s = U.mk s in
384 385 386 387
	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))
388
    | "`"; a = tag -> a
389
    | c = char -> exp _loc (Char c)
390 391 392
    ]

  ];
393

394
  tag: [ [ a = [ IDENT | keyword ] -> exp _loc (Atom (ident a)) ] ];
395 396

  tag_type: [
397 398 399
    [ "_" ->  mk _loc (Internal (Types.atom Atoms.any))
    | a = [ IDENT | keyword ] -> mk _loc (Cst (Atom (ident a)))
    | t = ANY_IN_NS -> mk _loc (NsT (ident t)) 
400 401 402
    ]
  ];

403
  seq_elem: [
404
    [ x = STRING1 -> 
405
	let s = U.mk x in
406 407
	`String (_loc, U.start_index s, U.end_index s, s)
    | e = expr LEVEL "no_appl" -> `Elems (_loc,e)
408
    | "!"; e = expr LEVEL "no_appl" -> `Explode e
409 410
    ]
  ];
411 412
	
  namespace_binding: [
413 414 415 416
    [ "namespace"; r = [
	[ name = 
	    [ name = [ IDENT | keyword ]; "=" -> ident name
	    | -> U.mk "" ];
417
	  ns = ns_expr -> `Prefix (name,ns)
418 419 420
	| IDENT "on" -> `Keep true
	| IDENT "off" -> `Keep false ]
      ] -> r ]
421 422
  ];

423 424 425 426 427 428 429
  ns_expr: [
    [ uri = STRING2 -> `Uri (Ns.Uri.mk (ident uri))
    | ids = LIST1 [ IDENT | keyword ] SEP "." -> 	  
	let ids = List.map (fun x -> ident x) ids in
	`Path ids ]
  ];

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

445
 fun_decl_after_lparen: [
446
(* need an hack to do this, because both productions would
447
   match   [ OPT IDENT; "("; pat ] .... *)
448 449 450 451 452 453
   [ p1 = pat LEVEL "no_arrow";
     res = [ "->"; p2 = pat;
	     a = [ ";"; a = LIST0 arrow SEP ";" -> a | -> [] ];
	     ")"; b = branches -> `Classic (p2,a,b)
	   | ":"; targ1 = pat;
	     args = LIST0 [ ","; arg = pat; ":"; targ = pat -> (arg,targ) ]; 
454 455 456 457 458 459 460 461 462
	     ")";
	     others = LIST0 
			[ "(";
			  args = 
			    LIST1 
			      [ arg = pat; ":"; targ = pat -> (arg,targ) ]
			      SEP ",";
			  ")" -> args ];
	     ":"; tres = pat ; 
463
	     "="; body = expr ->
464
	       `Compact (targ1,args,others,tres,body)
465 466 467
	   ] ->
       match res with
	 | `Classic (p2,a,b) -> (p1,p2)::a,b
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
	 | `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
		    let e = Abstraction 
			      { fun_name = None; fun_iface = [targ,tres]; 
				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)]
486
	      ] ]; 
487 488 489


 fun_decl: [
490
   [ f = OPT located_ident; "("; (a,b) = fun_decl_after_lparen ->
491
       (f,a,b)
492
   ]
493 494
 ];

495
 arrow: [
496
    [ t1 = pat LEVEL "no_arrow"; "->"; t2 = pat -> (t1,t2)]
497 498 499
  ];

  branches: [
500
    [ OPT "|"; l = LIST1 branch SEP "|" -> l ]
501 502 503
  ];

  branch: [
504
    [ p = pat LEVEL "no_arrow"; "->"; e = expr -> (p,e) ]
505 506 507 508
  ];

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

575
  schema_ref: [
576
    [ schema = IDENT; "."; typ = [ IDENT | keyword ] -> (U.mk schema, ident typ)
577 578 579
    ]
  ];

580
  located_ident: [ [ a = [IDENT|keyword] -> (lop _loc,ident a) ] ];
581

582
  pat: [ 
583
      [ x = pat; "where"; 
584 585
        b = LIST1 [ (la,a) = located_ident; "="; y = pat -> 
		      (la,a,y) ] SEP "and"
586 587 588 589 590 591 592
            -> mk _loc (Recurs (x,b)) ]
    | 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)) ]
    | "no_arrow" [ x = pat; "|"; y = pat -> mk _loc (Or (x,y)) ] 
    | "simple" [ x = pat; "&"; y = pat -> mk _loc (And (x,y)) 
	       | x = pat; "\\"; y = pat -> mk _loc (Diff (x,y)) ]
593
    | 
594
      [ "{"; r = record_spec; "}" -> r
595
      | "ref"; p = pat ->
596 597
	  let get_fun = mk _loc (Arrow (pat_nil, p)) 
	  and set_fun = mk _loc (Arrow (p, pat_nil))in
598 599
	  let fields = 
	    [ label "get", (get_fun, None); label "set", (set_fun, None) ] in
600 601
	  mk _loc (Record (false, fields))
      | "_" -> mk _loc (Internal Types.any)
602
      | "("; a = IDENT; ":="; c = expr; ")" -> 
603
	  mk _loc (Constant (ident a,c))
604
      | "!"; a = IDENT ->
605
	  mk _loc (Internal (Types.abstract (Types.Abstract.atom a)))
606 607
      | ids = LIST1 [ IDENT | keyword ] SEP "." ->
	  let ids = List.map (fun x -> ident x) ids in
608
	  mk _loc (PatVar ids)
609
      | i = INT ; "--"; j = INT -> 
610 611
          let i =  Intervals.V.mk i 
	  and j =  Intervals.V.mk j in
612
          mk _loc (Internal (Types.interval (Intervals.bounded i j)))
613
      | i = INT -> 
614
          let i =  Intervals.V.mk i  in
615
          mk _loc (Internal (Types.interval (Intervals.atom i)))
616
      | "*"; "--"; j = INT ->
617
	  let j =  Intervals.V.mk j in
618
          mk _loc (Internal (Types.interval (Intervals.left j)))
619
      | i = INT; "--"; "*" ->
620
	  let i = Intervals.V.mk i in
621
          mk _loc (Internal (Types.interval (Intervals.right i)))
622
      | i = char ->
623
          mk _loc (Internal (Types.char (Chars.char_class i i)))
624
      | i = char ; "--"; j = char ->
625
          mk _loc (Internal (Types.char (Chars.char_class i j)))
626
      | "`"; c = tag_type -> c
627
      | "("; l = LIST1 pat SEP ","; ")" -> multi_prod _loc l
628
      | "["; r = [ r = regexp -> r | -> Epsilon ];
629 630 631 632 633
             q = [ ";"; q = pat -> Some q
                 | -> None ]; 
             "]" -> 
	       let r = match q with
		 | Some q -> 	
634
		     let any = mk _loc (Internal (Types.any)) in
635 636 637
		     Seq(r,Seq(Guard q, Star (Elem any)))
		 | None -> r
	       in
638
	       mk _loc (Regexp r)
639
      | "<"; t =
640 641
            [ x = tag_type -> x
            | "("; t = pat; ")" -> t ];
642
	a = attrib_spec; ">"; c = pat ->
643
          mk _loc (XmlT (t, multi_prod _loc [a;c]))
644
      | s = STRING2 ->
645 646 647 648 649 650
	  let s = 
	    List.map 
	      (fun c -> 
		 mknoloc (Internal
			     (Types.char
				(Chars.atom
651
				   (Chars.V.mk_int c))))) 
652 653
	      (seq_of_string s) in
	  let s = s @ [mknoloc (Internal (Sequence.nil_type))] in
654
	  multi_prod _loc s
655 656 657 658
      ]
    
  ];

659 660
  or_else : [ [ OPT [ "else"; y = pat -> y ]  ] ];

661
  opt_field_pat: [ [ OPT [ "=";
662
                  o = [ "?" -> true | -> false]; 
663 664 665
                  x = pat;  y = or_else -> (o,x,y) ] ] ];

  record_spec:
666
    [ [ r = LIST0 [ l = [IDENT | keyword ]; f = opt_field_pat; OPT ";" ->
667 668
		      let (o,x,y) =
			match f with
669
			  | None -> (false, mknoloc (PatVar [ident l]), None)
670 671
			  | Some z -> z
		      in
672
		      let x = if o then mk _loc (Optional x) else x in
673
		      (label l, (x,y))
674
                  ]; op = [ ".." -> true | -> false ] ->
675
	  mk _loc (Record (op,r))
676 677
      ] ];
  
678 679
  char:
    [ 
680
      [ c = STRING1 -> Chars.V.mk_int (parse_char _loc c) ]
681 682 683
    ];