forked from JetBrains/kotlin
/
ExpressionCodegen.java
4939 lines (4172 loc) · 222 KB
/
ExpressionCodegen.java
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
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.codegen;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.psi.PsiElement;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Function;
import com.intellij.util.containers.Stack;
import kotlin.Pair;
import kotlin.Unit;
import kotlin.collections.CollectionsKt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.backend.common.CodegenUtil;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.codegen.binding.CalculatedClosure;
import org.jetbrains.kotlin.codegen.binding.CodegenBinding;
import org.jetbrains.kotlin.codegen.context.*;
import org.jetbrains.kotlin.codegen.coroutines.CoroutineCodegenForLambda;
import org.jetbrains.kotlin.codegen.coroutines.CoroutineCodegenUtilKt;
import org.jetbrains.kotlin.codegen.coroutines.ResolvedCallWithRealDescriptor;
import org.jetbrains.kotlin.codegen.extensions.ExpressionCodegenExtension;
import org.jetbrains.kotlin.codegen.inline.*;
import org.jetbrains.kotlin.codegen.intrinsics.*;
import org.jetbrains.kotlin.codegen.pseudoInsns.PseudoInsnsKt;
import org.jetbrains.kotlin.codegen.range.RangeValue;
import org.jetbrains.kotlin.codegen.range.RangeValuesKt;
import org.jetbrains.kotlin.codegen.range.forLoop.ForLoopGenerator;
import org.jetbrains.kotlin.codegen.signature.BothSignatureWriter;
import org.jetbrains.kotlin.codegen.signature.JvmSignatureWriter;
import org.jetbrains.kotlin.codegen.state.GenerationState;
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper;
import org.jetbrains.kotlin.codegen.when.SwitchCodegen;
import org.jetbrains.kotlin.codegen.when.SwitchCodegenProvider;
import org.jetbrains.kotlin.config.ApiVersion;
import org.jetbrains.kotlin.config.JVMAssertionsMode;
import org.jetbrains.kotlin.config.LanguageFeature;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.descriptors.impl.*;
import org.jetbrains.kotlin.diagnostics.Errors;
import org.jetbrains.kotlin.lexer.KtTokens;
import org.jetbrains.kotlin.load.java.JvmAbi;
import org.jetbrains.kotlin.load.java.sam.SamConstructorDescriptor;
import org.jetbrains.kotlin.load.kotlin.MethodSignatureMappingKt;
import org.jetbrains.kotlin.load.kotlin.TypeSignatureMappingKt;
import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.psi.*;
import org.jetbrains.kotlin.psi.psiUtil.PsiUtilsKt;
import org.jetbrains.kotlin.resolve.*;
import org.jetbrains.kotlin.resolve.calls.callResolverUtil.CallResolverUtilKt;
import org.jetbrains.kotlin.resolve.calls.callUtil.CallUtilKt;
import org.jetbrains.kotlin.resolve.calls.model.*;
import org.jetbrains.kotlin.resolve.calls.util.CallMaker;
import org.jetbrains.kotlin.resolve.calls.util.FakeCallableDescriptorForObject;
import org.jetbrains.kotlin.resolve.calls.util.FakeCallableDescriptorForTypeAliasObject;
import org.jetbrains.kotlin.resolve.calls.util.UnderscoreUtilKt;
import org.jetbrains.kotlin.resolve.checkers.PrimitiveNumericComparisonInfo;
import org.jetbrains.kotlin.resolve.constants.*;
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluatorKt;
import org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilsKt;
import org.jetbrains.kotlin.resolve.inline.InlineUtil;
import org.jetbrains.kotlin.resolve.jvm.AsmTypes;
import org.jetbrains.kotlin.resolve.jvm.JvmBindingContextSlices;
import org.jetbrains.kotlin.resolve.jvm.JvmConstantsKt;
import org.jetbrains.kotlin.resolve.jvm.RuntimeAssertionInfo;
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOriginKt;
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodParameterKind;
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodParameterSignature;
import org.jetbrains.kotlin.resolve.scopes.receivers.*;
import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor;
import org.jetbrains.kotlin.types.KotlinType;
import org.jetbrains.kotlin.types.SimpleType;
import org.jetbrains.kotlin.types.TypeProjection;
import org.jetbrains.kotlin.types.TypeUtils;
import org.jetbrains.kotlin.types.expressions.DoubleColonLHS;
import org.jetbrains.kotlin.types.typesApproximation.CapturedTypeApproximationKt;
import org.jetbrains.kotlin.util.OperatorNameConventions;
import org.jetbrains.org.objectweb.asm.Label;
import org.jetbrains.org.objectweb.asm.MethodVisitor;
import org.jetbrains.org.objectweb.asm.Opcodes;
import org.jetbrains.org.objectweb.asm.Type;
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter;
import org.jetbrains.org.objectweb.asm.commons.Method;
import java.util.*;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.isInt;
import static org.jetbrains.kotlin.codegen.AsmUtil.*;
import static org.jetbrains.kotlin.codegen.CodegenUtilKt.*;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.*;
import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.*;
import static org.jetbrains.kotlin.codegen.inline.InlineCodegenUtilsKt.*;
import static org.jetbrains.kotlin.resolve.BindingContext.*;
import static org.jetbrains.kotlin.resolve.BindingContextUtils.getDelegationConstructorCall;
import static org.jetbrains.kotlin.resolve.BindingContextUtils.isVarCapturedInClosure;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.*;
import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.*;
import static org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils.isFunctionExpression;
import static org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils.isFunctionLiteral;
import static org.jetbrains.org.objectweb.asm.Opcodes.*;
public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> implements LocalLookup, BaseExpressionCodegen {
private final GenerationState state;
final KotlinTypeMapper typeMapper;
private final BindingContext bindingContext;
public final InstructionAdapter v;
public final FrameMap myFrameMap;
public final MethodContext context;
private final Type returnType;
private final CodegenStatementVisitor statementVisitor = new CodegenStatementVisitor(this);
private final MemberCodegen<?> parentCodegen;
private final TailRecursionCodegen tailRecursionCodegen;
public final CallGenerator defaultCallGenerator = new CallGenerator.DefaultCallGenerator(this);
private final SwitchCodegenProvider switchCodegenProvider;
private final Stack<BlockStackElement> blockStackElements = new Stack<>();
/*
* When we create a temporary variable to hold some value not to compute it many times
* we put it into this map to emit access to that variable instead of evaluating the whole expression
*/
public final Map<KtElement, StackValue> tempVariables = new HashMap<>();
private int myLastLineNumber = -1;
private boolean shouldMarkLineNumbers = true;
private int finallyDepth = 0;
public ExpressionCodegen(
@NotNull MethodVisitor mv,
@NotNull FrameMap frameMap,
@NotNull Type returnType,
@NotNull MethodContext context,
@NotNull GenerationState state,
@NotNull MemberCodegen<?> parentCodegen
) {
this.state = state;
this.typeMapper = state.getTypeMapper();
this.bindingContext = state.getBindingContext();
this.v = new InstructionAdapter(mv);
this.myFrameMap = frameMap;
this.context = context;
this.returnType = returnType;
this.parentCodegen = parentCodegen;
this.tailRecursionCodegen = new TailRecursionCodegen(context, this, this.v, state);
this.switchCodegenProvider = new SwitchCodegenProvider(this);
}
@Nullable
private static FunctionDescriptor getOriginalSuspendLambdaDescriptorFromContext(MethodContext context) {
if ((context.getParentContext() instanceof ClosureContext) &&
(context.getParentContext().closure != null) &&
context.getParentContext().closure.isSuspend()) {
return ((ClosureContext) context.getParentContext()).getOriginalSuspendLambdaDescriptor();
}
return null;
}
static class BlockStackElement {
}
static class LoopBlockStackElement extends BlockStackElement {
final Label continueLabel;
final Label breakLabel;
public final KtSimpleNameExpression targetLabel;
LoopBlockStackElement(Label breakLabel, Label continueLabel, KtSimpleNameExpression targetLabel) {
this.breakLabel = breakLabel;
this.continueLabel = continueLabel;
this.targetLabel = targetLabel;
}
}
static class FinallyBlockStackElement extends BlockStackElement {
List<Label> gaps = new ArrayList<>();
final KtTryExpression expression;
FinallyBlockStackElement(KtTryExpression expression) {
this.expression = expression;
}
private void addGapLabel(Label label){
gaps.add(label);
}
}
@NotNull
public GenerationState getState() {
return state;
}
@NotNull
public BindingContext getBindingContext() {
return bindingContext;
}
@NotNull
public MemberCodegen<?> getParentCodegen() {
return parentCodegen;
}
@NotNull
public ObjectLiteralResult generateObjectLiteral(@NotNull KtObjectLiteralExpression literal) {
KtObjectDeclaration objectDeclaration = literal.getObjectDeclaration();
ClassDescriptor classDescriptor = bindingContext.get(CLASS, objectDeclaration);
assert classDescriptor != null;
Type asmType = asmTypeForAnonymousClass(bindingContext, objectDeclaration);
ClassBuilder classBuilder = state.getFactory().newVisitor(
JvmDeclarationOriginKt.OtherOrigin(objectDeclaration, classDescriptor),
asmType,
literal.getContainingFile()
);
ClassContext objectContext = context.intoAnonymousClass(classDescriptor, this, OwnerKind.IMPLEMENTATION);
MemberCodegen literalCodegen = new ImplementationBodyCodegen(
objectDeclaration, objectContext, classBuilder, state, getParentCodegen(),
/* isLocal = */ true);
literalCodegen.generate();
addReifiedParametersFromSignature(literalCodegen, classDescriptor);
propagateChildReifiedTypeParametersUsages(literalCodegen.getReifiedTypeParametersUsages());
return new ObjectLiteralResult(
literalCodegen.getReifiedTypeParametersUsages().wereUsedReifiedParameters(),
classDescriptor
);
}
private static void addReifiedParametersFromSignature(@NotNull MemberCodegen member, @NotNull ClassDescriptor descriptor) {
for (KotlinType type : descriptor.getTypeConstructor().getSupertypes()) {
for (TypeProjection supertypeArgument : type.getArguments()) {
TypeParameterDescriptor parameterDescriptor = TypeUtils.getTypeParameterDescriptorOrNull(supertypeArgument.getType());
if (parameterDescriptor != null && parameterDescriptor.isReified()) {
member.getReifiedTypeParametersUsages().addUsedReifiedParameter(parameterDescriptor.getName().asString());
}
}
}
}
private static class ObjectLiteralResult {
private final boolean wereReifiedMarkers;
private final ClassDescriptor classDescriptor;
public ObjectLiteralResult(boolean wereReifiedMarkers, @NotNull ClassDescriptor classDescriptor) {
this.wereReifiedMarkers = wereReifiedMarkers;
this.classDescriptor = classDescriptor;
}
}
@NotNull
private StackValue castToRequiredTypeOfInterfaceIfNeeded(
StackValue inner,
@NotNull ClassDescriptor provided,
@NotNull ClassDescriptor required
) {
if (!isJvmInterface(provided) && isJvmInterface(required)) {
SimpleType requiredDefaultType = required.getDefaultType();
return StackValue.coercion(inner, asmType(requiredDefaultType), requiredDefaultType);
}
return inner;
}
public StackValue genQualified(StackValue receiver, KtElement selector) {
return genQualified(receiver, selector, this);
}
private StackValue genQualified(StackValue receiver, KtElement selector, KtVisitor<StackValue, StackValue> visitor) {
if (tempVariables.containsKey(selector)) {
throw new IllegalStateException("Inconsistent state: expression saved to a temporary variable is a selector");
}
if (!(selector instanceof KtBlockExpression)) {
markStartLineNumber(selector);
}
try {
if (selector instanceof KtExpression) {
StackValue samValue = genSamInterfaceValue((KtExpression) selector, visitor);
if (samValue != null) {
return samValue;
}
}
StackValue stackValue = selector.accept(visitor, receiver);
stackValue = suspendFunctionTypeWrapperIfNeeded(selector, stackValue);
RuntimeAssertionInfo runtimeAssertionInfo = null;
if (selector instanceof KtExpression) {
KtExpression expression = (KtExpression) selector;
runtimeAssertionInfo = bindingContext.get(JvmBindingContextSlices.RUNTIME_ASSERTION_INFO, expression);
if (runtimeAssertionInfo == null &&
state.getLanguageVersionSettings().supportsFeature(LanguageFeature.StrictJavaNullabilityAssertions)) {
runtimeAssertionInfo = bindingContext.get(JvmBindingContextSlices.BODY_RUNTIME_ASSERTION_INFO, expression);
}
}
if (BuiltinSpecialBridgesKt.isValueArgumentForCallToMethodWithTypeCheckBarrier(selector, bindingContext)) return stackValue;
return genNotNullAssertions(state, stackValue, runtimeAssertionInfo);
}
catch (ProcessCanceledException | CompilationException e) {
throw e;
}
catch (Throwable error) {
String message = error.getMessage();
throw new CompilationException(message != null ? message : "null", error, selector);
}
}
private StackValue suspendFunctionTypeWrapperIfNeeded(KtElement selector, StackValue stackValue) {
Type functionTypeForWrapper =
selector instanceof KtExpression
? bindingContext.get(CodegenBinding.FUNCTION_TYPE_FOR_SUSPEND_WRAPPER, (KtExpression) selector)
: null;
if (functionTypeForWrapper == null) return stackValue;
StackValue stackValueToWrap = stackValue;
stackValue = new StackValue(stackValue.type, stackValue.kotlinType) {
@Override
public void putSelector(
@NotNull Type type, @Nullable KotlinType kotlinType, @NotNull InstructionAdapter v
) {
stackValueToWrap.put(functionTypeForWrapper, null, v);
invokeCoroutineMigrationMethod(
v,
"toExperimentalSuspendFunction",
Type.getMethodDescriptor(functionTypeForWrapper, functionTypeForWrapper)
);
coerce(functionTypeForWrapper, type, v);
}
};
return stackValue;
}
public StackValue gen(KtElement expr) {
StackValue tempVar = tempVariables.get(expr);
return tempVar != null ? tempVar : genQualified(StackValue.none(), expr);
}
public void gen(KtElement expr, Type type) {
gen(expr, type, null);
}
public void gen(KtElement expr, Type type, KotlinType kotlinType) {
StackValue value = Type.VOID_TYPE.equals(type) ? genStatement(expr) : gen(expr);
putStackValue(expr, type, kotlinType, value);
}
private void putStackValue(@Nullable KtElement expr, @NotNull Type type, @Nullable KotlinType kotlinType, @NotNull StackValue value) {
// for repl store the result of the last line into special field
if (value.type != Type.VOID_TYPE && state.getReplSpecific().getShouldGenerateScriptResultValue()) {
ScriptContext context = getScriptContext();
if (expr == context.getLastStatement()) {
StackValue.Field resultValue = StackValue.field(context.getResultFieldInfo(), StackValue.LOCAL_0);
resultValue.store(value, v);
state.getReplSpecific().setHasResult(true);
return;
}
}
value.put(type, kotlinType, v);
}
@NotNull
private ScriptContext getScriptContext() {
CodegenContext context = getContext();
while (!(context instanceof ScriptContext)) {
context = context.getParentContext();
}
return (ScriptContext) context;
}
private StackValue genLazy(KtElement expr, Type type) {
StackValue value = gen(expr);
return StackValue.coercion(value, type, null);
}
private StackValue genLazy(KtElement expr, Type type, KotlinType kotlinType) {
StackValue value = gen(expr);
return StackValue.coercion(value, type, kotlinType);
}
private StackValue genStatement(KtElement statement) {
return genQualified(StackValue.none(), statement, statementVisitor);
}
@Override
public StackValue visitClass(@NotNull KtClass klass, StackValue data) {
return visitClassOrObject(klass);
}
@Override
public StackValue visitTypeAlias(@NotNull KtTypeAlias typeAlias, StackValue data) {
return StackValue.none();
}
private StackValue visitClassOrObject(KtClassOrObject declaration) {
ClassDescriptor descriptor = bindingContext.get(CLASS, declaration);
assert descriptor != null;
Type asmType = asmTypeForAnonymousClass(bindingContext, declaration);
ClassBuilder classBuilder = state.getFactory().newVisitor(JvmDeclarationOriginKt.OtherOrigin(declaration, descriptor), asmType, declaration.getContainingFile());
ClassContext objectContext = context.intoAnonymousClass(descriptor, this, OwnerKind.IMPLEMENTATION);
new ImplementationBodyCodegen(declaration, objectContext, classBuilder, state, getParentCodegen(), /* isLocal = */ true).generate();
return StackValue.none();
}
@Override
public StackValue visitObjectDeclaration(@NotNull KtObjectDeclaration declaration, StackValue data) {
return visitClassOrObject(declaration);
}
@Override
public StackValue visitExpression(@NotNull KtExpression expression, StackValue receiver) {
throw new UnsupportedOperationException("Codegen for " + expression + " is not yet implemented");
}
@Override
public StackValue visitSuperExpression(@NotNull KtSuperExpression expression, StackValue data) {
return StackValue.thisOrOuter(this, getSuperCallLabelTarget(context, expression), true, false);
}
@NotNull
public static ClassDescriptor getSuperCallLabelTarget(
@NotNull CodegenContext<?> context,
@NotNull KtSuperExpression expression
) {
KotlinType thisTypeForSuperCall = context.getState().getBindingContext().get(BindingContext.THIS_TYPE_FOR_SUPER_EXPRESSION, expression);
assert thisTypeForSuperCall != null : "This type for superCall ''" + expression.getText() + "'' should be not null!";
ClassifierDescriptor descriptor = thisTypeForSuperCall.getConstructor().getDeclarationDescriptor();
assert descriptor instanceof ClassDescriptor :
"'This' reference target for ''" + expression.getText() + "''should be class descriptor, but was " + descriptor;
return (ClassDescriptor) descriptor;
}
@NotNull
public Type asmType(@NotNull KotlinType type) {
return typeMapper.mapType(type);
}
@NotNull
public Type expressionType(@Nullable KtExpression expression) {
return CodegenUtilKt.asmType(expression, typeMapper, bindingContext);
}
@Nullable
public KotlinType kotlinType(@Nullable KtExpression expression) {
return CodegenUtilKt.kotlinType(expression, bindingContext);
}
@Override
public StackValue visitParenthesizedExpression(@NotNull KtParenthesizedExpression expression, StackValue receiver) {
return genQualified(receiver, expression.getExpression());
}
@Override
public StackValue visitAnnotatedExpression(@NotNull KtAnnotatedExpression expression, StackValue receiver) {
return genQualified(receiver, expression.getBaseExpression());
}
private static boolean isEmptyExpression(@Nullable KtElement expr) {
if (expr == null) {
return true;
}
if (expr instanceof KtBlockExpression) {
KtBlockExpression blockExpression = (KtBlockExpression) expr;
List<KtExpression> statements = blockExpression.getStatements();
if (statements.size() == 0 || statements.size() == 1 && isEmptyExpression(statements.get(0))) {
return true;
}
}
return false;
}
@Override
public StackValue visitIfExpression(@NotNull KtIfExpression expression, StackValue receiver) {
return generateIfExpression(expression, false);
}
/* package */ StackValue generateIfExpression(@NotNull KtIfExpression expression, boolean isStatement) {
Type asmType = isStatement ? Type.VOID_TYPE : expressionType(expression);
KotlinType kotlinType = isStatement ? null : kotlinType(expression);
StackValue condition = gen(expression.getCondition());
KtExpression thenExpression = expression.getThen();
KtExpression elseExpression = expression.getElse();
if (isEmptyExpression(thenExpression)) {
if (isEmptyExpression(elseExpression)) {
return StackValue.coercion(condition, asmType, kotlinType);
}
return generateSingleBranchIf(condition, expression, elseExpression, false, isStatement);
}
else {
if (isEmptyExpression(elseExpression)) {
return generateSingleBranchIf(condition, expression, thenExpression, true, isStatement);
}
}
return StackValue.operation(asmType, v -> {
Label elseLabel = new Label();
BranchedValue.Companion.condJump(condition, elseLabel, true, v);
Label end = new Label();
gen(thenExpression, asmType, kotlinType);
v.goTo(end);
v.mark(elseLabel);
gen(elseExpression, asmType, kotlinType);
markLineNumber(expression, isStatement);
v.mark(end);
return Unit.INSTANCE;
});
}
@Override
public StackValue visitWhileExpression(@NotNull KtWhileExpression expression, StackValue receiver) {
return StackValue.operation(Type.VOID_TYPE, adapter -> {
generateWhile(expression);
return Unit.INSTANCE;
});
}
private void generateWhile(@NotNull KtWhileExpression expression) {
Label condition = new Label();
v.mark(condition);
Label end = new Label();
blockStackElements.push(new LoopBlockStackElement(end, condition, targetLabel(expression)));
StackValue conditionValue = gen(expression.getCondition());
BranchedValue.Companion.loopJump(conditionValue, end, true, v);
generateLoopBody(expression.getBody());
markStartLineNumber(expression);
v.goTo(condition);
v.mark(end);
blockStackElements.pop();
}
@Override
public StackValue visitDoWhileExpression(@NotNull KtDoWhileExpression expression, StackValue receiver) {
return StackValue.operation(Type.VOID_TYPE, adapter -> {
generateDoWhile(expression);
return Unit.INSTANCE;
});
}
private void generateDoWhile(@NotNull KtDoWhileExpression expression) {
Label beginLoopLabel = new Label();
v.mark(beginLoopLabel);
Label breakLabel = new Label();
Label continueLabel = new Label();
blockStackElements.push(new LoopBlockStackElement(breakLabel, continueLabel, targetLabel(expression)));
PseudoInsnsKt.fakeAlwaysFalseIfeq(v, continueLabel);
PseudoInsnsKt.fakeAlwaysFalseIfeq(v, breakLabel);
KtExpression body = expression.getBody();
KtExpression condition = expression.getCondition();
StackValue conditionValue;
StackValueWithLeaveTask leaveTask = null;
if (body instanceof KtBlockExpression) {
// If body's a block, it can contain variable declarations which may be used in the condition of a do-while loop.
// We handle this case separately because otherwise such variable will be out of the frame map after the block ends
List<KtExpression> doWhileStatements = ((KtBlockExpression) body).getStatements();
List<KtExpression> statements = new ArrayList<>(doWhileStatements.size() + 1);
statements.addAll(doWhileStatements);
statements.add(condition);
//Need to split leave task and condition cause otherwise BranchedValue optimizations wouldn't work
leaveTask = generateBlock(statements, false, continueLabel, null);
conditionValue = leaveTask.getStackValue();
}
else {
if (body != null) {
gen(body, Type.VOID_TYPE);
}
v.mark(continueLabel);
conditionValue = gen(condition);
}
BranchedValue.Companion.loopJump(conditionValue, beginLoopLabel, false, v);
if (leaveTask != null) {
leaveTask.getLeaveTasks().invoke(conditionValue);
}
v.mark(breakLabel);
blockStackElements.pop();
}
@Override
public StackValue visitForExpression(@NotNull KtForExpression forExpression, StackValue receiver) {
return StackValue.operation(Type.VOID_TYPE, adapter -> {
generateFor(forExpression);
return Unit.INSTANCE;
});
}
private void generateFor(@NotNull KtForExpression forExpression) {
KtExpression range = forExpression.getLoopRange();
assert range != null : "No loop range in for expression";
RangeValue rangeValue = RangeValuesKt.createRangeValueForExpression(this, range);
generateForLoop(rangeValue.createForLoopGenerator(this, forExpression));
}
@NotNull
public static KotlinType getExpectedReceiverType(@NotNull ResolvedCall<? extends CallableDescriptor> resolvedCall) {
ReceiverParameterDescriptor extensionReceiver = resolvedCall.getResultingDescriptor().getExtensionReceiverParameter();
assert extensionReceiver != null : "Extension receiver should be non-null";
return extensionReceiver.getType();
}
@Nullable
public static KtExpression getSingleArgumentExpression(@NotNull ResolvedCall<? extends CallableDescriptor> resolvedCall) {
List<ResolvedValueArgument> resolvedValueArguments = resolvedCall.getValueArgumentsByIndex();
if (resolvedValueArguments == null) return null;
if (resolvedValueArguments.size() != 1) return null;
List<ValueArgument> valueArguments = resolvedValueArguments.get(0).getArguments();
if (valueArguments.size() != 1) return null;
return valueArguments.get(0).getArgumentExpression();
}
private OwnerKind contextKind() {
return context.getContextKind();
}
private void generateForLoop(ForLoopGenerator generator) {
Label loopExit = new Label();
Label loopEntry = new Label();
Label continueLabel = new Label();
generator.beforeLoop();
generator.checkEmptyLoop(loopExit);
v.mark(loopEntry);
generator.checkPreCondition(loopExit);
// Some forms of for-loop can be optimized as post-condition loops.
PseudoInsnsKt.fakeAlwaysFalseIfeq(v, continueLabel);
generator.beforeBody();
blockStackElements.push(new LoopBlockStackElement(loopExit, continueLabel, targetLabel(generator.getForExpression())));
generator.body();
blockStackElements.pop();
v.mark(continueLabel);
generator.afterBody(loopExit);
v.goTo(loopEntry);
v.mark(loopExit);
generator.afterLoop();
}
public void generateLoopBody(@Nullable KtExpression body) {
if (body != null) {
gen(body, Type.VOID_TYPE);
}
}
@Override
public StackValue visitBreakExpression(@NotNull KtBreakExpression expression, StackValue receiver) {
return generateBreakOrContinueExpression(expression, true, new Label());
}
@Override
public StackValue visitContinueExpression(@NotNull KtContinueExpression expression, StackValue receiver) {
return generateBreakOrContinueExpression(expression, false, new Label());
}
@NotNull
private StackValue generateBreakOrContinueExpression(
@NotNull KtExpressionWithLabel expression,
boolean isBreak,
@NotNull Label afterBreakContinueLabel
) {
assert expression instanceof KtContinueExpression || expression instanceof KtBreakExpression;
if (blockStackElements.isEmpty()) {
throw new UnsupportedOperationException("Target label for break/continue not found");
}
BlockStackElement stackElement = blockStackElements.peek();
if (stackElement instanceof FinallyBlockStackElement) {
FinallyBlockStackElement finallyBlockStackElement = (FinallyBlockStackElement) stackElement;
//noinspection ConstantConditions
genFinallyBlockOrGoto(finallyBlockStackElement, null, afterBreakContinueLabel);
}
else if (stackElement instanceof LoopBlockStackElement) {
LoopBlockStackElement loopBlockStackElement = (LoopBlockStackElement) stackElement;
KtSimpleNameExpression labelElement = expression.getTargetLabel();
//noinspection ConstantConditions
if (labelElement == null ||
loopBlockStackElement.targetLabel != null &&
labelElement.getReferencedName().equals(loopBlockStackElement.targetLabel.getReferencedName())) {
Label label = isBreak ? loopBlockStackElement.breakLabel : loopBlockStackElement.continueLabel;
return StackValue.operation(
Type.VOID_TYPE, adapter -> {
PseudoInsnsKt.fixStackAndJump(v, label);
v.mark(afterBreakContinueLabel);
return Unit.INSTANCE;
}
);
}
}
else {
throw new UnsupportedOperationException("Wrong BlockStackElement in processing stack");
}
blockStackElements.pop();
StackValue result = generateBreakOrContinueExpression(expression, isBreak, afterBreakContinueLabel);
blockStackElements.push(stackElement);
return result;
}
private StackValue generateSingleBranchIf(
StackValue condition,
KtIfExpression ifExpression,
KtExpression expression,
boolean inverse,
boolean isStatement
) {
Type targetType = isStatement ? Type.VOID_TYPE : expressionType(ifExpression);
KotlinType targetKotlinType = isStatement ? null : kotlinType(ifExpression);
return StackValue.operation(targetType, v -> {
Label elseLabel = new Label();
BranchedValue.Companion.condJump(condition, elseLabel, inverse, v);
if (isStatement) {
gen(expression, Type.VOID_TYPE);
v.mark(elseLabel);
}
else {
gen(expression, targetType, targetKotlinType);
Label end = new Label();
v.goTo(end);
v.mark(elseLabel);
StackValue.putUnitInstance(v);
markStartLineNumber(ifExpression);
v.mark(end);
}
return null;
});
}
@Override
public StackValue visitConstantExpression(@NotNull KtConstantExpression expression, StackValue receiver) {
ConstantValue<?> compileTimeValue = getPrimitiveOrStringCompileTimeConstant(expression);
assert compileTimeValue != null;
return StackValue.constant(compileTimeValue.getValue(), expressionType(expression), kotlinType(expression));
}
@Nullable
public ConstantValue<?> getCompileTimeConstant(@NotNull KtExpression expression) {
return getCompileTimeConstant(expression, bindingContext, state.getShouldInlineConstVals());
}
@Nullable
public ConstantValue<?> getPrimitiveOrStringCompileTimeConstant(@NotNull KtExpression expression) {
return getPrimitiveOrStringCompileTimeConstant(expression, bindingContext, state.getShouldInlineConstVals());
}
@Nullable
public static ConstantValue<?> getPrimitiveOrStringCompileTimeConstant(
@NotNull KtExpression expression,
@NotNull BindingContext bindingContext,
boolean shouldInlineConstVals) {
ConstantValue<?> constant = getCompileTimeConstant(expression, bindingContext, false, shouldInlineConstVals);
if (constant == null || ConstantExpressionEvaluatorKt.isStandaloneOnlyConstant(constant)) {
return null;
}
return constant;
}
@Nullable
public static ConstantValue<?> getCompileTimeConstant(
@NotNull KtExpression expression,
@NotNull BindingContext bindingContext,
boolean shouldInlineConstVals) {
return getCompileTimeConstant(expression, bindingContext, false, shouldInlineConstVals);
}
@Nullable
public static ConstantValue<?> getCompileTimeConstant(
@NotNull KtExpression expression,
@NotNull BindingContext bindingContext,
boolean takeUpConstValsAsConst,
boolean shouldInlineConstVals
) {
return JvmConstantsKt.getCompileTimeConstant(expression, bindingContext, takeUpConstValsAsConst, shouldInlineConstVals);
}
@Override
public StackValue visitStringTemplateExpression(@NotNull KtStringTemplateExpression expression, StackValue receiver) {
List<StringTemplateEntry> entries = preprocessStringTemplate(expression);
Type type = expressionType(expression);
if (entries.size() == 0) {
return StackValue.constant("", type);
}
else if (entries.size() == 1) {
StringTemplateEntry entry = entries.get(0);
if (entry instanceof StringTemplateEntry.Expression) {
KtExpression expr = ((StringTemplateEntry.Expression) entry).expression;
return genToString(gen(expr), expressionType(expr), kotlinType(expr));
}
else {
return StackValue.constant(((StringTemplateEntry.Constant) entry).value, type);
}
}
else {
return StackValue.operation(type, v -> {
genStringBuilderConstructor(v);
invokeAppendForEntries(v, entries);
v.invokevirtual("java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false);
return Unit.INSTANCE;
});
}
}
private void invokeAppendForEntries(InstructionAdapter v, List<StringTemplateEntry> entries) {
for (StringTemplateEntry entry : entries) {
if (entry instanceof StringTemplateEntry.Expression) {
invokeAppend(v, ((StringTemplateEntry.Expression) entry).expression);
}
else {
String value = ((StringTemplateEntry.Constant) entry).value;
if (value.length() == 1) {
v.iconst(value.charAt(0));
genInvokeAppendMethod(v, Type.CHAR_TYPE, null);
}
else {
v.aconst(value);
genInvokeAppendMethod(v, JAVA_STRING_TYPE, null);
}
}
}
}
private static abstract class StringTemplateEntry {
static class Constant extends StringTemplateEntry {
final String value;
Constant(String value) {
this.value = value;
}
}
static class Expression extends StringTemplateEntry {
final KtExpression expression;
Expression(KtExpression expression) {
this.expression = expression;
}
}
}
private @NotNull List<StringTemplateEntry> preprocessStringTemplate(@NotNull KtStringTemplateExpression expression) {
KtStringTemplateEntry[] entries = expression.getEntries();
List<StringTemplateEntry> result = new ArrayList<>(entries.length);
StringBuilder constantValue = new StringBuilder("");
for (KtStringTemplateEntry entry : entries) {
if (entry instanceof KtLiteralStringTemplateEntry) {
constantValue.append(entry.getText());
}
else if (entry instanceof KtEscapeStringTemplateEntry) {
constantValue.append(((KtEscapeStringTemplateEntry) entry).getUnescapedValue());
}
else if (entry instanceof KtStringTemplateEntryWithExpression) {
KtExpression entryExpression = entry.getExpression();
if (entryExpression == null) throw new AssertionError("No expression in " + entry);
ConstantValue<?> compileTimeConstant = getPrimitiveOrStringCompileTimeConstant(entryExpression);
if (compileTimeConstant != null && isConstantValueInlinableInStringTemplate(compileTimeConstant)) {
constantValue.append(String.valueOf(compileTimeConstant.getValue()));
}
else {
String accumulatedConstantValue = constantValue.toString();
if (accumulatedConstantValue.length() > 0) {
result.add(new StringTemplateEntry.Constant(accumulatedConstantValue));
}
constantValue.setLength(0);
result.add(new StringTemplateEntry.Expression(entryExpression));
}
}
else {
throw new AssertionError("Unexpected string template entry: " + entry);
}
}
String leftoverConstantValue = constantValue.toString();
if (leftoverConstantValue.length() > 0) {
result.add(new StringTemplateEntry.Constant(leftoverConstantValue));
}
return result;
}
private static boolean isConstantValueInlinableInStringTemplate(@NotNull ConstantValue<?> constant) {
return constant instanceof StringValue ||
constant instanceof BooleanValue ||
constant instanceof DoubleValue ||
constant instanceof FloatValue ||
constant instanceof IntegerValueConstant ||
constant instanceof NullValue;
}
@Override
public StackValue visitBlockExpression(@NotNull KtBlockExpression expression, StackValue receiver) {
return generateBlock(expression, false);
}
@Override
public StackValue visitNamedFunction(@NotNull KtNamedFunction function, StackValue data) {
return visitNamedFunction(function, data, false);
}
public StackValue visitNamedFunction(@NotNull KtNamedFunction function, StackValue data, boolean isStatement) {
assert data == StackValue.none();
if (KtPsiUtil.isScriptDeclaration(function)) {
return StackValue.none();
}
StackValue closure = genClosure(function, null);
if (isStatement) {
DeclarationDescriptor descriptor = bindingContext.get(DECLARATION_TO_DESCRIPTOR, function);
int index = lookupLocalIndex(descriptor);
closure.put(OBJECT_TYPE, null, v);
v.store(index, OBJECT_TYPE);
return StackValue.none();
}
else {
return closure;
}
}
@Override
public StackValue visitLambdaExpression(@NotNull KtLambdaExpression expression, StackValue receiver) {
if (Boolean.TRUE.equals(bindingContext.get(BLOCK, expression))) {
return gen(expression.getFunctionLiteral().getBodyExpression());
}
else {
return genClosure(expression.getFunctionLiteral(), null);
}
}
@NotNull
private StackValue genClosure(KtDeclarationWithBody declaration, @Nullable SamType samType) {
FunctionDescriptor descriptor = bindingContext.get(FUNCTION, declaration);
assert descriptor != null : "Function is not resolved to descriptor: " + declaration.getText();
return genClosure(
declaration, descriptor, new ClosureGenerationStrategy(state, declaration), samType, null, null
);
}
@NotNull
private StackValue genClosure(
@NotNull KtElement declaration,
@NotNull FunctionDescriptor descriptor,
@NotNull FunctionGenerationStrategy strategy,
@Nullable SamType samType,