parser.ml 16.1 KB
Newer Older
1 2
open Location
open Ast
3
open Ident
4
open Printf
5

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

10

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

13 14 15 16
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)
17

18 19
let parse_ident = Encodings.Utf8.mk_latin1

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

25
let prog    = Grammar.Entry.create gram "prog"
26
let top_phrases   = Grammar.Entry.create gram "toplevel phrases"
27 28 29 30 31
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"
		
32 33
let exp pos e = LocatedExpr (loc_of_pos pos,e)

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

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


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

65 66 67 68 69 70 71 72 73 74 75 76 77 78
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

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

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

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

91 92
let char_list loc s = 
  let s = seq_of_string loc s in
93
  List.map (fun (loc,c) -> exp loc (Cst (Types.Char (Chars.mk_int c)))) s
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 102 103 104 105 106 107 108 109
let is_fun_decl =
   Grammar.Entry.of_parser gram "[is_fun_decl]"
     (fun strm ->
       match Stream.npeek 3 strm with
	 | [ ("", "fun"); ("LIDENT", _); ("", "(") ]
	 | [ ("LIDENT", _) ; ("", "(") ; _ ] -> ()
	 | _ -> raise Stream.Failure
     )

110
let dot_RE = Pcre.regexp "\\."
111

112
EXTEND
113 114 115
  GLOBAL: top_phrases prog expr pat regexp const;

  top_phrases: [
116
    [ l = LIST0 phrase; ";;" -> List.flatten l  ]
117
  ];
