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