]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaScript.ml
some cosmetic fixes
[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           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 v = UM.strip_xpointer (UM.uri_of_string v) in
97         if List.exists (fun (s,_) -> s = v) new_status.objects then
98           acc
99         else
100           DTE.add k value acc
101     ) new_aliases DTE.empty
102   in
103   let new_text =
104     if DisambiguateTypes.Environment.is_empty new_aliases then
105       parsed_text
106     else
107       prepend_text (CicTextualParser2.EnvironmentP3.to_string new_aliases)
108         parsed_text
109   in
110   let new_text =
111     if !goal_changed then
112       prepend_text
113         (TAPp.pp_tactic (TA.Goal (loc, user_goal))(* ^ "\n"*))
114         new_text
115     else
116       new_text
117   in
118     [ new_status, new_text ], parsed_text_length
119
120 let disambiguate term status =
121   let module MD = MatitaDisambiguator in
122   let dbd = MatitaDb.instance () in
123   let metasenv = MatitaMisc.get_proof_metasenv status in
124   let context = MatitaMisc.get_proof_context status in
125   let aliases = MatitaMisc.get_proof_aliases status in
126   let interps = MD.disambiguate_term dbd context metasenv aliases term in
127   match interps with 
128   | [_,_,x,_] -> x
129   | _ -> assert false
130  
131 let eval_macro status (mathviewer:MatitaTypes.mathViewer) urichooser parsed_text
132   script mac
133 =
134   let module TA = TacticAst in
135   let module TAPp = TacticAstPp in
136   let module MQ = MetadataQuery in
137   let module MDB = MatitaDb in
138   let module CTC = CicTypeChecker in
139   let module CU = CicUniv in
140   (* no idea why ocaml wants this *)
141   let advance ?statement () = script#advance ?statement () in
142   let parsed_text_length = String.length parsed_text in
143   let dbd = MatitaDb.instance () in
144   match mac with
145   (* WHELP's stuff *)
146   | TA.WMatch (loc, term) -> 
147       let term = disambiguate term status in
148       let l =  MQ.match_term ~dbd term in
149       let entry = `Whelp (TAPp.pp_macro_cic (TA.WMatch (loc, term)), l) in
150       mathviewer#show_uri_list ~reuse:true ~entry l;
151       [], parsed_text_length
152   | TA.WInstance (loc, term) ->
153       let term = disambiguate term status in
154       let l = MQ.instance ~dbd term in
155       let entry = `Whelp (TAPp.pp_macro_cic (TA.WInstance (loc, term)), l) in
156       mathviewer#show_uri_list ~reuse:true ~entry l;
157       [], parsed_text_length
158   | TA.WLocate (loc, s) -> 
159       let l = MQ.locate ~dbd s in
160       let entry = `Whelp (TAPp.pp_macro_cic (TA.WLocate (loc, s)), l) in
161       mathviewer#show_uri_list ~reuse:true ~entry l;
162       [], parsed_text_length
163   | TA.WElim (loc, term) ->
164       let term = disambiguate term status in
165       let uri =
166         match term with
167         | Cic.MutInd (uri,n,_) -> UriManager.string_of_uriref (uri,[n])
168         | _ -> failwith "Not a MutInd"
169       in
170       let l = MQ.elim ~dbd uri in
171       let entry = `Whelp (TAPp.pp_macro_cic (TA.WElim (loc, term)), l) in
172       mathviewer#show_uri_list ~reuse:true ~entry l;
173       [], parsed_text_length
174   | TA.WHint (loc, term) ->
175       let term = disambiguate term status in
176       let s = ((None,[0,[],term], Cic.Meta (0,[]) ,term),0) in
177       let l = List.map fst (MQ.experimental_hint ~dbd s) in
178       let entry = `Whelp (TAPp.pp_macro_cic (TA.WHint (loc, term)), l) in
179       mathviewer#show_uri_list ~reuse:true ~entry l;
180       [], parsed_text_length
181   (* REAL macro *)
182   | TA.Hint loc -> 
183       let s = MatitaMisc.get_proof_status status in
184       let l = List.map fst (MQ.experimental_hint ~dbd s) in
185       let selected = urichooser l in
186       (match selected with
187       | [] -> [], parsed_text_length
188       | [uri] -> 
189         let ast = 
190           (TA.Executable (loc,
191             (TA.Tactical (loc, 
192                TA.Tactic (loc,
193                  TA.Apply (loc, CicAst.Uri (uri,None))))))) 
194         in
195         let new_status = MatitaEngine.eval_ast status ast in
196         let extra_text = 
197           comment parsed_text ^ 
198           "\n" ^ TAPp.pp_statement ast
199         in
200         [ new_status , extra_text ], parsed_text_length
201       | _ -> 
202           MatitaLog.error 
203             "The result of the urichooser should be only 1 uri, not:\n";
204           List.iter (
205             fun u -> MatitaLog.error (u ^ "\n")
206           ) selected;
207           assert false)
208   | TA.Check (_,term) ->
209       let metasenv = MatitaMisc.get_proof_metasenv status in
210       let context = MatitaMisc.get_proof_context status in
211       let aliases = MatitaMisc.get_proof_aliases status in
212       let interps = 
213         MatitaDisambiguator.disambiguate_term 
214           dbd context metasenv aliases term 
215       in
216       let _, metasenv , term, ugraph =
217         match interps with 
218         | [x] -> x
219         | _ -> assert false
220       in
221       let ty,_ = CTC.type_of_aux' metasenv context term ugraph in
222       let t_and_ty = Cic.Cast (term,ty) in
223       mathviewer#show_entry (`Cic (t_and_ty,metasenv));
224       [], parsed_text_length
225 (*   | TA.Abort _ -> 
226       let rec go_back () =
227         let status = script#status.proof_status in
228         match status with
229         | No_proof -> ()
230         | _ -> script#retract ();go_back()
231       in
232       [], parsed_text_length, Some go_back
233   | TA.Redo (_, Some i) ->  [], parsed_text_length, 
234       Some (fun () -> for j = 1 to i do advance () done)
235   | TA.Redo (_, None) ->   [], parsed_text_length, 
236       Some (fun () -> advance ())
237   | TA.Undo (_, Some i) ->  [], parsed_text_length, 
238       Some (fun () -> for j = 1 to i do script#retract () done)
239   | TA.Undo (_, None) -> [], parsed_text_length, 
240       Some (fun () -> script#retract ()) *)
241   (* TODO *)
242   | TA.Quit _ -> failwith "not implemented"
243   | TA.Print (_,kind) -> failwith "not implemented"
244   | TA.Search_pat (_, search_kind, str) -> failwith "not implemented"
245   | TA.Search_term (_, search_kind, term) -> failwith "not implemented"
246
247                                 
248 let eval_executable status (mathviewer:MatitaTypes.mathViewer) urichooser
249 user_goal parsed_text script ex =
250   let module TA = TacticAst in
251   let module TAPp = TacticAstPp in
252   let module MD = MatitaDisambiguator in
253   let parsed_text_length = String.length parsed_text in
254   match ex with
255   | TA.Command (loc, _) | TA.Tactical (loc, _) ->
256       eval_with_engine status user_goal parsed_text (TA.Executable (loc, ex))
257   | TA.Macro (_,mac) ->
258       eval_macro status mathviewer urichooser parsed_text script mac
259
260 let rec eval_statement status (mathviewer:MatitaTypes.mathViewer) urichooser
261 user_goal script s =
262   if Pcre.pmatch ~rex:only_dust_RE s then raise Margin;
263   let st = CicTextualParser2.parse_statement (Stream.of_string s) in
264   let text_of_loc loc =
265     let parsed_text_length = snd (CicAst.loc_of_floc loc) in
266     let parsed_text = safe_substring s 0 parsed_text_length in
267     parsed_text, parsed_text_length
268   in
269   match st with
270   | TacticAst.Comment (loc,_)-> 
271       let parsed_text, parsed_text_length = text_of_loc loc in
272       let remain_len = String.length s - parsed_text_length in
273       let s = String.sub s parsed_text_length remain_len in
274       let s,len = 
275         eval_statement status mathviewer urichooser user_goal script s 
276       in
277       (match s with
278       | (status, text) :: tl ->
279         ((status, parsed_text ^ text)::tl), (parsed_text_length + len)
280       | [] -> [], 0)
281   | TacticAst.Executable (loc, ex) ->
282       let parsed_text, parsed_text_length = text_of_loc loc in
283       eval_executable 
284         status mathviewer urichooser user_goal parsed_text script ex
285   
286
287 class script ~(buffer: GText.buffer) ~(init: MatitaTypes.status) 
288               ~(mathviewer: MatitaTypes.mathViewer) 
289               ~urichooser () =
290 object (self)
291   initializer self#reset ()
292
293   val mutable statements = [];    (** executed statements *)
294   val mutable history = [ init ];
295     (** list of states before having executed statements. Head element of this
296       * list is the current state, last element is the state at the beginning of
297       * the script.
298       * Invariant: this list length is 1 + length of statements *)
299
300   (** goal as seen by the user (i.e. metano corresponding to current tab) *)
301   val mutable userGoal = ~-1
302
303   (** text mark and tag representing locked part of a script *)
304   val locked_mark =
305     buffer#create_mark ~name:"locked" ~left_gravity:true buffer#start_iter
306   val locked_tag = buffer#create_tag [`BACKGROUND "lightblue"; `EDITABLE false]
307
308     (* history can't be empty, the invariant above grant that it contains at
309      * least the init status *)
310   method status = match history with hd :: _ -> hd | _ -> assert false
311
312   method private _advance ?statement () =
313     let s = match statement with Some s -> s | None -> self#getFuture in
314     MatitaLog.debug ("evaluating: " ^ first_line s ^ " ...");
315     let (entries, parsed_len) = 
316       eval_statement self#status mathviewer urichooser userGoal self s in
317     let (new_statuses, new_statements) = List.split entries in
318 (*
319 prerr_endline "evalStatement returned";
320 List.iter (fun s -> prerr_endline ("'" ^ s ^ "'")) new_statements;
321 *)
322     history <- List.rev new_statuses @ history;
323     statements <- List.rev new_statements @ statements;
324     let start = buffer#get_iter_at_mark (`MARK locked_mark) in
325     if statement = None then begin
326       let stop = start#copy#forward_chars parsed_len in
327       buffer#delete ~start ~stop
328     end;
329     let new_text = String.concat "" new_statements in
330     buffer#insert ~iter:start new_text;
331     self#moveMark (String.length new_text)
332
333   method private _retract () =
334     match statements, history with
335     | last_statement :: _, cur_status :: prev_status :: _ ->
336         MatitaSync.time_travel ~present:cur_status ~past:prev_status;
337         statements <- List.tl statements;
338         history <- List.tl history;
339         self#moveMark (- (String.length last_statement));
340     | _ -> raise Margin
341
342   method advance ?statement () =
343     try
344       self#_advance ?statement ()
345     with Margin -> ()
346
347   method retract () = try self#_retract () with Margin -> ()
348
349   method private getFuture =
350     buffer#get_text ~start:(buffer#get_iter_at_mark (`MARK locked_mark))
351       ~stop:buffer#end_iter ()
352
353   (** @param rel_offset relative offset from current position of locked_mark *)
354   method private moveMark rel_offset =
355     let mark = `MARK locked_mark in
356     let old_insert = buffer#get_iter_at_mark `INSERT in
357     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
358     let current_mark_pos = buffer#get_iter_at_mark mark in
359     let new_mark_pos =
360       match rel_offset with
361       | 0 -> current_mark_pos
362       | n when n > 0 -> current_mark_pos#forward_chars n
363       | n (* when n < 0 *) -> current_mark_pos#backward_chars (abs n)
364     in
365     buffer#move_mark mark ~where:new_mark_pos;
366     buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:new_mark_pos;
367     buffer#move_mark `INSERT old_insert;
368     self#notify
369
370   val mutable observers = []
371
372   method addObserver (o: MatitaTypes.status -> unit) =
373     observers <- o :: observers
374
375   method private notify =
376     let status = self#status in
377     List.iter (fun o -> o status) observers
378
379   method loadFrom fname =
380     buffer#set_text (MatitaMisc.input_file fname);
381     self#goto_top
382
383   method saveTo fname =
384     let oc = open_out fname in
385     output_string oc (buffer#get_text ~start:buffer#start_iter
386                         ~stop:buffer#end_iter ());
387     close_out oc
388
389   method private goto_top =
390     MatitaSync.time_travel ~present:self#status ~past:init;
391     statements <- [];
392     history <- [ init ];
393     userGoal <- ~-1;
394     self#notify;
395     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
396     buffer#move_mark (`MARK locked_mark) ~where:buffer#start_iter
397
398   method reset () =
399     self#goto_top;
400     buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter
401
402   method goto (pos: [`Top | `Bottom | `Cursor]) () =
403     match pos with
404     | `Top -> self#goto_top
405     | `Bottom ->
406         (try while true do self#_advance () done with Margin -> ())
407     | `Cursor ->
408         let locked_iter () = buffer#get_iter_at_mark (`NAME "locked") in
409         let cursor_iter () = buffer#get_iter_at_mark `INSERT in
410         let rec forward_until_cursor () = (* go forward until locked > cursor *)
411           self#_advance ();
412           if (locked_iter ())#compare (cursor_iter ()) < 0 then
413             forward_until_cursor ()
414         in
415         let rec back_until_cursor () = (* go backward until locked < cursor *)
416           self#_retract ();
417           if (locked_iter ())#compare (cursor_iter ()) > 0 then
418             back_until_cursor ()
419         in
420         let cmp = (locked_iter ())#compare (cursor_iter ()) in
421         (try
422           if cmp < 0 then       (* locked < cursor *)
423             forward_until_cursor ()
424           else if cmp > 0 then  (* locked > cursor *)
425             back_until_cursor ()
426           else                  (* cursor = locked *)
427               ()
428         with Margin -> ())
429
430   method onGoingProof () =
431     match self#status.proof_status with
432     | No_proof | Proof _ -> false
433     | Incomplete_proof _ -> true
434     | Intermediate _ -> assert false
435
436   method proofStatus = MatitaMisc.get_proof_status self#status
437   method proofMetasenv = MatitaMisc.get_proof_metasenv self#status
438   method proofContext = MatitaMisc.get_proof_context self#status
439   method setGoal n = userGoal <- n
440
441   (* debug *)
442   method dump () =
443     MatitaLog.debug "script status:";
444     MatitaLog.debug ("history size: " ^ string_of_int (List.length history));
445     MatitaLog.debug (sprintf "%d statements:" (List.length statements));
446     List.iter MatitaLog.debug statements;
447
448 end
449
450 let _script = ref None
451
452 let script ~buffer ~init ~mathviewer ~urichooser () =
453   let s = new script ~buffer ~init ~mathviewer ~urichooser () in
454   _script := Some s;
455   s
456
457 let instance () = match !_script with None -> assert false | Some s -> s
458
459