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