1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #[allow(missing_doc)];
14 use digest::DigestUtil;
17 use serialize::{Encoder, Encodable, Decoder, Decodable};
22 use std::comm::{PortOne, oneshot, send_one, recv_one};
23 use std::either::{Either, Left, Right};
31 * This is a loose clone of the [fbuild build system](https://github.com/felix-lang/fbuild),
32 * made a touch more generic (not wired to special cases on files) and much
33 * less metaprogram-y due to rust's comparative weakness there, relative to
36 * It's based around _imperative builds_ that happen to have some function
37 * calls cached. That is, it's _just_ a mechanism for describing cached
38 * functions. This makes it much simpler and smaller than a "build system"
39 * that produces an IR and evaluates it. The evaluation order is normal
40 * function calls. Some of them just return really quickly.
42 * A cached function consumes and produces a set of _works_. A work has a
43 * name, a kind (that determines how the value is to be checked for
44 * freshness) and a value. Works must also be (de)serializable. Some
48 * ------------------------
53 * Works are conceptually single units, but we store them most of the time
54 * in maps of the form (type,name) => value. These are WorkMaps.
56 * A cached function divides the works it's interested in into inputs and
57 * outputs, and subdivides those into declared (input) works and
58 * discovered (input and output) works.
60 * A _declared_ input or is one that is given to the workcache before
61 * any work actually happens, in the "prep" phase. Even when a function's
62 * work-doing part (the "exec" phase) never gets called, it has declared
63 * inputs, which can be checked for freshness (and potentially
64 * used to determine that the function can be skipped).
66 * The workcache checks _all_ works for freshness, but uses the set of
67 * discovered outputs from the _previous_ exec (which it will re-discover
68 * and re-record each time the exec phase runs).
70 * Therefore the discovered works cached in the db might be a
71 * mis-approximation of the current discoverable works, but this is ok for
72 * the following reason: we assume that if an artifact A changed from
73 * depending on B,C,D to depending on B,C,D,E, then A itself changed (as
74 * part of the change-in-dependencies), so we will be ok.
76 * Each function has a single discriminated output work called its _result_.
77 * This is only different from other works in that it is returned, by value,
78 * from a call to the cacheable function; the other output works are used in
79 * passing to invalidate dependencies elsewhere in the cache, but do not
80 * otherwise escape from a function invocation. Most functions only have one
81 * output work anyways.
83 * A database (the central store of a workcache) stores a mappings:
85 * (fn_name,{declared_input}) => ({discovered_input},
86 * {discovered_output},result)
88 * (Note: fbuild, which workcache is based on, has the concept of a declared
89 * output as separate from a discovered output. This distinction exists only
90 * as an artifact of how fbuild works: via annotations on function types
91 * and metaprogramming, with explicit dependency declaration as a fallback.
92 * Workcache is more explicit about dependencies, and as such treats all
93 * outputs the same, as discovered-during-the-last-run.)
97 #[deriving(Clone, Eq, Encodable, Decodable, TotalOrd, TotalEq)]
104 pub fn new(kind: &str, name: &str) -> WorkKey {
106 kind: kind.to_owned(),
107 name: name.to_owned(),
112 #[deriving(Clone, Eq, Encodable, Decodable)]
113 struct WorkMap(TreeMap<WorkKey, ~str>);
116 fn new() -> WorkMap { WorkMap(TreeMap::new()) }
121 db_cache: TreeMap<~str, ~str>,
127 pub fn new(p: Path) -> Database {
130 db_cache: TreeMap::new(),
135 pub fn prepare(&self,
137 declared_inputs: &WorkMap)
138 -> Option<(WorkMap, WorkMap, ~str)> {
139 let k = json_encode(&(fn_name, declared_inputs));
140 match self.db_cache.find(&k) {
142 Some(v) => Some(json_decode(*v))
146 pub fn cache(&mut self,
148 declared_inputs: &WorkMap,
149 discovered_inputs: &WorkMap,
150 discovered_outputs: &WorkMap,
152 let k = json_encode(&(fn_name, declared_inputs));
153 let v = json_encode(&(discovered_inputs,
156 self.db_cache.insert(k,v);
162 // FIXME #4432: Fill in
168 pub fn new() -> Logger {
172 pub fn info(&self, i: &str) {
173 io::println(~"workcache: " + i);
181 freshness: TreeMap<~str,@fn(&str,&str)->bool>
185 ctxt: &'self Context,
187 declared_inputs: WorkMap,
191 discovered_inputs: WorkMap,
192 discovered_outputs: WorkMap
195 struct Work<'self, T> {
196 prep: &'self Prep<'self>,
197 res: Option<Either<T,PortOne<(Exec,T)>>>
200 fn json_encode<T:Encodable<json::Encoder>>(t: &T) -> ~str {
201 do io::with_str_writer |wr| {
202 let mut encoder = json::Encoder(wr);
203 t.encode(&mut encoder);
208 fn json_decode<T:Decodable<json::Decoder>>(s: &str) -> T {
209 do io::with_str_reader(s) |rdr| {
210 let j = result::unwrap(json::from_reader(rdr));
211 let mut decoder = json::Decoder(j);
212 Decodable::decode(&mut decoder)
216 fn digest<T:Encodable<json::Encoder>>(t: &T) -> ~str {
217 let mut sha = ~Sha1::new();
218 (*sha).input_str(json_encode(t));
222 fn digest_file(path: &Path) -> ~str {
223 let mut sha = ~Sha1::new();
224 let s = io::read_whole_file_str(path);
225 (*sha).input_str(*s.get_ref());
231 pub fn new(db: RWARC<Database>, lg: Logger, cfg: json::Object) -> Context {
236 freshness: TreeMap::new()
240 pub fn prep<'a>(&'a self, fn_name: &'a str) -> Prep<'a> {
241 Prep::new(self, fn_name)
244 pub fn with_prep<'a, T>(&'a self, fn_name: &'a str, blk: &fn(p: &mut Prep) -> T) -> T {
245 let mut p = self.prep(fn_name);
251 impl<'self> Prep<'self> {
252 fn new(ctxt: &'self Context, fn_name: &'self str) -> Prep<'self> {
256 declared_inputs: WorkMap::new()
261 impl<'self> Prep<'self> {
262 fn declare_input(&mut self, kind:&str, name:&str, val:&str) {
263 self.declared_inputs.insert(WorkKey::new(kind, name),
267 fn is_fresh(&self, cat: &str, kind: &str,
268 name: &str, val: &str) -> bool {
269 let k = kind.to_owned();
270 let f = self.ctxt.freshness.find(&k);
271 let fresh = match f {
272 None => fail!("missing freshness-function for '%s'", kind),
273 Some(f) => (*f)(name, val)
275 let lg = self.ctxt.logger;
277 lg.info(fmt!("%s %s:%s is fresh",
280 lg.info(fmt!("%s %s:%s is not fresh",
286 fn all_fresh(&self, cat: &str, map: &WorkMap) -> bool {
287 for map.iter().advance |(k, v)| {
288 if ! self.is_fresh(cat, k.kind, k.name, *v) {
296 Encodable<json::Encoder> +
297 Decodable<json::Decoder>>(
298 &'self self, blk: ~fn(&Exec) -> T) -> T {
299 self.exec_work(blk).unwrap()
302 fn exec_work<T:Send +
303 Encodable<json::Encoder> +
304 Decodable<json::Decoder>>( // FIXME(#5121)
305 &'self self, blk: ~fn(&Exec) -> T) -> Work<'self, T> {
306 let mut bo = Some(blk);
308 let cached = do self.ctxt.db.read |db| {
309 db.prepare(self.fn_name, &self.declared_inputs)
312 let res = match cached {
313 Some((ref disc_in, ref disc_out, ref res))
314 if self.all_fresh("declared input",&self.declared_inputs) &&
315 self.all_fresh("discovered input", disc_in) &&
316 self.all_fresh("discovered output", disc_out) => {
317 Left(json_decode(*res))
321 let (port, chan) = oneshot();
322 let blk = bo.take_unwrap();
323 let chan = Cell::new(chan);
327 discovered_inputs: WorkMap::new(),
328 discovered_outputs: WorkMap::new(),
330 let chan = chan.take();
332 send_one(chan, (exe, v));
342 Encodable<json::Encoder> +
343 Decodable<json::Decoder>>
344 Work<'self, T> { // FIXME(#5121)
346 pub fn new(p: &'self Prep<'self>, e: Either<T,PortOne<(Exec,T)>>) -> Work<'self, T> {
347 Work { prep: p, res: Some(e) }
350 pub fn unwrap(self) -> T {
351 let Work { prep, res } = self;
355 Some(Right(port)) => {
356 let (exe, v) = recv_one(port);
357 let s = json_encode(&v);
358 do prep.ctxt.db.write |db| {
359 db.cache(prep.fn_name,
360 &prep.declared_inputs,
361 &exe.discovered_inputs,
362 &exe.discovered_outputs,
374 use std::io::WriterUtil;
376 let pth = Path("foo.c");
378 let r = io::file_writer(&pth, [io::Create]);
379 r.get_ref().write_str("int main() { return 0; }");
382 let cx = Context::new(RWARC(Database::new(Path("db.json"))),
383 Logger::new(), TreeMap::new());
385 let s = do cx.with_prep("test1") |prep| {
386 prep.declare_input("file", pth.to_str(), digest_file(&pth));
387 do prep.exec |_exe| {
388 let out = Path("foo.o");
389 run::process_status("gcc", [~"foo.c", ~"-o", out.to_str()]);