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