]> matita.cs.unibo.it Git - helm.git/blob - components/content_pres/cicNotationLexer.ml
tagged 0.5.0-rc1
[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 ident_decoration = '\'' | '?' | '`'
54 let regexp ident_cont = ident_letter | xml_digit | '_'
55 let regexp ident = ident_letter ident_cont* ident_decoration*
56
57 let regexp tex_token = '\\' ident
58
59 let regexp delim_begin = "\\["
60 let regexp delim_end = "\\]"
61
62 let regexp qkeyword = "'" ident "'"
63
64 let regexp implicit = '?'
65 let regexp placeholder = '%'
66 let regexp meta = implicit number
67
68 let regexp csymbol = '\'' ident
69
70 let regexp begin_group = "@{" | "${"
71 let regexp end_group = '}'
72 let regexp wildcard = "$_"
73 let regexp ast_ident = "@" ident
74 let regexp ast_csymbol = "@" csymbol
75 let regexp meta_ident = "$" ident
76 let regexp meta_anonymous = "$_"
77 let regexp qstring = '"' [^ '"']* '"'
78
79 let regexp begincomment = "(**" utf8_blank
80 let regexp beginnote = "(*"
81 let regexp endcomment = "*)"
82 (* let regexp comment_char = [^'*'] | '*'[^')']
83 let regexp note = "|+" ([^'*'] | "**") comment_char* "+|" *)
84
85 let level1_layouts = 
86   [ "sub"; "sup";
87     "below"; "above";
88     "over"; "atop"; "frac";
89     "sqrt"; "root"
90   ]
91
92 let level1_keywords =
93   [ "hbox"; "hvbox"; "hovbox"; "vbox";
94     "break";
95     "list0"; "list1"; "sep";
96     "opt";
97     "term"; "ident"; "number"
98   ] @ level1_layouts
99
100 let level2_meta_keywords =
101   [ "if"; "then"; "else";
102     "fold"; "left"; "right"; "rec";
103     "fail";
104     "default";
105     "anonymous"; "ident"; "number"; "term"; "fresh"
106   ]
107
108   (* (string, unit) Hashtbl.t, to exploit multiple bindings *)
109 let level2_ast_keywords = Hashtbl.create 23
110 let _ =
111   List.iter (fun k -> Hashtbl.add level2_ast_keywords k ())
112   [ "CProp"; "Prop"; "Type"; "Set"; "let"; "rec"; "corec"; "match";
113   "with"; "in"; "by"; "and"; "to"; "as"; "on"; "return"; "done" ]
114
115 let add_level2_ast_keyword k = Hashtbl.add level2_ast_keywords k ()
116 let remove_level2_ast_keyword k = Hashtbl.remove level2_ast_keywords k
117
118   (* (string, int) Hashtbl.t, with multiple bindings.
119    * int is the unicode codepoint *)
120 let ligatures = Hashtbl.create 23
121 let _ =
122   List.iter
123     (fun (ligature, symbol) -> Hashtbl.add ligatures ligature symbol)
124     [ ("->", <:unicode<to>>);   ("=>", <:unicode<Rightarrow>>);
125       ("<=", <:unicode<leq>>);  (">=", <:unicode<geq>>);
126       ("<>", <:unicode<neq>>);  (":=", <:unicode<def>>);
127       ("==", <:unicode<equiv>>);
128     ]
129
130 let regexp uri_step = [ 'a' - 'z' 'A' - 'Z' '0' - '9' '_' '-' ''' ]+
131
132 let regexp uri =
133   ("cic:/" | "theory:/")              (* schema *)
134 (*   ident ('/' ident)*                  |+ path +| *)
135   uri_step ('/' uri_step)*            (* path *)
136   ('.' ident)+                        (* ext *)
137   ("#xpointer(" number ('/' number)+ ")")?  (* xpointer *)
138
139 let error lexbuf msg =
140   let begin_cnum, end_cnum = Ulexing.loc lexbuf in
141   raise (Error (begin_cnum, end_cnum, msg))
142 let error_at_end lexbuf msg =
143   let begin_cnum, end_cnum = Ulexing.loc lexbuf in
144   raise (Error (begin_cnum, end_cnum, msg))
145
146 let return_with_loc token begin_cnum end_cnum =
147   let flocation = HExtlib.floc_of_loc (begin_cnum,end_cnum) in
148    token, flocation
149
150 let return lexbuf token =
151   let begin_cnum, end_cnum = Ulexing.loc lexbuf in
152     return_with_loc token begin_cnum end_cnum
153
154 let return_lexeme lexbuf name = return lexbuf (name, Ulexing.utf8_lexeme lexbuf)
155
156 let return_symbol lexbuf s = return lexbuf ("SYMBOL", s)
157 let return_eoi lexbuf = return lexbuf ("EOI", "")
158
159 let remove_quotes s = String.sub s 1 (String.length s - 2)
160
161 let mk_lexer token =
162   let tok_func stream =
163 (*     let lexbuf = Ulexing.from_utf8_stream stream in *)
164 (** XXX Obj.magic rationale.
165  * The problem.
166  *  camlp5 constraints the tok_func field of Token.glexer to have type:
167  *    Stream.t char -> (Stream.t 'te * flocation_function)
168  *  In order to use ulex we have (in theory) to instantiate a new lexbuf each
169  *  time a char Stream.t is passed, destroying the previous lexbuf which may
170  *  have consumed a character from the old stream which is lost forever :-(
171  * The "solution".
172  *  Instead of passing to camlp5 a char Stream.t we pass a lexbuf, casting it to
173  *  char Stream.t with Obj.magic where needed.
174  *)
175     let lexbuf = Obj.magic stream in
176     Token.make_stream_and_location
177       (fun () ->
178         try
179           token lexbuf
180         with
181         | Ulexing.Error -> error_at_end lexbuf "Unexpected character"
182         | Ulexing.InvalidCodepoint p ->
183             error_at_end lexbuf (sprintf "Invalid code point: %d" p))
184   in
185   {
186     Token.tok_func = tok_func;
187     Token.tok_using = (fun _ -> ());
188     Token.tok_removing = (fun _ -> ()); 
189     Token.tok_match = Token.default_match;
190     Token.tok_text = Token.lexer_text;
191     Token.tok_comm = None;
192   }
193
194 let expand_macro lexbuf =
195   let macro =
196     Ulexing.utf8_sub_lexeme lexbuf 1 (Ulexing.lexeme_length lexbuf - 1)
197   in
198   try
199     ("SYMBOL", Utf8Macro.expand macro)
200   with Utf8Macro.Macro_not_found _ -> "SYMBOL", Ulexing.utf8_lexeme lexbuf
201
202 let remove_quotes s = String.sub s 1 (String.length s - 2)
203 let remove_left_quote s = String.sub s 1 (String.length s - 1)
204
205 let rec level2_pattern_token_group counter buffer =
206   lexer
207   | end_group -> 
208       if (counter > 0) then
209         Buffer.add_string buffer (Ulexing.utf8_lexeme lexbuf) ;
210       snd (Ulexing.loc lexbuf)
211   | begin_group -> 
212       Buffer.add_string buffer (Ulexing.utf8_lexeme lexbuf) ;
213       ignore (level2_pattern_token_group (counter + 1) buffer lexbuf) ;
214       level2_pattern_token_group counter buffer lexbuf
215   | _ -> 
216       Buffer.add_string buffer (Ulexing.utf8_lexeme lexbuf) ;
217       level2_pattern_token_group counter buffer lexbuf
218
219 let read_unparsed_group token_name lexbuf =
220   let buffer = Buffer.create 16 in
221   let begin_cnum, _ = Ulexing.loc lexbuf in
222   let end_cnum = level2_pattern_token_group 0 buffer lexbuf in
223     return_with_loc (token_name, Buffer.contents buffer) begin_cnum end_cnum
224
225 let rec level2_meta_token =
226   lexer
227   | utf8_blank+ -> level2_meta_token lexbuf
228   | ident ->
229       let s = Ulexing.utf8_lexeme lexbuf in
230         begin
231           if List.mem s level2_meta_keywords then
232             return lexbuf ("", s)
233           else
234             return lexbuf ("IDENT", s)
235         end
236   | "@{" -> read_unparsed_group "UNPARSED_AST" lexbuf
237   | ast_ident ->
238       return lexbuf ("UNPARSED_AST",
239         remove_left_quote (Ulexing.utf8_lexeme lexbuf))
240   | ast_csymbol ->
241       return lexbuf ("UNPARSED_AST",
242         remove_left_quote (Ulexing.utf8_lexeme lexbuf))
243   | eof -> return_eoi lexbuf
244
245 let rec comment_token acc depth =
246   lexer
247   | beginnote ->
248       let acc = acc ^ Ulexing.utf8_lexeme lexbuf in
249       comment_token acc (depth + 1) lexbuf
250   | endcomment ->
251       let acc = acc ^ Ulexing.utf8_lexeme lexbuf in
252       if depth = 0
253       then acc
254       else comment_token acc (depth - 1) lexbuf
255   | _ ->
256       let acc = acc ^ Ulexing.utf8_lexeme lexbuf in
257       comment_token acc depth lexbuf
258
259   (** @param k continuation to be invoked when no ligature has been found *)
260 let rec ligatures_token k =
261   lexer
262   | ligature ->
263       let lexeme = Ulexing.utf8_lexeme lexbuf in
264       (match List.rev (Hashtbl.find_all ligatures lexeme) with
265       | [] -> (* ligature not found, rollback and try default lexer *)
266           Ulexing.rollback lexbuf;
267           k lexbuf
268       | default_lig :: _ -> (* ligatures found, use the default one *)
269           return_symbol lexbuf default_lig)
270   | eof -> return_eoi lexbuf
271   | _ ->  (* not a ligature, rollback and try default lexer *)
272       Ulexing.rollback lexbuf;
273       k lexbuf
274
275 and level2_ast_token =
276   lexer
277   | utf8_blank+ -> ligatures_token level2_ast_token lexbuf
278   | meta ->
279      let s = Ulexing.utf8_lexeme lexbuf in
280       return lexbuf ("META", String.sub s 1 (String.length s - 1))
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   | utf8_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 _ -> []
351