]>
Commit | Line | Data |
---|---|---|
dfeec247 XL |
1 | use crate::clean::auto_trait::AutoTraitFinder; |
2 | use crate::clean::blanket_impl::BlanketImplFinder; | |
60c5eb7d | 3 | use crate::clean::{ |
6a06907d XL |
4 | inline, Clean, Crate, ExternalCrate, Generic, GenericArg, GenericArgs, ImportSource, Item, |
5 | ItemKind, Lifetime, MacroKind, Path, PathSegment, Primitive, PrimitiveType, ResolvedPath, Type, | |
6 | TypeBinding, TypeKind, | |
60c5eb7d | 7 | }; |
dfeec247 | 8 | use crate::core::DocContext; |
60c5eb7d | 9 | |
dfeec247 XL |
10 | use rustc_hir as hir; |
11 | use rustc_hir::def::{DefKind, Res}; | |
12 | use rustc_hir::def_id::{DefId, LOCAL_CRATE}; | |
29967ef6 | 13 | use rustc_middle::mir::interpret::ConstValue; |
ba9703b0 | 14 | use rustc_middle::ty::subst::{GenericArgKind, SubstsRef}; |
6a06907d | 15 | use rustc_middle::ty::{self, DefIdTree, TyCtxt}; |
dfeec247 | 16 | use rustc_span::symbol::{kw, sym, Symbol}; |
60c5eb7d XL |
17 | use std::mem; |
18 | ||
6a06907d | 19 | crate fn krate(cx: &mut DocContext<'_>) -> Crate { |
60c5eb7d XL |
20 | use crate::visit_lib::LibEmbargoVisitor; |
21 | ||
22 | let krate = cx.tcx.hir().krate(); | |
6a06907d | 23 | let module = crate::visit_ast::RustdocVisitor::new(cx).visit(krate); |
60c5eb7d | 24 | |
6a06907d XL |
25 | cx.cache.deref_trait_did = cx.tcx.lang_items().deref_trait(); |
26 | cx.cache.deref_mut_trait_did = cx.tcx.lang_items().deref_mut_trait(); | |
27 | cx.cache.owned_box_did = cx.tcx.lang_items().owned_box(); | |
60c5eb7d XL |
28 | |
29 | let mut externs = Vec::new(); | |
30 | for &cnum in cx.tcx.crates().iter() { | |
31 | externs.push((cnum, cnum.clean(cx))); | |
32 | // Analyze doc-reachability for extern items | |
6a06907d | 33 | LibEmbargoVisitor::new(cx).visit_lib(cnum); |
60c5eb7d XL |
34 | } |
35 | externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b)); | |
36 | ||
74b04a01 | 37 | // Clean the crate, translating the entire librustc_ast AST to one that is |
60c5eb7d XL |
38 | // understood by rustdoc. |
39 | let mut module = module.clean(cx); | |
60c5eb7d | 40 | |
5869c6ff | 41 | match *module.kind { |
fc512014 | 42 | ItemKind::ModuleItem(ref module) => { |
60c5eb7d XL |
43 | for it in &module.items { |
44 | // `compiler_builtins` should be masked too, but we can't apply | |
45 | // `#[doc(masked)]` to the injected `extern crate` because it's unstable. | |
46 | if it.is_extern_crate() | |
47 | && (it.attrs.has_doc_flag(sym::masked) | |
48 | || cx.tcx.is_compiler_builtins(it.def_id.krate)) | |
49 | { | |
6a06907d | 50 | cx.cache.masked_crates.insert(it.def_id.krate); |
60c5eb7d XL |
51 | } |
52 | } | |
53 | } | |
54 | _ => unreachable!(), | |
55 | } | |
56 | ||
57 | let ExternalCrate { name, src, primitives, keywords, .. } = LOCAL_CRATE.clean(cx); | |
58 | { | |
5869c6ff | 59 | let m = match *module.kind { |
fc512014 | 60 | ItemKind::ModuleItem(ref mut m) => m, |
60c5eb7d XL |
61 | _ => unreachable!(), |
62 | }; | |
fc512014 XL |
63 | m.items.extend(primitives.iter().map(|&(def_id, prim)| { |
64 | Item::from_def_id_and_parts( | |
65 | def_id, | |
66 | Some(prim.as_sym()), | |
67 | ItemKind::PrimitiveItem(prim), | |
68 | cx, | |
69 | ) | |
60c5eb7d | 70 | })); |
fc512014 | 71 | m.items.extend(keywords.into_iter().map(|(def_id, kw)| { |
5869c6ff | 72 | Item::from_def_id_and_parts(def_id, Some(kw), ItemKind::KeywordItem(kw), cx) |
60c5eb7d XL |
73 | })); |
74 | } | |
75 | ||
76 | Crate { | |
77 | name, | |
60c5eb7d XL |
78 | src, |
79 | module: Some(module), | |
80 | externs, | |
81 | primitives, | |
82 | external_traits: cx.external_traits.clone(), | |
60c5eb7d XL |
83 | collapsed: false, |
84 | } | |
85 | } | |
86 | ||
29967ef6 | 87 | fn external_generic_args( |
6a06907d | 88 | cx: &mut DocContext<'_>, |
60c5eb7d XL |
89 | trait_did: Option<DefId>, |
90 | has_self: bool, | |
91 | bindings: Vec<TypeBinding>, | |
92 | substs: SubstsRef<'_>, | |
93 | ) -> GenericArgs { | |
94 | let mut skip_self = has_self; | |
95 | let mut ty_kind = None; | |
dfeec247 XL |
96 | let args: Vec<_> = substs |
97 | .iter() | |
98 | .filter_map(|kind| match kind.unpack() { | |
3dfed10e | 99 | GenericArgKind::Lifetime(lt) => match lt { |
fc512014 XL |
100 | ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrAnon(_) }) => { |
101 | Some(GenericArg::Lifetime(Lifetime::elided())) | |
102 | } | |
3dfed10e XL |
103 | _ => lt.clean(cx).map(GenericArg::Lifetime), |
104 | }, | |
dfeec247 XL |
105 | GenericArgKind::Type(_) if skip_self => { |
106 | skip_self = false; | |
107 | None | |
108 | } | |
109 | GenericArgKind::Type(ty) => { | |
1b1a35ee | 110 | ty_kind = Some(ty.kind()); |
dfeec247 XL |
111 | Some(GenericArg::Type(ty.clean(cx))) |
112 | } | |
113 | GenericArgKind::Const(ct) => Some(GenericArg::Const(ct.clean(cx))), | |
114 | }) | |
115 | .collect(); | |
60c5eb7d XL |
116 | |
117 | match trait_did { | |
118 | // Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C | |
74b04a01 | 119 | Some(did) if cx.tcx.fn_trait_kind_from_lang_item(did).is_some() => { |
60c5eb7d XL |
120 | assert!(ty_kind.is_some()); |
121 | let inputs = match ty_kind { | |
122 | Some(ty::Tuple(ref tys)) => tys.iter().map(|t| t.expect_ty().clean(cx)).collect(), | |
123 | _ => return GenericArgs::AngleBracketed { args, bindings }, | |
124 | }; | |
125 | let output = None; | |
126 | // FIXME(#20299) return type comes from a projection now | |
127 | // match types[1].kind { | |
128 | // ty::Tuple(ref v) if v.is_empty() => None, // -> () | |
129 | // _ => Some(types[1].clean(cx)) | |
130 | // }; | |
131 | GenericArgs::Parenthesized { inputs, output } | |
60c5eb7d | 132 | } |
dfeec247 | 133 | _ => GenericArgs::AngleBracketed { args, bindings }, |
60c5eb7d XL |
134 | } |
135 | } | |
136 | ||
137 | // trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar | |
138 | // from Fn<(A, B,), C> to Fn(A, B) -> C | |
29967ef6 | 139 | pub(super) fn external_path( |
6a06907d | 140 | cx: &mut DocContext<'_>, |
dfeec247 XL |
141 | name: Symbol, |
142 | trait_did: Option<DefId>, | |
143 | has_self: bool, | |
144 | bindings: Vec<TypeBinding>, | |
145 | substs: SubstsRef<'_>, | |
146 | ) -> Path { | |
60c5eb7d XL |
147 | Path { |
148 | global: false, | |
149 | res: Res::Err, | |
150 | segments: vec![PathSegment { | |
fc512014 | 151 | name, |
dfeec247 | 152 | args: external_generic_args(cx, trait_did, has_self, bindings, substs), |
60c5eb7d XL |
153 | }], |
154 | } | |
155 | } | |
156 | ||
fc512014 | 157 | crate fn strip_type(ty: Type) -> Type { |
60c5eb7d XL |
158 | match ty { |
159 | Type::ResolvedPath { path, param_names, did, is_generic } => { | |
160 | Type::ResolvedPath { path: strip_path(&path), param_names, did, is_generic } | |
161 | } | |
162 | Type::Tuple(inner_tys) => { | |
163 | Type::Tuple(inner_tys.iter().map(|t| strip_type(t.clone())).collect()) | |
164 | } | |
165 | Type::Slice(inner_ty) => Type::Slice(Box::new(strip_type(*inner_ty))), | |
166 | Type::Array(inner_ty, s) => Type::Array(Box::new(strip_type(*inner_ty)), s), | |
167 | Type::RawPointer(m, inner_ty) => Type::RawPointer(m, Box::new(strip_type(*inner_ty))), | |
168 | Type::BorrowedRef { lifetime, mutability, type_ } => { | |
169 | Type::BorrowedRef { lifetime, mutability, type_: Box::new(strip_type(*type_)) } | |
170 | } | |
dfeec247 XL |
171 | Type::QPath { name, self_type, trait_ } => Type::QPath { |
172 | name, | |
173 | self_type: Box::new(strip_type(*self_type)), | |
174 | trait_: Box::new(strip_type(*trait_)), | |
175 | }, | |
176 | _ => ty, | |
60c5eb7d XL |
177 | } |
178 | } | |
179 | ||
fc512014 | 180 | crate fn strip_path(path: &Path) -> Path { |
dfeec247 XL |
181 | let segments = path |
182 | .segments | |
183 | .iter() | |
184 | .map(|s| PathSegment { | |
5869c6ff | 185 | name: s.name, |
dfeec247 XL |
186 | args: GenericArgs::AngleBracketed { args: vec![], bindings: vec![] }, |
187 | }) | |
188 | .collect(); | |
60c5eb7d | 189 | |
dfeec247 | 190 | Path { global: path.global, res: path.res, segments } |
60c5eb7d XL |
191 | } |
192 | ||
fc512014 | 193 | crate fn qpath_to_string(p: &hir::QPath<'_>) -> String { |
60c5eb7d XL |
194 | let segments = match *p { |
195 | hir::QPath::Resolved(_, ref path) => &path.segments, | |
196 | hir::QPath::TypeRelative(_, ref segment) => return segment.ident.to_string(), | |
3dfed10e | 197 | hir::QPath::LangItem(lang_item, ..) => return lang_item.name().to_string(), |
60c5eb7d XL |
198 | }; |
199 | ||
200 | let mut s = String::new(); | |
201 | for (i, seg) in segments.iter().enumerate() { | |
202 | if i > 0 { | |
203 | s.push_str("::"); | |
204 | } | |
205 | if seg.ident.name != kw::PathRoot { | |
206 | s.push_str(&seg.ident.as_str()); | |
207 | } | |
208 | } | |
209 | s | |
210 | } | |
211 | ||
6a06907d | 212 | crate fn build_deref_target_impls(cx: &mut DocContext<'_>, items: &[Item], ret: &mut Vec<Item>) { |
60c5eb7d XL |
213 | let tcx = cx.tcx; |
214 | ||
215 | for item in items { | |
5869c6ff | 216 | let target = match *item.kind { |
fc512014 | 217 | ItemKind::TypedefItem(ref t, true) => &t.type_, |
60c5eb7d XL |
218 | _ => continue, |
219 | }; | |
5869c6ff XL |
220 | |
221 | if let Some(prim) = target.primitive_type() { | |
222 | for &did in prim.impls(tcx).iter().filter(|did| !did.is_local()) { | |
223 | inline::build_impl(cx, None, did, None, ret); | |
60c5eb7d | 224 | } |
5869c6ff | 225 | } else if let ResolvedPath { did, .. } = *target { |
60c5eb7d | 226 | if !did.is_local() { |
5869c6ff | 227 | inline::build_impls(cx, None, did, None, ret); |
60c5eb7d XL |
228 | } |
229 | } | |
230 | } | |
231 | } | |
232 | ||
fc512014 | 233 | crate trait ToSource { |
60c5eb7d XL |
234 | fn to_src(&self, cx: &DocContext<'_>) -> String; |
235 | } | |
236 | ||
dfeec247 | 237 | impl ToSource for rustc_span::Span { |
60c5eb7d | 238 | fn to_src(&self, cx: &DocContext<'_>) -> String { |
6a06907d | 239 | debug!("converting span {:?} to snippet", self); |
60c5eb7d XL |
240 | let sn = match cx.sess().source_map().span_to_snippet(*self) { |
241 | Ok(x) => x, | |
dfeec247 | 242 | Err(_) => String::new(), |
60c5eb7d XL |
243 | }; |
244 | debug!("got snippet {}", sn); | |
245 | sn | |
246 | } | |
247 | } | |
248 | ||
fc512014 | 249 | crate fn name_from_pat(p: &hir::Pat<'_>) -> Symbol { |
dfeec247 | 250 | use rustc_hir::*; |
60c5eb7d XL |
251 | debug!("trying to get a name from pattern: {:?}", p); |
252 | ||
fc512014 XL |
253 | Symbol::intern(&match p.kind { |
254 | PatKind::Wild => return kw::Underscore, | |
255 | PatKind::Binding(_, _, ident, _) => return ident.name, | |
60c5eb7d | 256 | PatKind::TupleStruct(ref p, ..) | PatKind::Path(ref p) => qpath_to_string(p), |
dfeec247 XL |
257 | PatKind::Struct(ref name, ref fields, etc) => format!( |
258 | "{} {{ {}{} }}", | |
259 | qpath_to_string(name), | |
260 | fields | |
261 | .iter() | |
262 | .map(|fp| format!("{}: {}", fp.ident, name_from_pat(&fp.pat))) | |
263 | .collect::<Vec<String>>() | |
264 | .join(", "), | |
265 | if etc { ", .." } else { "" } | |
266 | ), | |
fc512014 XL |
267 | PatKind::Or(ref pats) => pats |
268 | .iter() | |
269 | .map(|p| name_from_pat(&**p).to_string()) | |
270 | .collect::<Vec<String>>() | |
271 | .join(" | "), | |
dfeec247 XL |
272 | PatKind::Tuple(ref elts, _) => format!( |
273 | "({})", | |
fc512014 XL |
274 | elts.iter() |
275 | .map(|p| name_from_pat(&**p).to_string()) | |
276 | .collect::<Vec<String>>() | |
277 | .join(", ") | |
dfeec247 | 278 | ), |
fc512014 XL |
279 | PatKind::Box(ref p) => return name_from_pat(&**p), |
280 | PatKind::Ref(ref p, _) => return name_from_pat(&**p), | |
60c5eb7d | 281 | PatKind::Lit(..) => { |
dfeec247 | 282 | warn!( |
1b1a35ee | 283 | "tried to get argument name from PatKind::Lit, which is silly in function arguments" |
dfeec247 | 284 | ); |
fc512014 | 285 | return Symbol::intern("()"); |
dfeec247 | 286 | } |
5869c6ff | 287 | PatKind::Range(..) => return kw::Underscore, |
60c5eb7d | 288 | PatKind::Slice(ref begin, ref mid, ref end) => { |
fc512014 | 289 | let begin = begin.iter().map(|p| name_from_pat(&**p).to_string()); |
60c5eb7d | 290 | let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter(); |
fc512014 | 291 | let end = end.iter().map(|p| name_from_pat(&**p).to_string()); |
60c5eb7d | 292 | format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", ")) |
dfeec247 | 293 | } |
fc512014 | 294 | }) |
60c5eb7d XL |
295 | } |
296 | ||
fc512014 | 297 | crate fn print_const(cx: &DocContext<'_>, n: &'tcx ty::Const<'_>) -> String { |
60c5eb7d | 298 | match n.val { |
3dfed10e XL |
299 | ty::ConstKind::Unevaluated(def, _, promoted) => { |
300 | let mut s = if let Some(def) = def.as_local() { | |
301 | let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def.did); | |
6a06907d | 302 | print_const_expr(cx.tcx, cx.tcx.hir().body_owned_by(hir_id)) |
60c5eb7d | 303 | } else { |
3dfed10e | 304 | inline::print_inlined_const(cx, def.did) |
dfeec247 XL |
305 | }; |
306 | if let Some(promoted) = promoted { | |
307 | s.push_str(&format!("::{:?}", promoted)) | |
60c5eb7d | 308 | } |
dfeec247 XL |
309 | s |
310 | } | |
60c5eb7d XL |
311 | _ => { |
312 | let mut s = n.to_string(); | |
313 | // array lengths are obviously usize | |
f035d41b XL |
314 | if s.ends_with("_usize") { |
315 | let n = s.len() - "_usize".len(); | |
60c5eb7d XL |
316 | s.truncate(n); |
317 | if s.ends_with(": ") { | |
318 | let n = s.len() - ": ".len(); | |
319 | s.truncate(n); | |
320 | } | |
321 | } | |
322 | s | |
dfeec247 XL |
323 | } |
324 | } | |
325 | } | |
326 | ||
fc512014 | 327 | crate fn print_evaluated_const(cx: &DocContext<'_>, def_id: DefId) -> Option<String> { |
ba9703b0 | 328 | cx.tcx.const_eval_poly(def_id).ok().and_then(|val| { |
74b04a01 | 329 | let ty = cx.tcx.type_of(def_id); |
1b1a35ee | 330 | match (val, ty.kind()) { |
74b04a01 XL |
331 | (_, &ty::Ref(..)) => None, |
332 | (ConstValue::Scalar(_), &ty::Adt(_, _)) => None, | |
333 | (ConstValue::Scalar(_), _) => { | |
334 | let const_ = ty::Const::from_value(cx.tcx, val, ty); | |
335 | Some(print_const_with_custom_print_scalar(cx, const_)) | |
dfeec247 XL |
336 | } |
337 | _ => None, | |
74b04a01 | 338 | } |
ba9703b0 | 339 | }) |
dfeec247 XL |
340 | } |
341 | ||
342 | fn format_integer_with_underscore_sep(num: &str) -> String { | |
343 | let num_chars: Vec<_> = num.chars().collect(); | |
344 | let num_start_index = if num_chars.get(0) == Some(&'-') { 1 } else { 0 }; | |
345 | ||
346 | num_chars[..num_start_index] | |
347 | .iter() | |
348 | .chain(num_chars[num_start_index..].rchunks(3).rev().intersperse(&['_']).flatten()) | |
349 | .collect() | |
350 | } | |
351 | ||
352 | fn print_const_with_custom_print_scalar(cx: &DocContext<'_>, ct: &'tcx ty::Const<'tcx>) -> String { | |
353 | // Use a slightly different format for integer types which always shows the actual value. | |
354 | // For all other types, fallback to the original `pretty_print_const`. | |
1b1a35ee | 355 | match (ct.val, ct.ty.kind()) { |
29967ef6 XL |
356 | (ty::ConstKind::Value(ConstValue::Scalar(int)), ty::Uint(ui)) => { |
357 | format!("{}{}", format_integer_with_underscore_sep(&int.to_string()), ui.name_str()) | |
dfeec247 | 358 | } |
29967ef6 XL |
359 | (ty::ConstKind::Value(ConstValue::Scalar(int)), ty::Int(i)) => { |
360 | let ty = cx.tcx.lift(ct.ty).unwrap(); | |
dfeec247 | 361 | let size = cx.tcx.layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size; |
29967ef6 XL |
362 | let data = int.assert_bits(size); |
363 | let sign_extended_data = size.sign_extend(data) as i128; | |
dfeec247 XL |
364 | |
365 | format!( | |
366 | "{}{}", | |
367 | format_integer_with_underscore_sep(&sign_extended_data.to_string()), | |
368 | i.name_str() | |
369 | ) | |
370 | } | |
371 | _ => ct.to_string(), | |
372 | } | |
373 | } | |
374 | ||
fc512014 | 375 | crate fn is_literal_expr(cx: &DocContext<'_>, hir_id: hir::HirId) -> bool { |
dfeec247 XL |
376 | if let hir::Node::Expr(expr) = cx.tcx.hir().get(hir_id) { |
377 | if let hir::ExprKind::Lit(_) = &expr.kind { | |
378 | return true; | |
379 | } | |
380 | ||
6a06907d | 381 | if let hir::ExprKind::Unary(hir::UnOp::Neg, expr) = &expr.kind { |
dfeec247 XL |
382 | if let hir::ExprKind::Lit(_) = &expr.kind { |
383 | return true; | |
384 | } | |
385 | } | |
60c5eb7d | 386 | } |
dfeec247 XL |
387 | |
388 | false | |
60c5eb7d XL |
389 | } |
390 | ||
6a06907d XL |
391 | crate fn print_const_expr(tcx: TyCtxt<'_>, body: hir::BodyId) -> String { |
392 | let hir = tcx.hir(); | |
393 | let value = &hir.body(body).value; | |
dfeec247 XL |
394 | |
395 | let snippet = if !value.span.from_expansion() { | |
6a06907d | 396 | tcx.sess.source_map().span_to_snippet(value.span).ok() |
dfeec247 XL |
397 | } else { |
398 | None | |
399 | }; | |
400 | ||
6a06907d | 401 | snippet.unwrap_or_else(|| rustc_hir_pretty::id_to_string(&hir, body.hir_id)) |
60c5eb7d XL |
402 | } |
403 | ||
404 | /// Given a type Path, resolve it to a Type using the TyCtxt | |
6a06907d | 405 | crate fn resolve_type(cx: &mut DocContext<'_>, path: Path, id: hir::HirId) -> Type { |
ba9703b0 | 406 | debug!("resolve_type({:?},{:?})", path, id); |
60c5eb7d XL |
407 | |
408 | let is_generic = match path.res { | |
74b04a01 | 409 | Res::PrimTy(p) => return Primitive(PrimitiveType::from(p)), |
60c5eb7d | 410 | Res::SelfTy(..) if path.segments.len() == 1 => { |
fc512014 | 411 | return Generic(kw::SelfUpper); |
60c5eb7d XL |
412 | } |
413 | Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => { | |
5869c6ff | 414 | return Generic(Symbol::intern(&format!("{:#}", path.print(&cx.cache)))); |
60c5eb7d | 415 | } |
ba9703b0 | 416 | Res::SelfTy(..) | Res::Def(DefKind::TyParam | DefKind::AssocTy, _) => true, |
60c5eb7d XL |
417 | _ => false, |
418 | }; | |
6a06907d | 419 | let did = register_res(cx, path.res); |
60c5eb7d XL |
420 | ResolvedPath { path, param_names: None, did, is_generic } |
421 | } | |
422 | ||
fc512014 | 423 | crate fn get_auto_trait_and_blanket_impls( |
6a06907d XL |
424 | cx: &mut DocContext<'tcx>, |
425 | item_def_id: DefId, | |
60c5eb7d | 426 | ) -> impl Iterator<Item = Item> { |
5869c6ff XL |
427 | let auto_impls = cx |
428 | .sess() | |
429 | .prof | |
430 | .generic_activity("get_auto_trait_impls") | |
6a06907d | 431 | .run(|| AutoTraitFinder::new(cx).get_auto_trait_impls(item_def_id)); |
5869c6ff XL |
432 | let blanket_impls = cx |
433 | .sess() | |
434 | .prof | |
435 | .generic_activity("get_blanket_impls") | |
6a06907d | 436 | .run(|| BlanketImplFinder { cx }.get_blanket_impls(item_def_id)); |
fc512014 | 437 | auto_impls.into_iter().chain(blanket_impls) |
60c5eb7d XL |
438 | } |
439 | ||
6a06907d | 440 | crate fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId { |
60c5eb7d XL |
441 | debug!("register_res({:?})", res); |
442 | ||
443 | let (did, kind) = match res { | |
444 | Res::Def(DefKind::Fn, i) => (i, TypeKind::Function), | |
445 | Res::Def(DefKind::TyAlias, i) => (i, TypeKind::Typedef), | |
446 | Res::Def(DefKind::Enum, i) => (i, TypeKind::Enum), | |
447 | Res::Def(DefKind::Trait, i) => (i, TypeKind::Trait), | |
3dfed10e XL |
448 | Res::Def(DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst, i) => { |
449 | (cx.tcx.parent(i).unwrap(), TypeKind::Trait) | |
450 | } | |
60c5eb7d XL |
451 | Res::Def(DefKind::Struct, i) => (i, TypeKind::Struct), |
452 | Res::Def(DefKind::Union, i) => (i, TypeKind::Union), | |
453 | Res::Def(DefKind::Mod, i) => (i, TypeKind::Module), | |
454 | Res::Def(DefKind::ForeignTy, i) => (i, TypeKind::Foreign), | |
455 | Res::Def(DefKind::Const, i) => (i, TypeKind::Const), | |
456 | Res::Def(DefKind::Static, i) => (i, TypeKind::Static), | |
dfeec247 XL |
457 | Res::Def(DefKind::Variant, i) => { |
458 | (cx.tcx.parent(i).expect("cannot get parent def id"), TypeKind::Enum) | |
459 | } | |
60c5eb7d XL |
460 | Res::Def(DefKind::Macro(mac_kind), i) => match mac_kind { |
461 | MacroKind::Bang => (i, TypeKind::Macro), | |
462 | MacroKind::Attr => (i, TypeKind::Attr), | |
463 | MacroKind::Derive => (i, TypeKind::Derive), | |
464 | }, | |
465 | Res::Def(DefKind::TraitAlias, i) => (i, TypeKind::TraitAlias), | |
466 | Res::SelfTy(Some(def_id), _) => (def_id, TypeKind::Trait), | |
1b1a35ee | 467 | Res::SelfTy(_, Some((impl_def_id, _))) => return impl_def_id, |
dfeec247 | 468 | _ => return res.def_id(), |
60c5eb7d | 469 | }; |
dfeec247 XL |
470 | if did.is_local() { |
471 | return did; | |
472 | } | |
60c5eb7d XL |
473 | inline::record_extern_fqn(cx, did, kind); |
474 | if let TypeKind::Trait = kind { | |
475 | inline::record_extern_trait(cx, did); | |
476 | } | |
477 | did | |
478 | } | |
479 | ||
6a06907d | 480 | crate fn resolve_use_source(cx: &mut DocContext<'_>, path: Path) -> ImportSource { |
60c5eb7d | 481 | ImportSource { |
dfeec247 | 482 | did: if path.res.opt_def_id().is_none() { None } else { Some(register_res(cx, path.res)) }, |
60c5eb7d XL |
483 | path, |
484 | } | |
485 | } | |
486 | ||
6a06907d | 487 | crate fn enter_impl_trait<F, R>(cx: &mut DocContext<'_>, f: F) -> R |
60c5eb7d | 488 | where |
6a06907d | 489 | F: FnOnce(&mut DocContext<'_>) -> R, |
60c5eb7d | 490 | { |
6a06907d XL |
491 | let old_bounds = mem::take(&mut cx.impl_trait_bounds); |
492 | let r = f(cx); | |
493 | assert!(cx.impl_trait_bounds.is_empty()); | |
494 | cx.impl_trait_bounds = old_bounds; | |
60c5eb7d XL |
495 | r |
496 | } | |
fc512014 XL |
497 | |
498 | /// Find the nearest parent module of a [`DefId`]. | |
499 | /// | |
500 | /// **Panics if the item it belongs to [is fake][Item::is_fake].** | |
501 | crate fn find_nearest_parent_module(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> { | |
502 | if def_id.is_top_level_module() { | |
503 | // The crate root has no parent. Use it as the root instead. | |
504 | Some(def_id) | |
505 | } else { | |
506 | let mut current = def_id; | |
507 | // The immediate parent might not always be a module. | |
508 | // Find the first parent which is. | |
509 | while let Some(parent) = tcx.parent(current) { | |
510 | if tcx.def_kind(parent) == DefKind::Mod { | |
511 | return Some(parent); | |
512 | } | |
513 | current = parent; | |
514 | } | |
515 | None | |
516 | } | |
517 | } | |
6a06907d XL |
518 | |
519 | /// Checks for the existence of `hidden` in the attribute below if `flag` is `sym::hidden`: | |
520 | /// | |
521 | /// ``` | |
522 | /// #[doc(hidden)] | |
523 | /// pub fn foo() {} | |
524 | /// ``` | |
525 | /// | |
526 | /// This function exists because it runs on `hir::Attributes` whereas the other is a | |
527 | /// `clean::Attributes` method. | |
528 | crate fn has_doc_flag(attrs: ty::Attributes<'_>, flag: Symbol) -> bool { | |
529 | attrs.iter().any(|attr| { | |
530 | attr.has_name(sym::doc) | |
531 | && attr.meta_item_list().map_or(false, |l| rustc_attr::list_contains_name(&l, flag)) | |
532 | }) | |
533 | } |