parser.ml 25 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
(* let ()  = Camlp4_config.verbose := true *)
9

10
11
let tloc (i,j) = (i,j)
let nopos = (-1,-1)
12

13
let mk loc x = Cduce_loc.mk_located (tloc loc) x
14

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

19
module Gram = Camlp4.Struct.Grammar.Static.Make(Ulexer)
20

21
22
let id_dummy = U.mk "$$$"

Pietro Abate's avatar
Pietro Abate committed
23
let ident_aux s =
24
25
26
27
28
29
30
31
  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
32

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

36
37
38
39
40
41
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"
42

43
let lop pos = Cduce_loc.loc_of_pos (tloc pos)
44
let exp pos e = LocatedExpr (lop pos,e)
45

46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
let split_id_list loc l =
  let rec loop l acc =
  match l with
    [] -> acc, []
  | qname :: ll ->
    try
      let i = String.index qname ':' in
      let pre = String.sub qname 0 i in
      let post = String.sub qname (i+1) (String.length qname - i - 1) in
      pre :: acc, post::ll
    with
    Not_found -> loop ll (qname :: acc)
  in
  let l1, l2 = loop l [] in
  if l2 == [] then raise Stream.Failure else
    (mk loc (PatVar(List.rev_map ident l1, [])),
     mk loc (PatVar(List.map ident l2, [])))

64
65
66
67
let rec multi_prod loc = function
  | [ x ] -> x
  | x :: l -> mk loc (Prod (x, multi_prod loc l))
  | [] -> assert false
68

69
let rec tuple = function
70
  | [ x ] -> x
71
  | x :: l -> Pair (x, tuple l)
72
  | [] -> assert false
73

74
let tuple_queue =
75
  List.fold_right (fun x q -> Pair (x, q))
76

77
let char = mknoloc (Internal (Types.char Chars.any))
78
let string_regexp = Star (Elem char)
79

80
let seq_of_string s =
81
82
  let s = Encodings.Utf8.mk s in
  let rec aux i j =
83
84
    if Encodings.Utf8.equal_index i j then []
    else let (c,i) = Encodings.Utf8.next s i in c :: (aux i j)
85
  in
86
  aux (Encodings.Utf8.start_index s) (Encodings.Utf8.end_index s)
87

88
89
90
91
92
93
94
95
96
97
98
let rec unseq e = match e with
    Seq(Elem { descr = PatVar (ids, []); loc}, Arg (e0)) ->
    let ue0 = unseq e0 in begin
      match ue0 with
      | Elem p -> Elem {loc; descr = PatVar(ids, prod_to_list p) }
      | _ -> e
    end
  | Arg e -> unseq e
  | _ -> e


99
let parse_char loc s =
100
101
  match seq_of_string s with
    | [ c ] -> c
102
    | _ -> error loc "Character litteral must have length 1"
103

104
105
let include_stack = ref []

106
107
108
109
let protect_exn f g =
  try let x = f () in g (); x
  with e -> g (); raise e

110
let localize_exn f =
111
112
  try f ()
  with
113
114
115
116
117
  | 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
118

119
let is_fun_decl =
120
   Gram.Entry.of_parser "[is_fun_decl]"
121
122
     (fun strm ->
       match Stream.npeek 3 strm with
123
124
	 | [ KEYWORD "fun", _; IDENT _, _; KEYWORD "(", _ ]
	 | [ IDENT _, _; KEYWORD "(", _; _ ] -> ()
125
126
127
	 | _ -> raise Stream.Failure
     )

128
129
130
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])
131

132
133
134
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
135

136
let apply_op2_noloc op e1 e2 = Apply (Apply (Var (ident op), e1), e2)
137
let apply_op2 loc op e1 e2 = exp loc (apply_op2_noloc op e1 e2)
138

139
140
let set_ref e1 e2 = Apply (Dot (e1, U.mk "set"), e2)
let get_ref e = Apply (Dot (e, U.mk "get"), cst_nil)
141
142
143
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
144
let opt_to_list = function None -> [] | Some l -> l
145

