This repository has been archived by the owner on Mar 14, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
index.ts
542 lines (488 loc) · 15 KB
/
index.ts
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
import * as FZ from 'fuzzaldrin'
import { TextBuffer, Point, Disposable, Range, Directory } from 'atom'
import { BufferInfo } from './buffer-info'
import { ModuleInfo } from './module-info'
import { GhcModiProcess } from '../ghc-mod'
import * as Util from '../util'
import * as UPI from 'atom-haskell-upi'
import * as CB from 'atom-haskell-upi/completion-backend'
const { handleException } = Util
export class CompletionBackend implements CB.ICompletionBackend {
private bufferMap: WeakMap<TextBuffer, BufferInfo>
private dirMap: WeakMap<Directory, Map<string, ModuleInfo>>
private modListMap: WeakMap<Directory, string[]>
private languagePragmas: WeakMap<Directory, string[]>
private compilerOptions: WeakMap<Directory, string[]>
private isActive: boolean
constructor(
private process: GhcModiProcess,
public upi: Promise<UPI.IUPIInstance>,
) {
this.bufferMap = new WeakMap()
this.dirMap = new WeakMap()
this.modListMap = new WeakMap()
this.languagePragmas = new WeakMap()
this.compilerOptions = new WeakMap()
// compatibility with old clients
this.name = this.name.bind(this)
this.onDidDestroy = this.onDidDestroy.bind(this)
this.registerCompletionBuffer = this.registerCompletionBuffer.bind(this)
this.unregisterCompletionBuffer = this.unregisterCompletionBuffer.bind(this)
this.getCompletionsForSymbol = this.getCompletionsForSymbol.bind(this)
this.getCompletionsForType = this.getCompletionsForType.bind(this)
this.getCompletionsForClass = this.getCompletionsForClass.bind(this)
this.getCompletionsForModule = this.getCompletionsForModule.bind(this)
this.getCompletionsForSymbolInModule = this.getCompletionsForSymbolInModule.bind(
this,
)
this.getCompletionsForLanguagePragmas = this.getCompletionsForLanguagePragmas.bind(
this,
)
this.getCompletionsForCompilerOptions = this.getCompletionsForCompilerOptions.bind(
this,
)
this.getCompletionsForHole = this.getCompletionsForHole.bind(this)
this.process = process
this.isActive = true
this.process.onDidDestroy(() => {
this.isActive = false
})
}
/* Public interface below */
/*
name()
Get backend name
Returns String, unique string describing a given backend
*/
public name() {
return 'haskell-ghc-mod'
}
/*
onDidDestroy(callback)
Destruction event subscription. Usually should be called only on
package deactivation.
callback: () ->
*/
public onDidDestroy(callback: () => void) {
if (!this.isActive) {
throw new Error('Backend inactive')
}
return this.process.onDidDestroy(callback)
}
/*
registerCompletionBuffer(buffer)
Every buffer that would be used with autocompletion functions has to
be registered with this function.
buffer: TextBuffer, buffer to be used in autocompletion
Returns: Disposable, which will remove buffer from autocompletion
*/
public registerCompletionBuffer(buffer: TextBuffer) {
if (!this.isActive) {
throw new Error('Backend inactive')
}
if (this.bufferMap.has(buffer)) {
return new Disposable(() => {
/* void */
})
}
const { bufferInfo } = this.getBufferInfo({ buffer })
setImmediate(async () => {
const { rootDir, moduleMap } = await this.getModuleMap({ bufferInfo })
// tslint:disable-next-line:no-floating-promises
this.getModuleInfo({ bufferInfo, rootDir, moduleMap })
const imports = await bufferInfo.getImports()
for (const imprt of imports) {
// tslint:disable-next-line:no-floating-promises
this.getModuleInfo({
moduleName: imprt.name,
bufferInfo,
rootDir,
moduleMap,
})
}
})
return new Disposable(() => this.unregisterCompletionBuffer(buffer))
}
/*
unregisterCompletionBuffer(buffer)
buffer: TextBuffer, buffer to be removed from autocompletion
*/
public unregisterCompletionBuffer(buffer: TextBuffer) {
const x = this.bufferMap.get(buffer)
if (x) {
x.destroy()
}
}
/*
getCompletionsForSymbol(buffer,prefix,position)
buffer: TextBuffer, current buffer
prefix: String, completion prefix
position: Point, current cursor position
Returns: Promise([symbol])
symbol: Object, a completion symbol
name: String, symbol name
qname: String, qualified name, if module is qualified.
Otherwise, same as name
typeSignature: String, type signature
symbolType: String, one of ['type', 'class', 'function']
module: Object, symbol module information
qualified: Boolean, true if module is imported as qualified
name: String, module name
alias: String, module alias
hiding: Boolean, true if module is imported with hiding clause
importList: [String], array of explicit imports/hidden imports
*/
@handleException
public async getCompletionsForSymbol(
buffer: TextBuffer,
prefix: string,
_position: Point,
): Promise<CB.ISymbol[]> {
if (!this.isActive) {
throw new Error('Backend inactive')
}
const symbols = await this.getSymbolsForBuffer(buffer)
return this.filter(symbols, prefix, ['qname', 'qparent'])
}
/*
getCompletionsForType(buffer,prefix,position)
buffer: TextBuffer, current buffer
prefix: String, completion prefix
position: Point, current cursor position
Returns: Promise([symbol])
symbol: Same as getCompletionsForSymbol, except
symbolType is one of ['type', 'class']
*/
@handleException
public async getCompletionsForType(
buffer: TextBuffer,
prefix: string,
_position: Point,
): Promise<CB.ISymbol[]> {
if (!this.isActive) {
throw new Error('Backend inactive')
}
const symbols = await this.getSymbolsForBuffer(buffer, ['type', 'class'])
return FZ.filter(symbols, prefix, { key: 'qname' })
}
/*
getCompletionsForClass(buffer,prefix,position)
buffer: TextBuffer, current buffer
prefix: String, completion prefix
position: Point, current cursor position
Returns: Promise([symbol])
symbol: Same as getCompletionsForSymbol, except
symbolType is one of ['class']
*/
public async getCompletionsForClass(
buffer: TextBuffer,
prefix: string,
_position: Point,
): Promise<CB.ISymbol[]> {
if (!this.isActive) {
throw new Error('Backend inactive')
}
const symbols = await this.getSymbolsForBuffer(buffer, ['class'])
return FZ.filter(symbols, prefix, { key: 'qname' })
}
/*
getCompletionsForModule(buffer,prefix,position)
buffer: TextBuffer, current buffer
prefix: String, completion prefix
position: Point, current cursor position
Returns: Promise([module])
module: String, module name
*/
public async getCompletionsForModule(
buffer: TextBuffer,
prefix: string,
_position: Point,
): Promise<string[]> {
if (!this.isActive) {
throw new Error('Backend inactive')
}
const rootDir = await this.process.getRootDir(buffer)
let modules = this.modListMap.get(rootDir)
if (!modules) {
modules = await this.process.runList(buffer)
this.modListMap.set(rootDir, modules)
// refresh every minute
setTimeout(() => this.modListMap.delete(rootDir), 60 * 1000)
}
return FZ.filter(modules, prefix)
}
/*
getCompletionsForSymbolInModule(buffer,prefix,position,{module})
Used in import hiding/list completions
buffer: TextBuffer, current buffer
prefix: String, completion prefix
position: Point, current cursor position
module: String, module name (optional). If undefined, function
will attempt to infer module name from position and buffer.
Returns: Promise([symbol])
symbol: Object, symbol in given module
name: String, symbol name
typeSignature: String, type signature
symbolType: String, one of ['type', 'class', 'function']
*/
public async getCompletionsForSymbolInModule(
buffer: TextBuffer,
prefix: string,
position: Point,
opts?: { module: string },
): Promise<CB.ISymbol[]> {
if (!this.isActive) {
throw new Error('Backend inactive')
}
let moduleName = opts ? opts.module : undefined
if (!moduleName) {
const lineRange = new Range([0, position.row], position)
buffer.backwardsScanInRange(
/^import\s+([\w.]+)/,
lineRange,
({ match }) => (moduleName = match[1]),
)
}
const { bufferInfo } = this.getBufferInfo({ buffer })
const mis = await this.getModuleInfo({ bufferInfo, moduleName })
// tslint:disable: no-null-keyword
const symbols = await mis.moduleInfo.select(
{
qualified: false,
hiding: false,
name: moduleName || mis.moduleName,
importList: null,
alias: null,
},
undefined,
true,
)
// tslint:enable: no-null-keyword
return FZ.filter(symbols, prefix, { key: 'name' })
}
/*
getCompletionsForLanguagePragmas(buffer,prefix,position)
buffer: TextBuffer, current buffer
prefix: String, completion prefix
position: Point, current cursor position
Returns: Promise([pragma])
pragma: String, language option
*/
public async getCompletionsForLanguagePragmas(
buffer: TextBuffer,
prefix: string,
_position: Point,
): Promise<string[]> {
if (!this.isActive) {
throw new Error('Backend inactive')
}
const dir = await this.process.getRootDir(buffer)
let ps = this.languagePragmas.get(dir)
if (!ps) {
ps = await this.process.runLang(dir)
ps && this.languagePragmas.set(dir, ps)
}
return FZ.filter(ps, prefix)
}
/*
getCompletionsForCompilerOptions(buffer,prefix,position)
buffer: TextBuffer, current buffer
prefix: String, completion prefix
position: Point, current cursor position
Returns: Promise([ghcopt])
ghcopt: String, compiler option (starts with '-f')
*/
public async getCompletionsForCompilerOptions(
buffer: TextBuffer,
prefix: string,
_position: Point,
): Promise<string[]> {
if (!this.isActive) {
throw new Error('Backend inactive')
}
const dir = await this.process.getRootDir(buffer)
let co = this.compilerOptions.get(dir)
if (!co) {
co = await this.process.runFlag(dir)
this.compilerOptions.set(dir, co)
}
return FZ.filter(co, prefix)
}
/*
getCompletionsForHole(buffer,prefix,position)
Get completions based on expression type.
It is assumed that `prefix` starts with '_'
buffer: TextBuffer, current buffer
prefix: String, completion prefix
position: Point, current cursor position
Returns: Promise([symbol])
symbol: Same as getCompletionsForSymbol
*/
@handleException
public async getCompletionsForHole(
buffer: TextBuffer,
prefix: string,
position: Point,
): Promise<CB.ISymbol[]> {
if (!this.isActive) {
throw new Error('Backend inactive')
}
const range = new Range(position, position)
if (prefix.startsWith('_')) {
prefix = prefix.slice(1)
}
const { type } = await this.process.getTypeInBuffer(buffer, range)
const symbols = await this.getSymbolsForBuffer(buffer)
const ts = symbols.filter((s) => {
if (!s.typeSignature) {
return false
}
const tl = s.typeSignature.split(' -> ').slice(-1)[0]
if (tl.match(/^[a-z]$/)) {
return false
}
const ts2 = tl.replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&')
const rx = RegExp(ts2.replace(/\b[a-z]\b/g, '.+'), '')
return rx.test(type)
})
if (prefix.length === 0) {
return ts.sort(
(a, b) =>
// tslint:disable-next-line: no-non-null-assertion
FZ.score(b.typeSignature!, type) - FZ.score(a.typeSignature!, type),
)
} else {
return FZ.filter(ts, prefix, { key: 'qname' })
}
}
private async getSymbolsForBuffer(
buffer: TextBuffer,
symbolTypes?: CB.SymbolType[],
): Promise<CB.ISymbol[]> {
const { bufferInfo } = this.getBufferInfo({ buffer })
const { rootDir, moduleMap } = await this.getModuleMap({ bufferInfo })
if (bufferInfo && moduleMap) {
const imports = await bufferInfo.getImports()
const promises = await Promise.all(
imports.map(async (imp) => {
const res = await this.getModuleInfo({
bufferInfo,
moduleName: imp.name,
rootDir,
moduleMap,
})
if (!res) {
return []
}
return res.moduleInfo.select(imp, symbolTypes)
}),
)
return ([] as typeof promises[0]).concat(...promises)
} else {
return []
}
}
private getBufferInfo({
buffer,
}: {
buffer: TextBuffer
}): { bufferInfo: BufferInfo } {
let bi = this.bufferMap.get(buffer)
if (!bi) {
bi = new BufferInfo(buffer)
this.bufferMap.set(buffer, bi)
}
return { bufferInfo: bi }
}
private async getModuleMap({
bufferInfo,
rootDir,
}: {
bufferInfo: BufferInfo
rootDir?: Directory
}): Promise<{ rootDir: Directory; moduleMap: Map<string, ModuleInfo> }> {
if (!rootDir) {
rootDir = await this.process.getRootDir(bufferInfo.buffer)
}
let mm = this.dirMap.get(rootDir)
if (!mm) {
mm = new Map()
this.dirMap.set(rootDir, mm)
}
return {
rootDir,
moduleMap: mm,
}
}
private async getModuleInfo(arg: {
bufferInfo: BufferInfo
moduleName?: string
rootDir?: Directory
moduleMap?: Map<string, ModuleInfo>
}) {
const { bufferInfo } = arg
let dat
if (arg.rootDir && arg.moduleMap) {
dat = { rootDir: arg.rootDir, moduleMap: arg.moduleMap }
} else {
dat = await this.getModuleMap({ bufferInfo })
}
const { moduleMap, rootDir } = dat
let moduleName = arg.moduleName
if (!moduleName) {
moduleName = await bufferInfo.getModuleName()
}
if (!moduleName) {
throw new Error(`Nameless module in ${bufferInfo.buffer.getUri()}`)
}
let moduleInfo = moduleMap.get(moduleName)
if (!moduleInfo) {
moduleInfo = new ModuleInfo(moduleName, this.process, rootDir)
moduleMap.set(moduleName, moduleInfo)
const mn = moduleName
moduleInfo.onDidDestroy(() => {
moduleMap.delete(mn)
Util.debug(`${moduleName} removed from map`)
})
}
await moduleInfo.setBuffer(bufferInfo)
return { bufferInfo, rootDir, moduleMap, moduleInfo, moduleName }
}
private filter<T, K extends keyof T>(
candidates: T[],
prefix: string,
keys: K[],
): T[] {
if (!prefix) {
return candidates
}
const list = []
for (const candidate of candidates) {
const scores = keys.map((key) => {
const ck = candidate[key]
if (ck) {
return FZ.score(ck.toString(), prefix)
} else {
return 0
}
})
const score = Math.max(...scores)
if (score > 0) {
list.push({
score,
scoreN: scores.indexOf(score),
data: candidate,
})
}
}
return list
.sort((a, b) => {
const s = b.score - a.score
if (s === 0) {
return a.scoreN - b.scoreN
}
return s
})
.map(({ data }) => data)
}
}