]> matita.cs.unibo.it Git - helm.git/blob - matita/components/content_pres/cicNotationLexer.ml
big change in parsing, trying to make all functional
[helm.git] / matita / 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 module StringSet = Set.Make(String)
33
34 (* Lexer *)
35 let regexp number = xml_digit+
36 let regexp utf8_blank = " " | "\r\n" | "\n" | "\t" | [160] (* this is a nbsp *)
37 let regexp percentage = 
38   ('-' | "") [ '0' - '9' ] + '%'
39 let regexp floatwithunit = 
40   ('-' | "") [ '0' - '9' ] + ["."] [ '0' - '9' ] + ([ 'a' - 'z' ] + | "" )
41 let regexp color = "#" [ '0' - '9' 'a' - 'f' 'A' - 'F' ] [ '0' - '9' 'a' - 'f'
42 'A' - 'F' ] [ '0' - '9' 'a' - 'f' 'A' - 'F' ] [ '0' - '9' 'a' - 'f' 'A' - 'F' ]
43 [ '0' - '9' 'a' - 'f' 'A' - 'F' ] [ '0' - '9' 'a' - 'f' 'A' - 'F' ]
44
45   (* ZACK: breaks unicode's binder followed by an ascii letter without blank *)
46 (* let regexp ident_letter = xml_letter *)
47
48 let regexp ident_letter = [ 'a' - 'z' 'A' - 'Z' ]
49
50   (* must be in sync with "is_ligature_char" below *)
51 let regexp ligature_char = [ "'`~!?@*()[]<>-+=|:;.,/\"" ]
52 let regexp ligature = ligature_char ligature_char+
53
54 let regexp we_proved = "we" utf8_blank+ "proved"
55 let regexp we_have = "we" utf8_blank+ "have"
56 let regexp let_rec = "let" utf8_blank+ "rec" 
57 let regexp let_corec = "let" utf8_blank+  "corec"
58 let regexp ident_decoration = '\'' | '?' | '`'
59 let regexp ident_cont = ident_letter | xml_digit | '_'
60 let regexp ident_start = ident_letter 
61 let regexp ident = ident_letter ident_cont* ident_decoration* 
62 let regexp variable_ident = '_' '_' number
63 let regexp pident = '_' ident
64
65 let regexp tex_token = '\\' ident
66
67 let regexp delim_begin = "\\["
68 let regexp delim_end = "\\]"
69
70 let regexp qkeyword = "'" ( ident | pident ) "'"
71
72 let regexp implicit = '?'
73 let regexp placeholder = '%'
74 let regexp meta = implicit number
75
76 let regexp csymbol = '\'' ident
77
78 let regexp begin_group = "@{" | "${"
79 let regexp end_group = '}'
80 let regexp wildcard = "$_"
81 let regexp ast_ident = "@" ident
82 let regexp ast_csymbol = "@" csymbol
83 let regexp meta_ident = "$" ident
84 let regexp meta_anonymous = "$_"
85 let regexp qstring = '"' [^ '"']* '"'
86
87 let regexp begincomment = "(**" utf8_blank
88 let regexp beginnote = "(*"
89 let regexp endcomment = "*)"
90 (* let regexp comment_char = [^'*'] | '*'[^')']
91 let regexp note = "|+" ([^'*'] | "**") comment_char* "+|" *)
92
93 let level1_layouts = 
94   [ "sub"; "sup";
95     "below"; "above";
96     "over"; "atop"; "frac";
97     "sqrt"; "root"; "mstyle" ; "mpadded"; "maction"
98
99   ]
100
101 let level1_keywords =
102   [ "hbox"; "hvbox"; "hovbox"; "vbox";
103     "break";
104     "list0"; "list1"; "sep";
105     "opt";
106     "term"; "ident"; "number";
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, int) Hashtbl.t, with multiple bindings.
118    * int is the unicode codepoint *)
119 let ligatures = Hashtbl.create 23
120
121 let _ =
122   List.iter
123     (fun (ligature, symbol) -> Hashtbl.add ligatures ligature symbol)
124     [ ("->", <:unicode<to>>);   ("=>", <:unicode<Rightarrow>>);
125       (":=", <:unicode<def>>);
126     ]
127
128 let regexp uri_step = [ 'a' - 'z' 'A' - 'Z' '0' - '9' '_' '-' ''' ]+
129
130 let regexp uri =
131   ("cic:/" | "theory:/")              (* schema *)
132 (*   ident ('/' ident)*                  |+ path +| *)
133   uri_step ('/' uri_step)*            (* path *)
134   ('.' ident)+                        (* ext *)
135   ("#xpointer(" number ('/' number)+ ")")?  (* xpointer *)
136
137 let regexp nreference =
138   "cic:/"                             (* schema *)
139   uri_step ('/' uri_step)*            (* path *)
140   '.'
141   ( "dec"
142   | "def" "(" number ")"
143   | "fix" "(" number "," number "," number ")"
144   | "cfx" "(" number ")"
145   | "ind" "(" number "," number "," number ")"
146   | "con" "(" number "," number "," number ")") (* ext + reference *)
147
148 let error lexbuf msg =
149   let begin_cnum, end_cnum = Ulexing.loc lexbuf in
150   raise (Error (begin_cnum, end_cnum, msg))
151 let error_at_end lexbuf msg =
152   let begin_cnum, end_cnum = Ulexing.loc lexbuf in
153   raise (Error (begin_cnum, end_cnum, msg))
154
155 let return_with_loc token begin_cnum end_cnum =
156   let flocation = HExtlib.floc_of_loc (begin_cnum,end_cnum) in
157    token, flocation
158
159 let return lexbuf token =
160   let begin_cnum, end_cnum = Ulexing.loc lexbuf in
161     return_with_loc token begin_cnum end_cnum
162
163 let return_lexeme lexbuf name = return lexbuf (name, Ulexing.utf8_lexeme lexbuf)
164
165 let return_symbol lexbuf s = return lexbuf ("SYMBOL", s)
166 let return_eoi lexbuf = return lexbuf ("EOI", "")
167
168 let remove_quotes s = String.sub s 1 (String.length s - 2)
169
170 let mk_lexer token =
171   let tok_func stream =
172 (*     let lexbuf = Ulexing.from_utf8_stream stream in *)
173 (** XXX Obj.magic rationale.
174  * The problem.
175  *  camlp5 constraints the tok_func field of Token.glexer to have type:
176  *    Stream.t char -> (Stream.t 'te * flocation_function)
177  *  In order to use ulex we have (in theory) to instantiate a new lexbuf each
178  *  time a char Stream.t is passed, destroying the previous lexbuf which may
179  *  have consumed a character from the old stream which is lost forever :-(
180  * The "solution".
181  *  Instead of passing to camlp5 a char Stream.t we pass a lexbuf, casting it to
182  *  char Stream.t with Obj.magic where needed.
183  *)
184     let lexbuf = Obj.magic stream in
185     Token.make_stream_and_location
186       (fun () ->
187         try
188           token lexbuf
189         with
190         | Ulexing.Error -> error_at_end lexbuf "Unexpected character"
191         | Ulexing.InvalidCodepoint p ->
192             error_at_end lexbuf (sprintf "Invalid code point: %d" p))
193   in
194   {
195     Token.tok_func = tok_func;
196     Token.tok_using = (fun _ -> ());
197     Token.tok_removing = (fun _ -> ()); 
198     Token.tok_match = Token.default_match;
199     Token.tok_text = Token.lexer_text;
200     Token.tok_comm = None;
201   }
202
203 let expand_macro lexbuf =
204   let macro =
205     Ulexing.utf8_sub_lexeme lexbuf 1 (Ulexing.lexeme_length lexbuf - 1)
206   in
207   try
208     ("SYMBOL", Utf8Macro.expand macro)
209   with Utf8Macro.Macro_not_found _ -> 
210 (* FG: unexpanded TeX macros are terminated by a space for rendering *)     
211      "SYMBOL", (Ulexing.utf8_lexeme lexbuf ^ " ")
212
213 let remove_quotes s = String.sub s 1 (String.length s - 2)
214 let remove_left_quote s = String.sub s 1 (String.length s - 1)
215
216 let rec level2_pattern_token_group counter buffer =
217   lexer
218   | end_group -> 
219       if (counter > 0) then
220         Buffer.add_string buffer (Ulexing.utf8_lexeme lexbuf) ;
221       snd (Ulexing.loc lexbuf)
222   | begin_group -> 
223       Buffer.add_string buffer (Ulexing.utf8_lexeme lexbuf) ;
224       ignore (level2_pattern_token_group (counter + 1) buffer lexbuf) ;
225       level2_pattern_token_group counter buffer lexbuf
226   | _ -> 
227       Buffer.add_string buffer (Ulexing.utf8_lexeme lexbuf) ;
228       level2_pattern_token_group counter buffer lexbuf
229
230 let read_unparsed_group token_name lexbuf =
231   let buffer = Buffer.create 16 in
232   let begin_cnum, _ = Ulexing.loc lexbuf in
233   let end_cnum = level2_pattern_token_group 0 buffer lexbuf in
234     return_with_loc (token_name, Buffer.contents buffer) begin_cnum end_cnum
235
236 let handle_keywords lexbuf k name = 
237   let s = Ulexing.utf8_lexeme lexbuf in
238   if k s then
239             return lexbuf ("", s)
240           else
241             return lexbuf (name, s)
242 ;;
243
244 let rec level2_meta_token =
245   lexer
246   | utf8_blank+ -> level2_meta_token lexbuf
247   | ident ->
248       handle_keywords lexbuf (fun x -> List.mem x level2_meta_keywords) "IDENT"
249   | variable_ident -> return lexbuf ("IDENT", Ulexing.utf8_lexeme lexbuf)
250   | pident ->
251       handle_keywords lexbuf (fun x -> List.mem x level2_meta_keywords) "PIDENT"
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 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 let rec level2_ast_token status =
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 status) 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 -> handle_keywords lexbuf (fun x -> StringSet.mem x status) "IDENT"
304   | variable_ident -> return lexbuf ("IDENT", Ulexing.utf8_lexeme lexbuf)
305   | pident -> handle_keywords lexbuf (fun x -> StringSet.mem x status) "PIDENT"
306   | number -> return lexbuf ("NUMBER", Ulexing.utf8_lexeme lexbuf)
307   | tex_token -> return lexbuf (expand_macro lexbuf)
308   | nreference -> return lexbuf ("NREF", Ulexing.utf8_lexeme lexbuf)
309   | uri -> return lexbuf ("URI", Ulexing.utf8_lexeme lexbuf)
310   | qstring ->
311       return lexbuf ("QSTRING", remove_quotes (Ulexing.utf8_lexeme lexbuf))
312   | csymbol ->
313       return lexbuf ("CSYMBOL", remove_left_quote (Ulexing.utf8_lexeme lexbuf))
314   | "${" -> read_unparsed_group "UNPARSED_META" lexbuf
315   | "@{" -> read_unparsed_group "UNPARSED_AST" lexbuf
316   | '(' -> return lexbuf ("LPAREN", "")
317   | ')' -> return lexbuf ("RPAREN", "")
318   | meta_ident ->
319       return lexbuf ("UNPARSED_META",
320         remove_left_quote (Ulexing.utf8_lexeme lexbuf))
321   | meta_anonymous -> return lexbuf ("UNPARSED_META", "anonymous")
322   | beginnote -> 
323       let _comment = comment_token (Ulexing.utf8_lexeme lexbuf) 0 lexbuf in
324 (*       let comment =
325         Ulexing.utf8_sub_lexeme lexbuf 2 (Ulexing.lexeme_length lexbuf - 4)
326       in
327       return lexbuf ("NOTE", comment) *)
328       ligatures_token (level2_ast_token status) lexbuf
329   | begincomment -> return lexbuf ("BEGINCOMMENT","")
330   | endcomment -> return lexbuf ("ENDCOMMENT","")
331   | eof -> return_eoi lexbuf
332   | _ -> return_symbol lexbuf (Ulexing.utf8_lexeme lexbuf)
333
334 and level1_pattern_token =
335   lexer
336   | utf8_blank+ -> ligatures_token level1_pattern_token lexbuf
337   | number -> return lexbuf ("NUMBER", Ulexing.utf8_lexeme lexbuf)
338   | ident ->handle_keywords lexbuf (fun x -> List.mem x level1_keywords) "IDENT"
339   | variable_ident -> return lexbuf ("IDENT", Ulexing.utf8_lexeme lexbuf)
340   | pident->handle_keywords lexbuf (fun x->List.mem x level1_keywords) "PIDENT" 
341   | color -> return lexbuf ("COLOR", Ulexing.utf8_lexeme lexbuf)
342   | percentage -> 
343       return lexbuf ("PERCENTAGE", Ulexing.utf8_lexeme lexbuf)
344   | floatwithunit -> 
345       return lexbuf ("FLOATWITHUNIT", Ulexing.utf8_lexeme lexbuf)
346   | tex_token -> return lexbuf (expand_macro lexbuf)
347   | qkeyword ->
348       return lexbuf ("QKEYWORD", remove_quotes (Ulexing.utf8_lexeme lexbuf))
349   | '(' -> return lexbuf ("LPAREN", "")
350   | ')' -> return lexbuf ("RPAREN", "")
351   | eof -> return_eoi lexbuf
352   | _ -> return_symbol lexbuf (Ulexing.utf8_lexeme lexbuf)
353
354 let level1_pattern_token = ligatures_token level1_pattern_token
355 let level2_ast_token status = ligatures_token (level2_ast_token status)
356
357 (* API implementation *)
358 type lexers = {
359         level1_pattern_lexer : (string * string) Token.glexer;
360         level2_ast_lexer : (string * string) Token.glexer;
361         level2_meta_lexer : (string * string) Token.glexer
362 }
363
364 let mk_lexers keywords = 
365   let initial_keywords = 
366    [ "CProp"; "Prop"; "Type"; "Set"; "let"; "match";
367    "with"; "in"; "and"; "to"; "as"; "on"; "return"; "done" ]
368   in
369   let status = 
370     List.fold_right StringSet.add (initial_keywords @ keywords) StringSet.empty 
371   in 
372   {
373         level1_pattern_lexer = mk_lexer level1_pattern_token;
374         level2_ast_lexer = mk_lexer (level2_ast_token status);
375         level2_meta_lexer = mk_lexer level2_meta_token
376   }
377 ;;