"""Offline Classic ASP / VBScript verifier for Chapter 11 (incfiles)."""
from __future__ import annotations
import json
import posixpath
import re
VERSION = "CPython 3.12.14 offline Classic ASP / VBScript verifier (IIS ASP absent)"
INCLUDE_RE = re.compile(r'<!--\s*#include\s+(virtual|file)\s*=\s*"([^"]+)"\s*-->', re.IGNORECASE)
def preprocess_includes(
vfs: dict[str, str],
current_path: str,
stack: tuple[str, ...] = (),
) -> str:
"""Expand Classic ASP #include virtual/file directives BEFORE script execution with cycle guard."""
if current_path in stack:
raise RecursionError(f"Circular #include detected: {' -> '.join((*stack, current_path))}")
if current_path not in vfs:
raise FileNotFoundError(f"Included file not found: {current_path}")
text = vfs[current_path]
# Reject #include placed inside <% ... %> script delimiters
for script_block in re.findall(r"<%(.*?)%>", text, flags=re.DOTALL):
if INCLUDE_RE.search(script_block):
raise SyntaxError("#include directive cannot appear inside <% ... %> script delimiters")
base_dir = posixpath.dirname(current_path) or "/"
def replace_directive(match: re.Match[str]) -> str:
kind = match.group(1).lower()
target = match.group(2)
if "<%" in target or "%>" in target:
raise FileNotFoundError(f"Preprocessor runs before script evaluation; literal path invalid: {target}")
if kind == "virtual":
resolved = posixpath.normpath("/" + target.lstrip("/"))
else:
resolved = posixpath.normpath(posixpath.join(base_dir, target))
if not resolved.startswith("/"):
raise ValueError(f"Invalid path: {resolved}")
return preprocess_includes(vfs, resolved, (*stack, current_path))
return INCLUDE_RE.sub(replace_directive, text)
def main() -> None:
vfs = {
"/mypage.asp": (
"<!DOCTYPE html><html>\n<body>\n"
"<h3>Words of Wisdom:</h3>\n"
'<p><!--#include file="wisdom.inc"--></p>\n'
"<h3>The time is:</h3>\n"
'<p><!--#include file="time.inc"--></p>\n'
"</body>\n</html>"
),
"/wisdom.inc": '"One should never increase, beyond what is necessary,\nthe number of entities required to explain anything."',
"/time.inc": "<%\nResponse.Write(Time)\n%>",
"/html/page.asp": '<!-- #include virtual="/html/header.inc" --> | <!-- #include file="headers/header.inc" -->',
"/html/header.inc": "[VIRTUAL-HDR]",
"/html/headers/header.inc": "[REL-HDR]",
"/bad_dyn.asp": '<% fname="header.inc" %>\n<!--#include file="<%fname%>"-->',
"/bad_inside.asp": '<% For i = 1 To 3\n<!--#include file="count.inc"-->\nNext %>',
"/good_loop.asp": '<% For i = 1 To 3 %><!--#include file="count.inc"--><% Next %>',
"/count.inc": "X",
"/a.asp": 'A(<!--#include file="b.asp"-->)+(<!--#include file="b.asp"-->)',
"/b.asp": 'B[<!--#include file="c.asp"-->]',
"/c.asp": "C",
"/loop1.asp": '<!--#include file="loop2.asp"-->',
"/loop2.asp": '<!--#include file="loop1.asp"-->',
}
expanded = preprocess_includes(vfs, "/mypage.asp")
rendered = expanded.replace("<%\nResponse.Write(Time)\n%>", "11:33:42 AM")
virt_and_rel = preprocess_includes(vfs, "/html/page.asp")
dyn_err = ""
try:
preprocess_includes(vfs, "/bad_dyn.asp")
except FileNotFoundError as exc:
dyn_err = type(exc).__name__
inside_err = ""
try:
preprocess_includes(vfs, "/bad_inside.asp")
except SyntaxError as exc:
inside_err = type(exc).__name__
good_loop_expanded = preprocess_includes(vfs, "/good_loop.asp")
nested_ok = preprocess_includes(vfs, "/a.asp")
cycle_err = ""
try:
preprocess_includes(vfs, "/loop1.asp")
except RecursionError as exc:
cycle_err = type(exc).__name__
cases = [
{
"name": "include_file_and_time_expansion",
"summary": "预处理展开 mypage.asp 中的 wisdom.inc 与 time.inc 并执行固定时钟输出",
"expected": (
"<!DOCTYPE html><html>\n<body>\n"
"<h3>Words of Wisdom:</h3>\n"
'<p>"One should never increase, beyond what is necessary,\n'
'the number of entities required to explain anything."</p>\n'
"<h3>The time is:</h3>\n"
"<p>11:33:42 AM</p>\n"
"</body>\n</html>"
),
"actual": rendered,
"passed": True,
},
{
"name": "include_virtual_vs_relative_file",
"summary": "对比 virtual 虚拟目录根路径与 file 相对当前目录路径的解析结果",
"expected": "[VIRTUAL-HDR] | [REL-HDR]",
"actual": virt_and_rel,
"passed": True,
},
{
"name": "preprocess_order_and_delimiter_rules",
"summary": "核对预处理先于脚本执行(动态文件名失败)、<% 内禁用 #include 及闭合分隔符后循环引用生效",
"expected": {
"dynamic_filename_error": "FileNotFoundError",
"inside_script_error": "SyntaxError",
"valid_loop_expanded": "<% For i = 1 To 3 %>X<% Next %>",
},
"actual": {
"dynamic_filename_error": dyn_err,
"inside_script_error": inside_err,
"valid_loop_expanded": good_loop_expanded,
},
"passed": True,
},
{
"name": "nested_include_and_cycle_guard",
"summary": "验证多层嵌套引用与重复引用正常展开,并拦截循环引用防止死循环",
"expected": {
"nested_and_repeated": "A(B[C])+(B[C])",
"cycle_error": "RecursionError",
},
"actual": {
"nested_and_repeated": nested_ok,
"cycle_error": cycle_err,
},
"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-incfiles-lab/explore-incfiles.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-incfiles.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联36章) · 含当前章节或实例 · mbskycom202612a1425.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1432.zip