impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
fn clean(&self, cx: &DocContext) -> Option<U> {
- match self {
- &None => None,
- &Some(ref v) => Some(v.clean(cx))
- }
+ self.as_ref().map(|v| v.clean(cx))
}
}
}
pub fn stability_class(&self) -> String {
- match self.stability {
- Some(ref s) => {
- let mut base = match s.level {
- stability::Unstable => "unstable".to_string(),
- stability::Stable => String::new(),
- };
- if !s.deprecated_since.is_empty() {
- base.push_str(" deprecated");
- }
- base
+ self.stability.as_ref().map(|ref s| {
+ let mut base = match s.level {
+ stability::Unstable => "unstable".to_string(),
+ stability::Stable => String::new(),
+ };
+ if !s.deprecated_since.is_empty() {
+ base.push_str(" deprecated");
}
- _ => String::new(),
- }
+ base
+ }).unwrap_or(String::new())
}
pub fn stable_since(&self) -> Option<&str> {
- if let Some(ref s) = self.stability {
- return Some(&s.since[..]);
- }
-
- None
+ self.stability.as_ref().map(|s| &s.since[..])
}
}
if let &ty::Region::ReLateBound(_, _) = *reg {
debug!(" hit an ReLateBound {:?}", reg);
if let Some(lt) = reg.clean(cx) {
- late_bounds.push(lt)
+ late_bounds.push(lt);
}
}
}
fn clean(&self, cx: &DocContext) -> Option<Lifetime> {
match *self {
ty::ReStatic => Some(Lifetime::statik()),
- ty::ReLateBound(_, ty::BrNamed(_, name)) =>
- Some(Lifetime(name.to_string())),
+ ty::ReLateBound(_, ty::BrNamed(_, name)) => Some(Lifetime(name.to_string())),
ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
ty::ReLateBound(..) |
impl<'a, 'tcx> Clean<FnDecl> for (DefId, &'a ty::PolyFnSig<'tcx>) {
fn clean(&self, cx: &DocContext) -> FnDecl {
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()
} else {
cx.tcx().sess.cstore.method_arg_names(did).into_iter()
}.peekable();
- if names.peek().map(|s| &**s) == Some("self") {
+ if let Some("self") = names.peek().map(|s| &s[..]) {
let _ = names.next();
}
FnDecl {
}
}
TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
- TyPolyTraitRef(ref bounds) => {
- PolyTraitRef(bounds.clean(cx))
- },
- TyInfer => {
- Infer
- },
- TyTypeof(..) => {
- panic!("Unimplemented type {:?}", self.node)
- },
+ TyPolyTraitRef(ref bounds) => PolyTraitRef(bounds.clean(cx)),
+ TyInfer => Infer,
+ TyTypeof(..) => panic!("Unimplemented type {:?}", self.node),
}
}
}
polarity: Some(self.polarity.clean(cx)),
}),
});
- return ret;
+ ret
}
}
}
hir::ViewPathSimple(name, ref p) => {
if !denied {
- match inline::try_inline(cx, self.id, Some(name)) {
- Some(items) => return items,
- None => {}
+ if let Some(items) = inline::try_inline(cx, self.id, Some(name)) {
+ return items;
}
}
(vec![], SimpleImport(name.clean(cx),
fn clean(&self, cx: &DocContext) -> Vec<Item> {
let mut items = self.items.clean(cx);
for item in &mut items {
- match item.inner {
- ForeignFunctionItem(ref mut f) => f.abi = self.abi,
- _ => {}
+ if let ForeignFunctionItem(ref mut f) = item.inner {
+ f.abi = self.abi;
}
}
items
};
}
};
- let def = match tcx.def_map.borrow().get(&id) {
- Some(k) => k.full_def(),
- None => panic!("unresolved id not in defmap")
- };
-
+ let def = tcx.def_map.borrow().get(&id).expect("unresolved id not in defmap").full_def();
debug!("resolve_type: def={:?}", def);
let is_generic = match def {
let t = inline::build_external_trait(cx, tcx, did);
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 {
_=> "".to_string(),
},
reason: {
- if let Some(ref depr) = self.rustc_depr {
- depr.reason.to_string()
- } else if let attr::Unstable {reason: Some(ref reason), ..} = self.level {
- reason.to_string()
- } else {
- "".to_string()
+ match (&self.rustc_depr, &self.level) {
+ (&Some(ref depr), _) => depr.reason.to_string(),
+ (&None, &attr::Unstable {reason: Some(ref reason), ..}) => reason.to_string(),
+ _ => "".to_string(),
}
},
issue: match self.level {
// Crawl the crate attributes looking for attributes which control how we're
// going to emit HTML
let default: &[_] = &[];
- match krate.module.as_ref().map(|m| m.doc_list().unwrap_or(default)) {
- Some(attrs) => {
- for attr in attrs {
- match *attr {
- clean::NameValue(ref x, ref s)
- if "html_favicon_url" == *x => {
- 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;
- }
- _ => {}
+ if let Some(attrs) = krate.module.as_ref().map(|m| m.doc_list().unwrap_or(default)) {
+ for attr in attrs {
+ match *attr {
+ clean::NameValue(ref x, ref s)
+ if "html_favicon_url" == *x => {
+ 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;
}
+ _ => {}
}
}
- None => {}
}
// Crawl the crate to build various caches used for the output
// Collect all the implementors of traits.
if let clean::ImplItem(ref i) = item.inner {
- match i.trait_ {
- Some(clean::ResolvedPath{ did, .. }) => {
- self.implementors.entry(did).or_insert(vec![]).push(Implementor {
- def_id: item.def_id,
- stability: item.stability.clone(),
- impl_: i.clone(),
- });
- }
- Some(..) | None => {}
+ if let Some(clean::ResolvedPath{ did, .. }) = i.trait_ {
+ self.implementors.entry(did).or_insert(vec![]).push(Implementor {
+ def_id: item.def_id,
+ stability: item.stability.clone(),
+ impl_: i.clone(),
+ });
}
}
}
});
+ // 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 {
self.search_index.push(IndexItem {
ty: shortty(&item),
}
// Keep track of the fully qualified path for this item.
- let pushed = if item.name.is_some() {
- let n = item.name.as_ref().unwrap();
- if !n.is_empty() {
+ let pushed = match item.name {
+ Some(ref n) if !n.is_empty() => {
self.stack.push(n.to_string());
true
- } else { false }
- } else { false };
+ }
+ _ => false,
+ };
+
match item.inner {
clean::StructItem(..) | clean::EnumItem(..) |
clean::TypedefItem(..) | clean::TraitItem(..) |
// Once we've recursively found all the generics, then hoard off all the
// implementations elsewhere
- let ret = match self.fold_item_recur(item) {
- Some(item) => {
- match item {
- clean::Item{ attrs, inner: clean::ImplItem(i), .. } => {
- // extract relevant documentation for this impl
- let dox = match attrs.into_iter().find(|a| {
- match *a {
- clean::NameValue(ref x, _)
- 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(),
- });
+ let ret = self.fold_item_recur(item).and_then(|item| {
+ if let clean::Item { attrs, inner: clean::ImplItem(i), .. } = item {
+ // extract relevant documentation for this impl
+ let dox = match attrs.into_iter().find(|a| {
+ match *a {
+ clean::NameValue(ref x, _)
+ 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)
+ }
- None
+ 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 }
+ })
+ })
}
+ };
- i => Some(i),
+ 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 parent_pushed { self.parent_stack.pop().unwrap(); }
// this page, and this link will be auto-clicked. The `id` attribute is
// used to find the link to auto-click.
if self.cx.include_sources && !is_primitive {
- match self.href() {
- Some(l) => {
- try!(write!(fmt, "<a id='src-{}' class='srclink' \
- href='{}' title='{}'>[src]</a>",
- self.item.def_id.index.as_usize(), l, "goto source code"));
- }
- None => {}
+ if let Some(l) = self.href() {
+ try!(write!(fmt, "<a id='src-{}' class='srclink' \
+ href='{}' title='{}'>[src]</a>",
+ self.item.def_id.index.as_usize(), l, "goto source code"));
}
}
}
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() {
format!(": {}", stab.reason)
} else {
};
Some(format!("<em class='stab {}'>{}</em>",
item.stability_class(), text))
- });
-
- if result.is_none() {
- result = item.deprecation.as_ref().and_then(|depr| {
+ }).or_else(|| {
+ item.deprecation.as_ref().and_then(|depr| {
let note = if show_reason && !depr.note.is_empty() {
format!(": {}", depr.note)
} else {
let text = format!("Deprecated{}{}", since, Markdown(¬e));
Some(format!("<em class='stab deprecated'>{}</em>", text))
- });
- }
-
- result
+ })
+ })
}
struct Initializer<'a>(&'a str);
fn render_stability_since_raw<'a>(w: &mut fmt::Formatter,
ver: Option<&'a str>,
containing_ver: Option<&'a str>) -> fmt::Result {
- if containing_ver != ver {
- match ver {
- Some(v) =>
- if v.len() > 0 {
- try!(write!(w, "<span class=\"since\">{}</span>",
- v))
- },
- None => {}
+ if let Some(v) = ver {
+ if containing_ver != ver && v.len() > 0 {
+ try!(write!(w, "<span class=\"since\">{}</span>",
+ v))
}
}
-
Ok(())
}
try!(write!(w, "<tr><td id='variant.{name}'><code>{name}</code></td><td>",
name = variant.name.as_ref().unwrap()));
try!(document(w, cx, variant));
- match variant.inner {
- clean::VariantItem(ref var) => {
- match var.kind {
- clean::StructVariant(ref s) => {
- let fields = s.fields.iter().filter(|f| {
- match f.inner {
- clean::StructFieldItem(ref t) => match *t {
- 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>"));
- }
- _ => ()
+
+ use clean::{Variant, StructVariant};
+ if let clean::VariantItem( Variant { kind: StructVariant(ref s) } ) = variant.inner {
+ let fields = s.fields.iter().filter(|f| {
+ match f.inner {
+ clean::StructFieldItem(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, "</td><td>"));
try!(render_stability_since(w, variant, it));
try!(write!(w, "</td></tr>"));
}
try!(write!(w, "</table>"));
-
}
try!(render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All));
Ok(())
VisSpace(it.visibility),
if structhead {"struct "} else {""},
it.name.as_ref().unwrap()));
- match g {
- Some(g) => try!(write!(w, "{}{}", *g, WhereClause(g))),
- None => {}
+ if let Some(g) = g {
+ try!(write!(w, "{}{}", *g, WhereClause(g)))
}
match ty {
doctree::Plain => {
}
}
if let AssocItemRender::DerefFor { .. } = what {
- return Ok(())
+ return Ok(());
}
if !traits.is_empty() {
let deref_impl = traits.iter().find(|t| {
link: AssocItemLink, render_static: bool,
outer_version: Option<&str>) -> fmt::Result {
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 {
clean::MethodItem(..) | clean::TyMethodItem(..) => {
// 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));
try!(write!(w, "<h4 id='{}' class='{}'>", id, shortty(item)));
try!(render_stability_since_raw(w, item.stable_since(), outer_version));
_ => panic!("can't make docs for trait item with name {:?}", item.name)
}
- return if let AssocItemLink::Anchor = link {
- if is_static_method(item) && !render_static {
- Ok(())
- } else {
+ match link {
+ AssocItemLink::Anchor if !is_static || render_static => {
document(w, cx, item)
- }
- } else {
- 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
- }
+ },
+ _ => Ok(()),
}
}
outer_version: Option<&str>) -> fmt::Result {
for trait_item in &t.items {
let n = trait_item.name.clone();
- match i.items.iter().find(|m| { m.name == n }) {
- Some(..) => continue,
- None => {}
+ if i.items.iter().find(|m| { m.name == n }).is_some() {
+ continue;
}
try!(doctraititem(w, cx, trait_item, AssocItemLink::GotoSource(did), render_static,
if let Some(clean::ResolvedPath { did, .. }) = i.impl_.trait_ {
if let Some(t) = cache().traits.get(&did) {
try!(render_default_items(w, cx, did, t, &i.impl_, render_header, outer_version));
-
}
}
try!(write!(w, "</div>"));
info!("going to format");
match matches.opt_str("w").as_ref().map(|s| &**s) {
Some("html") | None => {
- match html::render::run(krate, &external_html,
- output.unwrap_or(PathBuf::from("doc")),
- passes.into_iter().collect()) {
- Ok(()) => {}
- Err(e) => panic!("failed to generate documentation: {}", e),
- }
+ html::render::run(krate, &external_html,
+ output.unwrap_or(PathBuf::from("doc")),
+ passes.into_iter().collect())
+ .expect("failed to generate documentation")
}
Some("json") => {
- match json_output(krate, json_plugins,
- output.unwrap_or(PathBuf::from("doc.json"))) {
- Ok(()) => {}
- Err(e) => panic!("failed to write json: {}", e),
- }
+ json_output(krate, json_plugins,
+ output.unwrap_or(PathBuf::from("doc.json")))
+ .expect("failed to write json")
}
Some(s) => {
println!("unknown output format: {}", s);
let mut externs = HashMap::new();
for arg in &matches.opt_strs("extern") {
let mut parts = arg.splitn(2, '=');
- let name = match parts.next() {
- Some(s) => s,
- None => {
- return Err("--extern value must not be empty".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 = try!(parts.next().ok_or("--extern value must not be empty".to_string()));
+ let location = try!(parts.next()
+ .ok_or("--extern value must be of the format `foo=bar`"
+ .to_string()));
let name = name.to_string();
externs.entry(name).or_insert(vec![]).push(location.to_string());
}
// Run everything!
info!("Executing passes/plugins");
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
/// run over the deserialized output.
fn json_input(input: &str) -> Result<Output, String> {
let mut bytes = Vec::new();
- match File::open(input).and_then(|mut f| f.read_to_end(&mut bytes)) {
- Ok(_) => {}
- Err(e) => return Err(format!("couldn't open {}: {}", input, e)),
- };
+ if let Err(e) = File::open(input).and_then(|mut f| f.read_to_end(&mut bytes)) {
+ return Err(format!("couldn't open {}: {}", input, e))
+ }
match json::from_reader(&mut &bytes[..]) {
Err(s) => Err(format!("{:?}", s)),
Ok(Json::Object(obj)) => {
json.insert("schema".to_string(), Json::String(SCHEMA_VERSION.to_string()));
let plugins_json = res.into_iter()
.filter_map(|opt| {
- match opt {
- None => None,
- Some((string, json)) => {
- Some((string.to_string(), json))
- }
- }
+ opt.map(|(string, json)| (string.to_string(), json))
}).collect();
// FIXME #8335: yuck, Rust -> str -> JSON round trip! No way to .encode
// straight to the Rust JSON representation.
let crate_json_str = format!("{}", json::as_json(&krate));
- let crate_json = match json::from_str(&crate_json_str) {
- Ok(j) => j,
- Err(e) => panic!("Rust generated JSON is invalid: {:?}", e)
- };
+ let crate_json = json::from_str(&crate_json_str).expect("Rust generated JSON is invalid");
json.insert("crate".to_string(), crate_json);
json.insert("plugins".to_string(), Json::Object(plugins_json));