蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行离线 Python 校验:Kotlin 泛型约束、out/in 型变与位置检查、星号投射及 reified

PYTHONWindows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。explore-generics.py
explore-generics.py222 行
"""Offline Kotlin 2.x semantic verifier for Chapter 24: Generics."""
import json

VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"


def case_generic_class_fn_and_inference():
    class Box:
        def __init__(self, value):
            self.value = value

    def box_in(value):
        return Box(value)

    def do_println(content) -> str:
        # Note: in Python bool is a subclass of int, so check bool first!
        if isinstance(content, bool):
            return "T 不是整型,也不是字符串"
        if isinstance(content, int):
            return f"整型数字为 {content}"
        if isinstance(content, str):
            return f"字符串转换为大写:{content.upper()}"
        return "T 不是整型,也不是字符串"

    actual = {
        "box_int": Box(10).value,
        "box_str": box_in("kotlin").value,
        "do_println": [do_println(23), do_println("kotlin"), do_println(True)],
        "inferred_list": ["kotlin", "jvm"],
        "explicit_any_list": ["kotlin", 42],
        "empty_target_inferred": None,
        "erased_runtime_same_class": type([1, 2]) is type(["a", "b"]),
    }
    expected = {
        "box_int": 10,
        "box_str": "kotlin",
        "do_println": ["整型数字为 23", "字符串转换为大写:KOTLIN", "T 不是整型,也不是字符串"],
        "inferred_list": ["kotlin", "jvm"],
        "explicit_any_list": ["kotlin", 42],
        "empty_target_inferred": None,
        "erased_runtime_same_class": True,
    }
    return {
        "name": "generic_class_fn_and_inference",
        "summary": "Verify generic Box<T>, boxIn<T>, type branching, target inference, and erasure",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_bounds_default_any_nullable_and_where():
    def sort_comparable(items: list):
        for item in items:
            if isinstance(item, dict):
                raise TypeError("HashMap is not Comparable")
        return sorted(items)

    def echo_any_nullable(value) -> str:
        return f"收到:{'null' if value is None else value}"

    def echo_non_null(value) -> str:
        if value is None:
            raise TypeError("COMPILE_ERROR: Type argument String? violates upper bound Any")
        return f"收到:{value}"

    def copy_when_greater(items: list[str], threshold: str) -> list[str]:
        return [str(x) for x in items if x > threshold]

    hashmap_rejected = False
    try:
        sort_comparable([{"a": 1}])
    except TypeError:
        hashmap_rejected = True

    null_rejected_for_any = False
    try:
        echo_non_null(None)
    except TypeError:
        null_rejected_for_any = True

    actual = {
        "sorted_ints": sort_comparable([3, 1, 2]),
        "sorted_strs": sort_comparable(["zeta", "kotlin", "alpha"]),
        "hashmap_rejected": hashmap_rejected,
        "echo_default_bound": [echo_any_nullable("kotlin"), echo_any_nullable(42), echo_any_nullable(None)],
        "null_rejected_for_any_bound": null_rejected_for_any,
        "where_greater": copy_when_greater(["alpha", "kotlin", "zeta"], "kotlin"),
    }
    expected = {
        "sorted_ints": [1, 2, 3],
        "sorted_strs": ["alpha", "kotlin", "zeta"],
        "hashmap_rejected": True,
        "echo_default_bound": ["收到:kotlin", "收到:42", "收到:null"],
        "null_rejected_for_any_bound": True,
        "where_greater": ["zeta"],
    }
    return {
        "name": "bounds_default_any_nullable_and_where",
        "summary": "Verify Comparable upper bound, default Any? vs non-null Any, and multi-bound where clause",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_declaration_and_use_site_variance():
    # Subtype relation: String <: Any
    subtypes = {("String", "String"), ("Any", "Any"), ("String", "Any")}

    def assignable(variance: str, src_arg: str, dst_arg: str) -> bool:
        if variance == "invariant":
            return src_arg == dst_arg
        if variance == "out":
            return (src_arg, dst_arg) in subtypes
        if variance == "in":
            return (dst_arg, src_arg) in subtypes
        raise ValueError(variance)

    def position_valid(variance: str, position: str) -> bool:
        if variance == "out":
            return position == "out"
        if variance == "in":
            return position == "in"
        return True

    # Use-site projection: copy(from: Array<out Any>, to: Array<Any>)
    src = ["kotlin", "generics"]
    dst = ["", ""]
    for i in range(len(src)):
        dst[i] = src[i]

    actual = {
        "producer_out_str_to_any": assignable("out", "String", "Any"),
        "producer_out_in_param_valid": position_valid("out", "in"),
        "consumer_in_any_to_str": assignable("in", "Any", "String"),
        "consumer_in_return_valid": position_valid("in", "out"),
        "array_invariant_str_to_any": assignable("invariant", "String", "Any"),
        "array_out_projection_copy": ", ".join(dst),
    }
    expected = {
        "producer_out_str_to_any": True,
        "producer_out_in_param_valid": False,
        "consumer_in_any_to_str": True,
        "consumer_in_return_valid": False,
        "array_invariant_str_to_any": False,
        "array_out_projection_copy": "kotlin, generics",
    }
    return {
        "name": "declaration_and_use_site_variance",
        "summary": "Verify out covariance, in contravariance, position checks, and Array<out Any> projection",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_star_projection_and_reified():
    star_rules = {
        "Foo<out T : TUpper>": {"equiv": "Foo<out TUpper>", "can_read": "TUpper", "can_write": False},
        "Foo<in T>": {"equiv": "Foo<in Nothing>", "can_read": None, "can_write": False},
        "Foo<T : TUpper>": {"equiv": "read:Foo<out TUpper>, write:Foo<in Nothing>", "can_read": "TUpper", "can_write": False},
    }
    fn1_projections = {
        "Function1<*, String>": "Function1<in Nothing, String>",
        "Function1<Int, *>": "Function1<Int, out Any?>",
        "Function1<*, *>": "Function1<in Nothing, out Any?>",
    }

    type_map = {"String": str, "Int": int}

    def reified_type_name(t_name: str) -> str:
        return t_name

    def reified_is_type(value, t_name: str) -> bool:
        if t_name == "Int" and isinstance(value, bool):
            return False
        return isinstance(value, type_map[t_name])

    mixed = ["kotlin", 42, "reified", 3.14]
    filtered_strings = [x for x in mixed if reified_is_type(x, "String")]

    actual = {
        "mutable_list_star_add_allowed": star_rules["Foo<T : TUpper>"]["can_write"],
        "fn1_projections": fn1_projections,
        "reified_names": [reified_type_name("String"), reified_type_name("Int")],
        "reified_checks": [reified_is_type("KOTLIN", "String"), reified_is_type("KOTLIN", "Int")],
        "filter_is_instance_string": filtered_strings,
    }
    expected = {
        "mutable_list_star_add_allowed": False,
        "fn1_projections": {
            "Function1<*, String>": "Function1<in Nothing, String>",
            "Function1<Int, *>": "Function1<Int, out Any?>",
            "Function1<*, *>": "Function1<in Nothing, out Any?>",
        },
        "reified_names": ["String", "Int"],
        "reified_checks": [True, False],
        "filter_is_instance_string": ["kotlin", "reified"],
    }
    return {
        "name": "star_projection_and_reified",
        "summary": "Verify star-projection read/write safety, Function1 projections, and inline reified type checks",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_generic_class_fn_and_inference(),
        case_bounds_default_any_nullable_and_where(),
        case_declaration_and_use_site_variance(),
        case_star_projection_and_reified(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。

入口文件:projects/kotlin-generics-lab/explore-generics.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-generics.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Kotlin

课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a2132.zip

下载课程关联工程包:Kotlin

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2149.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习