1
Fork 0

Simplify if let/match expressions

This commit is contained in:
mitaa 2016-02-28 12:11:13 +01:00
parent 62267470f6
commit 8f6e09a956
8 changed files with 212 additions and 320 deletions

View file

@ -138,13 +138,10 @@ pub fn load_attrs(cx: &DocContext, tcx: &TyCtxt,
/// These names are used later on by HTML rendering to generate things like /// These names are used later on by HTML rendering to generate things like
/// source links back to the original item. /// source links back to the original item.
pub fn record_extern_fqn(cx: &DocContext, did: DefId, kind: clean::TypeKind) { pub fn record_extern_fqn(cx: &DocContext, did: DefId, kind: clean::TypeKind) {
match cx.tcx_opt() { if let Some(tcx) = cx.tcx_opt() {
Some(tcx) => { let fqn = tcx.sess.cstore.extern_item_path(did);
let fqn = tcx.sess.cstore.extern_item_path(did); let fqn = fqn.into_iter().map(|i| i.to_string()).collect();
let fqn = fqn.into_iter().map(|i| i.to_string()).collect(); cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, kind));
cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, kind));
}
None => {}
} }
} }
@ -230,12 +227,9 @@ pub fn build_impls(cx: &DocContext, tcx: &TyCtxt,
tcx.populate_inherent_implementations_for_type_if_necessary(did); tcx.populate_inherent_implementations_for_type_if_necessary(did);
let mut impls = Vec::new(); let mut impls = Vec::new();
match tcx.inherent_impls.borrow().get(&did) { if let Some(i) = tcx.inherent_impls.borrow().get(&did) {
None => {} for &did in i.iter() {
Some(i) => { build_impl(cx, tcx, did, &mut impls);
for &did in i.iter() {
build_impl(cx, tcx, did, &mut impls);
}
} }
} }
@ -464,9 +458,8 @@ fn build_module(cx: &DocContext, tcx: &TyCtxt,
} }
cstore::DlDef(def) if item.vis == hir::Public => { cstore::DlDef(def) if item.vis == hir::Public => {
if !visited.insert(def) { continue } if !visited.insert(def) { continue }
match try_inline_def(cx, tcx, def) { if let Some(i) = try_inline_def(cx, tcx, def) {
Some(i) => items.extend(i), items.extend(i)
None => {}
} }
} }
cstore::DlDef(..) => {} cstore::DlDef(..) => {}

View file

