Generating Verilog code after BlackBoxing in Chisel3 - chisel

I am trying BlackBox feature in Chisel3. Every time I try to generate Verilog code of Chisel I got an error.
I followed the right steps, writing the class, class driver and build.sbt.
I am not sure where the problem is
This is my Chisel Code
import chisel3._
import chisel3.util._
import chisel3.experimental._
class BlackBoxRealAdd extends BlackBox with HasBlackBoxInline {
val io = IO(new Bundle() {
val in1 = Input(UInt(64.W))
val in2 = Input(UInt(64.W))
val out = Output(UInt(64.W))
})
setInline("BlackBoxRealAdd.v",
s"""
|module BlackBoxRealAdd(
| input [15:0] in1,
| input [15:0] in2,
| output [15:0] out
|);
|always #* begin
| out <= (in1) + (in2));
|end
|endmodule
""".stripMargin)
}
object BlackBoxRealAddDriver extends App {
chisel3.Driver.execute(args, () => new BlackBoxRealAdd)
}
scalaVersion := "2.11.12"
resolvers ++= Seq(
Resolver.sonatypeRepo("snapshots"),
Resolver.sonatypeRepo("releases")
)
libraryDependencies += "edu.berkeley.cs" %% "chisel3" % "3.1.+"

I have figured it out. The blackboxed module shouldn't be the top one.

Related

Debugging module internals in Chisel

I have a complex module written in Chisel. I'm using chiseltest to verify its operation. The test is failing. I want to be able to inspect the module's internal wire values to debug what is going wrong. Since the PeekPokeTester only allows me to inspect the value of the io signals, how can I inspect the internal wires?
Here is an example:
import chisel3._
class MyModule extends Module {
val io = IO(new Bundle {
val a = Input(Bool())
val b = Input(Bool())
val c = Input(Bool())
val d = Output(Bool())
})
val i = Wire(Bool())
i := io.a ^ io.b
io.d := i | io.c
}
import chisel3._
import chisel3.tester._
import org.scalatest.FreeSpec
class MyModuleTest extends FreeSpec with ChiselScalatestTester {
"MyModule should work properly" in {
test(new MyModule) { dut =>
dut.io.a.poke(true.B)
dut.io.b.poke(false.B)
dut.io.c.poke(false.B)
dut.i.expect(true.B) // This line throws a java.util.NoSuchElementException
// : key not found: Bool(Wire in MyModule)
}
}
}
How can I inspect the intermediate value "i"?
There's a few ways to do this.
1 ) Turn on VCD output by adding an annotation to your test, as in
import chiseltest.experimental.TestOptionBuilder._
import treadle._
...
test(new MyModule).withAnnotations(Seq(WriteVcdAnnotation)) { dut =>
The .vcd file will be placed in the relevant test_run_dir/ you can view it with GtkWave or similar
2 ) add printf statements to your module.
3 ) There is a simulation shell in the Treadle Repo that allows you to peek poke and step based on a firrtl file (the firrtl file should be in the same test_run_dir/ directory as above). There is A bit of documentation here
Good luck!

CIRCE: How to decode a json model with disjunction in a field type

The application I am developing has to decode json from a data source which for a given field may return either a List[String] or a List[Double]. I want to decode this json into a case class so i can process the data.
[{
"id": 123,
"latlng": ["-12.777", "18.776"]
}, {
"id": 123,
"latlng": [-12.777, 18.776]
}]
Im using circe 0.11.1
currently my case class looks like
case class Report(id:Int, latlng:Either[List[String],List[Double]])
and my decoding code
decode[List[Report]](testData)
i receive the error
DecodingFailure at [0].latlng: [A, B]Either[A, B]
It sounds like you already have a solution that works for you. I found a solution to your original problem though. It is not very elegant, but it works. There might be a more elegant solution that involves the Validated monad in Cats library, but I am not familiar enough with the Cats library to write it in that way.
import io.circe._
import io.circe.parser._
object Main {
def main(args: Array[String]) = {
val testData =
"""
|[{
| "id": 123,
| "latling": ["-12.777", "18.776"]
|}, {
| "id": 123,
| "latling": [-12.777, 18.776]
|}]
""".stripMargin
println(decode[List[Report]](testData))
}
case class Report(id: Int, latling: Either[List[String],List[Double]])
object Report {
implicit val reportDecoder: Decoder[Report] = new Decoder[Report] {
override def apply(c: HCursor): Decoder.Result[Report] = {
val stringAttempt = for {
id <- c.downField("id").as[Int]
latlingString <- c.downField("latling").as[List[String]]
} yield Report(id, Left(latlingString))
val doubleAttempt = for {
id <- c.downField("id").as[Int]
latlingDouble <- c.downField("latling").as[List[Double]]
} yield Report(id, Right(latlingDouble))
stringAttempt match {
case Right(stringValue) => Right(stringValue)
case Left(stringFailure) => doubleAttempt
}
}
}
}
}
You can run by starting up sbt with
sbt
and running
runMain Main
Here is my build.sbt file:
name := "stackoverflow20190821"
version := "0.1"
scalaVersion := "2.12.0"
val circeVersion = "0.11.1"
libraryDependencies ++= Seq(
"io.circe" %% "circe-core",
"io.circe" %% "circe-generic",
"io.circe" %% "circe-parser"
).map(_ % circeVersion)

