parser.ml 16.5 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
exception Error of string
let error (i,j) s = Location.raise_loc i j (Error s)
12

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

15 16 17 18
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)
19

20
let parse_ident = U.mk_latin1
21

22
let id_dummy = ident (U.mk "$$$")
23

24
(*
25 26 27 28 29 30 31 32
let split_qname s =
  try
    let i = String.index s ':' in
    let ns = String.sub s 0 i in
    let s = String.sub s (i + 1) (String.length s - i - 1) in
    (parse_ident ns, parse_ident s)
  with Not_found -> 
    (U.mk "", parse_ident s)
33
*)
34

35 36
(* TODO: NS *)
let label s = LabelPool.mk (Ns.empty, parse_ident s)
37
let ident s = ident (parse_ident s)
38

39
let prog    = Grammar.Entry.create gram "prog"
40
let top_phrases   = Grammar.Entry.create gram "toplevel phrases"
41 42 43 44 45
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"
		
46 47
let exp pos e = LocatedExpr (loc_of_pos pos,e)

48 49 50 51 52
let rec multi_prod loc = function
  | [ x ] -> x
  | x :: l -> mk loc (Prod (x, multi_prod loc l))
  | [] -> assert false
      
53
let rec tuple = function
54
  | [ x ] -> x
55
  | x :: l -> Pair (x, tuple l)
56
  | [] -> assert false
57 58

let tuple_queue = 
59
  List.fold_right (fun x q -> Pair (x, q))
60 61


62
let char = mknoloc (Internal (Types.char Chars.any))
63
let string_regexp = Star (Elem char)
64
	       
65
let cst_nil =  Cst (Const_internal (Types.Atom Sequence.nil_atom))
66
		 
67
let seq_of_string s =
68 69
  let s = Encodings.Utf8.mk s in
  let rec aux i j =
70 71
    if Encodings.Utf8.equal_index i j then []
    else let (c,i) = Encodings.Utf8.next s i in c :: (aux i j)
72
  in
73
  aux (Encodings.Utf8.start_index s) (Encodings.Utf8.end_index 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
  match seq_of_string s with
    | [ c ] -> c
81
    | _ -> error loc "Character litteral must have length 1"
82

83 84
let include_stack = ref []

85 86 87 88
let protect_exn f g =
  try let x = f () in g (); x
  with e -> g (); raise e

89 90 91 92 93 94 95 96 97
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
     )

98
let dot_RE = Pcre.regexp "\\."
99

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

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

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

111 112
  uident: [ [ x = UIDENT -> parse_ident x ] ];

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

  debug_directive: [
    [ LIDENT "filter"; t = pat; p = pat -> `Filter(t,p)
167
    | LIDENT "accept"; p = pat -> `Accept p
168
    | LIDENT "compile"; t = pat; p = LIST1 pat -> `Compile (t,p)
169
    | LIDENT "sample"; t = pat -> `Sample t
170
    | LIDENT "subtype"; t1 = pat; t2 = pat -> `Subtype (t1,t2)
171
    ]
172
  ];
173

174 175 176 177 178
  keyword: [
    [ a = 
	[ "map" | "match" | "with" | "try" | "xtransform"
	| "if" | "then"	| "else"
	| "transform" | "fun" | "in"
179
	| "let" | "type" | "debug" | "include"
180
        | "and" | "validate" | "schema" | "namespace"
181 182 183 184 185
	]
	-> a
    ]
  ];

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

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

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

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

  ];
297

298
  tag: [ [ a = [ LIDENT | UIDENT | keyword ] -> 
299
	     Const_atom (parse_ident a) ] ];
300 301 302

  tag_type: [
    [ LIDENT "_" ->  mk loc (Internal (Types.atom Atoms.any))
303 304
    | a = [ LIDENT | UIDENT | keyword ] -> mk loc (AtomT (parse_ident a))
    | t = ANY_IN_NS -> mk loc (NsT (parse_ident t)) 
305 306 307
    ]
  ];

308
  seq_elem: [
309
    [ x = STRING1 -> 
310
	let s = U.mk x in
311
	`String (loc, U.start_index s, U.end_index s, s)
312 313
    | e = expr LEVEL "no_appl" -> `Elems [e]
    | "!"; e = expr LEVEL "no_appl" -> `Explode e
314 315
    ]
  ];
