Skip to content
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

Add self argument destructuring. Closes #7613. #12566

Closed
wants to merge 1 commit into from
Closed
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
11 changes: 11 additions & 0 deletions src/doc/rust.md
Original file line number Diff line number Diff line change
Expand Up @@ -3422,6 +3422,17 @@ impl Printable for ~str {
`self` refers to the value of type `~str` that is the receiver for a
call to the method `make_string`.

The `self` argument may be destructured using `self @ pattern` syntax.
For example:

~~~~
struct Foo(uint);

impl Foo {
fn b(&self@&Foo(ref u)) { ... }
}
~~~~

## Type kinds

Types in Rust are categorized into kinds, based on various properties of the components of the type.
Expand Down
4 changes: 2 additions & 2 deletions src/libsyntax/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -893,7 +893,7 @@ pub struct Arg {
}

impl Arg {
pub fn new_self(span: Span, mutability: Mutability) -> Arg {
pub fn new_self(span: Span, mutability: Mutability, pat: Option<P<Pat>>) -> Arg {
let path = ast_util::ident_to_path(span, special_idents::self_);
Arg {
// HACK(eddyb) fake type for the self argument.
Expand All @@ -904,7 +904,7 @@ impl Arg {
}),
pat: @Pat {
id: DUMMY_NODE_ID,
node: PatIdent(BindByValue(mutability), path, None),
node: PatIdent(BindByValue(mutability), path, pat),
span: span
},
id: DUMMY_NODE_ID
Expand Down
2 changes: 1 addition & 1 deletion src/libsyntax/ext/deriving/generic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -581,7 +581,7 @@ impl<'a> MethodDef<'a> {

let self_arg = match explicit_self.node {
ast::SelfStatic => None,
_ => Some(ast::Arg::new_self(trait_.span, ast::MutImmutable))
_ => Some(ast::Arg::new_self(trait_.span, ast::MutImmutable, None))
};
let args = {
let args = arg_types.move_iter().map(|(name, ty)| {
Expand Down
52 changes: 36 additions & 16 deletions src/libsyntax/parse/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1058,6 +1058,17 @@ impl Parser {
p.parse_arg_general(false)
});

match explicit_self.node {
SelfStatic => (),
_ => match d.inputs[0].pat.node {
PatIdent(_, _, Some(_)) => {
p.span_err(d.inputs[0].pat.span,
"cannot destructure self in trait methods");
}
_ => (),
}
}

let hi = p.last_span.hi;
match p.token {
token::SEMI => {
Expand Down Expand Up @@ -3598,8 +3609,17 @@ impl Parser {
// that may have a self type.
fn parse_fn_decl_with_self(&mut self, parse_arg_fn: |&mut Parser| -> Arg)
-> (ExplicitSelf, P<FnDecl>) {
fn parse_self_pat(p: &mut Parser) -> Option<P<Pat>> {
if p.token == token::AT {
p.bump();
Some(p.parse_pat())
} else {
None
}
}

fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
-> ast::ExplicitSelf_ {
-> (ast::ExplicitSelf_,Option<P<Pat>>) {
// The following things are possible to see here:
//
// fn(&mut self)
Expand All @@ -3612,23 +3632,23 @@ impl Parser {
if this.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
this.bump();
this.expect_self_ident();
SelfRegion(None, MutImmutable)
(SelfRegion(None, MutImmutable), parse_self_pat(this))
} else if this.look_ahead(1, |t| Parser::token_is_mutability(t)) &&
this.look_ahead(2,
|t| token::is_keyword(keywords::Self,
t)) {
this.bump();
let mutability = this.parse_mutability();
this.expect_self_ident();
SelfRegion(None, mutability)
(SelfRegion(None, mutability), parse_self_pat(this))
} else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
this.look_ahead(2,
|t| token::is_keyword(keywords::Self,
t)) {
this.bump();
let lifetime = this.parse_lifetime();
this.expect_self_ident();
SelfRegion(Some(lifetime), MutImmutable)
(SelfRegion(Some(lifetime), MutImmutable), parse_self_pat(this))
} else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
this.look_ahead(2, |t| {
Parser::token_is_mutability(t)
Expand All @@ -3639,9 +3659,9 @@ impl Parser {
let lifetime = this.parse_lifetime();
let mutability = this.parse_mutability();
this.expect_self_ident();
SelfRegion(Some(lifetime), mutability)
(SelfRegion(Some(lifetime), mutability), parse_self_pat(this))
} else {
SelfStatic
(SelfStatic,None)
}
}

Expand All @@ -3651,7 +3671,7 @@ impl Parser {
// backwards compatible.
let lo = self.span.lo;
let mut mutbl_self = MutImmutable;
let explicit_self = match self.token {
let (explicit_self,self_pat) = match self.token {
token::BINOP(token::AND) => {
maybe_parse_borrowed_explicit_self(self)
}
Expand All @@ -3660,14 +3680,14 @@ impl Parser {
if self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
self.bump();
self.expect_self_ident();
SelfUniq
(SelfUniq,parse_self_pat(self))
} else {
SelfStatic
(SelfStatic,None)
}
}
token::IDENT(..) if self.is_self_ident() => {
self.bump();
SelfValue
(SelfValue,parse_self_pat(self))
}
token::BINOP(token::STAR) => {
// Possibly "*self" or "*mut self" -- not supported. Try to avoid
Expand All @@ -3680,23 +3700,23 @@ impl Parser {
self.span_err(self.span, "cannot pass self by unsafe pointer");
self.bump();
}
SelfValue
(SelfValue,parse_self_pat(self))
}
_ if Parser::token_is_mutability(&self.token) &&
self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) => {
mutbl_self = self.parse_mutability();
self.expect_self_ident();
SelfValue
(SelfValue,parse_self_pat(self))
}
_ if Parser::token_is_mutability(&self.token) &&
self.look_ahead(1, |t| *t == token::TILDE) &&
self.look_ahead(2, |t| token::is_keyword(keywords::Self, t)) => {
mutbl_self = self.parse_mutability();
self.bump();
self.expect_self_ident();
SelfUniq
(SelfUniq,parse_self_pat(self))
}
_ => SelfStatic
_ => (SelfStatic,None)
};

let explicit_self_sp = mk_sp(lo, self.span.hi);
Expand All @@ -3712,11 +3732,11 @@ impl Parser {
sep,
parse_arg_fn
);
fn_inputs.unshift(Arg::new_self(explicit_self_sp, mutbl_self));
fn_inputs.unshift(Arg::new_self(explicit_self_sp, mutbl_self, self_pat));
fn_inputs
}
token::RPAREN => {
~[Arg::new_self(explicit_self_sp, mutbl_self)]
~[Arg::new_self(explicit_self_sp, mutbl_self, self_pat)]
}
_ => {
let token_str = self.this_token_to_str();
Expand Down
22 changes: 15 additions & 7 deletions src/libsyntax/print/pprust.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1786,14 +1786,15 @@ pub fn print_pat(s: &mut State, pat: &ast::Pat) -> io::IoResult<()> {

pub fn explicit_self_to_str(explicit_self: &ast::ExplicitSelf_) -> ~str {
to_str(explicit_self, |a, &b| {
print_explicit_self(a, b, ast::MutImmutable).map(|_| ())
print_explicit_self(a, b, ast::MutImmutable, None).map(|_| ())
})
}

// Returns whether it printed anything
fn print_explicit_self(s: &mut State,
explicit_self: ast::ExplicitSelf_,
mutbl: ast::Mutability) -> io::IoResult<bool> {
mutbl: ast::Mutability,
self_pat: Option<P<ast::Pat>>) -> io::IoResult<bool> {
try!(print_mutability(s, mutbl));
match explicit_self {
ast::SelfStatic => { return Ok(false); }
Expand All @@ -1810,6 +1811,13 @@ fn print_explicit_self(s: &mut State,
try!(word(&mut s.s, "self"));
}
}
match self_pat {
Some(pat) => {
try!(word(&mut s.s, "@"));
try!(print_pat(s, pat));
}
None => ()
}
return Ok(true);
}

Expand Down Expand Up @@ -1840,14 +1848,14 @@ pub fn print_fn_args(s: &mut State, decl: &ast::FnDecl,
try!(rbox(s, 0u, Inconsistent));
let mut first = true;
for &explicit_self in opt_explicit_self.iter() {
let m = match explicit_self {
ast::SelfStatic => ast::MutImmutable,
let (m,self_pat) = match explicit_self {
ast::SelfStatic => (ast::MutImmutable,None),
_ => match decl.inputs[0].pat.node {
ast::PatIdent(ast::BindByValue(m), _, _) => m,
_ => ast::MutImmutable
ast::PatIdent(ast::BindByValue(m), _, pat) => (m,pat),
_ => (ast::MutImmutable,None),
}
};
first = !try!(print_explicit_self(s, explicit_self, m));
first = !try!(print_explicit_self(s, explicit_self, m, self_pat));
}

// HACK(eddyb) ignore the separately printed self argument.
Expand Down
8 changes: 8 additions & 0 deletions src/test/compile-fail/liveness-unused.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,5 +77,13 @@ fn f4b() -> int {
}
}

struct Foo(int);

impl Foo {
fn foo(&self@&Foo(i)) {
//~^ ERROR: unused variable: `i`
}
}

fn main() {
}
18 changes: 18 additions & 0 deletions src/test/compile-fail/self-pat-2.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

struct A(~uint);

trait T {
fn t(&self@&A(ref u));
//~^ ERROR: cannot destructure self in trait methods
}

fn main() {}
18 changes: 18 additions & 0 deletions src/test/compile-fail/self-pat-3.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

enum E { E1(int), E2(int) }

impl E {
fn t(&self@&E1(ref i)) {}
//~^ ERROR: refutable pattern in function argument
}

fn main() {}
28 changes: 28 additions & 0 deletions src/test/compile-fail/self-pat.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

struct A(~uint);

impl A {
fn a(&self@&A(ref mut u), i: uint) {
//~^ ERROR: cannot borrow immutable anonymous field as mutable
**u = i;
}

fn b(self@A(u)) -> ~uint {
let A(u) = self; // FIXME: Remove this line when #12534 is fixed
//~^ NOTE: `self#0` moved here
let _ = self;
//~^ ERROR: use of partially moved value: `self`
u
}
}

fn main() {}
56 changes: 56 additions & 0 deletions src/test/run-pass/self-pat.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

struct A(uint);

impl A {
fn a(self@A(u)) -> uint {
u
}

fn b(&mut self@&A(ref mut u), i: uint) {
*u = i;
}

fn c(~self@~A(u)) -> uint {
u
}
}

struct B<T> {
t: T,
}

impl<T> B<T> {
fn a(self@B { t: t }) -> T {
t
}

fn b(&mut self@&B { t: ref mut t }, i: T) {
*t = i;
}
}

fn main() {
let a = A(1);
assert_eq!(a.a(), 1);
let mut a = A(2);
a.b(3);
assert_eq!(a.a(), 3);
// FIXME A::c crashes (probably related to #12534)
// let a = ~A(1);
// assert_eq!(a.c(), 1);

let b = B { t: false };
assert!(!b.a());
let mut b = B { t: 0 as uint };
b.b(3);
assert_eq!(b.a(), 3);
}