1 (* Copyright (C) 2004, 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/
26 (** Interpreter for textual phrases coming from matita's console (textual entry
27 * window at the bottom of the main window).
29 * Interpreter is either in Command state or in Proof state (see state type
30 * below). In Command state commands for starting proofs are accepted, but
31 * tactic and tactical applications are not. In Proof state both
32 * tactic/tacticals and commands are accepted.
39 type state = Command | Proof
40 type outcome = New_state of state | Quiet | Echo of string
42 exception Command_error of string
46 UriManager.uri_of_string (sprintf "%s/%s" BuildTimeConf.base_uri name)
49 let baseuri = lazy (ref ("cic:/matita/" ^ Helm_registry.get "matita.owner"))
51 let baseuri = !(Lazy.force baseuri) in
52 if baseuri.[String.length baseuri - 1] = '/' then
55 String.concat "/" [baseuri; name]
56 let split_obj = function
57 | Cic.Constant (name, body, ty, _, attrs)
58 | Cic.Variable (name, body, ty, _, attrs) -> (name, body, ty, attrs)
61 let canonical_context metano metasenv =
63 let (_, context, _) = List.find (fun (m, _, _) -> m = metano) metasenv in
66 failwith (sprintf "Can't find canonical context for %d" metano)
68 let get_context_and_metasenv (currentProof:MatitaTypes.currentProof) =
69 if currentProof#onGoing () then
70 let proof = currentProof#proof in
71 let metasenv = proof#metasenv in
72 let goal = proof#goal in
73 (canonical_context goal metasenv, metasenv)
77 (** term AST -> Cic.term. Uses disambiguator and change imperatively the
78 * metasenv as needed *)
79 let disambiguate ~(disambiguator:MatitaTypes.disambiguator) ~currentProof ast =
80 if currentProof#onGoing () then begin
81 let proof = currentProof#proof in
82 let metasenv = proof#metasenv in
83 let goal = proof#goal in
84 let context = canonical_context goal metasenv in
85 let (_, metasenv, term,ugraph) as retval =
86 disambiguator#disambiguateTermAst ~context ~metasenv ast
88 proof#set_metasenv metasenv;
91 disambiguator#disambiguateTermAst ast
93 class virtual interpreterState =
94 (* static values, shared by all states inheriting this class *)
96 let history = ref [] in
97 fun ~(console: MatitaTypes.console) ->
100 (** eval a toplevel phrase in the current state and return the new state
102 method parsePhrase s =
103 match CicTextualParser2.parse_tactical s with
104 | (TacticAst.LocatedTactical (loc', tac)) as tactical ->
106 (match tac with (* update interpreter history *)
107 | TacticAst.Command (TacticAst.Qed None) ->
108 history := `Qed :: !history
109 | TacticAst.Command (TacticAst.Theorem (_, Some name, _, None)) ->
110 history := `Theorem name :: !history
111 | TacticAst.Command (TacticAst.Qed _)
112 | TacticAst.Command (TacticAst.Theorem _) -> assert false
113 | _ -> history := `Tactic :: !history);
117 method virtual evalTactical:
118 (CicAst.term, string) TacticAst.tactical -> outcome
120 method evalPhrase s =
121 debug_print (sprintf "evaluating '%s'" s);
122 self#evalTactical (self#parsePhrase (Stream.of_string s))
124 method evalAst ast = self#evalTactical ast
128 | Some (start_pos, end_pos) -> end_pos.Lexing.pos_cnum
129 | None -> failwith "MatitaInterpreter: no offset recorded"
133 (** Implements phrases that should be accepted in all states *)
135 ~(disambiguator: MatitaTypes.disambiguator)
136 ~(currentProof: MatitaTypes.currentProof)
137 ~(console: MatitaTypes.console)
138 ?(mathViewer: MatitaTypes.mathViewer option)
143 inherit interpreterState ~console
144 method evalTactical = function
145 | TacticAst.Command TacticAst.Quit ->
146 currentProof#quit ();
147 assert false (* dummy answer, useless *)
148 | TacticAst.Command TacticAst.Proof ->
149 (* do nothing, just for compatibility with coq syntax *)
151 | TacticAst.Command (TacticAst.Baseuri (Some uri)) ->
152 Lazy.force baseuri := uri;
153 console#echo_message (sprintf "base uri set to \"%s\"" uri);
155 | TacticAst.Command (TacticAst.Baseuri None) ->
156 console#echo_message (sprintf "base uri is \"%s\""
157 !(Lazy.force baseuri));
159 | TacticAst.Command (TacticAst.Check term) ->
160 let (_, _, term,ugraph) =
161 disambiguate ~disambiguator ~currentProof term
163 let (context, metasenv) = get_context_and_metasenv currentProof in
164 let dummyno = CicMkImplicit.new_meta metasenv [] in
166 CicTypeChecker.type_of_aux' metasenv context term ugraph
168 (* TASSI: here ugraph1 is unused.... FIXME *)
169 let expr = Cic.Cast (term, ty) in
170 let sequent = (dummyno, context, expr) in
171 (match mathViewer with
173 | Some v -> v#checkTerm sequent metasenv);
175 | TacticAst.Command (TacticAst.Search_pat (search_kind, pat)) ->
177 match search_kind with
178 | `Locate -> MetadataQuery.locate ~dbd pat
179 | `Elim -> MetadataQuery.elim ~dbd pat
182 (* TODO ZACK: show URIs to the user *)
185 raise (Command_error (TacticAstPp.pp_tactical tactical))
190 let pp_indtypes indTypes =
192 (fun (name, _, typ, constructors) ->
193 printf "%s: %s\n" name (CicPp.ppterm typ);
195 (fun (name, term) -> printf "\t%s: %s\n" name (CicPp.ppterm term))
200 let inddef_of_ast params indTypes (disambiguator:MatitaTypes.disambiguator) =
201 let add_pi binders t =
203 (fun (name, ast) acc ->
204 CicAst.Binder (`Forall, (Cic.Name name, Some ast), acc))
208 List.map (fun (name, _, typ, _) -> (name, add_pi params typ)) indTypes
210 let binders = ind_binders @ params in
212 let add_ast ast = asts := ast :: !asts in
213 let paramsno = List.length params in
214 let indbindersno = List.length ind_binders in
216 (fun (name, _, typ, constructors) ->
217 add_ast (add_pi params typ);
218 List.iter (fun (_, ast) -> add_ast (add_pi binders ast)) constructors)
220 let (_, metasenv, terms, ugraph) =
221 disambiguator#disambiguateTermAsts ~metasenv:[] !asts
223 let terms = ref (List.rev terms) in
225 match !terms with [] -> assert false | hd :: tl -> terms := tl; hd
229 | (name, _, _, _) :: _ -> qualify name ^ ".ind"
233 let counter = ref 0 in
237 CicUtil.term_of_uri (sprintf "%s#xpointer(1/%d)" uri !counter))
240 let subst_mutinds = List.fold_right CicSubstitution.subst mutinds in
243 (fun acc (name, inductive, typ, constructors) ->
244 let cicTyp = get_term () in
245 let cicConstructors =
247 (fun acc (name, _) ->
249 subst_mutinds (CicUtil.strip_prods indbindersno (get_term ()))
254 (name, inductive, cicTyp, List.rev cicConstructors) :: acc)
257 let cicIndTypes = List.rev cicIndTypes in
258 (UriManager.uri_of_string uri, (cicIndTypes, [], paramsno))
260 (* TODO Zack a lot more to be done here:
261 * - save object to disk in xml format
262 * - register uri to the getter
263 * - save universe file *)
264 let add_constant_to_world ~(console:MatitaTypes.console)
265 ~dbd ~uri ?body ~ty ?(params = []) ?(attrs = []) ~ugraph ()
267 let suri = UriManager.string_of_uri uri in
268 if CicEnvironment.in_library uri then
269 error (sprintf "%s constant already defined" suri)
271 let name = UriManager.name_of_uri uri in
272 let obj = Cic.Constant (name, body, ty, params, attrs) in
273 let ugraph = CicUnivUtils.clean_and_fill uri obj ugraph in
274 CicEnvironment.add_type_checked_term uri (obj, ugraph);
275 MetadataDb.index_constant ~dbd
276 ~owner:(Helm_registry.get "matita.owner") ~uri ~body ~ty;
277 console#echo_message (sprintf "%s constant defined" suri)
280 let add_inductive_def_to_world ~(console:MatitaTypes.console)
281 ~dbd ~uri ~indTypes ?(params = []) ?(leftno = 0) ?(attrs = []) ~ugraph ()
283 let suri = UriManager.string_of_uri uri in
284 if CicEnvironment.in_library uri then
285 error (sprintf "%s inductive type already defined" suri)
287 let name = UriManager.name_of_uri uri in
288 let obj = Cic.InductiveDefinition (indTypes, params, leftno, attrs) in
289 let ugraph = CicUnivUtils.clean_and_fill uri obj ugraph in
290 CicEnvironment.put_inductive_definition uri (obj, ugraph);
291 MetadataDb.index_inductive_def ~dbd
292 ~owner:(Helm_registry.get "matita.owner") ~uri ~types:indTypes;
293 console#echo_message (sprintf "%s inductive type defined" suri);
296 let obj = CicElim.elim_of ~sort uri 0 in
297 let (name, body, ty, attrs) = split_obj obj in
298 let suri = qualify name ^ ".con" in
299 let uri = UriManager.uri_of_string suri in
300 (* TODO Zack: make CicElim returns a universe *)
301 let ugraph = CicUniv.empty_ugraph in
302 add_constant_to_world ~console ~dbd ~uri ?body ~ty ~attrs ~ugraph ();
305 (sprintf "%s eliminator (automatically) defined" suri)
307 with CicElim.Can_t_eliminate -> ()
309 List.iter elim [ Cic.Prop; Cic.Set; (Cic.Type (CicUniv.fresh ())) ];
312 (** Implements phrases that should be accepted only in Command state *)
314 ~(disambiguator: MatitaTypes.disambiguator)
315 ~(currentProof: MatitaTypes.currentProof)
316 ~(console: MatitaTypes.console)
322 new sharedState ~disambiguator ~currentProof ~console ?mathViewer ~dbd ()
325 inherit interpreterState ~console
327 method evalTactical = function
328 | TacticAst.LocatedTactical (_, tactical) -> self#evalTactical tactical
329 | TacticAst.Command (TacticAst.Theorem (_, Some name, ast, None)) ->
330 let (_, metasenv, expr,ugraph) =
331 disambiguator#disambiguateTermAst ast
333 let uri = UriManager.uri_of_string (qualify name ^ ".con") in
334 let proof = MatitaProof.proof ~typ:expr ~uri ~metasenv () in
335 currentProof#start proof;
338 (TacticAst.Theorem (_, Some name, type_ast, Some body_ast)) ->
339 let (_, metasenv, type_cic, ugraph) =
340 disambiguator#disambiguateTermAst type_ast
342 let (_, metasenv, body_cic, ugraph) =
343 disambiguator#disambiguateTermAst ~metasenv body_ast
345 let (body_type, ugraph) =
346 CicTypeChecker.type_of_aux' metasenv [] body_cic ugraph
348 let uri = UriManager.uri_of_string (qualify name ^ ".con") in
349 let (subst, metasenv, ugraph) =
350 CicUnification.fo_unif metasenv [] body_type type_cic ugraph
352 let body = CicMetaSubst.apply_subst subst body_cic in
353 let ty = CicMetaSubst.apply_subst subst type_cic in
354 add_constant_to_world ~console ~dbd ~uri ~body ~ty ~ugraph ();
356 | TacticAst.Command (TacticAst.Inductive (params, indTypes)) ->
358 let (uri, (indTypes, params, leftno)) =
359 inddef_of_ast params indTypes disambiguator
361 let obj = Cic.InductiveDefinition (indTypes, params, leftno, []) in
363 CicTypeChecker.typecheck_mutual_inductive_defs uri
364 (indTypes, params, leftno) CicUniv.empty_ugraph
366 add_inductive_def_to_world ~console
367 ~dbd ~uri ~indTypes ~params ~leftno ~ugraph ();
369 | TacticAst.Command TacticAst.Quit ->
370 currentProof#quit ();
371 New_state Command (* dummy answer, useless *)
372 | TacticAst.Command TacticAst.Proof ->
373 (* do nothing, just for compatibility with coq syntax *)
375 | tactical -> shared#evalTactical tactical
378 (** create a ProofEngineTypes.mk_fresh_name_type function which uses given
379 * names as long as they are available, then it fallbacks to name generation
380 * using FreshNamesGenerator module *)
382 let len = List.length names in
384 fun metasenv context name ~typ ->
385 if !count < len then begin
386 let name = Cic.Name (List.nth names !count) in
390 FreshNamesGenerator.mk_fresh_name ~subst:[] metasenv context name ~typ
392 (** Implements phrases that should be accepted only in Proof state, basically
395 ~(disambiguator: MatitaTypes.disambiguator)
396 ~(currentProof: MatitaTypes.currentProof)
397 ~(console: MatitaTypes.console)
402 let disambiguate ast =
403 let (_, _, term, _) = disambiguate ~disambiguator ~currentProof ast in
406 (** tactic AST -> ProofEngineTypes.tactic *)
407 let rec lookup_tactic = function
408 | TacticAst.LocatedTactic (_, tactic) -> lookup_tactic tactic
409 | TacticAst.Intros (_, names) -> (* TODO Zack implement intros length *)
410 PrimitiveTactics.intros_tac ~mk_fresh_name_callback:(namer_of names) ()
411 | TacticAst.Reflexivity -> Tactics.reflexivity
412 | TacticAst.Assumption -> Tactics.assumption
413 | TacticAst.Contradiction -> Tactics.contradiction
414 | TacticAst.Exists -> Tactics.exists
415 | TacticAst.Fourier -> Tactics.fourier
416 | TacticAst.Left -> Tactics.left
417 | TacticAst.Right -> Tactics.right
418 | TacticAst.Ring -> Tactics.ring
419 | TacticAst.Split -> Tactics.split
420 | TacticAst.Symmetry -> Tactics.symmetry
421 | TacticAst.Transitivity term -> Tactics.transitivity (disambiguate term)
422 | TacticAst.Apply term -> Tactics.apply (disambiguate term)
423 | TacticAst.Absurd term -> Tactics.absurd (disambiguate term)
424 | TacticAst.Exact term -> Tactics.exact (disambiguate term)
425 | TacticAst.Cut term -> Tactics.cut (disambiguate term)
426 | TacticAst.Elim (term, _) -> (* TODO Zack implement "using" argument *)
427 Tactics.elim_intros_simpl (disambiguate term)
428 | TacticAst.ElimType term -> Tactics.elim_type (disambiguate term)
429 | TacticAst.Replace (what, with_what) ->
430 Tactics.replace ~what:(disambiguate what)
431 ~with_what:(disambiguate with_what)
432 | TacticAst.Auto -> Tactics.auto_new ~dbd
434 (* TODO Zack a lot more of tactics to be implemented here ... *)
435 | TacticAst.Change of 'term * 'term * 'ident option
436 | TacticAst.Change_pattern of 'term pattern * 'term * 'ident option
437 | TacticAst.Decompose of 'ident * 'ident list
438 | TacticAst.Discriminate of 'ident
439 | TacticAst.Fold of reduction_kind * 'term
440 | TacticAst.Injection of 'ident
441 | TacticAst.LetIn of 'term * 'ident
442 | TacticAst.Reduce of reduction_kind * 'term pattern * 'ident option
443 | TacticAst.Replace_pattern of 'term pattern * 'term
444 | TacticAst.Rewrite of direction * 'term * 'ident option
447 MatitaTypes.not_implemented "some tactic"
450 new sharedState ~disambiguator ~currentProof ~console ?mathViewer ~dbd ()
453 inherit interpreterState ~console
455 method evalTactical = function
456 | TacticAst.LocatedTactical (_, tactical) -> self#evalTactical tactical
457 | TacticAst.Command TacticAst.Abort ->
458 currentProof#abort ();
460 | TacticAst.Command (TacticAst.Undo steps) ->
461 currentProof#proof#undo ?steps ();
463 | TacticAst.Command (TacticAst.Redo steps) ->
464 currentProof#proof#redo ?steps ();
466 | TacticAst.Command (TacticAst.Qed None) ->
467 if not (currentProof#onGoing ()) then assert false;
468 let proof = currentProof#proof in
469 let (uri, metasenv, bo, ty) = proof#proof in
470 let uri = MatitaTypes.unopt_uri uri in
471 let suri = UriManager.string_of_uri uri in
472 (* TODO Zack this function probably should not simply fail with
473 * Failure, but rather raise some more meaningful exception *)
474 if metasenv <> [] then failwith "Proof not completed";
475 let proved_ty,ugraph =
476 CicTypeChecker.type_of_aux' [] [] bo CicUniv.empty_ugraph
479 CicReduction.are_convertible [] proved_ty ty ugraph
481 if not b then failwith "Wrong proof";
482 add_constant_to_world ~console ~dbd ~uri ~body:bo ~ty ~ugraph ();
483 currentProof#abort ();
484 (match mathViewer with None -> () | Some v -> v#unload ());
485 console#echo_message (sprintf "%s defined" suri);
487 | TacticAst.Seq tacticals ->
488 (* TODO Zack check for proof completed at each step? *)
489 List.iter (fun t -> ignore (self#evalTactical t)) tacticals;
491 | TacticAst.Tactic tactic_phrase ->
492 let tactic = lookup_tactic tactic_phrase in
493 currentProof#proof#apply_tactic tactic;
495 | tactical -> shared#evalTactical tactical
499 ~(disambiguator: MatitaTypes.disambiguator)
500 ~(currentProof: MatitaTypes.currentProof)
501 ~(console: MatitaTypes.console)
507 new commandState ~disambiguator ~currentProof ~console ?mathViewer ~dbd ()
510 new proofState ~disambiguator ~currentProof ~console ?mathViewer ~dbd ()
513 val mutable state = commandState
515 method reset = state <- commandState
517 method endOffset = state#endOffset
519 method private updateState = function
520 | New_state Command -> (state <- commandState)
521 | New_state Proof -> (state <- proofState)
524 method private eval f =
525 let ok () = (* console#clear (); *) (true, true) in
526 match console#wrap_exn f with
527 | Some (New_state Command) -> (state <- commandState); ok ()
528 | Some (New_state Proof) -> (state <- proofState); ok ()
529 | Some (Echo msg) -> console#echo_message msg; (true, false)
530 | Some Quiet -> ok ()
531 | None -> (false, false)
533 method evalPhrase s = self#eval (fun () -> state#evalPhrase s)
534 method evalAst ast = self#eval (fun () -> state#evalAst ast)