forked from dafny-lang/dafny
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SinglePassCompiler.cs
6065 lines (5519 loc) · 280 KB
/
SinglePassCompiler.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 (C) Microsoft Corporation. All Rights Reserved.
// 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 JetBrains.Annotations;
using Microsoft.BaseTypes;
using static Microsoft.Dafny.Compilers.CompilerErrors;
namespace Microsoft.Dafny.Compilers {
public abstract class SinglePassCompiler {
public DafnyOptions Options { get; }
/// <summary>
/// Emits a call to <c>mainMethod</c> as the program's entry point, if such an explicit call is
/// required in the target language.
/// </summary>
public abstract void EmitCallToMain(Method mainMethod, string baseName, ConcreteSyntaxTree callToMainTree);
/// <summary>
/// Change <c>name</c> into a valid identifier in the target language.
/// </summary>
public abstract string PublicIdProtect(string name);
public static Plugin Plugin =
new ConfiguredPlugin(InternalCompilersPluginConfiguration.Singleton);
public abstract IReadOnlySet<Feature> UnsupportedFeatures { get; }
/// <summary>
/// Whether or not the compiler turns
/// datatype Record = R(oneThing: X)
/// into just X, including the case where "Record" is a tuple type with 1 non-ghost component.
/// </summary>
public virtual bool SupportsDatatypeWrapperErasure => true;
public static string DefaultNameMain = "Main";
public virtual string ModuleSeparator => ".";
protected virtual string StaticClassAccessor => ".";
protected virtual string InstanceClassAccessor => ".";
protected ErrorReporter Reporter;
Stack<ConcreteSyntaxTree> copyInstrWriters = new Stack<ConcreteSyntaxTree>(); // a buffer that stores copy instructions generated by letExpr that uses out param.
protected TopLevelDeclWithMembers thisContext; // non-null when type members are being translated
protected ModuleDefinition enclosingModule; // non-null when a module body is being translated
protected Method enclosingMethod; // non-null when a method body is being translated
protected Function enclosingFunction; // non-null when a function body is being translated
protected internal readonly FreshIdGenerator idGenerator = new FreshIdGenerator();
private protected string ProtectedFreshId(string prefix) => IdProtect(idGenerator.FreshId(prefix));
private protected string ProtectedFreshNumericId(string prefix) => IdProtect(idGenerator.FreshNumericId(prefix));
Dictionary<Expression, int> uniqueAstNumbers = new Dictionary<Expression, int>();
int GetUniqueAstNumber(Expression expr) {
Contract.Requires(expr != null);
if (!uniqueAstNumbers.TryGetValue(expr, out var n)) {
n = uniqueAstNumbers.Count;
uniqueAstNumbers.Add(expr, n);
}
return n;
}
public readonly CoverageInstrumenter Coverage;
// Common limits on the size of builtins: tuple, arrow, and array types.
// Some backends have to enforce limits so that all built-ins can be pre-compiled
// into their runtimes.
// See CheckCommonSytemModuleLimits().
protected int MaxTupleNonGhostDims => 20;
// This one matches the maximum arity of the C# System.Func<> type used to implement arrows.
protected int MaxArrowArity => 16;
// This one is also limited by the maximum arrow arity, since a given array type
// uses an arrow of the matching arity for initialization.
protected int MaxArrayDims => MaxArrowArity;
protected SinglePassCompiler(DafnyOptions options, ErrorReporter reporter) {
this.Options = options;
Reporter = reporter;
Coverage = new CoverageInstrumenter(this);
System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(CompilerErrors).TypeHandle);
}
protected static void ReportError(ErrorId errorId, ErrorReporter reporter, IToken tok, string msg, ConcreteSyntaxTree/*?*/ wr, params object[] args) {
Contract.Requires(msg != null);
Contract.Requires(args != null);
reporter.Error(MessageSource.Compiler, errorId, tok, msg, args);
wr?.WriteLine("/* {0} */", string.Format("Compilation error: " + msg, args));
}
public void Error(ErrorId errorId, IToken tok, string msg, ConcreteSyntaxTree wr, params object[] args) {
ReportError(errorId, Reporter, tok, msg, wr, args);
}
protected void UnsupportedFeatureError(IToken tok, Feature feature, string message = null, ConcreteSyntaxTree wr = null, params object[] args) {
if (!UnsupportedFeatures.Contains(feature)) {
throw new Exception($"'{feature}' is not an element of the {GetType().Name} compiler's UnsupportedFeatures set");
}
message ??= UnsupportedFeatureException.MessagePrefix + FeatureDescriptionAttribute.GetDescription(feature).Description;
Error(ErrorId.c_unsupported_feature, tok, message, wr, args);
}
protected string IntSelect = ",int";
protected string LambdaExecute = "";
protected bool UnicodeCharEnabled => Options.Get(CommonOptionBag.UnicodeCharacters);
protected string CharMethodQualifier => UnicodeCharEnabled ? "Unicode" : "";
protected virtual void EmitHeader(Program program, ConcreteSyntaxTree wr) { }
protected virtual void EmitFooter(Program program, ConcreteSyntaxTree wr) { }
/// <summary>
/// Emits any supporting code necessary for built-in Dafny elements,
/// such as the `nat` subset type, or array and arrow types of various arities.
/// These built-in elements are generally declared in the internal _System module
/// by the SystemModuleManager.
/// Some of them are emitted by compiling their declarations in that module, such as tuples.
/// Others have {:compile false} added, so they are not normally given to the compiler at all,
/// but instead need special handling in this method.
///
/// It would likely be cleaner in the future to remove all of the {:compile false} attributes
/// on built-in declarations, and allow compilers to handle them directly
/// (which for many backends just means ignoring many of them).
/// </summary>
protected virtual void EmitBuiltInDecls(SystemModuleManager systemModuleManager, ConcreteSyntaxTree wr) { }
protected void CheckCommonSytemModuleLimits(SystemModuleManager systemModuleManager) {
// Check that the runtime already has all required builtins
if (systemModuleManager.MaxNonGhostTupleSizeUsed > MaxTupleNonGhostDims) {
UnsupportedFeatureError(systemModuleManager.MaxNonGhostTupleSizeToken, Feature.TuplesWiderThan20);
}
var maxArrowArity = systemModuleManager.ArrowTypeDecls.Keys.Max();
if (maxArrowArity > MaxArrowArity) {
UnsupportedFeatureError(Token.NoToken, Feature.ArrowsWithMoreThan16Arguments);
}
var maxArraysDims = systemModuleManager.arrayTypeDecls.Keys.Max();
if (maxArraysDims > MaxArrayDims) {
UnsupportedFeatureError(Token.NoToken, Feature.ArraysWithMoreThan16Dims);
}
}
/// <summary>
/// Checks that the system module contains all sizes of built-in types up to the maximum.
/// See also DafnyRuntime/systemModulePopulator.dfy.
/// </summary>
protected void CheckSystemModulePopulatedToCommonLimits(SystemModuleManager systemModuleManager) {
systemModuleManager.CheckHasAllTupleNonGhostDimsUpTo(MaxTupleNonGhostDims);
systemModuleManager.CheckHasAllArrayDimsUpTo(MaxArrayDims);
systemModuleManager.CheckHasAllArrowAritiesUpTo(MaxArrowArity);
}
/// <summary>
/// Creates a static Main method. The caller will fill the body of this static Main with a
/// call to the instance Main method in the enclosing class.
/// </summary>
protected abstract ConcreteSyntaxTree CreateStaticMain(IClassWriter wr, string argsParameterName);
protected abstract ConcreteSyntaxTree CreateModule(string moduleName, bool isDefault, ModuleDefinition externModule,
string libraryName /*?*/, ConcreteSyntaxTree wr);
/// <summary>
/// Indicates the current program depends on the given module without creating it.
/// Called when a module is out of scope for compilation, such as when using --library.
/// </summary>
protected virtual void DependOnModule(string moduleName, bool isDefault, ModuleDefinition externModule,
string libraryName /*?*/) { }
protected abstract string GetHelperModuleName();
protected interface IClassWriter {
ConcreteSyntaxTree/*?*/ CreateMethod(Method m, List<TypeArgumentInstantiation> typeArgs, bool createBody, bool forBodyInheritance, bool lookasideBody);
ConcreteSyntaxTree/*?*/ SynthesizeMethod(Method m, List<TypeArgumentInstantiation> typeArgs, bool createBody, bool forBodyInheritance, bool lookasideBody);
ConcreteSyntaxTree/*?*/ CreateFunction(string name, List<TypeArgumentInstantiation> typeArgs, List<Formal> formals, Type resultType, IToken tok, bool isStatic, bool createBody,
MemberDecl member, bool forBodyInheritance, bool lookasideBody);
ConcreteSyntaxTree/*?*/ CreateGetter(string name, TopLevelDecl enclosingDecl, Type resultType, IToken tok, bool isStatic, bool isConst, bool createBody, MemberDecl/*?*/ member, bool forBodyInheritance); // returns null iff !createBody
ConcreteSyntaxTree/*?*/ CreateGetterSetter(string name, Type resultType, IToken tok, bool createBody, MemberDecl/*?*/ member, out ConcreteSyntaxTree setterWriter, bool forBodyInheritance); // if createBody, then result and setterWriter are non-null, else both are null
void DeclareField(string name, TopLevelDecl enclosingDecl, bool isStatic, bool isConst, Type type, IToken tok, string rhs, Field/*?*/ field);
/// <summary>
/// InitializeField is called for inherited fields. It is in lieu of calling DeclareField and is called only if
/// ClassesRedeclareInheritedFields==false for the compiler.
/// </summary>
void InitializeField(Field field, Type instantiatedFieldType, TopLevelDeclWithMembers enclosingClass);
ConcreteSyntaxTree/*?*/ ErrorWriter();
void Finish();
}
protected virtual bool IncludeExternMembers { get => false; }
protected virtual bool SupportsStaticsInGenericClasses => true;
protected virtual bool TraitRepeatsInheritedDeclarations => false;
protected IClassWriter CreateClass(string moduleName, string name, TopLevelDecl cls, ConcreteSyntaxTree wr) {
return CreateClass(moduleName, name, false, null, cls.TypeArgs,
cls, (cls as TopLevelDeclWithMembers)?.ParentTypeInformation.UniqueParentTraits(), null, wr);
}
/// <summary>
/// "tok" can be "null" if "superClasses" is.
/// </summary>
protected abstract IClassWriter CreateClass(string moduleName, string name, bool isExtern, string/*?*/ fullPrintName,
List<TypeParameter> typeParameters, TopLevelDecl cls, List<Type>/*?*/ superClasses, IToken tok, ConcreteSyntaxTree wr);
/// <summary>
/// "tok" can be "null" if "superClasses" is.
/// </summary>
protected abstract IClassWriter CreateTrait(string name, bool isExtern, List<TypeParameter> typeParameters /*?*/,
TraitDecl trait, List<Type> superClasses /*?*/, IToken tok, ConcreteSyntaxTree wr);
protected virtual bool SupportsProperties => true;
protected abstract ConcreteSyntaxTree CreateIterator(IteratorDecl iter, ConcreteSyntaxTree wr);
/// <summary>
/// Returns an IClassWriter that can be used to write additional members. If "dt" is already written
/// in the DafnyRuntime.targetlanguage file, then returns "null".
/// </summary>
protected abstract IClassWriter/*?*/ DeclareDatatype(DatatypeDecl dt, ConcreteSyntaxTree wr);
protected virtual bool DatatypeDeclarationAndMemberCompilationAreSeparate => true;
/// <summary>
/// Returns an IClassWriter that can be used to write additional members.
/// </summary>
protected abstract IClassWriter DeclareNewtype(NewtypeDecl nt, ConcreteSyntaxTree wr);
protected abstract void DeclareSubsetType(SubsetTypeDecl sst, ConcreteSyntaxTree wr);
protected string GetNativeTypeName(NativeType nt) {
Contract.Requires(nt != null);
GetNativeInfo(nt.Sel, out var nativeName, out _, out _);
return nativeName;
}
protected abstract void GetNativeInfo(NativeType.Selection sel, out string name, out string literalSuffix, out bool needsCastAfterArithmetic);
protected List<T> SelectNonGhost<T>(TopLevelDecl cl, List<T> elements) {
Contract.Requires(cl != null && elements != null);
if (cl is TupleTypeDecl tupleDecl) {
Contract.Assert(elements.Count == tupleDecl.Dims);
return elements.Where((_, i) => !tupleDecl.ArgumentGhostness[i]).ToList();
} else {
return elements;
}
}
protected virtual List<TypeParameter> UsedTypeParameters(DatatypeDecl dt, bool alsoIncludeAutoInitTypeParameters = false) {
Contract.Requires(dt != null);
var idt = dt as IndDatatypeDecl;
if (idt == null) {
return dt.TypeArgs;
} else {
Contract.Assert(idt.TypeArgs.Count == idt.TypeParametersUsedInConstructionByGroundingCtor.Length);
var tps = new List<TypeParameter>();
for (int i = 0; i < idt.TypeArgs.Count; i++) {
if (idt.TypeParametersUsedInConstructionByGroundingCtor[i] || (alsoIncludeAutoInitTypeParameters && NeedsTypeDescriptor(idt.TypeArgs[i]))) {
tps.Add(idt.TypeArgs[i]);
}
}
return tps;
}
}
protected List<TypeArgumentInstantiation> UsedTypeParameters(DatatypeDecl dt, List<Type> typeArgs, bool alsoIncludeAutoInitTypeParameters = false) {
Contract.Requires(dt != null);
Contract.Requires(typeArgs != null);
Contract.Requires(dt.TypeArgs.Count == typeArgs.Count);
if (dt is not IndDatatypeDecl idt) {
return TypeArgumentInstantiation.ListFromClass(dt, typeArgs);
} else {
Contract.Assert(typeArgs.Count == idt.TypeParametersUsedInConstructionByGroundingCtor.Length);
var r = new List<TypeArgumentInstantiation>();
for (int i = 0; i < typeArgs.Count; i++) {
if (idt.TypeParametersUsedInConstructionByGroundingCtor[i] || (alsoIncludeAutoInitTypeParameters && NeedsTypeDescriptor(idt.TypeArgs[i]))) {
r.Add(new TypeArgumentInstantiation(dt.TypeArgs[i], typeArgs[i]));
}
}
return r;
}
}
protected bool NeedsTypeDescriptors(List<TypeArgumentInstantiation> typeArgs) {
Contract.Requires(typeArgs != null);
return typeArgs.Any(ta => NeedsTypeDescriptor(ta.Formal));
}
protected virtual bool NeedsTypeDescriptor(TypeParameter tp) {
Contract.Requires(tp != null);
return tp.Characteristics.HasCompiledValue;
}
protected abstract string TypeDescriptor(Type type, ConcreteSyntaxTree wr, IToken tok);
protected void EmitTypeDescriptorsActuals(List<TypeArgumentInstantiation> typeArgs, IToken tok, ConcreteSyntaxTree wr, bool useAllTypeArgs = false) {
var prefix = "";
EmitTypeDescriptorsActuals(typeArgs, tok, wr, ref prefix, useAllTypeArgs);
}
protected void EmitTypeDescriptorsActuals(List<TypeArgumentInstantiation> typeArgs, IToken tok, ConcreteSyntaxTree wr, ref string prefix, bool useAllTypeArgs = false) {
Contract.Requires(typeArgs != null);
Contract.Requires(tok != null);
Contract.Requires(wr != null);
Contract.Requires(prefix != null);
foreach (var ta in typeArgs) {
if (useAllTypeArgs || NeedsTypeDescriptor(ta.Formal)) {
wr.Write("{0}{1}", prefix, TypeDescriptor(ta.Actual, wr, tok));
prefix = ", ";
}
}
}
/// <summary>
/// EmitTailCallStructure evolves "wr" into a structure that can be used as the jump target
/// for tail calls (see EmitJumpToTailCallStart).
/// The precondition of the method is:
/// (member is Method m0 && m0.IsTailRecursive) || (member is Function f0 && f0.IsTailRecursive)
/// </summary>
protected abstract ConcreteSyntaxTree EmitTailCallStructure(MemberDecl member, ConcreteSyntaxTree wr);
protected abstract void EmitJumpToTailCallStart(ConcreteSyntaxTree wr);
internal abstract string TypeName(Type type, ConcreteSyntaxTree wr, IToken tok, MemberDecl/*?*/ member = null);
// For cases where a type looks different when it's an argument, such as (*sigh*) Java primitives
protected virtual string TypeArgumentName(Type type, ConcreteSyntaxTree wr, IToken tok) {
return TypeName(type, wr, tok);
}
/// <summary>
/// This method returns the target representation of one possible value of the type.
/// Requires: usePlaceboValue || type.HasCompilableValue
///
/// usePlaceboValue - If "true", the default value produced is one that the target language accepts as a value
/// of the type, but which may not correspond to a Dafny value. This option is used when it is known
/// that the Dafny program will not use the value (for example, when a field is automatically initialized
/// but the Dafny program will soon assign a new value).
/// </summary>
protected abstract string TypeInitializationValue(Type type, ConcreteSyntaxTree wr, IToken tok, bool usePlaceboValue, bool constructTypeParameterDefaultsFromTypeDescriptors);
protected string TypeName_UDT(string fullCompileName, UserDefinedType udt, ConcreteSyntaxTree wr, IToken tok, bool omitTypeArguments = false) {
Contract.Requires(fullCompileName != null);
Contract.Requires(udt != null);
Contract.Requires(wr != null);
Contract.Requires(tok != null);
Contract.Requires(udt.TypeArgs.Count == (udt.ResolvedClass == null ? 0 : udt.ResolvedClass.TypeArgs.Count));
var cl = udt.ResolvedClass;
var typeParams = SelectNonGhost(cl, cl.TypeArgs);
var typeArgs = SelectNonGhost(cl, udt.TypeArgs);
return TypeName_UDT(fullCompileName, typeParams.ConvertAll(tp => tp.Variance), typeArgs, wr, tok, omitTypeArguments);
}
protected abstract string TypeName_UDT(string fullCompileName, List<TypeParameter.TPVariance> variance, List<Type> typeArgs,
ConcreteSyntaxTree wr, IToken tok, bool omitTypeArguments);
protected abstract string/*?*/ TypeName_Companion(Type type, ConcreteSyntaxTree wr, IToken tok, MemberDecl/*?*/ member);
protected virtual void EmitTypeName_Companion(Type type, ConcreteSyntaxTree wr, ConcreteSyntaxTree surrounding, IToken tok, MemberDecl/*?*/ member) {
wr.Write(TypeName_Companion(type, surrounding, tok, member));
}
protected string TypeName_Companion(TopLevelDecl cls, ConcreteSyntaxTree wr, IToken tok) {
Contract.Requires(cls != null);
Contract.Requires(wr != null);
Contract.Requires(tok != null);
return TypeName_Companion(UserDefinedType.FromTopLevelDecl(tok, cls), wr, tok, null);
}
/// Return the "native form" of a type, to which EmitCoercionToNativeForm coerces it.
protected virtual Type NativeForm(Type type) {
return type;
}
protected abstract bool DeclareFormal(string prefix, string name, Type type, IToken tok, bool isInParam, ConcreteSyntaxTree wr);
/// <summary>
/// If "leaveRoomForRhs" is false and "rhs" is null, then generates:
/// type name;
/// If "leaveRoomForRhs" is false and "rhs" is non-null, then generates:
/// type name = rhs;
/// If "leaveRoomForRhs" is true, in which case "rhs" must be null, then generates:
/// type name
/// which is intended to be followed up by a call to EmitAssignmentRhs.
/// In the above, if "type" is null, then it is replaced by "var" or "let".
/// "tok" is allowed to be null if "type" is.
/// </summary>
protected abstract void DeclareLocalVar(string name, Type/*?*/ type, IToken /*?*/ tok, bool leaveRoomForRhs, string/*?*/ rhs, ConcreteSyntaxTree wr);
protected virtual void DeclareLocalVar(string name, Type /*?*/ type, IToken /*?*/ tok, bool leaveRoomForRhs, string /*?*/ rhs, ConcreteSyntaxTree wr, Type t) {
DeclareLocalVar(name, type, tok, leaveRoomForRhs, rhs, wr);
}
/// <summary>
/// Generates:
/// type name = rhs;
/// In the above, if "type" is null, then it is replaced by "var" or "let".
/// "tok" is allowed to be null if "type" is.
/// </summary>
protected virtual void DeclareLocalVar(string name, Type/*?*/ type, IToken/*?*/ tok, Expression rhs, bool inLetExprBody, ConcreteSyntaxTree wr) {
var wStmts = wr.Fork();
var w = DeclareLocalVar(name, type ?? rhs.Type, tok, wr);
EmitExpr(rhs, inLetExprBody, w, wStmts);
}
/// <summary>
/// Generates
/// type name = <<writer returned>>;
/// In the above, if "type" is null, then it is replaced by "var" or "let".
/// "tok" is allowed to be null if "type" is.
/// </summary>
protected abstract ConcreteSyntaxTree DeclareLocalVar(string name, Type/*?*/ type, IToken/*?*/ tok, ConcreteSyntaxTree wr);
protected virtual void DeclareOutCollector(string collectorVarName, ConcreteSyntaxTree wr) { } // called only for return-style calls
protected virtual void DeclareSpecificOutCollector(string collectorVarName, ConcreteSyntaxTree wr, List<Type> formalTypes, List<Type> lhsTypes) { DeclareOutCollector(collectorVarName, wr); } // for languages that don't allow "let" or "var" expressions
protected virtual bool UseReturnStyleOuts(Method m, int nonGhostOutCount) => false;
protected virtual ConcreteSyntaxTree EmitMethodReturns(Method m, ConcreteSyntaxTree wr) { return wr; } // for languages that need explicit return statements not provided by Dafny
protected virtual bool SupportsMultipleReturns { get => false; }
protected virtual bool SupportsAmbiguousTypeDecl { get => true; }
protected virtual bool ClassesRedeclareInheritedFields => true;
public int TargetTupleSize = 0;
/// The punctuation that comes at the end of a statement. Note that
/// statements are followed by newlines regardless.
protected virtual string StmtTerminator { get => ";"; }
protected virtual string True { get => "true"; }
protected virtual string False { get => "false"; }
protected virtual string Conj { get => "&&"; }
protected virtual string AssignmentSymbol { get => " = "; }
public void EndStmt(ConcreteSyntaxTree wr) { wr.WriteLine(StmtTerminator); }
protected abstract void DeclareLocalOutVar(string name, Type type, IToken tok, string rhs, bool useReturnStyleOuts, ConcreteSyntaxTree wr);
protected virtual void EmitActualOutArg(string actualOutParamName, ConcreteSyntaxTree wr) { } // actualOutParamName is always the name of a local variable; called only for non-return-style outs
protected virtual void EmitOutParameterSplits(string outCollector, List<string> actualOutParamNames, ConcreteSyntaxTree wr) { } // called only for return-style calls
protected virtual void EmitCastOutParameterSplits(string outCollector, List<string> actualOutParamNames, ConcreteSyntaxTree wr, List<Type> formalOutParamTypes, List<Type> lhsTypes, IToken tok) {
EmitOutParameterSplits(outCollector, actualOutParamNames, wr);
}
protected abstract void EmitActualTypeArgs(List<Type> typeArgs, IToken tok, ConcreteSyntaxTree wr);
protected virtual void EmitNameAndActualTypeArgs(string protectedName, List<Type> typeArgs, IToken tok, ConcreteSyntaxTree wr) {
wr.Write(protectedName);
EmitActualTypeArgs(typeArgs, tok, wr);
}
protected virtual ConcreteSyntaxTree EmitAssignment(ILvalue wLhs, Type lhsType /*?*/, Type rhsType /*?*/,
ConcreteSyntaxTree wr, IToken tok) {
var w = wLhs.EmitWrite(wr);
w = EmitCoercionIfNecessary(rhsType, lhsType, tok, w);
w = EmitDowncastIfNecessary(rhsType, lhsType, tok, w);
return w;
}
protected virtual void EmitAssignment(out ConcreteSyntaxTree wLhs, Type/*?*/ lhsType, out ConcreteSyntaxTree wRhs, Type/*?*/ rhsType, ConcreteSyntaxTree wr) {
wLhs = wr.Fork();
wr.Write(AssignmentSymbol);
var w = wr;
w = EmitCoercionIfNecessary(rhsType, lhsType, Token.NoToken, w);
w = EmitDowncastIfNecessary(rhsType, lhsType, Token.NoToken, w);
wRhs = w.Fork();
EndStmt(wr);
}
protected virtual void EmitAssignment(string lhs, Type/*?*/ lhsType, string rhs, Type/*?*/ rhsType, ConcreteSyntaxTree wr) {
EmitAssignment(out var wLhs, lhsType, out var wRhs, rhsType, wr);
wLhs.Write(lhs);
wRhs.Write(rhs);
}
protected void EmitAssignmentRhs(string rhs, ConcreteSyntaxTree wr) {
var w = EmitAssignmentRhs(wr);
w.Write(rhs);
}
protected void EmitAssignmentRhs(Expression rhs, bool inLetExprBody, ConcreteSyntaxTree wr, ConcreteSyntaxTree wStmts = null) {
wStmts ??= wr.Fork();
var w = EmitAssignmentRhs(wr);
EmitExpr(rhs, inLetExprBody, w, wStmts);
}
protected virtual ConcreteSyntaxTree EmitAssignmentRhs(ConcreteSyntaxTree wr) {
wr.Write(AssignmentSymbol);
var w = wr.Fork();
EndStmt(wr);
return w;
}
protected virtual string EmitAssignmentLhs(Expression e, ConcreteSyntaxTree wr) {
var wStmts = wr.Fork();
var target = ProtectedFreshId("_lhs");
EmitExpr(e, false, DeclareLocalVar(target, e.Type, e.tok, wr), wStmts);
return target;
}
protected virtual void EmitMultiAssignment(List<Expression> lhsExprs, List<ILvalue> lhss, List<Type> lhsTypes, out List<ConcreteSyntaxTree> wRhss,
List<Type> rhsTypes, ConcreteSyntaxTree wr) {
Contract.Assert(lhss.Count == lhsTypes.Count);
Contract.Assert(lhsTypes.Count == rhsTypes.Count);
wRhss = new List<ConcreteSyntaxTree>();
var rhsVars = new List<string>();
foreach (var rhsType in rhsTypes) {
string target = ProtectedFreshId("_rhs");
rhsVars.Add(target);
wRhss.Add(DeclareLocalVar(target, rhsType, Token.NoToken, wr));
}
List<ILvalue> lhssn;
if (lhss.Count > 1) {
lhssn = new List<ILvalue>();
for (int i = 0; i < lhss.Count; ++i) {
Expression lexpr = lhsExprs[i].Resolved;
ILvalue lhs = lhss[i];
if (lexpr is IdentifierExpr) {
lhssn.Add(lhs);
} else if (lexpr is MemberSelectExpr memberSelectExpr) {
string target = EmitAssignmentLhs(memberSelectExpr.Obj, wr);
var typeArgs = TypeArgumentInstantiation.ListFromMember(memberSelectExpr.Member,
null, memberSelectExpr.TypeApplication_JustMember);
ILvalue newLhs = EmitMemberSelect(w => EmitIdentifier(target, w), memberSelectExpr.Obj.Type, memberSelectExpr.Member, typeArgs,
memberSelectExpr.TypeArgumentSubstitutionsWithParents(), memberSelectExpr.Type, internalAccess: enclosingMethod is Constructor);
lhssn.Add(newLhs);
} else if (lexpr is SeqSelectExpr selectExpr) {
string targetArray = EmitAssignmentLhs(selectExpr.Seq, wr);
string targetIndex = EmitAssignmentLhs(selectExpr.E0, wr);
if (selectExpr.Seq.Type.IsArrayType || selectExpr.Seq.Type.AsSeqType != null) {
targetIndex = ArrayIndexToNativeInt(targetIndex, selectExpr.E0.Type);
}
ILvalue newLhs = new ArrayLvalueImpl(this, targetArray, new List<Action<ConcreteSyntaxTree>>() { wIndex => EmitIdentifier(targetIndex, wIndex) }, lhsTypes[i]);
lhssn.Add(newLhs);
} else if (lexpr is MultiSelectExpr multiSelectExpr) {
string targetArray = EmitAssignmentLhs(multiSelectExpr.Array, wr);
var targetIndices = new List<string>();
foreach (var index in multiSelectExpr.Indices) {
string targetIndex = EmitAssignmentLhs(index, wr);
targetIndex = ArrayIndexToNativeInt(targetIndex, index.Type);
targetIndices.Add(targetIndex);
}
ILvalue newLhs = new ArrayLvalueImpl(this, targetArray, Util.Map<string, Action<ConcreteSyntaxTree>>(targetIndices, i => wIndex => EmitIdentifier(i, wIndex)), lhsTypes[i]);
lhssn.Add(newLhs);
} else {
Contract.Assert(false); // Unknown kind of expression
lhssn.Add(lhs);
}
}
} else {
lhssn = lhss;
}
Contract.Assert(rhsVars.Count == lhsTypes.Count);
for (int i = 0; i < rhsVars.Count; i++) {
ConcreteSyntaxTree wRhsVar = EmitAssignment(lhssn[i], lhsTypes[i], rhsTypes[i], wr, Token.NoToken);
EmitIdentifier(rhsVars[i], wRhsVar);
}
}
protected virtual void EmitSetterParameter(ConcreteSyntaxTree wr) {
wr.Write("value");
}
protected abstract void EmitPrintStmt(ConcreteSyntaxTree wr, Expression arg);
protected abstract void EmitReturn(List<Formal> outParams, ConcreteSyntaxTree wr);
protected virtual void EmitReturnExpr(Expression expr, Type resultType, bool inLetExprBody, ConcreteSyntaxTree wr) { // emits "return <expr>;" for function bodies
var wStmts = wr.Fork();
var w = EmitReturnExpr(wr);
EmitExpr(expr, inLetExprBody, EmitCoercionIfNecessary(expr.Type, resultType, null, w), wStmts);
}
protected virtual void EmitReturnExpr(string returnExpr, ConcreteSyntaxTree wr) { // emits "return <returnExpr>;" for function bodies
var w = EmitReturnExpr(wr);
w.Write(returnExpr);
}
protected virtual ConcreteSyntaxTree EmitReturnExpr(ConcreteSyntaxTree wr) {
// emits "return <returnExpr>;" for function bodies
wr.Write("return ");
var w = wr.Fork();
EndStmt(wr);
return w;
}
/// <summary>
/// Labels the code written to the TargetWriter returned, in such that way that any
/// emitted break to the label inside that code will abruptly end the execution of the code.
/// </summary>
protected abstract ConcreteSyntaxTree CreateLabeledCode(string label, bool createContinueLabel, ConcreteSyntaxTree wr);
protected abstract void EmitBreak(string/*?*/ label, ConcreteSyntaxTree wr);
protected abstract void EmitContinue(string label, ConcreteSyntaxTree wr);
protected abstract void EmitYield(ConcreteSyntaxTree wr);
protected abstract void EmitAbsurd(string/*?*/ message, ConcreteSyntaxTree wr);
protected virtual void EmitAbsurd(string message, ConcreteSyntaxTree wr, bool needIterLimit) {
EmitAbsurd(message, wr);
}
protected abstract void EmitHalt(IToken tok, Expression /*?*/ messageExpr, ConcreteSyntaxTree wr);
protected ConcreteSyntaxTree EmitIf(string guard, bool hasElse, ConcreteSyntaxTree wr) {
var thn = EmitIf(out var guardWriter, hasElse, wr);
guardWriter.Write(guard);
return thn;
}
protected virtual ConcreteSyntaxTree EmitIf(out ConcreteSyntaxTree guardWriter, bool hasElse, ConcreteSyntaxTree wr) {
wr.Write("if (");
guardWriter = wr.Fork();
if (hasElse) {
var thn = wr.NewBlock(")", " else", BlockStyle.SpaceBrace, BlockStyle.SpaceBrace);
return thn;
} else {
var thn = wr.NewBlock(")");
return thn;
}
}
protected virtual ConcreteSyntaxTree EmitBlock(ConcreteSyntaxTree wr) {
return wr.NewBlock("", open: BlockStyle.Brace);
}
protected virtual ConcreteSyntaxTree EmitWhile(IToken tok, List<Statement> body, LList<Label> labels, ConcreteSyntaxTree wr) { // returns the guard writer
var wBody = CreateWhileLoop(out var guardWriter, wr);
wBody = EmitContinueLabel(labels, wBody);
Coverage.Instrument(tok, "while body", wBody);
TrStmtList(body, wBody);
return guardWriter;
}
protected abstract ConcreteSyntaxTree EmitForStmt(IToken tok, IVariable loopIndex, bool goingUp, string /*?*/ endVarName,
List<Statement> body, LList<Label> labels, ConcreteSyntaxTree wr);
protected virtual ConcreteSyntaxTree CreateWhileLoop(out ConcreteSyntaxTree guardWriter, ConcreteSyntaxTree wr) {
wr.Write("while (");
guardWriter = wr.Fork();
var wBody = wr.NewBlock(")");
return wBody;
}
/// <summary>
/// Create a for loop where the type of the index variable, along with "start" and "bound", is the native array-index type.
/// </summary>
protected abstract ConcreteSyntaxTree CreateForLoop(string indexVar, Action<ConcreteSyntaxTree> bound, ConcreteSyntaxTree wr, string start = null);
protected abstract ConcreteSyntaxTree CreateDoublingForLoop(string indexVar, int start, ConcreteSyntaxTree wr);
protected abstract void EmitIncrementVar(string varName, ConcreteSyntaxTree wr); // increments a BigInteger by 1
protected abstract void EmitDecrementVar(string varName, ConcreteSyntaxTree wr); // decrements a BigInteger by 1
protected abstract string GetQuantifierName(string bvType);
/// <summary>
/// Emit a loop like this:
/// foreach (tmpVarName:collectionElementType in [[collectionWriter]]) {
/// [[bodyWriter]]
/// }
/// where
/// * "[[collectionWriter]]" is the writer returned as "collectionWriter"
/// * "[[bodyWriter]]" is the block writer returned
/// </summary>
protected abstract ConcreteSyntaxTree CreateForeachLoop(
string tmpVarName, Type collectionElementType,
IToken tok, out ConcreteSyntaxTree collectionWriter, ConcreteSyntaxTree wr);
/// <summary>
/// Creates a guarded foreach loop that iterates over a collection, and apply required subtype
/// and compiled subset types filters. Will not emit intermediate ifs if there is no need.
///
/// foreach(collectionElementType tmpVarName in collectionWriter) {
/// if(tmpVarName is [boundVar.type]) {
/// var [IDName(boundVar)] = ([boundVar.type])(tmpvarName);
/// if(constraints_of_boundvar.Type([IdName(boundVar)])) {
/// ...
/// }
/// }
/// }
/// </summary>
/// <returns>A writer to write inside the deepest if-then</returns>
private ConcreteSyntaxTree CreateGuardedForeachLoop(
string tmpVarName, Type collectionElementType,
IVariable boundVar,
bool introduceBoundVar, bool inLetExprBody,
IToken tok, Action<ConcreteSyntaxTree> collection, ConcreteSyntaxTree wr
) {
wr = CreateForeachLoop(tmpVarName, collectionElementType, tok, out var collectionWriter, wr);
collection(collectionWriter);
wr = MaybeInjectSubtypeConstraint(tmpVarName, collectionElementType, boundVar.Type, inLetExprBody, tok, wr);
EmitDowncastVariableAssignment(IdName(boundVar), boundVar.Type, tmpVarName, collectionElementType,
introduceBoundVar, tok, wr);
wr = MaybeInjectSubsetConstraint(boundVar, boundVar.Type, collectionElementType, inLetExprBody, tok, wr);
return wr;
}
/// <summary>
/// Returns a subtype condition like:
/// tmpVarName is member of type boundVarType
/// Returns null if no condition is necessary
/// </summary>
[CanBeNull]
protected abstract Action<ConcreteSyntaxTree> GetSubtypeCondition(
string tmpVarName, Type boundVarType, IToken tok, ConcreteSyntaxTree wPreconditions);
/// <summary>
/// Emit an (already verified) downcast assignment like:
///
/// var boundVarName:boundVarType := tmpVarName as boundVarType;
/// [[bodyWriter]]
///
/// where
/// * "[[bodyWriter]]" is where the writer wr's position will be next
/// </summary>
/// <param name="boundVarName">Name of the variable after casting</param>
/// <param name="boundVarType">Expected variable type</param>
/// <param name="tmpVarName">The collection's variable name</param>
/// <param name="collectionElementType">type this variable is casted from, in case it is useful</param>
/// <param name="introduceBoundVar">Whether or not to declare the variable, in languages requiring declarations</param>
/// <param name="tok">A position in the AST</param>
/// <param name="wr">The concrete syntax tree writer</param>
protected abstract void EmitDowncastVariableAssignment(string boundVarName, Type boundVarType, string tmpVarName,
Type collectionElementType, bool introduceBoundVar, IToken tok, ConcreteSyntaxTree wr);
/// <summary>
/// Emit a simple foreach loop over the elements (which are known as "ingredients") of a collection assembled for
/// the purpose of compiling a "forall" statement.
///
/// foreach (boundVarName:boundVarType in [[coll]]) {
/// [[body]]
/// }
///
/// where "boundVarType" is an L-tuple whose components are "tupleTypeArgs" (see EmitIngredients). If "boundVarType" can
/// be inferred from the ingredients emitted by EmitIngredients, then "L" and "tupleTypeArgs" can be ignored and
/// "boundVarType" be replaced by some target-language way of saying "please infer the type" (like "var" in C#).
/// </summary>
protected abstract ConcreteSyntaxTree CreateForeachIngredientLoop(string boundVarName, int L, string tupleTypeArgs, out ConcreteSyntaxTree collectionWriter, ConcreteSyntaxTree wr);
/// <summary>
/// If "initCall" is non-null, then "initCall.Method is Constructor".
/// </summary>
protected abstract void EmitNew(Type type, IToken tok, CallStmt initCall /*?*/, ConcreteSyntaxTree wr,
ConcreteSyntaxTree wStmts);
// To support target language constructors without an additional initCall in {:extern} code, we ignore the initCall
// and call the constructor with all arguments.
protected string ConstructorArguments(CallStmt initCall, ConcreteSyntaxTree wStmts, Constructor ctor, string sep = "") {
var arguments = Enumerable.Empty<string>();
if (ctor != null && ctor.IsExtern(Options, out _, out _)) {
// the arguments of any external constructor are placed here
arguments = ctor.Ins.Select((f, i) => (f, i))
.Where(tp => !tp.f.IsGhost)
.Select(tp => Expr(initCall.Args[tp.i], false, wStmts).ToString());
}
return (arguments.Any() ? sep : "") + arguments.Comma();
}
protected virtual bool DeterminesArrayTypeFromExampleElement => false;
protected virtual string ArrayIndexLiteral(int x) => x.ToString();
/// <summary>
/// Allocates a new array with element type "elementType" and lengths "dimensions" in each dimension.
/// Note that "elementType" may denote a type parameter.
///
/// Each string in "dimensions" is generated as a Dafny "int" (that is, a BigInteger).
///
/// If "mustInitialize" is true, then fills each array element with a default value of type "elementType".
/// In this case, "exampleElement" must be null.
///
/// If "mustInitialize" is false, then the array's elements are left uninitialized.
/// In this case, "exampleElement" may be non-null as a guide to figuring out what run-time type the array should have.
/// Note that "exampleElement" is not written to the array.
///
/// "exampleElement" is always null if "DeterminesArrayTypeFromExampleElement" is false.
/// </summary>
protected abstract void EmitNewArray(Type elementType, IToken tok, List<string> dimensions,
bool mustInitialize, [CanBeNull] string exampleElement, ConcreteSyntaxTree wr, ConcreteSyntaxTree wStmts);
/// <summary>
/// Same as the EmitNewArray overload above, except that "dimensions" is "List<Expression>" instead of "List<string>".
/// </summary>
protected virtual void EmitNewArray(Type elementType, IToken tok, List<Expression> dimensions,
bool mustInitialize, [CanBeNull] string exampleElement, ConcreteSyntaxTree wr, ConcreteSyntaxTree wStmts) {
var dimStrings = dimensions.ConvertAll(expr => {
var wrDim = new ConcreteSyntaxTree();
EmitExpr(expr, false, ExprToInt(expr.Type, wrDim), wStmts);
return wrDim.ToString();
});
EmitNewArray(elementType, tok, dimStrings, mustInitialize, exampleElement, wr, wStmts);
}
protected abstract void EmitLiteralExpr(ConcreteSyntaxTree wr, LiteralExpr e);
protected abstract void EmitStringLiteral(string str, bool isVerbatim, ConcreteSyntaxTree wr);
protected abstract ConcreteSyntaxTree EmitBitvectorTruncation(BitvectorType bvType, bool surroundByUnchecked, ConcreteSyntaxTree wr);
protected delegate void FCE_Arg_Translator(Expression e, ConcreteSyntaxTree wr, bool inLetExpr, ConcreteSyntaxTree wStmts);
protected abstract void EmitRotate(Expression e0, Expression e1, bool isRotateLeft, ConcreteSyntaxTree wr,
bool inLetExprBody, ConcreteSyntaxTree wStmts, FCE_Arg_Translator tr);
/// <summary>
/// Return true if x < 0 should be rendered as sign(x) < 0 when x has the
/// given type. Typically, this is only a win at non-native types, since
/// BigIntegers benefit from not having to access the number zero.
/// </summary>
protected virtual bool CompareZeroUsingSign(Type type) {
return false;
}
protected virtual ConcreteSyntaxTree EmitSign(Type type, ConcreteSyntaxTree wr) {
// Currently, this should only be called when CompareZeroUsingSign is true
Contract.Assert(false);
throw new cce.UnreachableException();
}
protected abstract void EmitEmptyTupleList(string tupleTypeArgs, ConcreteSyntaxTree wr);
protected abstract ConcreteSyntaxTree EmitAddTupleToList(string ingredients, string tupleTypeArgs, ConcreteSyntaxTree wr);
protected abstract void EmitTupleSelect(string prefix, int i, ConcreteSyntaxTree wr);
protected virtual bool NeedsCastFromTypeParameter => false;
protected virtual bool TargetSubtypingRequiresEqualTypeArguments(Type type) => false;
protected virtual bool IsCoercionNecessary(Type /*?*/ from, Type /*?*/ to) {
return NeedsCastFromTypeParameter;
}
protected virtual Type TypeForCoercion(Type type) {
return type;
}
/// <summary>
/// If "from" and "to" are both given, and if a "from" needs an explicit coercion in order to become a "to", emit that coercion.
/// Needed in languages where either
/// (a) we need to represent upcasts as explicit operations (like Go, or array types in Java), or
/// (b) there's static typing but no parametric polymorphism (like Go) so that lots of things need to be boxed and unboxed.
/// "toOrig" is passed to represent the original, unsubstituted type, which is useful for detecting boxing situations in Java
/// </summary>
protected virtual ConcreteSyntaxTree EmitCoercionIfNecessary(Type/*?*/ from, Type/*?*/ to, IToken tok, ConcreteSyntaxTree wr, Type/*?*/ toOrig = null) {
if (from != null && to != null && from.IsTraitType && to.AsNewtype != null) {
return FromFatPointer(to, wr);
}
if (from != null && to != null && from.AsNewtype != null && to.IsTraitType && (enclosingMethod != null || enclosingFunction != null)) {
return ToFatPointer(from, wr);
}
return wr;
}
protected ConcreteSyntaxTree CoercionIfNecessary(Type/*?*/ from, Type/*?*/ to, IToken tok, ICanRender inner, Type/*?*/ toOrig = null) {
if (toOrig == null) {
toOrig = to;
}
var result = new ConcreteSyntaxTree();
EmitCoercionIfNecessary(from, to, tok, result, toOrig).Append(inner);
return result;
}
protected ConcreteSyntaxTree EmitDowncastIfNecessary(Type /*?*/ from, Type /*?*/ to, IToken tok, ConcreteSyntaxTree wr) {
Contract.Requires(tok != null);
Contract.Requires(wr != null);
if (from != null && to != null) {
from = DatatypeWrapperEraser.SimplifyType(Options, from);
to = DatatypeWrapperEraser.SimplifyType(Options, to);
if (!IsTargetSupertype(to, from)) {
// By the way, it is tempting to think that IsTargetSupertype(from, to)) would hold here, but that's not true.
// For one, in a language with NeedsCastFromTypeParameter, "to" and "from" may contain uninstantiated formal type parameters.
// Also, it is possible (subject to a check enforced by the verifier) to assign Datatype<X> to Datatype<Y>,
// where Datatype is co-variant in its argument type and X and Y are two incomparable types with a common supertype.
wr = EmitDowncast(from, to, tok, wr);
}
}
return wr;
}
protected virtual ConcreteSyntaxTree UnboxNewtypeValue(ConcreteSyntaxTree wr) {
return wr;
}
/// <summary>
/// Change from the fat-pointer representation of "type" to the ordinary representation of "type".
/// If these are the same, acts as the identity.
/// Note, the two representations are different only for newtypes, and only for newtypes that
/// extend a trait, see Type.HasFatPointer.
/// </summary>
protected virtual ConcreteSyntaxTree FromFatPointer(Type type, ConcreteSyntaxTree wr) {
return wr;
}
/// <summary>
/// Change from the ordinary representation of "type" to the fat-pointer representation of "type".
/// If these are the same, acts as the identity.
/// Note, the two representations are different only for newtypes, and only for newtypes that
/// extend a trait, see Type.HasFatPointer.
/// </summary>
protected virtual ConcreteSyntaxTree ToFatPointer(Type type, ConcreteSyntaxTree wr) {
return wr;
}
/// <summary>
/// Determine if "to" is a supertype of "from" in the target language, if "!typeEqualityOnly".
/// Determine if "to" is equal to "from" in the target language, if "typeEqualityOnly".
/// This to similar to Type.IsSupertype and Type.Equals, respectively, but ignores subset types (that
/// is, always uses the base type of any subset type).
/// </summary>
public bool IsTargetSupertype(Type to, Type from, bool typeEqualityOnly = false) {
Contract.Requires(from != null);
Contract.Requires(to != null);
to = to.NormalizeExpand();
from = from.NormalizeExpand();
if (Type.SameHead(to, from)) {
Contract.Assert(to.TypeArgs.Count == from.TypeArgs.Count);
var formalTypeParameters = (to as UserDefinedType)?.ResolvedClass?.TypeArgs;
Contract.Assert(formalTypeParameters == null || formalTypeParameters.Count == to.TypeArgs.Count);
Contract.Assert(formalTypeParameters != null || to.TypeArgs.Count == 0 || to is CollectionType);
for (var i = 0; i < to.TypeArgs.Count; i++) {
bool okay;
if (typeEqualityOnly || TargetSubtypingRequiresEqualTypeArguments(to)) {
okay = IsTargetSupertype(to.TypeArgs[i], from.TypeArgs[i], true);
} else if (formalTypeParameters == null || formalTypeParameters[i].Variance == TypeParameter.TPVariance.Co) {
okay = IsTargetSupertype(to.TypeArgs[i], from.TypeArgs[i]);
} else if (formalTypeParameters[i].Variance == TypeParameter.TPVariance.Contra) {
okay = IsTargetSupertype(from.TypeArgs[i], to.TypeArgs[i]);
} else {
okay = IsTargetSupertype(to.TypeArgs[i], from.TypeArgs[i], true);
}
if (!okay) {
return false;
}
}
return true;
} else if (typeEqualityOnly) {
return false;
} else if (to.IsObjectQ) {
return true;
} else {
return from.ParentTypes().Any(fromParentType => IsTargetSupertype(to, fromParentType));
}
}
protected ConcreteSyntaxTree Downcast(Type from, Type to, IToken tok, ICanRender expression) {
var result = new ConcreteSyntaxTree();
EmitDowncast(from, to, tok, result).Append(expression);
return result;
}
protected virtual ConcreteSyntaxTree EmitDowncast(Type from, Type to, IToken tok, ConcreteSyntaxTree wr) {
Contract.Requires(from != null);
Contract.Requires(to != null);
Contract.Requires(tok != null);
Contract.Requires(wr != null);
Contract.Requires(!IsTargetSupertype(to, from));
return wr;
}
protected virtual ConcreteSyntaxTree EmitCoercionToNativeInt(ConcreteSyntaxTree wr) {
return wr;
}
/// <summary>
/// Emit a coercion of a value to any tuple, returning the writer for the value to coerce. Needed in translating ForallStmt because some of the tuple components are native ints for which we have no Type object, but Go needs to coerce the value that comes out of the iterator. Safe to leave this alone in subclasses that don't have the same problem.
/// </summary>
protected virtual ConcreteSyntaxTree EmitCoercionToArbitraryTuple(ConcreteSyntaxTree wr) {
return wr;
}
protected virtual string IdName(TopLevelDecl d) {
Contract.Requires(d != null);
return IdProtect(d.GetCompileName(Options));
}
protected virtual string IdName(MemberDecl member) {
Contract.Requires(member != null);
return IdProtect(member.GetCompileName(Options));
}
protected virtual string CompanionMemberIdName(MemberDecl member) {
return IdName(member);
}
protected virtual string IdName(TypeParameter tp) {
Contract.Requires(tp != null);
return IdProtect(tp.GetCompileName(Options));
}
protected virtual string IdName(IVariable v) {
Contract.Requires(v != null);
return IdProtect(v.CompileName);
}
protected virtual string IdMemberName(MemberSelectExpr mse) {
Contract.Requires(mse != null);
return IdProtect(mse.MemberName);
}
protected virtual string IdProtect(string name) {
Contract.Requires(name != null);
return name;
}
protected abstract string FullTypeName(UserDefinedType udt, MemberDecl/*?*/ member = null);
protected abstract void EmitThis(ConcreteSyntaxTree wr, bool callToInheritedMember = false);
protected virtual void EmitNull(Type type, ConcreteSyntaxTree wr) {
wr.Write("null");
}
protected virtual void EmitITE(Expression guard, Expression thn, Expression els, Type resultType, bool inLetExprBody,
ConcreteSyntaxTree wr, ConcreteSyntaxTree wStmts) {
Contract.Requires(guard != null);
Contract.Requires(thn != null);
Contract.Requires(thn.Type != null);
Contract.Requires(els != null);
Contract.Requires(resultType != null);
Contract.Requires(wr != null);
resultType = resultType.NormalizeExpand();
var thenExpr = Expr(thn, inLetExprBody, wStmts);
var castedThenExpr = resultType.Equals(thn.Type.NormalizeExpand()) ? thenExpr : Cast(resultType, thenExpr);
var elseExpr = Expr(els, inLetExprBody, wStmts);
var castedElseExpr = resultType.Equals(els.Type.NormalizeExpand()) ? elseExpr : Cast(resultType, elseExpr);
wr.Format($"(({Expr(guard, inLetExprBody, wStmts)}) ? ({castedThenExpr}) : ({castedElseExpr}))");
}
public ConcreteSyntaxTree Cast(ICanRender toType, ConcreteSyntaxTree expr) {
var result = new ConcreteSyntaxTree();
EmitCast(toType, result).Append(expr);
return result;
}
public ConcreteSyntaxTree Cast(Type toType, ConcreteSyntaxTree expr) {
var result = new ConcreteSyntaxTree();
EmitCast(new LineSegment(TypeName(toType, result, Token.NoToken)), result).Append(expr);
return result;
}