Skip to content

Commit

Permalink
Provide require message for negative widths (#4008)
Browse files Browse the repository at this point in the history
(cherry picked from commit 751a4cf)

# Conflicts:
#	core/src/main/scala/chisel3/Width.scala
  • Loading branch information
jackkoenig authored and mergify[bot] committed Apr 17, 2024
1 parent daede76 commit dfe9e68
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
47 changes: 47 additions & 0 deletions core/src/main/scala/chisel3/Width.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// SPDX-License-Identifier: Apache-2.0

package chisel3

object Width {
def apply(x: Int): Width = KnownWidth(x)
def apply(): Width = UnknownWidth()
}

sealed abstract class Width {
type W = Int
def min(that: Width): Width = this.op(that, _ min _)
def max(that: Width): Width = this.op(that, _ max _)
def +(that: Width): Width = this.op(that, _ + _)
def +(that: Int): Width = this.op(this, (a, b) => a + that)
@deprecated(
"The width of shift-right now differs by type, use unsignedShiftRight and signedShiftRight",
"Chisel 7.0.0"
)
def shiftRight(that: Int): Width = this.op(this, (a, b) => 0.max(a - that))
def unsignedShiftRight(that: Int): Width = this.op(this, (a, b) => 0.max(a - that))
def signedShiftRight(that: Int): Width = this.op(this, (a, b) => 1.max(a - that))
def dynamicShiftLeft(that: Width): Width =
this.op(that, (a, b) => a + (1 << b) - 1)

def known: Boolean
def get: W
protected def op(that: Width, f: (W, W) => W): Width
}

sealed case class UnknownWidth() extends Width {
def known: Boolean = false
def get: Int = None.get
def op(that: Width, f: (W, W) => W): Width = this
override def toString: String = ""
}

sealed case class KnownWidth(value: Int) extends Width {
require(value >= 0, s"Widths must be non-negative, got $value")
def known: Boolean = true
def get: Int = value
def op(that: Width, f: (W, W) => W): Width = that match {
case KnownWidth(x) => KnownWidth(f(value, x))
case _ => that
}
override def toString: String = s"<${value.toString}>"
}
5 changes: 5 additions & 0 deletions src/test/scala/chiselTests/UIntOps.scala
Original file line number Diff line number Diff line change
Expand Up @@ -479,4 +479,9 @@ class UIntOpsSpec extends ChiselPropSpec with Matchers with Utils {
chirrtl should include("y <= a")
chirrtl should include("z <= b")
}

property("UInts with negative widths should have a decent error message") {
val e = the[IllegalArgumentException] thrownBy (UInt(-8.W))
e.getMessage should include("Widths must be non-negative, got -8")
}
}

0 comments on commit dfe9e68

Please sign in to comment.