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)];
16 use serialize::{Encoder, Encodable, Decoder, Decodable};
21 use std::comm::{PortOne, oneshot, send_one, recv_one};
22 use std::either::{Either, Left, Right};
29 * This is a loose clone of the [fbuild build system](https://github.com/felix-lang/fbuild),
30 * made a touch more generic (not wired to special cases on files) and much
31 * less metaprogram-y due to rust's comparative weakness there, relative to
34 * It's based around _imperative builds_ that happen to have some function
35 * calls cached. That is, it's _just_ a mechanism for describing cached
36 * functions. This makes it much simpler and smaller than a "build system"
37 * that produces an IR and evaluates it. The evaluation order is normal
38 * function calls. Some of them just return really quickly.
40 * A cached function consumes and produces a set of _works_. A work has a
41 * name, a kind (that determines how the value is to be checked for
42 * freshness) and a value. Works must also be (de)serializable. Some
46 * ------------------------
51 * Works are conceptually single units, but we store them most of the time
52 * in maps of the form (type,name) => value. These are WorkMaps.
54 * A cached function divides the works it's interested in into inputs and
55 * outputs, and subdivides those into declared (input) works and
56 * discovered (input and output) works.
58 * A _declared_ input or is one that is given to the workcache before
59 * any work actually happens, in the "prep" phase. Even when a function's
60 * work-doing part (the "exec" phase) never gets called, it has declared
61 * inputs, which can be checked for freshness (and potentially
62 * used to determine that the function can be skipped).
64 * The workcache checks _all_ works for freshness, but uses the set of
65 * discovered outputs from the _previous_ exec (which it will re-discover
66 * and re-record each time the exec phase runs).
68 * Therefore the discovered works cached in the db might be a
69 * mis-approximation of the current discoverable works, but this is ok for
70 * the following reason: we assume that if an artifact A changed from
71 * depending on B,C,D to depending on B,C,D,E, then A itself changed (as
72 * part of the change-in-dependencies), so we will be ok.
74 * Each function has a single discriminated output work called its _result_.
75 * This is only different from other works in that it is returned, by value,
76 * from a call to the cacheable function; the other output works are used in
77 * passing to invalidate dependencies elsewhere in the cache, but do not
78 * otherwise escape from a function invocation. Most functions only have one
79 * output work anyways.
81 * A database (the central store of a workcache) stores a mappings:
83 * (fn_name,{declared_input}) => ({discovered_input},
84 * {discovered_output},result)
86 * (Note: fbuild, which workcache is based on, has the concept of a declared
87 * output as separate from a discovered output. This distinction exists only
88 * as an artifact of how fbuild works: via annotations on function types
89 * and metaprogramming, with explicit dependency declaration as a fallback.
90 * Workcache is more explicit about dependencies, and as such treats all
91 * outputs the same, as discovered-during-the-last-run.)
95 #[deriving(Clone, Eq, Encodable, Decodable, TotalOrd, TotalEq)]
102 pub fn new(kind: &str, name: &str) -> WorkKey {
104 kind: kind.to_owned(),
105 name: name.to_owned(),
110 #[deriving(Clone, Eq, Encodable, Decodable)]
111 struct WorkMap(TreeMap<WorkKey, ~str>);
114 fn new() -> WorkMap { WorkMap(TreeMap::new()) }
119 db_cache: TreeMap<~str, ~str>,
125 pub fn new(p: Path) -> Database {
128 db_cache: TreeMap::new(),
133 pub fn prepare(&self,
135 declared_inputs: &WorkMap)
136 -> Option<(WorkMap, WorkMap, ~str)> {
137 let k = json_encode(&(fn_name, declared_inputs));
138 match self.db_cache.find(&k) {
140 Some(v) => Some(json_decode(*v))
144 pub fn cache(&mut self,
146 declared_inputs: &WorkMap,
147 discovered_inputs: &WorkMap,
148 discovered_outputs: &WorkMap,
150 let k = json_encode(&(fn_name, declared_inputs));
151 let v = json_encode(&(discovered_inputs,
154 self.db_cache.insert(k,v);
160 // FIXME #4432: Fill in
166 pub fn new() -> Logger {
170 pub fn info(&self, i: &str) {
171 io::println(~"workcache: " + i);
178 logger: RWArc<Logger>,
179 cfg: Arc<json::Object>,
180 freshness: Arc<TreeMap<~str,extern fn(&str,&str)->bool>>
184 ctxt: &'self Context,
186 declared_inputs: WorkMap,
190 discovered_inputs: WorkMap,
191 discovered_outputs: WorkMap
194 struct Work<'self, T> {
195 prep: &'self Prep<'self>,
196 res: Option<Either<T,PortOne<(Exec,T)>>>
199 fn json_encode<T:Encodable<json::Encoder>>(t: &T) -> ~str {
200 do io::with_str_writer |wr| {
201 let mut encoder = json::Encoder(wr);
202 t.encode(&mut encoder);
207 fn json_decode<T:Decodable<json::Decoder>>(s: &str) -> T {
208 do io::with_str_reader(s) |rdr| {
209 let j = json::from_reader(rdr).unwrap();
210 let mut decoder = json::Decoder(j);
211 Decodable::decode(&mut decoder)
215 fn digest<T:Encodable<json::Encoder>>(t: &T) -> ~str {
216 let mut sha = ~Sha1::new();
217 (*sha).input_str(json_encode(t));
221 fn digest_file(path: &Path) -> ~str {
222 let mut sha = ~Sha1::new();
223 let s = io::read_whole_file_str(path);
224 (*sha).input_str(*s.get_ref());
230 pub fn new(db: RWArc<Database>,
232 cfg: Arc<json::Object>) -> Context {
237 freshness: Arc::new(TreeMap::new())
241 pub fn prep<'a>(&'a self, fn_name: &'a str) -> Prep<'a> {
242 Prep::new(self, fn_name)
245 pub fn with_prep<'a, T>(&'a self, fn_name: &'a str, blk: &fn(p: &mut Prep) -> T) -> T {
246 let mut p = self.prep(fn_name);
252 impl<'self> Prep<'self> {
253 fn new(ctxt: &'self Context, fn_name: &'self str) -> Prep<'self> {
257 declared_inputs: WorkMap::new()
262 impl<'self> Prep<'self> {
263 fn declare_input(&mut self, kind:&str, name:&str, val:&str) {
264 self.declared_inputs.insert(WorkKey::new(kind, name),
268 fn is_fresh(&self, cat: &str, kind: &str,
269 name: &str, val: &str) -> bool {
270 let k = kind.to_owned();
271 let f = self.ctxt.freshness.get().find(&k);
272 let fresh = match f {
273 None => fail!("missing freshness-function for '%s'", kind),
274 Some(f) => (*f)(name, val)
276 do self.ctxt.logger.write |lg| {
278 lg.info(fmt!("%s %s:%s is fresh",
281 lg.info(fmt!("%s %s:%s is not fresh",
288 fn all_fresh(&self, cat: &str, map: &WorkMap) -> bool {
289 for (k, v) in map.iter() {
290 if ! self.is_fresh(cat, k.kind, k.name, *v) {
298 Encodable<json::Encoder> +
299 Decodable<json::Decoder>>(
300 &'self self, blk: ~fn(&Exec) -> T) -> T {
301 self.exec_work(blk).unwrap()
304 fn exec_work<T:Send +
305 Encodable<json::Encoder> +
306 Decodable<json::Decoder>>( // FIXME(#5121)
307 &'self self, blk: ~fn(&Exec) -> T) -> Work<'self, T> {
308 let mut bo = Some(blk);
310 let cached = do self.ctxt.db.read |db| {
311 db.prepare(self.fn_name, &self.declared_inputs)
314 let res = match cached {
315 Some((ref disc_in, ref disc_out, ref res))
316 if self.all_fresh("declared input",&self.declared_inputs) &&
317 self.all_fresh("discovered input", disc_in) &&
318 self.all_fresh("discovered output", disc_out) => {
319 Left(json_decode(*res))
323 let (port, chan) = oneshot();
324 let blk = bo.take_unwrap();
325 let chan = Cell::new(chan);
329 discovered_inputs: WorkMap::new(),
330 discovered_outputs: WorkMap::new(),
332 let chan = chan.take();
334 send_one(chan, (exe, v));
344 Encodable<json::Encoder> +
345 Decodable<json::Decoder>>
346 Work<'self, T> { // FIXME(#5121)
348 pub fn new(p: &'self Prep<'self>, e: Either<T,PortOne<(Exec,T)>>) -> Work<'self, T> {
349 Work { prep: p, res: Some(e) }
352 pub fn unwrap(self) -> T {
353 let Work { prep, res } = self;
357 Some(Right(port)) => {
358 let (exe, v) = recv_one(port);
359 let s = json_encode(&v);
360 do prep.ctxt.db.write |db| {
361 db.cache(prep.fn_name,
362 &prep.declared_inputs,
363 &exe.discovered_inputs,
364 &exe.discovered_outputs,
376 use std::io::WriterUtil;
378 let pth = Path("foo.c");
380 let r = io::file_writer(&pth, [io::Create]);
381 r.get_ref().write_str("int main() { return 0; }");
384 let cx = Context::new(RWArc::new(Database::new(Path("db.json"))),
385 RWArc::new(Logger::new()),
386 Arc::new(TreeMap::new()));
388 let s = do cx.with_prep("test1") |prep| {
390 let subcx = cx.clone();
392 prep.declare_input("file", pth.to_str(), digest_file(&pth));
393 do prep.exec |_exe| {
394 let out = Path("foo.o");
395 run::process_status("gcc", [~"foo.c", ~"-o", out.to_str()]);
397 let _proof_of_concept = subcx.prep("subfn");
398 // Could run sub-rules inside here.