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 val dbd = MatitaMisc.dbd_instance ()
71 val currentProof = MatitaProof.instance ()
73 (** eval a toplevel phrase in the current state and return the new state
75 method parsePhrase s =
76 match CicTextualParser2.parse_tactical s with
77 | (TacticAst.LocatedTactical (loc', tac)) as tactical ->
79 (match tac with (* update interpreter history *)
80 | TacticAst.Command (TacticAst.Qed None) ->
81 history := `Qed :: !history
82 | TacticAst.Command (TacticAst.Theorem (_, Some name, _, None)) ->
83 history := `Theorem name :: !history
84 | TacticAst.Command (TacticAst.Qed _)
85 | TacticAst.Command (TacticAst.Theorem _) -> assert false
86 | _ -> history := `Tactic :: !history);
90 method virtual evalTactical:
91 (CicAst.term, string) TacticAst.tactical -> outcome
94 debug_print (sprintf "evaluating '%s'" s);
95 self#evalTactical (self#parsePhrase (Stream.of_string s))
97 method evalAst ast = self#evalTactical ast
101 | Some (start_pos, end_pos) -> end_pos.Lexing.pos_cnum
102 | None -> failwith "MatitaInterpreter: no offset recorded"
106 (** Implements phrases that should be accepted in all states *)
108 ~(disambiguator: MatitaTypes.disambiguator)
109 ~(console: #MatitaTypes.console)
110 ?(mathViewer: MatitaTypes.mathViewer option)
114 inherit interpreterState ~console
115 method evalTactical = function
116 | TacticAst.Command TacticAst.Quit ->
117 currentProof#quit ();
118 assert false (* dummy answer, useless *)
119 | TacticAst.Command TacticAst.Proof ->
120 (* do nothing, just for compatibility with coq syntax *)
122 | TacticAst.Command (TacticAst.Baseuri (Some uri)) ->
123 Lazy.force baseuri := uri;
124 console#echo_message (sprintf "base uri set to \"%s\"" uri);
126 | TacticAst.Command (TacticAst.Baseuri None) ->
127 console#echo_message (sprintf "base uri is \"%s\""
128 !(Lazy.force baseuri));
130 | TacticAst.Command (TacticAst.Basedir (Some path)) ->
132 console#echo_message (sprintf "base dir set to \"%s\"" path);
134 | TacticAst.Command (TacticAst.Basedir None) ->
135 console#echo_message (sprintf "base dir is \"%s\"" !basedir);
137 | TacticAst.Command (TacticAst.Check term) ->
138 let (_, _, term,ugraph) =
139 MatitaCicMisc.disambiguate ~disambiguator ~currentProof term
141 let (context, metasenv) =
142 MatitaCicMisc.get_context_and_metasenv currentProof
144 (* this is the Eval Compute
145 let term = CicReduction.whd context term in
147 let dummyno = CicMkImplicit.new_meta metasenv [] in
149 CicTypeChecker.type_of_aux' metasenv context term ugraph
151 (* TASSI: here ugraph1 is unused.... FIXME *)
152 let expr = Cic.Cast (term, ty) in
153 (match mathViewer with
154 | Some v -> v#checkTerm (`Cic expr)
157 | TacticAst.Command (TacticAst.Search_pat (search_kind, pat)) ->
159 match search_kind with
160 | `Locate -> MetadataQuery.locate ~dbd pat
161 | `Elim -> MetadataQuery.elim ~dbd pat
164 (* TODO ZACK: show URIs to the user *)
166 | TacticAst.Command (TacticAst.Print `Env) ->
167 let uris = CicEnvironment.list_uri () in
168 console#echo_message "Environment:";
170 console#echo_message (" " ^ (UriManager.string_of_uri u))
173 | TacticAst.Command (TacticAst.Print `Coer) ->
174 let uris = CoercGraph.get_coercions_list () in
175 console#echo_message "Coercions:";
176 List.iter (fun (s,t,u) ->
177 console#echo_message (" " ^ (UriManager.string_of_uri u))
181 raise (Command_error (TacticAstPp.pp_tactical tactical))
186 let pp_indtypes indTypes =
188 (fun (name, _, typ, constructors) ->
189 printf "%s: %s\n" name (CicPp.ppterm typ);
191 (fun (name, term) -> printf "\t%s: %s\n" name (CicPp.ppterm term))
196 let inddef_of_ast params indTypes (disambiguator:MatitaTypes.disambiguator) =
197 let add_pi binders t =
199 (fun (name, ast) acc ->
200 CicAst.Binder (`Forall, (Cic.Name name, Some ast), acc))
204 List.map (fun (name, _, typ, _) -> (name, add_pi params typ)) indTypes
206 let binders = ind_binders @ params in
208 let add_ast ast = asts := ast :: !asts in
209 let paramsno = List.length params in
210 let indbindersno = List.length ind_binders in
212 (fun (name, _, typ, constructors) ->
213 add_ast (add_pi params typ);
214 List.iter (fun (_, ast) -> add_ast (add_pi binders ast)) constructors)
216 let (_, metasenv, terms, ugraph) =
217 disambiguator#disambiguateTermAsts ~metasenv:[] !asts
219 let terms = ref (List.rev terms) in
221 match !terms with [] -> assert false | hd :: tl -> terms := tl; hd
225 | (name, _, _, _) :: _ -> qualify name ^ ".ind"
229 let counter = ref 0 in
233 CicUtil.term_of_uri (sprintf "%s#xpointer(1/%d)" uri !counter))
236 let subst_mutinds = List.fold_right CicSubstitution.subst mutinds in
239 (fun acc (name, inductive, typ, constructors) ->
240 let cicTyp = get_term () in
241 let cicConstructors =
243 (fun acc (name, _) ->
245 subst_mutinds (CicUtil.strip_prods indbindersno (get_term ()))
250 (name, inductive, cicTyp, List.rev cicConstructors) :: acc)
253 let cicIndTypes = List.rev cicIndTypes in
254 (UriManager.uri_of_string uri, (cicIndTypes, [], paramsno))
257 save_object_to_disk uri obj
259 (* generate annobj, ids_to_inner_sorts and ids_to_inner_types *)
260 let annobj,_,_,ids_to_inner_sorts,ids_to_inner_types,_,_ =
261 Cic2acic.acic_object_of_cic_object ~eta_fix:false obj
266 Cic2Xml.print_object uri ~ids_to_inner_sorts ~ask_dtd_to_the_getter:false
270 Cic2Xml.print_inner_types uri ~ids_to_inner_sorts ~ids_to_inner_types
271 ~ask_dtd_to_the_getter:false
274 (* prepare URIs and paths *)
275 let innertypesuri = UriManager.innertypesuri_of_uri uri in
276 let bodyuri = UriManager.bodyuri_of_uri uri in
277 let innertypesfilename = Str.replace_first (Str.regexp "^cic:") ""
278 (UriManager.string_of_uri innertypesuri) ^ ".xml" in
279 let innertypespath = !basedir ^ "/" ^ innertypesfilename in
280 let xmlfilename = Str.replace_first (Str.regexp "^cic:") ""
281 (UriManager.string_of_uri uri) ^ ".xml" in
282 let xmlpath = !basedir ^ "/" ^ xmlfilename in
283 let xmlbodyfilename = Str.replace_first (Str.regexp "^cic:") ""
284 (UriManager.string_of_uri uri) ^ ".body.xml" in
285 let xmlbodypath = !basedir ^ "/" ^ xmlbodyfilename in
286 let path_scheme_of path = "file:/" ^ path in
288 (* now write to disk *)
289 Xml.pp ~quiet:true xmlinnertypes (Some innertypespath) ;
290 Xml.pp ~quiet:true xml (Some xmlpath) ;
292 (* now register to the getter *)
293 Http_getter.register' innertypesuri (path_scheme_of innertypespath);
294 Http_getter.register' uri (path_scheme_of xmlpath);
296 (* now the optional body, both write and register *)
297 (match bodyxml,bodyuri with
299 | Some bodyxml,Some bodyuri->
300 Xml.pp ~quiet:true bodyxml (Some xmlbodypath) ;
301 Http_getter.register' bodyuri (path_scheme_of xmlbodypath)
307 (* TODO Zack a lot more to be done here:
308 * - save object to disk in xml format
309 * - register uri to the getter
310 * - save universe file *)
311 let add_constant_to_world ~(console: #MatitaTypes.console)
312 ~dbd ~uri ?body ~ty ?(params = []) ?(attrs = []) ~ugraph ()
314 let suri = UriManager.string_of_uri uri in
315 if CicEnvironment.in_library uri then
316 error (sprintf "%s constant already defined" suri)
318 let name = UriManager.name_of_uri uri in
319 let obj = Cic.Constant (name, body, ty, params, attrs) in
320 let ugraph = CicUnivUtils.clean_and_fill uri obj ugraph in
321 CicEnvironment.add_type_checked_term uri (obj, ugraph);
322 MetadataDb.index_constant ~dbd
323 ~owner:(Helm_registry.get "matita.owner") ~uri ~body ~ty;
324 save_object_to_disk uri obj;
325 console#echo_message (sprintf "%s constant defined" suri)
328 let add_inductive_def_to_world ~(console: #MatitaTypes.console)
329 ~dbd ~uri ~indTypes ?(params = []) ?(leftno = 0) ?(attrs = []) ~ugraph ()
331 let suri = UriManager.string_of_uri uri in
332 if CicEnvironment.in_library uri then
333 error (sprintf "%s inductive type already defined" suri)
335 let name = UriManager.name_of_uri uri in
336 let obj = Cic.InductiveDefinition (indTypes, params, leftno, attrs) in
337 let ugraph = CicUnivUtils.clean_and_fill uri obj ugraph in
338 CicEnvironment.put_inductive_definition uri (obj, ugraph);
339 MetadataDb.index_inductive_def ~dbd
340 ~owner:(Helm_registry.get "matita.owner") ~uri ~types:indTypes;
341 save_object_to_disk uri obj;
342 console#echo_message (sprintf "%s inductive type defined" suri);
345 let obj = CicElim.elim_of ~sort uri 0 in
346 let (name, body, ty, attrs) = split_obj obj in
347 let suri = qualify name ^ ".con" in
348 let uri = UriManager.uri_of_string suri in
349 (* TODO Zack: make CicElim returns a universe *)
350 let ugraph = CicUniv.empty_ugraph in
351 add_constant_to_world ~console ~dbd ~uri ?body ~ty ~attrs ~ugraph ();
354 (sprintf "%s eliminator (automatically) defined" suri)
356 with CicElim.Can_t_eliminate -> ()
358 List.iter elim [ Cic.Prop; Cic.Set; (Cic.Type (CicUniv.fresh ())) ];
361 (** Implements phrases that should be accepted only in Command state *)
363 ~(disambiguator: MatitaTypes.disambiguator)
364 ~(console: #MatitaTypes.console)
368 let shared = new sharedState ~disambiguator ~console ?mathViewer () in
370 inherit interpreterState ~console
372 method evalTactical = function
373 | TacticAst.LocatedTactical (_, tactical) -> self#evalTactical tactical
374 | TacticAst.Command (TacticAst.Theorem (_, Some name, ast, None)) ->
375 let (_, metasenv, expr,ugraph) =
376 disambiguator#disambiguateTermAst ast
378 let uri = UriManager.uri_of_string (qualify name ^ ".con") in
379 let proof = MatitaProof.proof ~typ:expr ~uri ~metasenv () in
380 currentProof#start proof;
383 (TacticAst.Theorem (_, Some name, type_ast, Some body_ast)) ->
384 let (_, metasenv, type_cic, ugraph) =
385 disambiguator#disambiguateTermAst type_ast
387 let (_, metasenv, body_cic, ugraph) =
388 disambiguator#disambiguateTermAst ~metasenv body_ast
390 let (body_type, ugraph) =
391 CicTypeChecker.type_of_aux' metasenv [] body_cic ugraph
393 let uri = UriManager.uri_of_string (qualify name ^ ".con") in
394 let (subst, metasenv, ugraph) =
395 CicUnification.fo_unif metasenv [] body_type type_cic ugraph
397 let body = CicMetaSubst.apply_subst subst body_cic in
398 let ty = CicMetaSubst.apply_subst subst type_cic in
399 add_constant_to_world ~console ~dbd ~uri ~body ~ty ~ugraph ();
401 | TacticAst.Command (TacticAst.Inductive (params, indTypes)) ->
403 let (uri, (indTypes, params, leftno)) =
404 inddef_of_ast params indTypes disambiguator
406 let obj = Cic.InductiveDefinition (indTypes, params, leftno, []) in
408 CicTypeChecker.typecheck_mutual_inductive_defs uri
409 (indTypes, params, leftno) CicUniv.empty_ugraph
411 add_inductive_def_to_world ~console
412 ~dbd ~uri ~indTypes ~params ~leftno ~ugraph ();
414 | TacticAst.Command TacticAst.Quit ->
415 currentProof#quit ();
416 New_state Command (* dummy answer, useless *)
417 | TacticAst.Command TacticAst.Proof ->
418 (* do nothing, just for compatibility with coq syntax *)
420 | TacticAst.Command (TacticAst.Coercion c_ast) ->
421 let env, metasenv, coercion, ugraph =
422 disambiguator#disambiguateTermAst c_ast
424 let coer_uri,coer_ty =
429 CicEnvironment.get_obj CicUniv.empty_ugraph uri
432 | Cic.Constant (_,_,ty,_,_)
433 | Cic.Variable (_,_,ty,_,_) ->
436 | Cic.MutConstruct (uri,t,c,_) ->
438 CicEnvironment.get_obj CicUniv.empty_ugraph uri
441 | Cic.InductiveDefinition (l,_,_,_) ->
442 let (_,_,_,cl) = List.nth l t in
443 let (_,cty) = List.nth cl c in
448 (* we have to get the source and the tgt type uri
449 * in Coq syntax we have already their names, but
450 * since we don't support Funclass and similar I think
451 * all the coercion should be of the form
453 * So we should be able to extract them from the coercion type
455 let extract_last_two_p ty =
456 let rec aux = function
457 | Cic.Prod( _, src, Cic.Prod (n,t1,t2)) -> aux (Cic.Prod(n,t1,t2))
458 | Cic.Prod( _, src, tgt) -> src, tgt
463 let rec uri_of_term = function
464 | Cic.Const(u,_) -> u
465 | Cic.MutInd (u, i , _) ->
466 (* we have to build by hand the #xpointer *)
467 let base = UriManager.string_of_uri u in
468 let xp = "#xpointer(1/" ^ (string_of_int (i+1)) ^ ")" in
469 UriManager.uri_of_string (base ^ xp)
470 | Cic.Appl (he::_) -> uri_of_term he
472 prerr_endline ("Fallisco a estrarre la uri di " ^
476 let ty_src,ty_tgt = extract_last_two_p coer_ty in
477 let src_uri = uri_of_term ty_src in
478 let tgt_uri = uri_of_term ty_tgt in
479 let coercions_to_add =
480 CoercGraph.close_coercion_graph src_uri tgt_uri coer_uri
482 (* FIXME: we should chek it this object can be a coercion
483 * maybe add the check to extract_last_two_p
485 console#echo_message (sprintf "Coercion %s"
486 (UriManager.string_of_uri coer_uri));
487 List.iter (fun (uri,obj,ugraph) ->
490 (sprintf "Coercion (automatic) %s"
491 (UriManager.string_of_uri uri));
493 let (name, body, ty, attrs) = split_obj obj in
494 add_constant_to_world ~console
495 ~dbd ~uri ?body ~ty ~attrs ~ugraph ();
498 | tactical -> shared#evalTactical tactical
501 (** create a ProofEngineTypes.mk_fresh_name_type function which uses given
502 * names as long as they are available, then it fallbacks to name generation
503 * using FreshNamesGenerator module *)
505 let len = List.length names in
507 fun metasenv context name ~typ ->
508 if !count < len then begin
509 let name = Cic.Name (List.nth names !count) in
513 FreshNamesGenerator.mk_fresh_name ~subst:[] metasenv context name ~typ
515 (** Implements phrases that should be accepted only in Proof state, basically
518 ~(disambiguator: MatitaTypes.disambiguator)
519 ~(console: #MatitaTypes.console)
523 let shared = new sharedState ~disambiguator ~console ?mathViewer () in
525 inherit interpreterState ~console
527 method private disambiguate ast =
528 let (_, _, term, _) =
529 MatitaCicMisc.disambiguate ~disambiguator ~currentProof ast
533 (** tactic AST -> ProofEngineTypes.tactic *)
534 method private lookup_tactic = function
535 | TacticAst.LocatedTactic (_, tactic) -> self#lookup_tactic tactic
536 | TacticAst.Intros (_, names) -> (* TODO Zack implement intros length *)
537 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 ->
550 Tactics.transitivity (self#disambiguate term)
551 | TacticAst.Apply term -> Tactics.apply (self#disambiguate term)
552 | TacticAst.Absurd term -> Tactics.absurd (self#disambiguate term)
553 | TacticAst.Exact term -> Tactics.exact (self#disambiguate term)
554 | TacticAst.Cut term -> Tactics.cut (self#disambiguate term)
555 | TacticAst.Elim (term, _) -> (* TODO Zack implement "using" argument *)
556 Tactics.elim_intros_simpl (self#disambiguate term)
557 | TacticAst.ElimType term -> Tactics.elim_type (self#disambiguate term)
558 | TacticAst.Replace (what, with_what) ->
559 Tactics.replace ~what:(self#disambiguate what)
560 ~with_what:(self#disambiguate with_what)
561 | TacticAst.Auto -> Tactics.auto_new ~dbd
563 (* TODO Zack a lot more of tactics to be implemented here ... *)
564 | TacticAst.Change of 'term * 'term * 'ident option
565 | TacticAst.Change_pattern of 'term pattern * 'term * 'ident option
566 | TacticAst.Decompose of 'ident * 'ident list
567 | TacticAst.Discriminate of 'ident
568 | TacticAst.Fold of reduction_kind * 'term
569 | TacticAst.Injection of 'ident
570 | TacticAst.LetIn of 'term * 'ident
571 | TacticAst.Reduce of reduction_kind * 'term pattern * 'ident option
572 | TacticAst.Replace_pattern of 'term pattern * 'term
573 | TacticAst.Rewrite of direction * 'term * 'ident option
575 | _ -> MatitaTypes.not_implemented "some tactic"
577 method evalTactical = function
578 | TacticAst.LocatedTactical (_, tactical) -> self#evalTactical tactical
579 | TacticAst.Command TacticAst.Abort ->
580 currentProof#abort ();
582 | TacticAst.Command (TacticAst.Undo steps) ->
583 currentProof#proof#undo ?steps ();
585 | TacticAst.Command (TacticAst.Redo steps) ->
586 currentProof#proof#redo ?steps ();
588 | TacticAst.Command (TacticAst.Qed None) ->
589 if not (currentProof#onGoing ()) then assert false;
590 let proof = currentProof#proof in
591 let (uri, metasenv, bo, ty) = proof#proof in
592 let uri = MatitaTypes.unopt_uri uri in
593 let suri = UriManager.string_of_uri uri in
594 (* TODO Zack this function probably should not simply fail with
595 * Failure, but rather raise some more meaningful exception *)
596 if metasenv <> [] then failwith "Proof not completed";
597 let proved_ty,ugraph =
598 CicTypeChecker.type_of_aux' [] [] bo CicUniv.empty_ugraph
601 CicReduction.are_convertible [] proved_ty ty ugraph
603 if not b then failwith "Wrong proof";
604 add_constant_to_world ~console ~dbd ~uri ~body:bo ~ty ~ugraph ();
605 currentProof#abort ();
606 console#echo_message (sprintf "%s defined" suri);
608 | TacticAst.Seq tacticals ->
609 (* TODO Zack check for proof completed at each step? *)
610 List.iter (fun t -> ignore (self#evalTactical t)) tacticals;
612 | TacticAst.Tactic tactic_phrase ->
613 let tactic = self#lookup_tactic tactic_phrase in
614 currentProof#proof#apply_tactic tactic;
616 | tactical -> shared#evalTactical tactical
620 ~(disambiguator: MatitaTypes.disambiguator)
621 ~(console: #MatitaTypes.console)
625 let commandState = new commandState ~disambiguator ~console ?mathViewer () in
626 let proofState = new proofState ~disambiguator ~console ?mathViewer () in
628 val mutable state = commandState
630 method reset = state <- commandState
632 method endOffset = state#endOffset
634 method private updateState = function
635 | New_state Command -> (state <- commandState)
636 | New_state Proof -> (state <- proofState)
639 method private eval f =
640 let ok () = (* console#clear (); *) (true, true) in
641 match console#wrap_exn f with
642 | Some (New_state Command) -> (state <- commandState); ok ()
643 | Some (New_state Proof) -> (state <- proofState); ok ()
644 | Some (Echo msg) -> console#echo_message msg; (true, false)
645 | Some Quiet -> ok ()
646 | None -> (false, false)
648 method evalPhrase s = self#eval (fun () -> state#evalPhrase s)
649 method evalAst ast = self#eval (fun () -> state#evalAst ast)
653 ~(disambiguator: MatitaTypes.disambiguator)
654 ~(console: #MatitaTypes.console)
658 new interpreter ~disambiguator ~console ?mathViewer ()