]> git.lizzy.rs Git - rust.git/blob - src/librustc_save_analysis/sig.rs
Rollup merge of #59432 - phansch:compiletest_docs, r=alexcrichton
[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::Ctor(..) => {
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, r) => {
707                 let id = parent_id.unwrap();
708                 let name_def = SigElement {
709                     id: id_from_node_id(id, scx),
710                     start: offset,
711                     end: offset + text.len(),
712                 };
713                 text.push_str(" { ");
714                 let mut defs = vec![name_def];
715                 let mut refs = vec![];
716                 if r {
717                     text.push_str("/* parse error */ ");
718                 } else {
719                     for f in fields {
720                         let field_sig = f.make(offset + text.len(), Some(id), scx)?;
721                         text.push_str(&field_sig.text);
722                         text.push_str(", ");
723                         defs.extend(field_sig.defs.into_iter());
724                         refs.extend(field_sig.refs.into_iter());
725                     }
726                 }
727                 text.push('}');
728                 Ok(Signature { text, defs, refs })
729             }
730             ast::VariantData::Tuple(ref fields, id) => {
731                 let name_def = SigElement {
732                     id: id_from_node_id(id, scx),
733                     start: offset,
734                     end: offset + text.len(),
735                 };
736                 text.push('(');
737                 let mut defs = vec![name_def];
738                 let mut refs = vec![];
739                 for f in fields {
740                     let field_sig = f.make(offset + text.len(), Some(id), scx)?;
741                     text.push_str(&field_sig.text);
742                     text.push_str(", ");
743                     defs.extend(field_sig.defs.into_iter());
744                     refs.extend(field_sig.refs.into_iter());
745                 }
746                 text.push(')');
747                 Ok(Signature { text, defs, refs })
748             }
749             ast::VariantData::Unit(id) => {
750                 let name_def = SigElement {
751                     id: id_from_node_id(id, scx),
752                     start: offset,
753                     end: offset + text.len(),
754                 };
755                 Ok(Signature {
756                     text,
757                     defs: vec![name_def],
758                     refs: vec![],
759                 })
760             }
761         }
762     }
763 }
764
765 impl Sig for ast::ForeignItem {
766     fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext<'_, '_>) -> Result {
767         let id = Some(self.id);
768         match self.node {
769             ast::ForeignItemKind::Fn(ref decl, ref generics) => {
770                 let mut text = String::new();
771                 text.push_str("fn ");
772
773                 let mut sig = name_and_generics(text, offset, generics, self.id, self.ident, scx)?;
774
775                 sig.text.push('(');
776                 for i in &decl.inputs {
777                     // FIXME should descend into patterns to add defs.
778                     sig.text.push_str(&pprust::pat_to_string(&i.pat));
779                     sig.text.push_str(": ");
780                     let nested = i.ty.make(offset + sig.text.len(), Some(i.id), scx)?;
781                     sig.text.push_str(&nested.text);
782                     sig.text.push(',');
783                     sig.defs.extend(nested.defs.into_iter());
784                     sig.refs.extend(nested.refs.into_iter());
785                 }
786                 sig.text.push(')');
787
788                 if let ast::FunctionRetTy::Ty(ref t) = decl.output {
789                     sig.text.push_str(" -> ");
790                     let nested = t.make(offset + sig.text.len(), None, scx)?;
791                     sig.text.push_str(&nested.text);
792                     sig.defs.extend(nested.defs.into_iter());
793                     sig.refs.extend(nested.refs.into_iter());
794                 }
795                 sig.text.push(';');
796
797                 Ok(sig)
798             }
799             ast::ForeignItemKind::Static(ref ty, m) => {
800                 let mut text = "static ".to_owned();
801                 if m {
802                     text.push_str("mut ");
803                 }
804                 let name = self.ident.to_string();
805                 let defs = vec![
806                     SigElement {
807                         id: id_from_node_id(self.id, scx),
808                         start: offset + text.len(),
809                         end: offset + text.len() + name.len(),
810                     },
811                 ];
812                 text.push_str(&name);
813                 text.push_str(": ");
814
815                 let ty_sig = ty.make(offset + text.len(), id, scx)?;
816                 text.push(';');
817
818                 Ok(extend_sig(ty_sig, text, defs, vec![]))
819             }
820             ast::ForeignItemKind::Ty => {
821                 let mut text = "type ".to_owned();
822                 let name = self.ident.to_string();
823                 let defs = vec![
824                     SigElement {
825                         id: id_from_node_id(self.id, scx),
826                         start: offset + text.len(),
827                         end: offset + text.len() + name.len(),
828                     },
829                 ];
830                 text.push_str(&name);
831                 text.push(';');
832
833                 Ok(Signature {
834                     text: text,
835                     defs: defs,
836                     refs: vec![],
837                 })
838             }
839             ast::ForeignItemKind::Macro(..) => Err("macro"),
840         }
841     }
842 }
843
844 fn name_and_generics(
845     mut text: String,
846     offset: usize,
847     generics: &ast::Generics,
848     id: NodeId,
849     name: ast::Ident,
850     scx: &SaveContext<'_, '_>,
851 ) -> Result {
852     let name = name.to_string();
853     let def = SigElement {
854         id: id_from_node_id(id, scx),
855         start: offset + text.len(),
856         end: offset + text.len() + name.len(),
857     };
858     text.push_str(&name);
859     let generics: Signature = generics.make(offset + text.len(), Some(id), scx)?;
860     // FIXME where clause
861     let text = format!("{}{}", text, generics.text);
862     Ok(extend_sig(generics, text, vec![def], vec![]))
863 }
864
865
866 fn make_assoc_type_signature(
867     id: NodeId,
868     ident: ast::Ident,
869     bounds: Option<&ast::GenericBounds>,
870     default: Option<&ast::Ty>,
871     scx: &SaveContext<'_, '_>,
872 ) -> Result {
873     let mut text = "type ".to_owned();
874     let name = ident.to_string();
875     let mut defs = vec![
876         SigElement {
877             id: id_from_node_id(id, scx),
878             start: text.len(),
879             end: text.len() + name.len(),
880         },
881     ];
882     let mut refs = vec![];
883     text.push_str(&name);
884     if let Some(bounds) = bounds {
885         text.push_str(": ");
886         // FIXME should descend into bounds
887         text.push_str(&pprust::bounds_to_string(bounds));
888     }
889     if let Some(default) = default {
890         text.push_str(" = ");
891         let ty_sig = default.make(text.len(), Some(id), scx)?;
892         text.push_str(&ty_sig.text);
893         defs.extend(ty_sig.defs.into_iter());
894         refs.extend(ty_sig.refs.into_iter());
895     }
896     text.push(';');
897     Ok(Signature { text, defs, refs })
898 }
899
900 fn make_assoc_const_signature(
901     id: NodeId,
902     ident: ast::Name,
903     ty: &ast::Ty,
904     default: Option<&ast::Expr>,
905     scx: &SaveContext<'_, '_>,
906 ) -> Result {
907     let mut text = "const ".to_owned();
908     let name = ident.to_string();
909     let mut defs = vec![
910         SigElement {
911             id: id_from_node_id(id, scx),
912             start: text.len(),
913             end: text.len() + name.len(),
914         },
915     ];
916     let mut refs = vec![];
917     text.push_str(&name);
918     text.push_str(": ");
919
920     let ty_sig = ty.make(text.len(), Some(id), scx)?;
921     text.push_str(&ty_sig.text);
922     defs.extend(ty_sig.defs.into_iter());
923     refs.extend(ty_sig.refs.into_iter());
924
925     if let Some(default) = default {
926         text.push_str(" = ");
927         text.push_str(&pprust::expr_to_string(default));
928     }
929     text.push(';');
930     Ok(Signature { text, defs, refs })
931 }
932
933 fn make_method_signature(
934     id: NodeId,
935     ident: ast::Ident,
936     generics: &ast::Generics,
937     m: &ast::MethodSig,
938     scx: &SaveContext<'_, '_>,
939 ) -> Result {
940     // FIXME code dup with function signature
941     let mut text = String::new();
942     if m.header.constness.node == ast::Constness::Const {
943         text.push_str("const ");
944     }
945     if m.header.asyncness.node.is_async() {
946         text.push_str("async ");
947     }
948     if m.header.unsafety == ast::Unsafety::Unsafe {
949         text.push_str("unsafe ");
950     }
951     if m.header.abi != rustc_target::spec::abi::Abi::Rust {
952         text.push_str("extern");
953         text.push_str(&m.header.abi.to_string());
954         text.push(' ');
955     }
956     text.push_str("fn ");
957
958     let mut sig = name_and_generics(text, 0, generics, id, ident, scx)?;
959
960     sig.text.push('(');
961     for i in &m.decl.inputs {
962         // FIXME should descend into patterns to add defs.
963         sig.text.push_str(&pprust::pat_to_string(&i.pat));
964         sig.text.push_str(": ");
965         let nested = i.ty.make(sig.text.len(), Some(i.id), scx)?;
966         sig.text.push_str(&nested.text);
967         sig.text.push(',');
968         sig.defs.extend(nested.defs.into_iter());
969         sig.refs.extend(nested.refs.into_iter());
970     }
971     sig.text.push(')');
972
973     if let ast::FunctionRetTy::Ty(ref t) = m.decl.output {
974         sig.text.push_str(" -> ");
975         let nested = t.make(sig.text.len(), None, scx)?;
976         sig.text.push_str(&nested.text);
977         sig.defs.extend(nested.defs.into_iter());
978         sig.refs.extend(nested.refs.into_iter());
979     }
980     sig.text.push_str(" {}");
981
982     Ok(sig)
983 }