@kensnzk/koyu 0.5.0 → 0.11.0

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.
Files changed (128) hide show
  1. package/README.ja.md +43 -11
  2. package/README.md +51 -11
  3. package/dist/check.d.ts +34 -0
  4. package/dist/check.d.ts.map +1 -0
  5. package/dist/check.js +500 -0
  6. package/dist/check.js.map +1 -0
  7. package/dist/cli.d.ts +3 -0
  8. package/dist/cli.d.ts.map +1 -0
  9. package/dist/cli.js +319 -0
  10. package/dist/cli.js.map +1 -0
  11. package/dist/diff.d.ts +90 -0
  12. package/dist/diff.d.ts.map +1 -0
  13. package/dist/diff.js +522 -0
  14. package/dist/diff.js.map +1 -0
  15. package/dist/graph.d.ts +81 -0
  16. package/dist/graph.d.ts.map +1 -0
  17. package/dist/graph.js +328 -0
  18. package/dist/graph.js.map +1 -0
  19. package/dist/index.d.ts +9 -0
  20. package/dist/index.d.ts.map +1 -0
  21. package/dist/index.js +10 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/light.d.ts +15 -0
  24. package/dist/light.d.ts.map +1 -0
  25. package/dist/light.js +55 -0
  26. package/dist/light.js.map +1 -0
  27. package/dist/mcp.d.ts +3 -0
  28. package/dist/mcp.d.ts.map +1 -0
  29. package/dist/mcp.js +354 -0
  30. package/dist/mcp.js.map +1 -0
  31. package/dist/model.d.ts +264 -0
  32. package/dist/model.d.ts.map +1 -0
  33. package/dist/model.js +361 -0
  34. package/dist/model.js.map +1 -0
  35. package/dist/parse-file.d.ts +9 -0
  36. package/dist/parse-file.d.ts.map +1 -0
  37. package/dist/parse-file.js +22 -0
  38. package/dist/parse-file.js.map +1 -0
  39. package/dist/parse.d.ts +16 -0
  40. package/dist/parse.d.ts.map +1 -0
  41. package/dist/parse.js +922 -0
  42. package/dist/parse.js.map +1 -0
  43. package/dist/plan.d.ts +8 -0
  44. package/dist/plan.d.ts.map +1 -0
  45. package/dist/plan.js +267 -0
  46. package/dist/plan.js.map +1 -0
  47. package/dist/site.d.ts +24 -0
  48. package/dist/site.d.ts.map +1 -0
  49. package/dist/site.js +53 -0
  50. package/dist/site.js.map +1 -0
  51. package/examples/comparison/README.md +16 -1
  52. package/examples/comparison/gen-ifc4.ts +1 -1
  53. package/examples/comparison/gen-ifcx.ts +2 -2
  54. package/examples/comparison/two-rooms.ifcx +1 -1
  55. package/examples/house/L1.muro +16 -0
  56. package/examples/house/L2.muro +19 -0
  57. package/examples/house/assets.muro +9 -0
  58. package/examples/house/main.muro +27 -0
  59. package/examples/house/site.muro +31 -0
  60. package/examples/house.muro +1 -1
  61. package/examples/mansion.muro +1 -1
  62. package/examples/office.muro +1 -1
  63. package/examples/steps/01-one-room.muro +4 -0
  64. package/examples/steps/02-two-rooms.muro +5 -0
  65. package/examples/steps/03-door.muro +9 -0
  66. package/examples/steps/04-exterior.muro +15 -0
  67. package/examples/steps/05-two-storeys.muro +27 -0
  68. package/examples/steps/06-finished.muro +30 -0
  69. package/examples/steps/README.md +25 -0
  70. package/examples/tower/L1.muro +80 -0
  71. package/examples/tower/L11.muro +47 -0
  72. package/examples/tower/L2.muro +69 -0
  73. package/examples/tower/L3.muro +28 -0
  74. package/examples/tower/assets.muro +13 -0
  75. package/examples/tower/main.muro +37 -0
  76. package/examples/tower/site-geometry.muro +7 -0
  77. package/examples/tower/site.muro +33 -0
  78. package/examples/tower/typical.muro +124 -0
  79. package/examples/two-rooms.canonical.json +5 -2
  80. package/examples/two-rooms.muro +6 -5
  81. package/package.json +28 -2
  82. package/src/check.ts +352 -63
  83. package/src/cli.ts +76 -11
  84. package/src/diff.ts +608 -0
  85. package/src/graph.ts +90 -10
  86. package/src/index.ts +14 -2
  87. package/src/mcp.ts +390 -0
  88. package/src/model.ts +260 -55
  89. package/src/parse-file.ts +28 -0
  90. package/src/parse.ts +562 -44
  91. package/src/plan.ts +33 -4
  92. package/src/site.ts +13 -5
  93. package/.github/workflows/ci.yml +0 -16
  94. package/.zenodo.json +0 -20
  95. package/CITATION.cff +0 -26
  96. package/docs/decisions/0001-notation-v0.md +0 -29
  97. package/docs/decisions/0002-height-and-offsets.md +0 -27
  98. package/docs/decisions/0003-uncounted-divisions.md +0 -36
  99. package/docs/decisions/0004-typical-floors.md +0 -21
  100. package/docs/decisions/0005-zones-and-unions.md +0 -23
  101. package/docs/decisions/0006-voids-and-light.md +0 -31
  102. package/docs/decisions/0007-semi-outdoor-air.md +0 -27
  103. package/docs/decisions/0008-vocabulary-and-level-attr.md +0 -23
  104. package/docs/decisions/0009-site-and-exterior.md +0 -29
  105. package/docs/ifc-coverage.md +0 -82
  106. package/docs/ifcx-notes.md +0 -25
  107. package/docs/img/house-L1.svg +0 -80
  108. package/docs/img/house-L2.svg +0 -53
  109. package/docs/img/mansion-L1.svg +0 -113
  110. package/docs/img/mansion-L10.svg +0 -111
  111. package/docs/img/mansion-L5.svg +0 -160
  112. package/docs/img/office-L1.svg +0 -116
  113. package/docs/img/office-L2.svg +0 -109
  114. package/docs/img/two-rooms.svg +0 -39
  115. package/docs/log/2026-07-22.md +0 -13
  116. package/docs/log/2026-07-23.md +0 -51
  117. package/docs/roadmap.md +0 -55
  118. package/docs/writing-architecture.md +0 -119
  119. package/spec/notation-v0.md +0 -164
  120. package/spec/vocabulary.md +0 -62
  121. package/test/core.test.ts +0 -171
  122. package/test/design2.test.ts +0 -97
  123. package/test/house.test.ts +0 -74
  124. package/test/mansion.test.ts +0 -99
  125. package/test/office.test.ts +0 -71
  126. package/test/uncounted.test.ts +0 -120
  127. package/test/vertical.test.ts +0 -75
  128. package/tsconfig.json +0 -13
