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

3 4
open Cduce_loc
(* let raise = Pervasives.raise *)
5
open Ast
6
open Ident
7
open Printf
8
open Ulexer
9

10
(*
11
let ()  = Grammar.error_verbose := true
12
*)
13

14 15
let tloc (i,j) = (i,j)
let nopos = (-1,-1)
16 17


18
let mk loc x = Cduce_loc.mk_located (tloc loc) x
19

20
exception Error of string
21
let error (i,j) s = Cduce_loc.raise_loc i j (Error s)
22
let error loc s = error (tloc loc) s
23

24
module Gram = Camlp4.Struct.Grammar.Static.Make(Ulexer)
25

26 27 28 29 30 31 32 33 34 35 36
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
37

38 39
let label s = U.mk (ident s)
let ident s = U.mk (ident s)
40

41 42 43 44 45 46
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"
47

48
let lop pos = Cduce_loc.loc_of_pos (tloc pos)
49
let exp pos e = LocatedExpr (lop pos,e)
50

51 52 53 54
let rec multi_prod loc = function
  | [ x ] -> x
  | x :: l -> mk loc (Prod (x, multi_prod loc l))
  | [] -> assert false
55

56
let rec tuple = function
57
  | [ x ] -> x
58
  | x :: l -> Pair (x, tuple l)
59
  | [] -> assert false
60

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


65
let char = mknoloc (Internal (Types.char Chars.any))
66
let string_regexp = Star (Elem char)
67

68
let seq_of_string s =
69 70
  let s = Encodings.Utf8.mk s in
  let rec aux i j =
71 72
    if Encodings.Utf8.equal_index i j then []
    else let (c,i) = Encodings.Utf8.next s i in c :: (aux i j)
73
  in
74
  aux (Encodings.Utf8.start_index s) (Encodings.Utf8.end_index s)
75

76

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

82 83
let include_stack = ref []

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

88
let localize_exn f =
89 90
  try f ()
  with
91 92 93 94 95
  | 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
96

97
let is_fun_decl =
98
   Gram.Entry.of_parser "[is_fun_decl]"
99 100
     (fun strm ->
       match Stream.npeek 3 strm with
101 102
	 | [ KEYWORD "fun", _; IDENT _, _; KEYWORD "(", _ ]
	 | [ IDENT _, _; KEYWORD "(", _; _ ] -> ()
103 104 105
	 | _ -> raise Stream.Failure
     )

106
let is_capture =
107
   Gram.Entry.of_parser "[is_capture]"
108 109
     (fun strm ->
       match Stream.npeek 2 strm with
110
	 | [ IDENT _, _; KEYWORD "::", _; _ ] -> ()
111 112 113 114
	 | _ -> raise Stream.Failure
     )


115 116 117
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])
118

119 120 121
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
122

123
let apply_op2_noloc op e1 e2 = Apply (Apply (Var (ident op), e1), e2)
124
let apply_op2 loc op e1 e2 = exp loc (apply_op2_noloc op e1 e2)
125

126 127
let set_ref e1 e2 = Apply (Dot (e1, U.mk "set"), e2)
let get_ref e = Apply (Dot (e, U.mk "get"), cst_nil)
128 129 130
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
131

132
EXTEND Gram
133
  GLOBAL: top_phrases prog expr pat regexp keyword;
134 135

  top_phrases: [
136
    [ l = LIST0 phrase; ";;" -> List.flatten l  ]
137
  ];
138 139

  prog: [
140
    [ l = LIST0 [ p = phrase ; OPT ";;" -> p ]; `EOI -> List.flatten l ]
141 142 143
  ];

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

  debug_directive: [
215 216 217 218 219
    [ 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)
220
    | IDENT "single"; t = pat -> `Single t
221 222
    | IDENT "typed"; e = expr -> `Typed e
    | IDENT "lambda"; e = expr -> `Lambda e
223
    ]
224
  ];
225

226
  keyword: [
227
    [ a =
228 229 230
	[ "map" | "match" | "with" | "try" | "xtransform"
	| "if" | "then"	| "else"
	| "transform" | "fun" | "in"
231
	| "let" | "type" | "debug" | "include"
232
        | "and" | "or" | "validate" | "schema" | "namespace" | "ref" | "alias"
233
	| "not" | "as" | "where" | "select" | "from" | "open"
234 235 236 237 238
	]
	-> a
    ]
  ];

239 240 241 242 243
  ident_or_keyword: [
    [ s = IDENT -> s
    | s = keyword -> s ]
  ];

