"""Offline VS Code JS editing, IntelliSense tokenization & Code Action refactor verifier for Ch14."""
import json
import re
VERSION = "CPython 3.12.14 offline VS Code JS IntelliSense & Code Action verifier"
def check(name, summary, expected, actual):
return {
"name": name,
"summary": summary,
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def convert_concat_to_template(expr: str) -> str:
m = re.fullmatch(r"""\s*(['"])(.*?)\1\s*\+\s*([A-Za-z_$][\w$]*)\s*""", expr)
if not m:
return expr
prefix_text, ident = m.group(2), m.group(3)
return f"`{prefix_text}${{{ident}}}`"
def main():
cases = []
app_js = (
"function sayHello(name) {\n"
" console.log('Hello, ' + name);\n"
"}\n\n"
"sayHello('VS Code');\n"
)
js_keywords = {"function", "return", "const", "let", "var"}
tokens = re.findall(r"[A-Za-z_$][\w$]*|'[^']*'", app_js)
found_keywords = [t for t in tokens if t in js_keywords]
completions = [s for s in ["console", "const", "continue", "confirm"] if s.startswith("con")]
cases.append(
check(
"js_intellisense_and_syntax_tokens",
"Verify app.js syntax tokenization and IntelliSense prefix suggestion ranking",
{
"keywords": ["function"],
"contains_console_log": True,
"string_literals": ["'Hello, '", "'VS Code'"],
"top_completion_for_con": "console",
},
{
"keywords": found_keywords,
"contains_console_log": "console.log" in app_js,
"string_literals": [t for t in tokens if t.startswith("'")],
"top_completion_for_con": completions[0],
},
)
)
# Case 2: Code Action "Convert to template string" refactor
expr_double = '"Hello, " + name'
expr_single = "'Hello, ' + name"
refactored_double = convert_concat_to_template(expr_double)
refactored_single = convert_concat_to_template(expr_single)
transformed_js = app_js.replace(expr_single, refactored_single)
cases.append(
check(
"code_action_template_string_refactor",
"Verify Code Action refactoring of string concatenation into ES6 template literal",
{
"double_quote_refactor": "`Hello, ${name}`",
"single_quote_refactor": "`Hello, ${name}`",
"transformed_contains_template": True,
"eval_preview": "Hello, VS Code",
},
{
"double_quote_refactor": refactored_double,
"single_quote_refactor": refactored_single,
"transformed_contains_template": "console.log(`Hello, ${name}`);" in transformed_js,
"eval_preview": "Hello, " + "VS Code",
},
)
)
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/vscode-write-some-code-lab/explore-write-some-code.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-write-some-code.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联25章) · 含当前章节或实例 · mbskycom202612a2203.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2226.zip