Skip to content

Commit 1e576b5

Browse files
Merge pull request RustPython#273 from skinny121/tuple_add
Add tuple.__add__
2 parents 44e9658 + caac5a3 commit 1e576b5

File tree

3 files changed

+25
-0
lines changed

3 files changed

+25
-0
lines changed

parser/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ extern crate num_traits;
77
pub mod ast;
88
pub mod lexer;
99
pub mod parser;
10+
#[cfg_attr(rustfmt, rustfmt_skip)]
1011
mod python;
1112
pub mod token;
1213

tests/snippets/tuple.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
y = (1,)
77
assert y[0] == 1
88

9+
assert x + y == (1, 2, 1)
10+
911
assert x * 3 == (1, 2, 1, 2, 1, 2)
1012
# assert 3 * x == (1, 2, 1, 2, 1, 2)
1113
assert x * 0 == ()

vm/src/obj/objtuple.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,27 @@ use super::objtype;
1010
use num_bigint::ToBigInt;
1111
use std::hash::{Hash, Hasher};
1212

13+
fn tuple_add(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
14+
arg_check!(
15+
vm,
16+
args,
17+
required = [(zelf, Some(vm.ctx.tuple_type())), (other, None)]
18+
);
19+
20+
if objtype::isinstance(other, &vm.ctx.tuple_type()) {
21+
let e1 = get_elements(zelf);
22+
let e2 = get_elements(other);
23+
let elements = e1.iter().chain(e2.iter()).map(|e| e.clone()).collect();
24+
Ok(vm.ctx.new_tuple(elements))
25+
} else {
26+
Err(vm.new_type_error(format!(
27+
"Cannot add {} and {}",
28+
zelf.borrow(),
29+
other.borrow()
30+
)))
31+
}
32+
}
33+
1334
fn tuple_count(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
1435
arg_check!(
1536
vm,
@@ -165,6 +186,7 @@ pub fn tuple_contains(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
165186

166187
pub fn init(context: &PyContext) {
167188
let ref tuple_type = context.tuple_type;
189+
context.set_attr(&tuple_type, "__add__", context.new_rustfunc(tuple_add));
168190
context.set_attr(&tuple_type, "__eq__", context.new_rustfunc(tuple_eq));
169191
context.set_attr(
170192
&tuple_type,

0 commit comments

Comments
 (0)