244 245
  expr: [
    "top" RIGHTA
246
    [ "match"; e = SELF; "with"; b = branches ->
247
	exp _loc (Match (e,b))
248
    | "try"; e = SELF; "with"; b = branches ->
249
	exp _loc (Try (e,b))
250
    | "map"; e = SELF; "with"; b = branches ->
251
	exp _loc (Map (e,b))
252
    | "xtransform"; e = SELF; "with"; b = branches ->
253
	exp _loc (Xtrans (e,b))
254
    | "if"; e = SELF; "then"; e1 = SELF; "else"; e2 = SELF ->
255
	exp _loc (if_then_else e e1 e2)
256
    | "transform"; e = SELF; "with"; b = branches ->
257
	exp _loc (Transform (e,b))
258
    | "validate"; e = SELF; "with"; (schema, typ) = schema_ref ->
259
        exp _loc (Validate (e, [schema;typ]))
260
    | "select"; e = SELF; "from";
261
      l = LIST1 [ x = pat ; "in"; e = expr -> (x,e)] SEP "," ;
262 263
      cond = [ "where"; c = LIST1 [ expr ] SEP "and" -> c
	     | -> [] ] -> exp _loc (SelectFW (e,l,cond))
264
    | "fun"; (f,a,b) = fun_decl ->
265
	exp _loc (Abstraction { fun_name = f; fun_iface = a; fun_body = b })
266
    | (_,p,e1) = let_binding; "in"; e2 = expr LEVEL "top"->
267
        exp _loc (let_in e1 p e2)
268 269
    | n = namespace_binding; "in"; e2 = expr LEVEL "top" ->
	(match n with
270 271
	   | `Prefix (name,ns) -> exp _loc (NamespaceIn (name, ns, e2))
	   | `Keep f -> exp _loc (KeepNsIn (f,e2)))
272
    | e = expr; ":"; p = pat ->
273
	exp _loc (Forget (e,p))
274
    | e = expr; ":"; "?"; p = pat ->
275
	exp _loc (Check (e,p))
276
    | e1 = expr; ";"; e2 = expr ->
277
	exp _loc (seq e1 e2)
278
    | "ref"; p = pat; e = expr ->
279 280
	exp _loc (Ref (e,p))
    | "not"; e = expr -> exp _loc (logical_not e)
281 282
    ]
    |
283
    [ e1 = expr; ":="; e2 = expr -> exp _loc  (set_ref e1 e2)
284
    ]
285 286
    |
    [ e1 = expr; op = ["=" | "<=" | "<<" | ">>" | ">=" ]; e2 = expr ->
287 288 289 290
	let op = match op with
	  | "<<" -> "<"
	  | ">>" -> ">"
	  | s -> s in
291
	apply_op2 _loc op e1 e2
292 293
    ]

294
    |
295 296
    [ e1 = expr; op = ["+" | "-" | "@" ]; e2 = expr -> apply_op2 _loc op e1 e2
    | e1 = expr; ["||" | "or"]; e2 = expr -> exp _loc (logical_or e1 e2)
297 298
    | e = expr; "\\"; l = ident_or_keyword ->
	exp _loc (RemoveField (e, label l))
299 300
    ]
    |
301 302
    [ e1 = expr; op = ["*"]; e2 = expr -> apply_op2 _loc op e1 e2
    | e1 = expr; "&&"; e2 = expr -> exp _loc (logical_and e1 e2)
303
    | e = expr; op = "/"; p = pat LEVEL "simple" ->
304
	(* transform e with <(Atom)>[($$$::t|_)*] -> [$$$] *)
305
	let tag = mk _loc (Internal (Types.atom Atoms.any)) in
306 307
	let att = mk _loc (Internal Types.Record.any) in
	let any = mk _loc (Internal Types.any) in
308
	let re = Star(Alt(SeqCapture(noloc,id_dummy,Elem p), Elem any)) in
309 310 311
	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]))
312
    | e = expr; "/@"; a = ident_or_keyword ->
313
	(* transform e with <(Atom) {a=$$$}>_ -> [$$$] *)
314
        let tag = mk _loc (Internal (Types.atom Atoms.any)) in
315 316
        let any = mk _loc (Internal Types.any) in
        let att = mk _loc (Record
317
			    (true, [(label a,
318
				     (mk _loc (PatVar [id_dummy]),
319
				      None))])) in
320
        let p = mk _loc (XmlT (tag, multi_prod _loc [att;any])) in
321
        let t = (p, Pair (Var id_dummy,cst_nil)) in
322
        exp _loc (Transform (e,[t]))
323
     | e = expr; "//" ; p = pat ->
324 325
	 (* let $xstack=ref [p*] [] in
            let f  ( x : [Any*]) : [Any*] =
326 327 328
                     xtransform x with $$$ & p & <_ ..>[y::Any* ] ->  $stack := !$stack @ [$$$] ; f y
            in let _ =f e in !$stack *)

