lib.rs 41.5 KB
Newer Older
1
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 3 4 5 6 7 8 9 10
// 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.

11 12 13 14 15 16
#![crate_name = "rustc_save_analysis"]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
      html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
      html_root_url = "https://doc.rust-lang.org/nightly/")]
17
#![deny(warnings)]
18

19 20
#![feature(custom_attribute)]
#![allow(unused_attributes)]
21

22
#[macro_use] extern crate rustc;
23 24 25

#[macro_use] extern crate log;
#[macro_use] extern crate syntax;
N
Nick Cameron 已提交
26
extern crate rustc_serialize;
27
extern crate rustc_typeck;
28
extern crate syntax_pos;
29

30
extern crate rls_data;
31
extern crate rls_span;
32

N
Nick Cameron 已提交
33

N
Nick Cameron 已提交
34
mod json_api_dumper;
35 36 37
mod json_dumper;
mod dump_visitor;
#[macro_use]
38
mod span_utils;
N
Nick Cameron 已提交
39
mod sig;
40

41
use rustc::hir;
42 43
use rustc::hir::def::Def as HirDef;
use rustc::hir::map::{Node, NodeItem};
44
use rustc::hir::def_id::DefId;
45
use rustc::session::config::CrateType::CrateTypeExecutable;
46
use rustc::ty::{self, TyCtxt};
47
use rustc_typeck::hir_ty_to_ty;
48

49
use std::default::Default;
50
use std::env;
51
use std::fs::File;
52
use std::path::{Path, PathBuf};
N
Nick Cameron 已提交
53

54
use syntax::ast::{self, NodeId, PatKind, Attribute, CRATE_NODE_ID};
55
use syntax::parse::lexer::comments::strip_doc_comment_decoration;
56
use syntax::parse::token;
57
use syntax::print::pprust;
58
use syntax::symbol::keywords;
N
Nick Cameron 已提交
59
use syntax::visit::{self, Visitor};
60
use syntax::print::pprust::{ty_to_string, arg_to_string};
61 62
use syntax::codemap::MacroAttribute;
use syntax_pos::*;
63

64 65 66 67 68 69 70
pub use json_api_dumper::JsonApiDumper;
pub use json_dumper::JsonDumper;
use dump_visitor::DumpVisitor;
use span_utils::SpanUtils;

use rls_data::{Ref, RefKind, SpanData, MacroRef, Def, DefKind, Relation, RelationKind,
               ExternalCrateData, Import, CratePreludeData};
71
use rls_data::config::Config;
72

73

N
Nick Cameron 已提交
74
pub struct SaveContext<'l, 'tcx: 'l> {
75
    tcx: TyCtxt<'l, 'tcx, 'tcx>,
76
    tables: &'l ty::TypeckTables<'tcx>,
77
    analysis: &'l ty::CrateAnalysis,
N
Nick Cameron 已提交
78
    span_utils: SpanUtils<'tcx>,
79
    config: Config,
80 81
}

82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
#[derive(Debug)]
pub enum Data {
    /// Data about a macro use.
    MacroUseData(MacroRef),
    RefData(Ref),
    DefData(Def),
    RelationData(Relation),
}

pub trait Dump {
    fn crate_prelude(&mut self, _: CratePreludeData);
    fn macro_use(&mut self, _: MacroRef) {}
    fn import(&mut self, _: bool, _: Import);
    fn dump_ref(&mut self, _: Ref) {}
    fn dump_def(&mut self, _: bool, _: Def);
    fn dump_relation(&mut self, data: Relation);
}

100 101 102 103
macro_rules! option_try(
    ($e:expr) => (match $e { Some(e) => e, None => return None })
);

N
Nick Cameron 已提交
104
impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
    fn span_from_span(&self, span: Span) -> SpanData {
        use rls_span::{Row, Column};

        let cm = self.tcx.sess.codemap();
        let start = cm.lookup_char_pos(span.lo);
        let end = cm.lookup_char_pos(span.hi);

        SpanData {
            file_name: start.file.name.clone().into(),
            byte_start: span.lo.0,
            byte_end: span.hi.0,
            line_start: Row::new_one_indexed(start.line as u32),
            line_end: Row::new_one_indexed(end.line as u32),
            column_start: Column::new_one_indexed(start.col.0 as u32 + 1),
            column_end: Column::new_one_indexed(end.col.0 as u32 + 1),
        }
    }

123
    // List external crates used by the current crate.
124
    pub fn get_external_crates(&self) -> Vec<ExternalCrateData> {
125 126
        let mut result = Vec::new();

A
Ariel Ben-Yehuda 已提交
127
        for n in self.tcx.sess.cstore.crates() {
T
Taylor Cramer 已提交
128
            let span = match *self.tcx.extern_crate(n.as_def_id()) {
129 130 131 132 133 134
                Some(ref c) => c.span,
                None => {
                    debug!("Skipping crate {}, no data", n);
                    continue;
                }
            };
135 136
            let lo_loc = self.span_utils.sess.codemap().lookup_char_pos(span.lo);
            result.push(ExternalCrateData {
137
                name: self.tcx.sess.cstore.crate_name(n).to_string(),
138 139
                num: n.as_u32(),
                file_name: SpanUtils::make_path_string(&lo_loc.file.name),
N
Nick Cameron 已提交
140
            });
A
Ariel Ben-Yehuda 已提交
141
        }
142 143 144

        result
    }
N
Nick Cameron 已提交
145

