sig.rs 34.0 KB
Newer Older
N
Nick Cameron 已提交
1 2 3 4 5 6 7 8 9 10
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

N
Nick Cameron 已提交
11 12 13 14 15 16
// A signature is a string representation of an item's type signature, excluding
// any body. It also includes ids for any defs or refs in the signature. For
// example:
//
// ```
// fn foo(x: String) {
N
Nick Cameron 已提交
17
//     println!("{}", x);
N
Nick Cameron 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
// }
// ```
// The signature string is something like "fn foo(x: String) {}" and the signature
// will have defs for `foo` and `x` and a ref for `String`.
//
// All signature text should parse in the correct context (i.e., in a module or
// impl, etc.). Clients may want to trim trailing `{}` or `;`. The text of a
// signature is not guaranteed to be stable (it may improve or change as the
// syntax changes, or whitespace or punctuation may change). It is also likely
// not to be pretty - no attempt is made to prettify the text. It is recommended
// that clients run the text through Rustfmt.
//
// This module generates Signatures for items by walking the AST and looking up
// references.
//
// Signatures do not include visibility info. I'm not sure if this is a feature
// or an ommission (FIXME).
//
// FIXME where clauses need implementing, defs/refs in generics are mostly missing.
N
Nick Cameron 已提交
37

N
Nick Cameron 已提交
38
use {id_from_def_id, id_from_node_id, SaveContext};
N
Nick Cameron 已提交
39

N
Nick Cameron 已提交
40
use rls_data::{SigElement, Signature};
N
Nick Cameron 已提交
41 42 43 44 45 46

use rustc::hir::def::Def;
use syntax::ast::{self, NodeId};
use syntax::print::pprust;


N
Nick Cameron 已提交
47
pub fn item_signature(item: &ast::Item, scx: &SaveContext) -> Option<Signature> {
N
Nick Cameron 已提交
48 49 50
    if !scx.config.signatures {
        return None;
    }
N
Nick Cameron 已提交
51 52 53
    item.make(0, None, scx).ok()
}

54
pub fn foreign_item_signature(item: &ast::ForeignItem, scx: &SaveContext) -> Option<Signature> {
N
Nick Cameron 已提交
55 56 57
    if !scx.config.signatures {
        return None;
    }
58 59 60 61 62 63
    item.make(0, None, scx).ok()
}

/// Signature for a struct or tuple field declaration.
/// Does not include a trailing comma.
pub fn field_signature(field: &ast::StructField, scx: &SaveContext) -> Option<Signature> {
N
Nick Cameron 已提交
64 65 66
    if !scx.config.signatures {
        return None;
    }
67 68 69 70 71
    field.make(0, None, scx).ok()
}

/// Does not include a trailing comma.
pub fn variant_signature(variant: &ast::Variant, scx: &SaveContext) -> Option<Signature> {
N
Nick Cameron 已提交
72 73 74
    if !scx.config.signatures {
        return None;
    }
75 76 77
    variant.node.make(0, None, scx).ok()
}

N
Nick Cameron 已提交
78 79 80 81 82 83 84
pub fn method_signature(
    id: NodeId,
    ident: ast::Ident,
    generics: &ast::Generics,
    m: &ast::MethodSig,
    scx: &SaveContext,
) -> Option<Signature> {
N
Nick Cameron 已提交
85 86 87
    if !scx.config.signatures {
        return None;
    }
88
    make_method_signature(id, ident, generics, m, scx).ok()
N
Nick Cameron 已提交
89 90
}

N
Nick Cameron 已提交
91 92 93 94 95 96 97
pub fn assoc_const_signature(
    id: NodeId,
    ident: ast::Name,
    ty: &ast::Ty,
    default: Option<&ast::Expr>,
    scx: &SaveContext,
) -> Option<Signature> {
N
Nick Cameron 已提交
98 99 100
    if !scx.config.signatures {
        return None;
    }
N
Nick Cameron 已提交
101 102 103
    make_assoc_const_signature(id, ident, ty, default, scx).ok()
}

N
Nick Cameron 已提交
104 105 106 107 108 109 110
pub fn assoc_type_signature(
    id: NodeId,
    ident: ast::Ident,
    bounds: Option<&ast::TyParamBounds>,
    default: Option<&ast::Ty>,
    scx: &SaveContext,
) -> Option<Signature> {
N
Nick Cameron 已提交
111 112 113
    if !scx.config.signatures {
        return None;
    }
N
Nick Cameron 已提交
114 115 116
    make_assoc_type_signature(id, ident, bounds, default, scx).ok()
}

