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