netparse-cmdb 0.8.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
netparse/engine.py ADDED
@@ -0,0 +1,1834 @@
1
+ """嵌套状态栈解析引擎(netparse 核心实现)。
2
+
3
+ 语义(用户定义)
4
+ ----------------
5
+ 集合用缩进表达层级。每层是一个独立状态,有自己的 start / end / [value] / [rule]。
6
+
7
+ 逐行处理:
8
+ ① 从栈顶向下找第一个命中的 start(层 L):
9
+ · L 在栈上 → 存档 L 及其所有子层的当前记录,L 以下(更深)的层出栈
10
+ · L 不在栈上 → 压入 L 成为新栈顶
11
+ · 用 L 的 [rule] 匹配本行,结束
12
+ ② 没命中任何 start:
13
+ · end 从栈顶向下找第一个匹配层 → 收起该层及其所有子层
14
+ · 用栈顶的 [rule] 匹配本行;不匹配则依次向下(父层)尝试
15
+
16
+ 块分隔符:裸 `#` / `!`(长度 ≤ 2)是**块分隔符**,从栈顶向下反复收起所有 end 能匹配的层;
17
+ 更长的 `#` 行仍是注释。
18
+
19
+ 输出结构:子集合的元素嵌在父元素的对应字段里(无需 inherit)。
20
+ 聚合:同一父元素下,Key 相同的子记录合并成一个对象。
21
+
22
+ 用法(库)::
23
+
24
+ from netparse import parse_template, run
25
+ colls = parse_template("templates/huawei-vrp.cmdb")
26
+ result = run(colls, open("device.cfg", encoding="utf-8").readlines())
27
+
28
+ 用法(命令行)::
29
+
30
+ netparse parse <模板> <配置文件> [--json] [--lint]
31
+ """
32
+ import os
33
+ import re
34
+ import sys as _sys
35
+ import types as _types
36
+ from collections import OrderedDict
37
+
38
+ from . import masking as _masking
39
+ from .masking import MASK_DEFAULT, STATS, mask_value
40
+
41
+ # ── 脱敏配置 ──────────────────────────────────────────
42
+ # 配置只存一份,放在 masking.CONFIG(原因见 MaskingConfig 的文档字符串)。
43
+ # 本模块**不**再定义 MASK_VALUE / MASK_HEURISTIC 两个全局 —— 一旦定义,
44
+ # `from netparse.engine import MASK_HEURISTIC` 就会拿到副本,赋值静默失效。
45
+ # 兼容旧写法:模块级 __getattr__ / __setattr__ 把 `engine.MASK_VALUE = x`
46
+ # 转发到 CONFIG,所以 `P.MASK_HEURISTIC = False` 仍然生效。
47
+ CONFIG = _masking.CONFIG
48
+
49
+ #: 字段同时声明了多个 type(如 type(secret) type(int))时记这个标记
50
+ TYPE_CONFLICT_KEY = "__type_conflict__"
51
+
52
+ # ── transform 注册表 ─────────────────────────────────
53
+ # func= 引用的符号表:{名字: 可调用}。
54
+ # 来源:[python_file] 各模块公开符号 + [python] 段内联符号。
55
+ # 内联 > 文件(就近覆盖)。随 parse_template 结果存放在 Coll 之外的全局不可行
56
+ # (多模板并存),所以挂在 parse_template 返回的**列表容器属性**上。
57
+ import importlib.util as _imp_util
58
+
59
+ _RUNTIME_WARN_SEEN = set() # (字段路径, 异常摘要) 去重,避免编辑器实时 lint 重复报
60
+
61
+ #: lint 用的凭据关键字(词边界匹配,见 lint 的 _rule_has_credential_keyword)
62
+ CREDENTIAL_KEYWORDS = (
63
+ "password", "cipher", "secret", "shared-key", "md5-password",
64
+ "irreversible-cipher", "key-string", "authentication-key",
65
+ )
66
+
67
+
68
+ # ── 词法 ──────────────────────────────────────────────
69
+ def split_tokens(s):
70
+ """按空格切词,括号内的空格不切。"""
71
+ out, buf, depth = [], "", 0
72
+ for ch in s:
73
+ if ch == "(":
74
+ depth += 1
75
+ elif ch == ")":
76
+ depth -= 1
77
+ if ch == " " and depth == 0:
78
+ if buf:
79
+ out.append(buf)
80
+ buf = ""
81
+ else:
82
+ buf += ch
83
+ if buf:
84
+ out.append(buf)
85
+ return out
86
+
87
+
88
+ def parse_modifiers(toks):
89
+ """解析声明行的选项。
90
+
91
+ 返回 (attrs, flags):
92
+ attrs —— key(...) / key=value 形式的具名选项
93
+ flags —— 裸词与 option(...) 里的标记,如 Required / Key
94
+
95
+ ⚠️ 一个字段只能声明一种 type(secret 与其它类型互斥)。
96
+ 重复声明时保留**第一个** type,并打上冲突标记(由 lint 报错误、引擎不产出该字段)。
97
+ """
98
+ attrs = {}
99
+ flags = set()
100
+ for t in toks[1:]:
101
+ m = re.match(r"^([A-Za-z_]\w*)(?:\((.*)\))?$", t)
102
+ if m:
103
+ k, v = m.group(1), m.group(2)
104
+ if k == "option":
105
+ for f in re.split(r"[\s,]+", v or ""):
106
+ if f:
107
+ flags.add(f)
108
+ elif v is not None:
109
+ if k == "type" and "type" in attrs:
110
+ attrs[TYPE_CONFLICT_KEY] = True # 保留第一个 type
111
+ else:
112
+ attrs[k] = v
113
+ else:
114
+ flags.add(k)
115
+ continue
116
+ if "=" in t:
117
+ k, _, v = t.partition("=")
118
+ attrs[k] = v
119
+ return attrs, flags
120
+
121
+
122
+ # ── 模型 ──────────────────────────────────────────────
123
+ class Field:
124
+ """[value] 段里的一个字段(缩进 = 嵌套)。"""
125
+
126
+ def __init__(self, name, attrs, flags, parent=None):
127
+ self.name = name
128
+ self.parent = parent
129
+ self.path = name if parent is None else parent.path + "." + name
130
+ self.type = attrs.get("type", "str")
131
+ self.default = attrs.get("default")
132
+ self.reg = attrs.get("reg", r"\S+")
133
+ self.func = attrs.get("func") # transform 函数名(注册表查找)
134
+ self.desc = attrs.get("desc")
135
+ self.inherit = attrs.get("inherit")
136
+ self.required = "Required" in flags
137
+ self.is_key = "Key" in flags
138
+ self.type_conflict = bool(attrs.get(TYPE_CONFLICT_KEY))
139
+ self.children = OrderedDict()
140
+
141
+ def is_secret(self):
142
+ """type == 'secret' —— 该字段的值是凭据,落盘前必须遮蔽。"""
143
+ return self.type == "secret"
144
+
145
+ def __repr__(self):
146
+ return f"<Field {self.path} type={self.type}>"
147
+
148
+
149
+ class Coll:
150
+ """一个集合(一层状态)。
151
+
152
+ 层级有三种表达方式,可以混用:
153
+
154
+ 1. start / end 正则配对(原有方式,适合 Nokia 的 exit、Cisco 的 !)
155
+ 2. indent(n) —— 精确缩进锚定。声明后,本集合的**所有规则**只在
156
+ 恰好 n 个前导空格的行上生效。华为配置缩进严格(318 台全部 0/1/2 层),
157
+ 用它可以把「接口本级」和「bas 视图正文」放进同一个集合而互不串味。
158
+ 3. end_indent(n) —— 裸 `#` / `!` 分隔符的层级语义。声明后,只有
159
+ 恰好 n 个前导空格的 `#` 才关闭本层;未声明则维持旧行为
160
+ (任意 `#` 都可关闭本层)。
161
+
162
+ indent 与 end_indent 都是 **opt-in**:不写就完全保持旧行为,老模板零影响。
163
+ """
164
+
165
+ def __init__(self, name, attrs, flags, indent, parent):
166
+ self.name = name
167
+ self.attrs = attrs
168
+ self.flags = flags
169
+ self.indent = indent
170
+ self.parent = parent
171
+ self.children = [] # 子集合
172
+ self.fields = OrderedDict() # 顶层字段
173
+ self.all_fields = OrderedDict() # 路径 → 字段(含嵌套)
174
+ self.rules = []
175
+ self.type = attrs.get("type", "list")
176
+ self.start = attrs.get("start")
177
+ self.end = attrs.get("end")
178
+ self.desc = attrs.get("desc")
179
+ self.key_fields = [] # 由 option(Key) 派生
180
+ self.start_re = re.compile(self.start) if self.start else None
181
+ self.end_re = re.compile(self.end) if self.end else None
182
+
183
+ # indent(n):规则级缩进锚定。n 是**命令行的前导空格数**。
184
+ self.anchor_indent = None
185
+ self.indent_re = None
186
+ raw = attrs.get("indent")
187
+ if raw is not None:
188
+ try:
189
+ n = int(raw)
190
+ except (TypeError, ValueError):
191
+ raise ValueError(
192
+ "集合 %s 的 indent(...) 必须是整数,收到 %r" % (name, raw))
193
+ self.anchor_indent = n
194
+ self.indent_re = re.compile(r"^ {%d}\S" % n)
195
+
196
+ # end_indent(n):裸分隔符 `#` / `!` 的层级语义(opt-in)。
197
+ self.end_indent = None
198
+ raw = attrs.get("end_indent")
199
+ if raw is not None:
200
+ try:
201
+ self.end_indent = int(raw)
202
+ except (TypeError, ValueError):
203
+ raise ValueError(
204
+ "集合 %s 的 end_indent(...) 必须是整数,收到 %r" % (name, raw))
205
+
206
+
207
+ def __repr__(self):
208
+ return f"<Coll {self.name} d={self.indent} children={[c.name for c in self.children]}>"
209
+
210
+
211
+ class Rule:
212
+ def __init__(self, pattern, target):
213
+ self.pattern = pattern
214
+ self.target = target # None = 省略 ->
215
+
216
+ def __repr__(self):
217
+ return f"<Rule {self.pattern!r} -> {self.target!r}>"
218
+
219
+
220
+ class CompiledRule:
221
+ def __init__(self, rx, group_paths, path_groups, target):
222
+ self.rx = rx
223
+ self.group_paths = group_paths # 捕获组名 → 字段路径
224
+ self.path_groups = path_groups # 字段路径 → 捕获组名
225
+ self.target = target
226
+
227
+
228
+ # ── 模板解析 ──────────────────────────────────────────
229
+ def is_coll_decl(toks):
230
+ """集合声明判定:首 token 是合法标识符 + 第二个 token 是 type(...)
231
+
232
+ 集合: Interfaces type(list) Key(Name) start(...)
233
+ 字段: Name type(str) reg(\\S+) ← 在 [value] 段内,不走这条路
234
+ 规则: ^interface\\s+${Name} ← 首 token 不是标识符
235
+ """
236
+ if len(toks) < 2:
237
+ return False
238
+ if not re.match(r"^[A-Za-z_]\w*$", toks[0]):
239
+ return False
240
+ return toks[1].startswith("type(")
241
+
242
+
243
+ def _parse_template_file(path, colls, py_file_lines, py_blocks, main_lines, main_expect, main_expect_active,
244
+ seen_paths, imported_names, importing_from=None):
245
+ """解析单个模板文件(include/import 的递归工作体)。
246
+
247
+ colls/py_file_lines/py_blocks 是【主模板累计容器】:本文件的产物追加进去。
248
+ seen_paths:已处理绝对路径集合(循环引用检测)。
249
+ imported_names:已注册的顶层集合名 → 来源文件(同名冲突检测)。
250
+ importing_from:非 None 时为集合名集合(from ... import A, B 语法),
251
+ 只保留点名顶层集合(子集合随父)。
252
+ 返回:实际并入的顶层集合名列表。
253
+ """
254
+ tpath = os.path.abspath(path)
255
+ if tpath in seen_paths["on_stack"]:
256
+ raise TemplateFileError(
257
+ "%s: 循环 include/import 检测到(已在解析链中)" % path)
258
+ if tpath in seen_paths["done"]:
259
+ return [] # 菱形依赖:已完整加载过 → 幂等跳过
260
+ seen_paths["on_stack"].add(tpath)
261
+
262
+ colls_before = len(colls)
263
+ stack = []
264
+ cur = None
265
+ mode = None
266
+ base_indent = None
267
+ pending = None
268
+ field_stack = []
269
+ section_coll = None
270
+ cur_py = None
271
+ top_colls = [] # 本文件声明的顶层集合(判断 from 选择名单用)
272
+
273
+ def new_collection(toks, indent):
274
+ nonlocal stack, cur
275
+ while stack and stack[-1][0] >= indent:
276
+ stack.pop()
277
+ parent = stack[-1][1] if stack else None
278
+ attrs, flags = parse_modifiers(toks)
279
+ coll = Coll(toks[0], attrs, flags, indent, parent)
280
+ colls.append(coll)
281
+ if parent:
282
+ parent.children.append(coll)
283
+ else:
284
+ top_colls.append(coll)
285
+ stack.append((indent, coll))
286
+ cur = coll
287
+ return coll
288
+
289
+ def flush_pending():
290
+ nonlocal pending
291
+ if pending is None:
292
+ return
293
+ pat = pending
294
+ target = None
295
+ m = re.match(r"^(.*?)\s*->\s*(.+)$", pat)
296
+ if m:
297
+ pat, target = m.group(1).strip(), m.group(2).strip()
298
+ section_coll.rules.append(Rule(pat, target))
299
+ pending = None
300
+
301
+ for raw in open(path, encoding="utf-8"):
302
+ s = raw.rstrip("\n").rstrip("\r")
303
+ st = s.strip()
304
+ if not st:
305
+ flush_pending()
306
+ if mode not in ("rule", "python", "python_file", "__main__"):
307
+ mode = None
308
+ field_stack = []
309
+ base_indent = None
310
+ continue
311
+ if st.startswith("#"):
312
+ continue
313
+ low = st.lower()
314
+
315
+ # ── include / from-import(仅段外有效)──
316
+ if mode is None:
317
+ m_imp = re.match(r"^import\s+(.+)$", st)
318
+ m_from = re.match(r"^from\s+(\S+)\s+import\s+(.+)$", st)
319
+ if m_from:
320
+ rel, names_s = m_from.group(1), m_from.group(2)
321
+ if not os.path.splitext(rel)[1]:
322
+ # 双后缀兼容:from x == from x.np == from x.cmdb
323
+ base = os.path.join(os.path.dirname(tpath), rel)
324
+ sub = (base + ".np" if os.path.isfile(base + ".np")
325
+ else base + ".cmdb")
326
+ else:
327
+ sub = os.path.normpath(
328
+ os.path.join(os.path.dirname(tpath), rel))
329
+ if not os.path.isfile(sub):
330
+ raise TemplateFileError(
331
+ "%s: import 的模板不存在: %s" % (path, sub))
332
+ names = [x.strip() for x in names_s.split(",") if x.strip()]
333
+ sel = None if "*" in names else set(names)
334
+ _sub_main = [] # 子模板的 [__main__] 收集后丢弃(只有入口文件执行)
335
+ _parse_template_file(sub, colls, py_file_lines, py_blocks,
336
+ _sub_main, [], [False], seen_paths, imported_names,
337
+ importing_from=sel)
338
+ continue
339
+ if m_imp:
340
+ rel = m_imp.group(1).strip()
341
+ if not os.path.splitext(rel)[1]:
342
+ # 双后缀兼容:import x == import x.np == import x.cmdb
343
+ base = os.path.join(os.path.dirname(tpath), rel)
344
+ sub = (base + ".np" if os.path.isfile(base + ".np")
345
+ else base + ".cmdb")
346
+ else:
347
+ sub = os.path.normpath(
348
+ os.path.join(os.path.dirname(tpath), rel))
349
+ if not os.path.isfile(sub):
350
+ raise TemplateFileError(
351
+ "%s: import 的模板不存在: %s" % (path, sub))
352
+ _sub_main = [] # 子模板的 [__main__] 收集后丢弃(只有入口文件执行)
353
+ _parse_template_file(sub, colls, py_file_lines, py_blocks,
354
+ _sub_main, [], [False], seen_paths, imported_names, None)
355
+ continue
356
+
357
+ if low in ("[value]", "[vlaue]", "[rule]", "[python]", "[python_file]", "[__main__]"):
358
+ flush_pending()
359
+ if low == "[python]":
360
+ if cur_py:
361
+ py_blocks.append("\n".join(cur_py))
362
+ cur_py = []
363
+ mode = "python"
364
+ continue
365
+ if low == "[python_file]":
366
+ if cur_py:
367
+ py_blocks.append("\n".join(cur_py))
368
+ cur_py = None
369
+ mode = "python_file"
370
+ continue
371
+ if cur_py:
372
+ py_blocks.append("\n".join(cur_py))
373
+ cur_py = None
374
+ if low == "[__main__]":
375
+ mode = "__main__"
376
+ section_coll = cur
377
+ base_indent = None
378
+ field_stack = []
379
+ continue
380
+ mode = "value" if low != "[rule]" else "rule"
381
+ section_coll = cur
382
+ base_indent = None
383
+ field_stack = []
384
+ continue
385
+ if st.startswith("["):
386
+ if mode == "python":
387
+ if cur_py is None:
388
+ cur_py = []
389
+ cur_py.append(s)
390
+ continue
391
+ raise ValueError(
392
+ "%s: 未知的段头 %r(支持 [value] / [rule] / [python] / [python_file])"
393
+ % (path, st))
394
+ if mode == "python":
395
+ if re.match(r"^[A-Z]\w*\s+type\(", s):
396
+ if cur_py:
397
+ py_blocks.append("\n".join(cur_py))
398
+ cur_py = None
399
+ mode = None
400
+ else:
401
+ if cur_py is None:
402
+ cur_py = []
403
+ cur_py.append(s)
404
+ continue
405
+ if mode == "python_file":
406
+ if re.match(r"^[A-Z]\w*\s+type\(", s):
407
+ mode = None
408
+ else:
409
+ py_file_lines.append(s)
410
+ continue
411
+ if mode == "__main__":
412
+ # 顶格集合声明行结束该段(与 python_file 同规则)
413
+ if re.match(r"^[A-Z]\w*\s+type\(", s):
414
+ mode = None
415
+ # 落到下方段外分支正常处理集合声明
416
+ elif main_expect_active[0]:
417
+ # expect= | 块内容:缩进行原样收进 expect 文本
418
+ main_expect.append(s)
419
+ continue
420
+ elif s.strip() == "expect = |" or s.strip().startswith("expect=|"):
421
+ main_expect_active[0] = True
422
+ continue
423
+ else:
424
+ main_lines.append(s)
425
+ continue
426
+
427
+ indent = len(s) - len(s.lstrip())
428
+ toks = split_tokens(st)
429
+
430
+ if mode is None:
431
+ new_collection(toks, indent)
432
+ continue
433
+
434
+ if mode == "value":
435
+ if section_coll is None:
436
+ continue
437
+ while field_stack and field_stack[-1][0] >= indent:
438
+ field_stack.pop()
439
+ parent_field = field_stack[-1][1] if field_stack else None
440
+ attrs, flags = parse_modifiers(toks)
441
+ f = Field(toks[0], attrs, flags, parent_field)
442
+ if parent_field is None:
443
+ section_coll.fields[f.name] = f
444
+ else:
445
+ parent_field.children[f.name] = f
446
+ section_coll.all_fields[f.path] = f
447
+ field_stack.append((indent, f))
448
+ continue
449
+
450
+ if is_coll_decl(toks):
451
+ flush_pending()
452
+ coll = new_collection(toks, indent)
453
+ section_coll = coll
454
+ base_indent = None
455
+ field_stack = []
456
+ continue
457
+ if pending is not None and base_indent is not None and indent > base_indent:
458
+ pending = pending + st
459
+ continue
460
+ flush_pending()
461
+ if base_indent is None:
462
+ base_indent = indent
463
+ pending = st
464
+
465
+ flush_pending()
466
+ if cur_py:
467
+ py_blocks.append("\n".join(cur_py))
468
+
469
+ for c in colls:
470
+ c.key_fields = [f.path for f in c.all_fields.values()
471
+ if f.is_key and f.parent is None]
472
+
473
+ # ── from 选择:只保留点名顶层集合(子集合随父),其余移除 ──
474
+ merged_names = []
475
+ if importing_from is not None:
476
+ wanted = set(importing_from)
477
+ keep = set()
478
+ for tc in top_colls:
479
+ if tc.name in wanted:
480
+ keep.add(tc.name)
481
+ # 子树全部保留
482
+ todo = [tc]
483
+ while todo:
484
+ cur_c = todo.pop()
485
+ for ch in cur_c.children:
486
+ keep.add(ch.name)
487
+ todo.append(ch)
488
+ missing = wanted - {tc.name for tc in top_colls}
489
+ if missing:
490
+ raise TemplateFileError(
491
+ "%s: import 的集合不存在: %s(可导入: %s)"
492
+ % (path, "、".join(sorted(missing)),
493
+ "、".join(tc.name for tc in top_colls) or "(无)"))
494
+ kept = []
495
+ for c in colls[colls_before:]:
496
+ if c.parent is None or c.name in keep or (
497
+ c.parent is not None and c.parent.name in keep):
498
+ kept.append(c)
499
+ # 按父链精确过滤:只留 wanted 集合与其全部后代
500
+ keep_exact = set()
501
+ todo = []
502
+ for c in colls[colls_before:]:
503
+ if c.parent is None and c.name in wanted:
504
+ keep_exact.add(c.name)
505
+ todo.append(c)
506
+ while todo:
507
+ cur_c = todo.pop()
508
+ for ch in cur_c.children:
509
+ keep_exact.add(ch.name)
510
+ todo.append(ch)
511
+ kept = [c for c in colls[colls_before:] if c.name in keep_exact]
512
+ colls[:] = colls[:colls_before] + kept
513
+ merged_names = [tc.name for tc in top_colls if tc.name in keep_exact]
514
+ else:
515
+ merged_names = [tc.name for tc in top_colls]
516
+
517
+ # ── 同名冲突检测(跨文件顶层集合;已完成加载的文件跳过 → 不重复检测)──
518
+ if tpath in seen_paths["done"]:
519
+ return []
520
+ for nm in merged_names:
521
+ if nm in imported_names and imported_names[nm] != tpath:
522
+ raise TemplateFileError(
523
+ "集合 %s 重名:%s 与 %s 都定义了它(同一解析对象禁止两份定义)"
524
+ % (nm, imported_names[nm], tpath))
525
+ imported_names[nm] = tpath
526
+ seen_paths["on_stack"].discard(tpath)
527
+ seen_paths["done"].add(tpath)
528
+ return merged_names
529
+
530
+
531
+ def parse_template(path, *, main_cfg=None, main_argv=None):
532
+ # main_cfg/main_argv:CLI 解释器模式透传给 [__main__] 段的 cfg/argv
533
+ colls = []
534
+ py_file_lines = [] # [python_file] 段的路径行(声明顺序)
535
+ py_blocks = [] # [python] 段代码块(物理顺序,处理时统一按出现顺序执行)
536
+ main_lines = [] # [__main__] 自测试段代码行
537
+ main_expect = [] # expect= | 块文本行(声明式断言)
538
+ main_expect_active = [False] # 可变容器(递归内层可改)
539
+ seen_paths = {"on_stack": set(), "done": set()}
540
+ imported_names = {}
541
+ _parse_template_file(path, colls, py_file_lines, py_blocks, main_lines, main_expect, main_expect_active,
542
+ seen_paths, imported_names, None)
543
+ tpath = os.path.abspath(path)
544
+
545
+ # ── transform:加载 [python_file] + 执行 [python] ──
546
+ registry = {}
547
+ load_warnings = []
548
+ tpl_dir = os.path.dirname(tpath)
549
+ added_syspath = []
550
+ try:
551
+ for rel in py_file_lines:
552
+ p = os.path.normpath(os.path.join(tpl_dir, rel))
553
+ if not os.path.isfile(p):
554
+ raise TemplateFileError(
555
+ "%s: [python_file] 指向的文件不存在: %s" % (path, p))
556
+ if tpl_dir not in _sys.path:
557
+ _sys.path.insert(0, tpl_dir)
558
+ added_syspath.append(tpl_dir)
559
+ modname = "_np_tf_" + re.sub(r"[^\w]", "_", os.path.splitext(rel)[0])
560
+ spec = _imp_util.spec_from_file_location(modname, p)
561
+ mod = _imp_util.module_from_spec(spec)
562
+ spec.loader.exec_module(mod)
563
+ for sym in dir(mod):
564
+ if not sym.startswith("_") and callable(getattr(mod, sym)):
565
+ registry[sym] = getattr(mod, sym)
566
+ finally:
567
+ for d in added_syspath:
568
+ try:
569
+ _sys.path.remove(d)
570
+ except ValueError:
571
+ pass
572
+
573
+ inline_ns = {"__name__": "_np_inline_%d" % id(colls)}
574
+ for i, code in enumerate(py_blocks):
575
+ try:
576
+ exec(compile(code, "<%s [python] #%d>" % (path, i + 1), "exec"), inline_ns)
577
+ except SyntaxError as e:
578
+ raise TemplateFileError(
579
+ "%s: [python] 段 #%d 语法错误: %s" % (path, i + 1, e)) from None
580
+ for sym in list(inline_ns):
581
+ if not sym.startswith("__") and callable(inline_ns[sym]):
582
+ registry[sym] = inline_ns[sym]
583
+
584
+ pt = _ParsedTemplate(colls, registry, load_warnings)
585
+
586
+ def _run_compat(*args, fields=None):
587
+ """[__main__] 注入的 run:容忍 run(colls, x) 双参习惯。
588
+ args: (x) 或 (colls, x)——colls 恒用引擎加载的 pt,忽略传入值。"""
589
+ data = args[-1] if len(args) >= 2 else (args[0] if args else [])
590
+ return run(data, fields=fields)
591
+
592
+ # [__main__] 专用智能 run:文本/路径/行列表 自适应
593
+ class _ResultDict(dict):
594
+ """解析结果 dict + to_json():[__main__] 段内 res.to_json() 直接得 JSON 文本。"""
595
+
596
+ def to_json(self, indent=2):
597
+ import json as _json
598
+ return _json.dumps(self, ensure_ascii=False, indent=indent)
599
+
600
+ def save(self, path):
601
+ """同时落盘一份(UTF-8,ensure_ascii=False)。"""
602
+ import json as _json
603
+ with open(path, "w", encoding="utf-8") as fh:
604
+ _json.dump(self, fh, ensure_ascii=False, indent=2)
605
+ return path
606
+
607
+ def _wrap(res):
608
+ return _ResultDict(res)
609
+
610
+ _eng_run = globals()["run"] # 模块级引擎 run(本地 def 会遮蔽,绕开)
611
+
612
+ def run(source, fields=None):
613
+ """跑解析:行列表 / 配置文本 / 单个配置文件路径(自适应)。"""
614
+ if isinstance(source, str):
615
+ st = source.strip()
616
+ if ("\n" in st or " " in st or not st):
617
+ return _wrap(_eng_run(pt, source.splitlines(), fields=fields))
618
+ # 无空格无换行 → 可能是文件路径
619
+ full = (st if os.path.isabs(st)
620
+ else os.path.join(os.path.dirname(tpath), st))
621
+ if os.path.isfile(full):
622
+ with open(full, encoding="utf-8", errors="replace") as fh:
623
+ return _wrap(_eng_run(pt, fh.readlines(), fields=fields))
624
+ return _wrap(_eng_run(pt, source, fields=fields))
625
+
626
+ def run_file(path, fields=None):
627
+ """跑解析:path = 配置文件路径(相对模板目录或绝对)。"""
628
+ full = path if os.path.isabs(path) else os.path.join(os.path.dirname(tpath), path)
629
+ with open(full, encoding="utf-8", errors="replace") as fh:
630
+ return _wrap(_eng_run(pt, fh.readlines(), fields=fields))
631
+
632
+ def run_str(text, fields=None):
633
+ """跑解析:text = 配置文本(多行字符串)。"""
634
+ return _wrap(_eng_run(pt, text.splitlines(), fields=fields))
635
+
636
+ def run_files(*paths, fields=None):
637
+ """跑解析:多个配置文件路径,结果按文件名合并进同一批集合。"""
638
+ merged = _ResultDict()
639
+ for pth in paths:
640
+ full = pth if os.path.isabs(pth) else os.path.join(os.path.dirname(tpath), pth)
641
+ with open(full, encoding="utf-8", errors="replace") as fh:
642
+ part = _eng_run(pt, fh.readlines(), fields=fields)
643
+ for k, v in part.items():
644
+ merged.setdefault(k, []).extend(v)
645
+ return merged
646
+
647
+ # ── [__main__] 自测试段:exec 到独立命名空间(脚本模式)──
648
+ # 注入:colls(裸列表)/ pt(模板对象,run 需要其 registry 属性)/
649
+ # run(引擎解析入口)/ here(模板目录)
650
+ # 用户脚本从上到下执行;无异常 = 模板加载即自测通过
651
+ if main_lines:
652
+ code = "\n".join(main_lines)
653
+ import io as _io
654
+ _err = _sys.stderr
655
+ class _SelftestExit(SystemExit):
656
+ """段内 exit(code) 的显式失败信号(由 CLI 捕获转退出码)。"""
657
+ pass
658
+
659
+ def _selftest_print(*a, **k):
660
+ # [__main__] 段的 print 一律走 stderr——stdout 属于解析 JSON 输出
661
+ kw = dict(k)
662
+ kw["file"] = _err
663
+ return print(*a, **kw)
664
+
665
+
666
+ ns = {"__name__": "_np_selftest_%d" % id(pt),
667
+ "colls": pt, "pt": pt,
668
+ "run": _run_compat, "run_file": run_file, "run_str": run_str,
669
+ "run_files": run_files, "run_nq": run_file,
670
+ "print": _selftest_print,
671
+ "engine": _sys.modules[__name__],
672
+ "here": os.path.dirname(tpath),
673
+ "sys": _sys,
674
+ "cfg": main_cfg,
675
+ "argv": list(main_argv or []),}
676
+
677
+ def _summary(results):
678
+ """每集合一行摘要:名称 N 条 | Key 字段。"""
679
+ lines = []
680
+ for coll in pt:
681
+ recs = results.get(coll.name) or []
682
+ keyf = next((f.name for f in coll.fields.values()
683
+ if "Key" in (f.flags or [])), None)
684
+ lines.append("%s %d 条 | %s" % (coll.name, len(recs), keyf or "-"))
685
+ return "\n".join(lines)
686
+ ns["summary"] = _summary
687
+ ns["exit"] = _SelftestExit
688
+ # key= 行是合法 Python 赋值,直接 exec;整段在模板加载期执行一次
689
+ try:
690
+ exec(compile(code, "<%s [__main__]>" % (path,), "exec"), ns)
691
+ except _SelftestExit as e:
692
+ raise TemplateFileError(
693
+ "%s: [__main__] exit(%s) 显式退出"
694
+ % (path, e.code)) from None
695
+ except SyntaxError as e:
696
+ raise TemplateFileError(
697
+ "%s: [__main__] 段语法错误: %s" % (path, e)) from None
698
+ except Exception as e:
699
+ # 段内运行期异常(用户脚本里的 assert / IO 等)——加载期不吞:
700
+ # 显式抛出,让调用方(CLI/exe)看到真实的测试失败
701
+ raise TemplateFileError(
702
+ "%s: [__main__] 自测试失败: %s: %s"
703
+ % (path, type(e).__name__, e)) from None
704
+
705
+ # ── 声明式断言 expect= + 逃生门 check()(自动流程)──
706
+ # 1) 有样例(cfgstr/cfgpath)→ 自动解析一次
707
+ # 2) expect= 逐行断言(路径=期望值;支持 count 与 >/< 比较)
708
+ # 3) check(res) 若定义 → 逃生门
709
+ expect_text = "\n".join(main_expect) if main_expect else ns.get("expect")
710
+ check_fn = ns.get("check")
711
+ if expect_text or check_fn:
712
+ src = ns.get("cfgstr")
713
+ if not src and ns.get("cfgpath"):
714
+ src = ns["cfgpath"]
715
+ if src:
716
+ results = _run_compat(src)
717
+ else:
718
+ raise TemplateFileError(
719
+ "%s: [__main__] 有 expect/check 但没有 cfgstr/cfgpath 样例"
720
+ % path) from None
721
+ if expect_text:
722
+ for lineno, fpath, want, actual in _run_expect(expect_text, results):
723
+ raise TemplateFileError(
724
+ "%s: [__main__] expect 断言失败(L%d)%s: 期望 %r, 实际 %r"
725
+ % (path, lineno, fpath, want, actual)) from None
726
+ if check_fn:
727
+ check_fn(results)
728
+
729
+ return pt
730
+
731
+
732
+ def _get_by_path(results, path):
733
+ """expect 路径求值:Coll[0].Sub[1].Field / Coll.count。
734
+ 返回 (actual, found);找不到时 (None, False)。"""
735
+ import re as _re2
736
+ m = _re2.match(r"^([A-Z]\w*)(.*)$", path)
737
+ if not m:
738
+ return None, False
739
+ coll_name, rest = m.group(1), m.group(2)
740
+ obj = results.get(coll_name)
741
+ if obj is None:
742
+ return None, False
743
+ if rest == ".count":
744
+ return len(obj), True
745
+ segs = _re2.findall(r"\[(\d+)\]|\.(\w+)", rest)
746
+ cur = obj
747
+ for idx, key in segs:
748
+ if idx:
749
+ i = int(idx)
750
+ if not isinstance(cur, list) or i >= len(cur):
751
+ return None, False
752
+ cur = cur[i]
753
+ else:
754
+ if isinstance(cur, dict):
755
+ if key not in cur:
756
+ return None, False
757
+ cur = cur[key]
758
+ elif isinstance(cur, list):
759
+ vals = [x.get(key) for x in cur if isinstance(x, dict)]
760
+ if not vals:
761
+ return None, False
762
+ cur = vals if len(vals) > 1 else vals[0]
763
+ else:
764
+ return None, False
765
+ return cur, True
766
+
767
+
768
+ def _run_expect(expect_text, results):
769
+ """expect= 文本 → [(行号, 路径, 期望, 实际)] 失败列表。"""
770
+ failures = []
771
+ op_map = {">=": lambda a, b: a >= b, "<=": lambda a, b: a <= b,
772
+ ">": lambda a, b: a > b, "<": lambda a, b: a < b}
773
+ for lineno, raw in enumerate(expect_text.splitlines(), 1):
774
+ line = raw.strip()
775
+ if not line or line.startswith("#"):
776
+ continue
777
+ for op, cmp_fn in op_map.items():
778
+ if op in line:
779
+ fpath, want_s = line.split(op, 1)
780
+ actual, found = _get_by_path(results, fpath.strip())
781
+ if not found:
782
+ failures.append((lineno, fpath.strip(), op + " " + want_s, "<缺失>"))
783
+ elif not cmp_fn(actual, float(want_s)):
784
+ failures.append((lineno, fpath.strip(), op + " " + want_s, actual))
785
+ break
786
+ else:
787
+ if "=" in line:
788
+ fpath, want = line.split("=", 1)
789
+ fpath, want = fpath.strip(), want.strip()
790
+ actual, found = _get_by_path(results, fpath)
791
+ actual_s = "<缺失>" if not found else str(actual)
792
+ if not found or actual_s != want:
793
+ failures.append((lineno, fpath, want, actual_s))
794
+ return failures
795
+
796
+
797
+ class _ParsedTemplate(list):
798
+ """parse_template 的返回值:兼容 list(历史用法),额外携带 transform 注册表。"""
799
+
800
+ def __init__(self, colls, registry, warnings, selftest=None):
801
+ super().__init__(colls)
802
+ self.registry = registry
803
+ self.transform_warnings = warnings
804
+ self.selftest = selftest
805
+
806
+
807
+ class TemplateFileError(Exception):
808
+ """[python_file] 缺失 / [python] 语法错误等模板级致命问题。"""
809
+
810
+
811
+ # ── 规则编译 ──────────────────────────────────────────
812
+ def compile_rule(rule, coll):
813
+ """把 ${字段} 展开成命名捕获组。
814
+
815
+ 返回 CompiledRule;字段未声明时抛 KeyError(由 lint 汇总)。
816
+ """
817
+ fields = coll.all_fields
818
+ group_paths = OrderedDict()
819
+ path_groups = OrderedDict()
820
+ seen = set()
821
+
822
+ def sub(m):
823
+ ref = m.group(1)
824
+ fld = fields.get(ref)
825
+ if fld is None:
826
+ raise KeyError(ref)
827
+ group = fld.path.replace(".", "__")
828
+ if group in seen and group_paths.get(group) != fld.path:
829
+ raise KeyError("组名冲突: " + group)
830
+ group_paths[group] = fld.path
831
+ path_groups[fld.path] = group
832
+ if group in seen:
833
+ return f"(?P={group})" # 重复引用 → 回溯引用
834
+ seen.add(group)
835
+ return f"(?P<{group}>{fld.reg})"
836
+
837
+ try:
838
+ pattern = re.sub(r"\$\{([A-Za-z_][\w.]*)\}", sub, rule.pattern)
839
+ except KeyError as e:
840
+ raise KeyError(f"{coll.name}: 字段 {e.args[0]} 未声明") from None
841
+
842
+ # 手写的命名组也允许带点:`(?P<Sub.C>...)` 是字段路径的自然写法,
843
+ # 但 Python re 的组名只能是标识符,点会直接 PatternError。
844
+ # 这里统一把组名里的点换成 `__`,并在 group_paths 里登记回原路径,
845
+ # 这样 `_apply` 写回记录时仍然落在 Sub.C 上。
846
+ def norm_group(m):
847
+ defined, referenced = m.group(1), m.group(2)
848
+ name = defined if defined is not None else referenced
849
+ if "." not in name:
850
+ return m.group(0)
851
+ flat = name.replace(".", "__")
852
+ group_paths.setdefault(flat, name)
853
+ path_groups.setdefault(name, flat)
854
+ return f"(?P<{flat}>" if defined is not None else f"(?P={flat})"
855
+
856
+ pattern = re.sub(r"\(\?P(?:<([^>=]+)>|=([\w.]+))", norm_group, pattern)
857
+
858
+ # 尾部语义(2026-11-24 定案「匹配即提取」):放宽机制已删除。
859
+ # · 规则带 $ → 严格整行匹配(短行类命令:pim sm / bas / statistic enable)
860
+ # · 规则不带 $ → 前缀匹配提取(长行/带残余参数:qos-profile X inbound identifier none)
861
+ # 两种写法并存,作者按命令形态自选;$ 是作者的原生锚定语法,引擎不改写。
862
+ # 宽规则务必排在精确规则之后(lint 会对前缀抢位告警)。
863
+
864
+ return CompiledRule(re.compile(pattern), group_paths, path_groups, rule.target)
865
+
866
+
867
+ # ── 值处理 ────────────────────────────────────────────
868
+ def parse_literal(s):
869
+ """常量字面量 → Python 值。"""
870
+ s = s.strip()
871
+ if len(s) >= 2 and s[0] == s[-1] and s[0] in "\"'":
872
+ return s[1:-1]
873
+ low = s.lower()
874
+ if low in ("true", "yes"):
875
+ return True
876
+ if low in ("false", "no"):
877
+ return False
878
+ if low in ("null", "none"):
879
+ return None
880
+ if re.match(r"^-?\d+$", s):
881
+ return int(s)
882
+ if re.match(r"^-?\d+\.\d+$", s):
883
+ return float(s)
884
+ return s
885
+
886
+
887
+ def convert(value, fld):
888
+ """按字段声明的类型转换值。"""
889
+ if fld is None or value is None:
890
+ return value
891
+ if fld.is_secret():
892
+ # 遮蔽发生在 convert 之前:secret 字段的声明类型被强制视为 str,
893
+ # 否则掩码串会被 int/float 转换搞坏(转换失败回退原值 → 掩码失效)。
894
+ return value
895
+ t = fld.type
896
+ try:
897
+ if t == "int":
898
+ return int(value)
899
+ if t == "float":
900
+ return float(value)
901
+ if t == "bool":
902
+ if isinstance(value, bool):
903
+ return value
904
+ low = str(value).strip().lower()
905
+ if low in ("true", "yes", "on", "1"):
906
+ return True
907
+ if low in ("false", "no", "off", "0"):
908
+ return False
909
+ return value
910
+ if t in ("str", "dict", "list"):
911
+ return value if isinstance(value, str) else str(value)
912
+ except (TypeError, ValueError):
913
+ return value # 转不了就原样保留,不丢数据
914
+ return value
915
+
916
+
917
+ def apply_func(value, fld, registry, record, warnings, coll_name):
918
+ """convert 之后执行字段声明的 func= transform。
919
+
920
+ 语义(design.md §2.3):
921
+ - registry 无此名字 → 保持原值(lint 负责报"引用不存在",这里不炸)
922
+ - 返回 None → 保持原值
923
+ - 抛异常 → 捕获、保留原值、按 (字段路径, 异常摘要) 去重记警告
924
+ """
925
+ if fld is None or fld.func is None or value is None:
926
+ return value
927
+ fn = registry.get(fld.func)
928
+ if fn is None:
929
+ return value
930
+ try:
931
+ out = fn(value, record)
932
+ except Exception as e:
933
+ key = (fld.path, "%s: %s" % (type(e).__name__, e))
934
+ if key not in _RUNTIME_WARN_SEEN:
935
+ _RUNTIME_WARN_SEEN.add(key)
936
+ warnings.append("[transform] %s.%s: 函数 %s 执行失败 %s: %s(保留原值 %r)"
937
+ % (coll_name, fld.path, fld.func,
938
+ type(e).__name__, e, value))
939
+ return value
940
+ if out is None:
941
+ return value
942
+ return out
943
+
944
+
945
+ def get_path(obj, path):
946
+ cur = obj
947
+ for p in path.split("."):
948
+ if not isinstance(cur, dict) or p not in cur:
949
+ return None
950
+ cur = cur[p]
951
+ return cur
952
+
953
+
954
+ def set_path(obj, segs, value):
955
+ for p in segs[:-1]:
956
+ nxt = obj.get(p)
957
+ if not isinstance(nxt, dict):
958
+ nxt = {}
959
+ obj[p] = nxt
960
+ obj = nxt
961
+ obj[segs[-1]] = value
962
+
963
+
964
+ def apply_writes(rec, writes, coll, registry=None, tw=None, coll_name=""):
965
+ """把 (字段路径, 值) 写进记录。
966
+
967
+ 同一路径首段若是 type(list) 的字段 → 追加一个新元素;
968
+ 否则直接覆盖。同一批 writes 里首段相同的归到同一个元素。
969
+
970
+ ★ 脱敏点:遮蔽发生在 convert() **之前**(design.md D6)。
971
+ 值一旦进入记录对象就已经是掩码 → rec / children / last 缓存 / 异常栈里都没有明文。
972
+ """
973
+ groups = OrderedDict()
974
+ for path, value in writes:
975
+ groups.setdefault(path.split(".")[0], []).append((path, value))
976
+
977
+ for p0, items in groups.items():
978
+ fld = coll.all_fields.get(p0)
979
+ if fld is not None and fld.type == "list":
980
+ elem = {}
981
+ for path, value in items:
982
+ segs = path.split(".")[1:]
983
+ if not segs:
984
+ continue
985
+ tf = coll.all_fields.get(path)
986
+ if tf is not None and tf.type_conflict:
987
+ continue # type 声明冲突 → 该字段按缺字段处理,不产出
988
+ cv = convert(mask_value(value, tf, CONFIG.value, CONFIG.heuristic), tf)
989
+ cv = apply_func(cv, tf, registry, rec, tw if tw is not None else [], coll_name)
990
+ set_path(elem, segs, cv)
991
+ bucket = rec.setdefault(p0, [])
992
+ if isinstance(bucket, dict): # 容错:之前被写成 dict
993
+ bucket = [bucket]
994
+ rec[p0] = bucket
995
+ bucket.append(elem)
996
+ else:
997
+ # 首段是 dict,但**内部可能有 list 字段**(如
998
+ # Ipv4Family.VpnTargets)。裸 set_path 会把 list 字段反复覆盖成
999
+ # 一个 dict —— 三条 vpn-target 只剩最后一条。
1000
+ #
1001
+ # 语义与顶层 list 保持一致:同一次写入(= 同一行命令)里挂在
1002
+ # 同一个 list 前缀下的字段,归到**同一个新元素**;不同行的写入
1003
+ # 各追加一个元素。
1004
+ list_groups = OrderedDict()
1005
+ for path, value in items:
1006
+ segs = path.split(".")
1007
+ tf = coll.all_fields.get(path)
1008
+ if tf is not None and tf.type_conflict:
1009
+ continue # type 声明冲突 → 该字段按缺字段处理,不产出
1010
+ converted = convert(
1011
+ mask_value(value, tf, CONFIG.value, CONFIG.heuristic), tf)
1012
+ converted = apply_func(converted, tf, registry, rec, tw if tw is not None else [], coll_name)
1013
+ lpre = _list_prefix(rec, segs, coll)
1014
+ if lpre is None:
1015
+ set_path(rec, segs, converted)
1016
+ else:
1017
+ key = tuple(lpre)
1018
+ list_groups.setdefault(
1019
+ key, []).append((segs[len(lpre):], converted))
1020
+ for lkey, sub in list_groups.items():
1021
+ elem = {}
1022
+ for segs, converted in sub:
1023
+ set_path(elem, segs, converted)
1024
+ _append_to_list_path(rec, list(lkey), elem)
1025
+
1026
+
1027
+ def _list_prefix(rec, segs, coll):
1028
+ """segs 路径里**第一个指向 type(list) 字段**的前缀(含该字段本身)。
1029
+
1030
+ 返回 None 表示这条路径一路都是 dict/标量,不涉及 list。
1031
+ """
1032
+ for i in range(1, len(segs)):
1033
+ fpath = ".".join(segs[:i + 1])
1034
+ fld = coll.all_fields.get(fpath)
1035
+ if fld is not None and fld.type == "list":
1036
+ return segs[:i + 1]
1037
+ return None
1038
+
1039
+
1040
+ def _append_to_list_path(rec, lpre, elem):
1041
+ """沿 dict 路径走到 lpre 的父级,把 elem 追加到该 list 字段。"""
1042
+ cur = rec
1043
+ for p in lpre[:-1]:
1044
+ nxt = cur.get(p)
1045
+ if not isinstance(nxt, dict):
1046
+ nxt = {}
1047
+ cur[p] = nxt
1048
+ cur = nxt
1049
+ bucket = cur.get(lpre[-1])
1050
+ if isinstance(bucket, dict): # 容错:之前被写成 dict
1051
+ bucket = [bucket]
1052
+ cur[lpre[-1]] = bucket
1053
+ elif bucket is None:
1054
+ bucket = []
1055
+ cur[lpre[-1]] = bucket
1056
+ bucket.append(elem)
1057
+
1058
+
1059
+ # ── 目标解析 ──────────────────────────────────────────
1060
+ def parse_target(target):
1061
+ """-> 后面内容的两种形态:
1062
+
1063
+ ('members', base, [成员...]) -> 集合名{字段1,字段2=常量}
1064
+ ('assigns', [(名字, 值|None)]) -> 字段=常量 / 字段 / 路径.字段=常量
1065
+ """
1066
+ t = target.strip()
1067
+ if "{" in t:
1068
+ m = re.match(r"^([\w.]+)\{(.*)\}$", t, re.S)
1069
+ if not m:
1070
+ raise ValueError("目标写法无法解析: " + target)
1071
+ base = m.group(1)
1072
+ members = [x.strip() for x in m.group(2).split(",") if x.strip()]
1073
+ return "members", base, members
1074
+ items = []
1075
+ for part in t.split(","):
1076
+ part = part.strip()
1077
+ if not part:
1078
+ continue
1079
+ name, eq, val = part.partition("=")
1080
+ items.append((name.strip(), parse_literal(val.strip()) if eq else None))
1081
+ return "assigns", items, None
1082
+
1083
+
1084
+ # ── 引擎 ──────────────────────────────────────────────
1085
+ class Frame:
1086
+ """栈上的一层"""
1087
+ __slots__ = ("coll", "rec", "children")
1088
+
1089
+ def __init__(self, coll):
1090
+ self.coll = coll
1091
+ self.rec = {}
1092
+ self.children = OrderedDict() # 子集合名 -> [元素]
1093
+
1094
+
1095
+ def check_required(rec, coll):
1096
+ """记录是否满足所有 option(Required) 字段。"""
1097
+ for fld in coll.all_fields.values():
1098
+ if not fld.required:
1099
+ continue
1100
+ v = get_path(rec, fld.path)
1101
+ if v is None or v == "":
1102
+ return False
1103
+ return True
1104
+
1105
+
1106
+ def merge_by_key(elems, coll):
1107
+ """Key 聚合:Key 相同的子记录合并成一个。
1108
+
1109
+ 键 = 所有 option(Key) 字段值的元组:
1110
+ · 全部键字段都为空 → 记录无法识别 → 丢弃
1111
+ · 部分键字段为空(可选键,如路由的 VPN 实例)→ 空值参与键计算,不合并
1112
+ """
1113
+ if coll is None or not coll.key_fields:
1114
+ return elems
1115
+ merged, index = [], {}
1116
+ for el in elems:
1117
+ vals = tuple(get_path(el, kf) for kf in coll.key_fields)
1118
+ if all(v is None or v == "" for v in vals):
1119
+ continue # 键全空 → 丢弃
1120
+ if vals in index:
1121
+ for kk, vv in el.items():
1122
+ index[vals].setdefault(kk, vv) # 后到的补空缺,不覆盖
1123
+ else:
1124
+ index[vals] = el
1125
+ merged.append(el)
1126
+ return merged
1127
+
1128
+
1129
+ def derive_funcs(rec, coll, registry, tw, coll_name):
1130
+ """对『声明了 func 但记录里没有值』的字段补跑派生(value=None 传入)。
1131
+
1132
+ 典型场景:Type 由 func=iface_type(Name) 从同记录的 Name 派生——
1133
+ Type 在 [rule] 里没有对应捕获行,正常流程永远不会执行到它。
1134
+ 规则:只有当函数**返回非 None** 才写入(函数自己决定缺依据时返回 None)。
1135
+ """
1136
+ for fld in coll.all_fields.values():
1137
+ if fld.func is None or fld.type == "list":
1138
+ continue
1139
+ if get_path(rec, fld.path) is not None:
1140
+ continue
1141
+ fn = registry.get(fld.func)
1142
+ if fn is None:
1143
+ continue
1144
+ segs = fld.path.split(".")
1145
+ if len(segs) > 1 and get_path(rec, ".".join(segs[:-1])) is None:
1146
+ continue # 父对象不存在 → 不凭空产出
1147
+ try:
1148
+ out = fn(None, rec)
1149
+ except Exception as e:
1150
+ key = (fld.path, "%s: %s" % (type(e).__name__, e))
1151
+ if key not in _RUNTIME_WARN_SEEN:
1152
+ _RUNTIME_WARN_SEEN.add(key)
1153
+ tw.append("[transform] %s.%s: 派生 %s 执行失败 %s: %s(字段留空)"
1154
+ % (coll_name, fld.path, fld.func,
1155
+ type(e).__name__, e))
1156
+ continue
1157
+ if out is not None:
1158
+ set_path(rec, segs, out)
1159
+
1160
+
1161
+ def apply_defaults(rec, coll):
1162
+ """填充声明了 default 但没抓到值的字段。
1163
+
1164
+ ⚠️ 嵌套字段(如 Bas.ArpTrigger)只在**父对象已经存在**时才填。
1165
+ 否则一个根本没有 bas 块的接口也会凭空长出 `Bas: {ArpTrigger: true}` ——
1166
+ 「没出现」和「出现但取默认」是两件事,不能混。
1167
+ """
1168
+ for fld in coll.all_fields.values():
1169
+ if fld.default is None or fld.type == "list":
1170
+ continue
1171
+ if get_path(rec, fld.path) is not None:
1172
+ continue
1173
+ segs = fld.path.split(".")
1174
+ if len(segs) > 1 and get_path(rec, ".".join(segs[:-1])) is None:
1175
+ continue # 父对象不存在 → 整个子结构都不产出
1176
+ val = parse_literal(fld.default)
1177
+ if fld.is_secret():
1178
+ val = mask_value(val, fld, CONFIG.value, CONFIG.heuristic)
1179
+ set_path(rec, segs, convert(val, fld))
1180
+
1181
+
1182
+ def run(colls, lines, trace=None, fields=None):
1183
+ """trace: 可选列表,传入后记录每一行的匹配情况 (行号, 原始行, 命中集合名或 None)。
1184
+
1185
+ 这是 lint「命令覆盖率」统计的数据来源——必须来自真实匹配过程,
1186
+ 事后用正则重测会把作用域外的同名命令误判成已覆盖。
1187
+
1188
+ 每次调用会把脱敏统计(masking.STATS)复位 → 读完即"本次运行"的统计。
1189
+
1190
+ transform 警告收集在 colls.transform_warnings(每次 run 覆盖)。
1191
+
1192
+ fields: 可选字段白名单(输出层裁剪,解析始终全量)。
1193
+ 形态 1 dict: {"Interfaces": {"Name","Type","IpAddress"}, "Bgp": None}
1194
+ 值 None/空集合 = 保留该集合全部字段
1195
+ 形态 2 list: ["Interfaces.Name", "Interfaces.Type", "Bgp"](点路径前缀)
1196
+ 语义:未列出的集合 → 整个不输出;列出的集合未列字段 → 裁掉;
1197
+ Key 字段自动保留(记录身份不能丢)。
1198
+ """
1199
+ STATS.reset()
1200
+ registry = getattr(colls, "registry", {})
1201
+ _RUNTIME_WARN_SEEN.clear()
1202
+ tw = []
1203
+ colls.transform_warnings = tw
1204
+ ctx = {"registry": registry, "tw": tw}
1205
+ root = Coll("__root__", {}, set(), -1, None)
1206
+ compiled = {}
1207
+ for c in colls:
1208
+ items = []
1209
+ for r in c.rules:
1210
+ try:
1211
+ items.append(compile_rule(r, c))
1212
+ except KeyError:
1213
+ raise
1214
+ compiled[c.name] = items
1215
+
1216
+ stack = [Frame(root)]
1217
+ frame_of = {}
1218
+ # 无 start 的集合 = 栈底常驻层(规则始终兜底匹配)
1219
+ for c in colls:
1220
+ if not c.start:
1221
+ fr = Frame(c)
1222
+ stack.insert(1, fr)
1223
+ frame_of[c.name] = fr
1224
+
1225
+ results = OrderedDict()
1226
+ last = {}
1227
+ coll_by_name = {c.name: c for c in colls}
1228
+
1229
+ def commit(fr):
1230
+ """提交一层的当前记录:子层元素合并进来,存到父帧或顶层"""
1231
+ coll = fr.coll
1232
+ if coll is root:
1233
+ return
1234
+ for cname, elems in fr.children.items():
1235
+ if not elems:
1236
+ continue
1237
+ cdef = coll_by_name.get(cname)
1238
+ elems = [e for e in elems if check_required(e, cdef)]
1239
+ elems = merge_by_key(elems, cdef)
1240
+ if not elems:
1241
+ continue
1242
+ # 折叠条件看**子集合自己**的 type,不是父集合的。
1243
+ # 写错成 coll.type 时:Interfaces 是 list → 永远不折叠,
1244
+ # 声明为 type(dict) 的 Bas 也会被输出成 [{...}](实测 10,462 条全是 list1)。
1245
+ as_dict = cdef is not None and cdef.type == "dict" and len(elems) == 1
1246
+ fr.rec[cname] = elems[0] if as_dict else elems
1247
+ apply_defaults(fr.rec, coll)
1248
+ derive_funcs(fr.rec, coll, registry, tw, coll.name)
1249
+ if not check_required(fr.rec, coll):
1250
+ return
1251
+ parent = frame_of.get(coll.parent.name) if coll.parent else None
1252
+ if parent is None:
1253
+ results.setdefault(coll.name, []).append(fr.rec)
1254
+ else:
1255
+ parent.children.setdefault(coll.name, []).append(fr.rec)
1256
+
1257
+ for no, raw in enumerate(lines, 1):
1258
+ line = raw.rstrip("\n").rstrip("\r")
1259
+ if not line.strip():
1260
+ continue
1261
+ st = line.strip()
1262
+ # 裸 `#` / `!` / `$` 是**块分隔符**,不是注释:华为全量配置 100% 用 `#`
1263
+ # (222 万行抽样:`#` 249282 次、`!` 0 次);中兴 M6000 用 `$`
1264
+ # (64 台实测每台数百处,`$` 还带缩进变体:顶格关接口、缩进 2 关子块)。
1265
+ # 它必须参与 end 出栈,否则模板声明的 end(^#$) / end(^\s*\$\s*$) 永远不生效
1266
+ # —— 分层级会一路挂着不收起,后续无 start 的块(如 aaa)里的
1267
+ # description 会被归到上一个接口上。
1268
+ if len(st) <= 2 and st[:1] in ("#", "!", "$"):
1269
+ # 分隔符的层级语义分两档:
1270
+ # · 集合声明了 end_indent(k) → 只有「恰好 k 个前导空格」的 # 才关它(opt-in,新语义)
1271
+ # · 未声明 → 任意 # 都能关(旧行为,保证老模板与既有 fixture 不回归)
1272
+ # 为什么要分层:华为配置的 # 自带缩进,1 个空格 = 只关 1 层子视图。
1273
+ # 旧行为「一个 # 关整条嵌套块」会让 `bas` 块内的 # 连接口一起关掉。
1274
+ sep_indent = len(line) - len(line.lstrip())
1275
+ while len(stack) > 1:
1276
+ stop = None
1277
+ for depth in range(len(stack) - 1, 0, -1):
1278
+ fr = stack[depth]
1279
+ if not fr.coll.end_re:
1280
+ continue
1281
+ want = getattr(fr.coll, "end_indent", None)
1282
+ if want is not None and sep_indent != want:
1283
+ continue # 缩进对不上,这个 # 关不掉这一层
1284
+ if fr.coll.end_re.search(line):
1285
+ stop = depth
1286
+ break
1287
+ if stop is None:
1288
+ break
1289
+ while len(stack) > stop + 1:
1290
+ fr = stack.pop()
1291
+ commit(fr)
1292
+ frame_of.pop(fr.coll.name, None)
1293
+ fr = stack.pop()
1294
+ commit(fr)
1295
+ frame_of.pop(fr.coll.name, None)
1296
+ if trace is not None:
1297
+ trace.append((no, line, None, [f.coll.name for f in stack]))
1298
+ continue
1299
+ if st.startswith("#"):
1300
+ continue # 非裸 `#` 的长行仍按注释处理
1301
+
1302
+ # ① 找命中的 start:从栈顶向下,每层先看自己、再看子集合;
1303
+ # 最后看尚未激活的顶层集合
1304
+ hit = None
1305
+ for depth in range(len(stack) - 1, -1, -1):
1306
+ fr = stack[depth]
1307
+ if fr.coll.start_re and fr.coll.start_re.search(line):
1308
+ hit = ("self", fr.coll, depth)
1309
+ break
1310
+ for child in fr.coll.children:
1311
+ if child.start_re and child.start_re.search(line):
1312
+ hit = ("child", child, depth)
1313
+ break
1314
+ if hit:
1315
+ break
1316
+ if hit is None:
1317
+ for c in colls:
1318
+ if c.parent is None and c.start_re and c.start_re.search(line):
1319
+ hit = ("new", c, -1)
1320
+ break
1321
+
1322
+ hit_name = None
1323
+ if hit is not None:
1324
+ kind, coll, depth = hit
1325
+ # start 命中即算「本行已被消费」:`bas` / `interface xxx` 这类视图入口行
1326
+ # 由 start 语义吞掉,集合自己的 [rule] 里通常**没有**对应规则。
1327
+ # 若把 hit_name 绑在 _apply 的返回值上,这些行会被 trace 记成未命中。
1328
+ if kind == "self":
1329
+ fr = stack[depth]
1330
+ while len(stack) > depth + 1:
1331
+ commit(stack.pop())
1332
+ commit(fr)
1333
+ fr.rec = {}
1334
+ fr.children = OrderedDict()
1335
+ _apply(fr, line, compiled, last, from_start=True, ctx=ctx)
1336
+ hit_name = fr.coll.name
1337
+ elif kind == "child":
1338
+ idx = next((i for i, f in enumerate(stack) if f.coll is coll), None)
1339
+ if idx is None:
1340
+ fr = Frame(coll)
1341
+ stack.append(fr)
1342
+ else:
1343
+ while len(stack) > idx + 1:
1344
+ commit(stack.pop())
1345
+ commit(stack[idx])
1346
+ stack[idx].rec = {}
1347
+ stack[idx].children = OrderedDict()
1348
+ fr = stack[idx]
1349
+ frame_of[coll.name] = fr
1350
+ _apply(fr, line, compiled, last, from_start=True, ctx=ctx)
1351
+ hit_name = fr.coll.name
1352
+ else: # new
1353
+ fr = Frame(coll)
1354
+ stack.append(fr)
1355
+ frame_of[coll.name] = fr
1356
+ _apply(fr, line, compiled, last, from_start=True, ctx=ctx)
1357
+ hit_name = fr.coll.name
1358
+ if trace is not None:
1359
+ trace.append((no, line, hit_name, [f.coll.name for f in stack]))
1360
+ continue
1361
+
1362
+ # ② end 命中 → 出栈:从栈顶向下找「第一个 end 能匹配」的层,收起它连同其上所有子层。
1363
+ # 只收最内层(方案 X),不一路收到底 —— 一路收到底是分隔符 `#` 的专属语义,
1364
+ # 普通 end 命令(如 Nokia 的 exit)应该只关当前最内层块。
1365
+ # 为什么不能只查栈顶:Nokia 的 interface 块内常有 ipv6/egress 等子块,
1366
+ # 栈顶是子集合时父集合的 end 会匹配不到,导致 exit 永远关不掉接口块。
1367
+ stop = None
1368
+ for depth in range(len(stack) - 1, 0, -1):
1369
+ if stack[depth].coll.end_re and stack[depth].coll.end_re.search(line):
1370
+ stop = depth
1371
+ break
1372
+ if stop is not None:
1373
+ while len(stack) > stop + 1:
1374
+ fr = stack.pop()
1375
+ commit(fr)
1376
+ frame_of.pop(fr.coll.name, None)
1377
+ fr = stack.pop()
1378
+ commit(fr)
1379
+ frame_of.pop(fr.coll.name, None)
1380
+
1381
+ # ③ 栈顶向下匹配;不匹配继续父层
1382
+ for depth in range(len(stack) - 1, -1, -1):
1383
+ if _apply(stack[depth], line, compiled, last, ctx=ctx):
1384
+ hit_name = stack[depth].coll.name
1385
+ break
1386
+ if trace is not None:
1387
+ trace.append((no, line, hit_name, [f.coll.name for f in stack]))
1388
+
1389
+ while stack:
1390
+ commit(stack.pop())
1391
+
1392
+ # 顶层集合不做 Key 合并:Key 聚合的语义是「同一父元素下的子记录合并」,
1393
+ # 顶层集合没有父元素,重名对象(如 Nokia 不同 router 下的同名接口)必须各留一条。
1394
+ if fields:
1395
+ return _filter_fields(results, fields, coll_by_name)
1396
+ return results
1397
+
1398
+
1399
+ def _filter_fields(results, fields, coll_by_name):
1400
+ """字段白名单过滤(输出层)。解析始终全量,这里只裁剪视图。
1401
+
1402
+ fields 归一化为 {集合名: 允许字段名集合 or None(全部)}。
1403
+ Key 字段自动保留;子集合字段用 点路径(IpAddress.Address)声明。
1404
+ """
1405
+ # 归一化
1406
+ norm = {}
1407
+ if isinstance(fields, dict):
1408
+ for coll_name, flds in fields.items():
1409
+ norm[coll_name] = set(flds) if flds else None
1410
+ else: # list:点路径前缀
1411
+ for item in fields:
1412
+ c, _, f = item.partition(".")
1413
+ if c not in norm:
1414
+ norm[c] = None
1415
+ if f:
1416
+ if norm[c] is None:
1417
+ norm[c] = set()
1418
+ norm[c].add(f)
1419
+
1420
+ # 引用了不存在的集合名 → 报错并列出可用名(拼错静默吞数据比报错更糟)
1421
+ known = set(coll_by_name.keys())
1422
+ unknown = set(norm.keys()) - known
1423
+ if unknown:
1424
+ raise ValueError(
1425
+ "fields 引用了不存在的集合: %s(可用集合: %s)"
1426
+ % ("、".join(sorted(unknown)), "、".join(sorted(known))))
1427
+
1428
+ out = {}
1429
+ for cname, records in results.items():
1430
+ allowed = norm.get(cname, "__absent__")
1431
+ if allowed == "__absent__":
1432
+ continue # 未列出的集合 → 不输出
1433
+ cdef = coll_by_name.get(cname)
1434
+ if allowed is None or cdef is None:
1435
+ out[cname] = records
1436
+ continue
1437
+ # Key 字段自动并入
1438
+ keep = set(allowed)
1439
+ for kf in (cdef.key_fields or []):
1440
+ keep.add(kf.split(".")[-1])
1441
+ def prune(rec):
1442
+ return {k: v for k, v in rec.items()
1443
+ if k in keep or (cdef.all_fields.get(k) is not None
1444
+ and "." not in k and k not in keep
1445
+ and False)}
1446
+ def prune_deep(obj, prefix=""):
1447
+ row = {}
1448
+ for k, v in obj.items():
1449
+ path = (prefix + "." + k) if prefix else k
1450
+ fld = cdef.all_fields.get(path)
1451
+ # 子集合/视图(dict 或 list 容器字段)被点名 → 整棵子树保留
1452
+ if prefix == "" and k in keep and isinstance(v, (list, dict)):
1453
+ row[k] = v
1454
+ continue
1455
+ if isinstance(v, dict):
1456
+ sub = prune_deep(v, path)
1457
+ if sub:
1458
+ row[k] = sub
1459
+ elif isinstance(v, list):
1460
+ rows = []
1461
+ for el in v:
1462
+ if isinstance(el, dict):
1463
+ sub = prune_deep(el, path)
1464
+ if sub:
1465
+ rows.append(sub)
1466
+ else:
1467
+ if path.split(".")[-1] in keep or (
1468
+ fld is not None and fld.is_key):
1469
+ rows.append(el)
1470
+ if rows:
1471
+ row[k] = rows
1472
+ else:
1473
+ if k in keep or (fld is not None and fld.is_key):
1474
+ row[k] = v
1475
+ return row
1476
+ pruned = []
1477
+ for rec in records:
1478
+ pruned.append(prune_deep(rec))
1479
+ out[cname] = pruned
1480
+ return out
1481
+
1482
+
1483
+ def _apply(fr, line, compiled, last, from_start=False, ctx=None):
1484
+ """用 fr 的规则匹配 line。命中返回 True。
1485
+
1486
+ from_start=True 表示这一行是刚命中 start 的视图入口行(如 `bas`)。
1487
+ 此时**不做缩进校验**:indent(n) 约束的是「本集合的规则只在缩进 n 生效」,
1488
+ 而视图入口行本身属于父层级(`bas` 在缩进 1,而 BasView 正文在缩进 2)。
1489
+ 把两者混在一起会让 bas 的 start 命中后立刻被缩进校验打回。
1490
+
1491
+ ctx: run() 传入的 {'registry': ..., 'tw': [...]},transform 用。
1492
+ """
1493
+ ctx = ctx or {}
1494
+ registry = ctx.get("registry", {})
1495
+ tw = ctx.get("tw") if ctx.get("tw") is not None else []
1496
+ coll = fr.coll
1497
+ if coll.name not in compiled:
1498
+ return False
1499
+ # indent(n):本集合只在自己那一层缩进上生效。
1500
+ # 华为配置里 `user-vlan`(缩进 1)和 `access-type`(缩进 2)都可能出现在
1501
+ # 同一个接口块下,靠这条卡住才不会被上一层的规则误收。
1502
+ if not from_start:
1503
+ anchor = getattr(coll, "indent_re", None)
1504
+ if anchor is not None and not anchor.match(line):
1505
+ return False
1506
+ for cr in compiled[coll.name]:
1507
+ m = cr.rx.match(line)
1508
+ if not m:
1509
+ continue
1510
+ gd = m.groupdict()
1511
+ # ★ 脱敏点(写入时):捕获到的值在这里就变成掩码,
1512
+ # 之后 writes / last 缓存 / 记录对象里都不再有明文。
1513
+ # last 缓存必须存遮蔽后的值 —— 否则 inherit= 会把明文复制到普通字段,绕过遮蔽。
1514
+ masked = OrderedDict()
1515
+ for g, v in gd.items():
1516
+ if v is None:
1517
+ continue
1518
+ path = cr.group_paths.get(g, g)
1519
+ masked[path] = mask_value(v, coll.all_fields.get(path),
1520
+ CONFIG.value, CONFIG.heuristic)
1521
+ writes = list(masked.items())
1522
+ for path, mv in writes:
1523
+ last[(coll.name, path)] = mv
1524
+
1525
+ # inherit 补齐
1526
+ for fld in coll.all_fields.values():
1527
+ if not fld.inherit:
1528
+ continue
1529
+ if any(p == fld.path for p, _ in writes):
1530
+ continue
1531
+ src_coll, _, src_field = fld.inherit.partition(".")
1532
+ if (src_coll, src_field) in last:
1533
+ writes.append((fld.path, last[(src_coll, src_field)]))
1534
+
1535
+ target = cr.target
1536
+ if target is None:
1537
+ # 省略 -> :全部捕获组写进当前记录
1538
+ apply_writes(fr.rec, writes, coll, registry, tw, coll.name)
1539
+ return True
1540
+
1541
+ # 多 target:'-> A{...};B{...}' 用 ';' 分割,每段独立执行完整 target 语义
1542
+ for tgt in [t.strip() for t in target.split(";")] or [target]:
1543
+ if not tgt:
1544
+ continue
1545
+ kind, a, b = parse_target(tgt)
1546
+ if kind == "members":
1547
+ base, members = a, b
1548
+ obj = OrderedDict()
1549
+ for mem in members:
1550
+ if "=" in mem:
1551
+ k2, _, v2 = mem.partition("=")
1552
+ v2 = v2.strip()
1553
+ # 引用赋值:右侧是裸标识符(捕获组/字段路径)→ 取捕获值
1554
+ # 例:Out{Cir=In.Cir} → obj["Cir"] = In.Cir 捕获组的值
1555
+ if re.fullmatch(r"[A-Za-z_][\w.]*", v2):
1556
+ grp = (cr.path_groups.get(v2)
1557
+ or cr.path_groups.get(v2))
1558
+ if grp and cr.group_paths.get(grp) in masked:
1559
+ obj[k2.strip()] = masked[cr.group_paths[grp]]
1560
+ elif v2 in masked:
1561
+ obj[k2.strip()] = masked[v2]
1562
+ # 引用不存在 → 不写该键(与 members 缺成员语义一致)
1563
+ else:
1564
+ obj[k2.strip()] = parse_literal(v2)
1565
+ else:
1566
+ # 成员名先按完整路径找,再按相对 base 的路径找
1567
+ grp = cr.path_groups.get(mem) or cr.path_groups.get(base + "." + mem)
1568
+ if grp and cr.group_paths.get(grp) in masked:
1569
+ obj[mem] = masked[cr.group_paths[grp]]
1570
+ elif mem in masked:
1571
+ obj[mem] = masked[mem]
1572
+ if base == coll.name:
1573
+ # 目标就是当前集合 → 写进当前记录
1574
+ apply_writes(fr.rec, [(k, v) for k, v in obj.items()], coll, registry, tw, coll.name)
1575
+ elif base in coll.all_fields:
1576
+ # 目标是本层的嵌套字段(list → 追加元素,dict → 写进去)
1577
+ apply_writes(fr.rec, [(base + "." + k, v) for k, v in obj.items()], coll, registry, tw, coll.name)
1578
+ else:
1579
+ # 目标是一个(未展开的)子集合 → 塞进当前记录
1580
+ fr.rec[base] = dict(obj)
1581
+ else: # assigns
1582
+ items = a
1583
+ top_items = [(n, v) for n, v in items if "." not in n]
1584
+ path_items = [(n, v) for n, v in items if "." in n]
1585
+ out = []
1586
+ if top_items:
1587
+ # 顶层字段:先铺捕获组,再写常量。
1588
+ # ⚠️ v 为 None 表示 `-> A,B` 这种「只点名、不给常量」的写法,
1589
+ # 值应当来自同名捕获组(已在 writes 里)。若直接 append
1590
+ # (n, None) 会把捕获到的真值覆盖成 None —— 实测让
1591
+ # `access-type … authentication ont_rms_01` 的 AccessType /
1592
+ # AuthDomain 双双击成 null。这里只补 writes 里没有的常量。
1593
+ out += writes
1594
+ written = {p for p, _ in writes}
1595
+ for n, v in top_items:
1596
+ if v is None:
1597
+ if n in written:
1598
+ continue # 捕获组已经写过,别覆盖
1599
+ if n in masked:
1600
+ out.append((n, masked[n]))
1601
+ continue
1602
+ out.append((n, v))
1603
+ for n, v in path_items:
1604
+ # 嵌套路径:只写这一个路径,不铺其它捕获组
1605
+ if v is None:
1606
+ if n not in masked:
1607
+ continue
1608
+ out.append((n, masked[n]))
1609
+ else:
1610
+ out.append((n, v))
1611
+ apply_writes(fr.rec, out, coll, registry, tw, coll.name)
1612
+ return True
1613
+ return False
1614
+
1615
+
1616
+ # ── lint ──────────────────────────────────────────────
1617
+ def _rule_tokens(pattern):
1618
+ """把规则文本切成"词":非字母数字非连字符的字符都是分隔符。
1619
+
1620
+ 连字符保留 → `default-password-template` 是一个整词,不会被拆出 "password"。
1621
+ """
1622
+ return [t for t in re.split(r"[^A-Za-z0-9-]+", pattern) if t]
1623
+
1624
+
1625
+ def _rule_has_credential_keyword(pattern):
1626
+ """规则文本里有没有凭据关键字(整词匹配,避免 default-password-template 误报)。"""
1627
+ for tok in _rule_tokens(pattern):
1628
+ low = tok.lower()
1629
+ for kw in CREDENTIAL_KEYWORDS:
1630
+ if low == kw or low.startswith(kw + "-"):
1631
+ return True
1632
+ return False
1633
+
1634
+
1635
+ def _name_is_credential(name):
1636
+ """字段名本身像不像凭据(词边界 → Password 算,PasswordType 不算)。"""
1637
+ low = name.lower()
1638
+ for kw in CREDENTIAL_KEYWORDS:
1639
+ if re.search(r"\b" + re.escape(kw) + r"\b", low):
1640
+ return True
1641
+ return False
1642
+
1643
+
1644
+ def _rule_fields(c, rule, coll_by_name):
1645
+ """规则引用到的字段(Field 对象):${X} 引用 + -> 目标{} 里的字段。"""
1646
+ out = []
1647
+ for ref in re.findall(r"\$\{([A-Za-z_][\w.]*)\}", rule.pattern):
1648
+ f = c.all_fields.get(ref)
1649
+ if f is not None:
1650
+ out.append(f)
1651
+ if not rule.target:
1652
+ return out
1653
+ for tgt in [t.strip() for t in rule.target.split(";")] or [rule.target]:
1654
+ if not tgt:
1655
+ continue
1656
+ kind, a, b = parse_target(tgt)
1657
+ if kind != "members":
1658
+ continue
1659
+ base, members = a, b
1660
+ if base == c.name:
1661
+ for mem in members:
1662
+ key = mem.split("=")[0].strip()
1663
+ f = c.all_fields.get(key)
1664
+ if f is not None:
1665
+ out.append(f)
1666
+ elif base in c.all_fields:
1667
+ for mem in members:
1668
+ key = mem.split("=")[0].strip()
1669
+ f = c.all_fields.get(base + "." + key)
1670
+ if f is not None:
1671
+ out.append(f)
1672
+ else:
1673
+ tc = coll_by_name.get(base)
1674
+ if tc is not None:
1675
+ for mem in members:
1676
+ key = mem.split("=")[0].strip()
1677
+ f = tc.all_fields.get(key)
1678
+ if f is not None:
1679
+ out.append(f)
1680
+ return out
1681
+
1682
+
1683
+ def lint(colls):
1684
+ """模板体检。返回 [(级别, 集合, 说明)]"""
1685
+ issues = []
1686
+ registry = getattr(colls, "registry", {})
1687
+
1688
+ # ── 规则排序检查(匹配即提取语义下)──
1689
+ # 宽规则(是另一条规则文本的前缀)排在精确规则前面 → 警告:
1690
+ # 前缀匹配语义下宽规则会抢先命中,精确规则永远轮不到。
1691
+ for c in colls:
1692
+ rules = [r.pattern for r in getattr(c, "rules", [])]
1693
+ for i, a in enumerate(rules):
1694
+ for b in rules[i + 1:]:
1695
+ # a 是 b 的前缀(去锚定/空白后)且 a 更短 → a 宽、b 精
1696
+ a_core = a.rstrip("$").rstrip()
1697
+ b_core = b.rstrip("$").rstrip()
1698
+ if a_core and b_core.startswith(a_core) and len(b_core) > len(a_core):
1699
+ issues.append(("警告", c.name,
1700
+ f"规则排序:宽规则 [{a_core[:40]}] 排在它前缀的精确规则 [{b_core[:40]}] 之前,"
1701
+ "宽规则会抢先命中——精确规则应排在前面"))
1702
+ break # 每条宽规则只告警一次
1703
+ # ── transform 检查 ──
1704
+ # ① func= 引用必须存在于注册表
1705
+ seen_funcs = {}
1706
+ for c in colls:
1707
+ for fld in c.all_fields.values():
1708
+ if fld.func is None:
1709
+ continue
1710
+ if fld.is_secret():
1711
+ issues.append(("错误", c.name,
1712
+ f"secret 字段 {fld.path} 禁止 func=(防止凭据经函数外泄)"))
1713
+ continue
1714
+ if fld.func not in registry:
1715
+ issues.append(("错误", c.name,
1716
+ f"字段 {fld.path} 的 func={fld.func} 未定义"
1717
+ f"(检查 [python] 段或 [python_file] 文件)"))
1718
+ continue
1719
+ seen_funcs.setdefault(fld.func, []).append(c.name)
1720
+ # ② python_file 解析路径可见性(安全模型:可见即约束)
1721
+ for w in getattr(colls, "transform_warnings", []) or []:
1722
+ issues.append(("警告", "", w))
1723
+ coll_by_name = {c.name: c for c in colls}
1724
+ for c in colls:
1725
+ if "Key" in c.attrs or "Required" in c.attrs:
1726
+ issues.append(("错误", c.name,
1727
+ "集合级 Key(...)/Required(...) 已废弃,请写到字段的 option(Key/Required)"))
1728
+ if "Key" in c.flags or "Required" in c.flags:
1729
+ issues.append(("错误", c.name,
1730
+ "集合级 Key/Required 已废弃,请写到字段的 option(Key/Required)"))
1731
+ key_fields = []
1732
+ for fld in c.all_fields.values():
1733
+ if fld.type_conflict:
1734
+ issues.append(("错误", c.name,
1735
+ f"字段 {fld.path} 声明了多个 type:一个字段只能声明一种 type"
1736
+ "(secret 与其它类型互斥)"))
1737
+ if fld.is_key and fld.parent is not None:
1738
+ issues.append(("错误", c.name,
1739
+ f"option(Key) 字段 {fld.path} 必须是本集合的顶层字段"))
1740
+ if fld.is_key:
1741
+ key_fields.append(fld.path)
1742
+ # ① secret 字段不能当聚合键:遮蔽后所有记录的该字段值相同 → 聚合键全同 → 记录被合并丢失
1743
+ if fld.is_secret() and fld.is_key:
1744
+ issues.append(("错误", c.name,
1745
+ f"字段 {fld.path} 同时声明了 option(Key) 和 type(secret):"
1746
+ "遮蔽后所有记录的该字段值相同,聚合键会全部相同、不同记录被合并成一条"
1747
+ "(静默丢数据)。请去掉该字段的 Key 标记,或改用非 secret 字段做键"))
1748
+ # ② inherit 不能指向 secret 字段:会把凭据复制到未标记 secret 的字段,绕过遮蔽
1749
+ if fld.inherit:
1750
+ src_coll, _, src_field = fld.inherit.partition(".")
1751
+ tgt = coll_by_name.get(src_coll)
1752
+ if tgt is not None:
1753
+ tf = tgt.all_fields.get(src_field)
1754
+ if tf is None and "." in src_field:
1755
+ tf = tgt.all_fields.get(src_field.split(".")[-1])
1756
+ if tf is not None and tf.is_secret():
1757
+ issues.append(("错误", c.name,
1758
+ f"字段 {fld.path} 的 inherit={fld.inherit} 指向 secret 字段:"
1759
+ "inherit 会把凭据复制到未标记 secret 的字段,绕过遮蔽"))
1760
+ if key_fields:
1761
+ issues.append(("提示", c.name,
1762
+ "option(Key) 字段 " + "/".join(key_fields)
1763
+ + " 全部为空时,该记录会被丢弃"))
1764
+ if fld.required and fld.default is None:
1765
+ hit = any(fld.path in re.findall(r"\$\{([A-Za-z_][\w.]*)\}", r.pattern)
1766
+ for r in c.rules)
1767
+ if not hit:
1768
+ issues.append(("警告", c.name,
1769
+ f"option(Required) 字段 {fld.path} 没有规则会命中"))
1770
+ for r in c.rules:
1771
+ for ref in re.findall(r"\$\{([A-Za-z_][\w.]*)\}", r.pattern):
1772
+ if ref not in c.all_fields:
1773
+ issues.append(("错误", c.name, f"规则引用了未声明的字段 {ref}"))
1774
+ # ③ 疑似漏标:规则文本含凭据关键字,但捕获的字段没声明 type(secret)
1775
+ if _rule_has_credential_keyword(r.pattern):
1776
+ refs = _rule_fields(c, r, coll_by_name)
1777
+ cred_bad = [f for f in refs if not f.is_secret() and _name_is_credential(f.name)]
1778
+ if cred_bad:
1779
+ culprits = cred_bad
1780
+ elif any(f.is_secret() for f in refs):
1781
+ culprits = []
1782
+ else:
1783
+ culprits = [f for f in refs if not f.is_secret()]
1784
+ if culprits:
1785
+ issues.append(("警告", c.name,
1786
+ f"规则 '{r.pattern}' 含凭据关键字"
1787
+ f"({'/'.join(CREDENTIAL_KEYWORDS)}),但字段 "
1788
+ + "/".join(f.path for f in culprits)
1789
+ + " 未声明 type(secret)"))
1790
+ if not r.target:
1791
+ continue
1792
+ for tgt in [t.strip() for t in r.target.split(";")] or [r.target]:
1793
+ if not tgt:
1794
+ continue
1795
+ kind, a, b = parse_target(tgt)
1796
+ if kind == "members":
1797
+ base, members = a, b
1798
+ for mem in members:
1799
+ key = mem.split("=")[0].strip()
1800
+ if key and key not in c.all_fields and base == c.name:
1801
+ issues.append(("错误", c.name, f"目标里的字段 {key} 未声明"))
1802
+ else:
1803
+ for name, _v in a:
1804
+ if "." not in name and name not in c.all_fields:
1805
+ issues.append(("错误", c.name, f"目标字段 {name} 未声明"))
1806
+ elif "." in name and name not in c.all_fields:
1807
+ issues.append(("错误", c.name, f"目标路径 {name} 未声明"))
1808
+ return issues
1809
+
1810
+
1811
+ # ── 兼容层:把旧的模块级全局名转发到 CONFIG ────────────
1812
+ # PEP 562 的模块 __getattr__ 只能兜读;赋值要靠替换模块类。
1813
+ # 这样 `engine.MASK_VALUE` / `engine.MASK_HEURISTIC = False` 的旧用法都还能用,
1814
+ # 而且读和写都落到同一个 CONFIG 上,不会出现"设了没生效"。
1815
+ _REMOVED_GLOBALS = {"MASK_VALUE": "value", "MASK_HEURISTIC": "heuristic"}
1816
+
1817
+
1818
+ def __getattr__(name):
1819
+ field = _REMOVED_GLOBALS.get(name)
1820
+ if field is not None:
1821
+ return getattr(CONFIG, field)
1822
+ raise AttributeError("module %r has no attribute %r" % (__name__, name))
1823
+
1824
+
1825
+ class _EngineModule(_types.ModuleType):
1826
+ def __setattr__(self, name, value):
1827
+ field = _REMOVED_GLOBALS.get(name)
1828
+ if field is not None:
1829
+ setattr(CONFIG, field, value)
1830
+ return
1831
+ super().__setattr__(name, value)
1832
+
1833
+
1834
+ _sys.modules[__name__].__class__ = _EngineModule