N
Nick Cameron 已提交
117 118 119 120 121 122
type Result = ::std::result::Result<Signature, &'static str>;

trait Sig {
    fn make(&self, offset: usize, id: Option<NodeId>, scx: &SaveContext) -> Result;
}

N
Nick Cameron 已提交
123 124 125 126 127 128
fn extend_sig(
    mut sig: Signature,
    text: String,
    defs: Vec<SigElement>,
    refs: Vec<SigElement>,
) -> Signature {
N
Nick Cameron 已提交
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
    sig.text = text;
    sig.defs.extend(defs.into_iter());
    sig.refs.extend(refs.into_iter());
    sig
}

fn replace_text(mut sig: Signature, text: String) -> Signature {
    sig.text = text;
    sig
}

fn merge_sigs(text: String, sigs: Vec<Signature>) -> Signature {
    let mut result = Signature {
        text,
        defs: vec![],
        refs: vec![],
    };

    let (defs, refs): (Vec<_>, Vec<_>) = sigs.into_iter().map(|s| (s.defs, s.refs)).unzip();

N
Nick Cameron 已提交
149 150 151 152 153 154
    result
        .defs
        .extend(defs.into_iter().flat_map(|ds| ds.into_iter()));
    result
        .refs
        .extend(refs.into_iter().flat_map(|rs| rs.into_iter()));
N
Nick Cameron 已提交
155 156 157 158 159 160

    result
}

fn text_sig(text: String) -> Signature {
    Signature {
161
        text,
N
Nick Cameron 已提交
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
        defs: vec![],
        refs: vec![],
    }
}

impl Sig for ast::Ty {
    fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext) -> Result {
        let id = Some(self.id);
        match self.node {
            ast::TyKind::Slice(ref ty) => {
                let nested = ty.make(offset + 1, id, scx)?;
                let text = format!("[{}]", nested.text);
                Ok(replace_text(nested, text))
            }
            ast::TyKind::Ptr(ref mt) => {
                let prefix = match mt.mutbl {
                    ast::Mutability::Mutable => "*mut ",
                    ast::Mutability::Immutable => "*const ",
                };
                let nested = mt.ty.make(offset + prefix.len(), id, scx)?;
                let text = format!("{}{}", prefix, nested.text);
                Ok(replace_text(nested, text))
            }
            ast::TyKind::Rptr(ref lifetime, ref mt) => {
                let mut prefix = "&".to_owned();
                if let &Some(ref l) = lifetime {
                    prefix.push_str(&l.ident.to_string());
                    prefix.push(' ');
                }
                if let ast::Mutability::Mutable = mt.mutbl {
                    prefix.push_str("mut ");
                };

                let nested = mt.ty.make(offset + prefix.len(), id, scx)?;
                let text = format!("{}{}", prefix, nested.text);
                Ok(replace_text(nested, text))
            }
N
Nick Cameron 已提交
199
            ast::TyKind::Never => Ok(text_sig("!".to_owned())),
N
Nick Cameron 已提交
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
            ast::TyKind::Tup(ref ts) => {
                let mut text = "(".to_owned();
                let mut defs = vec![];
                let mut refs = vec![];
                for t in ts {
                    let nested = t.make(offset + text.len(), id, scx)?;
                    text.push_str(&nested.text);
                    text.push(',');
                    defs.extend(nested.defs.into_iter());
                    refs.extend(nested.refs.into_iter());
                }
                text.push(')');
                Ok(Signature { text, defs, refs })
            }
            ast::TyKind::Paren(ref ty) => {
                let nested = ty.make(offset + 1, id, scx)?;
                let text = format!("({})", nested.text);
                Ok(replace_text(nested, text))
            }
            ast::TyKind::BareFn(ref f) => {
                let mut text = String::new();
                if !f.lifetimes.is_empty() {
                    // FIXME defs, bounds on lifetimes
                    text.push_str("for<");
N
Nick Cameron 已提交
224 225 226 227 228
                    text.push_str(&f.lifetimes
                        .iter()
                        .map(|l| l.lifetime.ident.to_string())
                        .collect::<Vec<_>>()
                        .join(", "));
N
Nick Cameron 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
                    text.push('>');
                }

                if f.unsafety == ast::Unsafety::Unsafe {
                    text.push_str("unsafe ");
                }
                if f.abi != ::syntax::abi::Abi::Rust {
                    text.push_str("extern");
                    text.push_str(&f.abi.to_string());
                    text.push(' ');
                }
                text.push_str("fn(");

                let mut defs = vec![];
                let mut refs = vec![];
                for i in &f.decl.inputs {
                    let nested = i.ty.make(offset + text.len(), Some(i.id), scx)?;
                    text.push_str(&nested.text);
                    text.push(',');
                    defs.extend(nested.defs.into_iter());
                    refs.extend(nested.refs.into_iter());
                }
                text.push(')');
                if let ast::FunctionRetTy::Ty(ref t) = f.decl.output {
                    text.push_str(" -> ");
                    let nested = t.make(offset + text.len(), None, scx)?;
                    text.push_str(&nested.text);
                    text.push(',');
                    defs.extend(nested.defs.into_iter());
                    refs.extend(nested.refs.into_iter());
                }

                Ok(Signature { text, defs, refs })
            }
N
Nick Cameron 已提交
263
            ast::TyKind::Path(None, ref path) => path.make(offset, id, scx),
N
Nick Cameron 已提交
264 265 266 267 268 269 270 271 272
            ast::TyKind::Path(Some(ref qself), ref path) => {
                let nested_ty = qself.ty.make(offset + 1, id, scx)?;
                let prefix = if qself.position == 0 {
                    format!("<{}>::", nested_ty.text)
                } else if qself.position == 1 {
                    let first = pprust::path_segment_to_string(&path.segments[0]);
                    format!("<{} as {}>::", nested_ty.text, first)
                } else {
                    // FIXME handle path instead of elipses.
N
Nick Cameron 已提交
273
                    format!("<{} as ...>::", nested_ty.text)
N
Nick Cameron 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
                };

                let name = pprust::path_segment_to_string(path.segments.last().ok_or("Bad path")?);
                let def = scx.get_path_def(id.ok_or("Missing id for Path")?);
                let id = id_from_def_id(def.def_id());
                if path.segments.len() - qself.position == 1 {
                    let start = offset + prefix.len();
                    let end = start + name.len();

                    Ok(Signature {
                        text: prefix + &name,
                        defs: vec![],
                        refs: vec![SigElement { id, start, end }],
                    })
                } else {
                    let start = offset + prefix.len() + 5;
                    let end = start + name.len();
                    // FIXME should put the proper path in there, not elipses.
                    Ok(Signature {
                        text: prefix + "...::" + &name,
                        defs: vec![],
                        refs: vec![SigElement { id, start, end }],
                    })
                }
            }
V
Vadim Petrochenkov 已提交
299
            ast::TyKind::TraitObject(ref bounds, ..) => {
N
Nick Cameron 已提交
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
                // FIXME recurse into bounds
                let nested = pprust::bounds_to_string(bounds);
                Ok(text_sig(nested))
            }
            ast::TyKind::ImplTrait(ref bounds) => {
                // FIXME recurse into bounds
                let nested = pprust::bounds_to_string(bounds);
                Ok(text_sig(format!("impl {}", nested)))
            }
            ast::TyKind::Array(ref ty, ref v) => {
                let nested_ty = ty.make(offset + 1, id, scx)?;
                let expr = pprust::expr_to_string(v).replace('\n', " ");
                let text = format!("[{}; {}]", nested_ty.text, expr);
                Ok(replace_text(nested_ty, text))
            }
            ast::TyKind::Typeof(_) |
            ast::TyKind::Infer |
            ast::TyKind::Err |
            ast::TyKind::ImplicitSelf |
            ast::TyKind::Mac(_) => Err("Ty"),
        }
N
Nick Cameron 已提交
321
    }
N
Nick Cameron 已提交
322 323 324 325 326 327 328 329 330 331 332 333 334
}

