NaturalDeduction: remove unnecessary scnd_leaf, add (s)cnd_property
[coq-hetmet.git] / src / ExtractionMain.v
1 (*********************************************************************************************************************************)
2 (* ExtractionMain:                                                                                                               *)
3 (*                                                                                                                               *)
4 (*    This module is the "top level" for extraction                                                                              *)
5 (*                                                                                                                               *)
6 (*********************************************************************************************************************************)
7
8 Require Import Coq.Strings.Ascii.
9 Require Import Coq.Strings.String.
10 Require Import Coq.Lists.List.
11
12 Require Import Preamble.
13 Require Import General.
14
15 Require Import NaturalDeduction.
16 Require Import NaturalDeductionToLatex.
17
18 Require Import HaskKinds.
19 Require Import HaskLiteralsAndTyCons.
20 Require Import HaskCoreVars.
21 Require Import HaskCoreTypes.
22 Require Import HaskCore.
23 Require Import HaskWeakVars.
24 Require Import HaskWeakTypes.
25 Require Import HaskWeak.
26 Require Import HaskStrongTypes.
27 Require Import HaskStrong.
28 Require Import HaskProof.
29 Require Import HaskCoreToWeak.
30 Require Import HaskWeakToStrong.
31 Require Import HaskStrongToProof.
32 Require Import HaskProofToLatex.
33 Require Import HaskStrongToWeak.
34 Require Import HaskWeakToCore.
35 Require Import HaskProofToStrong.
36
37 Require Import ProgrammingLanguage.
38 Require Import HaskProofCategory.
39 Require Import ReificationsIsomorphicToGeneralizedArrows.
40
41 (*Require Import HaskStrongCategory.*)
42
43 Open Scope string_scope.
44 Extraction Language Haskell.
45
46 (*Extract Inductive vec    => "([])" [ "([])" "(:)" ].*)
47 (*Extract Inductive Tree   => "([])" [ "([])" "(:)" ].*)
48 (*Extract Inlined Constant map => "Prelude.map".*)
49
50 (* I try to reuse Haskell types mostly to get the "deriving Show" aspect *)
51 Extract Inductive option => "Prelude.Maybe" [ "Prelude.Just" "Prelude.Nothing" ].
52 Extract Inductive list   => "([])" [ "([])" "(:)" ].
53 Extract Inductive string => "Prelude.String" [ "[]" "(:)" ].
54 Extract Inductive prod   => "(,)" [ "(,)" ].
55 Extract Inductive sum    => "Prelude.Either" [ "Prelude.Left" "Prelude.Right" ].
56 Extract Inductive sumbool => "Prelude.Bool" [ "Prelude.True" "Prelude.False" ].
57 Extract Inductive bool    => "Prelude.Bool" [ "Prelude.True" "Prelude.False" ].
58 Extract Inductive unit    => "()" [ "()" ].
59 Extract Inlined Constant string_dec => "(==)".
60 Extract Inlined Constant ascii_dec => "(==)".
61
62 (* adapted from ExtrOcamlString.v *)
63 Extract Inductive ascii => "Char" [ "you_forgot_to_patch_coq" ] "you_forgot_to_patch_coq".
64 Extract Constant zero   => "'\000'".
65 Extract Constant one    => "'\001'".
66 Extract Constant shift  => "shiftAscii".
67
68 Unset Extraction Optimize.
69 Unset Extraction AutoInline.
70
71 Variable Name : Type.  Extract Inlined Constant Name => "Name.Name".
72 Variable mkSystemName : Unique -> string -> nat -> Name.
73   Extract Inlined Constant mkSystemName =>
74     "(\u s d -> Name.mkSystemName u (OccName.mkOccName (OccName.varNameDepth (nat2int d)) s))".
75 Variable mkTyVar : Name -> Kind -> CoreVar.
76   Extract Inlined Constant mkTyVar => "(\n k -> Var.mkTyVar n (kindToCoreKind k))".
77 Variable mkCoVar : Name -> CoreType -> CoreType -> CoreVar.
78   Extract Inlined Constant mkCoVar => "(\n t1 t2 -> Var.mkCoVar n (Coercion.mkCoKind t1 t2))".
79 Variable mkExVar : Name -> CoreType -> CoreVar.
80   Extract Inlined Constant mkExVar => "Id.mkLocalId".
81
82 Section core2proof.
83   Context (ce:@CoreExpr CoreVar).
84
85   Definition Γ : TypeEnv := nil.
86
87   Definition Δ : CoercionEnv Γ := nil.
88
89   Definition φ : TyVarResolver Γ :=
90     fun cv => Error ("unbound tyvar: " +++ toString (cv:CoreVar)).
91     (*fun tv => error ("tried to get the representative of an unbound tyvar:" +++ (getCoreVarOccString tv)).*)
92
93   Definition ψ : CoVarResolver Γ Δ :=
94     fun cv => Error ("tried to get the representative of an unbound covar!" (*+++ (getTypeVarOccString cv)*)).
95
96   (* We need to be able to resolve unbound exprvars, but we can be sure their types will have no
97    * free tyvars in them *)
98   Definition ξ (cv:CoreVar) : LeveledHaskType Γ ★ :=
99     match coreVarToWeakVar cv with
100       | WExprVar wev => match weakTypeToTypeOfKind φ wev ★ with
101                           | Error s => Prelude_error ("Error converting weakType of top-level variable "+++
102                                                          toString cv+++": " +++ s)
103                           | OK    t => t @@ nil
104                         end
105       | WTypeVar _   => Prelude_error "top-level xi got a type variable"
106       | WCoerVar _   => Prelude_error "top-level xi got a coercion variable"
107     end.
108
109
110   (* core-to-string (-dcoqpass) *)
111
112   Definition header : string :=
113     "\documentclass[9pt]{article}"+++eol+++
114     "\usepackage{amsmath}"+++eol+++
115     "\usepackage{amssymb}"+++eol+++
116     "\usepackage{proof}"+++eol+++
117     "\usepackage{mathpartir}   % http://cristal.inria.fr/~remy/latex/"+++eol+++
118     "\usepackage{trfrac}       % http://www.utdallas.edu/~hamlen/trfrac.sty"+++eol+++
119     "\def\code#1#2{\Box_{#1} #2}"+++eol+++
120     "\usepackage[paperwidth=200in,centering]{geometry}"+++eol+++
121     "\usepackage[displaymath,tightpage,active]{preview}"+++eol+++
122     "\begin{document}"+++eol+++
123     "\begin{preview}"+++eol.
124
125   Definition footer : string :=
126     eol+++"\end{preview}"+++
127     eol+++"\end{document}"+++
128     eol.
129
130
131   Definition coreToStringExpr' (ce:@CoreExpr CoreVar) : ???string :=
132     addErrorMessage ("input CoreSyn: " +++ toString ce)
133     (addErrorMessage ("input CoreType: " +++ toString (coreTypeOfCoreExpr ce)) (
134       coreExprToWeakExpr ce >>= fun we =>
135         addErrorMessage ("WeakExpr: " +++ toString we)
136           ((addErrorMessage ("CoreType of WeakExpr: " +++ toString (coreTypeOfCoreExpr (weakExprToCoreExpr we)))
137             ((weakTypeOfWeakExpr we) >>= fun t =>
138               (addErrorMessage ("WeakType: " +++ toString t)
139                 ((weakTypeToTypeOfKind φ t ★) >>= fun τ =>
140                   addErrorMessage ("HaskType: " +++ toString τ)
141                   ((weakExprToStrongExpr Γ Δ φ ψ ξ (fun _ => false) τ nil we) >>= fun e =>
142                     OK (eol+++"$$"+++ toString (nd_ml_toLatexMath (@expr2proof _ _ _ _ _ _ e))+++"$$"+++eol)
143                   )))))))).
144
145   Definition coreToStringExpr (ce:@CoreExpr CoreVar) : string :=
146     match coreToStringExpr' ce with
147       | OK x => x
148       | Error s => Prelude_error s
149     end.
150
151   Definition coreToStringBind (binds:@CoreBind CoreVar) : string :=
152     match binds with
153       | CoreNonRec _ e => coreToStringExpr e
154       | CoreRec    lbe => fold_left (fun x y => x+++eol+++eol+++y) (map (fun x => coreToStringExpr (snd x)) lbe) ""
155     end.
156
157   Definition coqPassCoreToString (lbinds:list (@CoreBind CoreVar)) : string :=
158     header +++
159     (fold_left (fun x y => x+++eol+++eol+++y) (map coreToStringBind lbinds) "")
160     +++ footer.
161
162
163   (* core-to-core (-fcoqpass) *)
164   Section CoreToCore.
165
166     Definition mkWeakTypeVar (u:Unique)(k:Kind)                 : WeakTypeVar :=
167       weakTypeVar (mkTyVar (mkSystemName u "tv" O) k) k.
168     Definition mkWeakCoerVar (u:Unique)(k:Kind)(t1 t2:WeakType) : WeakCoerVar :=
169       weakCoerVar (mkCoVar (mkSystemName u "cv" O) (weakTypeToCoreType t1) (weakTypeToCoreType t2)) k t1 t2.
170     Definition mkWeakExprVar (u:Unique)(t:WeakType)             : WeakExprVar :=
171       weakExprVar (mkExVar (mkSystemName u "ev" O) (weakTypeToCoreType t)) t.
172
173     Context (hetmet_brak  : WeakExprVar).
174     Context (hetmet_esc   : WeakExprVar).
175     Context (uniqueSupply : UniqSupply).
176
177     Definition useUniqueSupply {T}(ut:UniqM T) : ???T :=
178       match ut with
179         uniqM f =>
180          f uniqueSupply >>= fun x => OK (snd x)
181       end.
182
183     Definition larger : forall ln:list nat, { n:nat & forall n', In n' ln -> gt n n' }.
184       intros.
185       induction ln.
186       exists O.
187       intros.
188       inversion H.
189       destruct IHln as [n pf].
190       exists (plus (S n) a).
191       intros.
192       destruct H.
193       omega.
194       fold (@In _ n' ln) in H.
195       set (pf n' H) as q.
196       omega.
197       Defined.
198  
199   Definition FreshNat : @FreshMonad nat.
200     refine {| FMT       := fun T => nat -> prod nat T
201             ; FMT_fresh := _
202            |}.
203     Focus 2.
204     intros.
205     refine ((S H),_).
206     set (larger tl) as q.
207     destruct q as [n' pf].
208     exists n'.
209     intros.
210     set (pf _ H0) as qq.
211     omega.
212     
213     refine {| returnM := fun a (v:a) => _ |}.
214       intro n. exact (n,v).
215       intros.
216       set (X H) as q.
217       destruct q as [n' v].
218       set (X0 v n') as q'.
219       exact q'.
220       Defined.
221
222     Definition unFresh {T} : @FreshM _ FreshNat T -> T.
223       intros.
224       destruct X.
225       exact O.
226       apply t.
227       Defined.
228
229 (*
230     Definition env := ★::nil.
231     Definition freshTV : HaskType env ★ := haskTyVarToType (FreshHaskTyVar _).
232     Definition idproof0 : ND Rule [] [env > nil > [] |- [freshTV--->freshTV @@ nil]].
233       eapply nd_comp.
234       eapply nd_comp.
235       eapply nd_rule.
236       apply RVar.
237       eapply nd_rule
238       eapply (RArrange _ _ _ _ (RuCanL _ _)) .
239       eapply nd_rule.
240       eapply RLam.
241       Defined.
242
243
244     Definition coreToCoreExpr' (ce:@CoreExpr CoreVar) : ???(@CoreExpr CoreVar) :=
245     addErrorMessage ("input CoreSyn: " +++ toString ce)
246     (addErrorMessage ("input CoreType: " +++ toString (coreTypeOfCoreExpr ce)) (
247       coreExprToWeakExpr ce >>= fun we =>
248         addErrorMessage ("WeakExpr: " +++ toString we)
249           ((addErrorMessage ("CoreType of WeakExpr: " +++ toString (coreTypeOfCoreExpr (weakExprToCoreExpr we)))
250             ((weakTypeOfWeakExpr we) >>= fun t =>
251               (addErrorMessage ("WeakType: " +++ toString t)
252                 ((weakTypeToTypeOfKind φ t ★) >>= fun τ =>
253                   addErrorMessage ("HaskType: " +++ toString τ)
254                   ((weakExprToStrongExpr Γ Δ φ ψ ξ (fun _ => true) τ nil we) >>= fun e =>
255                         (let haskProof := @expr2proof _ _ _ _ _ _ e
256                           in (* insert HaskProof-to-HaskProof manipulations here *)
257                    (unFresh (@proof2expr nat _ FreshNat _ _ _ _ (fun _ => Prelude_error "unbound unique") _ haskProof))
258                   >>= fun e' => Error (@toString _ (ExprToString _ _ _ _) (projT2 e'))
259 (*
260                   >>= fun e' =>
261                     Prelude_error (@toString _ (@ExprToString nat _ _ _ _ _ _) (projT2 e'))
262   *)                  
263 )
264 )))))))).
265 (*                    Error "X").*)
266 (*
267                    strongExprToWeakExpr hetmet_brak hetmet_esc mkWeakTypeVar mkWeakCoerVar mkWeakExprVar uniqueSupply
268                    (projT2 e')
269                          INil
270                          >>= fun q => Error (toString q)
271                   ))))))))).
272 *)*)
273
274
275     Definition coreToCoreExpr' (ce:@CoreExpr CoreVar) : ???(@CoreExpr CoreVar) :=
276       addErrorMessage ("input CoreSyn: " +++ toString ce)
277       (addErrorMessage ("input CoreType: " +++ toString (coreTypeOfCoreExpr ce)) (
278         coreExprToWeakExpr ce >>= fun we =>
279           addErrorMessage ("WeakExpr: " +++ toString we)
280             ((addErrorMessage ("CoreType of WeakExpr: " +++ toString (coreTypeOfCoreExpr (weakExprToCoreExpr we)))
281               ((weakTypeOfWeakExpr we) >>= fun t =>
282                 (addErrorMessage ("WeakType: " +++ toString t)
283                   ((weakTypeToTypeOfKind φ t ★) >>= fun τ =>
284
285                     ((weakExprToStrongExpr Γ Δ φ ψ ξ (fun _ => true) τ nil we) >>= fun e =>
286
287                       (addErrorMessage ("HaskStrong...")
288                         (let haskProof := @expr2proof _ _ _ _ _ _ e
289                          in (* insert HaskProof-to-HaskProof manipulations here *)
290                          OK ((@proof2expr nat _ FreshNat _ _ _ _ (fun _ => Prelude_error "unbound unique") _ haskProof) O)
291                          >>= fun e' =>
292                            (snd e') >>= fun e'' =>
293                          strongExprToWeakExpr hetmet_brak hetmet_esc mkWeakTypeVar mkWeakCoerVar mkWeakExprVar uniqueSupply
294                            (projT2 e'') INil
295                          >>= fun q =>
296                            OK (weakExprToCoreExpr q)
297                     )))))))))).
298
299     Definition coreToCoreExpr (ce:@CoreExpr CoreVar) : (@CoreExpr CoreVar) :=
300       match coreToCoreExpr' ce with
301         | OK x    => x
302         | Error s => Prelude_error s
303       end.
304   
305     Definition coreToCoreBind (binds:@CoreBind CoreVar) : @CoreBind CoreVar :=
306       match binds with
307         | CoreNonRec v e => CoreNonRec v (coreToCoreExpr e)
308         | CoreRec    lbe => CoreRec (map (fun ve => match ve with (v,e) => (v,coreToCoreExpr e) end) lbe)
309       end.
310   
311     Definition coqPassCoreToCore' (lbinds:list (@CoreBind CoreVar)) : list (@CoreBind CoreVar) :=
312       map coreToCoreBind lbinds.
313
314   End CoreToCore.
315
316   Definition coqPassCoreToCore
317     (hetmet_brak  : CoreVar)
318     (hetmet_esc   : CoreVar)
319     (uniqueSupply : UniqSupply)
320     (lbinds:list (@CoreBind CoreVar)) : list (@CoreBind CoreVar) :=
321     match coreVarToWeakVar hetmet_brak with
322       | WExprVar hetmet_brak' => match coreVarToWeakVar hetmet_esc with
323                                    | WExprVar hetmet_esc' => coqPassCoreToCore' hetmet_brak' hetmet_esc' uniqueSupply lbinds
324                                    | _ => Prelude_error "IMPOSSIBLE"
325                                  end
326       | _ => Prelude_error "IMPOSSIBLE"
327     end.
328
329 End core2proof.