@chikx/compiler 0.1.0 → 0.1.1

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 (85) hide show
  1. package/README.md +5 -5
  2. package/package.json +3 -3
  3. package/src/emitter/index.ts +658 -0
  4. package/src/formatter/index.ts +544 -0
  5. package/src/host/node.ts +85 -0
  6. package/src/index.ts +1021 -0
  7. package/src/ir/factories.ts +85 -0
  8. package/src/ir/index.ts +28 -0
  9. package/src/ir/types.ts +145 -0
  10. package/src/lexer/at-keywords.ts +35 -0
  11. package/src/lexer/characters.ts +82 -0
  12. package/src/lexer/comments.ts +27 -0
  13. package/src/lexer/diagnostics.ts +42 -0
  14. package/src/lexer/dollar-refs.ts +23 -0
  15. package/src/lexer/index.ts +37 -0
  16. package/src/lexer/names.ts +49 -0
  17. package/src/lexer/numbers.ts +59 -0
  18. package/src/lexer/scanner.ts +199 -0
  19. package/src/lexer/strings.ts +52 -0
  20. package/src/lexer/urls.ts +63 -0
  21. package/src/lowering/expand-groups.ts +206 -0
  22. package/src/lowering/group.ts +119 -0
  23. package/src/lowering/index.ts +43 -0
  24. package/src/lowering/lower.ts +441 -0
  25. package/src/lowering/media.ts +314 -0
  26. package/src/lowering/merge.ts +163 -0
  27. package/src/lowering/property-families.ts +194 -0
  28. package/src/lowering/spans.ts +118 -0
  29. package/src/naming/index.ts +44 -0
  30. package/src/naming/mapgen.ts +252 -0
  31. package/src/naming/merge.ts +114 -0
  32. package/src/naming/rewrite.ts +333 -0
  33. package/src/naming/scan.ts +267 -0
  34. package/src/naming/table.ts +153 -0
  35. package/src/naming/types.ts +100 -0
  36. package/src/output/import-path.ts +30 -0
  37. package/src/output/index.ts +213 -0
  38. package/src/output/manifest.ts +28 -0
  39. package/src/output/paths.ts +200 -0
  40. package/src/output/resolve.ts +401 -0
  41. package/src/output/validate.ts +251 -0
  42. package/src/parser/cursor.ts +138 -0
  43. package/src/parser/declaration.ts +247 -0
  44. package/src/parser/diagnostics.ts +75 -0
  45. package/src/parser/group.ts +303 -0
  46. package/src/parser/index.ts +50 -0
  47. package/src/parser/modifier.ts +60 -0
  48. package/src/parser/recovery.ts +88 -0
  49. package/src/parser/rule.ts +370 -0
  50. package/src/parser/statement.ts +47 -0
  51. package/src/parser/statements.ts +667 -0
  52. package/src/parser/value.ts +265 -0
  53. package/src/resolver/graph.ts +467 -0
  54. package/src/resolver/groups.ts +177 -0
  55. package/src/resolver/index.ts +68 -0
  56. package/src/resolver/keyframes.ts +131 -0
  57. package/src/resolver/paths.ts +142 -0
  58. package/src/resolver/rules.ts +54 -0
  59. package/src/resolver/scopes.ts +342 -0
  60. package/src/resolver/types.ts +259 -0
  61. package/src/selectors/flatten.ts +448 -0
  62. package/src/selectors/index.ts +14 -0
  63. package/src/selectors/scan.ts +227 -0
  64. package/src/selectors/specificity.ts +319 -0
  65. package/src/setup-list.ts +172 -0
  66. package/src/sourcemaps/index.ts +25 -0
  67. package/src/sourcemaps/mappings.ts +190 -0
  68. package/src/sourcemaps/vlq.ts +29 -0
  69. package/src/types/ast.ts +318 -0
  70. package/src/types/diagnostics.ts +124 -0
  71. package/src/types/options.ts +286 -0
  72. package/src/types/result.ts +121 -0
  73. package/src/types/span.ts +18 -0
  74. package/src/types/token.ts +77 -0
  75. package/src/variables/ast.ts +182 -0
  76. package/src/variables/expand.ts +319 -0
  77. package/src/variables/index.ts +38 -0
  78. package/src/variables/naming.ts +46 -0
  79. package/src/variables/runtime.ts +336 -0
  80. package/src/variables/substitute.ts +148 -0
  81. package/src/variables/walk.ts +147 -0
  82. package/dist/output/importPath.d.ts +0 -27
  83. package/dist/output/importPath.d.ts.map +0 -1
  84. package/dist/output/importPath.js +0 -84
  85. package/dist/output/importPath.js.map +0 -1
