]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaScript.ml
all interface is locked during advance/retract
[helm.git] / helm / 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 open Printf
27 open MatitaTypes
28
29 let debug = true
30 let debug_print = if  debug then prerr_endline else ignore
31
32   (** raised when one of the script margins (top or bottom) is reached *)
33 exception Margin
34
35 let safe_substring s i j =
36   try String.sub s i j with Invalid_argument _ -> assert false
37
38 let heading_nl_RE = Pcre.regexp "^\\s*\n\\s*"
39 let only_dust_RE = Pcre.regexp "^(\\s|\n|%%[^\n]*\n)*$"
40 let multiline_RE = Pcre.regexp "^\n[^\n]+$"
41 let newline_RE = Pcre.regexp "\n"
42  
43 let comment str =
44   if Pcre.pmatch ~rex:multiline_RE str then
45     "\n(** " ^ (Pcre.replace ~rex:newline_RE str) ^ " **)"
46   else
47     "\n(**\n" ^ str ^ "\n**)"
48                      
49 let first_line s =
50   let s = Pcre.replace ~rex:heading_nl_RE s in
51   try
52     let nl_pos = String.index s '\n' in
53     String.sub s 0 nl_pos
54   with Not_found -> s
55
56 let prepend_text header base =
57   if Pcre.pmatch ~rex:heading_nl_RE base then
58     sprintf "\n%s%s" header base
59   else
60     sprintf "%s\n%s" header base
61
62   (** creates a statement AST for the Goal tactic, e.g. "goal 7" *)
63 let goal_ast n =
64   let module A = TacticAst in
65   let loc = CicAst.dummy_floc in
66   A.Executable (loc, A.Tactical (loc, A.Tactic (loc, A.Goal (loc, n))))
67
68 let eval_with_engine status user_goal parsed_text st =
69   let module TA = TacticAst in
70   let module TAPp = TacticAstPp in
71   let parsed_text_length = String.length parsed_text in
72   let loc, ex = 
73     match st with TA.Executable (loc,ex) -> loc, ex | _ -> assert false 
74   in
75   let goal_changed = ref false in
76   let status =
77     match status.proof_status with
78       | Incomplete_proof (_, goal) when goal <> user_goal ->
79           goal_changed := true;
80           MatitaEngine.eval_ast 
81             ~do_heavy_checks:true status (goal_ast user_goal)
82       | _ -> status
83   in
84   let new_status = MatitaEngine.eval_ast ~do_heavy_checks:true status st in
85   let new_aliases =
86     match ex with
87       | TA.Command (_, TA.Alias _)
88       | TA.Command (_, TA.Include _) -> DisambiguateTypes.Environment.empty
89       | _ -> MatitaSync.alias_diff ~from:status new_status
90   in
91   (* we remove the defined object since we consider them "automathic aliases" *)
92   let new_aliases = 
93     let module DTE = DisambiguateTypes.Environment in
94     let module UM = UriManager in
95     DTE.fold (
96       fun k ((v,_) as value) acc -> 
97         let b = 
98           try
99             let v = UM.strip_xpointer (UM.uri_of_string v) in
100             List.exists (fun (s,_) -> s = v) new_status.objects 
101           with UM.IllFormedUri _ -> false
102         in
103         if b then 
104           acc
105         else
106           DTE.add k value acc
107     ) new_aliases DTE.empty
108   in
109   let new_text =
110     if DisambiguateTypes.Environment.is_empty new_aliases then
111       parsed_text
112     else
113       prepend_text (CicTextualParser2.EnvironmentP3.to_string new_aliases)
114         parsed_text
115   in
116   let new_text =
117     if !goal_changed then
118       prepend_text
119         (TAPp.pp_tactic (TA.Goal (loc, user_goal))(* ^ "\n"*))
120         new_text
121     else
122       new_text
123   in
124     [ new_status, new_text ], parsed_text_length
125
126 let disambiguate term status =
127   let module MD = MatitaDisambiguator in
128   let dbd = MatitaDb.instance () in
129   let metasenv = MatitaMisc.get_proof_metasenv status in
130   let context = MatitaMisc.get_proof_context status in
131   let aliases = MatitaMisc.get_proof_aliases status in
132   let interps = MD.disambiguate_term dbd context metasenv aliases term in
133   match interps with 
134   | [_,_,x,_] -> x
135   | _ -> assert false
136  
137 let eval_macro status (mathviewer:MatitaTypes.mathViewer) urichooser
138  parsed_text script mac
139 =
140   let module TA = TacticAst in
141   let module TAPp = TacticAstPp in
142   let module MQ = MetadataQuery in
143   let module MDB = MatitaDb in
144   let module CTC = CicTypeChecker in
145   let module CU = CicUniv in
146   (* no idea why ocaml wants this *)
147   let advance ?statement () = script#advance ?statement () in
148   let parsed_text_length = String.length parsed_text in
149   let dbd = MatitaDb.instance () in
150   match mac with
151   (* WHELP's stuff *)
152   | TA.WMatch (loc, term) -> 
153       let term = disambiguate term status in
154       let l =  MQ.match_term ~dbd term in
155       let entry = `Whelp (TAPp.pp_macro_cic (TA.WMatch (loc, term)), l) in
156       mathviewer#show_uri_list ~reuse:true ~entry l;
157       [], parsed_text_length
158   | TA.WInstance (loc, term) ->
159       let term = disambiguate term status in
160       let l = MQ.instance ~dbd term in
161       let entry = `Whelp (TAPp.pp_macro_cic (TA.WInstance (loc, term)), l) in
162       mathviewer#show_uri_list ~reuse:true ~entry l;
163       [], parsed_text_length
164   | TA.WLocate (loc, s) -> 
165       let l = MQ.locate ~dbd s in
166       let entry = `Whelp (TAPp.pp_macro_cic (TA.WLocate (loc, s)), l) in
167       mathviewer#show_uri_list ~reuse:true ~entry l;
168       [], parsed_text_length
169   | TA.WElim (loc, term) ->
170       let term = disambiguate term status in
171       let uri =
172         match term with
173         | Cic.MutInd (uri,n,_) -> UriManager.uri_of_uriref uri n None 
174         | _ -> failwith "Not a MutInd"
175       in
176       let l = MQ.elim ~dbd uri in
177       let entry = `Whelp (TAPp.pp_macro_cic (TA.WElim (loc, term)), l) in
178       mathviewer#show_uri_list ~reuse:true ~entry l;
179       [], parsed_text_length
180   | TA.WHint (loc, term) ->
181       let term = disambiguate term status in
182       let s = ((None,[0,[],term], Cic.Meta (0,[]) ,term),0) in
183       let l = List.map fst (MQ.experimental_hint ~dbd s) in
184       let entry = `Whelp (TAPp.pp_macro_cic (TA.WHint (loc, term)), l) in
185       mathviewer#show_uri_list ~reuse:true ~entry l;
186       [], parsed_text_length
187   (* REAL macro *)
188   | TA.Hint loc -> 
189       let s = MatitaMisc.get_proof_status status in
190       let l = List.map fst (MQ.experimental_hint ~dbd s) in
191       let selected = urichooser l in
192       (match selected with
193       | [] -> [], parsed_text_length
194       | [uri] -> 
195         let ast = 
196          TA.Executable (loc,
197           (TA.Tactical (loc, 
198             TA.Tactic (loc,
199              TA.Apply (loc, CicAst.Uri (UriManager.string_of_uri uri,None))))))
200         in
201         let new_status = MatitaEngine.eval_ast status ast in
202         let extra_text = 
203           comment parsed_text ^ 
204           "\n" ^ TAPp.pp_statement ast
205         in
206         [ new_status , extra_text ], parsed_text_length
207       | _ -> 
208           MatitaLog.error 
209             "The result of the urichooser should be only 1 uri, not:\n";
210           List.iter (
211             fun u -> MatitaLog.error (UriManager.string_of_uri u ^ "\n")
212           ) selected;
213           assert false)
214   | TA.Check (_,term) ->
215       let metasenv = MatitaMisc.get_proof_metasenv status in
216       let context = MatitaMisc.get_proof_context status in
217       let aliases = MatitaMisc.get_proof_aliases status in
218       let interps = 
219         MatitaDisambiguator.disambiguate_term 
220           dbd context metasenv aliases term 
221       in
222       let _, metasenv , term, ugraph =
223         match interps with 
224         | [x] -> x
225         | _ -> assert false
226       in
227       let ty,_ = CTC.type_of_aux' metasenv context term ugraph in
228       let t_and_ty = Cic.Cast (term,ty) in
229       mathviewer#show_entry (`Cic (t_and_ty,metasenv));
230       [], parsed_text_length
231 (*   | TA.Abort _ -> 
232       let rec go_back () =
233         let status = script#status.proof_status in
234         match status with
235         | No_proof -> ()
236         | _ -> script#retract ();go_back()
237       in
238       [], parsed_text_length, Some go_back
239   | TA.Redo (_, Some i) ->  [], parsed_text_length, 
240       Some (fun () -> for j = 1 to i do advance () done)
241   | TA.Redo (_, None) ->   [], parsed_text_length, 
242       Some (fun () -> advance ())
243   | TA.Undo (_, Some i) ->  [], parsed_text_length, 
244       Some (fun () -> for j = 1 to i do script#retract () done)
245   | TA.Undo (_, None) -> [], parsed_text_length, 
246       Some (fun () -> script#retract ()) *)
247   (* TODO *)
248   | TA.Quit _ -> failwith "not implemented"
249   | TA.Print (_,kind) -> failwith "not implemented"
250   | TA.Search_pat (_, search_kind, str) -> failwith "not implemented"
251   | TA.Search_term (_, search_kind, term) -> failwith "not implemented"
252
253                                 
254 let eval_executable status (mathviewer:MatitaTypes.mathViewer) urichooser
255 ask_confirmation user_goal parsed_text script ex =
256   let module TA = TacticAst in
257   let module TAPp = TacticAstPp in
258   let module MD = MatitaDisambiguator in
259   let module ML = MatitacleanLib in
260   let parsed_text_length = String.length parsed_text in
261   match ex with
262   | TA.Command (loc, _) | TA.Tactical (loc, _) ->
263       (try 
264         (match ML.baseuri_of_baseuri_decl (TA.Executable (loc,ex)) with
265         | None -> ()
266         | Some u -> 
267             if not (MatitacleanLib.is_empty u) then
268               match 
269                 ask_confirmation 
270                   ~title:"Baseuri redefinition" 
271                   ~message:(
272                     "Baseuri " ^ u ^ " already exists.\n" ^
273                     "Do you want to redefine the corresponding "^
274                     "part of the library?")
275               with
276               | `YES -> MatitacleanLib.clean_baseuris [u]
277               | `NO -> ()
278               | `CANCEL -> raise MatitaTypes.Cancel);
279         eval_with_engine status user_goal parsed_text (TA.Executable (loc, ex))
280       with MatitaTypes.Cancel -> [], 0)
281   | TA.Macro (_,mac) ->
282       eval_macro status mathviewer urichooser parsed_text script mac
283
284 let rec eval_statement status (mathviewer:MatitaTypes.mathViewer) urichooser
285 ask_confirmation user_goal script s =
286   if Pcre.pmatch ~rex:only_dust_RE s then raise Margin;
287   let st = CicTextualParser2.parse_statement (Stream.of_string s) in
288   let text_of_loc loc =
289     let parsed_text_length = snd (CicAst.loc_of_floc loc) in
290     let parsed_text = safe_substring s 0 parsed_text_length in
291     parsed_text, parsed_text_length
292   in
293   match st with
294   | TacticAst.Comment (loc,_)-> 
295       let parsed_text, parsed_text_length = text_of_loc loc in
296       let remain_len = String.length s - parsed_text_length in
297       let s = String.sub s parsed_text_length remain_len in
298       let s,len = 
299         eval_statement status 
300           mathviewer urichooser ask_confirmation user_goal script s 
301       in
302       (match s with
303       | (status, text) :: tl ->
304         ((status, parsed_text ^ text)::tl), (parsed_text_length + len)
305       | [] -> [], 0)
306   | TacticAst.Executable (loc, ex) ->
307       let parsed_text, parsed_text_length = text_of_loc loc in
308       eval_executable 
309         status mathviewer urichooser ask_confirmation 
310           user_goal parsed_text script ex
311   
312 let fresh_script_id =
313   let i = ref 0 in
314   fun () -> incr i; !i
315
316 class script ~(buffer: GText.buffer) ~(init: MatitaTypes.status) 
317               ~(mathviewer: MatitaTypes.mathViewer) 
318               ~set_star
319               ~ask_confirmation
320               ~urichooser () =
321 object (self)
322   val mutable filename = None
323   val scriptId = fresh_script_id ()
324   method private getFilename =
325     match filename with Some f -> f | _ -> assert false
326   method private ppFilename =
327     match filename with Some f -> f | None -> sprintf ".unnamed%d.ma" scriptId
328   
329   initializer 
330     ignore(GMain.Timeout.add ~ms:300000 
331        ~callback:(fun _ -> self#_saveToBackuptFile ();true));
332     ignore(buffer#connect#modified_changed 
333        (fun _ -> if buffer#modified then 
334           set_star self#ppFilename true 
335         else 
336           set_star self#ppFilename false));
337     self#reset ();
338     self#template ()
339
340   val mutable statements = [];    (** executed statements *)
341   val mutable history = [ init ];
342     (** list of states before having executed statements. Head element of this
343       * list is the current state, last element is the state at the beginning of
344       * the script.
345       * Invariant: this list length is 1 + length of statements *)
346
347   (** goal as seen by the user (i.e. metano corresponding to current tab) *)
348   val mutable userGoal = ~-1
349
350   (** text mark and tag representing locked part of a script *)
351   val locked_mark =
352     buffer#create_mark ~name:"locked" ~left_gravity:true buffer#start_iter
353   val locked_tag = buffer#create_tag [`BACKGROUND "lightblue"; `EDITABLE false]
354
355     (* history can't be empty, the invariant above grant that it contains at
356      * least the init status *)
357   method status = match history with hd :: _ -> hd | _ -> assert false
358
359   method private _advance ?statement () =
360     let s = match statement with Some s -> s | None -> self#getFuture in
361     MatitaLog.debug ("evaluating: " ^ first_line s ^ " ...");
362     let (entries, parsed_len) = 
363       eval_statement self#status 
364         mathviewer urichooser ask_confirmation userGoal self s 
365     in
366     let (new_statuses, new_statements) = List.split entries in
367 (*
368 prerr_endline "evalStatement returned";
369 List.iter (fun s -> prerr_endline ("'" ^ s ^ "'")) new_statements;
370 *)
371     history <- List.rev new_statuses @ history;
372     statements <- List.rev new_statements @ statements;
373     let start = buffer#get_iter_at_mark (`MARK locked_mark) in
374     let new_text = String.concat "" new_statements in
375     if new_text <> String.sub s 0 parsed_len then
376       begin
377 (*       prerr_endline ("new:" ^ new_text); *)
378 (*       prerr_endline ("s:" ^ String.sub s 0 parsed_len); *)
379       let stop = start#copy#forward_chars parsed_len in
380       buffer#delete ~start ~stop;
381       buffer#insert ~iter:start new_text;
382 (*       prerr_endline "AUTOMATICALLY MODIFIED!!!!!" *)
383       end;
384     self#moveMark (String.length new_text)
385
386   method private _retract () =
387     match statements, history with
388     | last_statement :: _, cur_status :: prev_status :: _ ->
389         MatitaSync.time_travel ~present:cur_status ~past:prev_status;
390         statements <- List.tl statements;
391         history <- List.tl history;
392         self#moveMark (- (String.length last_statement));
393     | _ -> raise Margin
394
395   method advance ?statement () =
396     try
397       self#_advance ?statement ();
398       self#notify
399     with 
400     | Margin -> self#notify
401     | exc -> self#notify; raise exc
402
403   method retract () =
404     try
405       self#_retract ();
406       self#notify
407     with 
408     | Margin -> self#notify
409     | exc -> self#notify; raise exc
410
411   method private getFuture =
412     buffer#get_text ~start:(buffer#get_iter_at_mark (`MARK locked_mark))
413       ~stop:buffer#end_iter ()
414
415       
416   (** @param rel_offset relative offset from current position of locked_mark *)
417   method private moveMark rel_offset =
418     let mark = `MARK locked_mark in
419     let old_insert = buffer#get_iter_at_mark `INSERT in
420     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
421     let current_mark_pos = buffer#get_iter_at_mark mark in
422     let new_mark_pos =
423       match rel_offset with
424       | 0 -> current_mark_pos
425       | n when n > 0 -> current_mark_pos#forward_chars n
426       | n (* when n < 0 *) -> current_mark_pos#backward_chars (abs n)
427     in
428     buffer#move_mark mark ~where:new_mark_pos;
429     buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:new_mark_pos;
430     buffer#move_mark `INSERT old_insert;
431     begin
432      match self#status.proof_status with
433         Incomplete_proof (_,goal) -> self#setGoal goal
434       | _ -> ()
435     end ;
436     while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
437
438   method clean_dirty_lock =
439     let lock_mark_iter = buffer#get_iter_at_mark (`MARK locked_mark) in
440     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
441     buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:lock_mark_iter
442
443   val mutable observers = []
444
445   method addObserver (o: MatitaTypes.status -> unit) =
446     observers <- o :: observers
447
448   method private notify =
449     let status = self#status in
450     List.iter (fun o -> o status) observers
451
452   method loadFromFile () =
453     buffer#set_text (MatitaMisc.input_file self#getFilename);
454     self#goto_top;
455     buffer#set_modified false
456     
457   method assignFileName file =
458     filename <- Some file;
459     
460   method saveToFile () =
461     let oc = open_out self#getFilename in
462     output_string oc (buffer#get_text ~start:buffer#start_iter
463                         ~stop:buffer#end_iter ());
464     close_out oc;
465     buffer#set_modified false
466   
467   method private _saveToBackuptFile () =
468     if buffer#modified then
469       begin
470         let f = self#ppFilename ^ "~" in
471         let oc = open_out f in
472         output_string oc (buffer#get_text ~start:buffer#start_iter
473                             ~stop:buffer#end_iter ());
474         close_out oc;
475         MatitaLog.debug ("backup " ^ f ^ " saved")                    
476       end
477   
478   method private goto_top =
479     MatitaSync.time_travel ~present:self#status ~past:init;
480     statements <- [];
481     history <- [ init ];
482     userGoal <- ~-1;
483     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
484     buffer#move_mark (`MARK locked_mark) ~where:buffer#start_iter
485
486   method reset () =
487     self#goto_top;
488     buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter;
489     self#notify;
490     buffer#set_modified false
491
492   method template () =
493     let template = MatitaMisc.input_file BuildTimeConf.script_template in 
494     buffer#insert ~iter:(buffer#get_iter `START) template;
495     filename <- None;
496     buffer#set_modified false;
497     set_star self#ppFilename false
498
499   method goto (pos: [`Top | `Bottom | `Cursor]) () =
500     let getpos _ = buffer#get_iter_at_mark (`MARK locked_mark) in 
501     match pos with
502     | `Top -> self#goto_top; self#notify
503     | `Bottom ->
504         (try 
505           let rec dowhile pos =
506             self#_advance ();
507             if pos#compare (getpos ()) < 0 then
508               dowhile (getpos ())
509           in
510           dowhile (getpos ());
511           self#notify 
512         with 
513         | Margin -> self#notify
514         | exc -> self#notify; raise exc)
515     | `Cursor ->
516         let locked_iter () = buffer#get_iter_at_mark (`NAME "locked") in
517         let cursor_iter () = buffer#get_iter_at_mark `INSERT in
518         let forward_until_cursor () = (* go forward until locked > cursor *)
519           let rec aux oldpos =
520             self#_advance ();
521             if (locked_iter ())#compare (cursor_iter ()) < 0 &&
522                oldpos#compare (getpos ()) < 0 
523             then
524               aux (getpos ())
525           in
526           aux (getpos ())
527         in
528         let rec back_until_cursor () = (* go backward until locked < cursor *)
529           self#_retract ();
530           if (locked_iter ())#compare (cursor_iter ()) > 0 then
531             back_until_cursor ()
532         in
533         let cmp = (locked_iter ())#compare (cursor_iter ()) in
534         (try
535           if cmp < 0 then       (* locked < cursor *)
536             (forward_until_cursor (); self#notify)
537           else if cmp > 0 then  (* locked > cursor *)
538             (back_until_cursor (); self#notify)
539           else                  (* cursor = locked *)
540               ()
541         with 
542         | Margin -> self#notify
543         | exc -> self#notify; raise exc)
544               
545   method onGoingProof () =
546     match self#status.proof_status with
547     | No_proof | Proof _ -> false
548     | Incomplete_proof _ -> true
549     | Intermediate _ -> assert false
550
551   method proofStatus = MatitaMisc.get_proof_status self#status
552   method proofMetasenv = MatitaMisc.get_proof_metasenv self#status
553   method proofContext = MatitaMisc.get_proof_context self#status
554   method setGoal n = userGoal <- n
555
556   method eos = 
557     let s = self#getFuture in
558     let rec is_there_and_executable s = 
559       if Pcre.pmatch ~rex:only_dust_RE s then raise Margin;
560       let st = CicTextualParser2.parse_statement (Stream.of_string s) in
561       match st with
562       | TacticAst.Comment (loc,_)-> 
563           let parsed_text_length = snd (CicAst.loc_of_floc loc) in
564           let remain_len = String.length s - parsed_text_length in
565           let next = String.sub s parsed_text_length remain_len in
566           is_there_and_executable next
567       | TacticAst.Executable (loc, ex) -> false
568     in
569     try
570       is_there_and_executable s
571     with 
572     | CicTextualParser2.Parse_error _ -> false
573     | Margin -> true
574       
575     
576     
577   (* debug *)
578   method dump () =
579     MatitaLog.debug "script status:";
580     MatitaLog.debug ("history size: " ^ string_of_int (List.length history));
581     MatitaLog.debug (sprintf "%d statements:" (List.length statements));
582     List.iter MatitaLog.debug statements;
583     MatitaLog.debug ("Current file name: " ^
584       (match filename with None -> "[ no name ]" | Some f -> f));
585
586 end
587
588 let _script = ref None
589
590 let script ~buffer ~init ~mathviewer ~urichooser ~ask_confirmation ~set_star ()
591 =
592   let s = new script 
593     ~buffer ~init ~mathviewer ~ask_confirmation ~urichooser ~set_star () 
594   in
595   _script := Some s;
596   s
597
598 let instance () = match !_script with None -> assert false | Some s -> s
599
600