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

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

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

11 12 13 14
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)
15

16 17
let parse_ident = Encodings.Utf8.mk_latin1

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

23 24 25 26 27 28
let prog    = Grammar.Entry.create gram "prog"
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"
		
29 30
let exp pos e = LocatedExpr (loc_of_pos pos,e)

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

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


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

62 63 64 65 66 67 68 69 70 71 72 73 74 75
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

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

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

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

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


93 94
let include_stack = ref []

95
EXTEND
96 97 98
  GLOBAL: prog expr pat regexp const;

  prog: [
99
    [ l = LIST0 [ p = phrase; ";;" -> p ]; EOI -> List.flatten l ]
100 101 102
  ];

  phrase: [
103
    [ (p,e) = let_binding -> [ mk loc (LetDecl (p,e)) ]
104
    | (p,e1) = let_binding; "in"; e2 = expr LEVEL "top"->
105
        [ mk loc (EvalStatement (exp loc (Match (e1,[p,e2])))) ]
106
    | LIDENT "type"; x = UIDENT; "="; t = pat -> [ mk loc (TypeDecl (x,t)) ]
107
    | LIDENT "type"; x = LIDENT -> [ error loc "Type identifiers must be capitalized" ]
108 109
    | LIDENT "debug"; d = debug_directive -> [ mk loc (Debug d) ]
    | LIDENT "include"; s = STRING2 ->
110
	let s = get_string s in
111 112 113 114 115 116 117 118 119 120 121 122 123 124
	protect_op "File inclusion";
	(* avoid looping; should issue an error ? *)
	if List.mem s !include_stack then [] 
	else (
	  include_stack := s :: !include_stack;
	  let chan = open_in s in
	  Location.push_source (`File s);
	  let input = Stream.of_channel chan in
	  let l = Grammar.Entry.parse prog input in
	  close_in chan;
	  Location.pop_source ();
	  include_stack := List.tl !include_stack;
	  l
	)
125
    ] | 
126
    [ e = expr -> [ mk loc (EvalStatement e) ]
127 128 129 130 131
    ]
  ];

  debug_directive: [
    [ LIDENT "filter"; t = pat; p = pat -> `Filter(t,p)
132
    | LIDENT "accept"; p = pat -> `Accept p
133
    | LIDENT "compile"; t = pat; p = LIST1 pat -> `Compile (t,p)
134
    | LIDENT "sample"; t = pat -> `Sample t
135
    | LIDENT "subtype"; t1 = pat; t2 = pat -> `Subtype (t1,t2)
136
    ]
137
  ];
138

139 140 141 142 143 144 145 146 147 148 149
  keyword: [
    [ a = 
	[ "map" | "match" | "with" | "try" | "xtransform"
	| "if" | "then"	| "else"
	| "transform" | "fun" | "in"
	| "let"
	]
	-> a
    ]
  ];

150 151
  expr: [
    "top" RIGHTA
152 153
    [ "match"; e = SELF; "with"; b = branches -> 
	exp loc (Match (e,b))
154 155
    | "try"; e = SELF; "with"; b = branches -> 
	let default = 
156
	  mknoloc (Capture id_dummy), 
157
	  Op ("raise", [Var id_dummy]) in
158
	exp loc (Try (e,b@[default]))
159 160 161 162
    | "map"; e = SELF; "with"; b = branches -> 
	exp loc (Map (e,b))
    | "xtransform"; e = SELF; "with"; b = branches -> 
	exp loc (Xtrans (e,b))
163
    | "if"; e = SELF; "then"; e1 = SELF; "else"; e2 = SELF ->
164 165
	let p1 = mk loc (Internal true_type)
	and p2 = mk loc (Internal false_type) in
166
	exp loc (Match (e, [p1,e1; p2,e2]))
167
    | "transform"; e = SELF; "with"; b = branches -> 
168
	exp loc (Transform (e,b))
169
    | "fun"; (f,a,b) = fun_decl ->
170
	exp loc (Abstraction { fun_name = f; fun_iface = a; fun_body = b })
171
    | (p,e1) = let_binding; "in"; e2 = expr LEVEL "top"->
172
        exp loc (Match (e1,[p,e2]))
173
    | e = expr; ":"; p = pat ->
174
	exp loc (Forget (e,p))
175 176 177
    ]

    
178 179 180 181 182 183
    | 
    [ e1 = expr; op = ["=" | "<=" | "<<" | ">>" | ">=" ]; e2 = expr -> 
	let op = match op with
	  | "<<" -> "<"
	  | ">>" -> ">"
	  | s -> s in
184
	exp loc (Op (op,[e1;e2]))
185 186
    ]

187
    | 
188
    [ e1 = expr; op = ["+" | "-" | "@" ]; e2 = expr -> 
189
	exp loc (Op (op,[e1;e2]))
190
    | e = expr; "\\"; l = [LIDENT | UIDENT | keyword ] -> 
191
	exp loc (RemoveField (e, label l)) 
192 193
    ]
    |
194
    [ e1 = expr; op = ["*"]; e2 = expr -> exp loc (Op (op,[e1;e2]))  
195 196 197 198 199
    | 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
200
	let re = Star(Alt(SeqCapture(id_dummy,Elem p), Elem any)) in
201 202
	let ct = mk loc (Regexp (re,any)) in
        let p = mk loc (XmlT (tag, multi_prod loc [att;ct])) in
203
	let b = (p,  Var id_dummy) in
204
	exp loc (Transform (e,[b]))
205
    ]
206
    |
207
    [ e = expr;  "."; l = [LIDENT | UIDENT | keyword ] -> 
208
	exp loc (Dot (e, label l)) 
209
    ]  
210
 
211
    |
212 213
    [ op = [ LIDENT "flatten"
	   | LIDENT "load_xml"
214
	   | LIDENT "load_file" | LIDENT "load_file_utf8"
215
	   | LIDENT "load_html"
216
	   | LIDENT "print_xml" | LIDENT "print_xml_utf8"
217
	   | LIDENT "print"
218
	   | LIDENT "int_of"
219
	   | LIDENT "string_of"
220
	   | LIDENT "atom_of"
221
	   | LIDENT "raise"
222
	   ]; 
223
      e = expr -> exp loc (Op (op,[e]))
224
    | op = [ LIDENT "dump_to_file" | LIDENT "dump_to_file_utf8" ];
225 226 227 228
      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))
229 230
    ]

231
    | "no_appl" 
232 233
    [ c = const -> exp loc (Cst c)
    | "("; l = LIST1 expr SEP ","; ")" -> exp loc (tuple l)
234 235
    | "[";  l = LIST0 seq_elem; e = OPT [ ";"; e = expr -> e ]; "]" ->
	let e = match e with Some e -> e | None -> cst_nil in
236 237 238 239 240 241 242 243
	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
244 245
    | "<"; t = [ "("; e = expr; ")" -> e
	       | a = [ LIDENT | UIDENT | keyword ] -> 
246
		   exp loc (Cst (Types.Atom (atom a))) ];
247
	a = expr_attrib_spec; ">"; c = expr ->
248 249
	exp loc (Xml (t, Pair (a,c)))
    | "{"; r = [ expr_record_spec | -> exp loc (RecordLitt LabelMap.empty) ]; "}" -> r
250
    | s = STRING2 ->
251
	exp loc (tuple (char_list loc s @ [cst_nil]))
252
    | a = LIDENT -> exp loc (Var (ident a))
253 254 255
    ]

  ];