146 147 148 149 150
    pub fn get_extern_item_data(&self, item: &ast::ForeignItem) -> Option<Data> {
        let qualname = format!("::{}", self.tcx.node_path_str(item.id));
        match item.node {
            ast::ForeignItemKind::Fn(ref decl, ref generics) => {
                let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Fn);
N
rebased  
Nick Cameron 已提交
151
                filter!(self.span_utils, sub_span, item.span, None);
152 153 154 155 156

                Some(Data::DefData(Def {
                    kind: DefKind::Function,
                    id: id_from_node_id(item.id, self),
                    span: self.span_from_span(sub_span.unwrap()),
157
                    name: item.ident.to_string(),
158
                    qualname,
159 160
                    value: make_signature(decl, generics),
                    parent: None,
161 162
                    children: vec![],
                    decl_id: None,
163
                    docs: docs_for_attrs(&item.attrs),
164
                    sig: sig::foreign_item_signature(item, self),
165
                    attributes: lower_attributes(item.attrs.clone(), self),
166 167 168 169 170
                }))
            }
            ast::ForeignItemKind::Static(ref ty, m) => {
                let keyword = if m { keywords::Mut } else { keywords::Static };
                let sub_span = self.span_utils.sub_span_after_keyword(item.span, keyword);
N
rebased  
Nick Cameron 已提交
171
                filter!(self.span_utils, sub_span, item.span, None);
172 173 174 175 176 177 178 179

                let id = ::id_from_node_id(item.id, self);
                let span = self.span_from_span(sub_span.unwrap());

                Some(Data::DefData(Def {
                    kind: DefKind::Static,
                    id,
                    span,
180
                    name: item.ident.to_string(),
181 182
                    qualname,
                    value: ty_to_string(ty),
183
                    parent: None,
184 185
                    children: vec![],
                    decl_id: None,
186
                    docs: docs_for_attrs(&item.attrs),
187
                    sig: sig::foreign_item_signature(item, self),
188
                    attributes: lower_attributes(item.attrs.clone(), self),
189 190 191 192 193
                }))
            }
        }
    }

194
    pub fn get_item_data(&self, item: &ast::Item) -> Option<Data> {
N
Nick Cameron 已提交
195
        match item.node {
V
Vadim Petrochenkov 已提交
196
            ast::ItemKind::Fn(ref decl, .., ref generics, _) => {
197
                let qualname = format!("::{}", self.tcx.node_path_str(item.id));
N
Nick Cameron 已提交
198
                let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Fn);
199
                filter!(self.span_utils, sub_span, item.span, None);
200 201 202 203
                Some(Data::DefData(Def {
                    kind: DefKind::Function,
                    id: id_from_node_id(item.id, self),
                    span: self.span_from_span(sub_span.unwrap()),
204
                    name: item.ident.to_string(),
205
                    qualname,
206
                    value: make_signature(decl, generics),
207
                    parent: None,
208 209
                    children: vec![],
                    decl_id: None,
N
Nick Cameron 已提交
210
                    docs: docs_for_attrs(&item.attrs),
N
Nick Cameron 已提交
211
                    sig: sig::item_signature(item, self),
212
                    attributes: lower_attributes(item.attrs.clone(), self),
213
                }))
N
Nick Cameron 已提交
214
            }
215
            ast::ItemKind::Static(ref typ, mt, _) => {
216
                let qualname = format!("::{}", self.tcx.node_path_str(item.id));
217

218 219 220
                let keyword = match mt {
                    ast::Mutability::Mutable => keywords::Mut,
                    ast::Mutability::Immutable => keywords::Static,
221 222
                };

223
                let sub_span = self.span_utils.sub_span_after_keyword(item.span, keyword);
224
                filter!(self.span_utils, sub_span, item.span, None);
225 226 227 228 229 230 231 232

                let id = id_from_node_id(item.id, self);
                let span = self.span_from_span(sub_span.unwrap());

                Some(Data::DefData(Def {
                    kind: DefKind::Static,
                    id,
                    span,
233
                    name: item.ident.to_string(),
234 235
                    qualname,
                    value: ty_to_string(&typ),
236
                    parent: None,
237 238
                    children: vec![],
                    decl_id: None,
N
Nick Cameron 已提交
239
                    docs: docs_for_attrs(&item.attrs),
N
Nick Cameron 已提交
240
                    sig: sig::item_signature(item, self),
241
                    attributes: lower_attributes(item.attrs.clone(), self),
242
                }))
243
            }
244
            ast::ItemKind::Const(ref typ, _) => {
245
                let qualname = format!("::{}", self.tcx.node_path_str(item.id));
246
                let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Const);
247
                filter!(self.span_utils, sub_span, item.span, None);
248 249 250 251 252 253 254 255

                let id = id_from_node_id(item.id, self);
                let span = self.span_from_span(sub_span.unwrap());

                Some(Data::DefData(Def {
                    kind: DefKind::Const,
                    id,
                    span,
256
                    name: item.ident.to_string(),
257 258
                    qualname,
                    value: ty_to_string(typ),
259
                    parent: None,
260 261
                    children: vec![],
                    decl_id: None,
N
Nick Cameron 已提交
262
                    docs: docs_for_attrs(&item.attrs),
N
Nick Cameron 已提交
263
                    sig: sig::item_signature(item, self),
264
                    attributes: lower_attributes(item.attrs.clone(), self),
265
                }))
266
            }
267
            ast::ItemKind::Mod(ref m) => {
268
                let qualname = format!("::{}", self.tcx.node_path_str(item.id));
269

270
                let cm = self.tcx.sess.codemap();
271 272 273
                let filename = cm.span_to_filename(m.inner);

                let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Mod);
274
                filter!(self.span_utils, sub_span, item.span, None);
275

276 277 278
                Some(Data::DefData(Def {
                    kind: DefKind::Mod,
                    id: id_from_node_id(item.id, self),
279
                    name: item.ident.to_string(),
280 281 282 283 284 285
                    qualname,
                    span: self.span_from_span(sub_span.unwrap()),
                    value: filename,
                    parent: None,
                    children: m.items.iter().map(|i| id_from_node_id(i.id, self)).collect(),
                    decl_id: None,
N
Nick Cameron 已提交
286
                    docs: docs_for_attrs(&item.attrs),
N
Nick Cameron 已提交
287
                    sig: sig::item_signature(item, self),
288
                    attributes: lower_attributes(item.attrs.clone(), self),
289
                }))
N
Nick Cameron 已提交
290
            }
291 292 293
            ast::ItemKind::Enum(ref def, _) => {
                let name = item.ident.to_string();
                let qualname = format!("::{}", self.tcx.node_path_str(item.id));
P
Peter Elmers 已提交
294
                let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Enum);
295
                filter!(self.span_utils, sub_span, item.span, None);
296 297 298 299
                let variants_str = def.variants.iter()
                                      .map(|v| v.node.name.to_string())
                                      .collect::<Vec<_>>()
                                      .join(", ");
300 301 302 303 304 305 306 307 308 309 310 311 312 313
                let value = format!("{}::{{{}}}", name, variants_str);
                Some(Data::DefData(Def {
                    kind: DefKind::Enum,
                    id: id_from_node_id(item.id, self),
                    span: self.span_from_span(sub_span.unwrap()),
                    name,
                    qualname,
                    value,
                    parent: None,
                    children: def.variants
                                 .iter()
                                 .map(|v| id_from_node_id(v.node.data.id(), self))
                                 .collect(),
                    decl_id: None,
N
Nick Cameron 已提交
314
                    docs: docs_for_attrs(&item.attrs),
N
Nick Cameron 已提交
315
                    sig: sig::item_signature(item, self),
316
                    attributes: lower_attributes(item.attrs.to_owned(), self),
317
                }))
N
Nick Cameron 已提交
318
            }
V
Vadim Petrochenkov 已提交
319
            ast::ItemKind::Impl(.., ref trait_ref, ref typ, _) => {
320
                if let ast::TyKind::Path(None, ref path) = typ.node {
N
Nick Cameron 已提交
321
                    // Common case impl for a struct or something basic.
322 323
                    if generated_code(path.span) {
                        return None;
N
Nick Cameron 已提交
324
                    }
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
                    let sub_span = self.span_utils.sub_span_for_type_name(path.span);
                    filter!(self.span_utils, sub_span, typ.span, None);

                    let type_data = self.lookup_ref_id(typ.id);
                    type_data.map(|type_data| Data::RelationData(Relation {
                        kind: RelationKind::Impl,
                        span: self.span_from_span(sub_span.unwrap()),
                        from: id_from_def_id(type_data),
                        to: trait_ref.as_ref()
                                     .and_then(|t| self.lookup_ref_id(t.ref_id))
                                     .map(id_from_def_id)
                                     .unwrap_or(null_id()),
                    }))
                } else {
                    None
N
Nick Cameron 已提交
340 341
                }
            }
342 343
            _ => {
                // FIXME
344
                bug!();
345 346 347 348
            }
        }
    }

N
Nick Cameron 已提交
349 350 351
    pub fn get_field_data(&self,
                          field: &ast::StructField,
                          scope: NodeId)
352
                          -> Option<Def> {
353
        if let Some(ident) = field.ident {
N
Nick Cameron 已提交
354
            let name = ident.to_string();
355
            let qualname = format!("::{}::{}", self.tcx.node_path_str(scope), ident);
356 357
            let sub_span = self.span_utils.sub_span_before_token(field.span, token::Colon);
            filter!(self.span_utils, sub_span, field.span, None);
358
            let def_id = self.tcx.hir.local_def_id(field.id);
359
            let typ = self.tcx.type_of(def_id).to_string();
N
Nick Cameron 已提交
360

361 362 363 364 365 366 367 368 369 370 371 372 373 374

            let id = id_from_node_id(field.id, self);
            let span = self.span_from_span(sub_span.unwrap());

            Some(Def {
                kind: DefKind::Field,
                id,
                span,
                name,
                qualname,
                value: typ,
                parent: Some(id_from_node_id(scope, self)),
                children: vec![],
                decl_id: None,
N
Nick Cameron 已提交
375
                docs: docs_for_attrs(&field.attrs),
376
                sig: sig::field_signature(field, self),
377
                attributes: lower_attributes(field.attrs.clone(), self),
378 379 380
            })
        } else {
            None
381 382 383
        }
    }

N
Nick Cameron 已提交
384 385
    // FIXME would be nice to take a MethodItem here, but the ast provides both
    // trait and impl flavours, so the caller must do the disassembly.
N
Nick Cameron 已提交
386 387 388 389
    pub fn get_method_data(&self,
                           id: ast::NodeId,
                           name: ast::Name,
                           span: Span)
390
                           -> Option<Def> {
N
Nick Cameron 已提交
391 392
        // The qualname for a method is the trait name or name of the struct in an impl in
        // which the method is declared in, followed by the method's name.
393
        let (qualname, parent_scope, decl_id, docs, attributes) =
394 395
          match self.tcx.impl_of_method(self.tcx.hir.local_def_id(id)) {
            Some(impl_id) => match self.tcx.hir.get_if_local(impl_id) {
396
                Some(Node::NodeItem(item)) => {
N
Nick Cameron 已提交
397
                    match item.node {
V
Vadim Petrochenkov 已提交
398
                        hir::ItemImpl(.., ref ty, _) => {
N
Nick Cameron 已提交
399
                            let mut result = String::from("<");
400
                            result.push_str(&self.tcx.hir.node_to_pretty_string(ty.id));
N
Nick Cameron 已提交
401

402
                            let mut trait_id = self.tcx.trait_id_of_impl(impl_id);
403
                            let mut decl_id = None;
404
                            if let Some(def_id) = trait_id {
405 406
                                result.push_str(" as ");
                                result.push_str(&self.tcx.item_path_str(def_id));
407 408 409
                                self.tcx.associated_items(def_id)
                                    .find(|item| item.name == name)
                                    .map(|item| decl_id = Some(item.def_id));
410 411 412 413 414 415
                            } else {
                                if let Some(NodeItem(item)) = self.tcx.hir.find(id) {
                                    if let hir::ItemImpl(_, _, _, _, _, ref ty, _) = item.node {
                                        trait_id = self.lookup_ref_id(ty.id);
                                    }
                                }
N
Nick Cameron 已提交
416 417
                            }
                            result.push_str(">");
418 419

                            (result, trait_id, decl_id,
420
                             docs_for_attrs(&item.attrs),
421
                             item.attrs.to_vec())
N
Nick Cameron 已提交
422 423
                        }
                        _ => {
424 425 426 427
                            span_bug!(span,
                                      "Container {:?} for method {} not an impl?",
                                      impl_id,
                                      id);
N
Nick Cameron 已提交
428
                        }
N
Nick Cameron 已提交
429
                    }
N
Nick Cameron 已提交
430
                }
431
                r => {
432 433 434 435 436
                    span_bug!(span,
                              "Container {:?} for method {} is not a node item {:?}",
                              impl_id,
                              id,
                              r);
N
Nick Cameron 已提交
437
                }
N
Nick Cameron 已提交
438
            },
439
            None => match self.tcx.trait_of_item(self.tcx.hir.local_def_id(id)) {
N
Nick Cameron 已提交
440
                Some(def_id) => {
441
                    match self.tcx.hir.get_if_local(def_id) {
442
                        Some(Node::NodeItem(item)) => {
N
Nick Cameron 已提交
443
                            (format!("::{}", self.tcx.item_path_str(def_id)),
444
                             Some(def_id), None,
445
                             docs_for_attrs(&item.attrs),
446
                             item.attrs.to_vec())
N
Nick Cameron 已提交
447
                        }
448
                        r => {
449 450 451 452 453 454
                            span_bug!(span,
                                      "Could not find container {:?} for \
                                       method {}, got {:?}",
                                      def_id,
                                      id,
                                      r);
N
Nick Cameron 已提交
455 456
                        }
                    }
N
Nick Cameron 已提交
457
                }
N
Nick Cameron 已提交
458
                None => {
459 460 461 462
                    debug!("Could not find container for method {} at {:?}", id, span);
                    // This is not necessarily a bug, if there was a compilation error, the tables
                    // we need might not exist.
                    return None;
N
Nick Cameron 已提交
463
                }
N
Nick Cameron 已提交
464 465 466
            },
        };

467
        let qualname = format!("{}::{}", qualname, name);
N
Nick Cameron 已提交
468 469

        let sub_span = self.span_utils.sub_span_after_keyword(span, keywords::Fn);
470
        filter!(self.span_utils, sub_span, span, None);
471

472 473 474 475
        Some(Def {
            kind: DefKind::Method,
            id: id_from_node_id(id, self),
            span: self.span_from_span(sub_span.unwrap()),
N
Nick Cameron 已提交
476
            name: name.to_string(),
477
            qualname,
478 479
            // FIXME you get better data here by using the visitor.
            value: String::new(),
480 481 482 483
            parent: parent_scope.map(|id| id_from_def_id(id)),
            children: vec![],
            decl_id: decl_id.map(|id| id_from_def_id(id)),
            docs,
N
Nick Cameron 已提交
484
            sig: None,
485
            attributes: lower_attributes(attributes, self),
486
        })
N
Nick Cameron 已提交
487 488
    }

N
Nick Cameron 已提交
489
    pub fn get_trait_ref_data(&self,
490 491
                              trait_ref: &ast::TraitRef)
                              -> Option<Ref> {
492
        self.lookup_ref_id(trait_ref.ref_id).and_then(|def_id| {
493
            let span = trait_ref.path.span;
494 495 496
            if generated_code(span) {
                return None;
            }
497 498
            let sub_span = self.span_utils.sub_span_for_type_name(span).or(Some(span));
            filter!(self.span_utils, sub_span, span, None);
499 500 501 502 503
            let span = self.span_from_span(sub_span.unwrap());
            Some(Ref {
                kind: RefKind::Type,
                span,
                ref_id: id_from_def_id(def_id),
504
            })
N
Nick Cameron 已提交
505 506 507
        })
    }

