summaryrefslogtreecommitdiff
path: root/src/specialize.sml
blob: 33545250ba354913aad11476aec570bf9d029f44 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
(* Copyright (c) 2008-2010, Adam Chlipala
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * - The names of contributors may not be used to endorse or promote products
 *   derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *)

(* Simplify a Core program by repeating polymorphic definitions of datatypes *)

structure Specialize :> SPECIALIZE = struct

open Core

structure E = CoreEnv
structure U = CoreUtil

val liftConInCon = E.liftConInCon
val subConInCon = E.subConInCon

structure CK = struct
type ord_key = con list
val compare = Order.joinL U.Con.compare
end

structure CM = BinaryMapFn(CK)
structure IM = IntBinaryMap

type datatyp' = {
     name : int,
     constructors : int IM.map
}

type datatyp = {
     name : string,
     params : int,
     constructors : (string * int * con option) list,
     specializations : datatyp' CM.map
}

type state = {
     count : int,
     datatypes : datatyp IM.map,
     constructors : int IM.map,
     decls : (string * int * string list * (string * int * con option) list) list     
}

fun kind (k, st) = (k, st)

val isOpen = U.Con.exists {kind = fn _ => false,
                           con = fn c =>
                                    case c of
                                        CRel _ => true
                                      | _ => false}

