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