annotate src/sqlcache.sml @ 2236:fab8c1f131a5

Major DNF-calculation performance decrapification.
author Ziv Scully <ziv@mit.edu>
date Tue, 30 Jun 2015 01:56:22 -0700
parents 0aae15c2a05a
children e79ef5792c8b
rev   line source
ziv@2235 1 structure Sqlcache (* DEBUG: add back :> SQLCACHE. *) = struct
ziv@2209 2
ziv@2209 3 open Mono
ziv@2209 4
ziv@2209 5 structure IS = IntBinarySet
ziv@2209 6 structure IM = IntBinaryMap
ziv@2213 7 structure SK = struct type ord_key = string val compare = String.compare end
ziv@2213 8 structure SS = BinarySetFn(SK)
ziv@2213 9 structure SM = BinaryMapFn(SK)
ziv@2213 10 structure SIMM = MultimapFn(structure KeyMap = SM structure ValSet = IS)
ziv@2209 11
ziv@2216 12 (* Filled in by [cacheWrap] during [Sqlcache]. *)
ziv@2213 13 val ffiInfo : {index : int, params : int} list ref = ref []
ziv@2209 14
ziv@2227 15 fun resetFfiInfo () = ffiInfo := []
ziv@2227 16
ziv@2213 17 fun getFfiInfo () = !ffiInfo
ziv@2213 18
ziv@2215 19 (* Some FFIs have writing as their only effect, which the caching records. *)
ziv@2215 20 val ffiEffectful =
ziv@2223 21 (* ASK: how can this be less hard-coded? *)
ziv@2215 22 let
ziv@2215 23 val fs = SS.fromList ["htmlifyInt_w",
ziv@2215 24 "htmlifyFloat_w",
ziv@2215 25 "htmlifyString_w",
ziv@2215 26 "htmlifyBool_w",
ziv@2215 27 "htmlifyTime_w",
ziv@2215 28 "attrifyInt_w",
ziv@2215 29 "attrifyFloat_w",
ziv@2215 30 "attrifyString_w",
ziv@2215 31 "attrifyChar_w",
ziv@2215 32 "urlifyInt_w",
ziv@2215 33 "urlifyFloat_w",
ziv@2215 34 "urlifyString_w",
ziv@2215 35 "urlifyBool_w",
ziv@2215 36 "urlifyChannel_w"]
ziv@2215 37 in
ziv@2215 38 fn (m, f) => Settings.isEffectful (m, f)
ziv@2215 39 andalso not (m = "Basis" andalso SS.member (fs, f))
ziv@2215 40 end
ziv@2215 41
ziv@2234 42 val cache = ref LruCache.cache
ziv@2233 43 fun setCache c = cache := c
ziv@2233 44 fun getCache () = !cache
ziv@2233 45
ziv@2215 46
ziv@2215 47 (* Effect analysis. *)
ziv@2215 48
ziv@2216 49 (* Makes an exception for [EWrite] (which is recorded when caching). *)
ziv@2230 50 fun effectful doPrint (effs : IS.set) (inFunction : bool) (bound : int) : exp -> bool =
ziv@2215 51 (* If result is true, expression is definitely effectful. If result is
ziv@2215 52 false, then expression is definitely not effectful if effs is fully
ziv@2215 53 populated. The intended pattern is to use this a number of times equal
ziv@2215 54 to the number of declarations in a file, Bellman-Ford style. *)
ziv@2234 55 (* TODO: make incrementing of the number of bound variables cleaner,
ziv@2234 56 probably by using [MonoUtil] instead of all this. *)
ziv@2215 57 let
ziv@2215 58 (* DEBUG: remove printing when done. *)
ziv@2215 59 fun tru msg = if doPrint then (print (msg ^ "\n"); true) else true
ziv@2215 60 val rec eff' =
ziv@2215 61 (* ASK: is there a better way? *)
ziv@2215 62 fn EPrim _ => false
ziv@2215 63 (* We don't know if local functions have effects when applied. *)
ziv@2215 64 | ERel idx => if inFunction andalso idx >= bound
ziv@2215 65 then tru ("rel" ^ Int.toString idx) else false
ziv@2215 66 | ENamed name => if IS.member (effs, name) then tru "named" else false
ziv@2215 67 | ECon (_, _, NONE) => false
ziv@2215 68 | ECon (_, _, SOME e) => eff e
ziv@2215 69 | ENone _ => false
ziv@2215 70 | ESome (_, e) => eff e
ziv@2215 71 | EFfi (m, f) => if ffiEffectful (m, f) then tru "ffi" else false
ziv@2215 72 | EFfiApp (m, f, _) => if ffiEffectful (m, f) then tru "ffiapp" else false
ziv@2215 73 (* ASK: we're calling functions effectful if they have effects when
ziv@2215 74 applied or if the function expressions themselves have effects.
ziv@2215 75 Is that okay? *)
ziv@2215 76 (* This is okay because the values we ultimately care about aren't
ziv@2215 77 functions, and this is a conservative approximation, anyway. *)
ziv@2215 78 | EApp (eFun, eArg) => effectful doPrint effs true bound eFun orelse eff eArg
ziv@2215 79 | EAbs (_, _, _, e) => effectful doPrint effs inFunction (bound+1) e
ziv@2215 80 | EUnop (_, e) => eff e
ziv@2215 81 | EBinop (_, _, e1, e2) => eff e1 orelse eff e2
ziv@2215 82 | ERecord xs => List.exists (fn (_, e, _) => eff e) xs
ziv@2215 83 | EField (e, _) => eff e
ziv@2215 84 (* If any case could be effectful, consider it effectful. *)
ziv@2215 85 | ECase (e, xs, _) => eff e orelse List.exists (fn (_, e) => eff e) xs
ziv@2215 86 | EStrcat (e1, e2) => eff e1 orelse eff e2
ziv@2215 87 (* ASK: how should we treat these three? *)
ziv@2215 88 | EError _ => tru "error"
ziv@2215 89 | EReturnBlob _ => tru "blob"
ziv@2215 90 | ERedirect _ => tru "redirect"
ziv@2215 91 (* EWrite is a special exception because we record writes when caching. *)
ziv@2215 92 | EWrite _ => false
ziv@2215 93 | ESeq (e1, e2) => eff e1 orelse eff e2
ziv@2215 94 (* TODO: keep context of which local variables aren't effectful? Only
ziv@2215 95 makes a difference for function expressions, though. *)
ziv@2215 96 | ELet (_, _, eBind, eBody) => eff eBind orelse
ziv@2215 97 effectful doPrint effs inFunction (bound+1) eBody
ziv@2215 98 | EClosure (_, es) => List.exists eff es
ziv@2215 99 (* TODO: deal with EQuery. *)
ziv@2215 100 | EQuery _ => tru "query"
ziv@2215 101 | EDml _ => tru "dml"
ziv@2215 102 | ENextval _ => tru "nextval"
ziv@2215 103 | ESetval _ => tru "setval"
ziv@2215 104 | EUnurlify (e, _, _) => eff e
ziv@2215 105 (* ASK: how should we treat this? *)
ziv@2215 106 | EJavaScript _ => tru "javascript"
ziv@2215 107 (* ASK: these are all effectful, right? *)
ziv@2215 108 | ESignalReturn _ => tru "signalreturn"
ziv@2215 109 | ESignalBind _ => tru "signalbind"
ziv@2215 110 | ESignalSource _ => tru "signalsource"
ziv@2215 111 | EServerCall _ => tru "servercall"
ziv@2215 112 | ERecv _ => tru "recv"
ziv@2215 113 | ESleep _ => tru "sleep"
ziv@2215 114 | ESpawn _ => tru "spawn"
ziv@2215 115 and eff = fn (e', _) => eff' e'
ziv@2215 116 in
ziv@2215 117 eff
ziv@2215 118 end
ziv@2215 119
ziv@2215 120 (* TODO: test this. *)
ziv@2215 121 val effectfulMap =
ziv@2215 122 let
ziv@2215 123 fun doVal ((_, name, _, e, _), effMap) =
ziv@2215 124 if effectful false effMap false 0 e
ziv@2215 125 then IS.add (effMap, name)
ziv@2215 126 else effMap
ziv@2215 127 val doDecl =
ziv@2215 128 fn (DVal v, effMap) => doVal (v, effMap)
ziv@2215 129 (* Repeat the list of declarations a number of times equal to its size. *)
ziv@2215 130 | (DValRec vs, effMap) =>
ziv@2215 131 List.foldl doVal effMap (List.concat (List.map (fn _ => vs) vs))
ziv@2215 132 (* ASK: any other cases? *)
ziv@2215 133 | (_, effMap) => effMap
ziv@2215 134 in
ziv@2215 135 MonoUtil.File.fold {typ = #2, exp = #2, decl = doDecl} IS.empty
ziv@2215 136 end
ziv@2215 137
ziv@2215 138
ziv@2216 139 (* Boolean formula normalization. *)
ziv@2216 140
ziv@2234 141 datatype junctionType = Conj | Disj
ziv@2216 142
ziv@2216 143 datatype 'atom formula =
ziv@2216 144 Atom of 'atom
ziv@2216 145 | Negate of 'atom formula
ziv@2234 146 | Combo of junctionType * 'atom formula list
ziv@2216 147
ziv@2234 148 val flipJt = fn Conj => Disj | Disj => Conj
ziv@2216 149
ziv@2236 150 fun concatMap f xs = List.concat (map f xs)
ziv@2216 151
ziv@2216 152 val rec cartesianProduct : 'a list list -> 'a list list =
ziv@2216 153 fn [] => [[]]
ziv@2236 154 | (xs :: xss) => concatMap (fn ys => concatMap (fn x => [x :: ys]) xs)
ziv@2236 155 (cartesianProduct xss)
ziv@2216 156
ziv@2218 157 (* Pushes all negation to the atoms.*)
ziv@2218 158 fun pushNegate (negate : 'atom -> 'atom) (negating : bool) =
ziv@2218 159 fn Atom x => Atom (if negating then negate x else x)
ziv@2218 160 | Negate f => pushNegate negate (not negating) f
ziv@2234 161 | Combo (n, fs) => Combo (if negating then flipJt n else n, map (pushNegate negate negating) fs)
ziv@2218 162
ziv@2218 163 val rec flatten =
ziv@2235 164 fn Combo (_, [f]) => flatten f
ziv@2235 165 | Combo (j, fs) =>
ziv@2235 166 Combo (j, List.foldr (fn (f, acc) =>
ziv@2218 167 case f of
ziv@2235 168 Combo (j', fs') =>
ziv@2235 169 if j = j' orelse length fs' = 1
ziv@2235 170 then fs' @ acc
ziv@2235 171 else f :: acc
ziv@2218 172 | _ => f :: acc)
ziv@2218 173 []
ziv@2218 174 (map flatten fs))
ziv@2218 175 | f => f
ziv@2218 176
ziv@2236 177 fun normPlz (junc : junctionType) =
ziv@2236 178 fn Atom x => [[x]]
ziv@2236 179 | Combo (j, fs) =>
ziv@2236 180 let
ziv@2236 181 val fss = map (normPlz junc) fs
ziv@2236 182 in
ziv@2236 183 if j = junc
ziv@2236 184 then List.concat fss
ziv@2236 185 else map List.concat (cartesianProduct fss)
ziv@2236 186 end
ziv@2236 187 (* Excluded by pushNegate. *)
ziv@2236 188 | Negate _ => raise Match
ziv@2236 189
ziv@2236 190 fun normalize' ((simplifyLists, simplifyAtoms, negate)
ziv@2235 191 : ('a list list -> 'a list list)
ziv@2235 192 * ('a list -> 'a list)
ziv@2235 193 * ('a -> 'a))
ziv@2235 194 (junc : junctionType) =
ziv@2216 195 let
ziv@2236 196 fun simplify junc = simplifyLists o map simplifyAtoms
ziv@2235 197 fun norm junc =
ziv@2235 198 simplify junc
ziv@2235 199 o (fn Atom x => [[x]]
ziv@2235 200 | Negate f => map (map negate) (norm (flipJt junc) f)
ziv@2235 201 | Combo (j, fs) =>
ziv@2235 202 let
ziv@2236 203 val fss = map (norm junc) fs
ziv@2235 204 in
ziv@2236 205 if j = junc
ziv@2236 206 then List.concat fss
ziv@2236 207 else map List.concat (cartesianProduct fss)
ziv@2235 208 end)
ziv@2216 209 in
ziv@2235 210 norm junc
ziv@2216 211 end
ziv@2216 212
ziv@2236 213 fun normalize (simplifyLists, simplifyAtoms, negate, junc) =
ziv@2236 214 (normalize' (simplifyLists, simplifyAtoms, negate) junc)
ziv@2235 215 o flatten
ziv@2235 216 o pushNegate negate false
ziv@2216 217
ziv@2221 218 fun mapFormula mf =
ziv@2221 219 fn Atom x => Atom (mf x)
ziv@2221 220 | Negate f => Negate (mapFormula mf f)
ziv@2235 221 | Combo (j, fs) => Combo (j, map (mapFormula mf) fs)
ziv@2216 222
ziv@2230 223
ziv@2215 224 (* SQL analysis. *)
ziv@2213 225
ziv@2235 226 structure CmpKey : ORD_KEY = struct
ziv@2235 227
ziv@2235 228 type ord_key = Sql.cmp
ziv@2235 229
ziv@2235 230 val compare =
ziv@2235 231 fn (Sql.Eq, Sql.Eq) => EQUAL
ziv@2235 232 | (Sql.Eq, _) => LESS
ziv@2235 233 | (_, Sql.Eq) => GREATER
ziv@2235 234 | (Sql.Ne, Sql.Ne) => EQUAL
ziv@2235 235 | (Sql.Ne, _) => LESS
ziv@2235 236 | (_, Sql.Ne) => GREATER
ziv@2235 237 | (Sql.Lt, Sql.Lt) => EQUAL
ziv@2235 238 | (Sql.Lt, _) => LESS
ziv@2235 239 | (_, Sql.Lt) => GREATER
ziv@2235 240 | (Sql.Le, Sql.Le) => EQUAL
ziv@2235 241 | (Sql.Le, _) => LESS
ziv@2235 242 | (_, Sql.Le) => GREATER
ziv@2235 243 | (Sql.Gt, Sql.Gt) => EQUAL
ziv@2235 244 | (Sql.Gt, _) => LESS
ziv@2235 245 | (_, Sql.Gt) => GREATER
ziv@2235 246 | (Sql.Ge, Sql.Ge) => EQUAL
ziv@2235 247
ziv@2235 248 end
ziv@2235 249
ziv@2235 250
ziv@2235 251 functor ListKeyFn (K : ORD_KEY) : ORD_KEY = struct
ziv@2235 252
ziv@2235 253 type ord_key = K.ord_key list
ziv@2235 254
ziv@2235 255 val rec compare =
ziv@2235 256 fn ([], []) => EQUAL
ziv@2235 257 | ([], _) => LESS
ziv@2235 258 | (_, []) => GREATER
ziv@2235 259 | (x :: xs, y :: ys) => (case K.compare (x, y) of
ziv@2235 260 EQUAL => compare (xs, ys)
ziv@2235 261 | ord => ord)
ziv@2235 262
ziv@2235 263 end
ziv@2235 264
ziv@2235 265 functor OptionKeyFn (K : ORD_KEY) : ORD_KEY = struct
ziv@2235 266
ziv@2235 267 type ord_key = K.ord_key option
ziv@2235 268
ziv@2235 269 val compare =
ziv@2235 270 fn (NONE, NONE) => EQUAL
ziv@2235 271 | (NONE, _) => LESS
ziv@2235 272 | (_, NONE) => GREATER
ziv@2235 273 | (SOME x, SOME y) => K.compare (x, y)
ziv@2235 274
ziv@2235 275 end
ziv@2235 276
ziv@2235 277 functor TripleKeyFn (structure I : ORD_KEY
ziv@2235 278 structure J : ORD_KEY
ziv@2235 279 structure K : ORD_KEY)
ziv@2235 280 : ORD_KEY where type ord_key = I.ord_key * J.ord_key * K.ord_key = struct
ziv@2235 281
ziv@2235 282 type ord_key = I.ord_key * J.ord_key * K.ord_key
ziv@2235 283
ziv@2235 284 fun compare ((i1, j1, k1), (i2, j2, k2)) =
ziv@2235 285 case I.compare (i1, i2) of
ziv@2235 286 EQUAL => (case J.compare (j1, j2) of
ziv@2235 287 EQUAL => K.compare (k1, k2)
ziv@2235 288 | ord => ord)
ziv@2235 289 | ord => ord
ziv@2235 290
ziv@2235 291 end
ziv@2235 292
ziv@2216 293 val rec chooseTwos : 'a list -> ('a * 'a) list =
ziv@2216 294 fn [] => []
ziv@2216 295 | x :: ys => map (fn y => (x, y)) ys @ chooseTwos ys
ziv@2213 296
ziv@2216 297 datatype atomExp =
ziv@2216 298 QueryArg of int
ziv@2216 299 | DmlRel of int
ziv@2216 300 | Prim of Prim.t
ziv@2216 301 | Field of string * string
ziv@2216 302
ziv@2216 303 structure AtomExpKey : ORD_KEY = struct
ziv@2216 304
ziv@2234 305 type ord_key = atomExp
ziv@2216 306
ziv@2234 307 val compare =
ziv@2234 308 fn (QueryArg n1, QueryArg n2) => Int.compare (n1, n2)
ziv@2234 309 | (QueryArg _, _) => LESS
ziv@2234 310 | (_, QueryArg _) => GREATER
ziv@2234 311 | (DmlRel n1, DmlRel n2) => Int.compare (n1, n2)
ziv@2234 312 | (DmlRel _, _) => LESS
ziv@2234 313 | (_, DmlRel _) => GREATER
ziv@2234 314 | (Prim p1, Prim p2) => Prim.compare (p1, p2)
ziv@2234 315 | (Prim _, _) => LESS
ziv@2234 316 | (_, Prim _) => GREATER
ziv@2234 317 | (Field (t1, f1), Field (t2, f2)) =>
ziv@2234 318 case String.compare (t1, t2) of
ziv@2234 319 EQUAL => String.compare (f1, f2)
ziv@2234 320 | ord => ord
ziv@2216 321
ziv@2216 322 end
ziv@2216 323
ziv@2216 324 structure UF = UnionFindFn(AtomExpKey)
ziv@2234 325
ziv@2235 326 structure ConflictMaps = struct
ziv@2235 327
ziv@2235 328 structure TK = TripleKeyFn(structure I = CmpKey
ziv@2235 329 structure J = OptionKeyFn(AtomExpKey)
ziv@2235 330 structure K = OptionKeyFn(AtomExpKey))
ziv@2235 331 structure TS = BinarySetFn(TK)
ziv@2235 332 structure TLS = BinarySetFn(ListKeyFn(TK))
ziv@2235 333
ziv@2235 334 val toKnownEquality =
ziv@2235 335 (* [NONE] here means unkown. Anything that isn't a comparison between two
ziv@2235 336 knowns shouldn't be used, and simply dropping unused terms is okay in
ziv@2235 337 disjunctive normal form. *)
ziv@2235 338 fn (Sql.Eq, SOME e1, SOME e2) => SOME (e1, e2)
ziv@2235 339 | _ => NONE
ziv@2235 340
ziv@2235 341 val equivClasses : (Sql.cmp * atomExp option * atomExp option) list -> atomExp list list =
ziv@2235 342 UF.classes
ziv@2235 343 o List.foldl UF.union' UF.empty
ziv@2235 344 o List.mapPartial toKnownEquality
ziv@2235 345
ziv@2235 346 fun addToEqs (eqs, n, e) =
ziv@2235 347 case IM.find (eqs, n) of
ziv@2235 348 (* Comparing to a constant is probably better than comparing to a
ziv@2235 349 variable? Checking that existing constants match a new ones is
ziv@2235 350 handled by [accumulateEqs]. *)
ziv@2235 351 SOME (Prim _) => eqs
ziv@2235 352 | _ => IM.insert (eqs, n, e)
ziv@2235 353
ziv@2235 354 val accumulateEqs =
ziv@2235 355 (* [NONE] means we have a contradiction. *)
ziv@2235 356 fn (_, NONE) => NONE
ziv@2235 357 | ((Prim p1, Prim p2), eqso) =>
ziv@2235 358 (case Prim.compare (p1, p2) of
ziv@2235 359 EQUAL => eqso
ziv@2235 360 | _ => NONE)
ziv@2235 361 | ((QueryArg n, Prim p), SOME eqs) => SOME (addToEqs (eqs, n, Prim p))
ziv@2235 362 | ((QueryArg n, DmlRel r), SOME eqs) => SOME (addToEqs (eqs, n, DmlRel r))
ziv@2235 363 | ((Prim p, QueryArg n), SOME eqs) => SOME (addToEqs (eqs, n, Prim p))
ziv@2235 364 | ((DmlRel r, QueryArg n), SOME eqs) => SOME (addToEqs (eqs, n, DmlRel r))
ziv@2235 365 (* TODO: deal with equalities between [DmlRel]s and [Prim]s.
ziv@2235 366 This would involve guarding the invalidation with a check for the
ziv@2235 367 relevant comparisons. *)
ziv@2235 368 (* DEBUG: remove these print statements. *)
ziv@2235 369 (* | ((DmlRel r, Prim p), eqso) => (print ("sadness " ^ Int.toString r ^ " = " ^ Prim.toString p ^ "\n"); eqso) *)
ziv@2235 370 (* | ((Prim p, DmlRel r), eqso) => (print ("sadness " ^ Int.toString r ^ " = " ^ Prim.toString p ^ "\n"); eqso) *)
ziv@2235 371 | (_, eqso) => eqso
ziv@2235 372
ziv@2235 373 val eqsOfClass : atomExp list -> atomExp IM.map option =
ziv@2235 374 List.foldl accumulateEqs (SOME IM.empty)
ziv@2235 375 o chooseTwos
ziv@2235 376
ziv@2235 377 fun toAtomExps rel (cmp, e1, e2) =
ziv@2235 378 let
ziv@2235 379 val qa =
ziv@2235 380 (* Here [NONE] means unkown. *)
ziv@2235 381 fn Sql.SqConst p => SOME (Prim p)
ziv@2235 382 | Sql.Field tf => SOME (Field tf)
ziv@2235 383 | Sql.Inj (EPrim p, _) => SOME (Prim p)
ziv@2235 384 | Sql.Inj (ERel n, _) => SOME (rel n)
ziv@2235 385 (* We can't deal with anything else, e.g., CURRENT_TIMESTAMP
ziv@2235 386 becomes Sql.Unmodeled, which becomes NONE here. *)
ziv@2235 387 | _ => NONE
ziv@2235 388 in
ziv@2235 389 (cmp, qa e1, qa e2)
ziv@2235 390 end
ziv@2235 391
ziv@2235 392 fun negateCmp (cmp, e1, e2) =
ziv@2235 393 (case cmp of
ziv@2235 394 Sql.Eq => Sql.Ne
ziv@2235 395 | Sql.Ne => Sql.Eq
ziv@2235 396 | Sql.Lt => Sql.Ge
ziv@2235 397 | Sql.Le => Sql.Gt
ziv@2235 398 | Sql.Gt => Sql.Le
ziv@2235 399 | Sql.Ge => Sql.Lt,
ziv@2235 400 e1, e2)
ziv@2235 401
ziv@2235 402 val markQuery : (Sql.cmp * Sql.sqexp * Sql.sqexp) formula ->
ziv@2235 403 (Sql.cmp * atomExp option * atomExp option) formula =
ziv@2235 404 mapFormula (toAtomExps QueryArg)
ziv@2235 405
ziv@2235 406 val markDml : (Sql.cmp * Sql.sqexp * Sql.sqexp) formula ->
ziv@2235 407 (Sql.cmp * atomExp option * atomExp option) formula =
ziv@2235 408 mapFormula (toAtomExps DmlRel)
ziv@2235 409 (* No eqs should have key conflicts because no variable is in two
ziv@2235 410 equivalence classes, so the [#1] could be [#2]. *)
ziv@2235 411
ziv@2235 412 val mergeEqs : (atomExp IntBinaryMap.map option list
ziv@2235 413 -> atomExp IntBinaryMap.map option) =
ziv@2235 414 List.foldr (fn (SOME eqs, SOME acc) => SOME (IM.unionWith #1 (eqs, acc)) | _ => NONE)
ziv@2235 415 (SOME IM.empty)
ziv@2235 416
ziv@2235 417 fun dnf (fQuery, fDml) =
ziv@2235 418 let
ziv@2235 419 val isStar =
ziv@2235 420 (* TODO: decide if this is okay and, if so, factor out magic
ziv@2235 421 string "*" to a common location. *)
ziv@2235 422 (* First guess: definitely okay for conservative approximation,
ziv@2235 423 though information lost might be useful even in current
ziv@2235 424 implementation for finding an extra equality. *)
ziv@2235 425 fn SOME (Field (_, field)) => String.isSuffix "*" field
ziv@2235 426 | _ => false
ziv@2235 427 fun canIgnore (_, a1, a2) = isStar a1 orelse isStar a2
ziv@2235 428 fun simplifyLists xs = TLS.listItems (TLS.addList (TLS.empty, xs))
ziv@2236 429 fun simplifyAtoms xs = TS.listItems (TS.addList (TS.empty, xs))
ziv@2235 430 in
ziv@2236 431 normalize (simplifyLists, simplifyAtoms, negateCmp, Disj)
ziv@2235 432 (Combo (Conj, [markQuery fQuery, markDml fDml]))
ziv@2235 433 end
ziv@2235 434
ziv@2235 435 val conflictMaps = List.mapPartial (mergeEqs o map eqsOfClass o equivClasses) o dnf
ziv@2235 436
ziv@2235 437 end
ziv@2235 438
ziv@2235 439 val conflictMaps = ConflictMaps.conflictMaps
ziv@2213 440
ziv@2216 441 val rec sqexpToFormula =
ziv@2234 442 fn Sql.SqTrue => Combo (Conj, [])
ziv@2234 443 | Sql.SqFalse => Combo (Disj, [])
ziv@2216 444 | Sql.SqNot e => Negate (sqexpToFormula e)
ziv@2216 445 | Sql.Binop (Sql.RCmp c, e1, e2) => Atom (c, e1, e2)
ziv@2234 446 | Sql.Binop (Sql.RLop l, p1, p2) => Combo (case l of Sql.And => Conj | Sql.Or => Disj,
ziv@2216 447 [sqexpToFormula p1, sqexpToFormula p2])
ziv@2216 448 (* ASK: any other sqexps that can be props? *)
ziv@2216 449 | _ => raise Match
ziv@2213 450
ziv@2218 451 fun renameTables tablePairs =
ziv@2216 452 let
ziv@2216 453 fun renameString table =
ziv@2216 454 case List.find (fn (_, t) => table = t) tablePairs of
ziv@2216 455 NONE => table
ziv@2216 456 | SOME (realTable, _) => realTable
ziv@2216 457 val renameSqexp =
ziv@2216 458 fn Sql.Field (table, field) => Sql.Field (renameString table, field)
ziv@2216 459 | e => e
ziv@2218 460 fun renameAtom (cmp, e1, e2) = (cmp, renameSqexp e1, renameSqexp e2)
ziv@2216 461 in
ziv@2218 462 mapFormula renameAtom
ziv@2216 463 end
ziv@2218 464
ziv@2218 465 val rec queryToFormula =
ziv@2234 466 fn Sql.Query1 {Where = NONE, ...} => Combo (Conj, [])
ziv@2218 467 | Sql.Query1 {From = tablePairs, Where = SOME e, ...} =>
ziv@2218 468 renameTables tablePairs (sqexpToFormula e)
ziv@2234 469 | Sql.Union (q1, q2) => Combo (Disj, [queryToFormula q1, queryToFormula q2])
ziv@2216 470
ziv@2218 471 fun valsToFormula (table, vals) =
ziv@2234 472 Combo (Conj, map (fn (field, v) => Atom (Sql.Eq, Sql.Field (table, field), v)) vals)
ziv@2218 473
ziv@2216 474 val rec dmlToFormula =
ziv@2221 475 fn Sql.Insert (table, vals) => valsToFormula (table, vals)
ziv@2218 476 | Sql.Delete (table, wher) => renameTables [(table, "T")] (sqexpToFormula wher)
ziv@2218 477 | Sql.Update (table, vals, wher) =>
ziv@2218 478 let
ziv@2221 479 val fWhere = sqexpToFormula wher
ziv@2221 480 val fVals = valsToFormula (table, vals)
ziv@2221 481 (* TODO: don't use field name hack. *)
ziv@2221 482 val markField =
ziv@2221 483 fn Sql.Field (t, v) => Sql.Field (t, v ^ "*")
ziv@2221 484 | e => e
ziv@2221 485 val mark = mapFormula (fn (cmp, e1, e2) => (cmp, markField e1, markField e2))
ziv@2218 486 in
ziv@2218 487 renameTables [(table, "T")]
ziv@2234 488 (Combo (Disj, [Combo (Conj, [fVals, mark fWhere]),
ziv@2234 489 Combo (Conj, [mark fVals, fWhere])]))
ziv@2218 490 end
ziv@2213 491
ziv@2213 492 val rec tablesQuery =
ziv@2216 493 fn Sql.Query1 {From = tablePairs, ...} => SS.fromList (map #1 tablePairs)
ziv@2216 494 | Sql.Union (q1, q2) => SS.union (tablesQuery q1, tablesQuery q2)
ziv@2213 495
ziv@2213 496 val tableDml =
ziv@2216 497 fn Sql.Insert (tab, _) => tab
ziv@2216 498 | Sql.Delete (tab, _) => tab
ziv@2216 499 | Sql.Update (tab, _, _) => tab
ziv@2213 500
ziv@2213 501
ziv@2213 502 (* Program instrumentation. *)
ziv@2213 503
ziv@2234 504 val varName =
ziv@2234 505 let
ziv@2234 506 val varNumber = ref 0
ziv@2234 507 in
ziv@2234 508 fn s => (varNumber := !varNumber + 1; s ^ Int.toString (!varNumber))
ziv@2234 509 end
ziv@2234 510
ziv@2233 511 val {check, store, flush, ...} = getCache ()
ziv@2233 512
ziv@2230 513 val dummyLoc = ErrorMsg.dummySpan
ziv@2216 514
ziv@2230 515 fun stringExp s = (EPrim (Prim.String (Prim.Normal, s)), dummyLoc)
ziv@2230 516
ziv@2230 517 val stringTyp = (TFfi ("Basis", "string"), dummyLoc)
ziv@2213 518
ziv@2213 519 val sequence =
ziv@2213 520 fn (exp :: exps) =>
ziv@2213 521 let
ziv@2230 522 val loc = dummyLoc
ziv@2213 523 in
ziv@2213 524 List.foldl (fn (e', seq) => ESeq ((seq, loc), (e', loc))) exp exps
ziv@2213 525 end
ziv@2213 526 | _ => raise Match
ziv@2213 527
ziv@2215 528 (* Always increments negative indices because that's what we need later. *)
ziv@2215 529 fun incRelsBound bound inc =
ziv@2215 530 MonoUtil.Exp.mapB
ziv@2215 531 {typ = fn x => x,
ziv@2215 532 exp = fn level =>
ziv@2215 533 (fn ERel n => ERel (if n >= level orelse n < 0 then n + inc else n)
ziv@2215 534 | x => x),
ziv@2215 535 bind = fn (level, MonoUtil.Exp.RelE _) => level + 1 | (level, _) => level}
ziv@2215 536 bound
ziv@2215 537
ziv@2215 538 val incRels = incRelsBound 0
ziv@2213 539
ziv@2223 540 fun cacheWrap (query, i, urlifiedRel0, resultTyp, args) =
ziv@2213 541 let
ziv@2223 542 val () = ffiInfo := {index = i, params = length args} :: !ffiInfo
ziv@2230 543 val loc = dummyLoc
ziv@2223 544 (* We ensure before this step that all arguments aren't effectful.
ziv@2227 545 by turning them into local variables as needed. *)
ziv@2230 546 val argsInc = map (incRels 1) args
ziv@2233 547 val check = (check (i, args), dummyLoc)
ziv@2233 548 val store = (store (i, argsInc, urlifiedRel0), dummyLoc)
ziv@2223 549 val rel0 = (ERel 0, loc)
ziv@2213 550 in
ziv@2223 551 ECase (check,
ziv@2223 552 [((PNone stringTyp, loc),
ziv@2234 553 (ELet (varName "q", resultTyp, query, (ESeq (store, rel0), loc)), loc)),
ziv@2234 554 ((PSome (stringTyp, (PVar (varName "hit", stringTyp), loc)), loc),
ziv@2223 555 (* Boolean is false because we're not unurlifying from a cookie. *)
ziv@2223 556 (EUnurlify (rel0, resultTyp, false), loc))],
ziv@2223 557 {disc = stringTyp, result = resultTyp})
ziv@2213 558 end
ziv@2213 559
ziv@2213 560 fun fileMapfold doExp file start =
ziv@2213 561 case MonoUtil.File.mapfold {typ = Search.return2,
ziv@2213 562 exp = fn x => (fn s => Search.Continue (doExp x s)),
ziv@2213 563 decl = Search.return2} file start of
ziv@2213 564 Search.Continue x => x
ziv@2213 565 | Search.Return _ => raise Match
ziv@2213 566
ziv@2213 567 fun fileMap doExp file = #1 (fileMapfold (fn x => fn _ => (doExp x, ())) file ())
ziv@2213 568
ziv@2221 569 fun factorOutNontrivial text =
ziv@2221 570 let
ziv@2230 571 val loc = dummyLoc
ziv@2221 572 fun strcat (e1, e2) = (EStrcat (e1, e2), loc)
ziv@2221 573 val chunks = Sql.chunkify text
ziv@2221 574 val (newText, newVariables) =
ziv@2221 575 (* Important that this is foldr (to oppose foldl below). *)
ziv@2221 576 List.foldr
ziv@2221 577 (fn (chunk, (qText, newVars)) =>
ziv@2221 578 (* Variable bound to the head of newBs will have the lowest index. *)
ziv@2221 579 case chunk of
ziv@2221 580 Sql.Exp (e as (EPrim _, _)) => (strcat (e, qText), newVars)
ziv@2221 581 | Sql.Exp e =>
ziv@2221 582 let
ziv@2221 583 val n = length newVars
ziv@2221 584 in
ziv@2221 585 (* This is the (n + 1)th new variable, so there are
ziv@2221 586 already n new variables bound, so we increment
ziv@2221 587 indices by n. *)
ziv@2221 588 (strcat ((ERel (~(n+1)), loc), qText), incRels n e :: newVars)
ziv@2221 589 end
ziv@2221 590 | Sql.String s => (strcat (stringExp s, qText), newVars))
ziv@2221 591 (stringExp "", [])
ziv@2221 592 chunks
ziv@2221 593 fun wrapLets e' =
ziv@2221 594 (* Important that this is foldl (to oppose foldr above). *)
ziv@2234 595 List.foldl (fn (v, e') => ELet (varName "sqlArg", stringTyp, v, (e', loc)))
ziv@2221 596 e'
ziv@2221 597 newVariables
ziv@2221 598 val numArgs = length newVariables
ziv@2221 599 in
ziv@2221 600 (newText, wrapLets, numArgs)
ziv@2221 601 end
ziv@2221 602
ziv@2215 603 fun addChecking file =
ziv@2213 604 let
ziv@2223 605 fun doExp (queryInfo as (tableToIndices, indexToQueryNumArgs, index)) =
ziv@2223 606 fn e' as EQuery {query = origQueryText,
ziv@2223 607 sqlcacheInfo = urlifiedRel0,
ziv@2223 608 state = resultTyp,
ziv@2223 609 initial, body, tables, exps} =>
ziv@2213 610 let
ziv@2221 611 val (newQueryText, wrapLets, numArgs) = factorOutNontrivial origQueryText
ziv@2215 612 (* Increment once for each new variable just made. *)
ziv@2221 613 val queryExp = incRels numArgs
ziv@2215 614 (EQuery {query = newQueryText,
ziv@2223 615 sqlcacheInfo = urlifiedRel0,
ziv@2223 616 state = resultTyp,
ziv@2215 617 initial = initial,
ziv@2215 618 body = body,
ziv@2215 619 tables = tables,
ziv@2223 620 exps = exps},
ziv@2230 621 dummyLoc)
ziv@2215 622 val (EQuery {query = queryText, ...}, _) = queryExp
ziv@2235 623 (* DEBUG *)
ziv@2221 624 val () = Print.preface ("sqlcache> ", (MonoPrint.p_exp MonoEnv.empty queryText))
ziv@2230 625 val args = List.tabulate (numArgs, fn n => (ERel n, dummyLoc))
ziv@2213 626 fun bind x f = Option.mapPartial f x
ziv@2215 627 fun guard b x = if b then x else NONE
ziv@2215 628 (* DEBUG: set first boolean argument to true to turn on printing. *)
ziv@2215 629 fun safe bound = not o effectful true (effectfulMap file) false bound
ziv@2213 630 val attempt =
ziv@2213 631 (* Ziv misses Haskell's do notation.... *)
ziv@2215 632 guard (safe 0 queryText andalso safe 0 initial andalso safe 2 body) (
ziv@2216 633 bind (Sql.parse Sql.query queryText) (fn queryParsed =>
ziv@2223 634 SOME (wrapLets (cacheWrap (queryExp, index, urlifiedRel0, resultTyp, args)),
ziv@2218 635 (SS.foldr (fn (tab, qi) => SIMM.insert (qi, tab, index))
ziv@2218 636 tableToIndices
ziv@2218 637 (tablesQuery queryParsed),
ziv@2223 638 IM.insert (indexToQueryNumArgs, index, (queryParsed, numArgs)),
ziv@2223 639 index + 1))))
ziv@2213 640 in
ziv@2213 641 case attempt of
ziv@2213 642 SOME pair => pair
ziv@2213 643 | NONE => (e', queryInfo)
ziv@2213 644 end
ziv@2213 645 | e' => (e', queryInfo)
ziv@2213 646 in
ziv@2223 647 fileMapfold (fn exp => fn state => doExp state exp) file (SIMM.empty, IM.empty, 0)
ziv@2213 648 end
ziv@2213 649
ziv@2235 650 structure Invalidations = struct
ziv@2235 651
ziv@2235 652 val loc = dummyLoc
ziv@2235 653
ziv@2235 654 val optionAtomExpToExp =
ziv@2235 655 fn NONE => (ENone stringTyp, loc)
ziv@2235 656 | SOME e => (ESome (stringTyp,
ziv@2235 657 (case e of
ziv@2235 658 DmlRel n => ERel n
ziv@2235 659 | Prim p => EPrim p
ziv@2235 660 (* TODO: make new type containing only these two. *)
ziv@2235 661 | _ => raise Match,
ziv@2235 662 loc)),
ziv@2235 663 loc)
ziv@2235 664
ziv@2235 665 fun eqsToInvalidation numArgs eqs =
ziv@2235 666 let
ziv@2235 667 fun inv n = if n < 0 then [] else IM.find (eqs, n) :: inv (n - 1)
ziv@2235 668 in
ziv@2235 669 inv (numArgs - 1)
ziv@2235 670 end
ziv@2235 671
ziv@2235 672 (* Tests if [ys] makes [xs] a redundant cache invalidation. [NONE] here
ziv@2235 673 represents unknown, which means a wider invalidation. *)
ziv@2235 674 val rec madeRedundantBy : atomExp option list * atomExp option list -> bool =
ziv@2235 675 fn ([], []) => true
ziv@2235 676 | (NONE :: xs, _ :: ys) => madeRedundantBy (xs, ys)
ziv@2235 677 | (SOME x :: xs, SOME y :: ys) => (case AtomExpKey.compare (x, y) of
ziv@2235 678 EQUAL => madeRedundantBy (xs, ys)
ziv@2235 679 | _ => false)
ziv@2235 680 | _ => false
ziv@2235 681
ziv@2235 682 fun removeRedundant' (xss, yss) =
ziv@2235 683 case xss of
ziv@2235 684 [] => yss
ziv@2235 685 | xs :: xss' =>
ziv@2235 686 removeRedundant' (xss',
ziv@2235 687 if List.exists (fn ys => madeRedundantBy (xs, ys)) (xss' @ yss)
ziv@2235 688 then yss
ziv@2235 689 else xs :: yss)
ziv@2235 690
ziv@2235 691 fun removeRedundant xss = removeRedundant' (xss, [])
ziv@2235 692
ziv@2235 693 fun eqss (query, dml) = conflictMaps (queryToFormula query, dmlToFormula dml)
ziv@2235 694
ziv@2235 695 fun invalidations ((query, numArgs), dml) =
ziv@2235 696 (map (map optionAtomExpToExp)
ziv@2235 697 o removeRedundant
ziv@2235 698 o map (eqsToInvalidation numArgs)
ziv@2235 699 o eqss)
ziv@2235 700 (query, dml)
ziv@2235 701
ziv@2235 702 end
ziv@2235 703
ziv@2235 704 val invalidations = Invalidations.invalidations
ziv@2235 705
ziv@2235 706 (* DEBUG *)
ziv@2235 707 val gunk : ((Sql.query * int) * Sql.dml) list ref = ref []
ziv@2216 708
ziv@2223 709 fun addFlushing (file, (tableToIndices, indexToQueryNumArgs, _)) =
ziv@2213 710 let
ziv@2221 711 val flushes = List.concat o
ziv@2233 712 map (fn (i, argss) => map (fn args => flush (i, args)) argss)
ziv@2213 713 val doExp =
ziv@2221 714 fn EDml (origDmlText, failureMode) =>
ziv@2213 715 let
ziv@2221 716 val (newDmlText, wrapLets, numArgs) = factorOutNontrivial origDmlText
ziv@2221 717 val dmlText = incRels numArgs newDmlText
ziv@2221 718 val dmlExp = EDml (dmlText, failureMode)
ziv@2235 719 (* DEBUG *)
ziv@2221 720 val () = Print.preface ("sqlcache> ", (MonoPrint.p_exp MonoEnv.empty dmlText))
ziv@2221 721 val invs =
ziv@2216 722 case Sql.parse Sql.dml dmlText of
ziv@2218 723 SOME dmlParsed =>
ziv@2221 724 map (fn i => (case IM.find (indexToQueryNumArgs, i) of
ziv@2221 725 SOME queryNumArgs =>
ziv@2235 726 (* DEBUG *)
ziv@2235 727 (gunk := (queryNumArgs, dmlParsed) :: !gunk;
ziv@2235 728 (i, invalidations (queryNumArgs, dmlParsed)))
ziv@2221 729 (* TODO: fail more gracefully. *)
ziv@2221 730 | NONE => raise Match))
ziv@2221 731 (SIMM.findList (tableToIndices, tableDml dmlParsed))
ziv@2221 732 (* TODO: fail more gracefully. *)
ziv@2221 733 | NONE => raise Match
ziv@2213 734 in
ziv@2221 735 wrapLets (sequence (flushes invs @ [dmlExp]))
ziv@2213 736 end
ziv@2213 737 | e' => e'
ziv@2213 738 in
ziv@2235 739 (* DEBUG *)
ziv@2235 740 gunk := [];
ziv@2213 741 fileMap doExp file
ziv@2213 742 end
ziv@2213 743
ziv@2221 744 val inlineSql =
ziv@2221 745 let
ziv@2221 746 val doExp =
ziv@2221 747 (* TODO: EQuery, too? *)
ziv@2221 748 (* ASK: should this live in [MonoOpt]? *)
ziv@2221 749 fn EDml ((ECase (disc, cases, {disc = dTyp, ...}), loc), failureMode) =>
ziv@2221 750 let
ziv@2221 751 val newCases = map (fn (p, e) => (p, (EDml (e, failureMode), loc))) cases
ziv@2221 752 in
ziv@2221 753 ECase (disc, newCases, {disc = dTyp, result = (TRecord [], loc)})
ziv@2221 754 end
ziv@2221 755 | e => e
ziv@2221 756 in
ziv@2221 757 fileMap doExp
ziv@2221 758 end
ziv@2221 759
ziv@2213 760 fun go file =
ziv@2213 761 let
ziv@2235 762 (* TODO: do something nicer than [Sql] being in one of two modes. *)
ziv@2227 763 val () = (resetFfiInfo (); Sql.sqlcacheMode := true)
ziv@2221 764 val file' = addFlushing (addChecking (inlineSql file))
ziv@2215 765 val () = Sql.sqlcacheMode := false
ziv@2213 766 in
ziv@2221 767 file'
ziv@2213 768 end
ziv@2213 769
ziv@2209 770 end