parser.ml 13 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
let seq_of_string pos s =
39 40
  let s =  Encodings.Utf8.mk s in
  (* What about locations when input file is not Utf8 ? *)
41
  let (pos,_) = pos in
42 43 44 45 46 47 48
  let rec aux pos i j =
    if Encodings.Utf8.equal_index i j then []
    else
      let (c,i) = Encodings.Utf8.next s i in
      ((pos,pos+1),c)::(aux (pos+1) i j)
  in
  aux pos (Encodings.Utf8.start_index s) (Encodings.Utf8.end_index s)
49

50
exception Error of string
51
let error (i,j) s = Location.raise_loc i j (Error s)
52

53 54 55
let make_record loc r =
  LabelMap.from_list (fun _ _ -> error loc "Duplicated record field") r

56
let parse_char loc s =
57 58 59 60
  let s = seq_of_string loc s in
  match s with
    | [_,c] -> c
    | _ -> error loc "Character litteral must have length 1"
61

62
let char_list pos s = 
63
  let s = seq_of_string pos s in
64
  List.map (fun (loc,c) -> mk loc (Cst (Types.Char (Chars.mk_int c)))) s
65 66


67 68
let include_stack = ref []

69
EXTEND
70 71 72
  GLOBAL: prog expr pat regexp const;

  prog: [
73
    [ l = LIST0 [ p = phrase; ";;" -> p ]; EOI -> List.flatten l ]
74 75 76
  ];

  phrase: [
77
    [ (p,e) = let_binding -> [ mk loc (LetDecl (p,e)) ]
78
    | (p,e1) = let_binding; "in"; e2 = expr LEVEL "top"->
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
        [ 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
	)
97
    ] | 
98
    [ e = expr -> [ mk loc (EvalStatement e) ]
99 100 101 102 103
    ]
  ];

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

  expr: [
    "top" RIGHTA
    [ "match"; e = SELF; "with"; b = branches -> mk loc (Match (e,b))
115 116
    | "try"; e = SELF; "with"; b = branches -> 
	let default = 
117 118
	  (mknoloc (Capture (ident "x")),
	   mknoloc (Op ("raise",[mknoloc (Var (ident "x"))]))) in
119
	mk loc (Try (e,b@[default]))
120
    | "map"; e = SELF; "with"; b = branches -> mk loc (Map (e,b))
121
    | "ttree"; e = SELF; "with"; b = branches -> mk loc (Ttree (e,b))
122 123 124 125
    | "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]))
126
    | "transform"; e = SELF; "with"; b = branches -> 
127
	let default = mknoloc (Capture (ident "x")), cst_nil in
128
	mk loc (Op ("flatten", [mk loc (Map (e,b@[default]))]))
129
    | "fun"; (f,a,b) = fun_decl ->
130 131 132
	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]))
133 134
    | e = expr; ":"; p = pat ->
	mk loc (Forget (e,p))
135 136 137
    ]

    
138 139 140 141 142 143 144 145 146
    | 
    [ e1 = expr; op = ["=" | "<=" | "<<" | ">>" | ">=" ]; e2 = expr -> 
	let op = match op with
	  | "<<" -> "<"
	  | ">>" -> ">"
	  | s -> s in
	mk loc (Op (op,[e1;e2]))
    ]

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

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

  ];
