save_analysis: work on HIR tree instead of AST

This commit is contained in:
marmeladema 2020-05-30 18:30:34 +01:00
parent f3fadf6abd
commit 8ec687611b
5 changed files with 895 additions and 991 deletions

View file

@ -346,12 +346,15 @@ pub fn run_compiler(
queries.global_ctxt()?; queries.global_ctxt()?;
// Drop AST after creating GlobalCtxt to free memory
let _timer = sess.prof.generic_activity("drop_ast");
mem::drop(queries.expansion()?.take());
if sess.opts.debugging_opts.no_analysis || sess.opts.debugging_opts.ast_json { if sess.opts.debugging_opts.no_analysis || sess.opts.debugging_opts.ast_json {
return early_exit(); return early_exit();
} }
if sess.opts.debugging_opts.save_analysis { if sess.opts.debugging_opts.save_analysis {
let expanded_crate = &queries.expansion()?.peek().0;
let crate_name = queries.crate_name()?.peek().clone(); let crate_name = queries.crate_name()?.peek().clone();
queries.global_ctxt()?.peek_mut().enter(|tcx| { queries.global_ctxt()?.peek_mut().enter(|tcx| {
let result = tcx.analysis(LOCAL_CRATE); let result = tcx.analysis(LOCAL_CRATE);
@ -359,7 +362,6 @@ pub fn run_compiler(
sess.time("save_analysis", || { sess.time("save_analysis", || {
save::process_crate( save::process_crate(
tcx, tcx,
&expanded_crate,
&crate_name, &crate_name,
&compiler.input(), &compiler.input(),
None, None,
@ -371,13 +373,7 @@ pub fn run_compiler(
}); });
result result
// AST will be dropped *after* the `after_analysis` callback
// (needed by the RLS)
})?; })?;
} else {
// Drop AST after creating GlobalCtxt to free memory
let _timer = sess.prof.generic_activity("drop_ast");
mem::drop(queries.expansion()?.take());
} }
queries.global_ctxt()?.peek_mut().enter(|tcx| tcx.analysis(LOCAL_CRATE))?; queries.global_ctxt()?.peek_mut().enter(|tcx| tcx.analysis(LOCAL_CRATE))?;
@ -386,10 +382,6 @@ pub fn run_compiler(
return early_exit(); return early_exit();
} }
if sess.opts.debugging_opts.save_analysis {
mem::drop(queries.expansion()?.take());
}
queries.ongoing_codegen()?; queries.ongoing_codegen()?;
if sess.opts.debugging_opts.print_type_sizes { if sess.opts.debugging_opts.print_type_sizes {

View file

@ -203,6 +203,30 @@ pub fn visibility_qualified<S: Into<Cow<'static, str>>>(vis: &hir::Visibility<'_
}) })
} }
pub fn generic_params_to_string(generic_params: &[GenericParam<'_>]) -> String {
to_string(NO_ANN, |s| s.print_generic_params(generic_params))
}
pub fn bounds_to_string<'b>(bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>) -> String {
to_string(NO_ANN, |s| s.print_bounds("", bounds))
}
pub fn param_to_string(arg: &hir::Param<'_>) -> String {
to_string(NO_ANN, |s| s.print_param(arg))
}
pub fn ty_to_string(ty: &hir::Ty<'_>) -> String {
to_string(NO_ANN, |s| s.print_type(ty))
}
pub fn path_segment_to_string(segment: &hir::PathSegment<'_>) -> String {
to_string(NO_ANN, |s| s.print_path_segment(segment))
}
pub fn path_to_string(segment: &hir::Path<'_>) -> String {
to_string(NO_ANN, |s| s.print_path(segment, false))
}
impl<'a> State<'a> { impl<'a> State<'a> {
pub fn cbox(&mut self, u: usize) { pub fn cbox(&mut self, u: usize) {
self.s.cbox(u); self.s.cbox(u);

File diff suppressed because it is too large Load diff

View file

@ -9,14 +9,16 @@ mod dumper;
mod span_utils; mod span_utils;
mod sig; mod sig;
use rustc_ast::ast::{self, Attribute, NodeId, PatKind, DUMMY_NODE_ID}; use rustc_ast::ast::{self};
use rustc_ast::util::comments::strip_doc_comment_decoration; use rustc_ast::util::comments::strip_doc_comment_decoration;
use rustc_ast::visit::{self, Visitor}; use rustc_ast_pretty::pprust::attribute_to_string;
use rustc_ast_pretty::pprust::{self, param_to_string, ty_to_string};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::{CtorOf, DefKind as HirDefKind, Res}; use rustc_hir::def::{CtorOf, DefKind as HirDefKind, Res};
use rustc_hir::def_id::{DefId, LOCAL_CRATE}; use rustc_hir::def_id::{DefId, LOCAL_CRATE};
use rustc_hir::intravisit::{self, Visitor};
use rustc_hir::Node; use rustc_hir::Node;
use rustc_hir_pretty::ty_to_string;
use rustc_middle::hir::map::Map;
use rustc_middle::middle::cstore::ExternCrate; use rustc_middle::middle::cstore::ExternCrate;
use rustc_middle::middle::privacy::AccessLevels; use rustc_middle::middle::privacy::AccessLevels;
use rustc_middle::ty::{self, DefIdTree, TyCtxt}; use rustc_middle::ty::{self, DefIdTree, TyCtxt};
@ -129,34 +131,32 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> {
result result
} }
pub fn get_extern_item_data(&self, item: &ast::ForeignItem) -> Option<Data> { pub fn get_extern_item_data(&self, item: &hir::ForeignItem<'_>) -> Option<Data> {
let qualname = format!( let def_id = self.tcx.hir().local_def_id(item.hir_id).to_def_id();
"::{}", let qualname = format!("::{}", self.tcx.def_path_str(def_id));
self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id).to_def_id())
);
match item.kind { match item.kind {
ast::ForeignItemKind::Fn(_, ref sig, ref generics, _) => { hir::ForeignItemKind::Fn(ref decl, _, ref generics) => {
filter!(self.span_utils, item.ident.span); filter!(self.span_utils, item.ident.span);
Some(Data::DefData(Def { Some(Data::DefData(Def {
kind: DefKind::ForeignFunction, kind: DefKind::ForeignFunction,
id: id_from_node_id(item.id, self), id: id_from_def_id(def_id),
span: self.span_from_span(item.ident.span), span: self.span_from_span(item.ident.span),
name: item.ident.to_string(), name: item.ident.to_string(),
qualname, qualname,
value: make_signature(&sig.decl, generics), value: make_signature(decl, generics),
parent: None, parent: None,
children: vec![], children: vec![],
decl_id: None, decl_id: None,
docs: self.docs_for_attrs(&item.attrs), docs: self.docs_for_attrs(&item.attrs),
sig: sig::foreign_item_signature(item, self), sig: sig::foreign_item_signature(item, self),
attributes: lower_attributes(item.attrs.clone(), self), attributes: lower_attributes(item.attrs.to_vec(), self),
})) }))
} }
ast::ForeignItemKind::Static(ref ty, _, _) => { hir::ForeignItemKind::Static(ref ty, _) => {
filter!(self.span_utils, item.ident.span); filter!(self.span_utils, item.ident.span);
let id = id_from_node_id(item.id, self); let id = id_from_def_id(def_id);
let span = self.span_from_span(item.ident.span); let span = self.span_from_span(item.ident.span);
Some(Data::DefData(Def { Some(Data::DefData(Def {
@ -171,28 +171,23 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> {
decl_id: None, decl_id: None,
docs: self.docs_for_attrs(&item.attrs), docs: self.docs_for_attrs(&item.attrs),
sig: sig::foreign_item_signature(item, self), sig: sig::foreign_item_signature(item, self),
attributes: lower_attributes(item.attrs.clone(), self), attributes: lower_attributes(item.attrs.to_vec(), self),
})) }))
} }
// FIXME(plietar): needs a new DefKind in rls-data // FIXME(plietar): needs a new DefKind in rls-data
ast::ForeignItemKind::TyAlias(..) => None, hir::ForeignItemKind::Type => None,
ast::ForeignItemKind::MacCall(..) => None,
} }
} }
pub fn get_item_data(&self, item: &ast::Item) -> Option<Data> { pub fn get_item_data(&self, item: &hir::Item<'_>) -> Option<Data> {
let def_id = self.tcx.hir().local_def_id(item.hir_id).to_def_id();
match item.kind { match item.kind {
ast::ItemKind::Fn(_, ref sig, .., ref generics, _) => { hir::ItemKind::Fn(ref sig, ref generics, _) => {
let qualname = format!( let qualname = format!("::{}", self.tcx.def_path_str(def_id));
"::{}",
self.tcx.def_path_str(
self.tcx.hir().local_def_id_from_node_id(item.id).to_def_id()
)
);
filter!(self.span_utils, item.ident.span); filter!(self.span_utils, item.ident.span);
Some(Data::DefData(Def { Some(Data::DefData(Def {
kind: DefKind::Function, kind: DefKind::Function,
id: id_from_node_id(item.id, self), id: id_from_def_id(def_id),
span: self.span_from_span(item.ident.span), span: self.span_from_span(item.ident.span),
name: item.ident.to_string(), name: item.ident.to_string(),
qualname, qualname,
@ -202,20 +197,15 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> {
decl_id: None, decl_id: None,
docs: self.docs_for_attrs(&item.attrs), docs: self.docs_for_attrs(&item.attrs),
sig: sig::item_signature(item, self), sig: sig::item_signature(item, self),
attributes: lower_attributes(item.attrs.clone(), self), attributes: lower_attributes(item.attrs.to_vec(), self),
})) }))
} }
ast::ItemKind::Static(ref typ, ..) => { hir::ItemKind::Static(ref typ, ..) => {
let qualname = format!( let qualname = format!("::{}", self.tcx.def_path_str(def_id));
"::{}",
self.tcx.def_path_str(
self.tcx.hir().local_def_id_from_node_id(item.id).to_def_id()
)
);
filter!(self.span_utils, item.ident.span); filter!(self.span_utils, item.ident.span);
let id = id_from_node_id(item.id, self); let id = id_from_def_id(def_id);
let span = self.span_from_span(item.ident.span); let span = self.span_from_span(item.ident.span);
Some(Data::DefData(Def { Some(Data::DefData(Def {
@ -230,19 +220,14 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> {
decl_id: None, decl_id: None,
docs: self.docs_for_attrs(&item.attrs), docs: self.docs_for_attrs(&item.attrs),
sig: sig::item_signature(item, self), sig: sig::item_signature(item, self),
attributes: lower_attributes(item.attrs.clone(), self), attributes: lower_attributes(item.attrs.to_vec(), self),
})) }))
} }
ast::ItemKind::Const(_, ref typ, _) => { hir::ItemKind::Const(ref typ, _) => {
let qualname = format!( let qualname = format!("::{}", self.tcx.def_path_str(def_id));
"::{}",
self.tcx.def_path_str(
self.tcx.hir().local_def_id_from_node_id(item.id).to_def_id()
)
);
filter!(self.span_utils, item.ident.span); filter!(self.span_utils, item.ident.span);
let id = id_from_node_id(item.id, self); let id = id_from_def_id(def_id);
let span = self.span_from_span(item.ident.span); let span = self.span_from_span(item.ident.span);
Some(Data::DefData(Def { Some(Data::DefData(Def {
@ -257,16 +242,11 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> {
decl_id: None, decl_id: None,
docs: self.docs_for_attrs(&item.attrs), docs: self.docs_for_attrs(&item.attrs),
sig: sig::item_signature(item, self), sig: sig::item_signature(item, self),
attributes: lower_attributes(item.attrs.clone(), self), attributes: lower_attributes(item.attrs.to_vec(), self),
})) }))
} }
ast::ItemKind::Mod(ref m) => { hir::ItemKind::Mod(ref m) => {
let qualname = format!( let qualname = format!("::{}", self.tcx.def_path_str(def_id));
"::{}",
self.tcx.def_path_str(
self.tcx.hir().local_def_id_from_node_id(item.id).to_def_id()
)
);
let sm = self.tcx.sess.source_map(); let sm = self.tcx.sess.source_map();
let filename = sm.span_to_filename(m.inner); let filename = sm.span_to_filename(m.inner);
@ -275,48 +255,43 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> {
Some(Data::DefData(Def { Some(Data::DefData(Def {
kind: DefKind::Mod, kind: DefKind::Mod,
id: id_from_node_id(item.id, self), id: id_from_def_id(def_id),
name: item.ident.to_string(), name: item.ident.to_string(),
qualname, qualname,
span: self.span_from_span(item.ident.span), span: self.span_from_span(item.ident.span),
value: filename.to_string(), value: filename.to_string(),
parent: None, parent: None,
children: m.items.iter().map(|i| id_from_node_id(i.id, self)).collect(), children: m.item_ids.iter().map(|i| id_from_hir_id(i.id, self)).collect(),
decl_id: None, decl_id: None,
docs: self.docs_for_attrs(&item.attrs), docs: self.docs_for_attrs(&item.attrs),
sig: sig::item_signature(item, self), sig: sig::item_signature(item, self),
attributes: lower_attributes(item.attrs.clone(), self), attributes: lower_attributes(item.attrs.to_vec(), self),
})) }))
} }
ast::ItemKind::Enum(ref def, _) => { hir::ItemKind::Enum(ref def, _) => {
let name = item.ident.to_string(); let name = item.ident.to_string();
let qualname = format!( let qualname = format!("::{}", self.tcx.def_path_str(def_id));
"::{}",
self.tcx.def_path_str(
self.tcx.hir().local_def_id_from_node_id(item.id).to_def_id()
)
);
filter!(self.span_utils, item.ident.span); filter!(self.span_utils, item.ident.span);
let variants_str = let variants_str =
def.variants.iter().map(|v| v.ident.to_string()).collect::<Vec<_>>().join(", "); def.variants.iter().map(|v| v.ident.to_string()).collect::<Vec<_>>().join(", ");
let value = format!("{}::{{{}}}", name, variants_str); let value = format!("{}::{{{}}}", name, variants_str);
Some(Data::DefData(Def { Some(Data::DefData(Def {
kind: DefKind::Enum, kind: DefKind::Enum,
id: id_from_node_id(item.id, self), id: id_from_def_id(def_id),
span: self.span_from_span(item.ident.span), span: self.span_from_span(item.ident.span),
name, name,
qualname, qualname,
value, value,
parent: None, parent: None,
children: def.variants.iter().map(|v| id_from_node_id(v.id, self)).collect(), children: def.variants.iter().map(|v| id_from_hir_id(v.id, self)).collect(),
decl_id: None, decl_id: None,
docs: self.docs_for_attrs(&item.attrs), docs: self.docs_for_attrs(&item.attrs),
sig: sig::item_signature(item, self), sig: sig::item_signature(item, self),
attributes: lower_attributes(item.attrs.clone(), self), attributes: lower_attributes(item.attrs.to_vec(), self),
})) }))
} }
ast::ItemKind::Impl { ref of_trait, ref self_ty, ref items, .. } => { hir::ItemKind::Impl { ref of_trait, ref self_ty, ref items, .. } => {
if let ast::TyKind::Path(None, ref path) = self_ty.kind { if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = self_ty.kind {
// Common case impl for a struct or something basic. // Common case impl for a struct or something basic.
if generated_code(path.span) { if generated_code(path.span) {
return None; return None;
@ -327,7 +302,7 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> {
let impl_id = self.next_impl_id(); let impl_id = self.next_impl_id();
let span = self.span_from_span(sub_span); let span = self.span_from_span(sub_span);
let type_data = self.lookup_def_id(self_ty.id); let type_data = self.lookup_def_id(self_ty.hir_id);
type_data.map(|type_data| { type_data.map(|type_data| {
Data::RelationData( Data::RelationData(
Relation { Relation {
@ -336,7 +311,7 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> {
from: id_from_def_id(type_data), from: id_from_def_id(type_data),
to: of_trait to: of_trait
.as_ref() .as_ref()
.and_then(|t| self.lookup_def_id(t.ref_id)) .and_then(|t| self.lookup_def_id(t.hir_ref_id))
.map(id_from_def_id) .map(id_from_def_id)
.unwrap_or_else(null_id), .unwrap_or_else(null_id),
}, },
@ -351,7 +326,7 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> {
parent: None, parent: None,
children: items children: items
.iter() .iter()
.map(|i| id_from_node_id(i.id, self)) .map(|i| id_from_hir_id(i.id.hir_id, self))
.collect(), .collect(),
docs: String::new(), docs: String::new(),
sig: None, sig: None,
@ -370,126 +345,120 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> {
} }
} }
pub fn get_field_data(&self, field: &ast::StructField, scope: NodeId) -> Option<Def> { pub fn get_field_data(&self, field: &hir::StructField<'_>, scope: hir::HirId) -> Option<Def> {
if let Some(ident) = field.ident { let name = field.ident.to_string();
let name = ident.to_string(); let scope_def_id = self.tcx.hir().local_def_id(scope).to_def_id();
let qualname = format!( let qualname = format!("::{}::{}", self.tcx.def_path_str(scope_def_id), field.ident);
"::{}::{}", filter!(self.span_utils, field.ident.span);
self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(scope).to_def_id()), let field_def_id = self.tcx.hir().local_def_id(field.hir_id).to_def_id();
ident let typ = self.tcx.type_of(field_def_id).to_string();
);
filter!(self.span_utils, ident.span);
let def_id = self.tcx.hir().local_def_id_from_node_id(field.id).to_def_id();
let typ = self.tcx.type_of(def_id).to_string();
let id = id_from_node_id(field.id, self); let id = id_from_def_id(field_def_id);
let span = self.span_from_span(ident.span); let span = self.span_from_span(field.ident.span);
Some(Def { Some(Def {
kind: DefKind::Field, kind: DefKind::Field,
id, id,
span, span,
name, name,
qualname, qualname,
value: typ, value: typ,
parent: Some(id_from_node_id(scope, self)), parent: Some(id_from_def_id(scope_def_id)),
children: vec![], children: vec![],
decl_id: None, decl_id: None,
docs: self.docs_for_attrs(&field.attrs), docs: self.docs_for_attrs(&field.attrs),
sig: sig::field_signature(field, self), sig: sig::field_signature(field, self),
attributes: lower_attributes(field.attrs.clone(), self), attributes: lower_attributes(field.attrs.to_vec(), self),
}) })
} else {
None
}
} }
// FIXME would be nice to take a MethodItem here, but the ast provides both // 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. // trait and impl flavours, so the caller must do the disassembly.
pub fn get_method_data(&self, id: ast::NodeId, ident: Ident, span: Span) -> Option<Def> { pub fn get_method_data(&self, hir_id: hir::HirId, ident: Ident, span: Span) -> Option<Def> {
// The qualname for a method is the trait name or name of the struct in an impl in // 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. // which the method is declared in, followed by the method's name.
let (qualname, parent_scope, decl_id, docs, attributes) = match self let def_id = self.tcx.hir().local_def_id(hir_id).to_def_id();
.tcx let (qualname, parent_scope, decl_id, docs, attributes) =
.impl_of_method(self.tcx.hir().local_def_id_from_node_id(id).to_def_id()) match self.tcx.impl_of_method(def_id) {
{ Some(impl_id) => match self.tcx.hir().get_if_local(impl_id) {
Some(impl_id) => match self.tcx.hir().get_if_local(impl_id) { Some(Node::Item(item)) => match item.kind {
Some(Node::Item(item)) => match item.kind { hir::ItemKind::Impl { ref self_ty, .. } => {
hir::ItemKind::Impl { ref self_ty, .. } => { let hir = self.tcx.hir();
let hir = self.tcx.hir();
let mut qualname = String::from("<"); let mut qualname = String::from("<");
qualname.push_str(&rustc_hir_pretty::id_to_string(&hir, self_ty.hir_id)); qualname
.push_str(&rustc_hir_pretty::id_to_string(&hir, self_ty.hir_id));
let trait_id = self.tcx.trait_id_of_impl(impl_id); let trait_id = self.tcx.trait_id_of_impl(impl_id);
let mut docs = String::new();
let mut attrs = vec![];
if let Some(Node::ImplItem(item)) = hir.find(hir_id) {
docs = self.docs_for_attrs(&item.attrs);
attrs = item.attrs.to_vec();
}
let mut decl_id = None;
if let Some(def_id) = trait_id {
// A method in a trait impl.
qualname.push_str(" as ");
qualname.push_str(&self.tcx.def_path_str(def_id));
decl_id = self
.tcx
.associated_items(def_id)
.filter_by_name_unhygienic(ident.name)
.next()
.map(|item| item.def_id);
}
qualname.push_str(">");
(qualname, trait_id, decl_id, docs, attrs)
}
_ => {
span_bug!(
span,
"Container {:?} for method {} not an impl?",
impl_id,
hir_id
);
}
},
r => {
span_bug!(
span,
"Container {:?} for method {} is not a node item {:?}",
impl_id,
hir_id,
r
);
}
},
None => match self.tcx.trait_of_item(def_id) {
Some(def_id) => {
let mut docs = String::new(); let mut docs = String::new();
let mut attrs = vec![]; let mut attrs = vec![];
if let Some(Node::ImplItem(item)) = hir.find(hir.node_id_to_hir_id(id)) {
if let Some(Node::TraitItem(item)) = self.tcx.hir().find(hir_id) {
docs = self.docs_for_attrs(&item.attrs); docs = self.docs_for_attrs(&item.attrs);
attrs = item.attrs.to_vec(); attrs = item.attrs.to_vec();
} }
let mut decl_id = None; (
if let Some(def_id) = trait_id { format!("::{}", self.tcx.def_path_str(def_id)),
// A method in a trait impl. Some(def_id),
qualname.push_str(" as "); None,
qualname.push_str(&self.tcx.def_path_str(def_id)); docs,
attrs,
decl_id = self )
.tcx
.associated_items(def_id)
.filter_by_name_unhygienic(ident.name)
.next()
.map(|item| item.def_id);
}
qualname.push_str(">");
(qualname, trait_id, decl_id, docs, attrs)
} }
_ => { None => {
span_bug!(span, "Container {:?} for method {} not an impl?", impl_id, id); debug!("could not find container for method {} at {:?}", hir_id, span);
// This is not necessarily a bug, if there was a compilation error,
// the tables we need might not exist.
return None;
} }
}, },
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_from_node_id(id).to_def_id())
{
Some(def_id) => {
let mut docs = String::new();
let mut attrs = vec![];
let hir_id = self.tcx.hir().node_id_to_hir_id(id);
if let Some(Node::TraitItem(item)) = self.tcx.hir().find(hir_id) {
docs = self.docs_for_attrs(&item.attrs);
attrs = item.attrs.to_vec();
}
(
format!("::{}", self.tcx.def_path_str(def_id)),
Some(def_id),
None,
docs,
attrs,
)
}
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, ident.name); let qualname = format!("{}::{}", qualname, ident.name);
@ -497,7 +466,7 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> {
Some(Def { Some(Def {
kind: DefKind::Method, kind: DefKind::Method,
id: id_from_node_id(id, self), id: id_from_def_id(def_id),
span: self.span_from_span(ident.span), span: self.span_from_span(ident.span),
name: ident.name.to_string(), name: ident.name.to_string(),
qualname, qualname,
@ -512,8 +481,8 @@ impl<'l, 'tcx> 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: &hir::TraitRef<'_>) -> Option<Ref> {
self.lookup_def_id(trait_ref.ref_id).and_then(|def_id| { self.lookup_def_id(trait_ref.hir_ref_id).and_then(|def_id| {
let span = trait_ref.path.span; let span = trait_ref.path.span;
if generated_code(span) { if generated_code(span) {
return None; return None;
@ -525,22 +494,20 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> {
}) })
} }
pub fn get_expr_data(&self, expr: &ast::Expr) -> Option<Data> { pub fn get_expr_data(&self, expr: &hir::Expr<'_>) -> Option<Data> {
let expr_hir_id = self.tcx.hir().node_id_to_hir_id(expr.id); let hir_node = self.tcx.hir().expect_expr(expr.hir_id);
let hir_node = self.tcx.hir().expect_expr(expr_hir_id);
let ty = self.tables.expr_ty_adjusted_opt(&hir_node); let ty = self.tables.expr_ty_adjusted_opt(&hir_node);
if ty.is_none() || ty.unwrap().kind == ty::Error { if ty.is_none() || ty.unwrap().kind == ty::Error {
return None; return None;
} }
match expr.kind { match expr.kind {
ast::ExprKind::Field(ref sub_ex, ident) => { hir::ExprKind::Field(ref sub_ex, ident) => {
let sub_ex_hir_id = self.tcx.hir().node_id_to_hir_id(sub_ex.id); let hir_node = match self.tcx.hir().find(sub_ex.hir_id) {
let hir_node = match self.tcx.hir().find(sub_ex_hir_id) {
Some(Node::Expr(expr)) => expr, Some(Node::Expr(expr)) => expr,
_ => { _ => {
debug!( debug!(
"Missing or weird node for sub-expression {} in {:?}", "Missing or weird node for sub-expression {} in {:?}",
sub_ex.id, expr sub_ex.hir_id, expr
); );
return None; return None;
} }
@ -567,7 +534,7 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> {
} }
} }
} }
ast::ExprKind::Struct(ref path, ..) => { hir::ExprKind::Struct(hir::QPath::Resolved(_, path), ..) => {
match self.tables.expr_ty_adjusted(&hir_node).kind { match self.tables.expr_ty_adjusted(&hir_node).kind {
ty::Adt(def, _) if !def.is_enum() => { ty::Adt(def, _) if !def.is_enum() => {
let sub_span = path.segments.last().unwrap().ident.span; let sub_span = path.segments.last().unwrap().ident.span;
@ -587,9 +554,8 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> {
} }
} }
} }
ast::ExprKind::MethodCall(ref seg, ..) => { hir::ExprKind::MethodCall(ref seg, ..) => {
let expr_hir_id = self.tcx.hir().definitions().node_id_to_hir_id(expr.id); let method_id = match self.tables.type_dependent_def_id(expr.hir_id) {
let method_id = match self.tables.type_dependent_def_id(expr_hir_id) {
Some(id) => id, Some(id) => id,
None => { None => {
debug!("could not resolve method id for {:?}", expr); debug!("could not resolve method id for {:?}", expr);
@ -609,8 +575,8 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> {
ref_id: def_id.or(decl_id).map(id_from_def_id).unwrap_or_else(null_id), ref_id: def_id.or(decl_id).map(id_from_def_id).unwrap_or_else(null_id),
})) }))
} }
ast::ExprKind::Path(_, ref path) => { hir::ExprKind::Path(hir::QPath::Resolved(_, path)) => {
self.get_path_data(expr.id, path).map(Data::RefData) self.get_path_data(expr.hir_id, path).map(Data::RefData)
} }
_ => { _ => {
// FIXME // FIXME
@ -619,12 +585,7 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> {
} }
} }
pub fn get_path_res(&self, id: NodeId) -> Res { pub fn get_path_res(&self, hir_id: hir::HirId) -> Res {
// FIXME(#71104)
let hir_id = match self.tcx.hir().opt_node_id_to_hir_id(id) {
Some(id) => id,
None => return Res::Err,
};
match self.tcx.hir().get(hir_id) { match self.tcx.hir().get(hir_id) {
Node::TraitRef(tr) => tr.path.res, Node::TraitRef(tr) => tr.path.res,
@ -638,7 +599,7 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> {
Some(res) if res != Res::Err => res, Some(res) if res != Res::Err => res,
_ => { _ => {
let parent_node = self.tcx.hir().get_parent_node(hir_id); let parent_node = self.tcx.hir().get_parent_node(hir_id);
self.get_path_res(self.tcx.hir().hir_id_to_node_id(parent_node)) self.get_path_res(parent_node)
} }
}, },
@ -666,33 +627,24 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> {
} }
} }
pub fn get_path_data(&self, id: NodeId, path: &ast::Path) -> Option<Ref> { pub fn get_path_data(&self, id: hir::HirId, path: &hir::Path<'_>) -> Option<Ref> {
path.segments.last().and_then(|seg| { path.segments.last().and_then(|seg| {
self.get_path_segment_data(seg).or_else(|| self.get_path_segment_data_with_id(seg, id)) self.get_path_segment_data(seg).or_else(|| self.get_path_segment_data_with_id(seg, id))
}) })
} }
pub fn get_path_segment_data(&self, path_seg: &ast::PathSegment) -> Option<Ref> { pub fn get_path_segment_data(&self, path_seg: &hir::PathSegment<'_>) -> Option<Ref> {
self.get_path_segment_data_with_id(path_seg, path_seg.id) self.get_path_segment_data_with_id(path_seg, path_seg.hir_id?)
} }
fn get_path_segment_data_with_id( pub fn get_path_segment_data_with_id(
&self, &self,
path_seg: &ast::PathSegment, path_seg: &hir::PathSegment<'_>,
id: NodeId, id: hir::HirId,
) -> Option<Ref> { ) -> Option<Ref> {
// Returns true if the path is function type sugar, e.g., `Fn(A) -> B`. // Returns true if the path is function type sugar, e.g., `Fn(A) -> B`.
fn fn_type(seg: &ast::PathSegment) -> bool { fn fn_type(seg: &hir::PathSegment<'_>) -> bool {
if let Some(ref generic_args) = seg.args { seg.args.map(|args| args.parenthesized).unwrap_or(false)
if let ast::GenericArgs::Parenthesized(_) = **generic_args {
return true;
}
}
false
}
if id == DUMMY_NODE_ID {
return None;
} }
let res = self.get_path_res(id); let res = self.get_path_res(id);
@ -701,11 +653,9 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> {
let span = self.span_from_span(span); let span = self.span_from_span(span);
match res { match res {
Res::Local(id) => Some(Ref { Res::Local(id) => {
kind: RefKind::Variable, Some(Ref { kind: RefKind::Variable, span, ref_id: id_from_hir_id(id, self) })
span, }
ref_id: id_from_node_id(self.tcx.hir().hir_id_to_node_id(id), self),
}),
Res::Def(HirDefKind::Trait, def_id) if fn_type(path_seg) => { Res::Def(HirDefKind::Trait, def_id) if fn_type(path_seg) => {
Some(Ref { kind: RefKind::Type, span, ref_id: id_from_def_id(def_id) }) Some(Ref { kind: RefKind::Type, span, ref_id: id_from_def_id(def_id) })
} }
@ -791,7 +741,7 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> {
pub fn get_field_ref_data( pub fn get_field_ref_data(
&self, &self,
field_ref: &ast::Field, field_ref: &hir::Field<'_>,
variant: &ty::VariantDef, variant: &ty::VariantDef,
) -> Option<Ref> { ) -> Option<Ref> {
filter!(self.span_utils, field_ref.ident.span); filter!(self.span_utils, field_ref.ident.span);
@ -839,14 +789,14 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> {
}) })
} }
fn lookup_def_id(&self, ref_id: NodeId) -> Option<DefId> { fn lookup_def_id(&self, ref_id: hir::HirId) -> Option<DefId> {
match self.get_path_res(ref_id) { match self.get_path_res(ref_id) {
Res::PrimTy(_) | Res::SelfTy(..) | Res::Err => None, Res::PrimTy(_) | Res::SelfTy(..) | Res::Err => None,
def => def.opt_def_id(), def => def.opt_def_id(),
} }
} }
fn docs_for_attrs(&self, attrs: &[Attribute]) -> String { fn docs_for_attrs(&self, attrs: &[ast::Attribute]) -> String {
let mut result = String::new(); let mut result = String::new();
for attr in attrs { for attr in attrs {
@ -890,7 +840,7 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> {
} }
} }
fn make_signature(decl: &ast::FnDecl, generics: &ast::Generics) -> String { fn make_signature(decl: &hir::FnDecl<'_>, generics: &hir::Generics<'_>) -> String {
let mut sig = "fn ".to_owned(); let mut sig = "fn ".to_owned();
if !generics.params.is_empty() { if !generics.params.is_empty() {
sig.push('<'); sig.push('<');
@ -898,18 +848,18 @@ fn make_signature(decl: &ast::FnDecl, generics: &ast::Generics) -> String {
&generics &generics
.params .params
.iter() .iter()
.map(|param| param.ident.to_string()) .map(|param| param.name.ident().to_string())
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(", "), .join(", "),
); );
sig.push_str("> "); sig.push_str("> ");
} }
sig.push('('); sig.push('(');
sig.push_str(&decl.inputs.iter().map(param_to_string).collect::<Vec<_>>().join(", ")); sig.push_str(&decl.inputs.iter().map(ty_to_string).collect::<Vec<_>>().join(", "));
sig.push(')'); sig.push(')');
match decl.output { match decl.output {
ast::FnRetTy::Default(_) => sig.push_str(" -> ()"), hir::FnRetTy::DefaultReturn(_) => sig.push_str(" -> ()"),
ast::FnRetTy::Ty(ref t) => sig.push_str(&format!(" -> {}", ty_to_string(t))), hir::FnRetTy::Return(ref t) => sig.push_str(&format!(" -> {}", ty_to_string(t))),
} }
sig sig
@ -918,26 +868,33 @@ fn make_signature(decl: &ast::FnDecl, generics: &ast::Generics) -> String {
// An AST visitor for collecting paths (e.g., the names of structs) and formal // An AST visitor for collecting paths (e.g., the names of structs) and formal
// variables (idents) from patterns. // variables (idents) from patterns.
struct PathCollector<'l> { struct PathCollector<'l> {
collected_paths: Vec<(NodeId, &'l ast::Path)>, tcx: TyCtxt<'l>,
collected_idents: Vec<(NodeId, Ident, ast::Mutability)>, collected_paths: Vec<(hir::HirId, &'l hir::QPath<'l>)>,
collected_idents: Vec<(hir::HirId, Ident, hir::Mutability)>,
} }
impl<'l> PathCollector<'l> { impl<'l> PathCollector<'l> {
fn new() -> PathCollector<'l> { fn new(tcx: TyCtxt<'l>) -> PathCollector<'l> {
PathCollector { collected_paths: vec![], collected_idents: vec![] } PathCollector { tcx, collected_paths: vec![], collected_idents: vec![] }
} }
} }
impl<'l> Visitor<'l> for PathCollector<'l> { impl<'l> Visitor<'l> for PathCollector<'l> {
fn visit_pat(&mut self, p: &'l ast::Pat) { type Map = Map<'l>;
fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
intravisit::NestedVisitorMap::All(self.tcx.hir())
}
fn visit_pat(&mut self, p: &'l hir::Pat<'l>) {
match p.kind { match p.kind {
PatKind::Struct(ref path, ..) => { hir::PatKind::Struct(ref path, ..) => {
self.collected_paths.push((p.id, path)); self.collected_paths.push((p.hir_id, path));
} }
PatKind::TupleStruct(ref path, ..) | PatKind::Path(_, ref path) => { hir::PatKind::TupleStruct(ref path, ..) | hir::PatKind::Path(ref path) => {
self.collected_paths.push((p.id, path)); self.collected_paths.push((p.hir_id, path));
} }
PatKind::Ident(bm, ident, _) => { hir::PatKind::Binding(bm, _, ident, _) => {
debug!( debug!(
"PathCollector, visit ident in pat {}: {:?} {:?}", "PathCollector, visit ident in pat {}: {:?} {:?}",
ident, p.span, ident.span ident, p.span, ident.span
@ -946,14 +903,18 @@ impl<'l> Visitor<'l> for PathCollector<'l> {
// Even if the ref is mut, you can't change the ref, only // Even if the ref is mut, you can't change the ref, only
// the data pointed at, so showing the initialising expression // the data pointed at, so showing the initialising expression
// is still worthwhile. // is still worthwhile.
ast::BindingMode::ByRef(_) => ast::Mutability::Not, hir::BindingAnnotation::Unannotated | hir::BindingAnnotation::Ref => {
ast::BindingMode::ByValue(mt) => mt, hir::Mutability::Not
}
hir::BindingAnnotation::Mutable | hir::BindingAnnotation::RefMut => {
hir::Mutability::Mut
}
}; };
self.collected_idents.push((p.id, ident, immut)); self.collected_idents.push((p.hir_id, ident, immut));
} }
_ => {} _ => {}
} }
visit::walk_pat(self, p); intravisit::walk_pat(self, p);
} }
} }
@ -1035,7 +996,6 @@ impl SaveHandler for CallbackHandler<'_> {
pub fn process_crate<'l, 'tcx, H: SaveHandler>( pub fn process_crate<'l, 'tcx, H: SaveHandler>(
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
krate: &ast::Crate,
cratename: &str, cratename: &str,
input: &'l Input, input: &'l Input,
config: Option<Config>, config: Option<Config>,
@ -1063,9 +1023,9 @@ pub fn process_crate<'l, 'tcx, H: SaveHandler>(
let mut visitor = DumpVisitor::new(save_ctxt); let mut visitor = DumpVisitor::new(save_ctxt);
visitor.dump_crate_info(cratename, krate); visitor.dump_crate_info(cratename, tcx.hir().krate());
visitor.dump_compilation_options(input, cratename); visitor.dump_compilation_options(input, cratename);
visit::walk_crate(&mut visitor, krate); visitor.process_crate(tcx.hir().krate());
handler.save(&visitor.save_ctxt, &visitor.analysis()) handler.save(&visitor.save_ctxt, &visitor.analysis())
}) })
@ -1109,13 +1069,17 @@ fn id_from_def_id(id: DefId) -> rls_data::Id {
rls_data::Id { krate: id.krate.as_u32(), index: id.index.as_u32() } 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 { fn id_from_hir_id(id: hir::HirId, scx: &SaveContext<'_, '_>) -> rls_data::Id {
let def_id = scx.tcx.hir().opt_local_def_id_from_node_id(id); let def_id = scx.tcx.hir().opt_local_def_id(id);
def_id.map(|id| id_from_def_id(id.to_def_id())).unwrap_or_else(|| { def_id.map(|id| id_from_def_id(id.to_def_id())).unwrap_or_else(|| {
// Create a *fake* `DefId` out of a `NodeId` by subtracting the `NodeId` // Create a *fake* `DefId` out of a `HirId` by combining the owner
// out of the maximum u32 value. This will work unless you have *billions* // `local_def_index` and the `local_id`.
// of definitions in a single crate (very unlikely to actually happen). // This will work unless you have *billions* of definitions in a single
rls_data::Id { krate: LOCAL_CRATE.as_u32(), index: !id.as_u32() } // crate (very unlikely to actually happen).
rls_data::Id {
krate: LOCAL_CRATE.as_u32(),
index: id.owner.local_def_index.as_u32() | id.local_id.as_u32().reverse_bits(),
}
}) })
} }
@ -1123,7 +1087,10 @@ fn null_id() -> rls_data::Id {
rls_data::Id { krate: u32::max_value(), index: u32::max_value() } rls_data::Id { krate: u32::max_value(), index: u32::max_value() }
} }
fn lower_attributes(attrs: Vec<Attribute>, scx: &SaveContext<'_, '_>) -> Vec<rls_data::Attribute> { fn lower_attributes(
attrs: Vec<ast::Attribute>,
scx: &SaveContext<'_, '_>,
) -> Vec<rls_data::Attribute> {
attrs attrs
.into_iter() .into_iter()
// Only retain real attributes. Doc comments are lowered separately. // Only retain real attributes. Doc comments are lowered separately.
@ -1133,7 +1100,7 @@ fn lower_attributes(attrs: Vec<Attribute>, scx: &SaveContext<'_, '_>) -> Vec<rls
// attribute. First normalize all inner attribute (#![..]) to outer // attribute. First normalize all inner attribute (#![..]) to outer
// ones (#[..]), then remove the two leading and the one trailing character. // ones (#[..]), then remove the two leading and the one trailing character.
attr.style = ast::AttrStyle::Outer; attr.style = ast::AttrStyle::Outer;
let value = pprust::attribute_to_string(&attr); let value = attribute_to_string(&attr);
// This str slicing works correctly, because the leading and trailing characters // This str slicing works correctly, because the leading and trailing characters
// are in the ASCII range and thus exactly one byte each. // are in the ASCII range and thus exactly one byte each.
let value = value[2..value.len() - 1].to_string(); let value = value[2..value.len() - 1].to_string();

View file

@ -25,16 +25,18 @@
// //
// FIXME where clauses need implementing, defs/refs in generics are mostly missing. // FIXME where clauses need implementing, defs/refs in generics are mostly missing.
use crate::{id_from_def_id, id_from_node_id, SaveContext}; use crate::{id_from_def_id, id_from_hir_id, SaveContext};
use rls_data::{SigElement, Signature}; use rls_data::{SigElement, Signature};
use rustc_ast::ast::{self, Extern, NodeId}; use rustc_ast::ast::Mutability;
use rustc_ast_pretty::pprust; use rustc_hir as hir;
use rustc_hir::def::{DefKind, Res}; use rustc_hir::def::{DefKind, Res};
use rustc_hir_pretty::id_to_string;
use rustc_hir_pretty::{bounds_to_string, path_segment_to_string, path_to_string, ty_to_string};
use rustc_span::symbol::{Ident, Symbol}; use rustc_span::symbol::{Ident, Symbol};
pub fn item_signature(item: &ast::Item, scx: &SaveContext<'_, '_>) -> Option<Signature> { pub fn item_signature(item: &hir::Item<'_>, scx: &SaveContext<'_, '_>) -> Option<Signature> {
if !scx.config.signatures { if !scx.config.signatures {
return None; return None;
} }
@ -42,7 +44,7 @@ pub fn item_signature(item: &ast::Item, scx: &SaveContext<'_, '_>) -> Option<Sig
} }
pub fn foreign_item_signature( pub fn foreign_item_signature(
item: &ast::ForeignItem, item: &hir::ForeignItem<'_>,
scx: &SaveContext<'_, '_>, scx: &SaveContext<'_, '_>,
) -> Option<Signature> { ) -> Option<Signature> {
if !scx.config.signatures { if !scx.config.signatures {
@ -53,7 +55,10 @@ pub fn foreign_item_signature(
/// Signature for a struct or tuple field declaration. /// Signature for a struct or tuple field declaration.
/// Does not include a trailing comma. /// Does not include a trailing comma.
pub fn field_signature(field: &ast::StructField, scx: &SaveContext<'_, '_>) -> Option<Signature> { pub fn field_signature(
field: &hir::StructField<'_>,
scx: &SaveContext<'_, '_>,
) -> Option<Signature> {
if !scx.config.signatures { if !scx.config.signatures {
return None; return None;
} }
@ -61,7 +66,10 @@ pub fn field_signature(field: &ast::StructField, scx: &SaveContext<'_, '_>) -> O
} }
/// Does not include a trailing comma. /// Does not include a trailing comma.
pub fn variant_signature(variant: &ast::Variant, scx: &SaveContext<'_, '_>) -> Option<Signature> { pub fn variant_signature(
variant: &hir::Variant<'_>,
scx: &SaveContext<'_, '_>,
) -> Option<Signature> {
if !scx.config.signatures { if !scx.config.signatures {
return None; return None;
} }
@ -69,10 +77,10 @@ pub fn variant_signature(variant: &ast::Variant, scx: &SaveContext<'_, '_>) -> O
} }
pub fn method_signature( pub fn method_signature(
id: NodeId, id: hir::HirId,
ident: Ident, ident: Ident,
generics: &ast::Generics, generics: &hir::Generics<'_>,
m: &ast::FnSig, m: &hir::FnSig<'_>,
scx: &SaveContext<'_, '_>, scx: &SaveContext<'_, '_>,
) -> Option<Signature> { ) -> Option<Signature> {
if !scx.config.signatures { if !scx.config.signatures {
@ -82,10 +90,10 @@ pub fn method_signature(
} }
pub fn assoc_const_signature( pub fn assoc_const_signature(
id: NodeId, id: hir::HirId,
ident: Symbol, ident: Symbol,
ty: &ast::Ty, ty: &hir::Ty<'_>,
default: Option<&ast::Expr>, default: Option<&hir::Expr<'_>>,
scx: &SaveContext<'_, '_>, scx: &SaveContext<'_, '_>,
) -> Option<Signature> { ) -> Option<Signature> {
if !scx.config.signatures { if !scx.config.signatures {
@ -95,10 +103,10 @@ pub fn assoc_const_signature(
} }
pub fn assoc_type_signature( pub fn assoc_type_signature(
id: NodeId, id: hir::HirId,
ident: Ident, ident: Ident,
bounds: Option<&ast::GenericBounds>, bounds: Option<hir::GenericBounds<'_>>,
default: Option<&ast::Ty>, default: Option<&hir::Ty<'_>>,
scx: &SaveContext<'_, '_>, scx: &SaveContext<'_, '_>,
) -> Option<Signature> { ) -> Option<Signature> {
if !scx.config.signatures { if !scx.config.signatures {
@ -110,7 +118,7 @@ pub fn assoc_type_signature(
type Result = std::result::Result<Signature, &'static str>; type Result = std::result::Result<Signature, &'static str>;
trait Sig { trait Sig {
fn make(&self, offset: usize, id: Option<NodeId>, scx: &SaveContext<'_, '_>) -> Result; fn make(&self, offset: usize, id: Option<hir::HirId>, scx: &SaveContext<'_, '_>) -> Result;
} }
fn extend_sig( fn extend_sig(
@ -145,39 +153,34 @@ fn text_sig(text: String) -> Signature {
Signature { text, defs: vec![], refs: vec![] } Signature { text, defs: vec![], refs: vec![] }
} }
fn push_extern(text: &mut String, ext: Extern) { impl<'hir> Sig for hir::Ty<'hir> {
match ext { fn make(
Extern::None => {} &self,
Extern::Implicit => text.push_str("extern "), offset: usize,
Extern::Explicit(abi) => text.push_str(&format!("extern \"{}\" ", abi.symbol)), _parent_id: Option<hir::HirId>,
} scx: &SaveContext<'_, '_>,
} ) -> Result {
let id = Some(self.hir_id);
impl Sig for ast::Ty {
fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext<'_, '_>) -> Result {
let id = Some(self.id);
match self.kind { match self.kind {
ast::TyKind::Slice(ref ty) => { hir::TyKind::Slice(ref ty) => {
let nested = ty.make(offset + 1, id, scx)?; let nested = ty.make(offset + 1, id, scx)?;
let text = format!("[{}]", nested.text); let text = format!("[{}]", nested.text);
Ok(replace_text(nested, text)) Ok(replace_text(nested, text))
} }
ast::TyKind::Ptr(ref mt) => { hir::TyKind::Ptr(ref mt) => {
let prefix = match mt.mutbl { let prefix = match mt.mutbl {
ast::Mutability::Mut => "*mut ", hir::Mutability::Mut => "*mut ",
ast::Mutability::Not => "*const ", hir::Mutability::Not => "*const ",
}; };
let nested = mt.ty.make(offset + prefix.len(), id, scx)?; let nested = mt.ty.make(offset + prefix.len(), id, scx)?;
let text = format!("{}{}", prefix, nested.text); let text = format!("{}{}", prefix, nested.text);
Ok(replace_text(nested, text)) Ok(replace_text(nested, text))
} }
ast::TyKind::Rptr(ref lifetime, ref mt) => { hir::TyKind::Rptr(ref lifetime, ref mt) => {
let mut prefix = "&".to_owned(); let mut prefix = "&".to_owned();
if let &Some(ref l) = lifetime { prefix.push_str(&lifetime.name.ident().to_string());
prefix.push_str(&l.ident.to_string()); prefix.push(' ');
prefix.push(' '); if let hir::Mutability::Mut = mt.mutbl {
}
if let ast::Mutability::Mut = mt.mutbl {
prefix.push_str("mut "); prefix.push_str("mut ");
}; };
@ -185,9 +188,8 @@ impl Sig for ast::Ty {
let text = format!("{}{}", prefix, nested.text); let text = format!("{}{}", prefix, nested.text);
Ok(replace_text(nested, text)) Ok(replace_text(nested, text))
} }
ast::TyKind::Never => Ok(text_sig("!".to_owned())), hir::TyKind::Never => Ok(text_sig("!".to_owned())),
ast::TyKind::CVarArgs => Ok(text_sig("...".to_owned())), hir::TyKind::Tup(ts) => {
ast::TyKind::Tup(ref ts) => {
let mut text = "(".to_owned(); let mut text = "(".to_owned();
let mut defs = vec![]; let mut defs = vec![];
let mut refs = vec![]; let mut refs = vec![];
@ -201,12 +203,7 @@ impl Sig for ast::Ty {
text.push(')'); text.push(')');
Ok(Signature { text, defs, refs }) Ok(Signature { text, defs, refs })
} }
ast::TyKind::Paren(ref ty) => { hir::TyKind::BareFn(ref f) => {
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(); let mut text = String::new();
if !f.generic_params.is_empty() { if !f.generic_params.is_empty() {
// FIXME defs, bounds on lifetimes // FIXME defs, bounds on lifetimes
@ -215,8 +212,8 @@ impl Sig for ast::Ty {
&f.generic_params &f.generic_params
.iter() .iter()
.filter_map(|param| match param.kind { .filter_map(|param| match param.kind {
ast::GenericParamKind::Lifetime { .. } => { hir::GenericParamKind::Lifetime { .. } => {
Some(param.ident.to_string()) Some(param.name.ident().to_string())
} }
_ => None, _ => None,
}) })
@ -226,23 +223,22 @@ impl Sig for ast::Ty {
text.push('>'); text.push('>');
} }
if let ast::Unsafe::Yes(_) = f.unsafety { if let hir::Unsafety::Unsafe = f.unsafety {
text.push_str("unsafe "); text.push_str("unsafe ");
} }
push_extern(&mut text, f.ext);
text.push_str("fn("); text.push_str("fn(");
let mut defs = vec![]; let mut defs = vec![];
let mut refs = vec![]; let mut refs = vec![];
for i in &f.decl.inputs { for i in f.decl.inputs {
let nested = i.ty.make(offset + text.len(), Some(i.id), scx)?; let nested = i.make(offset + text.len(), Some(i.hir_id), scx)?;
text.push_str(&nested.text); text.push_str(&nested.text);
text.push(','); text.push(',');
defs.extend(nested.defs.into_iter()); defs.extend(nested.defs.into_iter());
refs.extend(nested.refs.into_iter()); refs.extend(nested.refs.into_iter());
} }
text.push(')'); text.push(')');
if let ast::FnRetTy::Ty(ref t) = f.decl.output { if let hir::FnRetTy::Return(ref t) = f.decl.output {
text.push_str(" -> "); text.push_str(" -> ");
let nested = t.make(offset + text.len(), None, scx)?; let nested = t.make(offset + text.len(), None, scx)?;
text.push_str(&nested.text); text.push_str(&nested.text);
@ -253,23 +249,19 @@ impl Sig for ast::Ty {
Ok(Signature { text, defs, refs }) Ok(Signature { text, defs, refs })
} }
ast::TyKind::Path(None, ref path) => path.make(offset, id, scx), hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => path.make(offset, id, scx),
ast::TyKind::Path(Some(ref qself), ref path) => { hir::TyKind::Path(hir::QPath::Resolved(Some(ref qself), ref path)) => {
let nested_ty = qself.ty.make(offset + 1, id, scx)?; let nested_ty = qself.make(offset + 1, id, scx)?;
let prefix = if qself.position == 0 { let prefix = format!(
format!("<{}>::", nested_ty.text) "<{} as {}>::",
} else if qself.position == 1 { nested_ty.text,
let first = pprust::path_segment_to_string(&path.segments[0]); path_segment_to_string(&path.segments[0])
format!("<{} as {}>::", nested_ty.text, first) );
} else {
// FIXME handle path instead of elipses.
format!("<{} as ...>::", nested_ty.text)
};
let name = pprust::path_segment_to_string(path.segments.last().ok_or("Bad path")?); let name = path_segment_to_string(path.segments.last().ok_or("Bad path")?);
let res = scx.get_path_res(id.ok_or("Missing id for Path")?); let res = scx.get_path_res(id.ok_or("Missing id for Path")?);
let id = id_from_def_id(res.def_id()); let id = id_from_def_id(res.def_id());
if path.segments.len() - qself.position == 1 { if path.segments.len() == 2 {
let start = offset + prefix.len(); let start = offset + prefix.len();
let end = start + name.len(); let end = start + name.len();
@ -289,44 +281,60 @@ impl Sig for ast::Ty {
}) })
} }
} }
ast::TyKind::TraitObject(ref bounds, ..) => { hir::TyKind::TraitObject(bounds, ..) => {
// FIXME recurse into bounds // FIXME recurse into bounds
let nested = pprust::bounds_to_string(bounds); let bounds: Vec<hir::GenericBound<'_>> = bounds
.iter()
.map(|hir::PolyTraitRef { bound_generic_params, trait_ref, span }| {
hir::GenericBound::Trait(
hir::PolyTraitRef {
bound_generic_params,
trait_ref: hir::TraitRef {
path: trait_ref.path,
hir_ref_id: trait_ref.hir_ref_id,
},
span: *span,
},
hir::TraitBoundModifier::None,
)
})
.collect();
let nested = bounds_to_string(&bounds);
Ok(text_sig(nested)) Ok(text_sig(nested))
} }
ast::TyKind::ImplTrait(_, ref bounds) => { hir::TyKind::Array(ref ty, ref anon_const) => {
// 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 nested_ty = ty.make(offset + 1, id, scx)?;
let expr = pprust::expr_to_string(&v.value).replace('\n', " "); let expr = id_to_string(&scx.tcx.hir(), anon_const.body.hir_id).replace('\n', " ");
let text = format!("[{}; {}]", nested_ty.text, expr); let text = format!("[{}; {}]", nested_ty.text, expr);
Ok(replace_text(nested_ty, text)) Ok(replace_text(nested_ty, text))
} }
ast::TyKind::Typeof(_) hir::TyKind::Typeof(_)
| ast::TyKind::Infer | hir::TyKind::Infer
| ast::TyKind::Err | hir::TyKind::Def(..)
| ast::TyKind::ImplicitSelf | hir::TyKind::Path(..)
| ast::TyKind::MacCall(_) => Err("Ty"), | hir::TyKind::Err => Err("Ty"),
} }
} }
} }
impl Sig for ast::Item { impl<'hir> Sig for hir::Item<'hir> {
fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext<'_, '_>) -> Result { fn make(
let id = Some(self.id); &self,
offset: usize,
_parent_id: Option<hir::HirId>,
scx: &SaveContext<'_, '_>,
) -> Result {
let id = Some(self.hir_id);
match self.kind { match self.kind {
ast::ItemKind::Static(ref ty, m, ref expr) => { hir::ItemKind::Static(ref ty, m, ref body) => {
let mut text = "static ".to_owned(); let mut text = "static ".to_owned();
if m == ast::Mutability::Mut { if m == hir::Mutability::Mut {
text.push_str("mut "); text.push_str("mut ");
} }
let name = self.ident.to_string(); let name = self.ident.to_string();
let defs = vec![SigElement { let defs = vec![SigElement {
id: id_from_node_id(self.id, scx), id: id_from_hir_id(self.hir_id, scx),
start: offset + text.len(), start: offset + text.len(),
end: offset + text.len() + name.len(), end: offset + text.len() + name.len(),
}]; }];
@ -336,21 +344,19 @@ impl Sig for ast::Item {
let ty = ty.make(offset + text.len(), id, scx)?; let ty = ty.make(offset + text.len(), id, scx)?;
text.push_str(&ty.text); text.push_str(&ty.text);
if let Some(expr) = expr { text.push_str(" = ");
text.push_str(" = "); let expr = id_to_string(&scx.tcx.hir(), body.hir_id).replace('\n', " ");
let expr = pprust::expr_to_string(expr).replace('\n', " "); text.push_str(&expr);
text.push_str(&expr);
}
text.push(';'); text.push(';');
Ok(extend_sig(ty, text, defs, vec![])) Ok(extend_sig(ty, text, defs, vec![]))
} }
ast::ItemKind::Const(_, ref ty, ref expr) => { hir::ItemKind::Const(ref ty, ref body) => {
let mut text = "const ".to_owned(); let mut text = "const ".to_owned();
let name = self.ident.to_string(); let name = self.ident.to_string();
let defs = vec![SigElement { let defs = vec![SigElement {
id: id_from_node_id(self.id, scx), id: id_from_hir_id(self.hir_id, scx),
start: offset + text.len(), start: offset + text.len(),
end: offset + text.len() + name.len(), end: offset + text.len() + name.len(),
}]; }];
@ -360,38 +366,35 @@ impl Sig for ast::Item {
let ty = ty.make(offset + text.len(), id, scx)?; let ty = ty.make(offset + text.len(), id, scx)?;
text.push_str(&ty.text); text.push_str(&ty.text);
if let Some(expr) = expr { text.push_str(" = ");
text.push_str(" = "); let expr = id_to_string(&scx.tcx.hir(), body.hir_id).replace('\n', " ");
let expr = pprust::expr_to_string(expr).replace('\n', " "); text.push_str(&expr);
text.push_str(&expr);
}
text.push(';'); text.push(';');
Ok(extend_sig(ty, text, defs, vec![])) Ok(extend_sig(ty, text, defs, vec![]))
} }
ast::ItemKind::Fn(_, ast::FnSig { ref decl, header }, ref generics, _) => { hir::ItemKind::Fn(hir::FnSig { ref decl, header }, ref generics, _) => {
let mut text = String::new(); let mut text = String::new();
if let ast::Const::Yes(_) = header.constness { if let hir::Constness::Const = header.constness {
text.push_str("const "); text.push_str("const ");
} }
if header.asyncness.is_async() { if hir::IsAsync::Async == header.asyncness {
text.push_str("async "); text.push_str("async ");
} }
if let ast::Unsafe::Yes(_) = header.unsafety { if let hir::Unsafety::Unsafe = header.unsafety {
text.push_str("unsafe "); text.push_str("unsafe ");
} }
push_extern(&mut text, header.ext);
text.push_str("fn "); 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.hir_id, self.ident, scx)?;
sig.text.push('('); sig.text.push('(');
for i in &decl.inputs { for i in decl.inputs {
// FIXME should descend into patterns to add defs. // FIXME should descend into patterns to add defs.
sig.text.push_str(&pprust::pat_to_string(&i.pat));
sig.text.push_str(": "); sig.text.push_str(": ");
let nested = i.ty.make(offset + sig.text.len(), Some(i.id), scx)?; let nested = i.make(offset + sig.text.len(), Some(i.hir_id), scx)?;
sig.text.push_str(&nested.text); sig.text.push_str(&nested.text);
sig.text.push(','); sig.text.push(',');
sig.defs.extend(nested.defs.into_iter()); sig.defs.extend(nested.defs.into_iter());
@ -399,7 +402,7 @@ impl Sig for ast::Item {
} }
sig.text.push(')'); sig.text.push(')');
if let ast::FnRetTy::Ty(ref t) = decl.output { if let hir::FnRetTy::Return(ref t) = decl.output {
sig.text.push_str(" -> "); sig.text.push_str(" -> ");
let nested = t.make(offset + sig.text.len(), None, scx)?; let nested = t.make(offset + sig.text.len(), None, scx)?;
sig.text.push_str(&nested.text); sig.text.push_str(&nested.text);
@ -410,11 +413,11 @@ impl Sig for ast::Item {
Ok(sig) Ok(sig)
} }
ast::ItemKind::Mod(ref _mod) => { hir::ItemKind::Mod(ref _mod) => {
let mut text = "mod ".to_owned(); let mut text = "mod ".to_owned();
let name = self.ident.to_string(); let name = self.ident.to_string();
let defs = vec![SigElement { let defs = vec![SigElement {
id: id_from_node_id(self.id, scx), id: id_from_hir_id(self.hir_id, scx),
start: offset + text.len(), start: offset + text.len(),
end: offset + text.len() + name.len(), end: offset + text.len() + name.len(),
}]; }];
@ -424,78 +427,82 @@ impl Sig for ast::Item {
Ok(Signature { text, defs, refs: vec![] }) Ok(Signature { text, defs, refs: vec![] })
} }
ast::ItemKind::TyAlias(_, ref generics, _, ref ty) => { hir::ItemKind::TyAlias(ref ty, ref generics) => {
let text = "type ".to_owned(); 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.hir_id, self.ident, scx)?;
sig.text.push_str(" = "); sig.text.push_str(" = ");
let ty = match ty { let ty = ty.make(offset + sig.text.len(), id, scx)?;
Some(ty) => ty.make(offset + sig.text.len(), id, scx)?,
None => return Err("Ty"),
};
sig.text.push_str(&ty.text); sig.text.push_str(&ty.text);
sig.text.push(';'); sig.text.push(';');
Ok(merge_sigs(sig.text.clone(), vec![sig, ty])) Ok(merge_sigs(sig.text.clone(), vec![sig, ty]))
} }
ast::ItemKind::Enum(_, ref generics) => { hir::ItemKind::Enum(_, ref generics) => {
let text = "enum ".to_owned(); 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.hir_id, self.ident, scx)?;
sig.text.push_str(" {}"); sig.text.push_str(" {}");
Ok(sig) Ok(sig)
} }
ast::ItemKind::Struct(_, ref generics) => { hir::ItemKind::Struct(_, ref generics) => {
let text = "struct ".to_owned(); 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.hir_id, self.ident, scx)?;
sig.text.push_str(" {}"); sig.text.push_str(" {}");
Ok(sig) Ok(sig)
} }
ast::ItemKind::Union(_, ref generics) => { hir::ItemKind::Union(_, ref generics) => {
let text = "union ".to_owned(); 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.hir_id, self.ident, scx)?;
sig.text.push_str(" {}"); sig.text.push_str(" {}");
Ok(sig) Ok(sig)
} }
ast::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, _) => { hir::ItemKind::Trait(is_auto, unsafety, ref generics, bounds, _) => {
let mut text = String::new(); let mut text = String::new();
if is_auto == ast::IsAuto::Yes { if is_auto == hir::IsAuto::Yes {
text.push_str("auto "); text.push_str("auto ");
} }
if let ast::Unsafe::Yes(_) = unsafety { if let hir::Unsafety::Unsafe = unsafety {
text.push_str("unsafe "); text.push_str("unsafe ");
} }
text.push_str("trait "); 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.hir_id, self.ident, scx)?;
if !bounds.is_empty() { if !bounds.is_empty() {
sig.text.push_str(": "); sig.text.push_str(": ");
sig.text.push_str(&pprust::bounds_to_string(bounds)); sig.text.push_str(&bounds_to_string(bounds));
} }
// FIXME where clause // FIXME where clause
sig.text.push_str(" {}"); sig.text.push_str(" {}");
Ok(sig) Ok(sig)
} }
ast::ItemKind::TraitAlias(ref generics, ref bounds) => { hir::ItemKind::TraitAlias(ref generics, bounds) => {
let mut text = String::new(); let mut text = String::new();
text.push_str("trait "); 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.hir_id, self.ident, scx)?;
if !bounds.is_empty() { if !bounds.is_empty() {
sig.text.push_str(" = "); sig.text.push_str(" = ");
sig.text.push_str(&pprust::bounds_to_string(bounds)); sig.text.push_str(&bounds_to_string(bounds));
} }
// FIXME where clause // FIXME where clause
sig.text.push_str(";"); sig.text.push_str(";");
Ok(sig) Ok(sig)
} }
ast::ItemKind::Impl { hir::ItemKind::Impl {
unsafety, unsafety,
polarity, polarity,
defaultness, defaultness,
defaultness_span: _,
constness, constness,
ref generics, ref generics,
ref of_trait, ref of_trait,
@ -503,14 +510,14 @@ impl Sig for ast::Item {
items: _, items: _,
} => { } => {
let mut text = String::new(); let mut text = String::new();
if let ast::Defaultness::Default(_) = defaultness { if let hir::Defaultness::Default { .. } = defaultness {
text.push_str("default "); text.push_str("default ");
} }
if let ast::Unsafe::Yes(_) = unsafety { if let hir::Unsafety::Unsafe = unsafety {
text.push_str("unsafe "); text.push_str("unsafe ");
} }
text.push_str("impl"); text.push_str("impl");
if let ast::Const::Yes(_) = constness { if let hir::Constness::Const = constness {
text.push_str(" const"); text.push_str(" const");
} }
@ -520,7 +527,7 @@ impl Sig for ast::Item {
text.push(' '); text.push(' ');
let trait_sig = if let Some(ref t) = *of_trait { let trait_sig = if let Some(ref t) = *of_trait {
if let ast::ImplPolarity::Negative(_) = polarity { if let hir::ImplPolarity::Negative(_) = polarity {
text.push('!'); text.push('!');
} }
let trait_sig = t.path.make(offset + text.len(), id, scx)?; let trait_sig = t.path.make(offset + text.len(), id, scx)?;
@ -540,27 +547,23 @@ impl Sig for ast::Item {
// FIXME where clause // FIXME where clause
} }
ast::ItemKind::ForeignMod(_) => Err("extern mod"), hir::ItemKind::ForeignMod(_) => Err("extern mod"),
ast::ItemKind::GlobalAsm(_) => Err("glboal asm"), hir::ItemKind::GlobalAsm(_) => Err("glboal asm"),
ast::ItemKind::ExternCrate(_) => Err("extern crate"), hir::ItemKind::ExternCrate(_) => Err("extern crate"),
hir::ItemKind::OpaqueTy(..) => Err("opaque type"),
// FIXME should implement this (e.g., pub use). // FIXME should implement this (e.g., pub use).
ast::ItemKind::Use(_) => Err("import"), hir::ItemKind::Use(..) => Err("import"),
ast::ItemKind::MacCall(..) | ast::ItemKind::MacroDef(_) => Err("Macro"),
} }
} }
} }
impl Sig for ast::Path { impl<'hir> Sig for hir::Path<'hir> {
fn make(&self, offset: usize, id: Option<NodeId>, scx: &SaveContext<'_, '_>) -> Result { fn make(&self, offset: usize, id: Option<hir::HirId>, scx: &SaveContext<'_, '_>) -> Result {
let res = scx.get_path_res(id.ok_or("Missing id for Path")?); let res = scx.get_path_res(id.ok_or("Missing id for Path")?);
let (name, start, end) = match res { let (name, start, end) = match res {
Res::PrimTy(..) | Res::SelfTy(..) | Res::Err => { Res::PrimTy(..) | Res::SelfTy(..) | Res::Err => {
return Ok(Signature { return Ok(Signature { text: path_to_string(self), defs: vec![], refs: vec![] });
text: pprust::path_to_string(self),
defs: vec![],
refs: vec![],
});
} }
Res::Def(DefKind::AssocConst | DefKind::Variant | DefKind::Ctor(..), _) => { Res::Def(DefKind::AssocConst | DefKind::Variant | DefKind::Ctor(..), _) => {
let len = self.segments.len(); let len = self.segments.len();
@ -570,13 +573,13 @@ impl Sig for ast::Path {
// FIXME: really we should descend into the generics here and add SigElements for // FIXME: really we should descend into the generics here and add SigElements for
// them. // them.
// FIXME: would be nice to have a def for the first path segment. // 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 seg1 = path_segment_to_string(&self.segments[len - 2]);
let seg2 = pprust::path_segment_to_string(&self.segments[len - 1]); let seg2 = path_segment_to_string(&self.segments[len - 1]);
let start = offset + seg1.len() + 2; let start = offset + seg1.len() + 2;
(format!("{}::{}", seg1, seg2), start, start + seg2.len()) (format!("{}::{}", seg1, seg2), start, start + seg2.len())
} }
_ => { _ => {
let name = pprust::path_segment_to_string(self.segments.last().ok_or("Bad path")?); let name = path_segment_to_string(self.segments.last().ok_or("Bad path")?);
let end = offset + name.len(); let end = offset + name.len();
(name, offset, end) (name, offset, end)
} }
@ -588,8 +591,13 @@ impl Sig for ast::Path {
} }
// This does not cover the where clause, which must be processed separately. // This does not cover the where clause, which must be processed separately.
impl Sig for ast::Generics { impl<'hir> Sig for hir::Generics<'hir> {
fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext<'_, '_>) -> Result { fn make(
&self,
offset: usize,
_parent_id: Option<hir::HirId>,
scx: &SaveContext<'_, '_>,
) -> Result {
if self.params.is_empty() { if self.params.is_empty() {
return Ok(text_sig(String::new())); return Ok(text_sig(String::new()));
} }
@ -597,30 +605,30 @@ impl Sig for ast::Generics {
let mut text = "<".to_owned(); let mut text = "<".to_owned();
let mut defs = Vec::with_capacity(self.params.len()); let mut defs = Vec::with_capacity(self.params.len());
for param in &self.params { for param in self.params {
let mut param_text = String::new(); let mut param_text = String::new();
if let ast::GenericParamKind::Const { .. } = param.kind { if let hir::GenericParamKind::Const { .. } = param.kind {
param_text.push_str("const "); param_text.push_str("const ");
} }
param_text.push_str(&param.ident.as_str()); param_text.push_str(&param.name.ident().as_str());
defs.push(SigElement { defs.push(SigElement {
id: id_from_node_id(param.id, scx), id: id_from_hir_id(param.hir_id, scx),
start: offset + text.len(), start: offset + text.len(),
end: offset + text.len() + param_text.as_str().len(), end: offset + text.len() + param_text.as_str().len(),
}); });
if let ast::GenericParamKind::Const { ref ty } = param.kind { if let hir::GenericParamKind::Const { ref ty } = param.kind {
param_text.push_str(": "); param_text.push_str(": ");
param_text.push_str(&pprust::ty_to_string(&ty)); param_text.push_str(&ty_to_string(&ty));
} }
if !param.bounds.is_empty() { if !param.bounds.is_empty() {
param_text.push_str(": "); param_text.push_str(": ");
match param.kind { match param.kind {
ast::GenericParamKind::Lifetime { .. } => { hir::GenericParamKind::Lifetime { .. } => {
let bounds = param let bounds = param
.bounds .bounds
.iter() .iter()
.map(|bound| match bound { .map(|bound| match bound {
ast::GenericBound::Outlives(lt) => lt.ident.to_string(), hir::GenericBound::Outlives(lt) => lt.name.ident().to_string(),
_ => panic!(), _ => panic!(),
}) })
.collect::<Vec<_>>() .collect::<Vec<_>>()
@ -628,11 +636,11 @@ impl Sig for ast::Generics {
param_text.push_str(&bounds); param_text.push_str(&bounds);
// FIXME add lifetime bounds refs. // FIXME add lifetime bounds refs.
} }
ast::GenericParamKind::Type { .. } => { hir::GenericParamKind::Type { .. } => {
param_text.push_str(&pprust::bounds_to_string(&param.bounds)); param_text.push_str(&bounds_to_string(param.bounds));
// FIXME descend properly into bounds. // FIXME descend properly into bounds.
} }
ast::GenericParamKind::Const { .. } => { hir::GenericParamKind::Const { .. } => {
// Const generics cannot contain bounds. // Const generics cannot contain bounds.
} }
} }
@ -646,21 +654,24 @@ impl Sig for ast::Generics {
} }
} }
impl Sig for ast::StructField { impl<'hir> Sig for hir::StructField<'hir> {
fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext<'_, '_>) -> Result { fn make(
&self,
offset: usize,
_parent_id: Option<hir::HirId>,
scx: &SaveContext<'_, '_>,
) -> Result {
let mut text = String::new(); let mut text = String::new();
let mut defs = None;
if let Some(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(&self.ident.to_string());
let defs = Some(SigElement {
id: id_from_hir_id(self.hir_id, scx),
start: offset,
end: offset + text.len(),
});
text.push_str(": ");
let mut ty_sig = self.ty.make(offset + text.len(), Some(self.hir_id), scx)?;
text.push_str(&ty_sig.text); text.push_str(&ty_sig.text);
ty_sig.text = text; ty_sig.text = text;
ty_sig.defs.extend(defs.into_iter()); ty_sig.defs.extend(defs.into_iter());
@ -668,14 +679,19 @@ impl Sig for ast::StructField {
} }
} }
impl Sig for ast::Variant { impl<'hir> Sig for hir::Variant<'hir> {
fn make(&self, offset: usize, parent_id: Option<NodeId>, scx: &SaveContext<'_, '_>) -> Result { fn make(
&self,
offset: usize,
parent_id: Option<hir::HirId>,
scx: &SaveContext<'_, '_>,
) -> Result {
let mut text = self.ident.to_string(); let mut text = self.ident.to_string();
match self.data { match self.data {
ast::VariantData::Struct(ref fields, r) => { hir::VariantData::Struct(fields, r) => {
let id = parent_id.unwrap(); let id = parent_id.unwrap();
let name_def = SigElement { let name_def = SigElement {
id: id_from_node_id(id, scx), id: id_from_hir_id(id, scx),
start: offset, start: offset,
end: offset + text.len(), end: offset + text.len(),
}; };
@ -696,9 +712,9 @@ impl Sig for ast::Variant {
text.push('}'); text.push('}');
Ok(Signature { text, defs, refs }) Ok(Signature { text, defs, refs })
} }
ast::VariantData::Tuple(ref fields, id) => { hir::VariantData::Tuple(fields, id) => {
let name_def = SigElement { let name_def = SigElement {
id: id_from_node_id(id, scx), id: id_from_hir_id(id, scx),
start: offset, start: offset,
end: offset + text.len(), end: offset + text.len(),
}; };
@ -715,9 +731,9 @@ impl Sig for ast::Variant {
text.push(')'); text.push(')');
Ok(Signature { text, defs, refs }) Ok(Signature { text, defs, refs })
} }
ast::VariantData::Unit(id) => { hir::VariantData::Unit(id) => {
let name_def = SigElement { let name_def = SigElement {
id: id_from_node_id(id, scx), id: id_from_hir_id(id, scx),
start: offset, start: offset,
end: offset + text.len(), end: offset + text.len(),
}; };
@ -727,23 +743,26 @@ impl Sig for ast::Variant {
} }
} }
impl Sig for ast::ForeignItem { impl<'hir> Sig for hir::ForeignItem<'hir> {
fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext<'_, '_>) -> Result { fn make(
let id = Some(self.id); &self,
offset: usize,
_parent_id: Option<hir::HirId>,
scx: &SaveContext<'_, '_>,
) -> Result {
let id = Some(self.hir_id);
match self.kind { match self.kind {
ast::ForeignItemKind::Fn(_, ref sig, ref generics, _) => { hir::ForeignItemKind::Fn(decl, _, ref generics) => {
let decl = &sig.decl;
let mut text = String::new(); let mut text = String::new();
text.push_str("fn "); 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.hir_id, self.ident, scx)?;
sig.text.push('('); sig.text.push('(');
for i in &decl.inputs { 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(": "); sig.text.push_str(": ");
let nested = i.ty.make(offset + sig.text.len(), Some(i.id), scx)?; let nested = i.make(offset + sig.text.len(), Some(i.hir_id), scx)?;
sig.text.push_str(&nested.text); sig.text.push_str(&nested.text);
sig.text.push(','); sig.text.push(',');
sig.defs.extend(nested.defs.into_iter()); sig.defs.extend(nested.defs.into_iter());
@ -751,7 +770,7 @@ impl Sig for ast::ForeignItem {
} }
sig.text.push(')'); sig.text.push(')');
if let ast::FnRetTy::Ty(ref t) = decl.output { if let hir::FnRetTy::Return(ref t) = decl.output {
sig.text.push_str(" -> "); sig.text.push_str(" -> ");
let nested = t.make(offset + sig.text.len(), None, scx)?; let nested = t.make(offset + sig.text.len(), None, scx)?;
sig.text.push_str(&nested.text); sig.text.push_str(&nested.text);
@ -762,14 +781,14 @@ impl Sig for ast::ForeignItem {
Ok(sig) Ok(sig)
} }
ast::ForeignItemKind::Static(ref ty, m, _) => { hir::ForeignItemKind::Static(ref ty, m) => {
let mut text = "static ".to_owned(); let mut text = "static ".to_owned();
if m == ast::Mutability::Mut { if m == Mutability::Mut {
text.push_str("mut "); text.push_str("mut ");
} }
let name = self.ident.to_string(); let name = self.ident.to_string();
let defs = vec![SigElement { let defs = vec![SigElement {
id: id_from_node_id(self.id, scx), id: id_from_hir_id(self.hir_id, scx),
start: offset + text.len(), start: offset + text.len(),
end: offset + text.len() + name.len(), end: offset + text.len() + name.len(),
}]; }];
@ -781,11 +800,11 @@ impl Sig for ast::ForeignItem {
Ok(extend_sig(ty_sig, text, defs, vec![])) Ok(extend_sig(ty_sig, text, defs, vec![]))
} }
ast::ForeignItemKind::TyAlias(..) => { hir::ForeignItemKind::Type => {
let mut text = "type ".to_owned(); let mut text = "type ".to_owned();
let name = self.ident.to_string(); let name = self.ident.to_string();
let defs = vec![SigElement { let defs = vec![SigElement {
id: id_from_node_id(self.id, scx), id: id_from_hir_id(self.hir_id, scx),
start: offset + text.len(), start: offset + text.len(),
end: offset + text.len() + name.len(), end: offset + text.len() + name.len(),
}]; }];
@ -794,7 +813,6 @@ impl Sig for ast::ForeignItem {
Ok(Signature { text, defs, refs: vec![] }) Ok(Signature { text, defs, refs: vec![] })
} }
ast::ForeignItemKind::MacCall(..) => Err("macro"),
} }
} }
} }
@ -802,14 +820,14 @@ impl Sig for ast::ForeignItem {
fn name_and_generics( fn name_and_generics(
mut text: String, mut text: String,
offset: usize, offset: usize,
generics: &ast::Generics, generics: &hir::Generics<'_>,
id: NodeId, id: hir::HirId,
name: Ident, name: Ident,
scx: &SaveContext<'_, '_>, scx: &SaveContext<'_, '_>,
) -> Result { ) -> Result {
let name = name.to_string(); let name = name.to_string();
let def = SigElement { let def = SigElement {
id: id_from_node_id(id, scx), id: id_from_hir_id(id, scx),
start: offset + text.len(), start: offset + text.len(),
end: offset + text.len() + name.len(), end: offset + text.len() + name.len(),
}; };
@ -821,16 +839,16 @@ fn name_and_generics(
} }
fn make_assoc_type_signature( fn make_assoc_type_signature(
id: NodeId, id: hir::HirId,
ident: Ident, ident: Ident,
bounds: Option<&ast::GenericBounds>, bounds: Option<hir::GenericBounds<'_>>,
default: Option<&ast::Ty>, default: Option<&hir::Ty<'_>>,
scx: &SaveContext<'_, '_>, scx: &SaveContext<'_, '_>,
) -> Result { ) -> Result {
let mut text = "type ".to_owned(); let mut text = "type ".to_owned();
let name = ident.to_string(); let name = ident.to_string();
let mut defs = vec![SigElement { let mut defs = vec![SigElement {
id: id_from_node_id(id, scx), id: id_from_hir_id(id, scx),
start: text.len(), start: text.len(),
end: text.len() + name.len(), end: text.len() + name.len(),
}]; }];
@ -839,7 +857,7 @@ fn make_assoc_type_signature(
if let Some(bounds) = bounds { if let Some(bounds) = bounds {
text.push_str(": "); text.push_str(": ");
// FIXME should descend into bounds // FIXME should descend into bounds
text.push_str(&pprust::bounds_to_string(bounds)); text.push_str(&bounds_to_string(bounds));
} }
if let Some(default) = default { if let Some(default) = default {
text.push_str(" = "); text.push_str(" = ");
@ -853,16 +871,16 @@ fn make_assoc_type_signature(
} }
fn make_assoc_const_signature( fn make_assoc_const_signature(
id: NodeId, id: hir::HirId,
ident: Symbol, ident: Symbol,
ty: &ast::Ty, ty: &hir::Ty<'_>,
default: Option<&ast::Expr>, default: Option<&hir::Expr<'_>>,
scx: &SaveContext<'_, '_>, scx: &SaveContext<'_, '_>,
) -> Result { ) -> Result {
let mut text = "const ".to_owned(); let mut text = "const ".to_owned();
let name = ident.to_string(); let name = ident.to_string();
let mut defs = vec![SigElement { let mut defs = vec![SigElement {
id: id_from_node_id(id, scx), id: id_from_hir_id(id, scx),
start: text.len(), start: text.len(),
end: text.len() + name.len(), end: text.len() + name.len(),
}]; }];
@ -877,41 +895,38 @@ fn make_assoc_const_signature(
if let Some(default) = default { if let Some(default) = default {
text.push_str(" = "); text.push_str(" = ");
text.push_str(&pprust::expr_to_string(default)); text.push_str(&id_to_string(&scx.tcx.hir(), default.hir_id));
} }
text.push(';'); text.push(';');
Ok(Signature { text, defs, refs }) Ok(Signature { text, defs, refs })
} }
fn make_method_signature( fn make_method_signature(
id: NodeId, id: hir::HirId,
ident: Ident, ident: Ident,
generics: &ast::Generics, generics: &hir::Generics<'_>,
m: &ast::FnSig, m: &hir::FnSig<'_>,
scx: &SaveContext<'_, '_>, scx: &SaveContext<'_, '_>,
) -> Result { ) -> Result {
// FIXME code dup with function signature // FIXME code dup with function signature
let mut text = String::new(); let mut text = String::new();
if let ast::Const::Yes(_) = m.header.constness { if let hir::Constness::Const = m.header.constness {
text.push_str("const "); text.push_str("const ");
} }
if m.header.asyncness.is_async() { if hir::IsAsync::Async == m.header.asyncness {
text.push_str("async "); text.push_str("async ");
} }
if let ast::Unsafe::Yes(_) = m.header.unsafety { if let hir::Unsafety::Unsafe = m.header.unsafety {
text.push_str("unsafe "); text.push_str("unsafe ");
} }
push_extern(&mut text, m.header.ext);
text.push_str("fn "); 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('('); sig.text.push('(');
for i in &m.decl.inputs { for i in m.decl.inputs {
// FIXME should descend into patterns to add defs.
sig.text.push_str(&pprust::pat_to_string(&i.pat));
sig.text.push_str(": "); sig.text.push_str(": ");
let nested = i.ty.make(sig.text.len(), Some(i.id), scx)?; let nested = i.make(sig.text.len(), Some(i.hir_id), scx)?;
sig.text.push_str(&nested.text); sig.text.push_str(&nested.text);
sig.text.push(','); sig.text.push(',');
sig.defs.extend(nested.defs.into_iter()); sig.defs.extend(nested.defs.into_iter());
@ -919,7 +934,7 @@ fn make_method_signature(
} }
sig.text.push(')'); sig.text.push(')');
if let ast::FnRetTy::Ty(ref t) = m.decl.output { if let hir::FnRetTy::Return(ref t) = m.decl.output {
sig.text.push_str(" -> "); sig.text.push_str(" -> ");
let nested = t.make(sig.text.len(), None, scx)?; let nested = t.make(sig.text.len(), None, scx)?;
sig.text.push_str(&nested.text); sig.text.push_str(&nested.text);