Skip to content

Implement #[deriving(Show)] #12066

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Feb 8, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/doc/rust.md
Original file line number Diff line number Diff line change
Expand Up @@ -1969,13 +1969,14 @@ impl<T: Eq> Eq for Foo<T> {
Supported traits for `deriving` are:

* Comparison traits: `Eq`, `TotalEq`, `Ord`, `TotalOrd`.
* Serialization: `Encodable`, `Decodable`. These require `extra`.
* Serialization: `Encodable`, `Decodable`. These require `serialize`.
* `Clone` and `DeepClone`, to perform (deep) copies.
* `IterBytes`, to iterate over the bytes in a data type.
* `Rand`, to create a random instance of a data type.
* `Default`, to create an empty instance of a data type.
* `Zero`, to create an zero instance of a numeric data type.
* `FromPrimitive`, to create an instance from a numeric primitve.
* `FromPrimitive`, to create an instance from a numeric primitive.
* `Show`, to format a value using the `{}` formatter.

### Stability
One can indicate the stability of an API using the following attributes:
Expand Down
2 changes: 1 addition & 1 deletion src/doc/tutorial.md
Original file line number Diff line number Diff line change
Expand Up @@ -2523,7 +2523,7 @@ enum ABC { A, B, C }

The full list of derivable traits is `Eq`, `TotalEq`, `Ord`,
`TotalOrd`, `Encodable` `Decodable`, `Clone`, `DeepClone`,
`IterBytes`, `Rand`, `Default`, `Zero`, and `ToStr`.
`IterBytes`, `Rand`, `Default`, `Zero`, `FromPrimitive` and `Show`.

# Crates and the module system

Expand Down
3 changes: 2 additions & 1 deletion src/etc/generate-deriving-span-tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,8 @@ def write_file(name, string):
for (trait, supers, errs) in [('Rand', [], 1),
('Clone', [], 1), ('DeepClone', ['Clone'], 1),
('Eq', [], 2), ('Ord', [], 8),
('TotalEq', [], 1), ('TotalOrd', ['TotalEq'], 1)]:
('TotalEq', [], 1), ('TotalOrd', ['TotalEq'], 1),
('Show', [], 1)]:
traits[trait] = (ALL, supers, errs)

for (trait, (types, super_traits, error_count)) in traits.items():
Expand Down
4 changes: 2 additions & 2 deletions src/librustdoc/html/escape.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ use std::fmt;
pub struct Escape<'a>(&'a str);

