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