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