]> git.lizzy.rs Git - rust.git/blob - src/librustc_save_analysis/sig.rs
Rollup merge of #68342 - lcnr:type_name_docs, r=Dylan-DPC
[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::{DefKind, Res};
33 use syntax::ast::{self, Extern, NodeId};
34 use syntax::print::pprust;
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 f.unsafety == ast::Unsafety::Unsafe {
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::FunctionRetTy::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                 text.push_str(" = ");
338
339                 let expr = pprust::expr_to_string(expr).replace('\n', " ");
340                 text.push_str(&expr);
341                 text.push(';');
342
343                 Ok(extend_sig(ty, text, defs, vec![]))
344             }
345             ast::ItemKind::Const(ref ty, ref expr) => {
346                 let mut text = "const ".to_owned();
347                 let name = self.ident.to_string();
348                 let defs = vec![SigElement {
349                     id: id_from_node_id(self.id, scx),
350                     start: offset + text.len(),
351                     end: offset + text.len() + name.len(),
352                 }];
353                 text.push_str(&name);
354                 text.push_str(": ");
355
356                 let ty = ty.make(offset + text.len(), id, scx)?;
357                 text.push_str(&ty.text);
358                 text.push_str(" = ");
359
360                 let expr = pprust::expr_to_string(expr).replace('\n', " ");
361                 text.push_str(&expr);
362                 text.push(';');
363
364                 Ok(extend_sig(ty, text, defs, vec![]))
365             }
366             ast::ItemKind::Fn(ast::FnSig { ref decl, header }, ref generics, _) => {
367                 let mut text = String::new();
368                 if header.constness.node == ast::Constness::Const {
369                     text.push_str("const ");
370                 }
371                 if header.asyncness.node.is_async() {
372                     text.push_str("async ");
373                 }
374                 if header.unsafety == ast::Unsafety::Unsafe {
375                     text.push_str("unsafe ");
376                 }
377                 push_extern(&mut text, header.ext);
378                 text.push_str("fn ");
379
380                 let mut sig = name_and_generics(text, offset, generics, self.id, self.ident, scx)?;
381
382                 sig.text.push('(');
383                 for i in &decl.inputs {
384                     // FIXME should descend into patterns to add defs.
385                     sig.text.push_str(&pprust::pat_to_string(&i.pat));
386                     sig.text.push_str(": ");
387                     let nested = i.ty.make(offset + sig.text.len(), Some(i.id), scx)?;
388                     sig.text.push_str(&nested.text);
389                     sig.text.push(',');
390                     sig.defs.extend(nested.defs.into_iter());
391                     sig.refs.extend(nested.refs.into_iter());
392                 }
393                 sig.text.push(')');
394
395                 if let ast::FunctionRetTy::Ty(ref t) = decl.output {
396                     sig.text.push_str(" -> ");
397                     let nested = t.make(offset + sig.text.len(), None, scx)?;
398                     sig.text.push_str(&nested.text);
399                     sig.defs.extend(nested.defs.into_iter());
400                     sig.refs.extend(nested.refs.into_iter());
401                 }
402                 sig.text.push_str(" {}");
403
404                 Ok(sig)
405             }
406             ast::ItemKind::Mod(ref _mod) => {
407                 let mut text = "mod ".to_owned();
408                 let name = self.ident.to_string();
409                 let defs = vec![SigElement {
410                     id: id_from_node_id(self.id, scx),
411                     start: offset + text.len(),
412                     end: offset + text.len() + name.len(),
413                 }];
414                 text.push_str(&name);
415                 // Could be either `mod foo;` or `mod foo { ... }`, but we'll just pick one.
416                 text.push(';');
417
418                 Ok(Signature { text, defs, refs: vec![] })
419             }
420             ast::ItemKind::TyAlias(ref ty, ref generics) => {
421                 let text = "type ".to_owned();
422                 let mut sig = name_and_generics(text, offset, generics, self.id, self.ident, scx)?;
423
424                 sig.text.push_str(" = ");
425                 let ty = ty.make(offset + sig.text.len(), id, scx)?;
426                 sig.text.push_str(&ty.text);
427                 sig.text.push(';');
428
429                 Ok(merge_sigs(sig.text.clone(), vec![sig, ty]))
430             }
431             ast::ItemKind::Enum(_, ref generics) => {
432                 let text = "enum ".to_owned();
433                 let mut sig = name_and_generics(text, offset, generics, self.id, self.ident, scx)?;
434                 sig.text.push_str(" {}");
435                 Ok(sig)
436             }
437             ast::ItemKind::Struct(_, ref generics) => {
438                 let text = "struct ".to_owned();
439                 let mut sig = name_and_generics(text, offset, generics, self.id, self.ident, scx)?;
440                 sig.text.push_str(" {}");
441                 Ok(sig)
442             }
443             ast::ItemKind::Union(_, ref generics) => {
444                 let text = "union ".to_owned();
445                 let mut sig = name_and_generics(text, offset, generics, self.id, self.ident, scx)?;
446                 sig.text.push_str(" {}");
447                 Ok(sig)
448             }
449             ast::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, _) => {
450                 let mut text = String::new();
451
452                 if is_auto == ast::IsAuto::Yes {
453                     text.push_str("auto ");
454                 }
455
456                 if unsafety == ast::Unsafety::Unsafe {
457                     text.push_str("unsafe ");
458                 }
459                 text.push_str("trait ");
460                 let mut sig = name_and_generics(text, offset, generics, self.id, self.ident, scx)?;
461
462                 if !bounds.is_empty() {
463                     sig.text.push_str(": ");
464                     sig.text.push_str(&pprust::bounds_to_string(bounds));
465                 }
466                 // FIXME where clause
467                 sig.text.push_str(" {}");
468
469                 Ok(sig)
470             }
471             ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
472                 let mut text = String::new();
473                 text.push_str("trait ");
474                 let mut sig = name_and_generics(text, offset, generics, self.id, self.ident, scx)?;
475
476                 if !bounds.is_empty() {
477                     sig.text.push_str(" = ");
478                     sig.text.push_str(&pprust::bounds_to_string(bounds));
479                 }
480                 // FIXME where clause
481                 sig.text.push_str(";");
482
483                 Ok(sig)
484             }
485             ast::ItemKind::Impl {
486                 unsafety,
487                 polarity,
488                 defaultness,
489                 ref generics,
490                 ref of_trait,
491                 ref self_ty,
492                 items: _,
493             } => {
494                 let mut text = String::new();
495                 if let ast::Defaultness::Default = defaultness {
496                     text.push_str("default ");
497                 }
498                 if unsafety == ast::Unsafety::Unsafe {
499                     text.push_str("unsafe ");
500                 }
501                 text.push_str("impl");
502
503                 let generics_sig = generics.make(offset + text.len(), id, scx)?;
504                 text.push_str(&generics_sig.text);
505
506                 text.push(' ');
507
508                 let trait_sig = if let Some(ref t) = *of_trait {
509                     if polarity == ast::ImplPolarity::Negative {
510                         text.push('!');
511                     }
512                     let trait_sig = t.path.make(offset + text.len(), id, scx)?;
513                     text.push_str(&trait_sig.text);
514                     text.push_str(" for ");
515                     trait_sig
516                 } else {
517                     text_sig(String::new())
518                 };
519
520                 let ty_sig = self_ty.make(offset + text.len(), id, scx)?;
521                 text.push_str(&ty_sig.text);
522
523                 text.push_str(" {}");
524
525                 Ok(merge_sigs(text, vec![generics_sig, trait_sig, ty_sig]))
526
527                 // FIXME where clause
528             }
529             ast::ItemKind::ForeignMod(_) => Err("extern mod"),
530             ast::ItemKind::GlobalAsm(_) => Err("glboal asm"),
531             ast::ItemKind::ExternCrate(_) => Err("extern crate"),
532             // FIXME should implement this (e.g., pub use).
533             ast::ItemKind::Use(_) => Err("import"),
534             ast::ItemKind::Mac(..) | ast::ItemKind::MacroDef(_) => Err("Macro"),
535         }
536     }
537 }
538
539 impl Sig for ast::Path {
540     fn make(&self, offset: usize, id: Option<NodeId>, scx: &SaveContext<'_, '_>) -> Result {
541         let res = scx.get_path_res(id.ok_or("Missing id for Path")?);
542
543         let (name, start, end) = match res {
544             Res::PrimTy(..) | Res::SelfTy(..) | Res::Err => {
545                 return Ok(Signature {
546                     text: pprust::path_to_string(self),
547                     defs: vec![],
548                     refs: vec![],
549                 });
550             }
551             Res::Def(DefKind::AssocConst, _)
552             | Res::Def(DefKind::Variant, _)
553             | Res::Def(DefKind::Ctor(..), _) => {
554                 let len = self.segments.len();
555                 if len < 2 {
556                     return Err("Bad path");
557                 }
558                 // FIXME: really we should descend into the generics here and add SigElements for
559                 // them.
560                 // FIXME: would be nice to have a def for the first path segment.
561                 let seg1 = pprust::path_segment_to_string(&self.segments[len - 2]);
562                 let seg2 = pprust::path_segment_to_string(&self.segments[len - 1]);
563                 let start = offset + seg1.len() + 2;
564                 (format!("{}::{}", seg1, seg2), start, start + seg2.len())
565             }
566             _ => {
567                 let name = pprust::path_segment_to_string(self.segments.last().ok_or("Bad path")?);
568                 let end = offset + name.len();
569                 (name, offset, end)
570             }
571         };
572
573         let id = id_from_def_id(res.def_id());
574         Ok(Signature { text: name, defs: vec![], refs: vec![SigElement { id, start, end }] })
575     }
576 }
577
578 // This does not cover the where clause, which must be processed separately.
579 impl Sig for ast::Generics {
580     fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext<'_, '_>) -> Result {
581         if self.params.is_empty() {
582             return Ok(text_sig(String::new()));
583         }
584
585         let mut text = "<".to_owned();
586
587         let mut defs = Vec::with_capacity(self.params.len());
588         for param in &self.params {
589             let mut param_text = String::new();
590             if let ast::GenericParamKind::Const { .. } = param.kind {
591                 param_text.push_str("const ");
592             }
593             param_text.push_str(&param.ident.as_str());
594             defs.push(SigElement {
595                 id: id_from_node_id(param.id, scx),
596                 start: offset + text.len(),
597                 end: offset + text.len() + param_text.as_str().len(),
598             });
599             if let ast::GenericParamKind::Const { ref ty } = param.kind {
600                 param_text.push_str(": ");
601                 param_text.push_str(&pprust::ty_to_string(&ty));
602             }
603             if !param.bounds.is_empty() {
604                 param_text.push_str(": ");
605                 match param.kind {
606                     ast::GenericParamKind::Lifetime { .. } => {
607                         let bounds = param
608                             .bounds
609                             .iter()
610                             .map(|bound| match bound {
611                                 ast::GenericBound::Outlives(lt) => lt.ident.to_string(),
612                                 _ => panic!(),
613                             })
614                             .collect::<Vec<_>>()
615                             .join(" + ");
616                         param_text.push_str(&bounds);
617                         // FIXME add lifetime bounds refs.
618                     }
619                     ast::GenericParamKind::Type { .. } => {
620                         param_text.push_str(&pprust::bounds_to_string(&param.bounds));
621                         // FIXME descend properly into bounds.
622                     }
623                     ast::GenericParamKind::Const { .. } => {
624                         // Const generics cannot contain bounds.
625                     }
626                 }
627             }
628             text.push_str(&param_text);
629             text.push(',');
630         }
631
632         text.push('>');
633         Ok(Signature { text, defs, refs: vec![] })
634     }
635 }
636
637 impl Sig for ast::StructField {
638     fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext<'_, '_>) -> Result {
639         let mut text = String::new();
640         let mut defs = None;
641         if let Some(ident) = self.ident {
642             text.push_str(&ident.to_string());
643             defs = Some(SigElement {
644                 id: id_from_node_id(self.id, scx),
645                 start: offset,
646                 end: offset + text.len(),
647             });
648             text.push_str(": ");
649         }
650
651         let mut ty_sig = self.ty.make(offset + text.len(), Some(self.id), scx)?;
652         text.push_str(&ty_sig.text);
653         ty_sig.text = text;
654         ty_sig.defs.extend(defs.into_iter());
655         Ok(ty_sig)
656     }
657 }
658
659 impl Sig for ast::Variant {
660     fn make(&self, offset: usize, parent_id: Option<NodeId>, scx: &SaveContext<'_, '_>) -> Result {
661         let mut text = self.ident.to_string();
662         match self.data {
663             ast::VariantData::Struct(ref fields, r) => {
664                 let id = parent_id.unwrap();
665                 let name_def = SigElement {
666                     id: id_from_node_id(id, scx),
667                     start: offset,
668                     end: offset + text.len(),
669                 };
670                 text.push_str(" { ");
671                 let mut defs = vec![name_def];
672                 let mut refs = vec![];
673                 if r {
674                     text.push_str("/* parse error */ ");
675                 } else {
676                     for f in fields {
677                         let field_sig = f.make(offset + text.len(), Some(id), scx)?;
678                         text.push_str(&field_sig.text);
679                         text.push_str(", ");
680                         defs.extend(field_sig.defs.into_iter());
681                         refs.extend(field_sig.refs.into_iter());
682                     }
683                 }
684                 text.push('}');
685                 Ok(Signature { text, defs, refs })
686             }
687             ast::VariantData::Tuple(ref fields, id) => {
688                 let name_def = SigElement {
689                     id: id_from_node_id(id, scx),
690                     start: offset,
691                     end: offset + text.len(),
692                 };
693                 text.push('(');
694                 let mut defs = vec![name_def];
695                 let mut refs = vec![];
696                 for f in fields {
697                     let field_sig = f.make(offset + text.len(), Some(id), scx)?;
698                     text.push_str(&field_sig.text);
699                     text.push_str(", ");
700                     defs.extend(field_sig.defs.into_iter());
701                     refs.extend(field_sig.refs.into_iter());
702                 }
703                 text.push(')');
704                 Ok(Signature { text, defs, refs })
705             }
706             ast::VariantData::Unit(id) => {
707                 let name_def = SigElement {
708                     id: id_from_node_id(id, scx),
709                     start: offset,
710                     end: offset + text.len(),
711                 };
712                 Ok(Signature { text, defs: vec![name_def], refs: vec![] })
713             }
714         }
715     }
716 }
717
718 impl Sig for ast::ForeignItem {
719     fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext<'_, '_>) -> Result {
720         let id = Some(self.id);
721         match self.kind {
722             ast::ForeignItemKind::Fn(ref decl, ref generics) => {
723                 let mut text = String::new();
724                 text.push_str("fn ");
725
726                 let mut sig = name_and_generics(text, offset, generics, self.id, self.ident, scx)?;
727
728                 sig.text.push('(');
729                 for i in &decl.inputs {
730                     // FIXME should descend into patterns to add defs.
731                     sig.text.push_str(&pprust::pat_to_string(&i.pat));
732                     sig.text.push_str(": ");
733                     let nested = i.ty.make(offset + sig.text.len(), Some(i.id), scx)?;
734                     sig.text.push_str(&nested.text);
735                     sig.text.push(',');
736                     sig.defs.extend(nested.defs.into_iter());
737                     sig.refs.extend(nested.refs.into_iter());
738                 }
739                 sig.text.push(')');
740
741                 if let ast::FunctionRetTy::Ty(ref t) = decl.output {
742                     sig.text.push_str(" -> ");
743                     let nested = t.make(offset + sig.text.len(), None, scx)?;
744                     sig.text.push_str(&nested.text);
745                     sig.defs.extend(nested.defs.into_iter());
746                     sig.refs.extend(nested.refs.into_iter());
747                 }
748                 sig.text.push(';');
749
750                 Ok(sig)
751             }
752             ast::ForeignItemKind::Static(ref ty, m) => {
753                 let mut text = "static ".to_owned();
754                 if m == ast::Mutability::Mut {
755                     text.push_str("mut ");
756                 }
757                 let name = self.ident.to_string();
758                 let defs = vec![SigElement {
759                     id: id_from_node_id(self.id, scx),
760                     start: offset + text.len(),
761                     end: offset + text.len() + name.len(),
762                 }];
763                 text.push_str(&name);
764                 text.push_str(": ");
765
766                 let ty_sig = ty.make(offset + text.len(), id, scx)?;
767                 text.push(';');
768
769                 Ok(extend_sig(ty_sig, text, defs, vec![]))
770             }
771             ast::ForeignItemKind::Ty => {
772                 let mut text = "type ".to_owned();
773                 let name = self.ident.to_string();
774                 let defs = vec![SigElement {
775                     id: id_from_node_id(self.id, scx),
776                     start: offset + text.len(),
777                     end: offset + text.len() + name.len(),
778                 }];
779                 text.push_str(&name);
780                 text.push(';');
781
782                 Ok(Signature { text: text, defs: defs, refs: vec![] })
783             }
784             ast::ForeignItemKind::Macro(..) => Err("macro"),
785         }
786     }
787 }
788
789 fn name_and_generics(
790     mut text: String,
791     offset: usize,
792     generics: &ast::Generics,
793     id: NodeId,
794     name: ast::Ident,
795     scx: &SaveContext<'_, '_>,
796 ) -> Result {
797     let name = name.to_string();
798     let def = SigElement {
799         id: id_from_node_id(id, scx),
800         start: offset + text.len(),
801         end: offset + text.len() + name.len(),
802     };
803     text.push_str(&name);
804     let generics: Signature = generics.make(offset + text.len(), Some(id), scx)?;
805     // FIXME where clause
806     let text = format!("{}{}", text, generics.text);
807     Ok(extend_sig(generics, text, vec![def], vec![]))
808 }
809
810 fn make_assoc_type_signature(
811     id: NodeId,
812     ident: ast::Ident,
813     bounds: Option<&ast::GenericBounds>,
814     default: Option<&ast::Ty>,
815     scx: &SaveContext<'_, '_>,
816 ) -> Result {
817     let mut text = "type ".to_owned();
818     let name = ident.to_string();
819     let mut defs = vec![SigElement {
820         id: id_from_node_id(id, scx),
821         start: text.len(),
822         end: text.len() + name.len(),
823     }];
824     let mut refs = vec![];
825     text.push_str(&name);
826     if let Some(bounds) = bounds {
827         text.push_str(": ");
828         // FIXME should descend into bounds
829         text.push_str(&pprust::bounds_to_string(bounds));
830     }
831     if let Some(default) = default {
832         text.push_str(" = ");
833         let ty_sig = default.make(text.len(), Some(id), scx)?;
834         text.push_str(&ty_sig.text);
835         defs.extend(ty_sig.defs.into_iter());
836         refs.extend(ty_sig.refs.into_iter());
837     }
838     text.push(';');
839     Ok(Signature { text, defs, refs })
840 }
841
842 fn make_assoc_const_signature(
843     id: NodeId,
844     ident: ast::Name,
845     ty: &ast::Ty,
846     default: Option<&ast::Expr>,
847     scx: &SaveContext<'_, '_>,
848 ) -> Result {
849     let mut text = "const ".to_owned();
850     let name = ident.to_string();
851     let mut defs = vec![SigElement {
852         id: id_from_node_id(id, scx),
853         start: text.len(),
854         end: text.len() + name.len(),
855     }];
856     let mut refs = vec![];
857     text.push_str(&name);
858     text.push_str(": ");
859
860     let ty_sig = ty.make(text.len(), Some(id), scx)?;
861     text.push_str(&ty_sig.text);
862     defs.extend(ty_sig.defs.into_iter());
863     refs.extend(ty_sig.refs.into_iter());
864
865     if let Some(default) = default {
866         text.push_str(" = ");
867         text.push_str(&pprust::expr_to_string(default));
868     }
869     text.push(';');
870     Ok(Signature { text, defs, refs })
871 }
872
873 fn make_method_signature(
874     id: NodeId,
875     ident: ast::Ident,
876     generics: &ast::Generics,
877     m: &ast::FnSig,
878     scx: &SaveContext<'_, '_>,
879 ) -> Result {
880     // FIXME code dup with function signature
881     let mut text = String::new();
882     if m.header.constness.node == ast::Constness::Const {
883         text.push_str("const ");
884     }
885     if m.header.asyncness.node.is_async() {
886         text.push_str("async ");
887     }
888     if m.header.unsafety == ast::Unsafety::Unsafe {
889         text.push_str("unsafe ");
890     }
891     push_extern(&mut text, m.header.ext);
892     text.push_str("fn ");
893
894     let mut sig = name_and_generics(text, 0, generics, id, ident, scx)?;
895
896     sig.text.push('(');
897     for i in &m.decl.inputs {
898         // FIXME should descend into patterns to add defs.
899         sig.text.push_str(&pprust::pat_to_string(&i.pat));
900         sig.text.push_str(": ");
901         let nested = i.ty.make(sig.text.len(), Some(i.id), scx)?;
902         sig.text.push_str(&nested.text);
903         sig.text.push(',');
904         sig.defs.extend(nested.defs.into_iter());
905         sig.refs.extend(nested.refs.into_iter());
906     }
907     sig.text.push(')');
908
909     if let ast::FunctionRetTy::Ty(ref t) = m.decl.output {
910         sig.text.push_str(" -> ");
911         let nested = t.make(sig.text.len(), None, scx)?;
912         sig.text.push_str(&nested.text);
913         sig.defs.extend(nested.defs.into_iter());
914         sig.refs.extend(nested.refs.into_iter());
915     }
916     sig.text.push_str(" {}");
917
918     Ok(sig)
919 }