impl Sig for ast::Item {
    fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext) -> Result {
        let id = Some(self.id);

        match self.node {
            ast::ItemKind::Static(ref ty, m, ref expr) => {
                let mut text = "static ".to_owned();
                if m == ast::Mutability::Mutable {
                    text.push_str("mut ");
                }
                let name = self.ident.to_string();
N
Nick Cameron 已提交
335 336 337 338 339 340 341
                let defs = vec![
                    SigElement {
                        id: id_from_node_id(self.id, scx),
                        start: offset + text.len(),
                        end: offset + text.len() + name.len(),
                    },
                ];
N
Nick Cameron 已提交
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
                text.push_str(&name);
                text.push_str(": ");

                let ty = ty.make(offset + text.len(), id, scx)?;
                text.push_str(&ty.text);
                text.push_str(" = ");

                let expr = pprust::expr_to_string(expr).replace('\n', " ");
                text.push_str(&expr);
                text.push(';');

                Ok(extend_sig(ty, text, defs, vec![]))
            }
            ast::ItemKind::Const(ref ty, ref expr) => {
                let mut text = "const ".to_owned();
                let name = self.ident.to_string();
N
Nick Cameron 已提交
358 359 360 361 362 363 364
                let defs = vec![
                    SigElement {
                        id: id_from_node_id(self.id, scx),
                        start: offset + text.len(),
                        end: offset + text.len() + name.len(),
                    },
                ];
N
Nick Cameron 已提交
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
                text.push_str(&name);
                text.push_str(": ");

                let ty = ty.make(offset + text.len(), id, scx)?;
                text.push_str(&ty.text);
                text.push_str(" = ");

                let expr = pprust::expr_to_string(expr).replace('\n', " ");
                text.push_str(&expr);
                text.push(';');

                Ok(extend_sig(ty, text, defs, vec![]))
            }
            ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, _) => {
                let mut text = String::new();
                if constness.node == ast::Constness::Const {
                    text.push_str("const ");
                }
                if unsafety == ast::Unsafety::Unsafe {
                    text.push_str("unsafe ");
                }
                if abi != ::syntax::abi::Abi::Rust {
                    text.push_str("extern");
                    text.push_str(&abi.to_string());
                    text.push(' ');
                }
                text.push_str("fn ");

N
Nick Cameron 已提交
393
                let mut sig = name_and_generics(text, offset, generics, self.id, self.ident, scx)?;
N
Nick Cameron 已提交
394 395 396

                sig.text.push('(');
                for i in &decl.inputs {
B
Bastien Orivel 已提交
397
                    // FIXME should descend into patterns to add defs.
N
Nick Cameron 已提交
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
                    sig.text.push_str(&pprust::pat_to_string(&i.pat));
                    sig.text.push_str(": ");
                    let nested = i.ty.make(offset + sig.text.len(), Some(i.id), scx)?;
                    sig.text.push_str(&nested.text);
                    sig.text.push(',');
                    sig.defs.extend(nested.defs.into_iter());
                    sig.refs.extend(nested.refs.into_iter());
                }
                sig.text.push(')');

                if let ast::FunctionRetTy::Ty(ref t) = decl.output {
                    sig.text.push_str(" -> ");
                    let nested = t.make(offset + sig.text.len(), None, scx)?;
                    sig.text.push_str(&nested.text);
                    sig.defs.extend(nested.defs.into_iter());
                    sig.refs.extend(nested.refs.into_iter());
                }
415
                sig.text.push_str(" {}");
N
Nick Cameron 已提交
416 417 418 419 420 421

                Ok(sig)
            }
            ast::ItemKind::Mod(ref _mod) => {
                let mut text = "mod ".to_owned();
                let name = self.ident.to_string();
N
Nick Cameron 已提交
422 423 424 425 426 427 428
                let defs = vec![
                    SigElement {
                        id: id_from_node_id(self.id, scx),
                        start: offset + text.len(),
                        end: offset + text.len() + name.len(),
                    },
                ];
N
Nick Cameron 已提交
429 430 431 432 433 434 435 436 437 438 439 440
                text.push_str(&name);
                // Could be either `mod foo;` or `mod foo { ... }`, but we'll just puck one.
                text.push(';');

                Ok(Signature {
                    text,
                    defs,
                    refs: vec![],
                })
            }
            ast::ItemKind::Ty(ref ty, ref generics) => {
                let text = "type ".to_owned();
N
Nick Cameron 已提交
441
                let mut sig = name_and_generics(text, offset, generics, self.id, self.ident, scx)?;
N
Nick Cameron 已提交
442 443 444 445 446 447 448 449 450 451

                sig.text.push_str(" = ");
                let ty = ty.make(offset + sig.text.len(), id, scx)?;
                sig.text.push_str(&ty.text);
                sig.text.push(';');

                Ok(merge_sigs(sig.text.clone(), vec![sig, ty]))
            }
            ast::ItemKind::Enum(_, ref generics) => {
                let text = "enum ".to_owned();
N
Nick Cameron 已提交
452
                let mut sig = name_and_generics(text, offset, generics, self.id, self.ident, scx)?;
N
Nick Cameron 已提交
453 454 455 456 457
                sig.text.push_str(" {}");
                Ok(sig)
            }
            ast::ItemKind::Struct(_, ref generics) => {
                let text = "struct ".to_owned();
N
Nick Cameron 已提交
458
                let mut sig = name_and_generics(text, offset, generics, self.id, self.ident, scx)?;
N
Nick Cameron 已提交
459 460 461 462 463
                sig.text.push_str(" {}");
                Ok(sig)
            }
            ast::ItemKind::Union(_, ref generics) => {
                let text = "union ".to_owned();
N
Nick Cameron 已提交
464
                let mut sig = name_and_generics(text, offset, generics, self.id, self.ident, scx)?;
N
Nick Cameron 已提交
465 466 467
                sig.text.push_str(" {}");
                Ok(sig)
            }
468
            ast::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, _) => {
N
Nick Cameron 已提交
469
                let mut text = String::new();
470 471 472 473 474

                if is_auto == ast::IsAuto::Yes {
                    text.push_str("auto ");
                }

N
Nick Cameron 已提交
475 476 477 478
                if unsafety == ast::Unsafety::Unsafe {
                    text.push_str("unsafe ");
                }
                text.push_str("trait ");
N
Nick Cameron 已提交
479
                let mut sig = name_and_generics(text, offset, generics, self.id, self.ident, scx)?;
N
Nick Cameron 已提交
480 481 482 483 484 485 486 487 488 489

                if !bounds.is_empty() {
                    sig.text.push_str(": ");
                    sig.text.push_str(&pprust::bounds_to_string(bounds));
                }
                // FIXME where clause
                sig.text.push_str(" {}");

                Ok(sig)
            }
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
            ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
                let mut text = String::new();
                text.push_str("trait ");
                let mut sig = name_and_generics(text,
                                                offset,
                                                generics,
                                                self.id,
                                                self.ident,
                                                scx)?;

                if !bounds.is_empty() {
                    sig.text.push_str(" = ");
                    sig.text.push_str(&pprust::bounds_to_string(bounds));
                }
                // FIXME where clause
                sig.text.push_str(";");

                Ok(sig)
            }
