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: UriManager.uri list -> UriManager.uri 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 ~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 = LexiconAstPp.pp_alias value in
96 (status,to_prepend ^ newtxt ^ "\n")::acc, "")
97 ([],skipped_txt) enriched_history_fragment
99 res,"",parsed_text_length
102 (* this function calls the parser in a way that it does not perform inclusions,
103 * so that we can ensure the inclusion is performed after the included file
104 * is compiled (if needed). matitac does not need that, since it compiles files
105 * in the good order, here files may be compiled on demand. *)
106 let wrap_with_make include_paths (f : #LexiconEngine.status GrafiteParser.statement) x =
108 f ~never_include:true ~include_paths x
110 | GrafiteParser.NoInclusionPerformed mafilename ->
111 let root, buri, _, tgt =
112 try Librarian.baseuri_of_script ~include_paths mafilename
113 with Librarian.NoRootFor _ ->
114 HLog.error ("The included file '"^mafilename^"' has no root file,");
115 HLog.error "please create it.";
116 raise (Failure ("No root file for "^mafilename))
118 let b = MatitacLib.Make.make root [tgt] in
120 try f ~include_paths x with LexiconEngine.IncludedFileNotCompiled _ ->
122 (Failure ("Including: "^tgt^
123 "\nNothing to do... did you run matitadep?"))
124 else raise (Failure ("Compiling: " ^ tgt))
127 let pp_eager_statement_ast =
128 GrafiteAstPp.pp_statement ~term_pp:CicNotationPp.pp_term
129 ~lazy_term_pp:(fun _ -> assert false) ~obj_pp:(fun _ -> assert false)
131 (* naive implementation of procedural proof script generation,
132 * starting from an applicatiove *auto generated) proof.
133 * this is out of place, but I like it :-P *)
134 let cic2grafite context menv t =
135 (* indents a proof script in a stupid way, better than nothing *)
136 let stupid_indenter s =
138 let idx_square_o = try String.index s '[' with Not_found -> -1 in
139 let idx_square_c = try String.index s ']' with Not_found -> -1 in
140 let idx_pipe = try String.index s '|' with Not_found -> -1 in
142 List.sort (fun (i,_) (j,_) -> compare i j)
143 [idx_square_o,'[';idx_square_c,']';idx_pipe,'|']
145 let tok = List.filter (fun (i,_) -> i <> -1) tok in
147 | (i,c)::_ -> Some (i,c)
150 let break_apply n s =
151 let tab = String.make (n+1) ' ' in
152 Pcre.replace ~templ:(".\n" ^ tab ^ "apply") ~pat:"\\.apply" s
158 | Some (position, char) ->
161 String.sub s 0 position,
162 String.sub s (position+1) (String.length s - (position+1))
165 | '[' -> break_apply n s1 ^ "\n" ^ String.make (n+2) ' ' ^
167 | '|' -> break_apply n s1 ^ "\n" ^ String.make n ' ' ^
169 | ']' -> break_apply n s1 ^ "\n" ^ String.make n ' ' ^
173 Invalid_argument err ->
179 let module PT = CicNotationPt in
180 let module GA = GrafiteAst in
183 List.map (function Some (n,_) -> Some n | None -> None) context
187 let sort_of context t =
190 CicTypeChecker.type_of_aux' menv context t
191 CicUniv.oblivion_ugraph
193 let sort,_ = CicTypeChecker.type_of_aux' menv context ty
194 CicUniv.oblivion_ugraph
197 | Cic.Sort Cic.Prop -> true
200 CicTypeChecker.TypeCheckerFailure _ ->
201 HLog.error "auto proof to sript transformation error"; false
203 let floc = HExtlib.dummy_floc in
204 (* minimalisti cic.term -> pt.term *)
206 let rec aux c = function
210 | Cic.Const _ as t ->
211 PT.Ident (pp_t c t, None)
212 | Cic.Appl l -> PT.Appl (List.map (aux c) l)
213 | Cic.Implicit _ -> PT.Implicit `JustOne
214 | Cic.Lambda (Cic.Name n, s, t) ->
215 PT.Binder (`Lambda, (PT.Ident (n,None), Some (aux c s)),
216 aux (Some (Cic.Name n, Cic.Decl s)::c) t)
217 | Cic.Prod (Cic.Name n, s, t) ->
218 PT.Binder (`Forall, (PT.Ident (n,None), Some (aux c s)),
219 aux (Some (Cic.Name n, Cic.Decl s)::c) t)
220 | Cic.LetIn (Cic.Name n, s, ty, t) ->
221 PT.Binder (`Lambda, (PT.Ident (n,None), Some (aux c s)),
222 aux (Some (Cic.Name n, Cic.Def (s,ty))::c) t)
223 | Cic.Meta _ -> PT.Implicit `JustOne
224 | Cic.Sort (Cic.Type u) -> PT.Sort (`Type u)
225 | Cic.Sort Cic.Set -> PT.Sort `Set
226 | Cic.Sort (Cic.CProp u) -> PT.Sort (`CProp u)
227 | Cic.Sort Cic.Prop -> PT.Sort `Prop
228 | _ as t -> PT.Ident ("ERROR: "^CicPp.ppterm t, None)
232 (* prints an applicative proof, that is an auto proof.
233 * don't use in the general case! *)
234 let rec print_proof context = function
236 | Cic.Const _ as t ->
237 [GA.Executable (floc,
239 Some (GA.Apply (floc, print_term context t)), GA.Dot floc))]
240 | Cic.Appl (he::tl) ->
241 let tl = List.map (fun t -> t, sort_of context t) tl in
243 HExtlib.filter_map (function (t,true) -> Some t | _ -> None) tl
246 List.map (function | (t,true) -> Cic.Implicit None | (t,_) -> t) tl
248 if List.length subgoals > 1 then
250 [GA.Executable (floc,
252 Some (GA.Apply (floc, print_term context (Cic.Appl (he::args)))),
253 GA.Semicolon floc))] @
254 [GA.Executable (floc, GA.Tactic (floc, None, GA.Branch floc))] @
256 ~sep:[GA.Executable (floc, GA.Tactic (floc, None,GA.Shift floc))]
257 (List.map (print_proof context) subgoals)) @
258 [GA.Executable (floc, GA.Tactic (floc, None,GA.Merge floc))]
261 [GA.Executable (floc,
264 (floc, print_term context (Cic.Appl (he::args)) )), GA.Dot floc))]
268 | [x] -> print_proof context x
270 | Cic.Lambda (Cic.Name n, ty, bo) ->
271 [GA.Executable (floc,
273 Some (GA.Cut (floc, Some n, (print_term context ty))),
275 (print_proof (Some (Cic.Name n, Cic.Decl ty)::context) bo) @
276 [GA.Executable (floc, GA.Tactic (floc, None,GA.Shift floc))] @
277 [GA.Executable (floc, GA.Tactic (floc,
278 Some (GA.Assumption floc),GA.Merge floc))]
281 debug_print (lazy (CicPp.ppterm t));
285 (* performs a lambda closure of the proof term abstracting metas.
286 * this is really an approximation of a closure, local subst of metas
287 * is not kept into account *)
288 let close_pt menv context t =
289 let metas = CicUtil.metas_of_term t in
291 HExtlib.list_uniq ~eq:(fun (i,_) (j,_) -> i = j)
292 (List.sort (fun (i,_) (j,_) -> compare i j) metas)
294 let mk_rels_and_collapse_metas metas =
295 let rec aux i map acc acc1 = function
296 | [] -> acc, acc1, map
298 let _,_,ty = CicUtil.lookup_meta j menv in
300 let n = List.assoc ty map in
301 aux i map (Cic.Rel n :: acc) (m::acc1) tl
303 let map = (ty, i)::map in
304 aux (i+1) map (Cic.Rel i :: acc) (m::acc1) tl
308 let rels, metas, map = mk_rels_and_collapse_metas metas in
309 let n_lambdas = List.length map in
315 ProofEngineReduction.replace_lifting
316 ~what:(List.map (fun (x,_) -> Cic.Meta (x,[])) metas)
319 ~equality:(fun _ x y ->
321 | Cic.Meta(i,_), Cic.Meta(j,_) when i=j -> true
323 ~where:(CicSubstitution.lift n_lambdas t)
325 let rec mk_lam = function
328 let name = "fresh_"^ string_of_int n in
329 Cic.Lambda (Cic.Name name, ty, mk_lam tl)
333 (fun (l,liftno) (ty,_) ->
334 (l @ [CicSubstitution.lift liftno ty,liftno] , liftno+1))
339 let ast = print_proof context (close_pt menv context t) in
341 (* ZACK: setting width to 80 will trigger a bug of BoxPp.render_to_string
342 * which will show up using the following command line:
343 * ./tptp2grafite -tptppath ~tassi/TPTP-v3.1.1 GRP170-1 *)
344 let width = max_int in
345 let term_pp content_term =
346 let pres_term = TermContentPres.pp_ast content_term in
347 let lookup_uri = fun _ -> None in
348 let markup = CicNotationPres.render ~lookup_uri pres_term in
349 let s = "(" ^ BoxPp.render_to_string
350 ~map_unicode_to_tex:(Helm_registry.get_bool
351 "matita.paste_unicode_as_tex")
352 List.hd width markup ^ ")" in
354 ~pat:"\\\\forall [Ha-z][a-z0-9_]*" ~subst:(fun x -> "\n" ^ x) s
356 CicNotationPp.set_pp_term term_pp;
357 let lazy_term_pp = fun x -> assert false in
358 let obj_pp = CicNotationPp.pp_obj CicNotationPp.pp_term in
359 GrafiteAstPp.pp_statement
360 ~map_unicode_to_tex:(Helm_registry.get_bool
361 "matita.paste_unicode_as_tex")
362 ~term_pp ~lazy_term_pp ~obj_pp t
364 let script = String.concat "" (List.map pp ast) in
365 prerr_endline script;
366 stupid_indenter script
368 let eval_nmacro include_paths (buffer : GText.buffer) guistuff grafite_status user_goal unparsed_text parsed_text script mac =
369 let parsed_text_length = String.length parsed_text in
371 | TA.Screenshot (_,name) ->
372 let status = script#grafite_status in
373 let _,_,menv,subst,_ = status#obj in
374 let name = Filename.dirname (script#filename) ^ "/" ^ name in
376 let selected = Continuationals.Stack.head_goals status#stack in
377 List.filter (fun x,_ -> List.mem x selected) menv
379 guistuff.mathviewer#screenshot status sequents menv subst name;
380 [status, parsed_text], "", parsed_text_length
382 let status = script#grafite_status in
383 let _,_,menv,subst,_ = status#obj in
385 try let _,(_,ctx,_) = List.hd menv in ctx
386 with Failure "hd" -> []
388 let m, s, status, t =
389 GrafiteDisambiguate.disambiguate_nterm
390 None status ctx menv subst (parsed_text,parsed_text_length,
391 CicNotationPt.Cast (t,CicNotationPt.Implicit `JustOne))
392 (* XXX use the metasenv, if possible *)
394 guistuff.mathviewer#show_entry (`NCic (t,ctx,m,s));
395 [status, parsed_text], "", parsed_text_length
396 | TA.NIntroGuess _loc ->
397 let names_ref = ref [] in
399 NTactics.intros_tac ~names_ref [] script#grafite_status
401 let rex = Pcre.regexp ~flags:[`MULTILINE] "\\A([\\n\\t\\r ]*).*\\Z" in
402 let nl = Pcre.replace ~rex ~templ:"$1" parsed_text in
403 [s, nl ^ "#" ^ String.concat " " !names_ref ^ ";"], "", parsed_text_length
404 | TA.NAutoInteractive (_loc, (None,a)) ->
405 let trace_ref = ref [] in
408 ~params:(None,a) ~trace_ref script#grafite_status
411 try List.assoc "depth" a
414 let trace = "/"^(if int_of_string depth > 1 then depth else "")^"/ by " in
416 match !trace_ref with
420 (HExtlib.filter_map (function
421 | CicNotationPt.NRef r -> Some (NCicPp.r2s true r)
425 let rex = Pcre.regexp ~flags:[`MULTILINE] "\\A([\\n\\t\\r ]*).*\\Z" in
426 let nl = Pcre.replace ~rex ~templ:"$1" parsed_text in
427 [s, nl ^ trace ^ thms ^ ";"], "", parsed_text_length
428 | TA.NAutoInteractive (_, (Some _,_)) -> assert false
430 let rec eval_macro include_paths (buffer : GText.buffer) guistuff grafite_status user_goal unparsed_text parsed_text script mac =
431 let module MQ = MetadataQuery in
432 let module CTC = CicTypeChecker in
433 (* no idea why ocaml wants this *)
434 let parsed_text_length = String.length parsed_text in
435 let dbd = LibraryDb.instance () in
438 | TA.Hint (loc, rewrite) -> (* MATITA 1.0 *) assert false
439 | TA.Eval (_, kind, term) ->
440 let metasenv = GrafiteTypes.get_proof_metasenv grafite_status in
444 | Some n -> GrafiteTypes.get_proof_context grafite_status n in
445 let ty,_ = CTC.type_of_aux' metasenv context term CicUniv.empty_ugraph in
449 CicReduction.normalize ~delta:true ~subst:[] context term
451 ProofEngineReduction.simpl context term
453 ProofEngineReduction.unfold ?what:None context term
454 | `Unfold (Some lazy_term) ->
456 lazy_term context metasenv CicUniv.empty_ugraph in
457 ProofEngineReduction.unfold ~what context term
459 CicReduction.whd ~delta:true ~subst:[] context term
461 let t_and_ty = Cic.Cast (term,ty) in
462 guistuff.mathviewer#show_entry (`Cic (t_and_ty,metasenv));
463 [(grafite_status#set_proof_status No_proof), parsed_text ],"",
465 | TA.Check (_,term) ->
466 let metasenv = GrafiteTypes.get_proof_metasenv grafite_status in
470 | Some n -> GrafiteTypes.get_proof_context grafite_status n in
471 let ty,_ = CTC.type_of_aux' metasenv context term CicUniv.empty_ugraph in
472 let t_and_ty = Cic.Cast (term,ty) in
473 guistuff.mathviewer#show_entry (`Cic (t_and_ty,metasenv));
474 [], "", parsed_text_length
475 | TA.AutoInteractive (_, params) ->
479 | None -> raise NoUnfinishedProof
481 let proof = GrafiteTypes.get_current_proof grafite_status in
482 let proof_status = proof,user_goal' in
484 let _,menv,_,_,_,_ = proof in
485 let i,cc,ty = CicUtil.lookup_meta user_goal' menv in
486 let timestamp = Unix.gettimeofday () in
487 let (_,menv,subst,_,_,_), _ =
488 ProofEngineTypes.apply_tactic
489 (Auto.auto_tac ~dbd ~params
490 ~automation_cache:grafite_status#automation_cache)
495 CicMkImplicit.identity_relocation_list_for_metavariable cc
497 CicMetaSubst.apply_subst subst (Cic.Meta (i,irl))
499 let time = Unix.gettimeofday () -. timestamp in
500 let size, depth = Auto.size_and_depth cc menv proof_term in
503 "\n(* end auto(%s) proof: TIME=%4.2f SIZE=%d DEPTH=%d *)"
504 Auto.revision time size depth
507 if List.exists (fun (s,_) -> s = "paramodulation") (snd params) then
508 let proof_term, how_many_lambdas =
509 Auto.lambda_close ~prefix_name:"orrible_hack_"
513 CicTypeChecker.type_of_aux'
514 [] [] proof_term CicUniv.empty_ugraph
516 prerr_endline (CicPp.ppterm proof_term ^ " n lambda= " ^ string_of_int how_many_lambdas);
517 (* use declarative output *)
519 (* il proof_term vive in cc, devo metterci i lambda no? *)
520 (Cic.CurrentProof ("xxx",[],proof_term,ty,[],[]))
522 ApplyTransformation.txt_of_cic_object
523 ~map_unicode_to_tex:(Helm_registry.get_bool
524 "matita.paste_unicode_as_tex")
525 ~skip_thm_and_qed:true
526 ~skip_initial_lambdas:how_many_lambdas
530 (* use cic2grafite *)
531 cic2grafite cc menv proof_term
533 (* alternative using FG stuff *)
534 let map_unicode_to_tex =
535 Helm_registry.get_bool "matita.paste_unicode_as_tex"
537 ApplyTransformation.procedural_txt_of_cic_term
538 ~map_unicode_to_tex 78 [] cc proof_term
540 let text = comment parsed_text ^ "\n" ^ proof_script ^ trailer in
541 [],text,parsed_text_length
543 ProofEngineTypes.Fail _ as exn ->
545 (* [], comment parsed_text ^ "\nfail.\n", parsed_text_length *))
546 | TA.Inline (_, suri, params) ->
548 ApplyTransformation.txt_of_inline_macro
549 ~map_unicode_to_tex:(Helm_registry.get_bool
550 "matita.paste_unicode_as_tex")
553 [], str, String.length parsed_text
555 and eval_executable include_paths (buffer : GText.buffer) guistuff
556 grafite_status user_goal unparsed_text skipped_txt nonskipped_txt
560 ignore (buffer#move_mark (`NAME "beginning_of_statement")
561 ~where:((buffer#get_iter_at_mark (`NAME "locked"))#forward_chars
562 (Glib.Utf8.length skipped_txt))) ;
563 eval_with_engine include_paths
564 guistuff grafite_status user_goal skipped_txt nonskipped_txt
565 (TA.Executable (loc, ex))
567 MatitaTypes.Cancel -> [], "", 0
568 | GrafiteEngine.Macro (_loc,lazy_macro) ->
572 | Some n -> GrafiteTypes.get_proof_context grafite_status n in
573 let grafite_status,macro = lazy_macro context in
574 eval_macro include_paths buffer guistuff grafite_status
575 user_goal unparsed_text (skipped_txt ^ nonskipped_txt) script macro
576 | GrafiteEngine.NMacro (_loc,macro) ->
577 eval_nmacro include_paths buffer guistuff grafite_status
578 user_goal unparsed_text (skipped_txt ^ nonskipped_txt) script macro
581 and eval_statement include_paths (buffer : GText.buffer) guistuff
582 grafite_status user_goal script statement
584 let (grafite_status,st), unparsed_text =
587 if Pcre.pmatch ~rex:only_dust_RE text then raise Margin;
589 wrap_with_make include_paths
590 (GrafiteParser.parse_statement (Ulexing.from_utf8_string text))
594 | `Ast (st, text) -> (grafite_status, st), text
596 let text_of_loc floc =
597 let nonskipped_txt,_ = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
598 let start, stop = HExtlib.loc_of_floc floc in
599 let floc = HExtlib.floc_of_loc (0, start) in
600 let skipped_txt,_ = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
601 let floc = HExtlib.floc_of_loc (0, stop) in
602 let txt,len = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
603 txt,nonskipped_txt,skipped_txt,len
606 | GrafiteParser.LNone loc ->
607 let parsed_text, _, _, parsed_text_length = text_of_loc loc in
608 [grafite_status,parsed_text],"",
610 | GrafiteParser.LSome (GrafiteAst.Executable (loc, ex)) ->
611 let _, nonskipped, skipped, parsed_text_length = text_of_loc loc in
612 eval_executable include_paths buffer guistuff
613 grafite_status user_goal unparsed_text skipped nonskipped script ex loc
614 | GrafiteParser.LSome (GrafiteAst.Comment (loc, GrafiteAst.Code (_, ex)))
615 when Helm_registry.get_bool "matita.execcomments" ->
616 let _, nonskipped, skipped, parsed_text_length = text_of_loc loc in
617 eval_executable include_paths buffer guistuff
618 grafite_status user_goal unparsed_text skipped nonskipped script ex loc
619 | GrafiteParser.LSome (GrafiteAst.Comment (loc, _)) ->
620 let parsed_text, _, _, parsed_text_length = text_of_loc loc in
621 let remain_len = String.length unparsed_text - parsed_text_length in
622 let s = String.sub unparsed_text parsed_text_length remain_len in
625 eval_statement include_paths buffer guistuff
626 grafite_status user_goal script (`Raw s)
628 HExtlib.Localized (floc, exn) ->
629 HExtlib.raise_localized_exception
630 ~offset:(MatitaGtkMisc.utf8_string_length parsed_text) floc exn
631 | MultiPassDisambiguator.DisambiguationError (offset,errorll) ->
633 (MultiPassDisambiguator.DisambiguationError
634 (offset+parsed_text_length, errorll))
636 assert (text=""); (* no macros inside comments, please! *)
638 | (statuses,text)::tl ->
639 (statuses,parsed_text ^ text)::tl,"",parsed_text_length + len
642 let fresh_script_id =
646 class script ~(source_view: GSourceView2.source_view)
647 ~(mathviewer: MatitaTypes.mathViewer)
652 let buffer = source_view#buffer in
653 let source_buffer = source_view#source_buffer in
654 let initial_statuses current baseuri =
655 let empty_lstatus = new LexiconEngine.status in
658 LexiconSync.time_travel ~present:current ~past:empty_lstatus;
659 GrafiteSync.time_travel ~present:current ();
660 (* CSC: there is a known bug in invalidation; temporary fix here *)
661 NCicEnvironment.invalidate ()
664 CicNotation2.load_notation ~include_paths:[] empty_lstatus
665 BuildTimeConf.core_notation_script
667 let grafite_status = GrafiteSync.init lexicon_status baseuri in
670 let read_include_paths file =
672 let root, _buri, _fname, _tgt =
673 Librarian.baseuri_of_script ~include_paths:[] file
676 Str.split (Str.regexp " ")
677 (List.assoc "include_paths" (Librarian.load_root_file (root^"/root")))
679 List.iter (HLog.debug) rc; rc
680 with Librarian.NoRootFor _ | Not_found -> []
682 let default_buri = "cic:/matita/tests" in
683 let default_fname = ".unnamed.ma" in
685 val mutable include_paths_ = []
687 val scriptId = fresh_script_id ()
690 mathviewer = mathviewer;
691 urichooser = urichooser;
692 ask_confirmation = ask_confirmation;
695 val mutable filename_ = (None : string option)
697 method has_name = filename_ <> None
699 method include_paths =
701 Helm_registry.get_list Helm_registry.string "matita.includes"
703 method private curdir =
705 let root, _buri, _fname, _tgt =
706 Librarian.baseuri_of_script ~include_paths:self#include_paths
710 with Librarian.NoRootFor _ -> Sys.getcwd ()
712 method buri_of_current_file =
714 | None -> default_buri
717 let _root, buri, _fname, _tgt =
718 Librarian.baseuri_of_script ~include_paths:self#include_paths f
721 with Librarian.NoRootFor _ -> default_buri
723 method filename = match filename_ with None -> default_fname | Some f -> f
726 ignore (GMain.Timeout.add ~ms:300000
727 ~callback:(fun _ -> self#_saveToBackupFile ();true));
728 ignore (buffer#connect#modified_changed
729 (fun _ -> set_star buffer#modified))
731 val mutable statements = [] (** executed statements *)
733 val mutable history = [ initial_statuses None default_buri ]
734 (** list of states before having executed statements. Head element of this
735 * list is the current state, last element is the state at the beginning of
737 * Invariant: this list length is 1 + length of statements *)
739 (** goal as seen by the user (i.e. metano corresponding to current tab) *)
740 val mutable userGoal = None
742 (** text mark and tag representing locked part of a script *)
744 buffer#create_mark ~name:"locked" ~left_gravity:true buffer#start_iter
745 val beginning_of_statement_mark =
746 buffer#create_mark ~name:"beginning_of_statement"
747 ~left_gravity:true buffer#start_iter
748 val locked_tag = buffer#create_tag [`BACKGROUND "lightblue"; `EDITABLE false]
749 val error_tag = buffer#create_tag [`UNDERLINE `SINGLE; `FOREGROUND "red"]
751 method locked_mark = locked_mark
752 method locked_tag = locked_tag
753 method error_tag = error_tag
755 (* history can't be empty, the invariant above grant that it contains at
756 * least the init grafite_status *)
757 method grafite_status = match history with s::_ -> s | _ -> assert false
759 method private _advance ?statement () =
760 let s = match statement with Some s -> s | None -> self#getFuture in
761 if self#bos then LibraryClean.clean_baseuris [self#buri_of_current_file];
762 HLog.debug ("evaluating: " ^ first_line s ^ " ...");
763 let time1 = Unix.gettimeofday () in
764 let entries, newtext, parsed_len =
766 eval_statement self#include_paths buffer guistuff
767 self#grafite_status userGoal self (`Raw s)
768 with End_of_file -> raise Margin
770 let time2 = Unix.gettimeofday () in
771 HLog.debug ("... done in " ^ string_of_float (time2 -. time1) ^ "s");
772 let new_statuses, new_statements =
773 let statuses, texts = List.split entries in
776 history <- new_statuses @ history;
777 statements <- new_statements @ statements;
778 let start = buffer#get_iter_at_mark (`MARK locked_mark) in
779 let new_text = String.concat "" (List.rev new_statements) in
780 if statement <> None then
781 buffer#insert ~iter:start new_text
783 let parsed_text = String.sub s 0 parsed_len in
784 if new_text <> parsed_text then begin
785 let stop = start#copy#forward_chars (Glib.Utf8.length parsed_text) in
786 buffer#delete ~start ~stop;
787 buffer#insert ~iter:start new_text;
790 self#moveMark (Glib.Utf8.length new_text);
791 buffer#insert ~iter:(buffer#get_iter_at_mark (`MARK locked_mark)) newtext;
792 (* here we need to set the Goal in case we are going to cursor (or to
793 bottom) and we will face a macro *)
794 match self#grafite_status#proof_status with
795 Incomplete_proof p ->
797 (try Some (Continuationals.Stack.find_goal p.stack)
798 with Failure _ -> None)
799 | _ -> userGoal <- None
801 method private _retract offset grafite_status new_statements
804 let cur_grafite_status =
805 match history with s::_ -> s | [] -> assert false
807 LexiconSync.time_travel ~present:cur_grafite_status ~past:grafite_status;
808 GrafiteSync.time_travel ~present:cur_grafite_status ~past:grafite_status ();
809 statements <- new_statements;
810 history <- new_history;
811 self#moveMark (- offset)
813 method advance ?statement () =
815 self#_advance ?statement ();
818 | Margin -> self#notify
819 | Not_found -> assert false
820 | Invalid_argument "Array.make" -> HLog.error "The script is too big!\n"
821 | exc -> self#notify; raise exc
825 let cmp,new_statements,new_history,grafite_status =
826 match statements,history with
827 stat::statements, _::(status::_ as history) ->
828 assert (Glib.Utf8.validate stat);
829 Glib.Utf8.length stat, statements, history, status
830 | [],[_] -> raise Margin
831 | _,_ -> assert false
833 self#_retract cmp grafite_status new_statements
837 | Margin -> self#notify
838 | Invalid_argument "Array.make" -> HLog.error "The script is too big!\n"
839 | exc -> self#notify; raise exc
841 method private getFuture =
842 let lock = buffer#get_iter_at_mark (`MARK locked_mark) in
843 let text = buffer#get_text ~start:lock ~stop:buffer#end_iter () in
846 method expandAllVirtuals =
847 let lock = buffer#get_iter_at_mark (`MARK locked_mark) in
848 let text = buffer#get_text ~start:lock ~stop:buffer#end_iter () in
849 buffer#delete ~start:lock ~stop:buffer#end_iter;
850 let text = Pcre.replace ~pat:":=" ~templ:"\\def" text in
851 let text = Pcre.replace ~pat:"->" ~templ:"\\to" text in
852 let text = Pcre.replace ~pat:"=>" ~templ:"\\Rightarrow" text in
854 Pcre.substitute_substrings
856 let pristine = Pcre.get_substring str 0 in
858 if pristine.[0] = ' ' then
859 String.sub pristine 1 (String.length pristine -1)
863 if input.[String.length input-1] = ' ' then
864 String.sub input 0 (String.length input -1)
868 if input = "\\forall" ||
869 input = "\\lambda" ||
870 input = "\\exists" then "","" else " ", " "
873 before ^ Glib.Utf8.from_unichar
874 (snd (Virtuals.symbol_of_virtual input)) ^ after
875 with Virtuals.Not_a_virtual -> pristine)
876 ~pat:" ?\\\\[a-zA-Z]+ ?" text
878 buffer#insert ~iter:lock text
880 (** @param rel_offset relative offset from current position of locked_mark *)
881 method private moveMark rel_offset =
882 let mark = `MARK locked_mark in
883 let old_insert = buffer#get_iter_at_mark `INSERT in
884 buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
885 let current_mark_pos = buffer#get_iter_at_mark mark in
887 match rel_offset with
888 | 0 -> current_mark_pos
889 | n when n > 0 -> current_mark_pos#forward_chars n
890 | n (* when n < 0 *) -> current_mark_pos#backward_chars (abs n)
892 buffer#move_mark mark ~where:new_mark_pos;
893 buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:new_mark_pos;
894 buffer#move_mark `INSERT old_insert;
895 let mark_position = buffer#get_iter_at_mark mark in
896 if source_view#move_mark_onscreen mark then
898 buffer#move_mark mark mark_position;
899 source_view#scroll_to_mark ~use_align:true ~xalign:1.0 ~yalign:0.1 mark;
901 while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
903 method clean_dirty_lock =
904 let lock_mark_iter = buffer#get_iter_at_mark (`MARK locked_mark) in
905 buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
906 buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:lock_mark_iter
908 val mutable observers = []
910 method addObserver (o: GrafiteTypes.status -> unit) =
911 observers <- o :: observers
913 method private notify =
914 let grafite_status = self#grafite_status in
915 List.iter (fun o -> o grafite_status) observers
917 method loadFromString s =
920 buffer#set_modified true
922 method loadFromFile f =
923 buffer#set_text (HExtlib.input_file f);
925 buffer#set_modified false
927 method assignFileName file =
930 | Some f -> Some (Librarian.absolutize f)
935 (match file with Some file -> read_include_paths file | None -> []);
937 Sys.chdir self#curdir;
938 HLog.debug ("Moving to " ^ Sys.getcwd ())
940 method saveToFile () =
941 if self#has_name then
942 let oc = open_out self#filename in
943 output_string oc (buffer#get_text ~start:buffer#start_iter
944 ~stop:buffer#end_iter ());
947 buffer#set_modified false
949 HLog.error "Can't save, no filename selected"
951 method private _saveToBackupFile () =
952 if buffer#modified then
954 let f = self#filename in
955 let oc = open_out f in
956 output_string oc (buffer#get_text ~start:buffer#start_iter
957 ~stop:buffer#end_iter ());
959 HLog.debug ("backup " ^ f ^ " saved")
962 method private reset_buffer =
964 history <- [ initial_statuses (Some self#grafite_status) self#buri_of_current_file ];
967 buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
968 buffer#move_mark (`MARK locked_mark) ~where:buffer#start_iter
972 source_buffer#begin_not_undoable_action ();
973 buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter;
974 source_buffer#end_not_undoable_action ();
975 buffer#set_modified false;
978 let template = HExtlib.input_file BuildTimeConf.script_template in
979 buffer#insert ~iter:(buffer#get_iter `START) template;
980 buffer#set_modified false;
983 method goto (pos: [`Top | `Bottom | `Cursor]) () =
985 let old_locked_mark =
987 (buffer#create_mark ~name:"old_locked_mark"
988 ~left_gravity:true (buffer#get_iter_at_mark (`MARK locked_mark))) in
989 let getpos _ = buffer#get_iter_at_mark (`MARK locked_mark) in
990 let getoldpos _ = buffer#get_iter_at_mark old_locked_mark in
991 let dispose_old_locked_mark () = buffer#delete_mark old_locked_mark in
994 dispose_old_locked_mark ();
1001 let newpos = getpos () in
1002 if (getoldpos ())#compare newpos < 0 then
1004 buffer#move_mark old_locked_mark newpos;
1009 dispose_old_locked_mark ();
1012 | Margin -> dispose_old_locked_mark (); self#notify
1013 | exc -> dispose_old_locked_mark (); self#notify; raise exc)
1015 let locked_iter () = buffer#get_iter_at_mark (`NAME "locked") in
1016 let cursor_iter () = buffer#get_iter_at_mark `INSERT in
1019 (buffer#create_mark ~name:"initial_insert"
1020 ~left_gravity:true (cursor_iter ())) in
1021 let dispose_remember () = buffer#delete_mark remember in
1022 let remember_iter () =
1023 buffer#get_iter_at_mark (`NAME "initial_insert") in
1024 let cmp () = (locked_iter ())#offset - (remember_iter ())#offset in
1025 let icmp = cmp () in
1026 let forward_until_cursor () = (* go forward until locked > cursor *)
1029 if cmp () < 0 && (getoldpos ())#compare (getpos ()) < 0
1032 buffer#move_mark old_locked_mark (getpos ());
1038 let rec back_until_cursor len = (* go backward until locked < cursor *)
1040 statements, ((grafite_status)::_ as history)
1042 self#_retract (icmp - len) grafite_status statements
1044 | statement::tl1, _::tl2 ->
1045 back_until_cursor (len - MatitaGtkMisc.utf8_string_length statement) (tl1,tl2)
1046 | _,_ -> assert false
1050 if icmp < 0 then (* locked < cursor *)
1051 (forward_until_cursor (); self#notify)
1052 else if icmp > 0 then (* locked > cursor *)
1053 (back_until_cursor icmp (statements,history); self#notify)
1054 else (* cursor = locked *)
1057 dispose_remember ();
1058 dispose_old_locked_mark ();
1060 | Margin -> dispose_remember (); dispose_old_locked_mark (); self#notify
1061 | exc -> dispose_remember (); dispose_old_locked_mark ();
1062 self#notify; raise exc)
1063 with Invalid_argument "Array.make" ->
1064 HLog.error "The script is too big!\n"
1066 method onGoingProof () =
1067 match self#grafite_status#proof_status with
1068 | No_proof | Proof _ -> false
1069 | Incomplete_proof _ -> true
1070 | Intermediate _ -> assert false
1072 (* method proofStatus = MatitaTypes.get_proof_status self#status *)
1073 method proofMetasenv = GrafiteTypes.get_proof_metasenv self#grafite_status
1075 method proofContext =
1078 | Some n -> GrafiteTypes.get_proof_context self#grafite_status n
1080 method proofConclusion =
1082 None -> assert false
1084 GrafiteTypes.get_proof_conclusion self#grafite_status n
1086 method stack = GrafiteTypes.get_stack self#grafite_status
1087 method setGoal n = userGoal <- n
1088 method goal = userGoal
1096 let rec is_there_only_comments lexicon_status s =
1097 if Pcre.pmatch ~rex:only_dust_RE s then raise Margin;
1098 let lexicon_status,st =
1099 GrafiteParser.parse_statement (Ulexing.from_utf8_string s)
1100 ~include_paths:self#include_paths lexicon_status
1103 | GrafiteParser.LSome (GrafiteAst.Comment (loc,_)) ->
1104 let _,parsed_text_length = MatitaGtkMisc.utf8_parsed_text s loc in
1105 (* CSC: why +1 in the following lines ???? *)
1106 let parsed_text_length = parsed_text_length + 1 in
1107 let remain_len = String.length s - parsed_text_length in
1108 let next = String.sub s parsed_text_length remain_len in
1109 is_there_only_comments lexicon_status next
1110 | GrafiteParser.LNone _
1111 | GrafiteParser.LSome (GrafiteAst.Executable _) -> false
1113 try is_there_only_comments self#grafite_status self#getFuture
1115 | LexiconEngine.IncludedFileNotCompiled _
1116 | HExtlib.Localized _
1117 | CicNotationParser.Parse_error _ -> false
1118 | Margin | End_of_file -> true
1119 | Invalid_argument "Array.make" -> false
1123 HLog.debug "script status:";
1124 HLog.debug ("history size: " ^ string_of_int (List.length history));
1125 HLog.debug (sprintf "%d statements:" (List.length statements));
1126 List.iter HLog.debug statements;
1127 HLog.debug ("Current file name: " ^ self#filename);
1130 let _script = ref None
1132 let script ~source_view ~mathviewer ~urichooser ~ask_confirmation ~set_star ()
1135 ~source_view ~mathviewer ~ask_confirmation ~urichooser ~set_star ()
1140 let current () = match !_script with None -> assert false | Some s -> s