]> matita.cs.unibo.it Git - helm.git/blob - components/content_pres/cicNotationPres.ml
tagged 0.5.0-rc1
[helm.git] / 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 child_assoc child_pos curr_prec t =
185 (*   eprintf
186     ("add_parens: " ^^
187     "child_prec = %d\nchild_assoc = %s\nchild_pos = %s\ncurr_prec= %d\n\n%!")
188     child_prec (pp_assoc child_assoc) (CicNotationPp.pp_pos child_pos)
189     curr_prec; *)
190   if is_atomic t then t
191   else if child_prec >= 0
192     && (child_prec < curr_prec
193       || (child_prec = curr_prec &&
194           child_assoc = Gramext.LeftA &&
195           child_pos <> `Left)
196       || (child_prec = curr_prec &&
197           child_assoc = Gramext.RightA &&
198           child_pos <> `Right))
199   then begin (* parens should be added *)
200 (*     prerr_endline "adding parens!"; *)
201     match t with
202     | Mpresentation.Mobject (_, box) ->
203         mpres_of_box (Box.H ([], [ open_box_paren; box; closed_box_paren ]))
204     | mpres -> Mpresentation.Mrow ([], [open_paren; t; closed_paren])
205   end else
206     t
207
208 let render ids_to_uris ?(prec=(-1)) =
209   let module A = Ast in
210   let module P = Mpresentation in
211 (*   let use_unicode = true in *)
212   let lookup_uri id =
213     (try
214       let uri = Hashtbl.find ids_to_uris id in
215       Some (UriManager.string_of_uri uri)
216     with Not_found -> None)
217   in
218   let make_href xmlattrs xref =
219     let xref_uris =
220       List.fold_right
221         (fun xref uris ->
222           match lookup_uri xref with
223           | None -> uris
224           | Some uri -> uri :: uris)
225         !xref []
226     in
227     let xmlattrs_uris, xmlattrs =
228       let xref_attrs, other_attrs =
229         List.partition
230           (function Some "xlink", "href", _ -> true | _ -> false)
231           xmlattrs
232       in
233       List.map (fun (_, _, uri) -> uri) xref_attrs,
234       other_attrs
235     in
236     let uris =
237       match xmlattrs_uris @ xref_uris with
238       | [] -> None
239       | uris ->
240           Some (String.concat " "
241             (HExtlib.list_uniq (List.sort String.compare uris)))
242     in
243     let xrefs =
244       match !xref with [] -> None | xrefs -> Some (String.concat " " xrefs)
245     in
246     xref := [];
247     xmlattrs
248     @ make_attributes [Some "helm", "xref"; Some "xlink", "href"]
249         [xrefs; uris]
250   in
251   let make_xref xref =
252     let xrefs =
253       match !xref with [] -> None | xrefs -> Some (String.concat " " xrefs)
254     in
255     xref := [];
256     make_attributes [Some "helm","xref"] [xrefs]
257   in
258   (* when mathonly is true no boxes should be generated, only mrows *)
259   (* "xref" is  *)
260   let rec aux xmlattrs mathonly xref pos prec t =
261     match t with
262     | A.AttributedTerm _ ->
263         aux_attributes xmlattrs mathonly xref pos prec t
264     | A.Num (literal, _) ->
265         let attrs =
266           (RenderingAttrs.number_attributes `MathML)
267           @ make_href xmlattrs xref
268         in
269         Mpres.Mn (attrs, literal)
270     | A.Symbol (literal, _) ->
271         let attrs =
272           (RenderingAttrs.symbol_attributes `MathML)
273           @ make_href xmlattrs xref
274         in
275         Mpres.Mo (attrs, to_unicode literal)
276     | A.Ident (literal, subst)
277     | A.Uri (literal, subst) ->
278         let attrs =
279           (RenderingAttrs.ident_attributes `MathML)
280           @ make_href xmlattrs xref
281         in
282         let name = Mpres.Mi (attrs, to_unicode literal) in
283         (match subst with
284         | Some []
285         | None -> name
286         | Some substs ->
287             let substs' =
288               box_of mathonly (A.H, false, false) []
289                 (open_brace
290                 :: (CicNotationUtil.dress semicolon
291                     (List.map
292                       (fun (name, t) ->
293                         box_of mathonly (A.H, false, false) [] [
294                           Mpres.Mi ([], name);
295                           Mpres.Mo ([], to_unicode "\\def");
296                           aux [] mathonly xref pos prec t ])
297                       substs))
298                 @ [ closed_brace ])
299             in
300             let substs_maction = toggle_action [ hidden_substs; substs' ] in
301             box_of mathonly (A.H, false, false) [] [ name; substs_maction ])
302     | A.Meta(n, l) ->
303         let local_context l =
304           box_of mathonly (A.H, false, false) []
305             ([ Mpres.Mtext ([], "[") ] @ 
306             (CicNotationUtil.dress (Mpres.Mtext ([],  ";"))
307               (List.map 
308                 (function 
309                 | None -> Mpres.Mtext ([],  "_")
310                 | Some t -> aux xmlattrs mathonly xref pos prec t) l)) @
311              [ Mpres.Mtext ([], "]")])
312         in
313         let lctxt_maction = toggle_action [ hidden_lctxt; local_context l ] in
314         box_of mathonly (A.H, false, false) []
315           ([Mpres.Mtext ([], "?"^string_of_int n) ] 
316             @ (if l <> [] then [lctxt_maction] else []))
317     | A.Literal l -> aux_literal xmlattrs xref prec l
318     | A.UserInput -> Mpres.Mtext ([], "%")
319     | A.Layout l -> aux_layout mathonly xref pos prec l
320     | A.Magic _
321     | A.Variable _ -> assert false  (* should have been instantiated *)
322     | t ->
323         prerr_endline ("unexpected ast: " ^ CicNotationPp.pp_term t);
324         assert false
325   and aux_attributes xmlattrs mathonly xref pos prec t =
326     let reset = ref false in
327     let new_level = ref None in
328     let new_xref = ref [] in
329     let new_xmlattrs = ref [] in
330     let new_pos = ref pos in
331 (*     let reinit = ref false in *)
332     let rec aux_attribute =
333       function
334       | A.AttributedTerm (attr, t) ->
335           (match attr with
336           | `Loc _
337           | `Raw _ -> ()
338           | `Level (-1, _) -> reset := true
339           | `Level (child_prec, child_assoc) ->
340               new_level := Some (child_prec, child_assoc)
341           | `IdRef xref -> new_xref := xref :: !new_xref
342           | `ChildPos pos -> new_pos := pos
343           | `XmlAttrs attrs -> new_xmlattrs := attrs @ !new_xmlattrs);
344           aux_attribute t
345       | t ->
346           (match !new_level with
347           | None -> aux !new_xmlattrs mathonly new_xref !new_pos prec t
348           | Some (child_prec, child_assoc) ->
349               let t' = 
350                 aux !new_xmlattrs mathonly new_xref !new_pos child_prec t in
351               if !reset
352               then t'
353               else add_parens child_prec child_assoc !new_pos prec t')
354     in
355     aux_attribute t
356   and aux_literal xmlattrs xref prec l =
357     let attrs = make_href xmlattrs xref in
358     (match l with
359     | `Symbol s -> Mpres.Mo (attrs, to_unicode s)
360     | `Keyword s -> Mpres.Mtext (attrs, to_unicode s)
361     | `Number s  -> Mpres.Mn (attrs, to_unicode s))
362   and aux_layout mathonly xref pos prec l =
363     let attrs = make_xref xref in
364     let invoke' t = aux [] true (ref []) pos prec t in
365       (* use the one below to reset precedence and associativity *)
366     let invoke_reinit t = aux [] mathonly xref `Inner ~-1 t in
367     match l with
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.Sqrt t -> Mpres.Msqrt (attrs, invoke_reinit t)
379     | A.Root (t1, t2) ->
380         Mpres.Mroot (attrs, invoke_reinit t1, invoke_reinit t2)
381     | A.Box ((_, spacing, _) as kind, terms) ->
382         let children =
383           aux_children mathonly spacing xref pos prec
384             (CicNotationUtil.ungroup terms)
385         in
386         box_of mathonly kind attrs children
387     | A.Group terms ->
388         let children =
389           aux_children mathonly false xref pos prec
390             (CicNotationUtil.ungroup terms)
391         in
392         box_of mathonly (A.H, false, false) attrs children
393     | A.Break -> assert false (* TODO? *)
394   and aux_children mathonly spacing xref pos prec terms =
395     let find_clusters =
396       let rec aux_list first clusters acc =
397         function
398             [] when acc = [] -> List.rev clusters
399           | [] -> aux_list first (List.rev acc :: clusters) [] []
400           | (A.Layout A.Break) :: tl when acc = [] ->
401               aux_list first clusters [] tl
402           | (A.Layout A.Break) :: tl ->
403               aux_list first (List.rev acc :: clusters) [] tl
404           | [hd] ->
405 (*               let pos' = 
406                 if first then
407                   pos
408                 else
409                   match pos with
410                       `None -> `Right
411                     | `Inner -> `Inner
412                     | `Right -> `Right
413                     | `Left -> `Inner
414               in *)
415                 aux_list false clusters
416                   (aux [] mathonly xref pos prec hd :: acc) []
417           | hd :: tl ->
418 (*               let pos' =
419                 match pos, first with
420                     `None, true -> `Left
421                   | `None, false -> `Inner
422                   | `Left, true -> `Left
423                   | `Left, false -> `Inner
424                   | `Right, _ -> `Inner
425                   | `Inner, _ -> `Inner
426               in *)
427                 aux_list false clusters
428                   (aux [] mathonly xref pos prec hd :: acc) tl
429       in
430         aux_list true [] []
431     in
432     let boxify_pres =
433       function
434           [t] -> t
435         | tl -> box_of mathonly (A.H, spacing, false) [] tl
436     in
437       List.map boxify_pres (find_clusters terms)
438   in
439   aux [] false (ref []) `Inner prec
440
441 let rec print_box (t: boxml_markup) =
442   Box.box2xml print_mpres t
443 and print_mpres (t: mathml_markup) =
444   Mpresentation.print_mpres print_box t
445
446 let print_xml = print_mpres
447
448 (* let render_to_boxml id_to_uri t =
449   let xml_stream = print_box (box_of_mpres (render id_to_uri t)) in
450   Xml.add_xml_declaration xml_stream *)
451