annotate src/sqlcache.sml @ 2244:e4a7e3cd6f11

Use uniform representation of comparisons for better simplification.
author Ziv Scully <ziv@mit.edu>
date Mon, 20 Jul 2015 23:25:44 -0700
parents da7d026d1a94
children e09c3dc102ef
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@2243 148 (* Guaranteed to have all negation pushed to the atoms. *)
ziv@2243 149 datatype 'atom formula' =
ziv@2243 150 Atom' of 'atom
ziv@2243 151 | Combo' of junctionType * 'atom formula' list
ziv@2243 152
ziv@2234 153 val flipJt = fn Conj => Disj | Disj => Conj
ziv@2216 154
ziv@2236 155 fun concatMap f xs = List.concat (map f xs)
ziv@2216 156
ziv@2216 157 val rec cartesianProduct : 'a list list -> 'a list list =
ziv@2216 158 fn [] => [[]]
ziv@2236 159 | (xs :: xss) => concatMap (fn ys => concatMap (fn x => [x :: ys]) xs)
ziv@2236 160 (cartesianProduct xss)
ziv@2216 161
ziv@2218 162 (* Pushes all negation to the atoms.*)
ziv@2244 163 fun pushNegate (normalizeAtom : bool * 'atom -> 'atom) (negating : bool) =
ziv@2244 164 fn Atom x => Atom' (normalizeAtom (negating, x))
ziv@2244 165 | Negate f => pushNegate normalizeAtom (not negating) f
ziv@2244 166 | Combo (j, fs) => Combo' (if negating then flipJt j else j,
ziv@2244 167 map (pushNegate normalizeAtom negating) fs)
ziv@2218 168
ziv@2218 169 val rec flatten =
ziv@2243 170 fn Combo' (_, [f]) => flatten f
ziv@2243 171 | Combo' (j, fs) =>
ziv@2243 172 Combo' (j, List.foldr (fn (f, acc) =>
ziv@2243 173 case f of
ziv@2243 174 Combo' (j', fs') =>
ziv@2243 175 if j = j' orelse length fs' = 1
ziv@2243 176 then fs' @ acc
ziv@2243 177 else f :: acc
ziv@2243 178 | _ => f :: acc)
ziv@2243 179 []
ziv@2243 180 (map flatten fs))
ziv@2218 181 | f => f
ziv@2218 182
ziv@2243 183 (* [simplify] operates on the desired normal form. E.g., if [junc] is [Disj],
ziv@2243 184 consider the list of lists to be a disjunction of conjunctions. *)
ziv@2237 185 fun normalize' (simplify : 'a list list -> 'a list list)
ziv@2235 186 (junc : junctionType) =
ziv@2216 187 let
ziv@2235 188 fun norm junc =
ziv@2237 189 simplify
ziv@2243 190 o (fn Atom' x => [[x]]
ziv@2243 191 | Combo' (j, fs) =>
ziv@2235 192 let
ziv@2236 193 val fss = map (norm junc) fs
ziv@2235 194 in
ziv@2236 195 if j = junc
ziv@2236 196 then List.concat fss
ziv@2236 197 else map List.concat (cartesianProduct fss)
ziv@2235 198 end)
ziv@2216 199 in
ziv@2235 200 norm junc
ziv@2216 201 end
ziv@2216 202
ziv@2244 203 fun normalize simplify normalizeAtom junc =
ziv@2243 204 normalize' simplify junc
ziv@2235 205 o flatten
ziv@2244 206 o pushNegate normalizeAtom false
ziv@2216 207
ziv@2221 208 fun mapFormula mf =
ziv@2221 209 fn Atom x => Atom (mf x)
ziv@2221 210 | Negate f => Negate (mapFormula mf f)
ziv@2235 211 | Combo (j, fs) => Combo (j, map (mapFormula mf) fs)
ziv@2216 212
ziv@2230 213
ziv@2215 214 (* SQL analysis. *)
ziv@2213 215
ziv@2240 216 structure CmpKey = struct
ziv@2235 217
ziv@2235 218 type ord_key = Sql.cmp
ziv@2235 219
ziv@2235 220 val compare =
ziv@2235 221 fn (Sql.Eq, Sql.Eq) => EQUAL
ziv@2235 222 | (Sql.Eq, _) => LESS
ziv@2235 223 | (_, Sql.Eq) => GREATER
ziv@2235 224 | (Sql.Ne, Sql.Ne) => EQUAL
ziv@2235 225 | (Sql.Ne, _) => LESS
ziv@2235 226 | (_, Sql.Ne) => GREATER
ziv@2235 227 | (Sql.Lt, Sql.Lt) => EQUAL
ziv@2235 228 | (Sql.Lt, _) => LESS
ziv@2235 229 | (_, Sql.Lt) => GREATER
ziv@2235 230 | (Sql.Le, Sql.Le) => EQUAL
ziv@2235 231 | (Sql.Le, _) => LESS
ziv@2235 232 | (_, Sql.Le) => GREATER
ziv@2235 233 | (Sql.Gt, Sql.Gt) => EQUAL
ziv@2235 234 | (Sql.Gt, _) => LESS
ziv@2235 235 | (_, Sql.Gt) => GREATER
ziv@2235 236 | (Sql.Ge, Sql.Ge) => EQUAL
ziv@2235 237
ziv@2235 238 end
ziv@2235 239
ziv@2216 240 val rec chooseTwos : 'a list -> ('a * 'a) list =
ziv@2216 241 fn [] => []
ziv@2216 242 | x :: ys => map (fn y => (x, y)) ys @ chooseTwos ys
ziv@2213 243
ziv@2237 244 fun removeRedundant madeRedundantBy zs =
ziv@2237 245 let
ziv@2237 246 fun removeRedundant' (xs, ys) =
ziv@2237 247 case xs of
ziv@2237 248 [] => ys
ziv@2237 249 | x :: xs' =>
ziv@2237 250 removeRedundant' (xs',
ziv@2237 251 if List.exists (fn y => madeRedundantBy (x, y)) (xs' @ ys)
ziv@2237 252 then ys
ziv@2237 253 else x :: ys)
ziv@2237 254 in
ziv@2237 255 removeRedundant' (zs, [])
ziv@2237 256 end
ziv@2237 257
ziv@2216 258 datatype atomExp =
ziv@2216 259 QueryArg of int
ziv@2216 260 | DmlRel of int
ziv@2216 261 | Prim of Prim.t
ziv@2216 262 | Field of string * string
ziv@2216 263
ziv@2216 264 structure AtomExpKey : ORD_KEY = struct
ziv@2216 265
ziv@2234 266 type ord_key = atomExp
ziv@2216 267
ziv@2234 268 val compare =
ziv@2234 269 fn (QueryArg n1, QueryArg n2) => Int.compare (n1, n2)
ziv@2234 270 | (QueryArg _, _) => LESS
ziv@2234 271 | (_, QueryArg _) => GREATER
ziv@2234 272 | (DmlRel n1, DmlRel n2) => Int.compare (n1, n2)
ziv@2234 273 | (DmlRel _, _) => LESS
ziv@2234 274 | (_, DmlRel _) => GREATER
ziv@2234 275 | (Prim p1, Prim p2) => Prim.compare (p1, p2)
ziv@2234 276 | (Prim _, _) => LESS
ziv@2234 277 | (_, Prim _) => GREATER
ziv@2234 278 | (Field (t1, f1), Field (t2, f2)) =>
ziv@2234 279 case String.compare (t1, t2) of
ziv@2234 280 EQUAL => String.compare (f1, f2)
ziv@2234 281 | ord => ord
ziv@2216 282
ziv@2216 283 end
ziv@2216 284
ziv@2244 285 structure AtomOptionKey = OptionKeyFn(AtomExpKey)
ziv@2244 286
ziv@2216 287 structure UF = UnionFindFn(AtomExpKey)
ziv@2234 288
ziv@2235 289 structure ConflictMaps = struct
ziv@2235 290
ziv@2235 291 structure TK = TripleKeyFn(structure I = CmpKey
ziv@2244 292 structure J = AtomOptionKey
ziv@2244 293 structure K = AtomOptionKey)
ziv@2244 294 structure TS : ORD_SET = BinarySetFn(TK)
ziv@2235 295
ziv@2235 296 val toKnownEquality =
ziv@2235 297 (* [NONE] here means unkown. Anything that isn't a comparison between two
ziv@2235 298 knowns shouldn't be used, and simply dropping unused terms is okay in
ziv@2235 299 disjunctive normal form. *)
ziv@2235 300 fn (Sql.Eq, SOME e1, SOME e2) => SOME (e1, e2)
ziv@2235 301 | _ => NONE
ziv@2235 302
ziv@2235 303 val equivClasses : (Sql.cmp * atomExp option * atomExp option) list -> atomExp list list =
ziv@2235 304 UF.classes
ziv@2235 305 o List.foldl UF.union' UF.empty
ziv@2235 306 o List.mapPartial toKnownEquality
ziv@2235 307
ziv@2235 308 fun addToEqs (eqs, n, e) =
ziv@2235 309 case IM.find (eqs, n) of
ziv@2235 310 (* Comparing to a constant is probably better than comparing to a
ziv@2235 311 variable? Checking that existing constants match a new ones is
ziv@2235 312 handled by [accumulateEqs]. *)
ziv@2235 313 SOME (Prim _) => eqs
ziv@2235 314 | _ => IM.insert (eqs, n, e)
ziv@2235 315
ziv@2235 316 val accumulateEqs =
ziv@2235 317 (* [NONE] means we have a contradiction. *)
ziv@2235 318 fn (_, NONE) => NONE
ziv@2235 319 | ((Prim p1, Prim p2), eqso) =>
ziv@2235 320 (case Prim.compare (p1, p2) of
ziv@2235 321 EQUAL => eqso
ziv@2235 322 | _ => NONE)
ziv@2235 323 | ((QueryArg n, Prim p), SOME eqs) => SOME (addToEqs (eqs, n, Prim p))
ziv@2235 324 | ((QueryArg n, DmlRel r), SOME eqs) => SOME (addToEqs (eqs, n, DmlRel r))
ziv@2235 325 | ((Prim p, QueryArg n), SOME eqs) => SOME (addToEqs (eqs, n, Prim p))
ziv@2235 326 | ((DmlRel r, QueryArg n), SOME eqs) => SOME (addToEqs (eqs, n, DmlRel r))
ziv@2235 327 (* TODO: deal with equalities between [DmlRel]s and [Prim]s.
ziv@2235 328 This would involve guarding the invalidation with a check for the
ziv@2235 329 relevant comparisons. *)
ziv@2235 330 | (_, eqso) => eqso
ziv@2235 331
ziv@2235 332 val eqsOfClass : atomExp list -> atomExp IM.map option =
ziv@2235 333 List.foldl accumulateEqs (SOME IM.empty)
ziv@2235 334 o chooseTwos
ziv@2235 335
ziv@2235 336 fun toAtomExps rel (cmp, e1, e2) =
ziv@2235 337 let
ziv@2235 338 val qa =
ziv@2235 339 (* Here [NONE] means unkown. *)
ziv@2235 340 fn Sql.SqConst p => SOME (Prim p)
ziv@2235 341 | Sql.Field tf => SOME (Field tf)
ziv@2235 342 | Sql.Inj (EPrim p, _) => SOME (Prim p)
ziv@2235 343 | Sql.Inj (ERel n, _) => SOME (rel n)
ziv@2235 344 (* We can't deal with anything else, e.g., CURRENT_TIMESTAMP
ziv@2235 345 becomes Sql.Unmodeled, which becomes NONE here. *)
ziv@2235 346 | _ => NONE
ziv@2235 347 in
ziv@2235 348 (cmp, qa e1, qa e2)
ziv@2235 349 end
ziv@2235 350
ziv@2244 351 val negateCmp =
ziv@2244 352 fn Sql.Eq => Sql.Ne
ziv@2244 353 | Sql.Ne => Sql.Eq
ziv@2244 354 | Sql.Lt => Sql.Ge
ziv@2244 355 | Sql.Le => Sql.Gt
ziv@2244 356 | Sql.Gt => Sql.Le
ziv@2244 357 | Sql.Ge => Sql.Lt
ziv@2244 358
ziv@2244 359 fun normalizeAtom (negating, (cmp, e1, e2)) =
ziv@2244 360 (* Restricting to Le/Lt and sorting the expressions in Eq/Ne helps with
ziv@2244 361 simplification, where we put the triples in sets. *)
ziv@2244 362 case (if negating then negateCmp cmp else cmp) of
ziv@2244 363 Sql.Eq => (case AtomOptionKey.compare (e1, e2) of
ziv@2244 364 LESS => (Sql.Eq, e2, e1)
ziv@2244 365 | _ => (Sql.Eq, e1, e2))
ziv@2244 366 | Sql.Ne => (case AtomOptionKey.compare (e1, e2) of
ziv@2244 367 LESS => (Sql.Ne, e2, e1)
ziv@2244 368 | _ => (Sql.Ne, e1, e2))
ziv@2244 369 | Sql.Lt => (Sql.Lt, e1, e2)
ziv@2244 370 | Sql.Le => (Sql.Le, e1, e2)
ziv@2244 371 | Sql.Gt => (Sql.Lt, e2, e1)
ziv@2244 372 | Sql.Ge => (Sql.Le, e2, e1)
ziv@2235 373
ziv@2235 374 val markQuery : (Sql.cmp * Sql.sqexp * Sql.sqexp) formula ->
ziv@2235 375 (Sql.cmp * atomExp option * atomExp option) formula =
ziv@2235 376 mapFormula (toAtomExps QueryArg)
ziv@2235 377
ziv@2235 378 val markDml : (Sql.cmp * Sql.sqexp * Sql.sqexp) formula ->
ziv@2235 379 (Sql.cmp * atomExp option * atomExp option) formula =
ziv@2235 380 mapFormula (toAtomExps DmlRel)
ziv@2235 381 (* No eqs should have key conflicts because no variable is in two
ziv@2235 382 equivalence classes, so the [#1] could be [#2]. *)
ziv@2235 383
ziv@2235 384 val mergeEqs : (atomExp IntBinaryMap.map option list
ziv@2235 385 -> atomExp IntBinaryMap.map option) =
ziv@2235 386 List.foldr (fn (SOME eqs, SOME acc) => SOME (IM.unionWith #1 (eqs, acc)) | _ => NONE)
ziv@2235 387 (SOME IM.empty)
ziv@2235 388
ziv@2239 389 val simplify =
ziv@2239 390 map TS.listItems
ziv@2239 391 o removeRedundant (fn (x, y) => TS.isSubset (y, x))
ziv@2239 392 o map (fn xs => TS.addList (TS.empty, xs))
ziv@2239 393
ziv@2235 394 fun dnf (fQuery, fDml) =
ziv@2244 395 normalize simplify normalizeAtom Disj (Combo (Conj, [markQuery fQuery, markDml fDml]))
ziv@2235 396
ziv@2235 397 val conflictMaps = List.mapPartial (mergeEqs o map eqsOfClass o equivClasses) o dnf
ziv@2235 398
ziv@2235 399 end
ziv@2235 400
ziv@2235 401 val conflictMaps = ConflictMaps.conflictMaps
ziv@2213 402
ziv@2216 403 val rec sqexpToFormula =
ziv@2234 404 fn Sql.SqTrue => Combo (Conj, [])
ziv@2234 405 | Sql.SqFalse => Combo (Disj, [])
ziv@2216 406 | Sql.SqNot e => Negate (sqexpToFormula e)
ziv@2216 407 | Sql.Binop (Sql.RCmp c, e1, e2) => Atom (c, e1, e2)
ziv@2234 408 | Sql.Binop (Sql.RLop l, p1, p2) => Combo (case l of Sql.And => Conj | Sql.Or => Disj,
ziv@2216 409 [sqexpToFormula p1, sqexpToFormula p2])
ziv@2216 410 (* ASK: any other sqexps that can be props? *)
ziv@2216 411 | _ => raise Match
ziv@2213 412
ziv@2218 413 fun renameTables tablePairs =
ziv@2216 414 let
ziv@2216 415 fun renameString table =
ziv@2216 416 case List.find (fn (_, t) => table = t) tablePairs of
ziv@2216 417 NONE => table
ziv@2216 418 | SOME (realTable, _) => realTable
ziv@2216 419 val renameSqexp =
ziv@2216 420 fn Sql.Field (table, field) => Sql.Field (renameString table, field)
ziv@2216 421 | e => e
ziv@2218 422 fun renameAtom (cmp, e1, e2) = (cmp, renameSqexp e1, renameSqexp e2)
ziv@2216 423 in
ziv@2218 424 mapFormula renameAtom
ziv@2216 425 end
ziv@2218 426
ziv@2218 427 val rec queryToFormula =
ziv@2234 428 fn Sql.Query1 {Where = NONE, ...} => Combo (Conj, [])
ziv@2218 429 | Sql.Query1 {From = tablePairs, Where = SOME e, ...} =>
ziv@2218 430 renameTables tablePairs (sqexpToFormula e)
ziv@2234 431 | Sql.Union (q1, q2) => Combo (Disj, [queryToFormula q1, queryToFormula q2])
ziv@2216 432
ziv@2218 433 fun valsToFormula (table, vals) =
ziv@2234 434 Combo (Conj, map (fn (field, v) => Atom (Sql.Eq, Sql.Field (table, field), v)) vals)
ziv@2218 435
ziv@2216 436 val rec dmlToFormula =
ziv@2221 437 fn Sql.Insert (table, vals) => valsToFormula (table, vals)
ziv@2218 438 | Sql.Delete (table, wher) => renameTables [(table, "T")] (sqexpToFormula wher)
ziv@2218 439 | Sql.Update (table, vals, wher) =>
ziv@2218 440 let
ziv@2221 441 val fWhere = sqexpToFormula wher
ziv@2221 442 val fVals = valsToFormula (table, vals)
ziv@2237 443 val modifiedFields = SS.addList (SS.empty, map #1 vals)
ziv@2221 444 (* TODO: don't use field name hack. *)
ziv@2221 445 val markField =
ziv@2237 446 fn e as Sql.Field (t, v) => if SS.member (modifiedFields, v)
ziv@2237 447 then Sql.Field (t, v ^ "'")
ziv@2237 448 else e
ziv@2221 449 | e => e
ziv@2221 450 val mark = mapFormula (fn (cmp, e1, e2) => (cmp, markField e1, markField e2))
ziv@2218 451 in
ziv@2218 452 renameTables [(table, "T")]
ziv@2234 453 (Combo (Disj, [Combo (Conj, [fVals, mark fWhere]),
ziv@2244 454 Combo (Conj, [mark fVals, fWhere])]))
ziv@2218 455 end
ziv@2213 456
ziv@2213 457 val rec tablesQuery =
ziv@2216 458 fn Sql.Query1 {From = tablePairs, ...} => SS.fromList (map #1 tablePairs)
ziv@2216 459 | Sql.Union (q1, q2) => SS.union (tablesQuery q1, tablesQuery q2)
ziv@2213 460
ziv@2213 461 val tableDml =
ziv@2216 462 fn Sql.Insert (tab, _) => tab
ziv@2216 463 | Sql.Delete (tab, _) => tab
ziv@2216 464 | Sql.Update (tab, _, _) => tab
ziv@2213 465
ziv@2213 466
ziv@2213 467 (* Program instrumentation. *)
ziv@2213 468
ziv@2234 469 val varName =
ziv@2234 470 let
ziv@2234 471 val varNumber = ref 0
ziv@2234 472 in
ziv@2234 473 fn s => (varNumber := !varNumber + 1; s ^ Int.toString (!varNumber))
ziv@2234 474 end
ziv@2234 475
ziv@2233 476 val {check, store, flush, ...} = getCache ()
ziv@2233 477
ziv@2230 478 val dummyLoc = ErrorMsg.dummySpan
ziv@2216 479
ziv@2230 480 fun stringExp s = (EPrim (Prim.String (Prim.Normal, s)), dummyLoc)
ziv@2230 481
ziv@2230 482 val stringTyp = (TFfi ("Basis", "string"), dummyLoc)
ziv@2213 483
ziv@2213 484 val sequence =
ziv@2213 485 fn (exp :: exps) =>
ziv@2213 486 let
ziv@2230 487 val loc = dummyLoc
ziv@2213 488 in
ziv@2213 489 List.foldl (fn (e', seq) => ESeq ((seq, loc), (e', loc))) exp exps
ziv@2213 490 end
ziv@2213 491 | _ => raise Match
ziv@2213 492
ziv@2215 493 (* Always increments negative indices because that's what we need later. *)
ziv@2215 494 fun incRelsBound bound inc =
ziv@2215 495 MonoUtil.Exp.mapB
ziv@2215 496 {typ = fn x => x,
ziv@2215 497 exp = fn level =>
ziv@2215 498 (fn ERel n => ERel (if n >= level orelse n < 0 then n + inc else n)
ziv@2215 499 | x => x),
ziv@2215 500 bind = fn (level, MonoUtil.Exp.RelE _) => level + 1 | (level, _) => level}
ziv@2215 501 bound
ziv@2215 502
ziv@2215 503 val incRels = incRelsBound 0
ziv@2213 504
ziv@2223 505 fun cacheWrap (query, i, urlifiedRel0, resultTyp, args) =
ziv@2213 506 let
ziv@2223 507 val () = ffiInfo := {index = i, params = length args} :: !ffiInfo
ziv@2230 508 val loc = dummyLoc
ziv@2223 509 (* We ensure before this step that all arguments aren't effectful.
ziv@2227 510 by turning them into local variables as needed. *)
ziv@2230 511 val argsInc = map (incRels 1) args
ziv@2233 512 val check = (check (i, args), dummyLoc)
ziv@2233 513 val store = (store (i, argsInc, urlifiedRel0), dummyLoc)
ziv@2223 514 val rel0 = (ERel 0, loc)
ziv@2213 515 in
ziv@2223 516 ECase (check,
ziv@2223 517 [((PNone stringTyp, loc),
ziv@2234 518 (ELet (varName "q", resultTyp, query, (ESeq (store, rel0), loc)), loc)),
ziv@2234 519 ((PSome (stringTyp, (PVar (varName "hit", stringTyp), loc)), loc),
ziv@2223 520 (* Boolean is false because we're not unurlifying from a cookie. *)
ziv@2223 521 (EUnurlify (rel0, resultTyp, false), loc))],
ziv@2223 522 {disc = stringTyp, result = resultTyp})
ziv@2213 523 end
ziv@2213 524
ziv@2213 525 fun fileMapfold doExp file start =
ziv@2213 526 case MonoUtil.File.mapfold {typ = Search.return2,
ziv@2213 527 exp = fn x => (fn s => Search.Continue (doExp x s)),
ziv@2213 528 decl = Search.return2} file start of
ziv@2213 529 Search.Continue x => x
ziv@2213 530 | Search.Return _ => raise Match
ziv@2213 531
ziv@2213 532 fun fileMap doExp file = #1 (fileMapfold (fn x => fn _ => (doExp x, ())) file ())
ziv@2213 533
ziv@2221 534 fun factorOutNontrivial text =
ziv@2221 535 let
ziv@2230 536 val loc = dummyLoc
ziv@2221 537 fun strcat (e1, e2) = (EStrcat (e1, e2), loc)
ziv@2221 538 val chunks = Sql.chunkify text
ziv@2221 539 val (newText, newVariables) =
ziv@2221 540 (* Important that this is foldr (to oppose foldl below). *)
ziv@2221 541 List.foldr
ziv@2221 542 (fn (chunk, (qText, newVars)) =>
ziv@2221 543 (* Variable bound to the head of newBs will have the lowest index. *)
ziv@2221 544 case chunk of
ziv@2221 545 Sql.Exp (e as (EPrim _, _)) => (strcat (e, qText), newVars)
ziv@2221 546 | Sql.Exp e =>
ziv@2221 547 let
ziv@2221 548 val n = length newVars
ziv@2221 549 in
ziv@2221 550 (* This is the (n + 1)th new variable, so there are
ziv@2221 551 already n new variables bound, so we increment
ziv@2221 552 indices by n. *)
ziv@2221 553 (strcat ((ERel (~(n+1)), loc), qText), incRels n e :: newVars)
ziv@2221 554 end
ziv@2221 555 | Sql.String s => (strcat (stringExp s, qText), newVars))
ziv@2221 556 (stringExp "", [])
ziv@2221 557 chunks
ziv@2221 558 fun wrapLets e' =
ziv@2221 559 (* Important that this is foldl (to oppose foldr above). *)
ziv@2234 560 List.foldl (fn (v, e') => ELet (varName "sqlArg", stringTyp, v, (e', loc)))
ziv@2221 561 e'
ziv@2221 562 newVariables
ziv@2221 563 val numArgs = length newVariables
ziv@2221 564 in
ziv@2221 565 (newText, wrapLets, numArgs)
ziv@2221 566 end
ziv@2221 567
ziv@2215 568 fun addChecking file =
ziv@2213 569 let
ziv@2223 570 fun doExp (queryInfo as (tableToIndices, indexToQueryNumArgs, index)) =
ziv@2223 571 fn e' as EQuery {query = origQueryText,
ziv@2223 572 sqlcacheInfo = urlifiedRel0,
ziv@2223 573 state = resultTyp,
ziv@2223 574 initial, body, tables, exps} =>
ziv@2213 575 let
ziv@2221 576 val (newQueryText, wrapLets, numArgs) = factorOutNontrivial origQueryText
ziv@2215 577 (* Increment once for each new variable just made. *)
ziv@2221 578 val queryExp = incRels numArgs
ziv@2215 579 (EQuery {query = newQueryText,
ziv@2223 580 sqlcacheInfo = urlifiedRel0,
ziv@2223 581 state = resultTyp,
ziv@2215 582 initial = initial,
ziv@2215 583 body = body,
ziv@2215 584 tables = tables,
ziv@2223 585 exps = exps},
ziv@2230 586 dummyLoc)
ziv@2215 587 val (EQuery {query = queryText, ...}, _) = queryExp
ziv@2235 588 (* DEBUG *)
ziv@2221 589 val () = Print.preface ("sqlcache> ", (MonoPrint.p_exp MonoEnv.empty queryText))
ziv@2230 590 val args = List.tabulate (numArgs, fn n => (ERel n, dummyLoc))
ziv@2213 591 fun bind x f = Option.mapPartial f x
ziv@2215 592 fun guard b x = if b then x else NONE
ziv@2215 593 (* DEBUG: set first boolean argument to true to turn on printing. *)
ziv@2215 594 fun safe bound = not o effectful true (effectfulMap file) false bound
ziv@2213 595 val attempt =
ziv@2213 596 (* Ziv misses Haskell's do notation.... *)
ziv@2215 597 guard (safe 0 queryText andalso safe 0 initial andalso safe 2 body) (
ziv@2216 598 bind (Sql.parse Sql.query queryText) (fn queryParsed =>
ziv@2223 599 SOME (wrapLets (cacheWrap (queryExp, index, urlifiedRel0, resultTyp, args)),
ziv@2218 600 (SS.foldr (fn (tab, qi) => SIMM.insert (qi, tab, index))
ziv@2218 601 tableToIndices
ziv@2218 602 (tablesQuery queryParsed),
ziv@2223 603 IM.insert (indexToQueryNumArgs, index, (queryParsed, numArgs)),
ziv@2223 604 index + 1))))
ziv@2213 605 in
ziv@2213 606 case attempt of
ziv@2213 607 SOME pair => pair
ziv@2213 608 | NONE => (e', queryInfo)
ziv@2213 609 end
ziv@2213 610 | e' => (e', queryInfo)
ziv@2213 611 in
ziv@2223 612 fileMapfold (fn exp => fn state => doExp state exp) file (SIMM.empty, IM.empty, 0)
ziv@2213 613 end
ziv@2213 614
ziv@2235 615 structure Invalidations = struct
ziv@2235 616
ziv@2235 617 val loc = dummyLoc
ziv@2235 618
ziv@2235 619 val optionAtomExpToExp =
ziv@2235 620 fn NONE => (ENone stringTyp, loc)
ziv@2235 621 | SOME e => (ESome (stringTyp,
ziv@2235 622 (case e of
ziv@2235 623 DmlRel n => ERel n
ziv@2235 624 | Prim p => EPrim p
ziv@2235 625 (* TODO: make new type containing only these two. *)
ziv@2235 626 | _ => raise Match,
ziv@2235 627 loc)),
ziv@2235 628 loc)
ziv@2235 629
ziv@2235 630 fun eqsToInvalidation numArgs eqs =
ziv@2235 631 let
ziv@2235 632 fun inv n = if n < 0 then [] else IM.find (eqs, n) :: inv (n - 1)
ziv@2235 633 in
ziv@2235 634 inv (numArgs - 1)
ziv@2235 635 end
ziv@2235 636
ziv@2235 637 (* Tests if [ys] makes [xs] a redundant cache invalidation. [NONE] here
ziv@2235 638 represents unknown, which means a wider invalidation. *)
ziv@2235 639 val rec madeRedundantBy : atomExp option list * atomExp option list -> bool =
ziv@2235 640 fn ([], []) => true
ziv@2237 641 | (_ :: xs, NONE :: ys) => madeRedundantBy (xs, ys)
ziv@2235 642 | (SOME x :: xs, SOME y :: ys) => (case AtomExpKey.compare (x, y) of
ziv@2235 643 EQUAL => madeRedundantBy (xs, ys)
ziv@2235 644 | _ => false)
ziv@2235 645 | _ => false
ziv@2235 646
ziv@2235 647 fun eqss (query, dml) = conflictMaps (queryToFormula query, dmlToFormula dml)
ziv@2235 648
ziv@2235 649 fun invalidations ((query, numArgs), dml) =
ziv@2235 650 (map (map optionAtomExpToExp)
ziv@2237 651 o removeRedundant madeRedundantBy
ziv@2235 652 o map (eqsToInvalidation numArgs)
ziv@2235 653 o eqss)
ziv@2235 654 (query, dml)
ziv@2235 655
ziv@2235 656 end
ziv@2235 657
ziv@2235 658 val invalidations = Invalidations.invalidations
ziv@2235 659
ziv@2235 660 (* DEBUG *)
ziv@2235 661 val gunk : ((Sql.query * int) * Sql.dml) list ref = ref []
ziv@2216 662
ziv@2223 663 fun addFlushing (file, (tableToIndices, indexToQueryNumArgs, _)) =
ziv@2213 664 let
ziv@2221 665 val flushes = List.concat o
ziv@2233 666 map (fn (i, argss) => map (fn args => flush (i, args)) argss)
ziv@2213 667 val doExp =
ziv@2221 668 fn EDml (origDmlText, failureMode) =>
ziv@2213 669 let
ziv@2221 670 val (newDmlText, wrapLets, numArgs) = factorOutNontrivial origDmlText
ziv@2221 671 val dmlText = incRels numArgs newDmlText
ziv@2221 672 val dmlExp = EDml (dmlText, failureMode)
ziv@2235 673 (* DEBUG *)
ziv@2221 674 val () = Print.preface ("sqlcache> ", (MonoPrint.p_exp MonoEnv.empty dmlText))
ziv@2221 675 val invs =
ziv@2216 676 case Sql.parse Sql.dml dmlText of
ziv@2218 677 SOME dmlParsed =>
ziv@2221 678 map (fn i => (case IM.find (indexToQueryNumArgs, i) of
ziv@2221 679 SOME queryNumArgs =>
ziv@2235 680 (* DEBUG *)
ziv@2235 681 (gunk := (queryNumArgs, dmlParsed) :: !gunk;
ziv@2235 682 (i, invalidations (queryNumArgs, dmlParsed)))
ziv@2221 683 (* TODO: fail more gracefully. *)
ziv@2221 684 | NONE => raise Match))
ziv@2221 685 (SIMM.findList (tableToIndices, tableDml dmlParsed))
ziv@2221 686 (* TODO: fail more gracefully. *)
ziv@2221 687 | NONE => raise Match
ziv@2213 688 in
ziv@2221 689 wrapLets (sequence (flushes invs @ [dmlExp]))
ziv@2213 690 end
ziv@2213 691 | e' => e'
ziv@2213 692 in
ziv@2235 693 (* DEBUG *)
ziv@2235 694 gunk := [];
ziv@2213 695 fileMap doExp file
ziv@2213 696 end
ziv@2213 697
ziv@2221 698 val inlineSql =
ziv@2221 699 let
ziv@2221 700 val doExp =
ziv@2221 701 (* TODO: EQuery, too? *)
ziv@2221 702 (* ASK: should this live in [MonoOpt]? *)
ziv@2221 703 fn EDml ((ECase (disc, cases, {disc = dTyp, ...}), loc), failureMode) =>
ziv@2221 704 let
ziv@2221 705 val newCases = map (fn (p, e) => (p, (EDml (e, failureMode), loc))) cases
ziv@2221 706 in
ziv@2221 707 ECase (disc, newCases, {disc = dTyp, result = (TRecord [], loc)})
ziv@2221 708 end
ziv@2221 709 | e => e
ziv@2221 710 in
ziv@2221 711 fileMap doExp
ziv@2221 712 end
ziv@2221 713
ziv@2213 714 fun go file =
ziv@2213 715 let
ziv@2235 716 (* TODO: do something nicer than [Sql] being in one of two modes. *)
ziv@2227 717 val () = (resetFfiInfo (); Sql.sqlcacheMode := true)
ziv@2221 718 val file' = addFlushing (addChecking (inlineSql file))
ziv@2215 719 val () = Sql.sqlcacheMode := false
ziv@2213 720 in
ziv@2221 721 file'
ziv@2213 722 end
ziv@2213 723
ziv@2209 724 end