Skip to content
← Back

src/syntax/process/completer.ghul

1
@@IF.dotnet()
2
3
namespace Syntax.Process is
4
use LAZY = System.Lazy
5
6
use IO.Std
7
8
use Pair = Collections.KeyValuePair
9
10
use Logging
11
use Source
12
13
// One context-appropriate keyword to offer, optionally with a snippet body.
14
// The body uses LSP tabstop syntax (`$1`, `$2`, `$0`); empty body means
15
// "insert `name` verbatim". The COMPLETION_HANDLER forwards both fields
16
// through to the client; the VSCE turns a non-empty body into a tabbable
17
// snippet insertion.
18
class KEYWORD_COMPLETION is
19
name: string public
20
snippet: string public
21
22
init(name: string, snippet: string) is
23
self.name = name
24
self.snippet = snippet
25
si
26
si
27
28
class COMPLETER: ScopedVisitor is
29
_target_line: int
30
_target_column: int
31
32
_dotnet_symbol_table: LAZY[Semantic.DotNet.SYMBOL_TABLE]
33
34
_results: Collections.MAP[string,Semantic.Symbols.Symbol]
35
_keyword_results: Collections.LIST[KEYWORD_COMPLETION]
36
37
_have_hit: bool
38
39
// Sticky: set to true when the cursor sits inside any
40
// type-expression node, so the final result set can be
41
// filtered down to type-like kinds (classes, traits,
42
// structs, enums, namespaces, type parameters). Values
43
// — locals, fields, functions, properties, constants —
44
// never belong in a type-expression position.
45
_in_type_position: bool
46
47
// Set when the cursor sits in the right-hand side of a `|>`,
48
// where the useful candidates are the functions the threaded
49
// subject can be passed to rather than every name in scope.
50
// Carries the subject's type when it has one, so the filter can
51
// judge each candidate's first parameter; null when the subject
52
// did not compile.
53
_thread_first_subject_type: Semantic.Types.Type?
54
_in_thread_first_position: bool
55
56
_thread_first_filter: THREAD_FIRST_CANDIDATE_FILTER
57
58
// Set when the results are the members of something to the left
59
// of a `.` — a member access or a qualified name — rather than
60
// the enclosing scope. A client that asked because the user
61
// typed a `.` reads this to tell an empty answer apart from an
62
// answer about the wrong thing.
63
_is_member_completion: bool
64
65
keyword_results: Collections.Iterable[KEYWORD_COMPLETION] => _keyword_results
66
67
is_member_completion: bool => _is_member_completion
68
69
// The result collections belong to one find_completions call and
70
// are rebuilt at the top of each.
71
@suppress("field-definite-assignment")
72
init(
73
logger: Logger,
74
symbol_table: Semantic.SYMBOL_TABLE,
75
namespaces: Semantic.NAMESPACES,
76
dotnet_symbol_table: LAZY[Semantic.DotNet.SYMBOL_TABLE]
77
)
78
is
79
super.init(logger, symbol_table, namespaces)
80
81
_dotnet_symbol_table = dotnet_symbol_table
82
_thread_first_filter = THREAD_FIRST_CANDIDATE_FILTER()
83
si
84
85
find_completions(root: Trees.Node, target_line: int, target_column: int) -> Collections.Iterable[Pair[string,Semantic.Symbols.Symbol]] is
86
_have_hit = false
87
_in_type_position = false
88
_is_member_completion = false
89
_in_thread_first_position = false
90
_thread_first_subject_type = null
91
92
_target_line = target_line
93
_target_column = target_column
94
95
_results = Collections.MAP[string,Semantic.Symbols.Symbol]()
96
_keyword_results = Collections.LIST[KEYWORD_COMPLETION]()
97
98
root.walk(self)
99
100
_apply_thread_first_filter()
101
_apply_type_position_filter()
102
103
return _results
104
si
105
106
// Note when the cursor sits inside a type-expression node.
107
// The flag is sticky once set: every TypeExpression pre
108
// override below funnels through here, and the cursor can
109
// only sit inside one of them at a time.
110
_check_type_position(node: Trees.Node) is
111
if !_in_type_position /\ node.location.contains(_target_line, _target_column) then
112
_in_type_position = true
113
fi
114
si
115
116
// If the cursor settled in a type-expression position, drop
117
// every non-type-like symbol from the result set. Allowed
118
// kinds: CLASS, INTERFACE (traits), STRUCT, ENUM, MODULE
119
// (namespaces), TYPE_PARAMETER. Locals, fields, functions,
120
// properties, constants, enum members and operators are
121
// never useful in a type expression. Statement keywords
122
// (`if`, `while`, `let`, …) get cleared too — none of them
123
// start a type expression.
124
_apply_type_position_filter() is
125
if !_in_type_position then
126
return
127
fi
128
129
let kept = Collections.MAP[string,Semantic.Symbols.Symbol]()
130
131
for pair in _results do
132
if _is_type_like(pair.value.completion_kind) then
133
kept.add(pair.key, pair.value)
134
fi
135
od
136
137
_results = kept
138
_keyword_results = Collections.LIST[KEYWORD_COMPLETION]()
139
si
140
141
// Reduce the scope dump to the names that could lead the call the
142
// `|>` is on its way to. Keywords go with them: none of them start
143
// a call.
144
_apply_thread_first_filter() is
145
// Only the scope dump is filtered. A `|>` whose call is written
146
// against a receiver or a namespace (`x |> box.combine(a)`)
147
// puts the cursor in a member position inside the same
148
// completion target, and those results are already the right
149
// ones.
150
if !_in_thread_first_position \/ _is_member_completion then
151
return
152
fi
153
154
_results = _thread_first_filter.apply(_results, _thread_first_subject_type)
155
_keyword_results = Collections.LIST[KEYWORD_COMPLETION]()
156
si
157
158
_is_type_like(kind: Semantic.Symbols.CompletionKind) -> bool =>
159
kind == Semantic.Symbols.CompletionKind.CLASS \/
160
kind == Semantic.Symbols.CompletionKind.INTERFACE \/
161
kind == Semantic.Symbols.CompletionKind.STRUCT \/
162
kind == Semantic.Symbols.CompletionKind.ENUM \/
163
kind == Semantic.Symbols.CompletionKind.MODULE \/
164
kind == Semantic.Symbols.CompletionKind.TYPE_PARAMETER
165
166
leave_scope(node: Trees.ScopeCarrier) is
167
if !_have_hit /\ !_is_synthesized_wrapper(node) /\ node.location.contains(_target_line, _target_column) then
168
add_keyword_matches(node)
169
add_scope_matches()
170
fi
171
172
super.leave_scope(node)
173
si
174
175
_is_synthesized_wrapper(node: Trees.ScopeCarrier) -> bool =>
176
if let function = cast Trees.Definitions.FUNCTION?(node) then function.is_synthesized_main_wrapper else false fi
177
178
// A namespace is left through leave_namespace rather than through the
179
// ScopeCarrier overload above, so a cursor in a namespace body - between
180
// definitions, or on the line after a `use` - reaches no scope at all
181
// without this.
182
visit(`namespace: Trees.Definitions.NAMESPACE) is
183
if !_have_hit /\ `namespace.location.contains(_target_line, _target_column) then
184
add_keyword_matches(`namespace)
185
add_scope_matches()
186
fi
187
188
super.visit(`namespace)
189
si
190
191
// The innermost scope containing the cursor is left first, so `node`
192
// here is the tightest enclosing definition / statement scope. Offer
193
// the keywords that can lead a construct in that context. Keywords
194
// whose canonical shape is a multi-line construct carry a snippet
195
// body the client can expand as a tabbable template; the rest insert
196
// their name verbatim.
197
//
198
// Snippet bodies use LSP tabstop syntax: `${N:placeholder}` for an
199
// ordered tabstop with a selectable default, `$0` for the final
200
// cursor position. The cursor starts at `$1` and ends at `$0`. For
201
// multi-line constructs `$0` sits in the body so the user lands
202
// ready to type the block contents after filling the header.
203
add_keyword_matches(node: Trees.ScopeCarrier) is
204
if isa Trees.Definitions.NAMESPACE(node) then
205
_snippet("namespace", "namespace ${1:Name} is\n\t$0\nsi")
206
_plain ("use")
207
_snippet("class", "class ${1:Name} is\n\t$0\nsi")
208
_snippet("trait", "trait ${1:Name} is\n\t$0\nsi")
209
_snippet("struct", "struct ${1:Name} is\n\t$0\nsi")
210
_snippet("union", "union ${1:Name} is\n\t$0\nsi")
211
_snippet("enum", "enum ${1:Name} is\n\t$0\nsi")
212
elif isa Trees.Definitions.ENUM(node) then
213
// an enum body holds enum members, not keyword-led constructs
214
elif isa Trees.Definitions.Classy(node) then
215
_plain ("use")
216
_snippet("class", "class ${1:Name} is\n\t$0\nsi")
217
_snippet("trait", "trait ${1:Name} is\n\t$0\nsi")
218
_snippet("struct", "struct ${1:Name} is\n\t$0\nsi")
219
_snippet("union", "union ${1:Name} is\n\t$0\nsi")
220
_snippet("enum", "enum ${1:Name} is\n\t$0\nsi")
221
_plain ("public")
222
_plain ("private")
223
_plain ("protected")
224
_plain ("static")
225
_plain ("field")
226
_plain ("innate")
227
else
228
_plain ("assert")
229
_snippet("break", "break;\n$0")
230
_snippet("case", "case ${1:expression}\n\twhen ${2:pattern} then\n\t\t$0\nesac")
231
_plain ("cast")
232
_snippet("continue", "continue;\n$0")
233
_snippet("do", "do\n\t$0\nod")
234
_plain ("false")
235
_snippet("for", "for ${1:element} in ${2:iterable} do\n\t$0\nod")
236
_snippet("if", "if ${1:condition} then\n\t$0\nfi")
237
_plain ("isa")
238
_snippet("let", "let $0")
239
_plain ("null")
240
_plain ("return")
241
_plain ("self")
242
_plain ("super")
243
_plain ("throw")
244
_plain ("true")
245
_snippet("try", "try\n\t$0\nyrt")
246
_plain ("typeof")
247
_snippet("while", "while ${1:condition} do\n\t$0\nod")
248
fi
249
si
250
251
_plain(name: string) is
252
_keyword_results.add(KEYWORD_COMPLETION(name, ""))
253
si
254
255
_snippet(name: string, body: string) is
256
_keyword_results.add(KEYWORD_COMPLETION(name, body))
257
si
258
259
add_scope_matches() is
260
find_matches("", _results)
261
262
_namespaces.find_root_matches(_results)
263
_dotnet_symbol_table.value.find_root_matches(_results)
264
265
_have_hit = true
266
si
267
268
visit_literal(location: LOCATION) is
269
if
270
location.contains(_target_line, _target_column) \/
271
location.contains(_target_line, _target_column - 1)
272
then
273
_have_hit = true
274
fi
275
si
276
277
pre(`use: Trees.Definitions.USE) -> bool => true
278
visit(`use: Trees.Definitions.USE) is
279
if !`use.location.contains(_target_line, _target_column) then
280
return
281
fi
282
283
let identifier = `use.`use
284
285
if identifier? /\ identifier.location.contains(_target_line, _target_column) /\ isa Trees.Identifiers.QUALIFIED(identifier) then
286
add_qualified_identifier_matches(identifier)
287
else
288
add_scope_matches()
289
fi
290
si
291
292
visit(literal: Trees.Expressions.Literals.INTEGER) is
293
visit_literal(literal.location)
294
si
295
296
visit(literal: Trees.Expressions.Literals.FLOAT) is
297
visit_literal(literal.location)
298
si
299
300
pre(interpolation: Trees.Expressions.STRING_INTERPOLATION) -> bool is
301
if !interpolation.location.contains(_target_line, _target_column) then
302
return true
303
fi
304
305
for f in interpolation.values do
306
if
307
f.is_expression /\
308
f.expression.location.contains(_target_line, _target_column)
309
then
310
// cursor is in an iterpolated expression - allow the tree walk
311
// to continue and let the appropriate expression node handle it
312
return false
313
fi
314
od
315
316
// none of the expressions contain the cursor - block the tree
317
// walk from continuing
318
_have_hit = true
319
return true
320
si
321
322
visit(literal: Trees.Expressions.STRING_INTERPOLATION) is
323
si
324
325
visit(literal: Trees.Expressions.Literals.CHARACTER) is
326
visit_literal(literal.location)
327
si
328
329
visit(literal: Trees.Expressions.Literals.BOOLEAN) is
330
visit_literal(literal.location)
331
si
332
333
visit(qualified: Trees.Identifiers.QUALIFIED) is
334
if !qualified.completion_target.contains(_target_line, _target_column) then
335
return
336
fi
337
338
add_qualified_identifier_matches(qualified)
339
si
340
341
add_qualified_identifier_matches(qualified: Trees.Identifiers.QUALIFIED) is
342
_is_member_completion = true
343
344
let symbol = find(qualified.qualifier)
345
let namespace_name = qualified.qualifier.to_string()
346
347
if !symbol? then
348
_namespaces.find_namespace_matches(namespace_name, _results)
349
_dotnet_symbol_table.value.find_member_matches(namespace_name, _results)
350
351
Semantic.DotNet.HIDDEN_SYMBOLS.prune_hidden(namespace_name, _results)
352
353
_have_hit = true
354
return
355
fi
356
357
if !isa Semantic.Symbols.Scoped(symbol) then
358
return
359
fi
360
361
symbol.find_member_matches("", _results)
362
363
_namespaces.find_namespace_matches(namespace_name, _results)
364
365
_dotnet_symbol_table.value.find_member_matches(namespace_name, _results)
366
367
Semantic.DotNet.HIDDEN_SYMBOLS.prune_hidden(namespace_name, _results)
368
369
_keep_offered_members(false)
370
371
_have_hit = true
372
si
373
374
// The right-hand side of a `|>`, whether or not the call is
375
// finished being typed. The subject has already been threaded in
376
// as argument 0, so its compiled type is what the candidates are
377
// judged against. The walk still continues: a cursor inside the
378
// remaining arguments is an ordinary expression position, and the
379
// completion target covers only the operator and the called name.
380
pre(call: Trees.Expressions.CALL) -> bool is
381
let target = call.completion_target
382
383
if
384
!call.is_thread_first \/ !target? \/
385
!target.contains(_target_line, _target_column)
386
then
387
return false
388
fi
389
390
_in_thread_first_position = true
391
392
let subject = call.arguments.expressions
393
394
if subject.count > 0 then
395
if let value = subject[0].value then
396
_thread_first_subject_type = value.type
397
fi
398
fi
399
400
return false
401
si
402
403
visit(member: Trees.Expressions.MEMBER) is
404
if !member.completion_target.contains(_target_line, _target_column) then
405
return
406
fi
407
408
// The cursor sits inside this member-access expression's
409
// completion target. Anything we return is "members of the
410
// LHS", never a scope dump — claim the hit up front so the
411
// enclosing leave_scope fallback can't add unrelated
412
// identifiers, keywords, or root namespaces.
413
_have_hit = true
414
_is_member_completion = true
415
416
let symbol = _resolve_member_lhs_symbol(member.left)
417
418
if !symbol? then
419
return
420
fi
421
422
symbol.find_member_matches("", _results)
423
424
_keep_offered_members(isa Trees.Expressions.SELF(member.left) \/ isa Trees.Expressions.SUPER(member.left))
425
si
426
427
// Drops what a program cannot write after this dot.
428
_keep_offered_members(from_inside: bool) is
429
let kept = Collections.MAP[string,Semantic.Symbols.Symbol]()
430
431
for pair in _results do
432
if MEMBER_COMPLETION_FILTER.is_offered(pair.key, pair.value, from_inside) then
433
kept.add(pair.key, pair.value)
434
fi
435
od
436
437
_results = kept
438
si
439
440
// Type-expression pre overrides — every subclass funnels
441
// through `_check_type_position` so the sticky type-position
442
// flag is set whenever the cursor lands in one. The walk
443
// continues into children normally (return false).
444
pre(named: Trees.TypeExpressions.NAMED) -> bool is _check_type_position(named); return false; si
445
pre(generic: Trees.TypeExpressions.GENERIC) -> bool is _check_type_position(generic); return false; si
446
pre(member: Trees.TypeExpressions.MEMBER) -> bool is _check_type_position(member); return false; si
447
pre(function: Trees.TypeExpressions.FUNCTION) -> bool is _check_type_position(function); return false; si
448
pre(functions: Trees.TypeExpressions.FUNCTION_GROUP) -> bool is _check_type_position(functions); return false; si
449
pre(tuple: Trees.TypeExpressions.TUPLE) -> bool is _check_type_position(tuple); return false; si
450
pre(array: Trees.TypeExpressions.ARRAY_) -> bool is _check_type_position(array); return false; si
451
pre(iterable: Trees.TypeExpressions.ITERABLE) -> bool is _check_type_position(iterable); return false; si
452
pre(pointer: Trees.TypeExpressions.POINTER) -> bool is _check_type_position(pointer); return false; si
453
pre(optional: Trees.TypeExpressions.OPTIONAL) -> bool is _check_type_position(optional); return false; si
454
pre(reference: Trees.TypeExpressions.REFERENCE) -> bool is _check_type_position(reference); return false; si
455
pre(infer: Trees.TypeExpressions.INFER) -> bool is _check_type_position(infer); return false; si
456
pre(undefined: Trees.TypeExpressions.UNDEFINED) -> bool is _check_type_position(undefined); return false; si
457
pre(constraint: Trees.TypeExpressions.TYPE_PARAMETER_CONSTRAINT) -> bool is _check_type_position(constraint); return false; si
458
459
// A NAMED_TUPLE_ELEMENT is either a tuple element (`(x: int,
460
// y: int)`), a function literal parameter (`(x: int) -> int`),
461
// or a generic type parameter declaration (`[T: Foo]`). The
462
// `name` slot in every one of those is a name the user is
463
// *introducing* — not a position to suggest existing symbols.
464
// When the cursor sits there, claim the hit and block the
465
// walk into children so the scope fallback can't dump.
466
// Otherwise treat the element as ordinary type-position
467
// context.
468
pre(element: Trees.TypeExpressions.NAMED_TUPLE_ELEMENT) -> bool is
469
if element.name.location.contains(_target_line, _target_column) then
470
_have_hit = true
471
return true
472
fi
473
474
_check_type_position(element)
475
return false
476
si
477
478
// When the user has typed `let x:` with nothing after, the
479
// parser produces an UNDEFINED type expression sitting on
480
// the next concrete token (often a line below) — its
481
// location doesn't cover the cursor, so the type-expression
482
// pre hooks above never fire. Recognise the type-position
483
// gap explicitly: a VARIABLE whose declared type is
484
// explicit, where the cursor is strictly past the variable
485
// name's end and strictly before the initializer's start
486
// (or there is no initializer), must be in the type slot.
487
pre(variable: Trees.Variables.VARIABLE) -> bool is
488
if !variable.is_explicit_type \/ !variable.location.contains(_target_line, _target_column) then
489
return false
490
fi
491
492
let cursor = Source.LOCATION.pair(_target_line, _target_column)
493
494
if variable.left.location.end >= cursor then
495
return false
496
fi
497
498
if variable.initializer? /\ variable.initializer.location.start <= cursor then
499
return false
500
fi
501
502
_in_type_position = true
503
return false
504
si
505
506
// Mirror the VARIABLE gap rule for a function's return type:
507
// the parser may park an UNDEFINED return type on the next
508
// token, away from the cursor. When the cursor sits inside
509
// the FUNCTION but strictly past the arguments' close-paren
510
// and strictly before the body's start (or there is no
511
// body), it's in the return-type slot. Forward to super so
512
// the function's scope still gets entered.
513
pre(function: Trees.Definitions.FUNCTION) -> bool is
514
let result = super.pre(function)
515
516
// A function the compiler writes around top-level statements is
517
// located at those statements, as are the parameters and return
518
// type it gives the entry, so none of them can be what the cursor
519
// is on. Only the statements themselves are walked.
520
if function.is_synthesized_main_wrapper then
521
return true
522
fi
523
524
if function.is_top_level_entry then
525
if let body = function.body then
526
body.walk(self)
527
528
// The statements end at their last token, so a cursor
529
// just after it - where a name being typed at the end
530
// of the file is completed - lies in no scope. It is
531
// still in the statements, and completes from them.
532
if !_have_hit /\ body.location.start <= Source.LOCATION.pair(_target_line, _target_column) then
533
add_keyword_matches(function)
534
add_scope_matches()
535
fi
536
fi
537
538
return true
539
fi
540
541
if !function.location.contains(_target_line, _target_column) then
542
return result
543
fi
544
545
// A function's generic parameters are not walked with it, so a
546
// cursor in one of their bounds is reached from here.
547
if function.generic_arguments.location.contains(_target_line, _target_column) then
548
function.generic_arguments.walk(self)
549
return result
550
fi
551
552
let cursor = Source.LOCATION.pair(_target_line, _target_column)
553
554
if function.arguments.location.end >= cursor then
555
return result
556
fi
557
558
if function.body? /\ function.body.extent.start <= cursor then
559
return result
560
fi
561
562
_in_type_position = true
563
return result
564
si
565
566
// Resolve the LHS of a member-access expression to the symbol
567
// whose members the completer should enumerate. Three sources,
568
// in order: the IR value's type for evaluated values (the
569
// common `local.|` case); the named identifier the LHS copies
570
// to for type / namespace references (`TYPE.|`, `Outer.Inner.|`,
571
// `IO.|`); null when neither resolves.
572
_resolve_member_lhs_symbol(left: Trees.Expressions.Expression) -> Semantic.Symbols.Symbol? is
573
if let value = left.value /\ value.type? /\ value.type.is_named then
574
let type = value.type
575
576
if type.is_ref then
577
// is_ref implies an element type; the runtime
578
// invariant guarantees get_element_type() non-null.
579
return type.get_element_type()!.symbol
580
fi
581
582
return type.symbol
583
fi
584
585
let identifier = left.try_copy_as_identifer()
586
587
if identifier? then
588
return try_find(identifier)
589
fi
590
591
return null
592
si
593
si
594
si