]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/core.rs
track extern traits being inlined
[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::{self, 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_resolve as resolve;
22 use rustc_metadata::creader::CrateLoader;
23 use rustc_metadata::cstore::CStore;
24
25 use syntax::ast::NodeId;
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::render::RenderInfo;
40
41 pub use rustc::session::config::Input;
42 pub use rustc::session::search_paths::SearchPaths;
43
44 pub type ExternalPaths = FxHashMap<DefId, (Vec<String>, clean::TypeKind)>;
45
46 pub struct DocContext<'a, 'tcx: 'a, 'rcx: 'a> {
47     pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
48     pub resolver: &'a RefCell<resolve::Resolver<'rcx>>,
49     /// The stack of module NodeIds up till this point
50     pub mod_ids: RefCell<Vec<NodeId>>,
51     pub populated_all_crate_impls: Cell<bool>,
52     // Note that external items for which `doc(hidden)` applies to are shown as
53     // non-reachable while local items aren't. This is because we're reusing
54     // the access levels from crateanalysis.
55     /// Later on moved into `clean::Crate`
56     pub access_levels: RefCell<AccessLevels<DefId>>,
57     /// Later on moved into `html::render::CACHE_KEY`
58     pub renderinfo: RefCell<RenderInfo>,
59     /// Later on moved through `clean::Crate` into `html::render::CACHE_KEY`
60     pub external_traits: RefCell<FxHashMap<DefId, clean::Trait>>,
61     /// Used while populating `external_traits` to ensure we don't process the same trait twice at
62     /// the same time.
63     pub active_extern_traits: RefCell<Vec<DefId>>,
64     // The current set of type and lifetime substitutions,
65     // for expanding type aliases at the HIR level:
66
67     /// Table type parameter definition -> substituted type
68     pub ty_substs: RefCell<FxHashMap<Def, clean::Type>>,
69     /// Table node id of lifetime parameter definition -> substituted lifetime
70     pub lt_substs: RefCell<FxHashMap<DefId, clean::Lifetime>>,
71 }
72
73 impl<'a, 'tcx, 'rcx> DocContext<'a, 'tcx, 'rcx> {
74     pub fn sess(&self) -> &session::Session {
75         &self.tcx.sess
76     }
77
78     /// Call the closure with the given parameters set as
79     /// the substitutions for a type alias' RHS.
80     pub fn enter_alias<F, R>(&self,
81                              ty_substs: FxHashMap<Def, clean::Type>,
82                              lt_substs: FxHashMap<DefId, clean::Lifetime>,
83                              f: F) -> R
84     where F: FnOnce() -> R {
85         let (old_tys, old_lts) =
86             (mem::replace(&mut *self.ty_substs.borrow_mut(), ty_substs),
87              mem::replace(&mut *self.lt_substs.borrow_mut(), lt_substs));
88         let r = f();
89         *self.ty_substs.borrow_mut() = old_tys;
90         *self.lt_substs.borrow_mut() = old_lts;
91         r
92     }
93 }
94
95 pub trait DocAccessLevels {
96     fn is_doc_reachable(&self, did: DefId) -> bool;
97 }
98
99 impl DocAccessLevels for AccessLevels<DefId> {
100     fn is_doc_reachable(&self, did: DefId) -> bool {
101         self.is_public(did)
102     }
103 }
104
105
106 pub fn run_core(search_paths: SearchPaths,
107                 cfgs: Vec<String>,
108                 externs: config::Externs,
109                 input: Input,
110                 triple: Option<String>,
111                 maybe_sysroot: Option<PathBuf>,
112                 allow_warnings: bool,
113                 force_unstable_if_unmarked: bool) -> (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_driver::get_trans(&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 mut crate_loader = CrateLoader::new(&sess, &cstore, &name);
166
167     let resolver_arenas = resolve::Resolver::arenas();
168     let result = driver::phase_2_configure_and_expand_inner(&sess,
169                                                       &cstore,
170                                                       krate,
171                                                       None,
172                                                       &name,
173                                                       None,
174                                                       resolve::MakeGlobMap::No,
175                                                       &resolver_arenas,
176                                                       &mut crate_loader,
177                                                       |_| Ok(()));
178     let driver::InnerExpansionResult {
179         mut hir_forest,
180         resolver,
181         ..
182     } = abort_on_err(result, &sess);
183
184     // We need to hold on to the complete resolver, so we clone everything
185     // for the analysis passes to use. Suboptimal, but necessary in the
186     // current architecture.
187     let defs = resolver.definitions.clone();
188     let resolutions = ty::Resolutions {
189         freevars: resolver.freevars.clone(),
190         export_map: resolver.export_map.clone(),
191         trait_map: resolver.trait_map.clone(),
192         maybe_unused_trait_imports: resolver.maybe_unused_trait_imports.clone(),
193         maybe_unused_extern_crates: resolver.maybe_unused_extern_crates.clone(),
194     };
195     let analysis = ty::CrateAnalysis {
196         access_levels: Rc::new(AccessLevels::default()),
197         name: name.to_string(),
198         glob_map: if resolver.make_glob_map { Some(resolver.glob_map.clone()) } else { None },
199     };
200
201     let arenas = AllArenas::new();
202     let hir_map = hir_map::map_crate(&sess, &*cstore, &mut hir_forest, &defs);
203     let output_filenames = driver::build_output_filenames(&input,
204                                                           &None,
205                                                           &None,
206                                                           &[],
207                                                           &sess);
208
209     let resolver = RefCell::new(resolver);
210
211     abort_on_err(driver::phase_3_run_analysis_passes(&*trans,
212                                                      control,
213                                                      &sess,
214                                                      &*cstore,
215                                                      hir_map,
216                                                      analysis,
217                                                      resolutions,
218                                                      &arenas,
219                                                      &name,
220                                                      &output_filenames,
221                                                      |tcx, analysis, _, result| {
222         if let Err(_) = result {
223             sess.fatal("Compilation failed, aborting rustdoc");
224         }
225
226         let ty::CrateAnalysis { access_levels, .. } = analysis;
227
228         // Convert from a NodeId set to a DefId set since we don't always have easy access
229         // to the map from defid -> nodeid
230         let access_levels = AccessLevels {
231             map: access_levels.map.iter()
232                                   .map(|(&k, &v)| (tcx.hir.local_def_id(k), v))
233                                   .collect()
234         };
235
236         let ctxt = DocContext {
237             tcx,
238             resolver: &resolver,
239             populated_all_crate_impls: Cell::new(false),
240             access_levels: RefCell::new(access_levels),
241             external_traits: Default::default(),
242             active_extern_traits: Default::default(),
243             renderinfo: Default::default(),
244             ty_substs: Default::default(),
245             lt_substs: Default::default(),
246             mod_ids: Default::default(),
247         };
248         debug!("crate: {:?}", tcx.hir.krate());
249
250         let krate = {
251             let mut v = RustdocVisitor::new(&*cstore, &ctxt);
252             v.visit(tcx.hir.krate());
253             v.clean(&ctxt)
254         };
255
256         (krate, ctxt.renderinfo.into_inner())
257     }), &sess)
258 }