-
Notifications
You must be signed in to change notification settings - Fork 274
/
Copy pathJavaCodeGenerator.cs
4375 lines (4011 loc) · 191 KB
/
JavaCodeGenerator.cs
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 by the contributors to the Dafny Project
// SPDX-License-Identifier: MIT
//
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.IO;
using System.Diagnostics.Contracts;
using System.Collections.ObjectModel;
using System.CommandLine;
using System.Text.RegularExpressions;
using JetBrains.Annotations;
using static Microsoft.Dafny.ConcreteSyntaxTreeUtils;
namespace Microsoft.Dafny.Compilers {
public class JavaCodeGenerator : SinglePassCodeGenerator {
public JavaCodeGenerator(DafnyOptions options, ErrorReporter reporter) : base(options, reporter) {
IntSelect = ",java.math.BigInteger";
LambdaExecute = ".apply";
}
public override IReadOnlySet<Feature> UnsupportedFeatures => new HashSet<Feature> {
Feature.Iterators,
Feature.SubsetTypeTests,
Feature.MethodSynthesis,
Feature.TuplesWiderThan20,
Feature.ArraysWithMoreThan16Dims,
Feature.ArrowsWithMoreThan16Arguments,
Feature.RuntimeCoverageReport,
};
const string DafnySetClass = "dafny.DafnySet";
const string DafnyMultiSetClass = "dafny.DafnyMultiset";
const string DafnySeqClass = "dafny.DafnySequence";
const string DafnyMapClass = "dafny.DafnyMap";
const string DafnyBigRationalClass = "dafny.BigRational";
const string DafnyEuclideanClass = "dafny.DafnyEuclidean";
const string DafnyHelpersClass = "dafny.Helpers";
const string DafnyTypeDescriptor = "dafny.TypeDescriptor";
string FormatDefaultTypeParameterValue(TypeParameter tp) => FormatDefaultTypeParameterValueName(tp.GetCompileName(Options));
static string FormatDefaultTypeParameterValueName(string tpName) => $"_default_{tpName}";
const string DafnyFunctionIfacePrefix = "dafny.Function";
const string DafnyMultiArrayClassPrefix = "dafny.Array";
const string DafnyTupleClassPrefix = "dafny.Tuple";
// Reserved name for Get method in co-datatypes. Starts with _ to avoid name clash
// with user-defined method
const string CoDatatypeGet = "_Get";
string DafnyMultiArrayClass(int dim) => DafnyMultiArrayClassPrefix + dim;
string DafnyTupleClass(int size) => DafnyTupleClassPrefix + size;
string DafnyFunctionIface(int arity) =>
arity == 1 ? "java.util.function.Function" : DafnyFunctionIfacePrefix + arity;
static string FormatExternBaseClassName(string externClassName) =>
$"_ExternBase_{externClassName}";
static string FormatTypeDescriptorVariable(string typeVarName) =>
$"_td_{typeVarName}";
string FormatTypeDescriptorVariable(TypeParameter tp) =>
FormatTypeDescriptorVariable(tp.GetCompileName(Options));
const string TypeMethodName = "_typeDescriptor";
private string ModuleName;
private string ModulePath;
private readonly List<GenericCompilationInstrumenter> Instrumenters = new();
public void AddInstrumenter(GenericCompilationInstrumenter compilationInstrumenter) {
Instrumenters.Add(compilationInstrumenter);
}
protected override bool UseReturnStyleOuts(Method m, int nonGhostOutCount) => true;
protected override bool SupportsAmbiguousTypeDecl => false;
protected override bool SupportsProperties => false;
private enum JavaNativeType { Byte, Short, Int, Long }
private static JavaNativeType AsJavaNativeType(NativeType.Selection sel) {
switch (sel) {
case NativeType.Selection.Byte:
case NativeType.Selection.SByte:
return JavaNativeType.Byte;
case NativeType.Selection.Short:
case NativeType.Selection.UShort:
return JavaNativeType.Short;
case NativeType.Selection.Int:
case NativeType.Selection.UInt:
return JavaNativeType.Int;
case NativeType.Selection.Long:
case NativeType.Selection.ULong:
return JavaNativeType.Long;
default:
Contract.Assert(false);
throw new cce.UnreachableException();
}
}
private static bool IsUnsignedJavaNativeType(NativeType nt) {
Contract.Requires(nt != null);
switch (nt.Sel) {
case NativeType.Selection.Byte:
case NativeType.Selection.UShort:
case NativeType.Selection.UInt:
case NativeType.Selection.ULong:
return true;
default:
return false;
}
}
private static JavaNativeType AsJavaNativeType(NativeType nt) {
return AsJavaNativeType(nt.Sel);
}
private JavaNativeType? AsJavaNativeType(Type type) {
var nt = AsNativeType(type);
if (nt == null) {
return null;
} else {
return AsJavaNativeType(nt);
}
}
protected override void DeclareSpecificOutCollector(string collectorVarName, ConcreteSyntaxTree wr, List<Type> formalTypes, List<Type> lhsTypes) {
// If the method returns an array of parameter type, and we're assigning
// to a variable with a more specific type, we need to insert a cast:
//
// Array<Integer> outcollector42 = obj.Method(); // <-- you are here
// int[] out43 = (int[]) outcollector42.unwrap();
var returnedTypes = new List<string>();
Contract.Assert(formalTypes.Count == lhsTypes.Count);
for (var i = 0; i < formalTypes.Count; i++) {
var formalType = formalTypes[i];
var lhsType = lhsTypes[i];
if (formalType.IsArrayType && formalType.AsArrayType.Dims == 1 && UserDefinedType.ArrayElementType(formalType).IsTypeParameter) {
returnedTypes.Add("java.lang.Object");
} else {
returnedTypes.Add(TypeName(lhsType, wr, Token.NoToken, boxed: formalTypes.Count > 1));
}
}
if (formalTypes.Count > 1) {
wr.Write($"{DafnyTupleClass(formalTypes.Count)}<{Util.Comma(returnedTypes)}> {collectorVarName} = ");
} else {
wr.Write($"{returnedTypes[0]} {collectorVarName} = ");
}
}
protected override void EmitCastOutParameterSplits(string outCollector, List<string> lhsNames,
ConcreteSyntaxTree wr, List<Type> formalTypes, List<Type> lhsTypes, IOrigin tok) {
var wOuts = new List<ConcreteSyntaxTree>();
for (var i = 0; i < lhsNames.Count; i++) {
wr.Write($"{lhsNames[i]} = ");
//
// Suppose we have:
//
// method Foo<A>(a : A) returns (arr : array<A>)
//
// This is compiled to:
//
// public <A> Object Foo(A a)
//
// (There's also an argument for the type descriptor, but I'm omitting
// it for clarity.) Foo returns Object, not A[], since A could be
// primitive and primitives cannot be generic parameters in Java
// (*sigh*). So when we call it:
//
// var arr : int[] := Foo(42);
//
// we have to add a type cast:
//
// BigInteger[] arr = (BigInteger[]) Foo(new BigInteger(42));
//
// Things can get more complicated than this, however. If the method returns
// the array as part of a tuple:
//
// method Foo<A>(a : A) returns (pair : (array<A>, array<A>))
//
// then we get:
//
// public <A> Tuple2<Object, Object> Foo(A a)
//
// and we have to write:
//
// BigInteger[] arr = (Pair<BigInteger[], BigInteger[]>) (Object) Foo(new BigInteger(42));
//
// (Note the extra cast to Object, since Java doesn't allow a cast to
// change a type parameter, as that's unsound in general. It just
// happens to be okay here!)
//
// Rather than try and exhaustively check for all the circumstances
// where a cast is necessary, for the moment we just always cast to the
// LHS type via Object, which is redundant 99% of the time but not
// harmful.
if (lhsTypes[i] == null) {
wr.Write($"(Object) ");
} else {
wr.Write($"({TypeName(lhsTypes[i], wr, Token.NoToken)}) (Object) ");
}
if (lhsNames.Count == 1) {
wr.Write(outCollector);
} else {
wr.Write($"{outCollector}.dtor__{i}()");
}
EndStmt(wr);
}
}
protected override void EmitSeqSelect(SingleAssignStmt s0, List<Type> tupleTypeArgsList, ConcreteSyntaxTree wr, string tup) {
wr.Write("(");
var lhs = (SeqSelectExpr)s0.Lhs;
EmitIndexCollectionUpdate(lhs.Seq.Type, out var wColl, out var wIndex, out var wValue, wr, nativeIndex: true);
var wCoerce = EmitCoercionIfNecessary(from: NativeObjectType, to: lhs.Seq.Type, tok: s0.Origin, wr: wColl);
wCoerce.Write($"({TypeName(lhs.Seq.Type.NormalizeExpand(), wCoerce, s0.Origin)})");
EmitTupleSelect(tup, 0, wCoerce);
wColl.Write(")");
var wCast = EmitCoercionToNativeInt(wIndex);
EmitTupleSelect(tup, 1, wCast);
wValue.Write($"({TypeName(tupleTypeArgsList[2].NormalizeExpand(), wValue, s0.Origin)})");
EmitTupleSelect(tup, 2, wValue);
EndStmt(wr);
}
protected override void EmitMultiSelect(SingleAssignStmt s0, List<Type> tupleTypeArgsList, ConcreteSyntaxTree wr, string tup, int L) {
var arrayType = tupleTypeArgsList[0];
var rhsType = tupleTypeArgsList[L - 1];
var lhs = (MultiSelectExpr)s0.Lhs;
var indices = new List<Action<ConcreteSyntaxTree>>();
for (var i = 0; i < lhs.Indices.Count; i++) {
var wIndex = new ConcreteSyntaxTree();
wIndex.Write("((java.math.BigInteger)");
EmitTupleSelect(tup, i + 1, wIndex);
wIndex.Write(")");
indices.Add(wr => wr.Write(wIndex.ToString()));
}
var (wArray, wRhs) = EmitArrayUpdate(indices, rhsType, wr);
wArray = EmitCoercionIfNecessary(from: null, to: arrayType, tok: s0.Origin, wr: wArray);
wArray.Write($"({TypeName(arrayType.NormalizeExpand(), wArray, s0.Origin)})");
EmitTupleSelect(tup, 0, wArray);
wRhs.Write($"({TypeName(rhsType, wr, s0.Origin)})");
EmitTupleSelect(tup, L - 1, wRhs);
EndStmt(wr);
}
protected override void WriteCast(string s, ConcreteSyntaxTree wr) {
wr.Write($"({s})");
}
protected override ConcreteSyntaxTree EmitIngredients(ConcreteSyntaxTree wr, string ingredients, int L, string tupleTypeArgs, ForallStmt s, SingleAssignStmt s0, Expression rhs) {
var wStmts = wr.Fork();
var wrVarInit = wr;
wrVarInit.Write($"java.util.ArrayList<{DafnyTupleClass(L)}<{tupleTypeArgs}>> {ingredients} = ");
Contract.Assert(L <= MaxTupleNonGhostDims);
EmitEmptyTupleList(tupleTypeArgs, wrVarInit);
var wrOuter = wr;
wr = CompileGuardedLoops(s.BoundVars, s.Bounds, s.Range, wr);
var wrTuple = EmitAddTupleToList(ingredients, tupleTypeArgs, wr);
wrTuple.Write($"{L}<{tupleTypeArgs}>(");
if (s0.Lhs is MemberSelectExpr lhs1) {
wrTuple.Append(Expr(lhs1.Obj, false, wStmts));
} else if (s0.Lhs is SeqSelectExpr lhs2) {
wrTuple.Append(Expr(lhs2.Seq, false, wStmts));
wrTuple.Write(", ");
TrParenExpr(lhs2.E0, wrTuple, false, wStmts);
} else {
var lhs = (MultiSelectExpr)s0.Lhs;
wrTuple.Append(Expr(lhs.Array, false, wStmts));
foreach (var t in lhs.Indices) {
wrTuple.Write(", ");
TrParenExpr(t, wrTuple, false, wStmts);
}
}
wrTuple.Write(", ");
if (rhs is MultiSelectExpr) {
Type t = rhs.Type.NormalizeExpand();
wrTuple.Write($"({TypeName(t, wrTuple, rhs.Origin)})");
}
wrTuple.Append(Expr(rhs, false, wStmts));
return wrOuter;
}
protected override void EmitHeader(Program program, ConcreteSyntaxTree wr) {
if (Options.IncludeRuntime) {
EmitRuntimeSource("DafnyRuntimeJava", wr);
}
if (Options.Get(CommonOptionBag.UseStandardLibraries) && Options.Get(CommonOptionBag.TranslateStandardLibrary)) {
EmitRuntimeSource("DafnyStandardLibraries_java", wr);
}
wr.WriteLine($"// Dafny program {program.Name} compiled into Java");
ModuleName = program.MainMethod != null ? "main" : Path.GetFileNameWithoutExtension(program.Name);
wr.WriteLine();
}
protected override void EmitBuiltInDecls(SystemModuleManager systemModuleManager, ConcreteSyntaxTree wr) {
switch (Options.SystemModuleTranslationMode) {
case CommonOptionBag.SystemModuleMode.Omit: {
CheckCommonSytemModuleLimits(systemModuleManager);
return;
}
case CommonOptionBag.SystemModuleMode.OmitAllOtherModules: {
CheckSystemModulePopulatedToCommonLimits(systemModuleManager);
break;
}
}
foreach (var kv in systemModuleManager.ArrowTypeDecls) {
var arity = kv.Key;
CreateLambdaFunctionInterface(arity, wr);
}
foreach (var decl in systemModuleManager.SystemModule.TopLevelDecls) {
if (decl is ArrayClassDecl classDecl) {
var dims = classDecl.Dims;
CreateDafnyArrays(dims, wr);
}
}
}
public static string TransformToClassName(string baseName) {
baseName = PublicIdProtectAux(baseName);
var sanitizedName = Regex.Replace(baseName, "[^_A-Za-z0-9$]", "_");
if (!Regex.IsMatch(sanitizedName, "^[_A-Za-z]")) {
sanitizedName = "_" + sanitizedName;
}
return sanitizedName;
}
public override void EmitCallToMain(Method mainMethod, string baseName, ConcreteSyntaxTree wr) {
var className = TransformToClassName(baseName);
wr = wr.NewBlock($"public class {className}");
var companion = TypeName_Companion(UserDefinedType.FromTopLevelDeclWithAllBooleanTypeParameters(mainMethod.EnclosingClass), wr, mainMethod.Origin, mainMethod);
var wBody = wr.NewNamedBlock("public static void main(String[] args)");
var modName = mainMethod.EnclosingClass.EnclosingModuleDefinition.GetCompileName(Options) == "_module" ? "_System." : "";
companion = modName + companion;
Coverage.EmitSetup(wBody);
wBody.WriteLine($"{DafnyHelpersClass}.withHaltHandling(() -> {{ {companion}.__Main({DafnyHelpersClass}.{CharMethodQualifier}FromMainArguments(args)); }} );");
Coverage.EmitTearDown(wBody);
}
string IdProtectModule(string moduleName) {
return string.Join(".", moduleName.Split(".").Select(IdProtect));
}
protected override ConcreteSyntaxTree CreateModule(ModuleDefinition module, string moduleName, bool isDefault,
ModuleDefinition externModule,
string libraryName /*?*/, Attributes moduleAttributes, ConcreteSyntaxTree wr) {
moduleName = IdProtectModule(moduleName);
if (isDefault) {
// Fold the default module into the main module
moduleName = "_System";
}
var pkgName = libraryName ?? IdProtect(moduleName);
var path = pkgName.Replace('.', '/');
ModuleName = IdProtect(moduleName);
ModulePath = path;
return wr;
}
protected override void FinishModule() {
}
protected override void DeclareSubsetType(SubsetTypeDecl sst, ConcreteSyntaxTree wr) {
var cw = (ClassWriter)CreateClass(IdProtect(sst.EnclosingModuleDefinition.GetCompileName(Options)), sst, wr);
if (sst.WitnessKind == SubsetTypeDecl.WKind.Compiled) {
var sw = new ConcreteSyntaxTree(cw.InstanceMemberWriter.RelativeIndentLevel);
var wStmts = cw.InstanceMemberWriter.Fork();
sw.Append(Expr(sst.Witness, false, wStmts));
var witness = sw.ToString();
var typeName = TypeName(sst.Rhs, cw.StaticMemberWriter, sst.Origin);
if (sst.TypeArgs.Count == 0) {
cw.DeclareField("Witness", sst, true, true, sst.Rhs, sst.Origin, witness, null);
witness = "Witness";
}
cw.StaticMemberWriter.Write($"public static {TypeParameters(sst.TypeArgs, " ")}{typeName} defaultValue(");
var typeDescriptorParams = sst.TypeArgs.Where(NeedsTypeDescriptor);
cw.StaticMemberWriter.Write(typeDescriptorParams.Comma(TypeDescriptorVariableDeclaration));
var w = cw.StaticMemberWriter.NewBlock(")");
w.WriteLine($"return {witness};");
}
GenerateIsMethod(sst, cw.StaticMemberWriter);
}
private string TypeDescriptorVariableDeclaration(TypeParameter tp) {
return $"{DafnyTypeDescriptor}<{tp.GetCompileName(Options)}> {FormatTypeDescriptorVariable(tp.GetCompileName(Options))}";
}
protected class ClassWriter : IClassWriter {
public readonly JavaCodeGenerator CodeGenerator;
public readonly ConcreteSyntaxTree InstanceMemberWriter;
public readonly ConcreteSyntaxTree StaticMemberWriter;
public readonly ConcreteSyntaxTree CtorBodyWriter;
public ClassWriter(JavaCodeGenerator codeGenerator, ConcreteSyntaxTree instanceMemberWriter, ConcreteSyntaxTree ctorBodyWriter, ConcreteSyntaxTree staticMemberWriter = null) {
Contract.Requires(codeGenerator != null);
Contract.Requires(instanceMemberWriter != null);
this.CodeGenerator = codeGenerator;
this.InstanceMemberWriter = instanceMemberWriter;
this.CtorBodyWriter = ctorBodyWriter;
this.StaticMemberWriter = staticMemberWriter ?? instanceMemberWriter;
}
public ConcreteSyntaxTree Writer(bool isStatic, bool createBody, MemberDecl/*?*/ member) {
if (createBody) {
if (isStatic || (member != null && member.EnclosingClass is TraitDecl && CodeGenerator.NeedsCustomReceiver(member))) {
return StaticMemberWriter;
}
}
return InstanceMemberWriter;
}
public ConcreteSyntaxTree/*?*/ CreateMethod(Method m, List<TypeArgumentInstantiation> typeArgs, bool createBody, bool forBodyInheritance, bool lookasideBody) {
return CodeGenerator.CreateMethod(m, typeArgs, createBody, Writer(m.IsStatic, createBody, m), forBodyInheritance, lookasideBody);
}
public ConcreteSyntaxTree SynthesizeMethod(Method m, List<TypeArgumentInstantiation> typeArgs, bool createBody, bool forBodyInheritance, bool lookasideBody) {
throw new UnsupportedFeatureException(m.Origin, Feature.MethodSynthesis);
}
public ConcreteSyntaxTree/*?*/ CreateFunction(string name, List<TypeArgumentInstantiation> typeArgs, List<Formal> formals, Type resultType, IOrigin tok, bool isStatic, bool createBody, MemberDecl member, bool forBodyInheritance, bool lookasideBody) {
return CodeGenerator.CreateFunction(name, typeArgs, formals, resultType, tok, isStatic, createBody, member, Writer(isStatic, createBody, member), forBodyInheritance, lookasideBody);
}
public ConcreteSyntaxTree/*?*/ CreateGetter(string name, TopLevelDecl enclosingDecl, Type resultType, IOrigin tok, bool isStatic, bool isConst, bool createBody, MemberDecl/*?*/ member, bool forBodyInheritance) {
return CodeGenerator.CreateGetter(name, resultType, tok, isStatic, createBody, Writer(isStatic, createBody, member));
}
public ConcreteSyntaxTree/*?*/ CreateGetterSetter(string name, Type resultType, IOrigin tok, bool createBody, MemberDecl/*?*/ member, out ConcreteSyntaxTree setterWriter, bool forBodyInheritance) {
return CodeGenerator.CreateGetterSetter(name, resultType, tok, createBody, out setterWriter, Writer(false, createBody, member));
}
public void DeclareField(string name, TopLevelDecl enclosingDecl, bool isStatic, bool isConst, Type type, IOrigin tok, string rhs, Field field) {
CodeGenerator.DeclareField(name, isStatic, isConst, type, tok, rhs, this);
}
public void InitializeField(Field field, Type instantiatedFieldType, TopLevelDeclWithMembers enclosingClass) {
throw new cce.UnreachableException(); // InitializeField should be called only for those compilers that set ClassesRedeclareInheritedFields to false.
}
public ConcreteSyntaxTree/*?*/ ErrorWriter() => InstanceMemberWriter;
public void Finish() { }
}
protected override bool SupportsStaticsInGenericClasses => false;
protected ConcreteSyntaxTree CreateGetter(string name, Type resultType, IOrigin tok, bool isStatic,
bool createBody, ConcreteSyntaxTree wr) {
wr.Write("public {0}{1} {2}()", isStatic ? "static " : "", TypeName(resultType, wr, tok), name);
if (createBody) {
var w = wr.NewBlock("", null, BlockStyle.NewlineBrace, BlockStyle.NewlineBrace);
return w;
} else {
wr.WriteLine(";");
return null;
}
}
protected override void DeclareLocalVar(string name, Type /*?*/ type, IOrigin /*?*/ tok, Expression rhs,
bool inLetExprBody, ConcreteSyntaxTree wr) {
if (type == null) {
type = rhs.Type;
}
var wStmts = wr.Fork();
var w = DeclareLocalVar(name, type, tok, wr);
w.Append(Expr(rhs, inLetExprBody, wStmts));
}
public ConcreteSyntaxTree /*?*/ CreateGetterSetter(string name, Type resultType, IOrigin tok,
bool createBody, out ConcreteSyntaxTree setterWriter, ConcreteSyntaxTree wr) {
wr.Write($"public {TypeName(resultType, wr, tok)} {name}()");
ConcreteSyntaxTree wGet = null;
if (createBody) {
wGet = wr.NewBlock("", null, BlockStyle.NewlineBrace, BlockStyle.NewlineBrace);
} else {
wr.WriteLine(";");
}
wr.Write($"public void set_{name}({TypeName(resultType, wr, tok)} value)");
if (createBody) {
setterWriter = wr.NewBlock("", null, BlockStyle.NewlineBrace, BlockStyle.NewlineBrace);
} else {
wr.WriteLine(";");
setterWriter = null;
}
return wGet;
}
protected ConcreteSyntaxTree CreateMethod(Method m, List<TypeArgumentInstantiation> typeArgs, bool createBody, ConcreteSyntaxTree wr, bool forBodyInheritance, bool lookasideBody) {
if (!createBody && (m.IsStatic || m is Constructor)) {
// No need for an abstract version of a static method or a constructor
return null;
}
string targetReturnTypeReplacement = null;
int nonGhostOuts = 0;
int nonGhostIndex = 0;
for (int i = 0; i < m.Outs.Count; i++) {
if (!m.Outs[i].IsGhost) {
nonGhostOuts += 1;
nonGhostIndex = i;
}
}
if (nonGhostOuts == 1) {
targetReturnTypeReplacement = TypeName(m.Outs[nonGhostIndex].Type, wr, m.Outs[nonGhostIndex].Origin);
} else if (nonGhostOuts > 1) {
targetReturnTypeReplacement = DafnyTupleClass(nonGhostOuts);
}
var customReceiver = createBody && !forBodyInheritance && NeedsCustomReceiver(m);
var receiverType = UserDefinedType.FromTopLevelDecl(m.Origin, m.EnclosingClass);
foreach (var instrumenter in Instrumenters) {
instrumenter.BeforeMethod(m, wr);
}
wr.Write("public {0}{1}", !createBody && !(m.EnclosingClass is TraitDecl) ? "abstract " : "", m.IsStatic || customReceiver ? "static " : "");
wr.Write(TypeParameters(TypeArgumentInstantiation.ToFormals(ForTypeParameters(typeArgs, m, lookasideBody)), " "));
wr.Write("{0} {1}", targetReturnTypeReplacement ?? "void", IdName(m));
wr.Write("(");
var sep = "";
WriteRuntimeTypeDescriptorsFormals(ForTypeDescriptors(typeArgs, m.EnclosingClass, m, lookasideBody), wr, ref sep,
TypeDescriptorVariableDeclaration);
if (customReceiver) {
DeclareFormal(sep, "_this", receiverType, m.Origin, true, wr);
sep = ", ";
}
WriteFormals(sep, m.Ins, wr);
if (!createBody) {
wr.WriteLine(");");
return null; // We do not want to write a function body, so instead of returning a BTW, we return null.
} else {
return wr.NewBlock(")", null, BlockStyle.NewlineBrace, BlockStyle.NewlineBrace);
}
}
protected override ConcreteSyntaxTree EmitMethodReturns(Method m, ConcreteSyntaxTree wr) {
int nonGhostOuts = 0;
foreach (var t in m.Outs) {
if (t.IsGhost) {
continue;
}
nonGhostOuts += 1;
break;
}
if (!m.Body.Body.OfType<ReturnStmt>().Any() && (nonGhostOuts > 0 || m.IsTailRecursive)) { // If method has out parameters or is tail-recursive but no explicit return statement in Dafny
var beforeReturn = wr.NewBlock("if(true)"); // Ensure no unreachable error is thrown for the return statement
EmitReturn(m.Outs, wr);
return beforeReturn;
}
return wr;
}
protected ConcreteSyntaxTree/*?*/ CreateFunction(string name, List<TypeArgumentInstantiation> typeArgs,
List<Formal> formals, Type resultType, IOrigin tok, bool isStatic, bool createBody, MemberDecl member,
ConcreteSyntaxTree wr, bool forBodyInheritance, bool lookasideBody) {
if (!createBody && isStatic) {
// No need for abstract version of static method
return null;
}
var customReceiver = createBody && !forBodyInheritance && NeedsCustomReceiver(member);
var receiverType = UserDefinedType.FromTopLevelDecl(member.Origin, member.EnclosingClass);
wr.Write("public {0}{1}", !createBody && !(member.EnclosingClass is TraitDecl) ? "abstract " : "", isStatic || customReceiver ? "static " : "");
wr.Write(TypeParameters(TypeArgumentInstantiation.ToFormals(ForTypeParameters(typeArgs, member, lookasideBody)), " "));
wr.Write($"{TypeName(resultType, wr, tok)} {name}(");
var sep = "";
var argCount = WriteRuntimeTypeDescriptorsFormals(ForTypeDescriptors(typeArgs, member.EnclosingClass, member, lookasideBody), wr, ref sep, TypeDescriptorVariableDeclaration);
if (customReceiver) {
DeclareFormal(sep, "_this", receiverType, tok, true, wr);
sep = ", ";
argCount++;
}
argCount += WriteFormals(sep, formals, wr);
if (!createBody) {
wr.WriteLine(");");
return null; // We do not want to write a function body, so instead of returning a BTW, we return null.
} else {
ConcreteSyntaxTree w;
if (argCount > 1) {
w = wr.NewBlock(")", null, BlockStyle.NewlineBrace, BlockStyle.NewlineBrace);
} else {
w = wr.NewBlock(")");
}
return w;
}
}
protected void DeclareField(string name, bool isStatic, bool isConst, Type type, IOrigin tok, string rhs, ClassWriter cw) {
if (isStatic) {
var r = rhs ?? DefaultValue(type, cw.StaticMemberWriter, tok);
var t = StripTypeParameters(TypeName(type, cw.StaticMemberWriter, tok));
cw.StaticMemberWriter.WriteLine($"public static {t} {name} = {r};");
} else {
Contract.Assert(cw.CtorBodyWriter != null, "Unexpected instance field");
cw.InstanceMemberWriter.WriteLine("public {0} {1};", TypeName(type, cw.InstanceMemberWriter, tok), name);
cw.CtorBodyWriter.WriteLine("this.{0} = {1};", name, rhs ?? PlaceboValue(type, cw.CtorBodyWriter, tok));
}
}
private string StripTypeParameters(string s) {
Contract.Requires(s != null);
return Regex.Replace(s, @"<.+>", "");
}
private void EmitSuppression(ConcreteSyntaxTree wr) {
wr.WriteLine("@SuppressWarnings({\"unchecked\", \"deprecation\"})");
}
string TypeParameters(List<TypeParameter>/*?*/ targs, string suffix = "") {
Contract.Requires(targs == null || cce.NonNullElements(targs));
Contract.Ensures(Contract.Result<string>() != null);
if (targs == null || targs.Count == 0) {
return ""; // ignore suffix
}
return $"<{Util.Comma(targs, IdName)}>{suffix}";
}
internal override string TypeName(Type type, ConcreteSyntaxTree wr, IOrigin tok, MemberDecl/*?*/ member = null) {
return TypeName(type, wr, tok, boxed: false, member);
}
private string BoxedTypeName(Type type, ConcreteSyntaxTree wr, IOrigin tok) {
return TypeName(type, wr, tok, boxed: true);
}
private string ActualTypeArgument(Type type, TypeParameter.TPVariance variance, ConcreteSyntaxTree wr, IOrigin tok) {
Contract.Requires(type != null);
Contract.Requires(wr != null);
Contract.Requires(tok != null);
var typeName = BoxedTypeName(type, wr, tok);
if (variance == TypeParameter.TPVariance.Co) {
return "? extends " + typeName;
} else if (variance == TypeParameter.TPVariance.Contra) {
if (type.IsRefType) {
return "? super " + typeName;
}
}
return typeName;
}
private string BoxedTypeNames(List<Type> types, ConcreteSyntaxTree wr, IOrigin tok) {
return Util.Comma(types, t => BoxedTypeName(t, wr, tok));
}
protected override string TypeArgumentName(Type type, ConcreteSyntaxTree wr, IOrigin tok) {
return BoxedTypeName(type, wr, tok);
}
private string TypeName(Type type, ConcreteSyntaxTree wr, IOrigin tok, bool boxed, MemberDecl /*?*/ member = null) {
return TypeName(type, wr, tok, boxed, false, member);
}
private string CharTypeName(bool boxed) {
if (UnicodeCharEnabled) {
return boxed ? "dafny.CodePoint" : "int";
} else {
return boxed ? "Character" : "char";
}
}
private string TypeName(Type type, ConcreteSyntaxTree wr, IOrigin tok, bool boxed, bool erased, MemberDecl/*?*/ member = null) {
Contract.Ensures(Contract.Result<string>() != null);
Contract.Assume(type != null); // precondition; this ought to be declared as a Requires in the superclass
var xType = DatatypeWrapperEraser.SimplifyType(Options, type);
if (xType is BoolType) {
return boxed ? "Boolean" : "boolean";
} else if (xType is CharType) {
return CharTypeName(boxed);
} else if (xType is IntType or BigOrdinalType) {
return "java.math.BigInteger";
} else if (xType is RealType) {
return DafnyBigRationalClass;
} else if (xType is BitvectorType) {
var t = (BitvectorType)xType;
return t.NativeType != null ? GetNativeTypeName(t.NativeType, boxed) : "java.math.BigInteger";
} else if (member == null && xType.AsNewtype != null) {
var newtypeDecl = xType.AsNewtype;
if (newtypeDecl.NativeType is { } nativeType) {
return GetNativeTypeName(nativeType, boxed);
}
return TypeName(newtypeDecl.ConcreteBaseType(xType.TypeArgs), wr, tok, boxed, erased);
} else if (xType.IsObjectQ) {
return "Object";
} else if (xType.IsArrayType) {
ArrayClassDecl at = xType.AsArrayType;
Contract.Assert(at != null); // follows from type.IsArrayType
Type elType = UserDefinedType.ArrayElementType(xType);
return ArrayTypeName(elType, at.Dims, wr, tok, erased);
} else if (xType is UserDefinedType udt) {
if (udt.ResolvedClass is TypeParameter tp) {
if (thisContext != null && thisContext.ParentFormalTypeParametersToActuals.TryGetValue(tp, out var instantiatedTypeParameter)) {
return TypeName(instantiatedTypeParameter, wr, tok, true, member);
}
}
var s = FullTypeName(udt, member);
if (s.Equals("string")) {
return "String";
}
var cl = udt.ResolvedClass;
if (cl is TupleTypeDecl tupleDecl) {
s = DafnyTupleClass(tupleDecl.NonGhostDims);
}
// When accessing a static member, leave off the type arguments
if (member != null) {
return TypeName_UDT(s, new List<TypeParameter.TPVariance>(), new List<Type>(), wr, udt.Origin, erased);
} else {
return TypeName_UDT(s, udt, wr, udt.Origin, erased);
}
} else if (xType is SetType) {
var argType = ((SetType)xType).Arg;
if (erased) {
return DafnySetClass;
}
return $"{DafnySetClass}<{ActualTypeArgument(argType, TypeParameter.TPVariance.Co, wr, tok)}>";
} else if (xType is SeqType) {
var argType = ((SeqType)xType).Arg;
if (erased) {
return DafnySeqClass;
}
return $"{DafnySeqClass}<{ActualTypeArgument(argType, TypeParameter.TPVariance.Co, wr, tok)}>";
} else if (xType is MultiSetType) {
var argType = ((MultiSetType)xType).Arg;
if (erased) {
return DafnyMultiSetClass;
}
return $"{DafnyMultiSetClass}<{ActualTypeArgument(argType, TypeParameter.TPVariance.Co, wr, tok)}>";
} else if (xType is MapType) {
var domType = ((MapType)xType).Domain;
var ranType = ((MapType)xType).Range;
if (erased) {
return DafnyMapClass;
}
return $"{DafnyMapClass}<{ActualTypeArgument(domType, TypeParameter.TPVariance.Co, wr, tok)}, {ActualTypeArgument(ranType, TypeParameter.TPVariance.Co, wr, tok)}>";
} else {
Contract.Assert(false); throw new cce.UnreachableException(); // unexpected type
}
}
string ArrayTypeName(Type elType, int dims, ConcreteSyntaxTree wr, IOrigin tok, bool erased) {
elType = DatatypeWrapperEraser.SimplifyType(Options, elType);
if (dims > 1) {
if (erased) {
return DafnyMultiArrayClass(dims);
} else {
return $"{DafnyMultiArrayClass(dims)}<{ActualTypeArgument(elType, TypeParameter.TPVariance.Non, wr, tok)}>";
}
} else if (elType.IsTypeParameter) {
return "java.lang.Object";
} else {
return $"{TypeName(elType, wr, tok, false, erased)}[]";
}
}
protected string CollectionTypeUnparameterizedName(CollectionType ct) {
if (ct is SeqType) {
return DafnySeqClass;
} else if (ct is SetType) {
return DafnySetClass;
} else if (ct is MultiSetType) {
return DafnyMultiSetClass;
} else if (ct is MapType) {
return DafnyMapClass;
} else {
Contract.Assert(false); // unexpected collection type
throw new cce.UnreachableException(); // to please the compiler
}
}
protected override string FullTypeName(UserDefinedType udt, MemberDecl /*?*/ member = null) {
return FullTypeName(udt, member, false);
}
protected string FullTypeName(UserDefinedType udt, MemberDecl member, bool useCompanionName) {
Contract.Requires(udt != null);
if (udt.IsBuiltinArrowType) {
return DafnyFunctionIface(udt.TypeArgs.Count - 1);
}
if (member != null && member.IsExtern(Options, out var qualification, out _) && qualification != null) {
return qualification;
}
var cl = udt.ResolvedClass;
if (cl is NonNullTypeDecl nntd) {
cl = nntd.Class;
}
if (cl is TypeParameter) {
return IdProtect(udt.GetCompileName(Options));
} else if (cl is TupleTypeDecl tupleDecl) {
return DafnyTupleClass(tupleDecl.NonGhostDims);
} else if (cl is TraitDecl && useCompanionName) {
return IdProtect(udt.GetFullCompanionCompileName(Options));
} else if (cl.EnclosingModuleDefinition.GetCompileName(Options) == ModuleName || cl.EnclosingModuleDefinition.TryToAvoidName) {
return IdProtect(cl.GetCompileName(Options));
} else {
return IdProtectModule(cl.EnclosingModuleDefinition.GetCompileName(Options)) + "." + IdProtect(cl.GetCompileName(Options));
}
}
protected override void TypeName_SplitArrayName(Type type, out Type innermostElementType, out string brackets) {
Contract.Requires(type != null);
type = DatatypeWrapperEraser.SimplifyType(Options, type);
var at = type.AsArrayType;
if (at != null && at.Dims == 1 && !DatatypeWrapperEraser.SimplifyType(Options, type.TypeArgs[0]).IsTypeParameter) {
TypeName_SplitArrayName(type.TypeArgs[0], out innermostElementType, out brackets);
brackets = TypeNameArrayBrackets(at.Dims) + brackets;
} else {
innermostElementType = type;
brackets = "";
}
}
protected override string TypeNameArrayBrackets(int dims) {
return Util.Repeat(dims, "[]");
}
protected override bool DeclareFormal(string prefix, string name, Type type, IOrigin tok, bool isInParam, ConcreteSyntaxTree wr) {
if (!isInParam) {
return false;
}
wr.Write($"{prefix}{TypeName(type, wr, tok)} {name}");
return true;
}
protected override string TypeName_UDT(string fullCompileName, List<TypeParameter.TPVariance> variance, List<Type> typeArgs,
ConcreteSyntaxTree wr, IOrigin tok, bool omitTypeArguments) {
Contract.Assume(fullCompileName != null); // precondition; this ought to be declared as a Requires in the superclass
Contract.Assume(variance != null); // precondition; this ought to be declared as a Requires in the superclass
Contract.Assume(typeArgs != null); // precondition; this ought to be declared as a Requires in the superclass
Contract.Assume(variance.Count == typeArgs.Count);
string s = IdProtect(fullCompileName);
if (typeArgs.Count != 0 && !omitTypeArguments) {
s += "<" + BoxedTypeNames(typeArgs, wr, tok) + ">";
}
return s;
}
// We write an extern class as a base class that the actual extern class
// needs to extend, so the extern methods and functions need to be abstract
// in the base class
protected override bool IncludeExternallyImportedMembers => true;
//
// An example to show how type parameters are dealt with:
//
// class Class<T /* needs auto-initializer */, U /* does not */> {
// private String sT; // type descriptor for T
//
// // Fields are assigned in the constructor because some will
// // depend on a type parameter
// public T t;
// public U u;
//
// public Class(String sT) {
// this.sT = sT;
// this.t = dafny.Helpers.getDefault(sT);
// // Note: The field must be assigned a real value before being read!
// this.u = null;
// }
//
// public __ctor(U u) {
// this.u = u;
// }
// }
//
protected override IClassWriter CreateClass(string moduleName, bool isExtern, string /*?*/ fullPrintName,
List<TypeParameter> typeParameters, TopLevelDecl cls, List<Type> /*?*/ superClasses, IOrigin tok, ConcreteSyntaxTree wr) {
var name = IdName(cls);
var javaName = isExtern ? FormatExternBaseClassName(name) : name;
var filename = $"{ModulePath}/{javaName}.java";
var w = wr.NewFile(filename);
w.WriteLine($"// Class {javaName}");
w.WriteLine($"// Dafny class {name} compiled into Java");
w.WriteLine($"package {ModuleName};");
w.WriteLine();
//TODO: Fix implementations so they do not need this suppression
EmitSuppression(w);
foreach (var instrumenter in Instrumenters) {
instrumenter.BeforeClass(cls, w);
}
var abstractness = isExtern ? "abstract " : "";
w.Write($"public {abstractness}class {javaName}{TypeParameters(typeParameters)}");
string sep;
// Since Java does not support multiple inheritance, we are assuming a list of "superclasses" is a list of interfaces
if (superClasses != null) {
sep = " implements ";
foreach (var trait in superClasses) {
if (!trait.IsObject) {
w.Write($"{sep}{TypeName(trait, w, tok)}");
sep = ", ";
}
}
}
var wBody = w.NewBlock("");
var wTypeFields = wBody.Fork();
wBody.Write($"public {javaName}(");
var wCtorParams = wBody.Fork();
var wCtorBody = wBody.NewBlock(")", "");
EmitTypeDescriptorsForClass(typeParameters, cls, wTypeFields, wCtorParams, null, wCtorBody);
// make sure the (static fields associated with the) type method come after the Witness static field
var wTypeMethod = wBody;
var wRestOfBody = wBody.Fork();
if (cls is DefaultClassDecl || (
(cls is ClassLikeDecl and not ArrayClassDecl) &&
!Options.Get(JavaBackend.LegacyDataConstructors))) {
// don't emit a type-descriptor method
} else {
EmitTypeDescriptorMethod(cls, typeParameters, null, null, wTypeMethod);
}
if (fullPrintName != null) {
// By emitting a toString() method, printing an object will give the same output as with other target languages.
EmitToString(fullPrintName, wBody);
}
return new ClassWriter(this, wRestOfBody, wCtorBody);
}
/// <summary>
/// For each type parameter X in "typeParametersForClass" that needs a type descriptor,
/// * Write "protected TypeDescriptor<X> _td_X;" to wTypeFields
/// -- each entry is terminated by a newline
/// * Write "TypeDescriptor<X> _td_X" to wCtorParams
/// -- entries are separated by a comma
/// * Write "_td_X" to wCallArguments
/// -- entries are separated by a comma
/// * Write "this._td_X := _td_X;" to wCtorBody
/// -- each entry is terminated by a newline
/// Any of the writer parameters may be null, so long as at least one is non-null.
/// The method returns the number type descriptors written.
/// </summary>
int EmitTypeDescriptorsForClass(List<TypeParameter> typeParametersForClass, TopLevelDecl cls,
[CanBeNull] ConcreteSyntaxTree wTypeFields, [CanBeNull] ConcreteSyntaxTree wCtorParams,
[CanBeNull] ConcreteSyntaxTree wCallArguments, [CanBeNull] ConcreteSyntaxTree wCtorBody,
string namePrefix = null) {
namePrefix ??= "";
var wError = wTypeFields ?? wCtorParams ?? wCallArguments ?? wCtorBody;
int numberOfEmittedTypeDescriptors = 0;
if (typeParametersForClass != null) {
var sep = "";
foreach (var ta in TypeArgumentInstantiation.ListFromFormals(typeParametersForClass)) {
if (NeedsTypeDescriptor(ta.Formal)) {
var fieldName = FormatTypeDescriptorVariable(ta.Formal.GetCompileName(Options));
var paramName = TypeDescriptor(ta.Actual, wError, ta.Formal.Origin);
var decl = $"{DafnyTypeDescriptor}<{namePrefix}{BoxedTypeName(ta.Actual, wError, ta.Formal.Origin)}> {fieldName}";
wTypeFields?.WriteLine($"protected {decl};");
if (ta.Formal.Parent == cls) {
wCtorParams?.Write($"{sep}{decl}");
}
wCtorBody?.WriteLine($"this.{fieldName} = {paramName};");
wCallArguments?.Write($"{sep}{paramName}");
sep = ", ";
numberOfEmittedTypeDescriptors++;
}
}
}
return numberOfEmittedTypeDescriptors;
}
private void EmitToString(string fullPrintName, ConcreteSyntaxTree wr) {
wr.WriteLine("@Override");
wr.NewBlock("public java.lang.String toString()")
.WriteLine($"return \"{fullPrintName}\";");
}
/// <summary>
/// Generate the "_typeDescriptor" method for a generated class.
/// "enclosingType" is allowed to be "null", in which case the target values are assumed to be references.
/// If "enclosingType" is null, then "targetTypeName" is expected to be the name of the Java type representing the type.
/// If "enclosingType" is non-null, then "targetTypeName" is expected to be null.
/// </summary>
private void EmitTypeDescriptorMethod([CanBeNull] TopLevelDecl enclosingTypeDecl, List<TypeParameter> typeParams, string targetTypeName,
[CanBeNull] string initializer, ConcreteSyntaxTree wr) {
Contract.Requires((enclosingTypeDecl != null) != (targetTypeName != null));
string typeDescriptorExpr;
if (enclosingTypeDecl == null) {
Contract.Assert(targetTypeName != null);
// use reference type
typeDescriptorExpr = $"{DafnyTypeDescriptor}.referenceWithInitializer({StripTypeParameters(targetTypeName)}.class, () -> {initializer ?? "null"})";
} else {
Contract.Assert(targetTypeName == null);