146
EXTEND Gram
147
  GLOBAL: top_phrases prog expr pat regexp keyword;
148
149

  top_phrases: [
150
    [ l = LIST0 phrase; ";;" -> List.flatten l  ]
151
  ];
152
153

  prog: [
154
    [ l = LIST0 [ p = phrase ; OPT ";;" -> p ]; `EOI -> List.flatten l ]
155
156
157
  ];

  phrase: [
158
    [ (f,p,e) = let_binding ->
159
160
	if f then [ mk _loc (FunDecl e) ] else
	  [ mk _loc (LetDecl (p,e)) ]
161
    | (_,p,e1) = let_binding; "in"; e2 = expr LEVEL "top"->
162
        [ mk _loc (EvalStatement (exp _loc (let_in e1 p e2))) ]
163
    | "type"; x = located_ident;
164
      args = OPT [ "("; l = LIST1 [ v = PVAR -> U.mk v ] SEP ","; ")" -> l ];
165
166
      "="; t = pat ->
      [ mk _loc (TypeDecl (x, opt_to_list args ,t)) ]
167
    | "using"; name = IDENT; "="; cu = [ x = IDENT -> x | x = STRING2 -> x ] ->
168
	[ mk _loc (Using (U.mk name, U.mk cu)) ]
169
    | "open"; ids = LIST1 ident_or_keyword SEP "." ->
170
	let ids = List.map (fun x -> ident x) ids in
171
	[ mk _loc (Open ids) ]
172
    | "schema"; name = IDENT; "="; uri = STRING2 ->
173
	protect_op "schema";
174
        [ mk _loc (SchemaDecl (U.mk name, uri)) ]
175
176
177
178
    | n = namespace_binding ->
	let d = match n with
	    | `Prefix (name,ns) ->  Namespace (name, ns)
	    | `Keep b -> KeepNs b in
179
	[ mk _loc d ]
180
    | n = namespace_binding; "in"; e2 = expr LEVEL "top" ->
181
	let e =
182
183
184
185
	  match n with
	    | `Prefix (name,ns) -> NamespaceIn (name, ns, e2)
	    | `Keep b -> KeepNsIn (b,e2)
	in
186
187
188
189
	[ 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) ]
190
191
192
    | "#"; IDENT "utf8" -> Ulexer.enc := Ulexing.Utf8; [ ]
    | "#"; IDENT "latin1" -> Ulexer.enc := Ulexing.Latin1; [ ]
    | "#"; IDENT "ascii" -> Ulexer.enc := Ulexing.Ascii; [ ]
193
194
    | "#"; IDENT "quit" -> [ mk _loc (Directive `Quit) ]
    | "#"; IDENT "env" -> [ mk _loc (Directive `Env) ]
195
    | "#"; IDENT "print_type"; t = pat ->
196
197
198
        [ mk _loc (Directive (`Print_type t)) ]
    | "#"; IDENT "dump_value"; e = expr -> [ mk _loc (Directive (`Dump e)) ]
    | "#"; IDENT "reinit_ns" -> [ mk _loc (Directive `Reinit_ns) ]
199
200
    | "#"; IDENT "help" -> [ mk _loc (Directive (`Help None)) ]
    | "#"; IDENT "help"; "debug" -> [ mk _loc (Directive (`Help (Some "debug"))) ]
201
    | "#"; IDENT "builtins" -> [ mk _loc (Directive `Builtins) ]
202
    | "include"; s = STRING2 ->
203
	protect_op "File inclusion";
204
	let s = Cduce_loc.resolve_filename s in
205
	(* avoid looping; should issue an error ? *)
206
207
	(* it is possible to have looping with x/../x/../x/.. ....
	   Need to canonicalize filename *)
208
	if List.mem s !include_stack then []
209
210
	else (
	  include_stack := s :: !include_stack;
211
	  Cduce_loc.push_source (`File s);
212
213
	  let saved_enc = !Ulexer.enc in
	  Ulexer.enc := Ulexing.Latin1;
214
215
216
	  protect_exn
	    (fun () ->
	       let chan = open_in s in
217
218
219
	       protect_exn
		 (fun () ->
		    let input = Stream.of_channel chan in
220
		    localize_exn (fun () -> Gram.parse prog Ulexer.Loc.ghost input))
221
		 (fun () -> close_in chan))
222
	    (fun () ->
223
	       Ulexer.enc := saved_enc;
224
	       Cduce_loc.pop_source ();
225
	       include_stack := List.tl !include_stack)
226
	)
227
    ] |