316 317 318 319 320 321 322
	
  namespace_binding: [
    [ "namespace"; 
	name = [ name = [ UIDENT | LIDENT | keyword ]; "=" ->
		   parse_ident name
	       | -> U.mk "" ];
	uri = STRING2 ->
323
	  let ns = Ns.mk (parse_ident uri) in
324 325 326 327 328
	  (name,ns)
    ]
  ];

  
329
  let_binding: [
330 331 332 333
    [ "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
334
        let e = exp loc (Abstraction abst) in
335
        (true,p,e)
336 337
    | "let"; p = pat; "="; e = expr -> (false,p,e)
    | "let"; p = pat; ":"; t = pat; "="; e = expr -> (false,p, Forget (e,t))
338 339 340
    ] 
  ];

341
 fun_decl_after_lparen: [
342 343
(* need an hack to do this, because both productions would
   match   [ OPT LIDENT; "("; pat ] .... *)
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
   [ 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 ->
367
	    (f,a,b)
368
   ]
369 370
 ];

371
 arrow: [
372
    [ t1 = pat LEVEL "no_arrow"; "->"; t2 = pat -> (t1,t2)]
373 374 375
  ];

  branches: [
376
    [ OPT "|"; l = LIST1 branch SEP "|" -> l ]
377 378 379
  ];

  branch: [
380
    [ p = pat LEVEL "no_arrow"; "->"; e = expr -> (p,e) ]
381 382 383 384
  ];

	  
  regexp: [ 
385 386 387 388 389
    [ x = regexp; "|"; y = regexp -> 
	match (x,y) with
	  | Elem x, Elem y -> Elem (mk loc (Or (x,y)))
	  | _ -> Alt (x,y) 
    ]
390
  | [ x = regexp; y = regexp -> Seq (x,y) ]
391
  | [ a = LIDENT; "::"; x = regexp -> SeqCapture (ident a,x) ]
392 393 394 395
  | [ x = regexp; "*" -> Star x
    | x = regexp; "*?" -> WeakStar x
    | x = regexp; "+" -> Seq (x, Star x)
    | x = regexp; "+?" -> Seq (x, WeakStar x)
396
    | x = regexp; "?" ->  Alt (x, Epsilon)
397 398
    | x = regexp; "??" -> Alt (Epsilon, x) ]
  | [ "("; x = regexp; ")" -> x
399
    | "("; a = LIDENT; ":="; c = const; ")" -> 
400
	Elem (mk loc (Constant ((ident a,c))))
401
    | UIDENT "PCDATA" -> string_regexp
402
    | i = STRING1; "--"; j = STRING1 ->
403 404
	let i = Chars.mk_int (parse_char loc i)
	and j = Chars.mk_int (parse_char loc j) in
405
        Elem (mk loc (Internal (Types.char (Chars.char_class i j))))
406
    |  s = STRING1 ->
407
	List.fold_right
408
	  (fun c accu -> 
409
	     let c = Chars.mk_int c in
410
	     let c = Chars.atom c in
411 412
	     Seq (Elem (mknoloc (Internal (Types.char c))), accu))
	  (seq_of_string s)
413
	  Epsilon 
414 415 416 417 418
    | e = pat LEVEL "simple" -> Elem e
    ]
  ];

  pat: [ 
419
      [ x = pat; LIDENT "where"; 
420
        b = LIST1 [ a = uident; "="; y = pat -> (a,y)
421 422
		  | LIDENT -> error loc "Type/pattern identifiers must be capitalized"
		  ] SEP "and"
423 424
            -> mk loc (Recurs (x,b)) ]
    | RIGHTA [ x = pat; "->"; y = pat -> mk loc (Arrow (x,y)) ]
425
    | "no_arrow" [ x = pat; "|"; y = pat -> mk loc (Or (x,y)) ] 
426
    | "simple" [ x = pat; "&"; y = pat -> mk loc (And (x,y)) 
427
	       | x = pat; "\\"; y = pat -> mk loc (Diff (x,y)) ]
428
    | 
429 430
      [ "{"; r = record_spec; "}" -> mk loc (Record (true,r))
      | "{|"; r = record_spec; "|}" -> mk loc (Record (false,r))
431
      | LIDENT "_" -> mk loc (Internal Types.any)
432
      | a = LIDENT -> mk loc (Capture (ident a))
433
      | "("; a = LIDENT; ":="; c = const; ")" -> 
434
	  mk loc (Constant (ident a,c))
435 436 437 438 439 440 441 442 443 444 445
      | 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))