509
            ast::ItemKind::AutoImpl(unsafety, ref trait_ref) => {
N
Nick Cameron 已提交
510 511 512 513 514 515 516 517 518 519
                let mut text = String::new();
                if unsafety == ast::Unsafety::Unsafe {
                    text.push_str("unsafe ");
                }
                text.push_str("impl ");
                let trait_sig = trait_ref.path.make(offset + text.len(), id, scx)?;
                text.push_str(&trait_sig.text);
                text.push_str(" for .. {}");
                Ok(replace_text(trait_sig, text))
            }
N
Nick Cameron 已提交
520 521 522 523 524 525 526 527 528
            ast::ItemKind::Impl(
                unsafety,
                polarity,
                defaultness,
                ref generics,
                ref opt_trait,
                ref ty,
                _,
            ) => {
N
Nick Cameron 已提交
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
                let mut text = String::new();
                if let ast::Defaultness::Default = defaultness {
                    text.push_str("default ");
                }
                if unsafety == ast::Unsafety::Unsafe {
                    text.push_str("unsafe ");
                }
                text.push_str("impl");

                let generics_sig = generics.make(offset + text.len(), id, scx)?;
                text.push_str(&generics_sig.text);

                text.push(' ');

                let trait_sig = if let Some(ref t) = *opt_trait {
                    if polarity == ast::ImplPolarity::Negative {
                        text.push('!');
                    }
                    let trait_sig = t.path.make(offset + text.len(), id, scx)?;
                    text.push_str(&trait_sig.text);
                    text.push_str(" for ");
                    trait_sig
                } else {
                    text_sig(String::new())
                };

                let ty_sig = ty.make(offset + text.len(), id, scx)?;
                text.push_str(&ty_sig.text);
N
Nick Cameron 已提交
557

N
Nick Cameron 已提交
558 559 560 561 562 563 564 565 566 567 568
                text.push_str(" {}");

                Ok(merge_sigs(text, vec![generics_sig, trait_sig, ty_sig]))

                // FIXME where clause
            }
            ast::ItemKind::ForeignMod(_) => Err("extern mod"),
            ast::ItemKind::GlobalAsm(_) => Err("glboal asm"),
            ast::ItemKind::ExternCrate(_) => Err("extern crate"),
            // FIXME should implement this (e.g., pub use).
            ast::ItemKind::Use(_) => Err("import"),
N
Nick Cameron 已提交
569
            ast::ItemKind::Mac(..) | ast::ItemKind::MacroDef(_) => Err("Macro"),
N
Nick Cameron 已提交
570 571 572 573 574 575 576 577 578
        }
    }
}