228
    [ e = expr -> [ mk _loc (EvalStatement e) ]
229
230
231
232
    ]
  ];

  debug_directive: [
233
234
235
236
237
    [ 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)
238
    | IDENT "single"; t = pat -> `Single t
239
240
    | IDENT "typed"; e = expr -> `Typed e
    | IDENT "lambda"; e = expr -> `Lambda e
241
242
    | IDENT "bdd"; t = pat -> `Bdd t
    | IDENT "id_bdd"; i = INT  -> `Id_bdd (int_of_string i)
243
    ]
244
  ];
245

246
  keyword: [
247
    [ a =
248
249
250
	[ "map" | "match" | "with" | "try" | "xtransform"
	| "if" | "then"	| "else"
	| "transform" | "fun" | "in"
251
	| "let" | "type" | "debug" | "include"
252
        | "and" | "or" | "validate" | "schema" | "namespace" | "ref" | "alias"
253
	| "not" | "as" | "where" | "select" | "from" | "open"
254
255
256
257
258
	]
	-> a
    ]
  ];

259
260
261
262
263
  ident_or_keyword: [
    [ s = IDENT -> s
    | s = keyword -> s ]
  ];

264
265
  expr: [
    "top" RIGHTA
266
    [ "match"; e = SELF; "with"; b = branches ->
267
	exp _loc (Match (e,b))
268
    | "try"; e = SELF; "with"; b = branches ->
269
	exp _loc (Try (e,b))
270
    | "map"; e = SELF; "with"; b = branches ->
271
	exp _loc (Map (e,b))
272
    | "xtransform"; e = SELF; "with"; b = branches ->
273
	exp _loc (Xtrans (e,b))
274
275
    | "if"; e = SELF; "then"; e1 = SELF ->
	exp _loc (if_then_else e e1 cst_nil)
276
    | "if"; e = SELF; "then"; e1 = SELF; "else"; e2 = SELF ->
277
	exp _loc (if_then_else e e1 e2)
278
    | "transform"; e = SELF; "with"; b = branches ->
279
	exp _loc (Transform (e,b))
280
    | "validate"; e = SELF; "with"; (schema, typ) = schema_ref ->
281
        exp _loc (Validate (e, [schema;typ]))
282
    | "select"; e = SELF; "from";
283
      l = LIST1 [ x = pat ; "in"; e = expr -> (x,e)] SEP "," ;
284
285
      cond = [ "where"; c = LIST1 [ expr ] SEP "and" -> c
	     | -> [] ] -> exp _loc (SelectFW (e,l,cond))
286
    | "fun"; (f,a,b) = fun_decl ->
287
	exp _loc (Abstraction { fun_name = f; fun_iface = a; fun_body = b })
288
    | (_,p,e1) = let_binding; "in"; e2 = expr LEVEL "top"->
289
        exp _loc (let_in e1 p e2)
290
291
    | n = namespace_binding; "in"; e2 = expr LEVEL "top" ->
	(match n with
292
293
	   | `Prefix (name,ns) -> exp _loc (NamespaceIn (name, ns, e2))
	   | `Keep f -> exp _loc (KeepNsIn (f,e2)))
Pietro Abate's avatar
Pietro Abate committed
294
295
296
297
    | e = expr; ":"; p = pat -> exp _loc (Forget (e,p))
    | e = expr; ":"; "?"; p = pat -> exp _loc (Check (e,p))
    | e1 = expr; ";"; e2 = expr -> exp _loc (seq e1 e2)
    | "ref"; p = pat; e = expr -> exp _loc (Ref (e,p))
298
    | "not"; e = expr -> exp _loc (logical_not e)
299
    ]
Pietro Abate's avatar
Pietro Abate committed
300
301
    | [ e1 = expr; ":="; e2 = expr -> exp _loc  (set_ref e1 e2) ]
    | [ e1 = expr; op = ["=" | "<=" | "<<" | ">>" | ">=" ]; e2 = expr ->
302
303
304
	let op = match op with
	  | "<<" -> "<"
	  | ">>" -> ">"
Pietro Abate's avatar
Pietro Abate committed
305
306
	  | s -> s
      in
307
	apply_op2 _loc op e1 e2
308
    ]
Pietro Abate's avatar
Pietro Abate committed
309
    | [ e1 = expr; op = ["+" | "-" | "@" ]; e2 = expr -> apply_op2 _loc op e1 e2
310
    | e1 = expr; ["||" | "or"]; e2 = expr -> exp _loc (logical_or e1 e2)
Pietro Abate's avatar
Pietro Abate committed
311
    | e = expr; "\\"; l = ident_or_keyword -> exp _loc (RemoveField (e, label l))
312
    ]
Pietro Abate's avatar
Pietro Abate committed
313
    | [ e1 = expr; op = ["*"]; e2 = expr -> apply_op2 _loc op e1 e2
314
    | e1 = expr; "&&"; e2 = expr -> exp _loc (logical_and e1 e2)
315
    | e = expr; op = "/"; p = pat LEVEL "simple" ->
316
	(* transform e with <(Atom)>[($$$::t|_)*] -> [$$$] *)
317
	let tag = mk _loc (Internal (Types.atom Atoms.any)) in
318
319
	let att = mk _loc (Internal Types.Record.any) in
	let any = mk _loc (Internal Types.any) in
Pietro Abate's avatar
Pietro Abate committed
320
	let re = Star(Alt(SeqCapture((noloc,id_dummy),Elem p), Elem any)) in
321
	let ct = mk _loc (Regexp re) in
Pietro Abate's avatar
Pietro Abate committed
322
      let p = mk _loc (XmlT (tag, multi_prod _loc [att;ct])) in
323
	exp _loc (Transform (e,[p, Var id_dummy]))
324
    | e = expr; "/@"; a = ident_or_keyword ->
325
	(* transform e with <(Atom) {a=$$$}>_ -> [$$$] *)
326
        let tag = mk _loc (Internal (Types.atom Atoms.any)) in
327
        let any = mk _loc (Internal Types.any) in
Pietro Abate's avatar
Pietro Abate committed
328
        let att = mk _loc (Record (true, [(label a, (mk _loc (PatVar([id_dummy],[])), None))])) in
329
        let p = mk _loc (XmlT (tag, multi_prod _loc [att;any])) in
330
        let t = (p, Pair (Var id_dummy,cst_nil)) in
331
        exp _loc (Transform (e,[t]))
332
     | e = expr; "//" ; p = pat ->
333
334
	 (* let $xstack=ref [p*] [] in
            let f  ( x : [Any*]) : [Any*] =
335
336
337
                     xtransform x with $$$ & p & <_ ..>[y::Any* ] ->  $stack := !$stack @ [$$$] ; f y
            in let _ =f e in !$stack *)

338
	 let stk = U.mk "$stack" in
339
340
341
	 let y = U.mk "y" in
	 let x = U.mk "x" in
	 let f = U.mk "f" in
342
	 let assign =
Pietro Abate's avatar
Pietro Abate committed
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
         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
360
          let body =
Pietro Abate's avatar
Pietro Abate committed
361
362
363
            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))))
364
	 in
365
	 exp _loc body
366
    ]
367
    | [
368
      e1 = SELF; IDENT "div"; e2 = expr -> apply_op2 _loc "/" e1 e2
369
370
    | e1 = SELF; IDENT "mod"; e2 = expr -> apply_op2 _loc "mod" e1 e2
    | e1 = SELF; e2 = expr -> exp _loc (Apply (e1,e2))
371
372
    ]

Pietro Abate's avatar
Pietro Abate committed
373
    | "no_appl" [ e = expr;  "."; l = ident_or_keyword;
374
375
376
      tyargs = [ "with"; "{"; tyargs = LIST0 pat; "}" -> Some tyargs
      | -> None ] ->
	let e = Dot (e,label l) in
377
	match tyargs with None -> exp _loc e | Some tyargs ->
378
	  exp _loc (TyArgs (e,tyargs))
379
380
    ]
    | [
381
      "("; l = LIST1 expr SEP ","; ")" -> exp _loc (tuple l)
382
    | "[";  l = LIST0 seq_elem; e = OPT [ ";"; e = expr -> e ];
383
      loc_end = ["]" -> _loc] ->
384
	let e = match e with Some e -> e | None -> cst_nil in
385
386
        let e = exp loc_end e in
        let (_,loc_end) = loc_end in
387
	let l = List.fold_right
388
389
		  (fun x q ->
		     match x with
390
		       | `String (loc,i,j,s) -> exp loc (String (i,j,s,q))
391
		       | `Elems ((loc,_),x) -> exp (loc,loc_end) (Pair(x,q))
392
		       | `Explode x -> concat x q
393
394
		  ) l e
	in
