1 use crate::core::DocContext;
3 Clean, Crate, Deprecation, ExternalCrate, FnDecl, FunctionRetTy, Generic, GenericArg,
4 GenericArgs, Generics, GenericBound, GenericParamDef, GetDefId, ImportSource, Item, ItemEnum,
5 Lifetime, MacroKind, Path, PathSegment, Primitive, PrimitiveType, Region, RegionVid,
6 ResolvedPath, Span, Stability, Type, TypeBinding, TypeKind, Visibility, WherePredicate, inline,
8 use crate::clean::blanket_impl::BlanketImplFinder;
9 use crate::clean::auto_trait::AutoTraitFinder;
12 use rustc::hir::def::{DefKind, Res};
13 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
14 use rustc::ty::{self, DefIdTree, Ty};
15 use rustc::ty::subst::{SubstsRef, GenericArgKind};
16 use rustc::util::nodemap::FxHashSet;
18 use syntax_pos::symbol::{Symbol, kw, sym};
22 pub fn krate(mut cx: &mut DocContext<'_>) -> Crate {
23 use crate::visit_lib::LibEmbargoVisitor;
25 let krate = cx.tcx.hir().krate();
26 let module = crate::visit_ast::RustdocVisitor::new(&mut cx).visit(krate);
28 let mut r = cx.renderinfo.get_mut();
29 r.deref_trait_did = cx.tcx.lang_items().deref_trait();
30 r.deref_mut_trait_did = cx.tcx.lang_items().deref_mut_trait();
31 r.owned_box_did = cx.tcx.lang_items().owned_box();
33 let mut externs = Vec::new();
34 for &cnum in cx.tcx.crates().iter() {
35 externs.push((cnum, cnum.clean(cx)));
36 // Analyze doc-reachability for extern items
37 LibEmbargoVisitor::new(&mut cx).visit_lib(cnum);
39 externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
41 // Clean the crate, translating the entire libsyntax AST to one that is
42 // understood by rustdoc.
43 let mut module = module.clean(cx);
44 let mut masked_crates = FxHashSet::default();
47 ModuleItem(ref module) => {
48 for it in &module.items {
49 // `compiler_builtins` should be masked too, but we can't apply
50 // `#[doc(masked)]` to the injected `extern crate` because it's unstable.
51 if it.is_extern_crate()
52 && (it.attrs.has_doc_flag(sym::masked)
53 || cx.tcx.is_compiler_builtins(it.def_id.krate))
55 masked_crates.insert(it.def_id.krate);
62 let ExternalCrate { name, src, primitives, keywords, .. } = LOCAL_CRATE.clean(cx);
64 let m = match module.inner {
65 ModuleItem(ref mut m) => m,
68 m.items.extend(primitives.iter().map(|&(def_id, prim, ref attrs)| {
70 source: Span::empty(),
71 name: Some(prim.to_url_str().to_string()),
74 stability: get_stability(cx, def_id),
75 deprecation: get_deprecation(cx, def_id),
77 inner: PrimitiveItem(prim),
80 m.items.extend(keywords.into_iter().map(|(def_id, kw, attrs)| {
82 source: Span::empty(),
83 name: Some(kw.clone()),
86 stability: get_stability(cx, def_id),
87 deprecation: get_deprecation(cx, def_id),
89 inner: KeywordItem(kw),
101 external_traits: cx.external_traits.clone(),
107 // extract the stability index for a node from tcx, if possible
108 pub fn get_stability(cx: &DocContext<'_>, def_id: DefId) -> Option<Stability> {
109 cx.tcx.lookup_stability(def_id).clean(cx)
112 pub fn get_deprecation(cx: &DocContext<'_>, def_id: DefId) -> Option<Deprecation> {
113 cx.tcx.lookup_deprecation(def_id).clean(cx)
116 pub fn external_generic_args(
118 trait_did: Option<DefId>,
120 bindings: Vec<TypeBinding>,
121 substs: SubstsRef<'_>,
123 let mut skip_self = has_self;
124 let mut ty_kind = None;
125 let args: Vec<_> = substs.iter().filter_map(|kind| match kind.unpack() {
126 GenericArgKind::Lifetime(lt) => {
127 lt.clean(cx).and_then(|lt| Some(GenericArg::Lifetime(lt)))
129 GenericArgKind::Type(_) if skip_self => {
133 GenericArgKind::Type(ty) => {
134 ty_kind = Some(&ty.kind);
135 Some(GenericArg::Type(ty.clean(cx)))
137 GenericArgKind::Const(ct) => Some(GenericArg::Const(ct.clean(cx))),
141 // Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C
142 Some(did) if cx.tcx.lang_items().fn_trait_kind(did).is_some() => {
143 assert!(ty_kind.is_some());
144 let inputs = match ty_kind {
145 Some(ty::Tuple(ref tys)) => tys.iter().map(|t| t.expect_ty().clean(cx)).collect(),
146 _ => return GenericArgs::AngleBracketed { args, bindings },
149 // FIXME(#20299) return type comes from a projection now
150 // match types[1].kind {
151 // ty::Tuple(ref v) if v.is_empty() => None, // -> ()
152 // _ => Some(types[1].clean(cx))
154 GenericArgs::Parenthesized { inputs, output }
157 GenericArgs::AngleBracketed { args, bindings }
162 // trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
163 // from Fn<(A, B,), C> to Fn(A, B) -> C
164 pub fn external_path(cx: &DocContext<'_>, name: Symbol, trait_did: Option<DefId>, has_self: bool,
165 bindings: Vec<TypeBinding>, substs: SubstsRef<'_>) -> Path {
169 segments: vec![PathSegment {
170 name: name.to_string(),
171 args: external_generic_args(cx, trait_did, has_self, bindings, substs)
176 /// The point of this function is to replace bounds with types.
178 /// i.e. `[T, U]` when you have the following bounds: `T: Display, U: Option<T>` will return
179 /// `[Display, Option]` (we just returns the list of the types, we don't care about the
180 /// wrapped types in here).
181 pub fn get_real_types(
186 ) -> FxHashSet<Type> {
187 let arg_s = arg.print().to_string();
188 let mut res = FxHashSet::default();
189 if recurse >= 10 { // FIXME: remove this whole recurse thing when the recursion bug is fixed
192 if arg.is_full_generic() {
193 if let Some(where_pred) = generics.where_predicates.iter().find(|g| {
195 &WherePredicate::BoundPredicate { ref ty, .. } => ty.def_id() == arg.def_id(),
199 let bounds = where_pred.get_bounds().unwrap_or_else(|| &[]);
200 for bound in bounds.iter() {
202 GenericBound::TraitBound(ref poly_trait, _) => {
203 for x in poly_trait.generic_params.iter() {
207 if let Some(ty) = x.get_type() {
208 let adds = get_real_types(generics, &ty, cx, recurse + 1);
209 if !adds.is_empty() {
211 } else if !ty.is_full_generic() {
221 if let Some(bound) = generics.params.iter().find(|g| {
222 g.is_type() && g.name == arg_s
224 for bound in bound.get_bounds().unwrap_or_else(|| &[]) {
225 if let Some(ty) = bound.get_trait_type() {
226 let adds = get_real_types(generics, &ty, cx, recurse + 1);
227 if !adds.is_empty() {
229 } else if !ty.is_full_generic() {
230 res.insert(ty.clone());
236 res.insert(arg.clone());
237 if let Some(gens) = arg.generics() {
238 for gen in gens.iter() {
239 if gen.is_full_generic() {
240 let adds = get_real_types(generics, gen, cx, recurse + 1);
241 if !adds.is_empty() {
245 res.insert(gen.clone());
253 /// Return the full list of types when bounds have been resolved.
255 /// i.e. `fn foo<A: Display, B: Option<A>>(x: u32, y: B)` will return
256 /// `[u32, Display, Option]`.
257 pub fn get_all_types(
261 ) -> (Vec<Type>, Vec<Type>) {
262 let mut all_types = FxHashSet::default();
263 for arg in decl.inputs.values.iter() {
264 if arg.type_.is_self_type() {
267 let args = get_real_types(generics, &arg.type_, cx, 0);
268 if !args.is_empty() {
269 all_types.extend(args);
271 all_types.insert(arg.type_.clone());
275 let ret_types = match decl.output {
276 FunctionRetTy::Return(ref return_type) => {
277 let mut ret = get_real_types(generics, &return_type, cx, 0);
279 ret.insert(return_type.clone());
281 ret.into_iter().collect()
285 (all_types.into_iter().collect(), ret_types)
288 pub fn strip_type(ty: Type) -> Type {
290 Type::ResolvedPath { path, param_names, did, is_generic } => {
291 Type::ResolvedPath { path: strip_path(&path), param_names, did, is_generic }
293 Type::Tuple(inner_tys) => {
294 Type::Tuple(inner_tys.iter().map(|t| strip_type(t.clone())).collect())
296 Type::Slice(inner_ty) => Type::Slice(Box::new(strip_type(*inner_ty))),
297 Type::Array(inner_ty, s) => Type::Array(Box::new(strip_type(*inner_ty)), s),
298 Type::RawPointer(m, inner_ty) => Type::RawPointer(m, Box::new(strip_type(*inner_ty))),
299 Type::BorrowedRef { lifetime, mutability, type_ } => {
300 Type::BorrowedRef { lifetime, mutability, type_: Box::new(strip_type(*type_)) }
302 Type::QPath { name, self_type, trait_ } => {
305 self_type: Box::new(strip_type(*self_type)), trait_: Box::new(strip_type(*trait_))
312 pub fn strip_path(path: &Path) -> Path {
313 let segments = path.segments.iter().map(|s| {
315 name: s.name.clone(),
316 args: GenericArgs::AngleBracketed {
325 res: path.res.clone(),
330 pub fn qpath_to_string(p: &hir::QPath) -> String {
331 let segments = match *p {
332 hir::QPath::Resolved(_, ref path) => &path.segments,
333 hir::QPath::TypeRelative(_, ref segment) => return segment.ident.to_string(),
336 let mut s = String::new();
337 for (i, seg) in segments.iter().enumerate() {
341 if seg.ident.name != kw::PathRoot {
342 s.push_str(&seg.ident.as_str());
348 pub fn build_deref_target_impls(cx: &DocContext<'_>,
350 ret: &mut Vec<Item>) {
351 use self::PrimitiveType::*;
355 let target = match item.inner {
356 TypedefItem(ref t, true) => &t.type_,
359 let primitive = match *target {
360 ResolvedPath { did, .. } if did.is_local() => continue,
361 ResolvedPath { did, .. } => {
362 ret.extend(inline::build_impls(cx, did, None));
365 _ => match target.primitive_type() {
370 let did = match primitive {
371 Isize => tcx.lang_items().isize_impl(),
372 I8 => tcx.lang_items().i8_impl(),
373 I16 => tcx.lang_items().i16_impl(),
374 I32 => tcx.lang_items().i32_impl(),
375 I64 => tcx.lang_items().i64_impl(),
376 I128 => tcx.lang_items().i128_impl(),
377 Usize => tcx.lang_items().usize_impl(),
378 U8 => tcx.lang_items().u8_impl(),
379 U16 => tcx.lang_items().u16_impl(),
380 U32 => tcx.lang_items().u32_impl(),
381 U64 => tcx.lang_items().u64_impl(),
382 U128 => tcx.lang_items().u128_impl(),
383 F32 => tcx.lang_items().f32_impl(),
384 F64 => tcx.lang_items().f64_impl(),
385 Char => tcx.lang_items().char_impl(),
386 Bool => tcx.lang_items().bool_impl(),
387 Str => tcx.lang_items().str_impl(),
388 Slice => tcx.lang_items().slice_impl(),
389 Array => tcx.lang_items().slice_impl(),
392 RawPointer => tcx.lang_items().const_ptr_impl(),
397 if let Some(did) = did {
399 inline::build_impl(cx, did, None, ret);
408 fn to_src(&self, cx: &DocContext<'_>) -> String;
411 impl ToSource for syntax_pos::Span {
412 fn to_src(&self, cx: &DocContext<'_>) -> String {
413 debug!("converting span {:?} to snippet", self.clean(cx));
414 let sn = match cx.sess().source_map().span_to_snippet(*self) {
416 Err(_) => String::new()
418 debug!("got snippet {}", sn);
423 pub fn name_from_pat(p: &hir::Pat) -> String {
425 debug!("trying to get a name from pattern: {:?}", p);
428 PatKind::Wild => "_".to_string(),
429 PatKind::Binding(_, _, ident, _) => ident.to_string(),
430 PatKind::TupleStruct(ref p, ..) | PatKind::Path(ref p) => qpath_to_string(p),
431 PatKind::Struct(ref name, ref fields, etc) => {
432 format!("{} {{ {}{} }}", qpath_to_string(name),
433 fields.iter().map(|fp| format!("{}: {}", fp.ident, name_from_pat(&fp.pat)))
434 .collect::<Vec<String>>().join(", "),
435 if etc { ", .." } else { "" }
438 PatKind::Or(ref pats) => {
439 pats.iter().map(|p| name_from_pat(&**p)).collect::<Vec<String>>().join(" | ")
441 PatKind::Tuple(ref elts, _) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
442 .collect::<Vec<String>>().join(", ")),
443 PatKind::Box(ref p) => name_from_pat(&**p),
444 PatKind::Ref(ref p, _) => name_from_pat(&**p),
445 PatKind::Lit(..) => {
446 warn!("tried to get argument name from PatKind::Lit, \
447 which is silly in function arguments");
450 PatKind::Range(..) => panic!("tried to get argument name from PatKind::Range, \
451 which is not allowed in function arguments"),
452 PatKind::Slice(ref begin, ref mid, ref end) => {
453 let begin = begin.iter().map(|p| name_from_pat(&**p));
454 let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
455 let end = end.iter().map(|p| name_from_pat(&**p));
456 format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
461 pub fn print_const(cx: &DocContext<'_>, n: &ty::Const<'_>) -> String {
463 ty::ConstKind::Unevaluated(def_id, _) => {
464 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(def_id) {
465 print_const_expr(cx, cx.tcx.hir().body_owned_by(hir_id))
467 inline::print_inlined_const(cx, def_id)
471 let mut s = n.to_string();
472 // array lengths are obviously usize
473 if s.ends_with("usize") {
474 let n = s.len() - "usize".len();
476 if s.ends_with(": ") {
477 let n = s.len() - ": ".len();
486 pub fn print_const_expr(cx: &DocContext<'_>, body: hir::BodyId) -> String {
487 cx.tcx.hir().hir_to_pretty_string(body.hir_id)
490 /// Given a type Path, resolve it to a Type using the TyCtxt
491 pub fn resolve_type(cx: &DocContext<'_>,
493 id: hir::HirId) -> Type {
494 if id == hir::DUMMY_HIR_ID {
495 debug!("resolve_type({:?})", path);
497 debug!("resolve_type({:?},{:?})", path, id);
500 let is_generic = match path.res {
501 Res::PrimTy(p) => match p {
502 hir::Str => return Primitive(PrimitiveType::Str),
503 hir::Bool => return Primitive(PrimitiveType::Bool),
504 hir::Char => return Primitive(PrimitiveType::Char),
505 hir::Int(int_ty) => return Primitive(int_ty.into()),
506 hir::Uint(uint_ty) => return Primitive(uint_ty.into()),
507 hir::Float(float_ty) => return Primitive(float_ty.into()),
509 Res::SelfTy(..) if path.segments.len() == 1 => {
510 return Generic(kw::SelfUpper.to_string());
512 Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => {
513 return Generic(format!("{:#}", path.print()));
516 | Res::Def(DefKind::TyParam, _)
517 | Res::Def(DefKind::AssocTy, _) => true,
520 let did = register_res(&*cx, path.res);
521 ResolvedPath { path, param_names: None, did, is_generic }
524 pub fn get_auto_trait_and_blanket_impls(
525 cx: &DocContext<'tcx>,
527 param_env_def_id: DefId,
528 ) -> impl Iterator<Item = Item> {
529 AutoTraitFinder::new(cx).get_auto_trait_impls(ty, param_env_def_id).into_iter()
530 .chain(BlanketImplFinder::new(cx).get_blanket_impls(ty, param_env_def_id))
533 pub fn register_res(cx: &DocContext<'_>, res: Res) -> DefId {
534 debug!("register_res({:?})", res);
536 let (did, kind) = match res {
537 Res::Def(DefKind::Fn, i) => (i, TypeKind::Function),
538 Res::Def(DefKind::TyAlias, i) => (i, TypeKind::Typedef),
539 Res::Def(DefKind::Enum, i) => (i, TypeKind::Enum),
540 Res::Def(DefKind::Trait, i) => (i, TypeKind::Trait),
541 Res::Def(DefKind::Struct, i) => (i, TypeKind::Struct),
542 Res::Def(DefKind::Union, i) => (i, TypeKind::Union),
543 Res::Def(DefKind::Mod, i) => (i, TypeKind::Module),
544 Res::Def(DefKind::ForeignTy, i) => (i, TypeKind::Foreign),
545 Res::Def(DefKind::Const, i) => (i, TypeKind::Const),
546 Res::Def(DefKind::Static, i) => (i, TypeKind::Static),
547 Res::Def(DefKind::Variant, i) => (cx.tcx.parent(i).expect("cannot get parent def id"),
549 Res::Def(DefKind::Macro(mac_kind), i) => match mac_kind {
550 MacroKind::Bang => (i, TypeKind::Macro),
551 MacroKind::Attr => (i, TypeKind::Attr),
552 MacroKind::Derive => (i, TypeKind::Derive),
554 Res::Def(DefKind::TraitAlias, i) => (i, TypeKind::TraitAlias),
555 Res::SelfTy(Some(def_id), _) => (def_id, TypeKind::Trait),
556 Res::SelfTy(_, Some(impl_def_id)) => return impl_def_id,
557 _ => return res.def_id()
559 if did.is_local() { return did }
560 inline::record_extern_fqn(cx, did, kind);
561 if let TypeKind::Trait = kind {
562 inline::record_extern_trait(cx, did);
567 pub fn resolve_use_source(cx: &DocContext<'_>, path: Path) -> ImportSource {
569 did: if path.res.opt_def_id().is_none() {
572 Some(register_res(cx, path.res))
578 pub fn enter_impl_trait<F, R>(cx: &DocContext<'_>, f: F) -> R
582 let old_bounds = mem::take(&mut *cx.impl_trait_bounds.borrow_mut());
584 assert!(cx.impl_trait_bounds.borrow().is_empty());
585 *cx.impl_trait_bounds.borrow_mut() = old_bounds;