How can I generate FIRRTL from chisel code?

How can I generate FIRRTL file from chisel code? I have installed sbt, firrtl and verilator according to the github wiki. And created a chisel code for simple adder. I want to generate the FIRRTL and covert it to Verilog? My problem is how to get the firrtl file from the chisel code.
Thanks.
Source file : MyQueueTest/src/main/scala/example/MyQueueDriver.scala
package example
import chisel3._
import chisel3.util._
class MyQueue extends Module {
val io = IO(new Bundle {
val a = Flipped(Decoupled(UInt(32.W)))
val b = Flipped(Decoupled(UInt(32.W)))
val z = Decoupled(UInt(32.W))
})
val qa = Queue(io.a)
val qb = Queue(io.b)
qa.nodeq()
qb.nodeq()
when (qa.valid && qb.valid && io.z.ready) {
io.z.enq(qa.deq() + qb.deq())
}
}
object MyQueueDriver extends App {
chisel3.Driver.execute(args, () => new MyQueue)
}
I asked a similar question here.
The solution could be to use full template provided here, or you can simply do that:
Add these lines at the end of your scala sources :
object YourModuleDriver extends App {
chisel3.Driver.execute(args, () => new YourModule)
}
Replacing "YourModule" by the name of your module.
And add a build.sbt file in the same directory of your sources with these lines :
scalaVersion := "2.11.8"
resolvers ++= Seq(
Resolver.sonatypeRepo("snapshots"),
Resolver.sonatypeRepo("releases")
)
libraryDependencies += "edu.berkeley.cs" %% "chisel3" % "3.0-SNAPSHOT"
To generate FIRRTL and Verilog you will just have to do :
$ sbt "run-main YourModuleDriver"
And the FIRRTL (yourmodule.fir) /Verilog (yourmodule.v) sources will be in generated directory.

Cannot write an instance of play.api.libs.json.JsLookupResult to HTTP response. Try to define a Writable[play.api.libs.json.JsLookupResult]

