-
Notifications
You must be signed in to change notification settings - Fork 515
/
calls.cc
4609 lines (4076 loc) · 210 KB
/
calls.cc
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
#include "absl/strings/match.h"
#include "absl/strings/str_split.h"
#include "common/common.h"
#include "common/sort/sort.h"
#include "common/typecase.h"
#include "core/GlobalState.h"
#include "core/Names.h"
#include "core/Symbols.h"
#include "core/TypeConstraint.h"
#include "core/TypeErrorDiagnostics.h"
#include "core/Types.h"
#include "core/errors/infer.h"
#include "core/errors/resolver.h"
#include <algorithm> // find_if, sort
#include "absl/strings/str_cat.h"
template class std::vector<sorbet::core::SymbolRef>;
using namespace std;
namespace sorbet::core {
namespace {
const bool IMPLICIT_CONVERSION_ALLOWS_PRIVATE = true;
DispatchResult dispatchCallProxyType(const GlobalState &gs, TypePtr und, const DispatchArgs &args) {
categoryCounterInc("dispatch_call", "proxytype");
return und.dispatchCall(gs, args.withThisRef(und));
}
bool allComponentsPresent(DispatchResult &res) {
if (!res.main.method.exists()) {
return false;
}
if (!res.secondary || res.secondaryKind == DispatchResult::Combinator::AND) {
return true;
}
return allComponentsPresent(*res.secondary);
}
} // namespace
bool NamedLiteralType::derivesFrom(const GlobalState &gs, core::ClassOrModuleRef klass) const {
return underlying(gs).derivesFrom(gs, klass);
}
bool IntegerLiteralType::derivesFrom(const GlobalState &gs, core::ClassOrModuleRef klass) const {
return underlying(gs).derivesFrom(gs, klass);
}
bool FloatLiteralType::derivesFrom(const GlobalState &gs, core::ClassOrModuleRef klass) const {
return underlying(gs).derivesFrom(gs, klass);
}
bool ShapeType::derivesFrom(const GlobalState &gs, core::ClassOrModuleRef klass) const {
return underlying(gs).derivesFrom(gs, klass);
}
bool TupleType::derivesFrom(const GlobalState &gs, core::ClassOrModuleRef klass) const {
return underlying(gs).derivesFrom(gs, klass);
}
DispatchResult NamedLiteralType::dispatchCall(const GlobalState &gs, const DispatchArgs &args) const {
return dispatchCallProxyType(gs, underlying(gs), args);
}
DispatchResult IntegerLiteralType::dispatchCall(const GlobalState &gs, const DispatchArgs &args) const {
return dispatchCallProxyType(gs, underlying(gs), args);
}
DispatchResult FloatLiteralType::dispatchCall(const GlobalState &gs, const DispatchArgs &args) const {
return dispatchCallProxyType(gs, underlying(gs), args);
}
DispatchResult OrType::dispatchCall(const GlobalState &gs, const DispatchArgs &args) const {
categoryCounterInc("dispatch_call", "ortype");
auto leftRet = left.dispatchCall(gs, args.withSelfAndThisRef(left));
auto rightRet = right.dispatchCall(gs, args.withSelfAndThisRef(right));
return DispatchResult::merge(gs, DispatchResult::Combinator::OR, std::move(leftRet), std::move(rightRet));
}
TypePtr OrType::getCallArguments(const GlobalState &gs, NameRef name) const {
auto largs = left.getCallArguments(gs, name);
auto rargs = right.getCallArguments(gs, name);
if (!largs) {
largs = Types::untypedUntracked();
}
if (!rargs) {
rargs = Types::untypedUntracked();
}
return Types::glb(gs, largs, rargs);
}
DispatchResult AndType::dispatchCall(const GlobalState &gs, const DispatchArgs &args) const {
categoryCounterInc("dispatch_call", "andtype");
// Tell dispatchCall to not produce any dispatch-related errors. They are very expensive to produce.
auto leftRet = left.dispatchCall(gs, args.withThisRef(left).withErrorsSuppressed());
auto rightRet = right.dispatchCall(gs, args.withThisRef(right).withErrorsSuppressed());
// If either side is missing the method, dispatch to the other.
auto leftOk = allComponentsPresent(leftRet);
auto rightOk = allComponentsPresent(rightRet);
if (leftOk && !rightOk) {
return leftRet;
}
if (rightOk && !leftOk) {
return rightRet;
}
if (!rightOk && !leftOk) {
// Expensive case. Re-dispatch the calls with errors enabled so we can give the user an error.
leftRet = left.dispatchCall(gs, args.withThisRef(left));
rightRet = right.dispatchCall(gs, args.withThisRef(right));
}
auto resultType = Types::all(gs, leftRet.returnType, rightRet.returnType);
return DispatchResult::merge(gs, DispatchResult::Combinator::AND, std::move(leftRet), std::move(rightRet));
}
TypePtr AndType::getCallArguments(const GlobalState &gs, NameRef name) const {
auto l = left.getCallArguments(gs, name);
auto r = right.getCallArguments(gs, name);
if (l == nullptr) {
return r;
}
if (r == nullptr) {
return l;
}
return Types::any(gs, l, r);
}
DispatchResult ShapeType::dispatchCall(const GlobalState &gs, const DispatchArgs &args) const {
categoryCounterInc("dispatch_call", "shapetype");
auto method = Symbols::Shape().data(gs)->findMethod(gs, args.name);
if (method.exists()) {
auto *intrinsic = method.data(gs)->getIntrinsic();
if (intrinsic != nullptr) {
DispatchComponent comp{args.selfType, method, {}, nullptr, nullptr, nullptr, {}, {}, nullptr};
DispatchResult res{nullptr, std::move(comp)};
intrinsic->apply(gs, args, res);
if (res.returnType != nullptr) {
return res;
}
}
}
return dispatchCallProxyType(gs, underlying(gs), args);
}
DispatchResult TupleType::dispatchCall(const GlobalState &gs, const DispatchArgs &args) const {
categoryCounterInc("dispatch_call", "tupletype");
auto method = Symbols::Tuple().data(gs)->findMethod(gs, args.name);
if (method.exists()) {
auto *intrinsic = method.data(gs)->getIntrinsic();
if (intrinsic != nullptr) {
DispatchComponent comp{args.selfType, method, {}, nullptr, nullptr, nullptr, {}, {}, nullptr};
DispatchResult res{nullptr, std::move(comp)};
intrinsic->apply(gs, args, res);
if (res.returnType != nullptr) {
return res;
}
}
}
return dispatchCallProxyType(gs, underlying(gs), args);
}
namespace {
void autocorrectReceiver(const core::GlobalState &gs, core::ErrorBuilder &e, core::Loc receiverLoc,
core::NameRef methodName) {
if (receiverLoc.exists() && (gs.suggestUnsafe.has_value())) {
auto wrapInFn = gs.suggestUnsafe.value();
if (receiverLoc.empty()) {
auto shortName = methodName.shortName(gs);
auto beginAdjust = -2; // (&
auto endAdjust = 1 + shortName.size() + 1; // :foo)
auto blockPassLoc = receiverLoc.adjust(gs, beginAdjust, endAdjust);
if (blockPassLoc.exists()) {
auto blockPassSource = blockPassLoc.source(gs).value();
if (blockPassSource == fmt::format("(&:{})", shortName)) {
e.replaceWith(fmt::format("Expand to block with `{}`", wrapInFn), blockPassLoc,
" {{ |x| {}(x).{} }}", wrapInFn, shortName);
}
}
} else {
e.replaceWith(fmt::format("Wrap in `{}`", wrapInFn), receiverLoc, "{}({})", wrapInFn,
receiverLoc.source(gs).value());
}
}
}
void addUnconstrainedIsaGenericNote(const GlobalState &gs, ErrorBuilder &e, SymbolRef definition, NameRef methodName,
string_view genericKind) {
if (methodName == Names::isA_p()) {
e.addErrorNote("Use `{}` instead of `{}` to check the type of an unconstrained generic type {}", "case",
methodName.show(gs), genericKind);
} else if (methodName == Names::nil_p()) {
e.addErrorNote("Use `{}` instead of `{}` to check whether an unconstrained generic type {} is nil",
"case ... when nil", methodName.show(gs), genericKind);
} else if (definition.isTypeMember()) {
e.addErrorSection(ErrorSection(
ErrorColors::format("Consider adding an `{}` bound to `{}` here", "upper", definition.show(gs)),
{{definition.loc(gs), ""}}));
} else {
auto showOptions = ShowOptions().withUseValidSyntax();
auto wrapped = fmt::format("T.all({}, Constraint)", definition.show(gs, showOptions));
e.addErrorNote("Consider using `{}` to place a constraint on this type", wrapped);
}
}
} // namespace
DispatchResult SelfTypeParam::dispatchCall(const GlobalState &gs, const DispatchArgs &args) const {
auto emptyResult = DispatchResult(Types::untypedUntracked(), std::move(args.selfType), Symbols::noMethod());
if (this->definition.isTypeArgument()) {
if (args.suppressErrors) {
// Short circuit here to avoid constructing an expensive error message.
return emptyResult;
}
auto e = gs.beginError(args.errLoc(), errors::Infer::CallOnTypeArgument);
if (e) {
auto thisStr = args.thisType.show(gs);
if (args.fullType.type != args.thisType) {
e.setHeader("Call to method `{}` on generic type `{}` component of `{}`", args.name.show(gs), thisStr,
args.fullType.type.show(gs));
} else {
e.setHeader("Call to method `{}` on unconstrained generic type `{}`", args.name.show(gs), thisStr);
}
e.addErrorSection(args.fullType.explainGot(gs, args.originForUninitialized));
autocorrectReceiver(gs, e, args.receiverLoc(), args.name);
addUnconstrainedIsaGenericNote(gs, e, this->definition, args.name, "parameter");
}
emptyResult.main.errors.emplace_back(e.build());
return emptyResult;
} else {
ENFORCE(this->definition.isTypeMember());
auto typeMember = this->definition.asTypeMemberRef();
auto &lambdaParam = cast_type_nonnull<LambdaParam>(typeMember.data(gs)->resultType);
auto upperBound = lambdaParam.upperBound;
if (upperBound.isTop()) {
if (args.suppressErrors) {
return emptyResult;
}
auto e = gs.beginError(args.errLoc(), errors::Infer::CallOnUnboundedTypeMember);
if (e) {
auto member = typeMember.data(gs)->owner.asClassOrModuleRef().data(gs)->attachedClass(gs).exists()
? "template"
: "member";
auto thisStr = args.thisType.show(gs);
if (args.fullType.type != args.thisType) {
e.setHeader("Call to method `{}` on unbounded type {} `{}` component of `{}`", args.name.show(gs),
member, thisStr, args.fullType.type.show(gs));
} else {
e.setHeader("Call to method `{}` on unbounded type {} `{}`", args.name.show(gs), member, thisStr);
}
e.addErrorSection(args.fullType.explainGot(gs, args.originForUninitialized));
autocorrectReceiver(gs, e, args.receiverLoc(), args.name);
addUnconstrainedIsaGenericNote(gs, e, this->definition, args.name, member);
}
emptyResult.main.errors.emplace_back(e.build());
return emptyResult;
}
return upperBound.dispatchCall(gs, args.withThisRef(upperBound));
}
}
namespace {
unique_ptr<Error> matchArgType(const GlobalState &gs, TypeConstraint &constr, Loc receiverLoc, ClassOrModuleRef inClass,
MethodRef method, const TypeAndOrigins &argTpe, const ArgInfo &argSym,
const TypePtr &selfType, const vector<TypePtr> &targs, Loc argLoc,
Loc originForUninitialized, bool mayBeSetter = false) {
TypePtr expectedType = Types::resultTypeAsSeenFrom(gs, argSym.type, method.data(gs)->owner, inClass, targs);
if (!expectedType) {
expectedType = Types::untyped(method);
}
expectedType = Types::replaceSelfType(gs, expectedType, selfType);
core::ErrorSection::Collector errorDetailsCollector;
if (Types::isSubTypeUnderConstraint(gs, constr, argTpe.type, expectedType, UntypedMode::AlwaysCompatible,
errorDetailsCollector)) {
if (expectedType.isUntyped()) {
// TODO(jez) We should have code like this, but currently there are too many places that
// are fine "accepting anything" that are typed as `T.untyped`.
//
// We should take a pass at fixing a lot of those in our RBI files, and then circle back
// to enabling this error.
//
// auto what = core::errors::Infer::errorClassForUntyped(gs, argLoc.file());
// if (auto e = gs.beginError(argLoc, what)) {
// e.setHeader("Method parameter `{}` is declared with `{}`", argSym.argumentName(gs), "T.untyped");
// TypeErrorDiagnostics::explainUntyped(gs, e, what, expectedType, argSym.loc, originForUninitialized);
// return e.build();
// }
} else if (argTpe.type.isUntyped() && expectedType != Types::top()) {
auto what = core::errors::Infer::errorClassForUntyped(gs, argLoc.file(), argTpe.type);
if (auto e = gs.beginError(argLoc, what)) {
e.setHeader("Argument passed to parameter `{}` is `{}`", argSym.argumentName(gs), "T.untyped");
auto for_ =
ErrorColors::format("argument `{}` of method `{}`", argSym.argumentName(gs), method.show(gs));
e.addErrorSection(TypeAndOrigins::explainExpected(gs, expectedType, argSym.loc, for_));
TypeErrorDiagnostics::explainUntyped(gs, e, what, argTpe, originForUninitialized);
return e.build();
}
}
return nullptr;
}
if (auto e = gs.beginError(argLoc, errors::Infer::MethodArgumentMismatch)) {
if (mayBeSetter && method.data(gs)->name.isSetter(gs)) {
e.setHeader("Assigning a value to `{}` that does not match expected type `{}`", argSym.argumentName(gs),
expectedType.show(gs));
} else {
e.setHeader("Expected `{}` but found `{}` for argument `{}`", expectedType.show(gs), argTpe.type.show(gs),
argSym.argumentName(gs));
auto for_ = ErrorColors::format("argument `{}` of method `{}`", argSym.argumentName(gs), method.show(gs));
e.addErrorSection(TypeAndOrigins::explainExpected(gs, expectedType, argSym.loc, for_));
}
e.addErrorSection(argTpe.explainGot(gs, originForUninitialized));
core::TypeErrorDiagnostics::explainTypeMismatch(gs, e, errorDetailsCollector, expectedType, argTpe.type);
TypeErrorDiagnostics::maybeAutocorrect(gs, e, argLoc, constr, expectedType, argTpe.type);
return e.build();
}
return nullptr;
}
unique_ptr<Error> missingArg(const GlobalState &gs, Loc argsLoc, Loc receiverLoc, MethodRef method, const ArgInfo &arg,
ClassOrModuleRef inClass, const vector<TypePtr> &targs) {
if (auto e = gs.beginError(argsLoc, errors::Infer::MethodArgumentCountMismatch)) {
auto argName = arg.name.show(gs);
e.setHeader("Missing required keyword argument `{}` for method `{}`", argName, method.show(gs));
auto expectedType = Types::resultTypeAsSeenFrom(gs, arg.type, method.data(gs)->owner, inClass, targs);
if (expectedType == nullptr) {
expectedType = Types::untyped(method);
}
e.addErrorLine(arg.loc, "Keyword argument `{}` declared to expect type `{}` here:", argName,
expectedType.show(gs));
return e.build();
}
return nullptr;
}
size_t getArity(const GlobalState &gs, MethodRef method) {
ENFORCE(!method.data(gs)->arguments.empty(), "Every method should have at least a block arg.");
ENFORCE(method.data(gs)->arguments.back().flags.isBlock, "Last arg should be the block arg.");
const auto &arguments = method.data(gs)->arguments;
if (absl::c_any_of(arguments, [&](const auto &arg) { return arg.flags.isRepeated && !arg.flags.isKeyword; })) {
return SIZE_MAX;
};
// Don't count the block arg in the arity
return method.data(gs)->arguments.size() - 1;
}
struct GuessOverloadCandidate {
MethodRef candidate;
shared_ptr<TypeConstraint> constr;
};
MethodRef guessOverload(const GlobalState &gs, ClassOrModuleRef inClass, MethodRef primary, uint16_t numPosArgs,
InlinedVector<const TypeAndOrigins *, 2> &args, const vector<TypePtr> &targs, bool hasBlock) {
counterInc("calls.overloaded_invocations");
MethodRef fallback = primary;
vector<MethodRef> allCandidates;
allCandidates.emplace_back(primary);
{ // create candidates and sort them by number of arguments(stable by symbol id)
size_t i = 0;
MethodRef current = primary;
while (current.data(gs)->flags.isOverloaded) {
i++;
NameRef overloadName = gs.lookupNameUnique(UniqueNameKind::Overload, primary.data(gs)->name, i);
MethodRef overload = primary.data(gs)->owner.data(gs)->findMethod(gs, overloadName);
if (!overload.exists()) {
Exception::raise("Corruption of overloads?");
} else {
allCandidates.emplace_back(overload);
current = overload;
}
}
fast_sort(allCandidates, [&](const auto &s1, const auto &s2) -> bool {
auto s1Arity = getArity(gs, s1);
auto s2Arity = getArity(gs, s2);
if (s1Arity < s2Arity) {
return true;
}
if (s1Arity == s2Arity) {
return s1.id() < s2.id();
}
return false;
});
}
vector<GuessOverloadCandidate> allCandidatesWithConstraints;
for (const auto &candidate : allCandidates) {
if (!candidate.data(gs)->flags.isGenericMethod) {
allCandidatesWithConstraints.emplace_back(GuessOverloadCandidate{candidate, nullptr});
continue;
}
// Make a new TypeConstraint with everything in the domain solving to `T.untyped`.
//
// This allows Sorbet to consider or reject an overload with a parameter like
// `T::Array[T.type_parameter(:U)]` based on whether the argument is `String`--in that case,
// it doesn't matter what the `T.type_parameter(:U)` is, because `String` is not an `Array`.
auto constr = make_unique<TypeConstraint>();
for (auto typeArgument : candidate.data(gs)->typeArguments()) {
constr->rememberIsSubtype(gs, typeArgument.data(gs)->resultType, Types::untypedUntracked());
}
if (!constr->solve(gs)) {
Exception::raise("Constraint should always solve after creating TypeConstraint with only untyped bounds");
}
allCandidatesWithConstraints.emplace_back(GuessOverloadCandidate{candidate, move(constr)});
}
// Copy the vector
auto leftCandidates = allCandidatesWithConstraints;
{
auto checkArg = [&](auto i, const TypePtr &arg) {
for (auto it = leftCandidates.begin(); it != leftCandidates.end(); /* nothing*/) {
const auto &[candidate, constr] = *it;
const auto &arguments = candidate.data(gs)->arguments;
TypePtr argTypeRaw;
auto arity = getArity(gs, candidate);
if (i < arguments.size() - 1) {
argTypeRaw = arguments[i].type;
} else if (arity == SIZE_MAX) {
auto restArg = absl::c_find_if(
arguments, [&](const auto &arg) { return arg.flags.isRepeated && !arg.flags.isKeyword; });
ENFORCE(restArg != arguments.end())
argTypeRaw = restArg->type;
} else {
it = leftCandidates.erase(it);
continue;
}
auto argType = Types::resultTypeAsSeenFrom(gs, argTypeRaw, candidate.data(gs)->owner, inClass, targs);
if (constr == nullptr) {
if (!Types::isSubType(gs, arg, argType)) {
it = leftCandidates.erase(it);
continue;
}
} else {
if (!Types::isSubTypeUnderConstraint(gs, *constr, arg, argType, UntypedMode::AlwaysCompatible,
ErrorSection::Collector::NO_OP)) {
it = leftCandidates.erase(it);
continue;
}
}
++it;
}
};
// Lets see if we can filter them out using arguments.
for (auto i = 0; i < numPosArgs; ++i) {
checkArg(i, args[i]->type);
}
// If keyword args are present, interpret them as an untyped hash
if (numPosArgs < args.size()) {
checkArg(numPosArgs, Types::hashOfUntyped());
}
}
if (leftCandidates.empty()) {
leftCandidates = allCandidatesWithConstraints;
} else {
fallback = leftCandidates[0].candidate;
}
{ // keep only candidates that have a block iff we are passing one
for (auto it = leftCandidates.begin(); it != leftCandidates.end(); /* nothing*/) {
const auto &[candidate, constr] = *it;
const auto &args = candidate.data(gs)->arguments;
ENFORCE(!args.empty(), "Should at least have a block argument.");
const auto &lastArg = args.back();
auto mentionsBlockArg = !lastArg.isSyntheticBlockArgument();
if (hasBlock) {
if (!mentionsBlockArg || lastArg.type == Types::nilClass()) {
it = leftCandidates.erase(it);
continue;
}
} else {
if (mentionsBlockArg && lastArg.type != nullptr &&
(!lastArg.type.isFullyDefined() || !Types::isSubType(gs, Types::nilClass(), lastArg.type))) {
it = leftCandidates.erase(it);
continue;
}
}
++it;
}
}
{ // keep only candidates with closest arity
struct Comp {
const GlobalState &gs;
bool operator()(GuessOverloadCandidate &s, int i) const {
return getArity(gs, s.candidate) < i;
}
bool operator()(int i, GuessOverloadCandidate &s) const {
return i < getArity(gs, s.candidate);
}
Comp(const GlobalState &gs) : gs(gs){};
} cmp(gs);
auto er = absl::c_equal_range(leftCandidates, args.size(), cmp);
if (er.first != leftCandidates.end()) {
leftCandidates.erase(leftCandidates.begin(), er.first);
}
}
if (!leftCandidates.empty()) {
return leftCandidates[0].candidate;
}
return fallback;
}
struct ArityComponents {
int required;
int optional;
bool repeated;
};
ArityComponents arityComponents(const GlobalState &gs, MethodRef method) {
int required = 0, optional = 0;
bool repeated = false;
for (const auto &arg : method.data(gs)->arguments) {
if (arg.flags.isKeyword || arg.flags.isBlock) {
// ignore
} else if (arg.flags.isDefault) {
++optional;
} else if (arg.flags.isRepeated) {
repeated = true;
} else {
++required;
}
}
return {required, optional, repeated};
}
string prettyArity(const GlobalState &gs, MethodRef method) {
auto [required, optional, repeated] = arityComponents(gs, method);
if (repeated) {
return absl::StrCat(required, "+");
} else if (optional > 0) {
return absl::StrCat(required, "..", required + optional);
} else {
return to_string(required);
}
}
void maybeSuggestUnsafeKwsplat(const core::GlobalState &gs, core::ErrorBuilder &e, core::Loc kwSplatArgLoc) {
if (!kwSplatArgLoc.exists() || kwSplatArgLoc.empty()) {
return;
}
auto replaceLoc = kwSplatArgLoc;
string maybeStarStar = "**";
if (kwSplatArgLoc.adjustLen(gs, 0, 2).source(gs) == "**") {
replaceLoc = kwSplatArgLoc.adjust(gs, 2, 0);
maybeStarStar = "";
}
auto suggestUnsafe = gs.suggestUnsafe.value_or("T.unsafe"s);
auto title = fmt::format("Wrap in `{}`", suggestUnsafe);
auto replaceValue = replaceLoc.source(gs).value();
if (absl::c_all_of(replaceValue, [](char c) { return absl::ascii_isalnum(c) || c == '_'; }) ||
(absl::StartsWith(replaceValue, "{") && absl::EndsWith(replaceValue, "}"))) {
e.replaceWith(title, replaceLoc, "{}{}({})", maybeStarStar, suggestUnsafe, replaceValue);
} else {
// wraps inside of T.unsafe(...) in `{...}`
auto extraStarStar = replaceLoc != kwSplatArgLoc ? "**" : "";
e.replaceWith(title, replaceLoc, "{}{}({{{}{}}})", maybeStarStar, suggestUnsafe, extraStarStar, replaceValue);
}
}
// Ensure that a ShapeType used as a keyword args splat in a send has only symbol keys present.
const ShapeType *fromKwargsHash(const GlobalState &gs, const TypePtr &ty) {
auto *hash = cast_type<ShapeType>(ty);
if (hash == nullptr) {
return nullptr;
}
if (!absl::c_all_of(hash->keys, [&gs](const auto &key) {
if (!isa_type<NamedLiteralType>(key)) {
return false;
}
auto klass = cast_type_nonnull<NamedLiteralType>(key).underlying(gs);
if (!isa_type<ClassType>(klass)) {
return false;
}
return cast_type_nonnull<ClassType>(klass).symbol == Symbols::Symbol();
})) {
return nullptr;
}
return hash;
}
// Heuristic to try to find leading commas. Not actually required for correctness
// (will still parse even if we delete something but don't find the comma) which is
// why we're fine with this just hard-coding two common cases (easiest to implement).
Loc expandToLeadingComma(const GlobalState &gs, Loc loc) {
if (loc.adjustLen(gs, -1, 1).source(gs) == ",") {
return loc.adjust(gs, -1, 0);
} else if (loc.adjustLen(gs, -2, 2).source(gs) == ", ") {
return loc.adjust(gs, -2, 0);
} else if (loc.adjustLen(gs, -1, 1).source(gs) == " ") {
return loc.adjust(gs, -1, 0);
} else {
return loc;
}
}
void handleBlockType(const GlobalState &gs, DispatchComponent &component, TypePtr blockType) {
if (!blockType) {
blockType = Types::untyped(component.method);
}
component.blockReturnType = Types::getProcReturnType(gs, Types::dropNil(gs, blockType));
blockType = component.constr->isSolved() ? Types::instantiate(gs, blockType, *component.constr)
: Types::approximate(gs, blockType, *component.constr);
component.blockPreType = blockType;
}
// This implements Ruby's argument matching logic (assigning values passed to a
// method call to formal parameters of the method).
//
// Known incompleteness or inconsistencies with Ruby:
// - Missing coercion to keyword arguments via `#to_hash`
// - We never allow a non-shaped Hash to satisfy keyword arguments;
// We should, at a minimum, probably allow one to satisfy an **kwargs : untyped
// (with a subtype check on the key type, once we have generics)
DispatchResult dispatchCallSymbol(const GlobalState &gs, const DispatchArgs &args, core::ClassOrModuleRef symbol,
const vector<TypePtr> &targs) {
auto errLoc = args.errLoc();
if (symbol == core::Symbols::untyped() && args.name != core::Names::methodNameMissing()) {
auto what = core::errors::Infer::errorClassForUntyped(gs, args.locs.file, args.thisType);
if (auto e = gs.beginError(errLoc, what)) {
e.setHeader("Call to method `{}` on `{}`", args.name.show(gs), "T.untyped");
TypeErrorDiagnostics::explainUntyped(gs, e, what, args.fullType, args.originForUninitialized);
}
return DispatchResult(Types::untyped(args.thisType.untypedBlame()), std::move(args.selfType),
Symbols::noMethod());
} else if (symbol == Symbols::void_()) {
if (!args.suppressErrors) {
if (auto e = gs.beginError(errLoc, errors::Infer::UnknownMethod)) {
e.setHeader("Cannot call method `{}` on void type", args.name.show(gs));
}
}
return DispatchResult(Types::untypedUntracked(), std::move(args.selfType), Symbols::noMethod());
} else if (symbol == Symbols::DeclBuilderForProcsSingleton() && args.name == Names::new_()) {
if (!args.suppressErrors) {
if (auto e = gs.beginError(errLoc, errors::Infer::MetaTypeDispatchCall)) {
e.setHeader("Call to method `{}` on `{}` mistakes a type for a value", Names::new_().show(gs),
symbol.show(gs));
}
}
return DispatchResult(Types::untypedUntracked(), std::move(args.selfType), Symbols::noMethod());
} else if (args.name == Names::methodNameMissing()) {
// We already reported a parse error earlier in the pipeline
return DispatchResult(Types::untypedUntracked(), std::move(args.selfType), Symbols::noMethod());
} else if (args.name == Names::untypedSuper()) {
// Currently, `super` is only checked for the following cases:
// - The receiver is a class
// - The super call is not inside a block
// No point in paying a full findMethodTransitive just to discover that.
return DispatchResult(Types::untyped(Symbols::Magic_UntypedSource_super()), std::move(args.selfType),
Symbols::noMethod());
}
auto targetName = args.name;
MethodRef mayBeOverloaded;
if (targetName == Names::super()) {
targetName = args.enclosingMethodForSuper;
mayBeOverloaded = symbol.data(gs)->findParentMethodTransitive(gs, targetName);
} else if (symbol != core::Symbols::top()) {
// TODO(jez) It would be nice to make `core::Symbols::top()` not have `Object` as its ancestor,
// in which case we could simply let the findMethodTransitive run and fail to find any methods
mayBeOverloaded = symbol.data(gs)->findMethodTransitive(gs, targetName);
}
if (!mayBeOverloaded.exists() && gs.requiresAncestorEnabled) {
// Before raising any error, we look if the method exists in all required ancestors by this symbol
auto ancestors = symbol.data(gs)->requiredAncestorsTransitive(gs);
for (auto ancst : ancestors) {
mayBeOverloaded = ancst.symbol.data(gs)->findMethodTransitive(gs, targetName);
if (mayBeOverloaded.exists()) {
break;
}
}
}
if (!mayBeOverloaded.exists()) {
auto result = DispatchResult(Types::untypedUntracked(), std::move(args.selfType), Symbols::noMethod());
if (args.suppressErrors) {
// Short circuit here to avoid constructing an expensive error message.
return result;
}
auto unknownMethodCode = args.name == Names::super()
// So we can attach super-specific autocorrects at some point in the future
? errors::Infer::UnknownSuperMethod
: errors::Infer::UnknownMethod;
// This is a hack. We want to always be able to build the error object
// so that it is not immediately sent to GlobalState::_error
// and recorded.
// Instead, the error always should get queued up in the
// errors list of the result so that the caller can deal with the error.
auto e = gs.beginError(errLoc, unknownMethodCode);
if (e) {
string thisStr = args.thisType.show(gs);
auto ancestorsOf = args.name == Names::super() ? "ancestors of " : "";
auto isSetter = targetName.isSetter(gs);
auto methodPrefix = isSetter ? "Setter method" : "Method";
if (args.fullType.type != args.thisType) {
e.setHeader("{} `{}` does not exist on {}`{}` component of `{}`", methodPrefix, targetName.show(gs),
ancestorsOf, thisStr, args.fullType.type.show(gs));
} else {
e.setHeader("{} `{}` does not exist on {}`{}`", methodPrefix, targetName.show(gs), ancestorsOf,
thisStr);
}
e.addErrorSection(args.fullType.explainGot(gs, args.originForUninitialized));
// catch the special case of `interface!`, `abstract!`, `final!`, or `sealed!` and
// suggest adding `extend T::Helpers`.
if (args.name == core::Names::declareInterface() || args.name == core::Names::declareAbstract() ||
args.name == core::Names::declareFinal() || args.name == core::Names::declareSealed() ||
args.name == core::Names::mixesInClassMethods() ||
(args.name == core::Names::requiresAncestor() && gs.requiresAncestorEnabled)) {
auto attachedClass = symbol.data(gs)->attachedClass(gs);
TypeErrorDiagnostics::maybeInsertDSLMethod(gs, e, args.locs.file, args.callLoc(), attachedClass,
Symbols::T_Helpers(), "");
} else if (args.name == core::Names::sig()) {
auto attachedClass = symbol.data(gs)->attachedClass(gs);
TypeErrorDiagnostics::maybeInsertDSLMethod(gs, e, args.locs.file, args.callLoc(), attachedClass,
Symbols::T_Sig(), "");
} else if (args.name == Names::super()) {
// TODO(jez) Special error for super.
// - If identical name exists as self/instance method in parent but we're currently
// an instance/self method, suggest changing enclosing method definition.
// - If similar name exists in parent suggest renaming enclosing method definition
// (intialize -> initialize, etc.)
// - Otherwise, suggest `T.bind`
// Note: super is not a method call, and so all the logic in the case below to
// compute autocorrects to potentially fix up the method call's receiver can't apply.
e.addErrorNote("For help fixing `{}` errors: {}", "super", "https://sorbet.org/docs/typed-super");
} else if (args.receiverLoc().exists() &&
(gs.suggestUnsafe.has_value() ||
(args.fullType.type != args.thisType && symbol == Symbols::NilClass()))) {
auto wrapInFn = gs.suggestUnsafe.value_or("T.must");
if (args.receiverLoc().empty()) {
auto shortName = args.name.shortName(gs);
auto beginAdjust = -2; // (&
auto endAdjust = 1 + shortName.size() + 1; // :foo)
auto blockPassLoc = args.receiverLoc().adjust(gs, beginAdjust, endAdjust);
if (blockPassLoc.exists()) {
auto blockPassSource = blockPassLoc.source(gs).value();
if (blockPassSource == fmt::format("(&:{})", shortName)) {
e.replaceWith(fmt::format("Expand to block with `{}`", wrapInFn), blockPassLoc,
" {{ |x| {}(x).{} }}", wrapInFn, shortName);
}
}
} else if (errLoc == args.funLoc() &&
args.funLoc().source(gs) == absl::StrCat(args.name.shortName(gs), "=")) {
e.replaceWith(fmt::format("Wrap in `{}`", wrapInFn), args.funLoc(), "= {}({}) {}", wrapInFn,
args.receiverLoc().source(gs).value(), args.name.shortName(gs));
} else {
e.replaceWith(fmt::format("Wrap in `{}`", wrapInFn), args.receiverLoc(), "{}({})", wrapInFn,
args.receiverLoc().source(gs).value());
}
} else {
auto canSkipFuzzyMatch = false;
if (symbol.data(gs)->isModule()) {
auto objMeth = core::Symbols::Object().data(gs)->findMethodTransitive(gs, args.name);
if (objMeth.exists() && objMeth.data(gs)->owner.data(gs)->isModule()) {
auto objData = objMeth.data(gs);
auto ownerName = objData->owner.data(gs)->name.show(gs);
e.addErrorNote("`{}` is actually defined as a method on `{}`. To call it, either\n"
" `{}` in this module to ensure the method is always there, or\n"
" call the method using `{}` instead.",
args.name.show(gs), ownerName, fmt::format("include {}", ownerName),
fmt::format("{}.{}", ownerName, args.name.show(gs)));
if (args.receiverLoc().exists() && args.receiverLoc().empty()) {
e.replaceWith("Prefix with `Kernel.`", args.receiverLoc(), "Kernel.");
}
}
} else if (!symbol.data(gs)->attachedClass(gs).exists() &&
symbol.data(gs)->lookupSingletonClass(gs).exists()) {
auto singleton = symbol.data(gs)->lookupSingletonClass(gs);
auto methodOnSingleton = singleton.data(gs)->findMethodTransitive(gs, args.name);
if (methodOnSingleton.exists()) {
// isPrivateOk implies that the singleton class of the receiver is also the
// singleton class of the enclosing method, because the receiver is not a
// module and is syntactically `self`.
auto eitherLine =
args.isPrivateOk
? ErrorLine::fromWithoutLoc(
"Either:\n"
" - use `{}` to call it,\n"
" - remove `{}` from its definition to make it an instance method, or\n"
" - define the current method as a singleton class method using `{}`",
".class", "self.", "def self.")
: ErrorLine::fromWithoutLoc(
"Either:\n"
" - use `{}` to call it, or\n"
" - remove `{}` from its definition to make it an instance method",
".class", "self.");
e.addErrorSection(
ErrorSection("There is a singleton class method with the same name:",
{
ErrorLine::from(methodOnSingleton.data(gs)->loc(), "Defined here"),
move(eitherLine),
}));
if (args.receiverLoc().exists() && args.receiverLoc().empty()) {
e.replaceWith("Insert `self.class.`", args.funLoc().copyWithZeroLength(), "self.class.");
} else if (args.receiverLoc().exists()) {
e.replaceWith("Insert `.class`", args.receiverLoc().copyEndWithZeroLength(), ".class");
}
canSkipFuzzyMatch = true;
}
}
if (!canSkipFuzzyMatch) {
auto alternatives = symbol.data(gs)->findMemberFuzzyMatch(gs, targetName);
for (auto alternative : alternatives) {
auto possibleSymbol = alternative.symbol;
if (!possibleSymbol.isClassOrModule() && !possibleSymbol.isMethod()) {
continue;
}
if (possibleSymbol.isMethod()) {
auto possibleMethod = possibleSymbol.asMethodRef().data(gs);
if ((possibleMethod->flags.isPrivate || possibleMethod->owner == Symbols::Kernel()) &&
!args.isPrivateOk) {
// Special-case Kernel methods, which should be treated as private, but aren't due to
// this bug: https://github.com/sorbet/sorbet/issues/4434
// (If we fix that bug, we can delete the `Kernel` reference above.)
continue;
}
}
if (isSetter && possibleSymbol.name(gs).lookupWithEq(gs) == args.name) {
e.addErrorLine(possibleSymbol.loc(gs),
"Method `{}` defined here without a corresponding setter",
possibleSymbol.name(gs).show(gs));
continue;
}
const auto toReplace = args.name.toString(gs);
if (args.funLoc().source(gs) != toReplace) {
auto suggestedName = possibleSymbol.isClassOrModule() ? possibleSymbol.show(gs) + ".new"
: possibleSymbol.show(gs);
e.addErrorLine(possibleSymbol.loc(gs), "Did you mean: `{}`", suggestedName);
continue;
}
if (possibleSymbol.isClassOrModule()) {
if (possibleSymbol.asClassOrModuleRef().data(gs)->typeArity(gs) > 0) {
// If this call was in type syntax, we might have already have built an
// autocorrect to turn this from `MyClass(...)` to `MyClass[...]`.
continue;
}
e.addErrorNote("Ruby uses `.new` to invoke a class's constructor");
e.replaceWith("Insert `.new`", args.funLoc().copyEndWithZeroLength(), ".new");
continue;
}
const auto replacement = possibleSymbol.name(gs).toString(gs);
if (replacement != toReplace) {
e.didYouMean(replacement, args.funLoc());
e.addErrorLine(possibleSymbol.loc(gs), "Defined here");
continue;
}
auto possibleSymbolOwner = possibleSymbol.asMethodRef().data(gs)->owner;
if (possibleSymbolOwner.data(gs)->lookupSingletonClass(gs) == symbol) {
auto defKeyword = "def ";
auto defKeywordLen = char_traits<char>::length(defKeyword);
auto prefixLen = defKeywordLen + toReplace.size();
auto declLocPrefix = possibleSymbol.loc(gs).adjustLen(gs, 0, prefixLen);
e.addErrorNote("Did you mean to define `{}` as a singleton class method?", toReplace);
if (declLocPrefix.source(gs) == fmt::format("{}{}", defKeyword, toReplace)) {
e.replaceWith("Define method with `self.`",
possibleSymbol.loc(gs).adjustLen(gs, defKeywordLen, 0), "self.");
} else {
e.addErrorLine(possibleSymbol.loc(gs), "`{}` defined here", toReplace);
}
}
}
}
}
}
result.main.errors.emplace_back(e.build());
return result;
}
auto method =
mayBeOverloaded.data(gs)->flags.isOverloaded
? guessOverload(gs, symbol, mayBeOverloaded, args.numPosArgs, args.args, targs, args.block != nullptr)
: mayBeOverloaded;
if (method.data(gs)->flags.isPrivate && !args.isPrivateOk) {
if (auto e = gs.beginError(errLoc, core::errors::Infer::PrivateMethod)) {
if (args.fullType.type != args.thisType) {
e.setHeader("Non-private call to private method `{}` on `{}` component of `{}`",
method.data(gs)->name.show(gs), args.thisType.show(gs), args.fullType.type.show(gs));
} else {
e.setHeader("Non-private call to private method `{}` on `{}`", method.data(gs)->name.show(gs),
args.thisType.show(gs));
}
e.addErrorLine(method.data(gs)->loc(), "Defined in `{}` here", method.data(gs)->owner.show(gs));
}
}
DispatchResult result;
auto &component = result.main;
component.receiver = args.selfType;
component.method = method;
auto data = method.data(gs);
unique_ptr<TypeConstraint> &maybeConstraint = result.main.constr;
TypeConstraint *constr;
if (args.block || data->flags.isGenericMethod) {
maybeConstraint = make_unique<TypeConstraint>();
constr = maybeConstraint.get();
} else {
constr = &TypeConstraint::EmptyFrozenConstraint;
}
if (data->flags.isGenericMethod) {
constr->defineDomain(gs, data->typeArguments());
}
auto posArgs = args.numPosArgs;
bool hasKwargs = absl::c_any_of(data->arguments, [](const auto &arg) { return arg.flags.isKeyword; });
auto nonPosArgs = (args.args.size() - args.numPosArgs);
bool hasKwsplat = nonPosArgs & 0x1;
auto numKwargs = hasKwsplat ? nonPosArgs - 1 : nonPosArgs;
// p -> params, i.e., what was mentioned in the definition
auto pit = data->arguments.begin();
auto pend = data->arguments.end();
ENFORCE(pit != pend, "Should at least have the block arg.");
ENFORCE((pend - 1)->flags.isBlock, "Last arg should be the block arg: {}", (pend - 1)->show(gs));
// We'll type check the block arg separately from the rest of the args.
--pend;
// a -> args, i.e., what was passed at the call site
auto ait = args.args.begin();
auto aend = args.args.end();
auto aPosEnd = args.args.begin() + args.numPosArgs;
while (pit != pend && ait != aPosEnd) {
const ArgInfo &spec = *pit;
auto &arg = *ait;
if (spec.flags.isKeyword) {
break;
}
if (ait + 1 == aend && hasKwargs && (spec.flags.isDefault || spec.flags.isRepeated) &&
Types::approximate(gs, arg->type, *constr).derivesFrom(gs, Symbols::Hash())) {
break;
}
auto offset = ait - args.args.begin();
if (auto e = matchArgType(gs, *constr, args.receiverLoc(), symbol, method, *arg, spec, args.selfType, targs,
args.argLoc(offset), args.originForUninitialized, args.args.size() == 1)) {
result.main.errors.emplace_back(std::move(e));
}
if (!spec.flags.isRepeated) {
++pit;
}
++ait;
}
// If positional arguments remain, the method accepts keyword arguments, and no keyword arguments were provided in
// the send, assume that the last argument is an implicit keyword args hash.
bool implicitKwsplat = false;
if (ait != aPosEnd && hasKwargs && args.args.size() == args.numPosArgs) {
auto splatLoc = args.argLoc(args.args.size() - 1);
// If --experimental-ruby3-keyword-args is set, we will treat "**-less" keyword hash argument as an error.
if (gs.ruby3KeywordArgs) {
if (auto e = gs.beginError(splatLoc, errors::Infer::KeywordArgHashWithoutSplat)) {
e.setHeader("Keyword argument hash without `{}` is deprecated", "**");
e.addErrorLine(splatLoc, "This produces a runtime warning in Ruby 2.7, "