annotate src/sqlcache.sml @ 2286:0bdfec16a01d

Fix issue with one-element caches. Locking still WIP.
author Ziv Scully <ziv@mit.edu>
date Fri, 13 Nov 2015 01:04:32 -0500
parents b7615e0ac4b0
children 98f96a976ede
rev   line source
ziv@2278 1 structure Sqlcache :> SQLCACHE = struct
ziv@2209 2
ziv@2286 3
ziv@2286 4 (*********************)
ziv@2286 5 (* General Utilities *)
ziv@2286 6 (*********************)
ziv@2209 7
ziv@2276 8 structure IK = struct type ord_key = int val compare = Int.compare end
ziv@2209 9 structure IS = IntBinarySet
ziv@2209 10 structure IM = IntBinaryMap
ziv@2213 11 structure SK = struct type ord_key = string val compare = String.compare end
ziv@2213 12 structure SS = BinarySetFn(SK)
ziv@2213 13 structure SM = BinaryMapFn(SK)
ziv@2286 14 structure IIMM = MultimapFn(structure KeyMap = IM structure ValSet = IS)
ziv@2213 15 structure SIMM = MultimapFn(structure KeyMap = SM structure ValSet = IS)
ziv@2209 16
ziv@2274 17 fun id x = x
ziv@2274 18
ziv@2250 19 fun iterate f n x = if n < 0
ziv@2250 20 then raise Fail "Can't iterate function negative number of times."
ziv@2250 21 else if n = 0
ziv@2250 22 then x
ziv@2250 23 else iterate f (n-1) (f x)
ziv@2250 24
ziv@2286 25 (* From the MLton wiki. *)
ziv@2286 26 infix 3 <\ fun x <\ f = fn y => f (x, y) (* Left section *)
ziv@2286 27 infix 3 \> fun f \> y = f y (* Left application *)
ziv@2286 28
ziv@2286 29 fun mapFst f (x, y) = (f x, y)
ziv@2286 30
ziv@2286 31 (* Option monad. *)
ziv@2286 32 fun obind (x, f) = Option.mapPartial f x
ziv@2286 33 fun oguard (b, x) = if b then x else NONE
ziv@2286 34 fun omap f = fn SOME x => SOME (f x) | _ => NONE
ziv@2286 35 fun omap2 f = fn (SOME x, SOME y) => SOME (f (x,y)) | _ => NONE
ziv@2286 36 fun osequence ys = List.foldr (omap2 op::) (SOME []) ys
ziv@2286 37
ziv@2286 38 fun indexOf test =
ziv@2286 39 let
ziv@2286 40 fun f n =
ziv@2286 41 fn [] => NONE
ziv@2286 42 | (x::xs) => if test x then SOME n else f (n+1) xs
ziv@2286 43 in
ziv@2286 44 f 0
ziv@2286 45 end
ziv@2286 46
ziv@2286 47
ziv@2286 48 (************)
ziv@2286 49 (* Settings *)
ziv@2286 50 (************)
ziv@2286 51
ziv@2286 52 open Mono
ziv@2286 53
ziv@2268 54 (* Filled in by [addFlushing]. *)
ziv@2268 55 val ffiInfoRef : {index : int, params : int} list ref = ref []
ziv@2209 56
ziv@2268 57 fun resetFfiInfo () = ffiInfoRef := []
ziv@2227 58
ziv@2268 59 fun getFfiInfo () = !ffiInfoRef
ziv@2213 60
ziv@2215 61 (* Some FFIs have writing as their only effect, which the caching records. *)
ziv@2215 62 val ffiEffectful =
ziv@2223 63 (* ASK: how can this be less hard-coded? *)
ziv@2215 64 let
ziv@2258 65 val okayWrites = SS.fromList ["htmlifyInt_w",
ziv@2258 66 "htmlifyFloat_w",
ziv@2258 67 "htmlifyString_w",
ziv@2258 68 "htmlifyBool_w",
ziv@2258 69 "htmlifyTime_w",
ziv@2258 70 "attrifyInt_w",
ziv@2258 71 "attrifyFloat_w",
ziv@2258 72 "attrifyString_w",
ziv@2258 73 "attrifyChar_w",
ziv@2258 74 "urlifyInt_w",
ziv@2258 75 "urlifyFloat_w",
ziv@2258 76 "urlifyString_w",
ziv@2258 77 "urlifyBool_w",
ziv@2258 78 "urlifyChannel_w"]
ziv@2215 79 in
ziv@2265 80 (* ASK: is it okay to hardcode Sqlcache functions as effectful? *)
ziv@2215 81 fn (m, f) => Settings.isEffectful (m, f)
ziv@2258 82 andalso not (m = "Basis" andalso SS.member (okayWrites, f))
ziv@2215 83 end
ziv@2215 84
ziv@2278 85 val cacheRef = ref LruCache.cache
ziv@2278 86 fun setCache c = cacheRef := c
ziv@2278 87 fun getCache () = !cacheRef
ziv@2278 88
ziv@2278 89 val alwaysConsolidateRef = ref true
ziv@2278 90 fun setAlwaysConsolidate b = alwaysConsolidateRef := b
ziv@2278 91 fun getAlwaysConsolidate () = !alwaysConsolidateRef
ziv@2233 92
ziv@2286 93
ziv@2286 94 (************************)
ziv@2286 95 (* Really Useful Things *)
ziv@2286 96 (************************)
ziv@2286 97
ziv@2248 98 (* Used to have type context for local variables in MonoUtil functions. *)
ziv@2248 99 val doBind =
ziv@2262 100 fn (env, MonoUtil.Exp.RelE (x, t)) => MonoEnv.pushERel env x t NONE
ziv@2262 101 | (env, MonoUtil.Exp.NamedE (x, n, t, eo, s)) => MonoEnv.pushENamed env x n t eo s
ziv@2262 102 | (env, MonoUtil.Exp.Datatype (x, n, cs)) => MonoEnv.pushDatatype env x n cs
ziv@2215 103
ziv@2271 104 val dummyLoc = ErrorMsg.dummySpan
ziv@2271 105
ziv@2278 106 (* DEBUG *)
ziv@2278 107 fun printExp msg exp = Print.preface ("SQLCACHE: " ^ msg ^ ":", MonoPrint.p_exp MonoEnv.empty exp)
ziv@2278 108 fun printExp' msg exp' = printExp msg (exp', dummyLoc)
ziv@2278 109 fun printTyp msg typ = Print.preface ("SQLCACHE: " ^ msg ^ ":", MonoPrint.p_typ MonoEnv.empty typ)
ziv@2278 110 fun printTyp' msg typ' = printTyp msg (typ', dummyLoc)
ziv@2278 111 fun obindDebug printer (x, f) =
ziv@2278 112 case x of
ziv@2278 113 NONE => NONE
ziv@2278 114 | SOME x' => case f x' of
ziv@2278 115 NONE => (printer (); NONE)
ziv@2278 116 | y => y
ziv@2271 117
ziv@2268 118
ziv@2248 119 (*******************)
ziv@2248 120 (* Effect Analysis *)
ziv@2248 121 (*******************)
ziv@2215 122
ziv@2286 123 (* TODO: test this. *)
ziv@2286 124 fun transitiveAnalysis doVal state (decls, _) =
ziv@2286 125 let
ziv@2286 126 val doDecl =
ziv@2286 127 fn ((DVal v, _), state) => doVal (v, state)
ziv@2286 128 (* Pass over the list of values a number of times equal to its size,
ziv@2286 129 making sure whatever property we're testing propagates everywhere
ziv@2286 130 it should. This is analagous to the Bellman-Ford algorithm. *)
ziv@2286 131 | ((DValRec vs, _), state) =>
ziv@2286 132 iterate (fn state => List.foldl doVal state vs) (length vs) state
ziv@2286 133 | (_, state) => state
ziv@2286 134 in
ziv@2286 135 List.foldl doDecl state decls
ziv@2286 136 end
ziv@2286 137
ziv@2216 138 (* Makes an exception for [EWrite] (which is recorded when caching). *)
ziv@2248 139 fun effectful (effs : IS.set) =
ziv@2215 140 let
ziv@2248 141 val isFunction =
ziv@2248 142 fn (TFun _, _) => true
ziv@2248 143 | _ => false
ziv@2250 144 fun doExp (env, e) =
ziv@2248 145 case e of
ziv@2248 146 EPrim _ => false
ziv@2248 147 (* For now: variables of function type might be effectful, but
ziv@2248 148 others are fully evaluated and are therefore not effectful. *)
ziv@2250 149 | ERel n => isFunction (#2 (MonoEnv.lookupERel env n))
ziv@2248 150 | ENamed n => IS.member (effs, n)
ziv@2248 151 | EFfi (m, f) => ffiEffectful (m, f)
ziv@2248 152 | EFfiApp (m, f, _) => ffiEffectful (m, f)
ziv@2248 153 (* These aren't effectful unless a subexpression is. *)
ziv@2248 154 | ECon _ => false
ziv@2248 155 | ENone _ => false
ziv@2248 156 | ESome _ => false
ziv@2248 157 | EApp _ => false
ziv@2248 158 | EAbs _ => false
ziv@2248 159 | EUnop _ => false
ziv@2248 160 | EBinop _ => false
ziv@2248 161 | ERecord _ => false
ziv@2248 162 | EField _ => false
ziv@2248 163 | ECase _ => false
ziv@2248 164 | EStrcat _ => false
ziv@2248 165 (* EWrite is a special exception because we record writes when caching. *)
ziv@2248 166 | EWrite _ => false
ziv@2248 167 | ESeq _ => false
ziv@2248 168 | ELet _ => false
ziv@2250 169 | EUnurlify _ => false
ziv@2248 170 (* ASK: what should we do about closures? *)
ziv@2248 171 (* Everything else is some sort of effect. We could flip this and
ziv@2248 172 explicitly list bits of Mono that are effectful, but this is
ziv@2248 173 conservatively robust to future changes (however unlikely). *)
ziv@2248 174 | _ => true
ziv@2215 175 in
ziv@2248 176 MonoUtil.Exp.existsB {typ = fn _ => false, exp = doExp, bind = doBind}
ziv@2215 177 end
ziv@2215 178
ziv@2215 179 (* TODO: test this. *)
ziv@2286 180 fun effectfulDecls file =
ziv@2286 181 transitiveAnalysis (fn ((_, name, _, e, _), effs) =>
ziv@2286 182 if effectful effs MonoEnv.empty e
ziv@2286 183 then IS.add (effs, name)
ziv@2286 184 else effs)
ziv@2286 185 IS.empty
ziv@2286 186 file
ziv@2215 187
ziv@2215 188
ziv@2248 189 (*********************************)
ziv@2248 190 (* Boolean Formula Normalization *)
ziv@2248 191 (*********************************)
ziv@2216 192
ziv@2234 193 datatype junctionType = Conj | Disj
ziv@2216 194
ziv@2216 195 datatype 'atom formula =
ziv@2216 196 Atom of 'atom
ziv@2216 197 | Negate of 'atom formula
ziv@2234 198 | Combo of junctionType * 'atom formula list
ziv@2216 199
ziv@2243 200 (* Guaranteed to have all negation pushed to the atoms. *)
ziv@2243 201 datatype 'atom formula' =
ziv@2243 202 Atom' of 'atom
ziv@2243 203 | Combo' of junctionType * 'atom formula' list
ziv@2243 204
ziv@2234 205 val flipJt = fn Conj => Disj | Disj => Conj
ziv@2216 206
ziv@2236 207 fun concatMap f xs = List.concat (map f xs)
ziv@2216 208
ziv@2216 209 val rec cartesianProduct : 'a list list -> 'a list list =
ziv@2216 210 fn [] => [[]]
ziv@2236 211 | (xs :: xss) => concatMap (fn ys => concatMap (fn x => [x :: ys]) xs)
ziv@2236 212 (cartesianProduct xss)
ziv@2216 213
ziv@2218 214 (* Pushes all negation to the atoms.*)
ziv@2244 215 fun pushNegate (normalizeAtom : bool * 'atom -> 'atom) (negating : bool) =
ziv@2244 216 fn Atom x => Atom' (normalizeAtom (negating, x))
ziv@2244 217 | Negate f => pushNegate normalizeAtom (not negating) f
ziv@2244 218 | Combo (j, fs) => Combo' (if negating then flipJt j else j,
ziv@2244 219 map (pushNegate normalizeAtom negating) fs)
ziv@2218 220
ziv@2218 221 val rec flatten =
ziv@2243 222 fn Combo' (_, [f]) => flatten f
ziv@2243 223 | Combo' (j, fs) =>
ziv@2243 224 Combo' (j, List.foldr (fn (f, acc) =>
ziv@2243 225 case f of
ziv@2243 226 Combo' (j', fs') =>
ziv@2243 227 if j = j' orelse length fs' = 1
ziv@2243 228 then fs' @ acc
ziv@2243 229 else f :: acc
ziv@2243 230 | _ => f :: acc)
ziv@2243 231 []
ziv@2243 232 (map flatten fs))
ziv@2218 233 | f => f
ziv@2218 234
ziv@2243 235 (* [simplify] operates on the desired normal form. E.g., if [junc] is [Disj],
ziv@2243 236 consider the list of lists to be a disjunction of conjunctions. *)
ziv@2237 237 fun normalize' (simplify : 'a list list -> 'a list list)
ziv@2235 238 (junc : junctionType) =
ziv@2216 239 let
ziv@2235 240 fun norm junc =
ziv@2237 241 simplify
ziv@2243 242 o (fn Atom' x => [[x]]
ziv@2243 243 | Combo' (j, fs) =>
ziv@2235 244 let
ziv@2236 245 val fss = map (norm junc) fs
ziv@2235 246 in
ziv@2236 247 if j = junc
ziv@2236 248 then List.concat fss
ziv@2236 249 else map List.concat (cartesianProduct fss)
ziv@2235 250 end)
ziv@2216 251 in
ziv@2235 252 norm junc
ziv@2216 253 end
ziv@2216 254
ziv@2244 255 fun normalize simplify normalizeAtom junc =
ziv@2243 256 normalize' simplify junc
ziv@2235 257 o flatten
ziv@2244 258 o pushNegate normalizeAtom false
ziv@2216 259
ziv@2221 260 fun mapFormula mf =
ziv@2221 261 fn Atom x => Atom (mf x)
ziv@2221 262 | Negate f => Negate (mapFormula mf f)
ziv@2235 263 | Combo (j, fs) => Combo (j, map (mapFormula mf) fs)
ziv@2216 264
ziv@2274 265 fun mapFormulaExps mf = mapFormula (fn (cmp, e1, e2) => (cmp, mf e1, mf e2))
ziv@2274 266
ziv@2230 267
ziv@2248 268 (****************)
ziv@2248 269 (* SQL Analysis *)
ziv@2248 270 (****************)
ziv@2213 271
ziv@2240 272 structure CmpKey = struct
ziv@2235 273
ziv@2235 274 type ord_key = Sql.cmp
ziv@2235 275
ziv@2235 276 val compare =
ziv@2235 277 fn (Sql.Eq, Sql.Eq) => EQUAL
ziv@2235 278 | (Sql.Eq, _) => LESS
ziv@2235 279 | (_, Sql.Eq) => GREATER
ziv@2235 280 | (Sql.Ne, Sql.Ne) => EQUAL
ziv@2235 281 | (Sql.Ne, _) => LESS
ziv@2235 282 | (_, Sql.Ne) => GREATER
ziv@2235 283 | (Sql.Lt, Sql.Lt) => EQUAL
ziv@2235 284 | (Sql.Lt, _) => LESS
ziv@2235 285 | (_, Sql.Lt) => GREATER
ziv@2235 286 | (Sql.Le, Sql.Le) => EQUAL
ziv@2235 287 | (Sql.Le, _) => LESS
ziv@2235 288 | (_, Sql.Le) => GREATER
ziv@2235 289 | (Sql.Gt, Sql.Gt) => EQUAL
ziv@2235 290 | (Sql.Gt, _) => LESS
ziv@2235 291 | (_, Sql.Gt) => GREATER
ziv@2235 292 | (Sql.Ge, Sql.Ge) => EQUAL
ziv@2235 293
ziv@2235 294 end
ziv@2235 295
ziv@2216 296 val rec chooseTwos : 'a list -> ('a * 'a) list =
ziv@2216 297 fn [] => []
ziv@2216 298 | x :: ys => map (fn y => (x, y)) ys @ chooseTwos ys
ziv@2213 299
ziv@2237 300 fun removeRedundant madeRedundantBy zs =
ziv@2237 301 let
ziv@2237 302 fun removeRedundant' (xs, ys) =
ziv@2237 303 case xs of
ziv@2237 304 [] => ys
ziv@2237 305 | x :: xs' =>
ziv@2237 306 removeRedundant' (xs',
ziv@2237 307 if List.exists (fn y => madeRedundantBy (x, y)) (xs' @ ys)
ziv@2237 308 then ys
ziv@2237 309 else x :: ys)
ziv@2237 310 in
ziv@2237 311 removeRedundant' (zs, [])
ziv@2237 312 end
ziv@2237 313
ziv@2216 314 datatype atomExp =
ziv@2216 315 QueryArg of int
ziv@2216 316 | DmlRel of int
ziv@2216 317 | Prim of Prim.t
ziv@2216 318 | Field of string * string
ziv@2216 319
ziv@2216 320 structure AtomExpKey : ORD_KEY = struct
ziv@2216 321
ziv@2234 322 type ord_key = atomExp
ziv@2216 323
ziv@2234 324 val compare =
ziv@2234 325 fn (QueryArg n1, QueryArg n2) => Int.compare (n1, n2)
ziv@2234 326 | (QueryArg _, _) => LESS
ziv@2234 327 | (_, QueryArg _) => GREATER
ziv@2234 328 | (DmlRel n1, DmlRel n2) => Int.compare (n1, n2)
ziv@2234 329 | (DmlRel _, _) => LESS
ziv@2234 330 | (_, DmlRel _) => GREATER
ziv@2234 331 | (Prim p1, Prim p2) => Prim.compare (p1, p2)
ziv@2234 332 | (Prim _, _) => LESS
ziv@2234 333 | (_, Prim _) => GREATER
ziv@2234 334 | (Field (t1, f1), Field (t2, f2)) =>
ziv@2234 335 case String.compare (t1, t2) of
ziv@2234 336 EQUAL => String.compare (f1, f2)
ziv@2234 337 | ord => ord
ziv@2216 338
ziv@2216 339 end
ziv@2216 340
ziv@2244 341 structure AtomOptionKey = OptionKeyFn(AtomExpKey)
ziv@2244 342
ziv@2271 343 val rec tablesOfQuery =
ziv@2271 344 fn Sql.Query1 {From = tablePairs, ...} => SS.fromList (map #1 tablePairs)
ziv@2271 345 | Sql.Union (q1, q2) => SS.union (tablesOfQuery q1, tablesOfQuery q2)
ziv@2271 346
ziv@2271 347 val tableOfDml =
ziv@2271 348 fn Sql.Insert (tab, _) => tab
ziv@2271 349 | Sql.Delete (tab, _) => tab
ziv@2271 350 | Sql.Update (tab, _, _) => tab
ziv@2271 351
ziv@2271 352 val freeVars =
ziv@2271 353 MonoUtil.Exp.foldB
ziv@2271 354 {typ = #2,
ziv@2271 355 exp = fn (bound, ERel n, vars) => if n < bound
ziv@2271 356 then vars
ziv@2271 357 else IS.add (vars, n - bound)
ziv@2271 358 | (_, _, vars) => vars,
ziv@2273 359 bind = fn (bound, MonoUtil.Exp.RelE _) => bound + 1
ziv@2273 360 | (bound, _) => bound}
ziv@2271 361 0
ziv@2271 362 IS.empty
ziv@2271 363
ziv@2276 364 (* A path is a number of field projections of a variable. *)
ziv@2278 365 type path = int * string list
ziv@2276 366 structure PK = PairKeyFn(structure I = IK structure J = ListKeyFn(SK))
ziv@2276 367 structure PS = BinarySetFn(PK)
ziv@2276 368
ziv@2276 369 val pathOfExp =
ziv@2276 370 let
ziv@2276 371 fun readFields acc exp =
ziv@2276 372 acc
ziv@2276 373 <\obind\>
ziv@2276 374 (fn fs =>
ziv@2276 375 case #1 exp of
ziv@2276 376 ERel n => SOME (n, fs)
ziv@2276 377 | EField (exp, f) => readFields (SOME (f::fs)) exp
ziv@2276 378 | _ => NONE)
ziv@2276 379 in
ziv@2276 380 readFields (SOME [])
ziv@2276 381 end
ziv@2276 382
ziv@2276 383 fun expOfPath (n, fs) =
ziv@2276 384 List.foldl (fn (f, exp) => (EField (exp, f), dummyLoc)) (ERel n, dummyLoc) fs
ziv@2276 385
ziv@2276 386 fun freePaths'' bound exp paths =
ziv@2276 387 case pathOfExp (exp, dummyLoc) of
ziv@2276 388 NONE => paths
ziv@2276 389 | SOME (n, fs) => if n < bound then paths else PS.add (paths, (n - bound, fs))
ziv@2276 390
ziv@2276 391 (* ASK: nicer way? :( *)
ziv@2276 392 fun freePaths' bound exp =
ziv@2276 393 case #1 exp of
ziv@2276 394 EPrim _ => id
ziv@2276 395 | e as ERel _ => freePaths'' bound e
ziv@2276 396 | ENamed _ => id
ziv@2276 397 | ECon (_, _, data) => (case data of NONE => id | SOME e => freePaths' bound e)
ziv@2276 398 | ENone _ => id
ziv@2276 399 | ESome (_, e) => freePaths' bound e
ziv@2276 400 | EFfi _ => id
ziv@2276 401 | EFfiApp (_, _, args) =>
ziv@2276 402 List.foldl (fn ((e, _), acc) => freePaths' bound e o acc) id args
ziv@2276 403 | EApp (e1, e2) => freePaths' bound e1 o freePaths' bound e2
ziv@2276 404 | EAbs (_, _, _, e) => freePaths' (bound + 1) e
ziv@2276 405 | EUnop (_, e) => freePaths' bound e
ziv@2276 406 | EBinop (_, _, e1, e2) => freePaths' bound e1 o freePaths' bound e2
ziv@2276 407 | ERecord fields => List.foldl (fn ((_, e, _), acc) => freePaths' bound e o acc) id fields
ziv@2276 408 | e as EField _ => freePaths'' bound e
ziv@2276 409 | ECase (e, cases, _) =>
ziv@2278 410 List.foldl (fn ((p, e), acc) => freePaths' (MonoEnv.patBindsN p + bound) e o acc)
ziv@2276 411 (freePaths' bound e)
ziv@2276 412 cases
ziv@2276 413 | EStrcat (e1, e2) => freePaths' bound e1 o freePaths' bound e2
ziv@2276 414 | EError (e, _) => freePaths' bound e
ziv@2276 415 | EReturnBlob {blob, mimeType = e, ...} =>
ziv@2276 416 freePaths' bound e o (case blob of NONE => id | SOME e => freePaths' bound e)
ziv@2276 417 | ERedirect (e, _) => freePaths' bound e
ziv@2276 418 | EWrite e => freePaths' bound e
ziv@2276 419 | ESeq (e1, e2) => freePaths' bound e1 o freePaths' bound e2
ziv@2278 420 | ELet (_, _, e1, e2) => freePaths' bound e1 o freePaths' (bound + 1) e2
ziv@2276 421 | EClosure (_, es) => List.foldl (fn (e, acc) => freePaths' bound e o acc) id es
ziv@2276 422 | EQuery {query = e1, body = e2, initial = e3, ...} =>
ziv@2276 423 freePaths' bound e1 o freePaths' (bound + 2) e2 o freePaths' bound e3
ziv@2276 424 | EDml (e, _) => freePaths' bound e
ziv@2276 425 | ENextval e => freePaths' bound e
ziv@2276 426 | ESetval (e1, e2) => freePaths' bound e1 o freePaths' bound e2
ziv@2276 427 | EUnurlify (e, _, _) => freePaths' bound e
ziv@2276 428 | EJavaScript (_, e) => freePaths' bound e
ziv@2276 429 | ESignalReturn e => freePaths' bound e
ziv@2276 430 | ESignalBind (e1, e2) => freePaths' bound e1 o freePaths' bound e2
ziv@2276 431 | ESignalSource e => freePaths' bound e
ziv@2276 432 | EServerCall (e, _, _, _) => freePaths' bound e
ziv@2276 433 | ERecv (e, _) => freePaths' bound e
ziv@2276 434 | ESleep e => freePaths' bound e
ziv@2276 435 | ESpawn e => freePaths' bound e
ziv@2276 436
ziv@2276 437 fun freePaths exp = freePaths' 0 exp PS.empty
ziv@2276 438
ziv@2271 439 datatype unbind = Known of exp | Unknowns of int
ziv@2271 440
ziv@2273 441 datatype cacheArg = AsIs of exp | Urlify of exp
ziv@2273 442
ziv@2278 443 structure InvalInfo :> sig
ziv@2271 444 type t
ziv@2271 445 type state = {tableToIndices : SIMM.multimap,
ziv@2271 446 indexToInvalInfo : (t * int) IntBinaryMap.map,
ziv@2271 447 ffiInfo : {index : int, params : int} list,
ziv@2271 448 index : int}
ziv@2271 449 val empty : t
ziv@2271 450 val singleton : Sql.query -> t
ziv@2271 451 val query : t -> Sql.query
ziv@2278 452 val orderArgs : t * Mono.exp -> cacheArg list
ziv@2271 453 val unbind : t * unbind -> t option
ziv@2271 454 val union : t * t -> t
ziv@2271 455 val updateState : t * int * state -> state
ziv@2278 456 end = struct
ziv@2271 457
ziv@2276 458 (* Variable, field projections, possible wrapped sqlification FFI call. *)
ziv@2278 459 type sqlArg = path * (string * string * typ) option
ziv@2273 460
ziv@2273 461 type subst = sqlArg IM.map
ziv@2273 462
ziv@2273 463 (* TODO: store free variables as well? *)
ziv@2273 464 type t = (Sql.query * subst) list
ziv@2271 465
ziv@2271 466 type state = {tableToIndices : SIMM.multimap,
ziv@2271 467 indexToInvalInfo : (t * int) IntBinaryMap.map,
ziv@2271 468 ffiInfo : {index : int, params : int} list,
ziv@2271 469 index : int}
ziv@2271 470
ziv@2278 471 structure AK = PairKeyFn(
ziv@2278 472 structure I = PK
ziv@2278 473 structure J = OptionKeyFn(TripleKeyFn(
ziv@2276 474 structure I = SK
ziv@2276 475 structure J = SK
ziv@2276 476 structure K = struct type ord_key = Mono.typ val compare = MonoUtil.Typ.compare end)))
ziv@2276 477 structure AM = BinaryMapFn(AK)
ziv@2271 478
ziv@2273 479 (* Traversal Utilities *)
ziv@2273 480 (* TODO: get rid of unused ones. *)
ziv@2271 481
ziv@2271 482 (* Need lift', etc. because we don't have rank-2 polymorphism. This should
ziv@2273 483 probably use a functor (an ML one, not Haskell) but works for now. *)
ziv@2271 484 fun traverseSqexp (pure, _, lift, _, lift'', lift2, _) f =
ziv@2271 485 let
ziv@2271 486 val rec tr =
ziv@2271 487 fn Sql.SqNot se => lift Sql.SqNot (tr se)
ziv@2271 488 | Sql.Binop (r, se1, se2) =>
ziv@2271 489 lift2 (fn (trse1, trse2) => Sql.Binop (r, trse1, trse2)) (tr se1, tr se2)
ziv@2271 490 | Sql.SqKnown se => lift Sql.SqKnown (tr se)
ziv@2271 491 | Sql.Inj (e', loc) => lift'' (fn fe' => Sql.Inj (fe', loc)) (f e')
ziv@2271 492 | Sql.SqFunc (s, se) => lift (fn trse => Sql.SqFunc (s, trse)) (tr se)
ziv@2271 493 | se => pure se
ziv@2271 494 in
ziv@2271 495 tr
ziv@2271 496 end
ziv@2271 497
ziv@2271 498 fun traverseQuery (ops as (_, pure', _, lift', _, _, lift2')) f =
ziv@2271 499 let
ziv@2271 500 val rec mp =
ziv@2271 501 fn Sql.Query1 q =>
ziv@2271 502 (case #Where q of
ziv@2271 503 NONE => pure' (Sql.Query1 q)
ziv@2271 504 | SOME se =>
ziv@2271 505 lift' (fn mpse => Sql.Query1 {Select = #Select q,
ziv@2271 506 From = #From q,
ziv@2271 507 Where = SOME mpse})
ziv@2271 508 (traverseSqexp ops f se))
ziv@2271 509 | Sql.Union (q1, q2) => lift2' Sql.Union (mp q1, mp q2)
ziv@2271 510 in
ziv@2271 511 mp
ziv@2271 512 end
ziv@2271 513
ziv@2273 514 (* Include unused tuple elements in argument for convenience of using same
ziv@2273 515 argument as [traverseQuery]. *)
ziv@2273 516 fun traverseIM (pure, _, _, _, _, lift2, _) f =
ziv@2273 517 IM.foldli (fn (k, v, acc) => lift2 (fn (acc, w) => IM.insert (acc, k, w)) (acc, f (k,v)))
ziv@2273 518 (pure IM.empty)
ziv@2271 519
ziv@2273 520 fun traverseSubst (ops as (_, pure', lift, _, _, _, lift2')) f =
ziv@2273 521 let
ziv@2278 522 fun mp ((n, fields), sqlify) =
ziv@2278 523 lift (fn ((n', fields'), sqlify') =>
ziv@2276 524 let
ziv@2278 525 fun wrap sq = ((n', fields' @ fields), sq)
ziv@2276 526 in
ziv@2276 527 case (fields', sqlify', fields, sqlify) of
ziv@2276 528 (_, NONE, _, NONE) => wrap NONE
ziv@2276 529 | (_, NONE, _, sq as SOME _) => wrap sq
ziv@2276 530 (* Last case should suffice because we don't
ziv@2276 531 project from a sqlified value (which is a
ziv@2276 532 string). *)
ziv@2276 533 | (_, sq as SOME _, [], NONE) => wrap sq
ziv@2276 534 | _ => raise Match
ziv@2276 535 end)
ziv@2276 536 (f n)
ziv@2273 537 in
ziv@2273 538 traverseIM ops (fn (_, v) => mp v)
ziv@2273 539 end
ziv@2273 540
ziv@2273 541 fun monoidOps plus zero = (fn _ => zero, fn _ => zero,
ziv@2273 542 fn _ => fn x => x, fn _ => fn x => x, fn _ => fn x => x,
ziv@2273 543 fn _ => plus, fn _ => plus)
ziv@2273 544
ziv@2273 545 val optionOps = (SOME, SOME, omap, omap, omap, omap2, omap2)
ziv@2273 546
ziv@2273 547 fun foldMapQuery plus zero = traverseQuery (monoidOps plus zero)
ziv@2273 548 val omapQuery = traverseQuery optionOps
ziv@2273 549 fun foldMapIM plus zero = traverseIM (monoidOps plus zero)
ziv@2273 550 fun omapIM f = traverseIM optionOps f
ziv@2273 551 fun foldMapSubst plus zero = traverseSubst (monoidOps plus zero)
ziv@2273 552 fun omapSubst f = traverseSubst optionOps f
ziv@2271 553
ziv@2271 554 val varsOfQuery = foldMapQuery IS.union
ziv@2271 555 IS.empty
ziv@2271 556 (fn e' => freeVars (e', dummyLoc))
ziv@2271 557
ziv@2276 558 fun varsOfSubst subst = foldMapSubst IS.union IS.empty IS.singleton subst
ziv@2273 559
ziv@2271 560 val varsOfList =
ziv@2271 561 fn [] => IS.empty
ziv@2271 562 | (q::qs) => varsOfQuery (List.foldl Sql.Union q qs)
ziv@2271 563
ziv@2273 564 (* Signature Implementation *)
ziv@2273 565
ziv@2273 566 val empty = []
ziv@2273 567
ziv@2278 568 fun singleton q = [(q, IS.foldl (fn (n, acc) => IM.insert (acc, n, ((n, []), NONE)))
ziv@2273 569 IM.empty
ziv@2273 570 (varsOfQuery q))]
ziv@2273 571
ziv@2273 572 val union = op@
ziv@2273 573
ziv@2273 574 fun sqlArgsMap (qs : t) =
ziv@2271 575 let
ziv@2273 576 val args =
ziv@2273 577 List.foldl (fn ((q, subst), acc) =>
ziv@2273 578 IM.foldl (fn (arg, acc) => AM.insert (acc, arg, ())) acc subst)
ziv@2273 579 AM.empty
ziv@2273 580 qs
ziv@2273 581 val countRef = ref (~1)
ziv@2273 582 fun count () = (countRef := !countRef + 1; !countRef)
ziv@2273 583 in
ziv@2273 584 (* Maps each arg to a different consecutive integer, starting from 0. *)
ziv@2273 585 AM.map count args
ziv@2273 586 end
ziv@2273 587
ziv@2278 588 fun expOfArg (path, sqlify) =
ziv@2276 589 let
ziv@2278 590 val exp = expOfPath path
ziv@2276 591 in
ziv@2276 592 case sqlify of
ziv@2276 593 NONE => exp
ziv@2276 594 | SOME (m, x, typ) => (EFfiApp (m, x, [(exp, typ)]), dummyLoc)
ziv@2276 595 end
ziv@2273 596
ziv@2278 597 fun orderArgs (qs : t, exp) =
ziv@2273 598 let
ziv@2278 599 val paths = freePaths exp
ziv@2273 600 fun erel n = (ERel n, dummyLoc)
ziv@2273 601 val argsMap = sqlArgsMap qs
ziv@2273 602 val args = map (expOfArg o #1) (AM.listItemsi argsMap)
ziv@2276 603 val invalPaths = List.foldl PS.union PS.empty (map freePaths args)
ziv@2271 604 in
ziv@2271 605 (* Put arguments we might invalidate by first. *)
ziv@2273 606 map AsIs args
ziv@2273 607 (* TODO: make sure these variables are okay to remove from the argument list. *)
ziv@2276 608 @ map (Urlify o expOfPath) (PS.listItems (PS.difference (paths, invalPaths)))
ziv@2271 609 end
ziv@2271 610
ziv@2271 611 (* As a kludge, we rename the variables in the query to correspond to the
ziv@2271 612 argument of the cache they're part of. *)
ziv@2273 613 fun query (qs : t) =
ziv@2271 614 let
ziv@2273 615 val argsMap = sqlArgsMap qs
ziv@2273 616 fun substitute subst =
ziv@2273 617 fn ERel n => IM.find (subst, n)
ziv@2273 618 <\obind\>
ziv@2273 619 (fn arg =>
ziv@2273 620 AM.find (argsMap, arg)
ziv@2273 621 <\obind\>
ziv@2273 622 (fn n' => SOME (ERel n')))
ziv@2271 623 | _ => raise Match
ziv@2271 624 in
ziv@2273 625 case (map #1 qs) of
ziv@2273 626 (q :: qs) =>
ziv@2273 627 let
ziv@2273 628 val q = List.foldl Sql.Union q qs
ziv@2273 629 val ns = IS.listItems (varsOfQuery q)
ziv@2273 630 val rename =
ziv@2273 631 fn ERel n => omap ERel (indexOf (fn n' => n' = n) ns)
ziv@2273 632 | _ => raise Match
ziv@2273 633 in
ziv@2273 634 case omapQuery rename q of
ziv@2273 635 SOME q => q
ziv@2273 636 (* We should never get NONE because indexOf should never fail. *)
ziv@2273 637 | NONE => raise Match
ziv@2273 638 end
ziv@2273 639 (* We should never reach this case because [updateState] won't
ziv@2273 640 put anything in the state if there are no queries. *)
ziv@2273 641 | [] => raise Match
ziv@2271 642 end
ziv@2271 643
ziv@2276 644 val argOfExp =
ziv@2276 645 let
ziv@2276 646 fun doFields acc exp =
ziv@2276 647 acc
ziv@2276 648 <\obind\>
ziv@2276 649 (fn (fs, sqlify) =>
ziv@2276 650 case #1 exp of
ziv@2276 651 ERel n => SOME (n, fs, sqlify)
ziv@2276 652 | EField (exp, f) => doFields (SOME (f::fs, sqlify)) exp
ziv@2276 653 | _ => NONE)
ziv@2276 654 in
ziv@2276 655 fn (EFfiApp ("Basis", x, [(exp, typ)]), _) =>
ziv@2276 656 if String.isPrefix "sqlify" x
ziv@2278 657 then omap (fn path => (path, SOME ("Basis", x, typ))) (pathOfExp exp)
ziv@2276 658 else NONE
ziv@2278 659 | exp => omap (fn path => (path, NONE)) (pathOfExp exp)
ziv@2276 660 end
ziv@2273 661
ziv@2273 662 val unbind1 =
ziv@2273 663 fn Known e =>
ziv@2273 664 let
ziv@2273 665 val replacement = argOfExp e
ziv@2273 666 in
ziv@2273 667 omapSubst (fn 0 => replacement
ziv@2278 668 | n => SOME ((n-1, []), NONE))
ziv@2273 669 end
ziv@2278 670 | Unknowns k => omapSubst (fn n => if n < k then NONE else SOME ((n-k, []), NONE))
ziv@2271 671
ziv@2271 672 fun unbind (qs, ub) =
ziv@2271 673 case ub of
ziv@2271 674 (* Shortcut if nothing's changing. *)
ziv@2271 675 Unknowns 0 => SOME qs
ziv@2273 676 | _ => osequence (map (fn (q, subst) => unbind1 ub subst
ziv@2273 677 <\obind\>
ziv@2273 678 (fn subst' => SOME (q, subst'))) qs)
ziv@2271 679
ziv@2273 680 fun updateState (qs, numArgs, state as {index, ...} : state) =
ziv@2273 681 {tableToIndices = List.foldr (fn ((q, _), acc) =>
ziv@2271 682 SS.foldl (fn (tab, acc) =>
ziv@2271 683 SIMM.insert (acc, tab, index))
ziv@2271 684 acc
ziv@2271 685 (tablesOfQuery q))
ziv@2271 686 (#tableToIndices state)
ziv@2271 687 qs,
ziv@2271 688 indexToInvalInfo = IM.insert (#indexToInvalInfo state, index, (qs, numArgs)),
ziv@2271 689 ffiInfo = {index = index, params = numArgs} :: #ffiInfo state,
ziv@2271 690 index = index + 1}
ziv@2271 691
ziv@2271 692 end
ziv@2271 693
ziv@2216 694 structure UF = UnionFindFn(AtomExpKey)
ziv@2234 695
ziv@2273 696 val rec sqexpToFormula =
ziv@2273 697 fn Sql.SqTrue => Combo (Conj, [])
ziv@2273 698 | Sql.SqFalse => Combo (Disj, [])
ziv@2273 699 | Sql.SqNot e => Negate (sqexpToFormula e)
ziv@2273 700 | Sql.Binop (Sql.RCmp c, e1, e2) => Atom (c, e1, e2)
ziv@2273 701 | Sql.Binop (Sql.RLop l, p1, p2) => Combo (case l of Sql.And => Conj | Sql.Or => Disj,
ziv@2273 702 [sqexpToFormula p1, sqexpToFormula p2])
ziv@2273 703 (* ASK: any other sqexps that can be props? *)
ziv@2273 704 | _ => raise Match
ziv@2273 705
ziv@2275 706 fun mapSqexpFields f =
ziv@2275 707 fn Sql.Field (t, v) => f (t, v)
ziv@2275 708 | Sql.SqNot e => Sql.SqNot (mapSqexpFields f e)
ziv@2275 709 | Sql.Binop (r, e1, e2) => Sql.Binop (r, mapSqexpFields f e1, mapSqexpFields f e2)
ziv@2275 710 | Sql.SqKnown e => Sql.SqKnown (mapSqexpFields f e)
ziv@2275 711 | Sql.SqFunc (s, e) => Sql.SqFunc (s, mapSqexpFields f e)
ziv@2275 712 | e => e
ziv@2275 713
ziv@2273 714 fun renameTables tablePairs =
ziv@2273 715 let
ziv@2275 716 fun rename table =
ziv@2273 717 case List.find (fn (_, t) => table = t) tablePairs of
ziv@2273 718 NONE => table
ziv@2273 719 | SOME (realTable, _) => realTable
ziv@2273 720 in
ziv@2275 721 mapSqexpFields (fn (t, f) => Sql.Field (rename t, f))
ziv@2273 722 end
ziv@2273 723
ziv@2274 724 fun queryToFormula marker =
ziv@2274 725 fn Sql.Query1 {Select = sitems, From = tablePairs, Where = wher} =>
ziv@2274 726 let
ziv@2274 727 val fWhere = case wher of
ziv@2274 728 NONE => Combo (Conj, [])
ziv@2275 729 | SOME e => sqexpToFormula (renameTables tablePairs e)
ziv@2274 730 in
ziv@2275 731 case marker of
ziv@2275 732 NONE => fWhere
ziv@2275 733 | SOME markFields =>
ziv@2275 734 let
ziv@2275 735 val fWhereMarked = mapFormulaExps markFields fWhere
ziv@2275 736 val toSqexp =
ziv@2275 737 fn Sql.SqField tf => Sql.Field tf
ziv@2275 738 | Sql.SqExp (se, _) => se
ziv@2275 739 fun ineq se = Atom (Sql.Ne, se, markFields se)
ziv@2275 740 val fIneqs = Combo (Disj, map (ineq o renameTables tablePairs o toSqexp) sitems)
ziv@2275 741 in
ziv@2275 742 (Combo (Conj,
ziv@2275 743 [fWhere,
ziv@2275 744 Combo (Disj,
ziv@2275 745 [Negate fWhereMarked,
ziv@2275 746 Combo (Conj, [fWhereMarked, fIneqs])])]))
ziv@2275 747 end
ziv@2274 748 end
ziv@2274 749 | Sql.Union (q1, q2) => Combo (Disj, [queryToFormula marker q1, queryToFormula marker q2])
ziv@2273 750
ziv@2274 751 fun valsToFormula (markLeft, markRight) (table, vals) =
ziv@2274 752 Combo (Conj,
ziv@2274 753 map (fn (field, v) => Atom (Sql.Eq, markLeft (Sql.Field (table, field)), markRight v))
ziv@2274 754 vals)
ziv@2273 755
ziv@2274 756 (* TODO: verify logic for insertion and deletion. *)
ziv@2274 757 val rec dmlToFormulaMarker =
ziv@2274 758 fn Sql.Insert (table, vals) => (valsToFormula (id, id) (table, vals), NONE)
ziv@2275 759 | Sql.Delete (table, wher) => (sqexpToFormula (renameTables [(table, "T")] wher), NONE)
ziv@2273 760 | Sql.Update (table, vals, wher) =>
ziv@2273 761 let
ziv@2275 762 val fWhere = sqexpToFormula (renameTables [(table, "T")] wher)
ziv@2274 763 fun fVals marks = valsToFormula marks (table, vals)
ziv@2273 764 val modifiedFields = SS.addList (SS.empty, map #1 vals)
ziv@2273 765 (* TODO: don't use field name hack. *)
ziv@2275 766 val markFields =
ziv@2275 767 mapSqexpFields (fn (t, v) => if t = table andalso SS.member (modifiedFields, v)
ziv@2276 768 then Sql.Field (t, v ^ "'")
ziv@2276 769 else Sql.Field (t, v))
ziv@2275 770 val mark = mapFormulaExps markFields
ziv@2273 771 in
ziv@2275 772 ((Combo (Disj, [Combo (Conj, [fVals (id, markFields), mark fWhere]),
ziv@2275 773 Combo (Conj, [fVals (markFields, id), fWhere])])),
ziv@2275 774 SOME markFields)
ziv@2273 775 end
ziv@2273 776
ziv@2274 777 fun pairToFormulas (query, dml) =
ziv@2274 778 let
ziv@2276 779 val (fDml, marker) = dmlToFormulaMarker dml
ziv@2274 780 in
ziv@2274 781 (queryToFormula marker query, fDml)
ziv@2274 782 end
ziv@2274 783
ziv@2235 784 structure ConflictMaps = struct
ziv@2235 785
ziv@2235 786 structure TK = TripleKeyFn(structure I = CmpKey
ziv@2244 787 structure J = AtomOptionKey
ziv@2244 788 structure K = AtomOptionKey)
ziv@2274 789
ziv@2244 790 structure TS : ORD_SET = BinarySetFn(TK)
ziv@2235 791
ziv@2235 792 val toKnownEquality =
ziv@2235 793 (* [NONE] here means unkown. Anything that isn't a comparison between two
ziv@2235 794 knowns shouldn't be used, and simply dropping unused terms is okay in
ziv@2235 795 disjunctive normal form. *)
ziv@2235 796 fn (Sql.Eq, SOME e1, SOME e2) => SOME (e1, e2)
ziv@2235 797 | _ => NONE
ziv@2235 798
ziv@2274 799 fun equivClasses atoms : atomExp list list option =
ziv@2274 800 let
ziv@2274 801 val uf = List.foldl UF.union' UF.empty (List.mapPartial toKnownEquality atoms)
ziv@2274 802 val ineqs = List.filter (fn (cmp, _, _) =>
ziv@2274 803 cmp = Sql.Ne orelse cmp = Sql.Lt orelse cmp = Sql.Gt)
ziv@2274 804 atoms
ziv@2274 805 val contradiction =
ziv@2274 806 fn (cmp, SOME ae1, SOME ae2) => (cmp = Sql.Ne orelse cmp = Sql.Lt orelse cmp = Sql.Gt)
ziv@2275 807 andalso UF.together (uf, ae1, ae2)
ziv@2274 808 (* If we don't know one side of the comparision, not a contradiction. *)
ziv@2274 809 | _ => false
ziv@2274 810 in
ziv@2274 811 not (List.exists contradiction atoms) <\oguard\> SOME (UF.classes uf)
ziv@2274 812 end
ziv@2235 813
ziv@2235 814 fun addToEqs (eqs, n, e) =
ziv@2235 815 case IM.find (eqs, n) of
ziv@2235 816 (* Comparing to a constant is probably better than comparing to a
ziv@2235 817 variable? Checking that existing constants match a new ones is
ziv@2235 818 handled by [accumulateEqs]. *)
ziv@2235 819 SOME (Prim _) => eqs
ziv@2235 820 | _ => IM.insert (eqs, n, e)
ziv@2235 821
ziv@2235 822 val accumulateEqs =
ziv@2235 823 (* [NONE] means we have a contradiction. *)
ziv@2235 824 fn (_, NONE) => NONE
ziv@2235 825 | ((Prim p1, Prim p2), eqso) =>
ziv@2235 826 (case Prim.compare (p1, p2) of
ziv@2235 827 EQUAL => eqso
ziv@2235 828 | _ => NONE)
ziv@2235 829 | ((QueryArg n, Prim p), SOME eqs) => SOME (addToEqs (eqs, n, Prim p))
ziv@2235 830 | ((QueryArg n, DmlRel r), SOME eqs) => SOME (addToEqs (eqs, n, DmlRel r))
ziv@2235 831 | ((Prim p, QueryArg n), SOME eqs) => SOME (addToEqs (eqs, n, Prim p))
ziv@2235 832 | ((DmlRel r, QueryArg n), SOME eqs) => SOME (addToEqs (eqs, n, DmlRel r))
ziv@2235 833 (* TODO: deal with equalities between [DmlRel]s and [Prim]s.
ziv@2235 834 This would involve guarding the invalidation with a check for the
ziv@2235 835 relevant comparisons. *)
ziv@2235 836 | (_, eqso) => eqso
ziv@2235 837
ziv@2235 838 val eqsOfClass : atomExp list -> atomExp IM.map option =
ziv@2235 839 List.foldl accumulateEqs (SOME IM.empty)
ziv@2235 840 o chooseTwos
ziv@2235 841
ziv@2235 842 fun toAtomExps rel (cmp, e1, e2) =
ziv@2235 843 let
ziv@2235 844 val qa =
ziv@2235 845 (* Here [NONE] means unkown. *)
ziv@2235 846 fn Sql.SqConst p => SOME (Prim p)
ziv@2235 847 | Sql.Field tf => SOME (Field tf)
ziv@2235 848 | Sql.Inj (EPrim p, _) => SOME (Prim p)
ziv@2235 849 | Sql.Inj (ERel n, _) => SOME (rel n)
ziv@2235 850 (* We can't deal with anything else, e.g., CURRENT_TIMESTAMP
ziv@2235 851 becomes Sql.Unmodeled, which becomes NONE here. *)
ziv@2235 852 | _ => NONE
ziv@2235 853 in
ziv@2235 854 (cmp, qa e1, qa e2)
ziv@2235 855 end
ziv@2235 856
ziv@2244 857 val negateCmp =
ziv@2244 858 fn Sql.Eq => Sql.Ne
ziv@2244 859 | Sql.Ne => Sql.Eq
ziv@2244 860 | Sql.Lt => Sql.Ge
ziv@2244 861 | Sql.Le => Sql.Gt
ziv@2244 862 | Sql.Gt => Sql.Le
ziv@2244 863 | Sql.Ge => Sql.Lt
ziv@2244 864
ziv@2244 865 fun normalizeAtom (negating, (cmp, e1, e2)) =
ziv@2244 866 (* Restricting to Le/Lt and sorting the expressions in Eq/Ne helps with
ziv@2244 867 simplification, where we put the triples in sets. *)
ziv@2244 868 case (if negating then negateCmp cmp else cmp) of
ziv@2244 869 Sql.Eq => (case AtomOptionKey.compare (e1, e2) of
ziv@2244 870 LESS => (Sql.Eq, e2, e1)
ziv@2244 871 | _ => (Sql.Eq, e1, e2))
ziv@2244 872 | Sql.Ne => (case AtomOptionKey.compare (e1, e2) of
ziv@2244 873 LESS => (Sql.Ne, e2, e1)
ziv@2244 874 | _ => (Sql.Ne, e1, e2))
ziv@2244 875 | Sql.Lt => (Sql.Lt, e1, e2)
ziv@2244 876 | Sql.Le => (Sql.Le, e1, e2)
ziv@2244 877 | Sql.Gt => (Sql.Lt, e2, e1)
ziv@2244 878 | Sql.Ge => (Sql.Le, e2, e1)
ziv@2235 879
ziv@2235 880 val markQuery : (Sql.cmp * Sql.sqexp * Sql.sqexp) formula ->
ziv@2235 881 (Sql.cmp * atomExp option * atomExp option) formula =
ziv@2235 882 mapFormula (toAtomExps QueryArg)
ziv@2235 883
ziv@2235 884 val markDml : (Sql.cmp * Sql.sqexp * Sql.sqexp) formula ->
ziv@2235 885 (Sql.cmp * atomExp option * atomExp option) formula =
ziv@2235 886 mapFormula (toAtomExps DmlRel)
ziv@2250 887
ziv@2235 888 (* No eqs should have key conflicts because no variable is in two
ziv@2235 889 equivalence classes, so the [#1] could be [#2]. *)
ziv@2235 890 val mergeEqs : (atomExp IntBinaryMap.map option list
ziv@2235 891 -> atomExp IntBinaryMap.map option) =
ziv@2271 892 List.foldr (omap2 (IM.unionWith #1)) (SOME IM.empty)
ziv@2235 893
ziv@2239 894 val simplify =
ziv@2239 895 map TS.listItems
ziv@2239 896 o removeRedundant (fn (x, y) => TS.isSubset (y, x))
ziv@2239 897 o map (fn xs => TS.addList (TS.empty, xs))
ziv@2239 898
ziv@2235 899 fun dnf (fQuery, fDml) =
ziv@2244 900 normalize simplify normalizeAtom Disj (Combo (Conj, [markQuery fQuery, markDml fDml]))
ziv@2235 901
ziv@2274 902 val conflictMaps =
ziv@2274 903 List.mapPartial (mergeEqs o map eqsOfClass)
ziv@2274 904 o List.mapPartial equivClasses
ziv@2274 905 o dnf
ziv@2235 906
ziv@2235 907 end
ziv@2235 908
ziv@2235 909 val conflictMaps = ConflictMaps.conflictMaps
ziv@2213 910
ziv@2213 911
ziv@2265 912 (*************************************)
ziv@2265 913 (* Program Instrumentation Utilities *)
ziv@2265 914 (*************************************)
ziv@2213 915
ziv@2233 916 val {check, store, flush, ...} = getCache ()
ziv@2233 917
ziv@2248 918 val dummyTyp = (TRecord [], dummyLoc)
ziv@2248 919
ziv@2230 920 fun stringExp s = (EPrim (Prim.String (Prim.Normal, s)), dummyLoc)
ziv@2230 921
ziv@2230 922 val stringTyp = (TFfi ("Basis", "string"), dummyLoc)
ziv@2213 923
ziv@2213 924 val sequence =
ziv@2213 925 fn (exp :: exps) =>
ziv@2213 926 let
ziv@2230 927 val loc = dummyLoc
ziv@2213 928 in
ziv@2213 929 List.foldl (fn (e', seq) => ESeq ((seq, loc), (e', loc))) exp exps
ziv@2213 930 end
ziv@2213 931 | _ => raise Match
ziv@2213 932
ziv@2248 933 (* Always increments negative indices as a hack we use later. *)
ziv@2248 934 fun incRels inc =
ziv@2215 935 MonoUtil.Exp.mapB
ziv@2248 936 {typ = fn t' => t',
ziv@2248 937 exp = fn bound =>
ziv@2248 938 (fn ERel n => ERel (if n >= bound orelse n < 0 then n + inc else n)
ziv@2248 939 | e' => e'),
ziv@2248 940 bind = fn (bound, MonoUtil.Exp.RelE _) => bound + 1 | (bound, _) => bound}
ziv@2248 941 0
ziv@2213 942
ziv@2262 943 fun fileTopLevelMapfoldB doTopLevelExp (decls, sideInfo) state =
ziv@2262 944 let
ziv@2262 945 fun doVal env ((x, n, t, exp, s), state) =
ziv@2262 946 let
ziv@2262 947 val (exp, state) = doTopLevelExp env exp state
ziv@2262 948 in
ziv@2262 949 ((x, n, t, exp, s), state)
ziv@2262 950 end
ziv@2262 951 fun doDecl' env (decl', state) =
ziv@2262 952 case decl' of
ziv@2262 953 DVal v =>
ziv@2262 954 let
ziv@2262 955 val (v, state) = doVal env (v, state)
ziv@2262 956 in
ziv@2262 957 (DVal v, state)
ziv@2262 958 end
ziv@2262 959 | DValRec vs =>
ziv@2262 960 let
ziv@2262 961 val (vs, state) = ListUtil.foldlMap (doVal env) state vs
ziv@2262 962 in
ziv@2262 963 (DValRec vs, state)
ziv@2262 964 end
ziv@2262 965 | _ => (decl', state)
ziv@2262 966 fun doDecl (decl as (decl', loc), (env, state)) =
ziv@2262 967 let
ziv@2262 968 val env = MonoEnv.declBinds env decl
ziv@2262 969 val (decl', state) = doDecl' env (decl', state)
ziv@2262 970 in
ziv@2262 971 ((decl', loc), (env, state))
ziv@2262 972 end
ziv@2262 973 val (decls, (_, state)) = (ListUtil.foldlMap doDecl (MonoEnv.empty, state) decls)
ziv@2262 974 in
ziv@2262 975 ((decls, sideInfo), state)
ziv@2262 976 end
ziv@2262 977
ziv@2262 978 fun fileAllMapfoldB doExp file start =
ziv@2248 979 case MonoUtil.File.mapfoldB
ziv@2248 980 {typ = Search.return2,
ziv@2250 981 exp = fn env => fn e' => fn s => Search.Continue (doExp env e' s),
ziv@2248 982 decl = fn _ => Search.return2,
ziv@2248 983 bind = doBind}
ziv@2250 984 MonoEnv.empty file start of
ziv@2213 985 Search.Continue x => x
ziv@2213 986 | Search.Return _ => raise Match
ziv@2213 987
ziv@2262 988 fun fileMap doExp file = #1 (fileAllMapfoldB (fn _ => fn e => fn _ => (doExp e, ())) file ())
ziv@2213 989
ziv@2267 990 (* TODO: make this a bit prettier.... *)
ziv@2267 991 val simplifySql =
ziv@2266 992 let
ziv@2267 993 fun factorOutNontrivial text =
ziv@2267 994 let
ziv@2267 995 val loc = dummyLoc
ziv@2267 996 fun strcat (e1, e2) = (EStrcat (e1, e2), loc)
ziv@2267 997 val chunks = Sql.chunkify text
ziv@2267 998 val (newText, newVariables) =
ziv@2267 999 (* Important that this is foldr (to oppose foldl below). *)
ziv@2267 1000 List.foldr
ziv@2267 1001 (fn (chunk, (qText, newVars)) =>
ziv@2267 1002 (* Variable bound to the head of newVars will have the lowest index. *)
ziv@2267 1003 case chunk of
ziv@2267 1004 (* EPrim should always be a string in this case. *)
ziv@2267 1005 Sql.Exp (e as (EPrim _, _)) => (strcat (e, qText), newVars)
ziv@2267 1006 | Sql.Exp e =>
ziv@2267 1007 let
ziv@2267 1008 val n = length newVars
ziv@2267 1009 in
ziv@2267 1010 (* This is the (n+1)th new variable, so there are
ziv@2267 1011 already n new variables bound, so we increment
ziv@2267 1012 indices by n. *)
ziv@2267 1013 (strcat ((ERel (~(n+1)), loc), qText), incRels n e :: newVars)
ziv@2267 1014 end
ziv@2267 1015 | Sql.String s => (strcat (stringExp s, qText), newVars))
ziv@2267 1016 (stringExp "", [])
ziv@2267 1017 chunks
ziv@2267 1018 fun wrapLets e' =
ziv@2267 1019 (* Important that this is foldl (to oppose foldr above). *)
ziv@2273 1020 List.foldl (fn (v, e') => ELet ("sqlArg", stringTyp, v, (e', loc)))
ziv@2267 1021 e'
ziv@2267 1022 newVariables
ziv@2267 1023 val numArgs = length newVariables
ziv@2267 1024 in
ziv@2267 1025 (newText, wrapLets, numArgs)
ziv@2267 1026 end
ziv@2267 1027 fun doExp exp' =
ziv@2267 1028 let
ziv@2267 1029 val text = case exp' of
ziv@2267 1030 EQuery {query = text, ...} => text
ziv@2267 1031 | EDml (text, _) => text
ziv@2267 1032 | _ => raise Match
ziv@2267 1033 val (newText, wrapLets, numArgs) = factorOutNontrivial text
ziv@2267 1034 val newExp' = case exp' of
ziv@2267 1035 EQuery q => EQuery {query = newText,
ziv@2267 1036 exps = #exps q,
ziv@2267 1037 tables = #tables q,
ziv@2267 1038 state = #state q,
ziv@2267 1039 body = #body q,
ziv@2267 1040 initial = #initial q}
ziv@2267 1041 | EDml (_, failureMode) => EDml (newText, failureMode)
ziv@2267 1042 | _ => raise Match
ziv@2267 1043 in
ziv@2267 1044 (* Increment once for each new variable just made. This is
ziv@2267 1045 where we use the negative De Bruijn indices hack. *)
ziv@2267 1046 (* TODO: please don't use that hack. As anyone could have
ziv@2267 1047 predicted, it was incomprehensible a year later.... *)
ziv@2267 1048 wrapLets (#1 (incRels numArgs (newExp', dummyLoc)))
ziv@2267 1049 end
ziv@2266 1050 in
ziv@2267 1051 fileMap (fn exp' => case exp' of
ziv@2267 1052 EQuery _ => doExp exp'
ziv@2267 1053 | EDml _ => doExp exp'
ziv@2267 1054 | _ => exp')
ziv@2266 1055 end
ziv@2266 1056
ziv@2250 1057
ziv@2250 1058 (**********************)
ziv@2250 1059 (* Mono Type Checking *)
ziv@2250 1060 (**********************)
ziv@2250 1061
ziv@2250 1062 fun typOfExp' (env : MonoEnv.env) : exp' -> typ option =
ziv@2250 1063 fn EPrim p => SOME (TFfi ("Basis", case p of
ziv@2250 1064 Prim.Int _ => "int"
ziv@2250 1065 | Prim.Float _ => "double"
ziv@2250 1066 | Prim.String _ => "string"
ziv@2250 1067 | Prim.Char _ => "char"),
ziv@2250 1068 dummyLoc)
ziv@2250 1069 | ERel n => SOME (#2 (MonoEnv.lookupERel env n))
ziv@2250 1070 | ENamed n => SOME (#2 (MonoEnv.lookupENamed env n))
ziv@2250 1071 (* ASK: okay to make a new [ref] each time? *)
ziv@2250 1072 | ECon (dk, PConVar nCon, _) =>
ziv@2250 1073 let
ziv@2250 1074 val (_, _, nData) = MonoEnv.lookupConstructor env nCon
ziv@2250 1075 val (_, cs) = MonoEnv.lookupDatatype env nData
ziv@2250 1076 in
ziv@2250 1077 SOME (TDatatype (nData, ref (dk, cs)), dummyLoc)
ziv@2250 1078 end
ziv@2250 1079 | ECon (_, PConFfi {mod = s, datatyp, ...}, _) => SOME (TFfi (s, datatyp), dummyLoc)
ziv@2250 1080 | ENone t => SOME (TOption t, dummyLoc)
ziv@2250 1081 | ESome (t, _) => SOME (TOption t, dummyLoc)
ziv@2250 1082 | EFfi _ => NONE
ziv@2250 1083 | EFfiApp _ => NONE
ziv@2250 1084 | EApp (e1, e2) => (case typOfExp env e1 of
ziv@2250 1085 SOME (TFun (_, t), _) => SOME t
ziv@2250 1086 | _ => NONE)
ziv@2250 1087 | EAbs (_, t1, t2, _) => SOME (TFun (t1, t2), dummyLoc)
ziv@2250 1088 (* ASK: is this right? *)
ziv@2250 1089 | EUnop (unop, e) => (case unop of
ziv@2250 1090 "!" => SOME (TFfi ("Basis", "bool"), dummyLoc)
ziv@2250 1091 | "-" => typOfExp env e
ziv@2250 1092 | _ => NONE)
ziv@2250 1093 (* ASK: how should this (and other "=> NONE" cases) work? *)
ziv@2250 1094 | EBinop _ => NONE
ziv@2250 1095 | ERecord fields => SOME (TRecord (map (fn (s, _, t) => (s, t)) fields), dummyLoc)
ziv@2250 1096 | EField (e, s) => (case typOfExp env e of
ziv@2250 1097 SOME (TRecord fields, _) =>
ziv@2286 1098 omap #2 (List.find (fn (s', _) => s = s') fields)
ziv@2250 1099 | _ => NONE)
ziv@2250 1100 | ECase (_, _, {result, ...}) => SOME result
ziv@2250 1101 | EStrcat _ => SOME (TFfi ("Basis", "string"), dummyLoc)
ziv@2250 1102 | EWrite _ => SOME (TRecord [], dummyLoc)
ziv@2250 1103 | ESeq (_, e) => typOfExp env e
ziv@2250 1104 | ELet (s, t, e1, e2) => typOfExp (MonoEnv.pushERel env s t (SOME e1)) e2
ziv@2250 1105 | EClosure _ => NONE
ziv@2250 1106 | EUnurlify (_, t, _) => SOME t
ziv@2269 1107 | EQuery {state, ...} => SOME state
ziv@2276 1108 | e => NONE
ziv@2250 1109
ziv@2250 1110 and typOfExp env (e', loc) = typOfExp' env e'
ziv@2250 1111
ziv@2250 1112
ziv@2266 1113 (***********)
ziv@2266 1114 (* Caching *)
ziv@2266 1115 (***********)
ziv@2250 1116
ziv@2271 1117 type state = InvalInfo.state
ziv@2271 1118
ziv@2271 1119 datatype subexp = Cachable of InvalInfo.t * (state -> exp * state) | Impure of exp
ziv@2271 1120
ziv@2271 1121 val isImpure =
ziv@2271 1122 fn Cachable _ => false
ziv@2271 1123 | Impure _ => true
ziv@2271 1124
ziv@2271 1125 val runSubexp : subexp * state -> exp * state =
ziv@2271 1126 fn (Cachable (_, f), state) => f state
ziv@2271 1127 | (Impure e, state) => (e, state)
ziv@2271 1128
ziv@2271 1129 val invalInfoOfSubexp =
ziv@2271 1130 fn Cachable (invalInfo, _) => invalInfo
ziv@2271 1131 | Impure _ => raise Match
ziv@2271 1132
ziv@2271 1133 fun cacheWrap (env, exp, typ, args, index) =
ziv@2265 1134 let
ziv@2265 1135 val loc = dummyLoc
ziv@2265 1136 val rel0 = (ERel 0, loc)
ziv@2265 1137 in
ziv@2271 1138 case MonoFooify.urlify env (rel0, typ) of
ziv@2265 1139 NONE => NONE
ziv@2265 1140 | SOME urlified =>
ziv@2265 1141 let
ziv@2265 1142 (* We ensure before this step that all arguments aren't effectful.
ziv@2265 1143 by turning them into local variables as needed. *)
ziv@2265 1144 val argsInc = map (incRels 1) args
ziv@2268 1145 val check = (check (index, args), loc)
ziv@2268 1146 val store = (store (index, argsInc, urlified), loc)
ziv@2265 1147 in
ziv@2271 1148 SOME (ECase (check,
ziv@2271 1149 [((PNone stringTyp, loc),
ziv@2273 1150 (ELet ("q", typ, exp, (ESeq (store, rel0), loc)), loc)),
ziv@2273 1151 ((PSome (stringTyp, (PVar ("hit", stringTyp), loc)), loc),
ziv@2271 1152 (* Boolean is false because we're not unurlifying from a cookie. *)
ziv@2271 1153 (EUnurlify (rel0, typ, false), loc))],
ziv@2271 1154 {disc = (TOption stringTyp, loc), result = typ}))
ziv@2265 1155 end
ziv@2265 1156 end
ziv@2265 1157
ziv@2258 1158 val expSize = MonoUtil.Exp.fold {typ = #2, exp = fn (_, n) => n+1} 0
ziv@2258 1159
ziv@2259 1160 (* TODO: pick a number. *)
ziv@2278 1161 val sizeWorthCaching = 5
ziv@2259 1162
ziv@2269 1163 val worthCaching =
ziv@2269 1164 fn EQuery _ => true
ziv@2269 1165 | exp' => expSize (exp', dummyLoc) > sizeWorthCaching
ziv@2269 1166
ziv@2278 1167 fun shouldConsolidate args =
ziv@2278 1168 let
ziv@2278 1169 val isAsIs = fn AsIs _ => true | Urlify _ => false
ziv@2278 1170 in
ziv@2278 1171 getAlwaysConsolidate ()
ziv@2278 1172 orelse not (List.exists isAsIs args andalso List.exists (not o isAsIs) args)
ziv@2278 1173 end
ziv@2278 1174
ziv@2273 1175 fun cacheExp (env, exp', invalInfo, state : state) =
ziv@2273 1176 case worthCaching exp' <\oguard\> typOfExp' env exp' of
ziv@2269 1177 NONE => NONE
ziv@2269 1178 | SOME (TFun _, _) => NONE
ziv@2269 1179 | SOME typ =>
ziv@2271 1180 let
ziv@2278 1181 val args = InvalInfo.orderArgs (invalInfo, (exp', dummyLoc))
ziv@2278 1182 in
ziv@2278 1183 shouldConsolidate args
ziv@2278 1184 <\oguard\>
ziv@2278 1185 List.foldr (fn (arg, acc) =>
ziv@2278 1186 acc
ziv@2278 1187 <\obind\>
ziv@2278 1188 (fn args' =>
ziv@2278 1189 (case arg of
ziv@2278 1190 AsIs exp => SOME exp
ziv@2278 1191 | Urlify exp =>
ziv@2278 1192 typOfExp env exp
ziv@2278 1193 <\obind\>
ziv@2278 1194 (fn typ => (MonoFooify.urlify env (exp, typ))))
ziv@2278 1195 <\obind\>
ziv@2278 1196 (fn arg' => SOME (arg' :: args'))))
ziv@2278 1197 (SOME [])
ziv@2278 1198 args
ziv@2278 1199 <\obind\>
ziv@2278 1200 (fn args' =>
ziv@2278 1201 cacheWrap (env, (exp', dummyLoc), typ, args', #index state)
ziv@2278 1202 <\obind\>
ziv@2278 1203 (fn cachedExp =>
ziv@2278 1204 SOME (cachedExp, InvalInfo.updateState (invalInfo, length args', state))))
ziv@2271 1205 end
ziv@2269 1206
ziv@2271 1207 fun cacheQuery (effs, env, q) : subexp =
ziv@2266 1208 let
ziv@2266 1209 (* We use dummyTyp here. I think this is okay because databases don't
ziv@2266 1210 store (effectful) functions, but perhaps there's some pathalogical
ziv@2266 1211 corner case missing.... *)
ziv@2266 1212 fun safe bound =
ziv@2266 1213 not
ziv@2266 1214 o effectful effs
ziv@2266 1215 (iterate (fn env => MonoEnv.pushERel env "_" dummyTyp NONE)
ziv@2266 1216 bound
ziv@2266 1217 env)
ziv@2271 1218 val {query = queryText, initial, body, ...} = q
ziv@2266 1219 val attempt =
ziv@2266 1220 (* Ziv misses Haskell's do notation.... *)
ziv@2267 1221 (safe 0 queryText andalso safe 0 initial andalso safe 2 body)
ziv@2273 1222 <\oguard\>
ziv@2268 1223 Sql.parse Sql.query queryText
ziv@2273 1224 <\obind\>
ziv@2268 1225 (fn queryParsed =>
ziv@2271 1226 let
ziv@2271 1227 val invalInfo = InvalInfo.singleton queryParsed
ziv@2271 1228 fun mkExp state =
ziv@2271 1229 case cacheExp (env, EQuery q, invalInfo, state) of
ziv@2271 1230 NONE => ((EQuery q, dummyLoc), state)
ziv@2271 1231 | SOME (cachedExp, state) => ((cachedExp, dummyLoc), state)
ziv@2271 1232 in
ziv@2271 1233 SOME (Cachable (invalInfo, mkExp))
ziv@2271 1234 end)
ziv@2266 1235 in
ziv@2266 1236 case attempt of
ziv@2271 1237 NONE => Impure (EQuery q, dummyLoc)
ziv@2271 1238 | SOME subexp => subexp
ziv@2266 1239 end
ziv@2266 1240
ziv@2278 1241 fun cacheTree (effs : IS.set) ((env, exp as (exp', loc)), state) =
ziv@2250 1242 let
ziv@2271 1243 fun wrapBindN (f : exp list -> exp')
ziv@2271 1244 (args : ((MonoEnv.env * exp) * unbind) list) =
ziv@2250 1245 let
ziv@2271 1246 val (subexps, state) =
ziv@2271 1247 ListUtil.foldlMap (cacheTree effs)
ziv@2271 1248 state
ziv@2271 1249 (map #1 args)
ziv@2268 1250 fun mkExp state = mapFst (fn exps => (f exps, loc))
ziv@2268 1251 (ListUtil.foldlMap runSubexp state subexps)
ziv@2271 1252 val attempt =
ziv@2271 1253 if List.exists isImpure subexps
ziv@2271 1254 then NONE
ziv@2271 1255 else (List.foldl (omap2 InvalInfo.union)
ziv@2271 1256 (SOME InvalInfo.empty)
ziv@2271 1257 (ListPair.map
ziv@2271 1258 (fn (subexp, (_, unbinds)) =>
ziv@2271 1259 InvalInfo.unbind (invalInfoOfSubexp subexp, unbinds))
ziv@2271 1260 (subexps, args)))
ziv@2273 1261 <\obind\>
ziv@2271 1262 (fn invalInfo =>
ziv@2271 1263 SOME (Cachable (invalInfo,
ziv@2271 1264 fn state =>
ziv@2271 1265 case cacheExp (env,
ziv@2271 1266 f (map (#2 o #1) args),
ziv@2271 1267 invalInfo,
ziv@2271 1268 state) of
ziv@2271 1269 NONE => mkExp state
ziv@2271 1270 | SOME (e', state) => ((e', loc), state)),
ziv@2271 1271 state))
ziv@2250 1272 in
ziv@2271 1273 case attempt of
ziv@2271 1274 SOME (subexp, state) => (subexp, state)
ziv@2271 1275 | NONE => mapFst Impure (mkExp state)
ziv@2250 1276 end
ziv@2250 1277 fun wrapBind1 f arg =
ziv@2250 1278 wrapBindN (fn [arg] => f arg | _ => raise Match) [arg]
ziv@2250 1279 fun wrapBind2 f (arg1, arg2) =
ziv@2250 1280 wrapBindN (fn [arg1, arg2] => f (arg1, arg2) | _ => raise Match) [arg1, arg2]
ziv@2271 1281 fun wrapN f es = wrapBindN f (map (fn e => ((env, e), Unknowns 0)) es)
ziv@2271 1282 fun wrap1 f e = wrapBind1 f ((env, e), Unknowns 0)
ziv@2271 1283 fun wrap2 f (e1, e2) = wrapBind2 f (((env, e1), Unknowns 0), ((env, e2), Unknowns 0))
ziv@2250 1284 in
ziv@2250 1285 case exp' of
ziv@2250 1286 ECon (dk, pc, SOME e) => wrap1 (fn e => ECon (dk, pc, SOME e)) e
ziv@2250 1287 | ESome (t, e) => wrap1 (fn e => ESome (t, e)) e
ziv@2250 1288 | EFfiApp (s1, s2, args) =>
ziv@2258 1289 if ffiEffectful (s1, s2)
ziv@2266 1290 then (Impure exp, state)
ziv@2258 1291 else wrapN (fn es =>
ziv@2258 1292 EFfiApp (s1, s2, ListPair.map (fn (e, (_, t)) => (e, t)) (es, args)))
ziv@2258 1293 (map #1 args)
ziv@2250 1294 | EApp (e1, e2) => wrap2 EApp (e1, e2)
ziv@2250 1295 | EAbs (s, t1, t2, e) =>
ziv@2250 1296 wrapBind1 (fn e => EAbs (s, t1, t2, e))
ziv@2271 1297 ((MonoEnv.pushERel env s t1 NONE, e), Unknowns 1)
ziv@2250 1298 | EUnop (s, e) => wrap1 (fn e => EUnop (s, e)) e
ziv@2250 1299 | EBinop (bi, s, e1, e2) => wrap2 (fn (e1, e2) => EBinop (bi, s, e1, e2)) (e1, e2)
ziv@2250 1300 | ERecord fields =>
ziv@2250 1301 wrapN (fn es => ERecord (ListPair.map (fn (e, (s, _, t)) => (s, e, t)) (es, fields)))
ziv@2250 1302 (map #2 fields)
ziv@2250 1303 | EField (e, s) => wrap1 (fn e => EField (e, s)) e
ziv@2250 1304 | ECase (e, cases, {disc, result}) =>
ziv@2250 1305 wrapBindN (fn (e::es) =>
ziv@2250 1306 ECase (e,
ziv@2250 1307 (ListPair.map (fn (e, (p, _)) => (p, e)) (es, cases)),
ziv@2256 1308 {disc = disc, result = result})
ziv@2256 1309 | _ => raise Match)
ziv@2271 1310 (((env, e), Unknowns 0)
ziv@2271 1311 :: map (fn (p, e) =>
ziv@2271 1312 ((MonoEnv.patBinds env p, e), Unknowns (MonoEnv.patBindsN p)))
ziv@2271 1313 cases)
ziv@2250 1314 | EStrcat (e1, e2) => wrap2 EStrcat (e1, e2)
ziv@2250 1315 (* We record page writes, so they're cachable. *)
ziv@2250 1316 | EWrite e => wrap1 EWrite e
ziv@2250 1317 | ESeq (e1, e2) => wrap2 ESeq (e1, e2)
ziv@2250 1318 | ELet (s, t, e1, e2) =>
ziv@2250 1319 wrapBind2 (fn (e1, e2) => ELet (s, t, e1, e2))
ziv@2271 1320 (((env, e1), Unknowns 0),
ziv@2271 1321 ((MonoEnv.pushERel env s t (SOME e1), e2), Known e1))
ziv@2250 1322 (* ASK: | EClosure (n, es) => ? *)
ziv@2250 1323 | EUnurlify (e, t, b) => wrap1 (fn e => EUnurlify (e, t, b)) e
ziv@2271 1324 | EQuery q => (cacheQuery (effs, env, q), state)
ziv@2269 1325 | _ => (if effectful effs env exp
ziv@2269 1326 then Impure exp
ziv@2271 1327 else Cachable (InvalInfo.empty,
ziv@2271 1328 fn state =>
ziv@2271 1329 case cacheExp (env, exp', InvalInfo.empty, state) of
ziv@2269 1330 NONE => ((exp', loc), state)
ziv@2269 1331 | SOME (exp', state) => ((exp', loc), state)),
ziv@2269 1332 state)
ziv@2256 1333 end
ziv@2256 1334
ziv@2266 1335 fun addCaching file =
ziv@2256 1336 let
ziv@2266 1337 val effs = effectfulDecls file
ziv@2271 1338 fun doTopLevelExp env exp state = runSubexp (cacheTree effs ((env, exp), state))
ziv@2256 1339 in
ziv@2271 1340 (fileTopLevelMapfoldB doTopLevelExp
ziv@2271 1341 file
ziv@2271 1342 {tableToIndices = SIMM.empty,
ziv@2271 1343 indexToInvalInfo = IM.empty,
ziv@2271 1344 ffiInfo = [],
ziv@2271 1345 index = 0},
ziv@2271 1346 effs)
ziv@2265 1347 end
ziv@2265 1348
ziv@2265 1349
ziv@2265 1350 (************)
ziv@2265 1351 (* Flushing *)
ziv@2265 1352 (************)
ziv@2265 1353
ziv@2265 1354 structure Invalidations = struct
ziv@2265 1355
ziv@2265 1356 val loc = dummyLoc
ziv@2265 1357
ziv@2265 1358 val optionAtomExpToExp =
ziv@2265 1359 fn NONE => (ENone stringTyp, loc)
ziv@2265 1360 | SOME e => (ESome (stringTyp,
ziv@2265 1361 (case e of
ziv@2265 1362 DmlRel n => ERel n
ziv@2265 1363 | Prim p => EPrim p
ziv@2265 1364 (* TODO: make new type containing only these two. *)
ziv@2265 1365 | _ => raise Match,
ziv@2265 1366 loc)),
ziv@2265 1367 loc)
ziv@2265 1368
ziv@2265 1369 fun eqsToInvalidation numArgs eqs =
ziv@2269 1370 List.tabulate (numArgs, (fn n => IM.find (eqs, n)))
ziv@2265 1371
ziv@2265 1372 (* Tests if [ys] makes [xs] a redundant cache invalidation. [NONE] here
ziv@2265 1373 represents unknown, which means a wider invalidation. *)
ziv@2265 1374 val rec madeRedundantBy : atomExp option list * atomExp option list -> bool =
ziv@2265 1375 fn ([], []) => true
ziv@2265 1376 | (_ :: xs, NONE :: ys) => madeRedundantBy (xs, ys)
ziv@2265 1377 | (SOME x :: xs, SOME y :: ys) => (case AtomExpKey.compare (x, y) of
ziv@2265 1378 EQUAL => madeRedundantBy (xs, ys)
ziv@2265 1379 | _ => false)
ziv@2265 1380 | _ => false
ziv@2265 1381
ziv@2271 1382 fun invalidations ((invalInfo, numArgs), dml) =
ziv@2271 1383 let
ziv@2271 1384 val query = InvalInfo.query invalInfo
ziv@2271 1385 in
ziv@2271 1386 (map (map optionAtomExpToExp)
ziv@2271 1387 o removeRedundant madeRedundantBy
ziv@2271 1388 o map (eqsToInvalidation numArgs)
ziv@2273 1389 o conflictMaps)
ziv@2274 1390 (pairToFormulas (query, dml))
ziv@2271 1391 end
ziv@2265 1392
ziv@2265 1393 end
ziv@2265 1394
ziv@2265 1395 val invalidations = Invalidations.invalidations
ziv@2265 1396
ziv@2273 1397 fun addFlushing ((file, {tableToIndices, indexToInvalInfo, ffiInfo, ...} : state), effs) =
ziv@2265 1398 let
ziv@2265 1399 val flushes = List.concat
ziv@2265 1400 o map (fn (i, argss) => map (fn args => flush (i, args)) argss)
ziv@2265 1401 val doExp =
ziv@2267 1402 fn dmlExp as EDml (dmlText, failureMode) =>
ziv@2265 1403 let
ziv@2265 1404 val inval =
ziv@2265 1405 case Sql.parse Sql.dml dmlText of
ziv@2265 1406 SOME dmlParsed =>
ziv@2271 1407 SOME (map (fn i => (case IM.find (indexToInvalInfo, i) of
ziv@2271 1408 SOME invalInfo =>
ziv@2271 1409 (i, invalidations (invalInfo, dmlParsed))
ziv@2265 1410 (* TODO: fail more gracefully. *)
ziv@2271 1411 (* This probably means invalidating everything.... *)
ziv@2265 1412 | NONE => raise Match))
ziv@2271 1413 (SIMM.findList (tableToIndices, tableOfDml dmlParsed)))
ziv@2265 1414 | NONE => NONE
ziv@2265 1415 in
ziv@2265 1416 case inval of
ziv@2265 1417 (* TODO: fail more gracefully. *)
ziv@2265 1418 NONE => raise Match
ziv@2267 1419 | SOME invs => sequence (flushes invs @ [dmlExp])
ziv@2265 1420 end
ziv@2265 1421 | e' => e'
ziv@2274 1422 val file = fileMap doExp file
ziv@2274 1423
ziv@2265 1424 in
ziv@2268 1425 ffiInfoRef := ffiInfo;
ziv@2274 1426 file
ziv@2265 1427 end
ziv@2265 1428
ziv@2265 1429
ziv@2286 1430 (***********)
ziv@2286 1431 (* Locking *)
ziv@2286 1432 (***********)
ziv@2286 1433
ziv@2286 1434 (* TODO: do this less evil-ly by not relying on specific FFI names, please? *)
ziv@2286 1435 fun locksNeeded file =
ziv@2286 1436 transitiveAnalysis
ziv@2286 1437 (fn ((_, name, _, e, _), state) =>
ziv@2286 1438 MonoUtil.Exp.fold
ziv@2286 1439 {typ = #2,
ziv@2286 1440 exp = fn (EFfiApp ("Sqlcache", x, _), state as {store, flush}) =>
ziv@2286 1441 (case Int.fromString (String.extract (x, 5, NONE)) of
ziv@2286 1442 NONE => raise Match
ziv@2286 1443 | SOME index =>
ziv@2286 1444 if String.isPrefix "store" x
ziv@2286 1445 then {store = IIMM.insert (store, name, index), flush = flush}
ziv@2286 1446 else if String.isPrefix "flush" x
ziv@2286 1447 then {store = store, flush = IIMM.insert (flush, name, index)}
ziv@2286 1448 else state)
ziv@2286 1449 | _ => state}
ziv@2286 1450 state
ziv@2286 1451 e)
ziv@2286 1452 {store = IIMM.empty, flush = IIMM.empty}
ziv@2286 1453 file
ziv@2286 1454
ziv@2286 1455 fun exports (decls, _) =
ziv@2286 1456 List.foldl (fn ((DExport (_, _, n, _, _, _), _), ns) => IS.add (ns, n)
ziv@2286 1457 | ((DTask _, _), _) => raise Fail "Sqlcache doesn't yet support tasks."
ziv@2286 1458 | (_, ns) => ns)
ziv@2286 1459 IS.empty
ziv@2286 1460 decls
ziv@2286 1461
ziv@2286 1462 (* fun addLocking file = *)
ziv@2286 1463 (* let *)
ziv@2286 1464 (* val whichLocks = locksNeeded file *)
ziv@2286 1465 (* val needsLocks = exports file *)
ziv@2286 1466 (* in *)
ziv@2286 1467
ziv@2286 1468 (* end *)
ziv@2286 1469
ziv@2268 1470 (************************)
ziv@2268 1471 (* Compiler Entry Point *)
ziv@2268 1472 (************************)
ziv@2265 1473
ziv@2265 1474 val inlineSql =
ziv@2265 1475 let
ziv@2265 1476 val doExp =
ziv@2265 1477 (* TODO: EQuery, too? *)
ziv@2265 1478 (* ASK: should this live in [MonoOpt]? *)
ziv@2265 1479 fn EDml ((ECase (disc, cases, {disc = dTyp, ...}), loc), failureMode) =>
ziv@2265 1480 let
ziv@2265 1481 val newCases = map (fn (p, e) => (p, (EDml (e, failureMode), loc))) cases
ziv@2265 1482 in
ziv@2265 1483 ECase (disc, newCases, {disc = dTyp, result = (TRecord [], loc)})
ziv@2265 1484 end
ziv@2265 1485 | e => e
ziv@2265 1486 in
ziv@2265 1487 fileMap doExp
ziv@2265 1488 end
ziv@2265 1489
ziv@2262 1490 fun insertAfterDatatypes ((decls, sideInfo), newDecls) =
ziv@2262 1491 let
ziv@2262 1492 val (datatypes, others) = List.partition (fn (DDatatype _, _) => true | _ => false) decls
ziv@2262 1493 in
ziv@2262 1494 (datatypes @ newDecls @ others, sideInfo)
ziv@2262 1495 end
ziv@2262 1496
ziv@2267 1497 val go' = addFlushing o addCaching o simplifySql o inlineSql
ziv@2256 1498
ziv@2256 1499 fun go file =
ziv@2256 1500 let
ziv@2256 1501 (* TODO: do something nicer than [Sql] being in one of two modes. *)
ziv@2256 1502 val () = (resetFfiInfo (); Sql.sqlcacheMode := true)
ziv@2262 1503 val file = go' file
ziv@2262 1504 (* Important that this happens after [MonoFooify.urlify] calls! *)
ziv@2262 1505 val fmDecls = MonoFooify.getNewFmDecls ()
ziv@2256 1506 val () = Sql.sqlcacheMode := false
ziv@2256 1507 in
ziv@2262 1508 insertAfterDatatypes (file, rev fmDecls)
ziv@2250 1509 end
ziv@2250 1510
ziv@2209 1511 end