parser.ml 23.1 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
55
let rec multi_prod loc = function
  | [ x ] -> x
  | x :: l -> mk loc (Prod (x, multi_prod loc l))
  | [] -> assert false
      
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 (Types.BoolChars.atom (Custom.Atm 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
89
90
let localize_exn f = 
  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
118
119
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
120

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

130
EXTEND Gram
131
  GLOBAL: top_phrases prog expr pat regexp keyword;
132
133

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

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

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

  debug_directive: [
213
214
215
216
217
    [ 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)
218
    | IDENT "single"; t = pat -> `Single t
219
    ]
220
  ];
221

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

235
236
237
238
239
  ident_or_keyword: [
    [ s = IDENT -> s
    | s = keyword -> s ]
  ];

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

290
    | 
291
292
    [ e1 = expr; op = ["+" | "-" | "@" ]; e2 = expr -> apply_op2 _loc op e1 e2
    | e1 = expr; ["||" | "or"]; e2 = expr -> exp _loc (logical_or e1 e2)
293
    | e = expr; "\\"; l = ident_or_keyword -> 
294
	exp _loc (RemoveField (e, label l)) 
295
296
    ]
    |
297
298
    [ e1 = expr; op = ["*"]; e2 = expr -> apply_op2 _loc op e1 e2
    | e1 = expr; "&&"; e2 = expr -> exp _loc (logical_and e1 e2)
299
    | e = expr; op = "/"; p = pat LEVEL "simple" ->
300
	(* transform e with <(Atom)>[($$$::t|_)*] -> [$$$] *)
301
	let tag = mk _loc (Internal (Types.atom (Types.BoolAtoms.atom (Custom.Atm (Atoms.any))))) in
302
303
	let att = mk _loc (Internal Types.Record.any) in
	let any = mk _loc (Internal Types.any) in
304
	let re = Star(Alt(SeqCapture(noloc,id_dummy,Elem p), Elem any)) in
305
306
307
	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]))
308
    | e = expr; "/@"; a = ident_or_keyword ->
309
	(* transform e with <(Atom) {a=$$$}>_ -> [$$$] *)
310
        let tag = mk _loc (Internal (Types.atom (Types.BoolAtoms.atom (Custom.Atm (Atoms.any))))) in
311
312
        let any = mk _loc (Internal Types.any) in
        let att = mk _loc (Record
313
			    (true, [(label a,
314
				     (mk _loc (PatVar [id_dummy]),
315
				      None))])) in
316
        let p = mk _loc (XmlT (tag, multi_prod _loc [att;any])) in
317
        let t = (p, Pair (Var id_dummy,cst_nil)) in
318
        exp _loc (Transform (e,[t]))
319
     | e = expr; "//" ; p = pat ->
320
321
322
323
324
325
326
327
328
	 (* 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
329
330
331
	 let assign = 
	   set_ref 
	     (Var stk)
332
	     (concat (get_ref (Var stk)) (Pair (Var id_dummy,cst_nil))) in  
333
        	let tag = mknoloc (Internal (Types.atom (Types.BoolAtoms.atom (Custom.Atm (Atoms.any))))) in
334
335
	        let att = mknoloc (Internal Types.Record.any) in
	        let any = mknoloc (Internal Types.any) in
336
	        let re = (SeqCapture(noloc,y,Star(Elem(any)))) in
337
338
339
340
	        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
341
	 let xt = Xtrans ((Var x),[capt,assign]) in 
342
343
	 let rf = Ref (cst_nil, mknoloc (Regexp (Star(Elem p)))) in 
         let targ = mknoloc (Regexp(Star(Elem(any)))) in
344
	 let tres = targ in
345
	 let arg = mknoloc(PatVar [x]) in
346
         let abst = {fun_name = Some (lop _loc,ident "f") ; fun_iface = [(targ, tres)] ;fun_body = [(arg,xt)] } in
347
	 let body = 
348
349
350
	   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))))
351
	 in
352
	 exp _loc body
353
    ]
354
    | [ 
355
356
357
      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))
358
359
    ]

360
    | "no_appl" 
361

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

  ];
402

403
  tag: [ [ a = ident_or_keyword -> exp _loc (Atom (ident a)) ] ];
404
405

  tag_type: [
406
407
    [ "_" ->  mk _loc (Internal (Types.atom (Types.BoolAtoms.atom (Custom.Atm (Atoms.any)))))
    | "$"; a = ident_or_keyword -> mk _loc (Cst (TVar a))
408
    | a = ident_or_keyword -> mk _loc (Cst (Atom (ident a)))
409
    | t = ANY_IN_NS -> mk _loc (NsT (ident t)) 
410
411
412
    ]
  ];

413
  seq_elem: [
414
    [ x = STRING1 -> 
415
	let s = U.mk x in
416
417
	`String (_loc, U.start_index s, U.end_index s, s)
    | e = expr LEVEL "no_appl" -> `Elems (_loc,e)
418
    | "!"; e = expr LEVEL "no_appl" -> `Explode e
419
420
    ]
  ];
421
422
	
  namespace_binding: [
423
424
    [ "namespace"; r = [
	[ name = 
425
	    [ name = ident_or_keyword; "=" -> ident name
426
	    | -> U.mk "" ];
427
	  ns = ns_expr -> `Prefix (name,ns)
428
429
430
	| IDENT "on" -> `Keep true
	| IDENT "off" -> `Keep false ]
      ] -> r ]
431
432
  ];

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

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

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


 fun_decl: [
500
   [ f = OPT located_ident; "("; (a,b) = fun_decl_after_lparen ->
501
       (f,a,b)
502
   ]
503
504
 ];

505
 arrow: [
506
    [ t1 = pat LEVEL "no_arrow"; "->"; t2 = pat -> (t1,t2)]
507
508
509
  ];

  branches: [
510
    [ OPT "|"; l = LIST1 branch SEP "|" -> l ]
511
512
513
  ];

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

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

585
  schema_ref: [
586
    [ schema = IDENT; "."; typ = ident_or_keyword -> (U.mk schema, ident typ)
587
588
589
    ]
  ];

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

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

670
671
  or_else : [ [ OPT [ "else"; y = pat -> y ]  ] ];

672
  opt_field_pat: [ [ OPT [ "=";
673
                  o = [ "?" -> true | -> false]; 
674
675
676
                  x = pat;  y = or_else -> (o,x,y) ] ] ];

  record_spec:
677
    [ [ r = LIST0 [ l = ident_or_keyword; f = opt_field_pat; OPT ";" ->
678
679
		      let (o,x,y) =
			match f with
680
			  | None -> (false, mknoloc (PatVar [ident l]), None)
681
682
			  | Some z -> z
		      in
683
		      let x = if o then mk _loc (Optional x) else x in
684
		      (label l, (x,y))
685
                  ]; op = [ ".." -> true | -> false ] ->
686
	  mk _loc (Record (op,r))
687
688
      ] ];
  
689
690
  char:
    [ 
691
      [ c = STRING1 -> Chars.V.mk_int (parse_char _loc c) ]
692
693
694
    ];
     

695
696
697
698
  attrib_spec: [
    [ r = record_spec -> r
    | "("; t = pat; ")" -> t 
    ] ];
699

700
701
  opt_field_expr: [ [ OPT [ "="; x = expr LEVEL "no_appl" -> x ] ] ];

702
  expr_record_spec:
703
    [ [ r = LIST0
704
	      [ l = ident_or_keyword; 
705
		x = opt_field_expr; OPT ";" ->
706
		  let x = match x with Some x -> x | None ->  Var (ident l) in
707
		  (label l,x) ] 
708
	  ->
709
	  exp _loc (RecordLitt r)
710
      ] ];
711

712
713
714
715
  expr_attrib_spec: [
    [ e = expr_record_spec -> e
    | "("; e = expr; ")" -> e 
    ] ];
716
717
END

718
719
720
module Hook = struct
  let expr = expr
  let pat = pat
721
  let keyword = keyword
722
723
end

724
725
726
727
let pat = Gram.parse pat Ulexer.Loc.ghost
and expr = Gram.parse expr Ulexer.Loc.ghost
and prog = Gram.parse prog Ulexer.Loc.ghost
and top_phrases = Gram.parse top_phrases Ulexer.Loc.ghost
728

729
let sync () = 
730
  match !Ulexer.lexbuf with
731
732
    | None -> ()
    | Some lb ->
733
        Ulexer.sync lb
734
735
736
737

let sync () =
  try sync ()
  with Ulexing.Error -> ()