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