impl<'a> fmt::Show for Escape<'a> {
fn fmt(s: &Escape<'a>, fmt: &mut fmt::Formatter) -> fmt::Result {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
// Because the internet is always right, turns out there's not that many
// characters to escape: http://stackoverflow.com/questions/7381974
let Escape(s) = *s;
let Escape(s) = *self;
let pile_o_bits = s.as_slice();
let mut last = 0;
for (i, ch) in s.bytes().enumerate() {
Expand Down
74 changes: 37 additions & 37 deletions src/librustdoc/html/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,23 +48,23 @@ impl PuritySpace {
}

impl fmt::Show for clean::Generics {
fn fmt(g: &clean::Generics, f: &mut fmt::Formatter) -> fmt::Result {
if g.lifetimes.len() == 0 && g.type_params.len() == 0 { return Ok(()) }
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.lifetimes.len() == 0 && self.type_params.len() == 0 { return Ok(()) }
if_ok!(f.buf.write("&lt;".as_bytes()));

for (i, life) in g.lifetimes.iter().enumerate() {
for (i, life) in self.lifetimes.iter().enumerate() {
if i > 0 {
if_ok!(f.buf.write(", ".as_bytes()));
}
if_ok!(write!(f.buf, "{}", *life));
}

if g.type_params.len() > 0 {
if g.lifetimes.len() > 0 {
if self.type_params.len() > 0 {
if self.lifetimes.len() > 0 {
if_ok!(f.buf.write(", ".as_bytes()));
}

for (i, tp) in g.type_params.iter().enumerate() {
for (i, tp) in self.type_params.iter().enumerate() {
if i > 0 {
if_ok!(f.buf.write(", ".as_bytes()))
}
Expand All @@ -87,16 +87,16 @@ impl fmt::Show for clean::Generics {
}

impl fmt::Show for clean::Lifetime {
fn fmt(l: &clean::Lifetime, f: &mut fmt::Formatter) -> fmt::Result {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if_ok!(f.buf.write("'".as_bytes()));
if_ok!(f.buf.write(l.get_ref().as_bytes()));
if_ok!(f.buf.write(self.get_ref().as_bytes()));
Ok(())
}
}

impl fmt::Show for clean::TyParamBound {
fn fmt(bound: &clean::TyParamBound, f: &mut fmt::Formatter) -> fmt::Result {
match *bound {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
clean::RegionBound => {
f.buf.write("'static".as_bytes())
}
Expand All @@ -108,11 +108,11 @@ impl fmt::Show for clean::TyParamBound {
}

impl fmt::Show for clean::Path {
fn fmt(path: &clean::Path, f: &mut fmt::Formatter) -> fmt::Result {
if path.global {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.global {
if_ok!(f.buf.write("::".as_bytes()))
}
for (i, seg) in path.segments.iter().enumerate() {
for (i, seg) in self.segments.iter().enumerate() {
if i > 0 {
if_ok!(f.buf.write("::".as_bytes()))
}
Expand Down Expand Up @@ -297,8 +297,8 @@ fn typarams(w: &mut io::Writer,
}

impl fmt::Show for clean::Type {
fn fmt(g: &clean::Type, f: &mut fmt::Formatter) -> fmt::Result {
match *g {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
clean::TyParamBinder(id) | clean::Generic(id) => {
local_data::get(cache_key, |cache| {
let m = cache.unwrap().get();
Expand Down Expand Up @@ -405,18 +405,18 @@ impl fmt::Show for clean::Type {
}

impl fmt::Show for clean::FnDecl {
fn fmt(d: &clean::FnDecl, f: &mut fmt::Formatter) -> fmt::Result {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f.buf, "({args}){arrow, select, yes{ -&gt; {ret}} other{}}",
args = d.inputs,
arrow = match d.output { clean::Unit => "no", _ => "yes" },
ret = d.output)
args = self.inputs,
arrow = match self.output { clean::Unit => "no", _ => "yes" },
ret = self.output)
}
}

impl fmt::Show for ~[clean::Argument] {
fn fmt(inputs: &~[clean::Argument], f: &mut fmt::Formatter) -> fmt::Result {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut args = ~"";
for (i, input) in inputs.iter().enumerate() {
for (i, input) in self.iter().enumerate() {
if i > 0 { args.push_str(", "); }
if input.name.len() > 0 {
args.push_str(format!("{}: ", input.name));
Expand All @@ -428,8 +428,8 @@ impl fmt::Show for ~[clean::Argument] {
}

impl<'a> fmt::Show for Method<'a> {
fn fmt(m: &Method<'a>, f: &mut fmt::Formatter) -> fmt::Result {
let Method(selfty, d) = *m;
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let Method(selfty, d) = *self;
let mut args = ~"";
match *selfty {
clean::SelfStatic => {},
Expand Down Expand Up @@ -463,8 +463,8 @@ impl<'a> fmt::Show for Method<'a> {
}

impl fmt::Show for VisSpace {
fn fmt(v: &VisSpace, f: &mut fmt::Formatter) -> fmt::Result {
match v.get() {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.get() {
Some(ast::Public) => write!(f.buf, "pub "),
Some(ast::Private) => write!(f.buf, "priv "),
Some(ast::Inherited) | None => Ok(())
Expand All @@ -473,8 +473,8 @@ impl fmt::Show for VisSpace {
}

impl fmt::Show for PuritySpace {
fn fmt(p: &PuritySpace, f: &mut fmt::Formatter) -> fmt::Result {
match p.get() {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.get() {
ast::UnsafeFn => write!(f.buf, "unsafe "),
ast::ExternFn => write!(f.buf, "extern "),
ast::ImpureFn => Ok(())
Expand All @@ -483,8 +483,8 @@ impl fmt::Show for PuritySpace {
}

impl fmt::Show for clean::ViewPath {
fn fmt(v: &clean::ViewPath, f: &mut fmt::Formatter) -> fmt::Result {
match *v {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
clean::SimpleImport(ref name, ref src) => {
if *name == src.path.segments.last().unwrap().name {
write!(f.buf, "use {};", *src)
Expand All @@ -510,14 +510,14 @@ impl fmt::Show for clean::ViewPath {
}

impl fmt::Show for clean::ImportSource {
fn fmt(v: &clean::ImportSource, f: &mut fmt::Formatter) -> fmt::Result {
match v.did {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.did {
// FIXME: shouldn't be restricted to just local imports
Some(did) if ast_util::is_local(did) => {
resolved_path(f.buf, did.node, &v.path, true)
resolved_path(f.buf, did.node, &self.path, true)
}
_ => {
for (i, seg) in v.path.segments.iter().enumerate() {
for (i, seg) in self.path.segments.iter().enumerate() {
if i > 0 {
if_ok!(write!(f.buf, "::"))
}
Expand All @@ -530,21 +530,21 @@ impl fmt::Show for clean::ImportSource {
}

impl fmt::Show for clean::ViewListIdent {
fn fmt(v: &clean::ViewListIdent, f: &mut fmt::Formatter) -> fmt::Result {
match v.source {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.source {
// FIXME: shouldn't be limited to just local imports
Some(did) if ast_util::is_local(did) => {
let path = clean::Path {
global: false,
segments: ~[clean::PathSegment {
name: v.name.clone(),
name: self.name.clone(),
lifetimes: ~[],
types: ~[],
}]
};
resolved_path(f.buf, did.node, &path, false)
}
_ => write!(f.buf, "{}", v.name),
_ => write!(f.buf, "{}", self.name),
}
}
}
4 changes: 2 additions & 2 deletions src/librustdoc/html/markdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,8 +211,8 @@ pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector) {
}

impl<'a> fmt::Show for Markdown<'a> {
fn fmt(md: &Markdown<'a>, fmt: &mut fmt::Formatter) -> fmt::Result {
let Markdown(md) = *md;
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let Markdown(md) = *self;
// This is actually common enough to special-case
if md.len() == 0 { return Ok(()) }
render(fmt.buf, md.as_slice())
Expand Down
57 changes: 28 additions & 29 deletions src/librustdoc/html/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -801,8 +801,8 @@ impl<'a> Item<'a> {
}

impl<'a> fmt::Show for Item<'a> {
fn fmt(it: &Item<'a>, fmt: &mut fmt::Formatter) -> fmt::Result {
match attr::find_stability(it.item.attrs.iter()) {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match attr::find_stability(self.item.attrs.iter()) {
Some(ref stability) => {
if_ok!(write!(fmt.buf,
"<a class='stability {lvl}' title='{reason}'>{lvl}</a>",
Expand All @@ -815,38 +815,38 @@ impl<'a> fmt::Show for Item<'a> {
None => {}
}

if it.cx.include_sources {
if self.cx.include_sources {
let mut path = ~[];
clean_srcpath(it.item.source.filename.as_bytes(), |component| {
clean_srcpath(self.item.source.filename.as_bytes(), |component| {
path.push(component.to_owned());
});
let href = if it.item.source.loline == it.item.source.hiline {
format!("{}", it.item.source.loline)
let href = if self.item.source.loline == self.item.source.hiline {
format!("{}", self.item.source.loline)
} else {
format!("{}-{}", it.item.source.loline, it.item.source.hiline)
format!("{}-{}", self.item.source.loline, self.item.source.hiline)
};
if_ok!(write!(fmt.buf,
"<a class='source'
href='{root}src/{crate}/{path}.html\\#{href}'>\
[src]</a>",
root = it.cx.root_path,
crate = it.cx.layout.crate,
root = self.cx.root_path,
crate = self.cx.layout.crate,
path = path.connect("/"),
href = href));
}

// Write the breadcrumb trail header for the top
if_ok!(write!(fmt.buf, "<h1 class='fqn'>"));
match it.item.inner {
match self.item.inner {
clean::ModuleItem(..) => if_ok!(write!(fmt.buf, "Module ")),
clean::FunctionItem(..) => if_ok!(write!(fmt.buf, "Function ")),
clean::TraitItem(..) => if_ok!(write!(fmt.buf, "Trait ")),
clean::StructItem(..) => if_ok!(write!(fmt.buf, "Struct ")),
clean::EnumItem(..) => if_ok!(write!(fmt.buf, "Enum ")),
_ => {}
}
let cur = it.cx.current.as_slice();
let amt = if it.ismodule() { cur.len() - 1 } else { cur.len() };
let cur = self.cx.current.as_slice();
let amt = if self.ismodule() { cur.len() - 1 } else { cur.len() };
for (i, component) in cur.iter().enumerate().take(amt) {
let mut trail = ~"";
for _ in range(0, cur.len() - i - 1) {
Expand All @@ -856,17 +856,17 @@ impl<'a> fmt::Show for Item<'a> {
trail, component.as_slice()));
}
if_ok!(write!(fmt.buf, "<a class='{}' href=''>{}</a></h1>",
shortty(it.item), it.item.name.get_ref().as_slice()));
shortty(self.item), self.item.name.get_ref().as_slice()));

match it.item.inner {
clean::ModuleItem(ref m) => item_module(fmt.buf, it.cx,
it.item, m.items),
match self.item.inner {
clean::ModuleItem(ref m) => item_module(fmt.buf, self.cx,
self.item, m.items),
clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
item_function(fmt.buf, it.item, f),
clean::TraitItem(ref t) => item_trait(fmt.buf, it.item, t),
clean::StructItem(ref s) => item_struct(fmt.buf, it.item, s),
clean::EnumItem(ref e) => item_enum(fmt.buf, it.item, e),
clean::TypedefItem(ref t) => item_typedef(fmt.buf, it.item, t),
item_function(fmt.buf, self.item, f),
clean::TraitItem(ref t) => item_trait(fmt.buf, self.item, t),
clean::StructItem(ref s) => item_struct(fmt.buf, self.item, s),
clean::EnumItem(ref e) => item_enum(fmt.buf, self.item, e),
clean::TypedefItem(ref t) => item_typedef(fmt.buf, self.item, t),
_ => Ok(())
}
}
Expand Down Expand Up @@ -992,9 +992,8 @@ fn item_module(w: &mut Writer, cx: &Context,
clean::StaticItem(ref s) | clean::ForeignStaticItem(ref s) => {
struct Initializer<'a>(&'a str);
impl<'a> fmt::Show for Initializer<'a> {
fn fmt(s: &Initializer<'a>,
f: &mut fmt::Formatter) -> fmt::Result {
let Initializer(s) = *s;
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let Initializer(s) = *self;
if s.len() == 0 { return Ok(()); }
if_ok!(write!(f.buf, "<code> = </code>"));
let tag = if s.contains("\n") { "pre" } else { "code" };
Expand Down Expand Up @@ -1518,9 +1517,9 @@ fn item_typedef(w: &mut Writer, it: &clean::Item,
}

impl<'a> fmt::Show for Sidebar<'a> {
fn fmt(s: &Sidebar<'a>, fmt: &mut fmt::Formatter) -> fmt::Result {
let cx = s.cx;
let it = s.item;
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let cx = self.cx;
let it = self.item;
if_ok!(write!(fmt.buf, "<p class='location'>"));
let len = cx.current.len() - if it.is_mod() {1} else {0};
for (i, name) in cx.current.iter().take(len).enumerate() {
Expand Down Expand Up @@ -1588,8 +1587,8 @@ fn build_sidebar(m: &clean::Module) -> HashMap<~str, ~[~str]> {
}

impl<'a> fmt::Show for Source<'a> {
fn fmt(s: &Source<'a>, fmt: &mut fmt::Formatter) -> fmt::Result {
let Source(s) = *s;
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let Source(s) = *self;
let lines = s.lines().len();
let mut cols = 0;
let mut tmp = lines;
Expand Down
Loading