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

离线校验截断除法、位运算 RGB/权限掩码、区间与 13 级运算符优先级

PYTHONWindows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。explore-operators.py
explore-operators.py224 行
"""Offline Kotlin 2.x semantic verifier for Chapter 10 (operators)."""
import json
import math
import sys

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


def kt_int_div(a: int, b: int) -> int:
    """Kotlin/JVM integer division truncates toward zero."""
    if b == 0:
        raise ZeroDivisionError("ArithmeticException: / by zero")
    return int(a / b) if (a < 0) ^ (b < 0) else a // b


def kt_int_rem(a: int, b: int) -> int:
    """Kotlin `%` remainder has the sign of the dividend."""
    return a - kt_int_div(a, b) * b


def to_int32(x: int) -> int:
    x &= 0xFFFFFFFF
    return x - 0x100000000 if x & 0x80000000 else x


def kt_shl(a: int, bits: int) -> int:
    return to_int32(a << (bits & 31))


def kt_shr(a: int, bits: int) -> int:
    return to_int32(to_int32(a) >> (bits & 31))


def kt_ushr(a: int, bits: int) -> int:
    return to_int32((a & 0xFFFFFFFF) >> (bits & 31))


def kt_inv(a: int) -> int:
    return to_int32(~a)


def kt_range(start: int, end: int, *, open_end: bool = False, down: bool = False, step: int = 1) -> list[int]:
    if step <= 0:
        raise ValueError("Step must be positive")
    if down:
        return list(range(start, end - 1, -step))
    stop = end if open_end else end + 1
    return list(range(start, stop, step))