impl Sig for ast::Path {
    fn make(&self, offset: usize, id: Option<NodeId>, scx: &SaveContext) -> Result {
        let def = scx.get_path_def(id.ok_or("Missing id for Path")?);

        let (name, start, end) = match def {
N
Nick Cameron 已提交
579
            Def::Label(..) | Def::PrimTy(..) | Def::SelfTy(..) | Def::Err => {
N
Nick Cameron 已提交
580 581 582 583 584 585
                return Ok(Signature {
                    text: pprust::path_to_string(self),
                    defs: vec![],
                    refs: vec![],
                })
            }
N
Nick Cameron 已提交
586
            Def::AssociatedConst(..) | Def::Variant(..) | Def::VariantCtor(..) => {
N
Nick Cameron 已提交
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
                let len = self.segments.len();
                if len < 2 {
                    return Err("Bad path");
                }
                // FIXME: really we should descend into the generics here and add SigElements for
                // them.
                // FIXME: would be nice to have a def for the first path segment.
                let seg1 = pprust::path_segment_to_string(&self.segments[len - 2]);
                let seg2 = pprust::path_segment_to_string(&self.segments[len - 1]);
                let start = offset + seg1.len() + 2;
                (format!("{}::{}", seg1, seg2), start, start + seg2.len())
            }
            _ => {
                let name = pprust::path_segment_to_string(self.segments.last().ok_or("Bad path")?);
                let end = offset + name.len();
                (name, offset, end)
            }
        };

N
Nick Cameron 已提交
606
        let id = id_from_def_id(def.def_id());
N
Nick Cameron 已提交
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
        Ok(Signature {
            text: name,
            defs: vec![],
            refs: vec![SigElement { id, start, end }],
        })
    }
}

// This does not cover the where clause, which must be processed separately.
impl Sig for ast::Generics {
    fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext) -> Result {
        let total = self.lifetimes.len() + self.ty_params.len();
        if total == 0 {
            return Ok(text_sig(String::new()));
        }

        let mut text = "<".to_owned();

        let mut defs = vec![];
        for l in &self.lifetimes {
            let mut l_text = l.lifetime.ident.to_string();
            defs.push(SigElement {
                id: id_from_node_id(l.lifetime.id, scx),
                start: offset + text.len(),
                end: offset + text.len() + l_text.len(),
            });

            if !l.bounds.is_empty() {
                l_text.push_str(": ");
N
Nick Cameron 已提交
636 637 638 639 640
                let bounds = l.bounds
                    .iter()
                    .map(|l| l.ident.to_string())
                    .collect::<Vec<_>>()
                    .join(" + ");
N
Nick Cameron 已提交
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
                l_text.push_str(&bounds);
                // FIXME add lifetime bounds refs.
            }
            text.push_str(&l_text);
            text.push(',');
        }
        for t in &self.ty_params {
            let mut t_text = t.ident.to_string();
            defs.push(SigElement {
                id: id_from_node_id(t.id, scx),
                start: offset + text.len(),
                end: offset + text.len() + t_text.len(),
            });

            if !t.bounds.is_empty() {
                t_text.push_str(": ");
                t_text.push_str(&pprust::bounds_to_string(&t.bounds));
                // FIXME descend properly into bounds.
            }
            text.push_str(&t_text);
            text.push(',');
        }

        text.push('>');
N
Nick Cameron 已提交
665 666 667 668 669
        Ok(Signature {
            text,
            defs,
            refs: vec![],
        })
N
Nick Cameron 已提交
670 671 672
    }
}

673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
impl Sig for ast::StructField {
    fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext) -> Result {
        let mut text = String::new();
        let mut defs = None;
        if let Some(ref ident) = self.ident {
            text.push_str(&ident.to_string());
            defs = Some(SigElement {
                id: id_from_node_id(self.id, scx),
                start: offset,
                end: offset + text.len(),
            });
            text.push_str(": ");
        }

        let mut ty_sig = self.ty.make(offset + text.len(), Some(self.id), scx)?;
        text.push_str(&ty_sig.text);
        ty_sig.text = text;
        ty_sig.defs.extend(defs.into_iter());
        Ok(ty_sig)
    }
}


