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