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