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

运行离线 Python 校验:Kotlin 命名与格式检查器、惯用法转换验证与反模式检测

PYTHONWindows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。explore-style.py
explore-style.py161 行
"""Offline Kotlin 2.x semantic verifier for Chapter 42: Coding Conventions & Idioms."""
from dataclasses import dataclass, replace
import json
import re

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


def case_naming_and_formatting_linter():
    def check_package(pkg: str) -> bool:
        return bool(re.fullmatch(r"[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)*", pkg))

    def check_class_name(name: str) -> bool:
        return bool(re.fullmatch(r"[A-Z][A-Za-z0-9]*", name))

    def check_const_name(name: str) -> bool:
        return bool(re.fullmatch(r"[A-Z][A-Z0-9_]*", name))

    def check_type_colon(decl: str) -> bool:
        return bool(re.search(r"[A-Za-z0-9_]+: [A-Z]", decl))

    def check_inherit_colon(decl: str) -> bool:
        return bool(re.search(r"[A-Za-z0-9_]+ : [A-Z]", decl))

    sample_lines = [
        "package com.example.demo",
        "data class Site(val name: String, val url: String)",
        "class Dog : Animal()",
        "    val port: Int = 443",
    ]
    no_tabs = all("\t" not in ln for ln in sample_lines)
    within_120 = all(len(ln) <= 120 for ln in sample_lines)
    backtick_cross_platform = False  # JVM only

    actual = {
        "valid_pkg": check_package("com.example.demo"),
        "underscore_pkg_rejected": check_package("com.example_demo"),
        "valid_class": check_class_name("SiteInfo"),
        "valid_const": check_const_name("MAX_SITE_COUNT"),
        "type_colon_ok": check_type_colon("val name: String"),
        "inherit_colon_ok": check_inherit_colon("class Dog : Animal()"),
        "no_tabs_and_width_120": no_tabs and within_120,
        "backtick_valid_on_js_native": backtick_cross_platform,
    }
    expected = {
        "valid_pkg": True,
        "underscore_pkg_rejected": False,
        "valid_class": True,
        "valid_const": True,
        "type_colon_ok": True,
        "inherit_colon_ok": True,
        "no_tabs_and_width_120": True,
        "backtick_valid_on_js_native": False,
    }
    return {
        "name": "naming_and_formatting_linter",
        "summary": "Verify Kotlin official naming rules (no-underscore packages, camel/const) and formatting rules",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_idiomatic_kotlin_patterns():
    @dataclass(frozen=True)
    class Site:
        name: str
        url: str

        @property
        def is_secure(self) -> bool:
            return self.url.startswith("https://")

    site = Site("BlueSky", "https://mbsky.cn")
    mobile = replace(site, url="https://m.mbsky.cn")

    # Extension function String.toDomain()
    def to_domain(url: str) -> str:
        after_scheme = url.split("://", 1)[1] if "://" in url else url
        return after_scheme.split("/", 1)[0]

    # apply + also flow
    configured = {"name": "", "url": ""}
    configured["name"] = "BlueSky"
    configured["url"] = "mbsky.cn"
    side_effect_log = f"配置完成:{configured['name']}"
    upper_url = configured["url"].upper()

    # Exhaustive when on sealed Result
    def describe(res: tuple[str, str]) -> str:
        kind, payload = res
        return f"成功:{payload}" if kind == "Success" else f"失败:{payload}"

    # Null safety ?. + ?: + ?.let
    maybe_name: str | None = None
    fallback_len = len(maybe_name) if maybe_name is not None else 0
    fallback_upper = maybe_name.upper() if maybe_name is not None else "未知"

    actual = {
        "is_secure": site.is_secure,
        "copy_url": mobile.url,
        "structural_eq": site == Site("BlueSky", "https://mbsky.cn"),
        "to_domain": to_domain("https://mbsky.cn/kotlin"),
        "also_log_and_upper": [side_effect_log, upper_url],
        "when_describe": [describe(("Success", "KOTLIN")), describe(("Failure", "网络超时"))],
        "null_safe_fallbacks": [fallback_len, fallback_upper],
    }
    expected = {
        "is_secure": True,
        "copy_url": "https://m.mbsky.cn",
        "structural_eq": True,
        "to_domain": "mbsky.cn",
        "also_log_and_upper": ["配置完成:BlueSky", "MBSKY.CN"],
        "when_describe": ["成功:KOTLIN", "失败:网络超时"],
        "null_safe_fallbacks": [0, "未知"],
    }
    return {
        "name": "idiomatic_kotlin_patterns",
        "summary": "Verify data class copy/equals, toDomain extension, apply/also, sealed when, and null-safe Elvis",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_antipattern_rewriter_checks():
    rewrites = {
        "unmodified_var": "val count = 0",
        "explicit_null_if": "x?.foo()",
        "bang_bang_assert": "x?.foo() ?: return",
        "manual_equals_hash_str": "data class",
        "utils_singleton_methods": "extension or top-level fun",
        "manual_index_loop": "for (item in list)",
        "deep_if_else_chain": "when expression",
        "null_for_error": "sealed class or Result",
        "string_builder_concat": 'string template "$name"',
        "java_getter_method": "property syntax",
    }
    actual = {"rule_count": len(rewrites), "has_all_core_idioms": "when expression" in rewrites.values()}
    expected = {"rule_count": 10, "has_all_core_idioms": True}
    return {
        "name": "antipattern_rewriter_checks",
        "summary": "Verify the 10-item Kotlin antipattern-to-idiom replacement checklist",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_naming_and_formatting_linter(),
        case_idiomatic_kotlin_patterns(),
        case_antipattern_rewriter_checks(),
    ]
    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-style-lab/explore-style.py

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

下载课程关联工程包:Kotlin

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

下载课程关联工程包:Kotlin

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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