Skip to content

use static reference for AsMapping / AsSequence #3750

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 9 commits into from
May 29, 2022
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
13 changes: 11 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

55 changes: 55 additions & 0 deletions benches/benchmarks/fannkuch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
"""
The Computer Language Benchmarks Game
http://benchmarksgame.alioth.debian.org/

Contributed by Sokolov Yura, modified by Tupteq.
"""

# import pyperf


DEFAULT_ARG = 9


def fannkuch(n):
count = list(range(1, n + 1))
max_flips = 0
m = n - 1
r = n
perm1 = list(range(n))
perm = list(range(n))
perm1_ins = perm1.insert
perm1_pop = perm1.pop

while 1:
while r != 1:
count[r - 1] = r
r -= 1

if perm1[0] != 0 and perm1[m] != m:
perm = perm1[:]
flips_count = 0
k = perm[0]
while k:
perm[:k + 1] = perm[k::-1]
flips_count += 1
k = perm[0]

if flips_count > max_flips:
max_flips = flips_count

while r != n:
perm1_ins(r, perm1_pop(0))
count[r] -= 1
if count[r] > 0:
break
r += 1
else:
return max_flips


if __name__ == "__main__":
#runner = pyperf.Runner()
arg = DEFAULT_ARG
#runner.bench_func('fannkuch', fannkuch, arg)
fannkuch(arg)
2 changes: 1 addition & 1 deletion derive/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ proc-macro = true

