parser.ml 15.3 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 s =
54 55
  let s = Encodings.Utf8.mk s in
  let rec aux i j =
56 57
    if Encodings.Utf8.equal_index i j then []
    else let (c,i) = Encodings.Utf8.next s i in c :: (aux i j)
58
  in
59
  aux (Encodings.Utf8.start_index s) (Encodings.Utf8.end_index s)
60

61
exception Error of string
62
let error (i,j) s = Location.raise_loc i j (Error s)
63

64 65 66
let make_record loc r =
  LabelMap.from_list (fun _ _ -> error loc "Duplicated record field") r

67
let parse_char loc s =
68 69
  match seq_of_string s with
    | [ c ] -> c
70
    | _ -> error loc "Character litteral must have length 1"
71

72 73
let include_stack = ref []

74 75 76 77
let protect_exn f g =
  try let x = f () in g (); x
  with e -> g (); raise e

78 79 80 81 82 83 84 85 86
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
     )

87
let dot_RE = Pcre.regexp "\\."
88

89
EXTEND
90 91 92
  GLOBAL: top_phrases prog expr pat regexp const;

  top_phrases: [
93
    [ l = LIST0 phrase; ";;" -> List.flatten l  ]
94
  ];
95 96

  prog: [
97
    [ l = LIST0 [ p = phrase ; OPT ";;" -> p ]; EOI -> List.flatten l ]
98 99 100
  ];

  phrase: [
101 102 103 104
    [ (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"->
105
        [ mk loc (EvalStatement (exp loc (Match (e1,[p,e2])))) ]
106 107
    | "type"; x = UIDENT; "="; t = pat -> [ mk loc (TypeDecl (x,t)) ]
    | "type"; x = LIDENT -> error loc "Type identifiers must be capitalized"
108
    | "schema"; name = UIDENT; "="; uri = STRING2 ->
109
	protect_op "schema";
110
        let schema_doc = Schema_xml.pxp_tree_of uri in
111 112
        let schema = Schema_parser.parse_schema schema_doc in
        [ mk loc (SchemaDecl (name, schema))]
113
    | "debug"; d = debug_directive -> [ mk loc (Debug d) ]
114 115
    | DIRECTIVE "#quit" -> [ mk loc (Directive `Quit) ]
    | DIRECTIVE "#env" -> [ mk loc (Directive `Env) ]
116
    | "include"; s = STRING2 ->
117 118 119 120
	let s = 
	  if Filename.is_relative s 
	  then Filename.concat (Location.current_dir ()) s
	  else s in
121 122
	protect_op "File inclusion";
	(* avoid looping; should issue an error ? *)
123 124
	(* it is possible to have looping with x/../x/../x/.. ....
	   Need to canonicalize filename *)
125 126 127 128
	if List.mem s !include_stack then [] 
	else (
	  include_stack := s :: !include_stack;
	  Location.push_source (`File s);
129 130 131
	  protect_exn
	    (fun () ->
	       let chan = open_in s in
132 133 134 135 136
	       protect_exn
		 (fun () ->
		    let input = Stream.of_channel chan in
		    Grammar.Entry.parse prog input)
		 (fun () -> close_in chan))
137 138 139
	    (fun () ->
	       Location.pop_source ();
	       include_stack := List.tl !include_stack)
140
	)
141
    ] | 
142
    [ e = expr -> [ mk loc (EvalStatement e) ]
143 144 145 146 147
    ]
  ];

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

155 156 157 158 159
  keyword: [
    [ a = 
	[ "map" | "match" | "with" | "try" | "xtransform"
	| "if" | "then"	| "else"
	| "transform" | "fun" | "in"
160
	| "let" | "type" | "debug" | "include"
161
        | "and" | "validate" | "schema"
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 184 185
    | "validate"; e = SELF; "with"; schema = UIDENT; "#";
      typ = [ UIDENT | LIDENT | keyword ] ->
        exp loc (Validate (e, schema, typ))
186
    | "fun"; (f,a,b) = fun_decl ->
187
	exp loc (Abstraction { fun_name = f; fun_iface = a; fun_body = b })
188
    | (_,p,e1) = let_binding; "in"; e2 = expr LEVEL "top"->
189
        exp loc (Match (e1,[p,e2]))
190
    | e = expr; ":"; p = pat ->
191
	exp loc (Forget (e,p))
192 193 194
    ]

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

204
    | 
205
    [ e1 = expr; op = ["+" | "-" | "@" ]; e2 = expr -> 
206
	exp loc (Op (op,[e1;e2]))
207
    | e = expr; "\\"; l = [LIDENT | UIDENT | keyword ] -> 
208
	exp loc (RemoveField (e, label l)) 
209 210
    ]
    |
211
    [ e1 = expr; op = ["*"]; e2 = expr -> exp loc (Op (op,[e1;e2]))  
212 213 214 215 216
    | 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
217
	let re = Star(Alt(SeqCapture(id_dummy,Elem p), Elem any)) in
218 219
	let ct = mk loc (Regexp (re,any)) in
        let p = mk loc (XmlT (tag, multi_prod loc [att;ct])) in
220
	let b = (p,  Var id_dummy) in
221
	exp loc (Transform (e,[b]))
222
    ]
223
    |
224
    [ e = expr;  "."; l = [LIDENT | UIDENT | keyword ] -> 
225
	exp loc (Dot (e, label l)) 
226
    ]  
227
 
228
    |
229 230
    [ op = [ LIDENT "flatten"
	   | LIDENT "load_xml"
231
	   | LIDENT "load_file" | LIDENT "load_file_utf8"
232
	   | LIDENT "load_html"
233
	   | LIDENT "print_xml" | LIDENT "print_xml_utf8"
234
	   | LIDENT "print"
235
	   | LIDENT "int_of"
236
	   | LIDENT "string_of"
237
	   | LIDENT "atom_of"
238
	   | LIDENT "raise"
239
	   ]; 
240
      e = expr -> exp loc (Op (op,[e]))
241
    | op = [ LIDENT "dump_to_file" | LIDENT "dump_to_file_utf8" ];
242 243 244 245
      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))
246 247
    ]

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

  ];
275 276

  seq_elem: [
277
    [ x = STRING1 -> 
278
	let s = U.mk x in
279
	`String (loc, U.start_index s, U.end_index s, s)
280 281
    | e = expr LEVEL "no_appl" -> `Elems [e]
    | "!"; e = expr LEVEL "no_appl" -> `Explode e
282 283
    ]
  ];
284 285
	  
  let_binding: [
286 287 288 289
    [ "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
290
        let e = exp loc (Abstraction abst) in
291
        (true,p,e)
292 293
    | "let"; p = pat; "="; e = expr -> (false,p,e)
    | "let"; p = pat; ":"; t = pat; "="; e = expr -> (false,p, Forget (e,t))
294 295 296
    ] 
  ];

297
 fun_decl_after_lparen: [
298 299
(* need an hack to do this, because both productions would
   match   [ OPT LIDENT; "("; pat ] .... *)
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
   [ 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 ->
323
	    (f,a,b)
324
   ]
325 326
 ];

327
 arrow: [
328
    [ t1 = pat LEVEL "no_arrow"; "->"; t2 = pat -> (t1,t2)]
329 330 331
  ];

  branches: [
332
    [ OPT "|"; l = LIST1 branch SEP "|" -> l ]
333 334 335
  ];

  branch: [
336
    [ p = pat LEVEL "no_arrow"; "->"; e = expr -> (p,e) ]
337 338 339 340
  ];

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

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

  record_spec:
449
    [ [ r = LIST0 [ l = [LIDENT | UIDENT | keyword ]; "=";
450
                  o = [ "?" -> true | -> false]; 
451 452
                  x = pat -> 
		    let x = if o then mk loc (Optional x) else x in
453
		    (label l, x)
454
                ] SEP ";" ->
455
	  make_record loc r
456 457
      ] ];
  
458 459
  char:
    [ 
460
      [ c = STRING1 -> Chars.mk_int (parse_char loc c) ]
461 462 463
    ];
     

464 465
  const:
    [ 
466
      [ i = INT -> Types.Integer (Intervals.mk i)
467
      | "`"; a = [LIDENT | UIDENT | keyword ] -> Types.Atom (atom a)
468
      | c = char -> Types.Char c ]
469 470 471 472
    ];


  attrib_spec:
473
    [ [ r = record_spec -> mk loc (Record (true,r)) 
474 475 476 477
      | "("; t = pat; ")" -> t 
      | "{"; r = record_spec; "}" -> mk loc (Record (true,r))
      | "{|"; r = record_spec; "|}" -> mk loc (Record (false,r))
      ] ];
478 479 480

  expr_record_spec:
    [ [ r = LIST1
481
	      [ l = [LIDENT | UIDENT | keyword ]; "="; x = expr -> 
482
		  (label l,x) ] 
483
	      SEP ";" ->
484
	  exp loc (RecordLitt (make_record loc r))
485 486 487 488 489
      ] ];
  
  expr_attrib_spec:
    [ [ r = expr_record_spec -> r ]
    | [ e = expr LEVEL "no_appl" -> e 
490
      | -> exp loc (RecordLitt (LabelMap.empty)) 
491 492 493 494
      ] 
    ];
END

495
let pat = Grammar.Entry.parse pat
496 497
and expr = Grammar.Entry.parse expr
and prog = Grammar.Entry.parse prog
498 499
and top_phrases = Grammar.Entry.parse top_phrases

500 501 502 503 504 505 506 507 508 509 510 511
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 ()