powertom 0.2.2

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.
@@ -0,0 +1,776 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "scanner"
4
+
5
+ module PowerTom
6
+ # 表格行/列循环的纯逻辑部分:根据表格单元格文本生成展开计划。
7
+ #
8
+ # 三种语法(设计见 docs/表格循环语法设计.md):
9
+ # L0 {{数组[].字段}} 单级行循环(一张表一个循环行)
10
+ # L1 {{#rows 路径}} 标记行 两级嵌套:父行 → 子行
11
+ # L2 {{#grid rows: .. cols: ..}} 动态列:首列固定,列按 cols 克隆
12
+ #
13
+ # plan 返回 nil 表示该表没有循环;结构错误抛 TemplateSyntaxError。
14
+ module TableLoop
15
+ # 行标记必须整格只有这一条标签
16
+ MARKER_RE = /\A\{\{\s*#rows\s+([A-Za-z0-9_\[\]\.]+)\s*\}\}\z/.freeze
17
+
18
+ # v0.2.x 区块语法:配对行区块 + 列带(可写在行区块内,支持多列模板)
19
+ COLS_OPEN_RE = /\A\{\{\s*#cols\s+([A-Za-z0-9_\.]+)(?:\s+value:\s*([A-Za-z0-9_\.]+(?:\s*,\s*[A-Za-z0-9_\.]+)*))?\s*\}\}\z/.freeze
20
+ IF_OPEN_RE = /\A\{\{\s*#if\s+([A-Za-z0-9_\[\]\.]+)\s*\}\}\z/.freeze
21
+ MAX_BLOCK_DEPTH = 3
22
+
23
+ module_function
24
+
25
+ # rows: [[cell_text, ...], ...]
26
+ # merged_rows: [bool](该行是否含合并单元格)
27
+ # columns: 表格列数(nil → 不校验 grid 的两列模板约束)
28
+ # 返回 nil / {kind: :simple, ...} / {kind: :nested, ...} / {kind: :grid, ...} /
29
+ # {kind: :blocks, blocks:, cols:}
30
+ def plan(rows, merged_rows: [], columns: nil)
31
+ return blocks_plan(rows, merged_rows) if block_syntax?(rows)
32
+
33
+ grid_markers = collect_grid_markers(rows)
34
+ row_markers = collect_row_markers(rows)
35
+
36
+ if !grid_markers.empty? && !row_markers.empty?
37
+ raise TemplateSyntaxError,
38
+ "表格第 #{grid_markers.first[:row] + 1} 行:同一张表不能混用 {{#grid}} 与 {{#rows}}"
39
+ end
40
+ plan = if !grid_markers.empty?
41
+ grid_plan(rows, grid_markers, merged_rows, columns)
42
+ elsif row_markers.empty?
43
+ simple_plan(rows, merged_rows)
44
+ else
45
+ nested_plan(rows, row_markers, merged_rows)
46
+ end
47
+ check_orphan_scope_labels!(rows) unless plan && plan[:kind] == :grid
48
+ plan
49
+ end
50
+
51
+ # 没有 #grid / 区块时,row. / col. / cell 是保留作用域变量,出现即报错
52
+ def check_orphan_scope_labels!(rows)
53
+ rows.each_with_index do |cells, r|
54
+ cells.each_with_index do |text, c|
55
+ label_paths(text).each do |path|
56
+ next unless scope_variable?(path)
57
+
58
+ raise TemplateSyntaxError,
59
+ "表格第 #{r + 1} 行第 #{c + 1} 列:{{#{path}}} 只能写在使用 " \
60
+ "{{#rows}} 区块或 {{#grid}} 的表格里"
61
+ end
62
+ end
63
+ end
64
+ end
65
+
66
+ def scope_variable?(path)
67
+ path == "cell" || path == "row" || path.start_with?("row.") ||
68
+ path == "col" || path.start_with?("col.")
69
+ end
70
+
71
+ # 文本里出现的循环数组根路径(如 "classes[].name" → "classes")
72
+ def loop_roots(text)
73
+ text.to_s.scan(Scanner::TAG_RE).filter_map do |tag|
74
+ raw = tag[/\{\{\s*([^{}]*?)\s*\}\}/, 1].to_s
75
+ next if raw.start_with?("#")
76
+
77
+ path = raw.split(":", 2).first
78
+ path.split("[]", 2).first if path.include?("[]")
79
+ end
80
+ end
81
+
82
+ # ---- L0:简单行循环 ----
83
+
84
+ def simple_plan(rows, merged_rows)
85
+ found = {}
86
+ rows.each_with_index do |cells, index|
87
+ roots = cells.flat_map { |text| loop_roots(text) }.uniq
88
+ next if roots.empty?
89
+
90
+ if roots.size > 1
91
+ raise TemplateSyntaxError,
92
+ "表格第 #{index + 1} 行包含多个循环数组(#{roots.join('、')}),一行只允许一个"
93
+ end
94
+ unless found.empty?
95
+ first = found.keys.first + 1
96
+ raise TemplateSyntaxError,
97
+ "一张表只支持一个行循环:第 #{first} 行已是循环行,第 #{index + 1} 行又出现"
98
+ end
99
+
100
+ found[index] = roots.first
101
+ end
102
+ return nil if found.empty?
103
+
104
+ row, root = found.first
105
+ if merged_rows[row]
106
+ raise TemplateSyntaxError,
107
+ "表格第 #{row + 1} 行:循环区域包含合并单元格,请先拆分(设计文档 §7)"
108
+ end
109
+ { kind: :simple, row: row, root: root }
110
+ end
111
+
112
+ # ---- L1:两级嵌套 ----
113
+
114
+ # 收集 {{#rows 路径}} 标记行,并校验标记本身的写法
115
+ def collect_row_markers(rows)
116
+ rows.each_with_index.filter_map do |cells, index|
117
+ tags = cells.each_with_index.flat_map do |text, col|
118
+ directive_tags(text).reject { |tag| grid_tag?(tag) }
119
+ .map { |tag| { col: col, tag: tag } }
120
+ end
121
+ next nil if tags.empty?
122
+
123
+ validate_marker_row!(cells, index, tags)
124
+ { row: index, path: tags.first[:tag][MARKER_RE, 1] }
125
+ end
126
+ end
127
+
128
+ def validate_marker_row!(cells, index, tags)
129
+ line = "表格第 #{index + 1} 行"
130
+ if tags.size > 1
131
+ raise TemplateSyntaxError,
132
+ "#{line}包含 #{tags.size} 条行指令,一行只允许一条 {{#rows 路径}}"
133
+ end
134
+
135
+ col = tags.first[:col]
136
+ tag = tags.first[:tag]
137
+ unless col.zero? && cells[col].to_s.strip == tag
138
+ raise TemplateSyntaxError, "#{line}:#{tag} 行标记必须独占首列单元格"
139
+ end
140
+ if cells.each_with_index.any? { |text, c| c != col && !text.to_s.strip.empty? }
141
+ raise TemplateSyntaxError, "#{line}:#{tag} 行标记必须独占一行,其余单元格请留空"
142
+ end
143
+
144
+ path = tag[MARKER_RE, 1]
145
+ unless path
146
+ raise TemplateSyntaxError, "#{line}:#{tag} 行标记不合法,应为 {{#rows 路径}}"
147
+ end
148
+
149
+ check_marker_path!(path, line, tag)
150
+ end
151
+
152
+ def check_marker_path!(path, line, tag)
153
+ if path.scan("[]").size > 1
154
+ raise TemplateSyntaxError,
155
+ "#{line}:#{tag} 堆叠层级超过 2 级,只支持「父级 → 子级」两层"
156
+ end
157
+ return unless path.match?(/\[\d+\]/)
158
+
159
+ raise TemplateSyntaxError, "#{line}:#{tag} 行标记路径不支持下标,请用数组名 + []"
160
+ end
161
+
162
+ def nested_plan(rows, markers, merged_rows)
163
+ if markers.size > 2
164
+ raise TemplateSyntaxError,
165
+ "表格第 #{markers[2][:row] + 1} 行:堆叠层级超过 2 级(一张表最多父级 + 子级)"
166
+ end
167
+
168
+ parent = markers.first
169
+ if parent[:path].include?("[]")
170
+ raise TemplateSyntaxError,
171
+ "表格第 #{parent[:row] + 1} 行:{{#rows #{parent[:path]}}} 前缺少父行标记(父级路径不带 [])"
172
+ end
173
+
174
+ parent_content = content_row_after(rows, markers, parent, "父")
175
+ if markers.size == 1
176
+ raise TemplateSyntaxError,
177
+ "表格第 #{parent[:row] + 1} 行:只有父行标记 {{#rows #{parent[:path]}}},缺少子行标记;" \
178
+ "单级循环请直接用 {{#{parent[:path]}[].字段}}"
179
+ end
180
+
181
+ child = markers[1]
182
+ relative = child_relative_path!(parent, child)
183
+ if child[:row] <= parent_content
184
+ raise TemplateSyntaxError,
185
+ "表格第 #{child[:row] + 1} 行:子行标记必须写在父行内容行(第 #{parent_content + 1} 行)之后"
186
+ end
187
+ child_content = content_row_after(rows, markers, child, "子")
188
+
189
+ check_merged!(merged_rows, [parent[:row], parent_content, child[:row], child_content])
190
+ check_no_mixed_loops!(rows, markers, [parent_content, child_content])
191
+
192
+ parent_prefix = "#{parent[:path]}[]"
193
+ child_prefix = "#{child[:path]}[]"
194
+ check_level_labels!(rows[parent_content], [parent_prefix], parent_content)
195
+ check_level_labels!(rows[child_content], [parent_prefix, child_prefix], child_content)
196
+
197
+ {
198
+ kind: :nested,
199
+ parent: { marker: parent[:row], content: parent_content,
200
+ path: parent[:path], prefix: parent_prefix },
201
+ child: { marker: child[:row], content: child_content,
202
+ path: child[:path], prefix: child_prefix, relative: relative }
203
+ }
204
+ end
205
+
206
+ # 标记行后必须紧跟一行内容行(且不能是另一条标记)
207
+ def content_row_after(rows, markers, marker, level)
208
+ content = marker[:row] + 1
209
+ if content >= rows.size
210
+ raise TemplateSyntaxError,
211
+ "表格第 #{marker[:row] + 1} 行:#{level}行标记后缺少内容行"
212
+ end
213
+ if markers.any? { |m| m[:row] == content }
214
+ raise TemplateSyntaxError,
215
+ "表格第 #{marker[:row] + 1} 行:#{level}行标记后必须紧跟内容行,不能紧跟另一条行标记"
216
+ end
217
+ content
218
+ end
219
+
220
+ # 子标记路径必须是 父级[] + "." + 相对字段(允许点路径,但只允许一个 [])
221
+ def child_relative_path!(parent, child)
222
+ prefix = "#{parent[:path]}[]"
223
+ relative = child[:path].delete_prefix("#{prefix}.")
224
+ return relative if child[:path] != prefix && child[:path].start_with?("#{prefix}.") && !relative.empty?
225
+
226
+ raise TemplateSyntaxError,
227
+ "表格第 #{child[:row] + 1} 行:子行标记 {{#rows #{child[:path]}}} 必须以 #{prefix} 开头" \
228
+ "(如 {{#rows #{prefix}.items}})"
229
+ end
230
+
231
+ def check_merged!(merged_rows, rows)
232
+ row = rows.find { |index| merged_rows[index] }
233
+ return unless row
234
+
235
+ raise TemplateSyntaxError, "表格第 #{row + 1} 行:循环区域包含合并单元格,请先拆分(设计文档 §7)"
236
+ end
237
+
238
+ # 有 #rows 标记时,其余行不能再出现 [] 标签(两种语法不混用)
239
+ def check_no_mixed_loops!(rows, markers, content_rows)
240
+ rows.each_with_index do |cells, index|
241
+ next if content_rows.include?(index) || markers.any? { |m| m[:row] == index }
242
+ next if cells.none? { |text| loop_roots(text).any? }
243
+
244
+ raise TemplateSyntaxError,
245
+ "表格第 #{index + 1} 行:同一张表不能混用 {{#rows}} 标记与 {{数组[].字段}} 行循环"
246
+ end
247
+ end
248
+
249
+ # 内容行里的 [] 标签必须指向本行已展开的层级(子行可引用父级字段)
250
+ def check_level_labels!(cells, prefixes, row_index)
251
+ cells.each do |text|
252
+ label_paths(text).each do |path|
253
+ next unless path.include?("[]")
254
+
255
+ match = prefixes.select { |prefix| path == prefix || path.start_with?("#{prefix}.") }
256
+ .max_by(&:length)
257
+ next if match && path.scan("[]").size == match.scan("[]").size
258
+
259
+ expected = prefixes.map { |prefix| "{{#{prefix}.字段}}" }.join(" 或 ")
260
+ raise TemplateSyntaxError,
261
+ "表格第 #{row_index + 1} 行:{{#{path}}} 与循环数组不匹配(当前行应为 #{expected})"
262
+ end
263
+ end
264
+ end
265
+
266
+ # ---- L2:动态列 ----
267
+
268
+ def collect_grid_markers(rows)
269
+ rows.each_with_index.filter_map do |cells, index|
270
+ tags = cells.each_with_index.flat_map do |text, col|
271
+ directive_tags(text).select { |tag| grid_tag?(tag) }
272
+ .map { |tag| { col: col, tag: tag } }
273
+ end
274
+ next nil if tags.empty?
275
+
276
+ validate_grid_row!(index, tags)
277
+ { row: index, col: tags.first[:col],
278
+ args: parse_grid_args(tags.first[:tag], index) }
279
+ end
280
+ end
281
+
282
+ def validate_grid_row!(index, tags)
283
+ line = "表格第 #{index + 1} 行"
284
+ if tags.size > 1
285
+ raise TemplateSyntaxError, "#{line}包含 #{tags.size} 条 grid 标记,一行只允许一条"
286
+ end
287
+ return if tags.first[:col].zero?
288
+
289
+ raise TemplateSyntaxError, "#{line}:#{tags.first[:tag]} grid 标记必须放在表头行首列"
290
+ end
291
+
292
+ # {{#grid rows: 数组 cols: 数组 [value: 行内字段]}}
293
+ def parse_grid_args(tag, row_index)
294
+ line = "表格第 #{row_index + 1} 行"
295
+ raw = tag[/\{\{\s*([^{}]*?)\s*\}\}/, 1].to_s
296
+ body = raw.sub(/\A#grid/, "")
297
+ args = {}
298
+ pos = 0
299
+ while pos < body.length
300
+ m = body.match(/\G\s*(rows|cols|value)\s*:\s*([A-Za-z0-9_\.]+)\s*/, pos)
301
+ unless m
302
+ raise TemplateSyntaxError,
303
+ "#{line}:#{tag} grid 标记写法不合法," \
304
+ "应为 {{#grid rows: 数组 cols: 数组 [value: 字段]}}"
305
+ end
306
+ key = m[1].to_sym
307
+ raise TemplateSyntaxError, "#{line}:#{tag} grid 参数重复:#{m[1]}" if args.key?(key)
308
+
309
+ args[key] = m[2]
310
+ pos = m.end(0)
311
+ end
312
+ %i[rows cols].each do |key|
313
+ next if args[key]
314
+
315
+ raise TemplateSyntaxError, "#{line}:#{tag} grid 标记缺少 #{key}: 参数"
316
+ end
317
+ args
318
+ end
319
+
320
+ def grid_plan(rows, markers, merged_rows, columns)
321
+ if markers.size > 1
322
+ raise TemplateSyntaxError,
323
+ "表格第 #{markers[1][:row] + 1} 行:一张表只允许一个 grid 标记" \
324
+ "(第 #{markers.first[:row] + 1} 行已声明)"
325
+ end
326
+
327
+ marker = markers.first
328
+ line = "表格第 #{marker[:row] + 1} 行"
329
+ if columns && columns != 2
330
+ raise TemplateSyntaxError,
331
+ "#{line}:grid 表只支持两列模板(首列行标题 + 第二列数据模板),当前 #{columns} 列"
332
+ end
333
+ if marker[:row] + 1 >= rows.size
334
+ raise TemplateSyntaxError, "#{line}:grid 标记后缺少内容行"
335
+ end
336
+
337
+ content = marker[:row] + 1
338
+ if merged_rows.any?
339
+ row = merged_rows.index(true)
340
+ raise TemplateSyntaxError, "表格第 #{row + 1} 行:grid 循环不支持合并单元格,请先拆分"
341
+ end
342
+
343
+ check_grid_no_loop_labels!(rows)
344
+ check_grid_header_labels!(rows[marker[:row]], marker[:row])
345
+ check_grid_content_labels!(rows[content], content)
346
+
347
+ {
348
+ kind: :grid,
349
+ grid: { header: marker[:row], content: content,
350
+ rows_path: marker[:args][:rows],
351
+ cols_path: marker[:args][:cols],
352
+ value_path: marker[:args][:value] }
353
+ }
354
+ end
355
+
356
+ def check_grid_no_loop_labels!(rows)
357
+ rows.each_with_index do |cells, index|
358
+ next if cells.none? { |text| loop_roots(text).any? }
359
+
360
+ raise TemplateSyntaxError,
361
+ "表格第 #{index + 1} 行:同一张表不能混用 {{#grid}} 与 {{数组[].字段}} 行循环"
362
+ end
363
+ end
364
+
365
+ # 表头数据列只允许 {{col.字段}}(列模板)
366
+ def check_grid_header_labels!(cells, row_index)
367
+ cells.each_with_index do |text, col|
368
+ next if col.zero?
369
+
370
+ label_paths(text).each do |path|
371
+ next if path == "col" || path.start_with?("col.")
372
+
373
+ raise TemplateSyntaxError,
374
+ "表格第 #{row_index + 1} 行第 #{col + 1} 列:{{#{path}}} 不属于 grid 表头作用域" \
375
+ "(应为 {{col.字段}})"
376
+ end
377
+ end
378
+ end
379
+
380
+ # 内容行:首列是行标题({{row.字段}}),其余列可用 {{row.*}} / {{col.*}} / {{cell}}
381
+ def check_grid_content_labels!(cells, row_index)
382
+ cells.each_with_index do |text, col|
383
+ label_paths(text).each do |path|
384
+ allowed = if col.zero?
385
+ !(path == "cell" || path == "col" || path.start_with?("col."))
386
+ else
387
+ path == "cell" || path == "row" || path.start_with?("row.") ||
388
+ path == "col" || path.start_with?("col.")
389
+ end
390
+ next if allowed
391
+
392
+ scope = col.zero? ? "首列只能写 {{row.字段}} 或整页字段" : "数据列应为 {{row.字段}} / {{col.字段}} / {{cell}}"
393
+ raise TemplateSyntaxError,
394
+ "表格第 #{row_index + 1} 行第 #{col + 1} 列:{{#{path}}} 不属于 grid 内容行作用域(#{scope})"
395
+ end
396
+ end
397
+ end
398
+
399
+ # ---- v0.2.0:配对行区块 + 单列带 ----
400
+
401
+ # 出现 {{/rows}}、{{/cols}}、{{#cols}}、{{#if}}、{{/if}} 即进入区块模式
402
+ def block_syntax?(rows)
403
+ rows.any? do |cells|
404
+ cells.any? do |text|
405
+ directive_tags(text).any? do |tag|
406
+ raw = raw_of(tag)
407
+ raw.start_with?("#cols", "#if") || raw.start_with?("/rows", "/cols", "/if")
408
+ end
409
+ end
410
+ end
411
+ end
412
+
413
+ def blocks_plan(rows, merged_rows)
414
+ row_tags, col_tags = collect_block_tags(rows)
415
+ blocks = parse_block_tree(rows, row_tags)
416
+ band = parse_column_band(rows, row_tags, col_tags)
417
+ if band && band_in_if?(blocks, band[:row])
418
+ raise TemplateSyntaxError, "表格第 #{band[:row] + 1} 行:列带不能写在条件区块内"
419
+ end
420
+ check_block_ifs!(blocks)
421
+ check_block_merges!(merged_rows, blocks, band)
422
+ stacks = build_row_stacks(blocks)
423
+ check_block_labels!(rows, stacks, band)
424
+ { kind: :blocks, blocks: blocks, cols: band }
425
+ end
426
+
427
+ def collect_block_tags(rows)
428
+ row_tags = []
429
+ col_tags = []
430
+ rows.each_with_index do |cells, r|
431
+ cells.each_with_index do |text, c|
432
+ directive_tags(text).each do |tag|
433
+ raw = raw_of(tag)
434
+ item = { row: r, col: c, raw: raw, tag: tag }
435
+ if raw.start_with?("#rows", "/rows", "#if", "/if")
436
+ row_tags << item
437
+ elsif raw.start_with?("#cols", "/cols")
438
+ col_tags << item
439
+ else
440
+ raise TemplateSyntaxError,
441
+ "表格第 #{r + 1} 行:区块模式不支持 #{tag}(只支持 #rows / #cols / #if 区块)"
442
+ end
443
+ end
444
+ end
445
+ end
446
+ [row_tags, col_tags]
447
+ end
448
+
449
+ def parse_block_tree(rows, tags)
450
+ roots = []
451
+ stack = []
452
+ if_stack = []
453
+ tags.each do |item|
454
+ case item[:raw]
455
+ when /\A#rows/
456
+ if if_stack.any?
457
+ raise TemplateSyntaxError,
458
+ "表格第 #{item[:row] + 1} 行:条件区块内不能放行区块(请把条件写在外层)"
459
+ end
460
+ stack.push(open_block(rows, item, stack))
461
+ when /\A\/rows/
462
+ if if_stack.any?
463
+ raise TemplateSyntaxError,
464
+ "表格第 #{item[:row] + 1} 行:条件区块必须完整包含在行区块内"
465
+ end
466
+ close_block(rows, item, stack, roots)
467
+ when /\A#if/
468
+ open_if(rows, item, stack, if_stack)
469
+ else
470
+ close_if(rows, item, stack, if_stack)
471
+ end
472
+ end
473
+ unless if_stack.empty?
474
+ node = if_stack.last
475
+ raise TemplateSyntaxError,
476
+ "表格第 #{node[:open] + 1} 行:{{#if #{node[:path]}}} 缺少 {{/if}}"
477
+ end
478
+ unless stack.empty?
479
+ block = stack.last
480
+ raise TemplateSyntaxError,
481
+ "表格第 #{block[:open] + 1} 行:{{#rows #{block[:path]}}} 缺少 {{/rows}}"
482
+ end
483
+ roots
484
+ end
485
+
486
+ def open_if(rows, item, stack, if_stack)
487
+ validate_block_marker!(rows, item, "#if")
488
+ path = item[:tag][IF_OPEN_RE, 1]
489
+ unless path
490
+ raise TemplateSyntaxError,
491
+ "表格第 #{item[:row] + 1} 行:#{item[:tag]} 条件标记不合法,应为 {{#if 路径}}"
492
+ end
493
+ if stack.empty?
494
+ raise TemplateSyntaxError, "表格第 #{item[:row] + 1} 行:条件区块必须写在行区块内"
495
+ end
496
+ if if_stack.any?
497
+ raise TemplateSyntaxError, "表格第 #{item[:row] + 1} 行:条件区块不能嵌套(请合并条件)"
498
+ end
499
+
500
+ if_stack.push({ path: path, open: item[:row], close: nil })
501
+ end
502
+
503
+ def close_if(rows, item, stack, if_stack)
504
+ validate_block_marker!(rows, item, "/if")
505
+ if if_stack.empty?
506
+ raise TemplateSyntaxError,
507
+ "表格第 #{item[:row] + 1} 行:{{/if}} 没有对应的 {{#if}}"
508
+ end
509
+
510
+ node = if_stack.pop
511
+ if item[:row] <= node[:open] + 1
512
+ raise TemplateSyntaxError,
513
+ "表格第 #{node[:open] + 1} 行:{{#if #{node[:path]}}} 区块内至少需要一行内容"
514
+ end
515
+ node[:close] = item[:row]
516
+ stack.last[:ifs] << node
517
+ end
518
+
519
+ def open_block(rows, item, stack)
520
+ validate_block_marker!(rows, item, "#rows")
521
+ path = item[:tag][MARKER_RE, 1]
522
+ unless path
523
+ raise TemplateSyntaxError,
524
+ "表格第 #{item[:row] + 1} 行:#{item[:tag]} 行区块标记不合法,应为 {{#rows 路径}}"
525
+ end
526
+ depth = stack.size + 1
527
+ if depth > MAX_BLOCK_DEPTH
528
+ raise TemplateSyntaxError,
529
+ "表格第 #{item[:row] + 1} 行:行区块嵌套超过 #{MAX_BLOCK_DEPTH} 级"
530
+ end
531
+
532
+ block = { path: path, open: item[:row], close: nil, children: [], ifs: [], depth: depth }
533
+ parent = stack.last
534
+ if parent
535
+ prefix = "#{parent[:path]}[]"
536
+ unless path.start_with?("#{prefix}.")
537
+ raise TemplateSyntaxError,
538
+ "表格第 #{item[:row] + 1} 行:{{#rows #{path}}} 必须以 #{prefix} 开头" \
539
+ "(父区块 #{parent[:path]})"
540
+ end
541
+ block[:relative] = path.delete_prefix("#{prefix}.")
542
+ elsif path.include?("[]")
543
+ raise TemplateSyntaxError,
544
+ "表格第 #{item[:row] + 1} 行:顶层行区块路径不带 [](如 {{#rows classes}})"
545
+ end
546
+ block[:prefix] = "#{path}[]"
547
+ block
548
+ end
549
+
550
+ def close_block(rows, item, stack, roots)
551
+ validate_block_marker!(rows, item, "/rows")
552
+ if stack.empty?
553
+ raise TemplateSyntaxError,
554
+ "表格第 #{item[:row] + 1} 行:{{/rows}} 没有对应的 {{#rows}}"
555
+ end
556
+
557
+ block = stack.pop
558
+ if item[:row] <= block[:open] + 1
559
+ raise TemplateSyntaxError,
560
+ "表格第 #{block[:open] + 1} 行:{{#rows #{block[:path]}}} 区块内至少需要一行内容"
561
+ end
562
+ block[:close] = item[:row]
563
+ (stack.last ? stack.last[:children] : roots) << block
564
+ end
565
+
566
+ # 区块标记必须独占整行首列
567
+ def validate_block_marker!(rows, item, kind)
568
+ cells = rows[item[:row]]
569
+ line = "表格第 #{item[:row] + 1} 行"
570
+ unless item[:col].zero? && cells[item[:col]].to_s.strip == item[:tag]
571
+ raise TemplateSyntaxError, "#{line}:#{item[:tag]} 区块标记必须独占整行首列"
572
+ end
573
+ if cells.each_with_index.any? { |text, c| c != item[:col] && !text.to_s.strip.empty? }
574
+ raise TemplateSyntaxError, "#{line}:#{item[:tag]} 区块标记必须独占整行,其余单元格请留空"
575
+ end
576
+ case kind
577
+ when "#rows"
578
+ return if item[:tag].match?(MARKER_RE)
579
+ when "/rows"
580
+ return if item[:raw].match?(/\A\/rows\z/)
581
+ when "#if"
582
+ return if item[:tag].match?(IF_OPEN_RE)
583
+ else
584
+ return if item[:raw].match?(/\A\/if\z/)
585
+ end
586
+
587
+ raise TemplateSyntaxError, "#{line}:#{item[:tag]} 区块标记不合法"
588
+ end
589
+
590
+ def parse_column_band(rows, row_tags, tags)
591
+ return nil if tags.empty?
592
+
593
+ opens = tags.select { |t| t[:raw].start_with?("#cols") }
594
+ closes = tags.select { |t| t[:raw].start_with?("/cols") }
595
+ if opens.size > 1 || closes.size > 1
596
+ extra = (opens + closes).max_by { |t| t[:row] }
597
+ raise TemplateSyntaxError, "表格第 #{extra[:row] + 1} 行:一张表只允许一个列带"
598
+ end
599
+ if opens.empty? || closes.empty?
600
+ raise TemplateSyntaxError,
601
+ "表格第 #{tags.first[:row] + 1} 行:列带必须同时有 {{#cols}} 与 {{/cols}}"
602
+ end
603
+
604
+ open = opens.first
605
+ close = closes.first
606
+ line = "表格第 #{open[:row] + 1} 行"
607
+ unless open[:row] == close[:row]
608
+ raise TemplateSyntaxError, "#{line}:{{#cols}} 与 {{/cols}} 必须写在同一行"
609
+ end
610
+ if row_tags.any? { |t| t[:row] == open[:row] }
611
+ raise TemplateSyntaxError, "#{line}:列带不能写在行区块标记行上"
612
+ end
613
+ if open[:col] < 1
614
+ raise TemplateSyntaxError, "#{line}:列带必须写在数据列(首列之外)"
615
+ end
616
+ if close[:col] < open[:col]
617
+ raise TemplateSyntaxError, "#{line}:{{/cols}} 必须在 {{#cols}} 右侧"
618
+ end
619
+
620
+ m = open[:tag].match(COLS_OPEN_RE)
621
+ unless m
622
+ raise TemplateSyntaxError,
623
+ "#{line}:{{#cols}} 写法不合法,应为 {{#cols 数组 [value: 字段1,字段2]}}"
624
+ end
625
+ width = close[:col] - open[:col] + 1
626
+ value_paths = m[2]&.split(/\s*,\s*/)
627
+ if value_paths && ![1, width].include?(value_paths.size)
628
+ raise TemplateSyntaxError,
629
+ "#{line}:value: 的数量必须为 1 或与列带宽度(#{width})一致,当前 #{value_paths.size} 个"
630
+ end
631
+ { path: m[1], value_paths: value_paths, row: open[:row],
632
+ first_col: open[:col], last_col: close[:col], width: width }
633
+ end
634
+
635
+ def check_block_merges!(merged_rows, blocks, band)
636
+ if band
637
+ row = merged_rows.index(true)
638
+ if row
639
+ raise TemplateSyntaxError, "表格第 #{row + 1} 行:列带循环不支持合并单元格,请先拆分"
640
+ end
641
+ end
642
+
643
+ stacks = build_row_stacks(blocks)
644
+ merged_rows.each_with_index do |merged, r|
645
+ next unless merged
646
+ next if stacks[r].nil?
647
+
648
+ raise TemplateSyntaxError, "表格第 #{r + 1} 行:行区块内不支持合并单元格,请先拆分"
649
+ end
650
+ end
651
+
652
+ # 条件区块里不允许出现列带
653
+ def band_in_if?(blocks, row)
654
+ blocks.any? do |block|
655
+ block[:ifs].any? { |node| row.between?(node[:open], node[:close]) } ||
656
+ band_in_if?(block[:children], row)
657
+ end
658
+ end
659
+
660
+ # 条件路径含 [] 时,必须匹配当前区块栈里的某个作用域
661
+ def check_block_ifs!(blocks, ancestors = [])
662
+ blocks.each do |block|
663
+ stack = ancestors + [block]
664
+ block[:ifs].each do |node|
665
+ path = node[:path]
666
+ next unless path.include?("[]")
667
+
668
+ match = stack.select { |b| path == b[:prefix] || path.start_with?("#{b[:prefix]}.") }
669
+ .max_by { |b| b[:prefix].length }
670
+ if match.nil?
671
+ raise TemplateSyntaxError,
672
+ "表格第 #{node[:open] + 1} 行:{{#if #{path}}} 不在当前行区块作用域内"
673
+ end
674
+ if path.scan("[]").size > match[:prefix].scan("[]").size
675
+ raise TemplateSyntaxError,
676
+ "表格第 #{node[:open] + 1} 行:{{#if #{path}}} 引用了未展开的下一级数组"
677
+ end
678
+ end
679
+ check_block_ifs!(block[:children], stack)
680
+ end
681
+ end
682
+
683
+ # 每个表格行所属的区块栈(外层 → 内层),供作用域校验与 check 复用
684
+ def build_row_stacks(blocks)
685
+ stacks = {}
686
+ mark_block_rows(blocks, [], stacks)
687
+ stacks
688
+ end
689
+
690
+ def mark_block_rows(blocks, ancestors, stacks)
691
+ blocks.each do |block|
692
+ (block[:open]..block[:close]).each { |r| stacks[r] = ancestors + [block] }
693
+ mark_block_rows(block[:children], ancestors + [block], stacks)
694
+ end
695
+ end
696
+
697
+ def check_block_labels!(rows, stacks, band)
698
+ rows.each_with_index do |cells, r|
699
+ stack = stacks[r] || []
700
+ cells.each_with_index do |text, c|
701
+ label_paths(text).each do |path|
702
+ in_band = band && c.between?(band[:first_col], band[:last_col])
703
+ band_decl_row = band && r == band[:row]
704
+ validate_block_label!(path, r, c, stack, in_band, band_decl_row)
705
+ end
706
+ end
707
+ end
708
+ end
709
+
710
+ def validate_block_label!(path, row, col, stack, in_band, band_decl_row)
711
+ line = "表格第 #{row + 1} 行第 #{col + 1} 列"
712
+ if path == "cell"
713
+ unless in_band && !stack.empty?
714
+ raise TemplateSyntaxError,
715
+ "#{line}:{{cell}} 只能写在行区块内的列带单元格里"
716
+ end
717
+ return
718
+ end
719
+ if path == "col" || path.start_with?("col.")
720
+ unless in_band
721
+ raise TemplateSyntaxError, "#{line}:{{#{path}}} 只能写在列带单元格里"
722
+ end
723
+ return
724
+ end
725
+ if path == "row" || path.start_with?("row.")
726
+ if stack.empty?
727
+ raise TemplateSyntaxError, "#{line}:{{#{path}}} 只能写在行区块内容行里"
728
+ end
729
+ return
730
+ end
731
+ if band_decl_row && in_band
732
+ raise TemplateSyntaxError,
733
+ "#{line}:列带声明行只能写 {{col.字段}},不能写 {{#{path}}}"
734
+ end
735
+ return unless path.include?("[]")
736
+
737
+ match = stack.select { |b| path == b[:prefix] || path.start_with?("#{b[:prefix]}.") }
738
+ .max_by { |b| b[:prefix].length }
739
+ if match.nil?
740
+ raise TemplateSyntaxError,
741
+ "#{line}:{{#{path}}} 不在当前行区块作用域内"
742
+ end
743
+ if path.scan("[]").size > match[:prefix].scan("[]").size
744
+ raise TemplateSyntaxError,
745
+ "#{line}:{{#{path}}} 引用了未展开的下一级数组(当前最内层 #{match[:prefix]})"
746
+ end
747
+ end
748
+
749
+ # ---- 文本工具 ----
750
+
751
+ def directive_tags(text)
752
+ text.to_s.scan(Scanner::TAG_RE).select do |tag|
753
+ raw = raw_of(tag)
754
+ raw.start_with?("#") || raw.start_with?("/")
755
+ end
756
+ end
757
+
758
+ def raw_of(tag)
759
+ tag[/\{\{\s*([^{}]*?)\s*\}\}/, 1].to_s
760
+ end
761
+
762
+ def grid_tag?(tag)
763
+ tag[/\{\{\s*([^{}]*?)\s*\}\}/, 1].to_s.start_with?("#grid")
764
+ end
765
+
766
+ # 单元格里可绑定的标签路径(去掉 formatter 与 # / 闭合指令)
767
+ def label_paths(text)
768
+ text.to_s.scan(Scanner::TAG_RE).filter_map do |tag|
769
+ raw = raw_of(tag)
770
+ next if raw.start_with?("#") || raw.start_with?("/")
771
+
772
+ raw.split(":", 2).first
773
+ end
774
+ end
775
+ end
776
+ end