213 214

  seq_elem: [
215 216 217
    [ x = STRING1 -> `Elems (char_list loc x)
    | e = expr LEVEL "no_appl" -> `Elems [e]
    | "!"; e = expr LEVEL "no_appl" -> `Explode e
218 219
    ]
  ];
220 221 222
	  
  let_binding: [
    [ "let"; p = pat; "="; e = expr -> (p,e)
223
    | "let"; p = pat; ":"; t = pat; "="; e = expr -> (p, mknoloc (Forget (e,t)))
224 225 226 227 228 229
    | "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
230
        let e = mk loc (Abstraction abst) in
231
        (p,e);
232 233 234
    ] 
  ];

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

260
 arrow: [
261
    [ t1 = pat LEVEL "no_arrow"; "->"; t2 = pat -> (t1,t2)]
262 263 264
  ];

  branches: [
265
    [ OPT "|"; l = LIST1 branch SEP "|" -> l ]
266 267 268
  ];

  branch: [
269
    [ p = pat LEVEL "no_arrow"; "->"; e = expr -> (p,e) ]
270 271 272 273
  ];

	  
  regexp: [ 
274 275 276 277 278
    [ x = regexp; "|"; y = regexp -> 
	match (x,y) with
	  | Elem x, Elem y -> Elem (mk loc (Or (x,y)))
	  | _ -> Alt (x,y) 
    ]
279
  | [ x = regexp; y = regexp -> Seq (x,y) ]
280
  | [ a = LIDENT; "::"; x = regexp -> SeqCapture (ident a,x) ]
281 282 283 284
  | [ x = regexp; "*" -> Star x
    | x = regexp; "*?" -> WeakStar x
    | x = regexp; "+" -> Seq (x, Star x)
    | x = regexp; "+?" -> Seq (x, WeakStar x)
285
    | x = regexp; "?" ->  Alt (x, Epsilon)
286 287
    | x = regexp; "??" -> Alt (Epsilon, x) ]
  | [ "("; x = regexp; ")" -> x
288 289
    | "("; a = LIDENT; ":="; c = const; ")" -> 
	Elem (mk loc (Constant ((ident a,c))))
290
    | UIDENT "PCDATA" -> string_regexp
291
    | i = STRING1; "--"; j = STRING1 ->
292 293
	let i = Chars.mk_int (parse_char loc i)
	and j = Chars.mk_int (parse_char loc j) in
294
        Elem (mk loc (Internal (Types.char (Chars.char_class i j))))
295 296
    |  s = STRING1 ->
	let s = seq_of_string loc s in
297
	List.fold_right
298
	  (fun (loc,c) accu -> 
299
	     let c = Chars.mk_int c in
300 301 302
	     let c = Chars.atom c in
	     Seq (Elem (mk loc (Internal (Types.char c))), accu))
	  s
303
	  Epsilon 
304 305 306 307 308 309 310 311 312
    | 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)) ]
313
    | "no_arrow" [ x = pat; "|"; y = pat -> mk loc (Or (x,y)) ] 
314
    | "simple" [ x = pat; "&"; y = pat -> mk loc (And (x,y)) 
315
	       | x = pat; "\\"; y = pat -> mk loc (Diff (x,y)) ]
316
    | 
317 318
      [ "{"; r = record_spec; "}" -> mk loc (Record (true,r))
      | "{|"; r = record_spec; "|}" -> mk loc (Record (false,r))
319
      | LIDENT "_" -> mk loc (Internal Types.any)
320 321 322
      | a = LIDENT -> mk loc (Capture (ident a))
      | "("; a = LIDENT; ":="; c = const; ")" -> 
	  mk loc (Constant (ident a,c))
323 324
      | a = UIDENT -> mk loc (PatVar a)
      | i = INT ; "--"; j = INT -> 
325 326
          let i =  Intervals.mk i 
	  and j =  Intervals.mk j in
327 328
          mk loc (Internal (Types.interval (Intervals.bounded i j)))
      | i = INT -> 
329
          let i =  Intervals.mk i  in
330
          mk loc (Internal (Types.interval (Intervals.atom i)))
331
      | "*"; "--"; j = INT ->
332
	  let j =  Intervals.mk j in
333
          mk loc (Internal (Types.interval (Intervals.left j)))
334
      | i = INT; "--"; "*" ->
335
	  let i = Intervals.mk i in
336
          mk loc (Internal (Types.interval (Intervals.right i)))
337 338
      | i = char ->
          mk loc (Internal (Types.char (Chars.char_class i i)))
339
      | i = char ; "--"; j = char ->
340
          mk loc (Internal (Types.char (Chars.char_class i j)))
341 342 343 344
      | 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 
345
                 | -> mknoloc (Internal (Sequence.nil_type)) ]; 
346
             "]" -> mk loc (Regexp (r,q))
347 348 349 350
      | t = [
	  [ "<"; LIDENT "_" -> mk loc (Internal (Types.atom (Atoms.any)))
	  | a = TAG -> 
	      mk loc 
351
	      (Internal (Types.atom (Atoms.atom (Atoms.mk a)))) ]
352 353 354
	| [ "<"; t = pat -> t ]
	];
	a = attrib_spec; ">"; c = pat ->
355
          mk loc (XmlT (t, multi_prod loc [a;c]))
356 357
      | s = STRING2 ->
	  let s = seq_of_string loc s in
358
	  let s = List.map 
359
		    (fun (loc,c) -> 
360 361 362
		       mk loc (Internal
				 (Types.char
				    (Chars.atom
363
				       (Chars.mk_int c))))) s in
364 365
	  let s = s @ [mk loc (Internal (Sequence.nil_type))] in
	  multi_prod loc s
366 367 368 369 370
      ]
    
  ];

  record_spec:
371 372
    [ [ r = LIST0 [ l = [LIDENT | UIDENT]; "=";
                  o = [ "?" -> true | -> false]; 
373 374
                  x = pat -> 
		    let x = if o then mk loc (Optional x) else x in
375
		    (LabelPool.mk l, x)
376
                ] SEP ";" ->
377
	  make_record loc r
378 379
      ] ];
  
380 381
  char:
    [ 
382
      [ c = STRING1 -> Chars.mk_int (parse_char loc c) ]
383 384 385
    ];
     

386 387
  const:
    [ 
388 389
      [ i = INT -> Types.Integer (Intervals.mk i)
      | "`"; a = [LIDENT | UIDENT] -> Types.Atom (Atoms.mk a)
390
      | c = char -> Types.Char c ]
391 392 393 394
    ];


  attrib_spec:
395
    [ [ r = record_spec -> mk loc (Record (true,r)) 
396 397 398 399
      | "("; t = pat; ")" -> t 
      | "{"; r = record_spec; "}" -> mk loc (Record (true,r))
      | "{|"; r = record_spec; "|}" -> mk loc (Record (false,r))
      ] ];
400 401 402

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

417 418 419 420 421
let pat'  = Grammar.Entry.create gram "type/pattern expression"
EXTEND GLOBAL: pat pat';
  pat': [  [ p = pat; EOI -> p ] ];
END

422
let pat = Grammar.Entry.parse pat
423 424
and expr = Grammar.Entry.parse expr
and prog = Grammar.Entry.parse prog
425

426

427
module From_string = struct
428
  let pat s = Grammar.Entry.parse pat' (Stream.of_string s)
429 430
  let expr s = expr (Stream.of_string s)
end
431