forked from dafny-lang/dafny
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Compiler-go.cs
3853 lines (3495 loc) · 160 KB
/
Compiler-go.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.Text.RegularExpressions;
using JetBrains.Annotations;
using static Microsoft.Dafny.ConcreteSyntaxTreeUtils;
namespace Microsoft.Dafny.Compilers {
class GoCompiler : SinglePassCompiler {
public GoCompiler(DafnyOptions options, ErrorReporter reporter) : base(options, reporter) {
if (Options?.CoverageLegendFile != null) {
Imports.Add(new Import { Name = "DafnyProfiling", Path = "DafnyProfiling" });
}
}
public override IReadOnlySet<Feature> UnsupportedFeatures => new HashSet<Feature> {
Feature.MethodSynthesis,
Feature.ExternalConstructors,
Feature.SubsetTypeTests,
Feature.AllUnderscoreExternalModuleNames,
Feature.RuntimeCoverageReport
};
public override string ModuleSeparator => "_";
string FormatDefaultTypeParameterValue(TopLevelDecl tp) {
Contract.Requires(tp is TypeParameter || tp is AbstractTypeDecl);
return $"_default_{tp.GetCompileName(Options)}";
}
private readonly List<Import> Imports = new(StandardImports);
private string ModuleName;
private ConcreteSyntaxTree RootImportWriter;
private ConcreteSyntaxTree RootImportDummyWriter;
private string MainModuleName;
private static List<Import> StandardImports =
new List<Import> {
new Import { Name = "_dafny", Path = "dafny" },
new Import { Name = "os", Path = "os" },
};
private static string DummyTypeName = "Dummy__";
private struct Import {
public string Name, Path;
public ModuleDefinition ExternModule;
}
protected override void EmitHeader(Program program, ConcreteSyntaxTree wr) {
wr.WriteLine("// Dafny program {0} compiled into Go", program.Name);
ModuleName = MainModuleName = program.MainMethod != null ? "main" : TransformToClassName(Path.GetFileNameWithoutExtension(program.Name));
wr.WriteLine("package {0}", ModuleName);
wr.WriteLine();
// Keep the import writers so that we can import subsequent modules into the main one
EmitImports(wr, out RootImportWriter, out RootImportDummyWriter);
if (Options.IncludeRuntime) {
EmitRuntimeSource("DafnyRuntimeGo", wr);
}
}
private string DafnyTypeDescriptor => $"{HelperModulePrefix}TypeDescriptor";
// The implementation of seq<T> is now in DafnyRuntimeDafny/src/dafnyRuntime.dfy.
// We have to special-case compiling this code a little bit in places to work around
// features Dafny doesn't support, such as customizing the definition of equality.
private bool IsDafnySequence(TopLevelDecl d) =>
Options.Get(DeveloperOptionBag.Bootstrapping) && d.GetFullCompileName(Options) == "dafny.Sequence";
private string DafnySequenceCompanion => $"{HelperModulePrefix}Companion_Sequence_";
void EmitModuleHeader(ConcreteSyntaxTree wr) {
wr.WriteLine("// Package {0}", ModuleName);
wr.WriteLine("// Dafny module {0} compiled into Go", ModuleName);
wr.WriteLine();
wr.WriteLine("package {0}", ModuleName);
wr.WriteLine();
// This is a non-main module; it only imports things declared before it, so we don't need these writers
EmitImports(wr, out _, out _);
wr.WriteLine();
wr.WriteLine("type {0} struct{{}}", DummyTypeName);
wr.WriteLine();
}
void EmitImports(ConcreteSyntaxTree wr, out ConcreteSyntaxTree importWriter, out ConcreteSyntaxTree importDummyWriter) {
wr.WriteLine("import (");
importWriter = wr.Fork(1);
wr.WriteLine(")");
importDummyWriter = wr.Fork();
if (ModuleName != "dafny") {
foreach (var import in Imports) {
EmitImport(import, importWriter, importDummyWriter);
}
}
}
public static string TransformToClassName(string baseName) =>
Regex.Replace(baseName, "[^_A-Za-z0-9$]", "_");
public override void EmitCallToMain(Method mainMethod, string baseName, ConcreteSyntaxTree wr) {
var companion = TypeName_Companion(UserDefinedType.FromTopLevelDeclWithAllBooleanTypeParameters(mainMethod.EnclosingClass), wr, mainMethod.tok, mainMethod);
var wBody = wr.NewNamedBlock("func main()");
wBody.WriteLine("defer _dafny.CatchHalt()");
var idName = IssueCreateStaticMain(mainMethod) ? "Main" : IdName(mainMethod);
Coverage.EmitSetup(wBody);
wBody.WriteLine($"{companion}.{idName}({GetHelperModuleName()}.{CharMethodQualifier}FromMainArguments(os.Args))");
Coverage.EmitTearDown(wBody);
}
ConcreteSyntaxTree CreateDescribedSection(string desc, ConcreteSyntaxTree wr, params object[] args) {
var body = wr.Fork();
var str = string.Format(desc, args);
body.WriteLine("// Definition of {0}", str);
wr.WriteLine("// End of {0}", str);
return body;
}
protected override ConcreteSyntaxTree CreateStaticMain(IClassWriter cw, string argsParameterName) {
var wr = ((GoCompiler.ClassWriter)cw).ConcreteMethodWriter;
return wr.NewNamedBlock("func (_this * {0}) Main({1} _dafny.Sequence)", FormatCompanionTypeName(((GoCompiler.ClassWriter)cw).ClassName), argsParameterName);
}
private Import CreateImport(string moduleName, bool isDefault, ModuleDefinition externModule, string /*?*/ libraryName) {
string pkgName;
if (libraryName != null) {
pkgName = libraryName;
} else {
// Go ignores all filenames starting with underscores. So we're forced
// to rewrite "__default" to "default__".
pkgName = moduleName;
if (pkgName != "" && pkgName.All(c => c == '_')) {
throw new UnsupportedFeatureException(Token.NoToken, Feature.AllUnderscoreExternalModuleNames,
$"Cannot have a package name with only underscores: {pkgName}");
}
while (pkgName.StartsWith("_")) {
pkgName = pkgName.Substring(1) + "_";
}
}
return new Import { Name = moduleName, Path = pkgName, ExternModule = externModule };
}
protected override ConcreteSyntaxTree CreateModule(string moduleName, bool isDefault,
ModuleDefinition externModule,
string libraryName /*?*/, ConcreteSyntaxTree wr) {
if (isDefault) {
// Fold the default module into the main module
return wr;
}
var import = CreateImport(moduleName, isDefault, externModule, libraryName);
var filename = string.Format("{0}/{0}.go", import.Path);
var w = wr.NewFile(filename);
ModuleName = moduleName;
EmitModuleHeader(w);
AddImport(import);
return w;
}
protected override void DependOnModule(string moduleName, bool isDefault, ModuleDefinition externModule,
string libraryName) {
var import = CreateImport(moduleName, isDefault, externModule, libraryName);
AddImport(import);
}
protected override void FinishModule() {
ModuleName = MainModuleName;
}
private void AddImport(Import import) {
// Import in root module
EmitImport(import, RootImportWriter, RootImportDummyWriter);
// Import in all subsequent modules
Imports.Add(import);
}
private void EmitImport(Import import, ConcreteSyntaxTree importWriter, ConcreteSyntaxTree importDummyWriter) {
var id = IdProtect(import.Name);
var path = import.Path;
importWriter.WriteLine("{0} \"{1}\"", id, path);
bool isType;
string memberName = null;
if (id == "os") {
memberName = "Args";
isType = false;
} else {
isType = true;
if (import.ExternModule != null) {
var attributes = Attributes.Find(import.ExternModule.Attributes, "dummyImportMember");
if (attributes != null && attributes.Args.Count == 2) {
if (attributes.Args[0] is LiteralExpr expr1 && expr1.Value is string isNameValue &&
attributes.Args[1] is LiteralExpr expr2 && expr2.Value is bool isTypeValue) {
memberName = isNameValue;
isType = isTypeValue;
}
}
} else {
memberName = DummyTypeName;
}
}
if (memberName != null) {
if (isType) {
importDummyWriter.WriteLine("var _ {0}.{1}", id, memberName);
} else {
importDummyWriter.WriteLine("var _ = {0}.{1}", id, memberName);
}
}
}
protected override string GetHelperModuleName() => "_dafny";
private string HelperModulePrefix => ModuleName == "dafny" ? "" : $"{GetHelperModuleName()}.";
protected override IClassWriter CreateClass(string moduleName, string name, bool isExtern, string/*?*/ fullPrintName,
List<TypeParameter> typeParameters, TopLevelDecl cls, List<Type>/*?*/ superClasses, IToken tok, ConcreteSyntaxTree wr) {
var isDefaultClass = cls is DefaultClassDecl;
bool isSequence = superClasses.Any(superClass => superClass is UserDefinedType udt && IsDafnySequence(udt.ResolvedClass));
return CreateClass(cls, name, isExtern, fullPrintName, typeParameters, superClasses, tok, wr, includeRtd: !isDefaultClass, includeEquals: !isSequence, includeString: !isSequence);
}
// TODO Consider splitting this into two functions; most things seem to be passing includeRtd: false, includeEquals: false and includeString: true.
private GoCompiler.ClassWriter CreateClass(TopLevelDecl classContext, string name, bool isExtern, string/*?*/ fullPrintName, List<TypeParameter>/*?*/ typeParameters, List<Type>/*?*/ superClasses, IToken tok, ConcreteSyntaxTree wr, bool includeRtd, bool includeEquals, bool includeString) {
// See docs/Compilation/ReferenceTypes.md for a description of how instance members of classes and traits are compiled into Go.
//
// func New_Class_(Type0 _dafny.TypeDescriptor, Type1 _dafny.TypeDescriptor) *Class {
// _this := Class{}
//
// // Have to do it this way because some default values (namely type
// // parameters) assume that _this points to the current value
// _this.Type0 = Type0
// _this.Type1 = Type1
// _this.Field0 = ...
// _this.Field1 = ...
// return &_this
// }
//
// func (_this *Class) InstanceMethod(param0 type0, ...) returnType {
// ...
// }
//
// func (_this *CompanionStruct_Class) StaticMethod(param0 type0, ...) returnType {
// ...
// }
//
// func (*Class) String() string {
// return "module.Class"
// }
//
// func Type_Class_(Type0 _dafny.TypeDescriptor, Type1 _dafny.TypeDescriptor) _dafny.TypeDescriptor {
// return type_Class_{Type0, Type1}
// }
//
// type type_Class_ struct{
// Type0 _dafny.TypeDescriptor
// Type1 _dafny.TypeDescriptor
// }
//
// func (_this type_Class_) Default() any {
// return (*Class)(nil)
// }
//
// func (_this type_Class_) String() string {
// return "module.Class"
// }
//
name = Capitalize(name);
var w = CreateDescribedSection("class {0}", wr, name);
var instanceFieldWriter = w.NewBlock(string.Format("type {0} struct", name));
w.WriteLine();
CreateInitializer(classContext, name, w, out var instanceFieldInitWriter, out var traitInitWriter, out var rtdParamWriter);
var isNewtypeWithTraits = classContext is NewtypeDecl { ParentTraits: { Count: > 0 } };
var rtdCount = 0;
if (typeParameters != null) {
rtdCount = WriteRuntimeTypeDescriptorsFields(typeParameters, false, instanceFieldWriter, instanceFieldInitWriter, rtdParamWriter);
}
if (isNewtypeWithTraits) {
var udt = UserDefinedType.FromTopLevelDecl(classContext.tok, classContext);
rtdParamWriter.Write($"value {TypeName(udt, rtdParamWriter, classContext.tok)}");
}
w.WriteLine();
var staticFieldWriter = w.NewNamedBlock("type {0} struct", FormatCompanionTypeName(name));
var staticFieldInitWriter = w.NewNamedBlock("var {0} = {1}", FormatCompanionName(name), FormatCompanionTypeName(name));
if (includeEquals) {
// This Equals() is so simple that we could just use == instead, but uniformity is good and it'll get inlined anyway.
w.WriteLine();
var wEquals = w.NewNamedBlock("func (_this *{0}) Equals(other *{0}) bool", name);
wEquals.WriteLine("return _this == other");
w.WriteLine();
var wEqualsGeneric = w.NewNamedBlock("func (_this *{0}) EqualsGeneric(x interface{{}}) bool", name);
wEqualsGeneric.WriteLine("other, ok := x.(*{0})", name);
wEqualsGeneric.WriteLine("return ok && _this.Equals(other)");
}
w.WriteLine();
if (includeString) {
if (isNewtypeWithTraits) {
var wString = w.NewNamedBlock("func (_this *{0}) String() string", name);
wString.WriteLine("return _dafny.String(_this._value)");
} else {
var wString = w.NewNamedBlock("func (*{0}) String() string", name);
// Be consistent with other back ends, which don't fold _module into the main module
var module = ModuleName == MainModuleName ? "_module" : ModuleName;
wString.WriteLine("return \"{0}.{1}\"", module, name);
}
}
if (includeRtd) {
CreateRTD(name, typeParameters, out var wDefault, w);
wDefault.WriteLine("return (*{0})(nil)", name);
}
var cw = new ClassWriter(this, classContext, tok != null, name, isExtern, null, w, instanceFieldWriter, instanceFieldInitWriter, traitInitWriter, staticFieldWriter, staticFieldInitWriter);
if (superClasses != null) {
superClasses = superClasses.Where(trait => !trait.IsObject).ToList();
EmitParentTraits(tok, name, true, superClasses, w);
}
return cw;
}
private void EmitParentTraits(IToken tok, string childName, bool childIsUsedAsPointer, List<Type> parentTraits, ConcreteSyntaxTree wr) {
var star = childIsUsedAsPointer ? "*" : "";
var addressOf = childIsUsedAsPointer ? "&" : "";
// Emit a method that returns the ID of each parent trait
var parentTraitsWriter = wr.NewBlock($"func (_this {star}{childName}) ParentTraits_() []*{HelperModulePrefix}TraitID");
parentTraitsWriter.WriteLine("return [](*{0}TraitID){{{1}}};", HelperModulePrefix, Util.Comma(parentTraits, parent => {
var trait = ((UserDefinedType)parent).ResolvedClass;
return TypeName_Companion(trait, parentTraitsWriter, tok) + ".TraitID_";
}));
foreach (Type typ in parentTraits) {
// Emit a compile-time sanity check that the class emitted does indeed have the methods required by the parent trait
wr.WriteLine($"var _ {TypeName(typ, wr, tok)} = {addressOf}{childName}{{}}");
}
wr.WriteLine($"var _ {HelperModulePrefix}TraitOffspring = {addressOf}{childName}{{}}");
wr.WriteLine();
}
protected override IClassWriter CreateTrait(string name, bool isExtern, List<TypeParameter> typeParameters /*?*/,
TraitDecl trait, List<Type> superClasses /*?*/, IToken tok, ConcreteSyntaxTree wr) {
//
// type Trait interface {
// String() string
// AbstractMethod0(param0 type0, ...) returnType0
// ...
// }
//
// type companionStruct_Trait_ struct {
// StaticField0 type0
// StaticField1 type1
// ...
// }
//
// var Companion_Trait_ = companionStruct_Trait{
// StaticField0: ...,
// StaticField1: ...,
// }
//
// func (_static *companionStruct_Trait) CastTo_(x any) Trait {
// var t Trait
// t, _ = x.(Trait)
// return t
// }
//
// func (_static *companionStruct_Trait) ConcreteInstanceMethod(_this Trait, ...) ... {
// ...
// }
//
// func (_static *companionStruct_Trait) StaticMethod(...) ... {
// ...
// }
wr = CreateDescribedSection("trait {0}", wr, name);
var abstractMethodWriter = wr.NewNamedBlock("type {0} interface", name);
var concreteMethodWriter = wr.Fork();
abstractMethodWriter.WriteLine("String() string");
if (IsDafnySequence(trait)) {
abstractMethodWriter.WriteLine("Equals(other Sequence) bool");
abstractMethodWriter.WriteLine("EqualsGeneric(x interface{}) bool");
abstractMethodWriter.WriteLine("VerbatimString(isLiteral bool) string");
}
var staticFieldWriter = wr.NewNamedBlock("type {0} struct", FormatCompanionTypeName(name));
var staticFieldInitWriter = wr.NewNamedBlock("var {0} = {1}", FormatCompanionName(name), FormatCompanionTypeName(name));
var wCastTo = wr.NewNamedBlock("func ({0}) CastTo_(x interface{{}}) {1}", FormatCompanionTypeName(name), name);
wCastTo.WriteLine("var t {0}", name);
wCastTo.WriteLine("t, _ = x.({0})", name);
wCastTo.WriteLine("return t");
var cw = new ClassWriter(this, trait, false, name, isExtern, abstractMethodWriter, concreteMethodWriter, null, null, null, staticFieldWriter, staticFieldInitWriter);
staticFieldWriter.WriteLine($"TraitID_ *{HelperModulePrefix}TraitID");
staticFieldInitWriter.WriteLine($"TraitID_: &{HelperModulePrefix}TraitID{{}},");
return cw;
}
protected void CreateInitializer(TopLevelDecl classContext, string name, ConcreteSyntaxTree wr,
out ConcreteSyntaxTree instanceFieldInitWriter, out ConcreteSyntaxTree traitInitWriter, out ConcreteSyntaxTree rtdParamWriter) {
wr.Write("func {0}(", FormatInitializerName(name));
rtdParamWriter = wr.Fork();
var w = wr.NewNamedBlock(") *{0}", name);
var parameters = classContext is NewtypeDecl { ParentTraits: { Count: > 0 } } ? "value" : "";
w.WriteLine($"_this := {name}{{{parameters}}}");
w.WriteLine();
instanceFieldInitWriter = w.Fork();
traitInitWriter = w.Fork();
w.WriteLine("return &_this");
}
protected override bool SupportsProperties => false;
protected override ConcreteSyntaxTree CreateIterator(IteratorDecl iter, ConcreteSyntaxTree wr) {
// FIXME: There should be tests to make sure that the finalizer mechanism achieves what I hope it does, namely allowing the iterator's goroutine to be garbage-collected along with the iterator.
//
// type MyIteratorExample struct {
// cont chan<- struct{}
// yielded <-chan struct{}
//
// // Fields
// }
//
// func (_this * MyIteratorExample) Ctor__(/* params */) {
// _cont := make(chan struct{})
// _yielded := make(chan struct{})
// _this.cont = _cont
// _this.yielded = _yielded
// // assign params
//
// go _this.run(_cont, _yielded)
//
// _dafny.SetFinalizer(this_, func(_ MyIteratorExample) {
// close(_cont) // will cause the iterator to return and close _yielded
// })
// }
//
// func (_this * MyIteratorExample) MoveNext() bool {
// _this.cont <- struct{}{}
// _, ok <- _this.yielded
//
// return ok
// }
//
// func (_this * MyIteratorExample) run(_cont <-chan struct{}, _yielded chan<- struct{}) {
// defer close(_yielded)
//
// var _ok bool
// _, _ok = <- _cont
// if !_ok { return }
//
// // Statements ... yield becomes:
// _yielded <- struct{}{}
// _, _ok = <- _cont
// if !_ok { return }
//
// // break becomes:
// return
// }()
var cw = CreateClass(iter, IdName(iter), false, null, iter.TypeArgs, null, null, wr, includeRtd: false, includeEquals: false, includeString: true);
cw.InstanceFieldWriter.WriteLine("cont chan<- struct{}");
cw.InstanceFieldWriter.WriteLine("yielded <-chan struct{}");
Constructor ct = null;
foreach (var member in iter.Members) {
if (member is Field f && !f.IsGhost) {
cw.DeclareField(IdName(f), iter, false, false, f.Type, f.tok, PlaceboValue(f.Type, wr, f.tok, true), f);
} else if (member is Constructor c) {
Contract.Assert(ct == null);
ct = c;
}
}
Contract.Assert(ct != null);
cw.ConcreteMethodWriter.Write("func (_this * {0}) {1}(", IdName(iter), IdName(ct));
string sep = "";
foreach (var p in ct.Ins) {
if (!p.IsGhost) {
// here we rely on the parameters and the corresponding fields having the same names
cw.ConcreteMethodWriter.Write("{0}{1} {2}", sep, IdName(p), TypeName(p.Type, wr, p.tok));
sep = ", ";
}
}
var wCtor = cw.ConcreteMethodWriter.NewBlock(")");
wCtor.WriteLine("_cont := make(chan struct{})");
wCtor.WriteLine("_yielded := make(chan struct{})");
wCtor.WriteLine("_this.cont = _cont");
wCtor.WriteLine("_this.yielded = _yielded");
wCtor.WriteLine();
foreach (var p in ct.Ins) {
if (!p.IsGhost) {
wCtor.WriteLine("_this.{0} = {1}", Capitalize(IdName(p)), IdName(p));
}
}
wCtor.WriteLine();
wCtor.WriteLine("go _this.run(_cont, _yielded)");
wCtor.WriteLine();
wCtor.WriteLine("_dafny.SetFinalizer(_this, func(_ * {0}) {{ close(_cont) }})", IdName(iter));
var wMoveNext = cw.ConcreteMethodWriter.NewNamedBlock("func (_this * {0}) MoveNext() bool", IdName(iter));
wMoveNext.WriteLine("_this.cont <- struct{}{}");
wMoveNext.WriteLine("_, ok := <- _this.yielded");
wMoveNext.WriteLine();
wMoveNext.WriteLine("return ok");
var wRun = cw.ConcreteMethodWriter.NewNamedBlock("func (_this * {0}) run(_cont <-chan struct{{}}, _yielded chan<- struct{{}})", IdName(iter));
wRun.WriteLine("defer close(_yielded)");
wRun.WriteLine();
wRun.WriteLine("_, _ok := <- _cont");
wRun.WriteLine("if !_ok { return }");
wRun.WriteLine();
return wRun;
}
protected override IClassWriter/*?*/ DeclareDatatype(DatatypeDecl dt, ConcreteSyntaxTree wr) {
// ===== For inductive datatypes:
//
// type Dt struct {
// Data_Dt_
// }
//
// type Data_Dt_ interface {
// isDt()
// }
//
// // For uniformity with co-datatypes
// func (_this Dt) Get_() Data_Dt_ {
// return _this.Data_Dt_
// }
//
// type CompanionStruct_Dt_ struct {}
//
// var Companion_Dt_ = CompanionStruct_Dt_ {}
//
// ...
//
// type Dt_Ctor0 struct {
// Field0 type0
// Field1 type1
// ...
// }
//
// func (Dt_Ctor0) isDt() {}
//
// func (_ CompanionStruct_Dt_) CreateCtor0(field0 type0, field1 type1) Dt {
// return Dt{Dt_Ctor0{type0, type1}}
// }
//
// func (_this Dt) IsCtor0() bool {
// _, ok := _this.Data_Dt_.(Dt_Ctor0)
// return ok
// }
//
// type Dt_Ctor1 struct {
// ...
// }
//
// ...
//
// func (_this Dt) DtorDtor0() (dtor0Type, bool) {
// return _this.Data_Dt_.(Dt_Ctor0).Field0
// }
//
// func (_this Dt) DtorDtor1() (dtor1Type, bool) {
// switch data := _this.Data_Dt_.(type) {
// case Dt_Ctor0:
// return data.Field1
// default:
// return data.(Dt_Ctor1).Field0
// }
// }
//
// func (_this Dt) String() { ... }
//
// func (_this Dt) EqualsGeneric(other any) bool { ... }
//
// func (CompanionStruct_Dt_) AllSingletonConstructors() _dafny.Iterator {
// i := -1
// return func() (any, bool) {
// i++
// switch i {
// case 0:
// return Companion_Dt_.Create_Ctor0(), true
// case 1:
// return Companion_Dt_.Create_Ctor1(), true
// ...
// default:
// return Dt{}, false
// }
// }
// }
//
// func Type_Dt_(tyArg0 Type, tyArg1 Type, ...) _dafny.TypeDescriptor {
// return type_Dt_{tyArg0, tyArg1, ...}
// }
//
// type type_Dt_ struct {
// tyArg0 Type
// tyArg1 Type
// }
//
// func (ty type_Dt_) Default() any {
// tyArg0 := ty.tyArg0
// tyArg1 := ty.tyArg1
// return Companion_Dt_.Create_CtorK(...)
// }
//
// func (ty type_Dt_) String() string {
// return "module.Dt"
// }
//
// TODO Optimize record types
//
// ===== For co-inductive datatypes:
//
// type Dt struct {
// Iface_Dt_
// }
//
// type Iface_Dt_ interface {
// Get_() Data_Dt_
// }
//
// type lazyDt struct {
// value Iface_Dt_
// init func() Dt
// }
//
// func (_this * lazyDt) Get_() *Iface_Dt {
// if _this.value == nil {
// _this.value = _this.init().Get_()
// _this.init = nil // allow GC of values in closure
// }
// return _this.value
// }
//
// ...
//
// func (_ CompanionStruct_Dt_) LazyDt(f func() Dt) Dt {
// return Dt{*lazyDt{nil, f}}
// }
//
// func (_ CompanionStruct_Dt_) CreateCtor0(field0 type0, field1 type1) Dt {
// return Dt{*Dt_Ctor0{type0, type1}}
// }
//
// func (_this * Dt_Ctor0) Get_() Dt {
// return _this
// }
if (dt is TupleTypeDecl) {
// Tuple types are declared once and for all in DafnyRuntime.go
return null;
}
string name = Capitalize(dt.GetCompileName(Options));
string companionTypeName = FormatCompanionTypeName(name);
string dataName = FormatDatatypeInterfaceName(name);
string ifaceName = FormatLazyInterfaceName(name);
var simplifiedType = DatatypeWrapperEraser.SimplifyType(Options, UserDefinedType.FromTopLevelDecl(dt.tok, dt));
var simplifiedTypeName = TypeName(simplifiedType, wr, dt.tok);
string StructOfCtor(DatatypeCtor ctor) {
return string.Format("{0}{1}_{2}", dt is CoDatatypeDecl ? "*" : "", name, ctor.GetCompileName(Options));
}
// from here on, write everything into the new block created here:
wr = CreateDescribedSection("{0} {1}", wr, dt.WhatKind, name);
if (dt is IndDatatypeDecl) {
var wStruct = wr.NewNamedBlock("type {0} struct", name);
WriteRuntimeTypeDescriptorsFields(dt.TypeArgs, false, wStruct, null, null);
wStruct.WriteLine(dataName);
wr.WriteLine();
var wGet = wr.NewNamedBlock("func (_this {0}) Get_() {1}", name, dataName);
wGet.WriteLine("return _this.{0}", dataName);
} else {
var wDt = wr.NewNamedBlock("type {0} struct", name);
WriteRuntimeTypeDescriptorsFields(dt.TypeArgs, false, wDt, null, null);
wDt.WriteLine(ifaceName);
wr.WriteLine();
var wIface = wr.NewNamedBlock("type {0} interface", ifaceName);
wIface.WriteLine("Get_() {0}", dataName);
wr.WriteLine();
var wLazy = wr.NewNamedBlock("type lazy_{0}_ struct", name);
wLazy.WriteLine("value {0}", dataName);
wLazy.WriteLine("init func() {0}", name);
wr.WriteLine();
var wLazyGet = wr.NewNamedBlock("func (_this *lazy_{0}_) Get_() {1}", name, dataName);
var wIf = wLazyGet.NewBlock("if _this.value == nil");
wIf.WriteLine("_this.value = _this.init().Get_()");
wIf.WriteLine("_this.init = nil"); // allow GC of values in closure
wLazyGet.WriteLine("return _this.value");
wr.WriteLine();
var typeDescriptorCount = WriteRuntimeTypeDescriptorsFormals(dt.TypeArgs, false, out var wrFormals, out var wrActuals);
var sep = typeDescriptorCount > 0 ? ", " : "";
var wLazyCreate = wr.NewNamedBlock($"func ({companionTypeName}) {FormatLazyConstructorName(name)}({wrFormals}{sep}f func () {name}) {name}");
wLazyCreate.WriteLine($"return {name}{{{wrActuals}{sep}&lazy_{name}_{{nil, f}}}}");
}
{
wr.WriteLine();
var wIface = wr.NewNamedBlock("type {0} interface", dataName);
wIface.WriteLine("is{0}()", name);
}
wr.WriteLine();
var staticFieldWriter = wr.NewNamedBlock("type {0} struct", companionTypeName);
var staticFieldInitWriter = wr.NewNamedBlock("var {0} = {1}", FormatCompanionName(name), companionTypeName);
string typeDescriptorDeclarations;
string typeDescriptorUses;
{
WriteRuntimeTypeDescriptorsFormals(dt.TypeArgs, false, out var wTypeDescriptorDeclarations, out var wTypeDescriptorUses);
typeDescriptorDeclarations = wTypeDescriptorDeclarations.ToString();
typeDescriptorUses = wTypeDescriptorUses.ToString();
}
foreach (var ctor in dt.Ctors.Where(ctor => !ctor.IsGhost)) {
var ctorStructName = name + "_" + ctor.GetCompileName(Options);
wr.WriteLine();
var wStruct = wr.NewNamedBlock("type {0} struct", ctorStructName);
var k = 0;
foreach (var formal in ctor.Formals) {
if (!formal.IsGhost) {
wStruct.WriteLine("{0} {1}", DatatypeFieldName(formal, k), TypeName(formal.Type, wr, formal.Tok));
k++;
}
}
wr.WriteLine();
wr.WriteLine("func ({0}{1}) is{2}() {{}}", dt is CoDatatypeDecl ? "*" : "", ctorStructName, name);
wr.WriteLine();
wr.Write($"func ({companionTypeName}) {FormatDatatypeConstructorName(ctor.GetCompileName(Options))}({typeDescriptorDeclarations}");
var sep = typeDescriptorDeclarations.Length != 0 ? ", " : "";
var argNames = new List<string>();
k = 0;
foreach (var formal in ctor.Formals) {
if (!formal.IsGhost) {
var formalName = DatatypeFieldName(formal, k);
wr.Write($"{sep}{formalName} {TypeName(formal.Type, wr, formal.Tok)}");
argNames.Add(formalName);
sep = ", ";
k++;
}
}
var wCreateBody = wr.NewNamedBlock(") {0}", name);
sep = typeDescriptorDeclarations.Length != 0 ? ", " : "";
var co = dt is CoDatatypeDecl ? "&" : "";
wCreateBody.WriteLine($"return {name}{{{typeDescriptorUses}{sep}{co}{ctorStructName}{{{Util.Comma(argNames)}}}}}");
wr.WriteLine();
var wCheck = wr.NewNamedBlock("func (_this {0}) {1}() bool", name, FormatDatatypeConstructorCheckName(ctor.GetCompileName(Options)));
wCheck.WriteLine("_, ok := _this.Get_().({0})", StructOfCtor(ctor));
wCheck.WriteLine("return ok");
if (dt is CoDatatypeDecl) {
wr.WriteLine();
var wGet = wr.NewNamedBlock("func (_this *{0}) Get_() {1}", ctorStructName, dataName);
wGet.WriteLine("return _this");
}
}
/* func (_static CompanionStruct_Dt_) Default(_default_A any, _default_B any) Dt {
* return Dt{Dt_GroundingCtor{...}}
* }
*/
wr.WriteLine();
wr.Write($"func ({companionTypeName}) Default({typeDescriptorDeclarations}");
var usedParameters = UsedTypeParameters(dt);
if (typeDescriptorDeclarations.Length != 0 && usedParameters.Count != 0) {
wr.Write(", ");
}
wr.Write(usedParameters.Comma(tp => $"{FormatDefaultTypeParameterValue(tp)} interface{{}}"));
{
var wDefault = wr.NewBlock($") {simplifiedTypeName}");
wDefault.Write("return ");
var groundingCtor = dt.GetGroundingCtor();
if (groundingCtor.IsGhost) {
wDefault.Write(ForcePlaceboValue(simplifiedType, wDefault, dt.tok));
} else if (DatatypeWrapperEraser.GetInnerTypeOfErasableDatatypeWrapper(Options, dt, out var innerType)) {
wDefault.Write(DefaultValue(innerType, wDefault, dt.tok));
} else {
var nonGhostFormals = groundingCtor.Formals.Where(f => !f.IsGhost).ToList();
var arguments = nonGhostFormals.Comma(f => DefaultValue(f.Type, wDefault, f.tok));
EmitDatatypeValue(dt, groundingCtor, dt is CoDatatypeDecl, typeDescriptorUses, arguments, wDefault);
}
wDefault.WriteLine();
}
if (dt.HasFinitePossibleValues) {
wr.WriteLine();
var wSingles = wr.NewNamedBlock("func (_ {0}) AllSingletonConstructors() _dafny.Iterator", companionTypeName);
wSingles.WriteLine("i := -1");
wSingles = wSingles.NewNamedBlock("return func() (interface{{}}, bool)");
wSingles.WriteLine("i++");
wSingles = wSingles.NewNamedBlock("switch i");
var i = 0;
foreach (var ctor in dt.Ctors.Where(ctor => !ctor.IsGhost)) {
wSingles.WriteLine("case {0}: return {1}.{2}(), true", i, FormatCompanionName(name), FormatDatatypeConstructorName(ctor.GetCompileName(Options)));
i++;
}
wSingles.WriteLine("default: return {0}{{}}, false", name);
}
// destructors
foreach (var ctor in dt.Ctors) {
foreach (var dtor in ctor.Destructors.Where(dtor => dtor.EnclosingCtors[0] == ctor)) {
var compiledConstructorCount = dtor.EnclosingCtors.Count(constructor => !constructor.IsGhost);
if (compiledConstructorCount != 0) {
var arg = dtor.CorrespondingFormals[0];
if (!arg.IsGhost && arg.HasName) {
wr.WriteLine();
var wDtor = wr.NewNamedBlock("func (_this {0}) {1}() {2}", name, FormatDatatypeDestructorName(arg.CompileName), TypeName(arg.Type, wr, arg.tok));
var n = dtor.EnclosingCtors.Count;
if (n == 1) {
wDtor.WriteLine("return _this.Get_().({0}).{1}", StructOfCtor(dtor.EnclosingCtors[0]), DatatypeFieldName(arg));
} else {
wDtor = wDtor.NewBlock("switch data := _this.Get_().(type)");
var compiledConstructorsProcessed = 0;
for (var i = 0; i < n; i++) {
var ctor_i = dtor.EnclosingCtors[i];
Contract.Assert(arg.CompileName == dtor.CorrespondingFormals[i].CompileName);
if (ctor_i.IsGhost) {
continue;
}
if (compiledConstructorsProcessed < compiledConstructorCount - 1) {
wDtor.WriteLine("case {0}: return data.{1}", StructOfCtor(ctor_i), DatatypeFieldName(arg));
} else {
wDtor.WriteLine("default: return data.({0}).{1}", StructOfCtor(ctor_i), DatatypeFieldName(arg));
}
compiledConstructorsProcessed++;
}
}
}
}
}
}
{
// String() method
wr.WriteLine();
var w = wr.NewNamedBlock("func (_this {0}) String() string", name);
// TODO Avoid switch if only one branch
var needData = dt is IndDatatypeDecl && dt.Ctors.Exists(ctor => !ctor.IsGhost && ctor.Formals.Exists(arg => !arg.IsGhost));
w = w.NewNamedBlock("switch {0}_this.Get_().(type)", needData ? "data := " : "");
w.WriteLine("case nil: return \"null\"");
foreach (var ctor in dt.Ctors.Where(ctor => !ctor.IsGhost)) {
var wCase = w.NewNamedBlock("case {0}:", StructOfCtor(ctor));
var nm = (dt.EnclosingModuleDefinition.TryToAvoidName ? "" : dt.EnclosingModuleDefinition.Name + ".") + dt.Name + "." + ctor.Name;
if (dt is CoDatatypeDecl) {
wCase.WriteLine("return \"{0}\"", nm);
} else {
wCase.Write("return \"{0}\"", nm);
var sep = " + \"(\" + ";
var anyFormals = false;
var k = 0;
foreach (var arg in ctor.Formals) {
if (!arg.IsGhost) {
anyFormals = true;
if (UnicodeCharEnabled && arg.Type.IsStringType) {
wCase.Write($"{sep}data.{DatatypeFieldName(arg, k)}.VerbatimString(true)");
} else {
wCase.Write($"{sep}{HelperModulePrefix}String(data.{DatatypeFieldName(arg, k)})");
}
sep = " + \", \" + ";
k++;
}
}
if (anyFormals) {
wCase.Write(" + \")\"");
}
wCase.WriteLine();
}
}
var wDefault = w.NewBlock("default:");
if (dt is CoDatatypeDecl) {
wDefault.WriteLine("return \"{0}.{1}.unexpected\"", dt.EnclosingModuleDefinition.GetCompileName(Options), dt.GetCompileName(Options));
} else {
wDefault.WriteLine("return \"<unexpected>\"");
}
}
// Equals method
{
wr.WriteLine();
var wEquals = wr.NewNamedBlock("func (_this {0}) Equals(other {0}) bool", name);
// TODO: Way to implement shortcut check for address equality?
var needData1 = dt.Ctors.Exists(ctor => !ctor.IsGhost && ctor.Formals.Exists(arg => !arg.IsGhost));
wEquals = wEquals.NewNamedBlock("switch {0}_this.Get_().(type)", needData1 ? "data1 := " : "");
foreach (var ctor in dt.Ctors.Where(ctor => !ctor.IsGhost)) {
var wCase = wEquals.NewNamedBlock("case {0}:", StructOfCtor(ctor));
var needData2 = ctor.Formals.Exists(arg => !arg.IsGhost);
wCase.WriteLine("{0}, ok := other.Get_().({1})", needData2 ? "data2" : "_", StructOfCtor(ctor));
wCase.Write("return ok");
var k = 0;
foreach (Formal arg in ctor.Formals) {
if (!arg.IsGhost) {
wCase.Write(" && ");
string nm = DatatypeFieldName(arg, k);
var eqType = DatatypeWrapperEraser.SimplifyType(Options, arg.Type);
if (IsDirectlyComparable(eqType)) {
wCase.Write("data1.{0} == data2.{0}", nm);
} else if (IsOrderedByCmp(eqType)) {
wCase.Write("data1.{0}.Cmp(data2.{0}) == 0", nm);
} else if (IsComparedByEquals(eqType)) {
wCase.Write("data1.{0}.Equals(data2.{0})", nm);
} else {
wCase.Write("{0}AreEqual(data1.{1}, data2.{1})", HelperModulePrefix, nm);
}
k++;
}
}
wCase.WriteLine();
}
var wDefault = wEquals.NewNamedBlock("default:");
wDefault.WriteLine("return false; // unexpected");
wr.WriteLine();
var wEqualsGeneric = wr.NewNamedBlock("func (_this {0}) EqualsGeneric(other interface{{}}) bool", name);
wEqualsGeneric.WriteLine("typed, ok := other.({0})", name);
wEqualsGeneric.WriteLine("return ok && _this.Equals(typed)");
}
// RTD
{
var usedOrAutoInitTypeParams = UsedTypeParameters(dt, true);
CreateRTD(name, usedOrAutoInitTypeParams, out var wDefault, wr);
WriteRuntimeTypeDescriptorsLocals(usedOrAutoInitTypeParams, true, wDefault);
var usedTypeParams = UsedTypeParameters(dt);
var sep = typeDescriptorUses.Length != 0 && usedTypeParams.Count != 0 ? ", " : "";
var arguments = usedTypeParams.Comma(tp => DefaultValue(new UserDefinedType(tp), wDefault, dt.tok, true));
wDefault.WriteLine($"return {TypeName_Companion(dt, wr, dt.tok)}.Default({typeDescriptorUses}{sep}{arguments});");
}
EmitParentTraits(dt.tok, name, false, dt.ParentTraits, wr);
return new ClassWriter(this, dt, false, name, dt.IsExtern(Options, out _, out _), null,
wr, wr, wr, wr, staticFieldWriter, staticFieldInitWriter);
}
protected override IClassWriter DeclareNewtype(NewtypeDecl nt, ConcreteSyntaxTree wr) {
var cw = CreateClass(nt, IdName(nt), false, null, nt.TypeArgs,
nt.ParentTypeInformation.UniqueParentTraits(), null, wr, includeRtd: false, includeEquals: false, includeString: true);
var w = cw.ConcreteMethodWriter;
var nativeType = nt.NativeType != null ? GetNativeTypeName(nt.NativeType) : null;
if (nt.NativeType != null) {
var intType = $"{HelperModulePrefix}Int";
var wIntegerRangeBody = w.NewNamedBlock($"func (_this *{FormatCompanionTypeName(IdName(nt))}) IntegerRange(lo {intType}, hi {intType}) {HelperModulePrefix}Iterator");
wIntegerRangeBody.WriteLine($"iter := {HelperModulePrefix}IntegerRange(lo, hi)");
var wIterFuncBody = wIntegerRangeBody.NewBlock($"return func() ({AnyType}, bool)");
wIterFuncBody.WriteLine("next, ok := iter()");