]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaInterpreter.ml
bb43d67e0ae950159bb249a45d09262cb46bbaff
[helm.git] / helm / matita / matitaInterpreter.ml
1 (* Copyright (C) 2004, HELM Team.
2  * 
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.
6  * 
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.
11  * 
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.
16  *
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,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://helm.cs.unibo.it/
24  *)
25
26 (** Interpreter for textual phrases coming from matita's console (textual entry
27 * window at the bottom of the main window).
28 *
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.
33 *)
34
35 open Printf
36
37 open MatitaTypes
38
39 type state = Command | Proof
40 type outcome = New_state of state | Quiet | Echo of string
41
42 exception Command_error of string
43
44 (*
45 let uri name =
46   UriManager.uri_of_string (sprintf "%s/%s" BuildTimeConf.base_uri name)
47 *)
48
49 let baseuri = ref "cic:/matita"
50 let qualify name =
51   let baseuri = !baseuri in
52   if baseuri.[String.length baseuri - 1] = '/' then
53     baseuri ^ name
54   else
55     String.concat "/" [baseuri; name]
56 let split_obj = function
57   | Cic.Constant (name, body, ty, _)
58   | Cic.Variable (name, body, ty, _) -> (name, body, ty)
59   | _ -> assert false
60
61 let canonical_context metano metasenv =
62   try
63     let (_, context, _) = List.find (fun (m, _, _) -> m = metano) metasenv in
64     context
65   with Not_found ->
66     failwith (sprintf "Can't find canonical context for %d" metano)
67
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)
74   else
75     ([], [])
76
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
87     in
88     proof#set_metasenv metasenv;
89     retval
90   end else
91     disambiguator#disambiguateTermAst ast
92
93 class virtual interpreterState = 
94     (* static values, shared by all states inheriting this class *)
95   let loc = ref None in
96   let history = ref [] in
97   fun ~(console: MatitaTypes.console) ->
98   object (self)
99
100       (** eval a toplevel phrase in the current state and return the new state
101       *)
102     method parsePhrase s =
103       match CicTextualParser2.parse_tactical s with
104       | (TacticAst.LocatedTactical (loc', tac)) as tactical ->
105           loc := Some loc';
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);
114           tactical
115       | _ -> assert false
116
117     method virtual evalTactical:
118       (CicAst.term, string) TacticAst.tactical -> outcome
119
120     method evalPhrase s =
121       debug_print (sprintf "evaluating '%s'" s);
122       self#evalTactical (self#parsePhrase (Stream.of_string s))
123
124     method evalAst ast = self#evalTactical ast
125
126     method endOffset =
127       match !loc with
128       | Some (start_pos, end_pos) -> end_pos.Lexing.pos_cnum
129       | None -> failwith "MatitaInterpreter: no offset recorded"
130
131   end
132
133   (** Implements phrases that should be accepted in all states *)
134 class sharedState
135   ~(disambiguator: MatitaTypes.disambiguator)
136   ~(currentProof: MatitaTypes.currentProof)
137   ~(console: MatitaTypes.console)
138   ?(mathViewer: MatitaTypes.mathViewer option)
139   ~(dbd: Mysql.dbd)
140   ()
141 =
142   object (self)
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 *)
150           New_state Command
151       | TacticAst.Command (TacticAst.Baseuri (Some uri)) ->
152           baseuri := uri;
153           console#echo_message (sprintf "base uri set to \"%s\"" uri);
154           Quiet
155       | TacticAst.Command (TacticAst.Baseuri None) ->
156           console#echo_message (sprintf "base uri is \"%s\"" !baseuri);
157           Quiet
158       | TacticAst.Command (TacticAst.Check term) ->
159           let (_, _, term,ugraph) = 
160             disambiguate ~disambiguator ~currentProof term 
161           in
162           let (context, metasenv) = get_context_and_metasenv currentProof in
163           let dummyno = CicMkImplicit.new_meta metasenv [] in
164           let ty,ugraph1 = 
165             CicTypeChecker.type_of_aux' metasenv context term ugraph 
166           in
167             (* TASSI: here ugraph1 is unused.... FIXME *)
168           let expr = Cic.Cast (term, ty) in
169           let sequent = (dummyno, context, expr) in
170           (match mathViewer with
171           | None -> ()
172           | Some v -> v#checkTerm sequent metasenv);
173           Quiet
174       | TacticAst.Command (TacticAst.Search_pat (search_kind, pat)) ->
175           let uris =
176             match search_kind with
177             | `Locate -> MetadataQuery.locate ~dbd pat
178             | `Elim -> MetadataQuery.elim ~dbd pat
179             | _ -> assert false
180           in
181           (* TODO ZACK: show URIs to the user *)
182           Quiet
183       | tactical ->
184           raise (Command_error (TacticAstPp.pp_tactical tactical))
185   end
186
187 open Printf
188
189 let pp_indtypes indTypes =
190   List.iter
191     (fun (name, _, typ, constructors) ->
192       printf "%s: %s\n" name (CicPp.ppterm typ);
193       List.iter
194         (fun (name, term) -> printf "\t%s: %s\n" name (CicPp.ppterm term))
195         constructors)
196     indTypes;
197   flush stdout
198
199 let inddef_of_ast params indTypes (disambiguator:MatitaTypes.disambiguator) =
200   let add_pi binders t =
201     List.fold_right
202       (fun (name, ast) acc ->
203         CicAst.Binder (`Forall, (Cic.Name name, Some ast), acc))
204       binders t
205   in
206   let ind_binders =
207     List.map (fun (name, _, typ, _) -> (name, add_pi params typ)) indTypes
208   in
209   let binders = ind_binders @ params in
210   let asts = ref [] in
211   let add_ast ast = asts := ast :: !asts in
212   let paramsno = List.length params in
213   let indbindersno = List.length ind_binders in
214   List.iter
215     (fun (name, _, typ, constructors) ->
216       add_ast (add_pi params typ);
217       List.iter (fun (_, ast) -> add_ast (add_pi binders ast)) constructors)
218     indTypes;
219   let (_, metasenv, terms, ugraph) =
220     disambiguator#disambiguateTermAsts ~metasenv:[] !asts
221   in
222   let terms = ref (List.rev terms) in
223   let get_term () =
224     match !terms with [] -> assert false | hd :: tl -> terms := tl; hd
225   in
226   let uri =
227     match indTypes with
228     | (name, _, _, _) :: _ -> qualify name ^ ".ind"
229     | _ -> assert false
230   in
231   let mutinds =
232     let counter = ref 0 in
233     List.map
234       (fun _ ->
235         incr counter;
236         CicUtil.term_of_uri (sprintf "%s#xpointer(1/%d)" uri !counter))
237       indTypes
238   in
239   let subst_mutinds = List.fold_right CicSubstitution.subst mutinds in
240   let cicIndTypes =
241     List.fold_left
242       (fun acc (name, inductive, typ, constructors) ->
243         let cicTyp = get_term () in
244         let cicConstructors =
245           List.fold_left
246             (fun acc (name, _) ->
247               let typ =
248                 subst_mutinds (CicUtil.strip_prods indbindersno (get_term ()))
249               in
250               (name, typ) :: acc)
251             [] constructors
252         in
253         (name, inductive, cicTyp, List.rev cicConstructors) :: acc)
254       [] indTypes
255   in
256   let cicIndTypes = List.rev cicIndTypes in
257   (UriManager.uri_of_string uri, (cicIndTypes, [], paramsno))
258
259   (* TODO Zack a lot more to be done here:
260     * - save object to disk in xml format
261     * - register uri to the getter 
262     * - save universe file *)
263 let add_constant_to_world ~dbd ~uri ?body ~ty ~ugraph () =
264   let name = UriManager.name_of_uri uri in
265   let obj = Cic.Constant (name, body, ty, []) in
266   let ugraph = CicUnivUtils.clean_and_fill uri obj ugraph in
267   CicEnvironment.add_type_checked_term uri (obj, ugraph);
268   MetadataDb.index_constant ~dbd
269     ~owner:(Helm_registry.get "matita.owner") ~uri ~body ~ty
270
271   (** Implements phrases that should be accepted only in Command state *)
272 class commandState
273   ~(disambiguator: MatitaTypes.disambiguator)
274   ~(currentProof: MatitaTypes.currentProof)
275   ~(console: MatitaTypes.console)
276   ?mathViewer
277   ~(dbd: Mysql.dbd)
278   ()
279 =
280   let shared =
281     new sharedState ~disambiguator ~currentProof ~console ?mathViewer ~dbd ()
282   in
283   object (self)
284     inherit interpreterState ~console
285
286     method evalTactical = function
287       | TacticAst.LocatedTactical (_, tactical) -> self#evalTactical tactical
288       | TacticAst.Command (TacticAst.Theorem (_, Some name, ast, None)) ->
289           let (_, metasenv, expr,ugraph) = 
290             disambiguator#disambiguateTermAst ast 
291           in
292           let uri = UriManager.uri_of_string (qualify name ^ ".con") in
293           let proof = MatitaProof.proof ~typ:expr ~uri ~metasenv () in
294           currentProof#start proof;
295           New_state Proof
296       | TacticAst.Command
297         (TacticAst.Theorem (_, Some name, type_ast, Some body_ast)) ->
298           let (_, metasenv, type_cic, ugraph) = 
299             disambiguator#disambiguateTermAst type_ast
300           in
301           let (_, metasenv, body_cic, ugraph) = 
302             disambiguator#disambiguateTermAst ~metasenv body_ast
303           in
304           let (body_type, ugraph) =
305             CicTypeChecker.type_of_aux' metasenv [] body_cic ugraph
306           in
307           let uri = UriManager.uri_of_string (qualify name ^ ".con") in
308           let (subst, metasenv, ugraph) =
309             CicUnification.fo_unif metasenv [] body_type type_cic ugraph
310           in
311           let body = CicMetaSubst.apply_subst subst body_cic in
312           let ty = CicMetaSubst.apply_subst subst type_cic in
313           add_constant_to_world ~dbd ~uri ~body ~ty ~ugraph ();
314           Quiet
315       | TacticAst.Command (TacticAst.Inductive (params, indTypes)) ->
316           let (uri, (indTypes, params, leftno)) =
317             inddef_of_ast params indTypes disambiguator
318           in
319           let obj = Cic.InductiveDefinition (indTypes, params, leftno) in
320           let ugraph =
321             CicTypeChecker.typecheck_mutual_inductive_defs uri
322               (indTypes, params, leftno) CicUniv.empty_ugraph
323          in
324           let ugraph = CicUnivUtils.clean_and_fill uri obj ugraph in 
325           CicEnvironment.put_inductive_definition uri (obj, ugraph);
326           MetadataDb.index_inductive_def ~dbd
327             ~owner:(Helm_registry.get "matita.owner") ~uri ~types:indTypes;
328           let msgs = ref [] in
329           let elim sort =
330             try
331               let obj = CicElim.elim_of ~sort uri 0 in
332               let (name, body, ty) = split_obj obj in
333               let uri = UriManager.uri_of_string (qualify name ^ ".con") in
334                 (* TODO Zack: make CicElim returns a universe *)
335               let ugraph = CicUniv.empty_ugraph in
336               add_constant_to_world ~dbd ~uri ?body ~ty ~ugraph ();
337               msgs := (sprintf "%s defined" name) :: !msgs;
338             with CicElim.Can_t_eliminate -> ()
339           in
340           List.iter elim [ Cic.Prop; Cic.Set; (Cic.Type (CicUniv.fresh ())) ];
341           Echo (String.concat "\n" (List.rev !msgs))
342       | TacticAst.Command TacticAst.Quit ->
343           currentProof#quit ();
344           New_state Command (* dummy answer, useless *)
345       | TacticAst.Command TacticAst.Proof ->
346             (* do nothing, just for compatibility with coq syntax *)
347           New_state Command
348       | tactical -> shared#evalTactical tactical
349   end
350
351   (** create a ProofEngineTypes.mk_fresh_name_type function which uses given
352   * names as long as they are available, then it fallbacks to name generation
353   * using FreshNamesGenerator module *)
354 let namer_of names =
355   let len = List.length names in
356   let count = ref 0 in
357   fun metasenv context name ~typ ->
358     if !count < len then begin
359       let name = Cic.Name (List.nth names !count) in
360       incr count;
361       name
362     end else
363       FreshNamesGenerator.mk_fresh_name ~subst:[] metasenv context name ~typ
364
365   (** Implements phrases that should be accepted only in Proof state, basically
366   * tacticals *)
367 class proofState
368   ~(disambiguator: MatitaTypes.disambiguator)
369   ~(currentProof: MatitaTypes.currentProof)
370   ~(console: MatitaTypes.console)
371   ?mathViewer
372   ~(dbd: Mysql.dbd)
373   ()
374 =
375   let disambiguate ast =
376     let (_, _, term, _) = disambiguate ~disambiguator ~currentProof ast in
377     term
378   in
379     (** tactic AST -> ProofEngineTypes.tactic *)
380   let rec lookup_tactic = function
381     | TacticAst.LocatedTactic (_, tactic) -> lookup_tactic tactic
382     | TacticAst.Intros (_, names) ->  (* TODO Zack implement intros length *)
383         PrimitiveTactics.intros_tac ~mk_fresh_name_callback:(namer_of names) ()
384     | TacticAst.Reflexivity -> Tactics.reflexivity
385     | TacticAst.Assumption -> Tactics.assumption
386     | TacticAst.Contradiction -> Tactics.contradiction
387     | TacticAst.Exists -> Tactics.exists
388     | TacticAst.Fourier -> Tactics.fourier
389     | TacticAst.Left -> Tactics.left
390     | TacticAst.Right -> Tactics.right
391     | TacticAst.Ring -> Tactics.ring
392     | TacticAst.Split -> Tactics.split
393     | TacticAst.Symmetry -> Tactics.symmetry
394     | TacticAst.Transitivity term -> Tactics.transitivity (disambiguate term)
395     | TacticAst.Apply term -> Tactics.apply (disambiguate term)
396     | TacticAst.Absurd term -> Tactics.absurd (disambiguate term)
397     | TacticAst.Exact term -> Tactics.exact (disambiguate term)
398     | TacticAst.Cut term -> Tactics.cut (disambiguate term)
399     | TacticAst.Elim (term, _) -> (* TODO Zack implement "using" argument *)
400         Tactics.elim_intros_simpl (disambiguate term)
401     | TacticAst.ElimType term -> Tactics.elim_type (disambiguate term)
402     | TacticAst.Replace (what, with_what) ->
403         Tactics.replace ~what:(disambiguate what)
404           ~with_what:(disambiguate with_what)
405     | TacticAst.Auto -> Tactics.auto_new ~dbd
406   (*
407     (* TODO Zack a lot more of tactics to be implemented here ... *)
408     | TacticAst.Change of 'term * 'term * 'ident option
409     | TacticAst.Change_pattern of 'term pattern * 'term * 'ident option
410     | TacticAst.Decompose of 'ident * 'ident list
411     | TacticAst.Discriminate of 'ident
412     | TacticAst.Fold of reduction_kind * 'term
413     | TacticAst.Injection of 'ident
414     | TacticAst.LetIn of 'term * 'ident
415     | TacticAst.Reduce of reduction_kind * 'term pattern * 'ident option
416     | TacticAst.Replace_pattern of 'term pattern * 'term
417     | TacticAst.Rewrite of direction * 'term * 'ident option
418   *)
419     | _ ->
420         MatitaTypes.not_implemented "some tactic"
421   in
422   let shared =
423     new sharedState ~disambiguator ~currentProof ~console ?mathViewer ~dbd ()
424   in
425   object (self)
426     inherit interpreterState ~console
427
428     method evalTactical = function
429       | TacticAst.LocatedTactical (_, tactical) -> self#evalTactical tactical
430       | TacticAst.Command TacticAst.Abort ->
431           currentProof#abort ();
432           New_state Command
433       | TacticAst.Command (TacticAst.Undo steps) ->
434           currentProof#proof#undo ?steps ();
435           New_state Proof
436       | TacticAst.Command (TacticAst.Redo steps) ->
437           currentProof#proof#redo ?steps ();
438           New_state Proof
439       | TacticAst.Command (TacticAst.Qed None) ->
440           if not (currentProof#onGoing ()) then assert false;
441           let proof = currentProof#proof in
442           let (uri, metasenv, bo, ty) = proof#proof in
443           let uri = MatitaTypes.unopt_uri uri in
444             (* TODO Zack this function probably should not simply fail with
445             * Failure, but rather raise some more meaningful exception *)
446           if metasenv <> [] then failwith "Proof not completed";
447           let proved_ty,ugraph = 
448             CicTypeChecker.type_of_aux' [] [] bo CicUniv.empty_ugraph
449           in
450           let b,ugraph = 
451             CicReduction.are_convertible [] proved_ty ty ugraph 
452           in
453           if not b then failwith "Wrong proof";
454           add_constant_to_world ~dbd ~uri ~body:bo ~ty ~ugraph ();
455           currentProof#abort ();
456           (match mathViewer with None -> () | Some v -> v#unload ());
457           New_state Command
458       | TacticAst.Seq tacticals ->
459           (* TODO Zack check for proof completed at each step? *)
460           List.iter (fun t -> ignore (self#evalTactical t)) tacticals;
461           New_state Proof
462       | TacticAst.Tactic tactic_phrase ->
463           let tactic = lookup_tactic tactic_phrase in
464           currentProof#proof#apply_tactic tactic;
465           New_state Proof
466       | tactical -> shared#evalTactical tactical
467   end
468
469 class interpreter
470   ~(disambiguator: MatitaTypes.disambiguator)
471   ~(currentProof: MatitaTypes.currentProof)
472   ~(console: MatitaTypes.console)
473   ?mathViewer
474   ~(dbd: Mysql.dbd)
475   ()
476 =
477   let commandState =
478     new commandState ~disambiguator ~currentProof ~console ?mathViewer ~dbd ()
479   in
480   let proofState =
481     new proofState ~disambiguator ~currentProof ~console ?mathViewer ~dbd ()
482   in
483   object (self)
484     val mutable state = commandState
485
486     method reset = state <- commandState
487
488     method endOffset = state#endOffset
489
490     method private updateState = function
491       | New_state Command -> (state <- commandState)
492       | New_state Proof -> (state <- proofState)
493       | _ -> ()
494
495     method private eval f =
496       let ok () = console#clear (); (true, true) in
497       match console#wrap_exn f with
498       | Some (New_state Command) -> (state <- commandState); ok ()
499       | Some (New_state Proof) -> (state <- proofState); ok ()
500       | Some (Echo msg) -> console#echo_message msg; (true, false)
501       | Some Quiet -> ok ()
502       | None -> (false, false)
503
504     method evalPhrase s = self#eval (fun () -> state#evalPhrase s)
505     method evalAst ast = self#eval (fun () -> state#evalAst ast)
506   end
507