1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
// Copyright 2016 The RLS Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![feature(const_fn)]
#![feature(type_ascription)]

#[macro_use]
extern crate derive_new;
#[macro_use]
extern crate log;
extern crate rls_data as data;
extern crate rls_span as span;
extern crate rustc_serialize;

pub mod raw;
mod lowering;
mod listings;
mod util;
#[cfg(test)]
mod test;

pub use self::raw::{Target, name_space_for_def_kind, read_analyis_incremental};

use std::collections::HashMap;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Mutex;
use std::time::{Instant, SystemTime};

pub struct AnalysisHost<L: AnalysisLoader = CargoAnalysisLoader> {
    analysis: Mutex<Option<Analysis>>,
    master_crate_map: Mutex<HashMap<String, u32>>,
    loader: L,
}

pub struct CargoAnalysisLoader {
    path_prefix: Mutex<Option<PathBuf>>,
    target: Target,
}

pub type AResult<T> = Result<T, AError>;

#[derive(Debug, Copy, Clone)]
pub enum AError {
    MutexPoison,
    Unclassified,
}

impl ::std::error::Error for AError {
    fn description(&self) -> &str {
        match *self {
            AError::MutexPoison => "poison error in a mutex (usually a secondary error)",
            AError::Unclassified => "unknown error",
        }        
    }
}

impl ::std::fmt::Display for AError {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        write!(f, "{}", ::std::error::Error::description(self))
    }
}

impl<T> From<::std::sync::PoisonError<T>> for AError {
    fn from(_: ::std::sync::PoisonError<T>) -> AError {
        AError::MutexPoison
    }
}

macro_rules! clone_field {
    ($field: ident) => { |x| x.$field.clone() }
}

macro_rules! def_span {
    ($analysis: expr, $id: expr) => {
        $analysis.with_defs_and_then($id, |def| {
            if def.api_crate {
                None
            } else {
                Some(def.span.clone())
            }
        })
    }
}

pub trait AnalysisLoader: Sized {
    fn needs_hard_reload(&self, path_prefix: &Path) -> bool;
    fn fresh_host(&self) -> AnalysisHost<Self>;
    fn set_path_prefix(&self, path_prefix: &Path);
    fn abs_path_prefix(&self) -> Option<PathBuf>;
    fn iter_paths<F, T>(&self, f: F) -> Vec<T>
        where F: Fn(&Path) -> Vec<T>;
}

impl AnalysisLoader for CargoAnalysisLoader {
    fn needs_hard_reload(&self, path_prefix: &Path) -> bool {
        let pp = self.path_prefix.lock().unwrap();
        pp.is_none() || pp.as_ref().unwrap() != path_prefix
    }

    fn fresh_host(&self) -> AnalysisHost<Self> {
        let pp = self.path_prefix.lock().unwrap();
        AnalysisHost::new_with_loader(CargoAnalysisLoader {
            path_prefix: Mutex::new(pp.clone()),
            target: self.target,
        })
    }

    fn set_path_prefix(&self, path_prefix: &Path) {
        let mut pp = self.path_prefix.lock().unwrap();
        *pp = Some(path_prefix.to_owned())
    }

    fn abs_path_prefix(&self) -> Option<PathBuf> {
        let p = self.path_prefix.lock().unwrap();
        p.as_ref().map(|s| Path::new(s).canonicalize().unwrap().to_owned())
    }

    fn iter_paths<F, T>(&self, f: F) -> Vec<T>
        where F: Fn(&Path) -> Vec<T>
    {
        let path_prefix = self.path_prefix.lock().unwrap();
        let path_prefix = path_prefix.as_ref().unwrap();
        let target = self.target.to_string();

        // TODO deps path allows to break out of 'sandbox' - is that Ok?
        let principle_path = path_prefix.join("target").join("rls").join(&target).join("save-analysis");
        let deps_path = path_prefix.join("target").join("rls").join(&target).join("deps").join("save-analysis");
        let sys_root_path = sys_root_path();
        let target_triple = extract_target_triple(sys_root_path.as_path());
        let libs_path = sys_root_path
            .join("lib")
            .join("rustlib")
            .join(&target_triple)
            .join("analysis");
        let paths = &[&libs_path,
                      &deps_path,
                      &principle_path];

        paths.iter().flat_map(|p| f(p).into_iter()).collect()
    }
}

