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