简体   繁体   English

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

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

I'm trying to learn chisel3, and I also try to be able to use implicit type conversion from Int to UInt in specific case. 我正在尝试学习chisel3,我也尝试在特定情况下使用从Int到UInt的隐式类型转换。

Following is my code. 以下是我的代码。

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)
}

I expected scala compiler will try to convert two values in VecInit from Int to UInt, but compiler reports error like below. 我希望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

First, I thougth compiler can not get int2UInt (implicit type converter function in object VecTest ) because of out of scope. 首先,由于超出范围,我认为编译器无法获取int2UIntobject VecTest隐式类型转换器函数)。 However, when I fixed the code like below, it will work. 但是,当我修改下面的代码时,它会起作用。

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

I also make a hypotheses that chisel3 already has a implicit type converter like my converter, but that is probably not correct. 我还假设chisel3已经有像我的转换器那样的隐式类型转换器,但这可能不正确。

Where is my misstakes? 我的错误在哪里?

I think the closest answer is the second answer here . 我认为最接近的答案是这里的第二个答案。 In short, because VecInit is parameterized with [T <: Data] the entire space of T is not searched to see what Implicit conversions might return a T. 简而言之,因为VecInit使用[T <:Data]参数化,所以不搜索T的整个空间以查看隐式转换可能返回T的内容。

You can manually force the proper implicit like this 您可以像这样手动强制正确隐式

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

I would like to point out that earlier versions of chisel allowed Int parameters on VecInit and its allies. 我想指出,早期版本的凿子允许VecInit及其盟友使用Int参数。 Our experience was that requiring specific Hardware Types was less error prone and easier to read. 我们的经验是,要求特定的硬件类型不易出错,更易于阅读。 Adding .U to the numbers is fairly low boilerplate overhead. 将.U添加到数字是相当低的样板开销。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM