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/
31 module TA = GrafiteAst
34 let debug_print = if debug then prerr_endline else ignore
36 (** raised when one of the script margins (top or bottom) is reached *)
38 exception NoUnfinishedProof
39 exception ActionCancelled of string
41 let safe_substring s i j =
42 try String.sub s i j with Invalid_argument _ -> assert false
44 let heading_nl_RE = Pcre.regexp "^\\s*\n\\s*"
45 let heading_nl_RE' = Pcre.regexp "^(\\s*\n\\s*)"
46 let only_dust_RE = Pcre.regexp "^(\\s|\n|%%[^\n]*\n)*$"
47 let multiline_RE = Pcre.regexp "^\n[^\n]+$"
48 let newline_RE = Pcre.regexp "\n"
49 let comment_RE = Pcre.regexp "\\(\\*(.|\n)*\\*\\)\n?" ~flags:[`UNGREEDY]
52 if Pcre.pmatch ~rex:multiline_RE str then
53 "\n(** " ^ (Pcre.replace ~rex:newline_RE str) ^ " *)"
55 "\n(**\n" ^ str ^ "\n*)"
57 let strip_comments str =
58 Pcre.qreplace ~templ:"\n" ~pat:"\n\n" (Pcre.qreplace ~rex:comment_RE str)
62 let s = Pcre.replace ~rex:heading_nl_RE s in
64 let nl_pos = String.index s '\n' in
69 mathviewer:MatitaTypes.mathViewer;
70 urichooser: NReference.reference list -> NReference.reference list;
71 ask_confirmation: title:string -> message:string -> [`YES | `NO | `CANCEL];
74 let eval_with_engine include_paths guistuff grafite_status user_goal
75 skipped_txt nonskipped_txt st
77 let parsed_text_length =
78 String.length skipped_txt + String.length nonskipped_txt
80 let text = skipped_txt ^ nonskipped_txt in
81 let prefix_len = MatitaGtkMisc.utf8_string_length skipped_txt in
82 let enriched_history_fragment =
83 MatitaEngine.eval_ast ~include_paths ~do_heavy_checks:(Helm_registry.get_bool
84 "matita.do_heavy_checks")
85 grafite_status (text,prefix_len,st)
87 let enriched_history_fragment = List.rev enriched_history_fragment in
91 (fun (acc, to_prepend) (status,alias) ->
93 | None -> (status,to_prepend ^ nonskipped_txt)::acc,""
95 let newtxt = GrafiteAstPp.pp_alias value in
96 (status,to_prepend ^ newtxt ^ "\n")::acc, "")
97 ([],skipped_txt) enriched_history_fragment
99 res,"",parsed_text_length
102 let pp_eager_statement_ast = GrafiteAstPp.pp_statement
104 let eval_nmacro include_paths (buffer : GText.buffer) guistuff grafite_status user_goal unparsed_text parsed_text script mac =
105 let parsed_text_length = String.length parsed_text in
107 | TA.Screenshot (_,name) ->
108 let status = script#grafite_status in
109 let _,_,menv,subst,_ = status#obj in
110 let name = Filename.dirname (script#filename) ^ "/" ^ name in
112 let selected = Continuationals.Stack.head_goals status#stack in
113 List.filter (fun x,_ -> List.mem x selected) menv
115 guistuff.mathviewer#screenshot status sequents menv subst name;
116 [status, parsed_text], "", parsed_text_length
118 let status = script#grafite_status in
119 let _,_,menv,subst,_ = status#obj in
121 try let _,(_,ctx,_) = List.hd menv in ctx
122 with Failure "hd" -> []
124 let m, s, status, t =
125 GrafiteDisambiguate.disambiguate_nterm
126 status None ctx menv subst (parsed_text,parsed_text_length,
127 NotationPt.Cast (t,NotationPt.Implicit `JustOne))
128 (* XXX use the metasenv, if possible *)
130 guistuff.mathviewer#show_entry (`NCic (t,ctx,m,s));
131 [status, parsed_text], "", parsed_text_length
132 | TA.NIntroGuess _loc ->
133 let names_ref = ref [] in
135 NTactics.intros_tac ~names_ref [] script#grafite_status
137 let rex = Pcre.regexp ~flags:[`MULTILINE] "\\A([\\n\\t\\r ]*).*\\Z" in
138 let nl = Pcre.replace ~rex ~templ:"$1" parsed_text in
139 [s, nl ^ "#" ^ String.concat " " !names_ref ^ ";"], "", parsed_text_length
140 | TA.NAutoInteractive (_loc, (None,a)) ->
141 let trace_ref = ref [] in
144 ~params:(None,a) ~trace_ref script#grafite_status
147 try List.assoc "depth" a
150 let trace = "/"^(if int_of_string depth > 1 then depth else "")^"/ by " in
152 match !trace_ref with
156 (HExtlib.filter_map (function
157 | NotationPt.NRef r -> Some (NCicPp.r2s true r)
161 let rex = Pcre.regexp ~flags:[`MULTILINE] "\\A([\\n\\t\\r ]*).*\\Z" in
162 let nl = Pcre.replace ~rex ~templ:"$1" parsed_text in
163 [s, nl ^ trace ^ thms ^ ";"], "", parsed_text_length
164 | TA.NAutoInteractive (_, (Some _,_)) -> assert false
166 let rec eval_executable include_paths (buffer : GText.buffer) guistuff
167 grafite_status user_goal unparsed_text skipped_txt nonskipped_txt
171 ignore (buffer#move_mark (`NAME "beginning_of_statement")
172 ~where:((buffer#get_iter_at_mark (`NAME "locked"))#forward_chars
173 (Glib.Utf8.length skipped_txt))) ;
174 eval_with_engine include_paths
175 guistuff grafite_status user_goal skipped_txt nonskipped_txt
176 (TA.Executable (loc, ex))
178 MatitaTypes.Cancel -> [], "", 0
179 | GrafiteEngine.NMacro (_loc,macro) ->
180 eval_nmacro include_paths buffer guistuff grafite_status
181 user_goal unparsed_text (skipped_txt ^ nonskipped_txt) script macro
184 and eval_statement include_paths (buffer : GText.buffer) guistuff
185 grafite_status user_goal script statement
187 let st,unparsed_text =
190 if Pcre.pmatch ~rex:only_dust_RE text then raise Margin;
191 let ast = MatitaEngine.toplevel grafite_status include_paths text in
193 | `Ast (st, text) -> st, text
195 let text_of_loc floc =
196 let nonskipped_txt,_ = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
197 let start, stop = HExtlib.loc_of_floc floc in
198 let floc = HExtlib.floc_of_loc (0, start) in
199 let skipped_txt,_ = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
200 let floc = HExtlib.floc_of_loc (0, stop) in
201 let txt,len = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
202 txt,nonskipped_txt,skipped_txt,len
205 | GrafiteAst.Executable (loc, ex) ->
206 let _, nonskipped, skipped, parsed_text_length = text_of_loc loc in
207 eval_executable include_paths buffer guistuff
208 grafite_status user_goal unparsed_text skipped nonskipped script ex loc
209 | GrafiteAst.Comment (loc, GrafiteAst.Code (_, ex))
210 when Helm_registry.get_bool "matita.execcomments" ->
211 let _, nonskipped, skipped, parsed_text_length = text_of_loc loc in
212 eval_executable include_paths buffer guistuff
213 grafite_status user_goal unparsed_text skipped nonskipped script ex loc
214 | GrafiteAst.Comment (loc, _) ->
215 let parsed_text, _, _, parsed_text_length = text_of_loc loc in
216 let remain_len = String.length unparsed_text - parsed_text_length in
217 let s = String.sub unparsed_text parsed_text_length remain_len in
220 eval_statement include_paths buffer guistuff
221 grafite_status user_goal script (`Raw s)
223 HExtlib.Localized (floc, exn) ->
224 HExtlib.raise_localized_exception
225 ~offset:(MatitaGtkMisc.utf8_string_length parsed_text) floc exn
226 | MultiPassDisambiguator.DisambiguationError (offset,errorll) ->
228 (MultiPassDisambiguator.DisambiguationError
229 (offset+parsed_text_length, errorll))
231 assert (text=""); (* no macros inside comments, please! *)
233 | (statuses,text)::tl ->
234 (statuses,parsed_text ^ text)::tl,"",parsed_text_length + len
237 let fresh_script_id =
241 class script ~(source_view: GSourceView2.source_view)
242 ~(mathviewer: MatitaTypes.mathViewer)
247 let buffer = source_view#buffer in
248 let source_buffer = source_view#source_buffer in
249 let initial_statuses current baseuri =
250 let empty_lstatus = new GrafiteDisambiguate.status in
253 NCicLibrary.time_travel
254 ((new GrafiteTypes.status current#baseuri)#set_disambiguate_db current#disambiguate_db);
255 (* CSC: there is a known bug in invalidation; temporary fix here *)
256 NCicEnvironment.invalidate ()
258 let lexicon_status = empty_lstatus in
259 let grafite_status = (new GrafiteTypes.status baseuri)#set_disambiguate_db lexicon_status#disambiguate_db in
262 let read_include_paths file =
264 let root, _buri, _fname, _tgt =
265 Librarian.baseuri_of_script ~include_paths:[] file
268 Str.split (Str.regexp " ")
269 (List.assoc "include_paths" (Librarian.load_root_file (root^"/root")))
271 List.iter (HLog.debug) rc; rc
272 with Librarian.NoRootFor _ | Not_found -> []
274 let default_buri = "cic:/matita/tests" in
275 let default_fname = ".unnamed.ma" in
277 val mutable include_paths_ = []
279 val scriptId = fresh_script_id ()
282 mathviewer = mathviewer;
283 urichooser = urichooser;
284 ask_confirmation = ask_confirmation;
287 val mutable filename_ = (None : string option)
289 method has_name = filename_ <> None
291 method include_paths =
293 Helm_registry.get_list Helm_registry.string "matita.includes"
295 method private curdir =
297 let root, _buri, _fname, _tgt =
298 Librarian.baseuri_of_script ~include_paths:self#include_paths
302 with Librarian.NoRootFor _ -> Sys.getcwd ()
304 method buri_of_current_file =
306 | None -> default_buri
309 let _root, buri, _fname, _tgt =
310 Librarian.baseuri_of_script ~include_paths:self#include_paths f
313 with Librarian.NoRootFor _ -> default_buri
315 method filename = match filename_ with None -> default_fname | Some f -> f
318 ignore (GMain.Timeout.add ~ms:300000
319 ~callback:(fun _ -> self#_saveToBackupFile ();true));
320 ignore (buffer#connect#modified_changed
321 (fun _ -> set_star buffer#modified))
323 val mutable statements = [] (** executed statements *)
325 val mutable history = [ initial_statuses None default_buri ]
326 (** list of states before having executed statements. Head element of this
327 * list is the current state, last element is the state at the beginning of
329 * Invariant: this list length is 1 + length of statements *)
331 (** goal as seen by the user (i.e. metano corresponding to current tab) *)
332 val mutable userGoal = (None : int option)
334 (** text mark and tag representing locked part of a script *)
336 buffer#create_mark ~name:"locked" ~left_gravity:true buffer#start_iter
337 val beginning_of_statement_mark =
338 buffer#create_mark ~name:"beginning_of_statement"
339 ~left_gravity:true buffer#start_iter
340 val locked_tag = buffer#create_tag [`BACKGROUND "lightblue"; `EDITABLE false]
341 val error_tag = buffer#create_tag [`UNDERLINE `SINGLE; `FOREGROUND "red"]
343 method locked_mark = locked_mark
344 method locked_tag = locked_tag
345 method error_tag = error_tag
347 (* history can't be empty, the invariant above grant that it contains at
348 * least the init grafite_status *)
349 method grafite_status = match history with s::_ -> s | _ -> assert false
351 method private _advance ?statement () =
352 let s = match statement with Some s -> s | None -> self#getFuture in
353 if self#bos then LibraryClean.clean_baseuris [self#buri_of_current_file];
354 HLog.debug ("evaluating: " ^ first_line s ^ " ...");
355 let time1 = Unix.gettimeofday () in
356 let entries, newtext, parsed_len =
358 eval_statement self#include_paths buffer guistuff
359 self#grafite_status userGoal self (`Raw s)
360 with End_of_file -> raise Margin
362 let time2 = Unix.gettimeofday () in
363 HLog.debug ("... done in " ^ string_of_float (time2 -. time1) ^ "s");
364 let new_statuses, new_statements =
365 let statuses, texts = List.split entries in
368 history <- new_statuses @ history;
369 statements <- new_statements @ statements;
370 let start = buffer#get_iter_at_mark (`MARK locked_mark) in
371 let new_text = String.concat "" (List.rev new_statements) in
372 if statement <> None then
373 buffer#insert ~iter:start new_text
375 let parsed_text = String.sub s 0 parsed_len in
376 if new_text <> parsed_text then begin
377 let stop = start#copy#forward_chars (Glib.Utf8.length parsed_text) in
378 buffer#delete ~start ~stop;
379 buffer#insert ~iter:start new_text;
382 self#moveMark (Glib.Utf8.length new_text);
383 buffer#insert ~iter:(buffer#get_iter_at_mark (`MARK locked_mark)) newtext;
384 (* here we need to set the Goal in case we are going to cursor (or to
385 bottom) and we will face a macro *)
388 method private _retract offset grafite_status new_statements new_history =
389 NCicLibrary.time_travel grafite_status;
390 statements <- new_statements;
391 history <- new_history;
392 self#moveMark (- offset)
394 method advance ?statement () =
396 self#_advance ?statement ();
399 | Margin -> self#notify
400 | Not_found -> assert false
401 | Invalid_argument "Array.make" -> HLog.error "The script is too big!\n"
402 | exc -> self#notify; raise exc
406 let cmp,new_statements,new_history,grafite_status =
407 match statements,history with
408 stat::statements, _::(status::_ as history) ->
409 assert (Glib.Utf8.validate stat);
410 Glib.Utf8.length stat, statements, history, status
411 | [],[_] -> raise Margin
412 | _,_ -> assert false
414 self#_retract cmp grafite_status new_statements
418 | Margin -> self#notify
419 | Invalid_argument "Array.make" -> HLog.error "The script is too big!\n"
420 | exc -> self#notify; raise exc
422 method private getFuture =
423 let lock = buffer#get_iter_at_mark (`MARK locked_mark) in
424 let text = buffer#get_text ~start:lock ~stop:buffer#end_iter () in
427 method expandAllVirtuals =
428 let lock = buffer#get_iter_at_mark (`MARK locked_mark) in
429 let text = buffer#get_text ~start:lock ~stop:buffer#end_iter () in
430 buffer#delete ~start:lock ~stop:buffer#end_iter;
431 let text = Pcre.replace ~pat:":=" ~templ:"\\def" text in
432 let text = Pcre.replace ~pat:"->" ~templ:"\\to" text in
433 let text = Pcre.replace ~pat:"=>" ~templ:"\\Rightarrow" text in
435 Pcre.substitute_substrings
437 let pristine = Pcre.get_substring str 0 in
439 if pristine.[0] = ' ' then
440 String.sub pristine 1 (String.length pristine -1)
444 if input.[String.length input-1] = ' ' then
445 String.sub input 0 (String.length input -1)
449 if input = "\\forall" ||
450 input = "\\lambda" ||
451 input = "\\exists" then "","" else " ", " "
454 before ^ Glib.Utf8.from_unichar
455 (snd (Virtuals.symbol_of_virtual input)) ^ after
456 with Virtuals.Not_a_virtual -> pristine)
457 ~pat:" ?\\\\[a-zA-Z]+ ?" text
459 buffer#insert ~iter:lock text
461 (** @param rel_offset relative offset from current position of locked_mark *)
462 method private moveMark rel_offset =
463 let mark = `MARK locked_mark in
464 let old_insert = buffer#get_iter_at_mark `INSERT in
465 buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
466 let current_mark_pos = buffer#get_iter_at_mark mark in
468 match rel_offset with
469 | 0 -> current_mark_pos
470 | n when n > 0 -> current_mark_pos#forward_chars n
471 | n (* when n < 0 *) -> current_mark_pos#backward_chars (abs n)
473 buffer#move_mark mark ~where:new_mark_pos;
474 buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:new_mark_pos;
475 buffer#move_mark `INSERT old_insert;
476 let mark_position = buffer#get_iter_at_mark mark in
477 if source_view#move_mark_onscreen mark then
479 buffer#move_mark mark mark_position;
480 source_view#scroll_to_mark ~use_align:true ~xalign:1.0 ~yalign:0.1 mark;
482 while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
484 method clean_dirty_lock =
485 let lock_mark_iter = buffer#get_iter_at_mark (`MARK locked_mark) in
486 buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
487 buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:lock_mark_iter
489 val mutable observers = []
491 method addObserver (o: GrafiteTypes.status -> unit) =
492 observers <- o :: observers
494 method private notify =
495 let grafite_status = self#grafite_status in
496 List.iter (fun o -> o grafite_status) observers
498 method loadFromString s =
501 buffer#set_modified true
503 method loadFromFile f =
504 buffer#set_text (HExtlib.input_file f);
506 buffer#set_modified false
508 method assignFileName file =
511 | Some f -> Some (Librarian.absolutize f)
516 (match file with Some file -> read_include_paths file | None -> []);
518 Sys.chdir self#curdir;
519 HLog.debug ("Moving to " ^ Sys.getcwd ())
521 method saveToFile () =
522 if self#has_name then
523 let oc = open_out self#filename in
524 output_string oc (buffer#get_text ~start:buffer#start_iter
525 ~stop:buffer#end_iter ());
528 buffer#set_modified false
530 HLog.error "Can't save, no filename selected"
532 method private _saveToBackupFile () =
533 if buffer#modified then
535 let f = self#filename in
536 let oc = open_out f in
537 output_string oc (buffer#get_text ~start:buffer#start_iter
538 ~stop:buffer#end_iter ());
540 HLog.debug ("backup " ^ f ^ " saved")
543 method private reset_buffer =
545 history <- [ initial_statuses (Some self#grafite_status) self#buri_of_current_file ];
548 buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
549 buffer#move_mark (`MARK locked_mark) ~where:buffer#start_iter
553 source_buffer#begin_not_undoable_action ();
554 buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter;
555 source_buffer#end_not_undoable_action ();
556 buffer#set_modified false;
559 let template = HExtlib.input_file BuildTimeConf.script_template in
560 buffer#insert ~iter:(buffer#get_iter `START) template;
561 buffer#set_modified false;
564 method goto (pos: [`Top | `Bottom | `Cursor]) () =
566 let old_locked_mark =
568 (buffer#create_mark ~name:"old_locked_mark"
569 ~left_gravity:true (buffer#get_iter_at_mark (`MARK locked_mark))) in
570 let getpos _ = buffer#get_iter_at_mark (`MARK locked_mark) in
571 let getoldpos _ = buffer#get_iter_at_mark old_locked_mark in
572 let dispose_old_locked_mark () = buffer#delete_mark old_locked_mark in
575 dispose_old_locked_mark ();
582 let newpos = getpos () in
583 if (getoldpos ())#compare newpos < 0 then
585 buffer#move_mark old_locked_mark newpos;
590 dispose_old_locked_mark ();
593 | Margin -> dispose_old_locked_mark (); self#notify
594 | exc -> dispose_old_locked_mark (); self#notify; raise exc)
596 let locked_iter () = buffer#get_iter_at_mark (`NAME "locked") in
597 let cursor_iter () = buffer#get_iter_at_mark `INSERT in
600 (buffer#create_mark ~name:"initial_insert"
601 ~left_gravity:true (cursor_iter ())) in
602 let dispose_remember () = buffer#delete_mark remember in
603 let remember_iter () =
604 buffer#get_iter_at_mark (`NAME "initial_insert") in
605 let cmp () = (locked_iter ())#offset - (remember_iter ())#offset in
607 let forward_until_cursor () = (* go forward until locked > cursor *)
610 if cmp () < 0 && (getoldpos ())#compare (getpos ()) < 0
613 buffer#move_mark old_locked_mark (getpos ());
619 let rec back_until_cursor len = (* go backward until locked < cursor *)
621 statements, ((grafite_status)::_ as history)
623 self#_retract (icmp - len) grafite_status statements
625 | statement::tl1, _::tl2 ->
626 back_until_cursor (len - MatitaGtkMisc.utf8_string_length statement) (tl1,tl2)
627 | _,_ -> assert false
631 if icmp < 0 then (* locked < cursor *)
632 (forward_until_cursor (); self#notify)
633 else if icmp > 0 then (* locked > cursor *)
634 (back_until_cursor icmp (statements,history); self#notify)
635 else (* cursor = locked *)
639 dispose_old_locked_mark ();
641 | Margin -> dispose_remember (); dispose_old_locked_mark (); self#notify
642 | exc -> dispose_remember (); dispose_old_locked_mark ();
643 self#notify; raise exc)
644 with Invalid_argument "Array.make" ->
645 HLog.error "The script is too big!\n"
647 method stack = (assert false : Continuationals.Stack.t) (* MATITA 1.0 GrafiteTypes.get_stack
648 self#grafite_status *)
649 method setGoal n = userGoal <- n
650 method goal = userGoal
658 let rec is_there_only_comments lexicon_status s =
659 if Pcre.pmatch ~rex:only_dust_RE s then raise Margin;
661 GrafiteParser.parse_statement lexicon_status (Ulexing.from_utf8_string s)
663 | GrafiteAst.Comment (loc,_) ->
664 let _,parsed_text_length = MatitaGtkMisc.utf8_parsed_text s loc in
665 (* CSC: why +1 in the following lines ???? *)
666 let parsed_text_length = parsed_text_length + 1 in
667 let remain_len = String.length s - parsed_text_length in
668 let next = String.sub s parsed_text_length remain_len in
669 is_there_only_comments lexicon_status next
670 | GrafiteAst.Executable _ -> false
672 try is_there_only_comments self#grafite_status self#getFuture
674 | NCicLibrary.IncludedFileNotCompiled _
675 | HExtlib.Localized _
676 | CicNotationParser.Parse_error _ -> false
677 | Margin | End_of_file -> true
678 | Invalid_argument "Array.make" -> false
682 HLog.debug "script status:";
683 HLog.debug ("history size: " ^ string_of_int (List.length history));
684 HLog.debug (sprintf "%d statements:" (List.length statements));
685 List.iter HLog.debug statements;
686 HLog.debug ("Current file name: " ^ self#filename);
689 let _script = ref None
691 let script ~source_view ~mathviewer ~urichooser ~ask_confirmation ~set_star ()
694 ~source_view ~mathviewer ~ask_confirmation ~urichooser ~set_star ()
699 let current () = match !_script with None -> assert false | Some s -> s