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
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
(* TODO: NS *)
25
let label = parse_ident
26
let ident s = ident (parse_ident s)
27

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

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

let tuple_queue = 
48
  List.fold_right (fun x q -> Pair (x, q))
49
50


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

64

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

70
71
let include_stack = ref []

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

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

85
let dot_RE = Pcre.regexp "\\."
86

87
EXTEND
88
89
90
  GLOBAL: top_phrases prog expr pat regexp const;

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

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

98
99
  uident: [ [ x = UIDENT -> parse_ident x ] ];

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
    | "type"; x = uident; "="; t = pat -> [ mk loc (TypeDecl (x,t)) ]
107
    | "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
114
115
116
117
    | (name,ns) = namespace_binding ->
	[ 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)) ]
118
    | "debug"; d = debug_directive -> [ mk loc (Debug d) ]
119
120
    | DIRECTIVE "#quit" -> [ mk loc (Directive `Quit) ]
    | DIRECTIVE "#env" -> [ mk loc (Directive `Env) ]
121
    | "include"; s = STRING2 ->
122
123
124
125
	let s = 
	  if Filename.is_relative s 
	  then Filename.concat (Location.current_dir ()) s
	  else s in
126
127
	protect_op "File inclusion";
	(* avoid looping; should issue an error ? *)
128
129
	(* it is possible to have looping with x/../x/../x/.. ....
	   Need to canonicalize filename *)
130
131
132
133
	if List.mem s !include_stack then [] 
	else (
	  include_stack := s :: !include_stack;
	  Location.push_source (`File s);
134
135
136
	  protect_exn
	    (fun () ->
	       let chan = open_in s in
137
138
139
140
141
	       protect_exn
		 (fun () ->
		    let input = Stream.of_channel chan in
		    Grammar.Entry.parse prog input)
		 (fun () -> close_in chan))
142
143
144
	    (fun () ->
	       Location.pop_source ();
	       include_stack := List.tl !include_stack)
145
	)
146
    ] | 
147
    [ e = expr -> [ mk loc (EvalStatement e) ]
148
149
150
151
152
    ]
  ];

  debug_directive: [
    [ LIDENT "filter"; t = pat; p = pat -> `Filter(t,p)
153
    | LIDENT "accept"; p = pat -> `Accept p
154
    | LIDENT "compile"; t = pat; p = LIST1 pat -> `Compile (t,p)
155
    | LIDENT "sample"; t = pat -> `Sample t
156
    | LIDENT "subtype"; t1 = pat; t2 = pat -> `Subtype (t1,t2)
157
    ]
158
  ];
159

160
161
162
163
164
  keyword: [
    [ a = 
	[ "map" | "match" | "with" | "try" | "xtransform"
	| "if" | "then"	| "else"
	| "transform" | "fun" | "in"
165
	| "let" | "type" | "debug" | "include"
166
        | "and" | "validate" | "schema" | "namespace"
167
168
169
170
171
	]
	-> a
    ]
  ];

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

    
202
203
204
205
206
207
    | 
    [ e1 = expr; op = ["=" | "<=" | "<<" | ">>" | ">=" ]; e2 = expr -> 
	let op = match op with
	  | "<<" -> "<"
	  | ">>" -> ">"
	  | s -> s in
208
	exp loc (Op (op,[e1;e2]))
209
210
    ]

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

255
    | "no_appl" 
256
257
    [ c = const -> exp loc (Cst c)
    | "("; l = LIST1 expr SEP ","; ")" -> exp loc (tuple l)
258
259
    | "[";  l = LIST0 seq_elem; e = OPT [ ";"; e = expr -> e ]; "]" ->
	let e = match e with Some e -> e | None -> cst_nil in
260
261
262
	let l = List.fold_right 
		  (fun x q ->
		     match x with
263
		       | `String (loc,i,j,s) -> exp loc (String (i,j,s,q))
264
265
266
267
268
		       | `Elems l -> tuple_queue l q
		       | `Explode x -> Op ("@",[x;q])
		  ) l e
	in
	exp loc l
269
    | "<"; t = [ "("; e = expr; ")" -> e
270
271
	       | a = tag -> exp loc (Cst a)
	       ];
272
	a = expr_attrib_spec; ">"; c = expr ->
273
274
(*	  let t = Pair (cst_nil, t) in *)
	  exp loc (Xml (t, Pair (a,c)))
275
    | "{"; r = [ expr_record_spec | -> exp loc (RecordLitt []) ]; "}" -> r
276
    | s = STRING2 ->
277
	let s = U.mk s in
278
	exp loc (String (U.start_index s, U.end_index s, s, cst_nil))
279
    | a = LIDENT -> exp loc (Var (ident a))
280
281
282
    ]

  ];
283

284
  tag: [ [ a = [ LIDENT | UIDENT | keyword ] -> 
285
	     Const_atom (parse_ident a) ] ];
286
287
288

  tag_type: [
    [ LIDENT "_" ->  mk loc (Internal (Types.atom Atoms.any))
289
290
    | a = [ LIDENT | UIDENT | keyword ] -> mk loc (AtomT (parse_ident a))
    | t = ANY_IN_NS -> mk loc (NsT (parse_ident t)) 
291
292
293
    ]
  ];

294
  seq_elem: [
295
    [ x = STRING1 -> 
296
	let s = U.mk x in
297
	`String (loc, U.start_index s, U.end_index s, s)
298
299
    | e = expr LEVEL "no_appl" -> `Elems [e]
    | "!"; e = expr LEVEL "no_appl" -> `Explode e
300
301
    ]
  ];