395
	exp _loc l
396
    | "<"; t = [ "("; e = expr; ")" -> e
397
	       | a = tag -> exp _loc a
398
	       ];
399
	a = expr_attrib_spec; ">"; c = expr ->
400
	  exp _loc (Xml (t, Pair (a,c)))
401
    | "{"; r = expr_record_spec; "}" -> r
402
    | s = STRING2 ->
403
	let s = U.mk s in
404
405
	exp _loc (String (U.start_index s, U.end_index s, s, cst_nil))
    | a = IDENT -> exp _loc (Var (ident a))
406
    | "!"; e = expr LEVEL "no_appl" -> exp _loc (get_ref e)
407
    | i = INT -> exp _loc (Integer (Intervals.V.mk i))
408
409
410
411
412
413
414
    | f = FLOAT -> (* TODO : add a direct representation of floats in the AST ? *)
       let e1 =  (Var (ident "float_of")) in
       let e2 =
	 let s = U.mk f in
	  (String (U.start_index s, U.end_index s, s, cst_nil))
       in
       exp _loc (Apply (e1,e2))
415
    | "`"; a = tag -> a
416
    | c = char -> exp _loc (Char c)
417
418
419
    ]

  ];
420

421
  tag: [ [ a = ident_or_keyword -> exp _loc (Atom (ident a)) ] ];
