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 = GrafiteAst in
65 let loc = Disambiguate.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 = GrafiteAst in
78 let module TAPp = GrafiteAstPp 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 (DisambiguatePp.pp_environment 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
155 while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
157 if not(MatitamakeLib.build_development_in_bg ~target refresh_cb d) then
160 eval_with_engine guistuff status user_goal parsed_text st
162 let do_nothing () = [], 0 in
163 let handle_with_devel d =
164 let name = MatitamakeLib.name_for_development d in
165 let title = "Unable to include " ^ what in
167 what ^ " is handled by development <b>" ^ name ^ "</b>.\n\n" ^
168 "<i>Should I compile it and Its dependencies?</i>"
170 (match guistuff.ask_confirmation ~title ~message with
171 | `YES -> compile_needed_and_go_on d
173 | `CANCEL -> do_nothing ())
175 let handle_withoud_devel filename =
176 let title = "Unable to include " ^ what in
178 what ^ " is <b>not</b> handled by a development.\n" ^
179 "All dependencies are authomatically solved for a development.\n\n" ^
180 "<i>Do you want to set up a development?</i>"
182 (match guistuff.ask_confirmation ~title ~message with
186 guistuff.develcreator ~containing:(Some (Filename.dirname f))
187 | None -> guistuff.develcreator ~containing:None);
190 | `CANCEL -> do_nothing())
192 match guistuff.filenamedata with
193 | None,None -> handle_withoud_devel None
194 | None,Some d -> handle_with_devel d
196 match MatitamakeLib.development_for_dir (Filename.dirname f) with
197 | None -> handle_withoud_devel (Some f)
198 | Some d -> handle_with_devel d
201 let disambiguate term status =
202 let module MD = MatitaDisambiguator in
203 let dbd = MatitaDb.instance () in
204 let metasenv = MatitaMisc.get_proof_metasenv status in
205 let context = MatitaMisc.get_proof_context status in
206 let aliases = MatitaMisc.get_proof_aliases status in
207 let interps = MD.disambiguate_term dbd context metasenv aliases term in
212 let eval_macro guistuff status parsed_text script mac
214 let module TA = GrafiteAst in
215 let module TAPp = GrafiteAstPp in
216 let module MQ = MetadataQuery in
217 let module MDB = MatitaDb in
218 let module CTC = CicTypeChecker in
219 let module CU = CicUniv in
220 (* no idea why ocaml wants this *)
221 let advance ?statement () = script#advance ?statement () in
222 let parsed_text_length = String.length parsed_text in
223 let dbd = MatitaDb.instance () in
226 | TA.WMatch (loc, term) ->
227 let term = disambiguate term status in
228 let l = MQ.match_term ~dbd term in
229 let entry = `Whelp (TAPp.pp_macro_cic (TA.WMatch (loc, term)), l) in
230 guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
231 [], parsed_text_length
232 | TA.WInstance (loc, term) ->
233 let term = disambiguate term status in
234 let l = MQ.instance ~dbd term in
235 let entry = `Whelp (TAPp.pp_macro_cic (TA.WInstance (loc, term)), l) in
236 guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
237 [], parsed_text_length
238 | TA.WLocate (loc, s) ->
239 let l = MQ.locate ~dbd s in
240 let entry = `Whelp (TAPp.pp_macro_cic (TA.WLocate (loc, s)), l) in
241 guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
242 [], parsed_text_length
243 | TA.WElim (loc, term) ->
244 let term = disambiguate term status in
247 | Cic.MutInd (uri,n,_) -> UriManager.uri_of_uriref uri n None
248 | _ -> failwith "Not a MutInd"
250 let l = MQ.elim ~dbd uri in
251 let entry = `Whelp (TAPp.pp_macro_cic (TA.WElim (loc, term)), l) in
252 guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
253 [], parsed_text_length
254 | TA.WHint (loc, term) ->
255 let term = disambiguate term status in
256 let s = ((None,[0,[],term], Cic.Meta (0,[]) ,term),0) in
257 let l = List.map fst (MQ.experimental_hint ~dbd s) in
258 let entry = `Whelp (TAPp.pp_macro_cic (TA.WHint (loc, term)), l) in
259 guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
260 [], parsed_text_length
263 let s = MatitaMisc.get_proof_status status in
264 let l = List.map fst (MQ.experimental_hint ~dbd s) in
265 let selected = guistuff.urichooser l in
267 | [] -> [], parsed_text_length
273 TA.Apply (loc, CicNotationPt.Uri (UriManager.string_of_uri uri,None))))))
275 let new_status = MatitaEngine.eval_ast status ast in
277 comment parsed_text ^
278 "\n" ^ TAPp.pp_statement ast
280 [ new_status , extra_text ], parsed_text_length
283 "The result of the urichooser should be only 1 uri, not:\n";
285 fun u -> MatitaLog.error (UriManager.string_of_uri u ^ "\n")
288 | TA.Check (_,term) ->
289 let metasenv = MatitaMisc.get_proof_metasenv status in
290 let context = MatitaMisc.get_proof_context status in
291 let aliases = MatitaMisc.get_proof_aliases status in
293 MatitaDisambiguator.disambiguate_term
294 dbd context metasenv aliases term
296 let _, metasenv , term, ugraph =
301 let ty,_ = CTC.type_of_aux' metasenv context term ugraph in
302 let t_and_ty = Cic.Cast (term,ty) in
303 guistuff.mathviewer#show_entry (`Cic (t_and_ty,metasenv));
304 [], parsed_text_length
307 let status = script#status.proof_status in
310 | _ -> script#retract ();go_back()
312 [], parsed_text_length, Some go_back
313 | TA.Redo (_, Some i) -> [], parsed_text_length,
314 Some (fun () -> for j = 1 to i do advance () done)
315 | TA.Redo (_, None) -> [], parsed_text_length,
316 Some (fun () -> advance ())
317 | TA.Undo (_, Some i) -> [], parsed_text_length,
318 Some (fun () -> for j = 1 to i do script#retract () done)
319 | TA.Undo (_, None) -> [], parsed_text_length,
320 Some (fun () -> script#retract ()) *)
322 | TA.Quit _ -> failwith "not implemented"
323 | TA.Print (_,kind) -> failwith "not implemented"
324 | TA.Search_pat (_, search_kind, str) -> failwith "not implemented"
325 | TA.Search_term (_, search_kind, term) -> failwith "not implemented"
328 let eval_executable guistuff status user_goal parsed_text script ex =
329 let module TA = GrafiteAst in
330 let module TAPp = GrafiteAstPp in
331 let module MD = MatitaDisambiguator in
332 let module ML = MatitacleanLib in
333 let parsed_text_length = String.length parsed_text in
335 | TA.Command (loc, _) | TA.Tactical (loc, _) ->
337 (match ML.baseuri_of_baseuri_decl (TA.Executable (loc,ex)) with
340 if not (ML.is_empty u) then
342 guistuff.ask_confirmation
343 ~title:"Baseuri redefinition"
345 "Baseuri " ^ u ^ " already exists.\n" ^
346 "Do you want to redefine the corresponding "^
347 "part of the library?")
349 | `YES -> MatitacleanLib.clean_baseuris [u]
351 | `CANCEL -> raise MatitaTypes.Cancel);
353 guistuff status user_goal parsed_text (TA.Executable (loc, ex))
354 with MatitaTypes.Cancel -> [], 0)
355 | TA.Macro (_,mac) ->
356 eval_macro guistuff status parsed_text script mac
358 let rec eval_statement guistuff status user_goal script s =
359 if Pcre.pmatch ~rex:only_dust_RE s then raise Margin;
360 let st = GrafiteParser.parse_statement (Stream.of_string s) in
361 let text_of_loc loc =
362 let parsed_text_length = snd (CicNotationPt.loc_of_floc loc) in
363 let parsed_text = safe_substring s 0 parsed_text_length in
364 parsed_text, parsed_text_length
367 | GrafiteAst.Comment (loc,_)->
368 let parsed_text, parsed_text_length = text_of_loc loc in
369 let remain_len = String.length s - parsed_text_length in
370 let s = String.sub s parsed_text_length remain_len in
372 eval_statement guistuff status user_goal script s
375 | (status, text) :: tl ->
376 ((status, parsed_text ^ text)::tl), (parsed_text_length + len)
378 | GrafiteAst.Executable (loc, ex) ->
379 let parsed_text, parsed_text_length = text_of_loc loc in
380 eval_executable guistuff status user_goal parsed_text script ex
382 let fresh_script_id =
386 class script ~(view: GText.view)
387 ~(init: MatitaTypes.status)
388 ~(mathviewer: MatitaTypes.mathViewer)
394 let buffer = view#buffer in
396 val scriptId = fresh_script_id ()
399 mathviewer = mathviewer;
400 urichooser = urichooser;
401 ask_confirmation = ask_confirmation;
402 develcreator = develcreator;
403 filenamedata = (None, None)}
405 method private getFilename =
406 match guistuff.filenamedata with Some f,_ -> f | _ -> assert false
408 method private ppFilename =
409 match guistuff.filenamedata with
411 | None,_ -> sprintf ".unnamed%d.ma" scriptId
414 ignore(GMain.Timeout.add ~ms:300000
415 ~callback:(fun _ -> self#_saveToBackuptFile ();true));
416 ignore(buffer#connect#modified_changed
417 (fun _ -> if buffer#modified then
418 set_star self#ppFilename true
420 set_star self#ppFilename false))
422 val mutable statements = []; (** executed statements *)
423 val mutable history = [ init ];
424 (** list of states before having executed statements. Head element of this
425 * list is the current state, last element is the state at the beginning of
427 * Invariant: this list length is 1 + length of statements *)
429 (** goal as seen by the user (i.e. metano corresponding to current tab) *)
430 val mutable userGoal = ~-1
432 (** text mark and tag representing locked part of a script *)
434 buffer#create_mark ~name:"locked" ~left_gravity:true buffer#start_iter
435 val locked_tag = buffer#create_tag [`BACKGROUND "lightblue"; `EDITABLE false]
437 method locked_mark = locked_mark
439 (* history can't be empty, the invariant above grant that it contains at
440 * least the init status *)
441 method status = match history with hd :: _ -> hd | _ -> assert false
443 method private _advance ?statement () =
444 let s = match statement with Some s -> s | None -> self#getFuture in
445 MatitaLog.debug ("evaluating: " ^ first_line s ^ " ...");
446 let (entries, parsed_len) =
447 eval_statement guistuff self#status userGoal self s
449 let (new_statuses, new_statements) = List.split entries in
451 prerr_endline "evalStatement returned";
452 List.iter (fun s -> prerr_endline ("'" ^ s ^ "'")) new_statements;
454 history <- List.rev new_statuses @ history;
455 statements <- List.rev new_statements @ statements;
456 let start = buffer#get_iter_at_mark (`MARK locked_mark) in
457 let new_text = String.concat "" new_statements in
458 if new_text <> String.sub s 0 parsed_len then
460 (* prerr_endline ("new:" ^ new_text); *)
461 (* prerr_endline ("s:" ^ String.sub s 0 parsed_len); *)
462 let stop = start#copy#forward_chars parsed_len in
463 buffer#delete ~start ~stop;
464 buffer#insert ~iter:start new_text;
465 (* prerr_endline "AUTOMATICALLY MODIFIED!!!!!" *)
467 self#moveMark (String.length new_text)
469 method private _retract offset status new_statements new_history =
470 let cur_status = match history with s::_ -> s | [] -> assert false in
471 MatitaSync.time_travel ~present:cur_status ~past:status;
472 statements <- new_statements;
473 history <- new_history;
474 self#moveMark (- offset)
476 method advance ?statement () =
478 self#_advance ?statement ();
481 | Margin -> self#notify
482 | exc -> self#notify; raise exc
486 let cmp,new_statements,new_history,status =
487 match statements,history with
488 stat::statements, _::(status::_ as history) ->
489 String.length stat, statements, history, status
490 | [],[_] -> raise Margin
491 | _,_ -> assert false
493 self#_retract cmp status new_statements new_history;
496 | Margin -> self#notify
497 | exc -> self#notify; raise exc
499 method private getFuture =
500 buffer#get_text ~start:(buffer#get_iter_at_mark (`MARK locked_mark))
501 ~stop:buffer#end_iter ()
504 (** @param rel_offset relative offset from current position of locked_mark *)
505 method private moveMark rel_offset =
506 let mark = `MARK locked_mark in
507 let old_insert = buffer#get_iter_at_mark `INSERT in
508 buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
509 let current_mark_pos = buffer#get_iter_at_mark mark in
511 match rel_offset with
512 | 0 -> current_mark_pos
513 | n when n > 0 -> current_mark_pos#forward_chars n
514 | n (* when n < 0 *) -> current_mark_pos#backward_chars (abs n)
516 buffer#move_mark mark ~where:new_mark_pos;
517 buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:new_mark_pos;
518 buffer#move_mark `INSERT old_insert;
520 match self#status.proof_status with
521 Incomplete_proof (_,goal) -> self#setGoal goal
524 let mark_position = buffer#get_iter_at_mark mark in
525 if view#move_mark_onscreen mark then
527 buffer#move_mark mark mark_position;
528 view#scroll_to_mark ~use_align:true ~xalign:1.0 ~yalign:0.1 mark;
530 while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
532 method clean_dirty_lock =
533 let lock_mark_iter = buffer#get_iter_at_mark (`MARK locked_mark) in
534 buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
535 buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:lock_mark_iter
537 val mutable observers = []
539 method addObserver (o: MatitaTypes.status -> unit) =
540 observers <- o :: observers
542 method private notify =
543 let status = self#status in
544 List.iter (fun o -> o status) observers
546 method loadFromFile () =
547 buffer#set_text (MatitaMisc.input_file self#getFilename);
549 buffer#set_modified false
551 method assignFileName file =
552 let abspath = MatitaMisc.absolute_path file in
553 let devel = MatitamakeLib.development_for_dir (Filename.dirname abspath) in
554 guistuff.filenamedata <- Some abspath, devel
556 method saveToFile () =
557 let oc = open_out self#getFilename in
558 output_string oc (buffer#get_text ~start:buffer#start_iter
559 ~stop:buffer#end_iter ());
561 buffer#set_modified false
563 method private _saveToBackuptFile () =
564 if buffer#modified then
566 let f = self#ppFilename ^ "~" in
567 let oc = open_out f in
568 output_string oc (buffer#get_text ~start:buffer#start_iter
569 ~stop:buffer#end_iter ());
571 MatitaLog.debug ("backup " ^ f ^ " saved")
574 method private goto_top =
575 MatitaSync.time_travel ~present:self#status ~past:init;
579 buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
580 buffer#move_mark (`MARK locked_mark) ~where:buffer#start_iter
584 buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter;
586 buffer#set_modified false
589 let template = MatitaMisc.input_file BuildTimeConf.script_template in
590 buffer#insert ~iter:(buffer#get_iter `START) template;
591 guistuff.filenamedata <-
592 (None,MatitamakeLib.development_for_dir (Unix.getcwd ()));
593 buffer#set_modified false;
594 set_star self#ppFilename false
596 method goto (pos: [`Top | `Bottom | `Cursor]) () =
597 let getpos _ = buffer#get_iter_at_mark (`MARK locked_mark) in
599 | `Top -> self#goto_top; self#notify
602 let rec dowhile pos =
604 if pos#compare (getpos ()) < 0 then
610 | Margin -> self#notify
611 | exc -> self#notify; raise exc)
613 let locked_iter () = buffer#get_iter_at_mark (`NAME "locked") in
614 let cursor_iter = buffer#get_iter_at_mark `INSERT in
615 let cmp = (locked_iter ())#offset - cursor_iter#offset in
616 let forward_until_cursor () = (* go forward until locked > cursor *)
619 if (locked_iter ())#compare cursor_iter < 0 &&
620 oldpos#compare (getpos ()) < 0
626 let rec back_until_cursor len = (* go backward until locked < cursor *)
628 statements, (status::_ as history) when len <= 0 ->
629 self#_retract (cmp - len) status statements history
630 | statement::tl1, _::tl2 ->
631 back_until_cursor (len - String.length statement) (tl1,tl2)
632 | _,_ -> assert false
635 if cmp < 0 then (* locked < cursor *)
636 (forward_until_cursor (); self#notify)
637 else if cmp > 0 then (* locked > cursor *)
638 (back_until_cursor cmp (statements,history); self#notify)
639 else (* cursor = locked *)
642 | Margin -> self#notify
643 | exc -> self#notify; raise exc)
645 method onGoingProof () =
646 match self#status.proof_status with
647 | No_proof | Proof _ -> false
648 | Incomplete_proof _ -> true
649 | Intermediate _ -> assert false
651 method proofStatus = MatitaMisc.get_proof_status self#status
652 method proofMetasenv = MatitaMisc.get_proof_metasenv self#status
653 method proofContext = MatitaMisc.get_proof_context self#status
654 method setGoal n = userGoal <- n
657 let s = self#getFuture in
658 let rec is_there_and_executable s =
659 if Pcre.pmatch ~rex:only_dust_RE s then raise Margin;
660 let st = GrafiteParser.parse_statement (Stream.of_string s) in
662 | GrafiteAst.Comment (loc,_)->
663 let parsed_text_length = snd (CicNotationPt.loc_of_floc loc) in
664 let remain_len = String.length s - parsed_text_length in
665 let next = String.sub s parsed_text_length remain_len in
666 is_there_and_executable next
667 | GrafiteAst.Executable (loc, ex) -> false
670 is_there_and_executable s
672 | CicNotationParser.Parse_error _ -> false
679 MatitaLog.debug "script status:";
680 MatitaLog.debug ("history size: " ^ string_of_int (List.length history));
681 MatitaLog.debug (sprintf "%d statements:" (List.length statements));
682 List.iter MatitaLog.debug statements;
683 MatitaLog.debug ("Current file name: " ^
684 (match guistuff.filenamedata with
685 |None,_ -> "[ no name ]"
690 let _script = ref None
692 let script ~view ~init ~mathviewer ~urichooser ~develcreator ~ask_confirmation ~set_star ()
695 ~view ~init ~mathviewer ~ask_confirmation ~urichooser ~develcreator ~set_star ()
700 let instance () = match !_script with None -> assert false | Some s -> s