forked from sorbet/sorbet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDesugar.cc
2246 lines (2076 loc) · 113 KB
/
Desugar.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 <algorithm>
#include "absl/strings/numbers.h"
#include "absl/strings/str_replace.h"
#include "ast/Helpers.h"
#include "ast/ast.h"
#include "ast/desugar/Desugar.h"
#include "ast/verifier/verifier.h"
#include "common/common.h"
#include "common/formatting.h"
#include "core/Names.h"
#include "core/errors/desugar.h"
#include "core/errors/internal.h"
namespace sorbet::ast::desugar {
using namespace std;
namespace {
struct DesugarContext final {
core::MutableContext ctx;
uint32_t &uniqueCounter;
core::NameRef enclosingBlockArg;
core::LocOffsets enclosingMethodLoc;
core::NameRef enclosingMethodName;
DesugarContext(core::MutableContext ctx, uint32_t &uniqueCounter, core::NameRef enclosingBlockArg,
core::LocOffsets enclosingMethodLoc, core::NameRef enclosingMethodName)
: ctx(ctx), uniqueCounter(uniqueCounter), enclosingBlockArg(enclosingBlockArg),
enclosingMethodLoc(enclosingMethodLoc), enclosingMethodName(enclosingMethodName){};
core::NameRef freshNameUnique(core::NameRef name) {
return ctx.state.freshNameUnique(core::UniqueNameKind::Desugar, name, ++uniqueCounter);
}
};
core::NameRef blockArg2Name(DesugarContext dctx, const BlockArg &blkArg) {
auto blkIdent = cast_tree<UnresolvedIdent>(blkArg.expr);
ENFORCE(blkIdent != nullptr, "BlockArg must wrap UnresolvedIdent in desugar.");
return blkIdent->name;
}
// Get the num from the name of the Node if it's a LVar.
// Return -1 otherwise.
int numparamNum(DesugarContext dctx, parser::Node *decl) {
if (auto *lvar = parser::cast_node<parser::LVar>(decl)) {
auto name_str = lvar->name.show(dctx.ctx);
return name_str[1] - 48;
}
return -1;
}
// Get the highest numparams used in `decls`
// Return 0 if the list of declarations is empty.
int numparamMax(DesugarContext dctx, parser::NodeVec *decls) {
int max = 0;
for (auto &decl : *decls) {
auto num = numparamNum(dctx, decl.get());
if (num > max) {
max = num;
}
}
return max;
}
// Create a local variable from the first declaration for the name "_num" from all the `decls` if any.
// Return a dummy variable if no declaration is found for `num`.
ExpressionPtr numparamTree(DesugarContext dctx, int num, parser::NodeVec *decls) {
for (auto &decl : *decls) {
if (auto *lvar = parser::cast_node<parser::LVar>(decl.get())) {
if (numparamNum(dctx, decl.get()) == num) {
return MK::Local(lvar->loc, lvar->name);
}
} else {
ENFORCE(false, "NumParams declaring node is not a LVar.");
}
}
core::NameRef name = dctx.ctx.state.enterNameUTF8("_" + std::to_string(num));
return MK::Local(core::LocOffsets::none(), name);
}
ExpressionPtr node2TreeImpl(DesugarContext dctx, unique_ptr<parser::Node> what);
pair<MethodDef::ARGS_store, InsSeq::STATS_store> desugarArgs(DesugarContext dctx, core::LocOffsets loc,
unique_ptr<parser::Node> &argnode) {
MethodDef::ARGS_store args;
InsSeq::STATS_store destructures;
if (auto *oargs = parser::cast_node<parser::Args>(argnode.get())) {
args.reserve(oargs->args.size());
for (auto &arg : oargs->args) {
if (auto *lhs = parser::cast_node<parser::Mlhs>(arg.get())) {
core::NameRef temporary = dctx.freshNameUnique(core::Names::destructureArg());
args.emplace_back(MK::Local(arg->loc, temporary));
unique_ptr<parser::Node> lvarNode = make_unique<parser::LVar>(arg->loc, temporary);
unique_ptr<parser::Node> destructure =
make_unique<parser::Masgn>(arg->loc, std::move(arg), std::move(lvarNode));
destructures.emplace_back(node2TreeImpl(dctx, std::move(destructure)));
} else if (auto *lhs = parser::cast_node<parser::Kwnilarg>(arg.get())) {
// TODO implement logic for `**nil` args
} else if (auto *fargs = parser::cast_node<parser::ForwardArg>(arg.get())) {
// we desugar (m, n, ...) into (m, n, *<fwd-args>, **<fwd-kwargs>, &<fwd-block>)
// add `*<fwd-args>`
unique_ptr<parser::Node> rest =
make_unique<parser::Restarg>(fargs->loc, core::Names::fwdArgs(), fargs->loc);
args.emplace_back(node2TreeImpl(dctx, std::move(rest)));
// add `**<fwd-kwargs>`
unique_ptr<parser::Node> kwrest = make_unique<parser::Kwrestarg>(fargs->loc, core::Names::fwdKwargs());
args.emplace_back(node2TreeImpl(dctx, std::move(kwrest)));
// add `&<fwd-block>`
unique_ptr<parser::Node> block = make_unique<parser::Blockarg>(fargs->loc, core::Names::fwdBlock());
args.emplace_back(node2TreeImpl(dctx, std::move(block)));
} else {
args.emplace_back(node2TreeImpl(dctx, std::move(arg)));
}
}
} else if (auto *numparams = parser::cast_node<parser::NumParams>(argnode.get())) {
// The block uses numbered parameters like `_1` or `_9` so we add them as parameters
// from _1 to the highest number used.
for (int i = 1; i <= numparamMax(dctx, &numparams->decls); i++) {
args.emplace_back(numparamTree(dctx, i, &numparams->decls));
}
} else if (argnode.get() == nullptr) {
// do nothing
} else {
Exception::raise("not implemented: {}", argnode->nodeName());
}
return make_pair(std::move(args), std::move(destructures));
}
ExpressionPtr desugarBody(DesugarContext dctx, core::LocOffsets loc, unique_ptr<parser::Node> &bodynode,
InsSeq::STATS_store destructures) {
auto body = node2TreeImpl(dctx, std::move(bodynode));
if (!destructures.empty()) {
auto bodyLoc = body.loc();
if (!bodyLoc.exists()) {
bodyLoc = loc;
}
body = MK::InsSeq(loc, std::move(destructures), std::move(body));
}
return body;
}
ExpressionPtr desugarBlock(DesugarContext dctx, core::LocOffsets loc, core::LocOffsets blockLoc,
unique_ptr<parser::Node> &blockSend, unique_ptr<parser::Node> &blockArgs,
unique_ptr<parser::Node> &blockBody) {
blockSend->loc = loc;
auto recv = node2TreeImpl(dctx, std::move(blockSend));
Send *send;
ExpressionPtr res;
if ((send = cast_tree<Send>(recv)) != nullptr) {
res = std::move(recv);
} else {
// This must have been a csend; That will have been desugared
// into an insseq with an If in the expression.
res = std::move(recv);
auto *is = cast_tree<InsSeq>(res);
if (!is) {
if (auto e = dctx.ctx.beginError(blockLoc, core::errors::Desugar::UnsupportedNode)) {
e.setHeader("No body in block");
}
return MK::EmptyTree();
}
auto *iff = cast_tree<If>(is->expr);
ENFORCE(iff != nullptr, "DesugarBlock: failed to find If");
send = cast_tree<Send>(iff->elsep);
ENFORCE(send != nullptr, "DesugarBlock: failed to find Send");
}
auto [args, destructures] = desugarArgs(dctx, loc, blockArgs);
auto desugaredBody = desugarBody(dctx, loc, blockBody, std::move(destructures));
// TODO the send->block's loc is too big and includes the whole send
send->setBlock(MK::Block(loc, std::move(desugaredBody), std::move(args)));
return res;
}
bool isStringLit(DesugarContext dctx, ExpressionPtr &expr) {
Literal *lit;
return (lit = cast_tree<Literal>(expr)) && lit->isString(dctx.ctx);
}
ExpressionPtr mergeStrings(DesugarContext dctx, core::LocOffsets loc,
InlinedVector<ExpressionPtr, 4> stringsAccumulated) {
if (stringsAccumulated.size() == 1) {
return move(stringsAccumulated[0]);
} else {
return MK::String(
loc,
dctx.ctx.state.enterNameUTF8(fmt::format(
"{}", fmt::map_join(stringsAccumulated.begin(), stringsAccumulated.end(), "", [&](const auto &expr) {
if (isa_tree<EmptyTree>(expr)) {
return ""sv;
} else {
return cast_tree<Literal>(expr)->asString(dctx.ctx).shortName(dctx.ctx);
}
}))));
}
}
ExpressionPtr desugarDString(DesugarContext dctx, core::LocOffsets loc, parser::NodeVec nodes) {
if (nodes.empty()) {
return MK::String(loc, core::Names::empty());
}
auto it = nodes.begin();
auto end = nodes.end();
ExpressionPtr first = node2TreeImpl(dctx, std::move(*it));
InlinedVector<ExpressionPtr, 4> stringsAccumulated;
Send::ARGS_store interpArgs;
bool allStringsSoFar;
if (isStringLit(dctx, first) || isa_tree<EmptyTree>(first)) {
stringsAccumulated.emplace_back(std::move(first));
allStringsSoFar = true;
} else {
interpArgs.emplace_back(std::move(first));
allStringsSoFar = false;
}
++it;
for (; it != end; ++it) {
auto &stat = *it;
ExpressionPtr narg = node2TreeImpl(dctx, std::move(stat));
if (allStringsSoFar && isStringLit(dctx, narg)) {
stringsAccumulated.emplace_back(std::move(narg));
} else if (isa_tree<EmptyTree>(narg)) {
// no op
} else {
if (allStringsSoFar) {
allStringsSoFar = false;
interpArgs.emplace_back(mergeStrings(dctx, loc, std::move(stringsAccumulated)));
}
interpArgs.emplace_back(std::move(narg));
}
};
if (allStringsSoFar) {
return mergeStrings(dctx, loc, std::move(stringsAccumulated));
} else {
auto recv = MK::Constant(loc, core::Symbols::Magic());
return MK::Send(loc, std::move(recv), core::Names::stringInterpolate(), loc.copyWithZeroLength(),
interpArgs.size(), std::move(interpArgs));
}
}
bool isIVarAssign(ExpressionPtr &stat) {
auto assign = cast_tree<Assign>(stat);
if (!assign) {
return false;
}
auto ident = cast_tree<UnresolvedIdent>(assign->lhs);
if (!ident) {
return false;
}
if (ident->kind != UnresolvedIdent::Kind::Instance) {
return false;
}
return true;
}
ExpressionPtr validateRBIBody(DesugarContext dctx, ExpressionPtr body) {
if (!dctx.ctx.file.data(dctx.ctx).isRBI()) {
return body;
}
if (!body.loc().exists()) {
return body;
}
auto loc = core::Loc(dctx.ctx.file, body.loc());
if (isa_tree<EmptyTree>(body)) {
return body;
} else if (isa_tree<Assign>(body)) {
if (!isIVarAssign(body)) {
if (auto e = dctx.ctx.beginError(body.loc(), core::errors::Desugar::CodeInRBI)) {
e.setHeader("RBI methods must not have code");
e.replaceWith("Delete the body", loc, "");
}
}
} else if (auto inseq = cast_tree<InsSeq>(body)) {
for (auto &stat : inseq->stats) {
if (!isIVarAssign(stat)) {
if (auto e = dctx.ctx.beginError(stat.loc(), core::errors::Desugar::CodeInRBI)) {
e.setHeader("RBI methods must not have code");
e.replaceWith("Delete the body", loc, "");
}
}
}
if (!isIVarAssign(inseq->expr)) {
if (auto e = dctx.ctx.beginError(inseq->expr.loc(), core::errors::Desugar::CodeInRBI)) {
e.setHeader("RBI methods must not have code");
e.replaceWith("Delete the body", loc, "");
}
}
} else {
if (auto e = dctx.ctx.beginError(body.loc(), core::errors::Desugar::CodeInRBI)) {
e.setHeader("RBI methods must not have code");
e.replaceWith("Delete the body", loc, "");
}
}
return body;
}
ExpressionPtr buildMethod(DesugarContext dctx, core::LocOffsets loc, core::LocOffsets declLoc, core::NameRef name,
unique_ptr<parser::Node> &argnode, unique_ptr<parser::Node> &body, bool isSelf) {
// Reset uniqueCounter within this scope (to keep numbers small)
uint32_t uniqueCounter = 1;
DesugarContext dctx1(dctx.ctx, uniqueCounter, dctx.enclosingBlockArg, declLoc, name);
auto [args, destructures] = desugarArgs(dctx1, loc, argnode);
if (args.empty() || !isa_tree<BlockArg>(args.back())) {
auto blkLoc = core::LocOffsets::none();
args.emplace_back(MK::BlockArg(blkLoc, MK::Local(blkLoc, core::Names::blkArg())));
}
const auto &blkArg = cast_tree<BlockArg>(args.back());
ENFORCE(blkArg != nullptr, "Every method's last arg must be a block arg by now.");
auto enclosingBlockArg = blockArg2Name(dctx, *blkArg);
DesugarContext dctx2(dctx1.ctx, dctx1.uniqueCounter, enclosingBlockArg, declLoc, name);
ExpressionPtr desugaredBody = desugarBody(dctx2, loc, body, std::move(destructures));
desugaredBody = validateRBIBody(dctx2, move(desugaredBody));
auto mdef = MK::Method(loc, declLoc, name, std::move(args), std::move(desugaredBody));
cast_tree<MethodDef>(mdef)->flags.isSelfMethod = isSelf;
return mdef;
}
ExpressionPtr symbol2Proc(DesugarContext dctx, ExpressionPtr expr) {
auto loc = expr.loc();
core::NameRef temp = dctx.freshNameUnique(core::Names::blockPassTemp());
Literal *lit = cast_tree<Literal>(expr);
ENFORCE(lit && lit->isSymbol(dctx.ctx));
// &:foo => {|temp| temp.foo() }
core::NameRef name = core::cast_type_nonnull<core::LiteralType>(lit->value).asName(dctx.ctx);
// `temp` does not refer to any specific source text, so give it a 0-length Loc so LSP ignores it.
auto zeroLengthLoc = loc.copyWithZeroLength();
ExpressionPtr recv = MK::Local(zeroLengthLoc, temp);
ExpressionPtr body = MK::Send0(loc, std::move(recv), name, zeroLengthLoc);
return MK::Block1(loc, std::move(body), MK::Local(zeroLengthLoc, temp));
}
ExpressionPtr unsupportedNode(DesugarContext dctx, parser::Node *node) {
if (auto e = dctx.ctx.beginError(node->loc, core::errors::Desugar::UnsupportedNode)) {
e.setHeader("Unsupported node type `{}`", node->nodeName());
}
return MK::EmptyTree();
}
ExpressionPtr desugarMlhs(DesugarContext dctx, core::LocOffsets loc, parser::Mlhs *lhs, ExpressionPtr rhs) {
InsSeq::STATS_store stats;
core::NameRef tempRhs = dctx.freshNameUnique(core::Names::assignTemp());
core::NameRef tempExpanded = dctx.freshNameUnique(core::Names::assignTemp());
int i = 0;
int before = 0, after = 0;
bool didSplat = false;
for (auto &c : lhs->exprs) {
if (auto *splat = parser::cast_node<parser::SplatLhs>(c.get())) {
ENFORCE(!didSplat, "did splat already");
didSplat = true;
ExpressionPtr lh = node2TreeImpl(dctx, std::move(splat->var));
int left = i;
int right = lhs->exprs.size() - left - 1;
if (!isa_tree<EmptyTree>(lh)) {
auto exclusive = MK::True(lh.loc());
if (right == 0) {
right = 1;
exclusive = MK::False(lh.loc());
}
auto lhloc = lh.loc();
auto zlhloc = lhloc.copyWithZeroLength();
auto index = MK::Send3(lhloc, MK::Constant(lhloc, core::Symbols::Range()), core::Names::new_(), zlhloc,
MK::Int(lhloc, left), MK::Int(lhloc, -right), std::move(exclusive));
stats.emplace_back(MK::Assign(
lhloc, std::move(lh),
MK::Send1(loc, MK::Local(loc, tempExpanded), core::Names::slice(), zlhloc, std::move(index))));
}
i = -right;
} else {
if (didSplat) {
++after;
} else {
++before;
}
auto val = MK::Send1(loc, MK::Local(loc, tempExpanded), core::Names::squareBrackets(),
loc.copyWithZeroLength(), MK::Int(loc, i));
if (auto *mlhs = parser::cast_node<parser::Mlhs>(c.get())) {
stats.emplace_back(desugarMlhs(dctx, mlhs->loc, mlhs, std::move(val)));
} else {
ExpressionPtr lh = node2TreeImpl(dctx, std::move(c));
if (auto restArg = cast_tree<RestArg>(lh)) {
if (auto e = dctx.ctx.beginError(lh.loc(), core::errors::Desugar::UnsupportedRestArgsDestructure)) {
e.setHeader("Unsupported rest args in destructure");
}
lh = move(restArg->expr);
}
auto lhloc = lh.loc();
stats.emplace_back(MK::Assign(lhloc, std::move(lh), std::move(val)));
}
i++;
}
}
auto expanded =
MK::Send3(loc, MK::Constant(loc, core::Symbols::Magic()), core::Names::expandSplat(), loc.copyWithZeroLength(),
MK::Local(loc, tempRhs), MK::Int(loc, before), MK::Int(loc, after));
stats.insert(stats.begin(), MK::Assign(loc, tempExpanded, std::move(expanded)));
stats.insert(stats.begin(), MK::Assign(loc, tempRhs, std::move(rhs)));
// Regardless of how we destructure an assignment, Ruby evaluates the expression to the entire right hand side,
// not any individual component of the destructured assignment.
return MK::InsSeq(loc, std::move(stats), MK::Local(loc, tempRhs));
}
// Map all MatchVars used in `pattern` to local variables initialized from magic calls
void desugarPatternMatchingVars(InsSeq::STATS_store &vars, DesugarContext dctx, unique_ptr<parser::Node> &node) {
if (auto var = parser::cast_node<parser::MatchVar>(node.get())) {
auto loc = var->loc;
auto recv = MK::Constant(loc, core::Symbols::Magic());
auto val = MK::RaiseUnimplemented(loc);
vars.emplace_back(MK::Assign(loc, var->name, std::move(val)));
} else if (auto rest = parser::cast_node<parser::MatchRest>(node.get())) {
desugarPatternMatchingVars(vars, dctx, rest->var);
} else if (auto pair = parser::cast_node<parser::Pair>(node.get())) {
desugarPatternMatchingVars(vars, dctx, pair->value);
} else if (auto as_pattern = parser::cast_node<parser::MatchAs>(node.get())) {
auto loc = as_pattern->as->loc;
auto name = parser::cast_node<parser::MatchVar>(as_pattern->as.get())->name;
auto recv = MK::Constant(loc, core::Symbols::Magic());
auto val = MK::RaiseUnimplemented(loc);
vars.emplace_back(MK::Assign(loc, name, std::move(val)));
desugarPatternMatchingVars(vars, dctx, as_pattern->value);
} else if (auto array_pattern = parser::cast_node<parser::ArrayPattern>(node.get())) {
for (auto &elt : array_pattern->elts) {
desugarPatternMatchingVars(vars, dctx, elt);
}
} else if (auto array_pattern = parser::cast_node<parser::ArrayPatternWithTail>(node.get())) {
for (auto &elt : array_pattern->elts) {
desugarPatternMatchingVars(vars, dctx, elt);
}
} else if (auto hash_pattern = parser::cast_node<parser::HashPattern>(node.get())) {
for (auto &elt : hash_pattern->pairs) {
desugarPatternMatchingVars(vars, dctx, elt);
}
} else if (auto alt_pattern = parser::cast_node<parser::MatchAlt>(node.get())) {
desugarPatternMatchingVars(vars, dctx, alt_pattern->left);
desugarPatternMatchingVars(vars, dctx, alt_pattern->right);
}
}
// Desugar `in` and `=>` oneline pattern matching
ExpressionPtr desugarOnelinePattern(DesugarContext dctx, core::LocOffsets loc, unique_ptr<parser::Node> &match) {
auto matchExpr = MK::RaiseUnimplemented(loc);
auto bodyExpr = MK::RaiseUnimplemented(loc);
auto elseExpr = MK::EmptyTree();
InsSeq::STATS_store vars;
desugarPatternMatchingVars(vars, dctx, match);
if (!vars.empty()) {
bodyExpr = MK::InsSeq(match->loc, std::move(vars), std::move(bodyExpr));
}
return MK::If(loc, std::move(matchExpr), std::move(bodyExpr), std::move(elseExpr));
}
bool locReported = false;
ClassDef::RHS_store scopeNodeToBody(DesugarContext dctx, unique_ptr<parser::Node> node) {
ClassDef::RHS_store body;
// Reset uniqueCounter within this scope (to keep numbers small)
uint32_t uniqueCounter = 1;
DesugarContext dctx1(dctx.ctx, uniqueCounter, dctx.enclosingBlockArg, dctx.enclosingMethodLoc,
dctx.enclosingMethodName);
if (auto *begin = parser::cast_node<parser::Begin>(node.get())) {
body.reserve(begin->stmts.size());
for (auto &stat : begin->stmts) {
body.emplace_back(node2TreeImpl(dctx1, std::move(stat)));
};
} else {
body.emplace_back(node2TreeImpl(dctx1, std::move(node)));
}
return body;
}
struct OpAsgnScaffolding {
core::NameRef temporaryName;
InsSeq::STATS_store statementBody;
uint16_t numPosArgs;
Send::ARGS_store readArgs;
Send::ARGS_store assgnArgs;
};
// Desugaring passes for op-assignments (like += or &&=) will first desugar the LHS, which often results in a send if
// there's a dot anywhere on the LHS. Consider an expression like `x.y += 1`. We'll want to desugar this to
//
// { $tmp = x.y; x.y = $tmp + 1 }
//
// which now involves two (slightly different) sends: the .y() in the first statement, and the .y=() in the second
// statement. The first one will have as many arguments as the original, while the second will have one more than the
// original (to allow for the passed value). This function creates both argument lists as well as the instruction block
// and the temporary variable: how these will be used will differ slightly depending on whether we're desugaring &&=,
// ||=, or some other op-assign, but the logic contained here will stay in common.
OpAsgnScaffolding copyArgsForOpAsgn(DesugarContext dctx, Send *s) {
// this is for storing the temporary assignments followed by the final update. In the case that we have other
// arguments to the send (e.g. in the case of x.y[z] += 1) we'll want to store the other parameters (z) in a
// temporary as well, producing a sequence like
//
// { $arg = z; $tmp = x.y[$arg]; x.y[$arg] = $tmp + 1 }
//
// This means we'll always need statements for as many arguments as the send has, plus two more: one for the
// temporary assignment and the last for the actual update we're desugaring.
ENFORCE(!s->hasKwArgs() && !s->hasBlock());
const auto numPosArgs = s->numPosArgs();
InsSeq::STATS_store stats;
stats.reserve(numPosArgs + 2);
core::NameRef tempRecv = dctx.freshNameUnique(s->fun);
stats.emplace_back(MK::Assign(s->loc, tempRecv, std::move(s->recv)));
Send::ARGS_store readArgs;
Send::ARGS_store assgnArgs;
// these are the arguments for the first send, e.g. x.y(). The number of arguments should be identical to whatever
// we saw on the LHS.
readArgs.reserve(numPosArgs);
// these are the arguments for the second send, e.g. x.y=(val). That's why we need the space for the extra argument
// here: to accomodate the call to field= instead of just field.
assgnArgs.reserve(numPosArgs + 1);
for (auto &arg : s->posArgs()) {
auto argLoc = arg.loc();
core::NameRef name = dctx.freshNameUnique(s->fun);
stats.emplace_back(MK::Assign(argLoc, name, std::move(arg)));
readArgs.emplace_back(MK::Local(argLoc, name));
assgnArgs.emplace_back(MK::Local(argLoc, name));
}
return {tempRecv, std::move(stats), numPosArgs, std::move(readArgs), std::move(assgnArgs)};
}
// while true
// body
// if cond
// break
// end
// end
ExpressionPtr doUntil(DesugarContext dctx, core::LocOffsets loc, ExpressionPtr cond, ExpressionPtr body) {
auto breaker = MK::If(loc, std::move(cond), MK::Break(loc, MK::EmptyTree()), MK::EmptyTree());
auto breakWithBody = MK::InsSeq1(loc, std::move(body), std::move(breaker));
return MK::While(loc, MK::True(loc), std::move(breakWithBody));
}
class DuplicateHashKeyCheck {
DesugarContext dctx;
const core::GlobalState &gs;
UnorderedMap<core::NameRef, core::LocOffsets> hashKeySymbols;
UnorderedMap<core::NameRef, core::LocOffsets> hashKeyStrings;
public:
DuplicateHashKeyCheck(DesugarContext dctx) : dctx{dctx}, gs{dctx.ctx.state}, hashKeySymbols(), hashKeyStrings() {}
void check(const ExpressionPtr &key) {
auto lit = ast::cast_tree<ast::Literal>(key);
if (lit == nullptr) {
return;
}
auto isSymbol = lit->isSymbol(gs);
core::NameRef nameRef;
if (!lit) {
return;
}
if (isSymbol) {
nameRef = lit->asSymbol(gs);
} else if (lit->isString(gs)) {
nameRef = lit->asString(gs);
} else {
return;
}
if (isSymbol && !hashKeySymbols.contains(nameRef)) {
hashKeySymbols[nameRef] = key.loc();
} else if (!isSymbol && !hashKeyStrings.contains(nameRef)) {
hashKeyStrings[nameRef] = key.loc();
} else {
if (auto e = dctx.ctx.beginError(key.loc(), core::errors::Desugar::DuplicatedHashKeys)) {
core::LocOffsets originalLoc;
if (isSymbol) {
originalLoc = hashKeySymbols[nameRef];
} else {
originalLoc = hashKeyStrings[nameRef];
}
e.setHeader("Hash key `{}` is duplicated", nameRef.toString(gs));
e.addErrorLine(core::Loc(dctx.ctx.file, originalLoc), "First occurrence of `{}` hash key",
nameRef.toString(gs));
}
}
}
void reset() {
hashKeySymbols.clear();
hashKeyStrings.clear();
}
// This is only used with Send::ARGS_store and Array::ELEMS_store
template <typename T> static void checkSendArgs(DesugarContext dctx, int numPosArgs, const T &args) {
DuplicateHashKeyCheck duplicateKeyCheck{dctx};
// increment by two so that a keyword args splat gets skipped.
for (int i = numPosArgs; i < args.size(); i += 2) {
duplicateKeyCheck.check(args[i]);
}
}
};
ExpressionPtr node2TreeImpl(DesugarContext dctx, unique_ptr<parser::Node> what) {
try {
if (what.get() == nullptr) {
return MK::EmptyTree();
}
auto loc = what->loc;
auto locZeroLen = what->loc.copyWithZeroLength();
ENFORCE(loc.exists(), "parse-tree node has no location: {}", what->toString(dctx.ctx));
ExpressionPtr result;
typecase(
what.get(),
// The top N clauses here are ordered according to observed
// frequency in pay-server. Do not reorder the top of this list, or
// add entries here, without consulting the "node.*" counters from a
// run over a representative code base.
[&](parser::Const *const_) {
auto scope = node2TreeImpl(dctx, std::move(const_->scope));
ExpressionPtr res = MK::UnresolvedConstant(loc, std::move(scope), const_->name);
result = std::move(res);
},
[&](parser::Send *send) {
Send::Flags flags;
auto rec = node2TreeImpl(dctx, std::move(send->receiver));
if (isa_tree<EmptyTree>(rec)) {
// 0-sized Loc, since `self.` doesn't appear in the original file.
rec = MK::Self(loc.copyWithZeroLength());
flags.isPrivateOk = true;
} else if (rec.isSelfReference()) {
// In Ruby 2.7 `self.foo()` is also allowed for private method calls,
// not only `foo()`. This pre-emptively allow the new syntax.
flags.isPrivateOk = true;
}
if (absl::c_any_of(send->args, [](auto &arg) {
return parser::isa_node<parser::Splat>(arg.get()) ||
parser::isa_node<parser::ForwardedArgs>(arg.get());
})) {
// Build up an array that represents the keyword args for the send. When there is a Kwsplat, treat
// all keyword arguments as a single argument.
unique_ptr<parser::Node> kwArray;
// If there's a &blk node in the last position, pop that off (we'll put it back later, but
// subsequent logic for dealing with the kwargs hash is simpler this way).
unique_ptr<parser::Node> savedBlockPass = nullptr;
if (!send->args.empty() && parser::isa_node<parser::BlockPass>(send->args.back().get())) {
savedBlockPass = std::move(send->args.back());
send->args.pop_back();
}
// Deconstruct the kwargs hash if it's present.
if (!send->args.empty()) {
if (auto *hash = parser::cast_node<parser::Hash>(send->args.back().get())) {
if (hash->kwargs) {
// hold a reference to the node, and remove it from the back of the send list
auto node = std::move(send->args.back());
send->args.pop_back();
parser::NodeVec elts;
// skip inlining the kwargs if there are any kwsplat nodes present
if (absl::c_any_of(hash->pairs, [](auto &node) {
// the parser guarantees that if we see a kwargs hash it only contains pair or
// kwsplat nodes
ENFORCE(parser::isa_node<parser::Kwsplat>(node.get()) ||
parser::isa_node<parser::Pair>(node.get()));
return parser::isa_node<parser::Kwsplat>(node.get());
})) {
elts.emplace_back(std::move(node));
} else {
// inline the hash into the send args
for (auto &entry : hash->pairs) {
typecase(
entry.get(),
[&](parser::Pair *pair) {
elts.emplace_back(std::move(pair->key));
elts.emplace_back(std::move(pair->value));
},
[&](parser::Node *node) { Exception::raise("Unhandled case"); });
}
}
kwArray = make_unique<parser::Array>(loc, std::move(elts));
}
}
}
// Put the &blk arg back, if present.
if (savedBlockPass) {
send->args.emplace_back(std::move(savedBlockPass));
}
// If the kwargs hash is not present, make a `nil` to put in the place of that argument. This
// will be used in the implementation of the intrinsic to tell the difference between keyword
// args, keyword args with kw splats, and no keyword args at all.
if (kwArray == nullptr) {
kwArray = make_unique<parser::Nil>(loc);
}
// If we have a splat anywhere in the argument list, desugar
// the argument list as a single Array node, and then
// synthesize a call to
// Magic.callWithSplat(receiver, method, argArray, [&blk])
// The callWithSplat implementation (in C++) will unpack a
// tuple type and call into the normal call merchanism.
unique_ptr<parser::Node> block;
auto argnodes = std::move(send->args);
auto it = absl::c_find_if(argnodes,
[](auto &arg) { return parser::isa_node<parser::BlockPass>(arg.get()); });
if (it != argnodes.end()) {
auto *bp = parser::cast_node<parser::BlockPass>(it->get());
block = std::move(bp->block);
argnodes.erase(it);
}
auto hasFwdArgs = false;
auto fwdIt = absl::c_find_if(
argnodes, [](auto &arg) { return parser::isa_node<parser::ForwardedArgs>(arg.get()); });
if (fwdIt != argnodes.end()) {
block = make_unique<parser::LVar>(loc, core::Names::fwdBlock());
hasFwdArgs = true;
argnodes.erase(fwdIt);
}
auto array = make_unique<parser::Array>(loc, std::move(argnodes));
auto args = node2TreeImpl(dctx, std::move(array));
if (hasFwdArgs) {
auto fwdArgs = MK::Local(loc, core::Names::fwdArgs());
auto argsSplat = MK::Send0(loc, std::move(fwdArgs), core::Names::toA(), locZeroLen);
auto argsConcat =
MK::Send1(loc, std::move(args), core::Names::concat(), locZeroLen, std::move(argsSplat));
auto fwdKwargs = MK::Local(loc, core::Names::fwdKwargs());
auto kwargsSplat = MK::Send1(loc, MK::Constant(loc, core::Symbols::Magic()),
core::Names::toHashDup(), locZeroLen, std::move(fwdKwargs));
Array::ENTRY_store kwargsEntries;
kwargsEntries.emplace_back(std::move(kwargsSplat));
auto kwargsArray = MK::Array(loc, std::move(kwargsEntries));
argsConcat = MK::Send1(loc, std::move(argsConcat), core::Names::concat(), locZeroLen,
std::move(kwargsArray));
args = std::move(argsConcat);
}
auto kwargs = node2TreeImpl(dctx, std::move(kwArray));
auto method =
MK::Literal(loc, core::make_type<core::LiteralType>(core::Symbols::Symbol(), send->method));
if (auto *array = cast_tree<Array>(kwargs)) {
DuplicateHashKeyCheck::checkSendArgs(dctx, 0, array->elems);
}
Send::ARGS_store sendargs;
sendargs.emplace_back(std::move(rec));
sendargs.emplace_back(std::move(method));
sendargs.emplace_back(std::move(args));
sendargs.emplace_back(std::move(kwargs));
ExpressionPtr res;
if (block == nullptr) {
res = MK::Send(loc, MK::Constant(loc, core::Symbols::Magic()), core::Names::callWithSplat(),
locZeroLen, 4, std::move(sendargs), flags);
} else {
auto convertedBlock = node2TreeImpl(dctx, std::move(block));
Literal *lit;
if ((lit = cast_tree<Literal>(convertedBlock)) && lit->isSymbol(dctx.ctx)) {
res = MK::Send(loc, MK::Constant(loc, core::Symbols::Magic()), core::Names::callWithSplat(),
locZeroLen, 4, std::move(sendargs), flags);
ast::cast_tree_nonnull<ast::Send>(res).setBlock(
symbol2Proc(dctx, std::move(convertedBlock)));
} else {
sendargs.emplace_back(std::move(convertedBlock));
res = MK::Send(loc, MK::Constant(loc, core::Symbols::Magic()),
core::Names::callWithSplatAndBlock(), locZeroLen, 5, std::move(sendargs),
flags);
}
}
result = std::move(res);
} else {
int numPosArgs = send->args.size();
if (numPosArgs > 0) {
// Deconstruct the kwargs hash in the last argument if it's present.
if (auto *hash = parser::cast_node<parser::Hash>(send->args.back().get())) {
if (hash->kwargs) {
numPosArgs--;
// skip inlining the kwargs if there are any non-key/value pairs present
if (!absl::c_any_of(hash->pairs, [](auto &node) {
// the parser guarantees that if we see a kwargs hash it only contains pair or
// kwsplat nodes
ENFORCE(parser::isa_node<parser::Kwsplat>(node.get()) ||
parser::isa_node<parser::Pair>(node.get()));
return parser::isa_node<parser::Kwsplat>(node.get());
})) {
// hold a reference to the node, and remove it from the back fo the send list
auto node = std::move(send->args.back());
send->args.pop_back();
// inline the hash into the send args
for (auto &entry : hash->pairs) {
typecase(
entry.get(),
[&](parser::Pair *pair) {
send->args.emplace_back(std::move(pair->key));
send->args.emplace_back(std::move(pair->value));
},
[&](parser::Node *node) { Exception::raise("Unhandled case"); });
}
}
}
}
}
Send::ARGS_store args;
unique_ptr<parser::Node> block;
args.reserve(send->args.size());
for (auto &stat : send->args) {
if (auto bp = parser::cast_node<parser::BlockPass>(stat.get())) {
ENFORCE(block == nullptr, "passing a block where there is no block");
block = std::move(bp->block);
// we don't count the block arg as part of the positional arguments anymore.
numPosArgs = max(0, numPosArgs - 1);
} else {
args.emplace_back(node2TreeImpl(dctx, std::move(stat)));
}
};
DuplicateHashKeyCheck::checkSendArgs(dctx, numPosArgs, args);
ExpressionPtr res;
if (block == nullptr) {
res = MK::Send(loc, std::move(rec), send->method, send->methodLoc, numPosArgs, std::move(args),
flags);
} else {
auto method =
MK::Literal(loc, core::make_type<core::LiteralType>(core::Symbols::Symbol(), send->method));
auto convertedBlock = node2TreeImpl(dctx, std::move(block));
Literal *lit;
if ((lit = cast_tree<Literal>(convertedBlock)) && lit->isSymbol(dctx.ctx)) {
res = MK::Send(loc, std::move(rec), send->method, send->methodLoc, numPosArgs,
std::move(args), flags);
ast::cast_tree_nonnull<ast::Send>(res).setBlock(
symbol2Proc(dctx, std::move(convertedBlock)));
} else {
Send::ARGS_store sendargs;
sendargs.emplace_back(std::move(rec));
sendargs.emplace_back(std::move(method));
sendargs.emplace_back(std::move(convertedBlock));
numPosArgs += 3;
for (auto &arg : args) {
sendargs.emplace_back(std::move(arg));
}
res = MK::Send(loc, MK::Constant(loc, core::Symbols::Magic()), core::Names::callWithBlock(),
locZeroLen, numPosArgs, std::move(sendargs), flags);
}
}
if (send->method == core::Names::blockGiven_p() && dctx.enclosingBlockArg.exists()) {
auto if_ = MK::If(loc, MK::Local(loc, dctx.enclosingBlockArg), std::move(res), MK::False(loc));
result = std::move(if_);
} else {
result = std::move(res);
}
}
},
[&](parser::String *string) {
ExpressionPtr res = MK::String(loc, string->val);
result = std::move(res);
},
[&](parser::Symbol *symbol) {
ExpressionPtr res = MK::Symbol(loc, symbol->val);
result = std::move(res);
},
[&](parser::LVar *var) {
ExpressionPtr res = MK::Local(loc, var->name);
result = std::move(res);
},
[&](parser::Hash *hash) {
InsSeq::STATS_store updateStmts;
updateStmts.reserve(hash->pairs.size());
auto acc = dctx.freshNameUnique(core::Names::hashTemp());
DuplicateHashKeyCheck hashKeyDupes(dctx);
Send::ARGS_store mergeValues;
mergeValues.reserve(hash->pairs.size() * 2 + 1);
mergeValues.emplace_back(MK::Local(loc, acc));
bool havePairsToMerge = false;
// build a hash literal assuming that the argument follows the same format as `mergeValues`:
// arg 0: the hash to merge into
// arg 1: key
// arg 2: value
// ...
// arg n: key
// arg n+1: value
auto buildHashLiteral = [loc](Send::ARGS_store &mergeValues) {
Hash::ENTRY_store keys;
Hash::ENTRY_store values;
keys.reserve(mergeValues.size() / 2);
values.reserve(mergeValues.size() / 2);
// skip the first positional argument for the accumulator that would have been mutated
for (auto it = mergeValues.begin() + 1; it != mergeValues.end();) {
keys.emplace_back(std::move(*it++));
values.emplace_back(std::move(*it++));
}
return MK::Hash(loc, std::move(keys), std::move(values));
};
// Desguar
// {**x, a: 'a', **y, remaining}
// into
// acc = <Magic>.<to-hash-dup>(x)
// acc = <Magic>.<merge-hash-values>(acc, :a, 'a')
// acc = <Magic>.<merge-hash>(acc, <Magic>.<to-hash-nodup>(y))
// acc = <Magic>.<merge-hash>(acc, remaining)
// acc
for (auto &pairAsExpression : hash->pairs) {
auto *pair = parser::cast_node<parser::Pair>(pairAsExpression.get());
if (pair != nullptr) {
auto key = node2TreeImpl(dctx, std::move(pair->key));
hashKeyDupes.check(key);
mergeValues.emplace_back(std::move(key));
auto value = node2TreeImpl(dctx, std::move(pair->value));
mergeValues.emplace_back(std::move(value));
havePairsToMerge = true;
continue;
}
auto *splat = parser::cast_node<parser::Kwsplat>(pairAsExpression.get());
ENFORCE(splat != nullptr, "kwsplat cast failed");
if (havePairsToMerge) {
havePairsToMerge = false;
// ensure that there's something to update
if (updateStmts.empty()) {
updateStmts.emplace_back(MK::Assign(loc, acc, buildHashLiteral(mergeValues)));
} else {
int numPosArgs = mergeValues.size();
updateStmts.emplace_back(MK::Assign(loc, acc,
MK::Send(loc, MK::Constant(loc, core::Symbols::Magic()),
core::Names::mergeHashValues(), locZeroLen,
numPosArgs, std::move(mergeValues))));
}
mergeValues.clear();
mergeValues.emplace_back(MK::Local(loc, acc));
}
auto expr = node2TreeImpl(dctx, std::move(splat->expr));
// If this is the first argument to `<Magic>.<merge-hash>`, it needs to be duplicated as that
// intrinsic is assumed to mutate its first argument.
if (updateStmts.empty()) {
updateStmts.emplace_back(
MK::Assign(loc, acc,
MK::Send1(loc, MK::Constant(loc, core::Symbols::Magic()),
core::Names::toHashDup(), locZeroLen, std::move(expr))));
} else {
updateStmts.emplace_back(
MK::Assign(loc, acc,
MK::Send2(loc, MK::Constant(loc, core::Symbols::Magic()),
core::Names::mergeHash(), locZeroLen, MK::Local(loc, acc),
MK::Send1(loc, MK::Constant(loc, core::Symbols::Magic()),
core::Names::toHashNoDup(), locZeroLen, std::move(expr)))));
}