]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/content_pres/cicNotationLexer.ml
support for mathml mpadded tag added (allows to overlap two subsequent symbols);...
[helm.git] / helm / software / 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 let regexp number = xml_digit+
33 let regexp utf8_blank = " " | "\r\n" | "\n" | "\t" | [160] (* this is a nbsp *)
34 let regexp percentage = 
35   ('-' | "") [ '0' - '9' ] + '%'
36 let regexp floatwithunit = 
37   ('-' | "") [ '0' - '9' ] + ["."] [ '0' - '9' ] + ([ 'a' - 'z' ] + | "" )
38 let regexp color = "#" [ '0' - '9' 'a' - 'f' 'A' - 'F' ] [ '0' - '9' 'a' - 'f'
39 'A' - 'F' ] [ '0' - '9' 'a' - 'f' 'A' - 'F' ] [ '0' - '9' 'a' - 'f' 'A' - 'F' ]
40 [ '0' - '9' 'a' - 'f' 'A' - 'F' ] [ '0' - '9' 'a' - 'f' 'A' - 'F' ]
41
42   (* ZACK: breaks unicode's binder followed by an ascii letter without blank *)
43 (* let regexp ident_letter = xml_letter *)
44
45 let regexp ident_letter = [ 'a' - 'z' 'A' - 'Z' ]
46
47   (* must be in sync with "is_ligature_char" below *)
48 let regexp ligature_char = [ "'`~!?@*()[]<>-+=|:;.,/\"" ]
49 let regexp ligature = ligature_char ligature_char+
50
51 let is_ligature_char =
52   (* must be in sync with "regexp ligature_char" above *)
53   let chars = "'`~!?@*()[]<>-+=|:;.,/\"" in
54   (fun char ->
55     (try
56       ignore (String.index chars char);
57       true
58     with Not_found -> false))
59
60 let regexp we_proved = "we" utf8_blank+ "proved"
61 let regexp we_have = "we" utf8_blank+ "have"
62 let regexp let_rec = "let" utf8_blank+ "rec" 
63 let regexp let_corec = "let" utf8_blank+  "corec"
64 let regexp ident_decoration = '\'' | '?' | '`'
65 let regexp ident_cont = ident_letter | xml_digit | '_'
66 let regexp ident = ident_letter ident_cont* ident_decoration*
67
68 let regexp tex_token = '\\' ident
69
70 let regexp delim_begin = "\\["
71 let regexp delim_end = "\\]"
72
73 let regexp qkeyword = "'" ident "'"
74
75 let regexp implicit = '?'
76 let regexp placeholder = '%'
77 let regexp meta = implicit number
78
79 let regexp csymbol = '\'' ident
80
81 let regexp begin_group = "@{" | "${"
82 let regexp end_group = '}'
83 let regexp wildcard = "$_"
84 let regexp ast_ident = "@" ident
85 let regexp ast_csymbol = "@" csymbol
86 let regexp meta_ident = "$" ident
87 let regexp meta_anonymous = "$_"
88 let regexp qstring = '"' [^ '"']* '"'
89
90 let regexp begincomment = "(**" utf8_blank
91 let regexp beginnote = "(*"
92 let regexp endcomment = "*)"
93 (* let regexp comment_char = [^'*'] | '*'[^')']
94 let regexp note = "|+" ([^'*'] | "**") comment_char* "+|" *)
95
96 let level1_layouts = 
97   [ "sub"; "sup";
98     "below"; "above";
99     "over"; "atop"; "frac";
100     "sqrt"; "root"
101   ]
102
103 let level1_keywords =
104   [ "hbox"; "hvbox"; "hovbox"; "vbox";
105     "break";
106     "list0"; "list1"; "sep";
107     "opt";
108     "term"; "ident"; "number"; "mstyle" ; "mpadded"
109   ] @ level1_layouts
110
111 let level2_meta_keywords =
112   [ "if"; "then"; "elCicNotationParser.se";
113     "fold"; "left"; "right"; "rec";
114     "fail";
115     "default";
116     "anonymous"; "ident"; "number"; "term"; "fresh"
117   ]
118
119   (* (string, unit) Hashtbl.t, to exploit multiple bindings *)
120 let initial_level2_ast_keywords () = Hashtbl.create 23;;
121
122 let level2_ast_keywords = ref (initial_level2_ast_keywords ())
123
124 let initialize_keywords () =
125   List.iter (fun k -> Hashtbl.add !level2_ast_keywords k ())
126   [ "CProp"; "Prop"; "Type"; "Set"; "let"; "match";
127   "with"; "in"; "and"; "to"; "as"; "on"; "return"; "done" ]
128 ;;
129
130 let _ = initialize_keywords ();;
131
132 let add_level2_ast_keyword k = Hashtbl.add !level2_ast_keywords k ()
133 let remove_level2_ast_keyword k = Hashtbl.remove !level2_ast_keywords k
134
135   (* (string, int) Hashtbl.t, with multiple bindings.
136    * int is the unicode codepoint *)
137 let ligatures = Hashtbl.create 23
138
139 let _ =
140   List.iter
141     (fun (ligature, symbol) -> Hashtbl.add ligatures ligature symbol)
142     [ ("->", <:unicode<to>>);   ("=>", <:unicode<Rightarrow>>);
143       ("<=", <:unicode<leq>>);  (">=", <:unicode<geq>>);
144       ("<>", <:unicode<neq>>);  (":=", <:unicode<def>>);
145       ("==", <:unicode<equiv>>);
146     ]
147
148 let regexp uri_step = [ 'a' - 'z' 'A' - 'Z' '0' - '9' '_' '-' ''' ]+
149
150 let regexp uri =
151   ("cic:/" | "theory:/")              (* schema *)
152 (*   ident ('/' ident)*                  |+ path +| *)
153   uri_step ('/' uri_step)*            (* path *)
154   ('.' ident)+                        (* ext *)
155   ("#xpointer(" number ('/' number)+ ")")?  (* xpointer *)
156
157 let error lexbuf msg =
158   let begin_cnum, end_cnum = Ulexing.loc lexbuf in
159   raise (Error (begin_cnum, end_cnum, msg))
160 let error_at_end lexbuf msg =
161   let begin_cnum, end_cnum = Ulexing.loc lexbuf in
162   raise (Error (begin_cnum, end_cnum, msg))
163
164 let return_with_loc token begin_cnum end_cnum =
165   let flocation = HExtlib.floc_of_loc (begin_cnum,end_cnum) in
166    token, flocation
167
168 let return lexbuf token =
169   let begin_cnum, end_cnum = Ulexing.loc lexbuf in
170     return_with_loc token begin_cnum end_cnum
171
172 let return_lexeme lexbuf name = return lexbuf (name, Ulexing.utf8_lexeme lexbuf)
173
174 let return_symbol lexbuf s = return lexbuf ("SYMBOL", s)
175 let return_eoi lexbuf = return lexbuf ("EOI", "")
176
177 let remove_quotes s = String.sub s 1 (String.length s - 2)
178
179 let mk_lexer token =
180   let tok_func stream =
181 (*     let lexbuf = Ulexing.from_utf8_stream stream in *)
182 (** XXX Obj.magic rationale.
183  * The problem.
184  *  camlp5 constraints the tok_func field of Token.glexer to have type:
185  *    Stream.t char -> (Stream.t 'te * flocation_function)
186  *  In order to use ulex we have (in theory) to instantiate a new lexbuf each
187  *  time a char Stream.t is passed, destroying the previous lexbuf which may
188  *  have consumed a character from the old stream which is lost forever :-(
189  * The "solution".
190  *  Instead of passing to camlp5 a char Stream.t we pass a lexbuf, casting it to
191  *  char Stream.t with Obj.magic where needed.
192  *)
193     let lexbuf = Obj.magic stream in
194     Token.make_stream_and_location
195       (fun () ->
196         try
197           token lexbuf
198         with
199         | Ulexing.Error -> error_at_end lexbuf "Unexpected character"
200         | Ulexing.InvalidCodepoint p ->
201             error_at_end lexbuf (sprintf "Invalid code point: %d" p))
202   in
203   {
204     Token.tok_func = tok_func;
205     Token.tok_using = (fun _ -> ());
206     Token.tok_removing = (fun _ -> ()); 
207     Token.tok_match = Token.default_match;
208     Token.tok_text = Token.lexer_text;
209     Token.tok_comm = None;
210   }
211
212 let expand_macro lexbuf =
213   let macro =
214     Ulexing.utf8_sub_lexeme lexbuf 1 (Ulexing.lexeme_length lexbuf - 1)
215   in
216   try
217     ("SYMBOL", Utf8Macro.expand macro)
218   with Utf8Macro.Macro_not_found _ -> "SYMBOL", Ulexing.utf8_lexeme lexbuf
219
220 let remove_quotes s = String.sub s 1 (String.length s - 2)
221 let remove_left_quote s = String.sub s 1 (String.length s - 1)
222
223 let rec level2_pattern_token_group counter buffer =
224   lexer
225   | end_group -> 
226       if (counter > 0) then
227         Buffer.add_string buffer (Ulexing.utf8_lexeme lexbuf) ;
228       snd (Ulexing.loc lexbuf)
229   | begin_group -> 
230       Buffer.add_string buffer (Ulexing.utf8_lexeme lexbuf) ;
231       ignore (level2_pattern_token_group (counter + 1) buffer lexbuf) ;
232       level2_pattern_token_group counter buffer lexbuf
233   | _ -> 
234       Buffer.add_string buffer (Ulexing.utf8_lexeme lexbuf) ;
235       level2_pattern_token_group counter buffer lexbuf
236
237 let read_unparsed_group token_name lexbuf =
238   let buffer = Buffer.create 16 in
239   let begin_cnum, _ = Ulexing.loc lexbuf in
240   let end_cnum = level2_pattern_token_group 0 buffer lexbuf in
241     return_with_loc (token_name, Buffer.contents buffer) begin_cnum end_cnum
242
243 let rec level2_meta_token =
244   lexer
245   | utf8_blank+ -> level2_meta_token lexbuf
246   | ident ->
247       let s = Ulexing.utf8_lexeme lexbuf in
248         begin
249           if List.mem s level2_meta_keywords then
250             return lexbuf ("", s)
251           else
252             return lexbuf ("IDENT", s)
253         end
254   | "@{" -> read_unparsed_group "UNPARSED_AST" lexbuf
255   | ast_ident ->
256       return lexbuf ("UNPARSED_AST",
257         remove_left_quote (Ulexing.utf8_lexeme lexbuf))
258   | ast_csymbol ->
259       return lexbuf ("UNPARSED_AST",
260         remove_left_quote (Ulexing.utf8_lexeme lexbuf))
261   | eof -> return_eoi lexbuf
262
263 let rec comment_token acc depth =
264   lexer
265   | beginnote ->
266       let acc = acc ^ Ulexing.utf8_lexeme lexbuf in
267       comment_token acc (depth + 1) lexbuf
268   | endcomment ->
269       let acc = acc ^ Ulexing.utf8_lexeme lexbuf in
270       if depth = 0
271       then acc
272       else comment_token acc (depth - 1) lexbuf
273   | _ ->
274       let acc = acc ^ Ulexing.utf8_lexeme lexbuf in
275       comment_token acc depth lexbuf
276
277   (** @param k continuation to be invoked when no ligature has been found *)
278 let rec ligatures_token k =
279   lexer
280   | ligature ->
281       let lexeme = Ulexing.utf8_lexeme lexbuf in
282       (match List.rev (Hashtbl.find_all ligatures lexeme) with
283       | [] -> (* ligature not found, rollback and try default lexer *)
284           Ulexing.rollback lexbuf;
285           k lexbuf
286       | default_lig :: _ -> (* ligatures found, use the default one *)
287           return_symbol lexbuf default_lig)
288   | eof -> return_eoi lexbuf
289   | _ ->  (* not a ligature, rollback and try default lexer *)
290       Ulexing.rollback lexbuf;
291       k lexbuf
292
293 and level2_ast_token =
294   lexer
295   | let_rec -> return lexbuf ("LETREC","")
296   | let_corec -> return lexbuf ("LETCOREC","")
297   | we_proved -> return lexbuf ("WEPROVED","")
298   | we_have -> return lexbuf ("WEHAVE","")
299   | utf8_blank+ -> ligatures_token level2_ast_token lexbuf
300   | meta ->
301      let s = Ulexing.utf8_lexeme lexbuf in
302       return lexbuf ("META", String.sub s 1 (String.length s - 1))
303   | implicit -> return lexbuf ("IMPLICIT", "")
304   | placeholder -> return lexbuf ("PLACEHOLDER", "")
305   | ident ->
306       let lexeme = Ulexing.utf8_lexeme lexbuf in
307       if Hashtbl.mem !level2_ast_keywords lexeme then
308         return lexbuf ("", lexeme)
309       else
310         return lexbuf ("IDENT", lexeme)
311   | number -> return lexbuf ("NUMBER", Ulexing.utf8_lexeme lexbuf)
312   | tex_token -> return lexbuf (expand_macro lexbuf)
313   | uri -> return lexbuf ("URI", Ulexing.utf8_lexeme lexbuf)
314   | qstring ->
315       return lexbuf ("QSTRING", remove_quotes (Ulexing.utf8_lexeme lexbuf))
316   | csymbol ->
317       return lexbuf ("CSYMBOL", remove_left_quote (Ulexing.utf8_lexeme lexbuf))
318   | "${" -> read_unparsed_group "UNPARSED_META" lexbuf
319   | "@{" -> read_unparsed_group "UNPARSED_AST" lexbuf
320   | '(' -> return lexbuf ("LPAREN", "")
321   | ')' -> return lexbuf ("RPAREN", "")
322   | meta_ident ->
323       return lexbuf ("UNPARSED_META",
324         remove_left_quote (Ulexing.utf8_lexeme lexbuf))
325   | meta_anonymous -> return lexbuf ("UNPARSED_META", "anonymous")
326   | beginnote -> 
327       let _comment = comment_token (Ulexing.utf8_lexeme lexbuf) 0 lexbuf in
328 (*       let comment =
329         Ulexing.utf8_sub_lexeme lexbuf 2 (Ulexing.lexeme_length lexbuf - 4)
330       in
331       return lexbuf ("NOTE", comment) *)
332       ligatures_token level2_ast_token lexbuf
333   | begincomment -> return lexbuf ("BEGINCOMMENT","")
334   | endcomment -> return lexbuf ("ENDCOMMENT","")
335   | eof -> return_eoi lexbuf
336   | _ -> return_symbol lexbuf (Ulexing.utf8_lexeme lexbuf)
337
338 and level1_pattern_token =
339   lexer
340   | utf8_blank+ -> ligatures_token level1_pattern_token lexbuf
341   | number -> return lexbuf ("NUMBER", Ulexing.utf8_lexeme lexbuf)
342   | ident ->
343       let s = Ulexing.utf8_lexeme lexbuf in
344         begin
345           if List.mem s level1_keywords then
346             return lexbuf ("", s)
347           else
348             return lexbuf ("IDENT", s)
349         end
350   | color -> return lexbuf ("COLOR", Ulexing.utf8_lexeme lexbuf)
351   | percentage -> 
352       return lexbuf ("PERCENTAGE", Ulexing.utf8_lexeme lexbuf)
353   | floatwithunit -> 
354       return lexbuf ("FLOATWITHUNIT", Ulexing.utf8_lexeme lexbuf)
355   | tex_token -> return lexbuf (expand_macro lexbuf)
356   | qkeyword ->
357       return lexbuf ("QKEYWORD", remove_quotes (Ulexing.utf8_lexeme lexbuf))
358   | '(' -> return lexbuf ("LPAREN", "")
359   | ')' -> return lexbuf ("RPAREN", "")
360   | eof -> return_eoi lexbuf
361   | _ -> return_symbol lexbuf (Ulexing.utf8_lexeme lexbuf)
362
363 let level1_pattern_token = ligatures_token level1_pattern_token
364 let level2_ast_token = ligatures_token level2_ast_token
365
366 (* API implementation *)
367
368 let initial_level1_pattern_lexer () = mk_lexer level1_pattern_token
369 let initial_level2_ast_lexer () = mk_lexer level2_ast_token
370 let initial_level2_meta_lexer () = mk_lexer level2_meta_token
371
372
373 let level1_pattern_lexer_ref = ref (initial_level1_pattern_lexer ())
374 let level2_ast_lexer_ref = ref (initial_level2_ast_lexer ())
375 let level2_meta_lexer_ref = ref (initial_level2_meta_lexer ())
376
377 let level1_pattern_lexer () = !level1_pattern_lexer_ref
378 let level2_ast_lexer () = !level2_ast_lexer_ref
379 let level2_meta_lexer () = !level2_meta_lexer_ref 
380
381 let lookup_ligatures lexeme =
382   try
383     if lexeme.[0] = '\\'
384     then [ Utf8Macro.expand (String.sub lexeme 1 (String.length lexeme - 1)) ]
385     else List.rev (Hashtbl.find_all ligatures lexeme)
386   with Invalid_argument _ | Utf8Macro.Macro_not_found _ -> []
387 ;;
388
389 let history = ref [];;
390
391 let push () =
392   history :=
393     (!level2_ast_keywords,!level1_pattern_lexer_ref,
394      !level2_ast_lexer_ref,!level2_meta_lexer_ref) :: !history;
395   level2_ast_keywords := initial_level2_ast_keywords ();
396   initialize_keywords ();
397   level1_pattern_lexer_ref := initial_level1_pattern_lexer ();
398   level2_ast_lexer_ref := initial_level2_ast_lexer ();
399   level2_meta_lexer_ref := initial_level2_meta_lexer ();
400 ;;
401
402 let pop () =
403   match !history with
404   | [] -> assert false
405   | (kwd,pl,al,ml) :: tl -> 
406       level2_ast_keywords := kwd;
407       level1_pattern_lexer_ref := pl;
408       level2_ast_lexer_ref := al;
409       level2_meta_lexer_ref := ml;
410       history := tl
411 ;;
412