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 "(", _ ]
97
       | [ IDENTPAR _, _; _ ; _ ]
98
	 | [ IDENT _, _; KEYWORD "(", _; _ ] -> ()
99
100
101
	 | _ -> raise Stream.Failure
     )

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

110
111
112
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])
113

114
115
116
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
117

118
let apply_op2_noloc op e1 e2 = Apply (Apply (Var (ident op), e1), e2)
119
let apply_op2 loc op e1 e2 = exp loc (apply_op2_noloc op e1 e2)
120

121
122
let set_ref e1 e2 = Apply (Dot (e1, U.mk "set"), e2)
let get_ref e = Apply (Dot (e, U.mk "get"), cst_nil)
123
124
125
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
126

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

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

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

  phrase: [
139
    [ (f,p,e) = let_binding ->
140
141
	if f then [ mk _loc (FunDecl e) ] else
	  [ mk _loc (LetDecl (p,e)) ]
142
    | (_,p,e1) = let_binding; "in"; e2 = expr LEVEL "top"->
143
        [ mk _loc (EvalStatement (exp _loc (let_in e1 p e2))) ]
144
    | "type"; x = IDENTPAR; pargs = LIST1 [ x = PVAR -> ident x ] SEP ","; ")"; "="; t = pat ->
Pietro Abate's avatar
Pietro Abate committed
145
146
147
          [ mk _loc (TypeDecl ((lop _loc,ident x),pargs,t)) ]
    | "type"; x = located_ident; "="; t = pat ->
        [ mk _loc (TypeDecl (x,[],t)) ]
148
    | "using"; name = IDENT; "="; cu = [ x = IDENT -> x | x = STRING -> 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 = STRING ->
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
    | n = namespace_binding; "in"; e2 = expr LEVEL "top" ->
162
	let e =
163
164
165
166
	  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
        [ mk _loc (Directive (`Print_type t)) ]
    | "#"; IDENT "dump_value"; e = expr -> [ mk _loc (Directive (`Dump e)) ]
    | "#"; IDENT "reinit_ns" -> [ mk _loc (Directive `Reinit_ns) ]
180
181
    | "#"; IDENT "help" -> [ mk _loc (Directive (`Help None)) ]
    | "#"; IDENT "help"; "debug" -> [ mk _loc (Directive (`Help (Some "debug"))) ]
182
    | "#"; IDENT "builtins" -> [ mk _loc (Directive `Builtins) ]
183
    | "include"; s = STRING ->
184
	protect_op "File inclusion";
185
	let s = Cduce_loc.resolve_filename s in
186
	(* avoid looping; should issue an error ? *)
187
188
	(* it is possible to have looping with x/../x/../x/.. ....
	   Need to canonicalize filename *)
189
	if List.mem s !include_stack then []
190
191
	else (
	  include_stack := s :: !include_stack;
192
	  Cduce_loc.push_source (`File s);
193
194
	  let saved_enc = !Ulexer.enc in
	  Ulexer.enc := Ulexing.Latin1;
195
196
197
	  protect_exn
	    (fun () ->
	       let chan = open_in s in
198
199
200
	       protect_exn
		 (fun () ->
		    let input = Stream.of_channel chan in
201
		    localize_exn (fun () -> Gram.parse prog Ulexer.Loc.ghost input))
202
		 (fun () -> close_in chan))
203
	    (fun () ->
204
	       Ulexer.enc := saved_enc;
205
	       Cduce_loc.pop_source ();
206
	       include_stack := List.tl !include_stack)
207
	)
208
    ] |
209
    [ e = expr -> [ mk _loc (EvalStatement e) ]
210
211
212
213
    ]
  ];

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

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

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

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

322
	 let stk = U.mk "$stack" in
323
324
325
	 let y = U.mk "y" in
	 let x = U.mk "x" in
	 let f = U.mk "f" in
326
	 let assign =
Pietro Abate's avatar
Pietro Abate committed
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
         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))))
348
	 in
349
	 exp _loc body
350
    ]
351
    | [
352
353
354
      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))
355
356
    ]

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

  ];
397

398
  tag: [ [ a = ident_or_keyword -> exp _loc (Atom (ident a)) ] ];
399
400

  tag_type: [
401
    [ "_" ->  mk _loc (Internal (Types.atom Atoms.any))
402
    | a = ident_or_keyword -> mk _loc (Cst (Atom (ident a)))
403
    | t = ANY_IN_NS -> mk _loc (NsT (ident t))
404
405
406
    ]
  ];

407
  seq_elem: [
408
    [ x = STRING2 ->
409
410
      let s = U.mk x in
      `String (_loc, U.start_index s, U.end_index s, s)
411
    | e = expr LEVEL "no_appl" -> `Elems (_loc,e)
412
    | "!"; e = expr LEVEL "no_appl" -> `Explode e
413
414
    ]
  ];
415

416
  namespace_binding: [
417
    [ "namespace"; r = [
418
	[ name =
419
	    [ name = ident_or_keyword; "=" -> ident name
420
	    | -> U.mk "" ];
421
	  ns = ns_expr -> `Prefix (name,ns)
422
423
424
	| IDENT "on" -> `Keep true
	| IDENT "off" -> `Keep false ]
      ] -> r ]
425
426
  ];

427
  ns_expr: [
428
429
    [ uri = STRING -> `Uri (Ns.Uri.mk (ident uri))
    | ids = LIST1 ident_or_keyword SEP "." ->
430
431
432
433
	let ids = List.map (fun x -> ident x) ids in
	`Path ids ]
  ];

434
  let_binding: [
435
436
    [ "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
437
      let p = mk _loc (PatVar([snd f],[])) in
438
	let abst = { fun_name = Some f; fun_iface = a; fun_body = b } in
439
        let e = exp _loc (Abstraction abst) in
440
        (true,p,e)
441
442
    | "let"; p = pat; "="; e = expr -> (false,p,e)
    | "let"; p = pat; ":"; t = pat; "="; e = expr -> (false,p, Forget (e,t))
443
    | "let"; p = pat; ":"; "?"; t = pat; "="; e = expr ->
444
	(false,p, Check (e,t))
445
    ]
446
447
  ];

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


 fun_decl: [
494
   [ f = OPT located_ident; "("; (a,b) = fun_decl_after_lparen -> (f,a,b)
495
   | f = IDENTPAR; (a,b) = fun_decl_after_lparen -> (Some (lop _loc,ident f),a,b)
496
   ]
497
498
 ];

499
 arrow: [
500
    [ t1 = pat LEVEL "no_arrow"; "->"; t2 = pat -> (t1,t2)]
501
502
503
  ];

  branches: [
504
    [ OPT "|"; l = LIST1 branch SEP "|" -> l ]
505
506
507
  ];

  branch: [
508
    [ p = pat LEVEL "no_arrow"; "->"; e = expr -> (p,e) ]
509
510
  ];

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

577
  schema_ref: [
578
    [ schema = IDENT; "."; typ = ident_or_keyword -> (U.mk schema, ident typ)
579
580
581
    ]
  ];

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

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

660
661
  ];

662
663
  or_else : [ [ OPT [ "else"; y = pat -> y ]  ] ];

Pietro Abate's avatar
Pietro Abate committed
664
665
666
667
668
669
  opt_field_pat: [ 
    [ OPT [ "=";
      o = [ "?" -> true | -> false];
      x = pat;  y = or_else -> (o,x,y) ] 
    ] 
  ];
670

Pietro Abate's avatar
Pietro Abate committed
671
672
  record_spec: [
    [ r = LIST0 [ l = ident_or_keyword; f = opt_field_pat; OPT ";" ->
Pietro Abate's avatar
Pietro Abate committed
673
674
675
676
677
678
679
680
681
      let (o,x,y) =
      match f with
        | None -> (false, mknoloc (PatVar([ident l],[])), None)
        | Some z -> z
      in
      let x = if o then mk _loc (Optional x) else x in
      (label l, (x,y))
      ]; op = [ ".." -> true | -> false ] ->
        mk _loc (Record (op,r))
Pietro Abate's avatar
Pietro Abate committed
682
683
    ]
  ];
684

Pietro Abate's avatar
Pietro Abate committed
685
686
687
  char: [
    [ c = CHAR -> Chars.V.mk_int (parse_char _loc c)
    | c = STRING2 -> Chars.V.mk_int (parse_char _loc c) ]