@ -100,10 +100,7 @@ impl<T: Clean<U>, U> Clean<U> for Rc<T> {
impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> { impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
fn clean(&self, cx: &DocContext) -> Option<U> { fn clean(&self, cx: &DocContext) -> Option<U> {
match self { self.as_ref().map(|v| v.clean(cx))
&None => None,
&Some(ref v) => Some(v.clean(cx))
}
} }
} }
@ -332,27 +329,20 @@ impl Item {
} }
pub fn stability_class(&self) -> String { pub fn stability_class(&self) -> String {
match self.stability { self.stability.as_ref().map(|ref s| {
Some(ref s) => { let mut base = match s.level {
let mut base = match s.level { stability::Unstable => "unstable".to_string(),
stability::Unstable => "unstable".to_string(), stability::Stable => String::new(),
stability::Stable => String::new(), };
}; if !s.deprecated_since.is_empty() {
if !s.deprecated_since.is_empty() { base.push_str(" deprecated");
base.push_str(" deprecated");
}
base
} }
_ => String::new(), base
} }).unwrap_or(String::new())
} }
pub fn stable_since(&self) -> Option<&str> { pub fn stable_since(&self) -> Option<&str> {
if let Some(ref s) = self.stability { self.stability.as_ref().map(|s| &s.since[..])
return Some(&s.since[..]);
}
None
} }
} }
@ -711,7 +701,7 @@ impl<'tcx> Clean<TyParamBound> for ty::TraitRef<'tcx> {
if let &ty::Region::ReLateBound(_, _) = *reg { if let &ty::Region::ReLateBound(_, _) = *reg {
debug!(" hit an ReLateBound {:?}", reg); debug!(" hit an ReLateBound {:?}", reg);
if let Some(lt) = reg.clean(cx) { if let Some(lt) = reg.clean(cx) {
late_bounds.push(lt) late_bounds.push(lt);
} }
} }
} }
@ -780,8 +770,7 @@ impl Clean<Option<Lifetime>> for ty::Region {
fn clean(&self, cx: &DocContext) -> Option<Lifetime> { fn clean(&self, cx: &DocContext) -> Option<Lifetime> {
match *self { match *self {
ty::ReStatic => Some(Lifetime::statik()), ty::ReStatic => Some(Lifetime::statik()),
ty::ReLateBound(_, ty::BrNamed(_, name)) => ty::ReLateBound(_, ty::BrNamed(_, name)) => Some(Lifetime(name.to_string())),
Some(Lifetime(name.to_string())),
ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))), ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
ty::ReLateBound(..) | ty::ReLateBound(..) |
@ -1151,12 +1140,12 @@ impl<'tcx> Clean<Type> for ty::FnOutput<'tcx> {
impl<'a, 'tcx> Clean<FnDecl> for (DefId, &'a ty::PolyFnSig<'tcx>) { impl<'a, 'tcx> Clean<FnDecl> for (DefId, &'a ty::PolyFnSig<'tcx>) {
fn clean(&self, cx: &DocContext) -> FnDecl { fn clean(&self, cx: &DocContext) -> FnDecl {
let (did, sig) = *self; let (did, sig) = *self;
let mut names = if let Some(_) = cx.map.as_local_node_id(did) { let mut names = if cx.map.as_local_node_id(did).is_some() {
vec![].into_iter() vec![].into_iter()
} else { } else {
cx.tcx().sess.cstore.method_arg_names(did).into_iter() cx.tcx().sess.cstore.method_arg_names(did).into_iter()
}.peekable(); }.peekable();
if names.peek().map(|s| &**s) == Some("self") { if let Some("self") = names.peek().map(|s| &s[..]) {
let _ = names.next(); let _ = names.next();
} }
FnDecl { FnDecl {
@ -1627,15 +1616,9 @@ impl Clean<Type> for hir::Ty {
} }
} }
TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)), TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
TyPolyTraitRef(ref bounds) => { TyPolyTraitRef(ref bounds) => PolyTraitRef(bounds.clean(cx)),
PolyTraitRef(bounds.clean(cx)) TyInfer => Infer,
}, TyTypeof(..) => panic!("Unimplemented type {:?}", self.node),
TyInfer => {
Infer
},
TyTypeof(..) => {
panic!("Unimplemented type {:?}", self.node)
},
} }
} }
} }
@ -2253,7 +2236,7 @@ impl Clean<Vec<Item>> for doctree::Impl {
polarity: Some(self.polarity.clean(cx)), polarity: Some(self.polarity.clean(cx)),
}), }),
}); });
return ret; ret
} }
} }
@ -2393,9 +2376,8 @@ impl Clean<Vec<Item>> for doctree::Import {
} }
hir::ViewPathSimple(name, ref p) => { hir::ViewPathSimple(name, ref p) => {
if !denied { if !denied {
match inline::try_inline(cx, self.id, Some(name)) { if let Some(items) = inline::try_inline(cx, self.id, Some(name)) {
Some(items) => return items, return items;
None => {}
} }
} }
(vec![], SimpleImport(name.clean(cx), (vec![], SimpleImport(name.clean(cx),
@ -2460,9 +2442,8 @@ impl Clean<Vec<Item>> for hir::ForeignMod {
fn clean(&self, cx: &DocContext) -> Vec<Item> { fn clean(&self, cx: &DocContext) -> Vec<Item> {
let mut items = self.items.clean(cx); let mut items = self.items.clean(cx);
for item in &mut items { for item in &mut items {
match item.inner { if let ForeignFunctionItem(ref mut f) = item.inner {
ForeignFunctionItem(ref mut f) => f.abi = self.abi, f.abi = self.abi;
_ => {}
} }
} }
items items
@ -2598,11 +2579,7 @@ fn resolve_type(cx: &DocContext,
}; };
} }
}; };
let def = match tcx.def_map.borrow().get(&id) { let def = tcx.def_map.borrow().get(&id).expect("unresolved id not in defmap").full_def();
Some(k) => k.full_def(),
None => panic!("unresolved id not in defmap")
};
debug!("resolve_type: def={:?}", def); debug!("resolve_type: def={:?}", def);
let is_generic = match def { let is_generic = match def {
@ -2659,7 +2636,7 @@ fn register_def(cx: &DocContext, def: Def) -> DefId {
let t = inline::build_external_trait(cx, tcx, did); let t = inline::build_external_trait(cx, tcx, did);
cx.external_traits.borrow_mut().as_mut().unwrap().insert(did, t); cx.external_traits.borrow_mut().as_mut().unwrap().insert(did, t);
} }
return did; did
} }
fn resolve_use_source(cx: &DocContext, path: Path, id: ast::NodeId) -> ImportSource { fn resolve_use_source(cx: &DocContext, path: Path, id: ast::NodeId) -> ImportSource {
@ -2732,12 +2709,10 @@ impl Clean<Stability> for attr::Stability {
_=> "".to_string(), _=> "".to_string(),
}, },
reason: { reason: {
if let Some(ref depr) = self.rustc_depr { match (&self.rustc_depr, &self.level) {
depr.reason.to_string() (&Some(ref depr), _) => depr.reason.to_string(),
} else if let attr::Unstable {reason: Some(ref reason), ..} = self.level { (&None, &attr::Unstable {reason: Some(ref reason), ..}) => reason.to_string(),
reason.to_string() _ => "".to_string(),
} else {
"".to_string()
} }
}, },
issue: match self.level { issue: match self.level {

View file

@ -81,6 +81,7 @@ pub trait DocFolder : Sized {
c.module = match replace(&mut c.module, None) { c.module = match replace(&mut c.module, None) {
Some(module) => self.fold_item(module), None => None Some(module) => self.fold_item(module), None => None
}; };
let external_traits = replace(&mut c.external_traits, HashMap::new()); let external_traits = replace(&mut c.external_traits, HashMap::new());
c.external_traits = external_traits.into_iter().map(|(k, mut v)| { c.external_traits = external_traits.into_iter().map(|(k, mut v)| {
let items = replace(&mut v.items, Vec::new()); let items = replace(&mut v.items, Vec::new());

View file

@ -433,41 +433,38 @@ pub fn run(mut krate: clean::Crate,
// Crawl the crate attributes looking for attributes which control how we're // Crawl the crate attributes looking for attributes which control how we're
// going to emit HTML // going to emit HTML
let default: &[_] = &[]; let default: &[_] = &[];
match krate.module.as_ref().map(|m| m.doc_list().unwrap_or(default)) { if let Some(attrs) = krate.module.as_ref().map(|m| m.doc_list().unwrap_or(default)) {
Some(attrs) => { for attr in attrs {
for attr in attrs { match *attr {
match *attr { clean::NameValue(ref x, ref s)
clean::NameValue(ref x, ref s) if "html_favicon_url" == *x => {
if "html_favicon_url" == *x => { cx.layout.favicon = s.to_string();
cx.layout.favicon = s.to_string();
}
clean::NameValue(ref x, ref s)
if "html_logo_url" == *x => {
cx.layout.logo = s.to_string();
}
clean::NameValue(ref x, ref s)
if "html_playground_url" == *x => {
cx.layout.playground_url = s.to_string();
markdown::PLAYGROUND_KRATE.with(|slot| {
if slot.borrow().is_none() {
let name = krate.name.clone();
*slot.borrow_mut() = Some(Some(name));
}
});
}
clean::NameValue(ref x, ref s)
if "issue_tracker_base_url" == *x => {
cx.issue_tracker_base_url = Some(s.to_string());
}
clean::Word(ref x)
if "html_no_source" == *x => {
cx.include_sources = false;
}
_ => {}
} }
clean::NameValue(ref x, ref s)
if "html_logo_url" == *x => {
cx.layout.logo = s.to_string();
}
clean::NameValue(ref x, ref s)
if "html_playground_url" == *x => {
cx.layout.playground_url = s.to_string();
markdown::PLAYGROUND_KRATE.with(|slot| {
if slot.borrow().is_none() {
let name = krate.name.clone();
*slot.borrow_mut() = Some(Some(name));
}
});
}
clean::NameValue(ref x, ref s)
if "issue_tracker_base_url" == *x => {
cx.issue_tracker_base_url = Some(s.to_string());
}
clean::Word(ref x)
if "html_no_source" == *x => {
cx.include_sources = false;
}
_ => {}
} }
} }
None => {}
} }
// Crawl the crate to build various caches used for the output // Crawl the crate to build various caches used for the output
@ -986,15 +983,12 @@ impl DocFolder for Cache {
// Collect all the implementors of traits. // Collect all the implementors of traits.
if let clean::ImplItem(ref i) = item.inner { if let clean::ImplItem(ref i) = item.inner {
match i.trait_ { if let Some(clean::ResolvedPath{ did, .. }) = i.trait_ {
Some(clean::ResolvedPath{ did, .. }) => { self.implementors.entry(did).or_insert(vec![]).push(Implementor {
self.implementors.entry(did).or_insert(vec![]).push(Implementor { def_id: item.def_id,
def_id: item.def_id, stability: item.stability.clone(),
stability: item.stability.clone(), impl_: i.clone(),
impl_: i.clone(), });
});
}
Some(..) | None => {}
} }
} }
@ -1054,6 +1048,9 @@ impl DocFolder for Cache {
} }
}); });
// A crate has a module at its root, containing all items,
// which should not be indexed. The crate-item itself is
// inserted later on when serializing the search-index.
if item.def_id.index != CRATE_DEF_INDEX { if item.def_id.index != CRATE_DEF_INDEX {
self.search_index.push(IndexItem { self.search_index.push(IndexItem {
ty: shortty(&item), ty: shortty(&item),
@ -1078,13 +1075,14 @@ impl DocFolder for Cache {
} }
// Keep track of the fully qualified path for this item. // Keep track of the fully qualified path for this item.
let pushed = if item.name.is_some() { let pushed = match item.name {
let n = item.name.as_ref().unwrap(); Some(ref n) if !n.is_empty() => {
if !n.is_empty() {
self.stack.push(n.to_string()); self.stack.push(n.to_string());
true true
} else { false } }
} else { false }; _ => false,
};
match item.inner { match item.inner {
clean::StructItem(..) | clean::EnumItem(..) | clean::StructItem(..) | clean::EnumItem(..) |
clean::TypedefItem(..) | clean::TraitItem(..) | clean::TypedefItem(..) | clean::TraitItem(..) |
@ -1153,60 +1151,53 @@ impl DocFolder for Cache {
// Once we've recursively found all the generics, then hoard off all the // Once we've recursively found all the generics, then hoard off all the
// implementations elsewhere // implementations elsewhere
let ret = match self.fold_item_recur(item) { let ret = self.fold_item_recur(item).and_then(|item| {
Some(item) => { if let clean::Item { attrs, inner: clean::ImplItem(i), .. } = item {
match item { // extract relevant documentation for this impl
clean::Item{ attrs, inner: clean::ImplItem(i), .. } => { let dox = match attrs.into_iter().find(|a| {
// extract relevant documentation for this impl match *a {
let dox = match attrs.into_iter().find(|a| { clean::NameValue(ref x, _)
match *a { if "doc" == *x => {
clean::NameValue(ref x, _) true
if "doc" == *x => {
true
}
_ => false
}
}) {
Some(clean::NameValue(_, dox)) => Some(dox),
Some(..) | None => None,
};
// Figure out the id of this impl. This may map to a
// primitive rather than always to a struct/enum.
let did = match i.for_ {
clean::ResolvedPath { did, .. } |
clean::BorrowedRef {
type_: box clean::ResolvedPath { did, .. }, ..
} => {
Some(did)
}
ref t => {
t.primitive_type().and_then(|t| {
self.primitive_locations.get(&t).map(|n| {
let id = t.to_def_index();
DefId { krate: *n, index: id }
})
})
}
};
if let Some(did) = did {
self.impls.entry(did).or_insert(vec![]).push(Impl {
impl_: i,
dox: dox,
stability: item.stability.clone(),
});
} }
_ => false
None }
}) {
Some(clean::NameValue(_, dox)) => Some(dox),
Some(..) | None => None,
};
// Figure out the id of this impl. This may map to a
// primitive rather than always to a struct/enum.
let did = match i.for_ {
clean::ResolvedPath { did, .. } |
clean::BorrowedRef {
type_: box clean::ResolvedPath { did, .. }, ..
} => {
Some(did)
} }
i => Some(i), ref t => {
t.primitive_type().and_then(|t| {
self.primitive_locations.get(&t).map(|n| {
let id = t.to_def_index();
DefId { krate: *n, index: id }
})
})
}
};
if let Some(did) = did {
self.impls.entry(did).or_insert(vec![]).push(Impl {
impl_: i,
dox: dox,
stability: item.stability.clone(),
});
} }
None
} else {
Some(item)
} }
i => i, });
};
if pushed { self.stack.pop().unwrap(); } if pushed { self.stack.pop().unwrap(); }
if parent_pushed { self.parent_stack.pop().unwrap(); } if parent_pushed { self.parent_stack.pop().unwrap(); }
@ -1581,13 +1572,10 @@ impl<'a> fmt::Display for Item<'a> {
// this page, and this link will be auto-clicked. The `id` attribute is // this page, and this link will be auto-clicked. The `id` attribute is
// used to find the link to auto-click. // used to find the link to auto-click.
if self.cx.include_sources && !is_primitive { if self.cx.include_sources && !is_primitive {
match self.href() { if let Some(l) = self.href() {
Some(l) => { try!(write!(fmt, "<a id='src-{}' class='srclink' \
try!(write!(fmt, "<a id='src-{}' class='srclink' \ href='{}' title='{}'>[src]</a>",
href='{}' title='{}'>[src]</a>", self.item.def_id.index.as_usize(), l, "goto source code"));
self.item.def_id.index.as_usize(), l, "goto source code"));
}
None => {}
} }
} }
@ -1801,7 +1789,7 @@ fn item_module(w: &mut fmt::Formatter, cx: &Context,
} }
fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Option<String> { fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Option<String> {
let mut result = item.stability.as_ref().and_then(|stab| { item.stability.as_ref().and_then(|stab| {
let reason = if show_reason && !stab.reason.is_empty() { let reason = if show_reason && !stab.reason.is_empty() {
format!(": {}", stab.reason) format!(": {}", stab.reason)
} else { } else {
@ -1836,10 +1824,8 @@ fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Optio
}; };
Some(format!("<em class='stab {}'>{}</em>", Some(format!("<em class='stab {}'>{}</em>",
item.stability_class(), text)) item.stability_class(), text))
}); }).or_else(|| {
item.deprecation.as_ref().and_then(|depr| {
if result.is_none() {
result = item.deprecation.as_ref().and_then(|depr| {
let note = if show_reason && !depr.note.is_empty() { let note = if show_reason && !depr.note.is_empty() {
format!(": {}", depr.note) format!(": {}", depr.note)
} else { } else {
@ -1853,10 +1839,8 @@ fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Optio
let text = format!("Deprecated{}{}", since, Markdown(&note)); let text = format!("Deprecated{}{}", since, Markdown(&note));
Some(format!("<em class='stab deprecated'>{}</em>", text)) Some(format!("<em class='stab deprecated'>{}</em>", text))
}); })
} })
result
} }
struct Initializer<'a>(&'a str); struct Initializer<'a>(&'a str);
@ -2108,17 +2092,12 @@ fn assoc_type(w: &mut fmt::Formatter, it: &clean::Item,
fn render_stability_since_raw<'a>(w: &mut fmt::Formatter, fn render_stability_since_raw<'a>(w: &mut fmt::Formatter,
ver: Option<&'a str>, ver: Option<&'a str>,
containing_ver: Option<&'a str>) -> fmt::Result { containing_ver: Option<&'a str>) -> fmt::Result {
if containing_ver != ver { if let Some(v) = ver {
match ver { if containing_ver != ver && v.len() > 0 {
Some(v) => try!(write!(w, "<span class=\"since\">{}</span>",
if v.len() > 0 { v))
try!(write!(w, "<span class=\"since\">{}</span>",
v))
},
None => {}
} }
} }
Ok(()) Ok(())
} }
@ -2289,43 +2268,33 @@ fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
try!(write!(w, "<tr><td id='variant.{name}'><code>{name}</code></td><td>", try!(write!(w, "<tr><td id='variant.{name}'><code>{name}</code></td><td>",
name = variant.name.as_ref().unwrap())); name = variant.name.as_ref().unwrap()));
try!(document(w, cx, variant)); try!(document(w, cx, variant));
match variant.inner {
clean::VariantItem(ref var) => { use clean::{Variant, StructVariant};
match var.kind { if let clean::VariantItem( Variant { kind: StructVariant(ref s) } ) = variant.inner {
clean::StructVariant(ref s) => { let fields = s.fields.iter().filter(|f| {
let fields = s.fields.iter().filter(|f| { match f.inner {
match f.inner { clean::StructFieldItem(clean::TypedStructField(..)) => true,
clean::StructFieldItem(ref t) => match *t { _ => false,
clean::HiddenStructField => false,
clean::TypedStructField(..) => true,
},
_ => false,
}
});
try!(write!(w, "<h3 class='fields'>Fields</h3>\n
<table>"));
for field in fields {
try!(write!(w, "<tr><td \
id='variant.{v}.field.{f}'>\
<code>{f}</code></td><td>",
v = variant.name.as_ref().unwrap(),
f = field.name.as_ref().unwrap()));
try!(document(w, cx, field));
try!(write!(w, "</td></tr>"));
}
try!(write!(w, "</table>"));
}
_ => ()
} }
});
try!(write!(w, "<h3 class='fields'>Fields</h3>\n
<table>"));
for field in fields {
try!(write!(w, "<tr><td \
id='variant.{v}.field.{f}'>\
<code>{f}</code></td><td>",
v = variant.name.as_ref().unwrap(),
f = field.name.as_ref().unwrap()));
try!(document(w, cx, field));
try!(write!(w, "</td></tr>"));
} }
_ => () try!(write!(w, "</table>"));
} }
try!(write!(w, "</td><td>")); try!(write!(w, "</td><td>"));
try!(render_stability_since(w, variant, it)); try!(render_stability_since(w, variant, it));
try!(write!(w, "</td></tr>")); try!(write!(w, "</td></tr>"));
} }
try!(write!(w, "</table>")); try!(write!(w, "</table>"));
} }
try!(render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)); try!(render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All));
Ok(()) Ok(())
@ -2356,9 +2325,8 @@ fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
VisSpace(it.visibility), VisSpace(it.visibility),
if structhead {"struct "} else {""}, if structhead {"struct "} else {""},
it.name.as_ref().unwrap())); it.name.as_ref().unwrap()));
match g { if let Some(g) = g {
Some(g) => try!(write!(w, "{}{}", *g, WhereClause(g))), try!(write!(w, "{}{}", *g, WhereClause(g)))
None => {}
} }
match ty { match ty {
doctree::Plain => { doctree::Plain => {
@ -2452,7 +2420,7 @@ fn render_assoc_items(w: &mut fmt::Formatter,
} }
} }
if let AssocItemRender::DerefFor { .. } = what { if let AssocItemRender::DerefFor { .. } = what {
return Ok(()) return Ok(());
} }
if !traits.is_empty() { if !traits.is_empty() {
let deref_impl = traits.iter().find(|t| { let deref_impl = traits.iter().find(|t| {
@ -2533,10 +2501,17 @@ fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLi
link: AssocItemLink, render_static: bool, link: AssocItemLink, render_static: bool,
outer_version: Option<&str>) -> fmt::Result { outer_version: Option<&str>) -> fmt::Result {
let name = item.name.as_ref().unwrap(); let name = item.name.as_ref().unwrap();
let is_static = match item.inner {
clean::MethodItem(ref method) => method.self_ == SelfTy::SelfStatic,
clean::TyMethodItem(ref method) => method.self_ == SelfTy::SelfStatic,
_ => false
};
match item.inner { match item.inner {
clean::MethodItem(..) | clean::TyMethodItem(..) => { clean::MethodItem(..) | clean::TyMethodItem(..) => {
// Only render when the method is not static or we allow static methods // Only render when the method is not static or we allow static methods
if !is_static_method(item) || render_static { if !is_static || render_static {
let id = derive_id(format!("method.{}", name)); let id = derive_id(format!("method.{}", name));
try!(write!(w, "<h4 id='{}' class='{}'>", id, shortty(item))); try!(write!(w, "<h4 id='{}' class='{}'>", id, shortty(item)));
try!(render_stability_since_raw(w, item.stable_since(), outer_version)); try!(render_stability_since_raw(w, item.stable_since(), outer_version));
@ -2572,22 +2547,11 @@ fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLi
_ => panic!("can't make docs for trait item with name {:?}", item.name) _ => panic!("can't make docs for trait item with name {:?}", item.name)
} }
return if let AssocItemLink::Anchor = link { match link {
if is_static_method(item) && !render_static { AssocItemLink::Anchor if !is_static || render_static => {
Ok(())
} else {
document(w, cx, item) document(w, cx, item)
} },
} else { _ => Ok(()),
Ok(())
};
fn is_static_method(item: &clean::Item) -> bool {
match item.inner {
clean::MethodItem(ref method) => method.self_ == SelfTy::SelfStatic,
clean::TyMethodItem(ref method) => method.self_ == SelfTy::SelfStatic,
_ => false
}
} }
} }
@ -2605,9 +2569,8 @@ fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLi
outer_version: Option<&str>) -> fmt::Result { outer_version: Option<&str>) -> fmt::Result {
for trait_item in &t.items { for trait_item in &t.items {
let n = trait_item.name.clone(); let n = trait_item.name.clone();
match i.items.iter().find(|m| { m.name == n }) { if i.items.iter().find(|m| { m.name == n }).is_some() {
Some(..) => continue, continue;
None => {}
} }
try!(doctraititem(w, cx, trait_item, AssocItemLink::GotoSource(did), render_static, try!(doctraititem(w, cx, trait_item, AssocItemLink::GotoSource(did), render_static,
@ -2623,7 +2586,6 @@ fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLi
if let Some(clean::ResolvedPath { did, .. }) = i.impl_.trait_ { if let Some(clean::ResolvedPath { did, .. }) = i.impl_.trait_ {
if let Some(t) = cache().traits.get(&did) { if let Some(t) = cache().traits.get(&did) {
try!(render_default_items(w, cx, did, t, &i.impl_, render_header, outer_version)); try!(render_default_items(w, cx, did, t, &i.impl_, render_header, outer_version));
} }
} }
try!(write!(w, "</div>")); try!(write!(w, "</div>"));

View file

@ -283,19 +283,15 @@ pub fn main_args(args: &[String]) -> isize {
info!("going to format"); info!("going to format");
match matches.opt_str("w").as_ref().map(|s| &**s) { match matches.opt_str("w").as_ref().map(|s| &**s) {
Some("html") | None => { Some("html") | None => {
match html::render::run(krate, &external_html, html::render::run(krate, &external_html,
output.unwrap_or(PathBuf::from("doc")), output.unwrap_or(PathBuf::from("doc")),
passes.into_iter().collect()) { passes.into_iter().collect())
Ok(()) => {} .expect("failed to generate documentation")
Err(e) => panic!("failed to generate documentation: {}", e),
}
} }
Some("json") => { Some("json") => {
match json_output(krate, json_plugins, json_output(krate, json_plugins,
output.unwrap_or(PathBuf::from("doc.json"))) { output.unwrap_or(PathBuf::from("doc.json")))
Ok(()) => {} .expect("failed to write json")
Err(e) => panic!("failed to write json: {}", e),
}
} }
Some(s) => { Some(s) => {
println!("unknown output format: {}", s); println!("unknown output format: {}", s);
@ -332,18 +328,10 @@ fn parse_externs(matches: &getopts::Matches) -> Result<core::Externs, String> {
let mut externs = HashMap::new(); let mut externs = HashMap::new();
for arg in &matches.opt_strs("extern") { for arg in &matches.opt_strs("extern") {
let mut parts = arg.splitn(2, '='); let mut parts = arg.splitn(2, '=');
let name = match parts.next() { let name = try!(parts.next().ok_or("--extern value must not be empty".to_string()));
Some(s) => s, let location = try!(parts.next()
None => { .ok_or("--extern value must be of the format `foo=bar`"
return Err("--extern value must not be empty".to_string()); .to_string()));
}
};
let location = match parts.next() {
Some(s) => s,
None => {
return Err("--extern value must be of the format `foo=bar`".to_string());
}
};
let name = name.to_string(); let name = name.to_string();
externs.entry(name).or_insert(vec![]).push(location.to_string()); externs.entry(name).or_insert(vec![]).push(location.to_string());
} }
@ -448,17 +436,16 @@ fn rust_input(cratefile: &str, externs: core::Externs, matches: &getopts::Matche
// Run everything! // Run everything!
info!("Executing passes/plugins"); info!("Executing passes/plugins");
let (krate, json) = pm.run_plugins(krate); let (krate, json) = pm.run_plugins(krate);
return Output { krate: krate, json_plugins: json, passes: passes, }; Output { krate: krate, json_plugins: json, passes: passes }
} }
/// This input format purely deserializes the json output file. No passes are /// This input format purely deserializes the json output file. No passes are
/// run over the deserialized output. /// run over the deserialized output.
fn json_input(input: &str) -> Result<Output, String> { fn json_input(input: &str) -> Result<Output, String> {
let mut bytes = Vec::new(); let mut bytes = Vec::new();
match File::open(input).and_then(|mut f| f.read_to_end(&mut bytes)) { if let Err(e) = File::open(input).and_then(|mut f| f.read_to_end(&mut bytes)) {
Ok(_) => {} return Err(format!("couldn't open {}: {}", input, e))
Err(e) => return Err(format!("couldn't open {}: {}", input, e)), }
};
match json::from_reader(&mut &bytes[..]) { match json::from_reader(&mut &bytes[..]) {
Err(s) => Err(format!("{:?}", s)), Err(s) => Err(format!("{:?}", s)),
Ok(Json::Object(obj)) => { Ok(Json::Object(obj)) => {
@ -507,21 +494,13 @@ fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
json.insert("schema".to_string(), Json::String(SCHEMA_VERSION.to_string())); json.insert("schema".to_string(), Json::String(SCHEMA_VERSION.to_string()));
let plugins_json = res.into_iter() let plugins_json = res.into_iter()
.filter_map(|opt| { .filter_map(|opt| {
match opt { opt.map(|(string, json)| (string.to_string(), json))
None => None,
Some((string, json)) => {
Some((string.to_string(), json))
}
}
}).collect(); }).collect();
// FIXME #8335: yuck, Rust -> str -> JSON round trip! No way to .encode // FIXME #8335: yuck, Rust -> str -> JSON round trip! No way to .encode
// straight to the Rust JSON representation. // straight to the Rust JSON representation.
let crate_json_str = format!("{}", json::as_json(&krate)); let crate_json_str = format!("{}", json::as_json(&krate));
let crate_json = match json::from_str(&crate_json_str) { let crate_json = json::from_str(&crate_json_str).expect("Rust generated JSON is invalid");
Ok(j) => j,
Err(e) => panic!("Rust generated JSON is invalid: {:?}", e)
};
json.insert("crate".to_string(), crate_json); json.insert("crate".to_string(), crate_json);
json.insert("plugins".to_string(), Json::Object(plugins_json)); json.insert("plugins".to_string(), Json::Object(plugins_json));

View file

@ -205,22 +205,19 @@ impl<'a> fold::DocFolder for Stripper<'a> {
self.fold_item_recur(i) self.fold_item_recur(i)
}; };
match i { i.and_then(|i| {
Some(i) => { match i.inner {
match i.inner { // emptied modules/impls have no need to exist
// emptied modules/impls have no need to exist clean::ModuleItem(ref m)
clean::ModuleItem(ref m) if m.items.is_empty() &&
if m.items.is_empty() && i.doc_value().is_none() => None,
i.doc_value().is_none() => None, clean::ImplItem(ref i) if i.items.is_empty() => None,
clean::ImplItem(ref i) if i.items.is_empty() => None, _ => {
_ => { self.retained.insert(i.def_id);
self.retained.insert(i.def_id); Some(i)
Some(i)
}
} }
} }
None => None, })
}
} }
} }
@ -275,13 +272,11 @@ pub fn collapse_docs(krate: clean::Crate) -> plugins::PluginResult {
let mut docstr = String::new(); let mut docstr = String::new();
let mut i = i; let mut i = i;
for attr in &i.attrs { for attr in &i.attrs {
match *attr { if let clean::NameValue(ref x, ref s) = *attr {
clean::NameValue(ref x, ref s) if "doc" == *x {
if "doc" == *x => {
docstr.push_str(s); docstr.push_str(s);
docstr.push('\n'); docstr.push('\n');
}, }
_ => ()
} }
} }
let mut a: Vec<clean::Attribute> = i.attrs.iter().filter(|&a| match a { let mut a: Vec<clean::Attribute> = i.attrs.iter().filter(|&a| match a {

View file

@ -121,9 +121,8 @@ pub fn run(input: &str,
let mut v = RustdocVisitor::new(&ctx, None); let mut v = RustdocVisitor::new(&ctx, None);
v.visit(ctx.map.krate()); v.visit(ctx.map.krate());
let mut krate = v.clean(&ctx); let mut krate = v.clean(&ctx);
match crate_name { if let Some(name) = crate_name {
Some(name) => krate.name = name, krate.name = name;
None => {}
} }
let (krate, _) = passes::collapse_docs(krate); let (krate, _) = passes::collapse_docs(krate);
let (krate, _) = passes::unindent_comments(krate); let (krate, _) = passes::unindent_comments(krate);
@ -334,13 +333,10 @@ pub fn maketest(s: &str, cratename: Option<&str>, dont_insert_main: bool,
// Don't inject `extern crate std` because it's already injected by the // Don't inject `extern crate std` because it's already injected by the
// compiler. // compiler.
if !s.contains("extern crate") && !opts.no_crate_inject && cratename != Some("std") { if !s.contains("extern crate") && !opts.no_crate_inject && cratename != Some("std") {
match cratename { if let Some(cratename) = cratename {
Some(cratename) => { if s.contains(cratename) {
if s.contains(cratename) { prog.push_str(&format!("extern crate {};\n", cratename));
prog.push_str(&format!("extern crate {};\n", cratename));
}
} }
None => {}
} }
} }
if dont_insert_main || s.contains("fn main") { if dont_insert_main || s.contains("fn main") {
@ -476,12 +472,7 @@ impl DocFolder for Collector {
_ => typename_if_impl(&item) _ => typename_if_impl(&item)
}; };
let pushed = if let Some(name) = current_name { let pushed = current_name.map(|name| self.names.push(name)).is_some();
self.names.push(name);
true
} else {
false
};
if let Some(doc) = item.doc_value() { if let Some(doc) = item.doc_value() {
self.cnt = 0; self.cnt = 0;

View file

@ -263,13 +263,9 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
let name = renamed.unwrap_or(item.name); let name = renamed.unwrap_or(item.name);
match item.node { match item.node {
hir::ItemExternCrate(ref p) => { hir::ItemExternCrate(ref p) => {
let path = match *p {
None => None,
Some(x) => Some(x.to_string()),
};
om.extern_crates.push(ExternCrate { om.extern_crates.push(ExternCrate {
name: name, name: name,
path: path, path: p.map(|x|x.to_string()),
vis: item.vis, vis: item.vis,
attrs: item.attrs.clone(), attrs: item.attrs.clone(),
whence: item.span, whence: item.span,