def run_cases() -> list[dict]:
    cases: list[dict] = []

    # Case 1: Arithmetic, truncating int division, remainder sign, float / 0, ++/--
    div_zero_exc = False
    try:
        kt_int_div(1, 0)
    except ZeroDivisionError:
        div_zero_exc = True
    i = 1
    post_inc = i
    i += 1
    after_post_inc = i
    i += 1
    pre_inc = i
    post_dec = i
    i -= 1
    after_post_dec = i
    actual_1 = {
        "basic_ops": [7 + 3, 7 - 3, 7 * 3, kt_int_div(7, 3), kt_int_rem(7, 3)],
        "neg_rem": kt_int_rem(-7, 3),
        "int_div_zero_throws": div_zero_exc,
        "float_div_zero_inf": math.isinf(float("inf")),
        "float_zero_div_zero_nan": math.isnan(float("nan")),
        "percent_int_vs_double": [kt_int_div(3, 4), 3.0 / 4, kt_int_div(3 * 100, 4)],
        "inc_dec_trace": [post_inc, after_post_inc, pre_inc, post_dec, after_post_dec],
        "has_power_operator": False,
        "pow_2_10_via_shl": kt_shl(1, 10),
    }
    expected_1 = {
        "basic_ops": [10, 4, 21, 2, 1],
        "neg_rem": -1,
        "int_div_zero_throws": True,
        "float_div_zero_inf": True,
        "float_zero_div_zero_nan": True,
        "percent_int_vs_double": [0, 0.75, 75],
        "inc_dec_trace": [1, 2, 3, 3, 2],
        "has_power_operator": False,
        "pow_2_10_via_shl": 1024,
    }
    cases.append({
        "name": "arithmetic_truncation_and_inc_dec",
        "summary": "Verify arithmetic operators, truncating division, remainder sign, /0 behavior, and ++/-- evaluation order.",
        "expected": expected_1,
        "actual": actual_1,
        "passed": actual_1 == expected_1,
    })

    # Case 2: Compound assignment, comparison, logical short-circuit
    a = 10
    trace_assign = []
    a += 5; trace_assign.append(a)
    a -= 3; trace_assign.append(a)
    a *= 2; trace_assign.append(a)
    a = kt_int_div(a, 5); trace_assign.append(a)
    a = kt_int_rem(a, 3); trace_assign.append(a)
    eval_log: list[str] = []

    def probe() -> bool:
        eval_log.append("hit")
        return True

    sc1 = False and probe()
    sc2 = True or probe()
    sc3 = True and probe()
    name: str | None = None
    null_guard_ok = not (name is not None and len(name) > 0)
    actual_2 = {
        "compound_trace": trace_assign,
        "assignment_is_expression": False,
        "comparisons": [3 == 3, 3 != 4, 3 < 4, 3 > 4, 3 <= 3, 3 >= 4, "abc" < "abd", 3 < 3.5],
        "short_circuit": [sc1, sc2, sc3],
        "probe_calls": len(eval_log),
        "null_guard_safe": null_guard_ok,
    }
    expected_2 = {
        "compound_trace": [15, 12, 24, 4, 1],
        "assignment_is_expression": False,
        "comparisons": [True, True, True, False, True, False, True, True],
        "short_circuit": [False, True, True],
        "probe_calls": 1,
        "null_guard_safe": True,
    }
    cases.append({
        "name": "assignment_comparison_and_logic",
        "summary": "Verify compound assignment, assignment-as-statement rule, comparisons, and short-circuit logic.",
        "expected": expected_2,
        "actual": actual_2,
        "passed": actual_2 == expected_2,
    })

    # Case 3: Bitwise named functions (shl, shr, ushr, and, or, xor, inv) + RGB & permission bitmask
    x, y = 0b1100, 0b1010
    color = 0xFFCC00
    red = kt_shr(color, 16) & 0xFF
    green = kt_shr(color, 8) & 0xFF
    blue = color & 0xFF
    READ, WRITE, EXEC = 0b001, 0b010, 0b100
    perm = READ | WRITE
    actual_3 = {
        "and_or_xor_inv": [x & y, x | y, x ^ y, kt_inv(x)],
        "shifts": [kt_shl(x, 1), kt_shr(x, 1), kt_shr(-8, 1), kt_ushr(-8, 1)],
        "infix_precedence_1_plus_2_shl_3": kt_shl(1 + 2, 3),
        "rgb": [red, green, blue],
        "permission_bits": [perm, (perm & READ) != 0, (perm & EXEC) != 0],
    }
    expected_3 = {
        "and_or_xor_inv": [8, 14, 6, -13],
        "shifts": [24, 6, -4, 2147483644],
        "infix_precedence_1_plus_2_shl_3": 24,
        "rgb": [255, 204, 0],
        "permission_bits": [3, True, False],
    }
    cases.append({
        "name": "bitwise_infix_rgb_and_bitmask",
        "summary": "Verify 32-bit shl/shr/ushr/and/or/xor/inv, infix precedence, RGB channel extraction, and permission bitmasks.",
        "expected": expected_3,
        "actual": actual_3,
        "passed": actual_3 == expected_3,
    })

    # Case 4: Ranges (.., ..<, until, downTo, step), in/!in, and operator precedence
    neg_step_rejected = False
    try:
        kt_range(1, 5, step=0)
    except ValueError:
        neg_step_rejected = True
    site = "www.mbsky.com"
    names = ["Mbsky", "Kotlin"]
    actual_4 = {
        "closed_1_5": kt_range(1, 5),
        "open_1_5": kt_range(1, 5, open_end=True),
        "down_5_1": kt_range(5, 1, down=True),
        "empty_5_1": kt_range(5, 1),
        "step_up": kt_range(1, 10, step=3),
        "step_down": kt_range(10, 1, down=True, step=3),
        "char_range": [chr(c) for c in range(ord("a"), ord("e") + 1)],
        "non_positive_step_rejected": neg_step_rejected,
        "in_checks": [3 in range(1, 6), 9 not in range(1, 6), "a" <= "c" <= "z", "a" <= "C" <= "z", "mbsky" in site, "MBSKY" in site, "Mbsky" in names, "Java" not in names],
        "precedence_and_gt_or": [True or (False and False), (True or False) and False],
        "progression_1_5_step_2": kt_range(1, 5, step=2),
    }
    expected_4 = {
        "closed_1_5": [1, 2, 3, 4, 5],
        "open_1_5": [1, 2, 3, 4],
        "down_5_1": [5, 4, 3, 2, 1],
        "empty_5_1": [],
        "step_up": [1, 4, 7, 10],
        "step_down": [10, 7, 4, 1],
        "char_range": ["a", "b", "c", "d", "e"],
        "non_positive_step_rejected": True,
        "in_checks": [True, True, True, False, True, False, True, True],
        "precedence_and_gt_or": [True, False],
        "progression_1_5_step_2": [1, 3, 5],
    }
    cases.append({
        "name": "ranges_membership_and_precedence",
        "summary": "Verify .., ..<, until, downTo, step, empty 5..1 range, in/!in membership, and operator precedence.",
        "expected": expected_4,
        "actual": actual_4,
        "passed": actual_4 == expected_4,
    })

    return cases


def main() -> None:
    payload = {"version": VERSION, "cases": run_cases()}
    sys.stdout.write(json.dumps(payload, ensure_ascii=False, indent=2) + "\n")


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

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

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

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

下载课程关联工程包:Kotlin

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

下载课程关联工程包:Kotlin

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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