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