422
423

  tag_type: [
424
    [ "_" ->  mk _loc (Internal (Types.atom Atoms.any))
425
    | a = ident_or_keyword -> mk _loc (Cst (Atom (ident a)))
426
    | t = ANY_IN_NS -> mk _loc (NsT (ident t))
427
428
429
    ]
  ];

430
  seq_elem: [
431
    [ x = STRING1 ->
432
433
      let s = U.mk x in
      `String (_loc, U.start_index s, U.end_index s, s)
434
    | e = expr LEVEL "no_appl" -> `Elems (_loc,e)
435
    | "!"; e = expr LEVEL "no_appl" -> `Explode e
436
437
    ]
  ];
438

439
  namespace_binding: [
440
    [ "namespace"; r = [
441
	[ name =
442
	    [ name = ident_or_keyword; "=" -> ident name
443
	    | -> U.mk "" ];
444
	  ns = ns_expr -> `Prefix (name,ns)
445
446
447
	| IDENT "on" -> `Keep true
	| IDENT "off" -> `Keep false ]
      ] -> r ]
448
449
  ];

450
  ns_expr: [
451
    [ uri = STRING2 -> `Uri (Ns.Uri.mk (ident uri))
452
    | ids = LIST1 ident_or_keyword SEP "." ->
453
454
455
456
	let ids = List.map (fun x -> ident x) ids in
	`Path ids ]
  ];

