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