]> matita.cs.unibo.it Git - helm.git/blob - helm/software/matita/matitaScript.ml
2055bb9cdbe3c2a99c7ef25e4722bafbee87dd6e
[helm.git] / helm / software / matita / matitaScript.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 open GrafiteTypes
30
31 module TA = GrafiteAst
32
33 let debug = false
34 let debug_print = if debug then prerr_endline else ignore
35
36   (** raised when one of the script margins (top or bottom) is reached *)
37 exception Margin
38 exception NoUnfinishedProof
39 exception ActionCancelled of string
40
41 let safe_substring s i j =
42   try String.sub s i j with Invalid_argument _ -> assert false
43
44 let heading_nl_RE = Pcre.regexp "^\\s*\n\\s*"
45 let heading_nl_RE' = Pcre.regexp "^(\\s*\n\\s*)"
46 let only_dust_RE = Pcre.regexp "^(\\s|\n|%%[^\n]*\n)*$"
47 let multiline_RE = Pcre.regexp "^\n[^\n]+$"
48 let newline_RE = Pcre.regexp "\n"
49 let comment_RE = Pcre.regexp "\\(\\*(.|\n)*\\*\\)\n?" ~flags:[`UNGREEDY]
50  
51 let comment str =
52   if Pcre.pmatch ~rex:multiline_RE str then
53     "\n(** " ^ (Pcre.replace ~rex:newline_RE str) ^ " *)"
54   else
55     "\n(**\n" ^ str ^ "\n*)"
56
57 let strip_comments str =
58   Pcre.qreplace ~templ:"\n" ~pat:"\n\n" (Pcre.qreplace ~rex:comment_RE str)
59 ;;
60                      
61 let first_line s =
62   let s = Pcre.replace ~rex:heading_nl_RE s in
63   try
64     let nl_pos = String.index s '\n' in
65     String.sub s 0 nl_pos
66   with Not_found -> s
67
68 type guistuff = {
69   mathviewer:MatitaTypes.mathViewer;
70   urichooser: UriManager.uri list -> UriManager.uri list;
71   ask_confirmation: title:string -> message:string -> [`YES | `NO | `CANCEL];
72 }
73
74 let eval_with_engine include_paths guistuff grafite_status user_goal
75  skipped_txt nonskipped_txt st
76 =
77   let parsed_text_length =
78     String.length skipped_txt + String.length nonskipped_txt 
79   in
80   let text = skipped_txt ^ nonskipped_txt in
81   let prefix_len = MatitaGtkMisc.utf8_string_length skipped_txt in
82   let enriched_history_fragment =
83    MatitaEngine.eval_ast ~do_heavy_checks:(Helm_registry.get_bool
84      "matita.do_heavy_checks")
85     grafite_status (text,prefix_len,st)
86   in
87   let enriched_history_fragment = List.rev enriched_history_fragment in
88   (* really fragile *)
89   let res,_ = 
90     List.fold_left 
91       (fun (acc, to_prepend) (status,alias) ->
92        match alias with
93        | None -> (status,to_prepend ^ nonskipped_txt)::acc,""
94        | Some (k,value) ->
95             let newtxt = LexiconAstPp.pp_alias value in
96             (status,to_prepend ^ newtxt ^ "\n")::acc, "")
97       ([],skipped_txt) enriched_history_fragment
98   in
99   res,"",parsed_text_length
100 ;;
101
102 (* this function calls the parser in a way that it does not perform inclusions,
103  * so that we can ensure the inclusion is performed after the included file 
104  * is compiled (if needed). matitac does not need that, since it compiles files
105  * in the good order, here files may be compiled on demand. *)
106 let wrap_with_make include_paths (f : #LexiconEngine.status GrafiteParser.statement) x = 
107   try      
108     f ~never_include:true ~include_paths x
109   with
110   | GrafiteParser.NoInclusionPerformed mafilename ->
111       let root, buri, _, tgt = 
112         try Librarian.baseuri_of_script ~include_paths mafilename
113         with Librarian.NoRootFor _ -> 
114           HLog.error ("The included file '"^mafilename^"' has no root file,");
115           HLog.error "please create it.";
116           raise (Failure ("No root file for "^mafilename))
117       in
118       let b = MatitacLib.Make.make root [tgt] in
119       if b then 
120         try f ~include_paths x with LexiconEngine.IncludedFileNotCompiled _ ->
121          raise 
122            (Failure ("Including: "^tgt^
123              "\nNothing to do... did you run matitadep?"))
124       else raise (Failure ("Compiling: " ^ tgt))
125 ;;
126
127 let pp_eager_statement_ast =
128   GrafiteAstPp.pp_statement ~term_pp:CicNotationPp.pp_term
129     ~lazy_term_pp:(fun _ -> assert false) ~obj_pp:(fun _ -> assert false)
130
131 (* naive implementation of procedural proof script generation, 
132  * starting from an applicatiove *auto generated) proof.
133  * this is out of place, but I like it :-P *)
134 let cic2grafite context menv t =
135   (* indents a proof script in a stupid way, better than nothing *)
136   let stupid_indenter s =
137     let next s = 
138       let idx_square_o = try String.index s '[' with Not_found -> -1 in
139       let idx_square_c = try String.index s ']' with Not_found -> -1 in
140       let idx_pipe = try String.index s '|' with Not_found -> -1 in
141       let tok = 
142         List.sort (fun (i,_) (j,_) -> compare i j)
143           [idx_square_o,'[';idx_square_c,']';idx_pipe,'|']
144       in
145       let tok = List.filter (fun (i,_) -> i <> -1) tok in
146       match tok with
147       | (i,c)::_ -> Some (i,c)
148       | _ -> None
149     in
150     let break_apply n s =
151       let tab = String.make (n+1) ' ' in
152       Pcre.replace ~templ:(".\n" ^ tab ^ "apply") ~pat:"\\.apply" s
153     in
154     let rec ind n s =
155       match next s with
156       | None -> 
157           s
158       | Some (position, char) ->
159           try 
160             let s1, s2 = 
161               String.sub s 0 position, 
162               String.sub s (position+1) (String.length s - (position+1))
163             in
164             match char with
165             | '[' -> break_apply n s1 ^ "\n" ^ String.make (n+2) ' ' ^
166                        "[" ^ ind (n+2) s2
167             | '|' -> break_apply n s1 ^ "\n" ^ String.make n ' ' ^ 
168                        "|" ^ ind n s2
169             | ']' -> break_apply n s1 ^ "\n" ^ String.make n ' ' ^ 
170                        "]" ^ ind (n-2) s2
171             | _ -> assert false
172           with
173           Invalid_argument err -> 
174             prerr_endline err;
175             s
176     in
177      ind 0 s
178   in
179   let module PT = CicNotationPt in
180   let module GA = GrafiteAst in
181   let pp_t context t =
182     let names = 
183       List.map (function Some (n,_) -> Some n | None -> None) context 
184     in
185     CicPp.pp t names
186   in
187   let sort_of context t = 
188     try
189       let ty,_ = 
190         CicTypeChecker.type_of_aux' menv context t
191           CicUniv.oblivion_ugraph 
192       in
193       let sort,_ = CicTypeChecker.type_of_aux' menv context ty
194           CicUniv.oblivion_ugraph
195       in
196       match sort with
197       | Cic.Sort Cic.Prop -> true
198       | _ -> false
199     with
200       CicTypeChecker.TypeCheckerFailure _ ->
201         HLog.error "auto proof to sript transformation error"; false
202   in
203   let floc = HExtlib.dummy_floc in
204   (* minimalisti cic.term -> pt.term *)
205   let print_term c t =
206     let rec aux c = function
207       | Cic.Rel _
208       | Cic.MutConstruct _ 
209       | Cic.MutInd _ 
210       | Cic.Const _ as t -> 
211           PT.Ident (pp_t c t, None)
212       | Cic.Appl l -> PT.Appl (List.map (aux c) l)
213       | Cic.Implicit _ -> PT.Implicit
214       | Cic.Lambda (Cic.Name n, s, t) ->
215           PT.Binder (`Lambda, (PT.Ident (n,None), Some (aux c s)),
216             aux (Some (Cic.Name n, Cic.Decl s)::c) t)
217       | Cic.Prod (Cic.Name n, s, t) ->
218           PT.Binder (`Forall, (PT.Ident (n,None), Some (aux c s)),
219             aux (Some (Cic.Name n, Cic.Decl s)::c) t)
220       | Cic.LetIn (Cic.Name n, s, ty, t) ->
221           PT.Binder (`Lambda, (PT.Ident (n,None), Some (aux c s)),
222             aux (Some (Cic.Name n, Cic.Def (s,ty))::c) t)
223       | Cic.Meta _ -> PT.Implicit
224       | Cic.Sort (Cic.Type u) -> PT.Sort (`Type u)
225       | Cic.Sort Cic.Set -> PT.Sort `Set
226       | Cic.Sort (Cic.CProp u) -> PT.Sort (`CProp u)
227       | Cic.Sort Cic.Prop -> PT.Sort `Prop
228       | _ as t -> PT.Ident ("ERROR: "^CicPp.ppterm t, None)
229     in
230     aux c t
231   in
232   (* prints an applicative proof, that is an auto proof.
233    * don't use in the general case! *)
234   let rec print_proof context = function
235     | Cic.Rel _
236     | Cic.Const _ as t -> 
237         [GA.Executable (floc, 
238           GA.Tactic (floc,
239           Some (GA.Apply (floc, print_term context t)), GA.Dot floc))]
240     | Cic.Appl (he::tl) ->
241         let tl = List.map (fun t -> t, sort_of context t) tl in
242         let subgoals = 
243           HExtlib.filter_map (function (t,true) -> Some t | _ -> None) tl
244         in
245         let args = 
246           List.map (function | (t,true) -> Cic.Implicit None | (t,_) -> t) tl
247         in
248         if List.length subgoals > 1 then
249           (* branch *)
250           [GA.Executable (floc, 
251             GA.Tactic (floc,
252               Some (GA.Apply (floc, print_term context (Cic.Appl (he::args)))),
253               GA.Semicolon floc))] @
254           [GA.Executable (floc, GA.Tactic (floc, None, GA.Branch floc))] @
255           (HExtlib.list_concat 
256           ~sep:[GA.Executable (floc, GA.Tactic (floc, None,GA.Shift floc))]
257             (List.map (print_proof context) subgoals)) @
258           [GA.Executable (floc, GA.Tactic (floc, None,GA.Merge floc))]
259         else
260           (* simple apply *)
261           [GA.Executable (floc, 
262             GA.Tactic (floc,
263             Some (GA.Apply 
264               (floc, print_term context (Cic.Appl (he::args)) )), GA.Dot floc))]
265           @
266           (match subgoals with
267           | [] -> []
268           | [x] -> print_proof context x
269           | _ -> assert false)
270     | Cic.Lambda (Cic.Name n, ty, bo) ->
271         [GA.Executable (floc, 
272           GA.Tactic (floc,
273             Some (GA.Cut (floc, Some n, (print_term context ty))),
274             GA.Branch floc))] @
275         (print_proof (Some (Cic.Name n, Cic.Decl ty)::context) bo) @
276         [GA.Executable (floc, GA.Tactic (floc, None,GA.Shift floc))] @
277         [GA.Executable (floc, GA.Tactic (floc, 
278           Some (GA.Assumption floc),GA.Merge floc))]
279     | _ -> []
280     (*
281         debug_print (lazy (CicPp.ppterm t));
282         assert false
283         *)
284   in
285   (* performs a lambda closure of the proof term abstracting metas.
286    * this is really an approximation of a closure, local subst of metas 
287    * is not kept into account *)
288   let close_pt menv context t =
289     let metas = CicUtil.metas_of_term t in
290     let metas = 
291       HExtlib.list_uniq ~eq:(fun (i,_) (j,_) -> i = j)
292         (List.sort (fun (i,_) (j,_) -> compare i j) metas)
293     in
294     let mk_rels_and_collapse_metas metas = 
295       let rec aux i map acc acc1 = function 
296         | [] -> acc, acc1, map
297         | (j,_ as m)::tl -> 
298             let _,_,ty = CicUtil.lookup_meta j menv in
299             try 
300               let n = List.assoc ty map in
301               aux i map (Cic.Rel n :: acc) (m::acc1) tl 
302             with Not_found -> 
303               let map = (ty, i)::map in
304               aux (i+1) map (Cic.Rel i :: acc) (m::acc1) tl
305       in
306       aux 1 [] [] [] metas
307     in
308     let rels, metas, map = mk_rels_and_collapse_metas metas in
309     let n_lambdas = List.length map in
310     let t = 
311       if metas = [] then 
312         t 
313       else
314         let t =
315           ProofEngineReduction.replace_lifting
316            ~what:(List.map (fun (x,_) -> Cic.Meta (x,[])) metas)
317            ~with_what:rels
318            ~context:context
319            ~equality:(fun _ x y ->
320              match x,y with
321              | Cic.Meta(i,_), Cic.Meta(j,_) when i=j -> true
322              | _ -> false)
323            ~where:(CicSubstitution.lift n_lambdas t)
324         in
325         let rec mk_lam = function 
326           | [] -> t 
327           | (ty,n)::tl -> 
328               let name = "fresh_"^ string_of_int n in
329               Cic.Lambda (Cic.Name name, ty, mk_lam tl)
330         in
331          mk_lam 
332           (fst (List.fold_left 
333             (fun (l,liftno) (ty,_)  -> 
334               (l @ [CicSubstitution.lift liftno ty,liftno] , liftno+1))
335             ([],0) map))
336     in
337       t
338   in
339   let ast = print_proof context (close_pt menv context t) in
340   let pp t = 
341     (* ZACK: setting width to 80 will trigger a bug of BoxPp.render_to_string
342      * which will show up using the following command line:
343      * ./tptp2grafite -tptppath ~tassi/TPTP-v3.1.1 GRP170-1 *)
344     let width = max_int in
345     let term_pp content_term =
346       let pres_term = TermContentPres.pp_ast content_term in
347       let lookup_uri = fun _ -> None in
348       let markup = CicNotationPres.render ~lookup_uri pres_term in
349       let s = "(" ^ BoxPp.render_to_string
350        ~map_unicode_to_tex:(Helm_registry.get_bool
351          "matita.paste_unicode_as_tex")
352        List.hd width markup ^ ")" in
353       Pcre.substitute 
354         ~pat:"\\\\forall [Ha-z][a-z0-9_]*" ~subst:(fun x -> "\n" ^ x) s
355     in
356     CicNotationPp.set_pp_term term_pp;
357     let lazy_term_pp = fun x -> assert false in
358     let obj_pp = CicNotationPp.pp_obj CicNotationPp.pp_term in
359     GrafiteAstPp.pp_statement
360      ~map_unicode_to_tex:(Helm_registry.get_bool
361        "matita.paste_unicode_as_tex")
362      ~term_pp ~lazy_term_pp ~obj_pp t
363   in
364   let script = String.concat "" (List.map pp ast) in
365   prerr_endline script;
366   stupid_indenter script
367 ;;
368
369 let rec eval_macro include_paths (buffer : GText.buffer) guistuff grafite_status user_goal unparsed_text parsed_text script mac =
370   let module MQ = MetadataQuery in
371   let module CTC = CicTypeChecker in
372   (* no idea why ocaml wants this *)
373   let parsed_text_length = String.length parsed_text in
374   let dbd = LibraryDb.instance () in
375   let pp_macro = ApplyTransformation.txt_of_macro ~map_unicode_to_tex:true in
376   match mac with
377   (* WHELP's stuff *)
378   | TA.WMatch (loc, term) -> 
379      let l =  Whelp.match_term ~dbd term in
380      let entry = `Whelp (pp_macro [] [] mac, l) in
381      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
382      [], "", parsed_text_length
383   | TA.WInstance (loc, term) ->
384      let l = Whelp.instance ~dbd term in
385      let entry = `Whelp (pp_macro [] [] mac, l) in
386      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
387      [], "", parsed_text_length
388   | TA.WLocate (loc, s) -> 
389      let l = Whelp.locate ~dbd s in
390      let entry = `Whelp (pp_macro [] [] mac, l) in
391      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
392      [], "", parsed_text_length
393   | TA.WElim (loc, term) ->
394      let uri =
395        match term with
396        | Cic.MutInd (uri,n,_) -> UriManager.uri_of_uriref uri n None 
397        | _ -> failwith "Not a MutInd"
398      in
399      let l = Whelp.elim ~dbd uri in
400      let entry = `Whelp (pp_macro [] [] mac, l) in
401      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
402      [], "", parsed_text_length
403   | TA.WHint (loc, term) ->
404      let _subst = [] in
405      let s = ((None,[0,[],term], _subst, lazy (Cic.Meta (0,[])) ,term, []),0) in
406      let l = List.map fst (MQ.experimental_hint ~dbd s) in
407      let entry = `Whelp (pp_macro [] [] mac, l) in
408      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
409      [], "", parsed_text_length
410   (* REAL macro *)
411   | TA.Hint (loc, rewrite) -> 
412       let user_goal' =
413        match user_goal with
414           Some n -> n
415         | None -> raise NoUnfinishedProof
416       in
417       let proof = GrafiteTypes.get_current_proof grafite_status in
418       let proof_status = proof,user_goal' in
419       if rewrite then
420         let l = MQ.equations_for_goal ~dbd proof_status in
421         let l = List.filter (fun u -> not (LibraryObjects.in_eq_URIs u)) l in
422         let entry = 
423           `Whelp (pp_macro [] [] (TA.WHint(loc, Cic.Implicit None)), l) in
424         guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
425         [], "", parsed_text_length
426       else
427         let l = List.map fst (MQ.experimental_hint ~dbd proof_status) in
428         let selected = guistuff.urichooser l in
429         (match selected with
430         | [] -> [], "", parsed_text_length
431         | [uri] -> 
432             let suri = UriManager.string_of_uri uri in
433             let ast loc =
434               TA.Executable (loc, (TA.Tactic (loc,
435                Some (TA.Apply (loc, CicNotationPt.Uri (suri, None))),
436                TA.Dot loc))) in
437             let text =
438              comment parsed_text ^ "\n" ^
439               pp_eager_statement_ast (ast HExtlib.dummy_floc)
440               ~map_unicode_to_tex:(Helm_registry.get_bool
441                 "matita.paste_unicode_as_tex")
442             in
443             let text_len = MatitaGtkMisc.utf8_string_length text in
444             let loc = HExtlib.floc_of_loc (0,text_len) in
445             let statement = `Ast (GrafiteParser.LSome (ast loc),text) in
446             let res,_,_parsed_text_len =
447              eval_statement include_paths buffer guistuff 
448               grafite_status user_goal script statement
449             in
450              (* we need to replace all the parsed_text *)
451              res,"",String.length parsed_text
452         | _ -> 
453             HLog.error 
454               "The result of the urichooser should be only 1 uri, not:\n";
455             List.iter (
456               fun u -> HLog.error (UriManager.string_of_uri u ^ "\n")
457             ) selected;
458             assert false)
459   | TA.Eval (_, kind, term) -> 
460       let metasenv = GrafiteTypes.get_proof_metasenv grafite_status in
461       let context =
462        match user_goal with
463           None -> []
464         | Some n -> GrafiteTypes.get_proof_context grafite_status n in
465       let ty,_ = CTC.type_of_aux' metasenv context term CicUniv.empty_ugraph in
466       let term = 
467         match kind with
468         | `Normalize ->
469              CicReduction.normalize ~delta:true ~subst:[] context term
470         | `Simpl -> 
471             ProofEngineReduction.simpl context term
472         | `Unfold None ->
473             ProofEngineReduction.unfold ?what:None context term
474         | `Unfold (Some lazy_term) ->
475              let what, _, _ = 
476                lazy_term context metasenv CicUniv.empty_ugraph in
477              ProofEngineReduction.unfold ~what context term
478         | `Whd ->
479             CicReduction.whd ~delta:true ~subst:[] context term
480       in
481       let t_and_ty = Cic.Cast (term,ty) in
482       guistuff.mathviewer#show_entry (`Cic (t_and_ty,metasenv));
483       [(grafite_status#set_proof_status No_proof), parsed_text ],"", 
484         parsed_text_length 
485   | TA.Check (_,term) ->
486       let metasenv = GrafiteTypes.get_proof_metasenv grafite_status in
487       let context =
488        match user_goal with
489           None -> []
490         | Some n -> GrafiteTypes.get_proof_context grafite_status n in
491       let ty,_ = CTC.type_of_aux' metasenv context term CicUniv.empty_ugraph in
492       let t_and_ty = Cic.Cast (term,ty) in
493       guistuff.mathviewer#show_entry (`Cic (t_and_ty,metasenv));
494       [], "", parsed_text_length
495   | TA.AutoInteractive (_, params) ->
496       let user_goal' =
497        match user_goal with
498           Some n -> n
499         | None -> raise NoUnfinishedProof
500       in
501       let proof = GrafiteTypes.get_current_proof grafite_status in
502       let proof_status = proof,user_goal' in
503       (try
504         let _,menv,_,_,_,_ = proof in
505         let i,cc,ty = CicUtil.lookup_meta user_goal' menv in
506         let timestamp = Unix.gettimeofday () in
507         let (_,menv,subst,_,_,_), _ = 
508           ProofEngineTypes.apply_tactic
509             (Auto.auto_tac ~dbd ~params
510               ~automation_cache:grafite_status#automation_cache) 
511             proof_status
512         in
513         let proof_term = 
514           let irl = 
515             CicMkImplicit.identity_relocation_list_for_metavariable cc
516           in
517           CicMetaSubst.apply_subst subst (Cic.Meta (i,irl))
518         in
519         let time = Unix.gettimeofday () -. timestamp in
520         let size, depth = Auto.size_and_depth cc menv proof_term in
521         let trailer = 
522           Printf.sprintf 
523             "\n(* end auto(%s) proof: TIME=%4.2f SIZE=%d DEPTH=%d *)"
524             Auto.revision time size depth
525         in
526         let proof_script = 
527           if List.exists (fun (s,_) -> s = "paramodulation") (snd params) then
528               let proof_term, how_many_lambdas = 
529                 Auto.lambda_close ~prefix_name:"orrible_hack_" 
530                   proof_term menv cc 
531               in
532               let ty,_ = 
533                 CicTypeChecker.type_of_aux'
534                   menv [] proof_term CicUniv.empty_ugraph
535               in
536               prerr_endline (CicPp.ppterm proof_term);
537               (* use declarative output *)
538               let obj =
539                 (* il proof_term vive in cc, devo metterci i lambda no? *)
540                 (Cic.CurrentProof ("xxx",menv,proof_term,ty,[],[]))
541               in
542                ApplyTransformation.txt_of_cic_object
543                 ~map_unicode_to_tex:(Helm_registry.get_bool
544                   "matita.paste_unicode_as_tex")
545                 ~skip_thm_and_qed:true
546                 ~skip_initial_lambdas:how_many_lambdas
547                 80 [] obj
548           else
549             if true then
550               (* use cic2grafite *)
551               cic2grafite cc menv proof_term 
552             else
553               (* alternative using FG stuff *)
554               let map_unicode_to_tex =
555                  Helm_registry.get_bool "matita.paste_unicode_as_tex"
556               in
557               ApplyTransformation.procedural_txt_of_cic_term
558                  ~map_unicode_to_tex 78 [] cc proof_term
559         in
560         let text = comment parsed_text ^ "\n" ^ proof_script ^ trailer in
561         [],text,parsed_text_length
562       with
563         ProofEngineTypes.Fail _ as exn -> 
564           raise exn
565           (* [], comment parsed_text ^ "\nfail.\n", parsed_text_length *))
566   | TA.Inline (_, suri, params) ->
567        let str = "\n\n" ^ 
568          ApplyTransformation.txt_of_inline_macro
569           ~map_unicode_to_tex:(Helm_registry.get_bool
570             "matita.paste_unicode_as_tex")
571           params suri 
572        in
573        [], str, String.length parsed_text
574                                 
575 and eval_executable include_paths (buffer : GText.buffer) guistuff
576 grafite_status user_goal unparsed_text skipped_txt nonskipped_txt
577 script ex loc
578 =
579   try
580    ignore (buffer#move_mark (`NAME "beginning_of_statement")
581     ~where:((buffer#get_iter_at_mark (`NAME "locked"))#forward_chars
582        (Glib.Utf8.length skipped_txt))) ;
583    eval_with_engine include_paths 
584     guistuff grafite_status user_goal skipped_txt nonskipped_txt
585      (TA.Executable (loc, ex))
586   with
587      MatitaTypes.Cancel -> [], "", 0
588    | GrafiteEngine.Macro (_loc,lazy_macro) ->
589       let context =
590        match user_goal with
591           None -> []
592         | Some n -> GrafiteTypes.get_proof_context grafite_status n in
593       let grafite_status,macro = lazy_macro context in
594        eval_macro include_paths buffer guistuff grafite_status
595         user_goal unparsed_text (skipped_txt ^ nonskipped_txt) script macro
596
597 and eval_statement include_paths (buffer : GText.buffer) guistuff 
598  grafite_status user_goal script statement
599 =
600   let (grafite_status,st), unparsed_text =
601     match statement with
602     | `Raw text ->
603         if Pcre.pmatch ~rex:only_dust_RE text then raise Margin;
604         let ast = 
605          wrap_with_make include_paths
606           (GrafiteParser.parse_statement (Ulexing.from_utf8_string text)) 
607             grafite_status
608         in
609           ast, text
610     | `Ast (st, text) -> (grafite_status, st), text
611   in
612   let text_of_loc floc = 
613     let nonskipped_txt,_ = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
614     let start, stop = HExtlib.loc_of_floc floc in 
615     let floc = HExtlib.floc_of_loc (0, start) in
616     let skipped_txt,_ = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
617     let floc = HExtlib.floc_of_loc (0, stop) in
618     let txt,len = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
619     txt,nonskipped_txt,skipped_txt,len
620   in 
621   match st with
622   | GrafiteParser.LNone loc ->
623       let parsed_text, _, _, parsed_text_length = text_of_loc loc in
624        [grafite_status,parsed_text],"",
625         parsed_text_length
626   | GrafiteParser.LSome (GrafiteAst.Comment (loc, _)) -> 
627       let parsed_text, _, _, parsed_text_length = text_of_loc loc in
628       let remain_len = String.length unparsed_text - parsed_text_length in
629       let s = String.sub unparsed_text parsed_text_length remain_len in
630       let s,text,len = 
631        try
632         eval_statement include_paths buffer guistuff 
633          grafite_status user_goal script (`Raw s)
634        with
635           HExtlib.Localized (floc, exn) ->
636            HExtlib.raise_localized_exception 
637              ~offset:(MatitaGtkMisc.utf8_string_length parsed_text) floc exn
638         | MultiPassDisambiguator.DisambiguationError (offset,errorll) ->
639            raise
640             (MultiPassDisambiguator.DisambiguationError
641               (offset+parsed_text_length, errorll))
642       in
643       assert (text=""); (* no macros inside comments, please! *)
644       (match s with
645       | (statuses,text)::tl ->
646          (statuses,parsed_text ^ text)::tl,"",parsed_text_length + len
647       | [] -> [], "", 0)
648   | GrafiteParser.LSome (GrafiteAst.Executable (loc, ex)) ->
649      let _, nonskipped, skipped, parsed_text_length = 
650        text_of_loc loc 
651      in
652       eval_executable include_paths buffer guistuff 
653        grafite_status user_goal unparsed_text skipped nonskipped script ex loc
654   
655 let fresh_script_id =
656   let i = ref 0 in
657   fun () -> incr i; !i
658
659 class script  ~(source_view: GSourceView.source_view)
660               ~(mathviewer: MatitaTypes.mathViewer) 
661               ~set_star
662               ~ask_confirmation
663               ~urichooser 
664               () =
665 let buffer = source_view#buffer in
666 let source_buffer = source_view#source_buffer in
667 let initial_statuses baseuri =
668  let lexicon_status =
669    CicNotation2.load_notation ~include_paths:[] (new LexiconEngine.status)
670      BuildTimeConf.core_notation_script 
671  in
672  let grafite_status = GrafiteSync.init lexicon_status baseuri in
673   grafite_status
674 in
675 let read_include_paths file =
676  try 
677    let root, _buri, _fname, _tgt = 
678      Librarian.baseuri_of_script ~include_paths:[] file 
679    in 
680    let rc = 
681     Str.split (Str.regexp " ") 
682      (List.assoc "include_paths" (Librarian.load_root_file (root^"/root")))
683    in
684    List.iter (HLog.debug) rc; rc
685  with Librarian.NoRootFor _ | Not_found -> []
686 in
687 let default_buri = "cic:/matita/tests" in
688 let default_fname = ".unnamed.ma" in
689 object (self)
690   val mutable include_paths_ = []
691
692   val scriptId = fresh_script_id ()
693
694   val guistuff = {
695     mathviewer = mathviewer;
696     urichooser = urichooser;
697     ask_confirmation = ask_confirmation;
698   }
699
700   val mutable filename_ = (None : string option)
701
702   method has_name = filename_ <> None
703   
704   method include_paths =
705     include_paths_ @ 
706     Helm_registry.get_list Helm_registry.string "matita.includes"
707
708   method private curdir =
709     try
710      let root, _buri, _fname, _tgt = 
711        Librarian.baseuri_of_script ~include_paths:self#include_paths
712        self#filename 
713      in 
714      root
715     with Librarian.NoRootFor _ -> Sys.getcwd ()
716
717   method buri_of_current_file =
718     match filename_ with
719     | None -> default_buri 
720     | Some f ->
721         try 
722           let _root, buri, _fname, _tgt = 
723             Librarian.baseuri_of_script ~include_paths:self#include_paths f 
724           in 
725           buri
726         with Librarian.NoRootFor _ -> default_buri
727
728   method filename = match filename_ with None -> default_fname | Some f -> f
729
730   initializer 
731     ignore (GMain.Timeout.add ~ms:300000 
732        ~callback:(fun _ -> self#_saveToBackupFile ();true));
733     ignore (buffer#connect#modified_changed 
734       (fun _ -> set_star buffer#modified))
735
736   val mutable statements = []    (** executed statements *)
737
738   val mutable history = [ initial_statuses default_buri ]
739     (** list of states before having executed statements. Head element of this
740       * list is the current state, last element is the state at the beginning of
741       * the script.
742       * Invariant: this list length is 1 + length of statements *)
743
744   (** goal as seen by the user (i.e. metano corresponding to current tab) *)
745   val mutable userGoal = None
746
747   (** text mark and tag representing locked part of a script *)
748   val locked_mark =
749     buffer#create_mark ~name:"locked" ~left_gravity:true buffer#start_iter
750   val beginning_of_statement_mark =
751     buffer#create_mark ~name:"beginning_of_statement"
752      ~left_gravity:true buffer#start_iter
753   val locked_tag = buffer#create_tag [`BACKGROUND "lightblue"; `EDITABLE false]
754   val error_tag = buffer#create_tag [`UNDERLINE `SINGLE; `FOREGROUND "red"]
755
756   method locked_mark = locked_mark
757   method locked_tag = locked_tag
758   method error_tag = error_tag
759
760     (* history can't be empty, the invariant above grant that it contains at
761      * least the init grafite_status *)
762   method grafite_status = match history with s::_ -> s | _ -> assert false
763
764   method private _advance ?statement () =
765    let s = match statement with Some s -> s | None -> self#getFuture in
766    if self#bos then LibraryClean.clean_baseuris [self#buri_of_current_file];
767    HLog.debug ("evaluating: " ^ first_line s ^ " ...");
768    let entries, newtext, parsed_len = 
769     try
770      eval_statement self#include_paths buffer guistuff
771       self#grafite_status userGoal self (`Raw s)
772     with End_of_file -> raise Margin
773    in
774    let new_statuses, new_statements =
775      let statuses, texts = List.split entries in
776      statuses, texts
777    in
778    history <- new_statuses @ history;
779    statements <- new_statements @ statements;
780    let start = buffer#get_iter_at_mark (`MARK locked_mark) in
781    let new_text = String.concat "" (List.rev new_statements) in
782    if statement <> None then
783      buffer#insert ~iter:start new_text
784    else begin
785      let parsed_text = String.sub s 0 parsed_len in
786      if new_text <> parsed_text then begin
787        let stop = start#copy#forward_chars (Glib.Utf8.length parsed_text) in
788        buffer#delete ~start ~stop;
789        buffer#insert ~iter:start new_text;
790      end;
791    end;
792    self#moveMark (Glib.Utf8.length new_text);
793    buffer#insert ~iter:(buffer#get_iter_at_mark (`MARK locked_mark)) newtext;
794    (* here we need to set the Goal in case we are going to cursor (or to
795       bottom) and we will face a macro *)
796    match self#grafite_status#proof_status with
797       Incomplete_proof p ->
798        userGoal <-
799          (try Some (Continuationals.Stack.find_goal p.stack)
800          with Failure _ -> None)
801     | _ -> userGoal <- None
802
803   method private _retract offset grafite_status new_statements
804    new_history
805   =
806    let cur_grafite_status =
807     match history with s::_ -> s | [] -> assert false
808    in
809     LexiconSync.time_travel ~present:cur_grafite_status ~past:grafite_status;
810     GrafiteSync.time_travel ~present:cur_grafite_status ~past:grafite_status;
811     statements <- new_statements;
812     history <- new_history;
813     self#moveMark (- offset)
814
815   method advance ?statement () =
816     try
817       self#_advance ?statement ();
818       self#notify
819     with 
820     | Margin -> self#notify
821     | Not_found -> assert false
822     | Invalid_argument "Array.make" -> HLog.error "The script is too big!\n"
823     | exc -> self#notify; raise exc
824
825   method retract () =
826     try
827       let cmp,new_statements,new_history,grafite_status =
828        match statements,history with
829           stat::statements, _::(status::_ as history) ->
830            assert (Glib.Utf8.validate stat);
831            Glib.Utf8.length stat, statements, history, status
832        | [],[_] -> raise Margin
833        | _,_ -> assert false
834       in
835        self#_retract cmp grafite_status new_statements
836         new_history;
837        self#notify
838     with 
839     | Margin -> self#notify
840     | Invalid_argument "Array.make" -> HLog.error "The script is too big!\n"
841     | exc -> self#notify; raise exc
842
843   method private getFuture =
844     let lock = buffer#get_iter_at_mark (`MARK locked_mark) in
845     let text = buffer#get_text ~start:lock ~stop:buffer#end_iter () in
846     text
847
848   method expandAllVirtuals =
849     let lock = buffer#get_iter_at_mark (`MARK locked_mark) in
850     let text = buffer#get_text ~start:lock ~stop:buffer#end_iter () in
851     buffer#delete ~start:lock ~stop:buffer#end_iter;
852     let text = Pcre.replace ~pat:":=" ~templ:"\\def" text in
853     let text = Pcre.replace ~pat:"->" ~templ:"\\to" text in
854     let text = Pcre.replace ~pat:"=>" ~templ:"\\Rightarrow" text in
855     let text = 
856       Pcre.substitute_substrings 
857         ~subst:(fun str -> 
858            let pristine = Pcre.get_substring str 0 in
859            let input = 
860              if pristine.[0] = ' ' then
861                String.sub pristine 1 (String.length pristine -1) 
862              else pristine 
863            in
864            let input = 
865              if input.[String.length input-1] = ' ' then
866                String.sub input 0 (String.length input -1) 
867              else input
868            in
869            let before, after =  
870              if input = "\\forall" || 
871                 input = "\\lambda" || 
872                 input = "\\exists" then "","" else " ", " " 
873            in
874            try 
875              before ^ Glib.Utf8.from_unichar 
876                (snd (Virtuals.symbol_of_virtual input)) ^ after
877            with Virtuals.Not_a_virtual -> pristine) 
878         ~pat:" ?\\\\[a-zA-Z]+ ?" text
879     in
880     buffer#insert ~iter:lock text
881       
882   (** @param rel_offset relative offset from current position of locked_mark *)
883   method private moveMark rel_offset =
884     let mark = `MARK locked_mark in
885     let old_insert = buffer#get_iter_at_mark `INSERT in
886     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
887     let current_mark_pos = buffer#get_iter_at_mark mark in
888     let new_mark_pos =
889       match rel_offset with
890       | 0 -> current_mark_pos
891       | n when n > 0 -> current_mark_pos#forward_chars n
892       | n (* when n < 0 *) -> current_mark_pos#backward_chars (abs n)
893     in
894     buffer#move_mark mark ~where:new_mark_pos;
895     buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:new_mark_pos;
896     buffer#move_mark `INSERT old_insert;
897     let mark_position = buffer#get_iter_at_mark mark in
898     if source_view#move_mark_onscreen mark then
899      begin
900       buffer#move_mark mark mark_position;
901       source_view#scroll_to_mark ~use_align:true ~xalign:1.0 ~yalign:0.1 mark;
902      end;
903     while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
904
905   method clean_dirty_lock =
906     let lock_mark_iter = buffer#get_iter_at_mark (`MARK locked_mark) in
907     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
908     buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:lock_mark_iter
909
910   val mutable observers = []
911
912   method addObserver (o: GrafiteTypes.status -> unit) =
913     observers <- o :: observers
914
915   method private notify =
916     let grafite_status = self#grafite_status in
917     List.iter (fun o -> o grafite_status) observers
918
919   method loadFromString s =
920     buffer#set_text s;
921     self#reset_buffer;
922     buffer#set_modified true
923
924   method loadFromFile f =
925     buffer#set_text (HExtlib.input_file f);
926     self#reset_buffer;
927     buffer#set_modified false
928
929   method assignFileName file =
930     let file = 
931       match file with 
932       | Some f -> Some (Librarian.absolutize f)
933       | None -> None
934     in
935     self#goto_top;
936     filename_ <- file; 
937     include_paths_ <- 
938       (match file with Some file -> read_include_paths file | None -> []);
939     self#reset_buffer;
940     Sys.chdir self#curdir;
941     HLog.debug ("Moving to " ^ Sys.getcwd ())
942     
943   method saveToFile () =
944     if self#has_name then
945       let oc = open_out self#filename in
946       output_string oc (buffer#get_text ~start:buffer#start_iter
947                         ~stop:buffer#end_iter ());
948       close_out oc;
949       set_star false;
950       buffer#set_modified false
951     else
952       HLog.error "Can't save, no filename selected"
953   
954   method private _saveToBackupFile () =
955     if buffer#modified then
956       begin
957         let f = self#filename in
958         let oc = open_out f in
959         output_string oc (buffer#get_text ~start:buffer#start_iter
960                             ~stop:buffer#end_iter ());
961         close_out oc;
962         HLog.debug ("backup " ^ f ^ " saved")                    
963       end
964   
965   method private goto_top =
966     let grafite_status = 
967       let rec last x = function 
968       | [] -> x
969       | hd::tl -> last hd tl
970       in
971       last (self#grafite_status) history
972     in
973     (* FIXME: this is not correct since there is no undo for 
974      * library_objects.set_default... *)
975     GrafiteSync.time_travel ~present:self#grafite_status ~past:grafite_status;
976     LexiconSync.time_travel ~present:self#grafite_status ~past:grafite_status
977
978   method private reset_buffer = 
979     statements <- [];
980     history <- [ initial_statuses self#buri_of_current_file ];
981     userGoal <- None;
982     self#notify;
983     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
984     buffer#move_mark (`MARK locked_mark) ~where:buffer#start_iter
985
986   method reset () =
987     self#reset_buffer;
988     source_buffer#begin_not_undoable_action ();
989     buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter;
990     source_buffer#end_not_undoable_action ();
991     buffer#set_modified false;
992   
993   method template () =
994     let template = HExtlib.input_file BuildTimeConf.script_template in 
995     buffer#insert ~iter:(buffer#get_iter `START) template;
996     buffer#set_modified false;
997     set_star false
998
999   method goto (pos: [`Top | `Bottom | `Cursor]) () =
1000   try  
1001     let old_locked_mark =
1002      `MARK
1003        (buffer#create_mark ~name:"old_locked_mark"
1004          ~left_gravity:true (buffer#get_iter_at_mark (`MARK locked_mark))) in
1005     let getpos _ = buffer#get_iter_at_mark (`MARK locked_mark) in 
1006     let getoldpos _ = buffer#get_iter_at_mark old_locked_mark in 
1007     let dispose_old_locked_mark () = buffer#delete_mark old_locked_mark in
1008     match pos with
1009     | `Top -> 
1010         dispose_old_locked_mark (); 
1011         self#goto_top; 
1012         self#reset_buffer;
1013         self#notify
1014     | `Bottom ->
1015         (try 
1016           let rec dowhile () =
1017             self#_advance ();
1018             let newpos = getpos () in
1019             if (getoldpos ())#compare newpos < 0 then
1020               begin
1021                 buffer#move_mark old_locked_mark newpos;
1022                 dowhile ()
1023               end
1024           in
1025           dowhile ();
1026           dispose_old_locked_mark ();
1027           self#notify 
1028         with 
1029         | Margin -> dispose_old_locked_mark (); self#notify
1030         | exc -> dispose_old_locked_mark (); self#notify; raise exc)
1031     | `Cursor ->
1032         let locked_iter () = buffer#get_iter_at_mark (`NAME "locked") in
1033         let cursor_iter () = buffer#get_iter_at_mark `INSERT in
1034         let remember =
1035          `MARK
1036            (buffer#create_mark ~name:"initial_insert"
1037              ~left_gravity:true (cursor_iter ())) in
1038         let dispose_remember () = buffer#delete_mark remember in
1039         let remember_iter () =
1040          buffer#get_iter_at_mark (`NAME "initial_insert") in
1041         let cmp () = (locked_iter ())#offset - (remember_iter ())#offset in
1042         let icmp = cmp () in
1043         let forward_until_cursor () = (* go forward until locked > cursor *)
1044           let rec aux () =
1045             self#_advance ();
1046             if cmp () < 0 && (getoldpos ())#compare (getpos ()) < 0 
1047             then
1048              begin
1049               buffer#move_mark old_locked_mark (getpos ());
1050               aux ()
1051              end
1052           in
1053           aux ()
1054         in
1055         let rec back_until_cursor len = (* go backward until locked < cursor *)
1056          function
1057             statements, ((grafite_status)::_ as history)
1058             when len <= 0 ->
1059              self#_retract (icmp - len) grafite_status statements
1060               history
1061           | statement::tl1, _::tl2 ->
1062              back_until_cursor (len - MatitaGtkMisc.utf8_string_length statement) (tl1,tl2)
1063           | _,_ -> assert false
1064         in
1065         (try
1066           begin
1067            if icmp < 0 then       (* locked < cursor *)
1068              (forward_until_cursor (); self#notify)
1069            else if icmp > 0 then  (* locked > cursor *)
1070              (back_until_cursor icmp (statements,history); self#notify)
1071            else                  (* cursor = locked *)
1072                ()
1073           end ;
1074           dispose_remember ();
1075           dispose_old_locked_mark ();
1076         with 
1077         | Margin -> dispose_remember (); dispose_old_locked_mark (); self#notify
1078         | exc -> dispose_remember (); dispose_old_locked_mark ();
1079                  self#notify; raise exc)
1080   with Invalid_argument "Array.make" ->
1081      HLog.error "The script is too big!\n"
1082   
1083   method onGoingProof () =
1084     match self#grafite_status#proof_status with
1085     | No_proof | Proof _ -> false
1086     | Incomplete_proof _ -> true
1087     | Intermediate _ -> assert false
1088
1089 (*   method proofStatus = MatitaTypes.get_proof_status self#status *)
1090   method proofMetasenv = GrafiteTypes.get_proof_metasenv self#grafite_status
1091
1092   method proofContext =
1093    match userGoal with
1094       None -> []
1095     | Some n -> GrafiteTypes.get_proof_context self#grafite_status n
1096
1097   method proofConclusion =
1098    match userGoal with
1099       None -> assert false
1100     | Some n ->
1101        GrafiteTypes.get_proof_conclusion self#grafite_status n
1102
1103   method stack = GrafiteTypes.get_stack self#grafite_status
1104   method setGoal n = userGoal <- n
1105   method goal = userGoal
1106
1107   method bos = 
1108     match history with
1109     | _::[] -> true
1110     | _ -> false
1111
1112   method eos = 
1113     let rec is_there_only_comments lexicon_status s = 
1114       if Pcre.pmatch ~rex:only_dust_RE s then raise Margin;
1115       let lexicon_status,st =
1116        GrafiteParser.parse_statement (Ulexing.from_utf8_string s)
1117         ~include_paths:self#include_paths lexicon_status
1118       in
1119       match st with
1120       | GrafiteParser.LSome (GrafiteAst.Comment (loc,_)) -> 
1121           let _,parsed_text_length = MatitaGtkMisc.utf8_parsed_text s loc in
1122           (* CSC: why +1 in the following lines ???? *)
1123           let parsed_text_length = parsed_text_length + 1 in
1124           let remain_len = String.length s - parsed_text_length in
1125           let next = String.sub s parsed_text_length remain_len in
1126           is_there_only_comments lexicon_status next
1127       | GrafiteParser.LNone _
1128       | GrafiteParser.LSome (GrafiteAst.Executable _) -> false
1129     in
1130     try is_there_only_comments self#grafite_status self#getFuture
1131     with 
1132     | LexiconEngine.IncludedFileNotCompiled _
1133     | HExtlib.Localized _
1134     | CicNotationParser.Parse_error _ -> false
1135     | Margin | End_of_file -> true
1136     | Invalid_argument "Array.make" -> false
1137
1138   (* debug *)
1139   method dump () =
1140     HLog.debug "script status:";
1141     HLog.debug ("history size: " ^ string_of_int (List.length history));
1142     HLog.debug (sprintf "%d statements:" (List.length statements));
1143     List.iter HLog.debug statements;
1144     HLog.debug ("Current file name: " ^ self#filename);
1145 end
1146
1147 let _script = ref None
1148
1149 let script ~source_view ~mathviewer ~urichooser ~ask_confirmation ~set_star ()
1150 =
1151   let s = new script 
1152     ~source_view ~mathviewer ~ask_confirmation ~urichooser ~set_star () 
1153   in
1154   _script := Some s;
1155   s
1156
1157 let current () = match !_script with None -> assert false | Some s -> s
1158