[dependencies]
syn = { version = "1.0.91", features = ["full", "extra-traits"] }
syn-ext = { version = "0.3.1", features = ["full"] }
syn-ext = { version = "0.4.0", features = ["full"] }
quote = "1.0.18"
proc-macro2 = "1.0.37"
rustpython-compiler = { path = "../compiler/porcelain", version = "0.1.1" }
Expand Down
21 changes: 12 additions & 9 deletions derive/src/pyclass.rs
Original file line number Diff line number Diff line change
Expand Up @@ -548,25 +548,28 @@ where
Item: ItemLike + ToTokens + GetIdent,
{
fn gen_impl_item(&self, args: ImplItemArgs<'_, Item>) -> Result<()> {
let func = args
.item
.function_or_method()
.map_err(|_| self.new_syn_error(args.item.span(), "can only be on a method"))?;
let ident = &func.sig().ident;
let (ident, span) = if let Ok(c) = args.item.constant() {
(c.ident(), c.span())
} else if let Ok(f) = args.item.function_or_method() {
(&f.sig().ident, f.span())
} else {
return Err(self.new_syn_error(args.item.span(), "can only be on a method"));
};

let item_attr = args.attrs.remove(self.index());
let item_meta = SlotItemMeta::from_attr(ident.clone(), &item_attr)?;

let slot_ident = item_meta.slot_name()?;
let slot_ident = Ident::new(&slot_ident.to_string().to_lowercase(), slot_ident.span());
let slot_name = slot_ident.to_string();
let tokens = {
const NON_ATOMIC_SLOTS: &[&str] = &["as_buffer"];
if NON_ATOMIC_SLOTS.contains(&slot_name.as_str()) {
quote_spanned! { func.span() =>
quote_spanned! { span =>
slots.#slot_ident = Some(Self::#ident as _);
}
} else {
quote_spanned! { func.span() =>
quote_spanned! { span =>
slots.#slot_ident.store(Some(Self::#ident as _));
}
}
Expand Down Expand Up @@ -599,11 +602,11 @@ where
Ok(py_name)
};
let (ident, py_name, tokens) =
if args.item.function_or_method().is_ok() || args.item.is_const() {
if args.item.function_or_method().is_ok() || args.item.constant().is_ok() {
let ident = args.item.get_ident().unwrap();
let py_name = get_py_name(&attr, ident)?;

let value = if args.item.is_const() {
let value = if args.item.constant().is_ok() {
// TODO: ctx.new_value
quote_spanned!(ident.span() => ctx.new_int(Self::#ident).into())
} else {
Expand Down
10 changes: 2 additions & 8 deletions stdlib/src/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1238,8 +1238,8 @@ mod array {
},
};

impl PyArray {
const MAPPING_METHODS: PyMappingMethods = PyMappingMethods {
impl AsMapping for PyArray {
const AS_MAPPING: PyMappingMethods = PyMappingMethods {
length: Some(|mapping, _vm| Ok(Self::mapping_downcast(mapping).len())),
subscript: Some(|mapping, needle, vm| {
Self::mapping_downcast(mapping)._getitem(needle, vm)
Expand All @@ -1255,12 +1255,6 @@ mod array {
};
}

impl AsMapping for PyArray {
fn as_mapping(_zelf: &Py<Self>, _vm: &VirtualMachine) -> PyMappingMethods {
Self::MAPPING_METHODS
}
}

impl Iterable for PyArray {
fn iter(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult {
Ok(PyArrayIter {
Expand Down
44 changes: 16 additions & 28 deletions vm/src/builtins/bytearray.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ use crate::{
TryFromBorrowedObject, TryFromObject, VirtualMachine,
};
use bstr::ByteSlice;
use std::{borrow::Cow, mem::size_of};
use std::mem::size_of;

#[pyclass(module = false, name = "bytearray")]
#[derive(Debug, Default)]
Expand Down Expand Up @@ -690,23 +690,6 @@ impl PyByteArray {
}
}

impl PyByteArray {
const MAPPING_METHODS: PyMappingMethods = PyMappingMethods {
length: Some(|mapping, _vm| Ok(Self::mapping_downcast(mapping).len())),
subscript: Some(|mapping, needle, vm| {
Self::mapping_downcast(mapping).getitem(needle.to_owned(), vm)
}),
ass_subscript: Some(|mapping, needle, value, vm| {
let zelf = Self::mapping_downcast(mapping);
if let Some(value) = value {
Self::setitem(zelf.to_owned(), needle.to_owned(), value, vm)
} else {
zelf.delitem(needle.to_owned(), vm)
}
}),
};
}

impl Constructor for PyByteArray {
type Args = FuncArgs;

Expand Down Expand Up @@ -784,19 +767,24 @@ impl<'a> BufferResizeGuard<'a> for PyByteArray {
}

impl AsMapping for PyByteArray {
fn as_mapping(_zelf: &crate::Py<Self>, _vm: &VirtualMachine) -> PyMappingMethods {
Self::MAPPING_METHODS
}
const AS_MAPPING: PyMappingMethods = PyMappingMethods {
length: Some(|mapping, _vm| Ok(Self::mapping_downcast(mapping).len())),
subscript: Some(|mapping, needle, vm| {
Self::mapping_downcast(mapping).getitem(needle.to_owned(), vm)
}),
ass_subscript: Some(|mapping, needle, value, vm| {
let zelf = Self::mapping_downcast(mapping);
if let Some(value) = value {
Self::setitem(zelf.to_owned(), needle.to_owned(), value, vm)
} else {
zelf.delitem(needle.to_owned(), vm)
}
}),
};
}

impl AsSequence for PyByteArray {
fn as_sequence(_zelf: &Py<Self>, _vm: &VirtualMachine) -> Cow<'static, PySequenceMethods> {
Cow::Borrowed(&Self::SEQUENCE_METHODS)
}
}

impl PyByteArray {
const SEQUENCE_METHODS: PySequenceMethods = PySequenceMethods {
const AS_SEQUENCE: PySequenceMethods = PySequenceMethods {
length: Some(|seq, _vm| Ok(Self::sequence_downcast(seq).len())),
concat: Some(|seq, other, vm| {
Self::sequence_downcast(seq)
Expand Down
28 changes: 8 additions & 20 deletions vm/src/builtins/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use crate::{
TryFromBorrowedObject, TryFromObject, VirtualMachine,
};
use bstr::ByteSlice;
use std::{borrow::Cow, mem::size_of, ops::Deref};
use std::{mem::size_of, ops::Deref};

#[pyclass(module = false, name = "bytes")]
#[derive(Clone, Debug)]
Expand Down Expand Up @@ -550,14 +550,6 @@ impl PyBytes {
}
}

impl PyBytes {
const MAPPING_METHODS: PyMappingMethods = PyMappingMethods {
length: Some(|mapping, _vm| Ok(Self::mapping_downcast(mapping).len())),
subscript: Some(|mapping, needle, vm| Self::mapping_downcast(mapping)._getitem(needle, vm)),
ass_subscript: None,
};
}

static BUFFER_METHODS: BufferMethods = BufferMethods {
obj_bytes: |buffer| buffer.obj_as::<PyBytes>().as_bytes().into(),
obj_bytes_mut: |_| panic!(),
Expand All @@ -577,19 +569,15 @@ impl AsBuffer for PyBytes {
}

impl AsMapping for PyBytes {
fn as_mapping(_zelf: &Py<Self>, _vm: &VirtualMachine) -> PyMappingMethods {
Self::MAPPING_METHODS
}
const AS_MAPPING: PyMappingMethods = PyMappingMethods {
length: Some(|mapping, _vm| Ok(Self::mapping_downcast(mapping).len())),
subscript: Some(|mapping, needle, vm| Self::mapping_downcast(mapping)._getitem(needle, vm)),
ass_subscript: None,
};
}

impl AsSequence for PyBytes {
fn as_sequence(_zelf: &Py<Self>, _vm: &VirtualMachine) -> Cow<'static, PySequenceMethods> {
Cow::Borrowed(&Self::SEQUENCE_METHODS)
}
}

impl PyBytes {
const SEQUENCE_METHODS: PySequenceMethods = PySequenceMethods {
const AS_SEQUENCE: PySequenceMethods = PySequenceMethods {
length: Some(|seq, _vm| Ok(Self::sequence_downcast(seq).len())),
concat: Some(|seq, other, vm| {
Self::sequence_downcast(seq)
Expand All @@ -614,7 +602,7 @@ impl PyBytes {
let other = <Either<PyBytesInner, PyIntRef>>::try_from_object(vm, other.to_owned())?;
Self::sequence_downcast(seq).contains(other, vm)
}),
..*PySequenceMethods::not_implemented()
..PySequenceMethods::NOT_IMPLEMENTED
};
}

Expand Down
Loading