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

离线校验词法与折叠区识别、多光标列编辑、提取/内联重构等价性与实时模板展开

PYTHONWindows x64、CPython 3.12.14 离线 PyCharm 工程语义与配置验证器(未启动桌面端 PyCharm IDE)。explore-code-editor.py
explore-code-editor.py197 行
"""Offline Python verification lab for PyCharm Chapter 09 (code-editor)."""
import ast
import io
import json
import keyword
import tokenize

VERSION = "CPython 3.12.14 offline PyCharm workflow verifier (desktop IDE not launched)"


def case_completion_syntax_and_folding():
    sample = (
        '"""\n多行模块说明\n"""\n'
        "import os\n"
        "import sys\n\n"
        "class Worker:\n"
        "    def run(self):\n"
        "        # 执行任务\n"
        '        return "ok"\n'
    )
    tokens = list(tokenize.generate_tokens(io.StringIO(sample).readline))
    kw_tokens = [t.string for t in tokens if t.type == tokenize.NAME and keyword.iskeyword(t.string)]
    comment_tokens = [t.string for t in tokens if t.type == tokenize.COMMENT]
    string_tokens = [t.string for t in tokens if t.type == tokenize.STRING]

    tree = ast.parse(sample)
    foldable_kinds = []
    if sum(1 for n in tree.body if isinstance(n, ast.Import)) >= 2:
        foldable_kinds.append("import_group")
    if ast.get_docstring(tree):
        foldable_kinds.append("multiline_comment")
    for n in ast.walk(tree):
        if isinstance(n, ast.ClassDef):
            foldable_kinds.append("class")
        elif isinstance(n, ast.FunctionDef):
            foldable_kinds.append("function")

    expected = {
        "has_def_and_class": True,
        "comment_count": 1,
        "string_count": 2,
        "foldable_kinds": ["import_group", "multiline_comment", "class", "function"],
    }
    actual = {
        "has_def_and_class": "def" in kw_tokens and "class" in kw_tokens,
        "comment_count": len(comment_tokens),
        "string_count": len(string_tokens),
        "foldable_kinds": foldable_kinds,
    }
    return {
        "name": "completion_syntax_and_folding",
        "summary": "利用 tokenize 与 ast 分类关键字/字符串/注释并识别导入组、多行注释、类与函数四类可折叠区域",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_editing_shortcuts_and_multicursor():
    lines = ["alpha = 1", "beta = 2", "gamma = 3"]
    # Ctrl+D duplicate line 0
    dup = [lines[0], lines[0], lines[1], lines[2]]
    # Ctrl+Y delete line 2 (beta = 2)
    after_del = [dup[0], dup[1], dup[3]]
    # Alt+Shift+Up move last line up
    after_move = [after_del[0], after_del[2], after_del[1]]

    # Column selection / multi-cursor prefix rename
    col_lines = ["old_name = 1", "old_value = 2"]
    col_edited = ["new_" + ln[4:] if ln.startswith("old_") else ln for ln in col_lines]

    expected = {
        "after_dup_len": 4,
        "after_move": ["alpha = 1", "gamma = 3", "alpha = 1"],
        "column_edited": ["new_name = 1", "new_value = 2"],
    }
    actual = {
        "after_dup_len": len(dup),
        "after_move": after_move,
        "column_edited": col_edited,
    }
    return {
        "name": "editing_shortcuts_and_multicursor",
        "summary": "验证复制行、删除行、移动行及列选择/多光标批量替换前缀的编辑效果",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_extract_method_and_inline_refactor():
    class Item:
        def __init__(self, val):
            self.val = val
        def is_valid(self):
            return self.val > 0

    def process_before(data):
        cleaned = []
        for item in data:
            if item.is_valid():
                cleaned.append(item)
        return cleaned

    def is_valid_item(item):
        return item.is_valid()

    def process_after(data):
        cleaned = []
        for item in data:
            if is_valid_item(item):
                cleaned.append(item)
        return cleaned

    sample = [Item(-1), Item(0), Item(5), Item(8)]
    before_vals = [x.val for x in process_before(sample)]
    after_vals = [x.val for x in process_after(sample)]

    def calculate_discount(price):
        return price * 0.9

    inline_before = calculate_discount(100)
    inline_after = 100 * 0.9

    expected = {
        "extract_before": [5, 8],
        "extract_after": [5, 8],
        "extract_equivalent": True,
        "inline_before": 90.0,
        "inline_after": 90.0,
    }
    actual = {
        "extract_before": before_vals,
        "extract_after": after_vals,
        "extract_equivalent": before_vals == after_vals,
        "inline_before": inline_before,
        "inline_after": inline_after,
    }
    return {
        "name": "extract_method_and_inline_refactor",
        "summary": "执行提取方法(Extract Method)与内联(Inline)重构前后代码,校验运行结果严格等价",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_live_templates_and_intentions():
    templates = {
        "im": "import ",
        "main": "if __name__ == '__main__':\n    pass\n",
        "iter": "for item in iterable:\n    pass\n",
        "try": "try:\n    pass\nexcept Exception as e:\n    pass\n",
    }
    # Check AST validity of block templates
    valid_blocks = []
    for key in ("main", "iter", "try"):
        ast.parse(templates[key])
        valid_blocks.append(key)

    # Simulate Alt+Enter intention: .format -> f-string equivalence
    user = "Alice"
    old_fmt = "Hello, {}!".format(user)
    new_fstr = f"Hello, {user}!"

    expected = {
        "im_expansion": "import ",
        "valid_block_templates": ["main", "iter", "try"],
        "intention_fstring_equal": True,
    }
    actual = {
        "im_expansion": templates["im"],
        "valid_block_templates": valid_blocks,
        "intention_fstring_equal": old_fmt == new_fstr,
    }
    return {
        "name": "live_templates_and_intentions",
        "summary": "验证 im/main/iter/try 实时模板展开语法正确性与 Alt+Enter 字符串格式化意图等价转换",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_completion_syntax_and_folding(),
        case_editing_shortcuts_and_multicursor(),
        case_extract_method_and_inline_refactor(),
        case_live_templates_and_intentions(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 PyCharm 工程语义与配置验证器(未启动桌面端 PyCharm IDE)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 PyCharm 工程语义与配置验证器(未启动桌面端 PyCharm IDE)。

入口文件:projects/pycharm-code-editor-lab/explore-code-editor.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-code-editor.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 PyCharm 工程语义与配置验证器(未启动桌面端 PyCharm IDE)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:PyCharm

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

下载课程关联工程包:PyCharm

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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