]> matita.cs.unibo.it Git - helm.git/blobdiff - helm/matita/matitaInterpreter.ml
bumped changelog line to match upload date
[helm.git] / helm / matita / matitaInterpreter.ml
index 4b87ec8f808012fcac907889e7484b4089dd18d5..35ec6119d2bf4d781fcf0c7c6e386da915e5dd6a 100644 (file)
  * http://helm.cs.unibo.it/
  *)
 
-type state_tag = [ `Command | `Proof ]
+(** 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_tag 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
+
+  (** None means: "same state as before" *)
+type state_tag = [ `Command | `Proof ] option
+
+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 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 (proof_handler:MatitaTypes.proof_handler) =
+  if proof_handler.MatitaTypes.has_proof () then
+    let proof = proof_handler.MatitaTypes.get_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) ~proof_handler ast =
+  if proof_handler.MatitaTypes.has_proof () then begin
+    let proof = proof_handler.MatitaTypes.get_proof () in
+    let metasenv = proof#metasenv in
+    let goal = proof#goal in
+    let context = canonical_context goal metasenv in
+    let (_, metasenv, term) 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: MatitaConsole.console) ->
+  object (self)
 
-class type interpreterState =
-  object
       (** eval a toplevel phrase in the current state and return the new state
       *)
-    method evalPhrase: string -> state_tag
+    method parsePhrase s =
+      match CicTextualParser2.parse_tactical (Stream.of_string 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 -> state_tag
+
+(*
+    method undo ?(steps = 1) () =
+      for i = 1 to steps do
+        match List.hd !history with
+        | `Qed 
+        FINQUI
+*)
+
+    method evalPhrase s =
+      debug_print (sprintf "evaluating '%s'" s);
+      self#evalTactical (self#parsePhrase s)
+
+    method endOffset =
+      match !loc with
+      | Some (start_pos, end_pos) -> end_pos.Lexing.pos_cnum
+      | None -> failwith "MatitaInterpreter: no offset recorded"
+
+  end
+
+let check_widget: MatitaTypes.sequent_viewer lazy_t = lazy
+  (let gui = MatitaGui.instance () in
+  MatitaMathView.sequent_viewer ~show:true ~packing:gui#check#scrolledCheck#add
+    ())
+
+  (** Implements phrases that should be accepted in all states *)
+class sharedState
+  ~(disambiguator: MatitaTypes.disambiguator)
+  ~(proof_handler: MatitaTypes.proof_handler)
+  ~(console: MatitaConsole.console)
+  ()
+=
+  object (self)
+    inherit interpreterState ~console
+    method evalTactical = function
+      | TacticAst.Command TacticAst.Quit ->
+          proof_handler.MatitaTypes.quit ();
+          Some `Command (* dummy answer, useless *)
+      | TacticAst.Command TacticAst.Proof ->
+            (* do nothing, just for compatibility with coq syntax *)
+          Some `Command
+      | TacticAst.Command (TacticAst.Baseuri (Some uri)) ->
+          baseuri := uri;
+          console#echo_message (sprintf "base uri set to \"%s\"" uri);
+          None
+      | TacticAst.Command (TacticAst.Baseuri None) ->
+          console#echo_message (sprintf "base uri is \"%s\"" !baseuri);
+          None
+      | TacticAst.Command (TacticAst.Check term) ->
+          let (_, _, term) = disambiguate ~disambiguator ~proof_handler term in
+          let (context, metasenv) = get_context_and_metasenv proof_handler in
+          let dummyno = CicMkImplicit.new_meta metasenv [] in
+          let ty = CicTypeChecker.type_of_aux' metasenv context term in
+          let expr = Cic.Cast (term, ty) in
+          let sequent = (dummyno, context, expr) in
+          let widget = Lazy.force check_widget in
+          let gui = MatitaGui.instance () in
+          gui#check#checkWin#show ();
+          gui#main#showCheckMenuItem#set_active true;
+          widget#load_sequent (sequent::metasenv) dummyno;
+          None
+      | tactical ->
+          raise (Command_error (TacticAstPp.pp_tactical tactical))
   end
 
+  (** Implements phrases that should be accepted only in `Command state *)
 class commandState
   ~(disambiguator: MatitaTypes.disambiguator)
   ~(proof_handler: MatitaTypes.proof_handler)
   ~(console: MatitaConsole.console)
   ()
 =
-  object
-    method evalPhrase s: state_tag =
-      let command = CicTextualParser2.parse_command (Stream.of_string s) in
-      match command with
-      | CommandAst.Theorem (_, _, Some name, ast, None) ->
+  let shared = new sharedState ~disambiguator ~proof_handler ~console () 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) = disambiguator#disambiguateTermAst ast in
-          let _  = CicTypeChecker.type_of_aux' metasenv [] expr in
-          let proof = MatitaProof.proof ~typ:expr ~metasenv () in
+          let uri = UriManager.uri_of_string (qualify name) in
+          let proof = MatitaProof.proof ~typ:expr ~uri ~metasenv () in
           proof_handler.MatitaTypes.new_proof proof;
-          `Proof
-      | CommandAst.Quit _ ->
+          Some `Proof
+      | TacticAst.Command TacticAst.Quit ->
           proof_handler.MatitaTypes.quit ();
