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

离线校验数值位宽溢出、显式转换、Int? 装箱缓存、短路布尔、Char 与数组不协变

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

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


def to_signed(val: int, bits: int) -> int:
    mask = (1 << bits) - 1
    v = val & mask
    return v - (1 << bits) if v >= (1 << (bits - 1)) else v


def to_unsigned(val: int, bits: int) -> int:
    return val & ((1 << bits) - 1)


def to_float32(val: float) -> float:
    return struct.unpack("<f", struct.pack("<f", val))[0]


class BoxedInt:
    """Models JVM boxed Integer (Kotlin Int?) with -128..127 integer cache."""

    _cache: dict[int, "BoxedInt"] = {}

    def __init__(self, value: int) -> None:
        self.value = to_signed(value, 32)

    @classmethod
    def box(cls, value: int) -> "BoxedInt":
        v = to_signed(value, 32)
        if -128 <= v <= 127:
            if v not in cls._cache:
                cls._cache[v] = cls(v)
            return cls._cache[v]
        return cls(v)

    def __eq__(self, other: object) -> bool:
        return isinstance(other, BoxedInt) and self.value == other.value


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

    # Case 1: Signed numeric ranges & 32-bit two's-complement wraparound overflow
    int_max = (1 << 31) - 1
    int_min = -(1 << 31)
    overflow_up = to_signed(int_max + 1, 32)
    overflow_down = to_signed(int_min - 1, 32)
    long_safe = to_signed(int_max + 1, 64)
    actual_1 = {
        "byte_range": [-128, 127],
        "short_range": [-32768, 32767],
        "int_max": int_max,
        "int_min": int_min,
        "int_max_plus_1": overflow_up,
        "int_min_minus_1": overflow_down,
        "long_plus_1": long_safe,
    }
    expected_1 = {
        "byte_range": [-128, 127],
        "short_range": [-32768, 32767],
        "int_max": 2147483647,
        "int_min": -2147483648,
        "int_max_plus_1": -2147483648,
        "int_min_minus_1": 2147483647,
        "long_plus_1": 2147483648,
    }
    cases.append({
        "name": "numeric_bitwidth_and_overflow",
        "summary": "Verify Byte/Short/Int/Long ranges and 32-bit Int wraparound overflow vs 64-bit Long widening.",
        "expected": expected_1,
        "actual": actual_1,
        "passed": actual_1 == expected_1,
    })

    # Case 2: Literals (dec, hex, bin, underscores, float/double, no octal)
    actual_2 = {
        "dec": 123,
        "hex": 0x0F,
        "bin": 0b00001011,
        "underscores": 1_000_000,
        "hex_bytes": 0xFF_EC_DE,
        "bin_bytes": 0b1101_0010,
        "double_sci": 123.5e10,
        "float32_3_14_approx": round(to_float32(3.14), 6),
        "octal_supported": False,
    }
    expected_2 = {
        "dec": 123,
        "hex": 15,
        "bin": 11,
        "underscores": 1000000,
        "hex_bytes": 16772318,
        "bin_bytes": 210,
        "double_sci": 1.235e12,
        "float32_3_14_approx": 3.14,
        "octal_supported": False,
    }
    cases.append({
        "name": "numeric_literals_and_underscores",
        "summary": "Verify decimal, hex, binary, underscore grouping, scientific notation, and absence of octal literals.",
        "expected": expected_2,
        "actual": actual_2,
        "passed": actual_2 == expected_2,
    })

    # Case 3: No implicit widening + explicit toX() conversions + unsigned types
    i_val = 65
    d_val = 3.99
    big_int = 300
    u_val = to_unsigned(42, 32)
    actual_3 = {
        "implicit_byte_to_int_allowed": False,
        "literal_100_to_byte_allowed": True,
        "int65_to_char": chr(i_val),
        "double_3_99_trunc_to_int": int(math.trunc(d_val)),
        "double_3_99_round": round(d_val),
        "int300_to_byte_trunc": to_signed(big_int, 8),
        "uint_max": (1 << 32) - 1,
        "ulong_max": (1 << 64) - 1,
        "ubyte_0xff": to_unsigned(0xFF, 8),
        "uint_add": to_unsigned(u_val + 1, 32),
    }
    expected_3 = {
        "implicit_byte_to_int_allowed": False,
        "literal_100_to_byte_allowed": True,
        "int65_to_char": "A",
        "double_3_99_trunc_to_int": 3,
        "double_3_99_round": 4,
        "int300_to_byte_trunc": 44,
        "uint_max": 4294967295,
        "ulong_max": 18446744073709551615,
        "ubyte_0xff": 255,
        "uint_add": 43,
    }
    cases.append({
        "name": "explicit_conversions_and_unsigned_types",
        "summary": "Verify explicit toByte/toInt/toChar truncation semantics and UByte/UShort/UInt/ULong bounds.",
        "expected": expected_3,
        "actual": actual_3,
        "passed": actual_3 == expected_3,
    })

    # Case 4: == vs === (primitive Int vs boxed Int? cache -128..127) & cross-type compareTo
    p = BoxedInt.box(1000)
    q = BoxedInt.box(1000)
    m = BoxedInt.box(100)
    n = BoxedInt.box(100)
    i5, d5 = 5, 5.0
    cmp_i_d = -1 if i5 < d5 else (1 if i5 > d5 else 0)
    actual_4 = {
        "primitive_int_1000_eq": 1000 == 1000,
        "primitive_int_1000_ref_eq_degenerates_to_val_eq": True,
        "boxed_1000_struct_eq": p == q,
        "boxed_1000_ref_eq": p is q,
        "boxed_100_ref_eq_cached": m is n,
        "cross_type_eq_int_double_allowed": False,
        "cross_type_compareTo": cmp_i_d,
        "int5_gt_4_9": i5 > 4.9,
    }
    expected_4 = {
        "primitive_int_1000_eq": True,
        "primitive_int_1000_ref_eq_degenerates_to_val_eq": True,
        "boxed_1000_struct_eq": True,
        "boxed_1000_ref_eq": False,
        "boxed_100_ref_eq_cached": True,
        "cross_type_eq_int_double_allowed": False,
        "cross_type_compareTo": 0,
        "int5_gt_4_9": True,
    }
    cases.append({
        "name": "equality_boxing_cache_and_compareTo",
        "summary": "Verify primitive == vs ===, boxed Int? JVM cache (-128..127), and cross-type Int.compareTo(Double).",
        "expected": expected_4,
        "actual": actual_4,
        "passed": actual_4 == expected_4,
    })

    # Case 5: Boolean short-circuiting & Char (.code, arithmetic, digitToInt, escapes)
    calls: list[str] = []

    def check() -> bool:
        calls.append("called")
        return True

    r1 = False and check()
    r2 = True or check()
    r3 = True and check()
    ch = "A"
    digit_5 = int("5")
    actual_5 = {
        "short_circuit_results": [r1, r2, r3],
        "check_call_count": len(calls),
        "xor_true_false": True ^ False,
        "char_code": ord(ch),
        "char_plus_1": chr(ord(ch) + 1),
        "char_diff": ord(ch) - ord("A"),
        "digit_to_int": digit_5,
        "unicode_escape_0041": "\u0041",
    }
    expected_5 = {
        "short_circuit_results": [False, True, True],
        "check_call_count": 1,
        "xor_true_false": True,
        "char_code": 65,
        "char_plus_1": "B",
        "char_diff": 0,
        "digit_to_int": 5,
        "unicode_escape_0041": "A",
    }
    cases.append({
        "name": "boolean_short_circuit_and_char_semantics",
        "summary": "Verify Boolean short-circuit evaluation, Char.code, Char arithmetic, digitToInt, and Unicode escapes.",
        "expected": expected_5,
        "actual": actual_5,
        "passed": actual_5 == expected_5,
    })

    # Case 6: Array<T>, IntArray, arrayOfNulls, 2D array & array invariance
    a = [1, 2, 3]
    b = [i * 2 for i in range(3)]
    a[0] = 100
    ints = [1, 2, 3]
    ints[0] = ints[1] + ints[2]
    squares = [i * i for i in range(5)]
    nulls = [None, None]
    grid = [[0, 0, 0] for _ in range(2)]
    grid[1][2] = 9
    actual_6 = {
        "a_after_set": a,
        "factory_b": b,
        "int_array_after_set": ints,
        "squares": squares,
        "nulls": nulls,
        "grid_row1": grid[1],
        "array_covariant_in_kotlin": False,
    }
    expected_6 = {
        "a_after_set": [100, 2, 3],
        "factory_b": [0, 2, 4],
        "int_array_after_set": [5, 2, 3],
        "squares": [0, 1, 4, 9, 16],
        "nulls": [None, None],
        "grid_row1": [0, 0, 9],
        "array_covariant_in_kotlin": False,
    }
    cases.append({
        "name": "arrays_primitive_arrays_and_invariance",
        "summary": "Verify arrayOf, Array(size){}, IntArray, arrayOfNulls, 2D grids, and Kotlin Array<T> invariance.",
        "expected": expected_6,
        "actual": actual_6,
        "passed": actual_6 == expected_6,
    })

    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-basic-types-lab/explore-basic-types.py

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

下载课程关联工程包:Kotlin

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

下载课程关联工程包:Kotlin

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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