-
Notifications
You must be signed in to change notification settings - Fork 546
Expand file tree
/
Copy pathAutocompleteCore.cpp
More file actions
2057 lines (1739 loc) · 69.7 KB
/
AutocompleteCore.cpp
File metadata and controls
2057 lines (1739 loc) · 69.7 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
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details
#include "AutocompleteCore.h"
#include "Luau/Ast.h"
#include "Luau/AstQuery.h"
#include "Luau/AutocompleteTypes.h"
#include "Luau/BuiltinDefinitions.h"
#include "Luau/Common.h"
#include "Luau/FileResolver.h"
#include "Luau/Frontend.h"
#include "Luau/TimeTrace.h"
#include "Luau/ToString.h"
#include "Luau/Subtyping.h"
#include "Luau/TypeInfer.h"
#include "Luau/TypePack.h"
#include <algorithm>
#include <unordered_set>
#include <utility>
LUAU_FASTFLAG(LuauSolverV2)
LUAU_FASTINT(LuauTypeInferIterationLimit)
LUAU_FASTINT(LuauTypeInferRecursionLimit)
LUAU_FASTFLAGVARIABLE(LuauAutocompleteRefactorsForIncrementalAutocomplete)
LUAU_FASTFLAGVARIABLE(LuauAutocompleteUsesModuleForTypeCompatibility)
static const std::unordered_set<std::string> kStatementStartingKeywords =
{"while", "if", "local", "repeat", "function", "do", "for", "return", "break", "continue", "type", "export"};
namespace Luau
{
static bool alreadyHasParens(const std::vector<AstNode*>& nodes)
{
auto iter = nodes.rbegin();
while (iter != nodes.rend() &&
((*iter)->is<AstExprLocal>() || (*iter)->is<AstExprGlobal>() || (*iter)->is<AstExprIndexName>() || (*iter)->is<AstExprIndexExpr>()))
{
iter++;
}
if (iter == nodes.rend() || iter == nodes.rbegin())
{
return false;
}
if (AstExprCall* call = (*iter)->as<AstExprCall>())
{
return call->func == *(iter - 1);
}
return false;
}
static ParenthesesRecommendation getParenRecommendationForFunc(const FunctionType* func, const std::vector<AstNode*>& nodes)
{
if (alreadyHasParens(nodes))
{
return ParenthesesRecommendation::None;
}
auto idxExpr = nodes.back()->as<AstExprIndexName>();
bool hasImplicitSelf = idxExpr && idxExpr->op == ':';
auto [argTypes, argVariadicPack] = Luau::flatten(func->argTypes);
if (argVariadicPack.has_value() && isVariadic(*argVariadicPack))
return ParenthesesRecommendation::CursorInside;
bool noArgFunction = argTypes.empty() || (hasImplicitSelf && argTypes.size() == 1);
return noArgFunction ? ParenthesesRecommendation::CursorAfter : ParenthesesRecommendation::CursorInside;
}
static ParenthesesRecommendation getParenRecommendationForIntersect(const IntersectionType* intersect, const std::vector<AstNode*>& nodes)
{
ParenthesesRecommendation rec = ParenthesesRecommendation::None;
for (Luau::TypeId partId : intersect->parts)
{
if (auto partFunc = Luau::get<FunctionType>(partId))
{
rec = std::max(rec, getParenRecommendationForFunc(partFunc, nodes));
}
else
{
return ParenthesesRecommendation::None;
}
}
return rec;
}
static ParenthesesRecommendation getParenRecommendation(TypeId id, const std::vector<AstNode*>& nodes, TypeCorrectKind typeCorrect)
{
// If element is already type-correct, even a function should be inserted without parenthesis
if (typeCorrect == TypeCorrectKind::Correct)
return ParenthesesRecommendation::None;
id = Luau::follow(id);
if (auto func = get<FunctionType>(id))
{
return getParenRecommendationForFunc(func, nodes);
}
else if (auto intersect = get<IntersectionType>(id))
{
return getParenRecommendationForIntersect(intersect, nodes);
}
return ParenthesesRecommendation::None;
}
static std::optional<TypeId> findExpectedTypeAt(const Module& module, AstNode* node, Position position)
{
auto expr = node->asExpr();
if (!expr)
return std::nullopt;
// Extra care for first function call argument location
// When we don't have anything inside () yet, we also don't have an AST node to base our lookup
if (AstExprCall* exprCall = expr->as<AstExprCall>())
{
if (exprCall->args.size == 0 && exprCall->argLocation.contains(position))
{
auto it = module.astTypes.find(exprCall->func);
if (!it)
return std::nullopt;
const FunctionType* ftv = get<FunctionType>(follow(*it));
if (!ftv)
return std::nullopt;
auto [head, tail] = flatten(ftv->argTypes);
unsigned index = exprCall->self ? 1 : 0;
if (index < head.size())
return head[index];
return std::nullopt;
}
}
auto it = module.astExpectedTypes.find(expr);
if (!it)
return std::nullopt;
return *it;
}
static bool checkTypeMatch(
const Module& module,
TypeId subTy,
TypeId superTy,
NotNull<Scope> scope,
TypeArena* typeArena,
NotNull<BuiltinTypes> builtinTypes
)
{
InternalErrorReporter iceReporter;
UnifierSharedState unifierState(&iceReporter);
SimplifierPtr simplifier = newSimplifier(NotNull{typeArena}, builtinTypes);
Normalizer normalizer{typeArena, builtinTypes, NotNull{&unifierState}};
if (FFlag::LuauAutocompleteUsesModuleForTypeCompatibility)
{
if (module.checkedInNewSolver)
{
TypeCheckLimits limits;
TypeFunctionRuntime typeFunctionRuntime{
NotNull{&iceReporter}, NotNull{&limits}
}; // TODO: maybe subtyping checks should not invoke user-defined type function runtime
unifierState.counters.recursionLimit = FInt::LuauTypeInferRecursionLimit;
unifierState.counters.iterationLimit = FInt::LuauTypeInferIterationLimit;
Subtyping subtyping{
builtinTypes,
NotNull{typeArena},
NotNull{simplifier.get()},
NotNull{&normalizer},
NotNull{&typeFunctionRuntime},
NotNull{&iceReporter}
};
return subtyping.isSubtype(subTy, superTy, scope).isSubtype;
}
else
{
Unifier unifier(NotNull<Normalizer>{&normalizer}, scope, Location(), Variance::Covariant);
// Cost of normalization can be too high for autocomplete response time requirements
unifier.normalize = false;
unifier.checkInhabited = false;
unifierState.counters.recursionLimit = FInt::LuauTypeInferRecursionLimit;
unifierState.counters.iterationLimit = FInt::LuauTypeInferIterationLimit;
return unifier.canUnify(subTy, superTy).empty();
}
}
else
{
if (FFlag::LuauSolverV2)
{
TypeCheckLimits limits;
TypeFunctionRuntime typeFunctionRuntime{
NotNull{&iceReporter}, NotNull{&limits}
}; // TODO: maybe subtyping checks should not invoke user-defined type function runtime
unifierState.counters.recursionLimit = FInt::LuauTypeInferRecursionLimit;
unifierState.counters.iterationLimit = FInt::LuauTypeInferIterationLimit;
Subtyping subtyping{
builtinTypes,
NotNull{typeArena},
NotNull{simplifier.get()},
NotNull{&normalizer},
NotNull{&typeFunctionRuntime},
NotNull{&iceReporter}
};
return subtyping.isSubtype(subTy, superTy, scope).isSubtype;
}
else
{
Unifier unifier(NotNull<Normalizer>{&normalizer}, scope, Location(), Variance::Covariant);
// Cost of normalization can be too high for autocomplete response time requirements
unifier.normalize = false;
unifier.checkInhabited = false;
unifierState.counters.recursionLimit = FInt::LuauTypeInferRecursionLimit;
unifierState.counters.iterationLimit = FInt::LuauTypeInferIterationLimit;
return unifier.canUnify(subTy, superTy).empty();
}
}
}
static TypeCorrectKind checkTypeCorrectKind(
const Module& module,
TypeArena* typeArena,
NotNull<BuiltinTypes> builtinTypes,
AstNode* node,
Position position,
TypeId ty
)
{
ty = follow(ty);
LUAU_ASSERT(module.hasModuleScope());
NotNull<Scope> moduleScope{module.getModuleScope().get()};
auto typeAtPosition = findExpectedTypeAt(module, node, position);
if (!typeAtPosition)
return TypeCorrectKind::None;
TypeId expectedType = follow(*typeAtPosition);
auto checkFunctionType = [typeArena, builtinTypes, moduleScope, &expectedType, &module](const FunctionType* ftv)
{
if (std::optional<TypeId> firstRetTy = first(ftv->retTypes))
return checkTypeMatch(module, *firstRetTy, expectedType, moduleScope, typeArena, builtinTypes);
return false;
};
// We also want to suggest functions that return compatible result
if (const FunctionType* ftv = get<FunctionType>(ty); ftv && checkFunctionType(ftv))
{
return TypeCorrectKind::CorrectFunctionResult;
}
else if (const IntersectionType* itv = get<IntersectionType>(ty))
{
for (TypeId id : itv->parts)
{
id = follow(id);
if (const FunctionType* ftv = get<FunctionType>(id); ftv && checkFunctionType(ftv))
{
return TypeCorrectKind::CorrectFunctionResult;
}
}
}
return checkTypeMatch(module, ty, expectedType, moduleScope, typeArena, builtinTypes) ? TypeCorrectKind::Correct : TypeCorrectKind::None;
}
enum class PropIndexType
{
Point,
Colon,
Key,
};
static void autocompleteProps(
const Module& module,
TypeArena* typeArena,
NotNull<BuiltinTypes> builtinTypes,
TypeId rootTy,
TypeId ty,
PropIndexType indexType,
const std::vector<AstNode*>& nodes,
AutocompleteEntryMap& result,
std::unordered_set<TypeId>& seen,
std::optional<const ClassType*> containingClass = std::nullopt
)
{
rootTy = follow(rootTy);
ty = follow(ty);
if (seen.count(ty))
return;
seen.insert(ty);
auto isWrongIndexer = [typeArena, builtinTypes, &module, rootTy, indexType](Luau::TypeId type)
{
if (indexType == PropIndexType::Key)
return false;
bool calledWithSelf = indexType == PropIndexType::Colon;
auto isCompatibleCall = [typeArena, builtinTypes, &module, rootTy, calledWithSelf](const FunctionType* ftv)
{
// Strong match with definition is a success
if (calledWithSelf == ftv->hasSelf)
return true;
// Calls on classes require strict match between how function is declared and how it's called
if (get<ClassType>(rootTy))
return false;
// When called with ':', but declared without 'self', it is invalid if a function has incompatible first argument or no arguments at all
// When called with '.', but declared with 'self', it is considered invalid if first argument is compatible
if (std::optional<TypeId> firstArgTy = first(ftv->argTypes))
{
if (checkTypeMatch(module, rootTy, *firstArgTy, NotNull{module.getModuleScope().get()}, typeArena, builtinTypes))
return calledWithSelf;
}
return !calledWithSelf;
};
if (const FunctionType* ftv = get<FunctionType>(type))
return !isCompatibleCall(ftv);
// For intersections, any part that is successful makes the whole call successful
if (const IntersectionType* itv = get<IntersectionType>(type))
{
for (auto subType : itv->parts)
{
if (const FunctionType* ftv = get<FunctionType>(Luau::follow(subType)))
{
if (isCompatibleCall(ftv))
return false;
}
}
}
return calledWithSelf;
};
auto fillProps = [&](const ClassType::Props& props)
{
for (const auto& [name, prop] : props)
{
// We are walking up the class hierarchy, so if we encounter a property that we have
// already populated, it takes precedence over the property we found just now.
if (result.count(name) == 0 && name != kParseNameError)
{
Luau::TypeId type;
if (FFlag::LuauSolverV2)
{
if (auto ty = prop.readTy)
type = follow(*ty);
else
continue;
}
else
type = follow(prop.type());
TypeCorrectKind typeCorrect = indexType == PropIndexType::Key
? TypeCorrectKind::Correct
: checkTypeCorrectKind(module, typeArena, builtinTypes, nodes.back(), {{}, {}}, type);
ParenthesesRecommendation parens =
indexType == PropIndexType::Key ? ParenthesesRecommendation::None : getParenRecommendation(type, nodes, typeCorrect);
result[name] = AutocompleteEntry{
AutocompleteEntryKind::Property,
type,
prop.deprecated,
isWrongIndexer(type),
typeCorrect,
containingClass,
&prop,
prop.documentationSymbol,
{},
parens,
{},
indexType == PropIndexType::Colon
};
}
}
};
auto fillMetatableProps = [&](const TableType* mtable)
{
auto indexIt = mtable->props.find("__index");
if (indexIt != mtable->props.end())
{
TypeId followed = follow(indexIt->second.type());
if (get<TableType>(followed) || get<MetatableType>(followed))
{
autocompleteProps(module, typeArena, builtinTypes, rootTy, followed, indexType, nodes, result, seen);
}
else if (auto indexFunction = get<FunctionType>(followed))
{
std::optional<TypeId> indexFunctionResult = first(indexFunction->retTypes);
if (indexFunctionResult)
autocompleteProps(module, typeArena, builtinTypes, rootTy, *indexFunctionResult, indexType, nodes, result, seen);
}
}
};
if (auto cls = get<ClassType>(ty))
{
containingClass = containingClass.value_or(cls);
fillProps(cls->props);
if (cls->parent)
autocompleteProps(module, typeArena, builtinTypes, rootTy, *cls->parent, indexType, nodes, result, seen, containingClass);
}
else if (auto tbl = get<TableType>(ty))
fillProps(tbl->props);
else if (auto mt = get<MetatableType>(ty))
{
autocompleteProps(module, typeArena, builtinTypes, rootTy, mt->table, indexType, nodes, result, seen);
if (auto mtable = get<TableType>(follow(mt->metatable)))
fillMetatableProps(mtable);
}
else if (auto i = get<IntersectionType>(ty))
{
// Complete all properties in every variant
for (TypeId ty : i->parts)
{
AutocompleteEntryMap inner;
std::unordered_set<TypeId> innerSeen = seen;
autocompleteProps(module, typeArena, builtinTypes, rootTy, ty, indexType, nodes, inner, innerSeen);
for (auto& pair : inner)
result.insert(pair);
}
}
else if (auto u = get<UnionType>(ty))
{
// Complete all properties common to all variants
auto iter = begin(u);
auto endIter = end(u);
while (iter != endIter)
{
if (isNil(*iter))
++iter;
else
break;
}
if (iter == endIter)
return;
autocompleteProps(module, typeArena, builtinTypes, rootTy, *iter, indexType, nodes, result, seen);
++iter;
while (iter != endIter)
{
AutocompleteEntryMap inner;
std::unordered_set<TypeId> innerSeen;
if (isNil(*iter))
{
++iter;
continue;
}
autocompleteProps(module, typeArena, builtinTypes, rootTy, *iter, indexType, nodes, inner, innerSeen);
std::unordered_set<std::string> toRemove;
for (const auto& [k, v] : result)
{
(void)v;
if (!inner.count(k))
toRemove.insert(k);
}
for (const std::string& k : toRemove)
result.erase(k);
++iter;
}
}
else if (auto pt = get<PrimitiveType>(ty))
{
if (pt->metatable)
{
if (auto mtable = get<TableType>(*pt->metatable))
fillMetatableProps(mtable);
}
}
else if (get<StringSingleton>(get<SingletonType>(ty)))
{
autocompleteProps(module, typeArena, builtinTypes, rootTy, builtinTypes->stringType, indexType, nodes, result, seen);
}
}
static void autocompleteKeywords(const std::vector<AstNode*>& ancestry, Position position, AutocompleteEntryMap& result)
{
LUAU_ASSERT(!ancestry.empty());
AstNode* node = ancestry.back();
if (!node->is<AstExprFunction>() && node->asExpr())
{
// This is not strictly correct. We should recommend `and` and `or` only after
// another expression, not at the start of a new one. We should only recommend
// `not` at the start of an expression. Detecting either case reliably is quite
// complex, however; this is good enough for now.
// These are not context-sensitive keywords, so we can unconditionally assign.
result["and"] = {AutocompleteEntryKind::Keyword};
result["or"] = {AutocompleteEntryKind::Keyword};
result["not"] = {AutocompleteEntryKind::Keyword};
}
}
static void autocompleteProps(
const Module& module,
TypeArena* typeArena,
NotNull<BuiltinTypes> builtinTypes,
TypeId ty,
PropIndexType indexType,
const std::vector<AstNode*>& nodes,
AutocompleteEntryMap& result
)
{
std::unordered_set<TypeId> seen;
autocompleteProps(module, typeArena, builtinTypes, ty, ty, indexType, nodes, result, seen);
}
AutocompleteEntryMap autocompleteProps(
const Module& module,
TypeArena* typeArena,
NotNull<BuiltinTypes> builtinTypes,
TypeId ty,
PropIndexType indexType,
const std::vector<AstNode*>& nodes
)
{
AutocompleteEntryMap result;
autocompleteProps(module, typeArena, builtinTypes, ty, indexType, nodes, result);
return result;
}
AutocompleteEntryMap autocompleteModuleTypes(const Module& module, const ScopePtr& scopeAtPosition, Position position, std::string_view moduleName)
{
AutocompleteEntryMap result;
ScopePtr startScope = FFlag::LuauAutocompleteRefactorsForIncrementalAutocomplete ? scopeAtPosition : findScopeAtPosition(module, position);
for (ScopePtr& scope = startScope; scope; scope = scope->parent)
{
if (auto it = scope->importedTypeBindings.find(std::string(moduleName)); it != scope->importedTypeBindings.end())
{
for (const auto& [name, ty] : it->second)
result[name] = AutocompleteEntry{AutocompleteEntryKind::Type, ty.type};
break;
}
}
return result;
}
static void autocompleteStringSingleton(TypeId ty, bool addQuotes, AstNode* node, Position position, AutocompleteEntryMap& result)
{
if (position == node->location.begin || position == node->location.end)
{
if (auto str = node->as<AstExprConstantString>(); str && str->isQuoted())
return;
else if (node->is<AstExprInterpString>())
return;
}
auto formatKey = [addQuotes](const std::string& key)
{
if (addQuotes)
return "\"" + escape(key) + "\"";
return escape(key);
};
ty = follow(ty);
if (auto ss = get<StringSingleton>(get<SingletonType>(ty)))
{
result[formatKey(ss->value)] = AutocompleteEntry{AutocompleteEntryKind::String, ty, false, false, TypeCorrectKind::Correct};
}
else if (auto uty = get<UnionType>(ty))
{
for (auto el : uty)
{
if (auto ss = get<StringSingleton>(get<SingletonType>(el)))
result[formatKey(ss->value)] = AutocompleteEntry{AutocompleteEntryKind::String, ty, false, false, TypeCorrectKind::Correct};
}
}
};
static bool canSuggestInferredType(ScopePtr scope, TypeId ty)
{
ty = follow(ty);
// No point in suggesting 'any', invalid to suggest others
if (get<AnyType>(ty) || get<ErrorType>(ty) || get<GenericType>(ty) || get<FreeType>(ty))
return false;
// No syntax for unnamed tables with a metatable
if (get<MetatableType>(ty))
return false;
if (const TableType* ttv = get<TableType>(ty))
{
if (ttv->name)
return true;
if (ttv->syntheticName)
return false;
}
// We might still have a type with cycles or one that is too long, we'll check that later
return true;
}
// Walk complex type trees to find the element that is being edited
static std::optional<TypeId> findTypeElementAt(AstType* astType, TypeId ty, Position position);
static std::optional<TypeId> findTypeElementAt(const AstTypeList& astTypeList, TypePackId tp, Position position)
{
for (size_t i = 0; i < astTypeList.types.size; i++)
{
AstType* type = astTypeList.types.data[i];
if (type->location.containsClosed(position))
{
auto [head, _] = flatten(tp);
if (i < head.size())
return findTypeElementAt(type, head[i], position);
}
}
if (AstTypePack* argTp = astTypeList.tailType)
{
if (auto variadic = argTp->as<AstTypePackVariadic>())
{
if (variadic->location.containsClosed(position))
{
auto [_, tail] = flatten(tp);
if (tail)
{
if (const VariadicTypePack* vtp = get<VariadicTypePack>(follow(*tail)))
return findTypeElementAt(variadic->variadicType, vtp->ty, position);
}
}
}
}
return {};
}
static std::optional<TypeId> findTypeElementAt(AstType* astType, TypeId ty, Position position)
{
ty = follow(ty);
if (astType->is<AstTypeReference>())
return ty;
if (astType->is<AstTypeError>())
return ty;
if (AstTypeFunction* type = astType->as<AstTypeFunction>())
{
const FunctionType* ftv = get<FunctionType>(ty);
if (!ftv)
return {};
if (auto element = findTypeElementAt(type->argTypes, ftv->argTypes, position))
return element;
if (auto element = findTypeElementAt(type->returnTypes, ftv->retTypes, position))
return element;
}
// It's possible to walk through other types like intrsection and unions if we find value in doing that
return {};
}
std::optional<TypeId> getLocalTypeInScopeAt(const Module& module, const ScopePtr& scopeAtPosition, Position position, AstLocal* local)
{
if (ScopePtr scope = FFlag::LuauAutocompleteRefactorsForIncrementalAutocomplete ? scopeAtPosition : findScopeAtPosition(module, position))
{
for (const auto& [name, binding] : scope->bindings)
{
if (name == local)
return binding.typeId;
}
}
return {};
}
template<typename T>
static std::optional<std::string> tryToStringDetailed(const ScopePtr& scope, T ty, bool functionTypeArguments)
{
ToStringOptions opts;
opts.useLineBreaks = false;
opts.hideTableKind = true;
opts.functionTypeArguments = functionTypeArguments;
opts.scope = scope;
ToStringResult name = toStringDetailed(ty, opts);
if (name.error || name.invalid || name.cycle || name.truncated)
return std::nullopt;
return name.name;
}
static std::optional<Name> tryGetTypeNameInScope(ScopePtr scope, TypeId ty, bool functionTypeArguments = false)
{
if (!canSuggestInferredType(scope, ty))
return std::nullopt;
return tryToStringDetailed(scope, ty, functionTypeArguments);
}
static bool tryAddTypeCorrectSuggestion(AutocompleteEntryMap& result, ScopePtr scope, AstType* topType, TypeId inferredType, Position position)
{
std::optional<TypeId> ty;
if (topType)
ty = findTypeElementAt(topType, inferredType, position);
else
ty = inferredType;
if (!ty)
return false;
if (auto name = tryGetTypeNameInScope(scope, *ty))
{
if (auto it = result.find(*name); it != result.end())
it->second.typeCorrect = TypeCorrectKind::Correct;
else
result[*name] = AutocompleteEntry{AutocompleteEntryKind::Type, *ty, false, false, TypeCorrectKind::Correct};
return true;
}
return false;
}
static std::optional<TypeId> tryGetTypePackTypeAt(TypePackId tp, size_t index)
{
auto [tpHead, tpTail] = flatten(tp);
if (index < tpHead.size())
return tpHead[index];
// Infinite tail
if (tpTail)
{
if (const VariadicTypePack* vtp = get<VariadicTypePack>(follow(*tpTail)))
return vtp->ty;
}
return {};
}
template<typename T>
std::optional<const T*> returnFirstNonnullOptionOfType(const UnionType* utv)
{
std::optional<const T*> ret;
for (TypeId subTy : utv)
{
if (isNil(subTy))
continue;
if (const T* ftv = get<T>(follow(subTy)))
{
if (ret.has_value())
{
return std::nullopt;
}
ret = ftv;
}
else
{
return std::nullopt;
}
}
return ret;
}
static std::optional<bool> functionIsExpectedAt(const Module& module, AstNode* node, Position position)
{
auto typeAtPosition = findExpectedTypeAt(module, node, position);
if (!typeAtPosition)
return std::nullopt;
TypeId expectedType = follow(*typeAtPosition);
if (get<FunctionType>(expectedType))
return true;
if (const IntersectionType* itv = get<IntersectionType>(expectedType))
{
return std::all_of(
begin(itv->parts),
end(itv->parts),
[](auto&& ty)
{
return get<FunctionType>(Luau::follow(ty)) != nullptr;
}
);
}
if (const UnionType* utv = get<UnionType>(expectedType))
return returnFirstNonnullOptionOfType<FunctionType>(utv).has_value();
return false;
}
AutocompleteEntryMap autocompleteTypeNames(
const Module& module,
const ScopePtr& scopeAtPosition,
Position& position,
const std::vector<AstNode*>& ancestry
)
{
AutocompleteEntryMap result;
ScopePtr startScope = FFlag::LuauAutocompleteRefactorsForIncrementalAutocomplete ? scopeAtPosition : findScopeAtPosition(module, position);
for (ScopePtr scope = startScope; scope; scope = scope->parent)
{
for (const auto& [name, ty] : scope->exportedTypeBindings)
{
if (!result.count(name))
result[name] = AutocompleteEntry{
AutocompleteEntryKind::Type,
ty.type,
false,
false,
TypeCorrectKind::None,
std::nullopt,
std::nullopt,
ty.type->documentationSymbol
};
}
for (const auto& [name, ty] : scope->privateTypeBindings)
{
if (!result.count(name))
result[name] = AutocompleteEntry{
AutocompleteEntryKind::Type,
ty.type,
false,
false,
TypeCorrectKind::None,
std::nullopt,
std::nullopt,
ty.type->documentationSymbol
};
}
for (const auto& [name, _] : scope->importedTypeBindings)
{
if (auto binding = scope->linearSearchForBinding(name, true))
{
if (!result.count(name))
result[name] = AutocompleteEntry{AutocompleteEntryKind::Module, binding->typeId};
}
}
}
AstNode* parent = nullptr;
AstType* topType = nullptr; // TODO: rename?
for (auto it = ancestry.rbegin(), e = ancestry.rend(); it != e; ++it)
{
if (AstType* asType = (*it)->asType())
{
topType = asType;
}
else
{
parent = *it;
break;
}
}
if (!parent)
return result;
if (AstStatLocal* node = parent->as<AstStatLocal>()) // Try to provide inferred type of the local
{
// Look at which of the variable types we are defining
for (size_t i = 0; i < node->vars.size; i++)
{
AstLocal* var = node->vars.data[i];
if (var->annotation && var->annotation->location.containsClosed(position))
{
if (node->values.size == 0)
break;
unsigned tailPos = 0;
// For multiple return values we will try to unpack last function call return type pack
if (i >= node->values.size)
{
tailPos = int(i) - int(node->values.size) + 1;
i = int(node->values.size) - 1;
}
AstExpr* expr = node->values.data[i]->asExpr();
if (!expr)
break;
TypeId inferredType = nullptr;
if (AstExprCall* exprCall = expr->as<AstExprCall>())
{
if (auto it = module.astTypes.find(exprCall->func))
{
if (const FunctionType* ftv = get<FunctionType>(follow(*it)))
{
if (auto ty = tryGetTypePackTypeAt(ftv->retTypes, tailPos))
inferredType = *ty;
}
}
}
else
{
if (tailPos != 0)
break;
if (auto it = module.astTypes.find(expr))
inferredType = *it;
}
if (inferredType)
tryAddTypeCorrectSuggestion(result, startScope, topType, inferredType, position);
break;
}
}
}
else if (AstExprFunction* node = parent->as<AstExprFunction>())
{
// For lookup inside expected function type if that's available
auto tryGetExpectedFunctionType = [](const Module& module, AstExpr* expr) -> const FunctionType*
{
auto it = module.astExpectedTypes.find(expr);
if (!it)
return nullptr;
TypeId ty = follow(*it);
if (const FunctionType* ftv = get<FunctionType>(ty))
return ftv;
// Handle optional function type
if (const UnionType* utv = get<UnionType>(ty))
{
return returnFirstNonnullOptionOfType<FunctionType>(utv).value_or(nullptr);
}
return nullptr;
};
// Find which argument type we are defining
for (size_t i = 0; i < node->args.size; i++)
{