256 257

  seq_elem: [
258 259 260
    [ x = STRING1 -> `Elems (char_list loc x)
    | e = expr LEVEL "no_appl" -> `Elems [e]
    | "!"; e = expr LEVEL "no_appl" -> `Explode e
261 262
    ]
  ];
263 264 265
	  
  let_binding: [
    [ "let"; p = pat; "="; e = expr -> (p,e)
266
    | "let"; p = pat; ":"; t = pat; "="; e = expr -> (p, Forget (e,t))
267 268 269 270 271 272
    | "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
273
        let e = exp loc (Abstraction abst) in
274
        (p,e);
275 276 277
    ] 
  ];

278
 fun_decl: [
279 280
(* need an hack to do this, because both productions would
   match   [ OPT LIDENT; "("; pat ] .... *)
281
   [ f = OPT [ x = LIDENT -> ident x]; "("; p1 = pat LEVEL "no_arrow";
282 283 284 285 286 287 288 289 290 291 292 293 294
    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
295 296
	    let targ = multi_prod nopos (List.map snd args) in
	    let arg = multi_prod nopos (List.map fst args) in
297 298 299
	    let b = [arg, body] in
	    let a = [targ,tres] in
	    (f,a,b)
300 301 302
  ]
 ];

303
 arrow: [
304
    [ t1 = pat LEVEL "no_arrow"; "->"; t2 = pat -> (t1,t2)]
305 306 307
  ];

  branches: [
308
    [ OPT "|"; l = LIST1 branch SEP "|" -> l ]
309 310 311
  ];

  branch: [
312
    [ p = pat LEVEL "no_arrow"; "->"; e = expr -> (p,e) ]
313 314 315 316
  ];

	  
  regexp: [ 
317 318 319 320 321
    [ x = regexp; "|"; y = regexp -> 
	match (x,y) with
	  | Elem x, Elem y -> Elem (mk loc (Or (x,y)))
	  | _ -> Alt (x,y) 
    ]
322
  | [ x = regexp; y = regexp -> Seq (x,y) ]
323
  | [ a = LIDENT; "::"; x = regexp -> SeqCapture (ident a,x) ]
324 325 326 327
  | [ x = regexp; "*" -> Star x
    | x = regexp; "*?" -> WeakStar x
    | x = regexp; "+" -> Seq (x, Star x)
    | x = regexp; "+?" -> Seq (x, WeakStar x)
328
    | x = regexp; "?" ->  Alt (x, Epsilon)
329 330
    | x = regexp; "??" -> Alt (Epsilon, x) ]
  | [ "("; x = regexp; ")" -> x
331
    | "("; a = LIDENT; ":="; c = const; ")" -> 
332
	Elem (mk loc (Constant ((ident a,c))))
333
    | UIDENT "PCDATA" -> string_regexp
334
    | i = STRING1; "--"; j = STRING1 ->
335 336
	let i = Chars.mk_int (parse_char loc i)
	and j = Chars.mk_int (parse_char loc j) in
337
        Elem (mk loc (Internal (Types.char (Chars.char_class i j))))
338 339
    |  s = STRING1 ->
	let s = seq_of_string loc s in
340
	List.fold_right
341
	  (fun (loc,c) accu -> 
342
	     let c = Chars.mk_int c in
343 344 345
	     let c = Chars.atom c in
	     Seq (Elem (mk loc (Internal (Types.char c))), accu))
	  s
346
	  Epsilon 
347 348 349 350 351
    | e = pat LEVEL "simple" -> Elem e
    ]
  ];

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

  record_spec:
414
    [ [ r = LIST0 [ l = [LIDENT | UIDENT | keyword ]; "=";
415
                  o = [ "?" -> true | -> false]; 
416 417
                  x = pat -> 
		    let x = if o then mk loc (Optional x) else x in
418
		    (label l, x)
419
                ] SEP ";" ->
420
	  make_record loc r
421 422
      ] ];
  
423 424
  char:
    [ 
425
      [ c = STRING1 -> Chars.mk_int (parse_char loc c) ]
426 427 428
    ];
     

429 430
  const:
    [ 
431
      [ i = INT -> Types.Integer (Intervals.mk i)
432
      | "`"; a = [LIDENT | UIDENT | keyword ] -> Types.Atom (atom a)
433
      | c = char -> Types.Char c ]
434 435 436 437
    ];


  attrib_spec:
438
    [ [ r = record_spec -> mk loc (Record (true,r)) 
439 440 441 442
      | "("; t = pat; ")" -> t 
      | "{"; r = record_spec; "}" -> mk loc (Record (true,r))
      | "{|"; r = record_spec; "|}" -> mk loc (Record (false,r))
      ] ];
443 444 445

  expr_record_spec:
    [ [ r = LIST1
446
	      [ l = [LIDENT | UIDENT | keyword ]; "="; x = expr -> 
447
		  (label l,x) ] 
448
	      SEP ";" ->
449
	  exp loc (RecordLitt (make_record loc r))
450 451 452 453 454
      ] ];
  
  expr_attrib_spec:
    [ [ r = expr_record_spec -> r ]
    | [ e = expr LEVEL "no_appl" -> e 
455
      | -> exp loc (RecordLitt (LabelMap.empty)) 
456 457 458 459
      ] 
    ];
END

460 461 462 463 464
let pat'  = Grammar.Entry.create gram "type/pattern expression"
EXTEND GLOBAL: pat pat';
  pat': [  [ p = pat; EOI -> p ] ];
END

465
let pat = Grammar.Entry.parse pat
466 467
and expr = Grammar.Entry.parse expr
and prog = Grammar.Entry.parse prog
468

469

470
module From_string = struct
471
  let pat s = Grammar.Entry.parse pat' (Stream.of_string s)
472 473
  let expr s = expr (Stream.of_string s)
end
474