]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/core.rs
auto merge of #15985 : jfager/rust/r6334, r=pnkfelix
[rust.git] / src / librustdoc / core.rs
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.
4 //
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.
10
11 use rustc;
12 use rustc::{driver, middle};
13 use rustc::middle::{privacy, ty};
14 use rustc::lint;
15 use rustc::back::link;
16
17 use syntax::ast;
18 use syntax::parse::token;
19 use syntax;
20
21 use std::cell::RefCell;
22 use std::gc::GC;
23 use std::os;
24 use std::collections::{HashMap, HashSet};
25
26 use visit_ast::RustdocVisitor;
27 use clean;
28 use clean::Clean;
29
30 /// Are we generating documentation (`Typed`) or tests (`NotTyped`)?
31 pub enum MaybeTyped {
32     Typed(middle::ty::ctxt),
33     NotTyped(driver::session::Session)
34 }
35
36 pub type ExternalPaths = RefCell<Option<HashMap<ast::DefId,
37                                                 (Vec<String>, clean::TypeKind)>>>;
38
39 pub struct DocContext {
40     pub krate: ast::Crate,
41     pub maybe_typed: MaybeTyped,
42     pub src: Path,
43     pub external_paths: ExternalPaths,
44     pub external_traits: RefCell<Option<HashMap<ast::DefId, clean::Trait>>>,
45     pub external_typarams: RefCell<Option<HashMap<ast::DefId, String>>>,
46     pub inlined: RefCell<Option<HashSet<ast::DefId>>>,
47     pub populated_crate_impls: RefCell<HashSet<ast::CrateNum>>,
48 }
49
50 impl DocContext {
51     pub fn sess<'a>(&'a self) -> &'a driver::session::Session {
52         match self.maybe_typed {
53             Typed(ref tcx) => &tcx.sess,
54             NotTyped(ref sess) => sess
55         }
56     }
57
58     pub fn tcx_opt<'a>(&'a self) -> Option<&'a ty::ctxt> {
59         match self.maybe_typed {
60             Typed(ref tcx) => Some(tcx),
61             NotTyped(_) => None
62         }
63     }
64
65     pub fn tcx<'a>(&'a self) -> &'a ty::ctxt {
66         let tcx_opt = self.tcx_opt();
67         tcx_opt.expect("tcx not present")
68     }
69 }
70
71 pub struct CrateAnalysis {
72     pub exported_items: privacy::ExportedItems,
73     pub public_items: privacy::PublicItems,
74     pub external_paths: ExternalPaths,
75     pub external_traits: RefCell<Option<HashMap<ast::DefId, clean::Trait>>>,
76     pub external_typarams: RefCell<Option<HashMap<ast::DefId, String>>>,
77     pub inlined: RefCell<Option<HashSet<ast::DefId>>>,
78 }
79
80 pub type Externs = HashMap<String, Vec<String>>;
81
82 /// Parses, resolves, and typechecks the given crate
83 fn get_ast_and_resolve(cpath: &Path, libs: HashSet<Path>, cfgs: Vec<String>,
84                        externs: Externs, triple: Option<String>)
85                        -> (DocContext, CrateAnalysis) {
86     use syntax::codemap::dummy_spanned;
87     use rustc::driver::driver::{FileInput,
88                                 phase_1_parse_input,
89                                 phase_2_configure_and_expand,
90                                 phase_3_run_analysis_passes};
91     use rustc::driver::config::build_configuration;
92
93     let input = FileInput(cpath.clone());
94
95     let warning_lint = lint::builtin::WARNINGS.name_lower();
96
97     let sessopts = driver::config::Options {
98         maybe_sysroot: Some(os::self_exe_path().unwrap().dir_path()),
99         addl_lib_search_paths: RefCell::new(libs),
100         crate_types: vec!(driver::config::CrateTypeRlib),
101         lint_opts: vec!((warning_lint, lint::Allow)),
102         externs: externs,
103         target_triple: triple.unwrap_or(driver::driver::host_triple().to_string()),
104         ..rustc::driver::config::basic_options().clone()
105     };
106
107
108     let codemap = syntax::codemap::CodeMap::new();
109     let diagnostic_handler = syntax::diagnostic::default_handler(syntax::diagnostic::Auto, None);
110     let span_diagnostic_handler =
111         syntax::diagnostic::mk_span_handler(diagnostic_handler, codemap);
112
113     let sess = driver::session::build_session_(sessopts,
114                                                Some(cpath.clone()),
115                                                span_diagnostic_handler);
116
117     let mut cfg = build_configuration(&sess);
118     for cfg_ in cfgs.move_iter() {
119         let cfg_ = token::intern_and_get_ident(cfg_.as_slice());
120         cfg.push(box(GC) dummy_spanned(ast::MetaWord(cfg_)));
121     }
122
123     let krate = phase_1_parse_input(&sess, cfg, &input);
124
125     let name = link::find_crate_name(Some(&sess), krate.attrs.as_slice(),
126                                      &input);
127
128     let (krate, ast_map)
129         = phase_2_configure_and_expand(&sess, krate, name.as_slice(), None)
130             .expect("phase_2_configure_and_expand aborted in rustdoc!");
131
132     let driver::driver::CrateAnalysis {
133         exported_items, public_items, ty_cx, ..
134     } = phase_3_run_analysis_passes(sess, &krate, ast_map, name);
135
136     debug!("crate: {:?}", krate);
137     (DocContext {
138         krate: krate,
139         maybe_typed: Typed(ty_cx),
140         src: cpath.clone(),
141         external_traits: RefCell::new(Some(HashMap::new())),
142         external_typarams: RefCell::new(Some(HashMap::new())),
143         external_paths: RefCell::new(Some(HashMap::new())),
144         inlined: RefCell::new(Some(HashSet::new())),
145         populated_crate_impls: RefCell::new(HashSet::new()),
146     }, CrateAnalysis {
147         exported_items: exported_items,
148         public_items: public_items,
149         external_paths: RefCell::new(None),
150         external_traits: RefCell::new(None),
151         external_typarams: RefCell::new(None),
152         inlined: RefCell::new(None),
153     })
154 }
155
156 pub fn run_core(libs: HashSet<Path>, cfgs: Vec<String>, externs: Externs,
157                 path: &Path, triple: Option<String>)
158                 -> (clean::Crate, CrateAnalysis) {
159     let (ctxt, analysis) = get_ast_and_resolve(path, libs, cfgs, externs, triple);
160     let ctxt = box(GC) ctxt;
161     super::ctxtkey.replace(Some(ctxt));
162
163     let krate = {
164         let mut v = RustdocVisitor::new(&*ctxt, Some(&analysis));
165         v.visit(&ctxt.krate);
166         v.clean()
167     };
168
169     let external_paths = ctxt.external_paths.borrow_mut().take();
170     *analysis.external_paths.borrow_mut() = external_paths;
171     let map = ctxt.external_traits.borrow_mut().take();
172     *analysis.external_traits.borrow_mut() = map;
173     let map = ctxt.external_typarams.borrow_mut().take();
174     *analysis.external_typarams.borrow_mut() = map;
175     let map = ctxt.inlined.borrow_mut().take();
176     *analysis.inlined.borrow_mut() = map;
177     (krate, analysis)
178 }