-          `Command (* dummy answer *)
-      | _ ->
-          MatitaTypes.not_implemented (* TODO Zack *)
-            "MatitaInterpreter.commandState#evalPhrase: commands other than full theorem ones";
-          `Proof
+          Some `Command (* dummy answer, useless *)
+      | TacticAst.Command TacticAst.Proof ->
+            (* do nothing, just for compatibility with coq syntax *)
+          Some `Command
+      | tactical -> shared#evalTactical tactical
   end
 
-  (* TODO Zack FINQUI
-  * bisogna rivedere la grammatica di tatticali/comandi
-  * molti comandi (o addirittura tutti tranne Theorem) hanno senso anche nello
-  * stato proof, e' quindi un casino parsare la phrase. Un'idea potrebbe essere
-  * quella di tentare di parsare una tattica e se il parsing fallisce provare a
-  * parsare un comando (BLEAARGH). Oppure si puo' aggiungere una possibile entry
-  * nella grammatica delle tattiche che punti ad un comando (RI-BLEAARGH).
-  * Oppure boh ...
-  *)
+  (** 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 metasenv context name ~typ
+
+  (** Implements phrases that should be accepted only in `Proof state, basically
+  * tacticals *)
 class proofState
   ~(disambiguator: MatitaTypes.disambiguator)
   ~(proof_handler: MatitaTypes.proof_handler)
   ~(console: MatitaConsole.console)
   ()
 =
-  object
-    method evalPhrase (s: string): state_tag =
-      (* TODO Zack *)
-      MatitaTypes.not_implemented "MatitaInterpreter.proofState#evalPhrase";
-      `Command
+  let disambiguate ast =
+    let (_, _, term) = disambiguate ~disambiguator ~proof_handler 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)
+  (*
+    (* 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 ~proof_handler ~console () in
+  object (self)
+    inherit interpreterState ~console
+
+    method evalTactical = function
+      | TacticAst.LocatedTactical (_, tactical) -> self#evalTactical tactical
+      | TacticAst.Command TacticAst.Abort ->
+          proof_handler.MatitaTypes.abort_proof ();
+          Some `Command
+      | TacticAst.Command (TacticAst.Undo steps) ->
+          (proof_handler.MatitaTypes.get_proof ())#undo ?steps ();
+          Some `Proof
+      | TacticAst.Command (TacticAst.Redo steps) ->
+          (proof_handler.MatitaTypes.get_proof ())#redo ?steps ();
+          Some `Proof
+      | TacticAst.Command (TacticAst.Qed None) ->
+          (* TODO Zack this function probably should not simply fail with
+          * Failure, but rather raise some more meaningful exception *)
+          if not (proof_handler.MatitaTypes.has_proof ()) then assert false;
+          let proof = proof_handler.MatitaTypes.get_proof () in
+          let (uri, metasenv, bo, ty) = proof#proof in
+          let uri = MatitaTypes.unopt_uri uri in
+          if metasenv <> [] then failwith "Proof not completed";
+          let proved_ty = CicTypeChecker.type_of_aux' [] [] bo in
+          if not (CicReduction.are_convertible [] proved_ty ty) then
+            failwith "Wrong proof";
+          (* TODO Zack [] probably wrong *)
+          CicEnvironment.add_type_checked_term uri
+            (Cic.Constant ((UriManager.name_of_uri uri),(Some bo),ty,[]));
+          proof_handler.MatitaTypes.set_proof None;
+          (MatitaMathView.proof_viewer_instance ())#unload;
+          (* TODO Zack a lot more to be done here:
+            * - save object to disk in xml format
+            * - collect metadata
+            * - register uri to the getter *)
+          Some `Command
+      | TacticAst.Seq tacticals ->
+          (* TODO Zack check for proof completed at each step? *)
+          List.iter (fun t -> ignore (self#evalTactical t)) tacticals;
+          Some `Proof
+      | TacticAst.Tactic tactic_phrase ->
+          let tactic = lookup_tactic tactic_phrase in
+          (proof_handler.MatitaTypes.get_proof ())#apply_tactic tactic;
+          Some `Proof
+      | tactical -> shared#evalTactical tactical
   end
 
 class interpreter
@@ -86,17 +327,30 @@ class interpreter
   ()
 =
   let commandState =
-    lazy (new commandState ~disambiguator ~proof_handler ~console ())
+    new commandState ~disambiguator ~proof_handler ~console ()
   in
-  let proofState =
-    lazy (new proofState ~disambiguator ~proof_handler ~console ())
-  in
-  object
-    val mutable state = Lazy.force commandState
+  let proofState = new proofState ~disambiguator ~proof_handler ~console () in
+  object (self)
+    val mutable state = commandState
+
+    method reset = state <- commandState
+
+    method endOffset = state#endOffset
+
+    method private updateState = function
+      | Some `Command -> state <- commandState
+      | Some `Proof -> state <- proofState
+      | None -> ()
+
+    method evalPhrase ?(transparent = false) s =
+      try
+        self#updateState (state#evalPhrase s)
+      with exn ->
+        if transparent then
+          raise exn
+        else
+          console#echo_error (sprintf "Uncaught exception: %s"
+            (Printexc.to_string exn))
 
-    method evalPhrase s =
-      match state#evalPhrase s with
-      | `Command -> state <- Lazy.force commandState
-      | `Proof -> state <- Lazy.force proofState
   end