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

运行离线 Python 校验:Kotlin 运算符重载翻译、+= 歧义拦截、invoke 与向量/金额模型

PYTHONWindows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。explore-operator.py
explore-operator.py268 行
"""Offline Kotlin 2.x semantic verifier for Chapter 29: Operator Overloading."""
from dataclasses import dataclass
import json

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


@dataclass(frozen=True)
class Point:
    x: int
    y: int

    def __add__(self, other: "Point") -> "Point":
        return Point(self.x + other.x, self.y + other.y)

    def __str__(self) -> str:
        return f"({self.x}, {self.y})"


@dataclass(frozen=True)
class Counter:
    value: int

    def __neg__(self) -> "Counter":
        return Counter(-self.value)

    def inc(self) -> "Counter":
        return Counter(self.value + 1)

    def dec(self) -> "Counter":
        return Counter(self.value - 1)


def case_arithmetic_unary_and_inc_dec():
    a, b = Point(1, 2), Point(3, 4)
    c = Counter(10)
    neg_c = -c

    # Emulate Kotlin postfix n++ (returns old, binds n = n.inc()) and prefix ++n (binds then returns new)
    n = Counter(0)
    postfix_ret = n
    n = n.inc()
    after_inc = n
    n = n.dec()
    after_dec = n
    n = n.inc()
    prefix_ret = n

    non_overloadable = ["&&", "||", "===", "!==", "is", "!is", "?:", "="]
    actual = {
        "point_plus": str(a + b),
        "counter_neg": neg_c.value,
        "postfix_returned_old": postfix_ret.value,
        "after_inc": after_inc.value,
        "after_dec": after_dec.value,
        "prefix_returned_new": prefix_ret.value,
        "non_overloadable_count": len(non_overloadable),
    }
    expected = {
        "point_plus": "(4, 6)",
        "counter_neg": -10,
        "postfix_returned_old": 0,
        "after_inc": 1,
        "after_dec": 0,
        "prefix_returned_new": 1,
        "non_overloadable_count": 8,
    }
    return {
        "name": "arithmetic_unary_and_inc_dec",
        "summary": "Verify plus, unaryMinus, inc/dec expression values, and non-overloadable operator list",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_compound_assignment_and_ambiguity():
    def resolve_plus_assign(has_plus: bool, has_plus_assign: bool, target_is_var: bool) -> str:
        if has_plus and has_plus_assign:
            return "COMPILE_ERROR: Assignment operators ambiguity (both plus and plusAssign)"
        if has_plus_assign:
            return "CALL: a.plusAssign(b)"
        if has_plus:
            return "CALL: a = a.plus(b)" if target_is_var else "COMPILE_ERROR: Val cannot be reassigned"
        return "COMPILE_ERROR: No operator"

    basket = []
    for item in ("苹果", "香蕉", "书签"):
        basket.append(item)

    actual = {
        "plus_only_var": resolve_plus_assign(True, False, True),
        "plus_only_val": resolve_plus_assign(True, False, False),
        "plusAssign_only_val": resolve_plus_assign(False, True, False),
        "both_defined": resolve_plus_assign(True, True, True),
        "basket": basket,
    }
    expected = {
        "plus_only_var": "CALL: a = a.plus(b)",
        "plus_only_val": "COMPILE_ERROR: Val cannot be reassigned",
        "plusAssign_only_val": "CALL: a.plusAssign(b)",
        "both_defined": "COMPILE_ERROR: Assignment operators ambiguity (both plus and plusAssign)",
        "basket": ["苹果", "香蕉", "书签"],
    }
    return {
        "name": "compound_assignment_and_ambiguity",
        "summary": "Verify += resolution for plus vs plusAssign, val/var constraint, and ambiguity rejection",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_comparison_indexing_contains_invoke():
    @dataclass(frozen=True, order=True)
    class Version:
        major: int
        minor: int

    cur = Version(2, 2)
    old = Version(1, 9)

    class Playlist:
        def __init__(self):
            self._songs: list[str] = []

        def __iadd__(self, song: str):
            self._songs.append(song)
            return self

        def __getitem__(self, idx: int) -> str:
            return self._songs[idx]

        def __setitem__(self, idx: int, val: str) -> None:
            self._songs[idx] = val

        def __contains__(self, keyword: str) -> bool:
            return any(keyword in s for s in self._songs)

    pl = Playlist()
    pl += "Kotlin 基础"
    pl += "Kotlin 入门"
    pl += "Kotlin 实战"
    first_song = pl[0]
    pl[1] = "Kotlin 值类"

    class Formatter:
        def __init__(self, prefix: str):
            self.prefix = prefix

        def __call__(self, *texts: str) -> str:
            return ", ".join(f"{self.prefix}{t}" for t in texts)

    fmt = Formatter("[APP] ")

    actual = {
        "version_cmp": [cur > old, cur < old, cur >= Version(2, 2), cur == Version(2, 2), cur != old],
        "playlist_first": first_song,
        "playlist_updated": pl[1],
        "contains_checks": ["值类" in pl, "Java" in pl],
        "invoke_single": fmt("第一条"),
        "invoke_vararg": fmt("第一条", "第二条", "第三条"),
        "range_until_1_9": list(range(0, 3)),
    }
    expected = {
        "version_cmp": [True, False, True, True, True],
        "playlist_first": "Kotlin 基础",
        "playlist_updated": "Kotlin 值类",
        "contains_checks": [True, False],
        "invoke_single": "[APP] 第一条",
        "invoke_vararg": "[APP] 第一条, [APP] 第二条, [APP] 第三条",
        "range_until_1_9": [0, 1, 2],
    }
    return {
        "name": "comparison_indexing_contains_invoke",
        "summary": "Verify Comparable, get/set/contains (in), overloaded invoke, and ..< rangeUntil",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_vector_and_money_practical():
    @dataclass(frozen=True)
    class Vector:
        x: float
        y: float

        def __add__(self, o: "Vector") -> "Vector":
            return Vector(self.x + o.x, self.y + o.y)

        def __sub__(self, o: "Vector") -> "Vector":
            return Vector(self.x - o.x, self.y - o.y)

        def __mul__(self, s: float) -> "Vector":
            return Vector(self.x * s, self.y * s)

        def __neg__(self) -> "Vector":
            return Vector(-self.x, -self.y)

        def __getitem__(self, idx: int) -> float:
            if idx == 0:
                return self.x
            if idx == 1:
                return self.y
            raise IndexError(idx)

        def __str__(self) -> str:
            return f"({self.x}, {self.y})"

    @dataclass(frozen=True, order=True)
    class Money:
        cents: int

        def __add__(self, o: "Money") -> "Money":
            return Money(self.cents + o.cents)

        def __sub__(self, o: "Money") -> "Money":
            return Money(self.cents - o.cents)

        def __mul__(self, qty: int) -> "Money":
            return Money(self.cents * qty)

        def __str__(self) -> str:
            sign = "-" if self.cents < 0 else ""
            a = abs(self.cents)
            return f"{sign}{a // 100}.{a % 100:02d}"

    va, vb = Vector(1.0, 2.0), Vector(3.0, 4.0)
    price = Money(1999)
    total = price * 3 + Money(500)

    actual = {
        "vector_ops": [str(va + vb), str(va - vb), str(va * 2.0), str(-va), va[0], va[1]],
        "money_price": str(price),
        "money_total": str(total),
        "money_gt": total > price,
        "money_diff": str(total - price),
    }
    expected = {
        "vector_ops": ["(4.0, 6.0)", "(-2.0, -2.0)", "(2.0, 4.0)", "(-1.0, -2.0)", 1.0, 2.0],
        "money_price": "19.99",
        "money_total": "64.97",
        "money_gt": True,
        "money_diff": "44.98",
    }
    return {
        "name": "vector_and_money_practical",
        "summary": "Verify 2D Vector arithmetic/indexing and exact integer-cent Money value class operators",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_arithmetic_unary_and_inc_dec(),
        case_compound_assignment_and_ambiguity(),
        case_comparison_indexing_contains_invoke(),
        case_vector_and_money_practical(),
    ]
    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-operator-lab/explore-operator.py

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

下载课程关联工程包:Kotlin

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

下载课程关联工程包:Kotlin

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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