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"))
50 let basedir = ref ((Unix.getpwuid (Unix.getuid ())).Unix.pw_dir) ;;
53 let baseuri = !(Lazy.force baseuri) in
54 if baseuri.[String.length baseuri - 1] = '/' then
57 String.concat "/" [baseuri; name]
58 let split_obj = function
59 | Cic.Constant (name, body, ty, _, attrs)
60 | Cic.Variable (name, body, ty, _, attrs) -> (name, body, ty, attrs)
63 let canonical_context metano metasenv =
65 let (_, context, _) = List.find (fun (m, _, _) -> m = metano) metasenv in
68 failwith (sprintf "Can't find canonical context for %d" metano)
70 let get_context_and_metasenv (currentProof:MatitaTypes.currentProof) =
71 if currentProof#onGoing () then
72 let proof = currentProof#proof in
73 let metasenv = proof#metasenv in
74 let goal = proof#goal in
75 (canonical_context goal metasenv, metasenv)
79 (** term AST -> Cic.term. Uses disambiguator and change imperatively the
80 * metasenv as needed *)
81 let disambiguate ~(disambiguator:MatitaTypes.disambiguator) ~currentProof ast =
82 if currentProof#onGoing () then begin
83 let proof = currentProof#proof in
84 let metasenv = proof#metasenv in
85 let goal = proof#goal in
86 let context = canonical_context goal metasenv in
87 let (_, metasenv, term,ugraph) as retval =
88 disambiguator#disambiguateTermAst ~context ~metasenv ast
90 proof#set_metasenv metasenv;
93 disambiguator#disambiguateTermAst ast
95 class virtual interpreterState =
96 (* static values, shared by all states inheriting this class *)
98 let history = ref [] in
99 fun ~(console: MatitaTypes.console) ->
102 (** eval a toplevel phrase in the current state and return the new state
104 method parsePhrase s =
105 match CicTextualParser2.parse_tactical s with
106 | (TacticAst.LocatedTactical (loc', tac)) as tactical ->
108 (match tac with (* update interpreter history *)
109 | TacticAst.Command (TacticAst.Qed None) ->
110 history := `Qed :: !history
111 | TacticAst.Command (TacticAst.Theorem (_, Some name, _, None)) ->
112 history := `Theorem name :: !history
113 | TacticAst.Command (TacticAst.Qed _)
114 | TacticAst.Command (TacticAst.Theorem _) -> assert false
115 | _ -> history := `Tactic :: !history);
119 method virtual evalTactical:
120 (CicAst.term, string) TacticAst.tactical -> outcome
122 method evalPhrase s =
123 debug_print (sprintf "evaluating '%s'" s);
124 self#evalTactical (self#parsePhrase (Stream.of_string s))
126 method evalAst ast = self#evalTactical ast
130 | Some (start_pos, end_pos) -> end_pos.Lexing.pos_cnum
131 | None -> failwith "MatitaInterpreter: no offset recorded"
135 (** Implements phrases that should be accepted in all states *)
137 ~(disambiguator: MatitaTypes.disambiguator)
138 ~(currentProof: MatitaTypes.currentProof)
139 ~(console: MatitaTypes.console)
140 ?(mathViewer: MatitaTypes.mathViewer option)
145 inherit interpreterState ~console
146 method evalTactical = function
147 | TacticAst.Command TacticAst.Quit ->
148 currentProof#quit ();
149 assert false (* dummy answer, useless *)
150 | TacticAst.Command TacticAst.Proof ->
151 (* do nothing, just for compatibility with coq syntax *)
153 | TacticAst.Command (TacticAst.Baseuri (Some uri)) ->
154 Lazy.force baseuri := uri;
155 console#echo_message (sprintf "base uri set to \"%s\"" uri);
157 | TacticAst.Command (TacticAst.Baseuri None) ->
158 console#echo_message (sprintf "base uri is \"%s\""
159 !(Lazy.force baseuri));
161 | TacticAst.Command (TacticAst.Basedir (Some path)) ->
163 console#echo_message (sprintf "base dir set to \"%s\"" path);
165 | TacticAst.Command (TacticAst.Basedir None) ->
166 console#echo_message (sprintf "base dir is \"%s\"" !basedir);
168 | TacticAst.Command (TacticAst.Check term) ->
169 let (_, _, term,ugraph) =
170 disambiguate ~disambiguator ~currentProof term
172 let (context, metasenv) = get_context_and_metasenv currentProof in
173 (* this is the Eval Compute
174 let term = CicReduction.whd context term in
176 let dummyno = CicMkImplicit.new_meta metasenv [] in
178 CicTypeChecker.type_of_aux' metasenv context term ugraph
180 (* TASSI: here ugraph1 is unused.... FIXME *)
181 let expr = Cic.Cast (term, ty) in
182 let sequent = (dummyno, context, expr) in
183 (match mathViewer with
185 | Some v -> v#checkTerm sequent metasenv);
187 | TacticAst.Command (TacticAst.Search_pat (search_kind, pat)) ->
189 match search_kind with
190 | `Locate -> MetadataQuery.locate ~dbd pat
191 | `Elim -> MetadataQuery.elim ~dbd pat
194 (* TODO ZACK: show URIs to the user *)
196 | TacticAst.Command (TacticAst.Print `Env) ->
197 let uris = CicEnvironment.list_uri () in
198 console#echo_message "Environment:";
200 console#echo_message (" " ^ (UriManager.string_of_uri u))
203 | TacticAst.Command (TacticAst.Print `Coer) ->
204 let uris = CoercGraph.get_coercions_list () in
205 console#echo_message "Coercions:";
206 List.iter (fun (s,t,u) ->
207 console#echo_message (" " ^ (UriManager.string_of_uri u))
211 raise (Command_error (TacticAstPp.pp_tactical tactical))
216 let pp_indtypes indTypes =
218 (fun (name, _, typ, constructors) ->
219 printf "%s: %s\n" name (CicPp.ppterm typ);
221 (fun (name, term) -> printf "\t%s: %s\n" name (CicPp.ppterm term))
226 let inddef_of_ast params indTypes (disambiguator:MatitaTypes.disambiguator) =
227 let add_pi binders t =
229 (fun (name, ast) acc ->
230 CicAst.Binder (`Forall, (Cic.Name name, Some ast), acc))
234 List.map (fun (name, _, typ, _) -> (name, add_pi params typ)) indTypes
236 let binders = ind_binders @ params in
238 let add_ast ast = asts := ast :: !asts in
239 let paramsno = List.length params in
240 let indbindersno = List.length ind_binders in
242 (fun (name, _, typ, constructors) ->
243 add_ast (add_pi params typ);
244 List.iter (fun (_, ast) -> add_ast (add_pi binders ast)) constructors)
246 let (_, metasenv, terms, ugraph) =
247 disambiguator#disambiguateTermAsts ~metasenv:[] !asts
249 let terms = ref (List.rev terms) in
251 match !terms with [] -> assert false | hd :: tl -> terms := tl; hd
255 | (name, _, _, _) :: _ -> qualify name ^ ".ind"
259 let counter = ref 0 in
263 CicUtil.term_of_uri (sprintf "%s#xpointer(1/%d)" uri !counter))
266 let subst_mutinds = List.fold_right CicSubstitution.subst mutinds in
269 (fun acc (name, inductive, typ, constructors) ->
270 let cicTyp = get_term () in
271 let cicConstructors =
273 (fun acc (name, _) ->
275 subst_mutinds (CicUtil.strip_prods indbindersno (get_term ()))
280 (name, inductive, cicTyp, List.rev cicConstructors) :: acc)
283 let cicIndTypes = List.rev cicIndTypes in
284 (UriManager.uri_of_string uri, (cicIndTypes, [], paramsno))
289 * FIXME this should be in another module, shared with gTopLevel
294 save_object_to_disk uri annobj ids_to_inner_sorts ids_to_inner_types pathname
297 let struri = UriManager.string_of_uri uri in
298 let idx = (String.rindex struri '/') + 1 in
299 String.sub struri idx (String.length struri - idx)
301 let path = pathname ^ "/" ^ name in
303 Cic2Xml.print_object uri ~ids_to_inner_sorts ~ask_dtd_to_the_getter:false
307 Cic2Xml.print_inner_types uri ~ids_to_inner_sorts ~ids_to_inner_types
308 ~ask_dtd_to_the_getter:false
311 let innertypesuri = UriManager.innertypesuri_of_uri uri in
312 Xml.pp ~quiet:true xmlinnertypes (Some (path ^ ".types.xml")) ;
313 Http_getter.register' innertypesuri
314 (Helm_registry.get "local_library.url" ^
315 Str.replace_first (Str.regexp "^cic:") ""
316 (UriManager.string_of_uri innertypesuri) ^ ".xml"
318 (* constant type / variable / mutual inductive types definition *)
319 Xml.pp ~quiet:true xml (Some (path ^ ".xml")) ;
320 Http_getter.register' uri
321 (Helm_registry.get "local_library.url" ^
322 Str.replace_first (Str.regexp "^cic:") ""
323 (UriManager.string_of_uri uri) ^ ".xml"
330 match UriManager.bodyuri_of_uri uri with
332 | Some bodyuri -> bodyuri
334 Xml.pp ~quiet:true bodyxml' (Some (path ^ ".body.xml")) ;
335 Http_getter.register' bodyuri
336 (Helm_registry.get "local_library.url" ^
337 Str.replace_first (Str.regexp "^cic:") ""
338 (UriManager.string_of_uri bodyuri) ^ ".xml"
342 (* TODO Zack a lot more to be done here:
343 * - save object to disk in xml format
344 * - register uri to the getter
345 * - save universe file *)
346 let add_constant_to_world ~(console:MatitaTypes.console)
347 ~dbd ~uri ?body ~ty ?(params = []) ?(attrs = []) ~ugraph ()
349 let suri = UriManager.string_of_uri uri in
350 if CicEnvironment.in_library uri then
351 error (sprintf "%s constant already defined" suri)
353 let name = UriManager.name_of_uri uri in
354 let obj = Cic.Constant (name, body, ty, params, attrs) in
355 let ugraph = CicUnivUtils.clean_and_fill uri obj ugraph in
356 CicEnvironment.add_type_checked_term uri (obj, ugraph);
357 MetadataDb.index_constant ~dbd
358 ~owner:(Helm_registry.get "matita.owner") ~uri ~body ~ty;
359 console#echo_message (sprintf "%s constant defined" suri)
362 let add_inductive_def_to_world ~(console:MatitaTypes.console)
363 ~dbd ~uri ~indTypes ?(params = []) ?(leftno = 0) ?(attrs = []) ~ugraph ()
365 let suri = UriManager.string_of_uri uri in
366 if CicEnvironment.in_library uri then
367 error (sprintf "%s inductive type already defined" suri)
369 let name = UriManager.name_of_uri uri in
370 let obj = Cic.InductiveDefinition (indTypes, params, leftno, attrs) in
371 let ugraph = CicUnivUtils.clean_and_fill uri obj ugraph in
372 CicEnvironment.put_inductive_definition uri (obj, ugraph);
373 MetadataDb.index_inductive_def ~dbd
374 ~owner:(Helm_registry.get "matita.owner") ~uri ~types:indTypes;
375 console#echo_message (sprintf "%s inductive type defined" suri);
378 let obj = CicElim.elim_of ~sort uri 0 in
379 let (name, body, ty, attrs) = split_obj obj in
380 let suri = qualify name ^ ".con" in
381 let uri = UriManager.uri_of_string suri in
382 (* TODO Zack: make CicElim returns a universe *)
383 let ugraph = CicUniv.empty_ugraph in
384 add_constant_to_world ~console ~dbd ~uri ?body ~ty ~attrs ~ugraph ();
387 (sprintf "%s eliminator (automatically) defined" suri)
389 with CicElim.Can_t_eliminate -> ()
391 List.iter elim [ Cic.Prop; Cic.Set; (Cic.Type (CicUniv.fresh ())) ];
394 (** Implements phrases that should be accepted only in Command state *)
396 ~(disambiguator: MatitaTypes.disambiguator)
397 ~(currentProof: MatitaTypes.currentProof)
398 ~(console: MatitaTypes.console)
404 new sharedState ~disambiguator ~currentProof ~console ?mathViewer ~dbd ()
407 inherit interpreterState ~console
409 method evalTactical = function
410 | TacticAst.LocatedTactical (_, tactical) -> self#evalTactical tactical
411 | TacticAst.Command (TacticAst.Theorem (_, Some name, ast, None)) ->
412 let (_, metasenv, expr,ugraph) =
413 disambiguator#disambiguateTermAst ast
415 let uri = UriManager.uri_of_string (qualify name ^ ".con") in
416 let proof = MatitaProof.proof ~typ:expr ~uri ~metasenv () in
417 currentProof#start proof;
420 (TacticAst.Theorem (_, Some name, type_ast, Some body_ast)) ->
421 let (_, metasenv, type_cic, ugraph) =
422 disambiguator#disambiguateTermAst type_ast
424 let (_, metasenv, body_cic, ugraph) =
425 disambiguator#disambiguateTermAst ~metasenv body_ast
427 let (body_type, ugraph) =
428 CicTypeChecker.type_of_aux' metasenv [] body_cic ugraph
430 let uri = UriManager.uri_of_string (qualify name ^ ".con") in
431 let (subst, metasenv, ugraph) =
432 CicUnification.fo_unif metasenv [] body_type type_cic ugraph
434 let body = CicMetaSubst.apply_subst subst body_cic in
435 let ty = CicMetaSubst.apply_subst subst type_cic in
436 add_constant_to_world ~console ~dbd ~uri ~body ~ty ~ugraph ();
438 | TacticAst.Command (TacticAst.Inductive (params, indTypes)) ->
440 let (uri, (indTypes, params, leftno)) =
441 inddef_of_ast params indTypes disambiguator
443 let obj = Cic.InductiveDefinition (indTypes, params, leftno, []) in
445 CicTypeChecker.typecheck_mutual_inductive_defs uri
446 (indTypes, params, leftno) CicUniv.empty_ugraph
448 add_inductive_def_to_world ~console
449 ~dbd ~uri ~indTypes ~params ~leftno ~ugraph ();
451 | TacticAst.Command TacticAst.Quit ->
452 currentProof#quit ();
453 New_state Command (* dummy answer, useless *)
454 | TacticAst.Command TacticAst.Proof ->
455 (* do nothing, just for compatibility with coq syntax *)
457 | TacticAst.Command (TacticAst.Coercion c_ast) ->
458 let env, metasenv, coercion, ugraph =
459 disambiguator#disambiguateTermAst c_ast
461 let coer_uri,coer_ty =
466 CicEnvironment.get_obj CicUniv.empty_ugraph uri
469 | Cic.Constant (_,_,ty,_,_)
470 | Cic.Variable (_,_,ty,_,_) ->
473 | Cic.MutConstruct (uri,t,c,_) ->
475 CicEnvironment.get_obj CicUniv.empty_ugraph uri
478 | Cic.InductiveDefinition (l,_,_,_) ->
479 let (_,_,_,cl) = List.nth l t in
480 let (_,cty) = List.nth cl c in
485 (* we have to get the source and the tgt type uri
486 * in Coq syntax we have already their names, but
487 * since we don't support Funclass and similar I think
488 * all the coercion should be of the form
490 * So we should be able to extract them from the coercion type
492 let extract_last_two_p ty =
493 let rec aux = function
494 | Cic.Prod( _, src, Cic.Prod (n,t1,t2)) -> aux (Cic.Prod(n,t1,t2))
495 | Cic.Prod( _, src, tgt) -> src, tgt
500 let rec uri_of_term = function
501 | Cic.Const(u,_) -> u
502 | Cic.MutInd (u, i , _) ->
503 (* we have to build by hand the #xpointer *)
504 let base = UriManager.string_of_uri u in
505 let xp = "#xpointer(1/" ^ (string_of_int (i+1)) ^ ")" in
506 UriManager.uri_of_string (base ^ xp)
507 | Cic.Appl (he::_) -> uri_of_term he
509 prerr_endline ("Fallisco a estrarre la uri di " ^
513 let ty_src,ty_tgt = extract_last_two_p coer_ty in
514 let src_uri = uri_of_term ty_src in
515 let tgt_uri = uri_of_term ty_tgt in
516 let coercions_to_add =
517 CoercGraph.close_coercion_graph src_uri tgt_uri coer_uri
519 (* FIXME: we should chek it this object can be a coercion
520 * maybe add the check to extract_last_two_p
522 console#echo_message (sprintf "Coercion %s"
523 (UriManager.string_of_uri coer_uri));
524 List.iter (fun (uri,obj,ugraph) ->
527 (sprintf "Coercion (automatic) %s"
528 (UriManager.string_of_uri uri));
530 let (name, body, ty, attrs) = split_obj obj in
531 add_constant_to_world ~console
532 ~dbd ~uri ?body ~ty ~attrs ~ugraph ();
535 | tactical -> shared#evalTactical tactical
538 (** create a ProofEngineTypes.mk_fresh_name_type function which uses given
539 * names as long as they are available, then it fallbacks to name generation
540 * using FreshNamesGenerator module *)
542 let len = List.length names in
544 fun metasenv context name ~typ ->
545 if !count < len then begin
546 let name = Cic.Name (List.nth names !count) in
550 FreshNamesGenerator.mk_fresh_name ~subst:[] metasenv context name ~typ
552 (** Implements phrases that should be accepted only in Proof state, basically
555 ~(disambiguator: MatitaTypes.disambiguator)
556 ~(currentProof: MatitaTypes.currentProof)
557 ~(console: MatitaTypes.console)
562 let disambiguate ast =
563 let (_, _, term, _) = disambiguate ~disambiguator ~currentProof ast in
566 (** tactic AST -> ProofEngineTypes.tactic *)
567 let rec lookup_tactic = function
568 | TacticAst.LocatedTactic (_, tactic) -> lookup_tactic tactic
569 | TacticAst.Intros (_, names) -> (* TODO Zack implement intros length *)
570 PrimitiveTactics.intros_tac ~mk_fresh_name_callback:(namer_of names) ()
571 | TacticAst.Reflexivity -> Tactics.reflexivity
572 | TacticAst.Assumption -> Tactics.assumption
573 | TacticAst.Contradiction -> Tactics.contradiction
574 | TacticAst.Exists -> Tactics.exists
575 | TacticAst.Fourier -> Tactics.fourier
576 | TacticAst.Left -> Tactics.left
577 | TacticAst.Right -> Tactics.right
578 | TacticAst.Ring -> Tactics.ring
579 | TacticAst.Split -> Tactics.split
580 | TacticAst.Symmetry -> Tactics.symmetry
581 | TacticAst.Transitivity term -> Tactics.transitivity (disambiguate term)
582 | TacticAst.Apply term -> Tactics.apply (disambiguate term)
583 | TacticAst.Absurd term -> Tactics.absurd (disambiguate term)
584 | TacticAst.Exact term -> Tactics.exact (disambiguate term)
585 | TacticAst.Cut term -> Tactics.cut (disambiguate term)
586 | TacticAst.Elim (term, _) -> (* TODO Zack implement "using" argument *)
587 Tactics.elim_intros_simpl (disambiguate term)
588 | TacticAst.ElimType term -> Tactics.elim_type (disambiguate term)
589 | TacticAst.Replace (what, with_what) ->
590 Tactics.replace ~what:(disambiguate what)
591 ~with_what:(disambiguate with_what)
592 | TacticAst.Auto -> Tactics.auto_new ~dbd
594 (* TODO Zack a lot more of tactics to be implemented here ... *)
595 | TacticAst.Change of 'term * 'term * 'ident option
596 | TacticAst.Change_pattern of 'term pattern * 'term * 'ident option
597 | TacticAst.Decompose of 'ident * 'ident list
598 | TacticAst.Discriminate of 'ident
599 | TacticAst.Fold of reduction_kind * 'term
600 | TacticAst.Injection of 'ident
601 | TacticAst.LetIn of 'term * 'ident
602 | TacticAst.Reduce of reduction_kind * 'term pattern * 'ident option
603 | TacticAst.Replace_pattern of 'term pattern * 'term
604 | TacticAst.Rewrite of direction * 'term * 'ident option
607 MatitaTypes.not_implemented "some tactic"
610 new sharedState ~disambiguator ~currentProof ~console ?mathViewer ~dbd ()
613 inherit interpreterState ~console
615 method evalTactical = function
616 | TacticAst.LocatedTactical (_, tactical) -> self#evalTactical tactical
617 | TacticAst.Command TacticAst.Abort ->
618 currentProof#abort ();
620 | TacticAst.Command (TacticAst.Undo steps) ->
621 currentProof#proof#undo ?steps ();
623 | TacticAst.Command (TacticAst.Redo steps) ->
624 currentProof#proof#redo ?steps ();
626 | TacticAst.Command (TacticAst.Qed None) ->
627 if not (currentProof#onGoing ()) then assert false;
628 let proof = currentProof#proof in
629 let (uri, metasenv, bo, ty) = proof#proof in
630 let uri = MatitaTypes.unopt_uri uri in
631 let suri = UriManager.string_of_uri uri in
632 (* TODO Zack this function probably should not simply fail with
633 * Failure, but rather raise some more meaningful exception *)
634 if metasenv <> [] then failwith "Proof not completed";
635 let proved_ty,ugraph =
636 CicTypeChecker.type_of_aux' [] [] bo CicUniv.empty_ugraph
639 CicReduction.are_convertible [] proved_ty ty ugraph
641 if not b then failwith "Wrong proof";
642 add_constant_to_world ~console ~dbd ~uri ~body:bo ~ty ~ugraph ();
643 currentProof#abort ();
644 (match mathViewer with None -> () | Some v -> v#unload ());
645 console#echo_message (sprintf "%s defined" suri);
647 | TacticAst.Seq tacticals ->
648 (* TODO Zack check for proof completed at each step? *)
649 List.iter (fun t -> ignore (self#evalTactical t)) tacticals;
651 | TacticAst.Tactic tactic_phrase ->
652 let tactic = lookup_tactic tactic_phrase in
653 currentProof#proof#apply_tactic tactic;
655 | tactical -> shared#evalTactical tactical
659 ~(disambiguator: MatitaTypes.disambiguator)
660 ~(currentProof: MatitaTypes.currentProof)
661 ~(console: MatitaTypes.console)
667 new commandState ~disambiguator ~currentProof ~console ?mathViewer ~dbd ()
670 new proofState ~disambiguator ~currentProof ~console ?mathViewer ~dbd ()
673 val mutable state = commandState
675 method reset = state <- commandState
677 method endOffset = state#endOffset
679 method private updateState = function
680 | New_state Command -> (state <- commandState)
681 | New_state Proof -> (state <- proofState)
684 method private eval f =
685 let ok () = (* console#clear (); *) (true, true) in
686 match console#wrap_exn f with
687 | Some (New_state Command) -> (state <- commandState); ok ()
688 | Some (New_state Proof) -> (state <- proofState); ok ()
689 | Some (Echo msg) -> console#echo_message msg; (true, false)
690 | Some Quiet -> ok ()
691 | None -> (false, false)
693 method evalPhrase s = self#eval (fun () -> state#evalPhrase s)
694 method evalAst ast = self#eval (fun () -> state#evalAst ast)