viperproject/silicon

Missing hashCode definitions

Closed this issue · 2 comments

fpoli commented

The Scalastyle linter complains about missing hashCode definitions in Silicon. I'm not sure if we did that intentionally but it seems worth double-checking, adding a comment to Silicon if there is nothing to fix.

Defining either equals() or hashCode() in a class without defining the other is a known source of bugs. Usually, when you define one, you should also define the other.

Further Reading: Scalastyle - EqualsHashCode

final class Rational(n: BigInt, d: BigInt) extends Ordered[Rational] {
require(d != 0, "Denominator of Rational must not be 0.")
private val g = n.gcd(d)
val numerator: BigInt = n / g * d.signum
val denominator: BigInt = d.abs / g
def +(that: Rational): Rational = {
val newNum = this.numerator * that.denominator + that.numerator * this.denominator
val newDen = this.denominator * that.denominator
Rational(newNum, newDen)
}
def -(that: Rational): Rational = this + (-that)
def unary_- = Rational(-numerator, denominator)
def abs = Rational(numerator.abs, denominator)
def signum = Rational(numerator.signum, 1)
def *(that: Rational): Rational = Rational(this.numerator * that.numerator, this.denominator * that.denominator)
def /(that: Rational): Rational = this * that.inverse
def inverse = Rational(denominator, numerator)
def compare(that: Rational) = (this.numerator * that.denominator - that.numerator * this.denominator).signum
override def equals(obj: Any) = obj match {
case that: Rational => this.numerator == that.numerator && this.denominator == that.denominator
case _ => false
}
override lazy val toString = s"$numerator/$denominator"
}

case class MagicWandIdentifier(ghostFreeWand: ast.MagicWand)(override val hashCode: Int) extends ChunkIdentifer {
override def equals(obj: Any): Boolean = obj match {
case w: MagicWandIdentifier => this.hashCode == w.hashCode
case _ => false
}
override lazy val toString = s"wand@${hashCode.toString}"
}

I'm confused. Don't the first two have both explicit equals and hashCode definitions? The other two look potentially problematic, I agree.

fpoli commented

I'm confused. Don't the first two have both explicit equals and hashCode definitions?

Yes, sorry. I just copy-pasted the warnings, but I guess that the linter didn't see the val methods.