fn extract_target_triple(sys_root_path: &Path) -> String {
    // Extracts nightly-x86_64-pc-windows-msvc from $HOME/.rustup/toolchains/nightly-x86_64-pc-windows-msvc
    let toolchain = sys_root_path.iter()
                                 .last()
                                 .and_then(OsStr::to_str)
                                 .expect("extracting toolchain failed");
    // Extracts x86_64-pc-windows-msvc from nightly-x86_64-pc-windows-pc
    let triple = toolchain.splitn(2, "-")
                          .last()
                          .map(String::from)
                          .expect("extracting triple failed");
    triple
}

fn sys_root_path() -> PathBuf {
    option_env!("SYSROOT")
        .map(PathBuf::from)
        .or_else(|| {
            option_env!("RUSTC")
                .and_then(|rustc| Command::new(rustc)
                    .arg("--print")
                    .arg("sysroot")
                    .output()
                    .ok()
                    .and_then(|out| String::from_utf8(out.stdout).ok())
                    .map(|s| PathBuf::from(s.trim())))
        })
        .or_else(|| {
            Command::new("rustc")
            .arg("--print")
            .arg("sysroot")
            .output()
            .ok()
            .and_then(|out| String::from_utf8(out.stdout).ok())
            .map(|s| PathBuf::from(s.trim()))
        })
        .expect("need to specify SYSROOT or RUSTC env vars, \
                 or rustc must be in PATH")
}

impl AnalysisHost<CargoAnalysisLoader> {
    pub fn new(target: Target) -> AnalysisHost {
        AnalysisHost {
            analysis: Mutex::new(None),
            master_crate_map: Mutex::new(HashMap::new()),
            loader: CargoAnalysisLoader {
                path_prefix: Mutex::new(None),
                target: target,
            }
        }
    }
}

impl<L: AnalysisLoader> AnalysisHost<L> {
    pub fn new_with_loader(l: L) -> AnalysisHost<L> {
        AnalysisHost {
            analysis: Mutex::new(None),
            master_crate_map: Mutex::new(HashMap::new()),
            loader: l,
        }
    }

    /// Reloads given data passed in `analysis`. This will first check and read
    /// on-disk data (just like `reload`). It then imports the data we're
    /// passing in directly.
    pub fn reload_from_analysis(&self,
                                analysis: data::Analysis,
                                path_prefix: &Path,
                                base_dir: &Path,
                                full_docs: bool)
                                -> AResult<()> {
        self.reload(path_prefix, base_dir, full_docs)?;

        lowering::lower(vec![raw::Crate::new(analysis, SystemTime::now(), None)],
                        base_dir,
                        full_docs,
                        self,
                        |host, per_crate, path| {
            let mut a = host.analysis.lock()?;
            a.as_mut().unwrap().update(per_crate, path);
            Ok(())
        })
    }

    pub fn reload(&self, path_prefix: &Path, base_dir: &Path, full_docs: bool) -> AResult<()> {
        trace!("reload {:?} {:?}", path_prefix, base_dir);
        let empty = {
            let a = self.analysis.lock()?;
            a.is_none()
        };
        if empty || self.loader.needs_hard_reload(path_prefix) {
            return self.hard_reload(path_prefix, base_dir, full_docs);
        }

        let timestamps = {
            let a = self.analysis.lock()?;
            a.as_ref().unwrap().timestamps()
        };

        let raw_analysis = read_analyis_incremental(&self.loader, timestamps);

        let result = lowering::lower(raw_analysis, base_dir, full_docs, self, |host, per_crate, path| {
            let mut a = host.analysis.lock()?;
            a.as_mut().unwrap().update(per_crate, path);
            Ok(())
        });
        result
    }