446
      | a = uident -> mk loc (PatVar a)
447
      | i = INT ; "--"; j = INT -> 
448 449
          let i =  Intervals.mk i 
	  and j =  Intervals.mk j in
450 451
          mk loc (Internal (Types.interval (Intervals.bounded i j)))
      | i = INT -> 
452
          let i =  Intervals.mk i  in
453
          mk loc (Internal (Types.interval (Intervals.atom i)))
454
      | "*"; "--"; j = INT ->
455
	  let j =  Intervals.mk j in
456
          mk loc (Internal (Types.interval (Intervals.left j)))
457
      | i = INT; "--"; "*" ->
458
	  let i = Intervals.mk i in
459
          mk loc (Internal (Types.interval (Intervals.right i)))
460 461
      | i = char ->
          mk loc (Internal (Types.char (Chars.char_class i i)))
462
      | i = char ; "--"; j = char ->
463
          mk loc (Internal (Types.char (Chars.char_class i j)))
464 465 466
      | "`"; c = tag_type -> c
      | c = const -> 
	  (match c with
467 468
	     | Const_atom l -> mk loc (AtomT l)
	     | Const_internal c -> mk loc (Internal (Types.constant c))
469
	  )
470 471 472
      | "("; l = LIST1 pat SEP ","; ")" -> multi_prod loc l
      | "["; r = [ r = regexp -> r | -> Epsilon ];
             q = [ ";"; q = pat -> q 
473
                 | -> mknoloc (Internal (Sequence.nil_type)) ]; 
474
             "]" -> mk loc (Regexp (r,q))
475
      | "<"; t =
476 477
            [ x = tag_type -> x
            | "("; t = pat; ")" -> t ];
478
	a = attrib_spec; ">"; c = pat ->
479
(*	  let t = mk loc (Prod (mk loc (Internal Sequence.nil_type), t)) in *)
480
          mk loc (XmlT (t, multi_prod loc [a;c]))
481
      | s = STRING2 ->
482 483 484 485 486 487 488 489 490
	  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
491
	  multi_prod loc s
492 493 494 495 496
      ]
    
  ];

  record_spec:
497
    [ [ r = LIST0 [ l = [LIDENT | UIDENT | keyword ]; "=";
498
                  o = [ "?" -> true | -> false]; 
499 500
                  x = pat -> 
		    let x = if o then mk loc (Optional x) else x in
501
		    (label l, x)
502
                ] SEP ";" ->
503
	  make_record loc r
504 505
      ] ];
  
506 507
  char:
    [ 
508
      [ c = STRING1 -> Chars.mk_int (parse_char loc c) ]
509 510 511
    ];
     

512 513
  const:
    [ 
514 515 516
      [ i = INT -> Const_internal (Types.Integer (Intervals.mk i))
      | "`"; a = tag -> a
      | c = char -> Const_internal (Types.Char c) ]
517 518 519 520
    ];


  attrib_spec:
521
    [ [ r = record_spec -> mk loc (Record (true,r)) 
522 523 524 525
      | "("; t = pat; ")" -> t 
      | "{"; r = record_spec; "}" -> mk loc (Record (true,r))
      | "{|"; r = record_spec; "|}" -> mk loc (Record (false,r))
      ] ];
526 527 528

  expr_record_spec:
    [ [ r = LIST1
529
	      [ l = [LIDENT | UIDENT | keyword ]; "="; x = expr -> 
530
		  (label l,x) ] 
531
	      SEP ";" ->
532
	  exp loc (RecordLitt (make_record loc r))
533 534 535 536 537
      ] ];
  
  expr_attrib_spec:
    [ [ r = expr_record_spec -> r ]
    | [ e = expr LEVEL "no_appl" -> e 
538
      | -> exp loc (RecordLitt (LabelMap.empty)) 
539 540 541 542
      ] 
    ];
END

543
let pat = Grammar.Entry.parse pat
544 545
and expr = Grammar.Entry.parse expr
and prog = Grammar.Entry.parse prog
546 547
and top_phrases = Grammar.Entry.parse top_phrases

548 549 550 551 552 553 554 555 556 557 558 559
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 ()