author | haftmann |
Wed, 15 Sep 2010 15:31:32 +0200 | |
changeset 39401 | 887f4218a39a |
parent 39209 | 1ca9055ba1f7 |
child 40705 | 03f1266a066e |
permissions | -rw-r--r-- |
37745
6315b6426200
checking generated code for various target languages
haftmann
parents:
37669
diff
changeset
|
1 |
(* Title: Tools/Code/code_haskell.ML |
28054 | 2 |
Author: Florian Haftmann, TU Muenchen |
3 |
||
4 |
Serializer for Haskell. |
|
5 |
*) |
|
6 |
||
7 |
signature CODE_HASKELL = |
|
8 |
sig |
|
37745
6315b6426200
checking generated code for various target languages
haftmann
parents:
37669
diff
changeset
|
9 |
val target: string |
28054 | 10 |
val setup: theory -> theory |
11 |
end; |
|
12 |
||
13 |
structure Code_Haskell : CODE_HASKELL = |
|
14 |
struct |
|
15 |
||
16 |
val target = "Haskell"; |
|
17 |
||
18 |
open Basic_Code_Thingol; |
|
19 |
open Code_Printer; |
|
20 |
||
21 |
infixr 5 @@; |
|
22 |
infixr 5 @|; |
|
23 |
||
24 |
||
25 |
(** Haskell serializer **) |
|
26 |
||
38923 | 27 |
fun print_haskell_stmt labelled_name class_syntax tyco_syntax const_syntax |
32924
d2e9b2dab760
dropped Code_Printer prefix where feasible; fixed whitespace issues; more coherent terminology
haftmann
parents:
32913
diff
changeset
|
28 |
reserved deresolve contr_classparam_typs deriving_show = |
28054 | 29 |
let |
38923 | 30 |
fun class_name class = case class_syntax class |
28054 | 31 |
of NONE => deresolve class |
28687 | 32 |
| SOME class => class; |
33991 | 33 |
fun print_typcontext tyvars vs = case maps (fn (v, sort) => map (pair v) sort) vs |
28054 | 34 |
of [] => [] |
37384
5aba26803073
more consistent naming aroud type classes and instances
haftmann
parents:
37242
diff
changeset
|
35 |
| constraints => enum "," "(" ")" ( |
28054 | 36 |
map (fn (v, class) => |
37384
5aba26803073
more consistent naming aroud type classes and instances
haftmann
parents:
37242
diff
changeset
|
37 |
str (class_name class ^ " " ^ lookup_var tyvars v)) constraints) |
28054 | 38 |
@@ str " => "; |
33991 | 39 |
fun print_typforall tyvars vs = case map fst vs |
28054 | 40 |
of [] => [] |
41 |
| vnames => str "forall " :: Pretty.breaks |
|
32924
d2e9b2dab760
dropped Code_Printer prefix where feasible; fixed whitespace issues; more coherent terminology
haftmann
parents:
32913
diff
changeset
|
42 |
(map (str o lookup_var tyvars) vnames) @ str "." @@ Pretty.brk 1; |
33991 | 43 |
fun print_tyco_expr tyvars fxy (tyco, tys) = |
44 |
brackify fxy (str tyco :: map (print_typ tyvars BR) tys) |
|
38923 | 45 |
and print_typ tyvars fxy (tycoexpr as tyco `%% tys) = (case tyco_syntax tyco |
33991 | 46 |
of NONE => print_tyco_expr tyvars fxy (deresolve tyco, tys) |
47 |
| SOME (i, print) => print (print_typ tyvars) fxy tys) |
|
48 |
| print_typ tyvars fxy (ITyVar v) = (str o lookup_var tyvars) v; |
|
49 |
fun print_typdecl tyvars (vs, tycoexpr) = |
|
50 |
Pretty.block (print_typcontext tyvars vs @| print_tyco_expr tyvars NOBR tycoexpr); |
|
51 |
fun print_typscheme tyvars (vs, ty) = |
|
52 |
Pretty.block (print_typforall tyvars vs @ print_typcontext tyvars vs @| print_typ tyvars NOBR ty); |
|
35228 | 53 |
fun print_term tyvars some_thm vars fxy (IConst c) = |
54 |
print_app tyvars some_thm vars fxy (c, []) |
|
55 |
| print_term tyvars some_thm vars fxy (t as (t1 `$ t2)) = |
|
28054 | 56 |
(case Code_Thingol.unfold_const_app t |
35228 | 57 |
of SOME app => print_app tyvars some_thm vars fxy app |
28054 | 58 |
| _ => |
59 |
brackify fxy [ |
|
35228 | 60 |
print_term tyvars some_thm vars NOBR t1, |
61 |
print_term tyvars some_thm vars BR t2 |
|
28054 | 62 |
]) |
35228 | 63 |
| print_term tyvars some_thm vars fxy (IVar NONE) = |
31889 | 64 |
str "_" |
35228 | 65 |
| print_term tyvars some_thm vars fxy (IVar (SOME v)) = |
32924
d2e9b2dab760
dropped Code_Printer prefix where feasible; fixed whitespace issues; more coherent terminology
haftmann
parents:
32913
diff
changeset
|
66 |
(str o lookup_var vars) v |
35228 | 67 |
| print_term tyvars some_thm vars fxy (t as _ `|=> _) = |
28054 | 68 |
let |
31874 | 69 |
val (binds, t') = Code_Thingol.unfold_pat_abs t; |
35228 | 70 |
val (ps, vars') = fold_map (print_bind tyvars some_thm BR o fst) binds vars; |
71 |
in brackets (str "\\" :: ps @ str "->" @@ print_term tyvars some_thm vars' NOBR t') end |
|
72 |
| print_term tyvars some_thm vars fxy (ICase (cases as (_, t0))) = |
|
28054 | 73 |
(case Code_Thingol.unfold_const_app t0 |
38923 | 74 |
of SOME (c_ts as ((c, _), _)) => if is_none (const_syntax c) |
35228 | 75 |
then print_case tyvars some_thm vars fxy cases |
76 |
else print_app tyvars some_thm vars fxy c_ts |
|
77 |
| NONE => print_case tyvars some_thm vars fxy cases) |
|
37449 | 78 |
and print_app_expr tyvars some_thm vars ((c, (_, function_typs)), ts) = case contr_classparam_typs c |
35228 | 79 |
of [] => (str o deresolve) c :: map (print_term tyvars some_thm vars BR) ts |
28054 | 80 |
| fingerprint => let |
33957 | 81 |
val ts_fingerprint = ts ~~ take (length ts) fingerprint; |
28054 | 82 |
val needs_annotation = forall (fn (_, NONE) => true | (t, SOME _) => |
83 |
(not o Code_Thingol.locally_monomorphic) t) ts_fingerprint; |
|
35228 | 84 |
fun print_term_anno (t, NONE) _ = print_term tyvars some_thm vars BR t |
33991 | 85 |
| print_term_anno (t, SOME _) ty = |
35228 | 86 |
brackets [print_term tyvars some_thm vars NOBR t, str "::", print_typ tyvars NOBR ty]; |
28054 | 87 |
in |
88 |
if needs_annotation then |
|
37449 | 89 |
(str o deresolve) c :: map2 print_term_anno ts_fingerprint (take (length ts) function_typs) |
35228 | 90 |
else (str o deresolve) c :: map (print_term tyvars some_thm vars BR) ts |
28054 | 91 |
end |
38923 | 92 |
and print_app tyvars = gen_print_app (print_app_expr tyvars) (print_term tyvars) const_syntax |
35228 | 93 |
and print_bind tyvars some_thm fxy p = gen_print_bind (print_term tyvars) some_thm fxy p |
94 |
and print_case tyvars some_thm vars fxy (cases as ((_, [_]), _)) = |
|
28054 | 95 |
let |
29952
9aed85067721
unified variable names in case expressions; no exponential fork in translation of case expressions
haftmann
parents:
29832
diff
changeset
|
96 |
val (binds, body) = Code_Thingol.unfold_let (ICase cases); |
33991 | 97 |
fun print_match ((pat, ty), t) vars = |
28054 | 98 |
vars |
35228 | 99 |
|> print_bind tyvars some_thm BR pat |
100 |
|>> (fn p => semicolon [p, str "=", print_term tyvars some_thm vars NOBR t]) |
|
33991 | 101 |
val (ps, vars') = fold_map print_match binds vars; |
31665 | 102 |
in brackify_block fxy (str "let {") |
103 |
ps |
|
35228 | 104 |
(concat [str "}", str "in", print_term tyvars some_thm vars' NOBR body]) |
28054 | 105 |
end |
35228 | 106 |
| print_case tyvars some_thm vars fxy (((t, ty), clauses as _ :: _), _) = |
28054 | 107 |
let |
33991 | 108 |
fun print_select (pat, body) = |
28054 | 109 |
let |
35228 | 110 |
val (p, vars') = print_bind tyvars some_thm NOBR pat vars; |
111 |
in semicolon [p, str "->", print_term tyvars some_thm vars' NOBR body] end; |
|
36576 | 112 |
in Pretty.block_enclose |
113 |
(concat [str "(case", print_term tyvars some_thm vars NOBR t, str "of", str "{"], str "})") |
|
33991 | 114 |
(map print_select clauses) |
28054 | 115 |
end |
35228 | 116 |
| print_case tyvars some_thm vars fxy ((_, []), _) = |
31376 | 117 |
(brackify fxy o Pretty.breaks o map str) ["error", "\"empty case\""]; |
37437 | 118 |
fun print_stmt (name, Code_Thingol.Fun (_, (((vs, ty), raw_eqs), _))) = |
28054 | 119 |
let |
32924
d2e9b2dab760
dropped Code_Printer prefix where feasible; fixed whitespace issues; more coherent terminology
haftmann
parents:
32913
diff
changeset
|
120 |
val tyvars = intro_vars (map fst vs) reserved; |
34269 | 121 |
fun print_err n = |
33991 | 122 |
semicolon ( |
39207
0c3d19af759d
dropped ancient deresolve_base; plain_const_syntax also needs modification of instance statement
haftmann
parents:
39206
diff
changeset
|
123 |
(str o deresolve) name |
28054 | 124 |
:: map str (replicate n "_") |
125 |
@ str "=" |
|
126 |
:: str "error" |
|
33991 | 127 |
@@ (str o ML_Syntax.print_string |
30364
577edc39b501
moved basic algebra of long names from structure NameSpace to Long_Name;
wenzelm
parents:
30280
diff
changeset
|
128 |
o Long_Name.base_name o Long_Name.qualifier) name |
34269 | 129 |
); |
35228 | 130 |
fun print_eqn ((ts, t), (some_thm, _)) = |
28054 | 131 |
let |
32913 | 132 |
val consts = fold Code_Thingol.add_constnames (t :: ts) []; |
32924
d2e9b2dab760
dropped Code_Printer prefix where feasible; fixed whitespace issues; more coherent terminology
haftmann
parents:
32913
diff
changeset
|
133 |
val vars = reserved |
d2e9b2dab760
dropped Code_Printer prefix where feasible; fixed whitespace issues; more coherent terminology
haftmann
parents:
32913
diff
changeset
|
134 |
|> intro_base_names |
38923 | 135 |
(is_none o const_syntax) deresolve consts |
32924
d2e9b2dab760
dropped Code_Printer prefix where feasible; fixed whitespace issues; more coherent terminology
haftmann
parents:
32913
diff
changeset
|
136 |
|> intro_vars ((fold o Code_Thingol.fold_varnames) |
32925 | 137 |
(insert (op =)) ts []); |
28054 | 138 |
in |
139 |
semicolon ( |
|
39207
0c3d19af759d
dropped ancient deresolve_base; plain_const_syntax also needs modification of instance statement
haftmann
parents:
39206
diff
changeset
|
140 |
(str o deresolve) name |
35228 | 141 |
:: map (print_term tyvars some_thm vars BR) ts |
28054 | 142 |
@ str "=" |
35228 | 143 |
@@ print_term tyvars some_thm vars NOBR t |
28054 | 144 |
) |
145 |
end; |
|
146 |
in |
|
147 |
Pretty.chunks ( |
|
33991 | 148 |
semicolon [ |
39207
0c3d19af759d
dropped ancient deresolve_base; plain_const_syntax also needs modification of instance statement
haftmann
parents:
39206
diff
changeset
|
149 |
(str o suffix " ::" o deresolve) name, |
33991 | 150 |
print_typscheme tyvars (vs, ty) |
28054 | 151 |
] |
34269 | 152 |
:: (case filter (snd o snd) raw_eqs |
153 |
of [] => [print_err ((length o fst o Code_Thingol.unfold_fun) ty)] |
|
154 |
| eqs => map print_eqn eqs) |
|
28054 | 155 |
) |
156 |
end |
|
33991 | 157 |
| print_stmt (name, Code_Thingol.Datatype (_, (vs, []))) = |
28054 | 158 |
let |
32924
d2e9b2dab760
dropped Code_Printer prefix where feasible; fixed whitespace issues; more coherent terminology
haftmann
parents:
32913
diff
changeset
|
159 |
val tyvars = intro_vars (map fst vs) reserved; |
28054 | 160 |
in |
161 |
semicolon [ |
|
162 |
str "data", |
|
39207
0c3d19af759d
dropped ancient deresolve_base; plain_const_syntax also needs modification of instance statement
haftmann
parents:
39206
diff
changeset
|
163 |
print_typdecl tyvars (vs, (deresolve name, map (ITyVar o fst) vs)) |
28054 | 164 |
] |
165 |
end |
|
37449 | 166 |
| print_stmt (name, Code_Thingol.Datatype (_, (vs, [((co, _), [ty])]))) = |
28054 | 167 |
let |
32924
d2e9b2dab760
dropped Code_Printer prefix where feasible; fixed whitespace issues; more coherent terminology
haftmann
parents:
32913
diff
changeset
|
168 |
val tyvars = intro_vars (map fst vs) reserved; |
28054 | 169 |
in |
170 |
semicolon ( |
|
171 |
str "newtype" |
|
39207
0c3d19af759d
dropped ancient deresolve_base; plain_const_syntax also needs modification of instance statement
haftmann
parents:
39206
diff
changeset
|
172 |
:: print_typdecl tyvars (vs, (deresolve name, map (ITyVar o fst) vs)) |
28054 | 173 |
:: str "=" |
39207
0c3d19af759d
dropped ancient deresolve_base; plain_const_syntax also needs modification of instance statement
haftmann
parents:
39206
diff
changeset
|
174 |
:: (str o deresolve) co |
33991 | 175 |
:: print_typ tyvars BR ty |
28054 | 176 |
:: (if deriving_show name then [str "deriving (Read, Show)"] else []) |
177 |
) |
|
178 |
end |
|
33991 | 179 |
| print_stmt (name, Code_Thingol.Datatype (_, (vs, co :: cos))) = |
28054 | 180 |
let |
32924
d2e9b2dab760
dropped Code_Printer prefix where feasible; fixed whitespace issues; more coherent terminology
haftmann
parents:
32913
diff
changeset
|
181 |
val tyvars = intro_vars (map fst vs) reserved; |
37449 | 182 |
fun print_co ((co, _), tys) = |
28054 | 183 |
concat ( |
39207
0c3d19af759d
dropped ancient deresolve_base; plain_const_syntax also needs modification of instance statement
haftmann
parents:
39206
diff
changeset
|
184 |
(str o deresolve) co |
33991 | 185 |
:: map (print_typ tyvars BR) tys |
28054 | 186 |
) |
187 |
in |
|
188 |
semicolon ( |
|
189 |
str "data" |
|
39207
0c3d19af759d
dropped ancient deresolve_base; plain_const_syntax also needs modification of instance statement
haftmann
parents:
39206
diff
changeset
|
190 |
:: print_typdecl tyvars (vs, (deresolve name, map (ITyVar o fst) vs)) |
28054 | 191 |
:: str "=" |
33991 | 192 |
:: print_co co |
193 |
:: map ((fn p => Pretty.block [str "| ", p]) o print_co) cos |
|
28054 | 194 |
@ (if deriving_show name then [str "deriving (Read, Show)"] else []) |
195 |
) |
|
196 |
end |
|
37447
ad3e04f289b6
transitive superclasses were also only a misunderstanding
haftmann
parents:
37446
diff
changeset
|
197 |
| print_stmt (name, Code_Thingol.Class (_, (v, (super_classes, classparams)))) = |
28054 | 198 |
let |
32924
d2e9b2dab760
dropped Code_Printer prefix where feasible; fixed whitespace issues; more coherent terminology
haftmann
parents:
32913
diff
changeset
|
199 |
val tyvars = intro_vars [v] reserved; |
33991 | 200 |
fun print_classparam (classparam, ty) = |
28054 | 201 |
semicolon [ |
39207
0c3d19af759d
dropped ancient deresolve_base; plain_const_syntax also needs modification of instance statement
haftmann
parents:
39206
diff
changeset
|
202 |
(str o deresolve) classparam, |
28054 | 203 |
str "::", |
33991 | 204 |
print_typ tyvars NOBR ty |
28054 | 205 |
] |
206 |
in |
|
207 |
Pretty.block_enclose ( |
|
208 |
Pretty.block [ |
|
209 |
str "class ", |
|
37384
5aba26803073
more consistent naming aroud type classes and instances
haftmann
parents:
37242
diff
changeset
|
210 |
Pretty.block (print_typcontext tyvars [(v, map fst super_classes)]), |
39207
0c3d19af759d
dropped ancient deresolve_base; plain_const_syntax also needs modification of instance statement
haftmann
parents:
39206
diff
changeset
|
211 |
str (deresolve name ^ " " ^ lookup_var tyvars v), |
28054 | 212 |
str " where {" |
213 |
], |
|
214 |
str "};" |
|
33991 | 215 |
) (map print_classparam classparams) |
28054 | 216 |
end |
37449 | 217 |
| print_stmt (_, Code_Thingol.Classinst ((class, (tyco, vs)), (_, (classparam_instances, _)))) = |
28054 | 218 |
let |
32924
d2e9b2dab760
dropped Code_Printer prefix where feasible; fixed whitespace issues; more coherent terminology
haftmann
parents:
32913
diff
changeset
|
219 |
val tyvars = intro_vars (map fst vs) reserved; |
38923 | 220 |
fun requires_args classparam = case const_syntax classparam |
39207
0c3d19af759d
dropped ancient deresolve_base; plain_const_syntax also needs modification of instance statement
haftmann
parents:
39206
diff
changeset
|
221 |
of NONE => NONE |
0c3d19af759d
dropped ancient deresolve_base; plain_const_syntax also needs modification of instance statement
haftmann
parents:
39206
diff
changeset
|
222 |
| SOME (Code_Printer.Plain_const_syntax _) => SOME 0 |
0c3d19af759d
dropped ancient deresolve_base; plain_const_syntax also needs modification of instance statement
haftmann
parents:
39206
diff
changeset
|
223 |
| SOME (Code_Printer.Complex_const_syntax (k,_ )) => SOME k; |
37881 | 224 |
fun print_classparam_instance ((classparam, const), (thm, _)) = |
225 |
case requires_args classparam |
|
39207
0c3d19af759d
dropped ancient deresolve_base; plain_const_syntax also needs modification of instance statement
haftmann
parents:
39206
diff
changeset
|
226 |
of NONE => semicolon [ |
0c3d19af759d
dropped ancient deresolve_base; plain_const_syntax also needs modification of instance statement
haftmann
parents:
39206
diff
changeset
|
227 |
(str o Long_Name.base_name o deresolve) classparam, |
28687 | 228 |
str "=", |
37881 | 229 |
print_app tyvars (SOME thm) reserved NOBR (const, []) |
28687 | 230 |
] |
39207
0c3d19af759d
dropped ancient deresolve_base; plain_const_syntax also needs modification of instance statement
haftmann
parents:
39206
diff
changeset
|
231 |
| SOME k => |
37881 | 232 |
let |
233 |
val (c, (_, tys)) = const; |
|
234 |
val (vs, rhs) = (apfst o map) fst |
|
235 |
(Code_Thingol.unfold_abs (Code_Thingol.eta_expand k (const, []))); |
|
38923 | 236 |
val s = if (is_some o const_syntax) c |
37881 | 237 |
then NONE else (SOME o Long_Name.base_name o deresolve) c; |
238 |
val vars = reserved |
|
239 |
|> intro_vars (map_filter I (s :: vs)); |
|
240 |
val lhs = IConst (classparam, (([], []), tys)) `$$ map IVar vs; |
|
241 |
(*dictionaries are not relevant at this late stage*) |
|
242 |
in |
|
243 |
semicolon [ |
|
244 |
print_term tyvars (SOME thm) vars NOBR lhs, |
|
245 |
str "=", |
|
246 |
print_term tyvars (SOME thm) vars NOBR rhs |
|
247 |
] |
|
248 |
end; |
|
28054 | 249 |
in |
250 |
Pretty.block_enclose ( |
|
251 |
Pretty.block [ |
|
252 |
str "instance ", |
|
33991 | 253 |
Pretty.block (print_typcontext tyvars vs), |
28054 | 254 |
str (class_name class ^ " "), |
33991 | 255 |
print_typ tyvars BR (tyco `%% map (ITyVar o fst) vs), |
28054 | 256 |
str " where {" |
257 |
], |
|
258 |
str "};" |
|
37384
5aba26803073
more consistent naming aroud type classes and instances
haftmann
parents:
37242
diff
changeset
|
259 |
) (map print_classparam_instance classparam_instances) |
28054 | 260 |
end; |
33991 | 261 |
in print_stmt end; |
28054 | 262 |
|
39202 | 263 |
fun haskell_program_of_program labelled_name module_alias module_prefix reserved = |
264 |
let |
|
265 |
fun namify_fun upper base (nsp_fun, nsp_typ) = |
|
266 |
let |
|
267 |
val (base', nsp_fun') = yield_singleton Name.variants |
|
268 |
(if upper then first_upper base else base) nsp_fun; |
|
269 |
in (base', (nsp_fun', nsp_typ)) end; |
|
270 |
fun namify_typ base (nsp_fun, nsp_typ) = |
|
271 |
let |
|
272 |
val (base', nsp_typ') = yield_singleton Name.variants |
|
273 |
(first_upper base) nsp_typ |
|
274 |
in (base', (nsp_fun, nsp_typ')) end; |
|
275 |
fun namify_stmt (Code_Thingol.Fun (_, (_, SOME _))) = pair |
|
276 |
| namify_stmt (Code_Thingol.Fun _) = namify_fun false |
|
277 |
| namify_stmt (Code_Thingol.Datatype _) = namify_typ |
|
278 |
| namify_stmt (Code_Thingol.Datatypecons _) = namify_fun true |
|
279 |
| namify_stmt (Code_Thingol.Class _) = namify_typ |
|
280 |
| namify_stmt (Code_Thingol.Classrel _) = pair |
|
281 |
| namify_stmt (Code_Thingol.Classparam _) = namify_fun false |
|
282 |
| namify_stmt (Code_Thingol.Classinst _) = pair; |
|
283 |
fun select_stmt (Code_Thingol.Fun (_, (_, SOME _))) = false |
|
284 |
| select_stmt (Code_Thingol.Fun _) = true |
|
285 |
| select_stmt (Code_Thingol.Datatype _) = true |
|
286 |
| select_stmt (Code_Thingol.Datatypecons _) = false |
|
287 |
| select_stmt (Code_Thingol.Class _) = true |
|
288 |
| select_stmt (Code_Thingol.Classrel _) = false |
|
289 |
| select_stmt (Code_Thingol.Classparam _) = false |
|
290 |
| select_stmt (Code_Thingol.Classinst _) = true; |
|
291 |
in |
|
39206 | 292 |
Code_Namespace.flat_program labelled_name |
39202 | 293 |
{ module_alias = module_alias, module_prefix = module_prefix, |
294 |
reserved = reserved, empty_nsp = (reserved, reserved), namify_stmt = namify_stmt, |
|
295 |
modify_stmt = fn stmt => if select_stmt stmt then SOME stmt else NONE } |
|
296 |
end; |
|
297 |
||
39142 | 298 |
fun serialize_haskell module_prefix string_classes { labelled_name, reserved_syms, |
299 |
includes, module_alias, class_syntax, tyco_syntax, const_syntax, program } = |
|
28054 | 300 |
let |
39204 | 301 |
|
302 |
(* build program *) |
|
38926 | 303 |
val reserved = fold (insert (op =) o fst) includes reserved_syms; |
39204 | 304 |
val { deresolver, flat_program = haskell_program } = haskell_program_of_program |
305 |
labelled_name module_alias module_prefix (Name.make_context reserved) program; |
|
306 |
||
307 |
(* print statements *) |
|
28054 | 308 |
val contr_classparam_typs = Code_Thingol.contr_classparam_typs program; |
309 |
fun deriving_show tyco = |
|
310 |
let |
|
311 |
fun deriv _ "fun" = false |
|
34085 | 312 |
| deriv tycos tyco = not (tyco = Code_Thingol.fun_tyco) |
313 |
andalso (member (op =) tycos tyco |
|
314 |
orelse case try (Graph.get_node program) tyco |
|
28663
bd8438543bf2
code identifier namings are no longer imperative
haftmann
parents:
28350
diff
changeset
|
315 |
of SOME (Code_Thingol.Datatype (_, (_, cs))) => forall (deriv' (tyco :: tycos)) |
28054 | 316 |
(maps snd cs) |
34085 | 317 |
| NONE => true) |
28054 | 318 |
and deriv' tycos (tyco `%% tys) = deriv tycos tyco |
319 |
andalso forall (deriv' tycos) tys |
|
320 |
| deriv' _ (ITyVar _) = true |
|
321 |
in deriv [] tyco end; |
|
39204 | 322 |
fun print_stmt deresolve = print_haskell_stmt labelled_name |
323 |
class_syntax tyco_syntax const_syntax (make_vars reserved) |
|
324 |
deresolve contr_classparam_typs |
|
28054 | 325 |
(if string_classes then deriving_show else K false); |
39204 | 326 |
|
327 |
(* print modules *) |
|
328 |
val import_includes_ps = |
|
329 |
map (fn (name, _) => str ("import qualified " ^ name ^ ";")) includes; |
|
330 |
fun print_module_frame module_name ps = |
|
331 |
(module_name, Pretty.chunks2 ( |
|
39209 | 332 |
str ("module " ^ module_name ^ " where {") |
39204 | 333 |
:: ps |
334 |
@| str "}" |
|
335 |
)); |
|
336 |
fun print_module module_name (gr, imports) = |
|
28054 | 337 |
let |
39204 | 338 |
val deresolve = deresolver module_name |
339 |
fun print_import module_name = (semicolon o map str) ["import qualified", module_name]; |
|
340 |
val import_ps = import_includes_ps @ map (print_import o fst) imports; |
|
341 |
fun print_stmt' gr name = case Graph.get_node gr name |
|
342 |
of (_, NONE) => NONE |
|
343 |
| (_, SOME stmt) => SOME (markup_stmt name (print_stmt deresolve (name, stmt))); |
|
344 |
val body_ps = map_filter (print_stmt' gr) ((flat o rev o Graph.strong_conn) gr); |
|
345 |
in |
|
346 |
print_module_frame module_name |
|
347 |
((if null import_ps then [] else [Pretty.chunks import_ps]) @ body_ps) |
|
348 |
end; |
|
349 |
||
350 |
(*serialization*) |
|
351 |
fun write_module width (SOME destination) (module_name, content) = |
|
38915 | 352 |
let |
353 |
val _ = File.check destination; |
|
39204 | 354 |
val filepath = (Path.append destination o Path.ext "hs" o Path.explode o implode |
355 |
o separate "/" o Long_Name.explode) module_name; |
|
356 |
val _ = File.mkdir_leaf (Path.dir filepath); |
|
39209 | 357 |
in |
358 |
(File.write filepath o format [] width o Pretty.chunks2) |
|
359 |
[str "{-# OPTIONS_GHC -fglasgow-exts #-}", content] |
|
360 |
end |
|
39056 | 361 |
| write_module width NONE (_, content) = writeln (format [] width content); |
28054 | 362 |
in |
38916 | 363 |
Code_Target.serialization |
38915 | 364 |
(fn width => fn destination => K () o map (write_module width destination)) |
39204 | 365 |
(fn present => fn width => rpair (fn _ => error "no deresolving") |
366 |
o format present width o Pretty.chunks o map snd) |
|
367 |
(map (uncurry print_module_frame o apsnd single) includes |
|
368 |
@ map (fn module_name => print_module module_name (Graph.get_node haskell_program module_name)) |
|
369 |
((flat o rev o Graph.strong_conn) haskell_program)) |
|
28054 | 370 |
end; |
371 |
||
38966 | 372 |
val serializer : Code_Target.serializer = |
39206 | 373 |
Code_Target.parse_args (Scan.optional (Args.$$$ "root" -- Args.colon |-- Args.name) "" |
38966 | 374 |
-- Scan.optional (Args.$$$ "string_classes" >> K true) false |
375 |
>> (fn (module_prefix, string_classes) => |
|
376 |
serialize_haskell module_prefix string_classes)); |
|
377 |
||
28064 | 378 |
val literals = let |
379 |
fun char_haskell c = |
|
380 |
let |
|
381 |
val s = ML_Syntax.print_char c; |
|
382 |
in if s = "'" then "\\'" else s end; |
|
34944
970e1466028d
code literals: distinguish numeral classes by different entries
haftmann
parents:
34269
diff
changeset
|
383 |
fun numeral_haskell k = if k >= 0 then string_of_int k |
970e1466028d
code literals: distinguish numeral classes by different entries
haftmann
parents:
34269
diff
changeset
|
384 |
else Library.enclose "(" ")" (signed_string_of_int k); |
28064 | 385 |
in Literals { |
34178
a78b8d5b91cb
take care for destructive print mode properly using dedicated pretty builders
haftmann
parents:
34085
diff
changeset
|
386 |
literal_char = Library.enclose "'" "'" o char_haskell, |
28064 | 387 |
literal_string = quote o translate_string char_haskell, |
34944
970e1466028d
code literals: distinguish numeral classes by different entries
haftmann
parents:
34269
diff
changeset
|
388 |
literal_numeral = numeral_haskell, |
970e1466028d
code literals: distinguish numeral classes by different entries
haftmann
parents:
34269
diff
changeset
|
389 |
literal_positive_numeral = numeral_haskell, |
37958
9728342bcd56
another refinement chapter in the neverending numeral story
haftmann
parents:
37881
diff
changeset
|
390 |
literal_alternative_numeral = numeral_haskell, |
34944
970e1466028d
code literals: distinguish numeral classes by different entries
haftmann
parents:
34269
diff
changeset
|
391 |
literal_naive_numeral = numeral_haskell, |
34178
a78b8d5b91cb
take care for destructive print mode properly using dedicated pretty builders
haftmann
parents:
34085
diff
changeset
|
392 |
literal_list = enum "," "[" "]", |
28064 | 393 |
infix_cons = (5, ":") |
394 |
} end; |
|
395 |
||
28054 | 396 |
|
397 |
(** optional monad syntax **) |
|
398 |
||
399 |
fun pretty_haskell_monad c_bind = |
|
400 |
let |
|
31874 | 401 |
fun dest_bind t1 t2 = case Code_Thingol.split_pat_abs t2 |
31889 | 402 |
of SOME ((pat, ty), t') => |
403 |
SOME ((SOME ((pat, ty), true), t1), t') |
|
28145 | 404 |
| NONE => NONE; |
28663
bd8438543bf2
code identifier namings are no longer imperative
haftmann
parents:
28350
diff
changeset
|
405 |
fun dest_monad c_bind_name (IConst (c, _) `$ t1 `$ t2) = |
bd8438543bf2
code identifier namings are no longer imperative
haftmann
parents:
28350
diff
changeset
|
406 |
if c = c_bind_name then dest_bind t1 t2 |
28145 | 407 |
else NONE |
28663
bd8438543bf2
code identifier namings are no longer imperative
haftmann
parents:
28350
diff
changeset
|
408 |
| dest_monad _ t = case Code_Thingol.split_let t |
28145 | 409 |
of SOME (((pat, ty), tbind), t') => |
31889 | 410 |
SOME ((SOME ((pat, ty), false), tbind), t') |
28145 | 411 |
| NONE => NONE; |
28663
bd8438543bf2
code identifier namings are no longer imperative
haftmann
parents:
28350
diff
changeset
|
412 |
fun implode_monad c_bind_name = Code_Thingol.unfoldr (dest_monad c_bind_name); |
33991 | 413 |
fun print_monad print_bind print_term (NONE, t) vars = |
414 |
(semicolon [print_term vars NOBR t], vars) |
|
415 |
| print_monad print_bind print_term (SOME ((bind, _), true), t) vars = vars |
|
416 |
|> print_bind NOBR bind |
|
417 |
|>> (fn p => semicolon [p, str "<-", print_term vars NOBR t]) |
|
418 |
| print_monad print_bind print_term (SOME ((bind, _), false), t) vars = vars |
|
419 |
|> print_bind NOBR bind |
|
37832 | 420 |
|>> (fn p => semicolon [str "let", str "{", p, str "=", print_term vars NOBR t, str "}"]); |
33991 | 421 |
fun pretty _ [c_bind'] print_term thm vars fxy [(t1, _), (t2, _)] = case dest_bind t1 t2 |
28145 | 422 |
of SOME (bind, t') => let |
31054 | 423 |
val (binds, t'') = implode_monad c_bind' t' |
33991 | 424 |
val (ps, vars') = fold_map (print_monad (gen_print_bind (K print_term) thm) print_term) |
425 |
(bind :: binds) vars; |
|
426 |
in |
|
37833
1381665d9550
more consistent spacing in generated monadic code
haftmann
parents:
37832
diff
changeset
|
427 |
(brackify fxy o single o enclose "do { " " }" o Pretty.breaks) |
33991 | 428 |
(ps @| print_term vars' NOBR t'') |
429 |
end |
|
28145 | 430 |
| NONE => brackify_infix (1, L) fxy |
37242
97097e589715
brackify_infix etc.: no break before infix operator -- eases survival in Scala
haftmann
parents:
36960
diff
changeset
|
431 |
(print_term vars (INFX (1, L)) t1, str ">>=", print_term vars (INFX (1, X)) t2) |
31054 | 432 |
in (2, ([c_bind], pretty)) end; |
28054 | 433 |
|
28145 | 434 |
fun add_monad target' raw_c_bind thy = |
28054 | 435 |
let |
31156 | 436 |
val c_bind = Code.read_const thy raw_c_bind; |
28054 | 437 |
in if target = target' then |
438 |
thy |
|
38923 | 439 |
|> Code_Target.add_const_syntax target c_bind |
37881 | 440 |
(SOME (Code_Printer.complex_const_syntax (pretty_haskell_monad c_bind))) |
28054 | 441 |
else error "Only Haskell target allows for monad syntax" end; |
442 |
||
443 |
||
444 |
(** Isar setup **) |
|
445 |
||
446 |
val _ = |
|
36960
01594f816e3a
prefer structure Keyword, Parse, Parse_Spec, Outer_Syntax;
wenzelm
parents:
36576
diff
changeset
|
447 |
Outer_Syntax.command "code_monad" "define code syntax for monads" Keyword.thy_decl ( |
01594f816e3a
prefer structure Keyword, Parse, Parse_Spec, Outer_Syntax;
wenzelm
parents:
36576
diff
changeset
|
448 |
Parse.term_group -- Parse.name >> (fn (raw_bind, target) => |
28145 | 449 |
Toplevel.theory (add_monad target raw_bind)) |
28054 | 450 |
); |
451 |
||
452 |
val setup = |
|
37821 | 453 |
Code_Target.add_target |
38966 | 454 |
(target, { serializer = serializer, literals = literals, |
37822
cf3588177676
use generic description slot for formal code checking
haftmann
parents:
37821
diff
changeset
|
455 |
check = { env_var = "EXEC_GHC", make_destination = I, |
38863
9070a7c356c9
code checking: compiler invocation happens in same directory as generated file -- avoid problem with different path representations on cygwin
haftmann
parents:
38779
diff
changeset
|
456 |
make_command = fn ghc => fn module_name => |
37822
cf3588177676
use generic description slot for formal code checking
haftmann
parents:
37821
diff
changeset
|
457 |
ghc ^ " -fglasgow-exts -odir build -hidir build -stubdir build -e \"\" " ^ module_name ^ ".hs" } }) |
38923 | 458 |
#> Code_Target.add_tyco_syntax target "fun" (SOME (2, fn print_typ => fn fxy => fn [ty1, ty2] => |
37242
97097e589715
brackify_infix etc.: no break before infix operator -- eases survival in Scala
haftmann
parents:
36960
diff
changeset
|
459 |
brackify_infix (1, R) fxy ( |
33991 | 460 |
print_typ (INFX (1, X)) ty1, |
28054 | 461 |
str "->", |
33991 | 462 |
print_typ (INFX (1, R)) ty2 |
37242
97097e589715
brackify_infix etc.: no break before infix operator -- eases survival in Scala
haftmann
parents:
36960
diff
changeset
|
463 |
))) |
28054 | 464 |
#> fold (Code_Target.add_reserved target) [ |
465 |
"hiding", "deriving", "where", "case", "of", "infix", "infixl", "infixr", |
|
466 |
"import", "default", "forall", "let", "in", "class", "qualified", "data", |
|
467 |
"newtype", "instance", "if", "then", "else", "type", "as", "do", "module" |
|
468 |
] |
|
469 |
#> fold (Code_Target.add_reserved target) [ |
|
470 |
"Prelude", "Main", "Bool", "Maybe", "Either", "Ordering", "Char", "String", "Int", |
|
471 |
"Integer", "Float", "Double", "Rational", "IO", "Eq", "Ord", "Enum", "Bounded", |
|
472 |
"Num", "Real", "Integral", "Fractional", "Floating", "RealFloat", "Monad", "Functor", |
|
473 |
"AlreadyExists", "ArithException", "ArrayException", "AssertionFailed", "AsyncException", |
|
474 |
"BlockedOnDeadMVar", "Deadlock", "Denormal", "DivideByZero", "DotNetException", "DynException", |
|
475 |
"Dynamic", "EOF", "EQ", "EmptyRec", "ErrorCall", "ExitException", "ExitFailure", |
|
476 |
"ExitSuccess", "False", "GT", "HeapOverflow", |
|
477 |
"IOError", "IOException", "IllegalOperation", |
|
478 |
"IndexOutOfBounds", "Just", "Key", "LT", "Left", "LossOfPrecision", "NoMethodError", |
|
479 |
"NoSuchThing", "NonTermination", "Nothing", "Obj", "OtherError", "Overflow", |
|
480 |
"PatternMatchFail", "PermissionDenied", "ProtocolError", "RecConError", "RecSelError", |
|
481 |
"RecUpdError", "ResourceBusy", "ResourceExhausted", "Right", "StackOverflow", |
|
482 |
"ThreadKilled", "True", "TyCon", "TypeRep", "UndefinedElement", "Underflow", |
|
483 |
"UnsupportedOperation", "UserError", "abs", "absReal", "acos", "acosh", "all", |
|
484 |
"and", "any", "appendFile", "asTypeOf", "asciiTab", "asin", "asinh", "atan", |
|
485 |
"atan2", "atanh", "basicIORun", "blockIO", "boundedEnumFrom", "boundedEnumFromThen", |
|
486 |
"boundedEnumFromThenTo", "boundedEnumFromTo", "boundedPred", "boundedSucc", "break", |
|
487 |
"catch", "catchException", "ceiling", "compare", "concat", "concatMap", "const", |
|
488 |
"cos", "cosh", "curry", "cycle", "decodeFloat", "denominator", "div", "divMod", |
|
489 |
"doubleToRatio", "doubleToRational", "drop", "dropWhile", "either", "elem", |
|
490 |
"emptyRec", "encodeFloat", "enumFrom", "enumFromThen", "enumFromThenTo", |
|
491 |
"enumFromTo", "error", "even", "exp", "exponent", "fail", "filter", "flip", |
|
492 |
"floatDigits", "floatProperFraction", "floatRadix", "floatRange", "floatToRational", |
|
493 |
"floor", "fmap", "foldl", "foldl'", "foldl1", "foldr", "foldr1", "fromDouble", |
|
494 |
"fromEnum", "fromEnum_0", "fromInt", "fromInteger", "fromIntegral", "fromObj", |
|
495 |
"fromRational", "fst", "gcd", "getChar", "getContents", "getLine", "head", |
|
496 |
"id", "inRange", "index", "init", "intToRatio", "interact", "ioError", "isAlpha", |
|
497 |
"isAlphaNum", "isDenormalized", "isDigit", "isHexDigit", "isIEEE", "isInfinite", |
|
498 |
"isLower", "isNaN", "isNegativeZero", "isOctDigit", "isSpace", "isUpper", "iterate", "iterate'", |
|
499 |
"last", "lcm", "length", "lex", "lexDigits", "lexLitChar", "lexmatch", "lines", "log", |
|
500 |
"logBase", "lookup", "loop", "map", "mapM", "mapM_", "max", "maxBound", "maximum", |
|
501 |
"maybe", "min", "minBound", "minimum", "mod", "negate", "nonnull", "not", "notElem", |
|
502 |
"null", "numerator", "numericEnumFrom", "numericEnumFromThen", "numericEnumFromThenTo", |
|
503 |
"numericEnumFromTo", "odd", "or", "otherwise", "pi", "pred", |
|
504 |
"print", "product", "properFraction", "protectEsc", "putChar", "putStr", "putStrLn", |
|
505 |
"quot", "quotRem", "range", "rangeSize", "rationalToDouble", "rationalToFloat", |
|
506 |
"rationalToRealFloat", "read", "readDec", "readField", "readFieldName", "readFile", |
|
507 |
"readFloat", "readHex", "readIO", "readInt", "readList", "readLitChar", "readLn", |
|
508 |
"readOct", "readParen", "readSigned", "reads", "readsPrec", "realFloatToRational", |
|
509 |
"realToFrac", "recip", "reduce", "rem", "repeat", "replicate", "return", "reverse", |
|
510 |
"round", "scaleFloat", "scanl", "scanl1", "scanr", "scanr1", "seq", "sequence", |
|
511 |
"sequence_", "show", "showChar", "showException", "showField", "showList", |
|
512 |
"showLitChar", "showParen", "showString", "shows", "showsPrec", "significand", |
|
513 |
"signum", "signumReal", "sin", "sinh", "snd", "span", "splitAt", "sqrt", "subtract", |
|
514 |
"succ", "sum", "tail", "take", "takeWhile", "takeWhile1", "tan", "tanh", "threadToIOResult", |
|
515 |
"throw", "toEnum", "toInt", "toInteger", "toObj", "toRational", "truncate", "uncurry", |
|
516 |
"undefined", "unlines", "unsafeCoerce", "unsafeIndex", "unsafeRangeSize", "until", "unwords", |
|
517 |
"unzip", "unzip3", "userError", "words", "writeFile", "zip", "zip3", "zipWith", "zipWith3" |
|
518 |
] (*due to weird handling of ':', we can't do anything else than to import *all* prelude symbols*); |
|
519 |
||
520 |
end; (*struct*) |