@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,319 @@
1
+ import { tokenize } from "../lexer/index.js";
2
+ import { KEYFRAMES_NAMESPACE } from "../resolver/index.js";
3
+ import type { ModuleGraph, ScopedToken } from "../resolver/index.js";
4
+ import type { Diagnostic } from "../types/diagnostics.js";
5
+ import { error } from "../types/diagnostics.js";
6
+ import type { Span } from "../types/span.js";
7
+
8
+ /**
9
+ * `$`-reference resolution and textual expansion (SPECIFICATION.md §6.1).
10
+ *
11
+ * Both passes share this core: substitution renders compile-time tokens
12
+ * textually and runtime tokens as `var(--...)`, while runtime emission reuses
13
+ * the same walk for `@runtime` values. Resolution always uses the token scope
14
+ * of the module whose text is being expanded, so imported values resolve in
15
+ * their defining module and a local override never mutates an imported module
16
+ * (§6.1).
17
+ *
18
+ * Expansion is textual, not evaluative: the authored slice is spliced, so
19
+ * whitespace, `calc()` spacing, comments and every non-reference token stay
20
+ * byte-identical. The built-in `keyframes` namespace (ADR-0015) is the one
21
+ * reference family with no declaring value: `$keyframes.<name>` resolves to the
22
+ * authored keyframe name text and is spliced as a literal.
23
+ */
24
+
25
+ /** Maximum nested compile-time expansions before a chain is rejected. */
26
+ export const MAX_EXPANSION_DEPTH = 64;
27
+
28
+ /**
29
+ * Where one value text came from.
30
+ *
31
+ * `module` selects the scope used to resolve references in the text. `start`
32
+ * is the absolute source offset of `text[0]` when it is known (the AST keeps
33
+ * parsed value tokens for values containing `$`, ADR-0005), which lets
34
+ * diagnostics point at the exact reference; otherwise `fallback` (the owning
35
+ * declaration or segment) is used.
36
+ */
37
+ export interface ValueOrigin {
38
+ /** Canonical path of the module that authored the text. */
39
+ readonly module: string;
40
+ /** Absolute offset of the first character of the text, or `null` when unknown. */
41
+ readonly start: number | null;
42
+ /** Span reported when the exact reference offset cannot be derived. */
43
+ readonly fallback: Span;
44
+ }
45
+
46
+ /** Hooks that make expansion policy explicit for each caller. */
47
+ export interface ExpansionHooks {
48
+ /**
49
+ * Renders a reference to a runtime token. Substitution and runtime emission
50
+ * both emit `var(--...)`; the authored text is passed for diagnostics.
51
+ */
52
+ readonly runtimeRef: (token: ScopedToken, authored: string) => string;
53
+ /** Receives one diagnostic per rejected reference. */
54
+ readonly report: (diagnostic: Diagnostic) => void;
55
+ }
56
+
57
+ /** One authored `$name` or `$name.member` reference. */
58
+ export interface TokenReference {
59
+ /** Symbol name without the `$` sigil or namespace. */
60
+ readonly name: string;
61
+ /** Namespace alias without the `$` sigil, when the reference is `$ns.member`. */
62
+ readonly namespace?: string;
63
+ }
64
+
65
+ /**
66
+ * Resolution outcome for one reference.
67
+ *
68
+ * `text` is a built-in compile-time reference whose expansion is literal CSS
69
+ * text rather than another value: `$keyframes.<name>` becomes the authored
70
+ * keyframe name (ADR-0015). It is spliced as-is and never recursed into.
71
+ */
72
+ export type ReferenceResolution =
73
+ | { readonly kind: "compile"; readonly token: ScopedToken }
74
+ | { readonly kind: "runtime"; readonly token: ScopedToken }
75
+ | { readonly kind: "text"; readonly text: string }
76
+ | { readonly kind: "error"; readonly diagnostic: Diagnostic };
77
+
78
+ /**
79
+ * Split authored `$ref` token text into name and optional namespace.
80
+ *
81
+ * Escapes are preserved: an escaped dot (`$a\.b`) stays part of the name
82
+ * because CSS escapes never introduce a member separator. Returns `null` for a
83
+ * bare `$`, which the lexer never emits as `dollar-ref` anyway.
84
+ */
85
+ export function splitReference(authored: string): TokenReference | null {
86
+ if (!authored.startsWith("$") || authored.length < 2) return null;
87
+ const body = authored.slice(1);
88
+ for (let index = 0; index < body.length; index++) {
89
+ const character = body[index] as string;
90
+ if (character === "\\") {
91
+ index++;
92
+ continue;
93
+ }
94
+ if (character === "." && index > 0 && index < body.length - 1) {
95
+ return { name: body.slice(index + 1), namespace: body.slice(0, index) };
96
+ }
97
+ }
98
+ return { name: body };
99
+ }
100
+
101
+ function fail(message: string, span: Span): ReferenceResolution {
102
+ return { kind: "error", diagnostic: error("CHIKX2001", message, span) };
103
+ }
104
+
105
+ /**
106
+ * Resolve one reference against a module's scopes.
107
+ *
108
+ * A bare `$name` consults the compile-time scope first, then the runtime scope
109
+ * (A07 handoff: the resolver already merged unqualified imports so a local
110
+ * definition shadows them). `$ns.member` consults only the namespace member
111
+ * maps, never the merged `$name` table, so namespaced imports stay independent
112
+ * (§6.1). Every failure is a CHIKX2001 with the reference span.
113
+ */
114
+ export function resolveReference(
115
+ reference: TokenReference,
116
+ module: string,
117
+ graph: ModuleGraph,
118
+ span: Span,
119
+ ): ReferenceResolution {
120
+ const record = graph.modules.get(module);
121
+ const display =
122
+ reference.namespace === undefined
123
+ ? `$${reference.name}`
124
+ : `$${reference.namespace}.${reference.name}`;
125
+
126
+ if (record === undefined) {
127
+ return fail(
128
+ `Module "${module}" is missing from the module graph, so "${display}" cannot be resolved.`,
129
+ span,
130
+ );
131
+ }
132
+
133
+ if (reference.namespace === undefined) {
134
+ const compile = record.compileScope.tokens.get(reference.name);
135
+ if (compile !== undefined) return { kind: "compile", token: compile };
136
+ const runtime = record.runtimeScope.tokens.get(reference.name);
137
+ if (runtime !== undefined) return { kind: "runtime", token: runtime };
138
+ if (reference.name === KEYFRAMES_NAMESPACE) {
139
+ return fail(
140
+ `"$${reference.name}" is a built-in namespace, not a token; reference a member such as "$${reference.name}.<name>".`,
141
+ span,
142
+ );
143
+ }
144
+ if (
145
+ record.compileScope.namespaces.has(reference.name) ||
146
+ record.runtimeScope.namespaces.has(reference.name)
147
+ ) {
148
+ return fail(
149
+ `"$${reference.name}" is a namespace, not a token; reference a member such as "$${reference.name}.<name>".`,
150
+ span,
151
+ );
152
+ }
153
+ return fail(`Undefined token "${display}" in "${module}".`, span);
154
+ }
155
+
156
+ // Built-in `keyframes` namespace (ADR-0015): a compile-time reference that
157
+ // expands to the authored keyframe name. Visibility is resolved by the module
158
+ // graph (own blocks plus `styles` imports), so an unknown member and an
159
+ // out-of-scope name both stay CHIKX2001 with the segment omitted.
160
+ if (reference.namespace === KEYFRAMES_NAMESPACE) {
161
+ const keyframe = record.keyframes.get(reference.name);
162
+ if (keyframe === undefined) {
163
+ return fail(
164
+ `Unknown keyframe "${display}" in "${module}"; "$keyframes" exposes this file's own @keyframes names and those of modules imported with @use "..." styles (ADR-0015).`,
165
+ span,
166
+ );
167
+ }
168
+ return { kind: "text", text: keyframe.name };
169
+ }
170
+
171
+ const compileNamespace = record.compileScope.namespaces.get(reference.namespace);
172
+ const runtimeNamespace = record.runtimeScope.namespaces.get(reference.namespace);
173
+ const namespace = compileNamespace ?? runtimeNamespace;
174
+ if (namespace === undefined) {
175
+ return fail(
176
+ `Unknown token namespace "$${reference.namespace}" in "${module}"; import it with @use "..." as ${reference.namespace}.`,
177
+ span,
178
+ );
179
+ }
180
+
181
+ const compileMember = compileNamespace?.members.get(reference.name);
182
+ if (compileMember !== undefined) return { kind: "compile", token: compileMember };
183
+ const runtimeMember = runtimeNamespace?.members.get(reference.name);
184
+ if (runtimeMember !== undefined) return { kind: "runtime", token: runtimeMember };
185
+ return fail(
186
+ `Module "${namespace.module}" does not export "${display}" through namespace "$${reference.namespace}".`,
187
+ span,
188
+ );
189
+ }
190
+
191
+ /**
192
+ * Absolute span of one `dollar-ref` token, or `null` when it is not authored.
193
+ *
194
+ * `text` is normally the authored slice starting at `origin.start`, but a
195
+ * rewritten value can contain generated `$` characters: an invalid `@setup
196
+ * prefix` such as `"$"` renders a runtime reference as `var(--$-p)`, and
197
+ * re-lexing that text would invent `$-p` at offsets taken from the *authored*
198
+ * base, ending past the end of the file. Offsets are only trusted while they
199
+ * still fall inside the fallback span of the text they were derived from; any
200
+ * other `$` is output from an earlier pass, not a reference the author wrote.
201
+ */
202
+ function referenceSpan(origin: ValueOrigin, start: number, end: number): Span | null {
203
+ if (origin.start === null) return origin.fallback;
204
+ const absoluteStart = origin.start + start;
205
+ const absoluteEnd = origin.start + end;
206
+ const authored = origin.fallback;
207
+ if (absoluteStart < authored.start || absoluteEnd > authored.end || absoluteStart > absoluteEnd) {
208
+ return null;
209
+ }
210
+ return { start: absoluteStart, end: absoluteEnd, file: origin.module };
211
+ }
212
+
213
+ /** `$name` display form used in cycle chains. */
214
+ function displayName(key: string): string {
215
+ return `$${key.slice(key.lastIndexOf("\u0000") + 1)}`;
216
+ }
217
+
218
+ function tokenKey(token: ScopedToken): string {
219
+ return `compile\u0000${token.module}\u0000${token.name}`;
220
+ }
221
+
222
+ /**
223
+ * Expand every `$` reference in `text`, or return `null` when a reference is
224
+ * rejected.
225
+ *
226
+ * Each resolved compile-time token inserts its defining module's raw value,
227
+ * recursively expanded in that module's scope. A repeated token on the current
228
+ * expansion stack, or a chain longer than {@link MAX_EXPANSION_DEPTH}, is a
229
+ * CHIKX2001 cycle/depth error and aborts the value so the caller can omit the
230
+ * affected construct instead of leaking a literal `$`.
231
+ *
232
+ * Purity: the input text and graph are never mutated, and the result is a new
233
+ * string. Lexer diagnostics from re-scanning a value slice are intentionally
234
+ * ignored; the parser already owns lexical reporting.
235
+ */
236
+ export function expandValue(
237
+ text: string,
238
+ origin: ValueOrigin,
239
+ graph: ModuleGraph,
240
+ hooks: ExpansionHooks,
241
+ stack: readonly string[] = [],
242
+ ): string | null {
243
+ if (!text.includes("$")) return text;
244
+
245
+ const { tokens } = tokenize(text, origin.module);
246
+ let output = "";
247
+ let cursor = 0;
248
+ let changed = false;
249
+
250
+ for (const token of tokens) {
251
+ if (token.kind !== "dollar-ref") continue;
252
+ const reference = splitReference(token.value);
253
+ if (reference === null) continue;
254
+ const span = referenceSpan(origin, token.start, token.end);
255
+ if (span === null) continue;
256
+ const resolution = resolveReference(reference, origin.module, graph, span);
257
+ if (resolution.kind === "error") {
258
+ hooks.report(resolution.diagnostic);
259
+ return null;
260
+ }
261
+
262
+ if (resolution.kind === "runtime") {
263
+ output += text.slice(cursor, token.start);
264
+ output += hooks.runtimeRef(resolution.token, token.value);
265
+ cursor = token.end;
266
+ changed = true;
267
+ continue;
268
+ }
269
+
270
+ if (resolution.kind === "text") {
271
+ // Built-in compile-time text (`$keyframes.<name>`, ADR-0015): spliced
272
+ // verbatim, never expanded recursively, so no `$` can survive here.
273
+ output += text.slice(cursor, token.start);
274
+ output += resolution.text;
275
+ cursor = token.end;
276
+ changed = true;
277
+ continue;
278
+ }
279
+
280
+ const definition = resolution.token;
281
+ const key = tokenKey(definition);
282
+ if (stack.includes(key)) {
283
+ const chain = [...stack.map(displayName), displayName(key)].join(" -> ");
284
+ hooks.report(error("CHIKX2001", `Detected a variable reference cycle: ${chain}.`, span));
285
+ return null;
286
+ }
287
+ if (stack.length >= MAX_EXPANSION_DEPTH) {
288
+ hooks.report(
289
+ error(
290
+ "CHIKX2001",
291
+ `Variable expansion exceeded ${MAX_EXPANSION_DEPTH} nested references at "$${definition.name}".`,
292
+ span,
293
+ ),
294
+ );
295
+ return null;
296
+ }
297
+
298
+ const nested = expandValue(
299
+ definition.declaration.value,
300
+ {
301
+ module: definition.module,
302
+ start: definition.declaration.tokens?.[0]?.start ?? null,
303
+ fallback: definition.span,
304
+ },
305
+ graph,
306
+ hooks,
307
+ [...stack, key],
308
+ );
309
+ if (nested === null) return null;
310
+
311
+ output += text.slice(cursor, token.start);
312
+ output += nested;
313
+ cursor = token.end;
314
+ changed = true;
315
+ }
316
+
317
+ if (!changed) return text;
318
+ return output + text.slice(cursor);
319
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Compile-time variables and runtime tokens (P3, SPECIFICATION.md §6).
3
+ *
4
+ * Two pure passes complete the variables story of the pipeline:
5
+ *
6
+ * 1. {@link substitute} — resolves every `$name` / `$name.member` reference in
7
+ * declaration values against A07's module scopes, splices compile-time values
8
+ * textually (recursively, in each value's defining module) and rewrites
9
+ * runtime references to `var(--...)`. Undefined symbols, unknown namespaces
10
+ * or members and reference cycles are CHIKX2001 at the reference span and the
11
+ * affected declaration segment is omitted, so a literal `$` never reaches
12
+ * CSS. The built-in `keyframes` namespace (ADR-0015) expands
13
+ * `$keyframes.<name>` to the authored keyframe name text.
14
+ * 2. {@link emitRuntimeTokens} — emits `:root` custom-property rules for
15
+ * `@runtime` tokens (prefix-aware) with conditional `:root` overrides for
16
+ * inline variants, resolves duplicate property names in merge order with the
17
+ * entry last (ADR-0016), and rewrites runtime references in declaration values.
18
+ *
19
+ * Canonical pipeline position for consumers:
20
+ *
21
+ * ```text
22
+ * parse → buildModuleGraph → lower → substitute → emitRuntimeTokens
23
+ * → (P4: class rewrite → groupRuns) → emitCss
24
+ * ```
25
+ *
26
+ * Both passes are deterministic, frozen-output and filesystem-free; they never
27
+ * read the AST for source text, mutate their inputs or throw on malformed IR.
28
+ * Barrel wiring is lead-directed; import this facade until integration.
29
+ */
30
+
31
+ export { emitRuntimeTokens } from "./runtime.js";
32
+ export type { RuntimeEmitOptions, RuntimeEmitResult } from "./runtime.js";
33
+
34
+ export { substitute } from "./substitute.js";
35
+ export type { SubstituteResult } from "./substitute.js";
36
+
37
+ export { effectivePrefix, runtimePropertyName } from "./naming.js";
38
+ export type { VariableNamingOptions } from "./naming.js";
@@ -0,0 +1,46 @@
1
+ import type { NamingOptions } from "../types/options.js";
2
+
3
+ /**
4
+ * Runtime custom-property naming (SPECIFICATION.md §6.2, §7.2).
5
+ *
6
+ * Runtime tokens are emitted as native custom properties whose name is the
7
+ * effective file prefix plus the authored token name:
8
+ *
9
+ * - prefix `ui`, token `primary` → `--ui-primary`;
10
+ * - empty prefix, token `primary` → `--primary`.
11
+ *
12
+ * The prefix is authored configuration, exactly like the class prefix of §7.2,
13
+ * and is copied verbatim. Validating it as a CSS identifier is class-naming
14
+ * work (P4/A09); this pass never rewrites the prefix, so an invalid prefix
15
+ * produces an authoring error rather than a silently renamed property.
16
+ */
17
+
18
+ /** Options that determine the effective runtime custom-property prefix. */
19
+ export interface VariableNamingOptions {
20
+ /**
21
+ * Effective file-level prefix, normally `CompileOptions.prefix` after `@setup`
22
+ * resolution. Empty or omitted means custom properties are unprefixed.
23
+ */
24
+ readonly prefix?: string;
25
+ /**
26
+ * Class-naming options; when `naming.prefix` is present it wins over
27
+ * {@link prefix}, matching the precedence documented on `CompileOptions`
28
+ * (SPECIFICATION.md §7.2).
29
+ */
30
+ readonly naming?: Pick<NamingOptions, "prefix">;
31
+ }
32
+
33
+ /** Resolve the effective prefix for runtime custom-property names. */
34
+ export function effectivePrefix(options: VariableNamingOptions = {}): string {
35
+ return options.naming?.prefix ?? options.prefix ?? "";
36
+ }
37
+
38
+ /**
39
+ * Custom-property name for one runtime token.
40
+ *
41
+ * Pure string composition: an empty prefix yields `--<name>`, otherwise
42
+ * `--<prefix>-<name>` (SPECIFICATION.md §6.2 example emits `--ui-primary`).
43
+ */
44
+ export function runtimePropertyName(name: string, prefix: string): string {
45
+ return prefix === "" ? `--${name}` : `--${prefix}-${name}`;
46
+ }