impl Sig for ast::Variant_ {
    fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext) -> Result {
        let mut text = self.name.to_string();
        match self.data {
            ast::VariantData::Struct(ref fields, id) => {
                let name_def = SigElement {
                    id: id_from_node_id(id, scx),
                    start: offset,
                    end: offset + text.len(),
                };
                text.push_str(" { ");
                let mut defs = vec![name_def];
                let mut refs = vec![];
                for f in fields {
                    let field_sig = f.make(offset + text.len(), Some(id), scx)?;
                    text.push_str(&field_sig.text);
                    text.push_str(", ");
                    defs.extend(field_sig.defs.into_iter());
                    refs.extend(field_sig.refs.into_iter());
                }
                text.push('}');
N
Nick Cameron 已提交
717
                Ok(Signature { text, defs, refs })
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
            }
            ast::VariantData::Tuple(ref fields, id) => {
                let name_def = SigElement {
                    id: id_from_node_id(id, scx),
                    start: offset,
                    end: offset + text.len(),
                };
                text.push('(');
                let mut defs = vec![name_def];
                let mut refs = vec![];
                for f in fields {
                    let field_sig = f.make(offset + text.len(), Some(id), scx)?;
                    text.push_str(&field_sig.text);
                    text.push_str(", ");
                    defs.extend(field_sig.defs.into_iter());
                    refs.extend(field_sig.refs.into_iter());
                }
                text.push(')');
N
Nick Cameron 已提交
736
                Ok(Signature { text, defs, refs })
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
            }
            ast::VariantData::Unit(id) => {
                let name_def = SigElement {
                    id: id_from_node_id(id, scx),
                    start: offset,
                    end: offset + text.len(),
                };
                Ok(Signature {
                    text,
                    defs: vec![name_def],
                    refs: vec![],
                })
            }
        }
    }
}

impl Sig for ast::ForeignItem {
    fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext) -> Result {
        let id = Some(self.id);
        match self.node {
            ast::ForeignItemKind::Fn(ref decl, ref generics) => {
                let mut text = String::new();
                text.push_str("fn ");

N
Nick Cameron 已提交
762
                let mut sig = name_and_generics(text, offset, generics, self.id, self.ident, scx)?;
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793

                sig.text.push('(');
                for i in &decl.inputs {
                    // FIXME should descend into patterns to add defs.
                    sig.text.push_str(&pprust::pat_to_string(&i.pat));
                    sig.text.push_str(": ");
                    let nested = i.ty.make(offset + sig.text.len(), Some(i.id), scx)?;
                    sig.text.push_str(&nested.text);
                    sig.text.push(',');
                    sig.defs.extend(nested.defs.into_iter());
                    sig.refs.extend(nested.refs.into_iter());
                }
                sig.text.push(')');

                if let ast::FunctionRetTy::Ty(ref t) = decl.output {
                    sig.text.push_str(" -> ");
                    let nested = t.make(offset + sig.text.len(), None, scx)?;
                    sig.text.push_str(&nested.text);
                    sig.defs.extend(nested.defs.into_iter());
                    sig.refs.extend(nested.refs.into_iter());
                }
                sig.text.push(';');

                Ok(sig)
            }
            ast::ForeignItemKind::Static(ref ty, m) => {
                let mut text = "static ".to_owned();
                if m {
                    text.push_str("mut ");
                }
                let name = self.ident.to_string();
N
Nick Cameron 已提交
794 795 796 797 798 799 800
                let defs = vec![
                    SigElement {
                        id: id_from_node_id(self.id, scx),
                        start: offset + text.len(),
                        end: offset + text.len() + name.len(),
                    },
                ];
801 802 803 804 805 806 807 808
                text.push_str(&name);
                text.push_str(": ");

                let ty_sig = ty.make(offset + text.len(), id, scx)?;
                text.push(';');

                Ok(extend_sig(ty_sig, text, defs, vec![]))
            }
P
Paul Lietar 已提交
809 810 811
            ast::ForeignItemKind::Ty => {
                let mut text = "type ".to_owned();
                let name = self.ident.to_string();
N
Nick Cameron 已提交
812 813 814 815 816 817 818
                let defs = vec![
                    SigElement {
                        id: id_from_node_id(self.id, scx),
                        start: offset + text.len(),
                        end: offset + text.len() + name.len(),
                    },
                ];
P
Paul Lietar 已提交
819 820 821 822 823 824 825 826 827
                text.push_str(&name);
                text.push(';');

                Ok(Signature {
                    text: text,
                    defs: defs,
                    refs: vec![],
                })
            }
828 829 830 831
        }
    }
}

N
Nick Cameron 已提交
832 833 834 835 836 837 838 839
fn name_and_generics(
    mut text: String,
    offset: usize,
    generics: &ast::Generics,
    id: NodeId,
    name: ast::Ident,
    scx: &SaveContext,
) -> Result {
840 841 842 843 844 845 846 847 848 849 850 851 852 853
    let name = name.to_string();
    let def = SigElement {
        id: id_from_node_id(id, scx),
        start: offset + text.len(),
        end: offset + text.len() + name.len(),
    };
    text.push_str(&name);
    let generics: Signature = generics.make(offset + text.len(), Some(id), scx)?;
    // FIXME where clause
    let text = format!("{}{}", text, generics.text);
    Ok(extend_sig(generics, text, vec![def], vec![]))
}