N
Nick Cameron 已提交
508
    pub fn get_expr_data(&self, expr: &ast::Expr) -> Option<Data> {
509
        let hir_node = self.tcx.hir.expect_expr(expr.id);
510
        let ty = self.tables.expr_ty_adjusted_opt(&hir_node);
511 512 513
        if ty.is_none() || ty.unwrap().sty == ty::TyError {
            return None;
        }
514
        match expr.node {
515
            ast::ExprKind::Field(ref sub_ex, ident) => {
516
                let hir_node = match self.tcx.hir.find(sub_ex.id) {
517 518 519 520 521 522 523
                    Some(Node::NodeExpr(expr)) => expr,
                    _ => {
                        debug!("Missing or weird node for sub-expression {} in {:?}",
                               sub_ex.id, expr);
                        return None;
                    }
                };
524
                match self.tables.expr_ty_adjusted(&hir_node).sty {
525
                    ty::TyAdt(def, _) if !def.is_enum() => {
526 527
                        let f = def.struct_variant().field_named(ident.node.name);
                        let sub_span = self.span_utils.span_for_last_ident(expr.span);
528
                        filter!(self.span_utils, sub_span, expr.span, None);
529 530 531 532 533
                        let span = self.span_from_span(sub_span.unwrap());
                        return Some(Data::RefData(Ref {
                            kind: RefKind::Variable,
                            span,
                            ref_id: id_from_def_id(f.did),
534
                        }));
535
                    }
N
Nick Cameron 已提交
536
                    _ => {
537
                        debug!("Expected struct or union type, found {:?}", ty);
N
Nick Cameron 已提交
538 539
                        None
                    }
540 541
                }
            }
V
Vadim Petrochenkov 已提交
542
            ast::ExprKind::Struct(ref path, ..) => {
543
                match self.tables.expr_ty_adjusted(&hir_node).sty {
544
                    ty::TyAdt(def, _) if !def.is_enum() => {
545
                        let sub_span = self.span_utils.span_for_last_ident(path.span);
546
                        filter!(self.span_utils, sub_span, path.span, None);
547 548 549 550 551
                        let span = self.span_from_span(sub_span.unwrap());
                        Some(Data::RefData(Ref {
                            kind: RefKind::Type,
                            span,
                            ref_id: id_from_def_id(def.did),
N
Nick Cameron 已提交
552
                        }))
553 554
                    }
                    _ => {
555
                        // FIXME ty could legitimately be an enum, but then we will fail
N
Nick Cameron 已提交
556
                        // later if we try to look up the fields.
557
                        debug!("expected struct or union, found {:?}", ty);
N
Nick Cameron 已提交
558
                        None
559 560 561
                    }
                }
            }
562
            ast::ExprKind::MethodCall(..) => {
563
                let method_id = self.tables.type_dependent_defs[&expr.id].def_id();
564
                let (def_id, decl_id) = match self.tcx.associated_item(method_id).container {
565
                    ty::ImplContainer(_) => (Some(method_id), None),
N
Nick Cameron 已提交
566
                    ty::TraitContainer(_) => (None, Some(method_id)),
567 568
                };
                let sub_span = self.span_utils.sub_span_for_meth_name(expr.span);
569
                filter!(self.span_utils, sub_span, expr.span, None);
570 571 572 573 574
                let span = self.span_from_span(sub_span.unwrap());
                Some(Data::RefData(Ref {
                    kind: RefKind::Function,
                    span,
                    ref_id: def_id.or(decl_id).map(|id| id_from_def_id(id)).unwrap_or(null_id()),
575 576
                }))
            }
577
            ast::ExprKind::Path(_, ref path) => {
578
                self.get_path_data(expr.id, path).map(|d| Data::RefData(d))
N
Nick Cameron 已提交
579
            }
N
Nick Cameron 已提交
580
            _ => {
581
                // FIXME
582
                bug!();
N
Nick Cameron 已提交
583 584 585 586
            }
        }
    }

587
    pub fn get_path_def(&self, id: NodeId) -> HirDef {
588
        match self.tcx.hir.get(id) {
589 590 591 592 593 594 595 596 597 598
            Node::NodeTraitRef(tr) => tr.path.def,

            Node::NodeItem(&hir::Item { node: hir::ItemUse(ref path, _), .. }) |
            Node::NodeVisibility(&hir::Visibility::Restricted { ref path, .. }) => path.def,

            Node::NodeExpr(&hir::Expr { node: hir::ExprPath(ref qpath), .. }) |
            Node::NodeExpr(&hir::Expr { node: hir::ExprStruct(ref qpath, ..), .. }) |
            Node::NodePat(&hir::Pat { node: hir::PatKind::Path(ref qpath), .. }) |
            Node::NodePat(&hir::Pat { node: hir::PatKind::Struct(ref qpath, ..), .. }) |
            Node::NodePat(&hir::Pat { node: hir::PatKind::TupleStruct(ref qpath, ..), .. }) => {
599
                self.tables.qpath_def(qpath, id)
600 601 602
            }

            Node::NodeLocal(&hir::Pat { node: hir::PatKind::Binding(_, def_id, ..), .. }) => {
603
                HirDef::Local(def_id)
604 605
            }

606 607 608 609 610 611
            Node::NodeTy(ty) => {
                if let hir::Ty { node: hir::TyPath(ref qpath), .. } = *ty {
                    match *qpath {
                        hir::QPath::Resolved(_, ref path) => path.def,
                        hir::QPath::TypeRelative(..) => {
                            let ty = hir_ty_to_ty(self.tcx, ty);
612
                            if let ty::TyProjection(proj) = ty.sty {
613
                                return HirDef::AssociatedTy(proj.item_def_id);
614
                            }
615
                            HirDef::Err
616
                        }
617
                    }
618
                } else {
619
                    HirDef::Err
620 621 622
                }
            }

623
            _ => HirDef::Err
624
        }
625
    }
626

