]> matita.cs.unibo.it Git - helm.git/blob - matitaB/components/content_pres/cicNotationLexer.ml
ce8fcec54b9fba727c1f97c40c6c203029946f72
[helm.git] / matitaB / 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 uri_step = [ 'a' - 'z' 'A' - 'Z' '0' - '9' '_' '-' ''' ]+
66
67 let regexp uri =
68   ("cic:/" | "theory:/")              (* schema *)
69 (*   ident ('/' ident)*                  |+ path +| *)
70   uri_step ('/' uri_step)*            (* path *)
71   ('.' ident)+                        (* ext *)
72 (*  ("#xpointer(" number ('/' number)+ ")")?  (* xpointer *) *)
73   ("(" number (',' number)* ")")?  (* reference spec *)
74
75 let regexp qstring = '"' [^ '"']* '"'
76 let regexp hreftag = "<" [ 'A' 'a' ]
77 let regexp href = "href=\"" uri "\""
78 let regexp hreftitle = "title=" qstring
79 let regexp hrefclose = "</" [ 'A' 'a' ] ">"
80
81 let regexp tex_token = '\\' ident
82
83 let regexp delim_begin = "\\["
84 let regexp delim_end = "\\]"
85
86 let regexp qkeyword = "'" ( ident | pident ) "'"
87
88 let regexp implicit = '?'
89 let regexp placeholder = '%'
90 let regexp meta = implicit number
91
92 let regexp csymbol = '\'' ident
93
94 let regexp begin_group = "@{" | "${"
95 let regexp end_group = '}'
96 let regexp wildcard = "$_"
97 let regexp ast_ident = "@" ident
98 let regexp ast_csymbol = "@" csymbol
99 let regexp meta_ident = "$" ident
100 let regexp meta_anonymous = "$_"
101
102 let regexp begincomment = "(**" utf8_blank
103 let regexp beginnote = "(*"
104 let regexp endcomment = "*)"
105 (* let regexp comment_char = [^'*'] | '*'[^')']
106 let regexp note = "|+" ([^'*'] | "**") comment_char* "+|" *)
107
108 let level1_layouts = 
109   [ "sub"; "sup";
110     "below"; "above";
111     "over"; "atop"; "frac";
112     "sqrt"; "root"; "mstyle" ; "mpadded"; "maction"
113
114   ]
115
116 let level1_keywords =
117   [ "hbox"; "hvbox"; "hovbox"; "vbox";
118     "break";
119     "list0"; "list1"; "sep";
120     "opt";
121     "term"; "ident"; "number";
122   ] @ level1_layouts
123
124 let level2_meta_keywords =
125   [ "if"; "then"; "elCicNotationParser.se";
126     "fold"; "left"; "right"; "rec";
127     "fail";
128     "default";
129     "anonymous"; "ident"; "number"; "term"; "fresh"
130   ]
131
132   (* (string, int) Hashtbl.t, with multiple bindings.
133    * int is the unicode codepoint *)
134 let ligatures = Hashtbl.create 23
135
136 let _ =
137   List.iter
138     (fun (ligature, symbol) -> Hashtbl.add ligatures ligature symbol)
139     [ ("->", <:unicode<to>>);   ("=>", <:unicode<Rightarrow>>);
140       (":=", <:unicode<def>>);
141     ]
142
143 let regexp nreference =
144   "cic:/"                             (* schema *)
145   uri_step ('/' uri_step)*            (* path *)
146   '.'
147   ( "dec"
148   | "def" "(" number ")"
149   | "fix" "(" number "," number "," number ")"
150   | "cfx" "(" number ")"
151   | "ind" "(" number "," number "," number ")"
152   | "con" "(" number "," number "," number ")") (* ext + reference *)
153
154 let error lexbuf msg =
155   let begin_cnum, end_cnum = Ulexing.loc lexbuf in
156   raise (Error (begin_cnum, end_cnum, msg))
157 let error_at_end lexbuf msg =
158   let begin_cnum, end_cnum = Ulexing.loc lexbuf in
159   raise (Error (begin_cnum, end_cnum, msg))
160
161 let loc_of_buf lexbuf = 
162   HExtlib.floc_of_loc (Ulexing.loc lexbuf)
163
164 let return_with_loc token begin_cnum end_cnum =
165   let flocation = HExtlib.floc_of_loc (begin_cnum,end_cnum) in
166    token, flocation
167
168 let return lexbuf token =
169   let begin_cnum, end_cnum = Ulexing.loc lexbuf in
170     return_with_loc token begin_cnum end_cnum
171
172 let return_lexeme lexbuf name = return lexbuf (name, Ulexing.utf8_lexeme lexbuf)
173
174 let return_symbol lexbuf s = return lexbuf ("SYMBOL", s)
175 let return_eoi lexbuf = return lexbuf ("EOI", "")
176
177 let remove_quotes s = String.sub s 1 (String.length s - 2)
178
179 let mk_lexer token =
180   let tok_func stream =
181 (*     let lexbuf = Ulexing.from_utf8_stream stream in *)
182 (** XXX Obj.magic rationale.
183  * The problem.
184  *  camlp5 constraints the tok_func field of Token.glexer to have type:
185  *    Stream.t char -> (Stream.t 'te * flocation_function)
186  *  In order to use ulex we have (in theory) to instantiate a new lexbuf each
187  *  time a char Stream.t is passed, destroying the previous lexbuf which may
188  *  have consumed a character from the old stream which is lost forever :-(
189  * The "solution".
190  *  Instead of passing to camlp5 a char Stream.t we pass a lexbuf, casting it to
191  *  char Stream.t with Obj.magic where needed.
192  *)
193     let lexbuf = Obj.magic stream in
194     Token.make_stream_and_location
195       (fun () ->
196         try
197           token lexbuf
198         with
199         | Ulexing.Error -> error_at_end lexbuf "Unexpected character"
200         | Ulexing.InvalidCodepoint p ->
201             error_at_end lexbuf (sprintf "Invalid code point: %d" p))
202   in
203   {
204     Token.tok_func = tok_func;
205     Token.tok_using = (fun _ -> ());
206     Token.tok_removing = (fun _ -> ()); 
207     Token.tok_match = Token.default_match;
208     Token.tok_text = Token.lexer_text;
209     Token.tok_comm = None;
210   }
211
212 let expand_macro lexbuf =
213   let macro =
214     Ulexing.utf8_sub_lexeme lexbuf 1 (Ulexing.lexeme_length lexbuf - 1)
215   in
216   try
217     ("SYMBOL", Utf8Macro.expand macro)
218   with Utf8Macro.Macro_not_found _ -> 
219 (* FG: unexpanded TeX macros are terminated by a space for rendering *)     
220      "SYMBOL", (Ulexing.utf8_lexeme lexbuf ^ " ")
221
222 let remove_quotes s = String.sub s 1 (String.length s - 2)
223 let remove_left_quote s = String.sub s 1 (String.length s - 1)
224
225 let rec level2_pattern_token_group counter buffer =
226   lexer
227   | end_group -> 
228       if (counter > 0) then
229         Buffer.add_string buffer (Ulexing.utf8_lexeme lexbuf) ;
230       snd (Ulexing.loc lexbuf)
231   | begin_group -> 
232       Buffer.add_string buffer (Ulexing.utf8_lexeme lexbuf) ;
233       ignore (level2_pattern_token_group (counter + 1) buffer lexbuf) ;
234       level2_pattern_token_group counter buffer lexbuf
235   | _ -> 
236       Buffer.add_string buffer (Ulexing.utf8_lexeme lexbuf) ;
237       level2_pattern_token_group counter buffer lexbuf
238
239 let read_unparsed_group token_name lexbuf =
240   let buffer = Buffer.create 16 in
241   let begin_cnum, _ = Ulexing.loc lexbuf in
242   let end_cnum = level2_pattern_token_group 0 buffer lexbuf in
243     return_with_loc (token_name, Buffer.contents buffer) begin_cnum end_cnum
244
245 let handle_keywords lexbuf k name = 
246   let s = Ulexing.utf8_lexeme lexbuf in
247   if k s then
248             return lexbuf ("", s)
249           else
250             return lexbuf (name, s)
251 ;;
252
253 let rec level2_meta_token =
254   lexer
255   | utf8_blank+ -> level2_meta_token lexbuf
256   | hreftag -> return lexbuf ("ATAG","")
257   | hrefclose -> return lexbuf ("ATAGEND","")
258   | ident ->
259       handle_keywords lexbuf (fun x -> List.mem x level2_meta_keywords) "IDENT"
260   | variable_ident -> return lexbuf ("IDENT", Ulexing.utf8_lexeme lexbuf)
261   | pident ->
262       handle_keywords lexbuf (fun x -> List.mem x level2_meta_keywords) "PIDENT"
263   | "@{" -> read_unparsed_group "UNPARSED_AST" lexbuf
264   | ast_ident ->
265       return lexbuf ("UNPARSED_AST",
266         remove_left_quote (Ulexing.utf8_lexeme lexbuf))
267   | ast_csymbol ->
268       return lexbuf ("UNPARSED_AST",
269         remove_left_quote (Ulexing.utf8_lexeme lexbuf))
270   | eof -> return_eoi lexbuf
271
272 let rec comment_token acc depth =
273   lexer
274   | beginnote ->
275       let acc = acc ^ Ulexing.utf8_lexeme lexbuf in
276       comment_token acc (depth + 1) lexbuf
277   | endcomment ->
278       let acc = acc ^ Ulexing.utf8_lexeme lexbuf in
279       if depth = 0
280       then acc
281       else comment_token acc (depth - 1) lexbuf
282   | _ ->
283       let acc = acc ^ Ulexing.utf8_lexeme lexbuf in
284       comment_token acc depth lexbuf
285
286   (** @param k continuation to be invoked when no ligature has been found *)
287 let ligatures_token k =
288   lexer
289   | ligature ->
290       let lexeme = Ulexing.utf8_lexeme lexbuf in
291       (match List.rev (Hashtbl.find_all ligatures lexeme) with
292       | [] -> (* ligature not found, rollback and try default lexer *)
293           Ulexing.rollback lexbuf;
294           k lexbuf
295       | default_lig :: _ -> (* ligatures found, use the default one *)
296           return_symbol lexbuf default_lig)
297   | eof -> return_eoi lexbuf
298   | _ ->  (* not a ligature, rollback and try default lexer *)
299       Ulexing.rollback lexbuf;
300       k lexbuf
301
302 module LocalizeOD =
303   struct
304     type t = Stdpp.location
305     let compare = Pervasives.compare
306   end
307
308 module LocalizeEnv = Map.Make (LocalizeOD)
309
310 let so_pp = function
311  | None -> "()"
312  | Some s -> "*" ^ s
313 ;;
314
315 let update_table loc desc href loctable =
316   if desc <> None || href <> None 
317     then 
318      (let s,e = HExtlib.loc_of_floc loc in
319       prerr_endline (Printf.sprintf "*** [%d,%d] \"%s\",\"%s\""
320         s e (so_pp href) (so_pp desc));
321       LocalizeEnv.add loc (href,desc) loctable)
322     else loctable
323 ;;
324
325 let level2_ast_token loctable status =
326   let rec aux desc href =
327     lexer
328     | let_rec -> return lexbuf ("LETREC","")
329     | let_corec -> return lexbuf ("LETCOREC","")
330     | we_proved -> return lexbuf ("WEPROVED","")
331     | we_have -> return lexbuf ("WEHAVE","")
332     | utf8_blank+ -> ligatures_token (aux desc href) lexbuf
333     | meta ->
334        let s = Ulexing.utf8_lexeme lexbuf in
335         return lexbuf ("META", String.sub s 1 (String.length s - 1))
336     | implicit -> return lexbuf ("IMPLICIT", "")
337     | placeholder -> return lexbuf ("PLACEHOLDER", "")
338     | hreftag -> aux_in_tag None None lexbuf
339     | hrefclose -> aux None None lexbuf
340     | ident -> loctable := 
341                  update_table (loc_of_buf lexbuf) desc href !loctable;
342                handle_keywords lexbuf (fun x -> StringSet.mem x status) "IDENT"
343     | variable_ident -> 
344                return lexbuf ("IDENT", Ulexing.utf8_lexeme lexbuf)
345     | pident -> loctable :=
346                   update_table (loc_of_buf lexbuf) desc href !loctable;
347                 handle_keywords lexbuf (fun x -> StringSet.mem x status) "PIDENT"
348     | number -> loctable := 
349                   update_table (loc_of_buf lexbuf) desc href !loctable;
350                 return lexbuf ("NUMBER", Ulexing.utf8_lexeme lexbuf)
351     | tex_token -> loctable := 
352                      update_table (loc_of_buf lexbuf) desc href !loctable;
353                    return lexbuf (expand_macro lexbuf)
354     | nreference -> return lexbuf ("NREF", Ulexing.utf8_lexeme lexbuf)
355     | uri -> return lexbuf ("URI", Ulexing.utf8_lexeme lexbuf)
356     | qstring ->
357         return lexbuf ("QSTRING", remove_quotes (Ulexing.utf8_lexeme lexbuf))
358     | csymbol ->
359         return lexbuf ("CSYMBOL", remove_left_quote (Ulexing.utf8_lexeme lexbuf))
360     | "${" -> read_unparsed_group "UNPARSED_META" lexbuf
361     | "@{" -> read_unparsed_group "UNPARSED_AST" lexbuf
362     | '(' -> return lexbuf ("LPAREN", "")
363     | ')' -> return lexbuf ("RPAREN", "")
364     | meta_ident ->
365         return lexbuf ("UNPARSED_META",
366           remove_left_quote (Ulexing.utf8_lexeme lexbuf))
367     | meta_anonymous -> return lexbuf ("UNPARSED_META", "anonymous")
368     | beginnote -> 
369         let _comment = comment_token (Ulexing.utf8_lexeme lexbuf) 0 lexbuf in
370   (*       let comment =
371           Ulexing.utf8_sub_lexeme lexbuf 2 (Ulexing.lexeme_length lexbuf - 4)
372         in
373         return lexbuf ("NOTE", comment) *)
374         ligatures_token (aux desc href) lexbuf
375     | begincomment -> return lexbuf ("BEGINCOMMENT","")
376     | endcomment -> return lexbuf ("ENDCOMMENT","")
377     | eof -> return_eoi lexbuf
378     | _ -> loctable := 
379              update_table (loc_of_buf lexbuf) desc href !loctable;
380            return_symbol lexbuf (Ulexing.utf8_lexeme lexbuf)
381
382   and aux_in_tag desc href = lexer
383     | utf8_blank+ -> ligatures_token (aux_in_tag desc href) lexbuf
384     | href -> 
385         aux_in_tag desc 
386           (Some (Ulexing.utf8_sub_lexeme lexbuf 6 (Ulexing.lexeme_length lexbuf - 7))) 
387           lexbuf
388     | hreftitle -> 
389         aux_in_tag 
390           (Some (Ulexing.utf8_sub_lexeme lexbuf 7 (Ulexing.lexeme_length lexbuf - 8))) 
391           href lexbuf
392     | ">" -> aux desc href lexbuf
393     | _ -> aux None None lexbuf
394   in aux None None 
395
396 let rec level1_pattern_token =
397   lexer
398   | utf8_blank+ -> ligatures_token level1_pattern_token lexbuf
399   | number -> return lexbuf ("NUMBER", Ulexing.utf8_lexeme lexbuf)
400   | hreftag -> return lexbuf ("ATAG", "")
401   | hrefclose -> return lexbuf ("ATAGEND","")
402   | ident ->handle_keywords lexbuf (fun x -> List.mem x level1_keywords) "IDENT"
403   | variable_ident -> return lexbuf ("IDENT", Ulexing.utf8_lexeme lexbuf)
404   | pident->handle_keywords lexbuf (fun x->List.mem x level1_keywords) "PIDENT" 
405   | color -> return lexbuf ("COLOR", Ulexing.utf8_lexeme lexbuf)
406   | percentage -> 
407       return lexbuf ("PERCENTAGE", Ulexing.utf8_lexeme lexbuf)
408   | floatwithunit -> 
409       return lexbuf ("FLOATWITHUNIT", Ulexing.utf8_lexeme lexbuf)
410   | tex_token -> return lexbuf (expand_macro lexbuf)
411   | qkeyword ->
412       return lexbuf ("QKEYWORD", remove_quotes (Ulexing.utf8_lexeme lexbuf))
413   | '(' -> return lexbuf ("LPAREN", "")
414   | ')' -> return lexbuf ("RPAREN", "")
415   | eof -> return_eoi lexbuf
416   | _ -> return_symbol lexbuf (Ulexing.utf8_lexeme lexbuf)
417
418 let level1_pattern_token = ligatures_token level1_pattern_token
419 let level2_ast_token loctable status = 
420   ligatures_token (level2_ast_token loctable status)
421
422 (* API implementation *)
423 type lexers = {
424         level1_pattern_lexer : (string * string) Token.glexer;
425         level2_ast_lexer : (string * string) Token.glexer;
426         level2_meta_lexer : (string * string) Token.glexer
427 }
428
429 let mk_lexers loctable keywords = 
430   let initial_keywords = 
431    [ "CProp"; "Prop"; "Type"; "Set"; "let"; "match";
432    "with"; "in"; "and"; "to"; "as"; "on"; "return"; "done" ]
433   in
434   let status = 
435     List.fold_right StringSet.add (initial_keywords @ keywords) StringSet.empty 
436   in 
437   {
438         level1_pattern_lexer = mk_lexer level1_pattern_token;
439         level2_ast_lexer = mk_lexer (level2_ast_token loctable status);
440         level2_meta_lexer = mk_lexer level2_meta_token
441   }
442 ;;