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