    // Reloads the entire project's analysis data.
    pub fn hard_reload(&self, path_prefix: &Path, base_dir: &Path, full_docs: bool) -> AResult<()> {
        trace!("hard_reload {:?} {:?}", path_prefix, base_dir);
        self.loader.set_path_prefix(path_prefix);
        let raw_analysis = read_analyis_incremental(&self.loader, HashMap::new());

        // We're going to create a dummy AnalysisHost that we will fill with data,
        // then once we're done, we'll swap its data into self.
        let mut fresh_host = self.loader.fresh_host();
        fresh_host.analysis = Mutex::new(Some(Analysis::new()));
        let lowering_result = lowering::lower(raw_analysis, base_dir, full_docs, &fresh_host, |host, per_crate, path| {
            host.analysis.lock().unwrap().as_mut().unwrap().per_crate.insert(path, per_crate);
            Ok(())
        });

        if let Err(s) = lowering_result {
            let mut a = self.analysis.lock()?;
            *a = None;
            return Err(s);
        }

        {
            let mut mcm = self.master_crate_map.lock()?;
            *mcm = fresh_host.master_crate_map.into_inner().unwrap();
        }

        let mut a = self.analysis.lock()?;
        *a = Some(fresh_host.analysis.into_inner().unwrap().unwrap());
        Ok(())
    }

    /// Note that self.has_def == true =/> self.goto_def.is_some(), since if the
    /// def is in an api crate, there is no reasonable span to jump to.
    pub fn has_def(&self, id: Id) -> bool {
        match self.analysis.lock() {
            Ok(a) => a.as_ref().unwrap().has_def(id),
            _ => false,
        }
    }

    pub fn get_def(&self, id: Id) -> AResult<Def> {
        self.with_analysis(|a| a.with_defs(id, |def| def.clone()))
    }

    pub fn goto_def(&self, span: &Span) -> AResult<Span> {
        self.with_analysis(|a| {
            a.def_id_for_span(span)
             .and_then(|id| def_span!(a, id))
        })
    }

    pub fn for_each_child_def<F, T>(&self, id: Id, f: F) -> AResult<Vec<T>>
        where F: FnMut(Id, &Def) -> T
    {
        self.with_analysis(|a| a.for_each_child(id, f))
    }

    pub fn def_parents(&self, id: Id) -> AResult<Vec<(Id, String)>> {
        self.with_analysis(|a| {
            let mut result = vec![];
            let mut next = id;
            loop {
                match a.with_defs_and_then(next, |def| def.parent.and_then(|p| {
                    a.with_defs(p, |def| (p, def.name.clone()))
                })) {
                    Some((id, name)) => {
                        result.insert(0, (id, name));
                        next = id;
                    }
                    None => {
                        return Some(result);
                    }
                }
            }
        })
    }

    /// Returns the name of each crate in the program and the id of the root
    /// module of that crate.
    pub fn def_roots(&self) -> AResult<Vec<(Id, String)>> {
        self.with_analysis(|a| {
            Some(a.for_all_crates(|c| c.root_id.map(|id| {
                vec![(id, c.name.clone())]
            })))
        })
    }

    pub fn id(&self, span: &Span) -> AResult<Id> {
        self.with_analysis(|a| a.def_id_for_span(span))
    }

    pub fn find_all_refs(&self, span: &Span, include_decl: bool) -> AResult<Vec<Span>> {
        let t_start = Instant::now();
        let result = if include_decl {
            self.with_analysis(|a| {
                a.def_id_for_span(span)
                 .and_then(|id| {
                    a.with_ref_spans(id, |refs| {
                        def_span!(a, id)
                         .into_iter()
                         .chain(refs.iter().cloned())
                         .collect::<Vec<_>>()
                     })
                     .or_else(|| def_span!(a, id).map(|s| vec![s]))
                 })
            })
        } else {
            self.with_analysis(|a| {
                a.def_id_for_span(span)
                 .map(|id| {
                    a.with_ref_spans(id, |refs| refs.clone())
                     .unwrap_or_else(Vec::new)
                 })
            })
        };

        let time = t_start.elapsed();
        info!("find_all_refs: {}s", time.as_secs() as f64 + time.subsec_nanos() as f64 / 1_000_000_000.0);
        result
    }

    pub fn show_type(&self, span: &Span) -> AResult<String> {
        self.with_analysis(|a| {
            a.def_id_for_span(span)
             .and_then(|id| a.with_defs(id, clone_field!(value)))
             .or_else(|| a.with_globs(span, clone_field!(value)))
        })
    }

    pub fn docs(&self, span: &Span) -> AResult<String> {
        self.with_analysis(|a| {
            a.def_id_for_span(span)
             .and_then(|id| a.with_defs(id, clone_field!(docs)))
         })
    }