package/src/parse.ts CHANGED
@@ -1,11 +1,14 @@
1
1
  // koyu v0 — 記法パーサ
2
2
  // 一行が一文。図面が数百年運んできた抽象度を、そのままテキストにする。
3
+ // import による合成 (ADR-0010): ファイル群を重ねて一つの模型にする。
4
+ // 分担して書き、合成時のコンフリクト (パス・アセット・グリッドの重複) は言葉のエラーになる。
3
5
 
4
6
  import {
5
7
  type Area,
6
8
  type Attrs,
7
9
  type AttrValue,
8
10
  type Boundary,
11
+ DEFAULT_LANGUAGE_VERSION,
9
12
  type Edge,
10
13
  type Model,
11
14
  type Opening,
@@ -13,67 +16,292 @@ import {
13
16
  type Seg,
14
17
  SourceError,
15
18
  type Space,
19
+ SUPPORTED_LANGUAGE_VERSIONS,
16
20
  } from "./model.js";
21
+ import { deriveDefaultBoundaries } from "./graph.js";
17
22
 
18
23
  const EDGES = new Set(["N", "E", "S", "W"]);
19
24
 
20
- export function parse(source: string): Model {
21
- const model: Model = {
22
- version: "0.1",
25
+ /**
26
+ * 帯 (band, ADR-0019) の宣言 — parse の局所状態であり Model には入らない。
27
+ * 帯は「位置ではなく寸法と並び」を書く記法で、垂直の矩計 (level の積み上げ) の水平版である。
28
+ * 展開すると通常の Space になるので、下流 (check/plan/graph/diff/light/site) は帯を知らない。
29
+ */
30
+ interface BandDecl {
31
+ axis: "X" | "Y";
32
+ /** 割る向きの区間 mm */
33
+ lo: number;
34
+ hi: number;
35
+ /** 帯の両端と直交方向の両端は「書かれた綴り」のまま要素へ渡す (意味保存の要) */
36
+ loRef: string;
37
+ hiRef: string;
38
+ crossA: string;
39
+ crossB: string;
40
+ members: BandMember[];
41
+ line: number;
42
+ }
43
+
44
+ interface BandMember {
45
+ path: string;
46
+ type: string;
47
+ /** 帯の向きの寸法mm。"rest" は残りを吸収する印 (帯に高々一つ) */
48
+ w: number | "rest";
49
+ attrTokens: string[];
50
+ line: number;
51
+ }
52
+
53
+ function emptyModel(): Model {
54
+ return {
55
+ version: DEFAULT_LANGUAGE_VERSION,
23
56
  unit: "mm",
24
57
  grid: { X: { names: [], coords: [] }, Y: { names: [], coords: [] } },
25
58
  levels: {},
26
59
  spaces: new Map(),
27
60
  zones: new Map(),
61
+ assets: new Map(),
28
62
  boundaries: [],
63
+ polygons: new Map(),
64
+ layers: [],
29
65
  };
66
+ }
67
+
68
+ /** レイヤーの読み込み口 — import の解決。fs版は parse-file.ts が、仮想版は parseFiles が与える。
69
+ * fromKey が undefined のときは entry 自身の解決 */
70
+ export type LayerLoader = (
71
+ fromKey: string | undefined,
72
+ ref: string,
73
+ ) => { key: string; src: string };
74
+
75
+ export function parse(source: string): Model {
76
+ const model = emptyModel();
77
+ ingest(model, source, undefined, new Set(), undefined);
78
+ deriveDefaultBoundaries(model); // 水平の既定は壁 (ADR-0014) — 合成・展開の完了後に一度だけ
79
+ return model;
80
+ }
81
+
82
+ /** ローダーを介した合成の入口。entry もローダーで読む (ADR-0010) */
83
+ export function parseWith(loader: LayerLoader, entry: string): Model {
84
+ const model = emptyModel();
85
+ let layer: { key: string; src: string };
86
+ try {
87
+ layer = loader(undefined, entry);
88
+ } catch {
89
+ throw new SourceError(0, `ファイルが読めません: ${entry}`);
90
+ }
91
+ ingestLayer(model, layer.key, layer.src, new Set(), loader);
92
+ deriveDefaultBoundaries(model); // 水平の既定は壁 (ADR-0014) — 合成・展開の完了後に一度だけ
93
+ return model;
94
+ }
30
95
 
96
+ /** 仮想ファイル群からの合成 — fsの無い環境 (ブラウザ等) 向け。
97
+ * キーはPOSIX風の相対パス (`L1.muro`, `floors/L1.muro`)。import はキー空間の中で解決される */
98
+ export function parseFiles(files: Record<string, string>, entry: string): Model {
99
+ const map = new Map(Object.entries(files).map(([k, v]) => [normKey(k), v]));
100
+ return parseWith((from, ref) => {
101
+ const key = from === undefined ? normKey(ref) : joinKey(dirKey(from), ref);
102
+ const src = map.get(key);
103
+ if (src === undefined) throw new Error(key);
104
+ return { key, src };
105
+ }, entry);
106
+ }
107
+
108
+ function normKey(p: string): string {
109
+ return joinKey("", p);
110
+ }
111
+ function dirKey(p: string): string {
112
+ const i = p.lastIndexOf("/");
113
+ return i < 0 ? "" : p.slice(0, i);
114
+ }
115
+ function joinKey(dir: string, rel: string): string {
116
+ const out: string[] = dir ? dir.split("/") : [];
117
+ for (const seg of rel.split("/")) {
118
+ if (seg === "" || seg === ".") continue;
119
+ if (seg === "..") out.pop();
120
+ else out.push(seg);
121
+ }
122
+ return out.join("/");
123
+ }
124
+
125
+ function ingestLayer(
126
+ model: Model,
127
+ key: string,
128
+ src: string,
129
+ seen: Set<string>,
130
+ loader: LayerLoader | undefined,
131
+ ): void {
132
+ if (seen.has(key)) return; // 同じレイヤーは一度だけ合成される (USDのsublayerと同じ)
133
+ seen.add(key);
134
+ model.layers.push(key); // 合成への参加を要素の有無によらず記録する (grid/levelだけの層も数える)
135
+ ingest(model, src, key, seen, loader);
136
+ }
137
+
138
+ function ingest(
139
+ model: Model,
140
+ source: string,
141
+ file: string | undefined,
142
+ seen: Set<string>,
143
+ loader: LayerLoader | undefined,
144
+ ): void {
31
145
  let current: Boundary[] = [];
32
146
  let currentSpaces: Space[] = [];
147
+ let band: BandDecl | undefined; // 帯は次の非字下げ行か層の終わりで展開される (ADR-0019)
33
148
  const lines = source.split(/\r?\n/);
34
149
 
35
150
  for (let i = 0; i < lines.length; i++) {
36
- const raw = lines[i]!;
37
- const ln = i + 1;
38
- const tokens = tokenize(raw, ln);
39
- if (tokens.length === 0) continue;
40
- const indented = /^\s/.test(raw);
41
- const [head, ...rest] = tokens as [string, ...string[]];
151
+ try {
152
+ const raw = lines[i]!;
153
+ const ln = i + 1;
154
+ const tokens = tokenize(raw, ln);
155
+ if (tokens.length === 0) continue;
156
+ const indented = /^\s/.test(raw);
157
+ const [head, ...rest] = tokens as [string, ...string[]];
42
158
 
43
159
  if (indented) {
44
160
  if (head === "door" || head === "window") {
45
161
  if (current.length === 0) {
46
162
  throw new SourceError(ln, `${head} は boundary の直下に字下げして書きます`);
47
163
  }
48
- for (const b of current) b.openings.push(parseOpening(head, rest, ln));
164
+ for (const b of current) b.openings.push(parseOpening(head, rest, ln, model));
49
165
  } else if (head === "seg") {
50
166
  if (current.length === 0) {
51
167
  throw new SourceError(ln, "seg は boundary の直下に字下げして書きます");
52
168
  }
53
- for (const b of current) b.segs.push(parseSeg(rest, ln));
169
+ for (const b of current) b.segs.push(parseSeg(rest, ln, model));
54
170
  } else if (head === "area") {
171
+ if (band) {
172
+ throw new SourceError(
173
+ ln,
174
+ "band の要素に area は書けません (領域が導出のため — area が要る室は位置で書きます)",
175
+ );
176
+ }
55
177
  if (currentSpaces.length === 0) {
56
178
  throw new SourceError(ln, "area は space の直下に字下げして書きます");
57
179
  }
58
180
  for (const s of currentSpaces) s.areas.push(parseArea(rest, ln, model));
181
+ } else if (head === "space") {
182
+ // 帯の要素 — 領域の代わりに幅 w: を持つ space 行 (ADR-0019)
183
+ if (!band) throw new SourceError(ln, "字下げした space は band の直下に書きます");
184
+ band.members.push(parseBandMember(rest, ln));
59
185
  } else {
60
186
  throw new SourceError(
61
187
  ln,
62
- `字下げ行に置けるのは door / window / seg / area のみです: ${head}`,
188
+ `字下げ行に置けるのは door / window / seg / area / space (band の要素) のみです: ${head}`,
63
189
  );
64
190
  }
65
191
  continue;
66
192
  }
67
193
 
194
+ // 帯は次の非字下げ行の直前に展開する (パス重複の検出順を宣言順に保つ)
195
+ if (band) {
196
+ expandBand(model, band, file);
197
+ band = undefined;
198
+ }
68
199
  current = [];
69
200
  currentSpaces = [];
70
201
  switch (head) {
71
202
  case "koyu": {
72
- model.version = rest[0] ?? "0.1";
203
+ const v = rest[0];
204
+ if (!v) throw new SourceError(ln, `koyu には版を書きます: koyu ${DEFAULT_LANGUAGE_VERSION}`);
205
+ if (rest.length > 1) {
206
+ throw new SourceError(ln, `koyu の版宣言に余分なトークンがあります: ${rest.slice(1).join(" ")}`);
207
+ }
208
+ if (!SUPPORTED_LANGUAGE_VERSIONS.includes(v)) {
209
+ throw new SourceError(
210
+ ln,
211
+ `対応していないkoyuの版です: ${v} (このツールの対応: ${SUPPORTED_LANGUAGE_VERSIONS.join(", ")})`,
212
+ );
213
+ }
214
+ // 版はbase層 (entry) でのみ・一度だけ宣言する — 合成順による黙った上書きを禁じる (ADR-0017)。
215
+ // gridの規律に合わせ、再宣言は同値でもエラー
216
+ if (file !== undefined && model.layers[0] !== file) {
217
+ throw new SourceError(ln, "koyu の版宣言はbase層 (entry) でのみ書きます");
218
+ }
219
+ if (model.versionDeclared) {
220
+ throw new SourceError(ln, `koyu の版は一度だけ宣言します (既に ${model.version})`);
221
+ }
222
+ model.version = v;
223
+ model.versionDeclared = true;
224
+ break;
225
+ }
226
+ case "import": {
227
+ const rel = rest[0];
228
+ if (!rel) throw new SourceError(ln, "import には相対パスを書きます: import ./assets.muro");
229
+ if (!loader) {
230
+ throw new SourceError(
231
+ ln,
232
+ "import はファイル合成 (parseFile / parseFiles / CLI) でのみ使えます",
233
+ );
234
+ }
235
+ let layer: { key: string; src: string };
236
+ try {
237
+ layer = loader(file, rel);
238
+ } catch {
239
+ throw new SourceError(ln, `ファイルが読めません: ${rel}`);
240
+ }
241
+ ingestLayer(model, layer.key, layer.src, seen, loader);
242
+ break;
243
+ }
244
+ case "asset": {
245
+ // 建具アセット (RevitのFamily / USDのReference — ADR-0010)
246
+ const aname = rest[0];
247
+ const akind = rest[1];
248
+ if (!aname || aname.includes(":") || aname.startsWith("/")) {
249
+ throw new SourceError(ln, "asset は asset <名> door|window [属性...] の形で書きます");
250
+ }
251
+ if (akind !== "door" && akind !== "window") {
252
+ throw new SourceError(ln, `asset の種別は door / window です: ${akind}`);
253
+ }
254
+ const prevA = model.assets.get(aname);
255
+ if (prevA) {
256
+ throw new SourceError(
257
+ ln,
258
+ `アセット名が重複しています: ${aname} (既出: ${prevA.file ?? "同ファイル"}:${prevA.line}行目)`,
259
+ );
260
+ }
261
+ model.assets.set(aname, {
262
+ name: aname,
263
+ kind: akind,
264
+ attrs: parseAttrs(rest.slice(2), ln),
265
+ line: ln,
266
+ ...(file ? { file } : {}),
267
+ });
268
+ break;
269
+ }
270
+ case "polygon": {
271
+ // 敷地形状 (ADR-0011) — 所与のジオメトリ。唯一、書かれる形。
272
+ // polygon /site -2600,-7000 38000,-7000 38000,15600 2000,16800 -2600,12000
273
+ const ppath = rest[0];
274
+ if (!ppath || !ppath.startsWith("/")) {
275
+ throw new SourceError(ln, "polygon は polygon /ゾーンパス x,y x,y x,y ... の形で書きます");
276
+ }
277
+ const pts = rest.slice(1).map((tok) => {
278
+ const m = /^(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)$/.exec(tok);
279
+ if (!m) throw new SourceError(ln, `頂点が読めません (x,y のmm座標): ${tok}`);
280
+ return { x: Number(m[1]), y: Number(m[2]) };
281
+ });
282
+ if (pts.length < 3) throw new SourceError(ln, "polygon には頂点を3つ以上書きます");
283
+ const prevP = model.polygons.get(ppath);
284
+ if (prevP) {
285
+ throw new SourceError(
286
+ ln,
287
+ `敷地形状が重複しています: ${ppath} (既出: ${prevP.file ?? "同ファイル"}:${prevP.line}行目)`,
288
+ );
289
+ }
290
+ model.polygons.set(ppath, {
291
+ path: ppath,
292
+ points: pts,
293
+ line: ln,
294
+ ...(file ? { file } : {}),
295
+ });
73
296
  break;
74
297
  }
75
298
  case "name": {
76
- model.name = rest.join(" ");
299
+ const nm = rest.join(" ");
300
+ if (!nm) throw new SourceError(ln, "name には値を書きます");
301
+ if (model.name !== undefined && model.name !== nm) {
302
+ throw new SourceError(ln, `name は一度だけ宣言します (既に「${model.name}」— 合成時はbase層で)`);
303
+ }
304
+ model.name = nm;
77
305
  break;
78
306
  }
79
307
  case "unit": {
@@ -85,6 +313,9 @@ export function parse(source: string): Model {
85
313
  if (axis !== "X" && axis !== "Y") {
86
314
  throw new SourceError(ln, `grid の軸は X か Y です: ${axis}`);
87
315
  }
316
+ if (model.grid[axis].coords.length > 0) {
317
+ throw new SourceError(ln, `grid ${axis} は一度だけ宣言します (合成時はbase層で)`);
318
+ }
88
319
  const coords = rest.slice(1).map((t) => toNumber(t, ln, "gridの座標"));
89
320
  if (coords.length < 2) throw new SourceError(ln, "grid には座標を2つ以上書きます");
90
321
  for (let k = 1; k < coords.length; k++) {
@@ -103,9 +334,9 @@ export function parse(source: string): Model {
103
334
  if (!name) throw new SourceError(ln, "level には名前が要ります");
104
335
  const z = toNumber(rest[1] ?? "", ln, "levelの高さ(z)");
105
336
  const attrs = parseAttrs(rest.slice(2), ln);
106
- const h = takeNumber(attrs, "h");
107
- const slab = takeNumber(attrs, "slab");
108
- const pitch = takeNumber(attrs, "pitch");
337
+ const h = takeNumber(attrs, "h", ln);
338
+ const slab = takeNumber(attrs, "slab", ln);
339
+ const pitch = takeNumber(attrs, "pitch", ln);
109
340
 
110
341
  // 範囲宣言: level L3..L9 6700 pitch:2900 — 基準階のレベルを一度に宣言する
111
342
  const range = /^([A-Za-z]+)(\d+)\.\.([A-Za-z]+)(\d+)$/.exec(name);
@@ -141,14 +372,31 @@ export function parse(source: string): Model {
141
372
  };
142
373
  break;
143
374
  }
375
+ case "band": {
376
+ // 帯 (ADR-0019) — 寸法と並びを書き、位置を導く。宣言はここ、展開は次の非字下げ行の直前
377
+ band = parseBandHead(rest, ln, model);
378
+ break;
379
+ }
144
380
  case "space": {
145
381
  const path = rest[0];
146
382
  if (!path) throw new SourceError(ln, "space にはパスが要ります");
383
+ // w: は帯の要素の語 — 字下げを落とした要素が「領域なしの空間」として黙って通るのを防ぐ
384
+ if (rest.some((t) => t === "w:" || t.startsWith("w:"))) {
385
+ throw new SourceError(
386
+ ln,
387
+ "space に w: は書けません (幅で書く空間は band の直下に字下げします)",
388
+ );
389
+ }
147
390
  for (const [p] of expandSpan(model, [path], ln)) {
148
391
  const space = parseSpace([p!, ...rest.slice(1)], ln, model);
149
- if (model.spaces.has(space.path)) {
150
- throw new SourceError(ln, `空間パスが重複しています: ${space.path}`);
392
+ const prevS = model.spaces.get(space.path);
393
+ if (prevS) {
394
+ throw new SourceError(
395
+ ln,
396
+ `空間パスが重複しています: ${space.path} (既出: ${prevS.file ?? "同ファイル"}:${prevS.line}行目)`,
397
+ );
151
398
  }
399
+ if (file) space.file = file;
152
400
  model.spaces.set(space.path, space);
153
401
  currentSpaces.push(space);
154
402
  }
@@ -162,6 +410,7 @@ export function parse(source: string): Model {
162
410
  }
163
411
  for (const [ea, eb] of expandSpan(model, [pa, pb], ln)) {
164
412
  const b = parseBoundary([ea!, eb!, ...rest.slice(2)], ln);
413
+ if (file) b.file = file;
165
414
  model.boundaries.push(b);
166
415
  current.push(b);
167
416
  }
@@ -174,10 +423,19 @@ export function parse(source: string): Model {
174
423
  throw new SourceError(ln, "zone は zone /パス [属性...] の形で書きます");
175
424
  }
176
425
  for (const [p] of expandSpan(model, [zpath], ln)) {
177
- if (model.zones.has(p!)) {
178
- throw new SourceError(ln, `ゾーンパスが重複しています: ${p}`);
426
+ const prevZ = model.zones.get(p!);
427
+ if (prevZ) {
428
+ throw new SourceError(
429
+ ln,
430
+ `ゾーンパスが重複しています: ${p} (既出: ${prevZ.file ?? "同ファイル"}:${prevZ.line}行目)`,
431
+ );
179
432
  }
180
- model.zones.set(p!, { path: p!, attrs: parseAttrs(rest.slice(1), ln), line: ln });
433
+ model.zones.set(p!, {
434
+ path: p!,
435
+ attrs: parseAttrs(rest.slice(1), ln),
436
+ line: ln,
437
+ ...(file ? { file } : {}),
438
+ });
181
439
  }
182
440
  break;
183
441
  }
@@ -203,6 +461,7 @@ export function parse(source: string): Model {
203
461
  openings: [],
204
462
  segs: [],
205
463
  line: ln,
464
+ ...(file ? { file } : {}),
206
465
  };
207
466
  model.boundaries.push(b);
208
467
  current.push(b);
@@ -212,8 +471,25 @@ export function parse(source: string): Model {
212
471
  default:
213
472
  throw new SourceError(ln, `未知のキーワードです: ${head}`);
214
473
  }
474
+ } catch (e) {
475
+ // 合成時はどのファイルのエラーかを言葉にする
476
+ if (e instanceof SourceError && !e.file && file) {
477
+ throw new SourceError(e.line, e.raw, file);
478
+ }
479
+ throw e;
480
+ }
481
+ }
482
+ // 層の終わりで閉じる帯 (最終行が帯の要素だった場合)
483
+ if (band) {
484
+ try {
485
+ expandBand(model, band, file);
486
+ } catch (e) {
487
+ if (e instanceof SourceError && !e.file && file) {
488
+ throw new SourceError(e.line, e.raw, file);
489
+ }
490
+ throw e;
491
+ }
215
492
  }
216
- return model;
217
493
  }
218
494
 
219
495
  // ---- 各要素 ----
@@ -258,6 +534,193 @@ function parseSpace(rest: string[], ln: number, model: Model): Space {
258
534
  return space;
259
535
  }
260
536
 
537
+ // ---- 帯 (band) — 寸法と並びから位置を導く (ADR-0019) ----
538
+
539
+ /** `band <軸> <X?..X?> <Y?..Y?>` の見出し行。key:value は書けない (帯は残らないので運び先が無い) */
540
+ function parseBandHead(rest: string[], ln: number, model: Model): BandDecl {
541
+ const axis = rest[0];
542
+ if (axis !== "X" && axis !== "Y") {
543
+ throw new SourceError(
544
+ ln,
545
+ `band の割る向きは X か Y です: ${axis ?? "(無し)"} (band X X1..X2 Y1..Y2 の形で書きます)`,
546
+ );
547
+ }
548
+ const tail = rest.slice(1);
549
+ const extra = tail.filter((t) => !t.includes(".."));
550
+ if (extra.length > 0) {
551
+ throw new SourceError(
552
+ ln,
553
+ `band の行に書けるのは 軸と領域だけです (属性は要素の space 行に書きます): ${extra.join(" ")}`,
554
+ );
555
+ }
556
+ // 逆順表記は space では同じ矩形の別綴りだが、帯では並びの向きが意味を持つので許さない
557
+ for (const t of tail) {
558
+ const [p, q] = t.split("..");
559
+ if (!p || !q) throw new SourceError(ln, `領域指定が読めません: ${t}`);
560
+ const rp = resolveRef(model, p, ln);
561
+ const rq = resolveRef(model, q, ln);
562
+ if (rp.axis === rq.axis && rp.coord > rq.coord) {
563
+ throw new SourceError(
564
+ ln,
565
+ `band の範囲は昇順で書きます (要素は 西→東 / 南→北 に並びます): ${t}`,
566
+ );
567
+ }
568
+ }
569
+ const r = parseRegion(tail, ln, model); // 軸の対・幅ゼロ・未定義の通り名は既存の言葉で弾かれる
570
+ return {
571
+ axis,
572
+ lo: axis === "X" ? r.rect.x1 : r.rect.y1,
573
+ hi: axis === "X" ? r.rect.x2 : r.rect.y2,
574
+ loRef: axis === "X" ? r.grid.xa : r.grid.ya,
575
+ hiRef: axis === "X" ? r.grid.xb : r.grid.yb,
576
+ crossA: axis === "X" ? r.grid.ya : r.grid.xa,
577
+ crossB: axis === "X" ? r.grid.yb : r.grid.xb,
578
+ members: [],
579
+ line: ln,
580
+ };
581
+ }
582
+
583
+ /** 帯の要素: `space <パス> <型> w:<mm>|w:rest [属性...]` — 領域の代わりに寸法を持つ space 行 */
584
+ function parseBandMember(rest: string[], ln: number): BandMember {
585
+ const path = rest[0];
586
+ if (!path?.startsWith("/")) {
587
+ throw new SourceError(ln, "band の要素は space /パス 型 w:(mm) の形で書きます");
588
+ }
589
+ const type = rest[1];
590
+ // 型の位置に k:v が来たら「型の書き忘れ」— 幅の欠落として誤報しない
591
+ if (!type || type.includes(":")) {
592
+ throw new SourceError(ln, `band の要素 ${path} に型(語彙)が要ります`);
593
+ }
594
+ let w: number | "rest" | undefined;
595
+ const attrTokens: string[] = [];
596
+ for (const t of rest.slice(2)) {
597
+ if (t === "+" || t.includes("..")) {
598
+ throw new SourceError(ln, `band の要素に領域は書けません (帯と w: が与えます): ${t}`);
599
+ }
600
+ if (t.startsWith("level:")) {
601
+ throw new SourceError(
602
+ ln,
603
+ `band の要素に level: は書けません (帯は一つのレベルの並びです): ${t}`,
604
+ );
605
+ }
606
+ if (t.startsWith("w:")) {
607
+ if (w !== undefined) throw new SourceError(ln, "属性キーが重複しています: w");
608
+ const v = t.slice(2);
609
+ if (v === "rest") w = "rest";
610
+ else if (/^\d+$/.test(v) && Number(v) > 0) w = Number(v);
611
+ else throw new SourceError(ln, `band の要素の幅は正の整数mm か rest で書きます: ${t}`);
612
+ continue;
613
+ }
614
+ attrTokens.push(t);
615
+ }
616
+ if (w === undefined) {
617
+ throw new SourceError(ln, `band の要素には幅 w:(mm) か w:rest が要ります: ${path}`);
618
+ }
619
+ return { path, type, w, attrTokens, line: ln };
620
+ }
621
+
622
+ /**
623
+ * resolveRef の逆 — 導かれた切り位置を通り参照に綴る「床規則」:
624
+ * その座標**以下**で最も大きい通り芯からのオフセット (オフセット0なら通り名だけ)。
625
+ * 上の通り芯から引く綴り (Y2-1800) は導出では生じない。
626
+ */
627
+ function spellRef(model: Model, axis: "X" | "Y", c: number, ln: number): string {
628
+ const g = model.grid[axis];
629
+ if (!Number.isInteger(c)) {
630
+ throw new SourceError(ln, `導かれた切り位置が整数mmになりません: ${c}`);
631
+ }
632
+ let i = 0;
633
+ for (let k = 0; k < g.coords.length; k++) if (g.coords[k]! <= c) i = k;
634
+ const off = c - g.coords[i]!;
635
+ if (off === 0) return g.names[i]!;
636
+ return `${g.names[i]}${off > 0 ? "+" : ""}${off}`;
637
+ }
638
+
639
+ /** 帯を通常の Space へ展開する。一方向・順序付き・決定的 — 足し算と一回の引き算だけ */
640
+ function expandBand(model: Model, band: BandDecl, file: string | undefined): void {
641
+ const { axis, lo, hi, members } = band;
642
+ if (members.length === 0) {
643
+ throw new SourceError(band.line, "band の下に space を字下げして1つ以上書きます");
644
+ }
645
+ const extent = hi - lo;
646
+ let sum = 0;
647
+ let restAt = -1;
648
+ for (let k = 0; k < members.length; k++) {
649
+ const m = members[k]!;
650
+ if (m.w === "rest") {
651
+ if (restAt >= 0) {
652
+ throw new SourceError(
653
+ m.line,
654
+ `残りを吸収する要素 (w:rest) は帯に一つだけです: ${members[restAt]!.path}, ${m.path}`,
655
+ );
656
+ }
657
+ restAt = k;
658
+ } else sum += m.w;
659
+ }
660
+ const list = members.map((m) => ` ${m.path} w:${m.w}`).join("\n");
661
+ if (sum > extent) {
662
+ throw new SourceError(
663
+ band.line,
664
+ `帯の幅 ${extent}mm に対し寸法の合計が ${sum}mm で、${sum - extent}mm 超えています\n${list}`,
665
+ );
666
+ }
667
+ const widths = members.map((m) => (m.w === "rest" ? 0 : m.w));
668
+ if (restAt >= 0) {
669
+ if (sum === extent) {
670
+ throw new SourceError(
671
+ members[restAt]!.line,
672
+ `帯の幅 ${extent}mm を他の寸法が使い切っていて、${members[restAt]!.path} (w:rest) の残りがゼロです`,
673
+ );
674
+ }
675
+ widths[restAt] = extent - sum;
676
+ } else if (sum < extent) {
677
+ throw new SourceError(
678
+ band.line,
679
+ `帯の幅 ${extent}mm に対し寸法の合計が ${sum}mm で、${extent - sum}mm 足りません ` +
680
+ `(寸法を直すか、どれかを w:rest にします)\n${list}`,
681
+ );
682
+ }
683
+
684
+ // レベルスパンは全要素をまとめて一度だけ展開する (帯の中で揃っていることを先に確かめる)
685
+ const iterations = expandSpan(model, members.map((m) => m.path), band.line);
686
+ for (const it of iterations) {
687
+ const lv = new Set(it.map((p) => p.split("/")[1]));
688
+ if (lv.size > 1) {
689
+ throw new SourceError(
690
+ band.line,
691
+ `帯の要素は同じレベルに展開します: ${it.map((p) => `${p} → ${p.split("/")[1]}`).join(", ")}`,
692
+ );
693
+ }
694
+ }
695
+
696
+ for (const it of iterations) {
697
+ let cursor = lo;
698
+ for (let k = 0; k < members.length; k++) {
699
+ const m = members[k]!;
700
+ const a = cursor;
701
+ const b = cursor + widths[k]!;
702
+ cursor = b;
703
+ // 帯の両端は書かれた綴りのまま。内側の切り位置だけを綴る (これが意味保存の要)
704
+ const aRef = a === lo ? band.loRef : spellRef(model, axis, a, m.line);
705
+ const bRef = b === hi ? band.hiRef : spellRef(model, axis, b, m.line);
706
+ const along = `${aRef}..${bRef}`;
707
+ const cross = `${band.crossA}..${band.crossB}`;
708
+ const xTok = axis === "X" ? along : cross;
709
+ const yTok = axis === "X" ? cross : along;
710
+ const space = parseSpace([it[k]!, m.type, xTok, yTok, ...m.attrTokens], m.line, model);
711
+ const prev = model.spaces.get(space.path);
712
+ if (prev) {
713
+ throw new SourceError(
714
+ m.line,
715
+ `空間パスが重複しています: ${space.path} (既出: ${prev.file ?? "同ファイル"}:${prev.line}行目)`,
716
+ );
717
+ }
718
+ if (file) space.file = file;
719
+ model.spaces.set(space.path, space);
720
+ }
721
+ }
722
+ }
723
+
261
724
  /** 領域指定 (X?..X? Y?..Y?) をグリッド参照とmm矩形に解決する */
262
725
  function parseRegion(
263
726
  regionTokens: string[],
@@ -279,12 +742,15 @@ function parseRegion(
279
742
  if (rp.axis !== rq.axis) {
280
743
  throw new SourceError(ln, `領域の両端は同じ軸の通りで指定します: ${t}`);
281
744
  }
745
+ // 逆順表記 (X2..X1) は同じ矩形の別綴り — 座標昇順に正規化して保存する (正準JSON・diffが揃う)
746
+ const [lo, hi] = rp.coord <= rq.coord ? [[rp.coord, p] as const, [rq.coord, q] as const]
747
+ : [[rq.coord, q] as const, [rp.coord, p] as const];
282
748
  if (rp.axis === "X") {
283
- xr = [rp.coord, rq.coord];
284
- xg = [p, q];
749
+ xr = [lo[0], hi[0]];
750
+ xg = [lo[1], hi[1]];
285
751
  } else {
286
- yr = [rp.coord, rq.coord];
287
- yg = [p, q];
752
+ yr = [lo[0], hi[0]];
753
+ yg = [lo[1], hi[1]];
288
754
  }
289
755
  }
290
756
  if (!xr || !yr || !xg || !yg) {
@@ -311,16 +777,37 @@ function parseArea(rest: string[], ln: number, model: Model): Area {
311
777
  }
312
778
 
313
779
  /** 数えない分節: 境界上の区間 (壁材の途中変更など) */
314
- function parseSeg(rest: string[], ln: number): Seg {
780
+ function parseSeg(rest: string[], ln: number, model: Model): Seg {
315
781
  const attrs = parseAttrs(rest, ln);
316
- const w = takeNumber(attrs, "w");
782
+ const w = takeNumber(attrs, "w", ln);
317
783
  if (w === undefined || w <= 0) {
318
784
  throw new SourceError(ln, "seg には幅 w:(mm) が要ります");
319
785
  }
320
- const at = takeNumber(attrs, "at") ?? 0.5;
321
- if (at < 0 || at > 1) throw new SourceError(ln, "at は 0..1 で指定します");
786
+ const at = parseAt(attrs, ln, model);
322
787
  const edge = takeEdge(attrs, ln);
323
- return { w, at, ...(edge ? { edge } : {}), attrs, line: ln };
788
+ return { w, ...at, ...(edge ? { edge } : {}), attrs, line: ln };
789
+ }
790
+
791
+ /**
792
+ * 位置指定: at は 0..1 の比率 (クランプされる) か、通り参照 (at:X2+450 — 明示位置)。
793
+ * 明示位置ははみ出しをクランプせずエラーにする (placeBand)
794
+ */
795
+ function parseAt(
796
+ attrs: Attrs,
797
+ ln: number,
798
+ model: Model,
799
+ ): { at: number; atRef?: string; atAbs?: number; atAxis?: "X" | "Y" } {
800
+ const v = attrs["at"];
801
+ if (v === undefined) return { at: 0.5 };
802
+ delete attrs["at"];
803
+ if (typeof v === "number") {
804
+ if (v < 0 || v > 1) {
805
+ throw new SourceError(ln, "at は 0..1 の比率か、通り参照 (at:X2+450) で指定します");
806
+ }
807
+ return { at: v };
808
+ }
809
+ const r = resolveRef(model, v, ln);
810
+ return { at: 0.5, atRef: v, atAbs: r.coord, atAxis: r.axis };
324
811
  }
325
812
 
326
813
  /** レベルのスパン (L2..L9) を、宣言済みレベルのz順の並びに解決する */
@@ -385,7 +872,7 @@ function parseBoundary(rest: string[], ln: number): Boundary {
385
872
  throw new SourceError(ln, "boundary は boundary /パスA /パスB [属性...] の形で書きます");
386
873
  }
387
874
  const attrs = parseAttrs(rest.slice(2), ln);
388
- const t = takeNumber(attrs, "t");
875
+ const t = takeNumber(attrs, "t", ln);
389
876
  const kindRaw = takeString(attrs, "type") ?? "wall";
390
877
  if (!["wall", "open", "stair", "shaft", "void"].includes(kindRaw)) {
391
878
  throw new SourceError(
@@ -393,7 +880,7 @@ function parseBoundary(rest: string[], ln: number): Boundary {
393
880
  `boundary の type は wall / open / stair / shaft / void です: ${kindRaw}`,
394
881
  );
395
882
  }
396
- const air = takeNumber(attrs, "air");
883
+ const air = takeNumber(attrs, "air", ln);
397
884
  if (air !== undefined && air !== 0 && air !== 1) {
398
885
  throw new SourceError(ln, "air は 0 / 1 で指定します (1=遮蔽しない: 手すり・柵など)");
399
886
  }
@@ -412,15 +899,37 @@ function parseBoundary(rest: string[], ln: number): Boundary {
412
899
  };
413
900
  }
414
901
 
415
- function parseOpening(kind: "door" | "window", rest: string[], ln: number): Opening {
416
- const attrs = parseAttrs(rest, ln);
417
- const w = takeNumber(attrs, "w");
902
+ function parseOpening(
903
+ kind: "door" | "window",
904
+ rest: string[],
905
+ ln: number,
906
+ model: Model,
907
+ ): Opening {
908
+ // 先頭の非 key:value トークンは建具アセット参照 (Instance←Reference — ADR-0010)。
909
+ // アセットの属性を既定とし、インスタンスの属性が上書きする
910
+ let ref: string | undefined;
911
+ let tokens = rest;
912
+ if (rest[0] && !rest[0].includes(":") && !rest[0].startsWith("/")) {
913
+ ref = rest[0];
914
+ tokens = rest.slice(1);
915
+ }
916
+ const attrs: Attrs = {};
917
+ if (ref) {
918
+ const asset = model.assets.get(ref);
919
+ if (!asset) throw new SourceError(ln, `未定義の建具アセットです: ${ref}`);
920
+ if (asset.kind !== kind) {
921
+ throw new SourceError(ln, `アセット ${ref} は ${asset.kind} です (${kind} として使えません)`);
922
+ }
923
+ Object.assign(attrs, asset.attrs);
924
+ }
925
+ Object.assign(attrs, parseAttrs(tokens, ln));
926
+
927
+ const w = takeNumber(attrs, "w", ln);
418
928
  if (w === undefined || w <= 0) {
419
- throw new SourceError(ln, `${kind} には幅 w:(mm) が要ります`);
929
+ throw new SourceError(ln, `${kind} には幅 w:(mm) が要ります (アセット側でも可)`);
420
930
  }
421
- const h = takeNumber(attrs, "h");
422
- const at = takeNumber(attrs, "at") ?? 0.5;
423
- if (at < 0 || at > 1) throw new SourceError(ln, "at は 0..1 で指定します");
931
+ const h = takeNumber(attrs, "h", ln);
932
+ const at = parseAt(attrs, ln, model);
424
933
  const edge = takeEdge(attrs, ln);
425
934
  const hingeRaw = takeString(attrs, "hinge");
426
935
  if (hingeRaw !== undefined && !EDGES.has(hingeRaw)) {
@@ -432,9 +941,10 @@ function parseOpening(kind: "door" | "window", rest: string[], ln: number): Open
432
941
  }
433
942
  return {
434
943
  kind,
944
+ ...(ref ? { ref } : {}),
435
945
  w,
436
946
  ...(h !== undefined ? { h } : {}),
437
- at,
947
+ ...at,
438
948
  ...(edge ? { edge } : {}),
439
949
  ...(hingeRaw ? { hinge: hingeRaw as Edge } : {}),
440
950
  ...(swingRaw ? { swing: swingRaw as "a" | "b" } : {}),
@@ -476,6 +986,10 @@ function parseAttrs(tokens: string[], ln: number): Attrs {
476
986
  const key = t.slice(0, idx);
477
987
  const rawVal = t.slice(idx + 1);
478
988
  if (rawVal === "") throw new SourceError(ln, `属性 ${key} に値がありません`);
989
+ if (attrs[key] !== undefined) {
990
+ // 後勝ちの黙認はtypoとマージ事故を隠す — 同一行内の重複はエラー (ADR-0013)
991
+ throw new SourceError(ln, `属性キーが重複しています: ${key}`);
992
+ }
479
993
  attrs[key] = maybeNumber(rawVal);
480
994
  }
481
995
  return attrs;
@@ -490,11 +1004,15 @@ function toNumber(v: string, ln: number, what: string): number {
490
1004
  return Number(v);
491
1005
  }
492
1006
 
493
- function takeNumber(attrs: Attrs, key: string): number | undefined {
1007
+ function takeNumber(attrs: Attrs, key: string, ln: number): number | undefined {
494
1008
  const v = attrs[key];
495
1009
  if (v === undefined) return undefined;
496
1010
  delete attrs[key];
497
- return typeof v === "number" ? v : Number.NaN;
1011
+ if (typeof v !== "number") {
1012
+ // NaNの黙認はcheck緑のまま導出を壊す (typo h:24O0 など) — その場のエラーにする
1013
+ throw new SourceError(ln, `属性 ${key} は数値で書きます: ${v}`);
1014
+ }
1015
+ return v;
498
1016
  }
499
1017
 
500
1018
  function takeString(attrs: Attrs, key: string): string | undefined {