-
Notifications
You must be signed in to change notification settings - Fork 319
Expand file tree
/
Copy pathDafnyOptions.cs
More file actions
1651 lines (1368 loc) · 63.2 KB
/
Copy pathDafnyOptions.cs
File metadata and controls
1651 lines (1368 loc) · 63.2 KB
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.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.CommandLine;
using System.Diagnostics;
using System.Linq;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using JetBrains.Annotations;
using Microsoft.Dafny;
using Microsoft.Dafny.Compilers;
using Microsoft.Dafny.Plugins;
using Bpl = Microsoft.Boogie;
namespace Microsoft.Dafny {
public enum FunctionSyntaxOptions {
Version3,
Migration3To4,
ExperimentalTreatUnspecifiedAsGhost,
ExperimentalTreatUnspecifiedAsCompiled,
ExperimentalPredicateAlwaysGhost,
Version4,
}
public enum QuantifierSyntaxOptions {
Version3,
Version4,
}
public record Options(IDictionary<Option, object> OptionArguments);
public class DafnyOptions : Bpl.CommandLineOptions {
public bool NonGhostsUseHeap => Allocated == 1 || Allocated == 2;
public bool AlwaysUseHeap => Allocated == 2;
public bool CommonHeapUse => Allocated >= 2;
public bool FrugalHeapUse => Allocated >= 3;
public bool FrugalHeapUseX => Allocated == 4;
static DafnyOptions() {
RegisterLegacyUi(CommonOptionBag.Target, ParseString, "Compilation options", "compileTarget", @"
cs (default) - Compile to .NET via C#.
go - Compile to Go.
js - Compile to JavaScript.
java - Compile to Java.
py - Compile to Python.
cpp - Compile to C++.
dfy - Compile to Dafny.
Note that the C++ backend has various limitations (see
Docs/Compilation/Cpp.md). This includes lack of support for
BigIntegers (aka int), most higher order functions, and advanced
features like traits or co-inductive types.".TrimStart(), "cs");
RegisterLegacyUi(CommonOptionBag.OptimizeErasableDatatypeWrapper, ParseBoolean, "Compilation options", "optimizeErasableDatatypeWrapper", @"
0 - Include all non-ghost datatype constructors in the compiled code
1 (default) - In the compiled target code, transform any non-extern
datatype with a single non-ghost constructor that has a single
non-ghost parameter into just that parameter. For example, the type
datatype Record = Record(x: int)
is transformed into just 'int' in the target code.".TrimStart(), defaultValue: true);
RegisterLegacyUi(CommonOptionBag.Output, ParseFileInfo, "Compilation options", "out");
RegisterLegacyUi(CommonOptionBag.UnicodeCharacters, ParseBoolean, "Language feature selection", "unicodeChar", @"
0 - The char type represents any UTF-16 code unit.
1 (default) - The char type represents any Unicode scalar value.".TrimStart(), defaultValue: true);
RegisterLegacyUi(CommonOptionBag.TypeSystemRefresh, ParseBoolean, "Language feature selection", "typeSystemRefresh", @"
0 (default) - The type-inference engine and supported types are those of Dafny 4.0.
1 - Use an updated type-inference engine. Warning: This mode is under construction and probably won't work at this time.".TrimStart(), defaultValue: false);
RegisterLegacyUi(CommonOptionBag.Plugin, ParseStringElement, "Plugins", defaultValue: new List<string>());
RegisterLegacyUi(CommonOptionBag.Prelude, ParseFileInfo, "Input configuration", "dprelude");
RegisterLegacyUi(CommonOptionBag.Libraries, ParseStringElement, "Compilation options", defaultValue: new List<string>());
RegisterLegacyUi(DeveloperOptionBag.ResolvedPrint, ParseString, "Overall reporting and printing", "rprint");
RegisterLegacyUi(DeveloperOptionBag.Print, ParseString, "Overall reporting and printing", "dprint");
RegisterLegacyUi(DafnyConsolePrinter.ShowSnippets, ParseBoolean, "Overall reporting and printing", "showSnippets", @"
0 (default) - Don't show source code snippets for Dafny messages.
1 - Show a source code snippet for each Dafny message.".TrimStart());
RegisterLegacyUi(Microsoft.Dafny.Printer.PrintMode, ParsePrintMode, "Overall reporting and printing", "printMode", legacyDescription: @"
Everything (default) - Print everything listed below.
DllEmbed - print the source that will be included in a compiled dll.
NoIncludes - disable printing of {:verify false} methods
incorporated via the include mechanism, as well as datatypes and
fields included from other files.
NoGhost - disable printing of functions, ghost methods, and proof
statements in implementation methods. It also disables anything
NoIncludes disables.".TrimStart(),
argumentName: "Everything|DllEmbed|NoIncludes|NoGhost",
defaultValue: PrintModes.Everything);
void ParsePrintMode(Option<PrintModes> option, Bpl.CommandLineParseState ps, DafnyOptions options) {
if (ps.ConfirmArgumentCount(1)) {
if (ps.args[ps.i].Equals("Everything")) {
options.Set(option, PrintModes.Everything);
} else if (ps.args[ps.i].Equals("NoIncludes")) {
options.Set(option, PrintModes.NoIncludes);
} else if (ps.args[ps.i].Equals("NoGhost")) {
options.Set(option, PrintModes.NoGhost);
} else if (ps.args[ps.i].Equals("DllEmbed")) {
options.Set(option, PrintModes.DllEmbed);
} else {
ps.Error("Invalid argument \"{0}\" to option {1}", ps.args[ps.i], option.Name);
}
}
}
}
public void ApplyBinding(Option option) {
if (legacyBindings.ContainsKey(option)) {
legacyBindings[option](this, Get(option));
}
}
public T Get<T>(Option<T> option) {
return (T)Options.OptionArguments.GetOrCreate(option, () => default(T));
}
public object Get(Option option) {
return Options.OptionArguments[option];
}
public void SetUntyped(Option option, object value) {
Options.OptionArguments[option] = value;
}
public void Set<T>(Option<T> option, T value) {
Options.OptionArguments[option] = value;
}
public void AddFile(string file) => base.AddFile(file, null);
private static Dictionary<Option, Action<DafnyOptions, object>> legacyBindings = new();
public static void RegisterLegacyBinding<T>(Option<T> option, Action<DafnyOptions, T> bind) {
legacyBindings[option] = (options, o) => bind(options, (T)o);
}
public static void ParseFileInfo(Option<FileInfo> option, Bpl.CommandLineParseState ps, DafnyOptions options) {
if (ps.ConfirmArgumentCount(1)) {
options.Set(option, new FileInfo(ps.args[ps.i]));
}
}
public static void ParseString(Option<string> option, Bpl.CommandLineParseState ps, DafnyOptions options) {
if (ps.ConfirmArgumentCount(1)) {
options.Set(option, ps.args[ps.i]);
}
}
public static void ParseStringElement(Option<IList<string>> option, Bpl.CommandLineParseState ps, DafnyOptions options) {
var value = (IList<string>)options.Options.OptionArguments.GetOrCreate(option, () => new List<string>());
if (ps.ConfirmArgumentCount(1)) {
value.Add(ps.args[ps.i]);
}
}
public static void ParseBoolean(Option<bool> option, Bpl.CommandLineParseState ps, DafnyOptions options) {
int result = 0;
if (ps.GetIntArgument(ref result, 2)) {
options.Set(option, result == 1);
}
}
private static readonly List<LegacyUiForOption> legacyUis = new();
public static void RegisterLegacyUi<T>(Option<T> option,
Action<Option<T>, Bpl.CommandLineParseState, DafnyOptions> parse,
string category, string legacyName = null, string legacyDescription = null, T defaultValue = default(T), string argumentName = null) {
legacyUis.Add(new LegacyUiForOption(
option,
(state, options) => parse(option, state, options),
category,
legacyName ?? option.Name,
legacyDescription ?? option.Description,
argumentName ?? option.ArgumentHelpName ?? "value",
defaultValue));
}
private static DafnyOptions defaultImmutableOptions;
public static DafnyOptions DefaultImmutableOptions => defaultImmutableOptions ??= Create();
public static DafnyOptions Create(params string[] arguments) {
var result = new DafnyOptions();
result.Parse(arguments);
return result;
}
public override bool Parse(string[] arguments) {
int i;
for (i = 0; i < arguments.Length; i++) {
if (arguments[i] == "--args") {
break;
}
}
if (i >= arguments.Length) {
return base.Parse(arguments);
}
MainArgs = arguments.Skip(i + 1).ToList();
return base.Parse(arguments.Take(i).ToArray());
}
public DafnyOptions()
: base("dafny", "Dafny program verifier", new Bpl.ConsolePrinter()) {
ErrorTrace = 0;
Prune = true;
NormalizeNames = true;
EmitDebugInformation = false;
Backend = new CsharpBackend(this);
Printer = new DafnyConsolePrinter(this);
Printer.Options = this;
}
public override string VersionNumber {
get {
return System.Diagnostics.FileVersionInfo
.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion;
}
}
public Options Options { get; set; } = new(new Dictionary<Option, object>());
public override string Version {
get { return ToolName + VersionSuffix; }
}
public override string VersionSuffix {
get { return " " + VersionNumber; }
}
public bool RunLanguageServer { get; set; }
public enum DiagnosticsFormats {
PlainText,
JSON,
}
public bool UsingNewCli = false;
public bool UnicodeOutput = false;
public DiagnosticsFormats DiagnosticsFormat = DiagnosticsFormats.PlainText;
public bool DisallowSoundnessCheating = false;
public int Induction = 4;
public int InductionHeuristic = 6;
public bool TypeInferenceDebug = false;
public string DafnyPrelude = null;
public string DafnyPrintFile = null;
public List<string> FoldersToFormat { get; } = new();
public enum ContractTestingMode {
None,
Externs,
TestedExterns,
}
public PrintModes PrintMode = PrintModes.Everything; // Default to printing everything
public bool DafnyVerify = true;
public string DafnyPrintResolvedFile = null;
public List<string> DafnyPrintExportedViews = new List<string>();
public bool Compile = true;
public List<string> MainArgs = new List<string>();
public bool Format = false;
public bool FormatCheck = false;
public string CompilerName;
public IExecutableBackend Backend;
public bool CompileVerbose = true;
public bool EnforcePrintEffects = false;
public string DafnyPrintCompiledFile = null;
public string CoverageLegendFile = null;
public string MainMethod = null;
public bool RunAllTests = false;
public bool ForceCompile = false;
public bool RunAfterCompile = false;
public uint SpillTargetCode = 0; // [0..4]
public bool DisallowIncludes = false;
public bool DisallowExterns = false;
public bool DisableNLarith = false;
public int ArithMode = 1; // [0..10]
public string AutoReqPrintFile = null;
public bool ignoreAutoReq = false;
public bool AllowGlobals = false;
public bool Optimize = false;
public bool AutoTriggers = true;
public bool RewriteFocalPredicates = true;
public bool PrintTooltips = false;
public bool PrintStats = false;
public bool DisallowConstructorCaseWithoutParentheses = false;
public bool PrintFunctionCallGraph = false;
public bool WarnShadowing = false;
public FunctionSyntaxOptions FunctionSyntax = FunctionSyntaxOptions.Version4;
public QuantifierSyntaxOptions QuantifierSyntax = QuantifierSyntaxOptions.Version4;
public int DefiniteAssignmentLevel = 1; // [0..5] 2 and 3 have the same effect, 4 turns off an array initialisation check and field initialization check, unless --enforce-determinism is used.
public HashSet<string> LibraryFiles { get; set; } = new();
public ContractTestingMode TestContracts = ContractTestingMode.None;
public bool ForbidNondeterminism { get; set; }
public int DeprecationNoise = 1;
public bool VerifyAllModules = false;
public bool SeparateModuleOutput = false;
public enum IncludesModes {
None,
Immediate,
Transitive
}
public IncludesModes PrintIncludesMode = IncludesModes.None;
public int OptimizeResolution = 2;
public bool IncludeRuntime = true;
public bool UseJavadocLikeDocstringRewriter = false;
public bool DisableScopes = false;
public int Allocated = 4;
public bool UseStdin = false;
public bool WarningsAsErrors = false;
[CanBeNull] private TestGenerationOptions testGenOptions = null;
public bool ExtractCounterexample = false;
public List<string> VerificationLoggerConfigs = new();
public bool AuditProgram = false;
public static string DefaultZ3Version = "4.12.1";
public static readonly ReadOnlyCollection<Plugin> DefaultPlugins =
new(new[] { SinglePassCompiler.Plugin, InternalDocstringRewritersPluginConfiguration.Plugin });
private IList<Plugin> cliPluginCache;
public IList<Plugin> Plugins => cliPluginCache ??= ComputePlugins();
public List<Plugin> AdditionalPlugins = new();
public IList<string> AdditionalPluginArguments = new List<string>();
IList<Plugin> ComputePlugins() {
var result = new List<Plugin>(DefaultPlugins.Concat(AdditionalPlugins));
foreach (var pluginAndArgument in AdditionalPluginArguments) {
try {
var pluginArray = pluginAndArgument.Split(',');
var pluginPath = pluginArray[0];
var arguments = Array.Empty<string>();
if (pluginArray.Length >= 2) {
// There are no commas in paths, but there can be in arguments
var argumentsString = string.Join(',', pluginArray.Skip(1));
// Parse arguments, accepting and remove double quotes that isolate long arguments
arguments = ParsePluginArguments(argumentsString);
}
result.Add(AssemblyPlugin.Load(pluginPath, arguments));
} catch (Exception e) {
result.Add(new ErrorPlugin(pluginAndArgument, e));
}
}
return result;
}
private static string[] ParsePluginArguments(string argumentsString) {
var splitter = new Regex(@"""(?<escapedArgument>(?:[^""\\]|\\\\|\\"")*)""|(?<rawArgument>[^ ]+)");
var escapedChars = new Regex(@"(?<escapedDoubleQuote>\\"")|\\\\");
return splitter.Matches(argumentsString).Select(
matchResult =>
matchResult.Groups["escapedArgument"].Success
? escapedChars.Replace(matchResult.Groups["escapedArgument"].Value,
matchResult2 => matchResult2.Groups["escapedDoubleQuote"].Success ? "\"" : "\\")
: matchResult.Groups["rawArgument"].Value
).ToArray();
}
/// <summary>
/// Automatic shallow-copy constructor
/// </summary>
public DafnyOptions(DafnyOptions src) : this() {
src.CopyTo(this);
}
public void CopyTo(DafnyOptions dst) {
var type = typeof(DafnyOptions);
while (type != null) {
var fields = type.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
foreach (var fi in fields) {
fi.SetValue(dst, fi.GetValue(this));
}
type = type.BaseType;
}
}
public virtual TestGenerationOptions TestGenOptions =>
testGenOptions ??= new TestGenerationOptions();
protected override bool ParseOption(string name, Bpl.CommandLineParseState ps) {
if (ParseDafnySpecificOption(name, ps)) {
return true;
}
foreach (var option in legacyUis.Where(o => o.Name == name)) {
option.Parse(ps, this);
return true;
}
return ParseBoogieOption(name, ps);
}
protected bool ParseBoogieOption(string name, Bpl.CommandLineParseState ps) {
return base.ParseOption(name, ps);
}
public override string Help => "Use 'dafny --help' to see help for a newer Dafny CLI format.\n" +
LegacyUiForOption.GenerateHelp(base.Help, legacyUis, true);
protected bool ParseDafnySpecificOption(string name, Bpl.CommandLineParseState ps) {
var args = ps.args; // convenient synonym
switch (name) {
case "view":
if (ps.ConfirmArgumentCount(1)) {
DafnyPrintExportedViews = args[ps.i].Split(',').ToList();
}
return true;
case "compile": {
int compile = 0;
if (ps.GetIntArgument(ref compile, 5)) {
// convert option to two booleans
Compile = compile != 0;
ForceCompile = compile == 2 || compile == 4;
RunAfterCompile = compile == 3 || compile == 4;
}
return true;
}
case "compileVerbose": {
int verbosity = 0;
if (ps.GetIntArgument(ref verbosity, 2)) {
CompileVerbose = verbosity == 1;
}
return true;
}
case "trackPrintEffects": {
int printEffects = 0;
if (ps.GetIntArgument(ref printEffects, 2)) {
EnforcePrintEffects = printEffects == 1;
}
return true;
}
case "Main":
case "main": {
if (ps.ConfirmArgumentCount(1)) {
MainMethod = args[ps.i];
}
return true;
}
case "check": {
if (!ps.hasColonArgument || ps.ConfirmArgumentCount(1)) {
FormatCheck = !ps.hasColonArgument || args[ps.i] == "1";
}
return true;
}
case "runAllTests": {
int runAllTests = 0;
if (ps.GetIntArgument(ref runAllTests, 2)) {
RunAllTests = runAllTests != 0; // convert to boolean
}
return true;
}
case "dafnyVerify": {
int verify = 0;
if (ps.GetIntArgument(ref verify, 2)) {
DafnyVerify = verify != 0; // convert to boolean
}
return true;
}
case "diagnosticsFormat": {
if (ps.ConfirmArgumentCount(1)) {
switch (args[ps.i]) {
case "json":
Printer = new DafnyJsonConsolePrinter(this);
DiagnosticsFormat = DiagnosticsFormats.JSON;
break;
case "text":
Printer = new DafnyConsolePrinter(this);
DiagnosticsFormat = DiagnosticsFormats.PlainText;
break;
case var df:
ps.Error($"Unsupported diagnostic format: '{df}'; expecting one of 'json', 'text'.");
break;
}
}
return true;
}
case "spillTargetCode": {
uint spill = 0;
if (ps.GetUnsignedNumericArgument(ref spill, x => true)) {
SpillTargetCode = spill;
}
return true;
}
case "coverage": {
if (ps.ConfirmArgumentCount(1)) {
CoverageLegendFile = args[ps.i];
}
return true;
}
case "noCheating": {
int cheat = 0; // 0 is default, allows cheating
if (ps.GetIntArgument(ref cheat, 2)) {
DisallowSoundnessCheating = cheat == 1;
}
return true;
}
case "titrace":
TypeInferenceDebug = true;
return true;
case "induction":
ps.GetIntArgument(ref Induction, 5);
return true;
case "inductionHeuristic":
ps.GetIntArgument(ref InductionHeuristic, 7);
return true;
case "noIncludes":
DisallowIncludes = true;
return true;
case "noExterns":
DisallowExterns = true;
return true;
case "noNLarith":
DisableNLarith = true;
return true;
case "arith": {
int a = 0;
if (ps.GetIntArgument(ref a, 11)) {
ArithMode = a;
}
return true;
}
case "mimicVerificationOf":
if (ps.ConfirmArgumentCount(1)) {
if (args[ps.i] == "3.3") {
Prune = false;
NormalizeNames = false;
EmitDebugInformation = true;
NormalizeDeclarationOrder = false;
} else {
ps.Error("Mimic verification is not supported for Dafny version {0}", ps.args[ps.i]);
}
}
return true;
case "autoReqPrint":
if (ps.ConfirmArgumentCount(1)) {
AutoReqPrintFile = args[ps.i];
}
return true;
case "noAutoReq":
ignoreAutoReq = true;
return true;
case "allowGlobals":
AllowGlobals = true;
return true;
case "stats":
PrintStats = true;
return true;
case "funcCallGraph":
PrintFunctionCallGraph = true;
return true;
case "warnShadowing":
WarnShadowing = true;
return true;
case "verifyAllModules":
VerifyAllModules = true;
return true;
case "separateModuleOutput":
SeparateModuleOutput = true;
return true;
case "deprecation": {
int d = 1;
if (ps.GetIntArgument(ref d, 3)) {
DeprecationNoise = d;
}
return true;
}
case "functionSyntax":
if (ps.ConfirmArgumentCount(1)) {
if (args[ps.i] == "3") {
FunctionSyntax = FunctionSyntaxOptions.Version3;
} else if (args[ps.i] == "4") {
FunctionSyntax = FunctionSyntaxOptions.Version4;
} else if (args[ps.i] == "migration3to4") {
FunctionSyntax = FunctionSyntaxOptions.Migration3To4;
} else if (args[ps.i] == "experimentalDefaultGhost") {
FunctionSyntax = FunctionSyntaxOptions.ExperimentalTreatUnspecifiedAsGhost;
} else if (args[ps.i] == "experimentalDefaultCompiled") {
FunctionSyntax = FunctionSyntaxOptions.ExperimentalTreatUnspecifiedAsCompiled;
} else if (args[ps.i] == "experimentalPredicateAlwaysGhost") {
FunctionSyntax = FunctionSyntaxOptions.ExperimentalPredicateAlwaysGhost;
} else {
InvalidArgumentError(name, ps);
}
}
return true;
case "quantifierSyntax":
if (ps.ConfirmArgumentCount(1)) {
if (args[ps.i] == "3") {
QuantifierSyntax = QuantifierSyntaxOptions.Version3;
} else if (args[ps.i] == "4") {
QuantifierSyntax = QuantifierSyntaxOptions.Version4;
} else {
InvalidArgumentError(name, ps);
}
}
return true;
case "printTooltips":
PrintTooltips = true;
return true;
case "warnMissingConstructorParentheses":
DisallowConstructorCaseWithoutParentheses = true;
return true;
case "autoTriggers": {
int autoTriggers = 0;
if (ps.GetIntArgument(ref autoTriggers, 2)) {
AutoTriggers = autoTriggers == 1;
}
return true;
}
case "rewriteFocalPredicates": {
int rewriteFocalPredicates = 0;
if (ps.GetIntArgument(ref rewriteFocalPredicates, 2)) {
RewriteFocalPredicates = rewriteFocalPredicates == 1;
}
return true;
}
case "optimize": {
Optimize = true;
return true;
}
case "allocated": {
ps.GetIntArgument(ref Allocated, 5);
if (Allocated != 4) {
Printer.AdvisoryWriteLine(Console.Out, "The /allocated:<n> option is deprecated");
}
return true;
}
case "optimizeResolution": {
int d = 2;
if (ps.GetIntArgument(ref d, 3)) {
OptimizeResolution = d;
}
return true;
}
case "definiteAssignment": {
int da = 0;
if (ps.GetIntArgument(ref da, 5)) {
DefiniteAssignmentLevel = da;
}
if (da == 3) {
ForbidNondeterminism = true;
}
return true;
}
case "useRuntimeLib": {
IncludeRuntime = false;
return true;
}
case "disableScopes": {
DisableScopes = true;
return true;
}
case "printIncludes":
if (ps.ConfirmArgumentCount(1)) {
if (args[ps.i].Equals("None")) {
PrintIncludesMode = IncludesModes.None;
} else if (args[ps.i].Equals("Immediate")) {
PrintIncludesMode = IncludesModes.Immediate;
} else if (args[ps.i].Equals("Transitive")) {
PrintIncludesMode = IncludesModes.Transitive;
} else {
InvalidArgumentError(name, ps);
}
if (PrintIncludesMode == IncludesModes.Immediate || PrintIncludesMode == IncludesModes.Transitive) {
Compile = false;
DafnyVerify = false;
}
}
return true;
case "stdin": {
UseStdin = true;
return true;
}
case "warningsAsErrors":
WarningsAsErrors = true;
return true;
case "extractCounterexample":
ExtractCounterexample = true;
return true;
case "verificationLogger":
if (ps.ConfirmArgumentCount(1)) {
if (args[ps.i].StartsWith("trx") || args[ps.i].StartsWith("csv") || args[ps.i].StartsWith("text")) {
VerificationLoggerConfigs.Add(args[ps.i]);
} else {
InvalidArgumentError(name, ps);
}
}
return true;
case "testContracts":
if (ps.ConfirmArgumentCount(1)) {
if (args[ps.i].Equals("Externs")) {
TestContracts = ContractTestingMode.Externs;
} else if (args[ps.i].Equals("TestedExterns")) {
TestContracts = ContractTestingMode.TestedExterns;
} else {
InvalidArgumentError(name, ps);
}
}
return true;
}
// Unless this is an option for test generation, defer to superclass
return TestGenOptions.ParseOption(name, ps) || base.ParseOption(name, ps);
}
private static string[] ParseInnerArguments(string argumentsString) {
var splitter = new Regex(@"""(?<escapedArgument>(?:[^""\\]|\\\\|\\"")*)""|(?<rawArgument>[^ ]+)");
var escapedChars = new Regex(@"(?<escapedDoubleQuote>\\"")|\\\\");
return splitter.Matches(argumentsString).Select(
matchResult =>
matchResult.Groups["escapedArgument"].Success
? escapedChars.Replace(matchResult.Groups["escapedArgument"].Value,
matchResult2 => matchResult2.Groups["escapedDoubleQuote"].Success ? "\"" : "\\")
: matchResult.Groups["rawArgument"].Value
).ToArray();
}
protected void InvalidArgumentError(string name, Bpl.CommandLineParseState ps) {
ps.Error("Invalid argument \"{0}\" to option {1}", ps.args[ps.i], name);
}
public override void ApplyDefaultOptions() {
foreach (var legacyUiOption in legacyUis) {
if (!Options.OptionArguments.ContainsKey(legacyUiOption.Option)) {
Options.OptionArguments[legacyUiOption.Option] = legacyUiOption.DefaultValue;
}
if (legacyBindings.ContainsKey(legacyUiOption.Option)) {
var value = Get(legacyUiOption.Option);
legacyBindings[legacyUiOption.Option](this, value);
}
}
ApplyDefaultOptionsWithoutSettingsDefault();
}
public void ApplyDefaultOptionsWithoutSettingsDefault() {
base.ApplyDefaultOptions();
Backend ??= new CsharpBackend(this);
// expand macros in filenames, now that LogPrefix is fully determined
if (!ProverOptions.Any(x => x.StartsWith("SOLVER=") && !x.EndsWith("=z3"))) {
var z3Version = SetZ3ExecutablePath();
SetZ3Options(z3Version);
}
// Ask Boogie to perform abstract interpretation
UseAbstractInterpretation = true;
Ai.J_Intervals = true;
}
public override string AttributeHelp =>
@"Dafny: The documentation about attributes is best viewed here:
https://dafny-lang.github.io/dafny/DafnyRef/DafnyRef#sec-attributes
The following attributes are supported by this version.
{:extern}
{:extern <s1:string>}
{:extern <s1:string>, <s2:string>}
NOTE: :extern is target-language dependent.
The extern modifier is used
* to alter the CompileName of entities such as modules, classes, methods, etc.,
* to alter the ReferenceName of the entities,
* to decide how to define external opaque types,
* to decide whether to emit target code or not, and
* to decide whether a declaration is allowed not to have a body.
The CompileName is the name for the entity when translating to one of the target languages.
The ReferenceName is the name used to refer to the entity in the target language.
A common use case of :extern is to avoid name clashes with existing library functions.
:extern takes 0, 1, or 2 (possibly empty) string arguments:
- 0: Dafny will use the Dafny name as the CompileName and not affect the ReferenceName
- 1: Dafny will use s1 as the CompileName, and replaces the last portion of the ReferenceName by s1.
When used on an opaque type, s1 is used as a hint as to how to declare that type when compiling.
- 2: Dafny will use s2 as the CompileName.
Dafny will use a combination of s1 and s2 such as for example s1.s2 as the ReferenceName
It may also be the case that one of the arguments is simply ignored.
Dafny does not perform sanity checks on the arguments---it is the user's responsibility not to generate
malformed target code.
{:compile}
The {:compile} attribute takes a boolean argument. It may be applied to any top-level declaration.
If that argument is false, then that declaration will not be compiled at all.
The difference with {:extern} is that {:extern} will still emit declaration code if necessary,
whereas {:compile false} will just ignore the declaration for compilation purposes.
{:main}
When executing a program, Dafny will first look for a method annotated with {:main}, and otherwise
will look for `method Main()`, and then execute the first of these two methods found.
{:axiom}
Ordinarily, the compiler gives an error for every function or
method without a body. If the function or method is ghost, then
marking it with {:axiom} suppresses the error. The {:axiom}
attribute says you're taking responsibility for the existence
of a body for the function or method.
{:abstemious}
TODO
{:print}
This attributes declares that a method may have print effects,
that is, it may use 'print' statements and may call other methods
that have print effects. The attribute can be applied to compiled
methods, constructors, and iterators, and it gives an error if
applied to functions or ghost methods. An overriding method is
allowed to use a {:print} attribute only if the overridden method
does.
Print effects are enforced only with /trackPrintEffects:1.
{:nativeType}
Can be applied to newtype declarations for integer types and
indicates an expectation of what native type (or not) the
newtype should compile to.
If a newtype declaration has no explicit :nativeType attribute,
then the compiler still attempts to find a suitable native numeric
type, which is then reflected in an informational message or
hovertext.
{:nativeType} and {:nativeType true} say that the type is expected
to compile to some native numeric type, but leaves it to the
compiler to choose which one. If no suitable native target type is
found, an error is generated.
{:nativeType false} says to avoid using a native numeric type.
Instead, the type will be compiled as an unbounded integer.
{:nativeType X} where X is one of the following strings:
""byte"" 8 bits, unsigned
""sbyte"" 8 bits, signed
""ushort"" 16 bits, unsigned
""short"" 16 bits, signed
""uint"" 32 bits, unsigned
""int"" 32 bits, signed
""number"" 53 bits, signed
""ulong"" 64 bits, unsigned
""long"" 64 bits, signed
says to use the indicated target type. If the target compiler
does not support X, then an error is generated. Also, if, after
scrutinizing the constraint predicate, the compiler cannot confirm
that the type's values will fit in X, an error is generated.
{:nativeType XX} where XX is a list of strings from the list above,
says to use the first X in XX that the compiler supports. If
the compiler doesn't support any native type in XX, then an error
is generated. Also, unless the compiler can confirm that all of
the listed native types can fit the type's values, an error is
generated.
{:tailrecursion}
Can be applied to methods and functions to direct compilation of
recursive calls as tail calls.
A method or function is _tail recursive_ if all of the following
points apply:
* It is not mutually recursive with another method or function.
* Ignoring any parts of the method/function body that are ghost,
every recursive call is a tail call (that is, the body has no
more work to do after a recursive call). Note that any ghost
code that follows a recursive method call is ignored.
* In the case of a function, the function is not used as a
first-class value inside the function body.
For a function F, this definition is extended to additionally allow
tail calls to appear in simple expressions like ""E + F(...)"" or
""F(...) + E"" for certain operators ""+"" where E does not mention
F, provided that all such expressions are compatible. These
are called _simple accumulator_ tail calls.
By default, Dafny compiles tail recursive methods and functions
using tail calls, automatically handling simple accumulator tail
calls.
{:tailrecursion false} is used to turn off tail calls.
{:tailrecursion} or {:tailrecursion true} is used to confirm
that the method/function is compiled and tail recursive. If it
is not, an error is given.
{:termination}
Dafny currently lacks the features needed to specify usable termination
metrics for trait methods that are dynamically dispatched to method
implementations given in other modules. This issue and a sketch of a
solution are described in https://github.com/dafny-lang/dafny/issues/1588.
Until such features are added to the language, a type `C` that extends a
trait `T` must be declared in the same module as `T`.
There is, however, an available loophole: if a programmer is willing to
take the responsibility that all calls to methods in a trait `T`
that dynamically dispatch to implementations in other modules terminate,
then the trait `T` can be marked with `{:termination false}`. This will
allow `T` to be extended by types declared in modules outside `T`'s module.
Caution: This loophole is unsound; that is, if a cross-module dynamic
dispatch fails to terminate, then this and other errors in the program
may have been overlooked by the verifier.
The meaning of `{:termination false}` is defined only on trait declarations.
It has no meaning if applied to other declarations.
Applying `{:termination false}` to a trait is similar to the
effect of declaring each of its methods with `decreases *`, but
there are several differences. The biggest difference is that
`decreases *` is sound, whereas the attribute is not. As such,
`decreases *` cannot be used with functions, lemmas, or ghost
methods, and callers of a `decreases *` method must themselves
be declared with `decreases *`. In contrast, `{:termination false}`
applies to all functions, lemmas, and methods of the trait, and
callers do not have to indicate that they are using such a
trait. Another difference is that `{:termination false}` does
not change checking for intra-module calls. That is, even if a
trait is declared with `{:termination false}`, calls to its
functions, lemmas, and methods from within the module where the
trait is declared are checked for termination in the usual