forked from dafny-lang/dafny
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Compiler-cpp.cs
2458 lines (2220 loc) · 105 KB
/
Compiler-cpp.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.Diagnostics.Contracts;
using System.Collections.ObjectModel;
using System.IO;
using JetBrains.Annotations;
namespace Microsoft.Dafny.Compilers {
class CppCompiler : SinglePassCompiler {
private readonly ReadOnlyCollection<string> headers;
public CppCompiler(DafnyOptions options, ErrorReporter reporter, ReadOnlyCollection<string> headers) : base(options, reporter) {
this.headers = headers;
}
public override IReadOnlySet<Feature> UnsupportedFeatures => new HashSet<Feature> {
Feature.UnboundedIntegers,
Feature.RealNumbers,
Feature.CollectionsOfTraits,
Feature.Codatatypes,
Feature.Multisets,
Feature.ExternalClasses,
Feature.Traits,
Feature.Iterators,
Feature.NonNativeNewtypes,
Feature.RuntimeTypeDescriptors,
Feature.MultiDimensionalArrays,
Feature.CollectionsOfTraits,
Feature.Quantifiers,
Feature.NewObject,
Feature.BitvectorRotateFunctions,
Feature.NonSequentializableForallStatements,
Feature.FunctionValues,
Feature.ArrayLength,
Feature.Ordinals,
Feature.MapItems,
Feature.Codatatypes,
Feature.LetSuchThatExpressions,
Feature.NonNativeNewtypes,
Feature.TypeTests,
Feature.SubsetTypeTests,
Feature.SequenceDisplaysOfCharacters,
Feature.MapComprehensions,
Feature.ExactBoundedPool,
Feature.RunAllTests,
Feature.MethodSynthesis,
Feature.UnicodeChars,
Feature.ConvertingValuesToStrings,
Feature.BuiltinsInRuntime,
Feature.RuntimeCoverageReport
};
private List<DatatypeDecl> datatypeDecls = new();
private List<string> classDefaults = new();
/*
* Unlike other Dafny and Dafny's other backends, C++ cares about
* the order in which types are declared. To make this more likely
* to succeed, we emit type information as gradually as possible
* in hopes that definitions are in place when needed.
*/
// Forward declarations of class and struct names
private ConcreteSyntaxTree modDeclsWr = null;
private ConcreteSyntaxTree modDeclWr = null;
// Dafny datatype declarations
private ConcreteSyntaxTree dtDeclsWr = null;
private ConcreteSyntaxTree dtDeclWr = null;
// Dafny class declarations
private ConcreteSyntaxTree classDeclsWr = null;
private ConcreteSyntaxTree classDeclWr = null;
// Dedicated hash-function definitions for each type
private ConcreteSyntaxTree hashWr = null;
const string DafnySetClass = "DafnySet";
const string DafnyMultiSetClass = "DafnyMultiset";
const string DafnySeqClass = "DafnySequence";
const string DafnyMapClass = "DafnyMap";
public override string ModuleSeparator => "::";
protected override string StaticClassAccessor => "::";
protected override string InstanceClassAccessor => "->";
protected override void EmitHeader(Program program, ConcreteSyntaxTree wr) {
// This seems to be a good place to check for unsupported options
if (UnicodeCharEnabled) {
throw new UnsupportedFeatureException(program.GetStartOfFirstFileToken(), Feature.UnicodeChars);
}
wr.WriteLine("// Dafny program {0} compiled into Cpp", program.Name);
wr.WriteLine("#include \"DafnyRuntime.h\"");
foreach (var header in this.headers) {
wr.WriteLine("#include \"{0}\"", Path.GetFileName(header));
}
// For "..."s string literals, to avoid interpreting /0 as the C end of the string, cstring-style
wr.WriteLine("using namespace std::literals;");
var filenameNoExtension = program.Name.Substring(0, program.Name.Length - 4);
var headerFileName = $"{filenameNoExtension}.h";
wr.WriteLine("#include \"{0}\"", Path.GetFileName(headerFileName));
var headerFileWr = wr.NewFile(headerFileName);
headerFileWr.WriteLine("// Dafny program {0} compiled into a Cpp header file", program.Name);
headerFileWr.WriteLine("#pragma once");
headerFileWr.WriteLine("#include \"DafnyRuntime.h\"");
this.modDeclsWr = headerFileWr.Fork();
this.dtDeclsWr = headerFileWr.Fork();
this.classDeclsWr = headerFileWr.Fork();
this.hashWr = headerFileWr.Fork();
if (Options.IncludeRuntime) {
EmitRuntimeSource("DafnyRuntimeCpp", wr);
}
}
protected override void EmitFooter(Program program, ConcreteSyntaxTree wr) {
// Define default values for each datatype
foreach (var dt in this.datatypeDecls) {
var wd = wr.NewBlock(String.Format("template <{0}>\nstruct get_default<{1}::{2}{3} >",
TypeParameters(dt.TypeArgs),
dt.EnclosingModuleDefinition.GetCompileName(Options),
dt.GetCompileName(Options),
InstantiateTemplate(dt.TypeArgs)), ";");
var wc = wd.NewBlock(String.Format("static {0}::{1}{2} call()",
dt.EnclosingModuleDefinition.GetCompileName(Options),
dt.GetCompileName(Options),
InstantiateTemplate(dt.TypeArgs)));
wc.WriteLine("return {0}::{1}{2}();", dt.EnclosingModuleDefinition.GetCompileName(Options), dt.GetCompileName(Options), InstantiateTemplate(dt.TypeArgs));
}
// Define default values for each class
foreach (var classDefault in classDefaults) {
wr.WriteLine(classDefault);
}
}
public override void EmitCallToMain(Method mainMethod, string baseName, ConcreteSyntaxTree wr) {
var w = wr.NewBlock("int main(int argc, char *argv[])");
var tryWr = w.NewBlock("try");
tryWr.WriteLine(string.Format("{0}::{1}::{2}(dafny_get_args(argc, argv));", mainMethod.EnclosingClass.EnclosingModuleDefinition.GetCompileName(Options), mainMethod.EnclosingClass.GetCompileName(Options), mainMethod.Name));
var catchWr = w.NewBlock("catch (DafnyHaltException & e)");
catchWr.WriteLine("std::cout << \"Program halted: \" << e.what() << std::endl;");
}
protected override ConcreteSyntaxTree CreateStaticMain(IClassWriter cw, string argsParameterName) {
var wr = (cw as ClassWriter).MethodWriter;
return wr.NewBlock($"int main(DafnySequence<DafnySequence<char>> {argsParameterName})");
}
protected override ConcreteSyntaxTree CreateModule(string moduleName, bool isDefault, ModuleDefinition externModule,
string libraryName /*?*/, ConcreteSyntaxTree wr) {
var s = $"namespace {IdProtect(moduleName)} ";
string footer = "// end of " + s + " declarations";
this.modDeclWr = this.modDeclsWr.NewBlock(s, footer);
string footer1 = "// end of " + s + " datatype declarations";
this.dtDeclWr = this.dtDeclsWr.NewBlock(s, footer1);
string footer2 = "// end of " + s + " class declarations";
this.classDeclWr = this.classDeclsWr.NewBlock(s, footer2);
string footer3 = "// end of " + s;
return wr.NewBlock(s, footer3);
}
private string TypeParameters(List<TypeParameter> targs) {
Contract.Requires(cce.NonNullElements(targs));
Contract.Ensures(Contract.Result<string>() != null);
if (targs != null) {
return Util.Comma(targs, tp => "typename " + IdName(tp));
} else {
return "";
}
}
private string DeclareTemplate(List<TypeParameter> typeArgs) {
var targs = "";
if (typeArgs != null && typeArgs.Count > 0) {
targs = String.Format("template <{0}>", TypeParameters(typeArgs));
}
return targs;
}
private string DeclareTemplate(List<Type> typeArgs) {
var targs = "";
if (typeArgs != null && typeArgs.Count > 0) {
targs = String.Format("template <{0}>", Util.Comma(typeArgs, t => "typename " + TypeName(t, null, null)));
}
return targs;
}
private string InstantiateTemplate(List<TypeParameter> typeArgs) {
if (typeArgs != null) {
var targs = "";
if (typeArgs.Count > 0) {
targs = String.Format("<{0}>", Util.Comma(typeArgs, ta => ta.GetCompileName(Options)));
}
return targs;
} else {
return "";
}
}
private string InstantiateTemplate(List<Type> typeArgs) {
if (typeArgs != null) {
var targs = "";
if (typeArgs.Count > 0) {
targs = String.Format("<{0}>", Util.Comma(typeArgs, ta => TypeName(ta, null, Token.NoToken)));
}
return targs;
} else {
return "";
}
}
protected override string GetHelperModuleName() => "_dafny";
protected override IClassWriter CreateClass(string moduleName, string name, bool isExtern, string/*?*/ fullPrintName, List<TypeParameter>/*?*/ typeParameters, TopLevelDecl cls, List<Type>/*?*/ superClasses, IToken tok, ConcreteSyntaxTree wr) {
if (isExtern) {
throw new UnsupportedFeatureException(tok, Feature.ExternalClasses, String.Format("extern in class {0}", name));
}
if (superClasses != null && superClasses.Any(trait => !trait.IsObject)) {
throw new UnsupportedFeatureException(tok, Feature.Traits);
}
var classDeclWriter = modDeclWr;
var classDefWriter = this.classDeclWr;
if (typeParameters != null && typeParameters.Count > 0) {
classDeclWriter.WriteLine(DeclareTemplate(typeParameters));
classDefWriter.WriteLine(DeclareTemplate(typeParameters));
}
var methodDeclWriter = classDefWriter.NewBlock(string.Format("class {0}", name), ";");
var methodDefWriter = wr;
classDeclWriter.WriteLine("class {0};", name);
methodDeclWriter.Write("public:\n");
methodDeclWriter.WriteLine("// Default constructor");
methodDeclWriter.WriteLine("{0}() {{}}", name);
// Create the code for the specialization of get_default
var fullName = moduleName + "::" + name;
var getDefaultStr = String.Format("template <{0}>\nstruct get_default<std::shared_ptr<{1}{2} > > {{\n",
TypeParameters(typeParameters),
fullName,
InstantiateTemplate(typeParameters));
getDefaultStr += String.Format("static std::shared_ptr<{0}{1} > call() {{\n",
fullName,
InstantiateTemplate(typeParameters));
getDefaultStr += String.Format("return std::shared_ptr<{0}{1} >();", fullName, InstantiateTemplate(typeParameters));
getDefaultStr += "}\n};";
this.classDefaults.Add(getDefaultStr);
var fieldWriter = methodDeclWriter;
return new ClassWriter(name, this, methodDeclWriter, methodDefWriter, fieldWriter, wr);
}
protected override bool SupportsProperties { get => false; }
protected override IClassWriter CreateTrait(string name, bool isExtern, List<TypeParameter> typeParameters /*?*/,
TraitDecl trait, List<Type> superClasses /*?*/, IToken tok, ConcreteSyntaxTree wr) {
throw new UnsupportedFeatureException(tok, Feature.Traits);
}
protected override ConcreteSyntaxTree CreateIterator(IteratorDecl iter, ConcreteSyntaxTree wr) {
throw new UnsupportedFeatureException(iter.tok, Feature.Iterators);
}
protected bool IsRecursiveConstructor(DatatypeDecl dt, DatatypeCtor ctor) {
foreach (var dtor in ctor.Destructors) {
if (dtor.Type is UserDefinedType t) {
if (t.ResolvedClass == dt) {
return true;
}
}
}
return false;
}
protected bool IsRecursiveDatatype(DatatypeDecl dt) {
foreach (var ctor in dt.Ctors) {
if (IsRecursiveConstructor(dt, ctor)) {
return true;
}
}
return false;
}
// Uniform naming convention
protected string DatatypeSubStructName(DatatypeCtor ctor, bool inclTemplateArgs = false) {
string args = "";
if (inclTemplateArgs) {
args = InstantiateTemplate(ctor.EnclosingDatatype.TypeArgs);
}
return String.Format("{0}_{1}{2}", IdProtect(ctor.EnclosingDatatype.GetCompileName(Options)), ctor.GetCompileName(Options), args);
}
protected override bool DatatypeDeclarationAndMemberCompilationAreSeparate => false;
public override bool SupportsDatatypeWrapperErasure => false;
protected override IClassWriter DeclareDatatype(DatatypeDecl dt, ConcreteSyntaxTree writer) {
if (dt is TupleTypeDecl) {
// Tuple types are declared once and for all in DafnyRuntime.h
return null;
}
this.datatypeDecls.Add(dt);
string DtT = dt.GetCompileName(Options);
string DtT_protected = IdProtect(DtT);
// Forward declaration of the type
this.modDeclWr.WriteLine("{0}\nstruct {1};", DeclareTemplate(dt.TypeArgs), DtT_protected);
var wdecl = this.dtDeclWr;
var wdef = writer;
if (IsRecursiveDatatype(dt)) { // Note that if this is true, there must be more than one constructor!
// Add some forward declarations
wdecl.WriteLine("{0}\nstruct {1};", DeclareTemplate(dt.TypeArgs), DtT_protected);
wdecl.WriteLine("{2}\nbool operator==(const {0}{1} &left, const {0}{1} &right); ", DtT_protected, InstantiateTemplate(dt.TypeArgs), DeclareTemplate(dt.TypeArgs));
}
// Optimize a not-uncommon case
if (dt.IsRecordType) {
var ctor = dt.Ctors[0];
var ws = wdecl.NewBlock(String.Format("{0}\nstruct {1}", DeclareTemplate(dt.TypeArgs), DtT_protected), ";");
// Declare the struct members
var i = 0;
var argNames = new List<string>();
foreach (Formal arg in ctor.Formals) {
if (!arg.IsGhost) {
ws.WriteLine("{0} {1};", TypeName(arg.Type, wdecl, arg.tok), FormalName(arg, i));
argNames.Add(FormalName(arg, i));
i++;
}
}
if (argNames.Count > 0) {
// Create a constructor with arguments
ws.Write("{0}(", DtT_protected);
WriteFormals("", ctor.Formals, ws);
ws.Write(")");
if (argNames.Count > 0) {
// Add initializers
ws.Write(" :");
ws.Write(Util.Comma(argNames, nm => String.Format(" {0} ({0})", IdProtect(nm))));
}
ws.WriteLine(" {}");
}
// Create a constructor with no arguments
ws.WriteLine("{0}();", DtT_protected);
var wc = wdef.NewNamedBlock("{1}\n{0}{2}::{0}()", DtT_protected, DeclareTemplate(dt.TypeArgs), InstantiateTemplate(dt.TypeArgs));
foreach (var arg in ctor.Formals) {
if (!arg.IsGhost) {
wc.WriteLine("{0} = {1};", arg.CompileName, DefaultValue(arg.Type, wc, arg.tok));
}
}
// Overload the comparison operator
var wrCompOp = ws.NewNamedBlock("friend bool operator==(const {0} &left, const {0} &right)", DtT_protected);
wrCompOp.Write("\treturn true");
foreach (var arg in argNames) {
wrCompOp.WriteLine("\t\t&& left.{0} == right.{0}", arg);
}
wrCompOp.WriteLine(";");
// Overload the not-comparison operator
ws.WriteLine("friend bool operator!=(const {0} &left, const {0} &right) {{ return !(left == right); }} ", DtT_protected);
wdecl.WriteLine("{0}\ninline bool is_{1}(const struct {2}{3} d) {{ (void) d; return true; }}", DeclareTemplate(dt.TypeArgs), ctor.GetCompileName(Options), DtT_protected, InstantiateTemplate(dt.TypeArgs));
// Define a custom hasher
hashWr.WriteLine("template <{0}>", TypeParameters(dt.TypeArgs));
var fullName = dt.EnclosingModuleDefinition.GetCompileName(Options) + "::" + DtT_protected + InstantiateTemplate(dt.TypeArgs);
var hwr = hashWr.NewBlock(string.Format("struct std::hash<{0}>", fullName), ";");
var owr = hwr.NewBlock(string.Format("std::size_t operator()(const {0}& x) const", fullName));
owr.WriteLine("size_t seed = 0;");
foreach (var arg in ctor.Formals) {
if (!arg.IsGhost) {
owr.WriteLine("hash_combine<{0}>(seed, x.{1});", TypeName(arg.Type, owr, dt.tok), arg.CompileName);
}
}
owr.WriteLine("return seed;");
} else {
/*** Create one struct for each constructor ***/
foreach (var ctor in dt.Ctors.Where(ctor => !ctor.IsGhost)) {
string structName = DatatypeSubStructName(ctor);
var wstruct = wdecl.NewBlock(String.Format("{0}\nstruct {1}", DeclareTemplate(dt.TypeArgs), structName), ";");
// Declare the struct members
var i = 0;
foreach (Formal arg in ctor.Formals) {
if (!arg.IsGhost) {
if (arg.Type is UserDefinedType udt && udt.ResolvedClass == dt) { // Recursive declaration needs to use a pointer
wstruct.WriteLine("std::shared_ptr<{0}> {1};", TypeName(arg.Type, wdecl, arg.tok), FormalName(arg, i));
} else {
wstruct.WriteLine("{0} {1};", TypeName(arg.Type, wdecl, arg.tok), FormalName(arg, i));
}
i++;
}
}
// Overload the comparison operator
wstruct.WriteLine("friend bool operator==(const {0} &left, const {0} &right) {{ ", structName);
var preReturn = wstruct.Fork();
wstruct.Write("\treturn true ");
i = 0;
foreach (Formal arg in ctor.Formals) {
if (!arg.IsGhost) {
if (arg.Type is UserDefinedType udt && udt.ResolvedClass == dt) { // Recursive destructor needs to use a pointer
wstruct.WriteLine("\t\t&& *(left.{0}) == *(right.{0})", FormalName(arg, i));
} else {
wstruct.WriteLine("\t\t&& left.{0} == right.{0}", FormalName(arg, i));
}
i++;
}
}
if (i == 0) { // Avoid a warning from the C++ compiler
preReturn.WriteLine("(void)left; (void) right;");
}
wstruct.WriteLine(";\n}");
// Overload the not-comparison operator
wstruct.WriteLine("friend bool operator!=(const {0} &left, const {0} &right) {{ return !(left == right); }} ", structName);
// Define a custom hasher
hashWr.WriteLine("template <{0}>", TypeParameters(dt.TypeArgs));
var fullName = dt.EnclosingModuleDefinition.GetCompileName(Options) + "::" + structName + InstantiateTemplate(dt.TypeArgs);
var hwr = hashWr.NewBlock(string.Format("struct std::hash<{0}>", fullName), ";");
var owr = hwr.NewBlock(string.Format("std::size_t operator()(const {0}& x) const", fullName));
owr.WriteLine("size_t seed = 0;");
int argCount = 0;
foreach (var arg in ctor.Formals) {
if (!arg.IsGhost) {
if (arg.Type is UserDefinedType udt && udt.ResolvedClass == dt) {
// Recursive destructor needs to use a pointer
owr.WriteLine("hash_combine<std::shared_ptr<{0}>>(seed, x.{1});", TypeName(arg.Type, owr, dt.tok), arg.CompileName);
} else {
owr.WriteLine("hash_combine<{0}>(seed, x.{1});", TypeName(arg.Type, owr, dt.tok), arg.CompileName);
}
argCount++;
}
}
if (argCount == 0) {
owr.WriteLine("(void)x;");
}
owr.WriteLine("return seed;");
}
/*** Declare the overall tagged union ***/
var ws = wdecl.NewBlock(String.Format("{0}\nstruct {1}", DeclareTemplate(dt.TypeArgs), DtT_protected), ";");
ws.WriteLine("std::variant<{0}> v;", Util.Comma(dt.Ctors, ctor => DatatypeSubStructName(ctor, true)));
// Declare static "constructors" for each Dafny constructor
foreach (var ctor in dt.Ctors) {
var wc = ws.NewNamedBlock("static {0} create_{1}({2})",
DtT_protected, ctor.GetCompileName(Options),
DeclareFormals(ctor.Formals));
wc.WriteLine("{0}{1} COMPILER_result;", DtT_protected, InstantiateTemplate(dt.TypeArgs));
wc.WriteLine("{0} COMPILER_result_subStruct;", DatatypeSubStructName(ctor, true));
foreach (Formal arg in ctor.Formals) {
if (!arg.IsGhost) {
if (arg.Type is UserDefinedType udt && udt.ResolvedClass == dt) {
// This is a recursive destuctor, so we need to allocate space and copy the input in
wc.WriteLine("COMPILER_result_subStruct.{0} = std::make_shared<{1}>({0});", arg.CompileName,
DtT_protected);
} else {
wc.WriteLine("COMPILER_result_subStruct.{0} = {0};", arg.CompileName);
}
}
}
wc.WriteLine("COMPILER_result.v = COMPILER_result_subStruct;");
wc.WriteLine("return COMPILER_result;");
}
// Declare a default constructor
ws.WriteLine("{0}();", DtT_protected);
var wd = wdef.NewNamedBlock(String.Format("{1}\n{0}{2}::{0}()", DtT_protected, DeclareTemplate(dt.TypeArgs), InstantiateTemplate(dt.TypeArgs)));
var default_ctor = dt.Ctors[0]; // Arbitrarily choose the first one
wd.WriteLine("{0} COMPILER_result_subStruct;", DatatypeSubStructName(default_ctor, true));
foreach (Formal arg in default_ctor.Formals) {
if (!arg.IsGhost) {
wd.WriteLine("COMPILER_result_subStruct.{0} = {1};", arg.CompileName,
DefaultValue(arg.Type, wd, arg.tok));
}
}
wd.WriteLine("v = COMPILER_result_subStruct;");
// Declare a default destructor
ws.WriteLine("~{0}() {{}}", DtT_protected);
{
// Declare a default copy constructor (just in case any of our components are non-trivial, i.e., contain smart_ptr)
var wcc = ws.NewNamedBlock(String.Format("{0}(const {0} &other)", DtT_protected));
wcc.WriteLine("v = other.v;");
}
{
// Declare a default copy assignment operator (just in case any of our components are non-trivial, i.e., contain smart_ptr)
var wcc = ws.NewNamedBlock(String.Format("{0}& operator=(const {0} other)", DtT_protected));
wcc.WriteLine("v = other.v;");
wcc.WriteLine("return *this;");
}
// Declare type queries, both as members and general-purpose functions
foreach (var ctor in dt.Ctors) {
var name = DatatypeSubStructName(ctor);
var holds = String.Format("std::holds_alternative<{0}{1}>", name, InstantiateTemplate(dt.TypeArgs));
ws.WriteLine("bool is_{0}() const {{ return {1}(v); }}", name, holds);
wdecl.WriteLine("{0}\ninline bool is_{1}(const struct {2}{3} d);", DeclareTemplate(dt.TypeArgs), name, DtT_protected, InstantiateTemplate(dt.TypeArgs));
wdef.WriteLine("{0}\ninline bool is_{1}(const struct {2}{3} d) {{ return {4}(d.v); }}",
DeclareTemplate(dt.TypeArgs), name, DtT_protected, InstantiateTemplate(dt.TypeArgs), holds);
}
// Overload the comparison operator
ws.WriteLine("friend bool operator==(const {0} &left, const {0} &right) {{ ", DtT_protected);
ws.WriteLine("\treturn left.v == right.v;\n}");
// Create destructors
foreach (var ctor in dt.Ctors) {
foreach (var dtor in ctor.Destructors) {
if (dtor.EnclosingCtors[0] == ctor) {
var arg = dtor.CorrespondingFormals[0];
if (!arg.IsGhost && arg.HasName) {
var returnType = TypeName(arg.Type, ws, arg.tok);
if (arg.Type is UserDefinedType udt && udt.ResolvedClass == dt) {
// This is a recursive destuctor, so return a pointer
returnType = String.Format("std::shared_ptr<{0}>", returnType);
}
var wDtor = ws.NewNamedBlock("{0} dtor_{1}()", returnType,
arg.CompileName);
if (dt.IsRecordType) {
wDtor.WriteLine("return this.{0};", IdName(arg));
} else {
var n = dtor.EnclosingCtors.Count;
for (int i = 0; i < n - 1; i++) {
var ctor_i = dtor.EnclosingCtors[i];
var ctor_name = DatatypeSubStructName(ctor_i);
Contract.Assert(arg.CompileName == dtor.CorrespondingFormals[i].CompileName);
wDtor.WriteLine("if (is_{0}()) {{ return std::get<{0}{1}>(v).{2}; }}",
ctor_name, InstantiateTemplate(dt.TypeArgs), IdName(arg));
}
Contract.Assert(arg.CompileName == dtor.CorrespondingFormals[n - 1].CompileName);
var final_ctor_name = DatatypeSubStructName(dtor.EnclosingCtors[n - 1], true);
wDtor.WriteLine("return std::get<{0}>(v).{1}; ",
final_ctor_name, IdName(arg));
}
}
}
}
}
// Overload the not-comparison operator
ws.WriteLine("friend bool operator!=(const {0} &left, const {0} &right) {{ return !(left == right); }} ", DtT_protected);
// Define a custom hasher for the struct as a whole
hashWr.WriteLine("template <{0}>", TypeParameters(dt.TypeArgs));
var fullStructName = dt.EnclosingModuleDefinition.GetCompileName(Options) + "::" + DtT_protected;
var hwr2 = hashWr.NewBlock(string.Format("struct std::hash<{0}{1}>", fullStructName, InstantiateTemplate(dt.TypeArgs)), ";");
var owr2 = hwr2.NewBlock(string.Format("std::size_t operator()(const {0}{1}& x) const", fullStructName, InstantiateTemplate(dt.TypeArgs)));
owr2.WriteLine("size_t seed = 0;");
var index = 0;
foreach (var ctor in dt.Ctors) {
var ifwr = owr2.NewBlock(string.Format("if (x.is_{0}())", DatatypeSubStructName(ctor)));
ifwr.WriteLine("hash_combine<uint64>(seed, {0});", index);
ifwr.WriteLine("hash_combine<struct {0}::{1}>(seed, std::get<{0}::{1}>(x.v));", dt.EnclosingModuleDefinition.GetCompileName(Options), DatatypeSubStructName(ctor, true));
index++;
}
owr2.WriteLine("return seed;");
if (IsRecursiveDatatype(dt)) {
// Emit a custom hasher for a pointer to this type
hashWr.WriteLine("template <{0}>", TypeParameters(dt.TypeArgs));
hwr2 = hashWr.NewBlock(string.Format("struct std::hash<std::shared_ptr<{0}{1}>>", fullStructName, InstantiateTemplate(dt.TypeArgs)), ";");
owr2 = hwr2.NewBlock(string.Format("std::size_t operator()(const std::shared_ptr<{0}{1}>& x) const", fullStructName, InstantiateTemplate(dt.TypeArgs)));
owr2.WriteLine("struct std::hash<{0}{1}> hasher;", fullStructName, InstantiateTemplate(dt.TypeArgs));
owr2.WriteLine("std::size_t h = hasher(*x);");
owr2.WriteLine("return h;");
}
}
return null;
}
protected override IClassWriter DeclareNewtype(NewtypeDecl nt, ConcreteSyntaxTree wr) {
if (nt.NativeType != null) {
if (nt.NativeType.Name != nt.Name) {
GetNativeInfo(nt.NativeType.Sel, out var nt_name_def, out var literalSuffice_def, out var needsCastAfterArithmetic_def);
wr.WriteLine("typedef {0} {1};", nt_name_def, nt.Name);
}
} else {
throw new UnsupportedFeatureException(nt.tok, Feature.NonNativeNewtypes);
}
var className = "class_" + IdName(nt);
var cw = CreateClass(nt.EnclosingModuleDefinition.GetCompileName(Options), className, nt, wr) as ClassWriter;
var w = cw.MethodDeclWriter;
if (nt.WitnessKind == SubsetTypeDecl.WKind.Compiled) {
var witness = new ConcreteSyntaxTree(w.RelativeIndentLevel);
var wStmts = w.Fork();
if (nt.NativeType == null) {
witness.Append(Expr(nt.Witness, false, wStmts));
} else {
TrParenExpr(nt.Witness, witness, false, wStmts);
witness.Write(".toNumber()");
}
DeclareField(className, nt.TypeArgs, "Witness", true, true, nt.BaseType, nt.tok, witness.ToString(), w, wr);
}
GetNativeInfo(nt.NativeType.Sel, out var nt_name, out var literalSuffice, out var needsCastAfterArithmetic);
var wDefault = w.NewBlock(string.Format("static {0} get_Default()", nt_name));
var udt = new UserDefinedType(nt.tok, nt.Name, nt, new List<Type>());
var d = TypeInitializationValue(udt, wr, nt.tok, false, false);
wDefault.WriteLine("return {0};", d);
return cw;
}
protected override void DeclareSubsetType(SubsetTypeDecl sst, ConcreteSyntaxTree wr) {
if (sst.Name == "nat") {
return; // C++ does not support Nats
}
string templateDecl = "";
if (sst.Var.Type is SeqType s) {
templateDecl = DeclareTemplate(s.TypeArgs[0].TypeArgs); // We want the type args (if any) for the seq-elt type, not the seq
} else {
templateDecl = DeclareTemplate(sst.Var.Type.TypeArgs);
}
this.modDeclWr.WriteLine("{0} using {1} = {2};", templateDecl, IdName(sst), TypeName(sst.Var.Type, wr, sst.tok));
var className = "class_" + IdName(sst);
var cw = CreateClass(sst.EnclosingModuleDefinition.GetCompileName(Options), className, sst, wr) as ClassWriter;
var w = cw.MethodDeclWriter;
if (sst.WitnessKind == SubsetTypeDecl.WKind.Compiled) {
var witness = new ConcreteSyntaxTree(w.RelativeIndentLevel);
witness.Append(Expr(sst.Witness, false, w));
DeclareField(className, sst.TypeArgs, "Witness", true, true, sst.Rhs, sst.tok, witness.ToString(), w, wr);
}
var wDefault = w.NewBlock(String.Format("static {0}{1} get_Default()", IdName(sst), InstantiateTemplate(sst.TypeArgs)));
var udt = new UserDefinedType(sst.tok, sst.Name, sst,
sst.TypeArgs.ConvertAll(tp => (Type)new UserDefinedType(tp)));
var d = TypeInitializationValue(udt, wr, sst.tok, false, false);
wDefault.WriteLine("return {0};", d);
}
protected override void GetNativeInfo(NativeType.Selection sel, out string name, out string literalSuffix, out bool needsCastAfterArithmetic) {
literalSuffix = "";
needsCastAfterArithmetic = false;
switch (sel) {
case NativeType.Selection.Byte:
name = "uint8";
break;
case NativeType.Selection.SByte:
name = "int8";
break;
case NativeType.Selection.UShort:
name = "uint16";
break;
case NativeType.Selection.Short:
name = "int16";
break;
case NativeType.Selection.UInt:
name = "uint32";
break;
case NativeType.Selection.Int:
name = "int32";
break;
case NativeType.Selection.ULong:
name = "uint64";
break;
case NativeType.Selection.Number:
case NativeType.Selection.Long:
name = "int64";
break;
default:
Contract.Assert(false); // unexpected native type
throw new cce.UnreachableException(); // to please the compiler
}
}
protected class ClassWriter : IClassWriter {
public string ClassName;
public readonly CppCompiler Compiler;
public readonly ConcreteSyntaxTree MethodDeclWriter;
public readonly ConcreteSyntaxTree MethodWriter;
public readonly ConcreteSyntaxTree FieldWriter;
public readonly ConcreteSyntaxTree Finisher;
public ClassWriter(string className, CppCompiler compiler, ConcreteSyntaxTree methodDeclWriter, ConcreteSyntaxTree methodWriter, ConcreteSyntaxTree fieldWriter, ConcreteSyntaxTree finisher) {
Contract.Requires(compiler != null);
Contract.Requires(methodDeclWriter != null);
Contract.Requires(methodWriter != null);
Contract.Requires(fieldWriter != null);
this.ClassName = className;
this.Compiler = compiler;
this.MethodDeclWriter = methodDeclWriter;
this.MethodWriter = methodWriter;
this.FieldWriter = fieldWriter;
this.Finisher = finisher;
}
public ConcreteSyntaxTree/*?*/ CreateMethod(Method m, List<TypeArgumentInstantiation> typeArgs, bool createBody, bool forBodyInheritance, bool lookasideBody) {
return Compiler.CreateMethod(m, typeArgs, createBody, MethodDeclWriter, MethodWriter, lookasideBody);
}
public ConcreteSyntaxTree SynthesizeMethod(Method m, List<TypeArgumentInstantiation> typeArgs, bool createBody, bool forBodyInheritance, bool lookasideBody) {
throw new UnsupportedFeatureException(m.tok, Feature.MethodSynthesis);
}
public ConcreteSyntaxTree/*?*/ CreateFunction(string name, List<TypeArgumentInstantiation>/*?*/ typeArgs,
List<Formal> formals, Type resultType, IToken tok, bool isStatic, bool createBody, MemberDecl member, bool forBodyInheritance, bool lookasideBody) {
return Compiler.CreateFunction(member.EnclosingClass.GetCompileName(Compiler.Options),
member.EnclosingClass.TypeArgs, name, typeArgs, formals, resultType, tok, isStatic, createBody, member,
MethodDeclWriter, MethodWriter, lookasideBody);
}
public ConcreteSyntaxTree/*?*/ CreateGetter(string name, TopLevelDecl enclosingDecl, Type resultType, IToken tok, bool isStatic, bool isConst, bool createBody, MemberDecl/*?*/ member, bool forBodyInheritance) {
return Compiler.CreateGetter(name, enclosingDecl, resultType, tok, isStatic, isConst, createBody, MethodDeclWriter, MethodWriter);
}
public ConcreteSyntaxTree/*?*/ CreateGetterSetter(string name, Type resultType, IToken tok, bool createBody, MemberDecl/*?*/ member, out ConcreteSyntaxTree setterWriter, bool forBodyInheritance) {
return Compiler.CreateGetterSetter(name, resultType, tok, createBody, out setterWriter, MethodWriter);
}
public void DeclareField(string name, TopLevelDecl enclosingDecl, bool isStatic, bool isConst, Type type, IToken tok, string rhs, Field field) {
Compiler.DeclareField(ClassName, enclosingDecl.TypeArgs, name, isStatic, isConst, type, tok, rhs, FieldWriter, Finisher);
}
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() => MethodWriter;
public void Finish() { }
}
protected ConcreteSyntaxTree/*?*/ CreateMethod(Method m, List<TypeArgumentInstantiation> typeArgs, bool createBody, ConcreteSyntaxTree wdr, ConcreteSyntaxTree wr, bool lookasideBody) {
List<Formal> nonGhostOuts = m.Outs.Where(o => !o.IsGhost).ToList();
string targetReturnTypeReplacement = null;
if (nonGhostOuts.Count == 1) {
targetReturnTypeReplacement = TypeName(nonGhostOuts[0].Type, wr, nonGhostOuts[0].tok);
} else if (nonGhostOuts.Count > 1) {
targetReturnTypeReplacement = String.Format("struct Tuple{0}", InstantiateTemplate(nonGhostOuts.ConvertAll(n => n.Type)));
}
if (!createBody) {
return null;
}
if (typeArgs.Count != 0) {
var formalTypeParameters = TypeArgumentInstantiation.ToFormals(ForTypeParameters(typeArgs, m, lookasideBody));
// Filter out type parameters we've already emitted at the class level, to avoid shadowing
// the class' template parameter (which C++ treats as an error)
formalTypeParameters = formalTypeParameters.Where(param =>
m.EnclosingClass.TypeArgs == null || !m.EnclosingClass.TypeArgs.Contains(param)).ToList();
wdr.WriteLine(DeclareTemplate(formalTypeParameters));
wr.WriteLine(DeclareTemplate(formalTypeParameters));
}
if (m.EnclosingClass.TypeArgs != null && m.EnclosingClass.TypeArgs.Count > 0) {
wr.WriteLine(DeclareTemplate(m.EnclosingClass.TypeArgs));
}
wr.Write("{0} {1}{2}::{3}",
targetReturnTypeReplacement ?? "void",
m.EnclosingClass.GetCompileName(Options),
InstantiateTemplate(m.EnclosingClass.TypeArgs),
IdName(m));
wdr.Write("{0}{1} {2}",
m.IsStatic ? "static " : "",
targetReturnTypeReplacement ?? "void",
IdName(m));
wr.Write("(");
wdr.Write("(");
int nIns = WriteFormals("", m.Ins, wr);
WriteFormals("", m.Ins, wdr);
if (targetReturnTypeReplacement == null) {
WriteFormals(nIns == 0 ? "" : ", ", m.Outs, wr);
WriteFormals(nIns == 0 ? "" : ", ", m.Outs, wdr);
}
wdr.Write(");\n");
var block = wr.NewBlock(")", null, BlockStyle.NewlineBrace, BlockStyle.NewlineBrace);
if (targetReturnTypeReplacement != null) {
var beforeReturnBlock = block.Fork(0);
EmitReturn(m.Outs, block);
return beforeReturnBlock;
}
return block;
}
protected ConcreteSyntaxTree/*?*/ CreateFunction(string className, List<TypeParameter> classArgs, string name, List<TypeArgumentInstantiation>/*?*/ typeArgs, List<Formal> formals, Type resultType, IToken tok, bool isStatic, bool createBody, MemberDecl member, ConcreteSyntaxTree wdr, ConcreteSyntaxTree wr, bool lookasideBody) {
if (!createBody) {
return null;
}
if (typeArgs.Count != 0) {
var formalTypeParameters = TypeArgumentInstantiation.ToFormals(ForTypeParameters(typeArgs, member, lookasideBody));
// Filter out type parameters we've already emitted at the class level, to avoid shadowing
// the class' template parameter (which C++ treats as an error)
formalTypeParameters = formalTypeParameters.Where(param =>
!classArgs.Contains(param)).ToList();
wdr.WriteLine(DeclareTemplate(formalTypeParameters));
wr.WriteLine(DeclareTemplate(formalTypeParameters));
}
if (classArgs != null && classArgs.Count != 0) {
wr.WriteLine(DeclareTemplate(classArgs));
}
wdr.Write("{0}{1} {2}",
isStatic ? "static " : "",
TypeName(resultType, wr, tok),
name);
wr.Write("{0} {1}{2}::{3}",
TypeName(resultType, wr, tok),
className,
InstantiateTemplate(classArgs),
name);
wdr.Write("(");
wr.Write("(");
WriteFormals("", formals, wdr);
int nIns = WriteFormals("", formals, wr);
wdr.Write(");");
var w = wr.NewBlock(")", null, BlockStyle.NewlineBrace, BlockStyle.NewlineBrace);
return w;
}
protected override void TypeArgDescriptorUse(bool isStatic, bool lookasideBody, TopLevelDeclWithMembers cl, out bool needsTypeParameter, out bool needsTypeDescriptor) {
needsTypeParameter = false;
needsTypeDescriptor = false;
}
protected override string TypeDescriptor(Type type, ConcreteSyntaxTree wr, IToken tok) {
Contract.Requires(type != null);
Contract.Requires(tok != null);
Contract.Requires(wr != null);
throw new UnsupportedFeatureException(tok, Feature.RuntimeTypeDescriptors, string.Format("RuntimeTypeDescriptor {0} not yet supported", type));
}
protected ConcreteSyntaxTree/*?*/ CreateGetter(string name, TopLevelDecl cls, Type resultType, IToken tok, bool isStatic, bool isConst, bool createBody, ConcreteSyntaxTree wdr, ConcreteSyntaxTree wr) {
// Compiler insists on using Getter for constants, but we just use the raw variable name to hold the value,
// because o/w Compiler tries to use the Getter function as an Lvalue in assignments
// Unfortunately, Compiler doesn't tell us what the initial value is, so we hack around it
// by declaring the variable and a function to statically initialize it
ConcreteSyntaxTree w = null;
string postfix = null;
if (createBody) {
w = wdr.NewNamedBlock("{0}{1} init__{2}()", isStatic ? "static " : "", TypeName(resultType, wr, tok), name);
postfix = String.Format(" init__{0}()", name);
}
DeclareField(cls.GetCompileName(Options), cls.TypeArgs, name, isStatic, isConst, resultType, tok, postfix, wdr, wr);
//wdr.Write("{0}{1} {2}{3};", isStatic ? "static " : "", TypeName(resultType, wr, tok), name, postfix);
return w;
}
protected ConcreteSyntaxTree/*?*/ CreateGetterSetter(string name, Type resultType, IToken tok, bool createBody, out ConcreteSyntaxTree setterWriter, ConcreteSyntaxTree wr) {
// We don't use getter/setter pairs; we just embed the trait's fields.
if (createBody) {
var abyss = new ConcreteSyntaxTree();
setterWriter = abyss;
return abyss.NewBlock("");
} else {
setterWriter = null;
return null;
}
}
protected override ConcreteSyntaxTree EmitTailCallStructure(MemberDecl member, ConcreteSyntaxTree wr) {
wr.WriteLine("TAIL_CALL_START:");
return wr;
}
protected override void EmitJumpToTailCallStart(ConcreteSyntaxTree wr) {
wr.WriteLine("goto TAIL_CALL_START;");
}
protected void Warn(string msg, IToken tok) {
Options.ErrorWriter.WriteLine("WARNING: {3} ({0}:{1}:{2})", tok.Filepath, tok.line, tok.col, msg);
}
// Because we use reference counting (via shared_ptr), the TypeName of a class differs
// depending on whether we are declaring a variable or talking about the class itself.
// Use class_name = true if you want the actual name of the class, not the type used when declaring variables/arguments/etc.
protected string TypeName(Type type, ConcreteSyntaxTree wr, IToken tok, MemberDecl/*?*/ member = null, bool class_name = false) {
Contract.Ensures(Contract.Result<string>() != null);
Contract.Assume(type != null); // precondition; this ought to be declared as a Requires in the superclass
var xType = type.NormalizeExpand();
if (xType is TypeProxy) {
// unresolved proxy; just treat as ref, since no particular type information is apparently needed for this type
return "object";
}
if (xType is BoolType) {
return "bool";
} else if (xType is CharType) {
return "char";
} else if (xType is IntType || xType is BigOrdinalType) {
UnsupportedFeatureError(tok, Feature.UnboundedIntegers);
return "BigNumber";
} else if (xType is RealType) {
UnsupportedFeatureError(tok, Feature.RealNumbers);
return "Dafny.BigRational";
} else if (xType is BitvectorType) {
var t = (BitvectorType)xType;
return t.NativeType != null ? GetNativeTypeName(t.NativeType) : "BigNumber";
} else if (xType.AsNewtype != null) {
NativeType nativeType = xType.AsNewtype.NativeType;
if (nativeType != null) {
return GetNativeTypeName(nativeType);
}
return TypeName(xType.AsNewtype.BaseType, wr, tok);
} 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);
if (at.Dims == 1) {
return "DafnyArray<" + TypeName(elType, wr, tok, null, false) + ">";
} else {
throw new UnsupportedFeatureException(tok, Feature.MultiDimensionalArrays);
}
} else if (xType is UserDefinedType) {
var udt = (UserDefinedType)xType;
var s = FullTypeName(udt, member);
var cl = udt.ResolvedClass;
if (class_name || xType.IsTypeParameter || xType.IsAbstractType || xType.IsDatatype) { // Don't add pointer decorations to class names or type parameters
return IdProtect(s) + ActualTypeArgs(xType.TypeArgs);
} else {
return TypeName_UDT(s, udt, wr, udt.tok);
}
} else if (xType is SetType) {
Type argType = ((SetType)xType).Arg;
if (ComplicatedTypeParameterForCompilation(TypeParameter.TPVariance.Co, argType)) {
UnsupportedFeatureError(tok, Feature.CollectionsOfTraits, "compilation of set<TRAIT> is not supported; consider introducing a ghost", wr);
}
return DafnySetClass + "<" + TypeName(argType, wr, tok) + ">";
} else if (xType is SeqType) {
Type argType = ((SeqType)xType).Arg;
if (ComplicatedTypeParameterForCompilation(TypeParameter.TPVariance.Co, argType)) {
UnsupportedFeatureError(tok, Feature.CollectionsOfTraits, "compilation of seq<TRAIT> is not supported; consider introducing a ghost", wr);
}
return DafnySeqClass + "<" + TypeName(argType, wr, tok) + ">";
} else if (xType is MultiSetType) {
Type argType = ((MultiSetType)xType).Arg;
if (ComplicatedTypeParameterForCompilation(TypeParameter.TPVariance.Co, argType)) {
UnsupportedFeatureError(tok, Feature.CollectionsOfTraits, "compilation of multiset<TRAIT> is not supported; consider introducing a ghost", wr);
}
return DafnyMultiSetClass + "<" + TypeName(argType, wr, tok) + ">";
} else if (xType is MapType) {
Type domType = ((MapType)xType).Domain;
Type ranType = ((MapType)xType).Range;
if (ComplicatedTypeParameterForCompilation(TypeParameter.TPVariance.Co, domType) || ComplicatedTypeParameterForCompilation(TypeParameter.TPVariance.Co, ranType)) {
UnsupportedFeatureError(tok, Feature.CollectionsOfTraits, "compilation of map<TRAIT, _> or map<_, TRAIT> is not supported; consider introducing a ghost", wr);
}
return DafnyMapClass + "<" + TypeName(domType, wr, tok) + "," + TypeName(ranType, wr, tok) + ">";
} else {
Contract.Assert(false); throw new cce.UnreachableException(); // unexpected type
}
}
internal override string TypeName(Type type, ConcreteSyntaxTree wr, IToken tok, 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
return TypeName(type, wr, tok, member, false);
}
protected override string TypeInitializationValue(Type type, ConcreteSyntaxTree wr, IToken tok, bool usePlaceboValue, bool constructTypeParameterDefaultsFromTypeDescriptors) {
var xType = type.NormalizeExpandKeepConstraints();
if (xType is BoolType) {
return "false";