parser.ml 12.7 KB
Newer Older
1
2
open Location
open Ast
3
open Ident
4

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

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


12
13
14
15
16
17
18
19
20
21
22
23
24
let prog    = Grammar.Entry.create gram "prog"
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"
		
let rec multi_prod loc = function
  | [ x ] -> x
  | x :: l -> mk loc (Prod (x, multi_prod loc l))
  | [] -> assert false
      
let rec tuple loc = function
  | [ x ] -> x
25
  | x :: l -> mk loc (Pair (x, tuple loc l))
26
  | [] -> assert false
27
28

let tuple_queue = 
29
  List.fold_right (fun x q -> mk_loc x.loc (Pair (x, q)))
30

31
32


33
let char = mknoloc (Internal (Types.char Chars.any))
34
let string_regexp = Star (Elem char)
35
	       
36
let cst_nil =  mknoloc (Cst (Types.Atom Sequence.nil_atom))
37
		 
38
39
40
41
42
43
let seq_of_string pos s =
  let (pos,_) = pos in
  let rec aux accu i = 
    if (i = 0) 
    then accu 
    else aux (((pos+i,pos+i+1),s.[i-1])::accu) (i-1) in
44
45
  aux [] (String.length s)

46
exception Error of string
47
let error (i,j) s = Location.raise_loc i j (Error s)
48

49
50
51
let make_record loc r =
  LabelMap.from_list (fun _ _ -> error loc "Duplicated record field") r

52
53
54
55
56
let parse_char loc s =
  (* TODO: Unicode *)
  if String.length s <> 1 then
    error loc "Character litteral must have length 1";
  s.[0]
57

58
let char_list pos s = 
59
  let s = seq_of_string pos s in
60
  List.map (fun (loc,c) -> mk loc (Cst (Types.Char (Chars.mk_char c)))) s
61
62


63
64
let include_stack = ref []

