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

Why does implicit type conversion from Int to UInt not work?

我正在尝试学习 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 已经有一个像我的转换器一样的隐式类型转换器,但这可能不正确。

我的错误在哪里?

我认为最接近的答案是第二个答案here。 简而言之,因为 VecInit 是用 [T <: Data] 参数化的,所以不会搜索 T 的整个 space 来查看隐式转换可能 return a T.

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

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

我想指出早期版本的 chisel 允许 VecInit 及其盟友使用 Int 参数。我们的经验是要求特定的硬件类型不易出错且更易于阅读。将 .U 添加到数字中是相当低的样板文件开销。

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