28054
|
1 |
(* Title: Tools/code/code_haskell.ML
|
|
2 |
ID: $Id$
|
|
3 |
Author: Florian Haftmann, TU Muenchen
|
|
4 |
|
|
5 |
Serializer for Haskell.
|
|
6 |
*)
|
|
7 |
|
|
8 |
signature CODE_HASKELL =
|
|
9 |
sig
|
|
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 |
|
|
27 |
fun pr_haskell_bind pr_term =
|
|
28 |
let
|
|
29 |
fun pr_bind ((NONE, NONE), _) = str "_"
|
|
30 |
| pr_bind ((SOME v, NONE), _) = str v
|
|
31 |
| pr_bind ((NONE, SOME p), _) = p
|
|
32 |
| pr_bind ((SOME v, SOME p), _) = brackets [str v, str "@", p];
|
|
33 |
in gen_pr_bind pr_bind pr_term end;
|
|
34 |
|
|
35 |
fun pr_haskell_stmt syntax_class syntax_tyco syntax_const labelled_name
|
|
36 |
init_syms deresolve is_cons contr_classparam_typs deriving_show =
|
|
37 |
let
|
|
38 |
val deresolve_base = NameSpace.base o deresolve;
|
|
39 |
fun class_name class = case syntax_class class
|
|
40 |
of NONE => deresolve class
|
|
41 |
| SOME (class, _) => class;
|
|
42 |
fun classparam_name class classparam = case syntax_class class
|
|
43 |
of NONE => deresolve_base classparam
|
|
44 |
| SOME (_, classparam_syntax) => case classparam_syntax classparam
|
|
45 |
of NONE => (snd o dest_name) classparam
|
|
46 |
| SOME classparam => classparam;
|
|
47 |
fun pr_typcontext tyvars vs = case maps (fn (v, sort) => map (pair v) sort) vs
|
|
48 |
of [] => []
|
|
49 |
| classbinds => Pretty.enum "," "(" ")" (
|
|
50 |
map (fn (v, class) =>
|
|
51 |
str (class_name class ^ " " ^ lookup_var tyvars v)) classbinds)
|
|
52 |
@@ str " => ";
|
|
53 |
fun pr_typforall tyvars vs = case map fst vs
|
|
54 |
of [] => []
|
|
55 |
| vnames => str "forall " :: Pretty.breaks
|
|
56 |
(map (str o lookup_var tyvars) vnames) @ str "." @@ Pretty.brk 1;
|
|
57 |
fun pr_tycoexpr tyvars fxy (tyco, tys) =
|
|
58 |
brackify fxy (str tyco :: map (pr_typ tyvars BR) tys)
|
|
59 |
and pr_typ tyvars fxy (tycoexpr as tyco `%% tys) = (case syntax_tyco tyco
|
|
60 |
of NONE => pr_tycoexpr tyvars fxy (deresolve tyco, tys)
|
|
61 |
| SOME (i, pr) => pr (pr_typ tyvars) fxy tys)
|
|
62 |
| pr_typ tyvars fxy (ITyVar v) = (str o lookup_var tyvars) v;
|
|
63 |
fun pr_typdecl tyvars (vs, tycoexpr) =
|
|
64 |
Pretty.block (pr_typcontext tyvars vs @| pr_tycoexpr tyvars NOBR tycoexpr);
|
|
65 |
fun pr_typscheme tyvars (vs, ty) =
|
|
66 |
Pretty.block (pr_typforall tyvars vs @ pr_typcontext tyvars vs @| pr_typ tyvars NOBR ty);
|
|
67 |
fun pr_term tyvars thm pat vars fxy (IConst c) =
|
|
68 |
pr_app tyvars thm pat vars fxy (c, [])
|
|
69 |
| pr_term tyvars thm pat vars fxy (t as (t1 `$ t2)) =
|
|
70 |
(case Code_Thingol.unfold_const_app t
|
|
71 |
of SOME app => pr_app tyvars thm pat vars fxy app
|
|
72 |
| _ =>
|
|
73 |
brackify fxy [
|
|
74 |
pr_term tyvars thm pat vars NOBR t1,
|
|
75 |
pr_term tyvars thm pat vars BR t2
|
|
76 |
])
|
|
77 |
| pr_term tyvars thm pat vars fxy (IVar v) =
|
|
78 |
(str o lookup_var vars) v
|
|
79 |
| pr_term tyvars thm pat vars fxy (t as _ `|-> _) =
|
|
80 |
let
|
|
81 |
val (binds, t') = Code_Thingol.unfold_abs t;
|
|
82 |
fun pr ((v, pat), ty) = pr_bind tyvars thm BR ((SOME v, pat), ty);
|
|
83 |
val (ps, vars') = fold_map pr binds vars;
|
|
84 |
in brackets (str "\\" :: ps @ str "->" @@ pr_term tyvars thm pat vars' NOBR t') end
|
|
85 |
| pr_term tyvars thm pat vars fxy (ICase (cases as (_, t0))) =
|
|
86 |
(case Code_Thingol.unfold_const_app t0
|
|
87 |
of SOME (c_ts as ((c, _), _)) => if is_none (syntax_const c)
|
|
88 |
then pr_case tyvars thm vars fxy cases
|
|
89 |
else pr_app tyvars thm pat vars fxy c_ts
|
|
90 |
| NONE => pr_case tyvars thm vars fxy cases)
|
|
91 |
and pr_app' tyvars thm pat vars ((c, (_, tys)), ts) = case contr_classparam_typs c
|
|
92 |
of [] => (str o deresolve) c :: map (pr_term tyvars thm pat vars BR) ts
|
|
93 |
| fingerprint => let
|
|
94 |
val ts_fingerprint = ts ~~ curry Library.take (length ts) fingerprint;
|
|
95 |
val needs_annotation = forall (fn (_, NONE) => true | (t, SOME _) =>
|
|
96 |
(not o Code_Thingol.locally_monomorphic) t) ts_fingerprint;
|
|
97 |
fun pr_term_anno (t, NONE) _ = pr_term tyvars thm pat vars BR t
|
|
98 |
| pr_term_anno (t, SOME _) ty =
|
|
99 |
brackets [pr_term tyvars thm pat vars NOBR t, str "::", pr_typ tyvars NOBR ty];
|
|
100 |
in
|
|
101 |
if needs_annotation then
|
|
102 |
(str o deresolve) c :: map2 pr_term_anno ts_fingerprint (curry Library.take (length ts) tys)
|
|
103 |
else (str o deresolve) c :: map (pr_term tyvars thm pat vars BR) ts
|
|
104 |
end
|
|
105 |
and pr_app tyvars = gen_pr_app (pr_app' tyvars) (pr_term tyvars) syntax_const is_cons
|
|
106 |
and pr_bind tyvars = pr_haskell_bind (pr_term tyvars)
|
|
107 |
and pr_case tyvars thm vars fxy (cases as ((_, [_]), _)) =
|
|
108 |
let
|
|
109 |
val (binds, t) = Code_Thingol.unfold_let (ICase cases);
|
|
110 |
fun pr ((pat, ty), t) vars =
|
|
111 |
vars
|
|
112 |
|> pr_bind tyvars thm BR ((NONE, SOME pat), ty)
|
|
113 |
|>> (fn p => semicolon [p, str "=", pr_term tyvars thm false vars NOBR t])
|
|
114 |
val (ps, vars') = fold_map pr binds vars;
|
|
115 |
in
|
|
116 |
Pretty.block_enclose (
|
|
117 |
str "let {",
|
|
118 |
concat [str "}", str "in", pr_term tyvars thm false vars' NOBR t]
|
|
119 |
) ps
|
|
120 |
end
|
|
121 |
| pr_case tyvars thm vars fxy (((td, ty), bs as _ :: _), _) =
|
|
122 |
let
|
|
123 |
fun pr (pat, t) =
|
|
124 |
let
|
|
125 |
val (p, vars') = pr_bind tyvars thm NOBR ((NONE, SOME pat), ty) vars;
|
|
126 |
in semicolon [p, str "->", pr_term tyvars thm false vars' NOBR t] end;
|
|
127 |
in
|
|
128 |
Pretty.block_enclose (
|
|
129 |
concat [str "(case", pr_term tyvars thm false vars NOBR td, str "of", str "{"],
|
|
130 |
str "})"
|
|
131 |
) (map pr bs)
|
|
132 |
end
|
|
133 |
| pr_case tyvars thm vars fxy ((_, []), _) = str "error \"empty case\"";
|
|
134 |
fun pr_stmt (name, Code_Thingol.Fun ((vs, ty), [])) =
|
|
135 |
let
|
|
136 |
val tyvars = intro_vars (map fst vs) init_syms;
|
|
137 |
val n = (length o fst o Code_Thingol.unfold_fun) ty;
|
|
138 |
in
|
|
139 |
Pretty.chunks [
|
|
140 |
Pretty.block [
|
|
141 |
(str o suffix " ::" o deresolve_base) name,
|
|
142 |
Pretty.brk 1,
|
|
143 |
pr_typscheme tyvars (vs, ty),
|
|
144 |
str ";"
|
|
145 |
],
|
|
146 |
concat (
|
|
147 |
(str o deresolve_base) name
|
|
148 |
:: map str (replicate n "_")
|
|
149 |
@ str "="
|
|
150 |
:: str "error"
|
|
151 |
@@ (str o (fn s => s ^ ";") o ML_Syntax.print_string
|
|
152 |
o NameSpace.base o NameSpace.qualifier) name
|
|
153 |
)
|
|
154 |
]
|
|
155 |
end
|
28350
|
156 |
| pr_stmt (name, Code_Thingol.Fun ((vs, ty), raw_eqs)) =
|
28054
|
157 |
let
|
28350
|
158 |
val eqs = filter (snd o snd) raw_eqs;
|
28054
|
159 |
val tyvars = intro_vars (map fst vs) init_syms;
|
28350
|
160 |
fun pr_eq ((ts, t), (thm, _)) =
|
28054
|
161 |
let
|
|
162 |
val consts = map_filter
|
|
163 |
(fn c => if (is_some o syntax_const) c
|
|
164 |
then NONE else (SOME o NameSpace.base o deresolve) c)
|
|
165 |
((fold o Code_Thingol.fold_constnames) (insert (op =)) (t :: ts) []);
|
|
166 |
val vars = init_syms
|
|
167 |
|> intro_vars consts
|
|
168 |
|> intro_vars ((fold o Code_Thingol.fold_unbound_varnames)
|
|
169 |
(insert (op =)) ts []);
|
|
170 |
in
|
|
171 |
semicolon (
|
|
172 |
(str o deresolve_base) name
|
|
173 |
:: map (pr_term tyvars thm true vars BR) ts
|
|
174 |
@ str "="
|
|
175 |
@@ pr_term tyvars thm false vars NOBR t
|
|
176 |
)
|
|
177 |
end;
|
|
178 |
in
|
|
179 |
Pretty.chunks (
|
|
180 |
Pretty.block [
|
|
181 |
(str o suffix " ::" o deresolve_base) name,
|
|
182 |
Pretty.brk 1,
|
|
183 |
pr_typscheme tyvars (vs, ty),
|
|
184 |
str ";"
|
|
185 |
]
|
|
186 |
:: map pr_eq eqs
|
|
187 |
)
|
|
188 |
end
|
|
189 |
| pr_stmt (name, Code_Thingol.Datatype (vs, [])) =
|
|
190 |
let
|
|
191 |
val tyvars = intro_vars (map fst vs) init_syms;
|
|
192 |
in
|
|
193 |
semicolon [
|
|
194 |
str "data",
|
|
195 |
pr_typdecl tyvars (vs, (deresolve_base name, map (ITyVar o fst) vs))
|
|
196 |
]
|
|
197 |
end
|
|
198 |
| pr_stmt (name, Code_Thingol.Datatype (vs, [(co, [ty])])) =
|
|
199 |
let
|
|
200 |
val tyvars = intro_vars (map fst vs) init_syms;
|
|
201 |
in
|
|
202 |
semicolon (
|
|
203 |
str "newtype"
|
|
204 |
:: pr_typdecl tyvars (vs, (deresolve_base name, map (ITyVar o fst) vs))
|
|
205 |
:: str "="
|
|
206 |
:: (str o deresolve_base) co
|
|
207 |
:: pr_typ tyvars BR ty
|
|
208 |
:: (if deriving_show name then [str "deriving (Read, Show)"] else [])
|
|
209 |
)
|
|
210 |
end
|
|
211 |
| pr_stmt (name, Code_Thingol.Datatype (vs, co :: cos)) =
|
|
212 |
let
|
|
213 |
val tyvars = intro_vars (map fst vs) init_syms;
|
|
214 |
fun pr_co (co, tys) =
|
|
215 |
concat (
|
|
216 |
(str o deresolve_base) co
|
|
217 |
:: map (pr_typ tyvars BR) tys
|
|
218 |
)
|
|
219 |
in
|
|
220 |
semicolon (
|
|
221 |
str "data"
|
|
222 |
:: pr_typdecl tyvars (vs, (deresolve_base name, map (ITyVar o fst) vs))
|
|
223 |
:: str "="
|
|
224 |
:: pr_co co
|
|
225 |
:: map ((fn p => Pretty.block [str "| ", p]) o pr_co) cos
|
|
226 |
@ (if deriving_show name then [str "deriving (Read, Show)"] else [])
|
|
227 |
)
|
|
228 |
end
|
|
229 |
| pr_stmt (name, Code_Thingol.Class (v, (superclasses, classparams))) =
|
|
230 |
let
|
|
231 |
val tyvars = intro_vars [v] init_syms;
|
|
232 |
fun pr_classparam (classparam, ty) =
|
|
233 |
semicolon [
|
|
234 |
(str o classparam_name name) classparam,
|
|
235 |
str "::",
|
|
236 |
pr_typ tyvars NOBR ty
|
|
237 |
]
|
|
238 |
in
|
|
239 |
Pretty.block_enclose (
|
|
240 |
Pretty.block [
|
|
241 |
str "class ",
|
|
242 |
Pretty.block (pr_typcontext tyvars [(v, map fst superclasses)]),
|
|
243 |
str (deresolve_base name ^ " " ^ lookup_var tyvars v),
|
|
244 |
str " where {"
|
|
245 |
],
|
|
246 |
str "};"
|
|
247 |
) (map pr_classparam classparams)
|
|
248 |
end
|
|
249 |
| pr_stmt (_, Code_Thingol.Classinst ((class, (tyco, vs)), (_, classparam_insts))) =
|
|
250 |
let
|
|
251 |
val tyvars = intro_vars (map fst vs) init_syms;
|
28350
|
252 |
fun pr_instdef ((classparam, c_inst), (thm, _)) =
|
28054
|
253 |
semicolon [
|
|
254 |
(str o classparam_name class) classparam,
|
|
255 |
str "=",
|
|
256 |
pr_app tyvars thm false init_syms NOBR (c_inst, [])
|
|
257 |
];
|
|
258 |
in
|
|
259 |
Pretty.block_enclose (
|
|
260 |
Pretty.block [
|
|
261 |
str "instance ",
|
|
262 |
Pretty.block (pr_typcontext tyvars vs),
|
|
263 |
str (class_name class ^ " "),
|
|
264 |
pr_typ tyvars BR (tyco `%% map (ITyVar o fst) vs),
|
|
265 |
str " where {"
|
|
266 |
],
|
|
267 |
str "};"
|
|
268 |
) (map pr_instdef classparam_insts)
|
|
269 |
end;
|
|
270 |
in pr_stmt end;
|
|
271 |
|
|
272 |
fun haskell_program_of_program labelled_name module_name module_prefix reserved_names raw_module_alias program =
|
|
273 |
let
|
|
274 |
val module_alias = if is_some module_name then K module_name else raw_module_alias;
|
|
275 |
val reserved_names = Name.make_context reserved_names;
|
|
276 |
val mk_name_module = mk_name_module reserved_names module_prefix module_alias program;
|
|
277 |
fun add_stmt (name, (stmt, deps)) =
|
|
278 |
let
|
|
279 |
val (module_name, base) = dest_name name;
|
|
280 |
val module_name' = mk_name_module module_name;
|
|
281 |
val mk_name_stmt = yield_singleton Name.variants;
|
|
282 |
fun add_fun upper (nsp_fun, nsp_typ) =
|
|
283 |
let
|
|
284 |
val (base', nsp_fun') =
|
|
285 |
mk_name_stmt (if upper then first_upper base else base) nsp_fun
|
|
286 |
in (base', (nsp_fun', nsp_typ)) end;
|
|
287 |
fun add_typ (nsp_fun, nsp_typ) =
|
|
288 |
let
|
|
289 |
val (base', nsp_typ') = mk_name_stmt (first_upper base) nsp_typ
|
|
290 |
in (base', (nsp_fun, nsp_typ')) end;
|
|
291 |
val add_name = case stmt
|
|
292 |
of Code_Thingol.Fun _ => add_fun false
|
|
293 |
| Code_Thingol.Datatype _ => add_typ
|
|
294 |
| Code_Thingol.Datatypecons _ => add_fun true
|
|
295 |
| Code_Thingol.Class _ => add_typ
|
|
296 |
| Code_Thingol.Classrel _ => pair base
|
|
297 |
| Code_Thingol.Classparam _ => add_fun false
|
|
298 |
| Code_Thingol.Classinst _ => pair base;
|
|
299 |
fun add_stmt' base' = case stmt
|
|
300 |
of Code_Thingol.Datatypecons _ =>
|
|
301 |
cons (name, (NameSpace.append module_name' base', NONE))
|
|
302 |
| Code_Thingol.Classrel _ => I
|
|
303 |
| Code_Thingol.Classparam _ =>
|
|
304 |
cons (name, (NameSpace.append module_name' base', NONE))
|
|
305 |
| _ => cons (name, (NameSpace.append module_name' base', SOME stmt));
|
|
306 |
in
|
|
307 |
Symtab.map_default (module_name', ([], ([], (reserved_names, reserved_names))))
|
|
308 |
(apfst (fold (insert (op = : string * string -> bool)) deps))
|
|
309 |
#> `(fn program => add_name ((snd o snd o the o Symtab.lookup program) module_name'))
|
|
310 |
#-> (fn (base', names) =>
|
|
311 |
(Symtab.map_entry module_name' o apsnd) (fn (stmts, _) =>
|
|
312 |
(add_stmt' base' stmts, names)))
|
|
313 |
end;
|
|
314 |
val hs_program = fold add_stmt (AList.make (fn name =>
|
|
315 |
(Graph.get_node program name, Graph.imm_succs program name))
|
|
316 |
(Graph.strong_conn program |> flat)) Symtab.empty;
|
|
317 |
fun deresolver name =
|
|
318 |
(fst o the o AList.lookup (op =) ((fst o snd o the
|
|
319 |
o Symtab.lookup hs_program) ((mk_name_module o fst o dest_name) name))) name
|
|
320 |
handle Option => error ("Unknown statement name: " ^ labelled_name name);
|
|
321 |
in (deresolver, hs_program) end;
|
|
322 |
|
|
323 |
fun serialize_haskell module_prefix raw_module_name string_classes labelled_name
|
|
324 |
reserved_names includes raw_module_alias
|
|
325 |
syntax_class syntax_tyco syntax_const program cs destination =
|
|
326 |
let
|
|
327 |
val stmt_names = Code_Target.stmt_names_of_destination destination;
|
|
328 |
val module_name = if null stmt_names then raw_module_name else SOME "Code";
|
|
329 |
val (deresolver, hs_program) = haskell_program_of_program labelled_name
|
|
330 |
module_name module_prefix reserved_names raw_module_alias program;
|
|
331 |
val is_cons = Code_Thingol.is_cons program;
|
|
332 |
val contr_classparam_typs = Code_Thingol.contr_classparam_typs program;
|
|
333 |
fun deriving_show tyco =
|
|
334 |
let
|
|
335 |
fun deriv _ "fun" = false
|
|
336 |
| deriv tycos tyco = member (op =) tycos tyco orelse
|
|
337 |
case try (Graph.get_node program) tyco
|
|
338 |
of SOME (Code_Thingol.Datatype (_, cs)) => forall (deriv' (tyco :: tycos))
|
|
339 |
(maps snd cs)
|
|
340 |
| NONE => true
|
|
341 |
and deriv' tycos (tyco `%% tys) = deriv tycos tyco
|
|
342 |
andalso forall (deriv' tycos) tys
|
|
343 |
| deriv' _ (ITyVar _) = true
|
|
344 |
in deriv [] tyco end;
|
|
345 |
val reserved_names = make_vars reserved_names;
|
|
346 |
fun pr_stmt qualified = pr_haskell_stmt syntax_class syntax_tyco
|
|
347 |
syntax_const labelled_name reserved_names
|
|
348 |
(if qualified then deresolver else NameSpace.base o deresolver)
|
|
349 |
is_cons contr_classparam_typs
|
|
350 |
(if string_classes then deriving_show else K false);
|
|
351 |
fun pr_module name content =
|
|
352 |
(name, Pretty.chunks [
|
|
353 |
str ("module " ^ name ^ " where {"),
|
|
354 |
str "",
|
|
355 |
content,
|
|
356 |
str "",
|
|
357 |
str "}"
|
|
358 |
]);
|
|
359 |
fun serialize_module1 (module_name', (deps, (stmts, _))) =
|
|
360 |
let
|
|
361 |
val stmt_names = map fst stmts;
|
|
362 |
val deps' = subtract (op =) stmt_names deps
|
|
363 |
|> distinct (op =)
|
|
364 |
|> map_filter (try deresolver);
|
|
365 |
val qualified = is_none module_name andalso
|
|
366 |
map deresolver stmt_names @ deps'
|
|
367 |
|> map NameSpace.base
|
|
368 |
|> has_duplicates (op =);
|
|
369 |
val imports = deps'
|
|
370 |
|> map NameSpace.qualifier
|
|
371 |
|> distinct (op =);
|
|
372 |
fun pr_import_include (name, _) = str ("import " ^ name ^ ";");
|
|
373 |
val pr_import_module = str o (if qualified
|
|
374 |
then prefix "import qualified "
|
|
375 |
else prefix "import ") o suffix ";";
|
|
376 |
val content = Pretty.chunks (
|
|
377 |
map pr_import_include includes
|
|
378 |
@ map pr_import_module imports
|
|
379 |
@ str ""
|
|
380 |
:: separate (str "") (map_filter
|
|
381 |
(fn (name, (_, SOME stmt)) => SOME (pr_stmt qualified (name, stmt))
|
|
382 |
| (_, (_, NONE)) => NONE) stmts)
|
|
383 |
)
|
|
384 |
in pr_module module_name' content end;
|
|
385 |
fun serialize_module2 (_, (_, (stmts, _))) = Pretty.chunks (
|
|
386 |
separate (str "") (map_filter
|
|
387 |
(fn (name, (_, SOME stmt)) => if null stmt_names
|
|
388 |
orelse member (op =) stmt_names name
|
|
389 |
then SOME (pr_stmt false (name, stmt))
|
|
390 |
else NONE
|
|
391 |
| (_, (_, NONE)) => NONE) stmts));
|
|
392 |
val serialize_module =
|
|
393 |
if null stmt_names then serialize_module1 else pair "" o serialize_module2;
|
|
394 |
fun write_module destination (modlname, content) =
|
|
395 |
let
|
|
396 |
val filename = case modlname
|
|
397 |
of "" => Path.explode "Main.hs"
|
|
398 |
| _ => (Path.ext "hs" o Path.explode o implode o separate "/"
|
|
399 |
o NameSpace.explode) modlname;
|
|
400 |
val pathname = Path.append destination filename;
|
|
401 |
val _ = File.mkdir (Path.dir pathname);
|
|
402 |
in File.write pathname (Code_Target.code_of_pretty content) end
|
|
403 |
in
|
|
404 |
Code_Target.mk_serialization target NONE
|
|
405 |
(fn NONE => K () o map (Code_Target.code_writeln o snd) | SOME file => K () o map (write_module file))
|
|
406 |
(rpair [] o cat_lines o map (Code_Target.code_of_pretty o snd))
|
|
407 |
(map (uncurry pr_module) includes
|
|
408 |
@ map serialize_module (Symtab.dest hs_program))
|
|
409 |
destination
|
|
410 |
end;
|
|
411 |
|
28064
|
412 |
val literals = let
|
|
413 |
fun char_haskell c =
|
|
414 |
let
|
|
415 |
val s = ML_Syntax.print_char c;
|
|
416 |
in if s = "'" then "\\'" else s end;
|
|
417 |
in Literals {
|
|
418 |
literal_char = enclose "'" "'" o char_haskell,
|
|
419 |
literal_string = quote o translate_string char_haskell,
|
|
420 |
literal_numeral = fn unbounded => fn k => if k >= 0 then string_of_int k
|
|
421 |
else enclose "(" ")" (signed_string_of_int k),
|
|
422 |
literal_list = Pretty.enum "," "[" "]",
|
|
423 |
infix_cons = (5, ":")
|
|
424 |
} end;
|
|
425 |
|
28054
|
426 |
|
|
427 |
(** optional monad syntax **)
|
|
428 |
|
|
429 |
fun pretty_haskell_monad c_bind =
|
|
430 |
let
|
28145
|
431 |
fun dest_bind t1 t2 = case Code_Thingol.split_abs t2
|
|
432 |
of SOME (((v, pat), ty), t') =>
|
|
433 |
SOME ((SOME (((SOME v, pat), ty), true), t1), t')
|
|
434 |
| NONE => NONE;
|
|
435 |
fun dest_monad (IConst (c, _) `$ t1 `$ t2) =
|
|
436 |
if c = c_bind then dest_bind t1 t2
|
|
437 |
else NONE
|
|
438 |
| dest_monad t = case Code_Thingol.split_let t
|
|
439 |
of SOME (((pat, ty), tbind), t') =>
|
|
440 |
SOME ((SOME (((NONE, SOME pat), ty), false), tbind), t')
|
|
441 |
| NONE => NONE;
|
|
442 |
val implode_monad = Code_Thingol.unfoldr dest_monad;
|
|
443 |
fun pr_monad pr_bind pr (NONE, t) vars =
|
|
444 |
(semicolon [pr vars NOBR t], vars)
|
|
445 |
| pr_monad pr_bind pr (SOME (bind, true), t) vars = vars
|
|
446 |
|> pr_bind NOBR bind
|
|
447 |
|>> (fn p => semicolon [p, str "<-", pr vars NOBR t])
|
|
448 |
| pr_monad pr_bind pr (SOME (bind, false), t) vars = vars
|
|
449 |
|> pr_bind NOBR bind
|
|
450 |
|>> (fn p => semicolon [str "let", p, str "=", pr vars NOBR t]);
|
|
451 |
fun pretty pr thm pat vars fxy [(t1, _), (t2, _)] = case dest_bind t1 t2
|
|
452 |
of SOME (bind, t') => let
|
|
453 |
val (binds, t'') = implode_monad t'
|
|
454 |
val (ps, vars') = fold_map (pr_monad (pr_haskell_bind (K (K pr)) thm) pr) (bind :: binds) vars;
|
|
455 |
in (brackify fxy o single o Pretty.enclose "do {" "}" o Pretty.breaks) (ps @| pr vars' NOBR t'') end
|
|
456 |
| NONE => brackify_infix (1, L) fxy
|
|
457 |
[pr vars (INFX (1, L)) t1, str ">>=", pr vars (INFX (1, X)) t2]
|
|
458 |
in (2, pretty) end;
|
28054
|
459 |
|
28145
|
460 |
fun add_monad target' raw_c_bind thy =
|
28054
|
461 |
let
|
|
462 |
val c_bind = Code_Unit.read_const thy raw_c_bind;
|
|
463 |
val c_bind' = Code_Name.const thy c_bind;
|
|
464 |
in if target = target' then
|
|
465 |
thy
|
28145
|
466 |
|> Code_Target.add_syntax_const target c_bind
|
28054
|
467 |
(SOME (pretty_haskell_monad c_bind'))
|
|
468 |
else error "Only Haskell target allows for monad syntax" end;
|
|
469 |
|
|
470 |
|
|
471 |
(** Isar setup **)
|
|
472 |
|
|
473 |
fun isar_seri_haskell module =
|
|
474 |
Code_Target.parse_args (Scan.option (Args.$$$ "root" -- Args.colon |-- Args.name)
|
|
475 |
-- Scan.optional (Args.$$$ "string_classes" >> K true) false
|
|
476 |
>> (fn (module_prefix, string_classes) =>
|
|
477 |
serialize_haskell module_prefix module string_classes));
|
|
478 |
|
|
479 |
val _ =
|
|
480 |
OuterSyntax.command "code_monad" "define code syntax for monads" OuterKeyword.thy_decl (
|
28145
|
481 |
OuterParse.term_group -- OuterParse.name >> (fn (raw_bind, target) =>
|
|
482 |
Toplevel.theory (add_monad target raw_bind))
|
28054
|
483 |
);
|
|
484 |
|
|
485 |
val setup =
|
28064
|
486 |
Code_Target.add_target (target, (isar_seri_haskell, literals))
|
28054
|
487 |
#> Code_Target.add_syntax_tyco target "fun" (SOME (2, fn pr_typ => fn fxy => fn [ty1, ty2] =>
|
|
488 |
brackify_infix (1, R) fxy [
|
|
489 |
pr_typ (INFX (1, X)) ty1,
|
|
490 |
str "->",
|
|
491 |
pr_typ (INFX (1, R)) ty2
|
|
492 |
]))
|
|
493 |
#> fold (Code_Target.add_reserved target) [
|
|
494 |
"hiding", "deriving", "where", "case", "of", "infix", "infixl", "infixr",
|
|
495 |
"import", "default", "forall", "let", "in", "class", "qualified", "data",
|
|
496 |
"newtype", "instance", "if", "then", "else", "type", "as", "do", "module"
|
|
497 |
]
|
|
498 |
#> fold (Code_Target.add_reserved target) [
|
|
499 |
"Prelude", "Main", "Bool", "Maybe", "Either", "Ordering", "Char", "String", "Int",
|
|
500 |
"Integer", "Float", "Double", "Rational", "IO", "Eq", "Ord", "Enum", "Bounded",
|
|
501 |
"Num", "Real", "Integral", "Fractional", "Floating", "RealFloat", "Monad", "Functor",
|
|
502 |
"AlreadyExists", "ArithException", "ArrayException", "AssertionFailed", "AsyncException",
|
|
503 |
"BlockedOnDeadMVar", "Deadlock", "Denormal", "DivideByZero", "DotNetException", "DynException",
|
|
504 |
"Dynamic", "EOF", "EQ", "EmptyRec", "ErrorCall", "ExitException", "ExitFailure",
|
|
505 |
"ExitSuccess", "False", "GT", "HeapOverflow",
|
|
506 |
"IOError", "IOException", "IllegalOperation",
|
|
507 |
"IndexOutOfBounds", "Just", "Key", "LT", "Left", "LossOfPrecision", "NoMethodError",
|
|
508 |
"NoSuchThing", "NonTermination", "Nothing", "Obj", "OtherError", "Overflow",
|
|
509 |
"PatternMatchFail", "PermissionDenied", "ProtocolError", "RecConError", "RecSelError",
|
|
510 |
"RecUpdError", "ResourceBusy", "ResourceExhausted", "Right", "StackOverflow",
|
|
511 |
"ThreadKilled", "True", "TyCon", "TypeRep", "UndefinedElement", "Underflow",
|
|
512 |
"UnsupportedOperation", "UserError", "abs", "absReal", "acos", "acosh", "all",
|
|
513 |
"and", "any", "appendFile", "asTypeOf", "asciiTab", "asin", "asinh", "atan",
|
|
514 |
"atan2", "atanh", "basicIORun", "blockIO", "boundedEnumFrom", "boundedEnumFromThen",
|
|
515 |
"boundedEnumFromThenTo", "boundedEnumFromTo", "boundedPred", "boundedSucc", "break",
|
|
516 |
"catch", "catchException", "ceiling", "compare", "concat", "concatMap", "const",
|
|
517 |
"cos", "cosh", "curry", "cycle", "decodeFloat", "denominator", "div", "divMod",
|
|
518 |
"doubleToRatio", "doubleToRational", "drop", "dropWhile", "either", "elem",
|
|
519 |
"emptyRec", "encodeFloat", "enumFrom", "enumFromThen", "enumFromThenTo",
|
|
520 |
"enumFromTo", "error", "even", "exp", "exponent", "fail", "filter", "flip",
|
|
521 |
"floatDigits", "floatProperFraction", "floatRadix", "floatRange", "floatToRational",
|
|
522 |
"floor", "fmap", "foldl", "foldl'", "foldl1", "foldr", "foldr1", "fromDouble",
|
|
523 |
"fromEnum", "fromEnum_0", "fromInt", "fromInteger", "fromIntegral", "fromObj",
|
|
524 |
"fromRational", "fst", "gcd", "getChar", "getContents", "getLine", "head",
|
|
525 |
"id", "inRange", "index", "init", "intToRatio", "interact", "ioError", "isAlpha",
|
|
526 |
"isAlphaNum", "isDenormalized", "isDigit", "isHexDigit", "isIEEE", "isInfinite",
|
|
527 |
"isLower", "isNaN", "isNegativeZero", "isOctDigit", "isSpace", "isUpper", "iterate", "iterate'",
|
|
528 |
"last", "lcm", "length", "lex", "lexDigits", "lexLitChar", "lexmatch", "lines", "log",
|
|
529 |
"logBase", "lookup", "loop", "map", "mapM", "mapM_", "max", "maxBound", "maximum",
|
|
530 |
"maybe", "min", "minBound", "minimum", "mod", "negate", "nonnull", "not", "notElem",
|
|
531 |
"null", "numerator", "numericEnumFrom", "numericEnumFromThen", "numericEnumFromThenTo",
|
|
532 |
"numericEnumFromTo", "odd", "or", "otherwise", "pi", "pred",
|
|
533 |
"print", "product", "properFraction", "protectEsc", "putChar", "putStr", "putStrLn",
|
|
534 |
"quot", "quotRem", "range", "rangeSize", "rationalToDouble", "rationalToFloat",
|
|
535 |
"rationalToRealFloat", "read", "readDec", "readField", "readFieldName", "readFile",
|
|
536 |
"readFloat", "readHex", "readIO", "readInt", "readList", "readLitChar", "readLn",
|
|
537 |
"readOct", "readParen", "readSigned", "reads", "readsPrec", "realFloatToRational",
|
|
538 |
"realToFrac", "recip", "reduce", "rem", "repeat", "replicate", "return", "reverse",
|
|
539 |
"round", "scaleFloat", "scanl", "scanl1", "scanr", "scanr1", "seq", "sequence",
|
|
540 |
"sequence_", "show", "showChar", "showException", "showField", "showList",
|
|
541 |
"showLitChar", "showParen", "showString", "shows", "showsPrec", "significand",
|
|
542 |
"signum", "signumReal", "sin", "sinh", "snd", "span", "splitAt", "sqrt", "subtract",
|
|
543 |
"succ", "sum", "tail", "take", "takeWhile", "takeWhile1", "tan", "tanh", "threadToIOResult",
|
|
544 |
"throw", "toEnum", "toInt", "toInteger", "toObj", "toRational", "truncate", "uncurry",
|
|
545 |
"undefined", "unlines", "unsafeCoerce", "unsafeIndex", "unsafeRangeSize", "until", "unwords",
|
|
546 |
"unzip", "unzip3", "userError", "words", "writeFile", "zip", "zip3", "zipWith", "zipWith3"
|
|
547 |
] (*due to weird handling of ':', we can't do anything else than to import *all* prelude symbols*);
|
|
548 |
|
|
549 |
end; (*struct*)
|