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