]> git.lizzy.rs Git - rust.git/blob - src/librustc_save_analysis/sig.rs
6a9ad3c38f496d3b0ed304aee5d2fd0ebdee3e35
[rust.git] / src / librustc_save_analysis / sig.rs
1 // A signature is a string representation of an item's type signature, excluding
2 // any body. It also includes ids for any defs or refs in the signature. For
3 // example:
4 //
5 // ```
6 // fn foo(x: String) {
7 //     println!("{}", x);
8 // }
9 // ```
10 // The signature string is something like "fn foo(x: String) {}" and the signature
11 // will have defs for `foo` and `x` and a ref for `String`.
12 //
13 // All signature text should parse in the correct context (i.e., in a module or
14 // impl, etc.). Clients may want to trim trailing `{}` or `;`. The text of a
15 // signature is not guaranteed to be stable (it may improve or change as the
16 // syntax changes, or whitespace or punctuation may change). It is also likely
17 // not to be pretty - no attempt is made to prettify the text. It is recommended
18 // that clients run the text through Rustfmt.
19 //
20 // This module generates Signatures for items by walking the AST and looking up
21 // references.
22 //
23 // Signatures do not include visibility info. I'm not sure if this is a feature
24 // or an ommission (FIXME).
25 //
26 // FIXME where clauses need implementing, defs/refs in generics are mostly missing.
27
28 use crate::{id_from_def_id, id_from_hir_id, SaveContext};
29
30 use rls_data::{SigElement, Signature};
31
32 use rustc_ast::ast::Mutability;
33 use rustc_hir as hir;
34 use rustc_hir::def::{DefKind, Res};
35 use rustc_hir_pretty::id_to_string;
36 use rustc_hir_pretty::{bounds_to_string, path_segment_to_string, path_to_string, ty_to_string};
37 use rustc_span::symbol::{Ident, Symbol};
38
39 pub fn item_signature(item: &hir::Item<'_>, scx: &SaveContext<'_>) -> Option<Signature> {
40     if !scx.config.signatures {
41         return None;
42     }
43     item.make(0, None, scx).ok()
44 }
45
46 pub fn foreign_item_signature(
47     item: &hir::ForeignItem<'_>,
48     scx: &SaveContext<'_>,
49 ) -> Option<Signature> {
50     if !scx.config.signatures {
51         return None;
52     }
53     item.make(0, None, scx).ok()
54 }
55
56 /// Signature for a struct or tuple field declaration.
57 /// Does not include a trailing comma.
58 pub fn field_signature(field: &hir::StructField<'_>, scx: &SaveContext<'_>) -> Option<Signature> {
59     if !scx.config.signatures {
60         return None;
61     }
62     field.make(0, None, scx).ok()
63 }
64
65 /// Does not include a trailing comma.
66 pub fn variant_signature(variant: &hir::Variant<'_>, scx: &SaveContext<'_>) -> Option<Signature> {
67     if !scx.config.signatures {
68         return None;
69     }
70     variant.make(0, None, scx).ok()
71 }
72
73 pub fn method_signature(
74     id: hir::HirId,
75     ident: Ident,
76     generics: &hir::Generics<'_>,
77     m: &hir::FnSig<'_>,
78     scx: &SaveContext<'_>,
79 ) -> Option<Signature> {
80     if !scx.config.signatures {
81         return None;
82     }
83     make_method_signature(id, ident, generics, m, scx).ok()
84 }
85
86 pub fn assoc_const_signature(
87     id: hir::HirId,
88     ident: Symbol,
89     ty: &hir::Ty<'_>,
90     default: Option<&hir::Expr<'_>>,
91     scx: &SaveContext<'_>,
92 ) -> Option<Signature> {
93     if !scx.config.signatures {
94         return None;
95     }
96     make_assoc_const_signature(id, ident, ty, default, scx).ok()
97 }
98
99 pub fn assoc_type_signature(
100     id: hir::HirId,
101     ident: Ident,
102     bounds: Option<hir::GenericBounds<'_>>,
103     default: Option<&hir::Ty<'_>>,
104     scx: &SaveContext<'_>,
105 ) -> Option<Signature> {
106     if !scx.config.signatures {
107         return None;
108     }
109     make_assoc_type_signature(id, ident, bounds, default, scx).ok()
110 }
111
112 type Result = std::result::Result<Signature, &'static str>;
113
114 trait Sig {
115     fn make(&self, offset: usize, id: Option<hir::HirId>, scx: &SaveContext<'_>) -> Result;
116 }
117
118 fn extend_sig(
119     mut sig: Signature,
120     text: String,
121     defs: Vec<SigElement>,
122     refs: Vec<SigElement>,
123 ) -> Signature {
124     sig.text = text;
125     sig.defs.extend(defs.into_iter());
126     sig.refs.extend(refs.into_iter());
127     sig
128 }
129
130 fn replace_text(mut sig: Signature, text: String) -> Signature {
131     sig.text = text;
132     sig
133 }
134
135 fn merge_sigs(text: String, sigs: Vec<Signature>) -> Signature {
136     let mut result = Signature { text, defs: vec![], refs: vec![] };
137
138     let (defs, refs): (Vec<_>, Vec<_>) = sigs.into_iter().map(|s| (s.defs, s.refs)).unzip();
139
140     result.defs.extend(defs.into_iter().flat_map(|ds| ds.into_iter()));
141     result.refs.extend(refs.into_iter().flat_map(|rs| rs.into_iter()));
142
143     result
144 }
145
146 fn text_sig(text: String) -> Signature {
147     Signature { text, defs: vec![], refs: vec![] }
148 }
149
150 impl<'hir> Sig for hir::Ty<'hir> {
151     fn make(&self, offset: usize, _parent_id: Option<hir::HirId>, scx: &SaveContext<'_>) -> Result {
152         let id = Some(self.hir_id);
153         match self.kind {
154             hir::TyKind::Slice(ref ty) => {
155                 let nested = ty.make(offset + 1, id, scx)?;
156                 let text = format!("[{}]", nested.text);
157                 Ok(replace_text(nested, text))
158             }
159             hir::TyKind::Ptr(ref mt) => {
160                 let prefix = match mt.mutbl {
161                     hir::Mutability::Mut => "*mut ",
162                     hir::Mutability::Not => "*const ",
163                 };
164                 let nested = mt.ty.make(offset + prefix.len(), id, scx)?;
165                 let text = format!("{}{}", prefix, nested.text);
166                 Ok(replace_text(nested, text))
167             }
168             hir::TyKind::Rptr(ref lifetime, ref mt) => {
169                 let mut prefix = "&".to_owned();
170                 prefix.push_str(&lifetime.name.ident().to_string());
171                 prefix.push(' ');
172                 if let hir::Mutability::Mut = mt.mutbl {
173                     prefix.push_str("mut ");
174                 };
175
176                 let nested = mt.ty.make(offset + prefix.len(), id, scx)?;
177                 let text = format!("{}{}", prefix, nested.text);
178                 Ok(replace_text(nested, text))
179             }
180             hir::TyKind::Never => Ok(text_sig("!".to_owned())),
181             hir::TyKind::Tup(ts) => {
182                 let mut text = "(".to_owned();
183                 let mut defs = vec![];
184                 let mut refs = vec![];
185                 for t in ts {
186                     let nested = t.make(offset + text.len(), id, scx)?;
187                     text.push_str(&nested.text);
188                     text.push(',');
189                     defs.extend(nested.defs.into_iter());
190                     refs.extend(nested.refs.into_iter());
191                 }
192                 text.push(')');
193                 Ok(Signature { text, defs, refs })
194             }
195             hir::TyKind::BareFn(ref f) => {
196                 let mut text = String::new();
197                 if !f.generic_params.is_empty() {
198                     // FIXME defs, bounds on lifetimes
199                     text.push_str("for<");
200                     text.push_str(
201                         &f.generic_params
202                             .iter()
203                             .filter_map(|param| match param.kind {
204                                 hir::GenericParamKind::Lifetime { .. } => {
205                                     Some(param.name.ident().to_string())
206                                 }
207                                 _ => None,
208                             })
209                             .collect::<Vec<_>>()
210                             .join(", "),
211                     );
212                     text.push('>');
213                 }
214
215                 if let hir::Unsafety::Unsafe = f.unsafety {
216                     text.push_str("unsafe ");
217                 }
218                 text.push_str("fn(");
219
220                 let mut defs = vec![];
221                 let mut refs = vec![];
222                 for i in f.decl.inputs {
223                     let nested = i.make(offset + text.len(), Some(i.hir_id), scx)?;
224                     text.push_str(&nested.text);
225                     text.push(',');
226                     defs.extend(nested.defs.into_iter());
227                     refs.extend(nested.refs.into_iter());
228                 }
229                 text.push(')');
230                 if let hir::FnRetTy::Return(ref t) = f.decl.output {
231                     text.push_str(" -> ");
232                     let nested = t.make(offset + text.len(), None, scx)?;
233                     text.push_str(&nested.text);
234                     text.push(',');
235                     defs.extend(nested.defs.into_iter());
236                     refs.extend(nested.refs.into_iter());
237                 }
238
239                 Ok(Signature { text, defs, refs })
240             }
241             hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => path.make(offset, id, scx),
242             hir::TyKind::Path(hir::QPath::Resolved(Some(ref qself), ref path)) => {
243                 let nested_ty = qself.make(offset + 1, id, scx)?;
244                 let prefix = format!(
245                     "<{} as {}>::",
246                     nested_ty.text,
247                     path_segment_to_string(&path.segments[0])
248                 );
249
250                 let name = path_segment_to_string(path.segments.last().ok_or("Bad path")?);
251                 let res = scx.get_path_res(id.ok_or("Missing id for Path")?);
252                 let id = id_from_def_id(res.def_id());
253                 if path.segments.len() == 2 {
254                     let start = offset + prefix.len();
255                     let end = start + name.len();
256
257                     Ok(Signature {
258                         text: prefix + &name,
259                         defs: vec![],
260                         refs: vec![SigElement { id, start, end }],
261                     })
262                 } else {
263                     let start = offset + prefix.len() + 5;
264                     let end = start + name.len();
265                     // FIXME should put the proper path in there, not elipses.
266                     Ok(Signature {
267                         text: prefix + "...::" + &name,
268                         defs: vec![],
269                         refs: vec![SigElement { id, start, end }],
270                     })
271                 }
272             }
273             hir::TyKind::Path(hir::QPath::TypeRelative(ty, segment)) => {
274                 let nested_ty = ty.make(offset + 1, id, scx)?;
275                 let prefix = format!("<{}>::", nested_ty.text,);
276
277                 let name = path_segment_to_string(segment);
278                 let res = scx.get_path_res(id.ok_or("Missing id for Path")?);
279                 let id = id_from_def_id(res.def_id());
280
281                 let start = offset + prefix.len();
282                 let end = start + name.len();
283                 Ok(Signature {
284                     text: prefix + &name,
285                     defs: vec![],
286                     refs: vec![SigElement { id, start, end }],
287                 })
288             }
289             hir::TyKind::Path(hir::QPath::LangItem(..)) => unimplemented!(),
290             hir::TyKind::TraitObject(bounds, ..) => {
291                 // FIXME recurse into bounds
292                 let bounds: Vec<hir::GenericBound<'_>> = bounds
293                     .iter()
294                     .map(|hir::PolyTraitRef { bound_generic_params, trait_ref, span }| {
295                         hir::GenericBound::Trait(
296                             hir::PolyTraitRef {
297                                 bound_generic_params,
298                                 trait_ref: hir::TraitRef {
299                                     path: trait_ref.path,
300                                     hir_ref_id: trait_ref.hir_ref_id,
301                                 },
302                                 span: *span,
303                             },
304                             hir::TraitBoundModifier::None,
305                         )
306                     })
307                     .collect();
308                 let nested = bounds_to_string(&bounds);
309                 Ok(text_sig(nested))
310             }
311             hir::TyKind::Array(ref ty, ref anon_const) => {
312                 let nested_ty = ty.make(offset + 1, id, scx)?;
313                 let expr = id_to_string(&scx.tcx.hir(), anon_const.body.hir_id).replace('\n', " ");
314                 let text = format!("[{}; {}]", nested_ty.text, expr);
315                 Ok(replace_text(nested_ty, text))
316             }
317             hir::TyKind::OpaqueDef(item_id, _) => {
318                 let item = scx.tcx.hir().item(item_id.id);
319                 item.make(offset, Some(item_id.id), scx)
320             }
321             hir::TyKind::Typeof(_) | hir::TyKind::Infer | hir::TyKind::Err => Err("Ty"),
322         }
323     }
324 }
325
326 impl<'hir> Sig for hir::Item<'hir> {
327     fn make(&self, offset: usize, _parent_id: Option<hir::HirId>, scx: &SaveContext<'_>) -> Result {
328         let id = Some(self.hir_id);
329
330         match self.kind {
331             hir::ItemKind::Static(ref ty, m, ref body) => {
332                 let mut text = "static ".to_owned();
333                 if m == hir::Mutability::Mut {
334                     text.push_str("mut ");
335                 }
336                 let name = self.ident.to_string();
337                 let defs = vec![SigElement {
338                     id: id_from_hir_id(self.hir_id, scx),
339                     start: offset + text.len(),
340                     end: offset + text.len() + name.len(),
341                 }];
342                 text.push_str(&name);
343                 text.push_str(": ");
344
345                 let ty = ty.make(offset + text.len(), id, scx)?;
346                 text.push_str(&ty.text);
347
348                 text.push_str(" = ");
349                 let expr = id_to_string(&scx.tcx.hir(), body.hir_id).replace('\n', " ");
350                 text.push_str(&expr);
351
352                 text.push(';');
353
354                 Ok(extend_sig(ty, text, defs, vec![]))
355             }
356             hir::ItemKind::Const(ref ty, ref body) => {
357                 let mut text = "const ".to_owned();
358                 let name = self.ident.to_string();
359                 let defs = vec![SigElement {
360                     id: id_from_hir_id(self.hir_id, scx),
361                     start: offset + text.len(),
362                     end: offset + text.len() + name.len(),
363                 }];
364                 text.push_str(&name);
365                 text.push_str(": ");
366
367                 let ty = ty.make(offset + text.len(), id, scx)?;
368                 text.push_str(&ty.text);
369
370                 text.push_str(" = ");
371                 let expr = id_to_string(&scx.tcx.hir(), body.hir_id).replace('\n', " ");
372                 text.push_str(&expr);
373
374                 text.push(';');
375
376                 Ok(extend_sig(ty, text, defs, vec![]))
377             }
378             hir::ItemKind::Fn(hir::FnSig { ref decl, header }, ref generics, _) => {
379                 let mut text = String::new();
380                 if let hir::Constness::Const = header.constness {
381                     text.push_str("const ");
382                 }
383                 if hir::IsAsync::Async == header.asyncness {
384                     text.push_str("async ");
385                 }
386                 if let hir::Unsafety::Unsafe = header.unsafety {
387                     text.push_str("unsafe ");
388                 }
389                 text.push_str("fn ");
390
391                 let mut sig =
392                     name_and_generics(text, offset, generics, self.hir_id, self.ident, scx)?;
393
394                 sig.text.push('(');
395                 for i in decl.inputs {
396                     // FIXME should descend into patterns to add defs.
397                     sig.text.push_str(": ");
398                     let nested = i.make(offset + sig.text.len(), Some(i.hir_id), scx)?;
399                     sig.text.push_str(&nested.text);
400                     sig.text.push(',');
401                     sig.defs.extend(nested.defs.into_iter());
402                     sig.refs.extend(nested.refs.into_iter());
403                 }
404                 sig.text.push(')');
405
406                 if let hir::FnRetTy::Return(ref t) = decl.output {
407                     sig.text.push_str(" -> ");
408                     let nested = t.make(offset + sig.text.len(), None, scx)?;
409                     sig.text.push_str(&nested.text);
410                     sig.defs.extend(nested.defs.into_iter());
411                     sig.refs.extend(nested.refs.into_iter());
412                 }
413                 sig.text.push_str(" {}");
414
415                 Ok(sig)
416             }
417             hir::ItemKind::Mod(ref _mod) => {
418                 let mut text = "mod ".to_owned();
419                 let name = self.ident.to_string();
420                 let defs = vec![SigElement {
421                     id: id_from_hir_id(self.hir_id, scx),
422                     start: offset + text.len(),
423                     end: offset + text.len() + name.len(),
424                 }];
425                 text.push_str(&name);
426                 // Could be either `mod foo;` or `mod foo { ... }`, but we'll just pick one.
427                 text.push(';');
428
429                 Ok(Signature { text, defs, refs: vec![] })
430             }
431             hir::ItemKind::TyAlias(ref ty, ref generics) => {
432                 let text = "type ".to_owned();
433                 let mut sig =
434                     name_and_generics(text, offset, generics, self.hir_id, self.ident, scx)?;
435
436                 sig.text.push_str(" = ");
437                 let ty = ty.make(offset + sig.text.len(), id, scx)?;
438                 sig.text.push_str(&ty.text);
439                 sig.text.push(';');
440
441                 Ok(merge_sigs(sig.text.clone(), vec![sig, ty]))
442             }
443             hir::ItemKind::Enum(_, ref generics) => {
444                 let text = "enum ".to_owned();
445                 let mut sig =
446                     name_and_generics(text, offset, generics, self.hir_id, self.ident, scx)?;
447                 sig.text.push_str(" {}");
448                 Ok(sig)
449             }
450             hir::ItemKind::Struct(_, ref generics) => {
451                 let text = "struct ".to_owned();
452                 let mut sig =
453                     name_and_generics(text, offset, generics, self.hir_id, self.ident, scx)?;
454                 sig.text.push_str(" {}");
455                 Ok(sig)
456             }
457             hir::ItemKind::Union(_, ref generics) => {
458                 let text = "union ".to_owned();
459                 let mut sig =
460                     name_and_generics(text, offset, generics, self.hir_id, self.ident, scx)?;
461                 sig.text.push_str(" {}");
462                 Ok(sig)
463             }
464             hir::ItemKind::Trait(is_auto, unsafety, ref generics, bounds, _) => {
465                 let mut text = String::new();
466
467                 if is_auto == hir::IsAuto::Yes {
468                     text.push_str("auto ");
469                 }
470
471                 if let hir::Unsafety::Unsafe = unsafety {
472                     text.push_str("unsafe ");
473                 }
474                 text.push_str("trait ");
475                 let mut sig =
476                     name_and_generics(text, offset, generics, self.hir_id, self.ident, scx)?;
477
478                 if !bounds.is_empty() {
479                     sig.text.push_str(": ");
480                     sig.text.push_str(&bounds_to_string(bounds));
481                 }
482                 // FIXME where clause
483                 sig.text.push_str(" {}");
484
485                 Ok(sig)
486             }
487             hir::ItemKind::TraitAlias(ref generics, bounds) => {
488                 let mut text = String::new();
489                 text.push_str("trait ");
490                 let mut sig =
491                     name_and_generics(text, offset, generics, self.hir_id, self.ident, scx)?;
492
493                 if !bounds.is_empty() {
494                     sig.text.push_str(" = ");
495                     sig.text.push_str(&bounds_to_string(bounds));
496                 }
497                 // FIXME where clause
498                 sig.text.push_str(";");
499
500                 Ok(sig)
501             }
502             hir::ItemKind::Impl {
503                 unsafety,
504                 polarity,
505                 defaultness,
506                 defaultness_span: _,
507                 constness,
508                 ref generics,
509                 ref of_trait,
510                 ref self_ty,
511                 items: _,
512             } => {
513                 let mut text = String::new();
514                 if let hir::Defaultness::Default { .. } = defaultness {
515                     text.push_str("default ");
516                 }
517                 if let hir::Unsafety::Unsafe = unsafety {
518                     text.push_str("unsafe ");
519                 }
520                 text.push_str("impl");
521                 if let hir::Constness::Const = constness {
522                     text.push_str(" const");
523                 }
524
525                 let generics_sig = generics.make(offset + text.len(), id, scx)?;
526                 text.push_str(&generics_sig.text);
527
528                 text.push(' ');
529
530                 let trait_sig = if let Some(ref t) = *of_trait {
531                     if let hir::ImplPolarity::Negative(_) = polarity {
532                         text.push('!');
533                     }
534                     let trait_sig = t.path.make(offset + text.len(), id, scx)?;
535                     text.push_str(&trait_sig.text);
536                     text.push_str(" for ");
537                     trait_sig
538                 } else {
539                     text_sig(String::new())
540                 };
541
542                 let ty_sig = self_ty.make(offset + text.len(), id, scx)?;
543                 text.push_str(&ty_sig.text);
544
545                 text.push_str(" {}");
546
547                 Ok(merge_sigs(text, vec![generics_sig, trait_sig, ty_sig]))
548
549                 // FIXME where clause
550             }
551             hir::ItemKind::ForeignMod(_) => Err("extern mod"),
552             hir::ItemKind::GlobalAsm(_) => Err("glboal asm"),
553             hir::ItemKind::ExternCrate(_) => Err("extern crate"),
554             hir::ItemKind::OpaqueTy(..) => Err("opaque type"),
555             // FIXME should implement this (e.g., pub use).
556             hir::ItemKind::Use(..) => Err("import"),
557         }
558     }
559 }
560
561 impl<'hir> Sig for hir::Path<'hir> {
562     fn make(&self, offset: usize, id: Option<hir::HirId>, scx: &SaveContext<'_>) -> Result {
563         let res = scx.get_path_res(id.ok_or("Missing id for Path")?);
564
565         let (name, start, end) = match res {
566             Res::PrimTy(..) | Res::SelfTy(..) | Res::Err => {
567                 return Ok(Signature { text: path_to_string(self), defs: vec![], refs: vec![] });
568             }
569             Res::Def(DefKind::AssocConst | DefKind::Variant | DefKind::Ctor(..), _) => {
570                 let len = self.segments.len();
571                 if len < 2 {
572                     return Err("Bad path");
573                 }
574                 // FIXME: really we should descend into the generics here and add SigElements for
575                 // them.
576                 // FIXME: would be nice to have a def for the first path segment.
577                 let seg1 = path_segment_to_string(&self.segments[len - 2]);
578                 let seg2 = path_segment_to_string(&self.segments[len - 1]);
579                 let start = offset + seg1.len() + 2;
580                 (format!("{}::{}", seg1, seg2), start, start + seg2.len())
581             }
582             _ => {
583                 let name = path_segment_to_string(self.segments.last().ok_or("Bad path")?);
584                 let end = offset + name.len();
585                 (name, offset, end)
586             }
587         };
588
589         let id = id_from_def_id(res.def_id());
590         Ok(Signature { text: name, defs: vec![], refs: vec![SigElement { id, start, end }] })
591     }
592 }
593
594 // This does not cover the where clause, which must be processed separately.
595 impl<'hir> Sig for hir::Generics<'hir> {
596     fn make(&self, offset: usize, _parent_id: Option<hir::HirId>, scx: &SaveContext<'_>) -> Result {
597         if self.params.is_empty() {
598             return Ok(text_sig(String::new()));
599         }
600
601         let mut text = "<".to_owned();
602
603         let mut defs = Vec::with_capacity(self.params.len());
604         for param in self.params {
605             let mut param_text = String::new();
606             if let hir::GenericParamKind::Const { .. } = param.kind {
607                 param_text.push_str("const ");
608             }
609             param_text.push_str(&param.name.ident().as_str());
610             defs.push(SigElement {
611                 id: id_from_hir_id(param.hir_id, scx),
612                 start: offset + text.len(),
613                 end: offset + text.len() + param_text.as_str().len(),
614             });
615             if let hir::GenericParamKind::Const { ref ty } = param.kind {
616                 param_text.push_str(": ");
617                 param_text.push_str(&ty_to_string(&ty));
618             }
619             if !param.bounds.is_empty() {
620                 param_text.push_str(": ");
621                 match param.kind {
622                     hir::GenericParamKind::Lifetime { .. } => {
623                         let bounds = param
624                             .bounds
625                             .iter()
626                             .map(|bound| match bound {
627                                 hir::GenericBound::Outlives(lt) => lt.name.ident().to_string(),
628                                 _ => panic!(),
629                             })
630                             .collect::<Vec<_>>()
631                             .join(" + ");
632                         param_text.push_str(&bounds);
633                         // FIXME add lifetime bounds refs.
634                     }
635                     hir::GenericParamKind::Type { .. } => {
636                         param_text.push_str(&bounds_to_string(param.bounds));
637                         // FIXME descend properly into bounds.
638                     }
639                     hir::GenericParamKind::Const { .. } => {
640                         // Const generics cannot contain bounds.
641                     }
642                 }
643             }
644             text.push_str(&param_text);
645             text.push(',');
646         }
647
648         text.push('>');
649         Ok(Signature { text, defs, refs: vec![] })
650     }
651 }
652
653 impl<'hir> Sig for hir::StructField<'hir> {
654     fn make(&self, offset: usize, _parent_id: Option<hir::HirId>, scx: &SaveContext<'_>) -> Result {
655         let mut text = String::new();
656
657         text.push_str(&self.ident.to_string());
658         let defs = Some(SigElement {
659             id: id_from_hir_id(self.hir_id, scx),
660             start: offset,
661             end: offset + text.len(),
662         });
663         text.push_str(": ");
664
665         let mut ty_sig = self.ty.make(offset + text.len(), Some(self.hir_id), scx)?;
666         text.push_str(&ty_sig.text);
667         ty_sig.text = text;
668         ty_sig.defs.extend(defs.into_iter());
669         Ok(ty_sig)
670     }
671 }
672
673 impl<'hir> Sig for hir::Variant<'hir> {
674     fn make(&self, offset: usize, parent_id: Option<hir::HirId>, scx: &SaveContext<'_>) -> Result {
675         let mut text = self.ident.to_string();
676         match self.data {
677             hir::VariantData::Struct(fields, r) => {
678                 let id = parent_id.unwrap();
679                 let name_def = SigElement {
680                     id: id_from_hir_id(id, scx),
681                     start: offset,
682                     end: offset + text.len(),
683                 };
684                 text.push_str(" { ");
685                 let mut defs = vec![name_def];
686                 let mut refs = vec![];
687                 if r {
688                     text.push_str("/* parse error */ ");
689                 } else {
690                     for f in fields {
691                         let field_sig = f.make(offset + text.len(), Some(id), scx)?;
692                         text.push_str(&field_sig.text);
693                         text.push_str(", ");
694                         defs.extend(field_sig.defs.into_iter());
695                         refs.extend(field_sig.refs.into_iter());
696                     }
697                 }
698                 text.push('}');
699                 Ok(Signature { text, defs, refs })
700             }
701             hir::VariantData::Tuple(fields, id) => {
702                 let name_def = SigElement {
703                     id: id_from_hir_id(id, scx),
704                     start: offset,
705                     end: offset + text.len(),
706                 };
707                 text.push('(');
708                 let mut defs = vec![name_def];
709                 let mut refs = vec![];
710                 for f in fields {
711                     let field_sig = f.make(offset + text.len(), Some(id), scx)?;
712                     text.push_str(&field_sig.text);
713                     text.push_str(", ");
714                     defs.extend(field_sig.defs.into_iter());
715                     refs.extend(field_sig.refs.into_iter());
716                 }
717                 text.push(')');
718                 Ok(Signature { text, defs, refs })
719             }
720             hir::VariantData::Unit(id) => {
721                 let name_def = SigElement {
722                     id: id_from_hir_id(id, scx),
723                     start: offset,
724                     end: offset + text.len(),
725                 };
726                 Ok(Signature { text, defs: vec![name_def], refs: vec![] })
727             }
728         }
729     }
730 }
731
732 impl<'hir> Sig for hir::ForeignItem<'hir> {
733     fn make(&self, offset: usize, _parent_id: Option<hir::HirId>, scx: &SaveContext<'_>) -> Result {
734         let id = Some(self.hir_id);
735         match self.kind {
736             hir::ForeignItemKind::Fn(decl, _, ref generics) => {
737                 let mut text = String::new();
738                 text.push_str("fn ");
739
740                 let mut sig =
741                     name_and_generics(text, offset, generics, self.hir_id, self.ident, scx)?;
742
743                 sig.text.push('(');
744                 for i in decl.inputs {
745                     sig.text.push_str(": ");
746                     let nested = i.make(offset + sig.text.len(), Some(i.hir_id), scx)?;
747                     sig.text.push_str(&nested.text);
748                     sig.text.push(',');
749                     sig.defs.extend(nested.defs.into_iter());
750                     sig.refs.extend(nested.refs.into_iter());
751                 }
752                 sig.text.push(')');
753
754                 if let hir::FnRetTy::Return(ref t) = decl.output {
755                     sig.text.push_str(" -> ");
756                     let nested = t.make(offset + sig.text.len(), None, scx)?;
757                     sig.text.push_str(&nested.text);
758                     sig.defs.extend(nested.defs.into_iter());
759                     sig.refs.extend(nested.refs.into_iter());
760                 }
761                 sig.text.push(';');
762
763                 Ok(sig)
764             }
765             hir::ForeignItemKind::Static(ref ty, m) => {
766                 let mut text = "static ".to_owned();
767                 if m == Mutability::Mut {
768                     text.push_str("mut ");
769                 }
770                 let name = self.ident.to_string();
771                 let defs = vec![SigElement {
772                     id: id_from_hir_id(self.hir_id, scx),
773                     start: offset + text.len(),
774                     end: offset + text.len() + name.len(),
775                 }];
776                 text.push_str(&name);
777                 text.push_str(": ");
778
779                 let ty_sig = ty.make(offset + text.len(), id, scx)?;
780                 text.push(';');
781
782                 Ok(extend_sig(ty_sig, text, defs, vec![]))
783             }
784             hir::ForeignItemKind::Type => {
785                 let mut text = "type ".to_owned();
786                 let name = self.ident.to_string();
787                 let defs = vec![SigElement {
788                     id: id_from_hir_id(self.hir_id, scx),
789                     start: offset + text.len(),
790                     end: offset + text.len() + name.len(),
791                 }];
792                 text.push_str(&name);
793                 text.push(';');
794
795                 Ok(Signature { text, defs, refs: vec![] })
796             }
797         }
798     }
799 }
800
801 fn name_and_generics(
802     mut text: String,
803     offset: usize,
804     generics: &hir::Generics<'_>,
805     id: hir::HirId,
806     name: Ident,
807     scx: &SaveContext<'_>,
808 ) -> Result {
809     let name = name.to_string();
810     let def = SigElement {
811         id: id_from_hir_id(id, scx),
812         start: offset + text.len(),
813         end: offset + text.len() + name.len(),
814     };
815     text.push_str(&name);
816     let generics: Signature = generics.make(offset + text.len(), Some(id), scx)?;
817     // FIXME where clause
818     let text = format!("{}{}", text, generics.text);
819     Ok(extend_sig(generics, text, vec![def], vec![]))
820 }
821
822 fn make_assoc_type_signature(
823     id: hir::HirId,
824     ident: Ident,
825     bounds: Option<hir::GenericBounds<'_>>,
826     default: Option<&hir::Ty<'_>>,
827     scx: &SaveContext<'_>,
828 ) -> Result {
829     let mut text = "type ".to_owned();
830     let name = ident.to_string();
831     let mut defs = vec![SigElement {
832         id: id_from_hir_id(id, scx),
833         start: text.len(),
834         end: text.len() + name.len(),
835     }];
836     let mut refs = vec![];
837     text.push_str(&name);
838     if let Some(bounds) = bounds {
839         text.push_str(": ");
840         // FIXME should descend into bounds
841         text.push_str(&bounds_to_string(bounds));
842     }
843     if let Some(default) = default {
844         text.push_str(" = ");
845         let ty_sig = default.make(text.len(), Some(id), scx)?;
846         text.push_str(&ty_sig.text);
847         defs.extend(ty_sig.defs.into_iter());
848         refs.extend(ty_sig.refs.into_iter());
849     }
850     text.push(';');
851     Ok(Signature { text, defs, refs })
852 }
853
854 fn make_assoc_const_signature(
855     id: hir::HirId,
856     ident: Symbol,
857     ty: &hir::Ty<'_>,
858     default: Option<&hir::Expr<'_>>,
859     scx: &SaveContext<'_>,
860 ) -> Result {
861     let mut text = "const ".to_owned();
862     let name = ident.to_string();
863     let mut defs = vec![SigElement {
864         id: id_from_hir_id(id, scx),
865         start: text.len(),
866         end: text.len() + name.len(),
867     }];
868     let mut refs = vec![];
869     text.push_str(&name);
870     text.push_str(": ");
871
872     let ty_sig = ty.make(text.len(), Some(id), scx)?;
873     text.push_str(&ty_sig.text);
874     defs.extend(ty_sig.defs.into_iter());
875     refs.extend(ty_sig.refs.into_iter());
876
877     if let Some(default) = default {
878         text.push_str(" = ");
879         text.push_str(&id_to_string(&scx.tcx.hir(), default.hir_id));
880     }
881     text.push(';');
882     Ok(Signature { text, defs, refs })
883 }
884
885 fn make_method_signature(
886     id: hir::HirId,
887     ident: Ident,
888     generics: &hir::Generics<'_>,
889     m: &hir::FnSig<'_>,
890     scx: &SaveContext<'_>,
891 ) -> Result {
892     // FIXME code dup with function signature
893     let mut text = String::new();
894     if let hir::Constness::Const = m.header.constness {
895         text.push_str("const ");
896     }
897     if hir::IsAsync::Async == m.header.asyncness {
898         text.push_str("async ");
899     }
900     if let hir::Unsafety::Unsafe = m.header.unsafety {
901         text.push_str("unsafe ");
902     }
903     text.push_str("fn ");
904
905     let mut sig = name_and_generics(text, 0, generics, id, ident, scx)?;
906
907     sig.text.push('(');
908     for i in m.decl.inputs {
909         sig.text.push_str(": ");
910         let nested = i.make(sig.text.len(), Some(i.hir_id), scx)?;
911         sig.text.push_str(&nested.text);
912         sig.text.push(',');
913         sig.defs.extend(nested.defs.into_iter());
914         sig.refs.extend(nested.refs.into_iter());
915     }
916     sig.text.push(')');
917
918     if let hir::FnRetTy::Return(ref t) = m.decl.output {
919         sig.text.push_str(" -> ");
920         let nested = t.make(sig.text.len(), None, scx)?;
921         sig.text.push_str(&nested.text);
922         sig.defs.extend(nested.defs.into_iter());
923         sig.refs.extend(nested.refs.into_iter());
924     }
925     sig.text.push_str(" {}");
926
927     Ok(sig)
928 }