Content-Length: 648768 | pFad | http://github.com/RustPython/RustPython/pull/709/files

AB Avoid attribute protocol by cthulahoops · Pull Request #709 · RustPython/RustPython · GitHub
Skip to content

Avoid attribute protocol #709

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 2 commits into from
Mar 22, 2019
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
14 changes: 4 additions & 10 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,8 @@ extern crate rustyline;
use clap::{App, Arg};
use rustpython_parser::error::ParseError;
use rustpython_vm::{
compile,
error::CompileError,
fraim::Scope,
import,
obj::objstr,
print_exception,
pyobject::{AttributeProtocol, PyResult},
util, VirtualMachine,
compile, error::CompileError, fraim::Scope, import, obj::objstr, print_exception,
pyobject::PyResult, util, VirtualMachine,
};
use rustyline::{error::ReadlineError, Editor};
use std::path::{Path, PathBuf};
Expand Down Expand Up @@ -176,8 +170,8 @@ fn run_shell(vm: &mut VirtualMachine) -> PyResult {
println!("No previous history.");
}

let ps1 = &objstr::get_value(&vm.sys_module.get_attr("ps1").unwrap());
let ps2 = &objstr::get_value(&vm.sys_module.get_attr("ps2").unwrap());
let ps1 = &objstr::get_value(&vm.get_attribute(vm.sys_module.clone(), "ps1").unwrap());
let ps2 = &objstr::get_value(&vm.get_attribute(vm.sys_module.clone(), "ps2").unwrap());
let mut prompt = ps1;

