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 = lazy (ref (Helm_registry.get "matita.basedir"))
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 ()
72 val disambiguator = MatitaDisambiguator.instance ()
74 (** eval a toplevel phrase in the current state and return the new state
76 method parsePhrase s =
77 match CicTextualParser2.parse_tactical s with
78 | (TacticAst.LocatedTactical (loc', tac)) as tactical ->
80 (match tac with (* update interpreter history *)
81 | TacticAst.Command (TacticAst.Qed None) ->
82 history := `Qed :: !history
83 | TacticAst.Command (TacticAst.Theorem (_, Some name, _, None)) ->
84 history := `Theorem name :: !history
85 | TacticAst.Command (TacticAst.Qed _)
86 | TacticAst.Command (TacticAst.Theorem _) -> assert false
87 | _ -> history := `Tactic :: !history);
91 method virtual evalTactical:
92 (CicAst.term, string) TacticAst.tactical -> outcome
95 debug_print (sprintf "evaluating '%s'" s);
96 self#evalTactical (self#parsePhrase (Stream.of_string s))
98 method evalAst ast = self#evalTactical ast
102 | Some (start_pos, end_pos) -> end_pos.Lexing.pos_cnum
103 | None -> failwith "MatitaInterpreter: no offset recorded"
107 (** Implements phrases that should be accepted in all states *)
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)) ->
131 Lazy.force basedir := 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\""
136 !(Lazy.force basedir));
138 | TacticAst.Command (TacticAst.Check term) ->
139 let (_, _, term,ugraph) =
140 MatitaCicMisc.disambiguate ~disambiguator ~currentProof term
142 let (context, metasenv) =
143 MatitaCicMisc.get_context_and_metasenv currentProof
145 (* this is the Eval Compute
146 let term = CicReduction.whd context term in
148 let dummyno = CicMkImplicit.new_meta metasenv [] in
150 CicTypeChecker.type_of_aux' metasenv context term ugraph
152 (* TASSI: here ugraph1 is unused.... FIXME *)
153 let expr = Cic.Cast (term, ty) in
154 (match mathViewer with
155 | Some v -> v#checkTerm (`Cic expr)
158 | TacticAst.Command (TacticAst.Search_pat (search_kind, pat)) ->
160 match search_kind with
161 | `Locate -> MetadataQuery.locate ~dbd pat
162 | `Elim -> MetadataQuery.elim ~dbd pat
165 (* TODO ZACK: show URIs to the user *)
167 | TacticAst.Command (TacticAst.Print `Env) ->
168 let uris = CicEnvironment.list_uri () in
169 console#echo_message "Environment:";
171 console#echo_message (" " ^ (UriManager.string_of_uri u))
174 | TacticAst.Command (TacticAst.Print `Coer) ->
175 let uris = CoercGraph.get_coercions_list () in
176 console#echo_message "Coercions:";
177 List.iter (fun (s,t,u) ->
178 console#echo_message (" " ^ (UriManager.string_of_uri u))
182 raise (Command_error (TacticAstPp.pp_tactical tactical))
187 let pp_indtypes indTypes =
189 (fun (name, _, typ, constructors) ->
190 printf "%s: %s\n" name (CicPp.ppterm typ);
192 (fun (name, term) -> printf "\t%s: %s\n" name (CicPp.ppterm term))
197 let inddef_of_ast params indTypes (disambiguator:MatitaTypes.disambiguator) =
198 let add_pi binders t =
200 (fun (name, ast) acc ->
201 CicAst.Binder (`Forall, (Cic.Name name, Some ast), acc))
205 List.map (fun (name, _, typ, _) -> (name, add_pi params typ)) indTypes
207 let binders = ind_binders @ params in
209 let add_ast ast = asts := ast :: !asts in
210 let paramsno = List.length params in
211 let indbindersno = List.length ind_binders in
213 (fun (name, _, typ, constructors) ->
214 add_ast (add_pi params typ);
215 List.iter (fun (_, ast) -> add_ast (add_pi binders ast)) constructors)
217 let (_, metasenv, terms, ugraph) =
218 disambiguator#disambiguateTermAsts ~metasenv:[] !asts
220 let terms = ref (List.rev terms) in
222 match !terms with [] -> assert false | hd :: tl -> terms := tl; hd
226 | (name, _, _, _) :: _ -> qualify name ^ ".ind"
230 let counter = ref 0 in
234 CicUtil.term_of_uri (sprintf "%s#xpointer(1/%d)" uri !counter))
237 let subst_mutinds = List.fold_right CicSubstitution.subst mutinds in
240 (fun acc (name, inductive, typ, constructors) ->
241 let cicTyp = get_term () in
242 let cicConstructors =
244 (fun acc (name, _) ->
246 subst_mutinds (CicUtil.strip_prods indbindersno (get_term ()))
251 (name, inductive, cicTyp, List.rev cicConstructors) :: acc)
254 let cicIndTypes = List.rev cicIndTypes in
255 (UriManager.uri_of_string uri, (cicIndTypes, [], paramsno))
257 let save_object_to_disk uri obj =
258 let ensure_path_exists path =
259 let dir = Filename.dirname path in
261 let stats = Unix.stat dir in
262 if stats.Unix.st_kind <> Unix.S_DIR then
263 raise (Failure (dir ^ " already exists and is not a directory"))
267 Unix.Unix_error (_,_,_) ->
268 let pstatus = Unix.system ("mkdir -p " ^ dir) in
270 | Unix.WEXITED n when n = 0 -> ()
271 | _ -> raise (Failure ("Unable to create " ^ dir))
273 (* generate annobj, ids_to_inner_sorts and ids_to_inner_types *)
274 let annobj,_,_,ids_to_inner_sorts,ids_to_inner_types,_,_ =
275 Cic2acic.acic_object_of_cic_object ~eta_fix:false obj
279 Cic2Xml.print_object uri ~ids_to_inner_sorts ~ask_dtd_to_the_getter:false
283 Cic2Xml.print_inner_types uri ~ids_to_inner_sorts ~ids_to_inner_types
284 ~ask_dtd_to_the_getter:false
286 (* prepare URIs and paths *)
287 let innertypesuri = UriManager.innertypesuri_of_uri uri in
288 let bodyuri = UriManager.bodyuri_of_uri uri in
289 let innertypesfilename = Str.replace_first (Str.regexp "^cic:") ""
290 (UriManager.string_of_uri innertypesuri) ^ ".xml.gz" in
291 let innertypespath = !(Lazy.force basedir) ^ "/" ^ innertypesfilename in
292 let xmlfilename = Str.replace_first (Str.regexp "^cic:/") ""
293 (UriManager.string_of_uri uri) ^ ".xml.gz" in
294 let xmlpath = !(Lazy.force basedir) ^ "/" ^ xmlfilename in
295 let xmlbodyfilename = Str.replace_first (Str.regexp "^cic:/") ""
296 (UriManager.string_of_uri uri) ^ ".body.xml.gz" in
297 let xmlbodypath = !(Lazy.force basedir) ^ "/" ^ xmlbodyfilename in
298 let path_scheme_of path = "file://" ^ path in
299 MatitaMisc.mkdirs (List.map Filename.dirname [innertypespath; xmlpath]);
300 (* now write to disk *)
301 ensure_path_exists innertypespath;
302 Xml.pp ~gzip:true xmlinnertypes (Some innertypespath) ;
303 ensure_path_exists xmlpath;
304 Xml.pp ~gzip:true xml (Some xmlpath) ;
306 (* now register to the getter *)
307 Http_getter.register' innertypesuri (path_scheme_of innertypespath);
308 Http_getter.register' uri (path_scheme_of xmlpath);
309 (* now the optional body, both write and register *)
310 (match bodyxml,bodyuri with
312 | Some bodyxml,Some bodyuri->
313 ensure_path_exists xmlbodypath;
314 Xml.pp ~gzip:true bodyxml (Some xmlbodypath) ;
315 Http_getter.register' bodyuri (path_scheme_of xmlbodypath)
318 (* TODO ZACK a lot more to be done here:
319 * - save universe file *)
320 let add_constant_to_world ~(console: #MatitaTypes.console)
321 ~dbd ~uri ?body ~ty ?(params = []) ?(attrs = []) ~ugraph ()
323 let suri = UriManager.string_of_uri uri in
324 if CicEnvironment.in_library uri then
325 error (sprintf "%s constant already defined" suri)
327 let name = UriManager.name_of_uri uri in
328 let obj = Cic.Constant (name, body, ty, params, attrs) in
329 let ugraph = CicUnivUtils.clean_and_fill uri obj ugraph in
330 CicEnvironment.add_type_checked_term uri (obj, ugraph);
331 MetadataDb.index_constant ~dbd ~uri ~body ~ty;
332 save_object_to_disk uri obj;
333 console#echo_message (sprintf "%s constant defined" suri)
336 let add_inductive_def_to_world ~(console: #MatitaTypes.console)
337 ~dbd ~uri ~indTypes ?(params = []) ?(leftno = 0) ?(attrs = []) ~ugraph ()
339 let suri = UriManager.string_of_uri uri in
340 if CicEnvironment.in_library uri then
341 error (sprintf "%s inductive type already defined" suri)
343 let name = UriManager.name_of_uri uri in
344 let obj = Cic.InductiveDefinition (indTypes, params, leftno, attrs) in
345 let ugraph = CicUnivUtils.clean_and_fill uri obj ugraph in
346 CicEnvironment.put_inductive_definition uri (obj, ugraph);
347 MetadataDb.index_inductive_def ~dbd ~uri ~types:indTypes;
348 save_object_to_disk uri obj;
349 console#echo_message (sprintf "%s inductive type defined" suri);
352 let obj = CicElim.elim_of ~sort uri 0 in
353 let (name, body, ty, attrs) = split_obj obj in
354 let suri = qualify name ^ ".con" in
355 let uri = UriManager.uri_of_string suri in
356 (* TODO Zack: make CicElim returns a universe *)
357 let ugraph = CicUniv.empty_ugraph in
358 add_constant_to_world ~console ~dbd ~uri ?body ~ty ~attrs ~ugraph ();
361 (sprintf "%s eliminator (automatically) defined" suri)
363 with CicElim.Can_t_eliminate -> ()
365 List.iter elim [ Cic.Prop; Cic.Set; (Cic.Type (CicUniv.fresh ())) ];
368 (** Implements phrases that should be accepted only in Command state *)
369 class commandState ~(console: #MatitaTypes.console) ?mathViewer () =
370 let shared = new sharedState ~console ?mathViewer () in
372 inherit interpreterState ~console
374 method evalTactical = function
375 | TacticAst.LocatedTactical (_, tactical) -> self#evalTactical tactical
376 | TacticAst.Command (TacticAst.Theorem (_, Some name, ast, None)) ->
377 let (_, metasenv, expr,ugraph) =
378 disambiguator#disambiguateTermAst ast
380 let uri = UriManager.uri_of_string (qualify name ^ ".con") in
381 let proof = MatitaProof.proof ~typ:expr ~uri ~metasenv () in
382 currentProof#start proof;
385 (TacticAst.Theorem (_, Some name, type_ast, Some body_ast)) ->
386 let (_, metasenv, type_cic, ugraph) =
387 disambiguator#disambiguateTermAst type_ast
389 let (_, metasenv, body_cic, ugraph) =
390 disambiguator#disambiguateTermAst ~metasenv body_ast
392 let (body_type, ugraph) =
393 CicTypeChecker.type_of_aux' metasenv [] body_cic ugraph
395 let uri = UriManager.uri_of_string (qualify name ^ ".con") in
396 let (subst, metasenv, ugraph) =
397 CicUnification.fo_unif metasenv [] body_type type_cic ugraph
399 let body = CicMetaSubst.apply_subst subst body_cic in
400 let ty = CicMetaSubst.apply_subst subst type_cic in
401 add_constant_to_world ~console ~dbd ~uri ~body ~ty ~ugraph ();
403 | TacticAst.Command (TacticAst.Inductive (params, indTypes)) ->
405 let (uri, (indTypes, params, leftno)) =
406 inddef_of_ast params indTypes disambiguator
408 let obj = Cic.InductiveDefinition (indTypes, params, leftno, []) in
410 CicTypeChecker.typecheck_mutual_inductive_defs uri
411 (indTypes, params, leftno) CicUniv.empty_ugraph
413 add_inductive_def_to_world ~console
414 ~dbd ~uri ~indTypes ~params ~leftno ~ugraph ();
416 | TacticAst.Command TacticAst.Quit ->
417 currentProof#quit ();
418 New_state Command (* dummy answer, useless *)
419 | TacticAst.Command TacticAst.Proof ->
420 (* do nothing, just for compatibility with coq syntax *)
422 | TacticAst.Command (TacticAst.Coercion c_ast) ->
423 let env, metasenv, coercion, ugraph =
424 disambiguator#disambiguateTermAst c_ast
426 let coer_uri,coer_ty =
431 CicEnvironment.get_obj CicUniv.empty_ugraph uri
434 | Cic.Constant (_,_,ty,_,_)
435 | Cic.Variable (_,_,ty,_,_) ->
438 | Cic.MutConstruct (uri,t,c,_) ->
440 CicEnvironment.get_obj CicUniv.empty_ugraph uri
443 | Cic.InductiveDefinition (l,_,_,_) ->
444 let (_,_,_,cl) = List.nth l t in
445 let (_,cty) = List.nth cl c in
450 (* we have to get the source and the tgt type uri
451 * in Coq syntax we have already their names, but
452 * since we don't support Funclass and similar I think
453 * all the coercion should be of the form
455 * So we should be able to extract them from the coercion type
457 let extract_last_two_p ty =
458 let rec aux = function
459 | Cic.Prod( _, src, Cic.Prod (n,t1,t2)) -> aux (Cic.Prod(n,t1,t2))
460 | Cic.Prod( _, src, tgt) -> src, tgt
465 let rec uri_of_term = function
466 | Cic.Const(u,_) -> u
467 | Cic.MutInd (u, i , _) ->
468 (* we have to build by hand the #xpointer *)
469 let base = UriManager.string_of_uri u in
470 let xp = "#xpointer(1/" ^ (string_of_int (i+1)) ^ ")" in
471 UriManager.uri_of_string (base ^ xp)
472 | Cic.Appl (he::_) -> uri_of_term he
474 prerr_endline ("Fallisco a estrarre la uri di " ^
478 let ty_src,ty_tgt = extract_last_two_p coer_ty in
479 let src_uri = uri_of_term ty_src in
480 let tgt_uri = uri_of_term ty_tgt in
481 let coercions_to_add =
482 CoercGraph.close_coercion_graph src_uri tgt_uri coer_uri
484 (* FIXME: we should chek it this object can be a coercion
485 * maybe add the check to extract_last_two_p
487 console#echo_message (sprintf "Coercion %s"
488 (UriManager.string_of_uri coer_uri));
489 List.iter (fun (uri,obj,ugraph) ->
492 (sprintf "Coercion (automatic) %s"
493 (UriManager.string_of_uri uri));
495 let (name, body, ty, attrs) = split_obj obj in
496 add_constant_to_world ~console
497 ~dbd ~uri ?body ~ty ~attrs ~ugraph ();
500 | tactical -> shared#evalTactical tactical
503 (** create a ProofEngineTypes.mk_fresh_name_type function which uses given
504 * names as long as they are available, then it fallbacks to name generation
505 * using FreshNamesGenerator module *)
507 let len = List.length names in
509 fun metasenv context name ~typ ->
510 if !count < len then begin
511 let name = Cic.Name (List.nth names !count) in
515 FreshNamesGenerator.mk_fresh_name ~subst:[] metasenv context name ~typ
517 (** Implements phrases that should be accepted only in Proof state, basically
519 class proofState ~(console: #MatitaTypes.console) ?mathViewer () =
520 let shared = new sharedState ~console ?mathViewer () in
522 inherit interpreterState ~console
524 method private disambiguate ast =
525 let (_, _, term, _) =
526 MatitaCicMisc.disambiguate ~disambiguator ~currentProof ast
530 (** tactic AST -> ProofEngineTypes.tactic *)
531 method private lookup_tactic = function
532 | TacticAst.LocatedTactic (_, tactic) -> self#lookup_tactic tactic
533 | TacticAst.Intros (_, names) -> (* TODO Zack implement intros length *)
534 PrimitiveTactics.intros_tac ~mk_fresh_name_callback:(namer_of names)
536 | TacticAst.Reflexivity -> Tactics.reflexivity
537 | TacticAst.Assumption -> Tactics.assumption
538 | TacticAst.Contradiction -> Tactics.contradiction
539 | TacticAst.Exists -> Tactics.exists
540 | TacticAst.Fourier -> Tactics.fourier
541 | TacticAst.Left -> Tactics.left
542 | TacticAst.Right -> Tactics.right
543 | TacticAst.Ring -> Tactics.ring
544 | TacticAst.Split -> Tactics.split
545 | TacticAst.Symmetry -> Tactics.symmetry
546 | TacticAst.Transitivity term ->
547 Tactics.transitivity (self#disambiguate term)
548 | TacticAst.Apply term -> Tactics.apply (self#disambiguate term)
549 | TacticAst.Absurd term -> Tactics.absurd (self#disambiguate term)
550 | TacticAst.Exact term -> Tactics.exact (self#disambiguate term)
551 | TacticAst.Cut term -> Tactics.cut (self#disambiguate term)
552 | TacticAst.Elim (term, _) -> (* TODO Zack implement "using" argument *)
553 Tactics.elim_intros_simpl (self#disambiguate term)
554 | TacticAst.ElimType term -> Tactics.elim_type (self#disambiguate term)
555 | TacticAst.Replace (what, with_what) ->
556 Tactics.replace ~what:(self#disambiguate what)
557 ~with_what:(self#disambiguate with_what)
558 | TacticAst.Auto -> Tactics.auto_new ~dbd
560 (* TODO Zack a lot more of tactics to be implemented here ... *)
561 | TacticAst.Change of 'term * 'term * 'ident option
562 | TacticAst.Change_pattern of 'term pattern * 'term * 'ident option
563 | TacticAst.Decompose of 'ident * 'ident list
564 | TacticAst.Discriminate of 'ident
565 | TacticAst.Fold of reduction_kind * 'term
566 | TacticAst.Injection of 'ident
567 | TacticAst.LetIn of 'term * 'ident
568 | TacticAst.Reduce of reduction_kind * 'term pattern * 'ident option
569 | TacticAst.Replace_pattern of 'term pattern * 'term
570 | TacticAst.Rewrite of direction * 'term * 'ident option
572 | _ -> MatitaTypes.not_implemented "some tactic"
574 method evalTactical = function
575 | TacticAst.LocatedTactical (_, tactical) -> self#evalTactical tactical
576 | TacticAst.Command TacticAst.Abort ->
577 currentProof#abort ();
579 | TacticAst.Command (TacticAst.Undo steps) ->
580 currentProof#proof#undo ?steps ();
582 | TacticAst.Command (TacticAst.Redo steps) ->
583 currentProof#proof#redo ?steps ();
585 | TacticAst.Command (TacticAst.Qed None) ->
586 if not (currentProof#onGoing ()) then assert false;
587 let proof = currentProof#proof in
588 let (uri, metasenv, bo, ty) = proof#proof in
589 let uri = MatitaTypes.unopt_uri uri in
590 let suri = UriManager.string_of_uri uri in
591 (* TODO Zack this function probably should not simply fail with
592 * Failure, but rather raise some more meaningful exception *)
593 if metasenv <> [] then failwith "Proof not completed";
594 let proved_ty,ugraph =
595 CicTypeChecker.type_of_aux' [] [] bo CicUniv.empty_ugraph
598 CicReduction.are_convertible [] proved_ty ty ugraph
600 if not b then failwith "Wrong proof";
601 add_constant_to_world ~console ~dbd ~uri ~body:bo ~ty ~ugraph ();
602 currentProof#abort ();
603 console#echo_message (sprintf "%s defined" suri);
605 | TacticAst.Seq tacticals ->
606 (* TODO Zack check for proof completed at each step? *)
607 List.iter (fun t -> ignore (self#evalTactical t)) tacticals;
609 | TacticAst.Tactic tactic_phrase ->
610 let tactic = self#lookup_tactic tactic_phrase in
611 currentProof#proof#apply_tactic tactic;
613 | tactical -> shared#evalTactical tactical
616 class interpreter ~(console: #MatitaTypes.console) ?mathViewer () =
617 let commandState = new commandState ~console ?mathViewer () in
618 let proofState = new proofState ~console ?mathViewer () in
620 val mutable state = commandState
622 method reset = state <- commandState
624 method endOffset = state#endOffset
626 method private updateState = function
627 | New_state Command -> (state <- commandState)
628 | New_state Proof -> (state <- proofState)
631 method private eval f =
632 let ok () = (* console#clear (); *) (true, true) in
633 match console#wrap_exn f with
634 | Some (New_state Command) -> (state <- commandState); ok ()
635 | Some (New_state Proof) -> (state <- proofState); ok ()
636 | Some (Echo msg) -> console#echo_message msg; (true, false)
637 | Some Quiet -> ok ()
638 | None -> (false, false)
640 method evalPhrase s = self#eval (fun () -> state#evalPhrase s)
641 method evalAst ast = self#eval (fun () -> state#evalAst ast)
644 let interpreter ~(console: #MatitaTypes.console) ?mathViewer () =
645 new interpreter ~console ?mathViewer ()