为什么从 Int 到 UInt 的隐式类型转换不起作用



我正在尝试学习chisel3,并且我还尝试在特定情况下使用从Int到UInt的隐式类型转换。

以下是我的代码。

package VecTest
import chisel3._
import scala.language.implicitConversions
object VecTestMain extends App {
  Driver.execute(args, () => new VecTest)
}

object VecTest {
  implicit def int2UInt(x: Int) = new fromtIntToLiteral(x).U
}
class VecTest extends Module {
  import VecTest._
  val io = IO(new Bundle{
    val in  = Input(UInt(1.W))
    val out = Output(UInt(8.W))
  })
  val v = VecInit(0x20, 0x30)
  io.out := v(io.in)
}

我预计 scala 编译器将尝试将 VecInit 中的两个值从 Int 转换为 UInt,但编译器报告如下错误。

[error] /src/directory/this/code/VecTest/VecTest.scala:23:11: inferred type arguments [Int] do not conform to macro method apply's type parameter bounds [T <: chisel3.core.Data]
[error]   val v = VecInit(0x20, 0x30)
[error]           ^
[error] /src/directory/this/code/VecTest/VecTest.scala:23:19: type mismatch;
[error]  found   : Int(32)
[error]  required: T
[error]   val v = VecInit(0x20, 0x30)
[error]                   ^
[error] /src/directory/this/code/VecTest/VecTest.scala:23:25: type mismatch;
[error]  found   : Int(48)
[error]  required: T
[error]   val v = VecInit(0x20, 0x30)
[error]                         ^
[error] three errors found

首先,由于超出范围,编译器无法获得int2UIntobject VecTest中的隐式转换器函数)。但是,当我像下面这样修复代码时,它会起作用。

val v = VecInit(int2UInt(0x20), int2UInt(0x30))

我还假设 chisel3 已经有一个像我的转换器这样的隐式类型转换器,但这可能不正确。

我的失误在哪里?

我认为最接近的答案是这里的第二个答案。简而言之,由于 VecInit 是使用 [T <:数据] 进行参数化的,因此不会搜索 T 的整个空间以查看隐式转换可能返回 T。

您可以像这样手动强制正确的隐式

val v = VecInit[UInt](0x20, 0x30)

我想指出的是,早期版本的凿子允许在 VecInit 及其盟友上使用 Int 参数。我们的经验是,需要特定的硬件类型更不容易出错,并且更易于阅读。 添加。你对数字是相当低的样板开销。

val v = VecInit(0x20.U, 0x30.U)

最新更新