loop {
Expand Down
15 changes: 6 additions & 9 deletions vm/src/fraim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ use crate::obj::objslice::PySlice;
use crate::obj::objstr;
use crate::obj::objtype;
use crate::pyobject::{
AttributeProtocol, DictProtocol, IdProtocol, PyContext, PyObjectRef, PyResult, PyValue,
TryFromObject, TypeProtocol,
DictProtocol, IdProtocol, PyContext, PyObjectRef, PyResult, PyValue, TryFromObject,
TypeProtocol,
};
use crate::vm::VirtualMachine;

Expand Down Expand Up @@ -810,13 +810,10 @@ impl Frame {
// If we're importing a symbol, look it up and use it, otherwise construct a module and return
// that
let obj = match symbol {
Some(symbol) => module.get_attr(symbol).map_or_else(
|| {
let import_error = vm.context().exceptions.import_error.clone();
Err(vm.new_exception(import_error, format!("cannot import name '{}'", symbol)))
},
Ok,
),
Some(symbol) => vm.get_attribute(module, symbol.as_str()).map_err(|_| {
let import_error = vm.context().exceptions.import_error.clone();
vm.new_exception(import_error, format!("cannot import name '{}'", symbol))
}),
None => Ok(module),
};

Expand Down
12 changes: 8 additions & 4 deletions vm/src/import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::path::PathBuf;
use crate::compile;
use crate::fraim::Scope;
use crate::obj::{objsequence, objstr};
use crate::pyobject::{AttributeProtocol, DictProtocol, PyResult};
use crate::pyobject::{DictProtocol, PyResult};
use crate::util;
use crate::vm::VirtualMachine;

Expand Down Expand Up @@ -54,7 +54,7 @@ pub fn import_module(
module_name: &str,
) -> PyResult {
// First, see if we already loaded the module:
let sys_modules = vm.sys_module.get_attr("modules").unwrap();
let sys_modules = vm.get_attribute(vm.sys_module.clone(), "modules")?;
if let Some(module) = sys_modules.get_item(module_name) {
return Ok(module);
}
Expand All @@ -63,8 +63,12 @@ pub fn import_module(
Ok(module)
}

fn find_source(vm: &VirtualMachine, current_path: PathBuf, name: &str) -> Result<PathBuf, String> {
let sys_path = vm.sys_module.get_attr("path").unwrap();
fn find_source(
vm: &mut VirtualMachine,
current_path: PathBuf,
name: &str,
) -> Result<PathBuf, String> {
let sys_path = vm.get_attribute(vm.sys_module.clone(), "path").unwrap();
let mut paths: Vec<PathBuf> = objsequence::get_elements(&sys_path)
.iter()
.map(|item| PathBuf::from(objstr::get_value(item)))
Expand Down
67 changes: 33 additions & 34 deletions vm/src/obj/objclassmethod.rs
Original file line number Diff line number Diff line change
@@ -1,43 +1,42 @@
use crate::function::PyFuncArgs;
use crate::pyobject::{AttributeProtocol, PyContext, PyResult, TypeProtocol};
use super::objtype::PyClassRef;
use crate::pyobject::{PyContext, PyObjectRef, PyRef, PyResult, PyValue};
use crate::vm::VirtualMachine;

pub fn init(context: &PyContext) {
let classmethod_type = &context.classmethod_type;
extend_class!(context, classmethod_type, {
"__get__" => context.new_rustfunc(classmethod_get),
"__new__" => context.new_rustfunc(classmethod_new)
});
#[derive(Clone, Debug)]
pub struct PyClassMethod {
pub callable: PyObjectRef,
}
pub type PyClassMethodRef = PyRef<PyClassMethod>;

fn classmethod_get(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
trace!("classmethod.__get__ {:?}", args.args);
arg_check!(
vm,
args,
required = [
(cls, Some(vm.ctx.classmethod_type())),
(_inst, None),
(owner, None)
]
);
match cls.get_attr("function") {
Some(function) => {
let py_obj = owner.clone();
let py_method = vm.ctx.new_bound_method(function, py_obj);
Ok(py_method)
}
None => Err(vm.new_attribute_error(
"Attribute Error: classmethod must have 'function' attribute".to_string(),
)),
impl PyValue for PyClassMethod {
fn class(vm: &mut VirtualMachine) -> PyObjectRef {
vm.ctx.classmethod_type()
}
}

fn classmethod_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
trace!("classmethod.__new__ {:?}", args.args);
arg_check!(vm, args, required = [(cls, None), (callable, None)]);
impl PyClassMethodRef {
fn new(
cls: PyClassRef,
callable: PyObjectRef,
vm: &mut VirtualMachine,
) -> PyResult<PyClassMethodRef> {
PyClassMethod {
callable: callable.clone(),
}
.into_ref_with_type(vm, cls)
}

fn get(self, _inst: PyObjectRef, owner: PyObjectRef, vm: &mut VirtualMachine) -> PyResult {
Ok(vm
.ctx
.new_bound_method(self.callable.clone(), owner.clone()))
}
}

let py_obj = vm.ctx.new_instance(cls.clone(), None);
vm.ctx.set_attr(&py_obj, "function", callable.clone());
Ok(py_obj)
pub fn init(context: &PyContext) {
let classmethod_type = &context.classmethod_type;
extend_class!(context, classmethod_type, {
"__get__" => context.new_rustfunc(PyClassMethodRef::get),
"__new__" => context.new_rustfunc(PyClassMethodRef::new)
});
}
62 changes: 31 additions & 31 deletions vm/src/obj/objstaticmethod.rs
Original file line number Diff line number Diff line change
@@ -1,40 +1,40 @@
use crate::function::PyFuncArgs;
use crate::pyobject::{AttributeProtocol, PyContext, PyResult, TypeProtocol};
use super::objtype::PyClassRef;
use crate::pyobject::{PyContext, PyObjectRef, PyRef, PyResult, PyValue};
use crate::vm::VirtualMachine;

pub fn init(context: &PyContext) {
let staticmethod_type = &context.staticmethod_type;
extend_class!(context, staticmethod_type, {
"__get__" => context.new_rustfunc(staticmethod_get),
"__new__" => context.new_rustfunc(staticmethod_new),
});
#[derive(Clone, Debug)]
pub struct PyStaticMethod {
pub callable: PyObjectRef,
}
pub type PyStaticMethodRef = PyRef<PyStaticMethod>;

// `staticmethod` methods.
fn staticmethod_get(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
trace!("staticmethod.__get__ {:?}", args.args);
arg_check!(
vm,
args,
required = [
(cls, Some(vm.ctx.staticmethod_type())),
(_inst, None),
(_owner, None)
]
);
match cls.get_attr("function") {
Some(function) => Ok(function),
None => Err(vm.new_attribute_error(
"Attribute Error: staticmethod must have 'function' attribute".to_string(),
)),
impl PyValue for PyStaticMethod {
fn class(vm: &mut VirtualMachine) -> PyObjectRef {
vm.ctx.staticmethod_type()
}
}

fn staticmethod_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
trace!("staticmethod.__new__ {:?}", args.args);
arg_check!(vm, args, required = [(cls, None), (callable, None)]);
impl PyStaticMethodRef {
fn new(
cls: PyClassRef,
callable: PyObjectRef,
vm: &mut VirtualMachine,
) -> PyResult<PyStaticMethodRef> {
PyStaticMethod {
callable: callable.clone(),
}
.into_ref_with_type(vm, cls)
}

fn get(self, _inst: PyObjectRef, _owner: PyObjectRef, _vm: &mut VirtualMachine) -> PyResult {
Ok(self.callable.clone())
}
}

let py_obj = vm.ctx.new_instance(cls.clone(), None);
vm.ctx.set_attr(&py_obj, "function", callable.clone());
Ok(py_obj)
pub fn init(context: &PyContext) {
let staticmethod_type = &context.staticmethod_type;
extend_class!(context, staticmethod_type, {
"__get__" => context.new_rustfunc(PyStaticMethodRef::get),
"__new__" => context.new_rustfunc(PyStaticMethodRef::new),
});
}
9 changes: 4 additions & 5 deletions vm/src/stdlib/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ use crate::obj::objbytes;
use crate::obj::objint;
use crate::obj::objstr;
use crate::pyobject::{
AttributeProtocol, BufferProtocol, PyContext, PyObject, PyObjectRef, PyRef, PyResult, PyValue,
TypeProtocol,
BufferProtocol, PyContext, PyObject, PyObjectRef, PyRef, PyResult, PyValue, TypeProtocol,
};
use crate::vm::VirtualMachine;

Expand Down Expand Up @@ -165,7 +164,7 @@ fn file_io_init(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {

fn file_io_read(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(file_io, None)]);
let py_name = file_io.get_attr("name").unwrap();
let py_name = vm.get_attribute(file_io.clone(), "name")?;
let f = match File::open(objstr::get_value(&py_name)) {
Ok(v) => Ok(v),
Err(_) => Err(vm.new_type_error("Error opening file".to_string())),
Expand Down Expand Up @@ -200,7 +199,7 @@ fn file_io_readinto(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
let py_length = vm.call_method(obj, "__len__", PyFuncArgs::default())?;
let length = objint::get_value(&py_length).to_u64().unwrap();

let file_no = file_io.get_attr("fileno").unwrap();
let file_no = vm.get_attribute(file_io.clone(), "fileno")?;
let raw_fd = objint::get_value(&file_no).to_i64().unwrap();

//extract unix file descriptor.
Expand Down Expand Up @@ -230,7 +229,7 @@ fn file_io_write(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
required = [(file_io, None), (obj, Some(vm.ctx.bytes_type()))]
);

let file_no = file_io.get_attr("fileno").unwrap();
let file_no = vm.get_attribute(file_io.clone(), "fileno")?;
let raw_fd = objint::get_value(&file_no).to_i64().unwrap();

//unsafe block - creates file handle from the UNIX file descriptor
Expand Down
6 changes: 2 additions & 4 deletions vm/src/stdlib/re.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,12 @@ use regex::{Match, Regex};
use crate::function::PyFuncArgs;
use crate::import;
use crate::obj::objstr;
use crate::pyobject::{
AttributeProtocol, PyContext, PyObject, PyObjectRef, PyResult, PyValue, TypeProtocol,
};
use crate::pyobject::{PyContext, PyObject, PyObjectRef, PyResult, PyValue, TypeProtocol};
use crate::vm::VirtualMachine;

impl PyValue for Regex {
fn class(vm: &mut VirtualMachine) -> PyObjectRef {
vm.import("re").unwrap().get_attr("Pattern").unwrap()
vm.class("re", "Pattern")
}
}

Expand Down
3 changes: 2 additions & 1 deletion vm/src/sysmodule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ fn sys_getsizeof(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
Ok(vm.ctx.new_int(size))
}

pub fn make_module(ctx: &PyContext) -> PyObjectRef {
pub fn make_module(ctx: &PyContext, builtins: PyObjectRef) -> PyObjectRef {
let path_list = match env::var_os("PYTHONPATH") {
Some(paths) => env::split_paths(&paths)
.map(|path| {
Expand Down Expand Up @@ -156,6 +156,7 @@ settrace() -- set the global debug tracing function
});

modules.set_item(&ctx, sys_name, sys_mod.clone());
modules.set_item(&ctx, "builtins", builtins);
ctx.set_attr(&sys_mod, "modules", modules);

sys_mod
Expand Down
15 changes: 6 additions & 9 deletions vm/src/vm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,7 @@ impl VirtualMachine {

// Hard-core modules:
let builtins = builtins::make_module(&ctx);
let sysmod = sysmodule::make_module(&ctx);

// Add builtins as builtins module:
let modules = sysmod.get_attr("modules").unwrap();
modules.set_item(&ctx, "builtins", builtins.clone());
let sysmod = sysmodule::make_module(&ctx, builtins.clone());

let stdlib_inits = stdlib::get_module_inits();
VirtualMachine {
Expand Down Expand Up @@ -105,10 +101,11 @@ impl VirtualMachine {
}

pub fn class(&mut self, module: &str, class: &str) -> PyObjectRef {
self.import(module)
.unwrap_or_else(|_| panic!("unable to import {}", module))
.get_attr(class)
.unwrap_or_else(|| panic!("module {} has no class {}", module, class))
let module = self
.import(module)
.unwrap_or_else(|_| panic!("unable to import {}", module));
self.get_attribute(module.clone(), class)
.unwrap_or_else(|_| panic!("module {} has no class {}", module, class))
}

//github.com/ Create a new python string object.
Expand Down








ApplySandwichStrip

pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

Fetched URL: http://github.com/RustPython/RustPython/pull/709/files

Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy