1 (* Copyright (C) 2004-2005, HELM Team.
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.
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.
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.
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,
22 * For details, see the HELM World-Wide-Web page,
23 * http://helm.cs.unibo.it/
30 let debug_print = if debug then prerr_endline else ignore
32 (** raised when one of the script margins (top or bottom) is reached *)
35 let safe_substring s i j =
36 try String.sub s i j with Invalid_argument _ -> assert false
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"
44 if Pcre.pmatch ~rex:multiline_RE str then
45 "\n(** " ^ (Pcre.replace ~rex:newline_RE str) ^ " **)"
47 "\n(**\n" ^ str ^ "\n**)"
50 let s = Pcre.replace ~rex:heading_nl_RE s in
52 let nl_pos = String.index s '\n' in
56 let prepend_text header base =
57 if Pcre.pmatch ~rex:heading_nl_RE base then
58 sprintf "\n%s%s" header base
60 sprintf "%s\n%s" header base
62 (** creates a statement AST for the Goal tactic, e.g. "goal 7" *)
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))))
69 mathviewer:MatitaTypes.mathViewer;
70 urichooser: UriManager.uri list -> UriManager.uri list;
71 ask_confirmation: title:string -> message:string -> [`YES | `NO | `CANCEL];
72 develcreator: containing:string option -> unit;
73 mutable filenamedata: string option * MatitamakeLib.development option
76 let eval_with_engine guistuff status user_goal parsed_text st =
77 let module TA = TacticAst in
78 let module TAPp = TacticAstPp in
80 match guistuff.filenamedata with
82 | None,Some devel -> [MatitamakeLib.root_for_development devel ]
84 match MatitamakeLib.development_for_dir (Filename.dirname f) with
86 | Some devel -> [MatitamakeLib.root_for_development devel ]
88 let parsed_text_length = String.length parsed_text in
90 match st with TA.Executable (loc,ex) -> loc, ex | _ -> assert false
92 let goal_changed = ref false in
94 match status.proof_status with
95 | Incomplete_proof (_, goal) when goal <> user_goal ->
97 MatitaEngine.eval_ast ~include_paths:include_
98 ~do_heavy_checks:true status (goal_ast user_goal)
102 MatitaEngine.eval_ast
103 ~include_paths:include_ ~do_heavy_checks:true status st
107 | TA.Command (_, TA.Alias _)
108 | TA.Command (_, TA.Include _) -> DisambiguateTypes.Environment.empty
109 | _ -> MatitaSync.alias_diff ~from:status new_status
111 (* we remove the defined object since we consider them "automathic aliases" *)
113 let module DTE = DisambiguateTypes.Environment in
114 let module UM = UriManager in
116 fun k ((v,_) as value) acc ->
119 let v = UM.strip_xpointer (UM.uri_of_string v) in
120 List.exists (fun (s,_) -> s = v) new_status.objects
121 with UM.IllFormedUri _ -> false
127 ) new_aliases DTE.empty
130 if DisambiguateTypes.Environment.is_empty new_aliases then
133 prepend_text (CicTextualParser2.EnvironmentP3.to_string new_aliases)
137 if !goal_changed then
139 (TAPp.pp_tactic (TA.Goal (loc, user_goal))(* ^ "\n"*))
144 [ new_status, new_text ], parsed_text_length
146 let eval_with_engine guistuff status user_goal parsed_text st =
148 eval_with_engine guistuff status user_goal parsed_text st
150 MatitaEngine.UnableToInclude what as exc ->
151 let compile_needed_and_go_on d =
152 let root = MatitamakeLib.root_for_development d in
153 let target = root ^ "/" ^ what in
154 if not(MatitamakeLib.build_development ~target d) then
157 eval_with_engine guistuff status user_goal parsed_text st
159 let do_nothing () = [], 0 in
160 let handle_with_devel d =
161 let name = MatitamakeLib.name_for_development d in
162 let title = "Unable to include " ^ what in
164 what ^ " is handled by development <b>" ^ name ^ "</b>.\n\n" ^
165 "<i>Should I compile it and Its dependencies?</i>"
167 (match guistuff.ask_confirmation ~title ~message with
168 | `YES -> compile_needed_and_go_on d
170 | `CANCEL -> do_nothing ())
172 let handle_withoud_devel filename =
173 let title = "Unable to include " ^ what in
175 what ^ " is <b>not</b> handled by a development.\n" ^
176 "All dependencies are authomatically solved for a development.\n\n" ^
177 "<i>Do you want to set up a development?</i>"
179 (match guistuff.ask_confirmation ~title ~message with
183 guistuff.develcreator ~containing:(Some (Filename.dirname f))
184 | None -> guistuff.develcreator ~containing:None);
187 | `CANCEL -> do_nothing())
189 match guistuff.filenamedata with
190 | None,None -> handle_withoud_devel None
191 | None,Some d -> handle_with_devel d
193 match MatitamakeLib.development_for_dir (Filename.dirname f) with
194 | None -> handle_withoud_devel (Some f)
195 | Some d -> handle_with_devel d
198 let disambiguate term status =
199 let module MD = MatitaDisambiguator in
200 let dbd = MatitaDb.instance () in
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 = MD.disambiguate_term dbd context metasenv aliases term in
209 let eval_macro guistuff status parsed_text script mac
211 let module TA = TacticAst in
212 let module TAPp = TacticAstPp in
213 let module MQ = MetadataQuery in
214 let module MDB = MatitaDb in
215 let module CTC = CicTypeChecker in
216 let module CU = CicUniv in
217 (* no idea why ocaml wants this *)
218 let advance ?statement () = script#advance ?statement () in
219 let parsed_text_length = String.length parsed_text in
220 let dbd = MatitaDb.instance () in
223 | TA.WMatch (loc, term) ->
224 let term = disambiguate term status in
225 let l = MQ.match_term ~dbd term in
226 let entry = `Whelp (TAPp.pp_macro_cic (TA.WMatch (loc, term)), l) in
227 guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
228 [], parsed_text_length
229 | TA.WInstance (loc, term) ->
230 let term = disambiguate term status in
231 let l = MQ.instance ~dbd term in
232 let entry = `Whelp (TAPp.pp_macro_cic (TA.WInstance (loc, term)), l) in
233 guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
234 [], parsed_text_length
235 | TA.WLocate (loc, s) ->
236 let l = MQ.locate ~dbd s in
237 let entry = `Whelp (TAPp.pp_macro_cic (TA.WLocate (loc, s)), l) in
238 guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
239 [], parsed_text_length
240 | TA.WElim (loc, term) ->
241 let term = disambiguate term status in
244 | Cic.MutInd (uri,n,_) -> UriManager.uri_of_uriref uri n None
245 | _ -> failwith "Not a MutInd"
247 let l = MQ.elim ~dbd uri in
248 let entry = `Whelp (TAPp.pp_macro_cic (TA.WElim (loc, term)), l) in
249 guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
250 [], parsed_text_length
251 | TA.WHint (loc, term) ->
252 let term = disambiguate term status in
253 let s = ((None,[0,[],term], Cic.Meta (0,[]) ,term),0) in
254 let l = List.map fst (MQ.experimental_hint ~dbd s) in
255 let entry = `Whelp (TAPp.pp_macro_cic (TA.WHint (loc, term)), l) in
256 guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
257 [], parsed_text_length
260 let s = MatitaMisc.get_proof_status status in
261 let l = List.map fst (MQ.experimental_hint ~dbd s) in
262 let selected = guistuff.urichooser l in
264 | [] -> [], parsed_text_length
270 TA.Apply (loc, CicAst.Uri (UriManager.string_of_uri uri,None))))))
272 let new_status = MatitaEngine.eval_ast status ast in
274 comment parsed_text ^
275 "\n" ^ TAPp.pp_statement ast
277 [ new_status , extra_text ], parsed_text_length
280 "The result of the urichooser should be only 1 uri, not:\n";
282 fun u -> MatitaLog.error (UriManager.string_of_uri u ^ "\n")
285 | TA.Check (_,term) ->
286 let metasenv = MatitaMisc.get_proof_metasenv status in
287 let context = MatitaMisc.get_proof_context status in
288 let aliases = MatitaMisc.get_proof_aliases status in
290 MatitaDisambiguator.disambiguate_term
291 dbd context metasenv aliases term
293 let _, metasenv , term, ugraph =
298 let ty,_ = CTC.type_of_aux' metasenv context term ugraph in
299 let t_and_ty = Cic.Cast (term,ty) in
300 guistuff.mathviewer#show_entry (`Cic (t_and_ty,metasenv));
301 [], parsed_text_length
304 let status = script#status.proof_status in
307 | _ -> script#retract ();go_back()
309 [], parsed_text_length, Some go_back
310 | TA.Redo (_, Some i) -> [], parsed_text_length,
311 Some (fun () -> for j = 1 to i do advance () done)
312 | TA.Redo (_, None) -> [], parsed_text_length,
313 Some (fun () -> advance ())
314 | TA.Undo (_, Some i) -> [], parsed_text_length,
315 Some (fun () -> for j = 1 to i do script#retract () done)
316 | TA.Undo (_, None) -> [], parsed_text_length,
317 Some (fun () -> script#retract ()) *)
319 | TA.Quit _ -> failwith "not implemented"
320 | TA.Print (_,kind) -> failwith "not implemented"
321 | TA.Search_pat (_, search_kind, str) -> failwith "not implemented"
322 | TA.Search_term (_, search_kind, term) -> failwith "not implemented"
325 let eval_executable guistuff status user_goal parsed_text script ex =
326 let module TA = TacticAst in
327 let module TAPp = TacticAstPp in
328 let module MD = MatitaDisambiguator in
329 let module ML = MatitacleanLib in
330 let parsed_text_length = String.length parsed_text in
332 | TA.Command (loc, _) | TA.Tactical (loc, _) ->
334 (match ML.baseuri_of_baseuri_decl (TA.Executable (loc,ex)) with
337 if not (MatitacleanLib.is_empty u) then
339 guistuff.ask_confirmation
340 ~title:"Baseuri redefinition"
342 "Baseuri " ^ u ^ " already exists.\n" ^
343 "Do you want to redefine the corresponding "^
344 "part of the library?")
346 | `YES -> MatitacleanLib.clean_baseuris [u]
348 | `CANCEL -> raise MatitaTypes.Cancel);
350 guistuff status user_goal parsed_text (TA.Executable (loc, ex))
351 with MatitaTypes.Cancel -> [], 0)
352 | TA.Macro (_,mac) ->
353 eval_macro guistuff status parsed_text script mac
355 let rec eval_statement guistuff status user_goal script s =
356 if Pcre.pmatch ~rex:only_dust_RE s then raise Margin;
357 let st = CicTextualParser2.parse_statement (Stream.of_string s) in
358 let text_of_loc loc =
359 let parsed_text_length = snd (CicAst.loc_of_floc loc) in
360 let parsed_text = safe_substring s 0 parsed_text_length in
361 parsed_text, parsed_text_length
364 | TacticAst.Comment (loc,_)->
365 let parsed_text, parsed_text_length = text_of_loc loc in
366 let remain_len = String.length s - parsed_text_length in
367 let s = String.sub s parsed_text_length remain_len in
369 eval_statement guistuff status user_goal script s
372 | (status, text) :: tl ->
373 ((status, parsed_text ^ text)::tl), (parsed_text_length + len)
375 | TacticAst.Executable (loc, ex) ->
376 let parsed_text, parsed_text_length = text_of_loc loc in
377 eval_executable guistuff status user_goal parsed_text script ex
379 let fresh_script_id =
383 class script ~(buffer: GText.buffer) ~(init: MatitaTypes.status)
384 ~(mathviewer: MatitaTypes.mathViewer)
391 val scriptId = fresh_script_id ()
394 mathviewer = mathviewer;
395 urichooser = urichooser;
396 ask_confirmation = ask_confirmation;
397 develcreator = develcreator;
398 filenamedata = (None, None)}
400 method private getFilename =
401 match guistuff.filenamedata with Some f,_ -> f | _ -> assert false
403 method private ppFilename =
404 match guistuff.filenamedata with
406 | None,_ -> sprintf ".unnamed%d.ma" scriptId
409 ignore(GMain.Timeout.add ~ms:300000
410 ~callback:(fun _ -> self#_saveToBackuptFile ();true));
411 ignore(buffer#connect#modified_changed
412 (fun _ -> if buffer#modified then
413 set_star self#ppFilename true
415 set_star self#ppFilename false));
419 val mutable statements = []; (** executed statements *)
420 val mutable history = [ init ];
421 (** list of states before having executed statements. Head element of this
422 * list is the current state, last element is the state at the beginning of
424 * Invariant: this list length is 1 + length of statements *)
426 (** goal as seen by the user (i.e. metano corresponding to current tab) *)
427 val mutable userGoal = ~-1
429 (** text mark and tag representing locked part of a script *)
431 buffer#create_mark ~name:"locked" ~left_gravity:true buffer#start_iter
432 val locked_tag = buffer#create_tag [`BACKGROUND "lightblue"; `EDITABLE false]
434 (* history can't be empty, the invariant above grant that it contains at
435 * least the init status *)
436 method status = match history with hd :: _ -> hd | _ -> assert false
438 method private _advance ?statement () =
439 let s = match statement with Some s -> s | None -> self#getFuture in
440 MatitaLog.debug ("evaluating: " ^ first_line s ^ " ...");
441 let (entries, parsed_len) =
442 eval_statement guistuff self#status userGoal self s
444 let (new_statuses, new_statements) = List.split entries in
446 prerr_endline "evalStatement returned";
447 List.iter (fun s -> prerr_endline ("'" ^ s ^ "'")) new_statements;
449 history <- List.rev new_statuses @ history;
450 statements <- List.rev new_statements @ statements;
451 let start = buffer#get_iter_at_mark (`MARK locked_mark) in
452 let new_text = String.concat "" new_statements in
453 if new_text <> String.sub s 0 parsed_len then
455 (* prerr_endline ("new:" ^ new_text); *)
456 (* prerr_endline ("s:" ^ String.sub s 0 parsed_len); *)
457 let stop = start#copy#forward_chars parsed_len in
458 buffer#delete ~start ~stop;
459 buffer#insert ~iter:start new_text;
460 (* prerr_endline "AUTOMATICALLY MODIFIED!!!!!" *)
462 self#moveMark (String.length new_text)
464 method private _retract () =
465 match statements, history with
466 | last_statement :: _, cur_status :: prev_status :: _ ->
467 MatitaSync.time_travel ~present:cur_status ~past:prev_status;
468 statements <- List.tl statements;
469 history <- List.tl history;
470 self#moveMark (- (String.length last_statement));
473 method advance ?statement () =
475 self#_advance ?statement ();
478 | Margin -> self#notify
479 | exc -> self#notify; raise exc
486 | Margin -> self#notify
487 | exc -> self#notify; raise exc
489 method private getFuture =
490 buffer#get_text ~start:(buffer#get_iter_at_mark (`MARK locked_mark))
491 ~stop:buffer#end_iter ()
494 (** @param rel_offset relative offset from current position of locked_mark *)
495 method private moveMark rel_offset =
496 let mark = `MARK locked_mark in
497 let old_insert = buffer#get_iter_at_mark `INSERT in
498 buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
499 let current_mark_pos = buffer#get_iter_at_mark mark in
501 match rel_offset with
502 | 0 -> current_mark_pos
503 | n when n > 0 -> current_mark_pos#forward_chars n
504 | n (* when n < 0 *) -> current_mark_pos#backward_chars (abs n)
506 buffer#move_mark mark ~where:new_mark_pos;
507 buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:new_mark_pos;
508 buffer#move_mark `INSERT old_insert;
510 match self#status.proof_status with
511 Incomplete_proof (_,goal) -> self#setGoal goal
514 while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
516 method clean_dirty_lock =
517 let lock_mark_iter = buffer#get_iter_at_mark (`MARK locked_mark) in
518 buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
519 buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:lock_mark_iter
521 val mutable observers = []
523 method addObserver (o: MatitaTypes.status -> unit) =
524 observers <- o :: observers
526 method private notify =
527 let status = self#status in
528 List.iter (fun o -> o status) observers
530 method loadFromFile () =
531 buffer#set_text (MatitaMisc.input_file self#getFilename);
533 buffer#set_modified false
535 method assignFileName file =
536 let abspath = MatitaMisc.absolute_path file in
537 let devel = MatitamakeLib.development_for_dir (Filename.dirname abspath) in
538 guistuff.filenamedata <- Some abspath, devel
540 method saveToFile () =
541 let oc = open_out self#getFilename in
542 output_string oc (buffer#get_text ~start:buffer#start_iter
543 ~stop:buffer#end_iter ());
545 buffer#set_modified false
547 method private _saveToBackuptFile () =
548 if buffer#modified then
550 let f = self#ppFilename ^ "~" in
551 let oc = open_out f in
552 output_string oc (buffer#get_text ~start:buffer#start_iter
553 ~stop:buffer#end_iter ());
555 MatitaLog.debug ("backup " ^ f ^ " saved")
558 method private goto_top =
559 MatitaSync.time_travel ~present:self#status ~past:init;
563 buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
564 buffer#move_mark (`MARK locked_mark) ~where:buffer#start_iter
568 buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter;
570 buffer#set_modified false
573 let template = MatitaMisc.input_file BuildTimeConf.script_template in
574 buffer#insert ~iter:(buffer#get_iter `START) template;
575 guistuff.filenamedata <-
576 (None,MatitamakeLib.development_for_dir (Unix.getcwd ()));
577 buffer#set_modified false;
578 set_star self#ppFilename false
580 method goto (pos: [`Top | `Bottom | `Cursor]) () =
581 let getpos _ = buffer#get_iter_at_mark (`MARK locked_mark) in
583 | `Top -> self#goto_top; self#notify
586 let rec dowhile pos =
588 if pos#compare (getpos ()) < 0 then
594 | Margin -> self#notify
595 | exc -> self#notify; raise exc)
597 let locked_iter () = buffer#get_iter_at_mark (`NAME "locked") in
598 let cursor_iter () = buffer#get_iter_at_mark `INSERT in
599 let forward_until_cursor () = (* go forward until locked > cursor *)
602 if (locked_iter ())#compare (cursor_iter ()) < 0 &&
603 oldpos#compare (getpos ()) < 0
609 let rec back_until_cursor () = (* go backward until locked < cursor *)
611 if (locked_iter ())#compare (cursor_iter ()) > 0 then
614 let cmp = (locked_iter ())#compare (cursor_iter ()) in
616 if cmp < 0 then (* locked < cursor *)
617 (forward_until_cursor (); self#notify)
618 else if cmp > 0 then (* locked > cursor *)
619 (back_until_cursor (); self#notify)
620 else (* cursor = locked *)
623 | Margin -> self#notify
624 | exc -> self#notify; raise exc)
626 method onGoingProof () =
627 match self#status.proof_status with
628 | No_proof | Proof _ -> false
629 | Incomplete_proof _ -> true
630 | Intermediate _ -> assert false
632 method proofStatus = MatitaMisc.get_proof_status self#status
633 method proofMetasenv = MatitaMisc.get_proof_metasenv self#status
634 method proofContext = MatitaMisc.get_proof_context self#status
635 method setGoal n = userGoal <- n
638 let s = self#getFuture in
639 let rec is_there_and_executable s =
640 if Pcre.pmatch ~rex:only_dust_RE s then raise Margin;
641 let st = CicTextualParser2.parse_statement (Stream.of_string s) in
643 | TacticAst.Comment (loc,_)->
644 let parsed_text_length = snd (CicAst.loc_of_floc loc) in
645 let remain_len = String.length s - parsed_text_length in
646 let next = String.sub s parsed_text_length remain_len in
647 is_there_and_executable next
648 | TacticAst.Executable (loc, ex) -> false
651 is_there_and_executable s
653 | CicTextualParser2.Parse_error _ -> false
660 MatitaLog.debug "script status:";
661 MatitaLog.debug ("history size: " ^ string_of_int (List.length history));
662 MatitaLog.debug (sprintf "%d statements:" (List.length statements));
663 List.iter MatitaLog.debug statements;
664 MatitaLog.debug ("Current file name: " ^
665 (match guistuff.filenamedata with
666 |None,_ -> "[ no name ]"
671 let _script = ref None
673 let script ~buffer ~init ~mathviewer ~urichooser ~develcreator ~ask_confirmation ~set_star ()
676 ~buffer ~init ~mathviewer ~ask_confirmation ~urichooser ~develcreator ~set_star ()
681 let instance () = match !_script with None -> assert false | Some s -> s