329
	 let stk = U.mk "$stack" in
330 331 332
	 let y = U.mk "y" in
	 let x = U.mk "x" in
	 let f = U.mk "f" in
333 334
	 let assign =
	   set_ref
335
	     (Var stk)
336
	     (concat (get_ref (Var stk)) (Pair (Var id_dummy,cst_nil))) in
337
        	let tag = mknoloc (Internal (Types.atom Atoms.any)) in
338 339
	        let att = mknoloc (Internal Types.Record.any) in
	        let any = mknoloc (Internal Types.any) in
340
	        let re = (SeqCapture(noloc,y,Star(Elem(any)))) in
341 342
	        let ct = mknoloc (Regexp re) in
                let children = mknoloc (XmlT (tag, multi_prod _loc [att;ct])) in
343
         let capt = mknoloc (And (mknoloc (And (mknoloc (PatVar [id_dummy]),p)),children)) in
344
	 let assign = seq assign ( (Apply(Var(f) , Var(y) ) ) ) in
345 346
	 let xt = Xtrans ((Var x),[capt,assign]) in
	 let rf = Ref (cst_nil, mknoloc (Regexp (Star(Elem p)))) in
347
         let targ = mknoloc (Regexp(Star(Elem(any)))) in
348
	 let tres = targ in
349
	 let arg = mknoloc(PatVar [x]) in
350
         let abst = {fun_name = Some (lop _loc,ident "f") ; fun_iface = [(targ, tres)] ;fun_body = [(arg,xt)] } in
351
	 let body =
352
	   let_in rf (mknoloc (PatVar [stk]))
353
	    (let_in ((Abstraction abst)) (mknoloc (PatVar[ident "f"]))
354
              (let_in ((Apply(Var(f) , e) )  ) (mknoloc (Internal Types.any)) (get_ref (Var stk))))
355
	 in
356
	 exp _loc body
357
    ]
358
    | [
359 360 361
      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))
362 363
    ]

364
    | "no_appl"
365

366
    [ e = expr;  "."; l = ident_or_keyword;
367 368 369
      tyargs = [ "with"; "{"; tyargs = LIST0 pat; "}" -> Some tyargs
      | -> None ] ->
	let e = Dot (e,label l) in
370
	match tyargs with None -> exp _loc e | Some tyargs ->
371
	  exp _loc (TyArgs (e,tyargs))
372 373
    ]
    | [
374
      "("; l = LIST1 expr SEP ","; ")" -> exp _loc (tuple l)
375
    | "[";  l = LIST0 seq_elem; e = OPT [ ";"; e = expr -> e ];
376
      loc_end = ["]" -> _loc] ->
377
	let e = match e with Some e -> e | None -> cst_nil in
378 379
        let e = exp loc_end e in
        let (_,loc_end) = loc_end in
380
	let l = List.fold_right
381 382
		  (fun x q ->
		     match x with
383
		       | `String (loc,i,j,s) -> exp loc (String (i,j,s,q))
384
		       | `Elems ((loc,_),x) -> exp (loc,loc_end) (Pair(x,q))
385
		       | `Explode x -> concat x q
386 387
		  ) l e
	in
388
	exp _loc l
389
    | "<"; t = [ "("; e = expr; ")" -> e
390
	       | a = tag -> exp _loc a
391
	       ];
392
	a = expr_attrib_spec; ">"; c = expr ->
393
	  exp _loc (Xml (t, Pair (a,c)))
394
    | "{"; r = expr_record_spec; "}" -> r
395
    | s = STRING ->
396
	let s = U.mk s in
397 398 399 400
	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))
401
    | "`"; a = tag -> a
402
    | c = char -> exp _loc (Char c)
403 404 405
    ]

  ];
406

407
  tag: [ [ a = ident_or_keyword -> exp _loc (Atom (ident a)) ] ];
408 409

  tag_type: [
410
    [ "_" ->  mk _loc (Internal (Types.atom Atoms.any))
411
    | a = ident_or_keyword -> mk _loc (Cst (Atom (ident a)))
412
    | t = ANY_IN_NS -> mk _loc (NsT (ident t))
413 414 415
    ]
  ];

416
  seq_elem: [
417
    [ x = STRING2 ->
418 419
      let s = U.mk x in
      `String (_loc, U.start_index s, U.end_index s, s)
420
    | e = expr LEVEL "no_appl" -> `Elems (_loc,e)
421
    | "!"; e = expr LEVEL "no_appl" -> `Explode e
422 423
    ]
  ];
424

425
  namespace_binding: [
426
    [ "namespace"; r = [
427
	[ name =
428
	    [ name = ident_or_keyword; "=" -> ident name
429
	    | -> U.mk "" ];
430
	  ns = ns_expr -> `Prefix (name,ns)
431 432 433
	| IDENT "on" -> `Keep true
	| IDENT "off" -> `Keep false ]
      ] -> r ]
