]> matita.cs.unibo.it Git - helm.git/blob - matitaB/components/content_pres/cicNotationLexer.ml
Matitaweb: Fixes a bug in the extensible parser which caused Matita to crash
[helm.git] / matitaB / components / content_pres / cicNotationLexer.ml
1 (* Copyright (C) 2005, HELM Team.
2  * 
3  * This file is part of HELM, an Hypertextual, Electronic
4  * Library of Mathematics, developed at the Computer Science
5  * Department, University of Bologna, Italy.
6  * 
7  * HELM is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * 
12  * HELM is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with HELM; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://helm.cs.unibo.it/
24  *)
25
26 (* $Id$ *)
27
28 open Printf
29
30 exception Error of int * int * string
31
32 module StringSet = Set.Make(String)
33
34 (* Lexer *)
35 let regexp number = xml_digit+
36 let regexp utf8_blank = " " | "\r\n" | "\n" | "\t" | [160] (* this is a nbsp *)
37 let regexp percentage = 
38   ('-' | "") [ '0' - '9' ] + '%'
39 let regexp floatwithunit = 
40   ('-' | "") [ '0' - '9' ] + ["."] [ '0' - '9' ] + ([ 'a' - 'z' ] + | "" )
41 let regexp color = "#" [ '0' - '9' 'a' - 'f' 'A' - 'F' ] [ '0' - '9' 'a' - 'f'
42 'A' - 'F' ] [ '0' - '9' 'a' - 'f' 'A' - 'F' ] [ '0' - '9' 'a' - 'f' 'A' - 'F' ]
43 [ '0' - '9' 'a' - 'f' 'A' - 'F' ] [ '0' - '9' 'a' - 'f' 'A' - 'F' ]
44
45   (* ZACK: breaks unicode's binder followed by an ascii letter without blank *)
46 (* let regexp ident_letter = xml_letter *)
47
48 let regexp ident_letter = [ 'a' - 'z' 'A' - 'Z' ]
49
50   (* must be in sync with "is_ligature_char" below *)
51 let regexp ligature_char = [ "'`~!?@*()[]<>-+=|:;.,/\"" ]
52 let regexp ligature = ligature_char ligature_char+
53
54 let regexp we_proved = "we" utf8_blank+ "proved"
55 let regexp we_have = "we" utf8_blank+ "have"
56 let regexp let_rec = "let" utf8_blank+ "rec" 
57 let regexp let_corec = "let" utf8_blank+  "corec"
58 let regexp ident_decoration = '\'' | '?' | '`'
59 let regexp ident_cont = ident_letter | xml_digit | '_'
60 let regexp ident_start = ident_letter 
61 let regexp ident = ident_letter ident_cont* ident_decoration* 
62 let regexp variable_ident = '_' '_' number
63 let regexp pident = '_' ident
64
65 let regexp uri_step = [ 'a' - 'z' 'A' - 'Z' '0' - '9' '_' '-' ''' ]+
66
67 let regexp uri =
68   ("cic:/" | "theory:/")              (* schema *)
69 (*   ident ('/' ident)*                  |+ path +| *)
70   uri_step ('/' uri_step)*            (* path *)
71   ('.' ident)+                        (* ext *)
72 (*  ("#xpointer(" number ('/' number)+ ")")?  (* xpointer *) *)
73   ("(" number (',' number)* ")")?  (* reference spec *)
74
75 let regexp qstring = '"' [^ '"']* '"'
76 let regexp xmarkup = '\005'
77 let regexp ymarkup = '\006'
78
79 let regexp hreftag = xmarkup [ 'A' 'a' ]
80 let regexp href = "href=\"" uri "\""
81 let regexp hreftitle = "title=" qstring
82 let regexp hrefclose = xmarkup "/" [ 'A' 'a' ] ymarkup
83
84 let regexp tag_cont = ident_letter | xml_digit | "_" | "-"
85 let regexp gtagname = [ 'B' - 'Z' 'b' - 'z' ] | ident_letter tag_cont+
86 let regexp attrname = ident_letter tag_cont*
87 let regexp gopentag = xmarkup gtagname
88 let regexp closetag = xmarkup "/" gtagname ymarkup
89 let regexp attribute = attrname "=" qstring
90 let regexp generictag = 
91   gopentag (utf8_blank+ attribute)* ymarkup
92
93 let regexp tex_token = '\\' ident
94
95 let regexp delim_begin = "\\["
96 let regexp delim_end = "\\]"
97
98 let regexp qkeyword = "'" ( ident | pident ) "'"
99
100 let regexp implicit = '?'
101 let regexp placeholder = '%'
102 let regexp meta = implicit number
103
104 let regexp csymbol = '\'' ident
105
106 let regexp begin_group = "@{" | "${"
107 let regexp end_group = '}'
108 let regexp wildcard = "$_"
109 let regexp ast_ident = "@" ident
110 let regexp ast_csymbol = "@" csymbol
111 let regexp meta_ident = "$" ident
112 let regexp meta_anonymous = "$_"
113
114 let regexp begincomment = "(**" utf8_blank
115 let regexp beginnote = "(*"
116 let regexp endcomment = "*)"
117 (* let regexp comment_char = [^'*'] | '*'[^')']
118 let regexp note = "|+" ([^'*'] | "**") comment_char* "+|" *)
119
120 let level1_layouts = 
121   [ "sub"; "sup";
122     "below"; "above";
123     "over"; "atop"; "frac";
124     "sqrt"; "root"; "mstyle" ; "mpadded"; "maction"
125
126   ]
127
128 let level1_keywords =
129   [ "hbox"; "hvbox"; "hovbox"; "vbox";
130     "break";
131     "list0"; "list1"; "sep";
132     "opt";
133     "term"; "ident"; "number";
134   ] @ level1_layouts
135
136 let level2_meta_keywords =
137   [ "if"; "then"; "elCicNotationParser.se";
138     "fold"; "left"; "right"; "rec";
139     "fail";
140     "default";
141     "anonymous"; "ident"; "number"; "term"; "fresh"
142   ]
143
144   (* (string, int) Hashtbl.t, with multiple bindings.
145    * int is the unicode codepoint *)
146 let ligatures = Hashtbl.create 23
147
148 let _ =
149   List.iter
150     (fun (ligature, symbol) -> Hashtbl.add ligatures ligature symbol)
151     [ ("->", <:unicode<to>>);   ("=>", <:unicode<Rightarrow>>);
152       (":=", <:unicode<def>>);
153     ]
154
155 let regexp nreference =
156   "cic:/"                             (* schema *)
157   uri_step ('/' uri_step)*            (* path *)
158   '.'
159   ( "dec"
160   | "def" "(" number ")"
161   | "fix" "(" number "," number "," number ")"
162   | "cfx" "(" number ")"
163   | "ind" "(" number "," number "," number ")"
164   | "con" "(" number "," number "," number ")") (* ext + reference *)
165
166 let error lexbuf msg =
167   let begin_cnum, end_cnum = Ulexing.loc lexbuf in
168   raise (Error (begin_cnum, end_cnum, msg))
169 let error_at_end lexbuf msg =
170   let begin_cnum, end_cnum = Ulexing.loc lexbuf in
171   raise (Error (begin_cnum, end_cnum, msg))
172
173 let loc_of_buf lexbuf = 
174   HExtlib.floc_of_loc (Ulexing.loc lexbuf)
175
176 let return_with_loc token begin_cnum end_cnum =
177   let flocation = HExtlib.floc_of_loc (begin_cnum,end_cnum) in
178    token, flocation
179
180 let return lexbuf token =
181   let begin_cnum, end_cnum = Ulexing.loc lexbuf in
182     return_with_loc token begin_cnum end_cnum
183
184 let return_lexeme lexbuf name = return lexbuf (name, Ulexing.utf8_lexeme lexbuf)
185
186 let return_symbol lexbuf s = return lexbuf ("SYMBOL", s)
187 let return_eoi lexbuf = return lexbuf ("EOI", "")
188
189 let remove_quotes s = String.sub s 1 (String.length s - 2)
190
191 let mk_lexer token =
192   let tok_func stream =
193 (*     let lexbuf = Ulexing.from_utf8_stream stream in *)
194 (** XXX Obj.magic rationale.
195  * The problem.
196  *  camlp5 constraints the tok_func field of Token.glexer to have type:
197  *    Stream.t char -> (Stream.t 'te * flocation_function)
198  *  In order to use ulex we have (in theory) to instantiate a new lexbuf each
199  *  time a char Stream.t is passed, destroying the previous lexbuf which may
200  *  have consumed a character from the old stream which is lost forever :-(
201  * The "solution".
202  *  Instead of passing to camlp5 a char Stream.t we pass a lexbuf, casting it to
203  *  char Stream.t with Obj.magic where needed.
204  *)
205     let lexbuf = Obj.magic stream in
206     Token.make_stream_and_location
207       (fun () ->
208         try
209           token lexbuf
210         with
211         | Ulexing.Error -> error_at_end lexbuf "Unexpected character"
212         | Ulexing.InvalidCodepoint p ->
213             error_at_end lexbuf (sprintf "Invalid code point: %d" p))
214   in
215   {
216     Token.tok_func = tok_func;
217     Token.tok_using = (fun _ -> ());
218     Token.tok_removing = (fun _ -> ()); 
219     Token.tok_match = Token.default_match;
220     Token.tok_text = Token.lexer_text;
221     Token.tok_comm = None;
222   }
223
224 let expand_macro lexbuf =
225   let macro =
226     Ulexing.utf8_sub_lexeme lexbuf 1 (Ulexing.lexeme_length lexbuf - 1)
227   in
228   try
229     ("SYMBOL", Utf8Macro.expand macro)
230   with Utf8Macro.Macro_not_found _ -> 
231 (* FG: unexpanded TeX macros are terminated by a space for rendering *)     
232      "SYMBOL", (Ulexing.utf8_lexeme lexbuf ^ " ")
233
234 let remove_quotes s = String.sub s 1 (String.length s - 2)
235 let remove_left_quote s = String.sub s 1 (String.length s - 1)
236
237 let rec level2_pattern_token_group counter buffer =
238   lexer
239   | end_group -> 
240       if (counter > 0) then
241         Buffer.add_string buffer (Ulexing.utf8_lexeme lexbuf) ;
242       snd (Ulexing.loc lexbuf)
243   | begin_group -> 
244       Buffer.add_string buffer (Ulexing.utf8_lexeme lexbuf) ;
245       ignore (level2_pattern_token_group (counter + 1) buffer lexbuf) ;
246       level2_pattern_token_group counter buffer lexbuf
247   | _ -> 
248       Buffer.add_string buffer (Ulexing.utf8_lexeme lexbuf) ;
249       level2_pattern_token_group counter buffer lexbuf
250
251 let read_unparsed_group token_name lexbuf =
252   let buffer = Buffer.create 16 in
253   let begin_cnum, _ = Ulexing.loc lexbuf in
254   let end_cnum = level2_pattern_token_group 0 buffer lexbuf in
255     return_with_loc (token_name, Buffer.contents buffer) begin_cnum end_cnum
256
257 let handle_keywords lexbuf k name =
258   let s = Ulexing.utf8_lexeme lexbuf in
259   prerr_endline (Printf.sprintf "handling \"%s\" as a keyword or %s?" s name);
260   if k s then
261             return lexbuf ("", s)
262           else
263             return lexbuf (name, s)
264 ;;
265
266 let rec level2_meta_token =
267   lexer
268   | utf8_blank+ -> level2_meta_token lexbuf
269   | hreftag -> return lexbuf ("ATAG","")
270   | hrefclose -> return lexbuf ("ATAGEND","")
271   | generictag
272   | closetag -> level2_meta_token lexbuf
273   | ident ->
274       handle_keywords lexbuf (fun x -> List.mem x level2_meta_keywords) "IDENT"
275   | variable_ident -> return lexbuf ("IDENT", Ulexing.utf8_lexeme lexbuf)
276   | pident ->
277       handle_keywords lexbuf (fun x -> List.mem x level2_meta_keywords) "PIDENT"
278   | "@{" -> read_unparsed_group "UNPARSED_AST" lexbuf
279   | ast_ident ->
280       return lexbuf ("UNPARSED_AST",
281         remove_left_quote (Ulexing.utf8_lexeme lexbuf))
282   | ast_csymbol ->
283       return lexbuf ("UNPARSED_AST",
284         remove_left_quote (Ulexing.utf8_lexeme lexbuf))
285   | eof -> return_eoi lexbuf
286
287 let rec comment_token acc depth =
288   lexer
289   | beginnote ->
290       let acc = acc ^ Ulexing.utf8_lexeme lexbuf in
291       comment_token acc (depth + 1) lexbuf
292   | endcomment ->
293       let acc = acc ^ Ulexing.utf8_lexeme lexbuf in
294       if depth = 0
295       then acc
296       else comment_token acc (depth - 1) lexbuf
297   | _ ->
298       let acc = acc ^ Ulexing.utf8_lexeme lexbuf in
299       comment_token acc depth lexbuf
300
301   (** @param k continuation to be invoked when no ligature has been found *)
302 let ligatures_token k =
303   lexer
304   | ligature ->
305       let lexeme = Ulexing.utf8_lexeme lexbuf in
306       (match List.rev (Hashtbl.find_all ligatures lexeme) with
307       | [] -> (* ligature not found, rollback and try default lexer *)
308           Ulexing.rollback lexbuf;
309           k lexbuf
310       | default_lig :: _ -> (* ligatures found, use the default one *)
311           return_symbol lexbuf default_lig)
312   | eof -> return_eoi lexbuf
313   | _ ->  (* not a ligature, rollback and try default lexer *)
314       Ulexing.rollback lexbuf;
315       k lexbuf
316
317 module LocalizeOD =
318   struct
319     type t = Stdpp.location
320     let compare = Pervasives.compare
321   end
322
323 module LocalizeEnv = Map.Make (LocalizeOD)
324
325 let so_pp = function
326  | None -> "()"
327  | Some s -> "*" ^ s
328 ;;
329
330 let update_table loc desc href loctable =
331   if desc <> None || href <> None 
332     then 
333      (let s,e = HExtlib.loc_of_floc loc in
334       
335       prerr_endline (Printf.sprintf "*** [%d,%d] \"%s\",\"%s\""
336         s e (so_pp href) (so_pp desc));
337         
338       Printf.printf "*** [%d,%d] \"%s\",\"%s\""
339         s e (so_pp href) (so_pp desc);
340       LocalizeEnv.add loc (href,desc) loctable)
341     else loctable
342 ;;
343
344 let level2_ast_token loctable status =
345   prerr_endline ("X keywords = " ^ (String.concat ", "
346                     (StringSet.elements status)));
347   (* start = starting point of last open A tag (default -1 = no tag) *)
348   let rec aux desc href start =
349     lexer
350     | let_rec -> return lexbuf ("LETREC","")
351     | let_corec -> return lexbuf ("LETCOREC","")
352     | we_proved -> return lexbuf ("WEPROVED","")
353     | we_have -> return lexbuf ("WEHAVE","")
354     | utf8_blank+ -> ligatures_token (aux desc href start) lexbuf
355     | meta ->
356        let s = Ulexing.utf8_lexeme lexbuf in
357         return lexbuf ("META", String.sub s 1 (String.length s - 1))
358     | implicit -> return lexbuf ("IMPLICIT", "")
359     | placeholder -> return lexbuf ("PLACEHOLDER", "")
360     | hreftag ->
361         let start = Ulexing.lexeme_start lexbuf in
362         aux_attr None None start lexbuf
363     | hrefclose -> return lexbuf ("LEXING_ERROR", Ulexing.utf8_lexeme lexbuf)
364     (* ignore other tags *)
365     | generictag 
366     | closetag -> ligatures_token (aux desc href start) lexbuf
367     | ident -> 
368         if start <> ~-1 then
369          let idtok,_ = 
370            handle_keywords lexbuf (fun x -> StringSet.mem x status) "IDENT"
371          in aux_close_tag desc href start idtok lexbuf 
372 (*         ("IDENT", Ulexing.utf8_lexeme lexbuf) lexbuf *)
373         else 
374            handle_keywords lexbuf (fun x -> StringSet.mem x status) "IDENT"
375     | variable_ident -> 
376                return lexbuf ("IDENT", Ulexing.utf8_lexeme lexbuf)
377     | pident -> if start <> ~-1 then
378                  aux_close_tag desc href start ("PIDENT", Ulexing.utf8_lexeme lexbuf) lexbuf
379                 else 
380                   handle_keywords lexbuf (fun x -> StringSet.mem x status) "PIDENT"
381     | number -> let token = "NUMBER", Ulexing.utf8_lexeme lexbuf
382                 in
383                 if start <> ~-1 then
384                   aux_close_tag desc href start token lexbuf
385                 else return lexbuf token
386     | tex_token -> let token = expand_macro lexbuf
387                    in
388                    if start <> ~-1 then
389                      aux_close_tag desc href start token lexbuf
390                    else return lexbuf token
391     | nreference -> return lexbuf ("NREF", Ulexing.utf8_lexeme lexbuf)
392     | uri -> return lexbuf ("URI", Ulexing.utf8_lexeme lexbuf)
393     | qstring ->
394         return lexbuf ("QSTRING", remove_quotes (Ulexing.utf8_lexeme lexbuf))
395     | csymbol ->
396         return lexbuf ("CSYMBOL", remove_left_quote (Ulexing.utf8_lexeme lexbuf))
397     | "${" -> read_unparsed_group "UNPARSED_META" lexbuf
398     | "@{" -> read_unparsed_group "UNPARSED_AST" lexbuf
399     | '(' -> return lexbuf ("LPAREN", "")
400     | ')' -> return lexbuf ("RPAREN", "")
401     | meta_ident ->
402         return lexbuf ("UNPARSED_META",
403           remove_left_quote (Ulexing.utf8_lexeme lexbuf))
404     | meta_anonymous -> return lexbuf ("UNPARSED_META", "anonymous")
405     | beginnote -> 
406         let _comment = comment_token (Ulexing.utf8_lexeme lexbuf) 0 lexbuf in
407   (*       let comment =
408           Ulexing.utf8_sub_lexeme lexbuf 2 (Ulexing.lexeme_length lexbuf - 4)
409         in
410         return lexbuf ("NOTE", comment) *)
411         ligatures_token (aux desc href start) lexbuf
412     | begincomment -> return lexbuf ("BEGINCOMMENT","")
413     | endcomment -> return lexbuf ("ENDCOMMENT","")
414     | eof -> return_eoi lexbuf
415     | _ -> let token = "SYMBOL", (Ulexing.utf8_lexeme lexbuf)
416            in
417            if start <> ~-1 then
418              aux_close_tag desc href start token lexbuf
419            else return lexbuf token
420
421    and aux_attr desc href start = lexer
422     | utf8_blank+ -> ligatures_token (aux_attr desc href start) lexbuf
423     | href -> 
424         aux_attr desc 
425           (Some (Ulexing.utf8_sub_lexeme lexbuf 6 (Ulexing.lexeme_length lexbuf - 7))) 
426           start lexbuf
427     | hreftitle -> 
428         aux_attr 
429           (Some (Ulexing.utf8_sub_lexeme lexbuf 7 (Ulexing.lexeme_length lexbuf - 8))) 
430           href start lexbuf
431     | ymarkup -> aux desc href start lexbuf
432     | _ -> return lexbuf ("LEXING_ERROR", Ulexing.utf8_lexeme lexbuf)
433
434 (*  and aux_in_tag desc href = lexer
435     | ident -> loctable := 
436                  update_table (loc_of_buf lexbuf) desc href !loctable;
437                handle_keywords lexbuf (fun x -> StringSet.mem x status) "IDENT"
438     | variable_ident -> 
439                return lexbuf ("IDENT", Ulexing.utf8_lexeme lexbuf)
440     | pident -> loctable :=
441                   update_table (loc_of_buf lexbuf) desc href !loctable;
442                 handle_keywords lexbuf (fun x -> StringSet.mem x status) "PIDENT"
443     | number -> loctable := 
444                   update_table (loc_of_buf lexbuf) desc href !loctable;
445                 return lexbuf ("NUMBER", Ulexing.utf8_lexeme lexbuf)
446     | tex_token -> loctable := 
447                      update_table (loc_of_buf lexbuf) desc href !loctable;
448                    return lexbuf (expand_macro lexbuf)
449     | _ -> loctable := 
450              update_table (loc_of_buf lexbuf) desc href !loctable;
451            return_symbol lexbuf (Ulexing.utf8_lexeme lexbuf)
452   *)  
453   and aux_close_tag desc href start token = lexer
454     | hrefclose -> let _,b = Ulexing.loc lexbuf in
455                    loctable := update_table (HExtlib.floc_of_loc (start,b)) desc href !loctable;
456                    prerr_endline 
457                      (Printf.sprintf "adding loc (%d,%d) to table" start b);
458                    return_with_loc token start b
459     | _ -> return lexbuf ("LEXING_ERROR", Ulexing.utf8_lexeme lexbuf)
460   in aux None None ~-1
461
462 let rec level1_pattern_token =
463   lexer
464   | utf8_blank+ -> ligatures_token level1_pattern_token lexbuf
465   | number -> return lexbuf ("NUMBER", Ulexing.utf8_lexeme lexbuf)
466   | hreftag -> return lexbuf ("ATAG", "")
467   | hrefclose -> return lexbuf ("ATAGEND","")
468   | generictag 
469   | closetag -> ligatures_token level1_pattern_token lexbuf
470   | ident -> handle_keywords lexbuf (fun x -> List.mem x level1_keywords) "IDENT"
471   | variable_ident -> return lexbuf ("IDENT", Ulexing.utf8_lexeme lexbuf)
472   | pident-> handle_keywords lexbuf (fun x->List.mem x level1_keywords) "PIDENT" 
473   | color -> return lexbuf ("COLOR", Ulexing.utf8_lexeme lexbuf)
474   | percentage -> 
475       return lexbuf ("PERCENTAGE", Ulexing.utf8_lexeme lexbuf)
476   | floatwithunit -> 
477       return lexbuf ("FLOATWITHUNIT", Ulexing.utf8_lexeme lexbuf)
478   | tex_token -> return lexbuf (expand_macro lexbuf)
479   | qkeyword ->
480       return lexbuf ("QKEYWORD", remove_quotes (Ulexing.utf8_lexeme lexbuf))
481   | '(' -> return lexbuf ("LPAREN", "")
482   | ')' -> return lexbuf ("RPAREN", "")
483   | eof -> return_eoi lexbuf
484   | _ -> return_symbol lexbuf (Ulexing.utf8_lexeme lexbuf)
485
486 let level1_pattern_token = ligatures_token level1_pattern_token
487 let level2_ast_token loctable status = 
488   ligatures_token (level2_ast_token loctable status)
489
490 (* API implementation *)
491 type lexers = {
492         level1_pattern_lexer : (string * string) Token.glexer;
493         level2_ast_lexer : (string * string) Token.glexer;
494         level2_meta_lexer : (string * string) Token.glexer;
495 }
496
497 let initial_keywords = 
498    [ "CProp"; "Prop"; "Type"; "Set"; "let"; "match";
499    "with"; "in"; "and"; "to"; "as"; "on"; "return"; "done" ]
500 ;;
501
502 let mk_lexers loctable keywords =
503   prerr_endline ("mk_lexers keywords: " ^ (String.concat ", " keywords)); 
504   let status = 
505     List.fold_right StringSet.add (initial_keywords @ keywords) StringSet.empty 
506   in 
507   {
508         level1_pattern_lexer = mk_lexer level1_pattern_token;
509         level2_ast_lexer = mk_lexer (level2_ast_token loctable status);
510         level2_meta_lexer = mk_lexer level2_meta_token;
511   }
512 ;;