"""Offline ASP.NET Razor VB variables verification lab for Chapter 23 (razor-vb-variables)."""
from datetime import date, datetime
from decimal import Decimal, InvalidOperation
import json
import re
VERSION = "CPython 3.12.14 offline ASP.NET Razor VB variables semantic verifier (IIS/ASP.NET host absent)"
def case_vb_dim_and_as_type_declarations():
decl_lines = [
'Dim greeting = "Welcome to ASP.NET"',
'Dim counter = 103',
'Dim today = DateTime.Today',
'Dim greeting2 As String = "Welcome to ASP.NET"',
'Dim counter2 As Integer = 103',
'Dim today2 As DateTime = DateTime.Today',
]
parsed = {}
for ln in decl_lines:
m = re.match(r'^Dim\s+([A-Za-z_]\w*)(?:\s+As\s+([A-Za-z]+))?\s*=\s*(.+)$', ln, flags=re.I)
assert m
name, explicit_type, expr = m.group(1).lower(), m.group(2), m.group(3)
if expr.startswith('"'):
inferred, val = "String", expr.strip('"')
elif expr.isdigit():
inferred, val = "Integer", int(expr)
else:
inferred, val = "DateTime", date(2026, 11, 2).isoformat()
parsed[name] = (explicit_type or inferred, val)
expected = {
"inferred_matches_explicit": True,
"comment_prefix_vb": "'",
"types": ["String", "Integer", "DateTime"],
}
actual = {
"inferred_matches_explicit": (
parsed["greeting"] == parsed["greeting2"]
and parsed["counter"] == parsed["counter2"]
and parsed["today"] == parsed["today2"]
),
"comment_prefix_vb": "'",
"types": [parsed["greeting"][0], parsed["counter"][0], parsed["today"][0]],
}
return {
"name": "vb_dim_and_as_type_declarations",
"summary": "解析 VB Dim 隐式推断与 Dim ... As Type 显式声明,并核对单引号 ' 注释语法规范",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_vb_types_and_case_insensitivity():
sym = {}
sym["mycount"] = 103
sym["ratio"] = 3.14
sym["amount"] = Decimal("1037.196543")
sym["isactive"] = True
sym["username"] = "John"
expected = {
"case_insensitive_hit": True,
"double_val": 3.14,
"decimal_str": "1037.196543",
"bool_val": True,
"string_val": "John",
}
actual = {
"case_insensitive_hit": sym["MYCOUNT".lower()] == 103 and sym["MyCount".lower()] == 103,
"double_val": sym["ratio"],
"decimal_str": str(sym["amount"]),
"bool_val": sym["isactive"],
"string_val": sym["username"],
}
return {
"name": "vb_types_and_case_insensitivity",
"summary": "核对 VB 常用数据类型(Integer/Double/Decimal/Boolean/String)与标识符不区分大小写特性",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_vb_operators_and_short_circuit():
i = 6
arith = [5 + 5, 5 - 5, 5 * 5, 5 / 5]
i += 1
inc_v = i
i -= 1
dec_v = i
names = ["Ada", "Bob", "Cid", "Dan"]
eval_log = []
def rhs():
eval_log.append("rhs_evaluated")
return True
eager_and = (False & rhs())
eager_count = len(eval_log)
eval_log.clear()
short_and_also = (False and rhs())
short_count = len(eval_log)
expected = {
"arith": [10, 0, 25, 1.0],
"inc_dec": [7, 6],
"vb_eq_neq": [False, True],
"vb_concat": "ASP.NET",
"vb_array_parens": "Dan",
"eager_and_called_rhs": [False, 1],
"short_circuit_andalso_skipped_rhs": [False, 0],
}
actual = {
"arith": arith,
"inc_dec": [inc_v, dec_v],
"vb_eq_neq": [i == 10, i != 10],
"vb_concat": "ASP" + ".NET",
"vb_array_parens": names[3],
"eager_and_called_rhs": [bool(eager_and), eager_count],
"short_circuit_andalso_skipped_rhs": [bool(short_and_also), short_count],
}
return {
"name": "vb_operators_and_short_circuit",
"summary": "校验 VB =/=/<> 比较、& 字符串连接、() 数组索引,以及 And/Or 急切求值与 AndAlso/OrElse 短路求值差异",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_vb_string_conversion_helpers():
def is_int(s):
return bool(re.fullmatch(r"[+-]?\d+", s.strip()))
def as_int(s):
return int(s.strip()) if is_int(s) else 0
def is_float(s):
try:
float(s.strip())
return True
except ValueError:
return False
def is_decimal(s):
try:
Decimal(s.strip())
return True
except InvalidOperation:
return False
def as_datetime(s):
return datetime.strptime(s.strip(), "%m/%d/%Y").strftime("%Y-%m-%d")
def as_bool(s):
return s.strip().lower() == "true"
expected = {
"int_pair": [True, 42],
"float_pair": [True, 2.5],
"decimal_pair": [True, "99.95"],
"datetime_iso": "2012-10-10",
"bool_val": True,
"to_string": "1234",
}
actual = {
"int_pair": [is_int("42"), as_int("42")],
"float_pair": [is_float("2.5"), float("2.5")],
"decimal_pair": [is_decimal("99.95"), str(Decimal("99.95"))],
"datetime_iso": as_datetime("10/10/2012"),
"bool_val": as_bool("True"),
"to_string": str(1234),
}
return {
"name": "vb_string_conversion_helpers",
"summary": "模拟 Razor VB 中的 IsInt/AsInt、IsFloat/AsFloat、IsDecimal/AsDecimal、AsDateTime、AsBool 与 ToString",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_vb_dim_and_as_type_declarations(),
case_vb_types_and_case_insensitivity(),
case_vb_operators_and_short_circuit(),
case_vb_string_conversion_helpers(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 ASP.NET Razor / MVC 语义验证器(未启动 Visual Studio / IIS / ASP.NET MVC 运行时宿主)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 ASP.NET Razor / MVC 语义验证器(未启动 Visual Studio / IIS / ASP.NET MVC 运行时宿主)。
入口文件:projects/web-forms-razor-vb-variables-lab/explore-razor-vb-variables.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-razor-vb-variables.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 ASP.NET Razor / MVC 语义验证器(未启动 Visual Studio / IIS / ASP.NET MVC 运行时宿主)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联55章) · 含当前章节或实例 · mbskycom202612a2981.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3000.zip