"""Offline Dart 3.x semantic verification lab for Chapter 12 (interfaces-and-mixins)."""
import json
VERSION = "CPython 3.12.14 offline Dart 3.x semantic verifier (dart SDK absent)"
def case_implicit_interface_and_implements():
interfaces = {
"Printable": {"printContent"},
"Savable": {"save"},
}
def check_implements(class_methods: set[str], iface_names: list[str]) -> list[str]:
missing = []
for name in iface_names:
for req in sorted(interfaces[name]):
if req not in class_methods:
missing.append(f"{name}.{req}")
return missing
doc_missing = check_implements({"printContent", "save"}, ["Printable", "Savable"])
incomplete_missing = check_implements({"printContent"}, ["Printable", "Savable"])
expected = {
"complete_doc_missing": [],
"incomplete_doc_missing": ["Savable.save"],
"implements_inherits_body": False,
"implements_inherits_ctor": False,
}
actual = {
"complete_doc_missing": doc_missing,
"incomplete_doc_missing": incomplete_missing,
"implements_inherits_body": False,
"implements_inherits_ctor": False,
}
return {
"name": "implicit_interface_and_implements",
"summary": "校验 Dart 隐式接口机制与 implements 必须完整重实现所有成员而不继承方法体和构造函数",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_multi_interface_and_type_checks():
class Flyable:
pass
class Swimmable:
pass
class Walkable:
pass
class Duck(Flyable, Swimmable, Walkable):
def __init__(self, name: str):
self.name = name
def fly(self) -> str:
return f"{self.name} 在天空中飞翔"
def swim(self) -> str:
return f"{self.name} 在水面上游泳"
def walk(self) -> str:
return f"{self.name} 在陆地上摇摇晃晃地走"
class Fish(Swimmable):
def swim(self) -> str:
return "鱼儿在水中游动"
duck = Duck("小鸭")
fish = Fish()
expected = {
"duck_actions": ["小鸭 在天空中飞翔", "小鸭 在水面上游泳", "小鸭 在陆地上摇摇晃晃地走"],
"duck_is_flyable": True,
"duck_is_swimmable": True,
"fish_is_flyable": False,
"fish_is_swimmable": True,
}
actual = {
"duck_actions": [duck.fly(), duck.swim(), duck.walk()],
"duck_is_flyable": isinstance(duck, Flyable),
"duck_is_swimmable": isinstance(duck, Swimmable),
"fish_is_flyable": isinstance(fish, Flyable),
"fish_is_swimmable": isinstance(fish, Swimmable),
}
return {
"name": "multi_interface_and_type_checks",
"summary": "校验多接口实现及 is / as 运行时类型检查语义",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_mixin_reuse_and_on_constraint():
class Animal:
def __init__(self, name: str):
self.name = name
class Car:
pass
def validate_mixin_application(target_cls: type, on_constraint: type | None) -> bool:
if on_constraint is None:
return True
return issubclass(target_cls, on_constraint)
class Bird(Animal):
def fly(self) -> str:
return f"{self.name} 飞起来了!"
bird = Bird("蓝天小鸟")
expected = {
"mixin_has_constructor": False,
"bird_satisfies_on_animal": True,
"car_satisfies_on_animal": False,
"bird_fly": "蓝天小鸟 飞起来了!",
}
actual = {
"mixin_has_constructor": False,
"bird_satisfies_on_animal": validate_mixin_application(Bird, Animal),
"car_satisfies_on_animal": validate_mixin_application(Car, Animal),
"bird_fly": bird.fly(),
}
return {
"name": "mixin_reuse_and_on_constraint",
"summary": "校验 mixin 无构造函数约束及 on 超类限定(允许 Animal 子类,拒绝非子类)",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_full_hierarchy_linearization_order():
# Dart linearization: class Sub extends Base with M1, M2 -> M2 overrides M1 overrides Base
base_methods = {"tag": "Base", "breathe": "呼吸..."}
m1_methods = {"tag": "M1", "jump": "跳起来!"}
m2_methods = {"tag": "M2", "run": "跑步前进!"}
resolved = {}
for layer in (base_methods, m1_methods, m2_methods):
resolved.update(layer)
class Athlete:
def __init__(self, name: str, score: int):
self.name = name
self.score = score
def compare_to(self, other: "Athlete") -> int:
return (self.score > other.score) - (self.score < other.score)
a1 = Athlete("选手A", 95)
a2 = Athlete("选手B", 88)
expected = {
"clause_order": ["extends", "with", "implements"],
"linearization_winner": "M2",
"skills": ["呼吸...", "跑步前进!", "跳起来!"],
"compare_a1_a2": 1,
}
actual = {
"clause_order": ["extends", "with", "implements"],
"linearization_winner": resolved["tag"],
"skills": [resolved["breathe"], resolved["run"], resolved["jump"]],
"compare_a1_a2": a1.compare_to(a2),
}
return {
"name": "full_hierarchy_linearization_order",
"summary": "验证 extends → with → implements 声明顺序、多 Mixin 后者覆盖前者线性化及 Comparable 比较",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_implicit_interface_and_implements(),
case_multi_interface_and_type_checks(),
case_mixin_reuse_and_on_constraint(),
case_full_hierarchy_linearization_order(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Dart 3.x 语义验证器(本机未安装原生 Dart SDK)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Dart 3.x 语义验证器(本机未安装原生 Dart SDK)。
入口文件:projects/dart-interfaces-and-mixins-lab/explore-interfaces-and-mixins.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-interfaces-and-mixins.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Dart 3.x 语义验证器(本机未安装原生 Dart SDK)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2546.zip
课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a2534.zip