Repository navigation
Expand file tree
/
Copy pathlinks.ts
More file actions
373 lines (311 loc) · 10.9 KB
/
Copy pathlinks.ts
File metadata and controls
373 lines (311 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
import {posix} from 'node:path';
import {foldersAbove, folderOf} from './files.ts';
import {IS} from './forest.ts';
import {hashOf, mix} from './hash.ts';
import type {Definition, Module, Reexport, Use} from './module.ts';
import type {Names} from './names.ts';
import type {Packages} from './projects.ts';
import {isState} from './state.ts';
/** Where a name leads: to something in the project, or somewhere outside it. */
type Place =
| {readonly tag: 'definition'; readonly module: Module; readonly definition: Definition}
| {readonly tag: 'elsewhere'; readonly name: string};
export type Links = {
/** The module `from` means in `module`, when it's one of the project's. */
readonly resolve: (module: Module, from: string) => Module | null;
readonly place: (module: Module, name: Use) => Place;
/**
* The same number for two names that stand for the same thing: the same
* definition, or two with the same tree that don't change.
*/
readonly identity: (module: Module, name: number) => number;
/** The modules of the project that a module imports. */
readonly importsOf: (module: Module) => readonly Module[];
/** The modules that use a definition of another's. */
readonly usersOf: (definition: Definition) => readonly Module[];
/** The modules of the project that a module imports, and those they import. */
readonly reachedFrom: (module: Module) => ReadonlySet<Module>;
/** Whether `from` can't import `to` without the two importing each other. */
readonly wouldCircle: (from: Module, to: Module) => boolean;
};
const ENDINGS = [
'',
'.ts',
'.tsx',
'.d.ts',
'.mts',
'.cts',
'.js',
'.jsx',
'.mjs',
'.cjs',
'/index.ts',
'/index.tsx',
'/index.js',
'/index.jsx',
'/index.mjs',
];
/** The module at a path that may have no ending, or the ending of what it's built into. */
export const moduleAt = (modules: ReadonlyMap<string, Module>, path: string): Module | null => {
const bare = path.replace(/\.(c|m)?jsx?$/, '');
const ending = ENDINGS.find(each => modules.has(path + each));
const other = ENDINGS.find(each => modules.has(bare + each));
return ending !== undefined
? (modules.get(path + ending) ?? null)
: other !== undefined
? (modules.get(bare + other) ?? null)
: null;
};
/** The name Gleam knows a file by, and the package it's in. */
export const gleamModule = (
path: string,
packages: readonly string[],
): {readonly name: string; readonly folder: string} | null => {
const folder = packages
.filter(each => each === '' || path.startsWith(`${each}/`))
.toSorted((a, b) => b.length - a.length)[0];
if (folder === undefined) {
return null;
}
const inside = folder === '' ? path : path.slice(folder.length + 1);
const name = /^(?:src|test|dev)\/(.*)\.gleam$/.exec(inside)?.[1];
return name === undefined ? null : {name, folder};
};
/** How far to look through the definitions a definition uses when comparing two. */
const DEPTH = 2;
const ITSELF = hashOf('itself');
/** Works something out the first time it's asked for. */
const V>(work: (key: K) => V): ((key: K) => V) => {
const known = new Map<K, V>();
return key => {
const found = known.get(key);
if (found !== undefined) {
return found;
}
const value = work(key);
known.set(key, value);
return value;
};
};
export const linksOf = (modules: readonly Module[], packages: Packages, names: Names): Links => {
const byPath = new Map(modules.map(module => [module.path, module]));
const gleamNames = new Map(
modules.flatMap(module => {
const gleam = module.language === 'gleam' ? gleamModule(module.path, packages.gleam) : null;
return gleam ? [[module, gleam] as const] : [];
}),
);
const byGleamName = Map.groupBy(
[...gleamNames].map(([module, gleam]) => ({module, ...gleam})),
({name}) => name,
);
const definitionsOf = once(
(module: Module) =>
new Map(
module.definitions.flatMap(definition =>
[definition.name, ...definition.alsoNames].map(name => [name, definition] as const),
),
),
);
const exportsOf = once(
(module: Module) =>
new Map(
module.definitions.flatMap(definition =>
definition.exportedAs === null ? [] : [[definition.exportedAs, definition] as const],
),
),
);
const resolveGleam = (module: Module, from: string): Module | null => {
const found = byGleamName.get(from) ?? [];
const own = gleamNames.get(module);
return (found.find(each => each.folder === own?.folder) ?? found[0])?.module ?? null;
};
const resolved = new Map<Module, Map<string, Module | null>>();
/** Everything under the same one of these folders means the same thing by a name. */
const baseOf = once(
(folder: string) => foldersAbove(`${folder}/`).find(each => packages.bases.has(each)) ?? '',
);
const named = new Map<string, Module | null>();
const resolveNamed = (module: Module, from: string): Module | null => {
const key = `${baseOf(folderOf(module.path))}\n${from}`;
const known = named.get(key);
if (known !== undefined) {
return known;
}
const [found = null] = names(module.path, from).flatMap(path => moduleAt(byPath, path) ?? []);
named.set(key, found);
return found;
};
const resolveAnew = (module: Module, from: string): Module | null =>
module.language === 'gleam'
? resolveGleam(module, from)
: from.startsWith('.')
? moduleAt(byPath, posix.join(folderOf(module.path), from))
: resolveNamed(module, from);
const resolve = (module: Module, from: string): Module | null => {
const ours = resolved.get(module) ?? new Map<string, Module | null>();
resolved.set(module, ours);
const known = ours.get(from);
if (known !== undefined) {
return known;
}
const found = resolveAnew(module, from);
ours.set(from, found);
return found;
};
const importsIn = once(
(module: Module) => new Map(module.imports.map(each => [each.local, each] as const)),
);
const reexportsOf = once((module: Module) =>
Map.groupBy(module.reexports, each => each.exportedAs),
);
const exportOf = (module: Module, name: string, seen: readonly string[]): Place | null => {
const key = `${module.path} ${name}`;
if (seen.includes(key)) {
return null;
}
const definition =
module.language === 'gleam' ? definitionsOf(module).get(name) : exportsOf(module).get(name);
if (definition) {
return {tag: 'definition', module, definition};
}
const >
const before = [...seen, key];
return [...(onward.get(name) ?? []), ...(onward.get('*') ?? [])].reduce<Place | null>(
(found, each) => found ?? through(module, each, name, before),
null,
);
};
/** What a module that exports something again means by it. */
const through = (
module: Module,
{name, exportedAs, from}: Reexport,
wanted: string,
seen: readonly string[],
): Place | null => {
const definition = from === '' ? definitionsOf(module).get(name) : undefined;
if (definition) {
return {tag: 'definition', module, definition};
}
const imported = from === '' ? importsIn(module).get(name) : undefined;
const target = resolve(module, imported?.from ?? from);
const inside = imported?.name ?? (exportedAs === '*' ? wanted : name);
return target ? exportOf(target, inside, seen) : null;
};
const exportsKnown = once((module: Module) => once((name: string) => exportOf(module, name, [])));
const place = (module: Module, {name, from}: Use): Place => {
if (from === '') {
const definition = definitionsOf(module).get(name);
return definition
? {tag: 'definition', module, definition}
: {tag: 'elsewhere', name: `global ${name}`};
}
const target = resolve(module, from);
return target
? (exportsKnown(target)(name) ?? {tag: 'elsewhere', name: `${target.path} ${name}`})
: {tag: 'elsewhere', name: `${from} ${name}`};
};
const contents = Array.from({length: DEPTH + 1}, () => new Map<Definition, number>());
/** A definition's tree hashed with its locals numbered, and what it uses `depth` deep. */
const contentOf = (module: Module, definition: Definition, depth: number): number => {
const known = contents[depth]?.get(definition);
if (known !== undefined) {
return known;
}
const {marks, own, refs, next} = module.forest;
const {node} = definition;
const numbers = new Map<number, number>();
const content = marks.subarray(node, next[node]).reduce((hash, mark, index) => {
const at = node + index;
const ref = refs[at] ?? 0;
if (mark === IS.local) {
const number = numbers.get(ref) ?? numbers.size;
numbers.set(ref, number);
return mix(hash, number);
}
return mix(
hash,
mark === IS.outer ? identityAt(module, ref, depth - 1, definition) : (own[at] ?? 0),
);
}, hashOf(definition.role));
contents[depth]?.set(definition, content);
return content;
};
const identityAt = (
module: Module,
ref: number,
depth: number,
within: Definition | null,
): number => {
const use = module.names[ref] ?? {name: '', from: ''};
const found = place(module, use);
if (found.tag === 'elsewhere') {
return hashOf(found.name);
}
if (found.definition === within) {
return ITSELF;
}
if (isState(found.module, found.definition)) {
return hashOf(`${found.module.path} ${found.definition.name}`);
}
const {name, alsoNames} = found.definition;
// A constructor is only part of its type, so it needs its name too.
const part = alsoNames.includes(use.name) ? use.name : '';
return depth <= 0
? hashOf(`name ${part === '' ? name : part}`)
: mix(contentOf(found.module, found.definition, depth), hashOf(part));
};
const identities = once((module: Module) => ({
values: new Uint32Array(module.names.length),
isKnown: new Uint8Array(module.names.length),
}));
const importsOf = once((module: Module): readonly Module[] => [
...new Set(
[...module.imports, ...module.reexports].flatMap(each => {
const target = resolve(module, each.from);
return target && target !== module ? [target] : [];
}),
),
]);
const reachInto = (module: Module, seen: Set<Module>): Set<Module> => {
importsOf(module).forEach(each => {
if (!seen.has(each)) {
seen.add(each);
reachInto(each, seen);
}
});
return seen;
};
const reachedFrom = once((module: Module): ReadonlySet<Module> => reachInto(module, new Set()));
const users = once((all: typeof modules) =>
all.reduce((found, module) => {
module.names
.filter(use => use.from !== '')
.forEach(use => {
const used = place(module, use);
if (used.tag === 'definition') {
const list = found.get(used.definition) ?? new Set();
list.add(module);
found.set(used.definition, list);
}
});
return found;
}, new Map<Definition, Set<Module>>()),
);
return {
resolve,
place,
importsOf,
usersOf: definition => [...(users(modules).get(definition) ?? [])],
wouldCircle: (from, to) => from !== to && reachedFrom(to).has(from),
reachedFrom,
identity: (module, ref) => {
const {values, isKnown} = identities(module);
if (isKnown[ref] !== 1) {
values[ref] = identityAt(module, ref, DEPTH, null);
isKnown[ref] = 1;
}
return values[ref] ?? 0;
},
};
};