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