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