457
  let_binding: [
458
459
    [ "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
460
      let p = mk _loc (PatVar([snd f],[])) in
461
	let abst = { fun_name = Some f; fun_iface = a; fun_body = b } in
462
        let e = exp _loc (Abstraction abst) in
463
        (true,p,e)
464
465
    | "let"; p = pat; "="; e = expr -> (false,p,e)
    | "let"; p = pat; ":"; t = pat; "="; e = expr -> (false,p, Forget (e,t))
466
    | "let"; p = pat; ":"; "?"; t = pat; "="; e = expr ->
467
	(false,p, Check (e,t))
468
    ]
469
470
  ];

471
472
473
474
475
476
477
478
479
480
481
  arg_colon_type: [
    [ p1 = pat ; targ1 = OPT [ ":"; p = pat -> p ] ->

      match p1.descr,targ1 with
        PatVar(id1, []), None ->
        split_id_list _loc (List.map Ident.U.get_str id1)
      | _, Some targ1 -> p1, targ1
      | _ -> raise Stream.Failure
    ]
  ];

482
 fun_decl_after_lparen: [
Pietro Abate's avatar
Pietro Abate committed
483
  (* need an hack to do this, because both productions would
484
   match   [ OPT IDENT; "("; pat ] .... *)
485
486
487
488
   [ p1 = pat LEVEL "no_arrow";
     res = [ "->"; p2 = pat;
	     a = [ ";"; a = LIST0 arrow SEP ";" -> a | -> [] ];
	     ")"; b = branches -> `Classic (p2,a,b)
489
490
	   | targ1 = OPT [ ":"; p = pat -> p ];
	     args = LIST0 [ ","; arg = arg_colon_type -> arg ];
491
	     ")";
492
	     others = LIST0
493
			[ "(";
494
495
			  args =
			    LIST1
496
			      [ arg = arg_colon_type -> arg ]
497
498
			      SEP ",";
			  ")" -> args ];
499
	     ":" ; tres = pat ;
500
	     "="; body = expr ->
501
	       `Compact (targ1,args,others,tres,body)
502

Pietro Abate's avatar
Pietro Abate committed
503
     ] ->
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
     match res with
     | `Classic (p2,a,b) -> (p1,p2)::a,b
     | `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 p1, targ1 =
         match p1.descr,targ1 with
           PatVar(id1, []), None ->
           split_id_list _loc (List.map Ident.U.get_str id1)
         | _, Some targ1 -> p1, targ1
         | _ -> raise Stream.Failure
       in
       let (targ,arg) = mkfun ((p1,targ1) :: args) in
       [(targ,tres)],[(arg,body)]
Pietro Abate's avatar
Pietro Abate committed
531
532
    ]
  ];
533
534
535


 fun_decl: [
536
   [ f = OPT located_ident; "("; (a,b) = fun_decl_after_lparen -> (f,a,b)
537
   ]
538
539
 ];

540
  arrow: [
541
    [ t1 = pat LEVEL "no_arrow"; "->"; t2 = pat -> (t1,t2)]
542
543
544
  ];

  branches: [
545
    [ OPT "|"; l = LIST1 branch SEP "|" -> l ]
546
547
548
  ];

  branch: [
549
    [ p = pat LEVEL "no_arrow"; "->"; e = expr -> (p,e) ]
550
551
  ];

