parser.ml 24.5 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
let parse_char loc s =
89 90
  match seq_of_string s with
    | [ c ] -> c
91
    | _ -> error loc "Character litteral must have length 1"
92

93 94
let include_stack = ref []

95 96 97 98
let protect_exn f g =
  try let x = f () in g (); x
  with e -> g (); raise e

99
let localize_exn f =
100 101
  try f ()
  with
102 103 104 105 106
  | 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
107

108
let is_fun_decl =
109
   Gram.Entry.of_parser "[is_fun_decl]"
110 111
     (fun strm ->
       match Stream.npeek 3 strm with
112 113
	 | [ KEYWORD "fun", _; IDENT _, _; KEYWORD "(", _ ]
	 | [ IDENT _, _; KEYWORD "(", _; _ ] -> ()
114 115 116
	 | _ -> raise Stream.Failure
     )

117 118 119
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])
120

121 122 123
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
124

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

128 129
let set_ref e1 e2 = Apply (Dot (e1, U.mk "set"), e2)
let get_ref e = Apply (Dot (e, U.mk "get"), cst_nil)
130 131 132
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
133
let opt_to_list = function None -> [] | Some l -> l
134

135
EXTEND Gram
136
  GLOBAL: top_phrases prog expr pat regexp keyword;
137 138

  top_phrases: [
139
    [ l = LIST0 phrase; ";;" -> List.flatten l  ]
140
  ];
141 142

  prog: [
143
    [ l = LIST0 [ p = phrase ; OPT ";;" -> p ]; `EOI -> List.flatten l ]
144 145 146
  ];

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

  debug_directive: [
222 223 224 225 226
    [ 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)
227
    | IDENT "single"; t = pat -> `Single t
228 229
    | IDENT "typed"; e = expr -> `Typed e
    | IDENT "lambda"; e = expr -> `Lambda e
230
    ]
231
  ];
232

233
  keyword: [
234
    [ a =
235 236 237
	[ "map" | "match" | "with" | "try" | "xtransform"
	| "if" | "then"	| "else"
	| "transform" | "fun" | "in"
238
	| "let" | "type" | "debug" | "include"
239
        | "and" | "or" | "validate" | "schema" | "namespace" | "ref" | "alias"
240
	| "not" | "as" | "where" | "select" | "from" | "open"
241 242 243 244 245
	]
	-> a
    ]
  ];

246 247 248 249 250
  ident_or_keyword: [
    [ s = IDENT -> s
    | s = keyword -> s ]
  ];

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

325
	 let stk = U.mk "$stack" in
326 327 328
	 let y = U.mk "y" in
	 let x = U.mk "x" in
	 let f = U.mk "f" in
329
	 let assign =
Pietro Abate's avatar
Pietro Abate committed
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
         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
347
          let body =
Pietro Abate's avatar
Pietro Abate committed
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
      e1 = SELF; IDENT "div"; e2 = expr -> apply_op2 _loc "/" e1 e2
356 357
    | e1 = SELF; IDENT "mod"; e2 = expr -> apply_op2 _loc "mod" e1 e2
    | e1 = SELF; e2 = expr -> exp _loc (Apply (e1,e2))
358 359
    ]

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

  ];
400

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

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

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

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

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

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

451 452 453 454 455 456 457 458 459 460 461
  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
    ]
  ];

462
 fun_decl_after_lparen: [
Pietro Abate's avatar
Pietro Abate committed
463
  (* need an hack to do this, because both productions would
464
   match   [ OPT IDENT; "("; pat ] .... *)
465 466 467 468
   [ p1 = pat LEVEL "no_arrow";
     res = [ "->"; p2 = pat;
	     a = [ ";"; a = LIST0 arrow SEP ";" -> a | -> [] ];
	     ")"; b = branches -> `Classic (p2,a,b)
469 470
	   | targ1 = OPT [ ":"; p = pat -> p ];
	     args = LIST0 [ ","; arg = arg_colon_type -> arg ];
471
	     ")";
472
	     others = LIST0
473
			[ "(";
474 475
			  args =
			    LIST1
476
			      [ arg = arg_colon_type -> arg ]
477 478
			      SEP ",";
			  ")" -> args ];
479
	     ":" ; tres = pat ;
480
	     "="; body = expr ->
481
	       `Compact (targ1,args,others,tres,body)
482

Pietro Abate's avatar
Pietro Abate committed
483
     ] ->
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
     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
511 512
    ]
  ];
513 514 515


 fun_decl: [
516
   [ f = OPT located_ident; "("; (a,b) = fun_decl_after_lparen -> (f,a,b)
517
   ]
518 519
 ];

520
  arrow: [
521
    [ t1 = pat LEVEL "no_arrow"; "->"; t2 = pat -> (t1,t2)]
522 523 524
  ];

  branches: [
525
    [ OPT "|"; l = LIST1 branch SEP "|" -> l ]
526 527 528
  ];

  branch: [
529
    [ p = pat LEVEL "no_arrow"; "->"; e = expr -> (p,e) ]
530 531
  ];

532 533
  regexp: [
    [ x = regexp; "|"; y = regexp ->
534
	match (x,y) with
535
	  | Elem x, Elem y -> Elem (mk _loc (Or (x,y)))
536
          | _ -> Alt (x, y)
537
    ]
538 539 540
  | [ x = regexp; y = regexp -> re_seq x y ]
  | [ x = regexp ; op = [ "&" -> "&" | "\\" -> "\\" ] ; y = regexp ->
      let rec unseq e = match e with
541 542
          Elem _ -> e
        | Seq(Elem { descr = PatVar (ids, []); loc}, Arg (e0)) ->
543 544 545 546 547 548 549
          let ue0 = unseq e0 in begin
            match ue0 with
            | Elem p -> Elem {loc; descr = PatVar(ids, prod_to_list p) }
            | _ -> e
          end
        | _ -> e
      in
550
      match unseq x, unseq y with
551
      | Elem x , Elem y ->
552 553 554
        let res = if op = "&" then And (x, y) else Diff (x, y) in
        Elem (mk _loc res)
      | _ -> error _loc ( op ^ " not allowed in regular expression")
555
    ]
556
  | "capture" [ a = IDENT; "::"; x = regexp -> SeqCapture ((lop _loc,ident a),x) ]
557 558 559 560
  | [ x = regexp; "*" -> Star x
    | x = regexp; "*?" -> WeakStar x
    | x = regexp; "+" -> Seq (x, Star x)
    | x = regexp; "+?" -> Seq (x, WeakStar x)
561
    | x = regexp; "?" ->  Alt (x, Epsilon)
562
    | x = regexp; "??" -> Alt (Epsilon, x)
563 564 565
    | x = regexp; "**"; i = INT ->
	let rec aux i accu =
	  if (i = 0) then accu
566
	  else aux (pred i) (re_seq x accu)
567
	in
568 569
	let i =
	  try
570 571 572
	    let i = int_of_string i in
	    if (i > 1024) then raise Exit else i
	      (* We cannot handle type that huge... *)
573
	  with Failure _ | Exit -> error _loc "Repetition number too large"
574
	in
575
	if (i <= 0) then
576
	  error _loc "Repetition number must be a positive integer";
577 578
	aux i Epsilon
    ]
579
  | [ "("; x = LIST1 regexp SEP ","; ")" ->
580 581
      (match x with
       | [ Elem x ] -> Arg (Elem x)
582
       | [ x ] -> x
583 584 585 586 587 588 589 590 591 592
       | _ ->
	 let x =
          List.map
            (function
	      | Elem x -> x
       | _ -> error _loc
		"Mixing regular expressions and products")
	    x
        in
        Arg (Elem (multi_prod _loc x)))
593
    | "("; a = IDENT; ":="; c = expr; ")" ->
594
	Elem (mk _loc (Constant ((ident a,c))))
595
    | "/"; p = pat LEVEL "simple" -> Guard p
596
    | IDENT "PCDATA" -> string_regexp
597
    | i = STRING1; "--"; j = STRING1 ->
598 599 600
      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))))
601
    | s = STRING1 ->
602
	List.fold_right
603
	  (fun c accu ->
604
	     let c = Chars.V.mk_int c in
605
	     let c = Chars.atom c in
606
	     re_seq (Elem (mknoloc (Internal (Types.char c)))) accu)
607
	  (seq_of_string s)
608
	  Epsilon ]
609
    | [ e = pat LEVEL "basic" -> Elem e ]
610 611
  ];

612
  schema_ref: [
613
    [ schema = IDENT; "."; typ = ident_or_keyword -> (U.mk schema, ident typ)
614 615 616
    ]
  ];

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

619
  pat: [
Pietro Abate's avatar
Pietro Abate committed
620
    [ x = pat; "where";
621
      b = LIST1 [ x = located_ident; "="; y = pat -> (x,[],y) ] SEP "and" ->
Pietro Abate's avatar
Pietro Abate committed
622
        mk _loc (Recurs (x,b)) ]
623 624 625
    | 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)) ]
626 627
    | "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
628
	         | x = pat; "\\"; y = pat -> mk _loc (Diff (x,y)) ]
629 630 631 632 633
    | "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 ->
634
        mk _loc (Internal (Types.var (Var.mk (ident_aux x))))
635 636 637
      | ids = LIST1 ident_or_keyword SEP "." ->
        mk _loc (PatVar (List.map ident ids, []))
      | "{"; r = record_spec; "}" -> r
638
      | "ref"; p = pat ->
639
	  let get_fun = mk _loc (Arrow (pat_nil, p))
640
	  and set_fun = mk _loc (Arrow (p, pat_nil))in
641
	  let fields =
642
	    [ label "get", (get_fun, None); label "set", (set_fun, None) ] in
643 644
	  mk _loc (Record (false, fields))
      | "_" -> mk _loc (Internal Types.any)
645
      | "("; a = IDENT; ":="; c = expr; ")" ->
646
	  mk _loc (Constant (ident a,c))
647
      | "!"; a = IDENT ->
648
	  mk _loc (Internal (Types.abstract (Types.Abstracts.atom a)))
649 650
      | i = INT ; "--"; j = INT ->
          let i =  Intervals.V.mk i
651
	  and j =  Intervals.V.mk j in