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