parser.ml 13.9 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
let parse_ident = Encodings.Utf8.mk_latin1

14 15
let id_dummy = ident (U.mk "$$$")
let atom s = Atoms.mk (parse_ident s)
16
let label s = LabelPool.mk (parse_ident s)
17
let ident s = ident (parse_ident s)
18

19 20 21 22 23 24
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"
		
25 26
let exp pos e = LocatedExpr (loc_of_pos pos,e)

27 28 29 30 31
let rec multi_prod loc = function
  | [ x ] -> x
  | x :: l -> mk loc (Prod (x, multi_prod loc l))
  | [] -> assert false
      
32
let rec tuple = function
33
  | [ x ] -> x
34
  | x :: l -> Pair (x, tuple l)
35
  | [] -> assert false
36 37

let tuple_queue = 
38
  List.fold_right (fun x q -> Pair (x, q))
39 40


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

58 59 60 61 62 63 64 65 66 67 68 69 70 71
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

72
exception Error of string
73
let error (i,j) s = Location.raise_loc i j (Error s)
74

75 76 77
let make_record loc r =
  LabelMap.from_list (fun _ _ -> error loc "Duplicated record field") r

78
let parse_char loc s =
79 80
  let s = seq_of_string loc s in
  match s with
81
    | [ loc,c ] -> c
82
    | _ -> error loc "Character litteral must have length 1"
83

84 85
let char_list loc s = 
  let s = seq_of_string loc s in
86
  List.map (fun (loc,c) -> exp loc (Cst (Types.Char (Chars.mk_int c)))) s
87 88


89 90
let include_stack = ref []

91
EXTEND
92 93 94
  GLOBAL: prog expr pat regexp const;

  prog: [
95
    [ l = LIST0 [ p = phrase; ";;" -> p ]; EOI -> List.flatten l ]
96 97 98
  ];

  phrase: [
99
    [ (p,e) = let_binding -> [ mk loc (LetDecl (p,e)) ]
100
    | (p,e1) = let_binding; "in"; e2 = expr LEVEL "top"->
101
        [ mk loc (EvalStatement (exp loc (Match (e1,[p,e2])))) ]
102
    | LIDENT "type"; x = UIDENT; "="; t = pat -> [ mk loc (TypeDecl (x,t)) ]
103
    | LIDENT "type"; x = LIDENT -> [ error loc "Type identifiers must be capitalized" ]
104 105
    | LIDENT "debug"; d = debug_directive -> [ mk loc (Debug d) ]
    | LIDENT "include"; s = STRING2 ->
106
	let s = get_string s in
107 108 109 110 111 112 113 114 115 116 117 118 119 120
	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
	)
121
    ] | 
122
    [ e = expr -> [ mk loc (EvalStatement e) ]
123 124 125 126 127
    ]
  ];

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

135 136 137 138 139 140 141 142 143 144 145
  keyword: [
    [ a = 
	[ "map" | "match" | "with" | "try" | "xtransform"
	| "if" | "then"	| "else"
	| "transform" | "fun" | "in"
	| "let"
	]
	-> a
    ]
  ];

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

    
171 172 173 174 175 176
    | 
    [ e1 = expr; op = ["=" | "<=" | "<<" | ">>" | ">=" ]; e2 = expr -> 
	let op = match op with
	  | "<<" -> "<"
	  | ">>" -> ">"
	  | s -> s in
177
	exp loc (Op (op,[e1;e2]))
178 179
    ]

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

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

  ];
249 250

  seq_elem: [
251 252 253
    [ x = STRING1 -> `Elems (char_list loc x)
    | e = expr LEVEL "no_appl" -> `Elems [e]
    | "!"; e = expr LEVEL "no_appl" -> `Explode e
254 255
    ]
  ];
256 257 258
	  
  let_binding: [
    [ "let"; p = pat; "="; e = expr -> (p,e)
259
    | "let"; p = pat; ":"; t = pat; "="; e = expr -> (p, Forget (e,t))
260 261 262 263 264 265
    | "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
266
        let e = exp loc (Abstraction abst) in
267
        (p,e);
268 269 270
    ] 
  ];

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

296
 arrow: [
297
    [ t1 = pat LEVEL "no_arrow"; "->"; t2 = pat -> (t1,t2)]
298 299 300
  ];

  branches: [
301
    [ OPT "|"; l = LIST1 branch SEP "|" -> l ]
302 303 304
  ];

  branch: [
305
    [ p = pat LEVEL "no_arrow"; "->"; e = expr -> (p,e) ]
306 307 308 309
  ];

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

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

  record_spec:
407
    [ [ r = LIST0 [ l = [LIDENT | UIDENT | keyword ]; "=";
408
                  o = [ "?" -> true | -> false]; 
409 410
                  x = pat -> 
		    let x = if o then mk loc (Optional x) else x in
411
		    (label l, x)
412
                ] SEP ";" ->
413
	  make_record loc r
414 415
      ] ];
  
416 417
  char:
    [ 
418
      [ c = STRING1 -> Chars.mk_int (parse_char loc c) ]
419 420 421
    ];
     

422 423
  const:
    [ 
424
      [ i = INT -> Types.Integer (Intervals.mk i)
425
      | "`"; a = [LIDENT | UIDENT | keyword ] -> Types.Atom (atom a)
426
      | c = char -> Types.Char c ]
427 428 429 430
    ];


  attrib_spec:
431
    [ [ r = record_spec -> mk loc (Record (true,r)) 
432 433 434 435
      | "("; t = pat; ")" -> t 
      | "{"; r = record_spec; "}" -> mk loc (Record (true,r))
      | "{|"; r = record_spec; "|}" -> mk loc (Record (false,r))
      ] ];
436 437 438

  expr_record_spec:
    [ [ r = LIST1
439
	      [ l = [LIDENT | UIDENT | keyword ]; "="; x = expr -> 
440
		  (label l,x) ] 
441
	      SEP ";" ->
442
	  exp loc (RecordLitt (make_record loc r))
443 444 445 446 447
      ] ];
  
  expr_attrib_spec:
    [ [ r = expr_record_spec -> r ]
    | [ e = expr LEVEL "no_appl" -> e 
448
      | -> exp loc (RecordLitt (LabelMap.empty)) 
449 450 451 452
      ] 
    ];
END

453 454 455 456 457
let pat'  = Grammar.Entry.create gram "type/pattern expression"
EXTEND GLOBAL: pat pat';
  pat': [  [ p = pat; EOI -> p ] ];
END

458
let pat = Grammar.Entry.parse pat
459 460
and expr = Grammar.Entry.parse expr
and prog = Grammar.Entry.parse prog
461

462

463
module From_string = struct
464
  let pat s = Grammar.Entry.parse pat' (Stream.of_string s)
465 466
  let expr s = expr (Stream.of_string s)
end
467