I am upgrading Play Framework server from 2.2.2 to 2.4.4, as my application is working fine with old version, but while upgrading it is giving various errors like:
Cannot write an instance of play.api.libs.json.JsLookupResult to HTTP response. Try to define a Writable[play.api.libs.json.JsLookupResult]
Ok<gts<0>>
^
build.sbt:
name := """TestApp"""
version := "1.0-SNAPSHOT"
lazy val root = (project in file(".")).enablePlugins(PlayJava)
//scalaVersion := "2.11.6"
//scalaVersion := "2.10.2"
libraryDependencies ++= Seq(
javaJdbc,
cache,
javaWs,
jdbc,
cache,
"com.typesafe.play" %% "anorm" % "2.4.0",
"com.google.inject" % "guice" % "4.0",
"javax.inject" % "javax.inject" % "1",
"org.reactivemongo" %% "reactivemongo" % "0.10.0",
"org.reactivemongo" %% "play2-reactivemongo" % "0.10.2",
"org.mockito" % "mockito-core" % "1.9.5" % "test",
"org.webjars" % "requirejs" % "2.1.1",
"org.postgresql" % "postgresql" % "9.4-1200-jdbc41",
"postgresql" % "postgresql" % "9.1-901.jdbc4",
"com.typesafe.play" % "play-iteratees_2.10" % "2.2.3",
"com.typesafe.slick" % "slick_2.10" % "2.1.0",
"com.typesafe.play" % "play-jdbc_2.10" % "2.4.4",
"org.apache.flume" % "flume-ng-core" % "1.5.2",
"org.apache.flume" % "flume-ng-sdk" % "1.5.2",
"org.scala-lang" % "scala-compiler" % "2.11.6"
)
app.scala:
package controllers
import play.modules.reactivemongo.MongoController
import play.modules.reactivemongo.json.collection.JSONCollection
import scala.concurrent.Future
import reactivemongo.api.Cursor
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import javax.inject.Singleton
import play.api.mvc._
import play.api.libs.json._
#Singleton
class Application extends Controller with MongoController {
def collection: JSONCollection = db.collection[JSONCollection]("Test")
import models._
import models.JsonFormats._
import reactivemongo.bson._
def index = Action.async {
val cursor: Cursor[JsValue] = collection.
find(Json.obj()).
cursor[JsValue]
val futureUsersList: Future[List[JsValue]] = cursor.collect[List]()
val futurePersonsJsonArray: Future[JsArray] = futureUsersList.map { dao =>
Json.arr(dao)
}
futurePersonsJsonArray.map {
dao =>
Ok(dao(0))
}
}
}
Please let me know where I am doing wrong whether it is in my controller class or build.sbt ? Thanks in advance.
Indexing a JsArray does not return the JsValue at that index but a JsLookupResult, which is either JsDefined or JsUndefined (if, e.g, the index is out-of-bounds.) I think this changed in Play 2.3.
While you can write a JsValue directly to an HTTP response via the default JSON writeable provided by Play, there is no such writeable for a JsLookupResult. You can fix it by pattern matching on the JsLookupResult to extract the value, and handle its absence:
futurePersonsJsonArray.map { dao =>
dao(0).match {
case JsDefined(js) => Ok(js)
case _ => NotFound
}
}
or use toOption to get an Option[JsValue]:
futurePersonsJsonArray.map { dao =>
dao(0).toOption.map(js => Ok(js)).getOrElse(NotFound)
}
However, a better way to fix the code would be to use Json.toJson() directly on the redeemed result of futureUserList, rather than putting it in a JSON array, and then immediately taking it out again:
def index = Action.async {
val cursor: Cursor[JsValue] = collection.
find(Json.obj()).
cursor[JsValue]
val futureUsersList: Future[List[JsValue]] = cursor.collect[List]()
futureUsersList.map { list =>
Ok(Json.toJson(list))
}
}

Sending a post request in spray

I need to make a simple HTTP request using spray framework. I found some examples on their web site but they turned out to be complicated and involving Akka which is not necessary for me.
Besides, I need to be able to fill in a request's headers (like X-Application, content-type, etc) and, of course, a requests's post data (in my case, it would be a data in JSON).
So how do I do that?
Here is an example. There is going to be a small amount of akka code but as I mentioned in my comment, it's necessary for spray:
import spray.httpx.RequestBuilding._
import spray.http._
import HttpMethods._
import HttpHeaders._
import MediaTypes._
import spray.json._
import DefaultJsonProtocol._
import spray.httpx.SprayJsonSupport._
import akka.actor.ActorSystem
import spray.io.IOExtension
import akka.actor.Props
import spray.can.client.HttpClient
import spray.client.HttpConduit
import scala.concurrent.Future
import scala.util.Failure
import scala.util.Success
case class MyObj(str:String, i:Int)
object SprayExample {
implicit val myObjFormat = jsonFormat2(MyObj)
def main(args: Array[String]) {
import concurrent.ExecutionContext.Implicits._
val obj = MyObj("hello", 1)
val req = Post("/some/url", obj) ~> addHeader("X-Foo", "bar")
implicit val system = ActorSystem()
val ioBridge = IOExtension(system).ioBridge()
val httpClient = system.actorOf(Props(new HttpClient(ioBridge)))
val conduit = system.actorOf(
props = Props(new HttpConduit(httpClient, "localhost", 8080)),
name = "http-conduit"
)
val pipeline = HttpConduit.sendReceive(conduit)
val response: Future[HttpResponse] = pipeline(req)
response onComplete{
case Failure(ex) => ex.printStackTrace()
case Success(resp) => println("success: " + resp.status)
}
}
}
My build file looks like this:
scalaVersion := "2.10.0"
resolvers ++= Seq(
"Scala Tools Repo Releases" at "http://scala-tools.org/repo-releases",
"Typesafe Repo Releases" at "http://repo.typesafe.com/typesafe/releases/",
"spray" at "http://repo.spray.io/"
)
libraryDependencies ++= Seq(
"io.spray" % "spray-httpx" % "1.1-M7",
"io.spray" % "spray-client" % "1.1-M7",
"com.typesafe.akka" %% "akka-actor" % "2.1.0",
"io.spray" %% "spray-json" % "1.2.5"
)