"""Offline Classic ASP / VBScript verifier for Chapter 04 (syntax)."""
from __future__ import annotations
import json
import re
VERSION = "CPython 3.12.14 offline Classic ASP / VBScript verifier (IIS ASP absent)"
def execute_asp_page(source: str) -> dict[str, object]:
"""Parse <%@ language="..." %> directive and render <% ... %> / <%= ... %> blocks."""
lang = "vbscript"
dir_match = re.match(r'\s*<%@\s*language\s*=\s*"([^"]+)"\s*%>', source, re.IGNORECASE)
body_src = source
if dir_match:
lang = dir_match.group(1).strip().lower()
body_src = source[dir_match.end():]
def eval_block(match: re.Match[str]) -> str:
inner = match.group(1).strip()
if inner.startswith("="):
rhs = inner[1:].strip()
if rhs.startswith('"') and rhs.endswith('"'):
return rhs[1:-1]
raise ValueError(f"Unsupported shorthand expression: {rhs}")
out: list[str] = []
for raw_line in inner.splitlines():
line = raw_line.strip().rstrip(";")
if not line:
continue
if lang == "vbscript":
m = re.fullmatch(r'response\.write\s*\(\s*"([^"]*)"\s*\)', line, re.IGNORECASE)
if not m:
raise ValueError(f"VBScript syntax error: {line}")
out.append(m.group(1))
elif lang in {"javascript", "jscript"}:
m = re.fullmatch(r'Response\.Write\s*\(\s*"([^"]*)"\s*\)', line)
if not m:
raise NameError(f"JScript case-sensitive error: {line}")
out.append(m.group(1))
else:
raise ValueError(f"External script engine required for: {lang}")
return "".join(out)
try:
rendered = re.sub(r"<%(.*?)%>", eval_block, body_src, flags=re.DOTALL).strip()
return {"ok": True, "language": lang, "html": rendered}
except Exception as exc:
return {"ok": False, "language": lang, "error": f"{type(exc).__name__}: {exc}"}
def main() -> None:
full_vb = '<!DOCTYPE html><html>\n<body><%\nresponse.write("Hello World!")\n%>\n</body>\n</html>'
short_vb = '<!DOCTYPE html><html>\n<body><%\n="Hello World!"\n%>\n</body>\n</html>'
res_full = execute_asp_page(full_vb)
res_short = execute_asp_page(short_vb)
vb_mixed = '<body><% RESPONSE.WRITE("Hello World!") %></body>'
res_vb_mixed = execute_asp_page(vb_mixed)
js_valid = '<%@ language="javascript"%>\n<body><% Response.Write("Hello World!") %></body>'
js_bad_case = '<%@ language="javascript"%>\n<body><% response.write("Hello World!") %></body>'
res_js_ok = execute_asp_page(js_valid)
res_js_bad = execute_asp_page(js_bad_case)
html_fmt = (
'<body><%\n'
'response.write("<h2>You can use HTML tags to format the text!</h2>")\n'
'response.write("<p style=\'color:#0000ff\'>Styled with CSS</p>")\n'
'%></body>'
)
res_fmt = execute_asp_page(html_fmt)
cases = [
{
"name": "response_write_and_shorthand",
"summary": "验证 response.write 与 <% =\"...\" %> 简写输出完全一致的 HTML",
"expected": {
"same_output": True,
"html": "<!DOCTYPE html><html>\n<body>Hello World!\n</body>\n</html>",
},
"actual": {
"same_output": res_full["html"] == res_short["html"],
"html": res_full["html"],
},
"passed": True,
},
{
"name": "vbscript_default_case_insensitivity",
"summary": "验证未声明 @language 时默认采用 VBScript 且对方法名大小写不敏感",
"expected": {"language": "vbscript", "html": "<body>Hello World!</body>"},
"actual": {"language": res_vb_mixed["language"], "html": res_vb_mixed["html"]},
"passed": True,
},
{
"name": "javascript_directive_case_sensitivity",
"summary": "验证 <%@ language=\"javascript\"%> 切换为大小写敏感模式并捕获小写 response.write 错误",
"expected": {
"valid_ok": True,
"valid_html": "<body>Hello World!</body>",
"wrong_case_ok": False,
"wrong_case_type": "NameError",
},
"actual": {
"valid_ok": res_js_ok["ok"],
"valid_html": res_js_ok["html"],
"wrong_case_ok": res_js_bad["ok"],
"wrong_case_type": str(res_js_bad["error"]).split(":")[0],
},
"passed": True,
},
{
"name": "html_tag_formatting_output",
"summary": "验证 ASP 脚本向响应写入带 HTML 标签与内联样式的格式化文本",
"expected": "<body><h2>You can use HTML tags to format the text!</h2><p style='color:#0000ff'>Styled with CSS</p></body>",
"actual": res_fmt["html"],
"passed": True,
},
]
for c in cases:
c["passed"] = c["actual"] == c["expected"]
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/asp-syntax-lab/explore-syntax.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-syntax.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联36章) · 含当前章节或实例 · mbskycom202612a1425.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1453.zip