302
303
304
305
306
307
308
	
  namespace_binding: [
    [ "namespace"; 
	name = [ name = [ UIDENT | LIDENT | keyword ]; "=" ->
		   parse_ident name
	       | -> U.mk "" ];
	uri = STRING2 ->
309
	  let ns = Ns.mk (parse_ident uri) in
310
311
312
313
314
	  (name,ns)
    ]
  ];

  
315
  let_binding: [
316
317
318
319
    [ "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
320
        let e = exp loc (Abstraction abst) in
321
        (true,p,e)
322
323
    | "let"; p = pat; "="; e = expr -> (false,p,e)
    | "let"; p = pat; ":"; t = pat; "="; e = expr -> (false,p, Forget (e,t))
324
325
326
    ] 
  ];

327
 fun_decl_after_lparen: [
328
329
(* need an hack to do this, because both productions would
   match   [ OPT LIDENT; "("; pat ] .... *)
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
   [ 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 ->
353
	    (f,a,b)
354
   ]
355
356
 ];

357
 arrow: [
358
    [ t1 = pat LEVEL "no_arrow"; "->"; t2 = pat -> (t1,t2)]
359
360
361
  ];

  branches: [
362
    [ OPT "|"; l = LIST1 branch SEP "|" -> l ]
363
364
365
  ];

  branch: [
366
    [ p = pat LEVEL "no_arrow"; "->"; e = expr -> (p,e) ]
367
368
369
370
  ];

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

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

  record_spec:
483
    [ [ r = LIST0 [ l = [LIDENT | UIDENT | keyword ]; "=";
484
                  o = [ "?" -> true | -> false]; 
485
486
                  x = pat -> 
		    let x = if o then mk loc (Optional x) else x in
487
		    (label l, x)
488
                ] SEP ";" ->
489
	  r
490
491
      ] ];
  
492
493
  char:
    [ 
494
      [ c = STRING1 -> Chars.mk_int (parse_char loc c) ]
495
496
497
    ];
     

498
499
  const:
    [ 
500
501
502
      [ i = INT -> Const_internal (Types.Integer (Intervals.mk i))
      | "`"; a = tag -> a
      | c = char -> Const_internal (Types.Char c) ]
503
504
505
506
    ];


  attrib_spec:
507
    [ [ r = record_spec -> mk loc (Record (true,r)) 
508
509
510
511
      | "("; t = pat; ")" -> t 
      | "{"; r = record_spec; "}" -> mk loc (Record (true,r))
      | "{|"; r = record_spec; "|}" -> mk loc (Record (false,r))
      ] ];
512
513
514

  expr_record_spec:
    [ [ r = LIST1
515
	      [ l = [LIDENT | UIDENT | keyword ]; "="; x = expr -> 
516
		  (label l,x) ] 
517
	      SEP ";" ->
518
	  exp loc (RecordLitt r)
519
520
521
522
523
      ] ];
  
  expr_attrib_spec:
    [ [ r = expr_record_spec -> r ]
    | [ e = expr LEVEL "no_appl" -> e 
524
      | -> exp loc (RecordLitt []) 
525
526
527
528
      ] 
    ];
END

529
let pat = Grammar.Entry.parse pat
530
531
and expr = Grammar.Entry.parse expr
and prog = Grammar.Entry.parse prog
532
533
and top_phrases = Grammar.Entry.parse top_phrases

534
535
536
537
538
539
540
541
542
543
544
545
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 ()