-
Notifications
You must be signed in to change notification settings - Fork 326
/
Copy pathcallTree.ts
568 lines (512 loc) · 18.3 KB
/
callTree.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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
import type { PortId } from '@/providers/portInfo'
import { WidgetInput } from '@/providers/widgetRegistry'
import type { WidgetConfiguration } from '@/providers/widgetRegistry/configuration'
import * as widgetCfg from '@/providers/widgetRegistry/configuration'
import { DisplayMode } from '@/providers/widgetRegistry/configuration'
import type { MethodCallInfo } from '@/stores/graph/graphDatabase'
import {
isRequiredArgument,
type SuggestionEntry,
type SuggestionEntryArgument,
} from '@/stores/suggestionDatabase/entry'
import { Ast } from '@/util/ast'
import type { AstId } from '@/util/ast/abstract'
import { findLastIndex, tryGetIndex } from '@/util/data/array'
import type { ExternalId } from 'ydoc-shared/yjsModel'
import { assert } from './assert'
export const enum ApplicationKind {
Prefix,
Infix,
}
class ArgumentFactory {
constructor(
private callId: string,
private kind: ApplicationKind,
private widgetCfg: widgetCfg.FunctionCall | undefined,
) {}
placeholder(index: number, info: SuggestionEntryArgument, insertAsNamed: boolean) {
return new ArgumentPlaceholder(
this.callId,
this.kind,
this.dynamicConfig(info.name),
index,
info,
insertAsNamed,
)
}
argument(
ast: Ast.Expression,
index: number | undefined,
info: SuggestionEntryArgument | undefined,
) {
return new ArgumentAst(
this.callId,
this.kind,
info && this.dynamicConfig(info.name),
index,
info,
ast,
)
}
private dynamicConfig(name: string) {
return this.widgetCfg?.parameters.get(name) ?? undefined
}
}
type ArgWidgetConfiguration = WidgetConfiguration & { display?: DisplayMode }
type WidgetInputValue = Ast.Expression | Ast.Token | string | undefined
abstract class Argument {
protected constructor(
public callId: string,
public kind: ApplicationKind,
public dynamicConfig: ArgWidgetConfiguration | undefined,
public index: number | undefined,
public argInfo: SuggestionEntryArgument | undefined,
) {}
abstract get portId(): PortId
abstract get value(): WidgetInputValue
get argId(): string | undefined {
return this.argInfo && `${this.callId}[${this.argInfo.name}]`
}
get hideByDefault(): boolean {
return false
}
toWidgetInput(): WidgetInput {
return {
portId: this.portId,
value: this.value,
expectedType: this.argInfo?.reprType,
[ArgumentInfoKey]: { info: this.argInfo, appKind: this.kind, argId: this.argId },
dynamicConfig: this.dynamicConfig,
}
}
}
/**
* Information about an argument that doesn't have an assigned value yet, therefore are not
* represented in the AST.
*/
export class ArgumentPlaceholder extends Argument {
public declare index: number
public declare argInfo: SuggestionEntryArgument
/** TODO: Add docs */
constructor(
callId: string,
kind: ApplicationKind,
dynamicConfig: ArgWidgetConfiguration | undefined,
index: number,
argInfo: SuggestionEntryArgument,
public insertAsNamed: boolean,
) {
super(callId, kind, dynamicConfig, index, argInfo)
}
/** TODO: Add docs */
get portId(): PortId {
return `${this.callId}[${this.index}]` as PortId
}
/** TODO: Add docs */
get value(): WidgetInputValue {
return this.argInfo.defaultValue
}
/** Whether the argument should be hidden when the component isn't currently focused for editing. */
override get hideByDefault(): boolean {
return (
this.argInfo.hasDefault &&
!isRequiredArgument(this.argInfo) &&
this.dynamicConfig?.display !== DisplayMode.Always
)
}
}
/** TODO: Add docs */
export class ArgumentAst extends Argument {
/** TODO: Add docs */
constructor(
callId: string,
kind: ApplicationKind,
dynamicConfig: ArgWidgetConfiguration | undefined,
index: number | undefined,
argInfo: SuggestionEntryArgument | undefined,
public ast: Ast.Expression,
) {
super(callId, kind, dynamicConfig, index, argInfo)
}
/** TODO: Add docs */
get portId(): PortId {
return this.ast.id
}
/** TODO: Add docs */
get value() {
return this.ast
}
}
export type InterpretedCall = InterpretedInfix | InterpretedPrefix
interface InterpretedInfix {
kind: 'infix'
appTree: Ast.OprApp
operator: Ast.Token | undefined
lhs: Ast.Expression | undefined
rhs: Ast.Expression | undefined
}
interface InterpretedPrefix {
kind: 'prefix'
func: Ast.Expression
args: FoundApplication[]
}
interface FoundApplication {
appTree: Ast.App
argument: Ast.Expression
argName: string | undefined
}
/** TODO: Add docs */
export function interpretCall(callRoot: Ast.Expression): InterpretedCall {
if (callRoot instanceof Ast.OprApp) {
// Infix chains are handled one level at a time. Each application may have at most 2 arguments.
return {
kind: 'infix',
appTree: callRoot,
operator: callRoot.operator.ok ? callRoot.operator.value : undefined,
lhs: callRoot.lhs ?? undefined,
rhs: callRoot.rhs ?? undefined,
}
} else {
// Prefix chains are handled all at once, as they may have arbitrary number of arguments.
const foundApplications: FoundApplication[] = []
let nextApplication = callRoot
// Traverse the AST and find all arguments applied in sequence to the same function.
while (nextApplication instanceof Ast.App) {
foundApplications.push({
appTree: nextApplication,
argument: nextApplication.argument,
argName: nextApplication.argumentName?.code() ?? undefined,
})
nextApplication = nextApplication.function
}
return {
kind: 'prefix',
func: nextApplication,
// The applications are peeled away from outer to inner, so arguments are in reverse order. We
// need to reverse them back to match them with the order in suggestion entry.
args: foundApplications.reverse(),
}
}
}
interface CallInfo {
notAppliedArguments?: number[] | undefined
suggestion?: SuggestionEntry | undefined
widgetCfg?: widgetCfg.FunctionCall | undefined
subjectAsSelf?: boolean | undefined
}
/** TODO: Add docs */
export class ArgumentApplication {
private constructor(
public appTree: Ast.Expression,
public target: ArgumentApplication | Ast.Expression | ArgumentPlaceholder | ArgumentAst,
public infixOperator: Ast.Token | undefined,
public argument: ArgumentAst | ArgumentPlaceholder,
public calledFunction: SuggestionEntry | undefined,
public isInnermost: boolean,
) {}
private static FromInterpretedInfix(interpreted: InterpretedInfix, callInfo: CallInfo) {
const { suggestion, widgetCfg } = callInfo
const makeArg = new ArgumentFactory(interpreted.appTree.id, ApplicationKind.Infix, widgetCfg)
const argFor = (key: 'lhs' | 'rhs', index: number) => {
const tree = interpreted[key]
const info = tryGetIndex(suggestion?.arguments, index) ?? unknownArgInfoNamed(key)
return tree != null ?
makeArg.argument(tree, index, info)
: makeArg.placeholder(index, info, false)
}
return new ArgumentApplication(
interpreted.appTree,
argFor('lhs', 0),
interpreted.operator,
argFor('rhs', 1),
suggestion,
true,
)
}
private static FromInterpretedPrefix(interpreted: InterpretedPrefix, callInfo: CallInfo) {
const { notAppliedArguments, suggestion, widgetCfg, subjectAsSelf } = callInfo
const knownArguments = suggestion?.arguments
const allPossiblePrefixArguments = Array.from(knownArguments ?? [], (_, i) => i)
// when this is a method application with applied 'self', the subject of the access operator is
// treated as a 'self' argument.
if (
subjectAsSelf &&
knownArguments?.[0]?.name === 'self' &&
getAccessOprSubject(interpreted.func) != null
) {
allPossiblePrefixArguments.shift()
}
const notAppliedOriginally = new Set(notAppliedArguments ?? allPossiblePrefixArguments)
const argumentsLeftToMatch = allPossiblePrefixArguments.filter((i) =>
notAppliedOriginally.has(i),
)
const resolvedArgs: Array<{
appTree: Ast.Expression
argument: ArgumentAst | ArgumentPlaceholder
}> = []
function nextArgumentNameInDefinition() {
return tryGetIndex(knownArguments, argumentsLeftToMatch[0])?.name
}
function takeNextArgumentFromDefinition() {
const index = argumentsLeftToMatch.shift()
const info = tryGetIndex(knownArguments, index)
return index != null && info != null ? { index, info } : undefined
}
function takeNamedArgumentFromDefinition(name: string) {
const takeIdx = argumentsLeftToMatch.findIndex(
(id) => tryGetIndex(knownArguments, id)?.name === name,
)
const index = argumentsLeftToMatch.splice(takeIdx, 1)[0]
const info = tryGetIndex(knownArguments, index)
return index != null && info != null ? { index, info } : undefined
}
function putBackArgument(index: number) {
argumentsLeftToMatch.unshift(index)
}
const lastPositionalArgIndex = findLastIndex(interpreted.args, (arg) => arg.argName == null)
let placeholderAlreadyInserted = false
let nextArgDefinition: ReturnType<typeof takeNextArgumentFromDefinition>
const makeArg = new ArgumentFactory(interpreted.func.id, ApplicationKind.Prefix, widgetCfg)
// Always insert a placeholder for the missing argument at the first position that is legal
// and don't invalidate further positional arguments, treating the named arguments at correct
// position as if they were positional.
for (let position = 0; position < interpreted.args.length; ++position) {
const argumentInCode = interpreted.args[position]
assert(!!argumentInCode)
const pastPositionalArguments = position > (lastPositionalArgIndex ?? -1)
if (
pastPositionalArguments &&
argumentInCode.argName != null &&
argumentInCode.argName !== nextArgumentNameInDefinition()
) {
// Named argument that is not in its natural position, and there are no more
// positional arguments to emit in the chain. At this point placeholders can be
// inserted. We need to figure out which placeholders can be inserted before
// emitting this named argument.
// all remaining arguments must be named, as we are past all positional arguments.
const remainingAppliedArguments = interpreted.args.slice(position)
// For each subsequent argument in its current natural position, insert a
// placeholder. Do that only if the argument is not defined further in the chain.
while ((nextArgDefinition = takeNextArgumentFromDefinition())) {
const { index, info } = nextArgDefinition
const isAppliedFurther = remainingAppliedArguments.some(
(arg) => arg.argName === info.name,
)
if (isAppliedFurther) {
putBackArgument(index)
break
} else {
resolvedArgs.push({
appTree: argumentInCode.appTree.function,
argument: makeArg.placeholder(index, info, placeholderAlreadyInserted),
})
placeholderAlreadyInserted = true
}
}
// Finally, we want to emit the named argument and remove it from the list of
// remaining known params.
const { index, info } = takeNamedArgumentFromDefinition(argumentInCode.argName) ?? {}
resolvedArgs.push({
appTree: argumentInCode.appTree,
argument: makeArg.argument(
argumentInCode.argument,
index,
info ?? unknownArgInfoNamed(argumentInCode.argName),
),
})
} else {
const argumentFromDefinition =
argumentInCode.argName == null ?
takeNextArgumentFromDefinition()
: takeNamedArgumentFromDefinition(argumentInCode.argName)
const { index, info } = argumentFromDefinition ?? {}
resolvedArgs.push({
appTree: argumentInCode.appTree,
argument: makeArg.argument(
argumentInCode.argument,
index,
info ??
(argumentInCode.argName != null ?
unknownArgInfoNamed(argumentInCode.argName)
: undefined),
),
})
}
}
const outerApp = interpreted.args[interpreted.args.length - 1]?.appTree ?? interpreted.func
// If there are any remaining known parameters, they must be inserted as trailing placeholders.
while ((nextArgDefinition = takeNextArgumentFromDefinition())) {
const { index, info } = nextArgDefinition
resolvedArgs.push({
appTree: outerApp,
argument: makeArg.placeholder(index, info, placeholderAlreadyInserted),
})
placeholderAlreadyInserted = true
}
return resolvedArgs.reduce(
(target: ArgumentApplication | Ast.Expression, toDisplay) =>
new ArgumentApplication(
toDisplay.appTree,
target,
undefined,
toDisplay.argument,
suggestion,
target === interpreted.func,
),
interpreted.func,
)
}
/** TODO: Add docs */
static FromInterpretedWithInfo(
interpreted: InterpretedCall,
callInfo: CallInfo = {},
): ArgumentApplication | Ast.Expression {
if (interpreted.kind === 'infix') {
return ArgumentApplication.FromInterpretedInfix(interpreted, callInfo)
} else {
return ArgumentApplication.FromInterpretedPrefix(interpreted, callInfo)
}
}
/** TODO: Add docs */
*iterApplications(): IterableIterator<ArgumentApplication> {
// This is not an alias, as it's an iteration variable.
// eslint-disable-next-line @typescript-eslint/no-this-alias
let current: typeof this.target = this
while (current instanceof ArgumentApplication) {
yield current
current = current.target
}
}
/** TODO: Add docs */
toWidgetInput(): WidgetInput {
return {
portId:
this.argument instanceof ArgumentAst ?
this.appTree.id
: (`app:${this.argument.portId}` as PortId),
value: this.appTree,
[ArgumentApplicationKey]: this,
}
}
/** TODO: Add docs */
static collectArgumentNamesAndUuids(
value: InterpretedCall,
mci: MethodCallInfo | undefined,
): Record<string, ExternalId> {
const namesAndExternalIds: Array<{
name: string | null
uuid: ExternalId | undefined
}> = []
const args = ArgumentApplication.FromInterpretedWithInfo(value)
if (args instanceof ArgumentApplication) {
for (const n of args.iterApplications()) {
const a = n.argument
if (a instanceof ArgumentPlaceholder) {
// pass thru
} else {
namesAndExternalIds.push({
name: a.argInfo?.name.toString() ?? null,
uuid: a.ast.externalId,
})
}
}
} else {
// don't process
}
namesAndExternalIds.reverse()
const argsExternalIds: Record<string, ExternalId> = {}
let index = 'self' === mci?.suggestion.arguments[0]?.name ? 1 : 0
for (const nameAndExtenalId of namesAndExternalIds) {
const notApplied = mci?.methodCall.notAppliedArguments ?? []
while (notApplied.indexOf(index) != -1) {
index++
}
if (nameAndExtenalId.uuid) {
argsExternalIds['' + index] = nameAndExtenalId.uuid
}
const suggestedName: string | undefined = mci?.suggestion.arguments[index]?.name
if (suggestedName && nameAndExtenalId.uuid) {
argsExternalIds[suggestedName] = nameAndExtenalId.uuid
}
index++
}
for (const nameAndExternalId of namesAndExternalIds) {
if (nameAndExternalId.name && nameAndExternalId.uuid) {
argsExternalIds[nameAndExternalId.name] = nameAndExternalId.uuid
}
}
return argsExternalIds
}
}
const unknownArgInfoNamed = (name: string) => ({
name,
reprType: 'Any',
isSuspended: false,
hasDefault: false,
})
/** TODO: Add docs */
export function getAccessOprSubject(app: Ast.Expression): Ast.Expression | undefined {
if (app instanceof Ast.PropertyAccess) return app.lhs
}
/**
* Same as {@link GraphDb.getMethodCallInfo} but with a special handling for nested Applications.
* Sometimes we receive MethodCallInfo for inner sub-applications of the expression,
* and we want to reuse it for outer application expressions when adding new arguments to the call.
* It requires adjusting `notAppliedArguments` array, but otherwise is a straightforward recursive call.
* We stop recursion at any not-application AST. We expect that a subexpression’s info is only valid if it is a part of the prefix application chain.
* We also don’t consider infix applications here, as using them inside a prefix chain would require additional syntax (like parenthesis).
*/
export function getMethodCallInfoRecursively(
ast: Ast.Expression,
graphDb: { getMethodCallInfo(id: AstId): MethodCallInfo | undefined },
): MethodCallInfo | undefined {
let appliedArgs = 0
const appliedNamedArgs: string[] = []
for (;;) {
const info = graphDb.getMethodCallInfo(ast.id)
if (info) {
// There is an info available! Stop the recursion and adjust `notAppliedArguments`.
// Indices of all named arguments applied so far.
const appliedNamed =
appliedNamedArgs.length > 0 ?
info.suggestion.arguments
.map((arg, index) => (appliedNamedArgs.includes(arg.name) ? index : -1))
.filter((i) => i !== -1)
: []
const withoutNamed = info.methodCall.notAppliedArguments.filter(
(idx) => !appliedNamed.includes(idx),
)
return {
methodCall: {
...info.methodCall,
notAppliedArguments: withoutNamed.sort().slice(appliedArgs),
},
methodCallSource: ast.id,
suggestion: info.suggestion,
}
}
// No info, continue recursion to the next sub-application AST.
if (ast instanceof Ast.App) {
if (ast.argumentName) {
appliedNamedArgs.push(ast.argumentName.code())
} else {
appliedArgs += 1
}
ast = ast.function
} else {
break
}
}
}
export const ArgumentApplicationKey: unique symbol = Symbol.for('WidgetInput:ArgumentApplication')
export const ArgumentInfoKey: unique symbol = Symbol.for('WidgetInput:ArgumentInfo')
declare module '@/providers/widgetRegistry' {
export interface WidgetInput {
[ArgumentApplicationKey]?: ArgumentApplication
[ArgumentInfoKey]?: {
appKind: ApplicationKind
info: SuggestionEntryArgument | undefined
argId: string | undefined
}
}
}