    /// Search for a symbol name, returns a list of spans matching defs and refs
    /// for that name.
    pub fn search(&self, name: &str) -> AResult<Vec<Span>> {
        let t_start = Instant::now();
        let result = self.with_analysis(|a| {
            Some(a.with_def_names(name, |defs| {
                info!("defs: {:?}", defs);
                defs.into_iter()
                    .flat_map(|id| {
                        a.with_ref_spans(*id, |refs|
                            {
                            def_span!(a, *id)
                             .into_iter()
                             .chain(refs.iter().cloned())
                             .collect::<Vec<_>>()})
                         .or_else(|| def_span!(a, *id).map(|s| vec![s]))
                         .unwrap_or_else(Vec::new)
                         .into_iter()
                     })
                     .collect(): Vec<Span>
             }))
        });

        let time = t_start.elapsed();
        info!("search: {}s", time.as_secs() as f64 + time.subsec_nanos() as f64 / 1_000_000_000.0);
        result
    }

    // TODO refactor search and find_all_refs to use this
    // Includes all references and the def, the def is always first.
    pub fn find_all_refs_by_id(&self, id: Id) -> AResult<Vec<Span>> {
        let t_start = Instant::now();
        let result = self.with_analysis(|a| {
            a.with_ref_spans(id, |refs| {
                def_span!(a, id)
                 .into_iter()
                 .chain(refs.iter().cloned())
                 .collect::<Vec<_>>()
             })
             .or_else(|| def_span!(a, id).map(|s| vec![s]))
        });

        let time = t_start.elapsed();
        info!("find_all_refs_by_id: {}s", time.as_secs() as f64 + time.subsec_nanos() as f64 / 1_000_000_000.0);
        result
    }

    pub fn find_impls(&self, id: Id) -> AResult<Vec<Span>> {
        self.with_analysis(|a| Some(a.for_all_crates(|c| c.impls.get(&id).map(|v| v.clone()))))
    }

    /// Search for a symbol name, returning a list of def_ids for that name.
    pub fn search_for_id(&self, name: &str) -> AResult<Vec<Id>> {
        self.with_analysis(|a| Some(a.with_def_names(name, |defs| defs.clone())))
    }

    pub fn symbols(&self, file_name: &Path) -> AResult<Vec<SymbolResult>> {
        self.with_analysis(|a| {
            a.with_defs_per_file(file_name, |ids| {
                ids.iter()
                   .map(|id| a.with_defs(*id, |def| SymbolResult::new(*id, def)).unwrap())
                   .collect()
            })
        })
    }

    pub fn doc_url(&self, span: &Span) -> AResult<String> {
        // e.g., https://doc.rust-lang.org/nightly/std/string/String.t.html
        self.with_analysis(|a| {
            a.def_id_for_span(span)
             .and_then(|id| a.with_defs_and_then(id, |def| AnalysisHost::<L>::mk_doc_url(def, a)))
        })
    }

    pub fn src_url(&self, span: &Span) -> AResult<String> {
        // e.g., https://github.com/rust-lang/rust/blob/master/src/libcollections/string.rs#L261-L263

        // FIXME would be nice not to do this every time.
        let path_prefix = &self.loader.abs_path_prefix();

        self.with_analysis(|a| {
            a.def_id_for_span(span)
             .and_then(|id| a.with_defs_and_then(id, |def| AnalysisHost::<L>::mk_src_url(def, path_prefix.as_ref(), a)))
        })
    }

    fn with_analysis<F, T>(&self, f: F) -> AResult<T>
        where F: FnOnce(&Analysis) -> Option<T>
    {
        let a = self.analysis.lock()?;
        if let Some(ref a) = *a {
            f(a).ok_or(AError::Unclassified)
        } else {
            Err(AError::Unclassified)
        }
    }

