Skip to content

Commit ee04326

Browse files
committed
add mapping type check to mappingproxy
As in cpython implementation there exists argument type checking before create mapping proxy like below. ```c if (!PyMapping_Check(mapping) || PyList_Check(mapping) || PyTuple_Check(mapping)) // print error ... ``` Signed-off-by: snowapril <sinjihng@gmail.com>
1 parent e0ac7a4 commit ee04326

File tree

2 files changed

+23
-5
lines changed

2 files changed

+23
-5
lines changed

vm/src/builtins/dict.rs

+9-1
Original file line numberDiff line numberDiff line change
@@ -926,7 +926,15 @@ pub struct PyMapping {
926926
Option<fn(PyObjectRef, PyObjectRef, Option<PyObjectRef>, &VirtualMachine) -> PyResult<()>>,
927927
}
928928

929-
impl PyMapping {}
929+
impl PyMapping {
930+
pub fn check(cls: &PyObjectRef, vm: &VirtualMachine) -> bool {
931+
if let Ok(mapping) = PyMapping::try_from_borrowed_object(vm, cls) {
932+
mapping.subscript.is_some()
933+
} else {
934+
false
935+
}
936+
}
937+
}
930938

931939
impl TryFromBorrowedObject for PyMapping {
932940
fn try_from_borrowed_object(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult<Self> {

vm/src/builtins/mappingproxy.rs

+14-4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use super::{PyDict, PyStrRef, PyTypeRef};
1+
use super::{PyDict, PyList, PyStrRef, PyTuple, PyTypeRef};
22
use crate::{
33
builtins::dict::PyMapping,
44
function::OptionalArg,
@@ -38,10 +38,20 @@ impl SlotConstructor for PyMappingProxy {
3838
type Args = PyObjectRef;
3939

4040
fn py_new(cls: PyTypeRef, mapping: Self::Args, vm: &VirtualMachine) -> PyResult {
41-
Self {
42-
mapping: MappingProxyInner::Dict(mapping),
41+
if !PyMapping::check(&mapping, vm)
42+
|| mapping.payload_if_subclass::<PyList>(vm).is_some()
43+
|| mapping.payload_if_subclass::<PyTuple>(vm).is_some()
44+
{
45+
Err(vm.new_type_error(format!(
46+
"mappingproxy() argument must be a mapping, not {}",
47+
mapping.class()
48+
)))
49+
} else {
50+
Self {
51+
mapping: MappingProxyInner::Dict(mapping),
52+
}
53+
.into_pyresult_with_type(vm, cls)
4354
}
44-
.into_pyresult_with_type(vm, cls)
4555
}
4656
}
4757

0 commit comments

Comments
 (0)