118 119

  prog: [
120
    [ l = LIST0 [ p = phrase ; OPT ";;" -> p ]; EOI -> List.flatten l ]
121 122 123
  ];

  phrase: [
124 125 126 127
    [ (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"->
128
        [ mk loc (EvalStatement (exp loc (Match (e1,[p,e2])))) ]
129 130
    | "type"; x = UIDENT; "="; t = pat -> [ mk loc (TypeDecl (x,t)) ]
    | "type"; x = LIDENT -> error loc "Type identifiers must be capitalized"
131
    | "schema"; name = UIDENT; "="; uri = STRING2 ->
132
	protect_op "schema";
133 134 135
        let schema_doc = Schema_xml.pxp_tree_of (get_string uri) in
        let schema = Schema_parser.parse_schema schema_doc in
        [ mk loc (SchemaDecl (name, schema))]
136
    | "debug"; d = debug_directive -> [ mk loc (Debug d) ]
137 138
    | DIRECTIVE "#quit" -> [ mk loc (Directive `Quit) ]
    | DIRECTIVE "#env" -> [ mk loc (Directive `Env) ]
139
    | "include"; s = STRING2 ->
140
	let s = get_string s in
141 142 143 144
	let s = 
	  if Filename.is_relative s 
	  then Filename.concat (Location.current_dir ()) s
	  else s in
145 146
	protect_op "File inclusion";
	(* avoid looping; should issue an error ? *)
147 148
	(* it is possible to have looping with x/../x/../x/.. ....
	   Need to canonicalize filename *)
149 150 151 152
	if List.mem s !include_stack then [] 
	else (
	  include_stack := s :: !include_stack;
	  Location.push_source (`File s);
153 154 155
	  protect_exn
	    (fun () ->
	       let chan = open_in s in
156 157 158 159 160
	       protect_exn
		 (fun () ->
		    let input = Stream.of_channel chan in
		    Grammar.Entry.parse prog input)
		 (fun () -> close_in chan))
161 162 163
	    (fun () ->
	       Location.pop_source ();
	       include_stack := List.tl !include_stack)
164
	)
165
    ] | 
166
    [ e = expr -> [ mk loc (EvalStatement e) ]
167 168 169 170 171
    ]
  ];

  debug_directive: [
    [ LIDENT "filter"; t = pat; p = pat -> `Filter(t,p)
172
    | LIDENT "accept"; p = pat -> `Accept p
173
    | LIDENT "compile"; t = pat; p = LIST1 pat -> `Compile (t,p)
174
    | LIDENT "sample"; t = pat -> `Sample t
175
    | LIDENT "subtype"; t1 = pat; t2 = pat -> `Subtype (t1,t2)
176
    ]
177
  ];
178

179 180 181 182 183
  keyword: [
    [ a = 
	[ "map" | "match" | "with" | "try" | "xtransform"
	| "if" | "then"	| "else"
	| "transform" | "fun" | "in"
184
	| "let" | "type" | "debug" | "include"
185
        | "and" | "validate" | "schema"
186 187 188 189 190
	]
	-> a
    ]
  ];

191 192
  expr: [
    "top" RIGHTA
193 194
    [ "match"; e = SELF; "with"; b = branches -> 
	exp loc (Match (e,b))
195
    | "try"; e = SELF; "with"; b = branches -> 
196
	exp loc (Try (e,b))
197 198 199 200
    | "map"; e = SELF; "with"; b = branches -> 
	exp loc (Map (e,b))
    | "xtransform"; e = SELF; "with"; b = branches -> 
	exp loc (Xtrans (e,b))
201
    | "if"; e = SELF; "then"; e1 = SELF; "else"; e2 = SELF ->
202 203
	let p1 = mk loc (Internal true_type)
	and p2 = mk loc (Internal false_type) in
204
	exp loc (Match (e, [p1,e1; p2,e2]))
205
    | "transform"; e = SELF; "with"; b = branches -> 
206
	exp loc (Transform (e,b))
207 208 209
    | "validate"; e = SELF; "with"; schema = UIDENT; "#";
      typ = [ UIDENT | LIDENT | keyword ] ->
        exp loc (Validate (e, schema, typ))
210
    | "fun"; (f,a,b) = fun_decl ->
211
	exp loc (Abstraction { fun_name = f; fun_iface = a; fun_body = b })
212
    | (_,p,e1) = let_binding; "in"; e2 = expr LEVEL "top"->
213
        exp loc (Match (e1,[p,e2]))
214
    | e = expr; ":"; p = pat ->
215
	exp loc (Forget (e,p))
216 217 218
    ]

    
219 220 221 222 223 224
    | 
    [ e1 = expr; op = ["=" | "<=" | "<<" | ">>" | ">=" ]; e2 = expr -> 
	let op = match op with
	  | "<<" -> "<"
	  | ">>" -> ">"
	  | s -> s in
225
	exp loc (Op (op,[e1;e2]))
226 227
    ]

228
    | 
229
    [ e1 = expr; op = ["+" | "-" | "@" ]; e2 = expr -> 
230
	exp loc (Op (op,[e1;e2]))
231
    | e = expr; "\\"; l = [LIDENT | UIDENT | keyword ] -> 
232
	exp loc (RemoveField (e, label l)) 
233 234
    ]
    |
235
    [ e1 = expr; op = ["*"]; e2 = expr -> exp loc (Op (op,[e1;e2]))  
236 237 238 239 240
    | 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
241
	let re = Star(Alt(SeqCapture(id_dummy,Elem p), Elem any)) in
242 243
	let ct = mk loc (Regexp (re,any)) in
        let p = mk loc (XmlT (tag, multi_prod loc [att;ct])) in
244
	let b = (p,  Var id_dummy) in
245
	exp loc (Transform (e,[b]))
246
    ]
247
    |
248
    [ e = expr;  "."; l = [LIDENT | UIDENT | keyword ] -> 
249
	exp loc (Dot (e, label l)) 
250
    ]  
251
 
252
    |
253 254
    [ op = [ LIDENT "flatten"
	   | LIDENT "load_xml"
255
	   | LIDENT "load_file" | LIDENT "load_file_utf8"
256
	   | LIDENT "load_html"
257
	   | LIDENT "print_xml" | LIDENT "print_xml_utf8"
258
	   | LIDENT "print"
259
	   | LIDENT "int_of"
260
	   | LIDENT "string_of"
261
	   | LIDENT "atom_of"
262
	   | LIDENT "raise"
263
	   ]; 
264
      e = expr -> exp loc (Op (op,[e]))
265
    | op = [ LIDENT "dump_to_file" | LIDENT "dump_to_file_utf8" ];
266 267 268 269
      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))
270 271
    ]

272
    | "no_appl" 
273 274
    [ c = const -> exp loc (Cst c)
    | "("; l = LIST1 expr SEP ","; ")" -> exp loc (tuple l)
275 276
    | "[";  l = LIST0 seq_elem; e = OPT [ ";"; e = expr -> e ]; "]" ->
	let e = match e with Some e -> e | None -> cst_nil in
277 278 279
	let l = List.fold_right 
		  (fun x q ->
		     match x with
280
		       | `String (loc,i,j,s) -> exp loc (String (i,j,s,q))
281 282 283 284 285
		       | `Elems l -> tuple_queue l q
		       | `Explode x -> Op ("@",[x;q])
		  ) l e
	in
	exp loc l
286 287
    | "<"; t = [ "("; e = expr; ")" -> e
	       | a = [ LIDENT | UIDENT | keyword ] -> 
288
		   exp loc (Cst (Types.Atom (atom a))) ];
289
	a = expr_attrib_spec; ">"; c = expr ->
290 291
	exp loc (Xml (t, Pair (a,c)))
    | "{"; r = [ expr_record_spec | -> exp loc (RecordLitt LabelMap.empty) ]; "}" -> r
292
    | s = STRING2 ->
293 294 295
	let s = U.mk (get_string s) in
	exp loc (String (U.start_index s, U.end_index s, s, cst_nil))
(*	exp loc (tuple (char_list loc s @ [cst_nil])) *)
296
    | a = LIDENT -> exp loc (Var (ident a))
297 298 299
    ]

  ];
300 301

  seq_elem: [
302 303 304 305
    [ x = STRING1 -> 
	let s = U.mk (get_string x) in
	`String (loc, U.start_index s, U.end_index s, s)
	(* `Elems (char_list loc x) *)
306 307
    | e = expr LEVEL "no_appl" -> `Elems [e]
    | "!"; e = expr LEVEL "no_appl" -> `Explode e
308 309
    ]
  ];
310 311
	  
  let_binding: [
312 313 314 315
    [ "let"; is_fun_decl; OPT "fun"; (f,a,b) = fun_decl ->
	let f = match f with Some x -> x | None -> assert false in
	let p = mk loc (Capture f) in
	let abst = { fun_name = Some f; fun_iface = a; fun_body = b } in
316
        let e = exp loc (Abstraction abst) in
317
        (true,p,e)
318 319
    | "let"; p = pat; "="; e = expr -> (false,p,e)
    | "let"; p = pat; ":"; t = pat; "="; e = expr -> (false,p, Forget (e,t))
320 321 322
    ] 
  ];

323
 fun_decl_after_lparen: [
324 325
(* need an hack to do this, because both productions would
   match   [ OPT LIDENT; "("; pat ] .... *)
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
   [ p1 = pat LEVEL "no_arrow";
     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) -> (p1,p2)::a,b
	 | `Compact (targ1,args,tres,body) ->
	     let args = (p1,targ1) :: args in
	     let targ = multi_prod nopos (List.map snd args) in
	     let arg = multi_prod nopos (List.map fst args) in
	     let b = [arg, body] in
	     let a = [targ,tres] in
	     (a,b) ] ];


 fun_decl: [
   [ f = OPT [ x = LIDENT -> ident x]; "("; (a,b) = fun_decl_after_lparen ->
349
	    (f,a,b)
350
   ]
351 352
 ];

353
 arrow: [
354
    [ t1 = pat LEVEL "no_arrow"; "->"; t2 = pat -> (t1,t2)]
355 356 357
  ];

  branches: [
358
    [ OPT "|"; l = LIST1 branch SEP "|" -> l ]
359 360 361
  ];

  branch: [
362
    [ p = pat LEVEL "no_arrow"; "->"; e = expr -> (p,e) ]
363 364 365 366
  ];

	  
  regexp: [ 
367 368 369 370 371
    [ x = regexp; "|"; y = regexp -> 
	match (x,y) with
	  | Elem x, Elem y -> Elem (mk loc (Or (x,y)))
	  | _ -> Alt (x,y) 
    ]
372
  | [ x = regexp; y = regexp -> Seq (x,y) ]
373
  | [ a = LIDENT; "::"; x = regexp -> SeqCapture (ident a,x) ]
374 375 376 377
  | [ x = regexp; "*" -> Star x
    | x = regexp; "*?" -> WeakStar x
    | x = regexp; "+" -> Seq (x, Star x)
    | x = regexp; "+?" -> Seq (x, WeakStar x)
378
    | x = regexp; "?" ->  Alt (x, Epsilon)
379 380
    | x = regexp; "??" -> Alt (Epsilon, x) ]
  | [ "("; x = regexp; ")" -> x
381
    | "("; a = LIDENT; ":="; c = const; ")" -> 
382
	Elem (mk loc (Constant ((ident a,c))))
383
    | UIDENT "PCDATA" -> string_regexp
384
    | i = STRING1; "--"; j = STRING1 ->
385 386
	let i = Chars.mk_int (parse_char loc i)
	and j = Chars.mk_int (parse_char loc j) in
387
        Elem (mk loc (Internal (Types.char (Chars.char_class i j))))
388 389
    |  s = STRING1 ->
	let s = seq_of_string loc s in
390
	List.fold_right
391
	  (fun (loc,c) accu -> 
392
	     let c = Chars.mk_int c in
393 394 395
	     let c = Chars.atom c in
	     Seq (Elem (mk loc (Internal (Types.char c))), accu))
	  s
396
	  Epsilon 
397 398 399 400 401
    | e = pat LEVEL "simple" -> Elem e
    ]
  ];

  pat: [ 
402
      [ x = pat; LIDENT "where"; 
403 404 405
        b = LIST1 [ a = UIDENT; "="; y = pat -> (a,y)
		  | LIDENT -> error loc "Type/pattern identifiers must be capitalized"
		  ] SEP "and"
406 407
            -> mk loc (Recurs (x,b)) ]
    | RIGHTA [ x = pat; "->"; y = pat -> mk loc (Arrow (x,y)) ]
408
    | "no_arrow" [ x = pat; "|"; y = pat -> mk loc (Or (x,y)) ] 
409
    | "simple" [ x = pat; "&"; y = pat -> mk loc (And (x,y)) 
410
	       | x = pat; "\\"; y = pat -> mk loc (Diff (x,y)) ]
411
    | 
412 413
      [ "{"; r = record_spec; "}" -> mk loc (Record (true,r))
      | "{|"; r = record_spec; "|}" -> mk loc (Record (false,r))
414
      | LIDENT "_" -> mk loc (Internal Types.any)
415
      | a = LIDENT -> mk loc (Capture (ident a))
416
      | "("; a = LIDENT; ":="; c = const; ")" -> 
417
	  mk loc (Constant (ident a,c))
418 419 420 421 422 423 424 425 426 427 428
      | schema = UIDENT; "#"; typ = [ UIDENT | LIDENT | keyword ];
        k = OPT [ "as"; k = [ "element" | "type" | "attribute" ] -> k ] ->
          let kind =
            match k with
            | None -> `Any
            | Some "element" -> `Element
            | Some "type" -> `Type
            | Some "attribute" -> `Attribute
            | _ -> assert false
          in
          mk loc (SchemaVar (kind, schema, typ))
429 430
      | a = UIDENT -> mk loc (PatVar a)
      | i = INT ; "--"; j = INT -> 
431 432
          let i =  Intervals.mk i 
	  and j =  Intervals.mk j in
433 434
          mk loc (Internal (Types.interval (Intervals.bounded i j)))
      | i = INT -> 
435
          let i =  Intervals.mk i  in
436
          mk loc (Internal (Types.interval (Intervals.atom i)))
437
      | "*"; "--"; j = INT ->
438
	  let j =  Intervals.mk j in
439
          mk loc (Internal (Types.interval (Intervals.left j)))
440
      | i = INT; "--"; "*" ->
441
	  let i = Intervals.mk i in
442
          mk loc (Internal (Types.interval (Intervals.right i)))
443 444
      | i = char ->
          mk loc (Internal (Types.char (Chars.char_class i i)))
445
      | i = char ; "--"; j = char ->
446
          mk loc (Internal (Types.char (Chars.char_class i j)))
447 448 449 450
      | 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 
451
                 | -> mknoloc (Internal (Sequence.nil_type)) ]; 
452
             "]" -> mk loc (Regexp (r,q))
453 454
      | "<"; t =
        [ x = [ LIDENT | UIDENT | keyword ] ->
455
	    let a = if x = "_" then Atoms.any else Atoms.atom (atom x) in
456 457
	    mk loc (Internal (Types.atom a))
	| "("; t = pat; ")" -> t ];
458
	a = attrib_spec; ">"; c = pat ->
459
          mk loc (XmlT (t, multi_prod loc [a;c]))
460 461
      | s = STRING2 ->
	  let s = seq_of_string loc s in
462
	  let s = List.map 
463
		    (fun (loc,c) -> 
464 465 466
		       mk loc (Internal
				 (Types.char
				    (Chars.atom
467
				       (Chars.mk_int c))))) s in
468 469
	  let s = s @ [mk loc (Internal (Sequence.nil_type))] in
	  multi_prod loc s
470 471 472 473 474
      ]
    
  ];

  record_spec:
475
    [ [ r = LIST0 [ l = [LIDENT | UIDENT | keyword ]; "=";
476
                  o = [ "?" -> true | -> false]; 
477 478
                  x = pat -> 
		    let x = if o then mk loc (Optional x) else x in
479
		    (label l, x)
480
                ] SEP ";" ->
481
	  make_record loc r
482 483
      ] ];
  
484 485
  char:
    [ 
486
      [ c = STRING1 -> Chars.mk_int (parse_char loc c) ]
487 488 489
    ];
     

490 491
  const:
    [ 
492
      [ i = INT -> Types.Integer (Intervals.mk i)
493
      | "`"; a = [LIDENT | UIDENT | keyword ] -> Types.Atom (atom a)
494
      | c = char -> Types.Char c ]
495 496 497 498
    ];


  attrib_spec:
499
    [ [ r = record_spec -> mk loc (Record (true,r)) 
500 501 502 503
      | "("; t = pat; ")" -> t 
      | "{"; r = record_spec; "}" -> mk loc (Record (true,r))
      | "{|"; r = record_spec; "|}" -> mk loc (Record (false,r))
      ] ];
504 505 506

  expr_record_spec:
    [ [ r = LIST1
507
	      [ l = [LIDENT | UIDENT | keyword ]; "="; x = expr -> 
508
		  (label l,x) ] 
509
	      SEP ";" ->
510
	  exp loc (RecordLitt (make_record loc r))
511 512 513 514 515
      ] ];
  
  expr_attrib_spec:
    [ [ r = expr_record_spec -> r ]
    | [ e = expr LEVEL "no_appl" -> e 
516
      | -> exp loc (RecordLitt (LabelMap.empty)) 
517 518 519 520
      ] 
    ];
END

521
let pat = Grammar.Entry.parse pat
522 523
and expr = Grammar.Entry.parse expr
and prog = Grammar.Entry.parse prog
524 525
and top_phrases = Grammar.Entry.parse top_phrases

526 527 528 529 530 531 532 533 534 535 536 537
let sync () = 
  match !Wlexer.lexbuf with
    | None -> ()
    | Some lb ->
	let rec aux () =
	  match !Wlexer.last_tok with
	    | ("",";;") | ("EOI","") -> ()
	    | _ -> 
		Wlexer.last_tok := Wlexer.token Wlexer.latin1_engine lb; 
		aux ()
	in
	aux ()