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