|
|
@@ -0,0 +1,272 @@
|
|
|
+# -*- coding: utf-8 -*-
|
|
|
+"""
|
|
|
+"rt_snprintf 不支持浮点" 回归的验证脚本(2026-09-30)。
|
|
|
+
|
|
|
+只读源文件, 中间产物全部写系统临时目录, 不在工程树里留 .c/.h。
|
|
|
+
|
|
|
+验证四项:
|
|
|
+ [A] 全 applications 扫描: 任何 printf 家族函数都不得带 %f/%e/%g 浮点格式符
|
|
|
+ (含 LOG_*/HMI_WRITE/DTU_Write 等封装, 因为它们最终都走 rt_vsnprintf)
|
|
|
+ [B] fmt_fixed2() 切块 —— 宿主 gcc -fsyntax-only
|
|
|
+ [C] 定点格式化算法的数值正确性 —— 用宿主 gcc 编译真函数跑一批用例,
|
|
|
+ 验证 0.00 / 3.14 / 25000.00 / 负数 / 各种舍入边界
|
|
|
+ [D] 三处原雷区的调用点是否都已改成 fmt_fixed2
|
|
|
+"""
|
|
|
+import os
|
|
|
+import re
|
|
|
+import sys
|
|
|
+import shutil
|
|
|
+import tempfile
|
|
|
+import subprocess
|
|
|
+
|
|
|
+ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
|
+GCC = r"D:\Strawberry\c\bin\gcc.exe"
|
|
|
+OUT = os.path.join(ROOT, ".workbuddy", "float_fmt_check.txt")
|
|
|
+APP = os.path.join(ROOT, "applications")
|
|
|
+
|
|
|
+lines = []
|
|
|
+
|
|
|
+
|
|
|
+def log(s=""):
|
|
|
+ lines.append(s)
|
|
|
+
|
|
|
+
|
|
|
+def read(p):
|
|
|
+ with open(p, "r", encoding="utf-8", errors="ignore") as f:
|
|
|
+ return f.read()
|
|
|
+
|
|
|
+
|
|
|
+def strip_code(txt):
|
|
|
+ """去注释与字符串, 只留代码"""
|
|
|
+ t = re.sub(r"/\*.*?\*/", "", txt, flags=re.S)
|
|
|
+ t = re.sub(r"//[^\n]*", "", t)
|
|
|
+ t = re.sub(r'"(\\.|[^"\\])*"', '""', t)
|
|
|
+ t = re.sub(r"'(\\.|[^'\\])*'", "''", t)
|
|
|
+ return t
|
|
|
+
|
|
|
+
|
|
|
+# ---------------- A. 全工程浮点格式符扫描 ----------------
|
|
|
+def check_no_float_fmt():
|
|
|
+ log("=" * 74)
|
|
|
+ log("[A] 全 applications 扫描: printf 家族不得使用 %f / %e / %g")
|
|
|
+ log("=" * 74)
|
|
|
+ # 任何最终会走到 rt_vsnprintf 的封装
|
|
|
+ pat = re.compile(
|
|
|
+ r"\b(rt_snprintf|rt_sprintf|rt_vsnprintf|snprintf|sprintf|vsnprintf"
|
|
|
+ r"|HMI_WRITE|DTU_Write|Uart5_Write|Uart5_Write_Bin"
|
|
|
+ r"|LOG_[IWED])\s*\(")
|
|
|
+ # 浮点转换符: %[flags][width][.prec][l|L]?[fFeEgG]
|
|
|
+ fconv = re.compile(r"%(?:[-+ #0]*)(?:\d+|\*)?(?:\.(?:\d+|\*))?[lL]?[fFeEgG]")
|
|
|
+
|
|
|
+ hits = []
|
|
|
+ for dirpath, _, names in os.walk(APP):
|
|
|
+ for n in names:
|
|
|
+ if not n.endswith((".c", ".h")):
|
|
|
+ continue
|
|
|
+ fp = os.path.join(dirpath, n)
|
|
|
+ code = strip_code(read(fp))
|
|
|
+ for m in pat.finditer(code):
|
|
|
+ # 取该调用从左括号起 600 字符的窗口(够覆盖多行格式串拼接)
|
|
|
+ seg = code[m.end():m.end() + 600]
|
|
|
+ for fm in fconv.finditer(seg):
|
|
|
+ # 排除 HMI_WRITE("...%s", str) 这种把已格式化串再拼的情况
|
|
|
+ hits.append("%s: %s( -> %s"
|
|
|
+ % (os.path.relpath(fp, ROOT), m.group(1),
|
|
|
+ fm.group(0)))
|
|
|
+ if hits:
|
|
|
+ for h in hits:
|
|
|
+ log(" [HIT] %s" % h)
|
|
|
+ else:
|
|
|
+ log(" 未发现任何浮点格式符 (共扫描 %s)" % APP)
|
|
|
+ log(" => %s" % ("PASS" if not hits else "FAIL"))
|
|
|
+ return not hits
|
|
|
+
|
|
|
+
|
|
|
+# ---------------- B. fmt_fixed2 语法检查 ----------------
|
|
|
+def check_syntax(tmp):
|
|
|
+ log()
|
|
|
+ log("=" * 74)
|
|
|
+ log("[B] control.c: fmt_fixed2() —— 宿主 gcc 语法检查")
|
|
|
+ log("=" * 74)
|
|
|
+ src = read(os.path.join(APP, "control.c")).splitlines()
|
|
|
+ s = e = -1
|
|
|
+ for i, ln in enumerate(src):
|
|
|
+ if s < 0 and re.search(r"^void fmt_fixed2\(", ln):
|
|
|
+ s = i
|
|
|
+ elif s >= 0 and re.match(r"^\}", ln):
|
|
|
+ e = i
|
|
|
+ break
|
|
|
+ if s < 0 or e < 0:
|
|
|
+ log(" [FAIL] 未定位到 fmt_fixed2()")
|
|
|
+ return False
|
|
|
+ blk = src[s:e + 1]
|
|
|
+
|
|
|
+ stub = r"""
|
|
|
+#include <stddef.h>
|
|
|
+typedef unsigned long rt_size_t;
|
|
|
+#define RT_NULL ((void *)0)
|
|
|
+extern int rt_snprintf(char *buf, rt_size_t size, const char *fmt, ...);
|
|
|
+"""
|
|
|
+ p = os.path.join(tmp, "b_fmt.c")
|
|
|
+ with open(p, "w", encoding="utf-8") as f:
|
|
|
+ f.write(stub + "\n" + "\n".join(blk) + "\n")
|
|
|
+ r = subprocess.run([GCC, "-x", "c", "-fsyntax-only", "-std=gnu99",
|
|
|
+ "-Wall", "-Wextra", "-Wno-unused-parameter", p],
|
|
|
+ cwd=tmp, capture_output=True, text=True,
|
|
|
+ encoding="utf-8", errors="replace", timeout=120)
|
|
|
+ log(" 切出 %d 行, gcc exit=%d" % (len(blk), r.returncode))
|
|
|
+ out = (r.stdout or "") + (r.stderr or "")
|
|
|
+ if out.strip():
|
|
|
+ log(out.strip()[:1500])
|
|
|
+ log(" => %s" % ("PASS" if r.returncode == 0 else "FAIL"))
|
|
|
+ return r.returncode == 0
|
|
|
+
|
|
|
+
|
|
|
+# ---------------- C. 算法数值正确性 ----------------
|
|
|
+def check_numeric(tmp):
|
|
|
+ log()
|
|
|
+ log("=" * 74)
|
|
|
+ log("[C] fmt_fixed2() 数值正确性 —— 真编译真运行")
|
|
|
+ log("=" * 74)
|
|
|
+ src = read(os.path.join(APP, "control.c")).splitlines()
|
|
|
+ s = e = -1
|
|
|
+ for i, ln in enumerate(src):
|
|
|
+ if s < 0 and re.search(r"^void fmt_fixed2\(", ln):
|
|
|
+ s = i
|
|
|
+ elif s >= 0 and re.match(r"^\}", ln):
|
|
|
+ e = i
|
|
|
+ break
|
|
|
+ blk = "\n".join(src[s:e + 1])
|
|
|
+
|
|
|
+ # 宿主 gcc 的 rt_snprintf 就是真 snprintf, 行为一致(都支持 %ld/%02ld)
|
|
|
+ cases = [
|
|
|
+ # (输入, prec, 期望输出)
|
|
|
+ (0.0, 2, "0.00"),
|
|
|
+ (3.14159, 2, "3.14"),
|
|
|
+ (3.145, 2, "3.15"), # 舍入
|
|
|
+ (3.144, 2, "3.14"),
|
|
|
+ (2.675, 2, "2.68"), # 经典二进制舍入陷阱, 加0.5法能吃掉
|
|
|
+ (9.999, 2, "10.00"), # 进位到整数位
|
|
|
+ (0.005, 2, "0.01"), # 边界
|
|
|
+ (0.004, 2, "0.00"),
|
|
|
+ (-3.14159, 2, "-3.14"), # 负数
|
|
|
+ (-0.5, 2, "-0.50"),
|
|
|
+ (20000.0, 2, "20000.00"),
|
|
|
+ (25000.0, 2, "20000.00"), # 超上限应被钳位(钳位先于舍入)
|
|
|
+ (19999.999, 2, "20000.00"),
|
|
|
+ # prec=1: 12.99 必须按 1 位小数四舍五入成 13.0, 不能截断成 12.9
|
|
|
+ (12.0, 1, "12.0"),
|
|
|
+ (12.94, 1, "12.9"),
|
|
|
+ (12.95, 1, "13.0"),
|
|
|
+ (12.99, 1, "13.0"),
|
|
|
+ (-12.95, 1, "-13.0"),
|
|
|
+ (12.34, 0, "12"),
|
|
|
+ (12.94, 0, "13"),
|
|
|
+ # 原始雷区的真实取值推演
|
|
|
+ (75.0, 2, "75.00"),
|
|
|
+ (162.5, 2, "162.50"), # (2481-2400)/0.4 附近
|
|
|
+ (310.0, 2, "310.00"), # (2481-2450)/0.1
|
|
|
+ ]
|
|
|
+ main = ['#include <stdio.h>', '#include <string.h>', '#include <stdarg.h>',
|
|
|
+ 'typedef unsigned long rt_size_t;',
|
|
|
+ '#define RT_NULL ((void*)0)',
|
|
|
+ '/* 宿主桩: RT-Thread 的 rt_snprintf 只支持 %d/%ld/%02ld/%s 等,',
|
|
|
+ ' 全部是标准 printf 也支持的非浮点格式符, 所以直接映射到 snprintf',
|
|
|
+ ' 就能验证 fmt_fixed2 的数值正确性。 */',
|
|
|
+ 'int rt_snprintf(char *buf, rt_size_t size, const char *fmt, ...)',
|
|
|
+ '{ va_list ap; int n; va_start(ap, fmt);',
|
|
|
+ ' n = vsnprintf(buf, (size_t)size, fmt, ap); va_end(ap); return n; }',
|
|
|
+ blk,
|
|
|
+ 'int main(void){', ' char b[32];', ' int fail=0;']
|
|
|
+ for v, pr, exp in cases:
|
|
|
+ main.append(f' memset(b,0,sizeof b); fmt_fixed2(b,sizeof b,{v:.10f},{pr});')
|
|
|
+ # 用 f-string 拼 C 代码, 其中的 % 会被 C 自己解析, 不需要也不能转义
|
|
|
+ main.append(f' if(strcmp(b,"{exp}")){{ '
|
|
|
+ f'printf(" FAIL %.6f prec={pr} -> [%s] want [{exp}]\\n", '
|
|
|
+ f'{v:.10f}, b); fail++; }}')
|
|
|
+ main.append(f' else printf(" ok %.6f prec={pr} -> %s\\n", '
|
|
|
+ f'{v:.10f}, b);')
|
|
|
+ main.append(' printf("\\n %d/%d passed\\n", %d-fail, %d);'
|
|
|
+ % (len(cases), len(cases), len(cases), len(cases)))
|
|
|
+ main.append(' return fail?1:0; }')
|
|
|
+
|
|
|
+ p = os.path.join(tmp, "c_num.c")
|
|
|
+ with open(p, "w", encoding="utf-8") as f:
|
|
|
+ f.write("\n".join(main))
|
|
|
+ exe = os.path.join(tmp, "c_num.exe")
|
|
|
+ r = subprocess.run([GCC, "-x", "c", "-std=gnu99", "-w", p, "-o", exe],
|
|
|
+ cwd=tmp, capture_output=True, text=True,
|
|
|
+ encoding="utf-8", errors="replace", timeout=120)
|
|
|
+ if r.returncode != 0 or not os.path.exists(exe):
|
|
|
+ log(" 编译失败 (gcc exit=%d):" % r.returncode)
|
|
|
+ log(((r.stdout or "") + (r.stderr or ""))[:1500])
|
|
|
+ log(" => FAIL")
|
|
|
+ return False
|
|
|
+ try:
|
|
|
+ r2 = subprocess.run([exe], cwd=tmp, capture_output=True, text=True,
|
|
|
+ encoding="utf-8", errors="replace", timeout=60)
|
|
|
+ except Exception as ex:
|
|
|
+ log(" 运行异常: %s" % ex)
|
|
|
+ log(" => FAIL")
|
|
|
+ return False
|
|
|
+ log((r2.stdout or "").rstrip())
|
|
|
+ if r2.returncode != 0:
|
|
|
+ log(" exe exit=%d, stderr=%s" % (r2.returncode, (r2.stderr or "").strip()[:300]))
|
|
|
+ log(" => %s" % ("PASS" if r2.returncode == 0 else "FAIL"))
|
|
|
+ return r2.returncode == 0
|
|
|
+
|
|
|
+
|
|
|
+# ---------------- D. 三处原雷区 ----------------
|
|
|
+def check_callsites():
|
|
|
+ log()
|
|
|
+ log("=" * 74)
|
|
|
+ log("[D] 原雷区调用点: power / heat_power / 相机参数")
|
|
|
+ log("=" * 74)
|
|
|
+ ok = True
|
|
|
+
|
|
|
+ sht = read(os.path.join(APP, "sht30_collect.c"))
|
|
|
+ code = strip_code(sht)
|
|
|
+ n_call = len(re.findall(r"fmt_fixed2\s*\(\s*device_status\.(power|heat_power)", code))
|
|
|
+ log(" sht30_collect.c: fmt_fixed2 写 power/heat_power 共 %d 处(应为 3)" % n_call)
|
|
|
+ ok = ok and (n_call == 3)
|
|
|
+
|
|
|
+ dtu = read(os.path.join(APP, "dtu_uart2.c"))
|
|
|
+ code2 = strip_code(dtu)
|
|
|
+ n2 = len(re.findall(r"fmt_fixed2\s*\(\s*d_(ExposureTime|Gamma)", code2))
|
|
|
+ log(" dtu_uart2.c: fmt_fixed2 写相机参数共 %d 处(应为 2)" % n2)
|
|
|
+ ok = ok and (n2 == 2)
|
|
|
+
|
|
|
+ ctl = read(os.path.join(APP, "control.c"))
|
|
|
+ log(" control.c: fmt_fixed2 定义 %d 处(应为 1)"
|
|
|
+ % len(re.findall(r"^void fmt_fixed2\(", ctl, re.M)))
|
|
|
+ ok = ok and (len(re.findall(r"^void fmt_fixed2\(", ctl, re.M)) == 1)
|
|
|
+
|
|
|
+ h = read(os.path.join(APP, "control.h"))
|
|
|
+ log(" control.h: fmt_fixed2 声明 %d 处(应为 1)"
|
|
|
+ % len(re.findall(r"^\s*void fmt_fixed2\(", h, re.M)))
|
|
|
+ ok = ok and (len(re.findall(r"^\s*void fmt_fixed2\(", h, re.M)) == 1)
|
|
|
+
|
|
|
+ log(" => %s" % ("PASS" if ok else "FAIL"))
|
|
|
+ return ok
|
|
|
+
|
|
|
+
|
|
|
+def main():
|
|
|
+ tmp = tempfile.mkdtemp(prefix="floatfmt_")
|
|
|
+ try:
|
|
|
+ a = check_no_float_fmt()
|
|
|
+ b = check_syntax(tmp)
|
|
|
+ c = check_numeric(tmp)
|
|
|
+ d = check_callsites()
|
|
|
+ log()
|
|
|
+ log("=" * 74)
|
|
|
+ log("总计: %s" % ("全部通过" if (a and b and c and d) else "存在 FAIL, 见上"))
|
|
|
+ log("=" * 74)
|
|
|
+ finally:
|
|
|
+ shutil.rmtree(tmp, ignore_errors=True)
|
|
|
+ with open(OUT, "w", encoding="utf-8") as f:
|
|
|
+ f.write("\n".join(lines))
|
|
|
+ print("done ->", OUT)
|
|
|
+
|
|
|
+
|
|
|
+if __name__ == "__main__":
|
|
|
+ main()
|