@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,68 @@
1
+ /**
2
+ * `@chikx/compiler` module resolver (P3).
3
+ *
4
+ * Turns entry paths into a validated import graph and per-module token scopes.
5
+ * The resolver is host-injected and pure: all reads, existence checks,
6
+ * canonicalization and workspace-root policy come from
7
+ * {@link ModuleHost}; nothing here imports `node:fs`, `node:path` or ambient
8
+ * state.
9
+ *
10
+ * Variable substitution itself is A08: this stage only reports import, cycle
11
+ * and scope-definition errors (CHIKX2001) and records enough provenance for
12
+ * substitution to resolve values in their defining module. Reusable declaration
13
+ * groups (ADR-0017) are collected and resolved here as well: `ModuleRecord.groups`
14
+ * carries the definitions a module may use, while use-site diagnostics and
15
+ * expansion belong to the later expansion pass (plan G3).
16
+ */
17
+
18
+ import type { CompileOptions, ModuleHost } from "../types/options.js";
19
+ import { resolveModuleGraph } from "./graph.js";
20
+ import type { ModuleGraph } from "./types.js";
21
+
22
+ export type {
23
+ GroupResolution,
24
+ ImportSymbolOrigin,
25
+ KeyframeName,
26
+ LocalSymbolOrigin,
27
+ ModuleGraph,
28
+ ModuleRecord,
29
+ ScopedNamespace,
30
+ ScopedToken,
31
+ ScopedTokenType,
32
+ SymbolOrigin,
33
+ TokenScope,
34
+ VisibleGroup,
35
+ } from "./types.js";
36
+ export { KEYFRAMES_NAMESPACE } from "./keyframes.js";
37
+ export { styleModuleOrder } from "./rules.js";
38
+
39
+ /**
40
+ * Build the validated module graph for `entries`.
41
+ *
42
+ * The function is asynchronous because every {@link ModuleHost} operation is
43
+ * asynchronous; otherwise it is deterministic. It reads each canonical module
44
+ * once, resolves every `@use` relative to its importer, enforces workspace
45
+ * containment (ADR-0007), detects cycles, and returns:
46
+ *
47
+ * - `modules` — every loaded module keyed by canonical path, including cycle
48
+ * members so tooling can recover from errors;
49
+ * - `order` — dependencies before importers, ties by canonical path, with
50
+ * cycle members excluded;
51
+ * - `diagnostics` — parse diagnostics plus CHIKX2001 resolver diagnostics,
52
+ * stably sorted.
53
+ *
54
+ * Undefined `$name` references are deliberately left to A08; scopes expose
55
+ * locals, unqualified imports and namespaced members so substitution can
56
+ * report them with full provenance.
57
+ *
58
+ * Rule-bearing imports (ADR-0014) are available through {@link styleModuleOrder},
59
+ * which returns the merged-build emission order for a `styleDependencies` edge
60
+ * set.
61
+ */
62
+ export async function buildModuleGraph(
63
+ entries: readonly string[],
64
+ host: ModuleHost,
65
+ options: CompileOptions,
66
+ ): Promise<ModuleGraph> {
67
+ return resolveModuleGraph(entries, host, options);
68
+ }
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Built-in `keyframes` namespace collection (ADR-0015).
3
+ *
4
+ * Authored `@keyframes <name>` blocks are native CSS and keep their meaning.
5
+ * This module only records their names so `$keyframes.<name>` in a declaration
6
+ * value can expand to the plain name text at compile time. It never rewrites,
7
+ * reorders or validates the at-rule itself.
8
+ *
9
+ * Visibility follows emit safety, not import syntax: a name is referenceable
10
+ * when the consuming build actually emits its `@keyframes` block. That is the
11
+ * module's own top-level blocks plus every module reached through a `styles`
12
+ * `@use` edge (ADR-0014), transitively. Token-only imports contribute no CSS,
13
+ * so referencing one of their names would emit `animation-name: spin` with no
14
+ * `@keyframes spin` block — a broken runtime stylesheet — and is therefore not
15
+ * visible.
16
+ */
17
+
18
+ import type { NativeAtRule, Stylesheet } from "../types/ast.js";
19
+ import type { KeyframeName } from "./types.js";
20
+
21
+ /** Built-in namespace alias that exposes visible keyframe names (ADR-0015). */
22
+ export const KEYFRAMES_NAMESPACE = "keyframes";
23
+
24
+ /**
25
+ * A prelude that can be addressed as `$keyframes.<member>`.
26
+ *
27
+ * Only a single plain identifier qualifies. CSS also allows string-named
28
+ * keyframes (`@keyframes "fade"`) and escaped identifiers; those stay native CSS
29
+ * and are not addressable in v0.1 (documented in `docs/known-limitations.md`),
30
+ * because the `$keyframes.<member>` member text must match the emitted name
31
+ * byte for byte.
32
+ */
33
+ const PLAIN_KEYFRAMES_NAME = /^[A-Za-z_-][A-Za-z0-9_-]*$/;
34
+
35
+ /**
36
+ * Collect one module's top-level `@keyframes` names in authored order.
37
+ *
38
+ * The first declaration of a name wins so the result is deterministic. A
39
+ * repeated name needs no diagnostic: both blocks are emitted (native CSS keeps
40
+ * the later definition) and every reference expands to the same name text
41
+ * (ADR-0015).
42
+ */
43
+ export function collectKeyframes(ast: Stylesheet): KeyframeName[] {
44
+ const names: KeyframeName[] = [];
45
+ const seen = new Set<string>();
46
+
47
+ for (const item of ast.items) {
48
+ if (item.kind !== "native-at-rule" || !isKeyframesAtRule(item)) continue;
49
+ const name = item.prelude.trim();
50
+ if (!PLAIN_KEYFRAMES_NAME.test(name) || seen.has(name)) continue;
51
+ seen.add(name);
52
+ names.push({ name, module: ast.file, span: item.span });
53
+ }
54
+
55
+ return names;
56
+ }
57
+
58
+ /**
59
+ * Per-module inputs for {@link visibleKeyframes}.
60
+ *
61
+ * Split from {@link ModuleRecord} because the record stores the *computed*
62
+ * visibility, so building the closure must not depend on it.
63
+ */
64
+ export interface KeyframeSource {
65
+ /** Top-level `@keyframes` names authored in this module, first definition wins. */
66
+ readonly own: readonly KeyframeName[];
67
+ /** Canonical paths of `styles` `@use` targets, in authored order (ADR-0014). */
68
+ readonly styleDependencies: readonly string[];
69
+ }
70
+
71
+ /**
72
+ * Resolve every module's visible keyframe names.
73
+ *
74
+ * Order is own names first, then each `styles` dependency depth-first in authored
75
+ * order, then that dependency's own merge closure. The module's own definition
76
+ * (and the first visited dependency) wins for a repeated name; the value only
77
+ * carries provenance — every reference expands to the same authored name text,
78
+ * so a repeated name across merged modules is *not* an error (ADR-0015).
79
+ *
80
+ * Modules are visited in sorted canonical-path order with a shared memo, so the
81
+ * result is deterministic even when a cycle is present (cycles are already
82
+ * CHIKX2001 at the closing edge; a back edge contributes nothing).
83
+ */
84
+ export function visibleKeyframes(
85
+ sources: ReadonlyMap<string, KeyframeSource>,
86
+ ): ReadonlyMap<string, ReadonlyMap<string, KeyframeName>> {
87
+ const memo = new Map<string, Map<string, KeyframeName>>();
88
+ const files = [...sources.keys()].sort((left, right) =>
89
+ left < right ? -1 : left > right ? 1 : 0,
90
+ );
91
+
92
+ for (const file of files) resolve(file, sources, memo, new Set());
93
+
94
+ return memo;
95
+ }
96
+
97
+ function resolve(
98
+ file: string,
99
+ sources: ReadonlyMap<string, KeyframeSource>,
100
+ memo: Map<string, Map<string, KeyframeName>>,
101
+ visiting: Set<string>,
102
+ ): Map<string, KeyframeName> {
103
+ const cached = memo.get(file);
104
+ if (cached !== undefined) return cached;
105
+ const source = sources.get(file);
106
+ if (source === undefined) return new Map();
107
+
108
+ // Post-error recovery: a back edge in a cycle contributes nothing, keeping the
109
+ // walk terminating and deterministic (the cycle itself is already reported).
110
+ if (visiting.has(file)) return new Map();
111
+ visiting.add(file);
112
+
113
+ const visible = new Map<string, KeyframeName>();
114
+ for (const keyframe of source.own) {
115
+ if (!visible.has(keyframe.name)) visible.set(keyframe.name, keyframe);
116
+ }
117
+ for (const dependency of source.styleDependencies) {
118
+ for (const [name, keyframe] of resolve(dependency, sources, memo, visiting)) {
119
+ if (!visible.has(name)) visible.set(name, keyframe);
120
+ }
121
+ }
122
+
123
+ visiting.delete(file);
124
+ memo.set(file, visible);
125
+ return visible;
126
+ }
127
+
128
+ /** At-rule names are ASCII case-insensitive, matching the parser's native set. */
129
+ function isKeyframesAtRule(item: NativeAtRule): boolean {
130
+ return item.name.toLowerCase() === KEYFRAMES_NAMESPACE;
131
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Lexical path and CSS string utilities for the resolver.
3
+ *
4
+ * The compiler never touches the filesystem: every path is an absolute POSIX
5
+ * path supplied by the {@link ModuleHost}, and these helpers only normalize or
6
+ * compare strings. No `node:path` import keeps the core platform-independent
7
+ * and bundled-host friendly.
8
+ */
9
+
10
+ /**
11
+ * Normalize a path to forward slashes and collapse `.`/`..` segments lexically.
12
+ *
13
+ * Absolute paths keep a single leading slash; relative paths keep leading
14
+ * `..` segments. A Windows drive prefix such as `C:` is treated as an ordinary
15
+ * first segment because hosts already convert platform separators at their
16
+ * boundary.
17
+ */
18
+ export function normalizePosixPath(path: string): string {
19
+ const slashed = path.replace(/\\/g, "/");
20
+ const absolute = slashed.startsWith("/");
21
+ const segments: string[] = [];
22
+
23
+ for (const segment of slashed.split("/")) {
24
+ if (segment === "" || segment === ".") continue;
25
+ if (segment === "..") {
26
+ const last = segments[segments.length - 1];
27
+ if (last !== undefined && last !== "..") segments.pop();
28
+ else if (!absolute) segments.push("..");
29
+ continue;
30
+ }
31
+ segments.push(segment);
32
+ }
33
+
34
+ const body = segments.join("/");
35
+ if (absolute) return body === "" ? "/" : `/${body}`;
36
+ return body === "" ? "." : body;
37
+ }
38
+
39
+ /**
40
+ * Whether `target` lies inside `root`, including the root itself.
41
+ *
42
+ * Comparison is lexical and case-sensitive: host implementations own symlink
43
+ * and case policy through {@link ModuleHost.canonicalize}. Both arguments are
44
+ * normalized first, so trailing separators and `..` segments do not affect the
45
+ * result.
46
+ */
47
+ export function isWithinWorkspace(root: string, target: string): boolean {
48
+ const base = trimTrailingSlash(normalizePosixPath(root));
49
+ const candidate = normalizePosixPath(target);
50
+ if (base === "/") return candidate.startsWith("/");
51
+ return candidate === base || candidate.startsWith(`${base}/`);
52
+ }
53
+
54
+ function trimTrailingSlash(path: string): string {
55
+ if (path === "/") return path;
56
+ return path.endsWith("/") ? path.slice(0, -1) : path;
57
+ }
58
+
59
+ /**
60
+ * Decode the raw text between the quotes of a `@use` specifier.
61
+ *
62
+ * The parser deliberately keeps CSS string escapes raw; resolution needs the
63
+ * authored path. Hexadecimal escapes (`\74`) consume up to six digits plus one
64
+ * optional whitespace terminator, escaped newlines are removed, other escaped
65
+ * characters stand for themselves, and invalid code points become U+FFFD per
66
+ * CSS string rules.
67
+ */
68
+ export function decodeCssString(raw: string): string {
69
+ let decoded = "";
70
+ let index = 0;
71
+
72
+ while (index < raw.length) {
73
+ const character = raw.charAt(index);
74
+ if (character !== "\\") {
75
+ decoded += character;
76
+ index += 1;
77
+ continue;
78
+ }
79
+
80
+ index += 1;
81
+ if (index >= raw.length) break;
82
+
83
+ const escaped = raw.charAt(index);
84
+ if (escaped === "\n") {
85
+ index += 1;
86
+ continue;
87
+ }
88
+ if (escaped === "\r") {
89
+ index += 1;
90
+ if (raw.charAt(index) === "\n") index += 1;
91
+ continue;
92
+ }
93
+ if (escaped === "\f") {
94
+ index += 1;
95
+ continue;
96
+ }
97
+
98
+ if (!isHexDigit(escaped)) {
99
+ decoded += escaped;
100
+ index += 1;
101
+ continue;
102
+ }
103
+
104
+ let digits = "";
105
+ while (digits.length < 6 && index < raw.length && isHexDigit(raw.charAt(index))) {
106
+ digits += raw.charAt(index);
107
+ index += 1;
108
+ }
109
+
110
+ const terminator = raw.charAt(index);
111
+ if (terminator === "\r") {
112
+ index += 1;
113
+ if (raw.charAt(index) === "\n") index += 1;
114
+ } else if (
115
+ terminator === " " ||
116
+ terminator === "\t" ||
117
+ terminator === "\n" ||
118
+ terminator === "\f"
119
+ ) {
120
+ index += 1;
121
+ }
122
+
123
+ const codePoint = Number.parseInt(digits, 16);
124
+ decoded += String.fromCodePoint(isValidCodePoint(codePoint) ? codePoint : 0xfffd);
125
+ }
126
+
127
+ return decoded;
128
+ }
129
+
130
+ function isHexDigit(character: string): boolean {
131
+ return (
132
+ (character >= "0" && character <= "9") ||
133
+ (character >= "a" && character <= "f") ||
134
+ (character >= "A" && character <= "F")
135
+ );
136
+ }
137
+
138
+ function isValidCodePoint(codePoint: number): boolean {
139
+ if (!Number.isFinite(codePoint) || codePoint === 0) return false;
140
+ if (codePoint > 0x10ffff) return false;
141
+ return codePoint < 0xd800 || codePoint > 0xdfff;
142
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Rule-bearing (`styles`) module ordering for merged builds (ADR-0014).
3
+ *
4
+ * A `@use "./card.cssx" styles;` edge contributes the target's stylesheet
5
+ * rules to the importing build in addition to its tokens. The cascade order of
6
+ * a merged build is native-`@import`-like: imported modules first (depth-first
7
+ * in authored `@use` order), then the importing file's own rules.
8
+ *
9
+ * Everything here is a pure projection of {@link ModuleGraph}: no filesystem
10
+ * access, no parsing and no mutation. Cycle edges are already reported as
11
+ * CHIKX2001 by the graph stage; this pass only makes sure the walk terminates
12
+ * deterministically when a cycle exists.
13
+ */
14
+
15
+ import type { ModuleGraph } from "./types.js";
16
+
17
+ /**
18
+ * Canonical paths of every module whose rules merge into `entryFile`, in
19
+ * emission order.
20
+ *
21
+ * Traversal is depth-first over `styleDependencies` in authored `@use` order and
22
+ * the result is a post-order, so a module always appears after the modules it
23
+ * style-imports. Each module appears exactly once (diamond imports merge once),
24
+ * and `entryFile` itself is never included.
25
+ *
26
+ * Modules with no `styles` edge anywhere in their imports contribute nothing and
27
+ * are absent. Modules participating in an import cycle stay in the order at
28
+ * their first reachable position; the cycle is reported separately as CHIKX2001
29
+ * and the walk does not recurse back into a module already on the stack.
30
+ *
31
+ * @param graph Module graph produced by `buildModuleGraph`.
32
+ * @param entryFile Canonical path of the entry whose build is being assembled.
33
+ * @returns Emitted stylesheet module order (imported modules first).
34
+ */
35
+ export function styleModuleOrder(graph: ModuleGraph, entryFile: string): string[] {
36
+ const order: string[] = [];
37
+ const seen = new Set<string>([entryFile]);
38
+
39
+ const visit = (file: string): void => {
40
+ const record = graph.modules.get(file);
41
+ if (record === undefined) return;
42
+ for (const target of record.styleDependencies) {
43
+ if (seen.has(target)) continue;
44
+ // Mark before descending so a style-import cycle terminates here; the
45
+ // graph stage has already reported it as CHIKX2001.
46
+ seen.add(target);
47
+ visit(target);
48
+ order.push(target);
49
+ }
50
+ };
51
+
52
+ visit(entryFile);
53
+ return order;
54
+ }