N
Nick Cameron 已提交
854 855 856 857 858 859 860
fn make_assoc_type_signature(
    id: NodeId,
    ident: ast::Ident,
    bounds: Option<&ast::TyParamBounds>,
    default: Option<&ast::Ty>,
    scx: &SaveContext,
) -> Result {
N
Nick Cameron 已提交
861 862
    let mut text = "type ".to_owned();
    let name = ident.to_string();
N
Nick Cameron 已提交
863 864 865 866 867 868 869
    let mut defs = vec![
        SigElement {
            id: id_from_node_id(id, scx),
            start: text.len(),
            end: text.len() + name.len(),
        },
    ];
N
Nick Cameron 已提交
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
    let mut refs = vec![];
    text.push_str(&name);
    if let Some(bounds) = bounds {
        text.push_str(": ");
        // FIXME should descend into bounds
        text.push_str(&pprust::bounds_to_string(bounds));
    }
    if let Some(default) = default {
        text.push_str(" = ");
        let ty_sig = default.make(text.len(), Some(id), scx)?;
        text.push_str(&ty_sig.text);
        defs.extend(ty_sig.defs.into_iter());
        refs.extend(ty_sig.refs.into_iter());
    }
    text.push(';');
    Ok(Signature { text, defs, refs })
}

N
Nick Cameron 已提交
888 889 890 891 892 893 894
fn make_assoc_const_signature(
    id: NodeId,
    ident: ast::Name,
    ty: &ast::Ty,
    default: Option<&ast::Expr>,
    scx: &SaveContext,
) -> Result {
N
Nick Cameron 已提交
895 896
    let mut text = "const ".to_owned();
    let name = ident.to_string();
N
Nick Cameron 已提交
897 898 899 900 901 902 903
    let mut defs = vec![
        SigElement {
            id: id_from_node_id(id, scx),
            start: text.len(),
            end: text.len() + name.len(),
        },
    ];
N
Nick Cameron 已提交
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
    let mut refs = vec![];
    text.push_str(&name);
    text.push_str(": ");

    let ty_sig = ty.make(text.len(), Some(id), scx)?;
    text.push_str(&ty_sig.text);
    defs.extend(ty_sig.defs.into_iter());
    refs.extend(ty_sig.refs.into_iter());

    if let Some(default) = default {
        text.push_str(" = ");
        text.push_str(&pprust::expr_to_string(default));
    }
    text.push(';');
    Ok(Signature { text, defs, refs })
}

N
Nick Cameron 已提交
921 922 923 924 925 926 927
fn make_method_signature(
    id: NodeId,
    ident: ast::Ident,
    generics: &ast::Generics,
    m: &ast::MethodSig,
    scx: &SaveContext,
) -> Result {
N
Nick Cameron 已提交
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
    // FIXME code dup with function signature
    let mut text = String::new();
    if m.constness.node == ast::Constness::Const {
        text.push_str("const ");
    }
    if m.unsafety == ast::Unsafety::Unsafe {
        text.push_str("unsafe ");
    }
    if m.abi != ::syntax::abi::Abi::Rust {
        text.push_str("extern");
        text.push_str(&m.abi.to_string());
        text.push(' ');
    }
    text.push_str("fn ");

N
Nick Cameron 已提交
943
    let mut sig = name_and_generics(text, 0, generics, id, ident, scx)?;
N
Nick Cameron 已提交
944 945 946

    sig.text.push('(');
    for i in &m.decl.inputs {
B
Bastien Orivel 已提交
947
        // FIXME should descend into patterns to add defs.
N
Nick Cameron 已提交
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
        sig.text.push_str(&pprust::pat_to_string(&i.pat));
        sig.text.push_str(": ");
        let nested = i.ty.make(sig.text.len(), Some(i.id), scx)?;
        sig.text.push_str(&nested.text);
        sig.text.push(',');
        sig.defs.extend(nested.defs.into_iter());
        sig.refs.extend(nested.refs.into_iter());
    }
    sig.text.push(')');

    if let ast::FunctionRetTy::Ty(ref t) = m.decl.output {
        sig.text.push_str(" -> ");
        let nested = t.make(sig.text.len(), None, scx)?;
        sig.text.push_str(&nested.text);
        sig.defs.extend(nested.defs.into_iter());
        sig.refs.extend(nested.refs.into_iter());
    }
    sig.text.push_str(" {}");

    Ok(sig)
}