552
553
  regexp: [
    [ x = regexp; "|"; y = regexp ->
554
	match (x,y) with
555
	  | Elem x, Elem y -> Elem (mk _loc (Or (x,y)))
556
          | _ -> Alt (x, y)
557
    ]
558
  | [ x = regexp; y = regexp -> re_seq x y ]
559
560
561
562
563
  | [ x = regexp ; op = [  "->" -> "->" ] ; y = regexp ->
      match unseq x, unseq y with
      | Elem x , Elem y -> Elem (mk _loc (Arrow (x, y)))
      | _ -> error _loc ( op ^ " not allowed in regular expression")
    ]
564
  | [ x = regexp ; op = [ "&" -> "&" | "\\" -> "\\" ] ; y = regexp ->
565
      match unseq x, unseq y with
566
      | Elem x , Elem y ->
567
568
569
        let res =
          if op = "&" then And (x, y) else Diff (x, y)
        in
570
        Elem (mk _loc res)
571
572
      | _ ->
        error _loc ( op ^ " not allowed in regular expression")
573
    ]
574
  | "capture" [ a = IDENT; "::"; x = regexp -> SeqCapture ((lop _loc,ident a),x) ]
575
576
577
578
  | [ x = regexp; "*" -> Star x
    | x = regexp; "*?" -> WeakStar x
    | x = regexp; "+" -> Seq (x, Star x)
    | x = regexp; "+?" -> Seq (x, WeakStar x)
579
    | x = regexp; "?" ->  Alt (x, Epsilon)
580
    | x = regexp; "??" -> Alt (Epsilon, x)
581
582
583
    | x = regexp; "**"; i = INT ->
	let rec aux i accu =
	  if (i = 0) then accu
584
	  else aux (pred i) (re_seq x accu)
585
	in
586
587
	let i =
	  try
588
589
590
	    let i = int_of_string i in
	    if (i > 1024) then raise Exit else i
	      (* We cannot handle type that huge... *)
591
	  with Failure _ | Exit -> error _loc "Repetition number too large"
592
	in
593
	if (i <= 0) then
594
	  error _loc "Repetition number must be a positive integer";
595
596
	aux i Epsilon
    ]
597
  | [ "("; x = LIST1 regexp SEP ","; ")" ->
598
599
      (match x with
       | [ Elem x ] -> Arg (Elem x)
600
       | [ x ] -> x
601
602
603
604
605
606
607
608
609
610
       | _ ->
	 let x =
          List.map
            (function
	      | Elem x -> x
       | _ -> error _loc
		"Mixing regular expressions and products")
	    x
        in
        Arg (Elem (multi_prod _loc x)))
611
    | "("; a = IDENT; ":="; c = expr; ")" ->
612
	Elem (mk _loc (Constant ((ident a,c))))
613
    | "/"; p = pat LEVEL "simple" -> Guard p
614
    | IDENT "PCDATA" -> string_regexp
615
    | i = STRING1; "--"; j = STRING1 ->
616
617
618
      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))))
619
    | s = STRING1 ->
620
	List.fold_right
621
	  (fun c accu ->
622
	     let c = Chars.V.mk_int c in
623
	     let c = Chars.atom c in
624
	     re_seq (Elem (mknoloc (Internal (Types.char c)))) accu)
625
	  (seq_of_string s)
626
	  Epsilon ]
627
    | [ e = pat LEVEL "basic" -> Elem e ]
628
629
  ];

630
  schema_ref: [
631
    [ schema = IDENT; "."; typ = ident_or_keyword -> (U.mk schema, ident typ)
632
633
634
    ]
  ];

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

637
  pat: [
Pietro Abate's avatar
Pietro Abate committed
638
    [ x = pat; "where";
639
      b = LIST1 [ x = located_ident; "="; y = pat -> (x,[],y) ] SEP "and" ->
Pietro Abate's avatar
Pietro Abate committed
640
        mk _loc (Recurs (x,b)) ]
641
642
643
    | 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)) ]
644
645
    | "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
646
	         | x = pat; "\\"; y = pat -> mk _loc (Diff (x,y)) ]
