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