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 class virtual interpreterState =
64 (* static values, shared by all states inheriting this class *)
66 let history = ref [] in
67 fun ~(console: MatitaTypes.console) ->
70 (** eval a toplevel phrase in the current state and return the new state
72 method parsePhrase s =
73 match CicTextualParser2.parse_tactical s with
74 | (TacticAst.LocatedTactical (loc', tac)) as tactical ->
76 (match tac with (* update interpreter history *)
77 | TacticAst.Command (TacticAst.Qed None) ->
78 history := `Qed :: !history
79 | TacticAst.Command (TacticAst.Theorem (_, Some name, _, None)) ->
80 history := `Theorem name :: !history
81 | TacticAst.Command (TacticAst.Qed _)
82 | TacticAst.Command (TacticAst.Theorem _) -> assert false
83 | _ -> history := `Tactic :: !history);
87 method virtual evalTactical:
88 (CicAst.term, string) TacticAst.tactical -> outcome
91 debug_print (sprintf "evaluating '%s'" s);
92 self#evalTactical (self#parsePhrase (Stream.of_string s))
94 method evalAst ast = self#evalTactical ast
98 | Some (start_pos, end_pos) -> end_pos.Lexing.pos_cnum
99 | None -> failwith "MatitaInterpreter: no offset recorded"
103 (** Implements phrases that should be accepted in all states *)
105 ~(disambiguator: MatitaTypes.disambiguator)
106 ~(currentProof: MatitaTypes.currentProof)
107 ~(console: MatitaTypes.console)
108 ?(mathViewer: MatitaTypes.mathViewer option)
113 inherit interpreterState ~console
114 method evalTactical = function
115 | TacticAst.Command TacticAst.Quit ->
116 currentProof#quit ();
117 assert false (* dummy answer, useless *)
118 | TacticAst.Command TacticAst.Proof ->
119 (* do nothing, just for compatibility with coq syntax *)
121 | TacticAst.Command (TacticAst.Baseuri (Some uri)) ->
122 Lazy.force baseuri := uri;
123 console#echo_message (sprintf "base uri set to \"%s\"" uri);
125 | TacticAst.Command (TacticAst.Baseuri None) ->
126 console#echo_message (sprintf "base uri is \"%s\""
127 !(Lazy.force baseuri));
129 | TacticAst.Command (TacticAst.Basedir (Some path)) ->
131 console#echo_message (sprintf "base dir set to \"%s\"" path);
133 | TacticAst.Command (TacticAst.Basedir None) ->
134 console#echo_message (sprintf "base dir is \"%s\"" !basedir);
136 | TacticAst.Command (TacticAst.Check term) ->
137 let (_, _, term,ugraph) =
138 MatitaCicMisc.disambiguate ~disambiguator ~currentProof term
140 let (context, metasenv) =
141 MatitaCicMisc.get_context_and_metasenv currentProof
143 (* this is the Eval Compute
144 let term = CicReduction.whd context term in
146 let dummyno = CicMkImplicit.new_meta metasenv [] in
148 CicTypeChecker.type_of_aux' metasenv context term ugraph
150 (* TASSI: here ugraph1 is unused.... FIXME *)
151 let expr = Cic.Cast (term, ty) in
152 (match mathViewer with
153 | Some v -> v#checkTerm (`Cic expr)
156 | TacticAst.Command (TacticAst.Search_pat (search_kind, pat)) ->
158 match search_kind with
159 | `Locate -> MetadataQuery.locate ~dbd pat
160 | `Elim -> MetadataQuery.elim ~dbd pat
163 (* TODO ZACK: show URIs to the user *)
165 | TacticAst.Command (TacticAst.Print `Env) ->
166 let uris = CicEnvironment.list_uri () in
167 console#echo_message "Environment:";
169 console#echo_message (" " ^ (UriManager.string_of_uri u))
172 | TacticAst.Command (TacticAst.Print `Coer) ->
173 let uris = CoercGraph.get_coercions_list () in
174 console#echo_message "Coercions:";
175 List.iter (fun (s,t,u) ->
176 console#echo_message (" " ^ (UriManager.string_of_uri u))
180 raise (Command_error (TacticAstPp.pp_tactical tactical))
185 let pp_indtypes indTypes =
187 (fun (name, _, typ, constructors) ->
188 printf "%s: %s\n" name (CicPp.ppterm typ);
190 (fun (name, term) -> printf "\t%s: %s\n" name (CicPp.ppterm term))
195 let inddef_of_ast params indTypes (disambiguator:MatitaTypes.disambiguator) =
196 let add_pi binders t =
198 (fun (name, ast) acc ->
199 CicAst.Binder (`Forall, (Cic.Name name, Some ast), acc))
203 List.map (fun (name, _, typ, _) -> (name, add_pi params typ)) indTypes
205 let binders = ind_binders @ params in
207 let add_ast ast = asts := ast :: !asts in
208 let paramsno = List.length params in
209 let indbindersno = List.length ind_binders in
211 (fun (name, _, typ, constructors) ->
212 add_ast (add_pi params typ);
213 List.iter (fun (_, ast) -> add_ast (add_pi binders ast)) constructors)
215 let (_, metasenv, terms, ugraph) =
216 disambiguator#disambiguateTermAsts ~metasenv:[] !asts
218 let terms = ref (List.rev terms) in
220 match !terms with [] -> assert false | hd :: tl -> terms := tl; hd
224 | (name, _, _, _) :: _ -> qualify name ^ ".ind"
228 let counter = ref 0 in
232 CicUtil.term_of_uri (sprintf "%s#xpointer(1/%d)" uri !counter))
235 let subst_mutinds = List.fold_right CicSubstitution.subst mutinds in
238 (fun acc (name, inductive, typ, constructors) ->
239 let cicTyp = get_term () in
240 let cicConstructors =
242 (fun acc (name, _) ->
244 subst_mutinds (CicUtil.strip_prods indbindersno (get_term ()))
249 (name, inductive, cicTyp, List.rev cicConstructors) :: acc)
252 let cicIndTypes = List.rev cicIndTypes in
253 (UriManager.uri_of_string uri, (cicIndTypes, [], paramsno))
256 save_object_to_disk uri obj
258 (* generate annobj, ids_to_inner_sorts and ids_to_inner_types *)
259 let annobj,_,_,ids_to_inner_sorts,ids_to_inner_types,_,_ =
260 Cic2acic.acic_object_of_cic_object ~eta_fix:false obj
265 Cic2Xml.print_object uri ~ids_to_inner_sorts ~ask_dtd_to_the_getter:false
269 Cic2Xml.print_inner_types uri ~ids_to_inner_sorts ~ids_to_inner_types
270 ~ask_dtd_to_the_getter:false
273 (* prepare URIs and paths *)
274 let innertypesuri = UriManager.innertypesuri_of_uri uri in
275 let bodyuri = UriManager.bodyuri_of_uri uri in
276 let innertypesfilename = Str.replace_first (Str.regexp "^cic:") ""
277 (UriManager.string_of_uri innertypesuri) ^ ".xml" in
278 let innertypespath = !basedir ^ "/" ^ innertypesfilename in
279 let xmlfilename = Str.replace_first (Str.regexp "^cic:") ""
280 (UriManager.string_of_uri uri) ^ ".xml" in
281 let xmlpath = !basedir ^ "/" ^ xmlfilename in
282 let xmlbodyfilename = Str.replace_first (Str.regexp "^cic:") ""
283 (UriManager.string_of_uri uri) ^ ".body.xml" in
284 let xmlbodypath = !basedir ^ "/" ^ xmlbodyfilename in
285 let path_scheme_of path = "file:/" ^ path in
287 (* now write to disk *)
288 Xml.pp ~quiet:true xmlinnertypes (Some innertypespath) ;
289 Xml.pp ~quiet:true xml (Some xmlpath) ;
291 (* now register to the getter *)
292 Http_getter.register' innertypesuri (path_scheme_of innertypespath);
293 Http_getter.register' uri (path_scheme_of xmlpath);
295 (* now the optional body, both write and register *)
296 (match bodyxml,bodyuri with
298 | Some bodyxml,Some bodyuri->
299 Xml.pp ~quiet:true bodyxml (Some xmlbodypath) ;
300 Http_getter.register' bodyuri (path_scheme_of xmlbodypath)
306 (* TODO Zack a lot more to be done here:
307 * - save object to disk in xml format
308 * - register uri to the getter
309 * - save universe file *)
310 let add_constant_to_world ~(console:MatitaTypes.console)
311 ~dbd ~uri ?body ~ty ?(params = []) ?(attrs = []) ~ugraph ()
313 let suri = UriManager.string_of_uri uri in
314 if CicEnvironment.in_library uri then
315 error (sprintf "%s constant already defined" suri)
317 let name = UriManager.name_of_uri uri in
318 let obj = Cic.Constant (name, body, ty, params, attrs) in
319 let ugraph = CicUnivUtils.clean_and_fill uri obj ugraph in
320 CicEnvironment.add_type_checked_term uri (obj, ugraph);
321 MetadataDb.index_constant ~dbd
322 ~owner:(Helm_registry.get "matita.owner") ~uri ~body ~ty;
323 save_object_to_disk uri obj;
324 console#echo_message (sprintf "%s constant defined" suri)
327 let add_inductive_def_to_world ~(console:MatitaTypes.console)
328 ~dbd ~uri ~indTypes ?(params = []) ?(leftno = 0) ?(attrs = []) ~ugraph ()
330 let suri = UriManager.string_of_uri uri in
331 if CicEnvironment.in_library uri then
332 error (sprintf "%s inductive type already defined" suri)
334 let name = UriManager.name_of_uri uri in
335 let obj = Cic.InductiveDefinition (indTypes, params, leftno, attrs) in
336 let ugraph = CicUnivUtils.clean_and_fill uri obj ugraph in
337 CicEnvironment.put_inductive_definition uri (obj, ugraph);
338 MetadataDb.index_inductive_def ~dbd
339 ~owner:(Helm_registry.get "matita.owner") ~uri ~types:indTypes;
340 save_object_to_disk uri obj;
341 console#echo_message (sprintf "%s inductive type defined" suri);
344 let obj = CicElim.elim_of ~sort uri 0 in
345 let (name, body, ty, attrs) = split_obj obj in
346 let suri = qualify name ^ ".con" in
347 let uri = UriManager.uri_of_string suri in
348 (* TODO Zack: make CicElim returns a universe *)
349 let ugraph = CicUniv.empty_ugraph in
350 add_constant_to_world ~console ~dbd ~uri ?body ~ty ~attrs ~ugraph ();
353 (sprintf "%s eliminator (automatically) defined" suri)
355 with CicElim.Can_t_eliminate -> ()
357 List.iter elim [ Cic.Prop; Cic.Set; (Cic.Type (CicUniv.fresh ())) ];
360 (** Implements phrases that should be accepted only in Command state *)
362 ~(disambiguator: MatitaTypes.disambiguator)
363 ~(currentProof: MatitaTypes.currentProof)
364 ~(console: MatitaTypes.console)
370 new sharedState ~disambiguator ~currentProof ~console ?mathViewer ~dbd ()
373 inherit interpreterState ~console
375 method evalTactical = function
376 | TacticAst.LocatedTactical (_, tactical) -> self#evalTactical tactical
377 | TacticAst.Command (TacticAst.Theorem (_, Some name, ast, None)) ->
378 let (_, metasenv, expr,ugraph) =
379 disambiguator#disambiguateTermAst ast
381 let uri = UriManager.uri_of_string (qualify name ^ ".con") in
382 let proof = MatitaProof.proof ~typ:expr ~uri ~metasenv () in
383 currentProof#start proof;
386 (TacticAst.Theorem (_, Some name, type_ast, Some body_ast)) ->
387 let (_, metasenv, type_cic, ugraph) =
388 disambiguator#disambiguateTermAst type_ast
390 let (_, metasenv, body_cic, ugraph) =
391 disambiguator#disambiguateTermAst ~metasenv body_ast
393 let (body_type, ugraph) =
394 CicTypeChecker.type_of_aux' metasenv [] body_cic ugraph
396 let uri = UriManager.uri_of_string (qualify name ^ ".con") in
397 let (subst, metasenv, ugraph) =
398 CicUnification.fo_unif metasenv [] body_type type_cic ugraph
400 let body = CicMetaSubst.apply_subst subst body_cic in
401 let ty = CicMetaSubst.apply_subst subst type_cic in
402 add_constant_to_world ~console ~dbd ~uri ~body ~ty ~ugraph ();
404 | TacticAst.Command (TacticAst.Inductive (params, indTypes)) ->
406 let (uri, (indTypes, params, leftno)) =
407 inddef_of_ast params indTypes disambiguator
409 let obj = Cic.InductiveDefinition (indTypes, params, leftno, []) in
411 CicTypeChecker.typecheck_mutual_inductive_defs uri
412 (indTypes, params, leftno) CicUniv.empty_ugraph
414 add_inductive_def_to_world ~console
415 ~dbd ~uri ~indTypes ~params ~leftno ~ugraph ();
417 | TacticAst.Command TacticAst.Quit ->
418 currentProof#quit ();
419 New_state Command (* dummy answer, useless *)
420 | TacticAst.Command TacticAst.Proof ->
421 (* do nothing, just for compatibility with coq syntax *)
423 | TacticAst.Command (TacticAst.Coercion c_ast) ->
424 let env, metasenv, coercion, ugraph =
425 disambiguator#disambiguateTermAst c_ast
427 let coer_uri,coer_ty =
432 CicEnvironment.get_obj CicUniv.empty_ugraph uri
435 | Cic.Constant (_,_,ty,_,_)
436 | Cic.Variable (_,_,ty,_,_) ->
439 | Cic.MutConstruct (uri,t,c,_) ->
441 CicEnvironment.get_obj CicUniv.empty_ugraph uri
444 | Cic.InductiveDefinition (l,_,_,_) ->
445 let (_,_,_,cl) = List.nth l t in
446 let (_,cty) = List.nth cl c in
451 (* we have to get the source and the tgt type uri
452 * in Coq syntax we have already their names, but
453 * since we don't support Funclass and similar I think
454 * all the coercion should be of the form
456 * So we should be able to extract them from the coercion type
458 let extract_last_two_p ty =
459 let rec aux = function
460 | Cic.Prod( _, src, Cic.Prod (n,t1,t2)) -> aux (Cic.Prod(n,t1,t2))
461 | Cic.Prod( _, src, tgt) -> src, tgt
466 let rec uri_of_term = function
467 | Cic.Const(u,_) -> u
468 | Cic.MutInd (u, i , _) ->
469 (* we have to build by hand the #xpointer *)
470 let base = UriManager.string_of_uri u in
471 let xp = "#xpointer(1/" ^ (string_of_int (i+1)) ^ ")" in
472 UriManager.uri_of_string (base ^ xp)
473 | Cic.Appl (he::_) -> uri_of_term he
475 prerr_endline ("Fallisco a estrarre la uri di " ^
479 let ty_src,ty_tgt = extract_last_two_p coer_ty in
480 let src_uri = uri_of_term ty_src in
481 let tgt_uri = uri_of_term ty_tgt in
482 let coercions_to_add =
483 CoercGraph.close_coercion_graph src_uri tgt_uri coer_uri
485 (* FIXME: we should chek it this object can be a coercion
486 * maybe add the check to extract_last_two_p
488 console#echo_message (sprintf "Coercion %s"
489 (UriManager.string_of_uri coer_uri));
490 List.iter (fun (uri,obj,ugraph) ->
493 (sprintf "Coercion (automatic) %s"
494 (UriManager.string_of_uri uri));
496 let (name, body, ty, attrs) = split_obj obj in
497 add_constant_to_world ~console
498 ~dbd ~uri ?body ~ty ~attrs ~ugraph ();
501 | tactical -> shared#evalTactical tactical
504 (** create a ProofEngineTypes.mk_fresh_name_type function which uses given
505 * names as long as they are available, then it fallbacks to name generation
506 * using FreshNamesGenerator module *)
508 let len = List.length names in
510 fun metasenv context name ~typ ->
511 if !count < len then begin
512 let name = Cic.Name (List.nth names !count) in
516 FreshNamesGenerator.mk_fresh_name ~subst:[] metasenv context name ~typ
518 (** Implements phrases that should be accepted only in Proof state, basically
521 ~(disambiguator: MatitaTypes.disambiguator)
522 ~(currentProof: MatitaTypes.currentProof)
523 ~(console: MatitaTypes.console)
528 let disambiguate ast =
529 let (_, _, term, _) =
530 MatitaCicMisc.disambiguate ~disambiguator ~currentProof ast
534 (** tactic AST -> ProofEngineTypes.tactic *)
535 let rec lookup_tactic = function
536 | TacticAst.LocatedTactic (_, tactic) -> lookup_tactic tactic
537 | TacticAst.Intros (_, names) -> (* TODO Zack implement intros length *)
538 PrimitiveTactics.intros_tac ~mk_fresh_name_callback:(namer_of names) ()
539 | TacticAst.Reflexivity -> Tactics.reflexivity
540 | TacticAst.Assumption -> Tactics.assumption
541 | TacticAst.Contradiction -> Tactics.contradiction
542 | TacticAst.Exists -> Tactics.exists
543 | TacticAst.Fourier -> Tactics.fourier
544 | TacticAst.Left -> Tactics.left
545 | TacticAst.Right -> Tactics.right
546 | TacticAst.Ring -> Tactics.ring
547 | TacticAst.Split -> Tactics.split
548 | TacticAst.Symmetry -> Tactics.symmetry
549 | TacticAst.Transitivity term -> Tactics.transitivity (disambiguate term)
550 | TacticAst.Apply term -> Tactics.apply (disambiguate term)
551 | TacticAst.Absurd term -> Tactics.absurd (disambiguate term)
552 | TacticAst.Exact term -> Tactics.exact (disambiguate term)
553 | TacticAst.Cut term -> Tactics.cut (disambiguate term)
554 | TacticAst.Elim (term, _) -> (* TODO Zack implement "using" argument *)
555 Tactics.elim_intros_simpl (disambiguate term)
556 | TacticAst.ElimType term -> Tactics.elim_type (disambiguate term)
557 | TacticAst.Replace (what, with_what) ->
558 Tactics.replace ~what:(disambiguate what)
559 ~with_what:(disambiguate with_what)
560 | TacticAst.Auto -> Tactics.auto_new ~dbd
562 (* TODO Zack a lot more of tactics to be implemented here ... *)
563 | TacticAst.Change of 'term * 'term * 'ident option
564 | TacticAst.Change_pattern of 'term pattern * 'term * 'ident option
565 | TacticAst.Decompose of 'ident * 'ident list
566 | TacticAst.Discriminate of 'ident
567 | TacticAst.Fold of reduction_kind * 'term
568 | TacticAst.Injection of 'ident
569 | TacticAst.LetIn of 'term * 'ident
570 | TacticAst.Reduce of reduction_kind * 'term pattern * 'ident option
571 | TacticAst.Replace_pattern of 'term pattern * 'term
572 | TacticAst.Rewrite of direction * 'term * 'ident option
575 MatitaTypes.not_implemented "some tactic"
578 new sharedState ~disambiguator ~currentProof ~console ?mathViewer ~dbd ()
581 inherit interpreterState ~console
583 method evalTactical = function
584 | TacticAst.LocatedTactical (_, tactical) -> self#evalTactical tactical
585 | TacticAst.Command TacticAst.Abort ->
586 currentProof#abort ();
588 | TacticAst.Command (TacticAst.Undo steps) ->
589 currentProof#proof#undo ?steps ();
591 | TacticAst.Command (TacticAst.Redo steps) ->
592 currentProof#proof#redo ?steps ();
594 | TacticAst.Command (TacticAst.Qed None) ->
595 if not (currentProof#onGoing ()) then assert false;
596 let proof = currentProof#proof in
597 let (uri, metasenv, bo, ty) = proof#proof in
598 let uri = MatitaTypes.unopt_uri uri in
599 let suri = UriManager.string_of_uri uri in
600 (* TODO Zack this function probably should not simply fail with
601 * Failure, but rather raise some more meaningful exception *)
602 if metasenv <> [] then failwith "Proof not completed";
603 let proved_ty,ugraph =
604 CicTypeChecker.type_of_aux' [] [] bo CicUniv.empty_ugraph
607 CicReduction.are_convertible [] proved_ty ty ugraph
609 if not b then failwith "Wrong proof";
610 add_constant_to_world ~console ~dbd ~uri ~body:bo ~ty ~ugraph ();
611 currentProof#abort ();
612 console#echo_message (sprintf "%s defined" suri);
614 | TacticAst.Seq tacticals ->
615 (* TODO Zack check for proof completed at each step? *)
616 List.iter (fun t -> ignore (self#evalTactical t)) tacticals;
618 | TacticAst.Tactic tactic_phrase ->
619 let tactic = lookup_tactic tactic_phrase in
620 currentProof#proof#apply_tactic tactic;
622 | tactical -> shared#evalTactical tactical
626 ~(disambiguator: MatitaTypes.disambiguator)
627 ~(currentProof: MatitaTypes.currentProof)
628 ~(console: MatitaTypes.console)
634 new commandState ~disambiguator ~currentProof ~console ?mathViewer ~dbd ()
637 new proofState ~disambiguator ~currentProof ~console ?mathViewer ~dbd ()
640 val mutable state = commandState
642 method reset = state <- commandState
644 method endOffset = state#endOffset
646 method private updateState = function
647 | New_state Command -> (state <- commandState)
648 | New_state Proof -> (state <- proofState)
651 method private eval f =
652 let ok () = (* console#clear (); *) (true, true) in
653 match console#wrap_exn f with
654 | Some (New_state Command) -> (state <- commandState); ok ()
655 | Some (New_state Proof) -> (state <- proofState); ok ()
656 | Some (Echo msg) -> console#echo_message msg; (true, false)
657 | Some Quiet -> ok ()
658 | None -> (false, false)
660 method evalPhrase s = self#eval (fun () -> state#evalPhrase s)
661 method evalAst ast = self#eval (fun () -> state#evalAst ast)