    fn mk_doc_url(def: &Def, analysis: &Analysis) -> Option<String> {
        if !def.api_crate {
            return None;
        }

        if def.parent.is_none() && def.qualname.contains('<') {
            debug!("mk_doc_url, bailing, found generic qualname: `{}`", def.qualname);
            return None;
        }

        match def.parent {
            Some(p) => {
                analysis.with_defs(p, |parent| {
                    let parent_qualpath = parent.qualname.replace("::", "/");
                    let ns = name_space_for_def_kind(def.kind);
                    format!("{}/{}.t.html#{}.{}", analysis.doc_url_base, parent_qualpath, def.name, ns)
                })
            }
            None => {
                let qualpath = def.qualname.replace("::", "/");
                let ns = name_space_for_def_kind(def.kind);
                Some(format!("{}/{}.{}.html", analysis.doc_url_base, qualpath, ns))
            }
        }
    }

    fn mk_src_url(def: &Def, path_prefix: Option<&PathBuf>, analysis: &Analysis) -> Option<String> {
        let path_prefix = match path_prefix {
            Some(pp) => pp,
            None => return None,
        };
        let file_path = &def.span.file;
        let file_path = match file_path.strip_prefix(&path_prefix) {
            Ok(p) => p,
            Err(_) => return None,
        };

        if def.api_crate {
            Some(format!("{}/{}#L{}-L{}",
                         analysis.src_url_base,
                         file_path.to_str().unwrap(),
                         def.span.range.row_start.one_indexed().0,
                         def.span.range.row_end.one_indexed().0))
        } else {
            None
        }
    }
}

#[derive(Debug, Clone)]
pub struct SymbolResult {
    pub id: Id,
    pub name: String,
    pub kind: raw::DefKind,
    pub span: Span,
}

impl SymbolResult {
    fn new(id: Id, def: &Def) -> SymbolResult {
        SymbolResult {
            id: id,
            name: def.name.clone(),
            span: def.span.clone(),
            kind: def.kind,
        }
    }
}

type Span = span::Span<span::ZeroIndexed>;

#[derive(Debug)]
pub struct Analysis {
    // The primary crate will have its data passed directly, not via a file, so
    // there is no path for it. Because of this key into the hashmap, this means
    // we can only pass the data for one crate directly.
    per_crate: HashMap<Option<PathBuf>, PerCrateAnalysis>,

    pub doc_url_base: String,
    pub src_url_base: String,
}

#[derive(Debug)]
pub struct PerCrateAnalysis {
    // Map span to id of def (either because it is the span of the def, or of the def for the ref).
    def_id_for_span: HashMap<Span, Id>,
    defs: HashMap<Id, Def>,
    defs_per_file: HashMap<PathBuf, Vec<Id>>,
    children: HashMap<Id, Vec<Id>>,
    def_names: HashMap<String, Vec<Id>>,
    ref_spans: HashMap<Id, Vec<Span>>,
    globs: HashMap<Span, Glob>,
    impls: HashMap<Id, Vec<Span>>,

    name: String,
    root_id: Option<Id>,
    timestamp: Option<SystemTime>,
}

#[derive(Debug, Clone)]
pub struct Def {
    pub kind: raw::DefKind,
    pub span: Span,
    pub name: String,
    pub qualname: String,
    pub api_crate: bool,
    pub parent: Option<Id>,
    pub value: String,
    pub docs: String,
    // pub sig: Option<Signature>,
}

#[derive(Debug, Clone)]
pub struct Signature {
    pub span: Span,
    pub text: String,
    pub ident_start: u32,
    pub ident_end: u32,
    pub defs: Vec<SigElement>,
    pub refs: Vec<SigElement>,
}

#[derive(Debug, Clone)]
pub struct SigElement {
    pub id: Id,
    pub start: usize,
    pub end: usize,
}

#[derive(Debug)]
pub struct Glob {
    pub value: String,
}

impl PerCrateAnalysis {
    pub fn new() -> PerCrateAnalysis {
        PerCrateAnalysis {
            def_id_for_span: HashMap::new(),
            defs: HashMap::new(),
            defs_per_file: HashMap::new(),
            children: HashMap::new(),
            def_names: HashMap::new(),
            ref_spans: HashMap::new(),
            globs: HashMap::new(),
            impls: HashMap::new(),
            name: String::new(),
            root_id: None,
            timestamp: None,
        }
    }
}

impl Analysis {
    pub fn new() -> Analysis {
        Analysis {
            per_crate: HashMap::new(),
            // TODO don't hardcode these
            doc_url_base: "https://doc.rust-lang.org/nightly".to_owned(),
            src_url_base: "https://github.com/rust-lang/rust/blob/master".to_owned(),
        }
    }