627
    pub fn get_path_data(&self, id: NodeId, path: &ast::Path) -> Option<Ref> {
628
        let def = self.get_path_def(id);
N
Nick Cameron 已提交
629
        let sub_span = self.span_utils.span_for_last_ident(path.span);
630
        filter!(self.span_utils, sub_span, path.span, None);
N
Nick Cameron 已提交
631
        match def {
632 633 634 635 636 637 638 639 640 641 642 643 644
            HirDef::Upvar(..) |
            HirDef::Local(..) |
            HirDef::Static(..) |
            HirDef::Const(..) |
            HirDef::AssociatedConst(..) |
            HirDef::StructCtor(..) |
            HirDef::VariantCtor(..) => {
                let span = self.span_from_span(sub_span.unwrap());
                Some(Ref {
                    kind: RefKind::Variable,
                    span,
                    ref_id: id_from_def_id(def.def_id()),
                })
N
Nick Cameron 已提交
645
            }
646 647 648 649 650 651 652 653 654 655 656 657 658 659
            HirDef::Struct(def_id) |
            HirDef::Variant(def_id, ..) |
            HirDef::Union(def_id) |
            HirDef::Enum(def_id) |
            HirDef::TyAlias(def_id) |
            HirDef::AssociatedTy(def_id) |
            HirDef::Trait(def_id) |
            HirDef::TyParam(def_id) => {
                let span = self.span_from_span(sub_span.unwrap());
                Some(Ref {
                    kind: RefKind::Type,
                    span,
                    ref_id: id_from_def_id(def_id),
                })
N
Nick Cameron 已提交
660
            }
661
            HirDef::Method(decl_id) => {
N
Nick Cameron 已提交
662
                let sub_span = self.span_utils.sub_span_for_meth_name(path.span);
663
                filter!(self.span_utils, sub_span, path.span, None);
664
                let def_id = if decl_id.is_local() {
665 666
                    let ti = self.tcx.associated_item(decl_id);
                    self.tcx.associated_items(ti.container.id())
667
                        .find(|item| item.name == ti.name && item.defaultness.has_value())
668
                        .map(|item| item.def_id)
N
Nick Cameron 已提交
669 670 671
                } else {
                    None
                };
672 673 674 675 676 677
                let span = self.span_from_span(sub_span.unwrap());
                Some(Ref {
                    kind: RefKind::Function,
                    span,
                    ref_id: id_from_def_id(def_id.unwrap_or(decl_id)),
                })
N
Nick Cameron 已提交
678
            }
679 680 681 682 683 684 685
            HirDef::Fn(def_id) => {
                let span = self.span_from_span(sub_span.unwrap());
                Some(Ref {
                    kind: RefKind::Function,
                    span,
                    ref_id: id_from_def_id(def_id),
                })
N
Nick Cameron 已提交
686
            }
687 688 689 690 691 692 693
            HirDef::Mod(def_id) => {
                let span = self.span_from_span(sub_span.unwrap());
                Some(Ref {
                    kind: RefKind::Mod,
                    span,
                    ref_id: id_from_def_id(def_id),
                })
694
            }
695 696 697 698 699 700
            HirDef::PrimTy(..) |
            HirDef::SelfTy(..) |
            HirDef::Label(..) |
            HirDef::Macro(..) |
            HirDef::GlobalAsm(..) |
            HirDef::Err => None,
N
Nick Cameron 已提交
701 702 703
        }
    }

704 705
    pub fn get_field_ref_data(&self,
                              field_ref: &ast::Field,
706 707
                              variant: &ty::VariantDef)
                              -> Option<Ref> {
708 709 710
        let f = variant.field_named(field_ref.ident.node.name);
        // We don't really need a sub-span here, but no harm done
        let sub_span = self.span_utils.span_for_last_ident(field_ref.ident.span);
711
        filter!(self.span_utils, sub_span, field_ref.ident.span, None);
712 713 714 715 716
        let span = self.span_from_span(sub_span.unwrap());
        Some(Ref {
            kind: RefKind::Variable,
            span,
            ref_id: id_from_def_id(f.did),
717
        })
718 719
    }

720
    /// Attempt to return MacroRef for any AST node.
721 722 723
    ///
    /// For a given piece of AST defined by the supplied Span and NodeId,
    /// returns None if the node is not macro-generated or the span is malformed,
724 725
    /// else uses the expansion callsite and callee to return some MacroRef.
    pub fn get_macro_use_data(&self, span: Span) -> Option<MacroRef> {
726 727 728 729 730 731
        if !generated_code(span) {
            return None;
        }
        // Note we take care to use the source callsite/callee, to handle
        // nested expansions and ensure we only generate data for source-visible
        // macro uses.
732
        let callsite = span.source_callsite();
733
        let callsite_span = self.span_from_span(callsite);
734
        let callee = option_try!(span.source_callee());
735 736 737 738 739 740 741 742 743 744 745 746
        let callee_span = option_try!(callee.span);

        // Ignore attribute macros, their spans are usually mangled
        if let MacroAttribute(_) = callee.format {
            return None;
        }

        // If the callee is an imported macro from an external crate, need to get
        // the source span and name from the session, as their spans are localized
        // when read in, and no longer correspond to the source.
        if let Some(mac) = self.tcx.sess.imported_macro_spans.borrow().get(&callee_span) {
            let &(ref mac_name, mac_span) = mac;
747 748 749 750 751 752
            let mac_span = self.span_from_span(mac_span);
            return Some(MacroRef {
                span: callsite_span,
                qualname: mac_name.clone(), // FIXME: generate the real qualname
                callee_span: mac_span,
            });
753 754
        }

755 756 757 758 759
        let callee_span = self.span_from_span(callee_span);
        Some(MacroRef {
            span: callsite_span,
            qualname: callee.name().to_string(), // FIXME: generate the real qualname
            callee_span,
760 761 762
        })
    }

N
Nick Cameron 已提交
763
    fn lookup_ref_id(&self, ref_id: NodeId) -> Option<DefId> {
764
        match self.get_path_def(ref_id) {
765
            HirDef::PrimTy(_) | HirDef::SelfTy(..) | HirDef::Err => None,
766
            def => Some(def.def_id()),
N
Nick Cameron 已提交
767 768 769
        }
    }

770
    #[inline]
771
    pub fn enclosing_scope(&self, id: NodeId) -> NodeId {
772
        self.tcx.hir.get_enclosing_scope(id).unwrap_or(CRATE_NODE_ID)
773
    }
774 775
}

