]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/core.rs
Rename `colorful-json` to `json-rendered` and make it a selection instead of a bool
[rust.git] / src / librustdoc / core.rs
1 use rustc_lint;
2 use rustc::session::{self, config};
3 use rustc::hir::def_id::{DefId, DefIndex, DefIndexAddressSpace, CrateNum, LOCAL_CRATE};
4 use rustc::hir::def::Def;
5 use rustc::hir::{self, HirId, HirVec};
6 use rustc::middle::cstore::CrateStore;
7 use rustc::middle::privacy::AccessLevels;
8 use rustc::ty::{self, TyCtxt};
9 use rustc::lint::{self, LintPass};
10 use rustc::session::config::ErrorOutputType;
11 use rustc::session::DiagnosticOutput;
12 use rustc::util::nodemap::{FxHashMap, FxHashSet};
13 use rustc_interface::interface;
14 use rustc_driver::abort_on_err;
15 use rustc_resolve as resolve;
16 use rustc_metadata::cstore::CStore;
17 use rustc_target::spec::TargetTriple;
18
19 use syntax::ast::{self, Ident};
20 use syntax::source_map;
21 use syntax::feature_gate::UnstableFeatures;
22 use syntax::json::JsonEmitter;
23 use syntax::ptr::P;
24 use syntax::symbol::keywords;
25 use syntax_pos::DUMMY_SP;
26 use errors;
27 use errors::emitter::{Emitter, EmitterWriter};
28 use parking_lot::ReentrantMutex;
29
30 use std::cell::RefCell;
31 use std::mem;
32 use rustc_data_structures::sync::{self, Lrc};
33 use std::sync::Arc;
34 use std::rc::Rc;
35
36 use crate::visit_ast::RustdocVisitor;
37 use crate::config::{Options as RustdocOptions, RenderOptions};
38 use crate::clean;
39 use crate::clean::{get_path_for_type, Clean, MAX_DEF_ID, AttributesExt};
40 use crate::html::render::RenderInfo;
41
42 use crate::passes;
43
44 pub use rustc::session::config::{Input, Options, CodegenOptions};
45 pub use rustc::session::search_paths::SearchPath;
46
47 pub type ExternalPaths = FxHashMap<DefId, (Vec<String>, clean::TypeKind)>;
48
49 pub struct DocContext<'tcx> {
50
51     pub tcx: TyCtxt<'tcx, 'tcx, 'tcx>,
52     pub resolver: Rc<Option<RefCell<interface::BoxedResolver>>>,
53     /// The stack of module NodeIds up till this point
54     pub crate_name: Option<String>,
55     pub cstore: Lrc<CStore>,
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: Arc<ReentrantMutex<RefCell<FxHashMap<DefId, clean::Trait>>>>,
60     /// Used while populating `external_traits` to ensure we don't process the same trait twice at
61     /// the same time.
62     pub active_extern_traits: RefCell<Vec<DefId>>,
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 `NodeId` of lifetime parameter definition -> substituted lifetime
69     pub lt_substs: RefCell<FxHashMap<DefId, clean::Lifetime>>,
70     /// Table node id of const parameter definition -> substituted const
71     pub ct_substs: RefCell<FxHashMap<Def, clean::Constant>>,
72     /// Table DefId of `impl Trait` in argument position -> bounds
73     pub impl_trait_bounds: RefCell<FxHashMap<DefId, Vec<clean::GenericBound>>>,
74     pub send_trait: Option<DefId>,
75     pub fake_def_ids: RefCell<FxHashMap<CrateNum, DefId>>,
76     pub all_fake_def_ids: RefCell<FxHashSet<DefId>>,
77     /// Maps (type_id, trait_id) -> auto trait impl
78     pub generated_synthetics: RefCell<FxHashSet<(DefId, DefId)>>,
79     pub all_traits: Vec<DefId>,
80 }
81
82 impl<'tcx> DocContext<'tcx> {
83     pub fn sess(&self) -> &session::Session {
84         &self.tcx.sess
85     }
86
87     pub fn enter_resolver<F, R>(&self, f: F) -> R
88     where F: FnOnce(&mut resolve::Resolver<'_>) -> R {
89         let resolver = &*self.resolver;
90         let resolver = resolver.as_ref().unwrap();
91         resolver.borrow_mut().access(f)
92     }
93
94     /// Call the closure with the given parameters set as
95     /// the substitutions for a type alias' RHS.
96     pub fn enter_alias<F, R>(&self,
97                              ty_substs: FxHashMap<Def, clean::Type>,
98                              lt_substs: FxHashMap<DefId, clean::Lifetime>,
99                              ct_substs: FxHashMap<Def, clean::Constant>,
100                              f: F) -> R
101     where F: FnOnce() -> R {
102         let (old_tys, old_lts, old_cts) = (
103             mem::replace(&mut *self.ty_substs.borrow_mut(), ty_substs),
104             mem::replace(&mut *self.lt_substs.borrow_mut(), lt_substs),
105             mem::replace(&mut *self.ct_substs.borrow_mut(), ct_substs),
106         );
107         let r = f();
108         *self.ty_substs.borrow_mut() = old_tys;
109         *self.lt_substs.borrow_mut() = old_lts;
110         *self.ct_substs.borrow_mut() = old_cts;
111         r
112     }
113
114     // This is an ugly hack, but it's the simplest way to handle synthetic impls without greatly
115     // refactoring either librustdoc or librustc. In particular, allowing new DefIds to be
116     // registered after the AST is constructed would require storing the defid mapping in a
117     // RefCell, decreasing the performance for normal compilation for very little gain.
118     //
119     // Instead, we construct 'fake' def ids, which start immediately after the last DefId in
120     // DefIndexAddressSpace::Low. In the Debug impl for clean::Item, we explicitly check for fake
121     // def ids, as we'll end up with a panic if we use the DefId Debug impl for fake DefIds
122     pub fn next_def_id(&self, crate_num: CrateNum) -> DefId {
123         let start_def_id = {
124             let next_id = if crate_num == LOCAL_CRATE {
125                 self.tcx
126                     .hir()
127                     .definitions()
128                     .def_path_table()
129                     .next_id(DefIndexAddressSpace::Low)
130             } else {
131                 self.cstore
132                     .def_path_table(crate_num)
133                     .next_id(DefIndexAddressSpace::Low)
134             };
135
136             DefId {
137                 krate: crate_num,
138                 index: next_id,
139             }
140         };
141
142         let mut fake_ids = self.fake_def_ids.borrow_mut();
143
144         let def_id = fake_ids.entry(crate_num).or_insert(start_def_id).clone();
145         fake_ids.insert(
146             crate_num,
147             DefId {
148                 krate: crate_num,
149                 index: DefIndex::from_array_index(
150                     def_id.index.as_array_index() + 1,
151                     def_id.index.address_space(),
152                 ),
153             },
154         );
155
156         MAX_DEF_ID.with(|m| {
157             m.borrow_mut()
158                 .entry(def_id.krate.clone())
159                 .or_insert(start_def_id);
160         });
161
162         self.all_fake_def_ids.borrow_mut().insert(def_id);
163
164         def_id.clone()
165     }
166
167     /// Like the function of the same name on the HIR map, but skips calling it on fake DefIds.
168     /// (This avoids a slice-index-out-of-bounds panic.)
169     pub fn as_local_node_id(&self, def_id: DefId) -> Option<ast::NodeId> {
170         if self.all_fake_def_ids.borrow().contains(&def_id) {
171             None
172         } else {
173             self.tcx.hir().as_local_node_id(def_id)
174         }
175     }
176
177     // FIXME(@ljedrz): remove the NodeId variant
178     pub fn as_local_hir_id(&self, def_id: DefId) -> Option<HirId> {
179         if self.all_fake_def_ids.borrow().contains(&def_id) {
180             None
181         } else {
182             self.tcx.hir().as_local_hir_id(def_id)
183         }
184     }
185
186     pub fn get_real_ty<F>(&self,
187                           def_id: DefId,
188                           def_ctor: &F,
189                           real_name: &Option<Ident>,
190                           generics: &ty::Generics,
191     ) -> hir::Ty
192     where F: Fn(DefId) -> Def {
193         let path = get_path_for_type(self.tcx, def_id, def_ctor);
194         let mut segments = path.segments.into_vec();
195         let last = segments.pop().expect("segments were empty");
196
197         segments.push(hir::PathSegment::new(
198             real_name.unwrap_or(last.ident),
199             None,
200             None,
201             self.generics_to_path_params(generics.clone()),
202             false,
203         ));
204
205         let new_path = hir::Path {
206             span: path.span,
207             def: path.def,
208             segments: HirVec::from_vec(segments),
209         };
210
211         hir::Ty {
212             node: hir::TyKind::Path(hir::QPath::Resolved(None, P(new_path))),
213             span: DUMMY_SP,
214             hir_id: hir::DUMMY_HIR_ID,
215         }
216     }
217
218     pub fn generics_to_path_params(&self, generics: ty::Generics) -> hir::GenericArgs {
219         let mut args = vec![];
220
221         for param in generics.params.iter() {
222             match param.kind {
223                 ty::GenericParamDefKind::Lifetime => {
224                     let name = if param.name == "" {
225                         hir::ParamName::Plain(keywords::StaticLifetime.ident())
226                     } else {
227                         hir::ParamName::Plain(ast::Ident::from_interned_str(param.name))
228                     };
229
230                     args.push(hir::GenericArg::Lifetime(hir::Lifetime {
231                         hir_id: hir::DUMMY_HIR_ID,
232                         span: DUMMY_SP,
233                         name: hir::LifetimeName::Param(name),
234                     }));
235                 }
236                 ty::GenericParamDefKind::Type { .. } => {
237                     args.push(hir::GenericArg::Type(self.ty_param_to_ty(param.clone())));
238                 }
239                 ty::GenericParamDefKind::Const => {
240                     args.push(hir::GenericArg::Const(hir::ConstArg {
241                         value: hir::AnonConst {
242                             hir_id: hir::DUMMY_HIR_ID,
243                             body: hir::BodyId {
244                                 hir_id: hir::DUMMY_HIR_ID,
245                             }
246                         },
247                         span: DUMMY_SP,
248                     }))
249                 }
250             }
251         }
252
253         hir::GenericArgs {
254             args: HirVec::from_vec(args),
255             bindings: HirVec::new(),
256             parenthesized: false,
257         }
258     }
259
260     pub fn ty_param_to_ty(&self, param: ty::GenericParamDef) -> hir::Ty {
261         debug!("ty_param_to_ty({:?}) {:?}", param, param.def_id);
262         hir::Ty {
263             node: hir::TyKind::Path(hir::QPath::Resolved(
264                 None,
265                 P(hir::Path {
266                     span: DUMMY_SP,
267                     def: Def::TyParam(param.def_id),
268                     segments: HirVec::from_vec(vec![
269                         hir::PathSegment::from_ident(Ident::from_interned_str(param.name))
270                     ]),
271                 }),
272             )),
273             span: DUMMY_SP,
274             hir_id: hir::DUMMY_HIR_ID,
275         }
276     }
277 }
278
279 pub trait DocAccessLevels {
280     fn is_doc_reachable(&self, did: DefId) -> bool;
281 }
282
283 impl DocAccessLevels for AccessLevels<DefId> {
284     fn is_doc_reachable(&self, did: DefId) -> bool {
285         self.is_public(did)
286     }
287 }
288
289 /// Creates a new diagnostic `Handler` that can be used to emit warnings and errors.
290 ///
291 /// If the given `error_format` is `ErrorOutputType::Json` and no `SourceMap` is given, a new one
292 /// will be created for the handler.
293 pub fn new_handler(error_format: ErrorOutputType,
294                    source_map: Option<Lrc<source_map::SourceMap>>,
295                    treat_err_as_bug: Option<usize>,
296                    ui_testing: bool,
297 ) -> errors::Handler {
298     // rustdoc doesn't override (or allow to override) anything from this that is relevant here, so
299     // stick to the defaults
300     let sessopts = Options::default();
301     let emitter: Box<dyn Emitter + sync::Send> = match error_format {
302         ErrorOutputType::HumanReadable(kind) => {
303             let (short, color_config) = kind.unzip();
304             Box::new(
305                 EmitterWriter::stderr(
306                     color_config,
307                     source_map.map(|cm| cm as _),
308                     short,
309                     sessopts.debugging_opts.teach,
310                 ).ui_testing(ui_testing)
311             )
312         },
313         ErrorOutputType::Json { pretty, json_rendered } => {
314             let source_map = source_map.unwrap_or_else(
315                 || Lrc::new(source_map::SourceMap::new(sessopts.file_path_mapping())));
316             Box::new(
317                 JsonEmitter::stderr(
318                     None,
319                     source_map,
320                     pretty,
321                     json_rendered,
322                 ).ui_testing(ui_testing)
323             )
324         },
325     };
326
327     errors::Handler::with_emitter_and_flags(
328         emitter,
329         errors::HandlerFlags {
330             can_emit_warnings: true,
331             treat_err_as_bug,
332             report_delayed_bugs: false,
333             external_macro_backtrace: false,
334             ..Default::default()
335         },
336     )
337 }
338
339 pub fn run_core(options: RustdocOptions) -> (clean::Crate, RenderInfo, RenderOptions, Vec<String>) {
340     // Parse, resolve, and typecheck the given crate.
341
342     let RustdocOptions {
343         input,
344         crate_name,
345         error_format,
346         libs,
347         externs,
348         cfgs,
349         codegen_options,
350         debugging_options,
351         target,
352         edition,
353         maybe_sysroot,
354         lint_opts,
355         describe_lints,
356         lint_cap,
357         mut default_passes,
358         mut manual_passes,
359         display_warnings,
360         render_options,
361         ..
362     } = options;
363
364     let cpath = Some(input.clone());
365     let input = Input::File(input);
366
367     let intra_link_resolution_failure_name = lint::builtin::INTRA_DOC_LINK_RESOLUTION_FAILURE.name;
368     let warnings_lint_name = lint::builtin::WARNINGS.name;
369     let missing_docs = rustc_lint::builtin::MISSING_DOCS.name;
370     let missing_doc_example = rustc_lint::builtin::MISSING_DOC_CODE_EXAMPLES.name;
371     let private_doc_tests = rustc_lint::builtin::PRIVATE_DOC_TESTS.name;
372
373     // In addition to those specific lints, we also need to whitelist those given through
374     // command line, otherwise they'll get ignored and we don't want that.
375     let mut whitelisted_lints = vec![warnings_lint_name.to_owned(),
376                                      intra_link_resolution_failure_name.to_owned(),
377                                      missing_docs.to_owned(),
378                                      missing_doc_example.to_owned(),
379                                      private_doc_tests.to_owned()];
380
381     whitelisted_lints.extend(lint_opts.iter().map(|(lint, _)| lint).cloned());
382
383     let lints = || {
384         lint::builtin::HardwiredLints
385             .get_lints()
386             .into_iter()
387             .chain(rustc_lint::SoftLints.get_lints().into_iter())
388     };
389
390     let lint_opts = lints().filter_map(|lint| {
391         if lint.name == warnings_lint_name ||
392             lint.name == intra_link_resolution_failure_name {
393             None
394         } else {
395             Some((lint.name_lower(), lint::Allow))
396         }
397     }).chain(lint_opts.into_iter()).collect::<Vec<_>>();
398
399     let lint_caps = lints().filter_map(|lint| {
400         // We don't want to whitelist *all* lints so let's
401         // ignore those ones.
402         if whitelisted_lints.iter().any(|l| &lint.name == l) {
403             None
404         } else {
405             Some((lint::LintId::of(lint), lint::Allow))
406         }
407     }).collect();
408
409     let host_triple = TargetTriple::from_triple(config::host_triple());
410     // plays with error output here!
411     let sessopts = config::Options {
412         maybe_sysroot,
413         search_paths: libs,
414         crate_types: vec![config::CrateType::Rlib],
415         lint_opts: if !display_warnings {
416             lint_opts
417         } else {
418             vec![]
419         },
420         lint_cap: Some(lint_cap.unwrap_or_else(|| lint::Forbid)),
421         cg: codegen_options,
422         externs,
423         target_triple: target.unwrap_or(host_triple),
424         // Ensure that rustdoc works even if rustc is feature-staged
425         unstable_features: UnstableFeatures::Allow,
426         actually_rustdoc: true,
427         debugging_opts: debugging_options.clone(),
428         error_format,
429         edition,
430         describe_lints,
431         ..Options::default()
432     };
433
434     let config = interface::Config {
435         opts: sessopts,
436         crate_cfg: config::parse_cfgspecs(cfgs),
437         input,
438         input_path: cpath,
439         output_file: None,
440         output_dir: None,
441         file_loader: None,
442         diagnostic_output: DiagnosticOutput::Default,
443         stderr: None,
444         crate_name: crate_name.clone(),
445         lint_caps,
446     };
447
448     interface::run_compiler_in_existing_thread_pool(config, |compiler| {
449         let sess = compiler.session();
450
451         // We need to hold on to the complete resolver, so we cause everything to be
452         // cloned for the analysis passes to use. Suboptimal, but necessary in the
453         // current architecture.
454         let resolver = abort_on_err(compiler.expansion(), sess).peek().1.clone();
455
456         if sess.err_count() > 0 {
457             sess.fatal("Compilation failed, aborting rustdoc");
458         }
459
460         let mut global_ctxt = abort_on_err(compiler.global_ctxt(), sess).take();
461
462         global_ctxt.enter(|tcx| {
463             tcx.analysis(LOCAL_CRATE).ok();
464
465             // Abort if there were any errors so far
466             sess.abort_if_errors();
467
468             let access_levels = tcx.privacy_access_levels(LOCAL_CRATE);
469             // Convert from a HirId set to a DefId set since we don't always have easy access
470             // to the map from defid -> hirid
471             let access_levels = AccessLevels {
472                 map: access_levels.map.iter()
473                                     .map(|(&k, &v)| (tcx.hir().local_def_id_from_hir_id(k), v))
474                                     .collect()
475             };
476
477             let send_trait = if crate_name == Some("core".to_string()) {
478                 clean::path_to_def_local(&tcx, &["marker", "Send"])
479             } else {
480                 clean::path_to_def(&tcx, &["core", "marker", "Send"])
481             };
482
483             let mut renderinfo = RenderInfo::default();
484             renderinfo.access_levels = access_levels;
485
486             let ctxt = DocContext {
487                 tcx,
488                 resolver,
489                 crate_name,
490                 cstore: compiler.cstore().clone(),
491                 external_traits: Default::default(),
492                 active_extern_traits: Default::default(),
493                 renderinfo: RefCell::new(renderinfo),
494                 ty_substs: Default::default(),
495                 lt_substs: Default::default(),
496                 ct_substs: Default::default(),
497                 impl_trait_bounds: Default::default(),
498                 send_trait: send_trait,
499                 fake_def_ids: Default::default(),
500                 all_fake_def_ids: Default::default(),
501                 generated_synthetics: Default::default(),
502                 all_traits: tcx.all_traits(LOCAL_CRATE).to_vec(),
503             };
504             debug!("crate: {:?}", tcx.hir().krate());
505
506             let mut krate = {
507                 let mut v = RustdocVisitor::new(&ctxt);
508                 v.visit(tcx.hir().krate());
509                 v.clean(&ctxt)
510             };
511
512             fn report_deprecated_attr(name: &str, diag: &errors::Handler) {
513                 let mut msg = diag.struct_warn(&format!("the `#![doc({})]` attribute is \
514                                                          considered deprecated", name));
515                 msg.warn("please see https://github.com/rust-lang/rust/issues/44136");
516
517                 if name == "no_default_passes" {
518                     msg.help("you may want to use `#![doc(document_private_items)]`");
519                 }
520
521                 msg.emit();
522             }
523
524             // Process all of the crate attributes, extracting plugin metadata along
525             // with the passes which we are supposed to run.
526             for attr in krate.module.as_ref().unwrap().attrs.lists("doc") {
527                 let diag = ctxt.sess().diagnostic();
528
529                 let name = attr.name_or_empty();
530                 if attr.is_word() {
531                     if name == "no_default_passes" {
532                         report_deprecated_attr("no_default_passes", diag);
533                         if default_passes == passes::DefaultPassOption::Default {
534                             default_passes = passes::DefaultPassOption::None;
535                         }
536                     }
537                 } else if let Some(value) = attr.value_str() {
538                     let sink = match name.get() {
539                         "passes" => {
540                             report_deprecated_attr("passes = \"...\"", diag);
541                             &mut manual_passes
542                         },
543                         "plugins" => {
544                             report_deprecated_attr("plugins = \"...\"", diag);
545                             eprintln!("WARNING: #![doc(plugins = \"...\")] no longer functions; \
546                                       see CVE-2018-1000622");
547                             continue
548                         },
549                         _ => continue,
550                     };
551                     for p in value.as_str().split_whitespace() {
552                         sink.push(p.to_string());
553                     }
554                 }
555
556                 if attr.is_word() && name == "document_private_items" {
557                     if default_passes == passes::DefaultPassOption::Default {
558                         default_passes = passes::DefaultPassOption::Private;
559                     }
560                 }
561             }
562
563             let mut passes: Vec<String> =
564                 passes::defaults(default_passes).iter().map(|p| p.to_string()).collect();
565             passes.extend(manual_passes);
566
567             info!("Executing passes");
568
569             for pass_name in &passes {
570                 match passes::find_pass(pass_name).map(|p| p.pass) {
571                     Some(pass) => {
572                         debug!("running pass {}", pass_name);
573                         krate = pass(krate, &ctxt);
574                     }
575                     None => error!("unknown pass {}, skipping", *pass_name),
576                 }
577             }
578
579             ctxt.sess().abort_if_errors();
580
581             (krate, ctxt.renderinfo.into_inner(), render_options, passes)
582         })
583     })
584 }