Validate declared class fields at construction and attribute writes

This commit is contained in:
2026-10-22 11:44:09 +08:00
parent 6346041f77
commit 20e29e3c5a
13 changed files with 342 additions and 26 deletions
+150 -1
View File
@@ -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);
}