    fn timestamps(&self) -> HashMap<PathBuf, Option<SystemTime>> {
        self.per_crate.iter().filter_map(|(s, pc)| s.as_ref().map(|s| (s.clone(), pc.timestamp))).collect()
    }

    fn update(&mut self, per_crate: PerCrateAnalysis, path: Option<PathBuf>) {
        self.per_crate.insert(path, per_crate);
    }

    fn has_def(&self, id: Id) -> bool {
        self.for_each_crate(|c| c.defs.get(&id).map(|_| ())).is_some()
    }

    fn for_each_crate<F, T>(&self, f: F) -> Option<T>
        where F: Fn(&PerCrateAnalysis) -> Option<T>
    {
        for per_crate in self.per_crate.values() {
            if let Some(t) = f(per_crate) {
                return Some(t);
            }
        }

        None
    }

    fn for_all_crates<F, T>(&self, f: F) -> Vec<T>
        where F: Fn(&PerCrateAnalysis) -> Option<Vec<T>>
    {
        let mut result = vec![];
        for per_crate in self.per_crate.values() {
            if let Some(this_crate) = f(per_crate) {
                result.extend(this_crate);
            }
        }

        result
    }

    fn def_id_for_span(&self, span: &Span) -> Option<Id> {
        self.for_each_crate(|c| c.def_id_for_span.get(span).cloned())
    }

    fn with_defs<F, T>(&self, id: Id, f: F) -> Option<T>
        where F: Fn(&Def) -> T
    {
        self.for_each_crate(|c| c.defs.get(&id).map(&f))
    }

    fn with_defs_and_then<F, T>(&self, id: Id, f: F) -> Option<T>
        where F: Fn(&Def) -> Option<T>
    {
        self.for_each_crate(|c| c.defs.get(&id).and_then(&f))
    }

    fn with_globs<F, T>(&self, span: &Span, f: F) -> Option<T>
        where F: Fn(&Glob) -> T
    {
        self.for_each_crate(|c| c.globs.get(span).map(&f))
    }

    fn for_each_child<F, T>(&self, id: Id, mut f: F) -> Option<Vec<T>>
        where F: FnMut(Id, &Def) -> T
    {
        for per_crate in self.per_crate.values() {
            if let Some(children) = per_crate.children.get(&id) {
                return Some(children.iter().filter_map(|id| {
                    let def = per_crate.defs.get(id);
                    if def.is_none() {
                        info!("def not found for {}", id);
                    }
                    def.map(|def| f(*id, &def))
                }).collect());
            }
        }

        Some(vec![])
    }

    fn with_ref_spans<F, T>(&self, id: Id, f: F) -> Option<T>
        where F: Fn(&Vec<Span>) -> T
    {
        self.for_each_crate(|c| c.ref_spans.get(&id).map(&f))
    }

    fn with_defs_per_file<F, T>(&self, file: &Path, f: F) -> Option<T>
        where F: Fn(&Vec<Id>) -> T
    {
        self.for_each_crate(|c| c.defs_per_file.get(file).map(&f))
    }

    fn with_def_names<F, T>(&self, name: &str, f: F) -> Vec<T>
        where F: Fn(&Vec<Id>) -> Vec<T>
    {
        self.for_all_crates(|c| c.def_names.get(name).map(&f))
    }
}

#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash, new)]
pub struct Id(u64);

impl ::std::fmt::Display for Id {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        self.0.fmt(f)
    }
}

// Used to indicate a missing index in the Id.
const NULL: Id = Id(u64::max_value());

#[cfg(test)]
mod tests {
    mod extract_target_triple {
        use std::path::Path;

        #[test]
        fn windows_path() {
            let path = Path::new(r#"C:\Users\user\.rustup\toolchains\nightly-x86_64-pc-windows-msvc"#);
            assert_eq!(::extract_target_triple(path), String::from("x86_64-pc-windows-msvc"));
        }

        #[test]
        fn unix_path() {
            let path = Path::new("/home/user/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu");
            assert_eq!(::extract_target_triple(path), String::from("x86_64-unknown-linux-gnu"));
        }
    }
}