parser.ml 16.6 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
let label s = LabelPool.mk (parse_ident s)
34
let ident s = ident (parse_ident s)
35

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

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

let tuple_queue = 
56
  List.fold_right (fun x q -> Pair (x, q))
57
58


59
let char = mknoloc (Internal (Types.char Chars.any))
60
let string_regexp = Star (Elem char)
61
	       
62
let cst_nil =  Cst (Const_internal (Types.Atom Sequence.nil_atom))
63
		 
64
let seq_of_string s =
65
66
  let s = Encodings.Utf8.mk s in
  let rec aux i j =
67
68
    if Encodings.Utf8.equal_index i j then []
    else let (c,i) = Encodings.Utf8.next s i in c :: (aux i j)
69
  in
70
  aux (Encodings.Utf8.start_index s) (Encodings.Utf8.end_index s)
71

72
73
74
let make_record loc r =
  LabelMap.from_list (fun _ _ -> error loc "Duplicated record field") r

75
let parse_char loc s =
76
77
  match seq_of_string s with
    | [ c ] -> c
78
    | _ -> error loc "Character litteral must have length 1"
79

80
81
let include_stack = ref []

82
83
84
85
let protect_exn f g =
  try let x = f () in g (); x
  with e -> g (); raise e

86
87
88
89
90
91
92
93
94
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
     )

95
let dot_RE = Pcre.regexp "\\."
96

97
EXTEND
98
99
100
  GLOBAL: top_phrases prog expr pat regexp const;

  top_phrases: [
101
    [ l = LIST0 phrase; ";;" -> List.flatten l  ]
102
  ];
103
104

  prog: [
105
    [ l = LIST0 [ p = phrase ; OPT ";;" -> p ]; EOI -> List.flatten l ]
106
107
  ];

108
109
  uident: [ [ x = UIDENT -> parse_ident x ] ];

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

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

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

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

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

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

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

  ];
294

295
296
297
298
299
300
301
302
303
304
305
306
307
  tag: [ [ a = [ LIDENT | UIDENT | keyword ] -> 
	     let (ns,l) = split_qname a in Const_atom (ns,l) ] ];

  tag_type: [
    [ LIDENT "_" ->  mk loc (Internal (Types.atom Atoms.any))
    | a = [ LIDENT | UIDENT | keyword ] -> 
	let (ns,l) = split_qname a in
	mk loc (AtomT (ns, Some l))
    | t = ANY_IN_NS -> 
	mk loc (AtomT (parse_ident t, None)) 
    ]
  ];

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
323
324
325
326
327
328
	
  namespace_binding: [
    [ "namespace"; 
	name = [ name = [ UIDENT | LIDENT | keyword ]; "=" ->
		   parse_ident name
	       | -> U.mk "" ];
	uri = STRING2 ->
	  let ns = Atoms.Ns.mk (parse_ident uri) in
	  (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
467
468
469
470
      | "`"; c = tag_type -> c
      | c = const -> 
	  (match c with
	     | Const_atom (ns,l) -> mk loc (AtomT (ns,Some l))
	     | Const_internal c ->
		 mk loc (Internal (Types.constant c))
	  )
471
472
473
      | "("; l = LIST1 pat SEP ","; ")" -> multi_prod loc l
      | "["; r = [ r = regexp -> r | -> Epsilon ];
             q = [ ";"; q = pat -> q 
474
                 | -> mknoloc (Internal (Sequence.nil_type)) ]; 
475
             "]" -> mk loc (Regexp (r,q))
476
      | "<"; t =
477
478
            [ x = tag_type -> x
            | "("; t = pat; ")" -> t ];
479
	a = attrib_spec; ">"; c = pat ->
480
(*	  let t = mk loc (Prod (mk loc (Internal Sequence.nil_type), t)) in *)
481
          mk loc (XmlT (t, multi_prod loc [a;c]))
482
      | s = STRING2 ->
483
484
485
486
487
488
489
490
491
	  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
492
	  multi_prod loc s
493
494
495
496
497
      ]
    
  ];

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

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


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

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

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

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