fun considerSpecialization (st : state, n, args, dt : datatyp) =
    let
        val args = map ReduceLocal.reduceCon args
    in
        case CM.find (#specializations dt, args) of
            SOME dt' => (#name dt', #constructors dt', st)
          | NONE =>
            let
                (*val () = Print.prefaces "Args" [("n", Print.PD.string (Int.toString n)),
                                                ("args", Print.p_list (CorePrint.p_con CoreEnv.empty) args)]*)

                val n' = #count st

                val nxs = length args - 1
                fun sub t = ListUtil.foldli (fn (i, arg, t) =>
                                                subConInCon (nxs - i, arg) t) t args

                val (cons, (count, cmap)) =
                    ListUtil.foldlMap (fn ((x, n, to), (count, cmap)) =>
                                          let
                                              val to = Option.map sub to
                                          in
                                              ((x, count, to),
                                               (count + 1,
                                                IM.insert (cmap, n, count)))
                                          end) (n' + 1, IM.empty) (#constructors dt)

                val st = {count = count,
                          datatypes = IM.insert (#datatypes st, n,
                                                 {name = #name dt,
                                                  params = #params dt,
                                                  constructors = #constructors dt,
                                                  specializations = CM.insert (#specializations dt,
                                                                               args,
                                                                               {name = n',
                                                                                constructors = cmap})}),
                          constructors = #constructors st,
                          decls = #decls st}

                val (cons, st) = ListUtil.foldlMap (fn ((x, n, NONE), st) => ((x, n, NONE), st)
                                                     | ((x, n, SOME t), st) =>
                                                       let
                                                           val (t, st) = specCon st t
                                                       in
                                                           ((x, n, SOME t), st)
                                                       end) st cons

                val dt = (#name dt ^ "_s",
                          n',
                          [],
                          cons)
            in
                (n', cmap, {count = #count st,
                            datatypes = #datatypes st,
                            constructors = #constructors st,
                            decls = dt :: #decls st})
            end
    end

and con (c, st : state) =
    let
        fun findApp (c, args) =
            case c of
                CApp ((c', _), arg) => findApp (c', arg :: args)
              | CNamed n => SOME (n, args)
              | _ => NONE
    in
        case findApp (c, []) of
            SOME (n, args as (_ :: _)) =>
            if List.exists isOpen args then
                (c, st)
            else
                (case IM.find (#datatypes st, n) of
                     NONE => (c, st)
                   | SOME dt =>
                     if length args <> #params dt then
                         (c, st)
                     else
                         let
                             val (n, _, st) = considerSpecialization (st, n, args, dt)
                         in
                             (CNamed n, st)
                         end)
          | _ => (c, st)
    end

and specCon st = U.Con.foldMap {kind = kind, con = con} st

fun pat (p, st) =
    case #1 p of
        PVar _ => (p, st)
      | PPrim _ => (p, st)
      | PCon (dk, PConVar pn, args as (_ :: _), po) =>
        let
            val (po, st) =
                case po of
                    NONE => (NONE, st)
                  | SOME p =>
                    let
                        val (p, st) = pat (p, st)
                    in
                        (SOME p, st)
                    end
            val p = (PCon (dk, PConVar pn, args, po), #2 p)
        in
            if List.exists isOpen args then
                (p, st)
            else
                case IM.find (#constructors st, pn) of
                    NONE => (p, st)
                  | SOME n =>
                    case IM.find (#datatypes st, n) of
                        NONE => (p, st)
                      | SOME dt =>
                        let
                            val (n, cmap, st) = considerSpecialization (st, n, args, dt)
                        in
                            case IM.find (cmap, pn) of
                                NONE => raise Fail "Specialize: Missing datatype constructor (pat)"
                              | SOME pn' => ((PCon (dk, PConVar pn', [], po), #2 p), st)
                        end
        end
      | PCon (dk, pc, args, SOME p') =>
        let
            val (p', st) = pat (p', st)
        in
            ((PCon (dk, pc, args, SOME p'), #2 p), st)
        end
      | PCon _ => (p, st)
      | PRecord xps =>
        let
            val (xps, st) = ListUtil.foldlMap (fn ((x, p, t), st) =>
                                                  let
                                                      val (p, st) = pat (p, st)
                                                  in
                                                      ((x, p, t), st)
                                                  end)
                            st xps
        in
            ((PRecord xps, #2 p), st)
        end

fun exp (e, st) =
    case e of
        ECon (dk, PConVar pn, args as (_ :: _), eo) =>
        if List.exists isOpen args then
            (e, st)
        else
            (case IM.find (#constructors st, pn) of
                 NONE => (e, st)
               | SOME n =>
                 case IM.find (#datatypes st, n) of
                     NONE => (e, st)
                   | SOME dt =>
                     let
                         val (n, cmap, st) = considerSpecialization (st, n, args, dt)
                     in
                         case IM.find (cmap, pn) of
                             NONE => raise Fail "Specialize: Missing datatype constructor"
                           | SOME pn' => (ECon (dk, PConVar pn', [], eo), st)
                     end)
      | ECase (e, pes, r) =>
        let
            val (pes, st) = ListUtil.foldlMap (fn ((p, e), st) =>
                                                  let
                                                      val (p, st) = pat (p, st)
                                                  in
                                                      ((p, e), st)
                                                  end) st pes
        in
            (ECase (e, pes, r), st)
        end
      | _ => (e, st)

fun decl (d, st) = (d, st)

val specDecl = U.Decl.foldMap {kind = kind, con = con, exp = exp, decl = decl}

fun specialize file =
    let
        fun doDecl (d, st) =
            let
                (*val () = Print.preface ("decl:", CorePrint.p_decl CoreEnv.empty all)*)
                val (d, st) = specDecl st d
            in
                case #1 d of
                    DDatatype dts =>
                    ((case #decls st of
                          [] => [d]
                        | dts' => [(DDatatype (dts' @ dts), #2 d)]),
                     {count = #count st,
                      datatypes = foldl (fn ((x, n, xs, xnts), dts) =>
                                            IM.insert (dts, n,
                                                       {name = x,
                                                        params = length xs,
                                                        constructors = xnts,
                                                        specializations = CM.empty}))
                                        (#datatypes st) dts,
                      constructors = foldl (fn ((x, n, xs, xnts), cs) =>
                                               foldl (fn ((_, n', _), constructors) =>
                                                         IM.insert (constructors, n', n))
                                                     cs xnts)
                                           (#constructors st) dts,
                      decls = []})
                  | _ =>
                    (case #decls st of
                          [] => [d]
                        | dts => [(DDatatype dts, #2 d), d],
                     {count = #count st,
                      datatypes = #datatypes st,
                      constructors = #constructors st,
                      decls = []})
            end

        val (ds, _) = ListUtil.foldlMapConcat doDecl
                      {count = U.File.maxName file + 1,
                       datatypes = IM.empty,
                       constructors = IM.empty,
                       decls = []} file
    in
        ds
    end

end