]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/content_pres/cicNotationPres.ml
82a326c48bbb4ffc70d64400ef043b1b74955fa0
[helm.git] / helm / software / 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 = CicNotationPt
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             CicNotationUtil.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 lookup_uri ids_to_uris id =
204  try
205    let uri = Hashtbl.find ids_to_uris id in
206    Some (UriManager.string_of_uri uri)
207  with Not_found -> None
208 ;;
209
210 let render ~lookup_uri ?(prec=(-1)) =
211   let module A = Ast in
212   let module P = Mpresentation in
213 (*   let use_unicode = true in *)
214   let make_href xmlattrs xref =
215     let xref_uris =
216       List.fold_right
217         (fun xref uris ->
218           match lookup_uri xref with
219           | None -> uris
220           | Some uri -> uri :: uris)
221         !xref []
222     in
223     let xmlattrs_uris, xmlattrs =
224       let xref_attrs, other_attrs =
225         List.partition
226           (function Some "xlink", "href", _ -> true | _ -> false)
227           xmlattrs
228       in
229       List.map (fun (_, _, uri) -> uri) xref_attrs,
230       other_attrs
231     in
232     let uris =
233       match xmlattrs_uris @ xref_uris with
234       | [] -> None
235       | uris ->
236           Some (String.concat " "
237             (HExtlib.list_uniq (List.sort String.compare uris)))
238     in
239     let xrefs =
240       match !xref with [] -> None | xrefs -> Some (String.concat " " xrefs)
241     in
242     xref := [];
243     xmlattrs
244     @ make_attributes [Some "helm", "xref"; Some "xlink", "href"]
245         [xrefs; uris]
246   in
247   let make_xref xref =
248     let xrefs =
249       match !xref with [] -> None | xrefs -> Some (String.concat " " xrefs)
250     in
251     xref := [];
252     make_attributes [Some "helm","xref"] [xrefs]
253   in
254   (* when mathonly is true no boxes should be generated, only mrows *)
255   (* "xref" is  *)
256   let rec aux xmlattrs mathonly xref  prec t =
257     match t with
258     | A.AttributedTerm _ ->
259         aux_attributes xmlattrs mathonly xref  prec t
260     | A.Num (literal, _) ->
261         let attrs =
262           (RenderingAttrs.number_attributes `MathML)
263           @ make_href xmlattrs xref
264         in
265         Mpres.Mn (attrs, literal)
266     | A.Symbol (literal, _) ->
267         let attrs =
268           (RenderingAttrs.symbol_attributes `MathML)
269           @ make_href xmlattrs xref
270         in
271         Mpres.Mo (attrs, to_unicode literal)
272     | A.Ident (literal, subst)
273     | A.Uri (literal, subst) ->
274         let attrs =
275           (RenderingAttrs.ident_attributes `MathML)
276           @ make_href xmlattrs xref
277         in
278         let name = Mpres.Mi (attrs, to_unicode literal) in
279         (match subst with
280         | Some []
281         | None -> name
282         | Some substs ->
283             let substs' =
284               box_of mathonly (A.H, false, false) []
285                 (open_brace
286                 :: (CicNotationUtil.dress semicolon
287                     (List.map
288                       (fun (name, t) ->
289                         box_of mathonly (A.H, false, false) [] [
290                           Mpres.Mi ([], name);
291                           Mpres.Mo ([], to_unicode "\\def");
292                           aux [] mathonly xref  prec t ])
293                       substs))
294                 @ [ closed_brace ])
295             in
296             let substs_maction = toggle_action [ hidden_substs; substs' ] in
297             box_of mathonly (A.H, false, false) [] [ name; substs_maction ])
298     | A.Meta(n, l) ->
299         let local_context l =
300           box_of mathonly (A.H, false, false) []
301             ([ Mpres.Mtext ([], "[") ] @ 
302             (CicNotationUtil.dress (Mpres.Mtext ([],  ";"))
303               (List.map 
304                 (function 
305                 | None -> Mpres.Mtext ([],  "_")
306                 | Some t -> aux xmlattrs mathonly xref  prec t) l)) @
307              [ Mpres.Mtext ([], "]")])
308         in
309         let lctxt_maction = toggle_action [ hidden_lctxt; local_context l ] in
310         box_of mathonly (A.H, false, false) []
311           ([Mpres.Mtext ([], "?"^string_of_int n) ] 
312             @ (if l <> [] then [lctxt_maction] else []))
313     | A.Literal l -> aux_literal xmlattrs xref prec l
314     | A.UserInput -> Mpres.Mtext ([], "%")
315     | A.Layout l -> aux_layout mathonly xref  prec l
316     | A.Magic _
317     | A.Variable _ -> assert false  (* should have been instantiated *)
318     | t ->
319         prerr_endline ("unexpected ast: " ^ CicNotationPp.pp_term t);
320         assert false
321   and aux_attributes xmlattrs mathonly xref  prec t =
322     let reset = ref false in
323     let inferred_level = ref None in
324     let expected_level = ref None in
325     let new_xref = ref [] in
326     let new_xmlattrs = ref [] in
327     let rec aux_attribute =
328       function
329       | A.AttributedTerm (attr, t) ->
330           (match attr with
331           | `Loc _
332           | `Raw _ -> ()
333           | `Level (-1) -> reset := true
334           | `Level child_prec ->
335 (*               assert (!expected_level = None); *)
336               expected_level := !inferred_level;
337               inferred_level := Some child_prec
338           | `IdRef xref -> new_xref := xref :: !new_xref
339           | `XmlAttrs attrs -> new_xmlattrs := attrs @ !new_xmlattrs);
340           aux_attribute t
341       | t ->
342           let prec = 
343             match !expected_level with
344             | None -> prec
345             | Some prec -> prec
346           in
347           (match !inferred_level with
348           | None -> aux !new_xmlattrs mathonly new_xref prec t
349           | Some child_prec ->
350               let t' = aux !new_xmlattrs mathonly new_xref child_prec t in
351               (*prerr_endline 
352                 ("inferred: "^string_of_int child_prec^ 
353                  " exp: "^string_of_int prec ^ 
354                  " term: "^BoxPp.render_to_string ~map_unicode_to_tex:false
355                     (function x::_->x|_->assert false) 80 t');*)
356               if !reset
357               then ((*prerr_endline "reset";*)t')
358               else add_parens child_prec prec t')
359     in
360 (*     prerr_endline (CicNotationPp.pp_term t); *)
361     aux_attribute t
362   and aux_literal xmlattrs xref prec l =
363     let attrs = make_href xmlattrs xref in
364     (match l with
365     | `Symbol s -> Mpres.Mo (attrs, to_unicode s)
366     | `Keyword s -> Mpres.Mtext (attrs, to_unicode s)
367     | `Number s  -> Mpres.Mn (attrs, to_unicode s))
368   and aux_layout mathonly xref  prec l =
369     let attrs = make_xref xref in
370     let invoke' t = aux [] true (ref [])  prec t in
371       (* use the one below to reset precedence and associativity *)
372     let invoke_reinit t = aux [] mathonly xref ~-1 t in
373     match l with
374     | A.Sup (A.Layout (A.Sub (t1,t2)), t3)
375     | A.Sup (A.AttributedTerm (_,A.Layout (A.Sub (t1,t2))), t3)
376       -> Mpres.Msubsup (attrs, invoke' t1, invoke_reinit t2, invoke_reinit t3)
377     | A.Sub (t1, t2) -> Mpres.Msub (attrs, invoke' t1, invoke_reinit t2)
378     | A.Sup (t1, t2) -> Mpres.Msup (attrs, invoke' t1, invoke_reinit t2)
379     | A.Below (t1, t2) -> Mpres.Munder (attrs, invoke' t1, invoke_reinit t2)
380     | A.Above (t1, t2) -> Mpres.Mover (attrs, invoke' t1, invoke_reinit t2)
381     | A.Frac (t1, t2)
382     | A.Over (t1, t2) ->
383         Mpres.Mfrac (attrs, invoke_reinit t1, invoke_reinit t2)
384     | A.Atop (t1, t2) ->
385         Mpres.Mfrac (atop_attributes @ attrs, invoke_reinit t1,
386           invoke_reinit t2)
387     | A.InfRule (t1, t2, t3) ->
388       Mpres.Mstyle ([None,"mathsize","big"],
389        Mpres.Mrow (attrs,
390         [Mpres.Mfrac ([],
391            Mpres.Mstyle ([None,"scriptlevel","0"],invoke_reinit t1),
392            Mpres.Mstyle ([None,"scriptlevel","0"],invoke_reinit t2));
393           Mpres.Mstyle ([None,"scriptlevel","2"],
394            Mpresentation.Mspace 
395             (RenderingAttrs.small_skip_attributes `MathML));
396          Mpres.Mstyle ([None,"scriptlevel","1"],invoke_reinit t3)]))
397     | A.Sqrt t -> Mpres.Msqrt (attrs, invoke_reinit t)
398     | A.Root (t1, t2) ->
399         Mpres.Mroot (attrs, invoke_reinit t1, invoke_reinit t2)
400     | A.Box ((_, spacing, _) as kind, terms) ->
401         let children =
402           aux_children mathonly spacing xref  prec
403             (CicNotationUtil.ungroup terms)
404         in
405         box_of mathonly kind attrs children
406     | A.Mstyle (l,terms) -> 
407         Mpres.Mstyle 
408           (List.map (fun (k,v) -> None,k,v) l, 
409            box_of mathonly (A.H, false, false) attrs 
410             (aux_children mathonly false xref  prec 
411               (CicNotationUtil.ungroup terms)))
412     | A.Mpadded (l,terms) -> 
413         Mpres.Mpadded 
414           (List.map (fun (k,v) -> None,k,v) l, 
415            box_of mathonly (A.H, false, false) attrs 
416             (aux_children mathonly false xref  prec 
417               (CicNotationUtil.ungroup terms)))
418     | A.Maction alternatives -> 
419          toggle_action (List.map invoke_reinit alternatives)
420     | A.Group terms ->
421         let children =
422           aux_children mathonly false xref  prec
423             (CicNotationUtil.ungroup terms)
424         in
425         box_of mathonly (A.H, false, false) attrs children
426     | A.Break -> assert false (* TODO? *)
427   and aux_children mathonly spacing xref  prec terms =
428     let find_clusters =
429       let rec aux_list first clusters acc =
430         function
431             [] when acc = [] -> List.rev clusters
432           | [] -> aux_list first (List.rev acc :: clusters) [] []
433           | (A.Layout A.Break) :: tl when acc = [] ->
434               aux_list first clusters [] tl
435           | (A.Layout A.Break) :: tl ->
436               aux_list first (List.rev acc :: clusters) [] tl
437           | [hd] ->
438                 aux_list false clusters
439                   (aux [] mathonly xref  prec hd :: acc) []
440           | hd :: tl ->
441                 aux_list false clusters
442                   (aux [] mathonly xref  prec hd :: acc) tl
443       in
444         aux_list true [] []
445     in
446     let boxify_pres =
447       function
448           [t] -> t
449         | tl -> box_of mathonly (A.H, spacing, false) [] tl
450     in
451       List.map boxify_pres (find_clusters terms)
452   in
453   aux [] false (ref []) prec
454
455 let rec print_box (t: boxml_markup) =
456   Box.box2xml print_mpres t
457 and print_mpres (t: mathml_markup) =
458   Mpresentation.print_mpres print_box t
459
460 let print_xml = print_mpres
461
462 (* let render_to_boxml id_to_uri t =
463   let xml_stream = print_box (box_of_mpres (render id_to_uri t)) in
464   Xml.add_xml_declaration xml_stream *)
465