434 435
  ];

436
  ns_expr: [
437 438
    [ uri = STRING -> `Uri (Ns.Uri.mk (ident uri))
    | ids = LIST1 ident_or_keyword SEP "." ->
439 440 441 442
	let ids = List.map (fun x -> ident x) ids in
	`Path ids ]
  ];

443

444
  let_binding: [
445 446
    [ "let"; is_fun_decl; OPT "fun"; (f,a,b) = fun_decl ->
	let f = match f with Some x -> x | None -> assert false in
447
	let p = mk _loc (PatVar [snd f]) in
448
	let abst = { fun_name = Some f; fun_iface = a; fun_body = b } in
449
        let e = exp _loc (Abstraction abst) in
450
        (true,p,e)
451 452
    | "let"; p = pat; "="; e = expr -> (false,p,e)
    | "let"; p = pat; ":"; t = pat; "="; e = expr -> (false,p, Forget (e,t))
453
    | "let"; p = pat; ":"; "?"; t = pat; "="; e = expr ->
454
	(false,p, Check (e,t))
455
    ]
456 457
  ];

458
 fun_decl_after_lparen: [
459
(* need an hack to do this, because both productions would
460
   match   [ OPT IDENT; "("; pat ] .... *)
461 462 463 464 465
   [ p1 = pat LEVEL "no_arrow";
     res = [ "->"; p2 = pat;
	     a = [ ";"; a = LIST0 arrow SEP ";" -> a | -> [] ];
	     ")"; b = branches -> `Classic (p2,a,b)
	   | ":"; targ1 = pat;
466
	     args = LIST0 [ ","; arg = pat; ":"; targ = pat -> (arg,targ) ];
467
	     ")";
468
	     others = LIST0
469
			[ "(";
470 471
			  args =
			    LIST1
472 473 474
			      [ arg = pat; ":"; targ = pat -> (arg,targ) ]
			      SEP ",";
			  ")" -> args ];
475
	     ":"; tres = pat ;
476
	     "="; body = expr ->
477
	       `Compact (targ1,args,others,tres,body)
478 479 480
	   ] ->
       match res with
	 | `Classic (p2,a,b) -> (p1,p2)::a,b
481 482 483 484 485 486 487 488 489
	 | `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
490 491
		    let e = Abstraction
			      { fun_name = None; fun_iface = [targ,tres];
492 493 494 495 496 497 498
				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)]
499
	      ] ];
500 501 502


 fun_decl: [
503
   [ f = OPT located_ident; "("; (a,b) = fun_decl_after_lparen ->
504
       (f,a,b)
505
   ]
506 507
 ];

508
 arrow: [
509
    [ t1 = pat LEVEL "no_arrow"; "->"; t2 = pat -> (t1,t2)]
510 511 512
  ];

  branches: [
513
    [ OPT "|"; l = LIST1 branch SEP "|" -> l ]
514 515 516
  ];

  branch: [
517
    [ p = pat LEVEL "no_arrow"; "->"; e = expr -> (p,e) ]
518 519
  ];

520 521 522

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

588
  schema_ref: [
589
    [ schema = IDENT; "."; typ = ident_or_keyword -> (U.mk schema, ident typ)
590 591 592
    ]
  ];

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

595 596 597
  pat: [
      [ x = pat; "where";
        b = LIST1 [ (la,a) = located_ident; "="; y = pat ->
598
		      (la,a,y) ] SEP "and"
599 600 601 602
            -> 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)) ]
603 604
    | "no_arrow" [ x = pat; "|"; y = pat -> mk _loc (Or (x,y)) ]
    | "simple" [ x = pat; "&"; y = pat -> mk _loc (And (x,y))
605
	       | x = pat; "\\"; y = pat -> mk _loc (Diff (x,y)) ]
606
    | "var_typ" [ x = PTYPE -> mk _loc (TVar x) ]
607
    |
608
      [ "{"; r = record_spec; "}" -> r
609
      | "ref"; p = pat ->
610
	  let get_fun = mk _loc (Arrow (pat_nil, p))
611
	  and set_fun = mk _loc (Arrow (p, pat_nil))in
612
	  let fields =
613
	    [ label "get", (get_fun, None); label "set", (set_fun, None) ] in
614 615
	  mk _loc (Record (false, fields))
      | "_" -> mk _loc (Internal Types.any)
616
      | "("; a = IDENT; ":="; c = expr; ")" ->
617
	  mk _loc (Constant (ident a,c))
618
      | "!"; a = IDENT ->
619
	  mk _loc (Internal (Types.abstract (Types.Abstracts.atom a)))
620