]> matita.cs.unibo.it Git - helm.git/blob - matita/components/content_pres/cicNotationPres.ml
Most warnings turned into errors and avoided
[helm.git] / matita / components / content_pres / cicNotationPres.ml
1 (* Copyright (C) 2004-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 module Ast = NotationPt
29 module Mpres = Mpresentation
30
31 type mathml_markup = boxml_markup Mpres.mpres
32 and boxml_markup = mathml_markup Box.box
33
34 type markup = mathml_markup
35
36 let atop_attributes = [None, "linethickness", "0pt"]
37
38 let to_unicode = Utf8Macro.unicode_of_tex
39
40 let rec make_attributes l1 = function
41   | [] -> []
42   | hd :: tl ->
43       (match hd with
44       | None -> make_attributes (List.tl l1) tl
45       | Some s ->
46           let p,n = List.hd l1 in
47           (p,n,s) :: make_attributes (List.tl l1) tl)
48
49 let box_of_mpres =
50   function
51   | Mpresentation.Mobject (attrs, box) ->
52       assert (attrs = []);
53       box
54   | mpres -> Box.Object ([], mpres)
55
56 let mpres_of_box =
57   function
58   | Box.Object (attrs, mpres) ->
59       assert (attrs = []);
60       mpres
61   | box -> Mpresentation.Mobject ([], box)
62
63 let rec genuine_math =
64   function
65   | Mpresentation.Mobject ([], obj) -> not (genuine_box obj)
66   | _ -> true
67 and genuine_box =
68   function
69   | Box.Object ([], mpres) -> not (genuine_math mpres)
70   | _ -> true
71
72 let rec eligible_math =
73   function
74   | Mpresentation.Mobject ([], Box.Object ([], mpres)) -> eligible_math mpres
75   | Mpresentation.Mobject ([], _) -> false
76   | _ -> true
77
78 let rec promote_to_math =
79   function
80   | Mpresentation.Mobject ([], Box.Object ([], mpres)) -> promote_to_math mpres
81   | math -> math
82
83 let small_skip =
84   Mpresentation.Mspace (RenderingAttrs.small_skip_attributes `MathML)
85
86 let rec add_mpres_attributes new_attr = function
87   | Mpresentation.Mobject (attr, box) ->
88       Mpresentation.Mobject (attr, add_box_attributes new_attr box)
89   | mpres ->
90       Mpresentation.set_attr (new_attr @ Mpresentation.get_attr mpres) mpres
91 and add_box_attributes new_attr = function
92   | Box.Object (attr, mpres) ->
93       Box.Object (attr, add_mpres_attributes new_attr mpres)
94   | box -> Box.set_attr (new_attr @ Box.get_attr box) box
95
96 let box_of mathonly spec attrs children =
97   match children with
98     | [t] -> add_mpres_attributes attrs t
99     | _ ->
100         let kind, spacing, indent = spec in
101         let dress children =
102           if spacing then
103             NotationUtil.dress small_skip children
104           else
105             children
106         in
107           if mathonly then Mpresentation.Mrow (attrs, dress children)
108           else
109             let attrs' =
110               (if spacing then RenderingAttrs.spacing_attributes `BoxML else [])
111               @ (if indent then RenderingAttrs.indent_attributes `BoxML else [])
112               @ attrs
113             in
114               match kind with
115                 | Ast.H ->
116                     if List.for_all eligible_math children then
117                       Mpresentation.Mrow (attrs',
118                         dress (List.map promote_to_math children))
119                     else
120                       mpres_of_box (Box.H (attrs',
121                         List.map box_of_mpres children))
122 (*                 | Ast.H when List.for_all genuine_math children ->
123                     Mpresentation.Mrow (attrs', dress children) *)
124                 | Ast.V ->
125                     mpres_of_box (Box.V (attrs',
126                       List.map box_of_mpres children))
127                 | Ast.HV ->
128                     mpres_of_box (Box.HV (attrs',
129                       List.map box_of_mpres children))
130                 | Ast.HOV ->
131                     mpres_of_box (Box.HOV (attrs',
132                       List.map box_of_mpres children))
133
134 let open_paren        = Mpresentation.Mo ([], "(")
135 let closed_paren      = Mpresentation.Mo ([], ")")
136 let open_bracket      = Mpresentation.Mo ([], "[")
137 let closed_bracket    = Mpresentation.Mo ([], "]")
138 let open_brace        = Mpresentation.Mo ([], "{")
139 let closed_brace      = Mpresentation.Mo ([], "}")
140 let hidden_substs     = Mpresentation.Mtext ([], "{...}")
141 let hidden_lctxt      = Mpresentation.Mtext ([], "[...]")
142 let open_box_paren    = Box.Text ([], "(")
143 let closed_box_paren  = Box.Text ([], ")")
144 let semicolon         = Mpresentation.Mo ([], ";")
145 let toggle_action children =
146   Mpresentation.Maction ([None, "actiontype", "toggle"], children)
147
148 type child_pos = [ `Left | `Right | `Inner ]
149
150 let pp_assoc =
151   function
152   | Gramext.LeftA -> "LeftA"
153   | Gramext.RightA -> "RightA"
154   | Gramext.NonA -> "NonA"
155
156 let is_atomic t =
157   let rec aux_mpres = function
158     | Mpres.Mi _
159     | Mpres.Mo _
160     | Mpres.Mn _
161     | Mpres.Ms _
162     | Mpres.Mtext _
163     | Mpres.Mspace _ -> true
164     | Mpres.Mobject (_, box) -> aux_box box
165     | Mpres.Maction (_, [mpres])
166     | Mpres.Mrow (_, [mpres]) -> aux_mpres mpres
167     | _ -> false
168   and aux_box = function
169     | Box.Space _
170     | Box.Ink _
171     | Box.Text _ -> true
172     | Box.Object (_, mpres) -> aux_mpres mpres
173     | Box.H (_, [box])
174     | Box.V (_, [box])
175     | Box.HV (_, [box])
176     | Box.HOV (_, [box])
177     | Box.Action (_, [box]) -> aux_box box
178     | _ -> false
179   in
180   aux_mpres t
181
182 let add_parens child_prec curr_prec t =
183   if is_atomic t then 
184     ((*prerr_endline ("NOT adding parens around ATOMIC: "^
185       BoxPp.render_to_string (function x::_->x|_->assert false)
186         ~map_unicode_to_tex:false 80 t);*)t)
187   else if child_prec >= 0 && child_prec < curr_prec then 
188     begin 
189     (*prerr_endline ("adding parens around: "^
190       BoxPp.render_to_string (function x::_->x|_->assert false)
191         ~map_unicode_to_tex:false 80 t);*)
192     match t with
193     | Mpresentation.Mobject (_, box) ->
194         mpres_of_box (Box.H ([], [ open_box_paren; box; closed_box_paren ]))
195     | _mpres -> Mpresentation.Mrow ([], [open_paren; t; closed_paren])
196   end else
197     ((*prerr_endline ("NOT adding parens around: "^
198       BoxPp.render_to_string (function x::_->x|_->assert false)
199         ~map_unicode_to_tex:false 80 t);*)t)
200
201 let render status ~lookup_uri ?(prec=(-1)) =
202   let module A = Ast in
203   let module P = Mpresentation in
204 (*   let use_unicode = true in *)
205   let make_href xmlattrs xref =
206     let xref_uris =
207       List.fold_right
208         (fun xref uris ->
209           match lookup_uri xref with
210           | None -> uris
211           | Some uri -> uri :: uris)
212         !xref []
213     in
214     let xmlattrs_uris, xmlattrs =
215       let xref_attrs, other_attrs =
216         List.partition
217           (function Some "xlink", "href", _ -> true | _ -> false)
218           xmlattrs
219       in
220       List.map (fun (_, _, uri) -> uri) xref_attrs,
221       other_attrs
222     in
223     let uris =
224       match xmlattrs_uris @ xref_uris with
225       | [] -> None
226       | uris ->
227           Some (String.concat " "
228             (HExtlib.list_uniq (List.sort String.compare uris)))
229     in
230     let xrefs =
231       match !xref with [] -> None | xrefs -> Some (String.concat " " xrefs)
232     in
233     xref := [];
234     xmlattrs
235     @ make_attributes [Some "helm", "xref"; Some "xlink", "href"]
236         [xrefs; uris]
237   in
238   let make_xref xref =
239     let xrefs =
240       match !xref with [] -> None | xrefs -> Some (String.concat " " xrefs)
241     in
242     xref := [];
243     make_attributes [Some "helm","xref"] [xrefs]
244   in
245   (* when mathonly is true no boxes should be generated, only mrows *)
246   (* "xref" is  *)
247   let rec aux xmlattrs mathonly xref  prec t =
248     match t with
249     | A.AttributedTerm _ ->
250         aux_attributes xmlattrs mathonly xref  prec t
251     | A.Num (literal, _) ->
252         let attrs =
253           (RenderingAttrs.number_attributes `MathML)
254           @ make_href xmlattrs xref
255         in
256         Mpres.Mn (attrs, literal)
257     | A.Symbol (literal, _) ->
258         let attrs =
259           (RenderingAttrs.symbol_attributes `MathML)
260           @ make_href xmlattrs xref
261         in
262         Mpres.Mo (attrs, to_unicode literal)
263     | A.Ident (literal, subst)
264     | A.Uri (literal, subst) ->
265         let attrs =
266           (RenderingAttrs.ident_attributes `MathML)
267           @ make_href xmlattrs xref
268         in
269         let name = Mpres.Mi (attrs, to_unicode literal) in
270         (match subst with
271         | Some []
272         | None -> name
273         | Some substs ->
274             let substs' =
275               box_of mathonly (A.H, false, false) []
276                 (open_brace
277                 :: (NotationUtil.dress semicolon
278                     (List.map
279                       (fun (name, t) ->
280                         box_of mathonly (A.H, false, false) [] [
281                           Mpres.Mi ([], name);
282                           Mpres.Mo ([], to_unicode "\\def");
283                           aux [] mathonly xref  prec t ])
284                       substs))
285                 @ [ closed_brace ])
286             in
287             let substs_maction = toggle_action [ hidden_substs; substs' ] in
288             box_of mathonly (A.H, false, false) [] [ name; substs_maction ])
289     | A.Meta(n, l) ->
290         let local_context l =
291           box_of mathonly (A.H, false, false) []
292             ([ Mpres.Mtext ([], "[") ] @ 
293             (NotationUtil.dress (Mpres.Mtext ([],  ";"))
294               (List.map 
295                 (function 
296                 | None -> Mpres.Mtext ([],  "_")
297                 | Some t -> aux xmlattrs mathonly xref  prec t) l)) @
298              [ Mpres.Mtext ([], "]")])
299         in
300         let lctxt_maction = toggle_action [ hidden_lctxt; local_context l ] in
301         box_of mathonly (A.H, false, false) []
302           ([Mpres.Mtext ([], "?"^string_of_int n) ] 
303             @ (if l <> [] then [lctxt_maction] else []))
304     | A.Literal l -> aux_literal xmlattrs xref prec l
305     | A.UserInput -> Mpres.Mtext ([], "%")
306     | A.Layout l -> aux_layout mathonly xref  prec l
307     | A.Magic _
308     | A.Variable _ -> assert false  (* should have been instantiated *)
309     | t ->
310         prerr_endline ("unexpected ast: " ^ NotationPp.pp_term status t);
311         assert false
312   and aux_attributes _xmlattrs mathonly _xref  prec t =
313     let reset = ref false in
314     let inferred_level = ref None in
315     let expected_level = ref None in
316     let new_xref = ref [] in
317     let new_xmlattrs = ref [] in
318     let rec aux_attribute =
319       function
320       | A.AttributedTerm (attr, t) ->
321           (match attr with
322           | `Loc _
323           | `Raw _ -> ()
324           | `Level (-1) -> reset := true
325           | `Level child_prec ->
326 (*               assert (!expected_level = None); *)
327               expected_level := !inferred_level;
328               inferred_level := Some child_prec
329           | `IdRef xref -> new_xref := xref :: !new_xref
330           | `XmlAttrs attrs -> new_xmlattrs := attrs @ !new_xmlattrs);
331           aux_attribute t
332       | t ->
333           let prec = 
334             match !expected_level with
335             | None -> prec
336             | Some prec -> prec
337           in
338           (match !inferred_level with
339           | None -> aux !new_xmlattrs mathonly new_xref prec t
340           | Some child_prec ->
341               let t' = aux !new_xmlattrs mathonly new_xref child_prec t in
342               (*prerr_endline 
343                 ("inferred: "^string_of_int child_prec^ 
344                  " exp: "^string_of_int prec ^ 
345                  " term: "^BoxPp.render_to_string ~map_unicode_to_tex:false
346                     (function x::_->x|_->assert false) 80 t');*)
347               if !reset
348               then ((*prerr_endline "reset";*)t')
349               else add_parens child_prec prec t')
350     in
351 (*     prerr_endline (NotationPp.pp_term t); *)
352     aux_attribute t
353   and aux_literal xmlattrs xref _prec l =
354     let attrs = make_href xmlattrs xref in
355     (match l with
356     | `Symbol s -> Mpres.Mo (attrs, to_unicode s)
357     | `Keyword s -> Mpres.Mtext (attrs, to_unicode s)
358     | `Number s  -> Mpres.Mn (attrs, to_unicode s))
359   and aux_layout mathonly xref  prec l =
360     let attrs = make_xref xref in
361     let invoke' t = aux [] true (ref [])  prec t in
362       (* use the one below to reset precedence and associativity *)
363     let invoke_reinit t = aux [] mathonly xref ~-1 t in
364     match l with
365     | A.Sup (A.Layout (A.Sub (t1,t2)), t3)
366     | A.Sup (A.AttributedTerm (_,A.Layout (A.Sub (t1,t2))), t3)
367       -> Mpres.Msubsup (attrs, invoke' t1, invoke_reinit t2, invoke_reinit t3)
368     | A.Sub (t1, t2) -> Mpres.Msub (attrs, invoke' t1, invoke_reinit t2)
369     | A.Sup (t1, t2) -> Mpres.Msup (attrs, invoke' t1, invoke_reinit t2)
370     | A.Below (t1, t2) -> Mpres.Munder (attrs, invoke' t1, invoke_reinit t2)
371     | A.Above (t1, t2) -> Mpres.Mover (attrs, invoke' t1, invoke_reinit t2)
372     | A.Frac (t1, t2)
373     | A.Over (t1, t2) ->
374         Mpres.Mfrac (attrs, invoke_reinit t1, invoke_reinit t2)
375     | A.Atop (t1, t2) ->
376         Mpres.Mfrac (atop_attributes @ attrs, invoke_reinit t1,
377           invoke_reinit t2)
378     | A.InfRule (t1, t2, t3) ->
379       Mpres.Mstyle ([None,"mathsize","big"],
380        Mpres.Mrow (attrs,
381         [Mpres.Mfrac ([],
382            Mpres.Mstyle ([None,"scriptlevel","0"],invoke_reinit t1),
383            Mpres.Mstyle ([None,"scriptlevel","0"],invoke_reinit t2));
384           Mpres.Mstyle ([None,"scriptlevel","2"],
385            Mpresentation.Mspace 
386             (RenderingAttrs.small_skip_attributes `MathML));
387          Mpres.Mstyle ([None,"scriptlevel","1"],invoke_reinit t3)]))
388     | A.Sqrt t -> Mpres.Msqrt (attrs, invoke_reinit t)
389     | A.Root (t1, t2) ->
390         Mpres.Mroot (attrs, invoke_reinit t1, invoke_reinit t2)
391     | A.Box ((_, spacing, _) as kind, terms) ->
392         let children =
393           aux_children mathonly spacing xref  prec
394             (NotationUtil.ungroup terms)
395         in
396         box_of mathonly kind attrs children
397     | A.Mstyle (l,terms) -> 
398         Mpres.Mstyle 
399           (List.map (fun (k,v) -> None,k,v) l, 
400            box_of mathonly (A.H, false, false) attrs 
401             (aux_children mathonly false xref  prec 
402               (NotationUtil.ungroup terms)))
403     | A.Mpadded (l,terms) -> 
404         Mpres.Mpadded 
405           (List.map (fun (k,v) -> None,k,v) l, 
406            box_of mathonly (A.H, false, false) attrs 
407             (aux_children mathonly false xref  prec 
408               (NotationUtil.ungroup terms)))
409     | A.Maction alternatives -> 
410          toggle_action (List.map invoke_reinit alternatives)
411     | A.Group terms ->
412         let children =
413           aux_children mathonly false xref  prec
414             (NotationUtil.ungroup terms)
415         in
416         box_of mathonly (A.H, false, false) attrs children
417     | A.Break -> assert false (* TODO? *)
418   and aux_children mathonly spacing xref  prec terms =
419     let find_clusters =
420       let rec aux_list first clusters acc =
421         function
422             [] when acc = [] -> List.rev clusters
423           | [] -> aux_list first (List.rev acc :: clusters) [] []
424           | (A.Layout A.Break) :: tl when acc = [] ->
425               aux_list first clusters [] tl
426           | (A.Layout A.Break) :: tl ->
427               aux_list first (List.rev acc :: clusters) [] tl
428           | [hd] ->
429                 aux_list false clusters
430                   (aux [] mathonly xref  prec hd :: acc) []
431           | hd :: tl ->
432                 aux_list false clusters
433                   (aux [] mathonly xref  prec hd :: acc) tl
434       in
435         aux_list true [] []
436     in
437     let boxify_pres =
438       function
439           [t] -> t
440         | tl -> box_of mathonly (A.H, spacing, false) [] tl
441     in
442       List.map boxify_pres (find_clusters terms)
443   in
444   aux [] false (ref []) prec
445
446 let rec print_box (t: boxml_markup) =
447   Box.box2xml print_mpres t
448 and print_mpres (t: mathml_markup) =
449   Mpresentation.print_mpres print_box t
450
451 let print_xml = print_mpres
452
453 (* let render_to_boxml id_to_uri t =
454   let xml_stream = print_box (box_of_mpres (render id_to_uri t)) in
455   Xml.add_xml_declaration xml_stream *)
456