Auto merge of #45848 - nrc:rls-bugs-4, r=eddyb

save-analysis: two fixes + rustfmt

Fix two regressions and run rustfmt.

r? @eddyb
This commit is contained in:
bors 2017-11-12 01:58:12 +00:00
commit e9f8542014
5 changed files with 964 additions and 775 deletions

File diff suppressed because it is too large Load Diff

View File

@ -12,8 +12,8 @@ use std::io::Write;
use rustc_serialize::json::as_json;
use rls_data::{self, Analysis, Import, Def, DefKind, Ref, RefKind, MacroRef,
Relation, CratePreludeData};
use rls_data::{self, Analysis, CratePreludeData, Def, DefKind, Import, MacroRef, Ref, RefKind,
Relation};
use rls_data::config::Config;
use rls_span::{Column, Row};
@ -54,15 +54,16 @@ impl<'b, W: Write> JsonDumper<WriteOutput<'b, W>> {
JsonDumper {
output: WriteOutput { output: writer },
config: config.clone(),
result: Analysis::new(config)
result: Analysis::new(config),
}
}
}
impl<'b> JsonDumper<CallbackOutput<'b>> {
pub fn with_callback(callback: &'b mut FnMut(&Analysis),
config: Config)
-> JsonDumper<CallbackOutput<'b>> {
pub fn with_callback(
callback: &'b mut FnMut(&Analysis),
config: Config,
) -> JsonDumper<CallbackOutput<'b>> {
JsonDumper {
output: CallbackOutput { callback: callback },
config: config.clone(),

View File

@ -9,20 +9,22 @@
// except according to those terms.
#![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/")]
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/")]
#![deny(warnings)]
#![feature(custom_attribute)]
#![allow(unused_attributes)]
#[macro_use] extern crate rustc;
#[macro_use]
extern crate rustc;
#[macro_use] extern crate log;
#[macro_use] extern crate syntax;
#[macro_use]
extern crate log;
extern crate rustc_data_structures;
extern crate rustc_serialize;
extern crate rustc_typeck;
#[macro_use]
extern crate syntax;
extern crate syntax_pos;
extern crate rls_data;
@ -38,7 +40,7 @@ mod sig;
use rustc::hir;
use rustc::hir::def::Def as HirDef;
use rustc::hir::map::{Node, NodeItem};
use rustc::hir::def_id::{LOCAL_CRATE, DefId};
use rustc::hir::def_id::{DefId, LOCAL_CRATE};
use rustc::session::config::CrateType::CrateTypeExecutable;
use rustc::ty::{self, TyCtxt};
use rustc_typeck::hir_ty_to_ty;
@ -48,13 +50,13 @@ use std::env;
use std::fs::File;
use std::path::{Path, PathBuf};
use syntax::ast::{self, NodeId, PatKind, Attribute};
use syntax::ast::{self, Attribute, NodeId, PatKind};
use syntax::parse::lexer::comments::strip_doc_comment_decoration;
use syntax::parse::token;
use syntax::print::pprust;
use syntax::symbol::keywords;
use syntax::visit::{self, Visitor};
use syntax::print::pprust::{ty_to_string, arg_to_string};
use syntax::print::pprust::{arg_to_string, ty_to_string};
use syntax::codemap::MacroAttribute;
use syntax_pos::*;
@ -62,8 +64,8 @@ use json_dumper::JsonDumper;
use dump_visitor::DumpVisitor;
use span_utils::SpanUtils;
use rls_data::{Ref, RefKind, SpanData, MacroRef, Def, DefKind, Relation, RelationKind,
ExternalCrateData, GlobalCrateId};
use rls_data::{Def, DefKind, ExternalCrateData, GlobalCrateId, MacroRef, Ref, RefKind, Relation,
RelationKind, SpanData};
use rls_data::config::Config;
@ -84,7 +86,7 @@ pub enum Data {
impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
fn span_from_span(&self, span: Span) -> SpanData {
use rls_span::{Row, Column};
use rls_span::{Column, Row};
let cm = self.tcx.sess.codemap();
let start = cm.lookup_char_pos(span.lo());
@ -119,8 +121,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
num: n.as_u32(),
id: GlobalCrateId {
name: self.tcx.crate_name(n).to_string(),
disambiguator: self.tcx.crate_disambiguator(n)
.to_fingerprint().as_value(),
disambiguator: self.tcx.crate_disambiguator(n).to_fingerprint().as_value(),
},
});
}
@ -132,7 +133,8 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
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);
let sub_span = self.span_utils
.sub_span_after_keyword(item.span, keywords::Fn);
filter!(self.span_utils, sub_span, item.span, None);
Some(Data::DefData(Def {
@ -182,7 +184,8 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
match item.node {
ast::ItemKind::Fn(ref decl, .., ref generics, _) => {
let qualname = format!("::{}", self.tcx.node_path_str(item.id));
let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Fn);
let sub_span = self.span_utils
.sub_span_after_keyword(item.span, keywords::Fn);
filter!(self.span_utils, sub_span, item.span, None);
Some(Data::DefData(Def {
kind: DefKind::Function,
@ -230,7 +233,8 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
}
ast::ItemKind::Const(ref typ, _) => {
let qualname = format!("::{}", self.tcx.node_path_str(item.id));
let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Const);
let sub_span = self.span_utils
.sub_span_after_keyword(item.span, keywords::Const);
filter!(self.span_utils, sub_span, item.span, None);
let id = id_from_node_id(item.id, self);
@ -257,7 +261,8 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
let cm = self.tcx.sess.codemap();
let filename = cm.span_to_filename(m.inner);
let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Mod);
let sub_span = self.span_utils
.sub_span_after_keyword(item.span, keywords::Mod);
filter!(self.span_utils, sub_span, item.span, None);
Some(Data::DefData(Def {
@ -268,7 +273,10 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
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(),
children: m.items
.iter()
.map(|i| id_from_node_id(i.id, self))
.collect(),
decl_id: None,
docs: self.docs_for_attrs(&item.attrs),
sig: sig::item_signature(item, self),
@ -278,12 +286,14 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
ast::ItemKind::Enum(ref def, _) => {
let name = item.ident.to_string();
let qualname = format!("::{}", self.tcx.node_path_str(item.id));
let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Enum);
let sub_span = self.span_utils
.sub_span_after_keyword(item.span, keywords::Enum);
filter!(self.span_utils, sub_span, item.span, None);
let variants_str = def.variants.iter()
.map(|v| v.node.name.to_string())
.collect::<Vec<_>>()
.join(", ");
let variants_str = def.variants
.iter()
.map(|v| v.node.name.to_string())
.collect::<Vec<_>>()
.join(", ");
let value = format!("{}::{{{}}}", name, variants_str);
Some(Data::DefData(Def {
kind: DefKind::Enum,
@ -294,9 +304,9 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
value,
parent: None,
children: def.variants
.iter()
.map(|v| id_from_node_id(v.node.data.id(), self))
.collect(),
.iter()
.map(|v| id_from_node_id(v.node.data.id(), self))
.collect(),
decl_id: None,
docs: self.docs_for_attrs(&item.attrs),
sig: sig::item_signature(item, self),
@ -313,15 +323,18 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
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()),
}))
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
}
@ -333,14 +346,12 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
}
}
pub fn get_field_data(&self,
field: &ast::StructField,
scope: NodeId)
-> Option<Def> {
pub fn get_field_data(&self, field: &ast::StructField, scope: NodeId) -> Option<Def> {
if let Some(ident) = field.ident {
let name = ident.to_string();
let qualname = format!("::{}::{}", self.tcx.node_path_str(scope), ident);
let sub_span = self.span_utils.sub_span_before_token(field.span, token::Colon);
let sub_span = self.span_utils
.sub_span_before_token(field.span, token::Colon);
filter!(self.span_utils, sub_span, field.span, None);
let def_id = self.tcx.hir.local_def_id(field.id);
let typ = self.tcx.type_of(def_id).to_string();
@ -370,18 +381,13 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
// 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.
pub fn get_method_data(&self,
id: ast::NodeId,
name: ast::Name,
span: Span)
-> Option<Def> {
pub fn get_method_data(&self, id: ast::NodeId, name: ast::Name, span: Span) -> Option<Def> {
// 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.
let (qualname, parent_scope, decl_id, docs, attributes) =
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) {
Some(Node::NodeItem(item)) => {
match item.node {
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) {
Some(Node::NodeItem(item)) => match item.node {
hir::ItemImpl(.., ref ty, _) => {
let mut result = String::from("<");
result.push_str(&self.tcx.hir.node_to_pretty_string(ty.id));
@ -391,7 +397,8 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
if let Some(def_id) = trait_id {
result.push_str(" as ");
result.push_str(&self.tcx.item_path_str(def_id));
self.tcx.associated_items(def_id)
self.tcx
.associated_items(def_id)
.find(|item| item.name == name)
.map(|item| decl_id = Some(item.def_id));
} else {
@ -403,53 +410,61 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
}
result.push_str(">");
(result, trait_id, decl_id,
self.docs_for_attrs(&item.attrs),
item.attrs.to_vec())
(
result,
trait_id,
decl_id,
self.docs_for_attrs(&item.attrs),
item.attrs.to_vec(),
)
}
_ => {
span_bug!(span,
"Container {:?} for method {} not an impl?",
impl_id,
id);
span_bug!(
span,
"Container {:?} for method {} not an impl?",
impl_id,
id
);
}
},
r => {
span_bug!(
span,
"Container {:?} for method {} is not a node item {:?}",
impl_id,
id,
r
);
}
}
r => {
span_bug!(span,
"Container {:?} for method {} is not a node item {:?}",
impl_id,
id,
r);
}
},
None => match self.tcx.trait_of_item(self.tcx.hir.local_def_id(id)) {
Some(def_id) => {
match self.tcx.hir.get_if_local(def_id) {
Some(Node::NodeItem(item)) => {
(format!("::{}", self.tcx.item_path_str(def_id)),
Some(def_id), None,
self.docs_for_attrs(&item.attrs),
item.attrs.to_vec())
}
},
None => match self.tcx.trait_of_item(self.tcx.hir.local_def_id(id)) {
Some(def_id) => match self.tcx.hir.get_if_local(def_id) {
Some(Node::NodeItem(item)) => (
format!("::{}", self.tcx.item_path_str(def_id)),
Some(def_id),
None,
self.docs_for_attrs(&item.attrs),
item.attrs.to_vec(),
),
r => {
span_bug!(span,
"Could not find container {:?} for \
method {}, got {:?}",
def_id,
id,
r);
span_bug!(
span,
"Could not find container {:?} for \
method {}, got {:?}",
def_id,
id,
r
);
}
},
None => {
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;
}
}
None => {
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;
}
},
};
},
};
let qualname = format!("{}::{}", qualname, name);
@ -473,9 +488,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
})
}
pub fn get_trait_ref_data(&self,
trait_ref: &ast::TraitRef)
-> Option<Ref> {
pub fn get_trait_ref_data(&self, trait_ref: &ast::TraitRef) -> Option<Ref> {
self.lookup_ref_id(trait_ref.ref_id).and_then(|def_id| {
let span = trait_ref.path.span;
if generated_code(span) {
@ -503,8 +516,11 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
let hir_node = match self.tcx.hir.find(sub_ex.id) {
Some(Node::NodeExpr(expr)) => expr,
_ => {
debug!("Missing or weird node for sub-expression {} in {:?}",
sub_ex.id, expr);
debug!(
"Missing or weird node for sub-expression {} in {:?}",
sub_ex.id,
expr
);
return None;
}
};
@ -548,7 +564,13 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
}
ast::ExprKind::MethodCall(ref seg, ..) => {
let expr_hir_id = self.tcx.hir.definitions().node_to_hir_id(expr.id);
let method_id = self.tables.type_dependent_defs()[expr_hir_id].def_id();
let method_id = match self.tables.type_dependent_defs().get(expr_hir_id) {
Some(id) => id.def_id(),
None => {
debug!("Could not resolve method id for {:?}", expr);
return None;
}
};
let (def_id, decl_id) = match self.tcx.associated_item(method_id).container {
ty::ImplContainer(_) => (Some(method_id), None),
ty::TraitContainer(_) => (None, Some(method_id)),
@ -559,7 +581,10 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
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()),
ref_id: def_id
.or(decl_id)
.map(|id| id_from_def_id(id))
.unwrap_or(null_id()),
}))
}
ast::ExprKind::Path(_, ref path) => {
@ -576,40 +601,61 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
match self.tcx.hir.get(id) {
Node::NodeTraitRef(tr) => tr.path.def,
Node::NodeItem(&hir::Item { node: hir::ItemUse(ref path, _), .. }) |
Node::NodeItem(&hir::Item {
node: hir::ItemUse(ref path, _),
..
}) |
Node::NodeVisibility(&hir::Visibility::Restricted { ref path, .. }) => path.def,
Node::NodeExpr(&hir::Expr { node: hir::ExprStruct(ref qpath, ..), .. }) |
Node::NodeExpr(&hir::Expr { node: hir::ExprPath(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, ..), .. }) => {
Node::NodeExpr(&hir::Expr {
node: hir::ExprStruct(ref qpath, ..),
..
}) |
Node::NodeExpr(&hir::Expr {
node: hir::ExprPath(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, ..),
..
}) => {
let hir_id = self.tcx.hir.node_to_hir_id(id);
self.tables.qpath_def(qpath, hir_id)
}
Node::NodeBinding(&hir::Pat {
node: hir::PatKind::Binding(_, canonical_id, ..), ..
node: hir::PatKind::Binding(_, canonical_id, ..),
..
}) => HirDef::Local(canonical_id),
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);
if let ty::TyProjection(proj) = ty.sty {
return HirDef::AssociatedTy(proj.item_def_id);
}
HirDef::Err
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);
if let ty::TyProjection(proj) = ty.sty {
return HirDef::AssociatedTy(proj.item_def_id);
}
HirDef::Err
}
} else {
HirDef::Err
}
}
} else {
HirDef::Err
},
_ => HirDef::Err
_ => HirDef::Err,
}
}
@ -636,8 +682,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
let sub_span = last_seg.span;
filter!(self.span_utils, Some(sub_span), path.span, None);
match def {
HirDef::Upvar(id, ..) |
HirDef::Local(id) => {
HirDef::Upvar(id, ..) | HirDef::Local(id) => {
let span = self.span_from_span(sub_span);
Some(Ref {
kind: RefKind::Variable,
@ -660,10 +705,12 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
// Function type bounds are desugared in the parser, so we have to
// special case them here.
let fn_span = self.span_utils.span_for_first_ident(path.span);
fn_span.map(|span| Ref {
kind: RefKind::Type,
span: self.span_from_span(span),
ref_id: id_from_def_id(def_id),
fn_span.map(|span| {
Ref {
kind: RefKind::Type,
span: self.span_from_span(span),
ref_id: id_from_def_id(def_id),
}
})
}
HirDef::Struct(def_id) |
@ -697,7 +744,8 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
HirDef::Method(decl_id) => {
let def_id = if decl_id.is_local() {
let ti = self.tcx.associated_item(decl_id);
self.tcx.associated_items(ti.container.id())
self.tcx
.associated_items(ti.container.id())
.find(|item| item.name == ti.name && item.defaultness.has_value())
.map(|item| item.def_id)
} else {
@ -735,10 +783,11 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
}
}
pub fn get_field_ref_data(&self,
field_ref: &ast::Field,
variant: &ty::VariantDef)
-> Option<Ref> {
pub fn get_field_ref_data(
&self,
field_ref: &ast::Field,
variant: &ty::VariantDef,
) -> Option<Ref> {
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);
@ -776,7 +825,12 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
// 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) {
if let Some(mac) = self.tcx
.sess
.imported_macro_spans
.borrow()
.get(&callee_span)
{
let &(ref mac_name, mac_span) = mac;
let mac_span = self.span_from_span(mac_span);
return Some(MacroRef {
@ -831,21 +885,29 @@ fn make_signature(decl: &ast::FnDecl, generics: &ast::Generics) -> String {
let mut sig = "fn ".to_owned();
if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
sig.push('<');
sig.push_str(&generics.lifetimes.iter()
.map(|l| l.lifetime.ident.name.to_string())
.collect::<Vec<_>>()
.join(", "));
sig.push_str(&generics
.lifetimes
.iter()
.map(|l| l.lifetime.ident.name.to_string())
.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(&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_str(&decl.inputs
.iter()
.map(arg_to_string)
.collect::<Vec<_>>()
.join(", "));
sig.push(')');
match decl.output {
ast::FunctionRetTy::Default(_) => sig.push_str(" -> ()"),
@ -877,15 +939,16 @@ impl<'l, 'a: 'l> Visitor<'a> for PathCollector<'l> {
PatKind::Struct(ref path, ..) => {
self.collected_paths.push((p.id, path));
}
PatKind::TupleStruct(ref path, ..) |
PatKind::Path(_, ref path) => {
PatKind::TupleStruct(ref path, ..) | PatKind::Path(_, ref path) => {
self.collected_paths.push((p.id, path));
}
PatKind::Ident(bm, ref path1, _) => {
debug!("PathCollector, visit ident in pat {}: {:?} {:?}",
path1.node,
p.span,
path1.span);
debug!(
"PathCollector, visit ident in pat {}: {:?} {:?}",
path1.node,
p.span,
path1.span
);
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
@ -893,7 +956,8 @@ impl<'l, 'a: 'l> Visitor<'a> for PathCollector<'l> {
ast::BindingMode::ByRef(_) => ast::Mutability::Immutable,
ast::BindingMode::ByValue(mt) => mt,
};
self.collected_idents.push((p.id, path1.node, path1.span, immut));
self.collected_idents
.push((p.id, path1.node, path1.span, immut));
}
_ => {}
}
@ -903,23 +967,25 @@ impl<'l, 'a: 'l> Visitor<'a> for PathCollector<'l> {
/// 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);
fn save<'l, 'tcx>(
&mut self,
save_ctxt: SaveContext<'l, 'tcx>,
krate: &ast::Crate,
cratename: &str,
);
}
/// Dump the save-analysis results to a file.
pub struct DumpHandler<'a> {
odir: Option<&'a Path>,
cratename: String
cratename: String,
}
impl<'a> DumpHandler<'a> {
pub fn new(odir: Option<&'a Path>, cratename: &str) -> DumpHandler<'a> {
DumpHandler {
odir,
cratename: cratename.to_owned()
cratename: cratename.to_owned(),
}
}
@ -937,8 +1003,10 @@ impl<'a> DumpHandler<'a> {
error!("Could not create directory {}: {}", root_path.display(), e);
}
let executable =
sess.crate_types.borrow().iter().any(|ct| *ct == CrateTypeExecutable);
let executable = sess.crate_types
.borrow()
.iter()
.any(|ct| *ct == CrateTypeExecutable);
let mut out_name = if executable {
"".to_owned()
} else {
@ -955,19 +1023,21 @@ impl<'a> DumpHandler<'a> {
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))
});
let output_file = File::create(&file_name).unwrap_or_else(
|e| sess.fatal(&format!("Could not open {}: {}", file_name.display(), e)),
);
output_file
}
}
impl<'a> SaveHandler for DumpHandler<'a> {
fn save<'l, 'tcx>(&mut self,
save_ctxt: SaveContext<'l, 'tcx>,
krate: &ast::Crate,
cratename: &str) {
fn save<'l, 'tcx>(
&mut self,
save_ctxt: SaveContext<'l, 'tcx>,
krate: &ast::Crate,
cratename: &str,
) {
let output = &mut self.output_file(&save_ctxt);
let mut dumper = JsonDumper::new(output, save_ctxt.config.clone());
let mut visitor = DumpVisitor::new(save_ctxt, &mut dumper);
@ -983,10 +1053,12 @@ pub struct CallbackHandler<'b> {
}
impl<'b> SaveHandler for CallbackHandler<'b> {
fn save<'l, 'tcx>(&mut self,
save_ctxt: SaveContext<'l, 'tcx>,
krate: &ast::Crate,
cratename: &str) {
fn save<'l, 'tcx>(
&mut self,
save_ctxt: SaveContext<'l, 'tcx>,
krate: &ast::Crate,
cratename: &str,
) {
// 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
@ -1000,12 +1072,14 @@ impl<'b> SaveHandler for CallbackHandler<'b> {
}
}
pub fn process_crate<'l, 'tcx, H: SaveHandler>(tcx: TyCtxt<'l, 'tcx, 'tcx>,
krate: &ast::Crate,
analysis: &'l ty::CrateAnalysis,
cratename: &str,
config: Option<Config>,
mut handler: H) {
pub fn process_crate<'l, 'tcx, H: SaveHandler>(
tcx: TyCtxt<'l, 'tcx, 'tcx>,
krate: &ast::Crate,
analysis: &'l ty::CrateAnalysis,
cratename: &str,
config: Option<Config>,
mut handler: H,
) {
let _ignore = tcx.dep_graph.in_ignore();
assert!(analysis.glob_map.is_some());
@ -1028,10 +1102,8 @@ fn find_config(supplied: Option<Config>) -> Config {
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")
},
Some(config_string) => rustc_serialize::json::decode(config_string.to_str().unwrap())
.expect("Could not deserialize save-analysis config"),
None => Config::default(),
}
}

View File

@ -35,9 +35,9 @@
//
// FIXME where clauses need implementing, defs/refs in generics are mostly missing.
use {SaveContext, id_from_def_id, id_from_node_id};
use {id_from_def_id, id_from_node_id, SaveContext};
use rls_data::{Signature, SigElement};
use rls_data::{SigElement, Signature};
use rustc::hir::def::Def;
use syntax::ast::{self, NodeId};
@ -75,36 +75,39 @@ pub fn variant_signature(variant: &ast::Variant, scx: &SaveContext) -> Option<Si
variant.node.make(0, None, scx).ok()
}
pub fn method_signature(id: NodeId,
ident: ast::Ident,
generics: &ast::Generics,
m: &ast::MethodSig,
scx: &SaveContext)
-> Option<Signature> {
pub fn method_signature(
id: NodeId,
ident: ast::Ident,
generics: &ast::Generics,
m: &ast::MethodSig,
scx: &SaveContext,
) -> Option<Signature> {
if !scx.config.signatures {
return None;
}
make_method_signature(id, ident, generics, m, scx).ok()
}
pub fn assoc_const_signature(id: NodeId,
ident: ast::Name,
ty: &ast::Ty,
default: Option<&ast::Expr>,
scx: &SaveContext)
-> Option<Signature> {
pub fn assoc_const_signature(
id: NodeId,
ident: ast::Name,
ty: &ast::Ty,
default: Option<&ast::Expr>,
scx: &SaveContext,
) -> Option<Signature> {
if !scx.config.signatures {
return None;
}
make_assoc_const_signature(id, ident, ty, default, scx).ok()
}
pub fn assoc_type_signature(id: NodeId,
ident: ast::Ident,
bounds: Option<&ast::TyParamBounds>,
default: Option<&ast::Ty>,
scx: &SaveContext)
-> Option<Signature> {
pub fn assoc_type_signature(
id: NodeId,
ident: ast::Ident,
bounds: Option<&ast::TyParamBounds>,
default: Option<&ast::Ty>,
scx: &SaveContext,
) -> Option<Signature> {
if !scx.config.signatures {
return None;
}
@ -117,11 +120,12 @@ trait Sig {
fn make(&self, offset: usize, id: Option<NodeId>, scx: &SaveContext) -> Result;
}
fn extend_sig(mut sig: Signature,
text: String,
defs: Vec<SigElement>,
refs: Vec<SigElement>)
-> Signature {
fn extend_sig(
mut sig: Signature,
text: String,
defs: Vec<SigElement>,
refs: Vec<SigElement>,
) -> Signature {
sig.text = text;
sig.defs.extend(defs.into_iter());
sig.refs.extend(refs.into_iter());
@ -142,8 +146,12 @@ fn merge_sigs(text: String, sigs: Vec<Signature>) -> Signature {
let (defs, refs): (Vec<_>, Vec<_>) = sigs.into_iter().map(|s| (s.defs, s.refs)).unzip();
result.defs.extend(defs.into_iter().flat_map(|ds| ds.into_iter()));
result.refs.extend(refs.into_iter().flat_map(|rs| rs.into_iter()));
result
.defs
.extend(defs.into_iter().flat_map(|ds| ds.into_iter()));
result
.refs
.extend(refs.into_iter().flat_map(|rs| rs.into_iter()));
result
}
@ -188,9 +196,7 @@ impl Sig for ast::Ty {
let text = format!("{}{}", prefix, nested.text);
Ok(replace_text(nested, text))
}
ast::TyKind::Never => {
Ok(text_sig("!".to_owned()))
},
ast::TyKind::Never => Ok(text_sig("!".to_owned())),
ast::TyKind::Tup(ref ts) => {
let mut text = "(".to_owned();
let mut defs = vec![];
@ -215,8 +221,11 @@ impl Sig for ast::Ty {
if !f.lifetimes.is_empty() {
// FIXME defs, bounds on lifetimes
text.push_str("for<");
text.push_str(&f.lifetimes.iter().map(|l|
l.lifetime.ident.to_string()).collect::<Vec<_>>().join(", "));
text.push_str(&f.lifetimes
.iter()
.map(|l| l.lifetime.ident.to_string())
.collect::<Vec<_>>()
.join(", "));
text.push('>');
}
@ -251,9 +260,7 @@ impl Sig for ast::Ty {
Ok(Signature { text, defs, refs })
}
ast::TyKind::Path(None, ref path) => {
path.make(offset, id, scx)
}
ast::TyKind::Path(None, ref path) => path.make(offset, id, scx),
ast::TyKind::Path(Some(ref qself), ref path) => {
let nested_ty = qself.ty.make(offset + 1, id, scx)?;
let prefix = if qself.position == 0 {
@ -325,11 +332,13 @@ impl Sig for ast::Item {
text.push_str("mut ");
}
let name = self.ident.to_string();
let defs = vec![SigElement {
id: id_from_node_id(self.id, scx),
start: offset + text.len(),
end: offset + text.len() + name.len(),
}];
let defs = vec![
SigElement {
id: id_from_node_id(self.id, scx),
start: offset + text.len(),
end: offset + text.len() + name.len(),
},
];
text.push_str(&name);
text.push_str(": ");
@ -346,11 +355,13 @@ impl Sig for ast::Item {
ast::ItemKind::Const(ref ty, ref expr) => {
let mut text = "const ".to_owned();
let name = self.ident.to_string();
let defs = vec![SigElement {
id: id_from_node_id(self.id, scx),
start: offset + text.len(),
end: offset + text.len() + name.len(),
}];
let defs = vec![
SigElement {
id: id_from_node_id(self.id, scx),
start: offset + text.len(),
end: offset + text.len() + name.len(),
},
];
text.push_str(&name);
text.push_str(": ");
@ -379,12 +390,7 @@ impl Sig for ast::Item {
}
text.push_str("fn ");
let mut sig = name_and_generics(text,
offset,
generics,
self.id,
self.ident,
scx)?;
let mut sig = name_and_generics(text, offset, generics, self.id, self.ident, scx)?;
sig.text.push('(');
for i in &decl.inputs {
@ -413,11 +419,13 @@ impl Sig for ast::Item {
ast::ItemKind::Mod(ref _mod) => {
let mut text = "mod ".to_owned();
let name = self.ident.to_string();
let defs = vec![SigElement {
id: id_from_node_id(self.id, scx),
start: offset + text.len(),
end: offset + text.len() + name.len(),
}];
let defs = vec![
SigElement {
id: id_from_node_id(self.id, scx),
start: offset + text.len(),
end: offset + text.len() + name.len(),
},
];
text.push_str(&name);
// Could be either `mod foo;` or `mod foo { ... }`, but we'll just puck one.
text.push(';');
@ -430,12 +438,7 @@ impl Sig for ast::Item {
}
ast::ItemKind::Ty(ref ty, ref generics) => {
let text = "type ".to_owned();
let mut sig = name_and_generics(text,
offset,
generics,
self.id,
self.ident,
scx)?;
let mut sig = name_and_generics(text, offset, generics, self.id, self.ident, scx)?;
sig.text.push_str(" = ");
let ty = ty.make(offset + sig.text.len(), id, scx)?;
@ -446,34 +449,19 @@ impl Sig for ast::Item {
}
ast::ItemKind::Enum(_, ref generics) => {
let text = "enum ".to_owned();
let mut sig = name_and_generics(text,
offset,
generics,
self.id,
self.ident,
scx)?;
let mut sig = name_and_generics(text, offset, generics, self.id, self.ident, scx)?;
sig.text.push_str(" {}");
Ok(sig)
}
ast::ItemKind::Struct(_, ref generics) => {
let text = "struct ".to_owned();
let mut sig = name_and_generics(text,
offset,
generics,
self.id,
self.ident,
scx)?;
let mut sig = name_and_generics(text, offset, generics, self.id, self.ident, scx)?;
sig.text.push_str(" {}");
Ok(sig)
}
ast::ItemKind::Union(_, ref generics) => {
let text = "union ".to_owned();
let mut sig = name_and_generics(text,
offset,
generics,
self.id,
self.ident,
scx)?;
let mut sig = name_and_generics(text, offset, generics, self.id, self.ident, scx)?;
sig.text.push_str(" {}");
Ok(sig)
}
@ -488,12 +476,7 @@ impl Sig for ast::Item {
text.push_str("unsafe ");
}
text.push_str("trait ");
let mut sig = name_and_generics(text,
offset,
generics,
self.id,
self.ident,
scx)?;
let mut sig = name_and_generics(text, offset, generics, self.id, self.ident, scx)?;
if !bounds.is_empty() {
sig.text.push_str(": ");
@ -515,13 +498,15 @@ impl Sig for ast::Item {
text.push_str(" for .. {}");
Ok(replace_text(trait_sig, text))
}
ast::ItemKind::Impl(unsafety,
polarity,
defaultness,
ref generics,
ref opt_trait,
ref ty,
_) => {
ast::ItemKind::Impl(
unsafety,
polarity,
defaultness,
ref generics,
ref opt_trait,
ref ty,
_,
) => {
let mut text = String::new();
if let ast::Defaultness::Default = defaultness {
text.push_str("default ");
@ -562,8 +547,7 @@ impl Sig for ast::Item {
ast::ItemKind::ExternCrate(_) => Err("extern crate"),
// FIXME should implement this (e.g., pub use).
ast::ItemKind::Use(_) => Err("import"),
ast::ItemKind::Mac(..) |
ast::ItemKind::MacroDef(_) => Err("Macro"),
ast::ItemKind::Mac(..) | ast::ItemKind::MacroDef(_) => Err("Macro"),
}
}
}
@ -573,19 +557,14 @@ impl Sig for ast::Path {
let def = scx.get_path_def(id.ok_or("Missing id for Path")?);
let (name, start, end) = match def {
Def::Label(..) |
Def::PrimTy(..) |
Def::SelfTy(..) |
Def::Err => {
Def::Label(..) | Def::PrimTy(..) | Def::SelfTy(..) | Def::Err => {
return Ok(Signature {
text: pprust::path_to_string(self),
defs: vec![],
refs: vec![],
})
}
Def::AssociatedConst(..) |
Def::Variant(..) |
Def::VariantCtor(..) => {
Def::AssociatedConst(..) | Def::Variant(..) | Def::VariantCtor(..) => {
let len = self.segments.len();
if len < 2 {
return Err("Bad path");
@ -635,9 +614,11 @@ impl Sig for ast::Generics {
if !l.bounds.is_empty() {
l_text.push_str(": ");
let bounds = l.bounds.iter().map(|l| {
l.ident.to_string()
}).collect::<Vec<_>>().join(" + ");
let bounds = l.bounds
.iter()
.map(|l| l.ident.to_string())
.collect::<Vec<_>>()
.join(" + ");
l_text.push_str(&bounds);
// FIXME add lifetime bounds refs.
}
@ -662,7 +643,11 @@ impl Sig for ast::Generics {
}
text.push('>');
Ok(Signature {text, defs, refs: vec![] })
Ok(Signature {
text,
defs,
refs: vec![],
})
}
}
@ -710,11 +695,7 @@ impl Sig for ast::Variant_ {
refs.extend(field_sig.refs.into_iter());
}
text.push('}');
Ok(Signature {
text,
defs,
refs,
})
Ok(Signature { text, defs, refs })
}
ast::VariantData::Tuple(ref fields, id) => {
let name_def = SigElement {
@ -733,11 +714,7 @@ impl Sig for ast::Variant_ {
refs.extend(field_sig.refs.into_iter());
}
text.push(')');
Ok(Signature {
text,
defs,
refs,
})
Ok(Signature { text, defs, refs })
}
ast::VariantData::Unit(id) => {
let name_def = SigElement {
@ -763,12 +740,7 @@ impl Sig for ast::ForeignItem {
let mut text = String::new();
text.push_str("fn ");
let mut sig = name_and_generics(text,
offset,
generics,
self.id,
self.ident,
scx)?;
let mut sig = name_and_generics(text, offset, generics, self.id, self.ident, scx)?;
sig.text.push('(');
for i in &decl.inputs {
@ -800,11 +772,13 @@ impl Sig for ast::ForeignItem {
text.push_str("mut ");
}
let name = self.ident.to_string();
let defs = vec![SigElement {
id: id_from_node_id(self.id, scx),
start: offset + text.len(),
end: offset + text.len() + name.len(),
}];
let defs = vec![
SigElement {
id: id_from_node_id(self.id, scx),
start: offset + text.len(),
end: offset + text.len() + name.len(),
},
];
text.push_str(&name);
text.push_str(": ");
@ -816,11 +790,13 @@ impl Sig for ast::ForeignItem {
ast::ForeignItemKind::Ty => {
let mut text = "type ".to_owned();
let name = self.ident.to_string();
let defs = vec![SigElement {
id: id_from_node_id(self.id, scx),
start: offset + text.len(),
end: offset + text.len() + name.len(),
}];
let defs = vec![
SigElement {
id: id_from_node_id(self.id, scx),
start: offset + text.len(),
end: offset + text.len() + name.len(),
},
];
text.push_str(&name);
text.push(';');
@ -834,13 +810,14 @@ impl Sig for ast::ForeignItem {
}
}
fn name_and_generics(mut text: String,
offset: usize,
generics: &ast::Generics,
id: NodeId,
name: ast::Ident,
scx: &SaveContext)
-> Result {
fn name_and_generics(
mut text: String,
offset: usize,
generics: &ast::Generics,
id: NodeId,
name: ast::Ident,
scx: &SaveContext,
) -> Result {
let name = name.to_string();
let def = SigElement {
id: id_from_node_id(id, scx),
@ -855,19 +832,22 @@ fn name_and_generics(mut text: String,
}
fn make_assoc_type_signature(id: NodeId,
ident: ast::Ident,
bounds: Option<&ast::TyParamBounds>,
default: Option<&ast::Ty>,
scx: &SaveContext)
-> Result {
fn make_assoc_type_signature(
id: NodeId,
ident: ast::Ident,
bounds: Option<&ast::TyParamBounds>,
default: Option<&ast::Ty>,
scx: &SaveContext,
) -> Result {
let mut text = "type ".to_owned();
let name = ident.to_string();
let mut defs = vec![SigElement {
id: id_from_node_id(id, scx),
start: text.len(),
end: text.len() + name.len(),
}];
let mut defs = vec![
SigElement {
id: id_from_node_id(id, scx),
start: text.len(),
end: text.len() + name.len(),
},
];
let mut refs = vec![];
text.push_str(&name);
if let Some(bounds) = bounds {
@ -886,19 +866,22 @@ fn make_assoc_type_signature(id: NodeId,
Ok(Signature { text, defs, refs })
}
fn make_assoc_const_signature(id: NodeId,
ident: ast::Name,
ty: &ast::Ty,
default: Option<&ast::Expr>,
scx: &SaveContext)
-> Result {
fn make_assoc_const_signature(
id: NodeId,
ident: ast::Name,
ty: &ast::Ty,
default: Option<&ast::Expr>,
scx: &SaveContext,
) -> Result {
let mut text = "const ".to_owned();
let name = ident.to_string();
let mut defs = vec![SigElement {
id: id_from_node_id(id, scx),
start: text.len(),
end: text.len() + name.len(),
}];
let mut defs = vec![
SigElement {
id: id_from_node_id(id, scx),
start: text.len(),
end: text.len() + name.len(),
},
];
let mut refs = vec![];
text.push_str(&name);
text.push_str(": ");
@ -916,12 +899,13 @@ fn make_assoc_const_signature(id: NodeId,
Ok(Signature { text, defs, refs })
}
fn make_method_signature(id: NodeId,
ident: ast::Ident,
generics: &ast::Generics,
m: &ast::MethodSig,
scx: &SaveContext)
-> Result {
fn make_method_signature(
id: NodeId,
ident: ast::Ident,
generics: &ast::Generics,
m: &ast::MethodSig,
scx: &SaveContext,
) -> Result {
// FIXME code dup with function signature
let mut text = String::new();
if m.constness.node == ast::Constness::Const {
@ -937,12 +921,7 @@ fn make_method_signature(id: NodeId,
}
text.push_str("fn ");
let mut sig = name_and_generics(text,
0,
generics,
id,
ident,
scx)?;
let mut sig = name_and_generics(text, 0, generics, id, ident, scx)?;
sig.text.push('(');
for i in &m.decl.inputs {

View File

@ -42,7 +42,11 @@ impl<'a> SpanUtils<'a> {
if path.is_absolute() {
path.clone().display().to_string()
} else {
env::current_dir().unwrap().join(&path).display().to_string()
env::current_dir()
.unwrap()
.join(&path)
.display()
.to_string()
}
}
@ -66,7 +70,7 @@ impl<'a> SpanUtils<'a> {
loop {
let ts = toks.real_token();
if ts.tok == token::Eof {
return result
return result;
}
if bracket_count == 0 && (ts.tok.is_ident() || ts.tok.is_keyword(keywords::SelfValue)) {
result = Some(ts.sp);
@ -122,10 +126,9 @@ impl<'a> SpanUtils<'a> {
loop {
let next = toks.real_token();
if (next.tok == token::Lt || next.tok == token::Colon) &&
angle_count == 0 &&
bracket_count == 0 &&
prev.tok.is_ident() {
if (next.tok == token::Lt || next.tok == token::Colon) && angle_count == 0
&& bracket_count == 0 && prev.tok.is_ident()
{
result = Some(prev.sp);
}
@ -152,12 +155,14 @@ impl<'a> SpanUtils<'a> {
}
if angle_count != 0 || bracket_count != 0 {
let loc = self.sess.codemap().lookup_char_pos(span.lo());
span_bug!(span,
"Mis-counted brackets when breaking path? Parsing '{}' \
in {}, line {}",
self.snippet(span),
loc.file.name,
loc.line);
span_bug!(
span,
"Mis-counted brackets when breaking path? Parsing '{}' \
in {}, line {}",
self.snippet(span),
loc.file.name,
loc.line
);
}
if result.is_none() && prev.tok.is_ident() && angle_count == 0 {
return Some(prev.sp);
@ -211,7 +216,7 @@ impl<'a> SpanUtils<'a> {
if f(ts.tok) {
let ts = toks.real_token();
if ts.tok == token::Eof {
return None
return None;
} else {
return Some(ts.sp);
}
@ -278,7 +283,12 @@ impl<'a> SpanUtils<'a> {
};
//If the span comes from a fake filemap, filter it.
if !self.sess.codemap().lookup_char_pos(parent.lo()).file.is_real_file() {
if !self.sess
.codemap()
.lookup_char_pos(parent.lo())
.file
.is_real_file()
{
return true;
}