Validate declared class fields at construction and attribute writes
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
# 编译链路检查
|
||||
|
||||
[classes.rs](classes.rs) 覆盖源码 class、NativeTyped 实际原生载荷继承和多层字段构造、继承字段构造、动态方法覆盖、绑定接收者保活/回收、绑定后参数数量和重复成员/缺少 self 的预执行诊断。只编译,不在本地运行。
|
||||
[classes.rs](classes.rs) 覆盖源码 class、NativeTyped 实际原生载荷继承和多层字段构造、声明字段检查的构造/写入/继承/环境/GC、继承字段构造、动态方法覆盖、绑定接收者保活/回收、绑定后参数数量和重复成员/缺少 self 的预执行诊断。只编译,不在本地运行。
|
||||
|
||||
[pipeline.rs](pipeline.rs) 将真实 Endor 示例交给 reader/parser/名称分析/代码生成/VM,检查函数值、前向引用、局部遮蔽、精确数字常量、语义诊断、宿主全局与属性回调、对象结果保活、跨 VM 模板装载、源码签名保留和参数/返回失败清理、反复调用、错误帧清理、递归限额、共享交互命名空间及超过 255 的操作数。
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ impl NativeCallable for WidgetFactory {
|
||||
if values.len() != fields.len() {
|
||||
return Err(VmError::InvalidArgument("widget field count"));
|
||||
}
|
||||
cx.store().check_class_field_arguments(*requested, values)?;
|
||||
let instance = cx.allocate(NativeWidget(native_label.clone()))?;
|
||||
cx.attach_type(instance, *requested)?;
|
||||
for (field, value) in fields.iter().zip(values) {
|
||||
@@ -52,6 +53,7 @@ impl NativeCallable for WidgetFactory {
|
||||
#[test]
|
||||
fn source_subclasses_preserve_native_allocation_fields_and_nominal_identity() {
|
||||
let mut vm = Vm::new().unwrap();
|
||||
vm.set_source_type_checks(true).unwrap();
|
||||
let globals = vm.new_dict().unwrap();
|
||||
let roots = vm.bootstrap_types().unwrap();
|
||||
let factory = vm
|
||||
@@ -79,6 +81,15 @@ fn source_subclasses_preserve_native_allocation_fields_and_nominal_identity() {
|
||||
execute(&mut vm, globals, source, ParseMode::Module),
|
||||
Value::Nil
|
||||
);
|
||||
assert!(matches!(
|
||||
try_execute(
|
||||
&mut vm,
|
||||
globals,
|
||||
r#"Grand("native", "bad", "extra")"#,
|
||||
ParseMode::Expression
|
||||
),
|
||||
Err(VmError::TypeMismatch { .. })
|
||||
));
|
||||
let value = execute(
|
||||
&mut vm,
|
||||
globals,
|
||||
@@ -111,6 +122,15 @@ fn source_subclasses_preserve_native_allocation_fields_and_nominal_identity() {
|
||||
}
|
||||
|
||||
fn execute(vm: &mut Vm, globals: ObjectRef, source: &str, mode: ParseMode) -> Value {
|
||||
try_execute(vm, globals, source, mode).unwrap()
|
||||
}
|
||||
|
||||
fn try_execute(
|
||||
vm: &mut Vm,
|
||||
globals: ObjectRef,
|
||||
source: &str,
|
||||
mode: ParseMode,
|
||||
) -> Result<Value, VmError> {
|
||||
let names = vm
|
||||
.dict_items(globals)
|
||||
.unwrap()
|
||||
@@ -126,7 +146,7 @@ fn execute(vm: &mut Vm, globals: ObjectRef, source: &str, mode: ParseMode) -> Va
|
||||
let source = EndorReader::from_text("<classes>", source);
|
||||
let template = compile_source(&source, mode, &CompileOptions { globals: names }).unwrap();
|
||||
let code = template.load(vm).unwrap();
|
||||
let result = vm.execute(code, globals).unwrap();
|
||||
let result = vm.execute(code, globals);
|
||||
vm.release(code).unwrap();
|
||||
result
|
||||
}
|
||||
@@ -221,3 +241,132 @@ fn duplicate_members_and_missing_receivers_fail_before_execution() {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declared_field_checks_cover_construction_inheritance_writes_and_gc() {
|
||||
let mut vm = Vm::new().unwrap();
|
||||
vm.set_source_type_checks(true).unwrap();
|
||||
let globals = vm.new_dict().unwrap();
|
||||
let roots = vm.bootstrap_types().unwrap();
|
||||
vm.dict_set(
|
||||
globals,
|
||||
Value::Text("Object".into()),
|
||||
Value::Object(roots.object),
|
||||
)
|
||||
.unwrap();
|
||||
vm.release(roots.object).unwrap();
|
||||
vm.release(roots.type_type).unwrap();
|
||||
execute(
|
||||
&mut vm,
|
||||
globals,
|
||||
r#"
|
||||
class Base { count: Number }
|
||||
class Child: Base { label: String }
|
||||
value = Child(9, "ok")
|
||||
class Holder { child: Base }
|
||||
holder = Holder(value)
|
||||
class Unknown { value: Missing }
|
||||
"#,
|
||||
ParseMode::Interactive,
|
||||
);
|
||||
let Value::Object(value) = vm
|
||||
.dict_get(globals, &Value::Text("value".into()))
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
else {
|
||||
panic!("instance")
|
||||
};
|
||||
let version = vm.object_store().change_version(value).unwrap();
|
||||
for source in [
|
||||
r#"Child("bad", "ok")"#,
|
||||
"Child(9, 2)",
|
||||
"Holder(1)",
|
||||
"Unknown(1)",
|
||||
r#"value.count = "bad""#,
|
||||
] {
|
||||
assert!(matches!(
|
||||
try_execute(&mut vm, globals, source, ParseMode::Interactive),
|
||||
Err(VmError::TypeMismatch { .. } | VmError::UnknownAnnotation(_))
|
||||
));
|
||||
}
|
||||
assert_eq!(
|
||||
vm.get_attr(value, "count").unwrap(),
|
||||
Value::Number(9.into())
|
||||
);
|
||||
assert_eq!(vm.object_store().change_version(value).unwrap(), version);
|
||||
assert!(vm.del_attr(value, "count").is_err());
|
||||
vm.set_attr(value, "count", Value::Number(10.into()))
|
||||
.unwrap();
|
||||
execute(&mut vm, globals, "class Base {}", ParseMode::Interactive);
|
||||
// Other nominal names resolve dynamically in the declaring environment.
|
||||
assert!(matches!(
|
||||
try_execute(&mut vm, globals, "Holder(value)", ParseMode::Expression),
|
||||
Err(VmError::TypeMismatch { .. })
|
||||
));
|
||||
// An inherited scalar field still belongs to its original declaration.
|
||||
vm.set_attr(value, "count", Value::Number(11.into()))
|
||||
.unwrap();
|
||||
vm.dict_clear(globals).unwrap();
|
||||
vm.release(globals).unwrap();
|
||||
vm.collect_cycles();
|
||||
assert_eq!(vm.object_count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checked_fields_keep_declaring_self_type_and_can_be_opted_out() {
|
||||
let mut vm = Vm::new().unwrap();
|
||||
vm.set_source_type_checks(true).unwrap();
|
||||
let globals = vm.new_dict().unwrap();
|
||||
let roots = vm.bootstrap_types().unwrap();
|
||||
vm.dict_set(
|
||||
globals,
|
||||
Value::Text("Object".into()),
|
||||
Value::Object(roots.object),
|
||||
)
|
||||
.unwrap();
|
||||
vm.release(roots.object).unwrap();
|
||||
vm.release(roots.type_type).unwrap();
|
||||
// Object permits nil, so a separate numeric field provides an initial instance.
|
||||
execute(
|
||||
&mut vm,
|
||||
globals,
|
||||
r#"
|
||||
class Link { next: Link }
|
||||
class Seed: Link {}
|
||||
"#,
|
||||
ParseMode::Interactive,
|
||||
);
|
||||
// A recursive nonnullable field can be initialized by the trusted host in two steps.
|
||||
let Value::Object(link) = vm
|
||||
.dict_get(globals, &Value::Text("Link".into()))
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
else {
|
||||
panic!("class")
|
||||
};
|
||||
let seed = vm.new_object().unwrap();
|
||||
vm.attach_type(seed, link).unwrap();
|
||||
vm.set_attr(seed, "next", Value::Object(seed)).unwrap();
|
||||
vm.dict_set(globals, Value::Text("old".into()), Value::Object(seed))
|
||||
.unwrap();
|
||||
execute(
|
||||
&mut vm,
|
||||
globals,
|
||||
"class Link { value: Number }",
|
||||
ParseMode::Interactive,
|
||||
);
|
||||
vm.set_attr(seed, "next", Value::Object(seed)).unwrap();
|
||||
assert!(matches!(
|
||||
vm.set_attr(seed, "next", Value::Nil),
|
||||
Err(VmError::TypeMismatch { .. })
|
||||
));
|
||||
vm.set_source_type_checks(false).unwrap();
|
||||
vm.set_attr(seed, "next", Value::Nil).unwrap();
|
||||
vm.set_source_type_checks(true).unwrap();
|
||||
vm.set_attr(seed, "next", Value::Object(seed)).unwrap();
|
||||
vm.release(seed).unwrap();
|
||||
vm.dict_clear(globals).unwrap();
|
||||
vm.release(globals).unwrap();
|
||||
vm.collect_cycles();
|
||||
assert_eq!(vm.object_count(), 0);
|
||||
}
|
||||
|
||||
@@ -5,9 +5,9 @@
|
||||
| 文件 | 职责 |
|
||||
| --- | --- |
|
||||
| [lib.rs](lib.rs) | VM 类型导出、objects 类型兼容重导出、宿主调用与字节码 rustdoc 示例 |
|
||||
| [vm.rs](vm.rs) | Vm 拥有 ObjectStore 与错误位置记录;对象操作和宿主 new_class 和显式Trait注册/关系查询显式委托给 objects;源码检查开关与函数类型配置 |
|
||||
| [vm.rs](vm.rs) | Vm 拥有 ObjectStore 与错误位置记录;对象操作和宿主 new_class 和显式Trait注册/关系查询显式委托给 objects;函数/字段检查统一开关与函数类型配置 |
|
||||
| [frame.rs](frame.rs) | EndorFrame、栈条目、返回类型执行根、执行位置元数据、ExecutionLimits |
|
||||
| [eval.rs](eval.rs) | execute/call、只读调用与依赖结果、参数绑定、可选注解检查、帧切换、取指分派、MakeFunction、结果根转移与失败清理 |
|
||||
| [eval.rs](eval.rs) | execute/call、只读调用与依赖结果、参数绑定、可选注解检查、源码类字段环境绑定、帧切换、取指分派、MakeFunction、结果根转移与失败清理 |
|
||||
|
||||
## 常见修改入口
|
||||
|
||||
|
||||
@@ -501,7 +501,8 @@ impl Vm {
|
||||
_ => Err(VmError::ObjectKindMismatch("class method")),
|
||||
})
|
||||
.collect::<Result<std::collections::BTreeMap<_, _>, _>>()?;
|
||||
self.objects.new_class(name, base, fields, methods)
|
||||
self.objects
|
||||
.new_class_with_scope(name, base, fields, methods, Some(frame.function))
|
||||
}
|
||||
|
||||
fn eval_frames(
|
||||
|
||||
@@ -21,6 +21,7 @@ impl Vm {
|
||||
"configure source type checks during read-only call",
|
||||
));
|
||||
}
|
||||
self.objects.set_field_type_checks(enabled)?;
|
||||
self.source_type_checks = enabled;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -6,13 +6,13 @@
|
||||
| --- | --- |
|
||||
| [lib.rs](lib.rs) | 包边界、对象类型/ObjectStore 公开导出(含Trait/MethodRequirement/SourceSignature/AnnotationType)与独立存储 rustdoc 示例 |
|
||||
| [object.rs](object.rs) | Value、CompareOp、ObjectPayload(含显式函数标记)、ObjectHeader、EndorObject、Record、NativeFunction |
|
||||
| [types.rs](types.rs) | 托管名义类型、显式 Object/Type 引导、继承查询、受管方法表/接收者绑定、类字段、显式Trait定义/声明/方法参数约束、原生构造委托、注解解析/匹配 |
|
||||
| [types.rs](types.rs) | 托管名义类型、显式 Object/Type 引导、继承查询、受管方法表/接收者绑定、类字段、显式Trait定义/声明/方法参数约束、原生构造委托、声明环境托管边、字段构造/写入检查与注解解析/匹配 |
|
||||
| [native.rs](native.rs) | NativeContext、上下文原生函数、作用域语言函数工厂、显式能力声明入口、函数标记、根与非递归委托调用 |
|
||||
| [changes.rs](changes.rs) | 合并变更批次、变更键与有界通知额度 |
|
||||
| [number.rs](number.rs) | Integer/Decimal/Rational/BinaryFloat/Complex 的无损表示和装箱载荷 |
|
||||
| [builtins.rs](builtins.rs) | String、Dict、Cell、Function、BaseException 载荷与 trace 边、语言函数标记 |
|
||||
| [heap.rs](heap.rs) | 私有 Heap、不可伪造 ObjectRef、稳定 Box、引用事务、迭代释放、循环回收、后代契约更新的私有借用枚举、同类型附加幂等、只读变更屏障/全调用及嵌套子调用读取跟踪及私有边界测试 |
|
||||
| [store.rs](store.rs) | ObjectStore、空堆创建、对象操作、retain/release 和回收入口、弱 Function 类型配置与分配分类 |
|
||||
| [store.rs](store.rs) | ObjectStore、空堆创建、字段检查配置/属性写入屏障、对象操作、retain/release 和回收入口、弱 Function 类型配置与分配分类 |
|
||||
| [store_builtins.rs](store_builtins.rs) | 载荷校验、代码/函数工厂、Dict/Cell 操作及键语义 |
|
||||
| [instruction.rs](instruction.rs) | Opcode、Instruction、wordcode 编解码、MakeFunction/比较参数与跳转读取接口 |
|
||||
| [code.rs](code.rs) | CodeLayout、EndorCode/EndorCodeObject、可选源码签名、共享不可变代码和操作数/控制流/栈验证 |
|
||||
|
||||
@@ -11,9 +11,21 @@ use crate::{
|
||||
pub struct ObjectStore {
|
||||
pub(crate) heap: Heap,
|
||||
function_type: Option<WeakObjectRef>,
|
||||
pub(crate) field_type_checks: bool,
|
||||
}
|
||||
|
||||
impl ObjectStore {
|
||||
/// Opt-in declared-field checks, shared by VM and NativeContext writes.
|
||||
pub fn set_field_type_checks(&mut self, enabled: bool) -> Result<(), VmError> {
|
||||
if self.is_read_only() {
|
||||
return Err(VmError::UnsupportedOperation(
|
||||
"configure field type checks during read-only call",
|
||||
));
|
||||
}
|
||||
self.field_type_checks = enabled;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Existing objects are immutable; fresh result graphs may be constructed.
|
||||
/// Scopes must end in LIFO order. Read handles are borrowed, never GC roots.
|
||||
pub fn begin_read_only(&mut self) -> usize {
|
||||
@@ -129,6 +141,7 @@ impl ObjectStore {
|
||||
Ok(Self {
|
||||
heap: Heap::new()?,
|
||||
function_type: None,
|
||||
field_type_checks: false,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -280,6 +293,9 @@ impl ObjectStore {
|
||||
if name == "type" && self.type_of(reference)?.is_some() {
|
||||
return Err(VmError::UnsupportedOperation("write object type"));
|
||||
}
|
||||
if self.field_type_checks {
|
||||
self.check_field_write(reference, &name, &value)?;
|
||||
}
|
||||
let storage = *self
|
||||
.attribute_path(reference)?
|
||||
.last()
|
||||
@@ -288,6 +304,9 @@ impl ObjectStore {
|
||||
}
|
||||
|
||||
pub fn del_attr(&mut self, reference: ObjectRef, name: &str) -> Result<(), VmError> {
|
||||
if self.field_type_checks && self.declared_field(reference, name)?.is_some() {
|
||||
return Err(VmError::UnsupportedOperation("delete declared class field"));
|
||||
}
|
||||
if name == "type" && self.type_of(reference)?.is_some() {
|
||||
return Err(VmError::UnsupportedOperation("delete object type"));
|
||||
}
|
||||
|
||||
+142
-13
@@ -21,7 +21,7 @@ pub enum TypeConstructor {
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ClassField {
|
||||
pub name: String,
|
||||
/// Preserved source annotation, like current function annotations.
|
||||
/// Source annotation resolved at checked construction/field writes.
|
||||
pub type_name: String,
|
||||
}
|
||||
|
||||
@@ -35,6 +35,8 @@ pub struct EndorTypeObject {
|
||||
constructor: TypeConstructor,
|
||||
methods: BTreeMap<String, ObjectRef>,
|
||||
fields: Vec<ClassField>,
|
||||
// Declaring execution environment; a managed edge, never an external root.
|
||||
field_scope: Option<ObjectRef>,
|
||||
traits: Vec<ObjectRef>,
|
||||
}
|
||||
|
||||
@@ -69,6 +71,9 @@ impl ObjectPayload for EndorTypeObject {
|
||||
{
|
||||
visit(function);
|
||||
}
|
||||
if let Some(scope) = self.field_scope {
|
||||
visit(scope);
|
||||
}
|
||||
for capability in &self.traits {
|
||||
visit(*capability);
|
||||
}
|
||||
@@ -121,6 +126,8 @@ impl NativeCallable for Construct {
|
||||
});
|
||||
}
|
||||
let fields = definition.fields.clone();
|
||||
cx.store()
|
||||
.check_class_field_arguments(type_object, arguments)?;
|
||||
let instance = cx.new_object()?;
|
||||
cx.attach_type(instance, type_object)?;
|
||||
for (field, value) in fields.iter().zip(arguments) {
|
||||
@@ -149,6 +156,7 @@ impl ObjectStore {
|
||||
constructor: TypeConstructor::Record,
|
||||
methods: BTreeMap::new(),
|
||||
fields: Vec::new(),
|
||||
field_scope: None,
|
||||
traits: Vec::new(),
|
||||
})?;
|
||||
let mut allocated_type = None;
|
||||
@@ -159,6 +167,7 @@ impl ObjectStore {
|
||||
constructor: TypeConstructor::Abstract,
|
||||
methods: BTreeMap::new(),
|
||||
fields: Vec::new(),
|
||||
field_scope: None,
|
||||
traits: Vec::new(),
|
||||
})?;
|
||||
allocated_type = Some(type_type);
|
||||
@@ -200,6 +209,7 @@ impl ObjectStore {
|
||||
constructor,
|
||||
methods: BTreeMap::new(),
|
||||
fields,
|
||||
field_scope: None,
|
||||
traits: Vec::new(),
|
||||
})?;
|
||||
if let Err(error) = self.attach_type(definition, metatype) {
|
||||
@@ -284,6 +294,7 @@ impl ObjectStore {
|
||||
constructor: definition.constructor,
|
||||
methods,
|
||||
fields: definition.fields.clone(),
|
||||
field_scope: definition.field_scope,
|
||||
traits: definition.traits.clone(),
|
||||
};
|
||||
self.heap.replace_payload(type_object, updated)
|
||||
@@ -299,6 +310,23 @@ impl ObjectStore {
|
||||
own_fields: Vec<ClassField>,
|
||||
methods: BTreeMap<String, ObjectRef>,
|
||||
) -> Result<ObjectRef, VmError> {
|
||||
self.new_class_with_scope(name, base, own_fields, methods, None)
|
||||
}
|
||||
|
||||
/// Source class builder with a traced function environment for field names.
|
||||
/// None supports primitive annotations and the declaring class itself.
|
||||
pub fn new_class_with_scope(
|
||||
&mut self,
|
||||
name: impl Into<String>,
|
||||
base: ObjectRef,
|
||||
own_fields: Vec<ClassField>,
|
||||
methods: BTreeMap<String, ObjectRef>,
|
||||
scope: Option<ObjectRef>,
|
||||
) -> Result<ObjectRef, VmError> {
|
||||
if let Some(scope) = scope {
|
||||
self.payload::<crate::EndorFunctionObject>(scope, "function")?;
|
||||
}
|
||||
let field_scope = if own_fields.is_empty() { None } else { scope };
|
||||
let definition = self.payload::<EndorTypeObject>(base, "Type")?;
|
||||
if matches!(definition.constructor, TypeConstructor::Native(_)) {
|
||||
return Err(VmError::UnsupportedOperation(
|
||||
@@ -309,6 +337,7 @@ impl ObjectStore {
|
||||
let mut fields = definition.fields.clone();
|
||||
for field in own_fields {
|
||||
if field.name.is_empty()
|
||||
|| field.type_name.is_empty()
|
||||
|| field.name == "type"
|
||||
|| fields.iter().any(|old| old.name == field.name)
|
||||
|| self.lookup_method(base, &field.name)?.is_some()
|
||||
@@ -340,6 +369,7 @@ impl ObjectStore {
|
||||
constructor,
|
||||
methods,
|
||||
fields,
|
||||
field_scope,
|
||||
traits: Vec::new(),
|
||||
})?;
|
||||
if let Err(error) = self
|
||||
@@ -754,6 +784,116 @@ impl AnnotationType {
|
||||
}
|
||||
}
|
||||
impl ObjectStore {
|
||||
fn primitive_annotation(name: &str) -> Option<AnnotationType> {
|
||||
match name {
|
||||
"Object" => Some(AnnotationType::Any),
|
||||
"Unit" => Some(AnnotationType::Unit),
|
||||
"Number" => Some(AnnotationType::Number),
|
||||
"String" | "Text" => Some(AnnotationType::String),
|
||||
"Bool" => Some(AnnotationType::Bool),
|
||||
"Function" => Some(AnnotationType::Function),
|
||||
"Type" => Some(AnnotationType::Type),
|
||||
"Trait" => Some(AnnotationType::Trait),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn declared_field(
|
||||
&self,
|
||||
object: ObjectRef,
|
||||
name: &str,
|
||||
) -> Result<Option<(ObjectRef, &ClassField)>, VmError> {
|
||||
self.declared_field_in_type(self.type_of(object)?, name)
|
||||
}
|
||||
|
||||
fn declared_field_in_type(
|
||||
&self,
|
||||
mut current: Option<ObjectRef>,
|
||||
name: &str,
|
||||
) -> Result<Option<(ObjectRef, &ClassField)>, VmError> {
|
||||
while let Some(definition) = current {
|
||||
let data = self.payload::<EndorTypeObject>(definition, "Type")?;
|
||||
let inherited = match data.base {
|
||||
Some(base) => self.payload::<EndorTypeObject>(base, "Type")?.fields.len(),
|
||||
None => 0,
|
||||
};
|
||||
if let Some(field) = data.fields[inherited..]
|
||||
.iter()
|
||||
.find(|field| field.name == name)
|
||||
{
|
||||
return Ok(Some((definition, field)));
|
||||
}
|
||||
current = data.base;
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub(crate) fn check_field_write(
|
||||
&self,
|
||||
object: ObjectRef,
|
||||
name: &str,
|
||||
value: &Value,
|
||||
) -> Result<(), VmError> {
|
||||
let Some((owner, field)) = self.declared_field(object, name)? else {
|
||||
return Ok(());
|
||||
};
|
||||
self.check_field_value(owner, field, value)
|
||||
}
|
||||
|
||||
/// NativeTyped allocators can validate their field suffix before any effects.
|
||||
/// Count is always checked; annotation matching follows the opt-in setting.
|
||||
pub fn check_class_field_arguments(
|
||||
&self,
|
||||
definition: ObjectRef,
|
||||
arguments: &[Value],
|
||||
) -> Result<(), VmError> {
|
||||
let data = self.payload::<EndorTypeObject>(definition, "Type")?;
|
||||
if arguments.len() != data.fields.len() {
|
||||
return Err(VmError::ArgumentCount {
|
||||
name: data.name.clone(),
|
||||
required: data.fields.len(),
|
||||
maximum: data.fields.len(),
|
||||
provided: arguments.len(),
|
||||
});
|
||||
}
|
||||
if self.field_type_checks {
|
||||
for (field, value) in data.fields.iter().zip(arguments) {
|
||||
let (owner, field) = self
|
||||
.declared_field_in_type(Some(definition), &field.name)?
|
||||
.expect("class field has a declaring type");
|
||||
self.check_field_value(owner, field, value)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_field_value(
|
||||
&self,
|
||||
owner: ObjectRef,
|
||||
field: &ClassField,
|
||||
value: &Value,
|
||||
) -> Result<(), VmError> {
|
||||
let definition = self.payload::<EndorTypeObject>(owner, "Type")?;
|
||||
let expected = if field.type_name == definition.name {
|
||||
AnnotationType::Nominal(owner)
|
||||
} else if let Some(primitive) = Self::primitive_annotation(&field.type_name) {
|
||||
primitive
|
||||
} else if let Some(scope) = definition.field_scope {
|
||||
self.annotation_type(scope, &field.type_name, None)?
|
||||
} else {
|
||||
return Err(VmError::UnknownAnnotation(field.type_name.clone()));
|
||||
};
|
||||
if !self.matches_annotation(value, expected)? {
|
||||
return Err(VmError::TypeMismatch {
|
||||
function: definition.name.clone(),
|
||||
position: format!("field {}", field.name),
|
||||
expected: field.type_name.clone(),
|
||||
actual: self.value_type_name(value)?,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn annotation_type(
|
||||
&self,
|
||||
function: ObjectRef,
|
||||
@@ -781,18 +921,7 @@ impl ObjectStore {
|
||||
current = payload.base;
|
||||
}
|
||||
}
|
||||
let primitive = match name {
|
||||
"Object" => Some(AnnotationType::Any),
|
||||
"Unit" => Some(AnnotationType::Unit),
|
||||
"Number" => Some(AnnotationType::Number),
|
||||
"String" | "Text" => Some(AnnotationType::String),
|
||||
"Bool" => Some(AnnotationType::Bool),
|
||||
"Function" => Some(AnnotationType::Function),
|
||||
"Type" => Some(AnnotationType::Type),
|
||||
"Trait" => Some(AnnotationType::Trait),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(primitive) = primitive {
|
||||
if let Some(primitive) = Self::primitive_annotation(name) {
|
||||
return Ok(primitive);
|
||||
}
|
||||
let value = self
|
||||
|
||||
Reference in New Issue
Block a user