parser.ml 14.4 KB
Newer Older
1 2
open Location
open Ast
3
open Ident
4

5
(*
6
let ()  = Grammar.error_verbose := true
7
*)
8

9

10 11
let gram    = Grammar.gcreate (Wlexer.lexer Wlexer.token Wlexer.latin1_engine)

12 13 14 15
let true_atom = Atoms.mk_ascii "true"
let false_atom = Atoms.mk_ascii "false"
let true_type = Types.atom (Atoms.atom true_atom)
let false_type = Types.atom (Atoms.atom false_atom)
16

17 18
let parse_ident = Encodings.Utf8.mk_latin1

19 20
let id_dummy = ident (U.mk "$$$")
let atom s = Atoms.mk (parse_ident s)
21
let label s = LabelPool.mk (parse_ident s)
22
let ident s = ident (parse_ident s)
23

24
let prog    = Grammar.Entry.create gram "prog"
25
let top_phrases   = Grammar.Entry.create gram "toplevel phrases"
26 27 28 29 30
let expr    = Grammar.Entry.create gram "expression"
let pat     = Grammar.Entry.create gram "type/pattern expression"
let regexp  = Grammar.Entry.create gram "type/pattern regexp"
let const   = Grammar.Entry.create gram "scalar constant"
		
31 32
let exp pos e = LocatedExpr (loc_of_pos pos,e)

33 34 35 36 37
let rec multi_prod loc = function
  | [ x ] -> x
  | x :: l -> mk loc (Prod (x, multi_prod loc l))
  | [] -> assert false
      
38
let rec tuple = function
39
  | [ x ] -> x
40
  | x :: l -> Pair (x, tuple l)
41
  | [] -> assert false
42 43

let tuple_queue = 
44
  List.fold_right (fun x q -> Pair (x, q))
45 46


47
let char = mknoloc (Internal (Types.char Chars.any))
48
let string_regexp = Star (Elem char)
49
	       
50
let cst_nil =  Cst (Types.Atom Sequence.nil_atom)
51
		 
52
let seq_of_string pos s =
53
  let s =  Encodings.Utf8.mk s in
54
  let (pos,_) = pos in
55 56 57
  let rec aux pos i j =
    if Encodings.Utf8.equal_index i j then []
    else
58
      let (len,i) = Encodings.Utf8.next s i in
59
      let (c,i) = Encodings.Utf8.next s i in
60
      ((pos,pos+len),c) :: (aux (pos + len) i j)
61
  in
62
  aux (pos+1) (Encodings.Utf8.start_index s) (Encodings.Utf8.end_index s)
63

64 65 66 67 68 69 70 71 72 73 74 75 76 77
let get_string s =
  let s = Encodings.Utf8.mk s in
  let b = Buffer.create 32 in
  let rec aux i j =
    if Encodings.Utf8.equal_index i j then ()
    else
      let (len,i) = Encodings.Utf8.next s i in
      let (c,i) = Encodings.Utf8.next s i in
      Encodings.Utf8.store b c;
      aux i j
  in
  aux (Encodings.Utf8.start_index s) (Encodings.Utf8.end_index s);
  Buffer.contents b

78
exception Error of string
79
let error (i,j) s = Location.raise_loc i j (Error s)
80

81 82 83
let make_record loc r =
  LabelMap.from_list (fun _ _ -> error loc "Duplicated record field") r

84
let parse_char loc s =
85 86
  let s = seq_of_string loc s in
  match s with
87
    | [ loc,c ] -> c
88
    | _ -> error loc "Character litteral must have length 1"
89

90 91
let char_list loc s = 
  let s = seq_of_string loc s in
92
  List.map (fun (loc,c) -> exp loc (Cst (Types.Char (Chars.mk_int c)))) s
93 94


95 96
let include_stack = ref []

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

101
EXTEND
102 103 104
  GLOBAL: top_phrases prog expr pat regexp const;

  top_phrases: [
105
    [ l = LIST0 phrase; ";;" -> List.flatten l  ]
106
  ];
107 108

  prog: [
109
    [ l = LIST0 [ p = phrase ; OPT ";;" -> p ]; EOI -> List.flatten l ]
110 111 112
  ];

  phrase: [
113 114 115 116
    [ (f,p,e) = let_binding -> 
	if f then [ mk loc (FunDecl e) ] else
	  [ mk loc (LetDecl (p,e)) ]
    | (_,p,e1) = let_binding; "in"; e2 = expr LEVEL "top"->
117
        [ mk loc (EvalStatement (exp loc (Match (e1,[p,e2])))) ]
118 119 120
    | "type"; x = UIDENT; "="; t = pat -> [ mk loc (TypeDecl (x,t)) ]
    | "type"; x = LIDENT -> error loc "Type identifiers must be capitalized"
    | "debug"; d = debug_directive -> [ mk loc (Debug d) ]
121 122
    | DIRECTIVE "#quit" -> [ mk loc (Directive `Quit) ]
    | DIRECTIVE "#env" -> [ mk loc (Directive `Env) ]
123
    | "include"; s = STRING2 ->
124
	let s = get_string s in
125 126 127 128 129 130
	protect_op "File inclusion";
	(* avoid looping; should issue an error ? *)
	if List.mem s !include_stack then [] 
	else (
	  include_stack := s :: !include_stack;
	  Location.push_source (`File s);
131 132 133 134 135 136 137 138 139 140
	  protect_exn
	    (fun () ->
	       let chan = open_in s in
	       let input = Stream.of_channel chan in
	       let l = Grammar.Entry.parse prog input in
	       close_in chan;
	       l)
	    (fun () ->
	       Location.pop_source ();
	       include_stack := List.tl !include_stack)
141
	)
142
    ] | 
143
    [ e = expr -> [ mk loc (EvalStatement e) ]
144 145 146 147 148
    ]
  ];

  debug_directive: [
    [ LIDENT "filter"; t = pat; p = pat -> `Filter(t,p)
149
    | LIDENT "accept"; p = pat -> `Accept p
150
    | LIDENT "compile"; t = pat; p = LIST1 pat -> `Compile (t,p)
151
    | LIDENT "sample"; t = pat -> `Sample t
152
    | LIDENT "subtype"; t1 = pat; t2 = pat -> `Subtype (t1,t2)
153
    ]
154
  ];
155

156 157 158 159 160
  keyword: [
    [ a = 
	[ "map" | "match" | "with" | "try" | "xtransform"
	| "if" | "then"	| "else"
	| "transform" | "fun" | "in"
161
	| "let" | "type" | "debug" | "include"
162 163 164 165 166
	]
	-> a
    ]
  ];

167 168
  expr: [
    "top" RIGHTA
169 170
    [ "match"; e = SELF; "with"; b = branches -> 
	exp loc (Match (e,b))
171
    | "try"; e = SELF; "with"; b = branches -> 
172
	exp loc (Try (e,b))
173 174 175 176
    | "map"; e = SELF; "with"; b = branches -> 
	exp loc (Map (e,b))
    | "xtransform"; e = SELF; "with"; b = branches -> 
	exp loc (Xtrans (e,b))
177
    | "if"; e = SELF; "then"; e1 = SELF; "else"; e2 = SELF ->
178 179
	let p1 = mk loc (Internal true_type)
	and p2 = mk loc (Internal false_type) in
180
	exp loc (Match (e, [p1,e1; p2,e2]))
181
    | "transform"; e = SELF; "with"; b = branches -> 
182
	exp loc (Transform (e,b))
183
    | "fun"; (f,a,b) = fun_decl ->
184
	exp loc (Abstraction { fun_name = f; fun_iface = a; fun_body = b })
185
    | (_,p,e1) = let_binding; "in"; e2 = expr LEVEL "top"->
186
        exp loc (Match (e1,[p,e2]))
187
    | e = expr; ":"; p = pat ->
188
	exp loc (Forget (e,p))
189 190 191
    ]

    
192 193 194 195 196 197
    | 
    [ e1 = expr; op = ["=" | "<=" | "<<" | ">>" | ">=" ]; e2 = expr -> 
	let op = match op with
	  | "<<" -> "<"
	  | ">>" -> ">"
	  | s -> s in
198
	exp loc (Op (op,[e1;e2]))
199 200
    ]

201
    | 
202
    [ e1 = expr; op = ["+" | "-" | "@" ]; e2 = expr -> 
203
	exp loc (Op (op,[e1;e2]))
204
    | e = expr; "\\"; l = [LIDENT | UIDENT | keyword ] -> 
205
	exp loc (RemoveField (e, label l)) 
206 207
    ]
    |
208
    [ e1 = expr; op = ["*"]; e2 = expr -> exp loc (Op (op,[e1;e2]))  
209 210 211 212 213
    | e = expr; op = "/"; p = pat ->

	let tag = mk loc (Internal (Types.atom (Atoms.any))) in
	let att = mk loc (Internal Types.Record.any) in
	let any = mk loc (Internal (Types.any)) in
214
	let re = Star(Alt(SeqCapture(id_dummy,Elem p), Elem any)) in
215 216
	let ct = mk loc (Regexp (re,any)) in
        let p = mk loc (XmlT (tag, multi_prod loc [att;ct])) in
217
	let b = (p,  Var id_dummy) in
218
	exp loc (Transform (e,[b]))
219
    ]
220
    |
221
    [ e = expr;  "."; l = [LIDENT | UIDENT | keyword ] -> 
222
	exp loc (Dot (e, label l)) 
223
    ]  
224
 
225
    |
226 227
    [ op = [ LIDENT "flatten"
	   | LIDENT "load_xml"
228
	   | LIDENT "load_file" | LIDENT "load_file_utf8"
229
	   | LIDENT "load_html"
230
	   | LIDENT "print_xml" | LIDENT "print_xml_utf8"
231
	   | LIDENT "print"
232
	   | LIDENT "int_of"
233
	   | LIDENT "string_of"
234
	   | LIDENT "atom_of"
235
	   | LIDENT "raise"
236
	   ]; 
237
      e = expr -> exp loc (Op (op,[e]))
238
    | op = [ LIDENT "dump_to_file" | LIDENT "dump_to_file_utf8" ];
239 240 241 242
      e1 = expr LEVEL "no_appl"; e2 = expr -> exp loc (Op (op, [e1;e2])) 
    | e1 = SELF; LIDENT "div"; e2 = expr -> exp loc (Op ("/", [e1;e2]))
    | e1 = SELF; LIDENT "mod"; e2 = expr -> exp loc (Op ("mod", [e1;e2]))
    | e1 = SELF; e2 = expr -> exp loc (Apply (e1,e2))
243 244
    ]

245
    | "no_appl" 
246 247
    [ c = const -> exp loc (Cst c)
    | "("; l = LIST1 expr SEP ","; ")" -> exp loc (tuple l)
248 249
    | "[";  l = LIST0 seq_elem; e = OPT [ ";"; e = expr -> e ]; "]" ->
	let e = match e with Some e -> e | None -> cst_nil in
250 251 252 253 254 255 256 257
	let l = List.fold_right 
		  (fun x q ->
		     match x with
		       | `Elems l -> tuple_queue l q
		       | `Explode x -> Op ("@",[x;q])
		  ) l e
	in
	exp loc l
258 259
    | "<"; t = [ "("; e = expr; ")" -> e
	       | a = [ LIDENT | UIDENT | keyword ] -> 
260
		   exp loc (Cst (Types.Atom (atom a))) ];
261
	a = expr_attrib_spec; ">"; c = expr ->
262 263
	exp loc (Xml (t, Pair (a,c)))
    | "{"; r = [ expr_record_spec | -> exp loc (RecordLitt LabelMap.empty) ]; "}" -> r
264
    | s = STRING2 ->
265
	exp loc (tuple (char_list loc s @ [cst_nil]))
266
    | a = LIDENT -> exp loc (Var (ident a))
267 268 269
    ]

  ];
270 271

  seq_elem: [
272 273 274
    [ x = STRING1 -> `Elems (char_list loc x)
    | e = expr LEVEL "no_appl" -> `Elems [e]
    | "!"; e = expr LEVEL "no_appl" -> `Explode e
275 276
    ]
  ];
277 278
	  
  let_binding: [
279 280
    [ "let"; p = pat; "="; e = expr -> (false,p,e)
    | "let"; p = pat; ":"; t = pat; "="; e = expr -> (false,p, Forget (e,t))
281 282 283 284 285 286
    | "let"; "fun"; (f,a,b) = fun_decl ->
	let p = match f with 
	  | Some x -> mk loc (Capture x)
	  | _ -> failwith "Function name mandatory in let fun declarations"
	in
	let abst = { fun_name = f; fun_iface = a; fun_body = b } in
287
        let e = exp loc (Abstraction abst) in
288
        (true,p,e)
289 290 291
    ] 
  ];

292
 fun_decl: [
293 294
(* need an hack to do this, because both productions would
   match   [ OPT LIDENT; "("; pat ] .... *)
295
   [ f = OPT [ x = LIDENT -> ident x]; "("; p1 = pat LEVEL "no_arrow";
296 297 298 299 300 301 302 303 304 305 306 307 308
    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) ]; 
	    ")"; ":"; tres = pat ; 
	    "="; body = expr ->
	      `Compact (targ1,args,tres,body)
	  ] ->
      match res with
	| `Classic (p2,a,b) -> f,(p1,p2)::a,b
	| `Compact (targ1,args,tres,body) ->
	    let args = (p1,targ1) :: args in
309 310
	    let targ = multi_prod nopos (List.map snd args) in
	    let arg = multi_prod nopos (List.map fst args) in
311 312 313
	    let b = [arg, body] in
	    let a = [targ,tres] in
	    (f,a,b)
314 315 316
  ]
 ];

317
 arrow: [
318
    [ t1 = pat LEVEL "no_arrow"; "->"; t2 = pat -> (t1,t2)]
319 320 321
  ];

  branches: [
322
    [ OPT "|"; l = LIST1 branch SEP "|" -> l ]
323 324 325
  ];

  branch: [
326
    [ p = pat LEVEL "no_arrow"; "->"; e = expr -> (p,e) ]
327 328 329 330
  ];

	  
  regexp: [ 
331 332 333 334 335
    [ x = regexp; "|"; y = regexp -> 
	match (x,y) with
	  | Elem x, Elem y -> Elem (mk loc (Or (x,y)))
	  | _ -> Alt (x,y) 
    ]
336
  | [ x = regexp; y = regexp -> Seq (x,y) ]
337
  | [ a = LIDENT; "::"; x = regexp -> SeqCapture (ident a,x) ]
338 339 340 341
  | [ x = regexp; "*" -> Star x
    | x = regexp; "*?" -> WeakStar x
    | x = regexp; "+" -> Seq (x, Star x)
    | x = regexp; "+?" -> Seq (x, WeakStar x)
342
    | x = regexp; "?" ->  Alt (x, Epsilon)
343 344
    | x = regexp; "??" -> Alt (Epsilon, x) ]
  | [ "("; x = regexp; ")" -> x
345
    | "("; a = LIDENT; ":="; c = const; ")" -> 
346
	Elem (mk loc (Constant ((ident a,c))))
347
    | UIDENT "PCDATA" -> string_regexp
348
    | i = STRING1; "--"; j = STRING1 ->
349 350
	let i = Chars.mk_int (parse_char loc i)
	and j = Chars.mk_int (parse_char loc j) in
351
        Elem (mk loc (Internal (Types.char (Chars.char_class i j))))
352 353
    |  s = STRING1 ->
	let s = seq_of_string loc s in
354
	List.fold_right
355
	  (fun (loc,c) accu -> 
356
	     let c = Chars.mk_int c in
357 358 359
	     let c = Chars.atom c in
	     Seq (Elem (mk loc (Internal (Types.char c))), accu))
	  s
360
	  Epsilon 
361 362 363 364 365
    | e = pat LEVEL "simple" -> Elem e
    ]
  ];

  pat: [ 
366
      [ x = pat; LIDENT "where"; 
367 368 369
        b = LIST1 [ a = UIDENT; "="; y = pat -> (a,y)
		  | LIDENT -> error loc "Type/pattern identifiers must be capitalized"
		  ] SEP "and"
370 371
            -> mk loc (Recurs (x,b)) ]
    | RIGHTA [ x = pat; "->"; y = pat -> mk loc (Arrow (x,y)) ]
372
    | "no_arrow" [ x = pat; "|"; y = pat -> mk loc (Or (x,y)) ] 
373
    | "simple" [ x = pat; "&"; y = pat -> mk loc (And (x,y)) 
374
	       | x = pat; "\\"; y = pat -> mk loc (Diff (x,y)) ]
375
    | 
376 377
      [ "{"; r = record_spec; "}" -> mk loc (Record (true,r))
      | "{|"; r = record_spec; "|}" -> mk loc (Record (false,r))
378
      | LIDENT "_" -> mk loc (Internal Types.any)
379
      | a = LIDENT -> mk loc (Capture (ident a))
380
      | "("; a = LIDENT; ":="; c = const; ")" -> 
381
	  mk loc (Constant (ident a,c))
382 383
      | a = UIDENT -> mk loc (PatVar a)
      | i = INT ; "--"; j = INT -> 
384 385
          let i =  Intervals.mk i 
	  and j =  Intervals.mk j in
386 387
          mk loc (Internal (Types.interval (Intervals.bounded i j)))
      | i = INT -> 
388
          let i =  Intervals.mk i  in
389
          mk loc (Internal (Types.interval (Intervals.atom i)))
390
      | "*"; "--"; j = INT ->
391
	  let j =  Intervals.mk j in
392
          mk loc (Internal (Types.interval (Intervals.left j)))
393
      | i = INT; "--"; "*" ->
394
	  let i = Intervals.mk i in
395
          mk loc (Internal (Types.interval (Intervals.right i)))
396 397
      | i = char ->
          mk loc (Internal (Types.char (Chars.char_class i i)))
398
      | i = char ; "--"; j = char ->
399
          mk loc (Internal (Types.char (Chars.char_class i j)))
400 401 402 403
      | c = const -> mk loc (Internal (Types.constant c))
      | "("; l = LIST1 pat SEP ","; ")" -> multi_prod loc l
      | "["; r = [ r = regexp -> r | -> Epsilon ];
             q = [ ";"; q = pat -> q 
404
                 | -> mknoloc (Internal (Sequence.nil_type)) ]; 
405
             "]" -> mk loc (Regexp (r,q))
406 407
      | "<"; t =
        [ x = [ LIDENT | UIDENT | keyword ] ->
408
	    let a = if x = "_" then Atoms.any else Atoms.atom (atom x) in
409 410
	    mk loc (Internal (Types.atom a))
	| "("; t = pat; ")" -> t ];
411
	a = attrib_spec; ">"; c = pat ->
412
          mk loc (XmlT (t, multi_prod loc [a;c]))
413 414
      | s = STRING2 ->
	  let s = seq_of_string loc s in
415
	  let s = List.map 
416
		    (fun (loc,c) -> 
417 418 419
		       mk loc (Internal
				 (Types.char
				    (Chars.atom
420
				       (Chars.mk_int c))))) s in
421 422
	  let s = s @ [mk loc (Internal (Sequence.nil_type))] in
	  multi_prod loc s
423 424 425 426 427
      ]
    
  ];

  record_spec:
428
    [ [ r = LIST0 [ l = [LIDENT | UIDENT | keyword ]; "=";
429
                  o = [ "?" -> true | -> false]; 
430 431
                  x = pat -> 
		    let x = if o then mk loc (Optional x) else x in
432
		    (label l, x)
433
                ] SEP ";" ->
434
	  make_record loc r
435 436
      ] ];
  
437 438
  char:
    [ 
439
      [ c = STRING1 -> Chars.mk_int (parse_char loc c) ]
440 441 442
    ];
     

443 444
  const:
    [ 
445
      [ i = INT -> Types.Integer (Intervals.mk i)
446
      | "`"; a = [LIDENT | UIDENT | keyword ] -> Types.Atom (atom a)
447
      | c = char -> Types.Char c ]
448 449 450 451
    ];


  attrib_spec:
452
    [ [ r = record_spec -> mk loc (Record (true,r)) 
453 454 455 456
      | "("; t = pat; ")" -> t 
      | "{"; r = record_spec; "}" -> mk loc (Record (true,r))
      | "{|"; r = record_spec; "|}" -> mk loc (Record (false,r))
      ] ];
457 458 459

  expr_record_spec:
    [ [ r = LIST1
460
	      [ l = [LIDENT | UIDENT | keyword ]; "="; x = expr -> 
461
		  (label l,x) ] 
462
	      SEP ";" ->
463
	  exp loc (RecordLitt (make_record loc r))
464 465 466 467 468
      ] ];
  
  expr_attrib_spec:
    [ [ r = expr_record_spec -> r ]
    | [ e = expr LEVEL "no_appl" -> e 
469
      | -> exp loc (RecordLitt (LabelMap.empty)) 
470 471 472 473
      ] 
    ];
END

474
let pat = Grammar.Entry.parse pat
475 476
and expr = Grammar.Entry.parse expr
and prog = Grammar.Entry.parse prog
477 478 479 480 481 482 483 484 485
and top_phrases = Grammar.Entry.parse top_phrases

let rec sync s =
  match Stream.next s with
    | ';' ->  
	(match Stream.next s with
	   | ';' -> ()
	   | _ -> sync s)
    | _ -> sync s
486 487 488 489

let sync s =
  try sync s with Stream.Failure -> ()