647
648
649
650
651
    | "instance" [ ids = LIST1 ident_or_keyword SEP ".";
                   args = OPT [ "("; l = LIST1 pat SEP ","; ")" -> l ] ->
                   mk _loc (PatVar (List.map ident ids, opt_to_list args)) ]
    | "basic" [
        x = PVAR ->
652
        mk _loc (Internal (Types.var (Var.mk (ident_aux x))))
653
654
655
      | ids = LIST1 ident_or_keyword SEP "." ->
        mk _loc (PatVar (List.map ident ids, []))
      | "{"; r = record_spec; "}" -> r
656
      | "ref"; p = pat ->
657
	  let get_fun = mk _loc (Arrow (pat_nil, p))
658
	  and set_fun = mk _loc (Arrow (p, pat_nil))in
659
	  let fields =
660
	    [ label "get", (get_fun, None); label "set", (set_fun, None) ] in
661
662
	  mk _loc (Record (false, fields))
      | "_" -> mk _loc (Internal Types.any)
663
      | "("; a = IDENT; ":="; c = expr; ")" ->
664
	  mk _loc (Constant (ident a,c))
665
      | "!"; a = IDENT ->
666
	  mk _loc (Internal (Types.abstract (Types.Abstracts.atom a)))
667
668
      | i = INT ; "--"; j = INT ->
          let i =  Intervals.V.mk i
669
	  and j =  Intervals.V.mk j in
670
          mk _loc (Internal (Types.interval (Intervals.bounded i j)))
671
      | i = INT ->
672
          let i =  Intervals.V.mk i  in
673
          mk _loc (Internal (Types.interval (Intervals.atom i)))
674
      | "*"; "--"; j = INT ->
675
	  let j =  Intervals.V.mk j in
676
          mk _loc (Internal (Types.interval (Intervals.left j)))
677
      | i = INT; "--"; "*" ->
678
	  let i = Intervals.V.mk i in
679
          mk _loc (Internal (Types.interval (Intervals.right i)))
680
      | i = char ->
681
          mk _loc (Internal (Types.char (Chars.char_class i i)))
682
      | i = char ; "--"; j = char ->
683
          mk _loc (Internal (Types.char (Chars.char_class i j)))
684
      | "`"; c = tag_type -> c
685
      | "("; l = LIST1 pat SEP ","; ")" -> multi_prod _loc l
686
      | "["; r = [ r = regexp -> r | -> Epsilon ];
Pietro Abate's avatar
Pietro Abate committed
687
             q = [ ";"; q = pat -> Some q | -> None ];
688
689
690
691
692
693
694
695
        "]" ->
	let r = match q with
                | Some q ->
                  let any = mk _loc (Internal (Types.any)) in
		  Seq(r,Seq(Guard q, Star (Elem any)))
		| None -> r
        in
	   mk _loc (Regexp r)
696
      | "<"; t =
697
            [ x = tag_type -> x
698
            | "("; t = pat; ")" -> t ];
Pietro Abate's avatar
Pietro Abate committed
699
700
            a = attrib_spec; ">"; c = pat ->
              mk _loc (XmlT (t, multi_prod _loc [a;c]))
701
      | s = STRING2 ->
702
703
704
	  let s =
	    List.map
	      (fun c ->
705
706
707
		 mknoloc (Internal
			     (Types.char
				(Chars.atom
708
				   (Chars.V.mk_int c)))))
709
710
	      (seq_of_string s) in
	  let s = s @ [mknoloc (Internal (Sequence.nil_type))] in
711
	  multi_prod _loc s
712
      ]
713

714
715
  ];

716
717
  or_else : [ [ OPT [ "else"; y = pat -> y ]  ] ];

718
  opt_field_pat: [
Pietro Abate's avatar
Pietro Abate committed
719
720
    [ OPT [ "=";
      o = [ "?" -> true | -> false];
721
722
      x = pat;  y = or_else -> (o,x,y) ]
    ]
Pietro Abate's avatar
Pietro Abate committed
723
  ];
724