776
fn make_signature(decl: &ast::FnDecl, generics: &ast::Generics) -> String {
777
    let mut sig = "fn ".to_owned();
778 779 780
    if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
        sig.push('<');
        sig.push_str(&generics.lifetimes.iter()
J
Jeffrey Seyfried 已提交
781
                              .map(|l| l.lifetime.ident.name.to_string())
782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
                              .collect::<Vec<_>>()
                              .join(", "));
        if !generics.lifetimes.is_empty() {
            sig.push_str(", ");
        }
        sig.push_str(&generics.ty_params.iter()
                              .map(|l| l.ident.to_string())
                              .collect::<Vec<_>>()
                              .join(", "));
        sig.push_str("> ");
    }
    sig.push('(');
    sig.push_str(&decl.inputs.iter().map(arg_to_string).collect::<Vec<_>>().join(", "));
    sig.push(')');
    match decl.output {
797
        ast::FunctionRetTy::Default(_) => sig.push_str(" -> ()"),
798 799 800 801 802 803
        ast::FunctionRetTy::Ty(ref t) => sig.push_str(&format!(" -> {}", ty_to_string(t))),
    }

    sig
}

N
Nick Cameron 已提交
804 805
// An AST visitor for collecting paths from patterns.
struct PathCollector {
806
    // The Row field identifies the kind of pattern.
807
    collected_paths: Vec<(NodeId, ast::Path, ast::Mutability)>,
N
Nick Cameron 已提交
808 809 810 811
}

impl PathCollector {
    fn new() -> PathCollector {
N
Nick Cameron 已提交
812
        PathCollector { collected_paths: vec![] }
N
Nick Cameron 已提交
813 814 815
    }
}

816
impl<'a> Visitor<'a> for PathCollector {
N
Nick Cameron 已提交
817 818
    fn visit_pat(&mut self, p: &ast::Pat) {
        match p.node {
V
Vadim Petrochenkov 已提交
819
            PatKind::Struct(ref path, ..) => {
820
                self.collected_paths.push((p.id, path.clone(),
821
                                           ast::Mutability::Mutable));
N
Nick Cameron 已提交
822
            }
V
Vadim Petrochenkov 已提交
823
            PatKind::TupleStruct(ref path, ..) |
824
            PatKind::Path(_, ref path) => {
825
                self.collected_paths.push((p.id, path.clone(),
826
                                           ast::Mutability::Mutable));
N
Nick Cameron 已提交
827
            }
828
            PatKind::Ident(bm, ref path1, _) => {
829
                debug!("PathCollector, visit ident in pat {}: {:?} {:?}",
830
                       path1.node,
831 832
                       p.span,
                       path1.span);
N
Nick Cameron 已提交
833 834 835 836
                let immut = match bm {
                    // Even if the ref is mut, you can't change the ref, only
                    // the data pointed at, so showing the initialising expression
                    // is still worthwhile.
837
                    ast::BindingMode::ByRef(_) => ast::Mutability::Immutable,
838
                    ast::BindingMode::ByValue(mt) => mt,
N
Nick Cameron 已提交
839 840
                };
                // collect path for either visit_local or visit_arm
E
Eduard Burtescu 已提交
841
                let path = ast::Path::from_ident(path1.span, path1.node);
842
                self.collected_paths.push((p.id, path, immut));
N
Nick Cameron 已提交
843 844 845 846 847 848 849
            }
            _ => {}
        }
        visit::walk_pat(self, p);
    }
}

N
Nick Cameron 已提交
850 851 852 853
fn docs_for_attrs(attrs: &[Attribute]) -> String {
    let mut result = String::new();

    for attr in attrs {
854
        if attr.check_name("doc") {
855
            if let Some(val) = attr.value_str() {
856
                if attr.is_sugared_doc {
857
                    result.push_str(&strip_doc_comment_decoration(&val.as_str()));
858
                } else {
859
                    result.push_str(&val.as_str());
860
                }
N
Nick Cameron 已提交
861 862 863 864 865 866 867 868
                result.push('\n');
            }
        }
    }

    result
}

869
#[derive(Clone, Copy, Debug, RustcEncodable)]
870 871
pub enum Format {
    Json,
872
    JsonApi,
873 874 875 876
}

impl Format {
    fn extension(&self) -> &'static str {
877
        ".json"
878 879 880
    }
}

881 882 883 884 885 886 887
/// Defines what to do with the results of saving the analysis.
pub trait SaveHandler {
    fn save<'l, 'tcx>(&mut self,
                      save_ctxt: SaveContext<'l, 'tcx>,
                      krate: &ast::Crate,
                      cratename: &str);
}
888

889 890 891 892 893 894
/// Dump the save-analysis results to a file.
pub struct DumpHandler<'a> {
    format: Format,
    odir: Option<&'a Path>,
    cratename: String
}
895