65
EXTEND
66
67
68
  GLOBAL: prog expr pat regexp const;

  prog: [
69
    [ l = LIST0 [ p = phrase; ";;" -> p ]; EOI -> List.flatten l ]
70
71
72
  ];

  phrase: [
73
    [ (p,e) = let_binding -> [ mk loc (LetDecl (p,e)) ]
74
    | (p,e1) = let_binding; "in"; e2 = expr LEVEL "top"->
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
        [ mk loc (EvalStatement (mk loc (Match (e1,[p,e2])))) ]
    | LIDENT "type"; x = UIDENT; "="; t = pat -> [ mk loc (TypeDecl (x,t)) ]
    | LIDENT "debug"; d = debug_directive -> [ mk loc (Debug d) ]
    | LIDENT "include"; s = STRING2 ->
	protect_op "File inclusion";
	(* avoid looping; should issue an error ? *)
	if List.mem s !include_stack then [] 
	else (
	  include_stack := s :: !include_stack;
	  let chan = open_in s in
	  Location.push_source (`File s);
	  let input = Stream.of_channel chan in
	  let l = Grammar.Entry.parse prog input in
	  close_in chan;
	  Location.pop_source ();
	  include_stack := List.tl !include_stack;
	  l
	)
93
    ] | 
94
    [ e = expr -> [ mk loc (EvalStatement e) ]
95
96
97
98
99
    ]
  ];

  debug_directive: [
    [ LIDENT "filter"; t = pat; p = pat -> `Filter(t,p)
100
    | LIDENT "accept"; p = pat -> `Accept p
101
    | LIDENT "compile"; t = pat; p = LIST1 pat -> `Compile (t,p)
102
    | LIDENT "normal_record"; t = pat -> `Normal_record t
103
    | LIDENT "compile2"; t = pat; p = LIST1 pat -> `Compile2 (t,p)
104
    | LIDENT "subtype"; t1 = pat; t2 = pat -> `Subtype (t1,t2)
105
    ]
106
  ];
107
108
109
110

  expr: [
    "top" RIGHTA
    [ "match"; e = SELF; "with"; b = branches -> mk loc (Match (e,b))
111
112
    | "try"; e = SELF; "with"; b = branches -> 
	let default = 
113
114
	  (mknoloc (Capture (ident "x")),
	   mknoloc (Op ("raise",[mknoloc (Var (ident "x"))]))) in
115
	mk loc (Try (e,b@[default]))
116
    | "map"; e = SELF; "with"; b = branches -> mk loc (Map (e,b))
117
118
119
120
    | "if"; e = SELF; "then"; e1 = SELF; "else"; e2 = SELF ->
	let p1 = mk loc (Internal (Builtin.true_type))
	and p2 = mk loc (Internal (Builtin.false_type)) in
	mk loc (Match (e, [p1,e1; p2,e2]))
121
    | "transform"; e = SELF; "with"; b = branches -> 
122
	let default = mknoloc (Capture (ident "x")), cst_nil in
123
	mk loc (Op ("flatten", [mk loc (Map (e,b@[default]))]))
124
    | "fun"; (f,a,b) = fun_decl ->
125
126
127
	mk loc (Abstraction { fun_name = f; fun_iface = a; fun_body = b })
    | (p,e1) = let_binding; "in"; e2 = expr LEVEL "top"->
        mk loc (Match (e1,[p,e2]))
128
129
    | e = expr; ":"; p = pat ->
	mk loc (Forget (e,p))
130
131
132
    ]

    
133
134
135
136
137
138
139
140
141
    | 
    [ e1 = expr; op = ["=" | "<=" | "<<" | ">>" | ">=" ]; e2 = expr -> 
	let op = match op with
	  | "<<" -> "<"
	  | ">>" -> ">"
	  | s -> s in
	mk loc (Op (op,[e1;e2]))
    ]

142
    | 
143
    [ e1 = expr; op = ["+" | "-" | "@" ]; e2 = expr -> 
144
	mk loc (Op (op,[e1;e2]))
145
    | e = expr; "\\"; l = [LIDENT | UIDENT] -> 
146
	mk loc (RemoveField (e,LabelPool.mk l)) 
147
148
    ]
    |
149
150
151
152
153
154
    [ e1 = expr; op = ["*"]; e2 = expr -> mk loc (Op (op,[e1;e2]))  
    | 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
155
	let re = Star(Alt(SeqCapture(ident "x",Elem p), Elem any)) in
156
157
	let ct = mk loc (Regexp (re,any)) in
        let p = mk loc (XmlT (tag, multi_prod loc [att;ct])) in
158
	let b = (p,  mk loc (Var (ident "x"))) in
159
	mk loc (Op ("flatten", [mk loc (Map (e,[b]))]))
160
    ]
161
    |
162
    [ e = expr;  "."; l = [LIDENT | UIDENT] -> 
163
	mk loc (Dot (e,LabelPool.mk l)) 
164
    ]  
165
 
166
    |
167
168
    [ op = [ LIDENT "flatten"
	   | LIDENT "load_xml"
169
	   | LIDENT "load_html"
170
	   | LIDENT "print_xml"
171
	   | LIDENT "print"
172
173
	   | LIDENT "raise" 
	   | LIDENT "int_of"
174
	   | LIDENT "string_of"
175
176
	   ]; 
      e = expr -> mk loc (Op (op,[e]))
177
178
    | op = [ LIDENT "dump_to_file" ];
      e1 = expr LEVEL "no_appl"; e2 = expr -> mk loc (Op (op, [e1;e2])) 
179
    | e1 = SELF; LIDENT "div"; e2 = expr -> mk loc (Op ("/", [e1;e2]))
180
    | e1 = SELF; LIDENT "mod"; e2 = expr -> mk loc (Op ("mod", [e1;e2]))
181
    | e1 = SELF; e2 = expr -> mk loc (Apply (e1,e2))
182
183
    ]

184
185
186
    | "no_appl" 
    [ c = const -> mk loc (Cst c)
    | "("; l = LIST1 expr SEP ","; ")" -> tuple loc l
187
188
    | "[";  l = LIST0 seq_elem; e = OPT [ ";"; e = expr -> e ]; "]" ->
	let e = match e with Some e -> e | None -> cst_nil in
189
190
191
192
	List.fold_right 
	  (fun x q ->
	     match x with
	       | `Elems l -> tuple_queue l q
193
	       | `Explode x -> mk_loc x.loc (Op ("@",[x;q]))
194
	  ) l e
195
    | t = [ a = TAG -> 
196
	      mk loc (Cst (Types.Atom (Atoms.mk a)))
197
198
	  | "<"; e = expr LEVEL "no_appl" -> e ];
	a = expr_attrib_spec; ">"; c = expr ->
199
	mk loc (Xml (t, mk loc (Pair (a,c))))
200
    | "{"; r = [ expr_record_spec | -> mk loc (RecordLitt LabelMap.empty) ]; "}" -> r
201
    | s = STRING2 ->
202
	tuple loc (char_list loc s @ [cst_nil])
203
    | a = LIDENT -> mk loc (Var (ident a))
204
205
206
    ]

  ];
207
208

  seq_elem: [
209
210
211
    [ x = STRING1 -> `Elems (char_list loc x)
    | e = expr LEVEL "no_appl" -> `Elems [e]
    | "!"; e = expr LEVEL "no_appl" -> `Explode e
212
213
    ]
  ];
214
215
216
	  
  let_binding: [
    [ "let"; p = pat; "="; e = expr -> (p,e)
217
    | "let"; p = pat; ":"; t = pat; "="; e = expr -> (p, mknoloc (Forget (e,t)))
218
219
220
221
222
223
    | "let"; "fun"; (f,a,b) = fun_decl ->
	let p = match f with 
	  | Some x -> mk loc (Capture x)
	  | _ -> failwith "Function name mandatory in let fun declarations"
	in
	let abst = { fun_name = f; fun_iface = a; fun_body = b } in
224
        let e = mk loc (Abstraction abst) in
225
        (p,e);
226
227
228
    ] 
  ];

229
 fun_decl: [
230
231
(* need an hack to do this, because both productions would
   match   [ OPT LIDENT; "("; pat ] .... *)
232
   [ f = OPT [ x = LIDENT -> ident x]; "("; p1 = pat LEVEL "no_arrow";
233
234
235
236
237
238
239
240
241
242
243
244
245
    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) -> f,(p1,p2)::a,b
	| `Compact (targ1,args,tres,body) ->
	    let args = (p1,targ1) :: args in
246
247
	    let targ = multi_prod nopos (List.map snd args) in
	    let arg = multi_prod nopos (List.map fst args) in
248
249
250
	    let b = [arg, body] in
	    let a = [targ,tres] in
	    (f,a,b)
251
252
253
  ]
 ];

254
 arrow: [
255
    [ t1 = pat LEVEL "no_arrow"; "->"; t2 = pat -> (t1,t2)]
256
257
258
  ];

  branches: [
259
    [ OPT "|"; l = LIST1 branch SEP "|" -> l ]
260
261
262
  ];

  branch: [
263
    [ p = pat LEVEL "no_arrow"; "->"; e = expr -> (p,e) ]
264
265
266
267
  ];

	  
  regexp: [ 
268
269
270
271
272
    [ x = regexp; "|"; y = regexp -> 
	match (x,y) with
	  | Elem x, Elem y -> Elem (mk loc (Or (x,y)))
	  | _ -> Alt (x,y) 
    ]
273
  | [ x = regexp; y = regexp -> Seq (x,y) ]
274
  | [ a = LIDENT; "::"; x = regexp -> SeqCapture (ident a,x) ]
275
276
277
278
  | [ x = regexp; "*" -> Star x
    | x = regexp; "*?" -> WeakStar x
    | x = regexp; "+" -> Seq (x, Star x)
    | x = regexp; "+?" -> Seq (x, WeakStar x)
279
    | x = regexp; "?" ->  Alt (x, Epsilon)
280
281
    | x = regexp; "??" -> Alt (Epsilon, x) ]
  | [ "("; x = regexp; ")" -> x
282
283
    | "("; a = LIDENT; ":="; c = const; ")" -> 
	Elem (mk loc (Constant ((ident a,c))))
284
    | UIDENT "PCDATA" -> string_regexp
285
    | i = STRING1; "--"; j = STRING1 ->
286
287
	let i = Chars.mk_char (parse_char loc i)
	and j = Chars.mk_char (parse_char loc j) in
288
        Elem (mk loc (Internal (Types.char (Chars.char_class i j))))
289
290
    |  s = STRING1 ->
	let s = seq_of_string loc s in
291
	List.fold_right
292
	  (fun (loc,c) accu -> 
293
	     let c = Chars.mk_char c in
294
295
296
	     let c = Chars.atom c in
	     Seq (Elem (mk loc (Internal (Types.char c))), accu))
	  s
297
	  Epsilon 
298
299
300
301
302
303
304
305
306
    | e = pat LEVEL "simple" -> Elem e
    ]
  ];

  pat: [ 
      [ x = pat; "where"; 
        b = LIST1 [ a = UIDENT; "="; y = pat -> (a,y)] SEP "and"
            -> mk loc (Recurs (x,b)) ]
    | RIGHTA [ x = pat; "->"; y = pat -> mk loc (Arrow (x,y)) ]
307
    | "no_arrow" [ x = pat; "|"; y = pat -> mk loc (Or (x,y)) ] 
308
    | "simple" [ x = pat; "&"; y = pat -> mk loc (And (x,y)) 
309
	       | x = pat; "\\"; y = pat -> mk loc (Diff (x,y)) ]
310
    | 
311
312
      [ "{"; r = record_spec; "}" -> mk loc (Record (true,r))
      | "{|"; r = record_spec; "|}" -> mk loc (Record (false,r))
313
      | LIDENT "_" -> mk loc (Internal Types.any)
314
315
316
      | a = LIDENT -> mk loc (Capture (ident a))
      | "("; a = LIDENT; ":="; c = const; ")" -> 
	  mk loc (Constant (ident a,c))
317
318
      | a = UIDENT -> mk loc (PatVar a)
      | i = INT ; "--"; j = INT -> 
319
320
          let i =  Intervals.mk i 
	  and j =  Intervals.mk j in
321
322
          mk loc (Internal (Types.interval (Intervals.bounded i j)))
      | i = INT -> 
323
          let i =  Intervals.mk i  in
324
          mk loc (Internal (Types.interval (Intervals.atom i)))
325
      | "*"; "--"; j = INT ->
326
	  let j =  Intervals.mk j in
327
          mk loc (Internal (Types.interval (Intervals.left j)))
328
      | i = INT; "--"; "*" ->
329
	  let i = Intervals.mk i in
330
          mk loc (Internal (Types.interval (Intervals.right i)))
331
332
      | i = char ->
          mk loc (Internal (Types.char (Chars.char_class i i)))
333
      | i = char ; "--"; j = char ->
334
          mk loc (Internal (Types.char (Chars.char_class i j)))
335
336
337
338
      | 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 
339
                 | -> mknoloc (Internal (Sequence.nil_type)) ]; 
340
             "]" -> mk loc (Regexp (r,q))
341
342
343
344
      | t = [
	  [ "<"; LIDENT "_" -> mk loc (Internal (Types.atom (Atoms.any)))
	  | a = TAG -> 
	      mk loc 
345
	      (Internal (Types.atom (Atoms.atom (Atoms.mk a)))) ]
346
347
348
	| [ "<"; t = pat -> t ]
	];
	a = attrib_spec; ">"; c = pat ->
349
          mk loc (XmlT (t, multi_prod loc [a;c]))
350
351
      | s = STRING2 ->
	  let s = seq_of_string loc s in
352
	  let s = List.map 
353
		    (fun (loc,c) -> 
354
355
356
		       mk loc (Internal
				 (Types.char
				    (Chars.atom
357
				       (Chars.mk_char c))))) s in
358
359
	  let s = s @ [mk loc (Internal (Sequence.nil_type))] in
	  multi_prod loc s
360
361
362
363
364
      ]
    
  ];

  record_spec:
365
366
    [ [ r = LIST0 [ l = [LIDENT | UIDENT]; "=";
                  o = [ "?" -> true | -> false]; 
367
368
                  x = pat -> 
		    let x = if o then mk loc (Optional x) else x in
369
		    (LabelPool.mk l, x)
370
                ] SEP ";" ->
371
	  make_record loc r
372
373
      ] ];
  
374
375
  char:
    [ 
376
377
      [ c = STRING1 -> Chars.mk_char (parse_char loc c)
      | "!"; i = INT -> Chars.mk_int (int_of_string i) ]
378
379
380
    ];
     

381
382
  const:
    [ 
383
384
      [ i = INT -> Types.Integer (Intervals.mk i)
      | "`"; a = [LIDENT | UIDENT] -> Types.Atom (Atoms.mk a)
385
      | c = char -> Types.Char c ]
386
387
388
389
    ];


  attrib_spec:
390
    [ [ r = record_spec -> mk loc (Record (true,r)) 
391
392
393
394
      | "("; t = pat; ")" -> t 
      | "{"; r = record_spec; "}" -> mk loc (Record (true,r))
      | "{|"; r = record_spec; "|}" -> mk loc (Record (false,r))
      ] ];
395
396
397

  expr_record_spec:
    [ [ r = LIST1
398
	      [ l = [LIDENT | UIDENT]; "="; x = expr -> 
399
		  (LabelPool.mk l,x) ] 
400
	      SEP ";" ->
401
	  mk loc (RecordLitt (make_record loc r))
402
403
404
405
406
      ] ];
  
  expr_attrib_spec:
    [ [ r = expr_record_spec -> r ]
    | [ e = expr LEVEL "no_appl" -> e 
407
      | -> mk loc (RecordLitt (LabelMap.empty)) 
408
409
410
411
      ] 
    ];
END

412
413
414
415
416
let pat'  = Grammar.Entry.create gram "type/pattern expression"
EXTEND GLOBAL: pat pat';
  pat': [  [ p = pat; EOI -> p ] ];
END

417
let pat = Grammar.Entry.parse pat
418
419
and expr = Grammar.Entry.parse expr
and prog = Grammar.Entry.parse prog
420

421

422
module From_string = struct
423
  let pat s = Grammar.Entry.parse pat' (Stream.of_string s)
424
425
  let expr s = expr (Stream.of_string s)
end
426