@@ -0,0 +1,336 @@
1
+ import { declarationIr, stylesheetIr } from "../ir/factories.js";
2
+ import type {
3
+ DeclarationIr,
4
+ MediaConditionIr,
5
+ NativeBlockIr,
6
+ RuleIr,
7
+ StylesheetIr,
8
+ } from "../ir/types.js";
9
+ import { buildMediaAliasTable, resolveMediaCondition } from "../lowering/index.js";
10
+ import { declarationSegmentSpans, modifierAliasSpans } from "../lowering/spans.js";
11
+ import type { ModuleGraph, ScopedToken } from "../resolver/index.js";
12
+ import type { Declaration } from "../types/ast.js";
13
+ import type { Diagnostic } from "../types/diagnostics.js";
14
+ import type { Span } from "../types/span.js";
15
+ import { astReferences, segmentValueTokens } from "./ast.js";
16
+ import { expandValue, resolveReference } from "./expand.js";
17
+ import type { ExpansionHooks, ValueOrigin } from "./expand.js";
18
+ import { effectivePrefix, runtimePropertyName } from "./naming.js";
19
+ import type { VariableNamingOptions } from "./naming.js";
20
+ import { mapIrDeclarations, rootRule } from "./walk.js";
21
+
22
+ /**
23
+ * Runtime token emission (SPECIFICATION.md §6.2).
24
+ *
25
+ * `@runtime` declarations become native custom properties:
26
+ *
27
+ * ```css
28
+ * :root { --ui-primary: #2563eb; }
29
+ * @media (prefers-color-scheme: dark) { :root { --ui-primary: #60a5fa; } }
30
+ * ```
31
+ *
32
+ * Naming rule: `--<prefix>-<name>`, or `--<name>` when the effective prefix is
33
+ * empty (`naming.prefix` wins over `prefix`, matching §7.2). The prefix is
34
+ * authored configuration and is never sanitized here (P4/A09 owns CSS identifier
35
+ * validation).
36
+ *
37
+ * Emission ownership (§6.2): runtime tokens visible to the entry module — its
38
+ * own `@runtime` declarations, unqualified imports and any namespaced member
39
+ * referenced by the entry or by reachable token modules — are emitted in every
40
+ * consuming entrypoint and deduplicated by custom-property name.
41
+ *
42
+ * A duplicated post-prefix property name is **not** an error (ADR-0016). Native
43
+ * custom properties are live cascade values, so the definition that comes later
44
+ * in merge order wins: style-imported modules in canonical DFS `@use` order
45
+ * (dependencies before importers), then other reachable token modules in graph
46
+ * topological order, and the entry last. That makes an entry's `@runtime`
47
+ * definition override a style-imported module's same-named property, and a later
48
+ * style module override an earlier one. The rule is deliberate and mirrors the
49
+ * §5.4 "later wins is authored CSS" precedent; do not turn it back into an
50
+ * error. Cross-entrypoint collision reporting is P5 project work.
51
+ *
52
+ * Inline variants on runtime tokens become conditional `:root` override rules.
53
+ * Conditions are resolved with the same alias table and AND semantics as
54
+ * lowering (A05), so keys and query text are identical. Declarations are grouped
55
+ * by resolved query in first-appearance order: base declarations first, then one
56
+ * `:root` rule per condition. This preserves each property's authored order
57
+ * while letting the native custom-property cascade do the work — conditional
58
+ * *reference* splitting is deliberately not performed.
59
+ *
60
+ * References inside declaration values are rewritten to `var(--...)`; a compile
61
+ * reference that reaches this pass is expanded textually in its defining module
62
+ * (the pass is safe to call without `substitute`, and idempotent after it).
63
+ */
64
+
65
+ /** Options for {@link emitRuntimeTokens}. */
66
+ export interface RuntimeEmitOptions extends VariableNamingOptions {
67
+ /** Project-level media alias overrides, merged before file `@media-types` (ADR-0006). */
68
+ readonly media?: Readonly<Record<string, string>>;
69
+ /**
70
+ * Rule-bearing (`styles`) modules merged into this build, in emission order
71
+ * (ADR-0014). Their rule-level runtime references register custom properties
72
+ * too, because their declarations are emitted in this build even though their
73
+ * `$references` were authored in another file. They are also the first ranks in
74
+ * merge order, so the entry's `@runtime` definition overrides them (ADR-0016).
75
+ */
76
+ readonly ruleModules?: readonly string[];
77
+ }
78
+
79
+ /** Result of {@link emitRuntimeTokens}. */
80
+ export interface RuntimeEmitResult {
81
+ /** IR with `:root` rules prepended and runtime references rewritten. */
82
+ readonly ir: StylesheetIr;
83
+ /** CHIKX2001 value-expansion errors and CHIKX3001 condition errors, in walk order. */
84
+ readonly diagnostics: Diagnostic[];
85
+ }
86
+
87
+ /** One custom-property slot; a later-in-merge-order definition replaces the value. */
88
+ interface EmittedToken {
89
+ readonly property: string;
90
+ token: ScopedToken;
91
+ span: Span;
92
+ /** Merge rank of the defining module; higher wins. */
93
+ rank: number;
94
+ }
95
+
96
+ interface ConditionGroup {
97
+ readonly condition: MediaConditionIr;
98
+ readonly declarations: DeclarationIr[];
99
+ }
100
+
101
+ /**
102
+ * Canonical path list of the modules reachable from `entry` through `@use`.
103
+ *
104
+ * Entry first, then `ModuleGraph.order` (dependencies before importers, path
105
+ * ties) restricted to reachable modules, then any remaining reachable module
106
+ * (cycle members are absent from `order`) sorted by path. Deterministic for a
107
+ * given graph.
108
+ */
109
+ function reachableModules(graph: ModuleGraph, entry: string): string[] {
110
+ const reachable = new Set<string>();
111
+ const queue: string[] = [entry];
112
+ while (queue.length > 0) {
113
+ const file = queue.shift() as string;
114
+ if (reachable.has(file)) continue;
115
+ const record = graph.modules.get(file);
116
+ if (record === undefined) continue;
117
+ reachable.add(file);
118
+ for (const dependency of record.dependencies) queue.push(dependency);
119
+ }
120
+
121
+ const ordered: string[] = [];
122
+ for (const file of graph.order) {
123
+ if (reachable.has(file)) ordered.push(file);
124
+ }
125
+ const seen = new Set(ordered);
126
+ const leftovers = [...reachable].filter((file) => !seen.has(file)).sort();
127
+ return [...ordered, ...leftovers];
128
+ }
129
+
130
+ /**
131
+ * Merge rank per module for runtime custom-property resolution (ADR-0016).
132
+ *
133
+ * Higher rank wins. Style-imported modules come first in canonical DFS `@use`
134
+ * post-order (the order their rules are emitted), then any other reachable
135
+ * runtime-token module in graph topological order, and the entry is always last.
136
+ * The ordering is a deterministic projection of the graph; ties cannot occur
137
+ * because every module is assigned at most one rank.
138
+ */
139
+ function moduleMergeRanks(
140
+ graph: ModuleGraph,
141
+ entry: string,
142
+ ruleModules: readonly string[] | undefined,
143
+ ): Map<string, number> {
144
+ const ranks = new Map<string, number>();
145
+ let next = 0;
146
+ const assign = (file: string): void => {
147
+ if (file === entry || ranks.has(file)) return;
148
+ ranks.set(file, next);
149
+ next += 1;
150
+ };
151
+
152
+ for (const file of ruleModules ?? []) assign(file);
153
+ for (const file of reachableModules(graph, entry)) assign(file);
154
+ ranks.set(entry, next);
155
+ return ranks;
156
+ }
157
+
158
+ /**
159
+ * Emit `@runtime` custom properties and rewrite runtime references in `ir`.
160
+ *
161
+ * Signature note (deviation from the task sketch): the input IR is required.
162
+ * Producing `:root` rules alone would leave declaration values untouched, so
163
+ * the prescribed `(graph, entryFile, options)` shape cannot satisfy
164
+ * "references become `var(--...)`" without re-reading the AST.
165
+ *
166
+ * Runtime rules are inserted after leading statement at-rules (`@charset`,
167
+ * `@import`, `@layer a, b;`) so emitted CSS stays valid, and before authored
168
+ * rules. The pass is pure, deterministic and never mutates the input IR; it
169
+ * returns the input instance when there is nothing to add.
170
+ */
171
+ export function emitRuntimeTokens(
172
+ ir: StylesheetIr,
173
+ graph: ModuleGraph,
174
+ entryFile: string,
175
+ options: RuntimeEmitOptions = {},
176
+ ): RuntimeEmitResult {
177
+ const entry = graph.modules.get(entryFile);
178
+ const diagnostics: Diagnostic[] = [];
179
+ if (entry === undefined) return { ir, diagnostics };
180
+
181
+ const prefix = effectivePrefix(options);
182
+ const table = buildMediaAliasTable(entry.ast, options.media);
183
+ const ranks = moduleMergeRanks(graph, entryFile, options.ruleModules);
184
+
185
+ const emitted: EmittedToken[] = [];
186
+ const byProperty = new Map<string, EmittedToken>();
187
+ const register = (token: ScopedToken, span: Span): void => {
188
+ if (token.tokenType !== "runtime") return;
189
+ const property = runtimePropertyName(token.name, prefix);
190
+ const rank = ranks.get(token.module) ?? -1;
191
+ const existing = byProperty.get(property);
192
+ if (existing === undefined) {
193
+ const slot: EmittedToken = { property, token, span, rank };
194
+ byProperty.set(property, slot);
195
+ emitted.push(slot);
196
+ return;
197
+ }
198
+ // ADR-0016: native custom properties are live cascade values, so the later
199
+ // definition in merge order wins. Equal ranks are the same definition
200
+ // registered again (a reference and its declaration), so the first span is
201
+ // kept. This intentionally reports no diagnostic.
202
+ if (rank > existing.rank) {
203
+ existing.token = token;
204
+ existing.span = span;
205
+ existing.rank = rank;
206
+ }
207
+ };
208
+
209
+ // 1. Unqualified runtime surface of the entry itself: locals in authored
210
+ // order, then unqualified imports (the A07 scope shape).
211
+ for (const token of entry.runtimeScope.tokens.values()) register(token, token.span);
212
+
213
+ // 2. Runtime tokens actually consumed through a reference, either by the
214
+ // entry's rules or by any reachable token module.
215
+ const registerReferences = (file: string, includeRules: boolean): void => {
216
+ const record = graph.modules.get(file);
217
+ if (record === undefined) return;
218
+ for (const reference of astReferences(record.ast, { includeRules })) {
219
+ const resolution = resolveReference(reference.reference, file, graph, reference.span);
220
+ if (resolution.kind === "runtime") register(resolution.token, reference.span);
221
+ }
222
+ };
223
+
224
+ registerReferences(entryFile, true);
225
+ for (const file of reachableModules(graph, entryFile)) {
226
+ if (file === entryFile) continue;
227
+ registerReferences(file, false);
228
+ }
229
+ // Rule-merge imports (ADR-0014): the merged module's own rules are emitted in
230
+ // this build, so their runtime references need a custom property here.
231
+ for (const file of options.ruleModules ?? []) {
232
+ if (file === entryFile) continue;
233
+ registerReferences(file, true);
234
+ }
235
+
236
+ const hooks: ExpansionHooks = {
237
+ runtimeRef: (token) => {
238
+ register(token, token.span);
239
+ return `var(${runtimePropertyName(token.name, prefix)})`;
240
+ },
241
+ report: (diagnostic) => diagnostics.push(diagnostic),
242
+ };
243
+
244
+ // 3. Defensive value rewrite: after `substitute` there are no `$` references
245
+ // left, but a standalone call still resolves and rewrites them here.
246
+ const segments = segmentValueTokens(entry.ast);
247
+ const originFor = (declaration: DeclarationIr): ValueOrigin => {
248
+ const tokens = segments.get(declaration.span.start);
249
+ return { module: entryFile, start: tokens?.[0]?.start ?? null, fallback: declaration.span };
250
+ };
251
+ const mapped = mapIrDeclarations(ir, (declaration) => {
252
+ if (!declaration.value.includes("$")) return declaration;
253
+ const expanded = expandValue(declaration.value, originFor(declaration), graph, hooks);
254
+ if (expanded === null) return null;
255
+ if (expanded === declaration.value) return declaration;
256
+ return declarationIr(declaration.property, expanded, declaration.span, declaration.important);
257
+ });
258
+
259
+ // 4. Render each runtime token (the list can grow while values expand, so a
260
+ // plain index loop reaches a fixed point deterministically).
261
+ const baseDeclarations: DeclarationIr[] = [];
262
+ const groups: ConditionGroup[] = [];
263
+ const groupByQuery = new Map<string, ConditionGroup>();
264
+
265
+ for (let index = 0; index < emitted.length; index++) {
266
+ const emittedToken = emitted[index];
267
+ if (emittedToken === undefined) continue;
268
+ const token = emittedToken.token;
269
+ const declaration = token.declaration;
270
+ if (token.tokenType !== "runtime" || !("variants" in declaration)) continue;
271
+
272
+ const spans = declarationSegmentSpans(declaration);
273
+ const baseValue = expandValue(
274
+ declaration.value,
275
+ { module: token.module, start: declaration.tokens?.[0]?.start ?? null, fallback: spans.base },
276
+ graph,
277
+ hooks,
278
+ );
279
+ if (baseValue === null) continue;
280
+ baseDeclarations.push(
281
+ declarationIr(emittedToken.property, baseValue, spans.base, declaration.important),
282
+ );
283
+
284
+ for (let variantIndex = 0; variantIndex < declaration.variants.length; variantIndex++) {
285
+ const variant = declaration.variants[variantIndex];
286
+ if (variant === undefined) continue;
287
+ const span = spans.variants[variantIndex] ?? declaration.span;
288
+ const value = expandValue(
289
+ variant.value,
290
+ { module: token.module, start: variant.tokens?.[0]?.start ?? null, fallback: span },
291
+ graph,
292
+ hooks,
293
+ );
294
+ if (value === null) continue;
295
+
296
+ const resolution = resolveMediaCondition(modifierAliasSpans(variant), table, variant.span);
297
+ if (!resolution.ok) {
298
+ diagnostics.push(resolution.diagnostic);
299
+ continue;
300
+ }
301
+
302
+ const rewritten = declarationIr(emittedToken.property, value, span, variant.important);
303
+ let group = groupByQuery.get(resolution.condition.query);
304
+ if (group === undefined) {
305
+ group = { condition: resolution.condition, declarations: [] };
306
+ groupByQuery.set(resolution.condition.query, group);
307
+ groups.push(group);
308
+ }
309
+ group.declarations.push(rewritten);
310
+ }
311
+ }
312
+
313
+ const runtimeRules: RuleIr[] = [];
314
+ if (baseDeclarations.length > 0) runtimeRules.push(rootRule(baseDeclarations, null));
315
+ for (const group of groups) {
316
+ if (group.declarations.length > 0)
317
+ runtimeRules.push(rootRule(group.declarations, group.condition));
318
+ }
319
+
320
+ if (runtimeRules.length === 0) return { ir: mapped.ir, diagnostics };
321
+
322
+ // Keep `@charset`/`@import`/statement `@layer` first; CSS requires at-rule
323
+ // statements before qualified rules.
324
+ const nodes: (RuleIr | NativeBlockIr)[] = [...mapped.ir.rules];
325
+ let insertAt = 0;
326
+ while (insertAt < nodes.length) {
327
+ const node = nodes[insertAt];
328
+ if (node !== undefined && !("declarations" in node) && node.statement === true) insertAt++;
329
+ else break;
330
+ }
331
+
332
+ return {
333
+ ir: stylesheetIr([...nodes.slice(0, insertAt), ...runtimeRules, ...nodes.slice(insertAt)]),
334
+ diagnostics,
335
+ };
336
+ }
@@ -0,0 +1,148 @@
1
+ import { declarationIr } from "../ir/factories.js";
2
+ import type { DeclarationIr, StylesheetIr } from "../ir/types.js";
3
+ import type { ModuleGraph } from "../resolver/index.js";
4
+ import type { Diagnostic } from "../types/diagnostics.js";
5
+ import { error } from "../types/diagnostics.js";
6
+ import type { Token } from "../types/token.js";
7
+ import { groupDefaultSegments, segmentValueTokens } from "./ast.js";
8
+ import { expandValue } from "./expand.js";
9
+ import type { ExpansionHooks, ValueOrigin } from "./expand.js";
10
+ import { effectivePrefix, runtimePropertyName } from "./naming.js";
11
+ import type { VariableNamingOptions } from "./naming.js";
12
+ import { mapIrDeclarations } from "./walk.js";
13
+
14
+ /**
15
+ * Compile-time variable substitution (SPECIFICATION.md §6.1).
16
+ *
17
+ * Pure post-lowering pass: for every {@link DeclarationIr} value that contains a
18
+ * `$`, the authored slice is re-scanned with the A03 lexer, each `$name` /
19
+ * `$name.member` reference is resolved against the scope of the module that
20
+ * **authored** the declaration, and compile-time values are spliced in
21
+ * textually. (Values without `$` are passed through untouched: a `dollar-ref`
22
+ * token always contains `$`.) Runtime references become
23
+ * `var(--<prefix>-<name>)` so `@runtime` tokens keep their native cascade
24
+ * (`emitRuntimeTokens` emits the custom-property rules).
25
+ *
26
+ * The authoring module is `declaration.span.file`, not the module being
27
+ * substituted: `@group.<name>` expansion splices another module's declarations
28
+ * at the use site with their own authored spans, so a group default's `$refs`
29
+ * resolve in the defining module while use-site declarations resolve in the
30
+ * consumer (ADR-0017 item 6). For ordinary, non-expanded declarations the two
31
+ * modules are the same.
32
+ *
33
+ * Policies, all deterministic:
34
+ *
35
+ * - An unresolvable reference (undefined token, unknown namespace or member, a
36
+ * bare namespace, a reference cycle or an over-deep chain) is CHIKX2001 at
37
+ * the reference span, and the **declaration segment** is omitted. A `$` never
38
+ * leaks into CSS.
39
+ * - A `@runtime` reference inside a group default is CHIKX2001 and the segment
40
+ * is omitted: owner decision (b) keeps defaults compile-time only, so they are
41
+ * never rewritten with the consuming build's prefix (ADR-0017 item 6).
42
+ * - The built-in `keyframes` namespace (ADR-0015) is not a variable:
43
+ * `$keyframes.<name>` expands to the authored name text of a visible
44
+ * `@keyframes` block.
45
+ * - A rule whose declarations are all omitted is dropped, and a native block
46
+ * whose children are all dropped is dropped too, so no empty shells that
47
+ * could change cascade or at-rule validity are emitted. Statement at-rules
48
+ * (`@import`, ...) are always kept.
49
+ * - Spans are unchanged. The IR carries no value-offset field, so the exact
50
+ * reference offset is recovered from the AST's parsed value tokens (ADR-0005,
51
+ * keyed by segment start); when an IR node has no authored counterpart the
52
+ * segment span is reported instead.
53
+ * - Only the value text changes; `property`, `important`, conditions, native
54
+ * contexts, selectors and node order are preserved byte for byte.
55
+ */
56
+
57
+ /** Result of {@link substitute}. */
58
+ export interface SubstituteResult {
59
+ /** Rewritten, re-frozen stylesheet IR (the input instance when nothing changed). */
60
+ readonly ir: StylesheetIr;
61
+ /** CHIKX2001 diagnostics in IR order, one per rejected reference. */
62
+ readonly diagnostics: Diagnostic[];
63
+ }
64
+
65
+ /** Authored value index of one module: segment tokens plus group-default origins. */
66
+ interface ModuleOrigins {
67
+ /** Parsed value tokens keyed by segment start offset. */
68
+ readonly segments: Map<number, readonly Token[]>;
69
+ /** Segment starts authored inside a top-level `@group.<name>` definition. */
70
+ readonly groupDefaults: ReadonlySet<number>;
71
+ }
72
+
73
+ /**
74
+ * Substitute every compile-time variable reference in `ir`.
75
+ *
76
+ * @param ir Lowered IR of `entryFile` (parse → `buildModuleGraph` → `lower`).
77
+ * @param graph Module graph produced by A07; supplies scopes and token values.
78
+ * @param entryFile Canonical path of the module that owns `ir`, used for
79
+ * references whose authored module cannot be read from their span.
80
+ * @param options Runtime custom-property prefix used to render `var(...)`
81
+ * references. It must match the prefix passed to `emitRuntimeTokens`.
82
+ */
83
+ export function substitute(
84
+ ir: StylesheetIr,
85
+ graph: ModuleGraph,
86
+ entryFile: string,
87
+ options: VariableNamingOptions = {},
88
+ ): SubstituteResult {
89
+ const prefix = effectivePrefix(options);
90
+ const diagnostics: Diagnostic[] = [];
91
+
92
+ // Earlier group expansion can splice declarations authored in another module,
93
+ // so the token scope is selected per declaration from its authored span
94
+ // (ADR-0017 item 6). Indexes are built once per module and cached.
95
+ const origins = new Map<string, ModuleOrigins>();
96
+ const originsFor = (file: string): ModuleOrigins => {
97
+ const cached = origins.get(file);
98
+ if (cached !== undefined) return cached;
99
+ const ast = graph.modules.get(file)?.ast;
100
+ const built: ModuleOrigins = {
101
+ segments: segmentValueTokens(ast),
102
+ groupDefaults: groupDefaultSegments(ast),
103
+ };
104
+ origins.set(file, built);
105
+ return built;
106
+ };
107
+
108
+ const mapped = mapIrDeclarations(ir, (declaration) => {
109
+ const authored = declaration.span.file === "" ? entryFile : declaration.span.file;
110
+ const module = graph.modules.has(authored) ? authored : entryFile;
111
+ const index = originsFor(module);
112
+ // Expanded group defaults are the only IR declarations whose segment lives
113
+ // inside a `@group` definition; definitions never emit on their own.
114
+ const groupDefault = index.groupDefaults.has(declaration.span.start);
115
+ if (!declaration.value.includes("$")) return declaration;
116
+
117
+ let rejectedRuntime = false;
118
+ const hooks: ExpansionHooks = {
119
+ runtimeRef: (token, authoredText) => {
120
+ if (!groupDefault) return `var(${runtimePropertyName(token.name, prefix)})`;
121
+ if (!rejectedRuntime) {
122
+ diagnostics.push(
123
+ error(
124
+ "CHIKX2001",
125
+ `A @runtime token is not allowed in a group default: "${authoredText}" (ADR-0017); reference runtime tokens at the use site.`,
126
+ declaration.span,
127
+ ),
128
+ );
129
+ }
130
+ rejectedRuntime = true;
131
+ return "";
132
+ },
133
+ report: (diagnostic) => diagnostics.push(diagnostic),
134
+ };
135
+ const tokens = index.segments.get(declaration.span.start);
136
+ const origin: ValueOrigin = {
137
+ module,
138
+ start: tokens?.[0]?.start ?? null,
139
+ fallback: declaration.span,
140
+ };
141
+ const expanded = expandValue(declaration.value, origin, graph, hooks);
142
+ if (rejectedRuntime || expanded === null) return null;
143
+ if (expanded === declaration.value) return declaration;
144
+ return declarationIr(declaration.property, expanded, declaration.span, declaration.important);
145
+ });
146
+
147
+ return { ir: mapped.ir, diagnostics };
148
+ }
@@ -0,0 +1,147 @@
1
+ import { nativeBlockIr, ruleIr, stylesheetIr } from "../ir/factories.js";
2
+ import type {
3
+ DeclarationIr,
4
+ NativeBlockChild,
5
+ NativeBlockIr,
6
+ RuleIr,
7
+ StylesheetIr,
8
+ } from "../ir/types.js";
9
+
10
+ /**
11
+ * Shared IR rewriting for the variable passes.
12
+ *
13
+ * The IR is immutable and source-ordered, so both substitution and runtime
14
+ * emission rebuild it with frozen factories instead of editing nodes. Rewriting
15
+ * is structural: node identity is preserved when nothing changed, a rule or
16
+ * block at-rule is dropped only when **this pass** rejected its last
17
+ * declaration/child (an authored empty block such as `@layer a {}` is kept
18
+ * because it carries meaning), and statement at-rules (`@import`, `@charset`,
19
+ * `@layer a, b;`) are always kept because they carry no declarations (A05
20
+ * additive field).
21
+ */
22
+
23
+ /** Result of {@link mapIrDeclarations}. */
24
+ export interface MappedIr {
25
+ /** Rebuilt IR, or the input instance when nothing changed. */
26
+ readonly ir: StylesheetIr;
27
+ /** Whether at least one node or declaration was replaced or dropped. */
28
+ readonly changed: boolean;
29
+ }
30
+
31
+ /**
32
+ * Rewrite every {@link DeclarationIr} of a stylesheet.
33
+ *
34
+ * `transform` returns the declaration to keep or `null` to omit it. A rule or
35
+ * block at-rule is dropped when the last of its declarations/children was
36
+ * omitted by this pass, so a rejected reference cannot leave an empty selector
37
+ * behind; containers that were already empty on input are preserved untouched.
38
+ */
39
+ export function mapIrDeclarations(
40
+ ir: StylesheetIr,
41
+ transform: (declaration: DeclarationIr) => DeclarationIr | null,
42
+ ): MappedIr {
43
+ let changed = false;
44
+
45
+ const rewriteRule = (rule: RuleIr): RuleIr | null => {
46
+ // An already-empty rule is authored input, not a rejection: preserve it so
47
+ // the pass never changes nodes it did not have to rewrite.
48
+ if (rule.declarations.length === 0) return rule;
49
+ const declarations: DeclarationIr[] = [];
50
+ for (const declaration of rule.declarations) {
51
+ const rewritten = transform(declaration);
52
+ if (rewritten !== null) declarations.push(rewritten);
53
+ }
54
+ if (declarations.length === 0) {
55
+ changed = true;
56
+ return null;
57
+ }
58
+ if (
59
+ declarations.length === rule.declarations.length &&
60
+ declarations.every((entry, index) => entry === rule.declarations[index])
61
+ ) {
62
+ return rule;
63
+ }
64
+ changed = true;
65
+ return ruleIr({
66
+ selector: rule.selector,
67
+ ancestors: rule.ancestors,
68
+ declarations,
69
+ condition: rule.condition,
70
+ context: rule.context,
71
+ span: rule.span,
72
+ });
73
+ };
74
+
75
+ const rewriteBlock = (block: NativeBlockIr): NativeBlockIr | null => {
76
+ if (block.statement === true) return block;
77
+ // An authored empty block is preserved: `@layer a {}` still declares layer
78
+ // order and an empty `@media` is the author's structure, not our rejection.
79
+ if (block.children.length === 0) return block;
80
+ const children: NativeBlockChild[] = [];
81
+ for (const child of block.children) {
82
+ if ("declarations" in child) {
83
+ const rewritten = rewriteRule(child);
84
+ if (rewritten !== null) children.push(rewritten);
85
+ continue;
86
+ }
87
+ if ("children" in child) {
88
+ const rewritten = rewriteBlock(child);
89
+ if (rewritten !== null) children.push(rewritten);
90
+ continue;
91
+ }
92
+ const rewritten = transform(child);
93
+ if (rewritten !== null) children.push(rewritten);
94
+ }
95
+ if (children.length === 0) {
96
+ changed = true;
97
+ return null;
98
+ }
99
+ if (
100
+ children.length === block.children.length &&
101
+ children.every((entry, index) => entry === block.children[index])
102
+ ) {
103
+ return block;
104
+ }
105
+ changed = true;
106
+ return nativeBlockIr({
107
+ name: block.name,
108
+ prelude: block.prelude,
109
+ children,
110
+ span: block.span,
111
+ });
112
+ };
113
+
114
+ const rules: (RuleIr | NativeBlockIr)[] = [];
115
+ for (const node of ir.rules) {
116
+ if ("declarations" in node) {
117
+ const rewritten = rewriteRule(node);
118
+ if (rewritten !== null) rules.push(rewritten);
119
+ continue;
120
+ }
121
+ const rewritten = rewriteBlock(node);
122
+ if (rewritten !== null) rules.push(rewritten);
123
+ }
124
+
125
+ return { ir: changed ? stylesheetIr(rules) : ir, changed };
126
+ }
127
+
128
+ /**
129
+ * Create the `:root` rule that carries runtime custom properties.
130
+ *
131
+ * The rule span is the first declaration's span, matching the lowering contract
132
+ * for runs; an empty list is defensive only and yields a zero-width span.
133
+ */
134
+ export function rootRule(
135
+ declarations: readonly DeclarationIr[],
136
+ condition: RuleIr["condition"],
137
+ ): RuleIr {
138
+ const first = declarations[0];
139
+ return ruleIr({
140
+ selector: ":root",
141
+ ancestors: [],
142
+ declarations,
143
+ condition,
144
+ context: [],
145
+ span: first?.span ?? { start: 0, end: 0, file: "" },
146
+ });
147
+ }
@@ -1,27 +0,0 @@
1
- /**
2
- * CSS side-effect import computation for the generated JS class map.
3
- *
4
- * The specifier is computed from the map file's directory to the CSS artifact,
5
- * always using forward slashes and a `./` prefix when the relative form does
6
- * not already start with `.`. The returned text is ready to place between
7
- * double quotes in `import "…";`: backslashes, double quotes, control
8
- * characters and JavaScript line separators are escaped.
9
- */
10
- /**
11
- * Compute the import specifier from a JS map file to a CSS file.
12
- *
13
- * @param mapPath Absolute POSIX path of the JS map artifact.
14
- * @param cssPath Absolute POSIX path of the CSS artifact.
15
- * @returns Escaped JS string-literal content such as `./button.css` or
16
- * `../styles/button.css`. If the paths have different roots, the absolute CSS
17
- * path is returned because no relative specifier exists; such a plan is
18
- * rejected earlier by containment checks.
19
- */
20
- export declare function importSpecifierFor(mapPath: string, cssPath: string): string;
21
- /**
22
- * Escape text so it can be inserted between double quotes in a JS string
23
- * literal. Ordinary path characters are unchanged, so a normal specifier such
24
- * as `../styles/button.css` round-trips byte for byte.
25
- */
26
- export declare function escapeJsString(value: string): string;
27
- //# sourceMappingURL=importPath.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"importPath.d.ts","sourceRoot":"","sources":["../../src/output/importPath.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAIH;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAQ3E;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CA0CpD"}