896 897 898 899 900 901 902 903
impl<'a> DumpHandler<'a> {
    pub fn new(format: Format, odir: Option<&'a Path>, cratename: &str) -> DumpHandler<'a> {
        DumpHandler {
            format: format,
            odir: odir,
            cratename: cratename.to_owned()
        }
    }
904

905 906 907 908 909 910 911 912 913
    fn output_file(&self, ctx: &SaveContext) -> File {
        let sess = &ctx.tcx.sess;
        let file_name = match ctx.config.output_file {
            Some(ref s) => PathBuf::from(s),
            None => {
                let mut root_path = match self.odir {
                    Some(val) => val.join("save-analysis"),
                    None => PathBuf::from("save-analysis-temp"),
                };
914

915 916 917
                if let Err(e) = std::fs::create_dir_all(&root_path) {
                    error!("Could not create directory {}: {}", root_path.display(), e);
                }
918

919 920 921 922 923 924 925 926 927 928
                let executable = sess.crate_types.borrow().iter().any(|ct| *ct == CrateTypeExecutable);
                let mut out_name = if executable {
                    "".to_owned()
                } else {
                    "lib".to_owned()
                };
                out_name.push_str(&self.cratename);
                out_name.push_str(&sess.opts.cg.extra_filename);
                out_name.push_str(self.format.extension());
                root_path.push(&out_name);
929

930 931
                root_path
            }
932
        };
933 934 935 936 937

        info!("Writing output to {}", file_name.display());

        let output_file = File::create(&file_name).unwrap_or_else(|e| {
            sess.fatal(&format!("Could not open {}: {}", file_name.display(), e))
938
        });
939

940
        output_file
941
    }
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
}

impl<'a> SaveHandler for DumpHandler<'a> {
    fn save<'l, 'tcx>(&mut self,
                      save_ctxt: SaveContext<'l, 'tcx>,
                      krate: &ast::Crate,
                      cratename: &str) {
        macro_rules! dump {
            ($new_dumper: expr) => {{
                let mut dumper = $new_dumper;
                let mut visitor = DumpVisitor::new(save_ctxt, &mut dumper);

                visitor.dump_crate_info(cratename, krate);
                visit::walk_crate(&mut visitor, krate);
            }}
        }

959
        let output = &mut self.output_file(&save_ctxt);
960

961 962 963 964
        match self.format {
            Format::Json => dump!(JsonDumper::new(output)),
            Format::JsonApi => dump!(JsonApiDumper::new(output)),
        }
965
    }
966
}
967

968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
/// Call a callback with the results of save-analysis.
pub struct CallbackHandler<'b> {
    pub callback: &'b mut FnMut(&rls_data::Analysis),
}

impl<'b> SaveHandler for CallbackHandler<'b> {
    fn save<'l, 'tcx>(&mut self,
                      save_ctxt: SaveContext<'l, 'tcx>,
                      krate: &ast::Crate,
                      cratename: &str) {
        macro_rules! dump {
            ($new_dumper: expr) => {{
                let mut dumper = $new_dumper;
                let mut visitor = DumpVisitor::new(save_ctxt, &mut dumper);

                visitor.dump_crate_info(cratename, krate);
                visit::walk_crate(&mut visitor, krate);
            }}
        }

        // We're using the JsonDumper here because it has the format of the
        // save-analysis results that we will pass to the callback. IOW, we are
        // using the JsonDumper to collect the save-analysis results, but not
        // actually to dump them to a file. This is all a bit convoluted and
        // there is certainly a simpler design here trying to get out (FIXME).
        dump!(JsonDumper::with_callback(self.callback))
    }
}

pub fn process_crate<'l, 'tcx, H: SaveHandler>(tcx: TyCtxt<'l, 'tcx, 'tcx>,
                                               krate: &ast::Crate,
                                               analysis: &'l ty::CrateAnalysis,
                                               cratename: &str,
1001
                                               config: Option<Config>,
1002 1003 1004 1005 1006 1007
                                               mut handler: H) {
    let _ignore = tcx.dep_graph.in_ignore();

    assert!(analysis.glob_map.is_some());

    info!("Dumping crate {}", cratename);
1008

1009 1010
    let save_ctxt = SaveContext {
        tcx: tcx,
1011
        tables: &ty::TypeckTables::empty(),
1012 1013
        analysis: analysis,
        span_utils: SpanUtils::new(&tcx.sess),
1014
        config: find_config(config),
1015
    };
1016

1017
    handler.save(save_ctxt, krate, cratename)
1018
}
1019

1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
fn find_config(supplied: Option<Config>) -> Config {
    if let Some(config) = supplied {
        return config;
    }
    match env::var_os("RUST_SAVE_ANALYSIS_CONFIG") {
        Some(config_string) => {
            rustc_serialize::json::decode(config_string.to_str().unwrap())
                .expect("Could not deserialize save-analysis config")
        },
        None => Config::default(),
    }
}

1033 1034 1035 1036 1037 1038 1039
// Utility functions for the module.

// Helper function to escape quotes in a string
fn escape(s: String) -> String {
    s.replace("\"", "\"\"")
}

1040 1041
// Helper function to determine if a span came from a
// macro expansion or syntax extension.
N
Nick Cameron 已提交
1042
fn generated_code(span: Span) -> bool {
1043
    span.ctxt != NO_EXPANSION || span == DUMMY_SP
1044
}
N
Nick Cameron 已提交
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055

// DefId::index is a newtype and so the JSON serialisation is ugly. Therefore
// we use our own Id which is the same, but without the newtype.
fn id_from_def_id(id: DefId) -> rls_data::Id {
    rls_data::Id {
        krate: id.krate.as_u32(),
        index: id.index.as_u32(),
    }
}

fn id_from_node_id(id: NodeId, scx: &SaveContext) -> rls_data::Id {
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
    let def_id = scx.tcx.hir.opt_local_def_id(id);
    def_id.map(|id| id_from_def_id(id)).unwrap_or_else(null_id)
}

fn null_id() -> rls_data::Id {
    rls_data::Id {
        krate: u32::max_value(),
        index: u32::max_value(),
    }
}

fn lower_attributes(attrs: Vec<Attribute>, scx: &SaveContext) -> Vec<rls_data::Attribute> {
    attrs.into_iter()
    // Only retain real attributes. Doc comments are lowered separately.
    .filter(|attr| attr.path != "doc")
    .map(|mut attr| {
        // Remove the surrounding '#[..]' or '#![..]' of the pretty printed
        // attribute. First normalize all inner attribute (#![..]) to outer
        // ones (#[..]), then remove the two leading and the one trailing character.
        attr.style = ast::AttrStyle::Outer;
        let value = pprust::attribute_to_string(&attr);
        // This str slicing works correctly, because the leading and trailing characters
        // are in the ASCII range and thus exactly one byte each.
        let value = value[2..value.len()-1].to_string();

        rls_data::Attribute {
            value: value,
            span: scx.span_from_span(attr.span),
        }
    }).collect()
N
Nick Cameron 已提交
1086
}