annotate src/sqlcache.sml @ 2305:9083b44bad0a

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