]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/core.rs
add a rustc_resolve::Resolver to DocContext
[rust.git] / src / librustdoc / core.rs
1 // Copyright 2012-2014 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_lint;
12 use rustc_driver::{driver, target_features, abort_on_err};
13 use rustc::session::{self, config};
14 use rustc::hir::def_id::DefId;
15 use rustc::hir::def::Def;
16 use rustc::middle::privacy::AccessLevels;
17 use rustc::ty::{self, TyCtxt, AllArenas};
18 use rustc::hir::map as hir_map;
19 use rustc::lint;
20 use rustc::util::nodemap::FxHashMap;
21 use rustc_trans;
22 use rustc_resolve as resolve;
23 use rustc_metadata::creader::CrateLoader;
24 use rustc_metadata::cstore::CStore;
25
26 use syntax::codemap;
27 use syntax::feature_gate::UnstableFeatures;
28 use errors;
29 use errors::emitter::ColorConfig;
30
31 use std::cell::{RefCell, Cell};
32 use std::mem;
33 use std::rc::Rc;
34 use std::path::PathBuf;
35
36 use visit_ast::RustdocVisitor;
37 use clean;
38 use clean::Clean;
39 use html::markdown::RenderType;
40 use html::render::RenderInfo;
41
42 pub use rustc::session::config::Input;
43 pub use rustc::session::search_paths::SearchPaths;
44
45 pub type ExternalPaths = FxHashMap<DefId, (Vec<String>, clean::TypeKind)>;
46
47 pub struct DocContext<'a, 'tcx: 'a, 'rcx> {
48     pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
49     pub resolver: resolve::Resolver<'rcx>,
50     pub populated_all_crate_impls: Cell<bool>,
51     // Note that external items for which `doc(hidden)` applies to are shown as
52     // non-reachable while local items aren't. This is because we're reusing
53     // the access levels from crateanalysis.
54     /// Later on moved into `clean::Crate`
55     pub access_levels: RefCell<AccessLevels<DefId>>,
56     /// Later on moved into `html::render::CACHE_KEY`
57     pub renderinfo: RefCell<RenderInfo>,
58     /// Later on moved through `clean::Crate` into `html::render::CACHE_KEY`
59     pub external_traits: RefCell<FxHashMap<DefId, clean::Trait>>,
60     /// Which markdown renderer to use when extracting links.
61     pub render_type: RenderType,
62
63     // The current set of type and lifetime substitutions,
64     // for expanding type aliases at the HIR level:
65
66     /// Table type parameter definition -> substituted type
67     pub ty_substs: RefCell<FxHashMap<Def, clean::Type>>,
68     /// Table node id of lifetime parameter definition -> substituted lifetime
69     pub lt_substs: RefCell<FxHashMap<DefId, clean::Lifetime>>,
70 }
71
72 impl<'a, 'tcx, 'rcx> DocContext<'a, 'tcx, 'rcx> {
73     pub fn sess(&self) -> &session::Session {
74         &self.tcx.sess
75     }
76
77     /// Call the closure with the given parameters set as
78     /// the substitutions for a type alias' RHS.
79     pub fn enter_alias<F, R>(&self,
80                              ty_substs: FxHashMap<Def, clean::Type>,
81                              lt_substs: FxHashMap<DefId, clean::Lifetime>,
82                              f: F) -> R
83     where F: FnOnce() -> R {
84         let (old_tys, old_lts) =
85             (mem::replace(&mut *self.ty_substs.borrow_mut(), ty_substs),
86              mem::replace(&mut *self.lt_substs.borrow_mut(), lt_substs));
87         let r = f();
88         *self.ty_substs.borrow_mut() = old_tys;
89         *self.lt_substs.borrow_mut() = old_lts;
90         r
91     }
92 }
93
94 pub trait DocAccessLevels {
95     fn is_doc_reachable(&self, did: DefId) -> bool;
96 }
97
98 impl DocAccessLevels for AccessLevels<DefId> {
99     fn is_doc_reachable(&self, did: DefId) -> bool {
100         self.is_public(did)
101     }
102 }
103
104
105 pub fn run_core(search_paths: SearchPaths,
106                 cfgs: Vec<String>,
107                 externs: config::Externs,
108                 input: Input,
109                 triple: Option<String>,
110                 maybe_sysroot: Option<PathBuf>,
111                 allow_warnings: bool,
112                 force_unstable_if_unmarked: bool,
113                 render_type: RenderType) -> (clean::Crate, RenderInfo)
114 {
115     // Parse, resolve, and typecheck the given crate.
116
117     let cpath = match input {
118         Input::File(ref p) => Some(p.clone()),
119         _ => None
120     };
121
122     let warning_lint = lint::builtin::WARNINGS.name_lower();
123
124     let sessopts = config::Options {
125         maybe_sysroot,
126         search_paths,
127         crate_types: vec![config::CrateTypeRlib],
128         lint_opts: if !allow_warnings { vec![(warning_lint, lint::Allow)] } else { vec![] },
129         lint_cap: Some(lint::Allow),
130         externs,
131         target_triple: triple.unwrap_or(config::host_triple().to_string()),
132         // Ensure that rustdoc works even if rustc is feature-staged
133         unstable_features: UnstableFeatures::Allow,
134         actually_rustdoc: true,
135         debugging_opts: config::DebuggingOptions {
136             force_unstable_if_unmarked,
137             ..config::basic_debugging_options()
138         },
139         ..config::basic_options().clone()
140     };
141
142     let codemap = Rc::new(codemap::CodeMap::new(sessopts.file_path_mapping()));
143     let diagnostic_handler = errors::Handler::with_tty_emitter(ColorConfig::Auto,
144                                                                true,
145                                                                false,
146                                                                Some(codemap.clone()));
147
148     let mut sess = session::build_session_(
149         sessopts, cpath, diagnostic_handler, codemap,
150     );
151     let trans = rustc_trans::LlvmTransCrate::new(&sess);
152     let cstore = Rc::new(CStore::new(trans.metadata_loader()));
153     rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
154
155     let mut cfg = config::build_configuration(&sess, config::parse_cfgspecs(cfgs));
156     target_features::add_configuration(&mut cfg, &sess, &*trans);
157     sess.parse_sess.config = cfg;
158
159     let control = &driver::CompileController::basic();
160
161     let krate = panictry!(driver::phase_1_parse_input(control, &sess, &input));
162
163     let name = ::rustc_trans_utils::link::find_crate_name(Some(&sess), &krate.attrs, &input);
164
165     let driver::ExpansionResult {
166         expanded_crate,
167         defs,
168         analysis,
169         resolutions,
170         mut hir_forest
171     } = {
172         let result = driver::phase_2_configure_and_expand(&sess,
173                                                           &cstore,
174                                                           krate,
175                                                           None,
176                                                           &name,
177                                                           None,
178                                                           resolve::MakeGlobMap::No,
179                                                           |_| Ok(()));
180         abort_on_err(result, &sess)
181     };
182
183     let arenas = AllArenas::new();
184     let mut crate_loader = CrateLoader::new(&sess, &cstore, &name);
185     let resolver_arenas = resolve::Resolver::arenas();
186     let hir_map = hir_map::map_crate(&sess, &*cstore, &mut hir_forest, &defs);
187     let output_filenames = driver::build_output_filenames(&input,
188                                                           &None,
189                                                           &None,
190                                                           &[],
191                                                           &sess);
192
193     abort_on_err(driver::phase_3_run_analysis_passes(&*trans,
194                                                      control,
195                                                      &sess,
196                                                      &*cstore,
197                                                      hir_map,
198                                                      analysis,
199                                                      resolutions,
200                                                      &arenas,
201                                                      &name,
202                                                      &output_filenames,
203                                                      |tcx, analysis, _, result| {
204         if let Err(_) = result {
205             sess.fatal("Compilation failed, aborting rustdoc");
206         }
207
208         let ty::CrateAnalysis { access_levels, .. } = analysis;
209
210         // Convert from a NodeId set to a DefId set since we don't always have easy access
211         // to the map from defid -> nodeid
212         let access_levels = AccessLevels {
213             map: access_levels.map.iter()
214                                   .map(|(&k, &v)| (tcx.hir.local_def_id(k), v))
215                                   .collect()
216         };
217
218         // Set up a Resolver so that the doc cleaning can look up paths in the docs
219         let mut resolver = resolve::Resolver::new(&sess,
220                                                   &*cstore,
221                                                   &expanded_crate,
222                                                   &name,
223                                                   resolve::MakeGlobMap::No,
224                                                   &mut crate_loader,
225                                                   &resolver_arenas);
226         resolver.resolve_crate(&expanded_crate);
227
228         let ctxt = DocContext {
229             tcx,
230             resolver,
231             populated_all_crate_impls: Cell::new(false),
232             access_levels: RefCell::new(access_levels),
233             external_traits: Default::default(),
234             renderinfo: Default::default(),
235             render_type,
236             ty_substs: Default::default(),
237             lt_substs: Default::default(),
238         };
239         debug!("crate: {:?}", tcx.hir.krate());
240
241         let krate = {
242             let mut v = RustdocVisitor::new(&*cstore, &ctxt);
243             v.visit(tcx.hir.krate());
244             v.clean(&ctxt)
245         };
246
247         (krate, ctxt.renderinfo.into_inner())
248     }), &sess)
249 }