]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/inline.rs
Add a test that rustc compiles and links separately
[rust.git] / src / librustdoc / clean / inline.rs
1 //! Support for inlining external documentation into the current AST.
2
3 use std::iter::once;
4
5 use rustc_ast as ast;
6 use rustc_data_structures::fx::FxHashSet;
7 use rustc_hir as hir;
8 use rustc_hir::def::{CtorKind, DefKind, Res};
9 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
10 use rustc_hir::Mutability;
11 use rustc_metadata::creader::LoadedMacro;
12 use rustc_middle::ty;
13 use rustc_mir::const_eval::is_min_const_fn;
14 use rustc_span::hygiene::MacroKind;
15 use rustc_span::symbol::{kw, sym, Symbol};
16 use rustc_span::Span;
17
18 use crate::clean::{self, Attributes, GetDefId, ToSource, TypeKind};
19 use crate::core::DocContext;
20 use crate::doctree;
21
22 use super::Clean;
23
24 type Attrs<'hir> = rustc_middle::ty::Attributes<'hir>;
25
26 /// Attempt to inline a definition into this AST.
27 ///
28 /// This function will fetch the definition specified, and if it is
29 /// from another crate it will attempt to inline the documentation
30 /// from the other crate into this crate.
31 ///
32 /// This is primarily used for `pub use` statements which are, in general,
33 /// implementation details. Inlining the documentation should help provide a
34 /// better experience when reading the documentation in this use case.
35 ///
36 /// The returned value is `None` if the definition could not be inlined,
37 /// and `Some` of a vector of items if it was successfully expanded.
38 ///
39 /// `parent_module` refers to the parent of the *re-export*, not the original item.
40 crate fn try_inline(
41     cx: &DocContext<'_>,
42     parent_module: DefId,
43     res: Res,
44     name: Symbol,
45     attrs: Option<Attrs<'_>>,
46     visited: &mut FxHashSet<DefId>,
47 ) -> Option<Vec<clean::Item>> {
48     let did = res.opt_def_id()?;
49     if did.is_local() {
50         return None;
51     }
52     let mut ret = Vec::new();
53
54     debug!("attrs={:?}", attrs);
55     let attrs_clone = attrs;
56
57     let kind = match res {
58         Res::Def(DefKind::Trait, did) => {
59             record_extern_fqn(cx, did, clean::TypeKind::Trait);
60             ret.extend(build_impls(cx, Some(parent_module), did, attrs));
61             clean::TraitItem(build_external_trait(cx, did))
62         }
63         Res::Def(DefKind::Fn, did) => {
64             record_extern_fqn(cx, did, clean::TypeKind::Function);
65             clean::FunctionItem(build_external_function(cx, did))
66         }
67         Res::Def(DefKind::Struct, did) => {
68             record_extern_fqn(cx, did, clean::TypeKind::Struct);
69             ret.extend(build_impls(cx, Some(parent_module), did, attrs));
70             clean::StructItem(build_struct(cx, did))
71         }
72         Res::Def(DefKind::Union, did) => {
73             record_extern_fqn(cx, did, clean::TypeKind::Union);
74             ret.extend(build_impls(cx, Some(parent_module), did, attrs));
75             clean::UnionItem(build_union(cx, did))
76         }
77         Res::Def(DefKind::TyAlias, did) => {
78             record_extern_fqn(cx, did, clean::TypeKind::Typedef);
79             ret.extend(build_impls(cx, Some(parent_module), did, attrs));
80             clean::TypedefItem(build_type_alias(cx, did), false)
81         }
82         Res::Def(DefKind::Enum, did) => {
83             record_extern_fqn(cx, did, clean::TypeKind::Enum);
84             ret.extend(build_impls(cx, Some(parent_module), did, attrs));
85             clean::EnumItem(build_enum(cx, did))
86         }
87         Res::Def(DefKind::ForeignTy, did) => {
88             record_extern_fqn(cx, did, clean::TypeKind::Foreign);
89             ret.extend(build_impls(cx, Some(parent_module), did, attrs));
90             clean::ForeignTypeItem
91         }
92         // Never inline enum variants but leave them shown as re-exports.
93         Res::Def(DefKind::Variant, _) => return None,
94         // Assume that enum variants and struct types are re-exported next to
95         // their constructors.
96         Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) => return Some(Vec::new()),
97         Res::Def(DefKind::Mod, did) => {
98             record_extern_fqn(cx, did, clean::TypeKind::Module);
99             clean::ModuleItem(build_module(cx, did, visited))
100         }
101         Res::Def(DefKind::Static, did) => {
102             record_extern_fqn(cx, did, clean::TypeKind::Static);
103             clean::StaticItem(build_static(cx, did, cx.tcx.is_mutable_static(did)))
104         }
105         Res::Def(DefKind::Const, did) => {
106             record_extern_fqn(cx, did, clean::TypeKind::Const);
107             clean::ConstantItem(build_const(cx, did))
108         }
109         Res::Def(DefKind::Macro(kind), did) => {
110             let mac = build_macro(cx, did, name);
111
112             let type_kind = match kind {
113                 MacroKind::Bang => TypeKind::Macro,
114                 MacroKind::Attr => TypeKind::Attr,
115                 MacroKind::Derive => TypeKind::Derive,
116             };
117             record_extern_fqn(cx, did, type_kind);
118             mac
119         }
120         _ => return None,
121     };
122
123     let target_attrs = load_attrs(cx, did);
124     let attrs = merge_attrs(cx, Some(parent_module), target_attrs, attrs_clone);
125
126     cx.renderinfo.borrow_mut().inlined.insert(did);
127     let what_rustc_thinks = clean::Item::from_def_id_and_parts(did, Some(name), kind, cx);
128     ret.push(clean::Item { attrs, ..what_rustc_thinks });
129     Some(ret)
130 }
131
132 crate fn try_inline_glob(
133     cx: &DocContext<'_>,
134     res: Res,
135     visited: &mut FxHashSet<DefId>,
136 ) -> Option<Vec<clean::Item>> {
137     if res == Res::Err {
138         return None;
139     }
140     let did = res.def_id();
141     if did.is_local() {
142         return None;
143     }
144
145     match res {
146         Res::Def(DefKind::Mod, did) => {
147             let m = build_module(cx, did, visited);
148             Some(m.items)
149         }
150         // glob imports on things like enums aren't inlined even for local exports, so just bail
151         _ => None,
152     }
153 }
154
155 crate fn load_attrs<'hir>(cx: &DocContext<'hir>, did: DefId) -> Attrs<'hir> {
156     cx.tcx.get_attrs(did)
157 }
158
159 /// Record an external fully qualified name in the external_paths cache.
160 ///
161 /// These names are used later on by HTML rendering to generate things like
162 /// source links back to the original item.
163 crate fn record_extern_fqn(cx: &DocContext<'_>, did: DefId, kind: clean::TypeKind) {
164     let crate_name = cx.tcx.crate_name(did.krate).to_string();
165
166     let relative = cx.tcx.def_path(did).data.into_iter().filter_map(|elem| {
167         // extern blocks have an empty name
168         let s = elem.data.to_string();
169         if !s.is_empty() { Some(s) } else { None }
170     });
171     let fqn = if let clean::TypeKind::Macro = kind {
172         vec![crate_name, relative.last().expect("relative was empty")]
173     } else {
174         once(crate_name).chain(relative).collect()
175     };
176
177     if did.is_local() {
178         cx.renderinfo.borrow_mut().exact_paths.insert(did, fqn);
179     } else {
180         cx.renderinfo.borrow_mut().external_paths.insert(did, (fqn, kind));
181     }
182 }
183
184 crate fn build_external_trait(cx: &DocContext<'_>, did: DefId) -> clean::Trait {
185     let trait_items =
186         cx.tcx.associated_items(did).in_definition_order().map(|item| item.clean(cx)).collect();
187
188     let predicates = cx.tcx.predicates_of(did);
189     let generics = (cx.tcx.generics_of(did), predicates).clean(cx);
190     let generics = filter_non_trait_generics(did, generics);
191     let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
192     let is_spotlight = load_attrs(cx, did).clean(cx).has_doc_flag(sym::spotlight);
193     let is_auto = cx.tcx.trait_is_auto(did);
194     clean::Trait {
195         unsafety: cx.tcx.trait_def(did).unsafety,
196         generics,
197         items: trait_items,
198         bounds: supertrait_bounds,
199         is_spotlight,
200         is_auto,
201     }
202 }
203
204 fn build_external_function(cx: &DocContext<'_>, did: DefId) -> clean::Function {
205     let sig = cx.tcx.fn_sig(did);
206
207     let constness =
208         if is_min_const_fn(cx.tcx, did) { hir::Constness::Const } else { hir::Constness::NotConst };
209     let asyncness = cx.tcx.asyncness(did);
210     let predicates = cx.tcx.predicates_of(did);
211     let (generics, decl) = clean::enter_impl_trait(cx, || {
212         ((cx.tcx.generics_of(did), predicates).clean(cx), (did, sig).clean(cx))
213     });
214     let (all_types, ret_types) = clean::get_all_types(&generics, &decl, cx);
215     clean::Function {
216         decl,
217         generics,
218         header: hir::FnHeader { unsafety: sig.unsafety(), abi: sig.abi(), constness, asyncness },
219         all_types,
220         ret_types,
221     }
222 }
223
224 fn build_enum(cx: &DocContext<'_>, did: DefId) -> clean::Enum {
225     let predicates = cx.tcx.explicit_predicates_of(did);
226
227     clean::Enum {
228         generics: (cx.tcx.generics_of(did), predicates).clean(cx),
229         variants_stripped: false,
230         variants: cx.tcx.adt_def(did).variants.clean(cx),
231     }
232 }
233
234 fn build_struct(cx: &DocContext<'_>, did: DefId) -> clean::Struct {
235     let predicates = cx.tcx.explicit_predicates_of(did);
236     let variant = cx.tcx.adt_def(did).non_enum_variant();
237
238     clean::Struct {
239         struct_type: match variant.ctor_kind {
240             CtorKind::Fictive => doctree::Plain,
241             CtorKind::Fn => doctree::Tuple,
242             CtorKind::Const => doctree::Unit,
243         },
244         generics: (cx.tcx.generics_of(did), predicates).clean(cx),
245         fields: variant.fields.clean(cx),
246         fields_stripped: false,
247     }
248 }
249
250 fn build_union(cx: &DocContext<'_>, did: DefId) -> clean::Union {
251     let predicates = cx.tcx.explicit_predicates_of(did);
252     let variant = cx.tcx.adt_def(did).non_enum_variant();
253
254     clean::Union {
255         struct_type: doctree::Plain,
256         generics: (cx.tcx.generics_of(did), predicates).clean(cx),
257         fields: variant.fields.clean(cx),
258         fields_stripped: false,
259     }
260 }
261
262 fn build_type_alias(cx: &DocContext<'_>, did: DefId) -> clean::Typedef {
263     let predicates = cx.tcx.explicit_predicates_of(did);
264
265     clean::Typedef {
266         type_: cx.tcx.type_of(did).clean(cx),
267         generics: (cx.tcx.generics_of(did), predicates).clean(cx),
268         item_type: build_type_alias_type(cx, did),
269     }
270 }
271
272 fn build_type_alias_type(cx: &DocContext<'_>, did: DefId) -> Option<clean::Type> {
273     let type_ = cx.tcx.type_of(did).clean(cx);
274     type_.def_id().and_then(|did| build_ty(cx, did))
275 }
276
277 crate fn build_ty(cx: &DocContext<'_>, did: DefId) -> Option<clean::Type> {
278     match cx.tcx.def_kind(did) {
279         DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::Const | DefKind::Static => {
280             Some(cx.tcx.type_of(did).clean(cx))
281         }
282         DefKind::TyAlias => build_type_alias_type(cx, did),
283         _ => None,
284     }
285 }
286
287 /// Builds all inherent implementations of an ADT (struct/union/enum) or Trait item/path/reexport.
288 crate fn build_impls(
289     cx: &DocContext<'_>,
290     parent_module: Option<DefId>,
291     did: DefId,
292     attrs: Option<Attrs<'_>>,
293 ) -> Vec<clean::Item> {
294     let tcx = cx.tcx;
295     let mut impls = Vec::new();
296
297     // for each implementation of an item represented by `did`, build the clean::Item for that impl
298     for &did in tcx.inherent_impls(did).iter() {
299         build_impl(cx, parent_module, did, attrs, &mut impls);
300     }
301
302     impls
303 }
304
305 /// `parent_module` refers to the parent of the re-export, not the original item
306 fn merge_attrs(
307     cx: &DocContext<'_>,
308     parent_module: Option<DefId>,
309     old_attrs: Attrs<'_>,
310     new_attrs: Option<Attrs<'_>>,
311 ) -> clean::Attributes {
312     // NOTE: If we have additional attributes (from a re-export),
313     // always insert them first. This ensure that re-export
314     // doc comments show up before the original doc comments
315     // when we render them.
316     if let Some(inner) = new_attrs {
317         if let Some(new_id) = parent_module {
318             let diag = cx.sess().diagnostic();
319             Attributes::from_ast(diag, old_attrs, Some((inner, new_id)))
320         } else {
321             let mut both = inner.to_vec();
322             both.extend_from_slice(old_attrs);
323             both.clean(cx)
324         }
325     } else {
326         old_attrs.clean(cx)
327     }
328 }
329
330 /// Builds a specific implementation of a type. The `did` could be a type method or trait method.
331 crate fn build_impl(
332     cx: &DocContext<'_>,
333     parent_module: impl Into<Option<DefId>>,
334     did: DefId,
335     attrs: Option<Attrs<'_>>,
336     ret: &mut Vec<clean::Item>,
337 ) {
338     if !cx.renderinfo.borrow_mut().inlined.insert(did) {
339         return;
340     }
341
342     let tcx = cx.tcx;
343     let associated_trait = tcx.impl_trait_ref(did);
344
345     // Only inline impl if the implemented trait is
346     // reachable in rustdoc generated documentation
347     if !did.is_local() {
348         if let Some(traitref) = associated_trait {
349             let did = traitref.def_id;
350             if !cx.renderinfo.borrow().access_levels.is_public(did) {
351                 return;
352             }
353
354             if let Some(stab) = tcx.lookup_stability(did) {
355                 if stab.level.is_unstable() && stab.feature == sym::rustc_private {
356                     return;
357                 }
358             }
359         }
360     }
361
362     let impl_item = match did.as_local() {
363         Some(did) => {
364             let hir_id = tcx.hir().local_def_id_to_hir_id(did);
365             match tcx.hir().expect_item(hir_id).kind {
366                 hir::ItemKind::Impl { self_ty, ref generics, ref items, .. } => {
367                     Some((self_ty, generics, items))
368                 }
369                 _ => panic!("`DefID` passed to `build_impl` is not an `impl"),
370             }
371         }
372         None => None,
373     };
374
375     let for_ = match impl_item {
376         Some((self_ty, _, _)) => self_ty.clean(cx),
377         None => tcx.type_of(did).clean(cx),
378     };
379
380     // Only inline impl if the implementing type is
381     // reachable in rustdoc generated documentation
382     if !did.is_local() {
383         if let Some(did) = for_.def_id() {
384             if !cx.renderinfo.borrow().access_levels.is_public(did) {
385                 return;
386             }
387
388             if let Some(stab) = tcx.lookup_stability(did) {
389                 if stab.level.is_unstable() && stab.feature == sym::rustc_private {
390                     return;
391                 }
392             }
393         }
394     }
395
396     let predicates = tcx.explicit_predicates_of(did);
397     let (trait_items, generics) = match impl_item {
398         Some((_, generics, items)) => (
399             items.iter().map(|item| tcx.hir().impl_item(item.id).clean(cx)).collect::<Vec<_>>(),
400             generics.clean(cx),
401         ),
402         None => (
403             tcx.associated_items(did)
404                 .in_definition_order()
405                 .filter_map(|item| {
406                     if associated_trait.is_some() || item.vis == ty::Visibility::Public {
407                         Some(item.clean(cx))
408                     } else {
409                         None
410                     }
411                 })
412                 .collect::<Vec<_>>(),
413             clean::enter_impl_trait(cx, || (tcx.generics_of(did), predicates).clean(cx)),
414         ),
415     };
416     let polarity = tcx.impl_polarity(did);
417     let trait_ = associated_trait.clean(cx).map(|bound| match bound {
418         clean::GenericBound::TraitBound(polyt, _) => polyt.trait_,
419         clean::GenericBound::Outlives(..) => unreachable!(),
420     });
421     if trait_.def_id() == tcx.lang_items().deref_trait() {
422         super::build_deref_target_impls(cx, &trait_items, ret);
423     }
424     if let Some(trait_did) = trait_.def_id() {
425         record_extern_trait(cx, trait_did);
426     }
427
428     let provided = trait_
429         .def_id()
430         .map(|did| tcx.provided_trait_methods(did).map(|meth| meth.ident.name).collect())
431         .unwrap_or_default();
432
433     debug!("build_impl: impl {:?} for {:?}", trait_.def_id(), for_.def_id());
434
435     let mut item = clean::Item::from_def_id_and_parts(
436         did,
437         None,
438         clean::ImplItem(clean::Impl {
439             unsafety: hir::Unsafety::Normal,
440             generics,
441             provided_trait_methods: provided,
442             trait_,
443             for_,
444             items: trait_items,
445             polarity: Some(polarity.clean(cx)),
446             synthetic: false,
447             blanket_impl: None,
448         }),
449         cx,
450     );
451     item.attrs = merge_attrs(cx, parent_module.into(), load_attrs(cx, did), attrs);
452     debug!("merged_attrs={:?}", item.attrs);
453     ret.push(item);
454 }
455
456 fn build_module(cx: &DocContext<'_>, did: DefId, visited: &mut FxHashSet<DefId>) -> clean::Module {
457     let mut items = Vec::new();
458     fill_in(cx, did, &mut items, visited);
459     return clean::Module { items, is_crate: false };
460
461     fn fill_in(
462         cx: &DocContext<'_>,
463         did: DefId,
464         items: &mut Vec<clean::Item>,
465         visited: &mut FxHashSet<DefId>,
466     ) {
467         // If we're re-exporting a re-export it may actually re-export something in
468         // two namespaces, so the target may be listed twice. Make sure we only
469         // visit each node at most once.
470         for &item in cx.tcx.item_children(did).iter() {
471             if item.vis == ty::Visibility::Public {
472                 if let Some(def_id) = item.res.mod_def_id() {
473                     if did == def_id || !visited.insert(def_id) {
474                         continue;
475                     }
476                 }
477                 if let Res::PrimTy(p) = item.res {
478                     // Primitive types can't be inlined so generate an import instead.
479                     items.push(clean::Item {
480                         name: None,
481                         attrs: clean::Attributes::default(),
482                         source: clean::Span::dummy(),
483                         def_id: DefId::local(CRATE_DEF_INDEX),
484                         visibility: clean::Public,
485                         stability: None,
486                         const_stability: None,
487                         deprecation: None,
488                         kind: clean::ImportItem(clean::Import::new_simple(
489                             item.ident.name,
490                             clean::ImportSource {
491                                 path: clean::Path {
492                                     global: false,
493                                     res: item.res,
494                                     segments: vec![clean::PathSegment {
495                                         name: clean::PrimitiveType::from(p).as_sym(),
496                                         args: clean::GenericArgs::AngleBracketed {
497                                             args: Vec::new(),
498                                             bindings: Vec::new(),
499                                         },
500                                     }],
501                                 },
502                                 did: None,
503                             },
504                             true,
505                         )),
506                     });
507                 } else if let Some(i) =
508                     try_inline(cx, did, item.res, item.ident.name, None, visited)
509                 {
510                     items.extend(i)
511                 }
512             }
513         }
514     }
515 }
516
517 crate fn print_inlined_const(cx: &DocContext<'_>, did: DefId) -> String {
518     if let Some(did) = did.as_local() {
519         let hir_id = cx.tcx.hir().local_def_id_to_hir_id(did);
520         rustc_hir_pretty::id_to_string(&cx.tcx.hir(), hir_id)
521     } else {
522         cx.tcx.rendered_const(did)
523     }
524 }
525
526 fn build_const(cx: &DocContext<'_>, did: DefId) -> clean::Constant {
527     clean::Constant {
528         type_: cx.tcx.type_of(did).clean(cx),
529         expr: print_inlined_const(cx, did),
530         value: clean::utils::print_evaluated_const(cx, did),
531         is_literal: did.as_local().map_or(false, |did| {
532             clean::utils::is_literal_expr(cx, cx.tcx.hir().local_def_id_to_hir_id(did))
533         }),
534     }
535 }
536
537 fn build_static(cx: &DocContext<'_>, did: DefId, mutable: bool) -> clean::Static {
538     clean::Static {
539         type_: cx.tcx.type_of(did).clean(cx),
540         mutability: if mutable { Mutability::Mut } else { Mutability::Not },
541         expr: "\n\n\n".to_string(), // trigger the "[definition]" links
542     }
543 }
544
545 fn build_macro(cx: &DocContext<'_>, did: DefId, name: Symbol) -> clean::ItemKind {
546     let imported_from = cx.tcx.original_crate_name(did.krate);
547     match cx.enter_resolver(|r| r.cstore().load_macro_untracked(did, cx.sess())) {
548         LoadedMacro::MacroDef(def, _) => {
549             let matchers: Vec<Span> = if let ast::ItemKind::MacroDef(ref def) = def.kind {
550                 let tts: Vec<_> = def.body.inner_tokens().into_trees().collect();
551                 tts.chunks(4).map(|arm| arm[0].span()).collect()
552             } else {
553                 unreachable!()
554             };
555
556             let source = format!(
557                 "macro_rules! {} {{\n{}}}",
558                 name.clean(cx),
559                 matchers
560                     .iter()
561                     .map(|span| { format!("    {} => {{ ... }};\n", span.to_src(cx)) })
562                     .collect::<String>()
563             );
564
565             clean::MacroItem(clean::Macro { source, imported_from: Some(imported_from) })
566         }
567         LoadedMacro::ProcMacro(ext) => clean::ProcMacroItem(clean::ProcMacro {
568             kind: ext.macro_kind(),
569             helpers: ext.helper_attrs,
570         }),
571     }
572 }
573
574 /// A trait's generics clause actually contains all of the predicates for all of
575 /// its associated types as well. We specifically move these clauses to the
576 /// associated types instead when displaying, so when we're generating the
577 /// generics for the trait itself we need to be sure to remove them.
578 /// We also need to remove the implied "recursive" Self: Trait bound.
579 ///
580 /// The inverse of this filtering logic can be found in the `Clean`
581 /// implementation for `AssociatedType`
582 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean::Generics {
583     for pred in &mut g.where_predicates {
584         match *pred {
585             clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref mut bounds }
586                 if *s == kw::SelfUpper =>
587             {
588                 bounds.retain(|bound| match *bound {
589                     clean::GenericBound::TraitBound(
590                         clean::PolyTrait { trait_: clean::ResolvedPath { did, .. }, .. },
591                         _,
592                     ) => did != trait_did,
593                     _ => true,
594                 });
595             }
596             _ => {}
597         }
598     }
599
600     g.where_predicates.retain(|pred| match *pred {
601         clean::WherePredicate::BoundPredicate {
602             ty:
603                 clean::QPath {
604                     self_type: box clean::Generic(ref s),
605                     trait_: box clean::ResolvedPath { did, .. },
606                     name: ref _name,
607                 },
608             ref bounds,
609         } => !(bounds.is_empty() || *s == kw::SelfUpper && did == trait_did),
610         _ => true,
611     });
612     g
613 }
614
615 /// Supertrait bounds for a trait are also listed in the generics coming from
616 /// the metadata for a crate, so we want to separate those out and create a new
617 /// list of explicit supertrait bounds to render nicely.
618 fn separate_supertrait_bounds(
619     mut g: clean::Generics,
620 ) -> (clean::Generics, Vec<clean::GenericBound>) {
621     let mut ty_bounds = Vec::new();
622     g.where_predicates.retain(|pred| match *pred {
623         clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref bounds }
624             if *s == kw::SelfUpper =>
625         {
626             ty_bounds.extend(bounds.iter().cloned());
627             false
628         }
629         _ => true,
630     });
631     (g, ty_bounds)
632 }
633
634 crate fn record_extern_trait(cx: &DocContext<'_>, did: DefId) {
635     if did.is_local() {
636         return;
637     }
638
639     {
640         if cx.external_traits.borrow().contains_key(&did)
641             || cx.active_extern_traits.borrow().contains(&did)
642         {
643             return;
644         }
645     }
646
647     {
648         cx.active_extern_traits.borrow_mut().insert(did);
649     }
650
651     debug!("record_extern_trait: {:?}", did);
652     let trait_ = build_external_trait(cx, did);
653
654     cx.external_traits.borrow_mut().insert(did, trait_);
655     cx.active_extern_traits.borrow_mut().remove(&did);
656 }