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