(* Copyright (C) 2004, HELM Team. * * This file is part of HELM, an Hypertextual, Electronic * Library of Mathematics, developed at the Computer Science * Department, University of Bologna, Italy. * * HELM is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * HELM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HELM; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. * * For details, see the HELM World-Wide-Web page, * http://helm.cs.unibo.it/ *) (** Interpreter for textual phrases coming from matita's console (textual entry * window at the bottom of the main window). * * Interpreter is either in Command state or in Proof state (see state type * below). In Command state commands for starting proofs are accepted, but * tactic and tactical applications are not. In Proof state both * tactic/tacticals and commands are accepted. *) open Printf open MatitaTypes type state = Command | Proof type outcome = New_state of state | Quiet | Echo of string exception Command_error of string (* let uri name = UriManager.uri_of_string (sprintf "%s/%s" BuildTimeConf.base_uri name) *) let baseuri = ref "cic:/matita" let qualify name = let baseuri = !baseuri in if baseuri.[String.length baseuri - 1] = '/' then baseuri ^ name else String.concat "/" [baseuri; name] let split_obj = function | Cic.Constant (name, body, ty, _) | Cic.Variable (name, body, ty, _) -> (name, body, ty) | _ -> assert false let canonical_context metano metasenv = try let (_, context, _) = List.find (fun (m, _, _) -> m = metano) metasenv in context with Not_found -> failwith (sprintf "Can't find canonical context for %d" metano) let get_context_and_metasenv (currentProof:MatitaTypes.currentProof) = if currentProof#onGoing () then let proof = currentProof#proof in let metasenv = proof#metasenv in let goal = proof#goal in (canonical_context goal metasenv, metasenv) else ([], []) (** term AST -> Cic.term. Uses disambiguator and change imperatively the * metasenv as needed *) let disambiguate ~(disambiguator:MatitaTypes.disambiguator) ~currentProof ast = if currentProof#onGoing () then begin let proof = currentProof#proof in let metasenv = proof#metasenv in let goal = proof#goal in let context = canonical_context goal metasenv in let (_, metasenv, term,ugraph) as retval = disambiguator#disambiguateTermAst ~context ~metasenv ast in proof#set_metasenv metasenv; retval end else disambiguator#disambiguateTermAst ast class virtual interpreterState = (* static values, shared by all states inheriting this class *) let loc = ref None in let history = ref [] in fun ~(console: MatitaTypes.console) -> object (self) (** eval a toplevel phrase in the current state and return the new state *) method parsePhrase s = match CicTextualParser2.parse_tactical s with | (TacticAst.LocatedTactical (loc', tac)) as tactical -> loc := Some loc'; (match tac with (* update interpreter history *) | TacticAst.Command (TacticAst.Qed None) -> history := `Qed :: !history | TacticAst.Command (TacticAst.Theorem (_, Some name, _, None)) -> history := `Theorem name :: !history | TacticAst.Command (TacticAst.Qed _) | TacticAst.Command (TacticAst.Theorem _) -> assert false | _ -> history := `Tactic :: !history); tactical | _ -> assert false method virtual evalTactical: (CicAst.term, string) TacticAst.tactical -> outcome method evalPhrase s = debug_print (sprintf "evaluating '%s'" s); self#evalTactical (self#parsePhrase (Stream.of_string s)) method evalAst ast = self#evalTactical ast method endOffset = match !loc with | Some (start_pos, end_pos) -> end_pos.Lexing.pos_cnum | None -> failwith "MatitaInterpreter: no offset recorded" end (** Implements phrases that should be accepted in all states *) class sharedState ~(disambiguator: MatitaTypes.disambiguator) ~(currentProof: MatitaTypes.currentProof) ~(console: MatitaTypes.console) ?(mathViewer: MatitaTypes.mathViewer option) ~(dbd: Mysql.dbd) () = object (self) inherit interpreterState ~console method evalTactical = function | TacticAst.Command TacticAst.Quit -> currentProof#quit (); assert false (* dummy answer, useless *) | TacticAst.Command TacticAst.Proof -> (* do nothing, just for compatibility with coq syntax *) New_state Command | TacticAst.Command (TacticAst.Baseuri (Some uri)) -> baseuri := uri; console#echo_message (sprintf "base uri set to \"%s\"" uri); Quiet | TacticAst.Command (TacticAst.Baseuri None) -> console#echo_message (sprintf "base uri is \"%s\"" !baseuri); Quiet | TacticAst.Command (TacticAst.Check term) -> let (_, _, term,ugraph) = disambiguate ~disambiguator ~currentProof term in let (context, metasenv) = get_context_and_metasenv currentProof in let dummyno = CicMkImplicit.new_meta metasenv [] in let ty,ugraph1 = CicTypeChecker.type_of_aux' metasenv context term ugraph in (* TASSI: here ugraph1 is unused.... FIXME *) let expr = Cic.Cast (term, ty) in let sequent = (dummyno, context, expr) in (match mathViewer with | None -> () | Some v -> v#checkTerm sequent metasenv); Quiet | TacticAst.Command (TacticAst.Search_pat (search_kind, pat)) -> let uris = match search_kind with | `Locate -> MetadataQuery.locate ~dbd pat | `Elim -> MetadataQuery.elim ~dbd pat | _ -> assert false in (* TODO ZACK: show URIs to the user *) Quiet | tactical -> raise (Command_error (TacticAstPp.pp_tactical tactical)) end open Printf let pp_indtypes indTypes = List.iter (fun (name, _, typ, constructors) -> printf "%s: %s\n" name (CicPp.ppterm typ); List.iter (fun (name, term) -> printf "\t%s: %s\n" name (CicPp.ppterm term)) constructors) indTypes; flush stdout let inddef_of_ast params indTypes (disambiguator:MatitaTypes.disambiguator) = let add_pi binders t = List.fold_right (fun (name, ast) acc -> CicAst.Binder (`Forall, (Cic.Name name, Some ast), acc)) binders t in let ind_binders = List.map (fun (name, _, typ, _) -> (name, add_pi params typ)) indTypes in let binders = ind_binders @ params in let asts = ref [] in let add_ast ast = asts := ast :: !asts in let paramsno = List.length params in let indbindersno = List.length ind_binders in List.iter (fun (name, _, typ, constructors) -> add_ast (add_pi params typ); List.iter (fun (_, ast) -> add_ast (add_pi binders ast)) constructors) indTypes; let (_, metasenv, terms, ugraph) = disambiguator#disambiguateTermAsts ~metasenv:[] !asts in let terms = ref (List.rev terms) in let get_term () = match !terms with [] -> assert false | hd :: tl -> terms := tl; hd in let uri = match indTypes with | (name, _, _, _) :: _ -> qualify name ^ ".ind" | _ -> assert false in let mutinds = let counter = ref 0 in List.map (fun _ -> incr counter; CicUtil.term_of_uri (sprintf "%s#xpointer(1/%d)" uri !counter)) indTypes in let subst_mutinds = List.fold_right CicSubstitution.subst mutinds in let cicIndTypes = List.fold_left (fun acc (name, inductive, typ, constructors) -> let cicTyp = get_term () in let cicConstructors = List.fold_left (fun acc (name, _) -> let typ = subst_mutinds (CicUtil.strip_prods indbindersno (get_term ())) in (name, typ) :: acc) [] constructors in (name, inductive, cicTyp, List.rev cicConstructors) :: acc) [] indTypes in let cicIndTypes = List.rev cicIndTypes in (* prerr_endline uri; pp_indtypes cicIndTypes; *) (UriManager.uri_of_string uri, (cicIndTypes, [], paramsno)) (* TODO Zack a lot more to be done here: * - save object to disk in xml format * - register uri to the getter * - save universe file *) let add_constant_to_world ~dbd ~uri ?body ~ty ~ugraph () = let name = UriManager.name_of_uri uri in let obj = Cic.Constant (name, body, ty, []) in let ugraph = CicUnivUtils.clean_and_fill uri obj ugraph in CicEnvironment.add_type_checked_term uri (obj, ugraph); MetadataDb.index_constant ~dbd ~owner:(Helm_registry.get "matita.owner") ~uri ~body ~ty (** Implements phrases that should be accepted only in Command state *) class commandState ~(disambiguator: MatitaTypes.disambiguator) ~(currentProof: MatitaTypes.currentProof) ~(console: MatitaTypes.console) ?mathViewer ~(dbd: Mysql.dbd) () = let shared = new sharedState ~disambiguator ~currentProof ~console ?mathViewer ~dbd () in object (self) inherit interpreterState ~console method evalTactical = function | TacticAst.LocatedTactical (_, tactical) -> self#evalTactical tactical | TacticAst.Command (TacticAst.Theorem (_, Some name, ast, None)) -> let (_, metasenv, expr,ugraph) = disambiguator#disambiguateTermAst ast in let uri = UriManager.uri_of_string (qualify name ^ ".con") in let proof = MatitaProof.proof ~typ:expr ~uri ~metasenv () in currentProof#start proof; New_state Proof | TacticAst.Command (TacticAst.Theorem (_, Some name, type_ast, Some body_ast)) -> let (_, metasenv, type_cic, ugraph) = disambiguator#disambiguateTermAst type_ast in let (_, metasenv, body_cic, ugraph) = disambiguator#disambiguateTermAst ~metasenv body_ast in let (body_type, ugraph) = CicTypeChecker.type_of_aux' metasenv [] body_cic ugraph in let uri = UriManager.uri_of_string (qualify name ^ ".con") in let (subst, metasenv, ugraph) = CicUnification.fo_unif metasenv [] body_type type_cic ugraph in let body = CicMetaSubst.apply_subst subst body_cic in let ty = CicMetaSubst.apply_subst subst type_cic in add_constant_to_world ~dbd ~uri ~body ~ty ~ugraph (); Quiet | TacticAst.Command (TacticAst.Inductive (params, indTypes)) -> let (uri, (indTypes, params, leftno)) = inddef_of_ast params indTypes disambiguator in let obj = Cic.InductiveDefinition (indTypes, params, leftno) in let ugraph = CicTypeChecker.typecheck_mutual_inductive_defs uri (indTypes, params, leftno) CicUniv.empty_ugraph in let ugraph = CicUnivUtils.clean_and_fill uri obj ugraph in CicEnvironment.put_inductive_definition uri (obj, ugraph); MetadataDb.index_inductive_def ~dbd ~owner:(Helm_registry.get "matita.owner") ~uri ~types:indTypes; let msgs = ref [] in let elim sort = try let obj = CicElim.elim_of ~sort uri 0 in let (name, body, ty) = split_obj obj in let uri = UriManager.uri_of_string (qualify name ^ ".con") in (* TODO Zack: make CicElim returns a universe *) let ugraph = CicUniv.empty_ugraph in add_constant_to_world ~dbd ~uri ?body ~ty ~ugraph (); msgs := (sprintf "%s defined" name) :: !msgs; with CicElim.Can_t_eliminate -> () in List.iter elim [ Cic.Prop; Cic.Set; (Cic.Type (CicUniv.fresh ())) ]; Echo (String.concat "\n" (List.rev !msgs)) | TacticAst.Command TacticAst.Quit -> currentProof#quit (); New_state Command (* dummy answer, useless *) | TacticAst.Command TacticAst.Proof -> (* do nothing, just for compatibility with coq syntax *) New_state Command | tactical -> shared#evalTactical tactical end (** create a ProofEngineTypes.mk_fresh_name_type function which uses given * names as long as they are available, then it fallbacks to name generation * using FreshNamesGenerator module *) let namer_of names = let len = List.length names in let count = ref 0 in fun metasenv context name ~typ -> if !count < len then begin let name = Cic.Name (List.nth names !count) in incr count; name end else FreshNamesGenerator.mk_fresh_name ~subst:[] metasenv context name ~typ (** Implements phrases that should be accepted only in Proof state, basically * tacticals *) class proofState ~(disambiguator: MatitaTypes.disambiguator) ~(currentProof: MatitaTypes.currentProof) ~(console: MatitaTypes.console) ?mathViewer ~(dbd: Mysql.dbd) () = let disambiguate ast = let (_, _, term, _) = disambiguate ~disambiguator ~currentProof ast in term in (** tactic AST -> ProofEngineTypes.tactic *) let rec lookup_tactic = function | TacticAst.LocatedTactic (_, tactic) -> lookup_tactic tactic | TacticAst.Intros (_, names) -> (* TODO Zack implement intros length *) PrimitiveTactics.intros_tac ~mk_fresh_name_callback:(namer_of names) () | TacticAst.Reflexivity -> Tactics.reflexivity | TacticAst.Assumption -> Tactics.assumption | TacticAst.Contradiction -> Tactics.contradiction | TacticAst.Exists -> Tactics.exists | TacticAst.Fourier -> Tactics.fourier | TacticAst.Left -> Tactics.left | TacticAst.Right -> Tactics.right | TacticAst.Ring -> Tactics.ring | TacticAst.Split -> Tactics.split | TacticAst.Symmetry -> Tactics.symmetry | TacticAst.Transitivity term -> Tactics.transitivity (disambiguate term) | TacticAst.Apply term -> Tactics.apply (disambiguate term) | TacticAst.Absurd term -> Tactics.absurd (disambiguate term) | TacticAst.Exact term -> Tactics.exact (disambiguate term) | TacticAst.Cut term -> Tactics.cut (disambiguate term) | TacticAst.Elim (term, _) -> (* TODO Zack implement "using" argument *) Tactics.elim_intros_simpl (disambiguate term) | TacticAst.ElimType term -> Tactics.elim_type (disambiguate term) | TacticAst.Replace (what, with_what) -> Tactics.replace ~what:(disambiguate what) ~with_what:(disambiguate with_what) | TacticAst.Auto -> Tactics.auto_new ~dbd (* (* TODO Zack a lot more of tactics to be implemented here ... *) | TacticAst.Change of 'term * 'term * 'ident option | TacticAst.Change_pattern of 'term pattern * 'term * 'ident option | TacticAst.Decompose of 'ident * 'ident list | TacticAst.Discriminate of 'ident | TacticAst.Fold of reduction_kind * 'term | TacticAst.Injection of 'ident | TacticAst.LetIn of 'term * 'ident | TacticAst.Reduce of reduction_kind * 'term pattern * 'ident option | TacticAst.Replace_pattern of 'term pattern * 'term | TacticAst.Rewrite of direction * 'term * 'ident option *) | _ -> MatitaTypes.not_implemented "some tactic" in let shared = new sharedState ~disambiguator ~currentProof ~console ~dbd () in object (self) inherit interpreterState ~console method evalTactical = function | TacticAst.LocatedTactical (_, tactical) -> self#evalTactical tactical | TacticAst.Command TacticAst.Abort -> currentProof#abort (); New_state Command | TacticAst.Command (TacticAst.Undo steps) -> currentProof#proof#undo ?steps (); New_state Proof | TacticAst.Command (TacticAst.Redo steps) -> currentProof#proof#redo ?steps (); New_state Proof | TacticAst.Command (TacticAst.Qed None) -> if not (currentProof#onGoing ()) then assert false; let proof = currentProof#proof in let (uri, metasenv, bo, ty) = proof#proof in let uri = MatitaTypes.unopt_uri uri in (* TODO Zack this function probably should not simply fail with * Failure, but rather raise some more meaningful exception *) if metasenv <> [] then failwith "Proof not completed"; let proved_ty,ugraph = CicTypeChecker.type_of_aux' [] [] bo CicUniv.empty_ugraph in let b,ugraph = CicReduction.are_convertible [] proved_ty ty ugraph in if not b then failwith "Wrong proof"; add_constant_to_world ~dbd ~uri ~body:bo ~ty ~ugraph (); currentProof#abort (); (match mathViewer with None -> () | Some v -> v#unload ()); New_state Command | TacticAst.Seq tacticals -> (* TODO Zack check for proof completed at each step? *) List.iter (fun t -> ignore (self#evalTactical t)) tacticals; New_state Proof | TacticAst.Tactic tactic_phrase -> let tactic = lookup_tactic tactic_phrase in currentProof#proof#apply_tactic tactic; New_state Proof | tactical -> shared#evalTactical tactical end class interpreter ~(disambiguator: MatitaTypes.disambiguator) ~(currentProof: MatitaTypes.currentProof) ~(console: MatitaTypes.console) ?mathViewer ~(dbd: Mysql.dbd) () = let commandState = new commandState ~disambiguator ~currentProof ~console ?mathViewer ~dbd () in let proofState = new proofState ~disambiguator ~currentProof ~console ?mathViewer ~dbd () in object (self) val mutable state = commandState method reset = state <- commandState method endOffset = state#endOffset method private updateState = function | New_state Command -> (state <- commandState) | New_state Proof -> (state <- proofState) | _ -> () method private eval f = let ok () = console#clear (); (true, true) in match console#wrap_exn f with | Some (New_state Command) -> (state <- commandState); ok () | Some (New_state Proof) -> (state <- proofState); ok () | Some (Echo msg) -> console#echo_message msg; (true, false) | Some Quiet -> ok () | None -> (false, false) method evalPhrase s = self#eval (fun () -> state#evalPhrase s) method evalAst ast = self#eval (fun () -> state#evalAst ast) end