Skip to content

Commit

Permalink
chore: Improve code (#5042)
Browse files Browse the repository at this point in the history
This PR consists only of minor code changes, like using more modern C#
constructions. (These particular changes were ones I came across as I
was working on other PRs, so they make no attempt at being exhaustive.)

Notes:
* The PR updates `.gitignore`
* There are lots of new calls to `Expression.CreateBoolLiteral`, which
creates a resolved boolean literal AST node. If I remember correctly,
one of those changes was actually a bug fix. I'm afraid I don't have the
test case in this PR, but it's somewhere in my upcoming PRs.
* In one place, I spotted a Rider warning that an enumeration was used
twice. I fixed that my adding a `.ToList()`.
* We don't really use `cce.NonNull` anymore, since Rider does some
static null checking. So, I removed some such wrapper that I thought
just cluttered up the code. (Historic note: Dafny was originally written
in Spec#, and then these had been `(!)` casts. When Spec# was at its end
of life, the Boogie and Dafny sources were converted to C#, at which
point these non-null casts were turned into the `cce.NonNull` wrappers.)
* A call to `Expression.IsIntLiteral` was assuming something about the
out-parameter when the method return `false`. I changed this to instead
look at the return value.

<small>By submitting this pull request, I confirm that my contribution
is made under the terms of the [MIT
license](https://github.com/dafny-lang/dafny/blob/master/LICENSE.txt).</small>
  • Loading branch information
RustanLeino authored Feb 2, 2024
1 parent aec4f71 commit fae62e6
Show file tree
Hide file tree
Showing 33 changed files with 7,161 additions and 7,220 deletions.
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,9 @@ docs/dev/*.fix
docs/dev/*.feat
docs/dev/*.break

Source/IntegrationTests/TestFiles/LitTests/LitTest/server/*.bvd
/Source/IntegrationTests/TestFiles/LitTests/LitTest/separate-verification/Inputs/wrappers3.doo
/Source/IntegrationTests/TestFiles/LitTests/LitTest/comp/replaceables/complex/Build1
/Source/IntegrationTests/TestFiles/LitTests/LitTest/separate-verification/assumptions-lib
/Source/IntegrationTests/TestFiles/LitTests/LitTest/cli/log.smt2
/Source/IntegrationTests/TestFiles/LitTests/LitTest/git-issues/model
Original file line number Diff line number Diff line change
Expand Up @@ -105,12 +105,13 @@ static Expression ChooseBestIntegerBound([CanBeNull] Expression a, [CanBeNull] E
return a ?? b;
}

if (Expression.IsIntLiteral(Expression.StripParensAndCasts(a), out var aa) &&
Expression.IsIntLiteral(Expression.StripParensAndCasts(b), out var bb)) {
if (Expression.IsIntLiteral(a, out var aa) && Expression.IsIntLiteral(b, out var bb)) {
var x = pickMax ? BigInteger.Max(aa, bb) : BigInteger.Min(aa, bb);
return new LiteralExpr(a.tok, x) { Type = a.Type };
}
return a; // we don't know how to determine which of "a" or "b" is better, so we'll just return "a"
// we don't know how to determine which of "a" or "b" is better, so we'll just return "a"
// (better would be to return an expression that computes to the minimum of "a" and "b")
return a;
}

public static List<VT> MissingBounds<VT>(List<VT> vars, List<BoundedPool> bounds, PoolVirtues requiredVirtues = PoolVirtues.None) where VT : IVariable {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ private void InitializeAttributes() {
foreach (var c in this.Cases) {
if (!Attributes.Contains(c.Attributes, "split")) {
List<Expression> args = new List<Expression>();
args.Add(new LiteralExpr(c.Tok, splitMatch));
args.Add(Expression.CreateBoolLiteral(c.Tok, splitMatch));
Attributes attrs = new Attributes("split", args, c.Attributes);
c.Attributes = attrs;
}
Expand Down
19 changes: 10 additions & 9 deletions Source/DafnyCore/AST/Expressions/Expression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -418,8 +418,9 @@ public static Expression CreateNatLiteral(IToken tok, int n, Type ty) {
/// </summary>
public static LiteralExpr CreateBoolLiteral(IToken tok, bool b) {
Contract.Requires(tok != null);
var lit = new LiteralExpr(tok, b);
lit.Type = Type.Bool; // resolve here
var lit = new LiteralExpr(tok, b) {
Type = Type.Bool
};
return lit;
}

Expand All @@ -429,8 +430,9 @@ public static LiteralExpr CreateBoolLiteral(IToken tok, bool b) {
public static LiteralExpr CreateStringLiteral(IToken tok, string s) {
Contract.Requires(tok != null);
Contract.Requires(s != null);
var lit = new StringLiteralExpr(tok, s, true);
lit.Type = new SeqType(new CharType()); // resolve here
var lit = new StringLiteralExpr(tok, s, true) {
Type = new SeqType(new CharType())
};
return lit;
}

Expand All @@ -440,8 +442,7 @@ public static LiteralExpr CreateStringLiteral(IToken tok, string s) {
/// </summary>
public static Expression StripParens(Expression expr) {
while (true) {
var e = expr as ParensExpression;
if (e == null) {
if (expr is not ParensExpression e) {
return expr;
}
expr = e.E;
Expand Down Expand Up @@ -493,11 +494,11 @@ public static bool IsBoolLiteral(Expression expr, out bool value) {
/// </summary>
public static bool IsIntLiteral(Expression expr, out BigInteger value) {
Contract.Requires(expr != null);
var e = StripParens(expr) as LiteralExpr;
if (e != null && e.Value is int x) {
var e = StripParensAndCasts(expr) as LiteralExpr;
if (e is { Value: int x }) {
value = new BigInteger(x);
return true;
} else if (e != null && e.Value is BigInteger xx) {
} else if (e is { Value: BigInteger xx }) {
value = xx;
return true;
} else {
Expand Down
4 changes: 2 additions & 2 deletions Source/DafnyCore/AST/Expressions/Operators/BinaryExpr.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ public enum ResolvedOpcode {
Le,
Ge,
Gt,
Add,
Sub,
Add, // also used for char
Sub, // also used for char
Mul,
Div,
Mod,
Expand Down
4 changes: 2 additions & 2 deletions Source/DafnyCore/AST/Expressions/StmtExpr.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,9 @@ public Expression GetSConclusion() {
var s = (CalcStmt)S;
return s.Result;
} else if (S is RevealStmt) {
return new LiteralExpr(tok, true); // one could use the definition axiom or the referenced labeled assertions, but "true" is conservative and much simpler :)
return CreateBoolLiteral(tok, true); // one could use the definition axiom or the referenced labeled assertions, but "true" is conservative and much simpler :)
} else if (S is UpdateStmt) {
return new LiteralExpr(tok, true); // one could use the postcondition of the method, suitably instantiated, but "true" is conservative and much simpler :)
return CreateBoolLiteral(tok, true); // one could use the postcondition of the method, suitably instantiated, but "true" is conservative and much simpler :)
} else {
Contract.Assert(false); throw new cce.UnreachableException(); // unexpected statement
}
Expand Down
3 changes: 1 addition & 2 deletions Source/DafnyCore/AST/Members/Function.cs
Original file line number Diff line number Diff line change
Expand Up @@ -536,8 +536,7 @@ public void AutoRevealDependencies(AutoRevealFunctionDependencies Rewriter, Dafn
}

if (autoRevealDepth > 0) {
Expression reqExpr = new LiteralExpr(Tok, true);
reqExpr.Type = Type.Bool;
Expression reqExpr = Expression.CreateBoolLiteral(Tok, true);

var bodyExpr = Body;

Expand Down
4 changes: 1 addition & 3 deletions Source/DafnyCore/AST/Members/Method.cs
Original file line number Diff line number Diff line change
Expand Up @@ -450,9 +450,7 @@ public void AutoRevealDependencies(AutoRevealFunctionDependencies Rewriter, Dafn
}

if (autoRevealDepth > 0) {
Expression reqExpr = new LiteralExpr(Tok, true) {
Type = Type.Bool
};
Expression reqExpr = Expression.CreateBoolLiteral(Tok, true);

foreach (var revealStmt in addedReveals) {
if (revealStmt.Depth <= autoRevealDepth) {
Expand Down
4 changes: 3 additions & 1 deletion Source/DafnyCore/AST/Substituter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -519,7 +519,9 @@ public ComprehensionExpr.BoundedPool SubstituteBoundedPool(ComprehensionExpr.Bou
return bound; // nothing to substitute
} else if (bound is ComprehensionExpr.IntBoundedPool) {
var b = (ComprehensionExpr.IntBoundedPool)bound;
return new ComprehensionExpr.IntBoundedPool(b.LowerBound == null ? null : Substitute(b.LowerBound), b.UpperBound == null ? null : Substitute(b.UpperBound));
return new ComprehensionExpr.IntBoundedPool(
b.LowerBound == null ? null : Substitute(b.LowerBound),
b.UpperBound == null ? null : Substitute(b.UpperBound));
} else if (bound is ComprehensionExpr.SetBoundedPool) {
var b = (ComprehensionExpr.SetBoundedPool)bound;
return new ComprehensionExpr.SetBoundedPool(Substitute(b.Set), b.BoundVariableType, b.CollectionElementType, b.IsFiniteCollection);
Expand Down
6 changes: 2 additions & 4 deletions Source/DafnyCore/AST/TypeDeclarations/NewtypeDecl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,7 @@ public NewtypeDecl(RangeToken rangeToken, Name name, ModuleDefinition module, Ty
this.NewSelfSynonym();
}
public NewtypeDecl(RangeToken rangeToken, Name name, ModuleDefinition module, BoundVar bv, Expression constraint,
SubsetTypeDecl.WKind witnessKind, Expression witness, List<Type> parentTraits, List<MemberDecl> members, Attributes attributes, bool isRefining)
: base(rangeToken, name, module, new List<TypeParameter>(), members, attributes, isRefining, parentTraits) {
SubsetTypeDecl.WKind witnessKind, Expression witness, List<Type> parentTraits, List<MemberDecl> members, Attributes attributes, bool isRefining) : base(rangeToken, name, module, new List<TypeParameter>(), members, attributes, isRefining, parentTraits) {
Contract.Requires(rangeToken != null);
Contract.Requires(name != null);
Contract.Requires(module != null);
Expand All @@ -49,8 +48,7 @@ public NewtypeDecl(RangeToken rangeToken, Name name, ModuleDefinition module, Bo
this.NewSelfSynonym();
}

/// <summary>
/// Return .BaseType instantiated with "typeArgs", but only look at the part of .BaseType that is in scope.
/// <summary> /// Return .BaseType instantiated with "typeArgs", but only look at the part of .BaseType that is in scope.
/// </summary>
public Type RhsWithArgument(List<Type> typeArgs) {
Contract.Requires(typeArgs != null);
Expand Down
1 change: 0 additions & 1 deletion Source/DafnyCore/AST/TypeDeclarations/SubsetTypeDecl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ public class SubsetTypeDecl : TypeSynonymDecl, RedirectingTypeDecl, ICanAutoReve
public enum WKind { CompiledZero, Compiled, Ghost, OptOut, Special }
public readonly WKind WitnessKind;
public Expression/*?*/ Witness; // non-null iff WitnessKind is Compiled or Ghost
[FilledInDuringResolution] public bool CheckedIfConstraintIsCompilable = false; // Set to true lazily by the Resolver when the Resolver fills in "ConstraintIsCompilable".

[FilledInDuringResolution] bool RedirectingTypeDecl.ConstraintIsCompilable { get; set; }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public Type RhsWithArgumentIgnoringScope(List<Type> typeArgs) {
Expression RedirectingTypeDecl.Constraint { get { return null; } }

bool RedirectingTypeDecl.ConstraintIsCompilable {
get => false;
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}

Expand Down
13 changes: 4 additions & 9 deletions Source/DafnyCore/AST/Types/Types.cs
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,7 @@ public string TypeArgsToString(DafnyOptions options, ModuleDefinition/*?*/ conte
public void AddFreeTypeParameters(ISet<TypeParameter> tps) {
Contract.Requires(tps != null);
var ty = this.NormalizeExpandKeepConstraints();
var tp = ty.AsTypeParameter;
if (tp != null) {
if (ty.AsTypeParameter is { } tp) {
tps.Add(tp);
}
foreach (var ta in ty.TypeArgs) {
Expand Down Expand Up @@ -186,9 +185,7 @@ public Type NormalizeExpand(ExpandMode expandMode = ExpandMode.ExpandSynonymsAnd

Type type = this;
while (true) {

var pt = type as TypeProxy;
if (pt != null && pt.T != null) {
if (type is TypeProxy { T: not null } pt) {
type = pt.T;
continue;
}
Expand Down Expand Up @@ -579,15 +576,13 @@ public UserDefinedType AsNonNullRefType {
get {
var t = this;
while (true) {
var udt = t.NormalizeExpandKeepConstraints() as UserDefinedType;
if (udt == null) {
if (t.NormalizeExpandKeepConstraints() is not UserDefinedType udt) {
return null;
}
if (udt.ResolvedClass is NonNullTypeDecl) {
return udt;
}
var sst = udt.ResolvedClass as SubsetTypeDecl;
if (sst != null) {
if (udt.ResolvedClass is SubsetTypeDecl sst) {
t = sst.RhsWithArgument(udt.TypeArgs); // continue the search up the chain of subset types
} else {
return null;
Expand Down
3 changes: 1 addition & 2 deletions Source/DafnyCore/CompileNestedMatch/MatchFlattener.cs
Original file line number Diff line number Diff line change
Expand Up @@ -396,8 +396,7 @@ private CaseBody CompileHeadsContainingConstructor(MatchCompilationState mti, Ma
}

var args = new List<Expression>();
var literalExpr = new LiteralExpr(mti.Tok, false);
literalExpr.Type = Type.Bool;
var literalExpr = Expression.CreateBoolLiteral(mti.Tok, false);
args.Add(literalExpr);
c.Attributes = new Attributes("split", args, c.Attributes);
}
Expand Down
10 changes: 5 additions & 5 deletions Source/DafnyCore/Compilers/CSharp/Compiler-Csharp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2205,8 +2205,8 @@ protected override void EmitLiteralExpr(ConcreteSyntaxTree wr, LiteralExpr e) {
}
} else if (e is StringLiteralExpr str) {
wr.Format($"{DafnySeqClass}<{CharTypeName}>.{CharMethodQualifier}FromString({StringLiteral(str)})");
} else if (AsNativeType(e.Type) != null) {
GetNativeInfo(AsNativeType(e.Type).Sel, out var nativeName, out var literalSuffix, out var needsCastAfterArithmetic);
} else if (AsNativeType(e.Type) is { } nativeType) {
GetNativeInfo(nativeType.Sel, out var nativeName, out var literalSuffix, out var needsCastAfterArithmetic);
if (needsCastAfterArithmetic) {
wr = wr.Write($"({nativeName})").ForkInParens();
}
Expand Down Expand Up @@ -2290,11 +2290,11 @@ protected override ConcreteSyntaxTree EmitBitvectorTruncation(BitvectorType bvTy

protected override void EmitRotate(Expression e0, Expression e1, bool isRotateLeft, ConcreteSyntaxTree wr,
bool inLetExprBody, ConcreteSyntaxTree wStmts, FCE_Arg_Translator tr) {
string nativeName = null, literalSuffix = null;
string nativeName = null;
bool needsCast = false;
var nativeType = AsNativeType(e0.Type);
if (nativeType != null) {
GetNativeInfo(nativeType.Sel, out nativeName, out literalSuffix, out needsCast);
GetNativeInfo(nativeType.Sel, out nativeName, out _, out needsCast);
}

// ( e0 op1 e1) | (e0 op2 (width - e1))
Expand All @@ -2308,7 +2308,7 @@ protected override void EmitRotate(Expression e0, Expression e1, bool isRotateLe
EmitShift(e0, e1, isRotateLeft ? ">>" : "<<", !isRotateLeft, nativeType, false, wr.ForkInParens(), inLetExprBody, wStmts, tr);
}

void EmitShift(Expression e0, Expression e1, string op, bool truncate, NativeType nativeType /*?*/, bool firstOp,
private void EmitShift(Expression e0, Expression e1, string op, bool truncate, [CanBeNull] NativeType nativeType, bool firstOp,
ConcreteSyntaxTree wr, bool inLetExprBody, ConcreteSyntaxTree wStmts, FCE_Arg_Translator tr) {
var bv = e0.Type.AsBitVectorType;
if (truncate) {
Expand Down
1 change: 0 additions & 1 deletion Source/DafnyCore/Compilers/Dafny/Compiler-dafny.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1885,7 +1885,6 @@ protected override void EmitDestructor(Action<ConcreteSyntaxTree> source, Formal
}
}

protected override bool TargetLambdasRestrictedToExpressions => true;
protected override ConcreteSyntaxTree CreateLambda(List<Type> inTypes, IToken tok, List<string> inNames,
Type resultType, ConcreteSyntaxTree wr, ConcreteSyntaxTree wStmts, bool untyped = false) {
if (wr is BuilderSyntaxTree<ExprContainer> builder) {
Expand Down
10 changes: 5 additions & 5 deletions Source/DafnyCore/Compilers/Java/Compiler-java.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1133,8 +1133,8 @@ protected override void EmitLiteralExpr(ConcreteSyntaxTree wr, LiteralExpr e) {
wr.Write(UnicodeCharEnabled ? $"{DafnySeqClass}.asUnicodeString(" : $"{DafnySeqClass}.asString(");
TrStringLiteral(str, wr);
wr.Write(")");
} else if (AsNativeType(e.Type) is NativeType nt) {
EmitNativeIntegerLiteral((BigInteger)e.Value, nt, wr);
} else if (AsNativeType(e.Type) is { } nativeType) {
EmitNativeIntegerLiteral((BigInteger)e.Value, nativeType, wr);
} else if (e.Value is BigInteger i) {
if (i.IsZero) {
wr.Write("java.math.BigInteger.ZERO");
Expand Down Expand Up @@ -1742,11 +1742,11 @@ protected override void EmitIndexCollectionUpdate(Expression source, Expression

protected override void EmitRotate(Expression e0, Expression e1, bool isRotateLeft, ConcreteSyntaxTree wr,
bool inLetExprBody, ConcreteSyntaxTree wStmts, FCE_Arg_Translator tr) {
string nativeName = null, literalSuffix = null;
string nativeName = null;
bool needsCast = false;
var nativeType = AsNativeType(e0.Type);
if (nativeType != null) {
GetNativeInfo(nativeType.Sel, out nativeName, out literalSuffix, out needsCast);
GetNativeInfo(nativeType.Sel, out nativeName, out _, out needsCast);
}
var leftShift = nativeType == null ? ".shiftLeft" : "<<";
var rightShift = nativeType == null ? ".shiftRight" : ">>>";
Expand All @@ -1770,7 +1770,7 @@ protected override void EmitRotate(Expression e0, Expression e1, bool isRotateLe
}
}

void EmitShift(Expression e0, Expression e1, string op, bool truncate, NativeType nativeType /*?*/, bool firstOp,
private void EmitShift(Expression e0, Expression e1, string op, bool truncate, [CanBeNull] NativeType nativeType, bool firstOp,
ConcreteSyntaxTree wr, bool inLetExprBody, ConcreteSyntaxTree wStmts, FCE_Arg_Translator tr) {
var bv = e0.Type.AsBitVectorType;
if (truncate) {
Expand Down
3 changes: 1 addition & 2 deletions Source/DafnyCore/Compilers/Python/Compiler-python.cs
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ protected override IClassWriter CreateClass(string moduleName, string name, bool
: "";
var methodWriter = wr.NewBlockPy(header: $"class {IdProtect(name)}{baseClasses}:");

var relevantTypeParameters = typeParameters.Where(NeedsTypeDescriptor);
var relevantTypeParameters = typeParameters.Where(NeedsTypeDescriptor).ToList();
var args = relevantTypeParameters.Comma(tp => tp.GetCompileName(Options));
if (!string.IsNullOrEmpty(args)) { args = $", {args}"; }
var isNewtypeWithTraits = cls is NewtypeDecl { ParentTraits: { Count: > 0 } };
Expand Down Expand Up @@ -1404,7 +1404,6 @@ protected override void EmitDestructor(Action<ConcreteSyntaxTree> source, Formal
}
}

protected override bool TargetLambdasRestrictedToExpressions => true;
protected override ConcreteSyntaxTree CreateLambda(List<Type> inTypes, IToken tok, List<string> inNames,
Type resultType, ConcreteSyntaxTree wr, ConcreteSyntaxTree wStmts, bool untyped = false) {
var functionName = ProtectedFreshId("_lambda");
Expand Down
Loading

0 comments on commit fae62e6

Please sign in to comment.