diff options
| author | Jack | 2022-01-12 04:27:19 +0000 |
|---|---|---|
| committer | Jack | 2022-01-12 04:27:19 +0000 |
| commit | 29df513e348cc809876893f650af8180f0190496 (patch) | |
| tree | 06daaea954b4e5af7113f06e4bdbb78b33515cb3 /src/test | |
| parent | 5242ce90659decb9058ee75db56e5c188029fbf9 (diff) | |
| parent | 747d16311bdf185d2e98e452b14cb5d8ccca004c (diff) | |
Merge branch 'master' into 3.5-release
Diffstat (limited to 'src/test')
142 files changed, 3470 insertions, 2888 deletions
diff --git a/src/test/scala/chisel3/testers/TreadleBackend.scala b/src/test/scala/chisel3/testers/TreadleBackend.scala index 19b94e91..9375b10a 100644 --- a/src/test/scala/chisel3/testers/TreadleBackend.scala +++ b/src/test/scala/chisel3/testers/TreadleBackend.scala @@ -17,10 +17,12 @@ import java.io.File case object TreadleBackend extends TesterDriver.Backend { val MaxTreadleCycles = 10000L - def execute(t: () => BasicTester, - additionalVResources: Seq[String] = Seq(), - annotations: AnnotationSeq = Seq(), - nameHint: Option[String] = None): Boolean = { + def execute( + t: () => BasicTester, + additionalVResources: Seq[String] = Seq(), + annotations: AnnotationSeq = Seq(), + nameHint: Option[String] = None + ): Boolean = { val generatorAnnotation = chisel3.stage.ChiselGeneratorAnnotation(t) // This provides an opportunity to translate from top level generic flags to backend specific annos @@ -37,7 +39,7 @@ case object TreadleBackend extends TesterDriver.Backend { if (!annotationSeq.exists(_.isInstanceOf[NoTargetAnnotation])) { annotationSeq = annotationSeq :+ TargetDirAnnotation(targetName.getPath) } - if (!annotationSeq.exists { case CallResetAtStartupAnnotation => true ; case _ => false }) { + if (!annotationSeq.exists { case CallResetAtStartupAnnotation => true; case _ => false }) { annotationSeq = annotationSeq :+ CallResetAtStartupAnnotation } diff --git a/src/test/scala/chiselTests/AdderTree.scala b/src/test/scala/chiselTests/AdderTree.scala index 171fa616..29ef97a4 100644 --- a/src/test/scala/chiselTests/AdderTree.scala +++ b/src/test/scala/chiselTests/AdderTree.scala @@ -10,14 +10,14 @@ class AdderTree[T <: Bits with Num[T]](genType: T, vecSize: Int) extends Module val numIn = Input(Vec(vecSize, genType)) val numOut = Output(genType) }) - io.numOut := io.numIn.reduceTree((a : T, b : T) => (a + b)) + io.numOut := io.numIn.reduceTree((a: T, b: T) => (a + b)) } class AdderTreeTester(bitWidth: Int, numsToAdd: List[Int]) extends BasicTester { val genType = UInt(bitWidth.W) val dut = Module(new AdderTree(genType, numsToAdd.size)) dut.io.numIn := VecInit(numsToAdd.map(x => x.asUInt(bitWidth.W))) - val sumCorrect = dut.io.numOut === (numsToAdd.reduce(_+_) % (1 << bitWidth)).asUInt(bitWidth.W) + val sumCorrect = dut.io.numOut === (numsToAdd.reduce(_ + _) % (1 << bitWidth)).asUInt(bitWidth.W) assert(sumCorrect) stop() } @@ -27,7 +27,7 @@ class AdderTreeSpec extends ChiselPropSpec { forAll(safeUIntN(20)) { case (w: Int, v: List[Int]) => { whenever(v.size > 0 && w > 0) { - assertTesterPasses { new AdderTreeTester(w, v.map(x => math.abs(x) % ( 1 << w )).toList) } + assertTesterPasses { new AdderTreeTester(w, v.map(x => math.abs(x) % (1 << w)).toList) } } } } diff --git a/src/test/scala/chiselTests/AnalogIntegrationSpec.scala b/src/test/scala/chiselTests/AnalogIntegrationSpec.scala index 7478f2eb..035a9d91 100644 --- a/src/test/scala/chiselTests/AnalogIntegrationSpec.scala +++ b/src/test/scala/chiselTests/AnalogIntegrationSpec.scala @@ -53,7 +53,7 @@ class AnalogBlackBoxWrapper(n: Int, idxs: Seq[Int]) extends AnalogBlackBoxModule val bbs = idxs.map(i => Module(new AnalogBlackBoxModule(i))) io.bus <> bbs.head.io.bus // Always bulk connect io.bus to first bus io.port <> bbs.flatMap(_.io.port) // Connect ports - attach(bbs.map(_.io.bus):_*) // Attach all the buses + attach(bbs.map(_.io.bus): _*) // Attach all the buses } // Common superclass for AnalogDUT and AnalogSmallDUT @@ -80,7 +80,7 @@ class AnalogDUT extends AnalogDUTModule(5) { // 5 BlackBoxes // Connect all ports to top io.ports <> mods.flatMap(_.io.port) // Attach first 3 Modules - attach(mods.take(3).map(_.io.bus):_*) + attach(mods.take(3).map(_.io.bus): _*) // Attach last module to 1st through AnalogConnector val con = Module(new AnalogConnector) attach(con.io.bus1, mods.head.io.bus) @@ -100,10 +100,9 @@ class AnalogSmallDUT extends AnalogDUTModule(4) { // 4 BlackBoxes // Connect all ports to top io.ports <> mods.flatMap(_.io.port) // Attach first 3 Modules - attach(mods.take(3).map(_.io.bus):_*) + attach(mods.take(3).map(_.io.bus): _*) } - // This tester is primarily intended to be able to pass the dut to synthesis class AnalogIntegrationTester(mod: => AnalogDUTModule) extends BasicTester { val BusValue = 2.U(32.W) // arbitrary @@ -122,17 +121,17 @@ class AnalogIntegrationTester(mod: => AnalogDUTModule) extends BasicTester { // Error checking assert(dut.out === expectedValue) - when (cycle === idx.U) { + when(cycle === idx.U) { expectedValue := BusValue + idx.U dut.in.valid := true.B } } - when (done) { stop() } + when(done) { stop() } } class AnalogIntegrationSpec extends ChiselFlatSpec { - behavior of "Verilator" + behavior.of("Verilator") it should "support simple bidirectional wires" in { assertTesterPasses( new AnalogIntegrationTester(new AnalogSmallDUT), diff --git a/src/test/scala/chiselTests/AnalogSpec.scala b/src/test/scala/chiselTests/AnalogSpec.scala index 42dafb6e..3d03af78 100644 --- a/src/test/scala/chiselTests/AnalogSpec.scala +++ b/src/test/scala/chiselTests/AnalogSpec.scala @@ -6,7 +6,7 @@ import chisel3._ import chisel3.stage.ChiselStage import chisel3.util._ import chisel3.testers.{BasicTester, TesterDriver} -import chisel3.experimental.{Analog, BaseModule, attach} +import chisel3.experimental.{attach, Analog, BaseModule} // IO for Modules that just connect bus to out class AnalogReaderIO extends Bundle { @@ -59,9 +59,14 @@ class VecAnalogReaderWrapper extends RawModule with AnalogReader { } class VecBundleAnalogReaderWrapper extends RawModule with AnalogReader { - val vecBunBus = IO(Vec(1, new Bundle { - val analog = Analog(32.W) - })) + val vecBunBus = IO( + Vec( + 1, + new Bundle { + val analog = Analog(32.W) + } + ) + ) def bus = vecBunBus(0).analog val out = IO(Output(UInt(32.W))) val mod = Module(new AnalogReaderBlackBox) @@ -74,7 +79,7 @@ abstract class AnalogTester extends BasicTester { final val BusValue = "hdeadbeef".U final val (cycle, done) = Counter(true.B, 2) - when (done) { stop() } + when(done) { stop() } final val writer = Module(new AnalogWriterBlackBox) writer.io.in := BusValue @@ -84,85 +89,103 @@ abstract class AnalogTester extends BasicTester { } class AnalogSpec extends ChiselFlatSpec with Utils { - behavior of "Analog" + behavior.of("Analog") it should "NOT be bindable to registers" in { - a [ChiselException] should be thrownBy extractCause[ChiselException] { - ChiselStage.elaborate { new Module { - val io = IO(new Bundle {}) - val reg = Reg(Analog(32.W)) - }} + a[ChiselException] should be thrownBy extractCause[ChiselException] { + ChiselStage.elaborate { + new Module { + val io = IO(new Bundle {}) + val reg = Reg(Analog(32.W)) + } + } } } it should "NOT be bindable to a direction" in { - a [ChiselException] should be thrownBy extractCause[ChiselException] { - ChiselStage.elaborate { new Module { - val io = IO(new Bundle { - val a = Input(Analog(32.W)) - }) - }} + a[ChiselException] should be thrownBy extractCause[ChiselException] { + ChiselStage.elaborate { + new Module { + val io = IO(new Bundle { + val a = Input(Analog(32.W)) + }) + } + } } - a [ChiselException] should be thrownBy extractCause[ChiselException] { - ChiselStage.elaborate { new Module { - val io = IO(new Bundle { - val a = Output(Analog(32.W)) - }) - }} + a[ChiselException] should be thrownBy extractCause[ChiselException] { + ChiselStage.elaborate { + new Module { + val io = IO(new Bundle { + val a = Output(Analog(32.W)) + }) + } + } } } it should "be flippable" in { - ChiselStage.elaborate { new Module { - val io = IO(new Bundle { - val a = Flipped(Analog(32.W)) - }) - }} + ChiselStage.elaborate { + new Module { + val io = IO(new Bundle { + val a = Flipped(Analog(32.W)) + }) + } + } } // There is no binding on the type of a memory // Should this be an error? ignore should "NOT be a legal type for Mem" in { - a [ChiselException] should be thrownBy extractCause[ChiselException] { - ChiselStage.elaborate { new Module { - val io = IO(new Bundle {}) - val mem = Mem(16, Analog(32.W)) - }} + a[ChiselException] should be thrownBy extractCause[ChiselException] { + ChiselStage.elaborate { + new Module { + val io = IO(new Bundle {}) + val mem = Mem(16, Analog(32.W)) + } + } } } it should "NOT be bindable to Mem ports" in { - a [ChiselException] should be thrownBy extractCause[ChiselException] { - ChiselStage.elaborate { new Module { - val io = IO(new Bundle {}) - val mem = Mem(16, Analog(32.W)) - val port = mem(5.U) - }} + a[ChiselException] should be thrownBy extractCause[ChiselException] { + ChiselStage.elaborate { + new Module { + val io = IO(new Bundle {}) + val mem = Mem(16, Analog(32.W)) + val port = mem(5.U) + } + } } } // TODO This should probably be caught in Chisel // Also note this relies on executing Firrtl from Chisel directly it should "NOT be connectable to UInts" in { - a [Exception] should be thrownBy { - runTester { new BasicTester { - val uint = WireDefault(0.U(32.W)) - val sint = Wire(Analog(32.W)) - sint := uint - }} + a[Exception] should be thrownBy { + runTester { + new BasicTester { + val uint = WireDefault(0.U(32.W)) + val sint = Wire(Analog(32.W)) + sint := uint + } + } } } it should "work with 2 blackboxes bulk connected" in { - assertTesterPasses(new AnalogTester { - val mod = Module(new AnalogReaderBlackBox) - mod.io.bus <> writer.io.bus - check(mod) - }, Seq("/chisel3/AnalogBlackBox.v"), TesterDriver.verilatorOnly) + assertTesterPasses( + new AnalogTester { + val mod = Module(new AnalogReaderBlackBox) + mod.io.bus <> writer.io.bus + check(mod) + }, + Seq("/chisel3/AnalogBlackBox.v"), + TesterDriver.verilatorOnly + ) } it should "error if any bulk connected more than once" in { - a [ChiselException] should be thrownBy extractCause[ChiselException] { + a[ChiselException] should be thrownBy extractCause[ChiselException] { ChiselStage.elaborate(new Module { val io = IO(new Bundle {}) val wires = List.fill(3)(Wire(Analog(32.W))) @@ -170,7 +193,7 @@ class AnalogSpec extends ChiselFlatSpec with Utils { wires(0) <> wires(2) }) } - a [ChiselException] should be thrownBy extractCause[ChiselException] { + a[ChiselException] should be thrownBy extractCause[ChiselException] { ChiselStage.elaborate(new Module { val io = IO(new Bundle {}) val wires = List.fill(2)(Wire(Analog(32.W))) @@ -217,82 +240,113 @@ class AnalogSpec extends ChiselFlatSpec with Utils { } it should "work with 3 blackboxes attached" in { - assertTesterPasses(new AnalogTester { - val mods = Seq.fill(2)(Module(new AnalogReaderBlackBox)) - attach(writer.io.bus, mods(0).io.bus, mods(1).io.bus) - mods.foreach(check(_)) - }, Seq("/chisel3/AnalogBlackBox.v"), TesterDriver.verilatorOnly) + assertTesterPasses( + new AnalogTester { + val mods = Seq.fill(2)(Module(new AnalogReaderBlackBox)) + attach(writer.io.bus, mods(0).io.bus, mods(1).io.bus) + mods.foreach(check(_)) + }, + Seq("/chisel3/AnalogBlackBox.v"), + TesterDriver.verilatorOnly + ) } it should "work with 3 blackboxes separately attached via a wire" in { - assertTesterPasses(new AnalogTester { - val mods = Seq.fill(2)(Module(new AnalogReaderBlackBox)) - val busWire = Wire(Analog(32.W)) - attach(busWire, writer.io.bus) - attach(busWire, mods(0).io.bus) - attach(mods(1).io.bus, busWire) - mods.foreach(check(_)) - }, Seq("/chisel3/AnalogBlackBox.v"), TesterDriver.verilatorOnly) + assertTesterPasses( + new AnalogTester { + val mods = Seq.fill(2)(Module(new AnalogReaderBlackBox)) + val busWire = Wire(Analog(32.W)) + attach(busWire, writer.io.bus) + attach(busWire, mods(0).io.bus) + attach(mods(1).io.bus, busWire) + mods.foreach(check(_)) + }, + Seq("/chisel3/AnalogBlackBox.v"), + TesterDriver.verilatorOnly + ) } // This does not currently work in Verilator unless Firrtl does constant prop and dead code // elimination on these wires ignore should "work with intermediate wires attached to each other" in { - assertTesterPasses(new AnalogTester { - val mod = Module(new AnalogReaderBlackBox) - val busWire = Seq.fill(2)(Wire(Analog(32.W))) - attach(busWire(0), writer.io.bus) - attach(busWire(1), mod.io.bus) - attach(busWire(0), busWire(1)) - check(mod) - }, Seq("/chisel3/AnalogBlackBox.v"), TesterDriver.verilatorOnly) + assertTesterPasses( + new AnalogTester { + val mod = Module(new AnalogReaderBlackBox) + val busWire = Seq.fill(2)(Wire(Analog(32.W))) + attach(busWire(0), writer.io.bus) + attach(busWire(1), mod.io.bus) + attach(busWire(0), busWire(1)) + check(mod) + }, + Seq("/chisel3/AnalogBlackBox.v"), + TesterDriver.verilatorOnly + ) } it should "work with blackboxes at different levels of the module hierarchy" in { - assertTesterPasses(new AnalogTester { - val mods = Seq(Module(new AnalogReaderBlackBox), Module(new AnalogReaderWrapper)) - val busWire = Wire(writer.io.bus.cloneType) - attach(writer.io.bus, mods(0).bus, mods(1).bus) - mods.foreach(check(_)) - }, Seq("/chisel3/AnalogBlackBox.v"), TesterDriver.verilatorOnly) + assertTesterPasses( + new AnalogTester { + val mods = Seq(Module(new AnalogReaderBlackBox), Module(new AnalogReaderWrapper)) + val busWire = Wire(writer.io.bus.cloneType) + attach(writer.io.bus, mods(0).bus, mods(1).bus) + mods.foreach(check(_)) + }, + Seq("/chisel3/AnalogBlackBox.v"), + TesterDriver.verilatorOnly + ) } // This does not currently work in Verilator, but does work in VCS ignore should "support two analog ports in the same module" in { - assertTesterPasses(new AnalogTester { - val reader = Module(new AnalogReaderBlackBox) - val connector = Module(new AnalogConnector) - connector.io.bus1 <> writer.io.bus - reader.io.bus <> connector.io.bus2 - check(reader) - }, Seq("/chisel3/AnalogBlackBox.v"), TesterDriver.verilatorOnly) + assertTesterPasses( + new AnalogTester { + val reader = Module(new AnalogReaderBlackBox) + val connector = Module(new AnalogConnector) + connector.io.bus1 <> writer.io.bus + reader.io.bus <> connector.io.bus2 + check(reader) + }, + Seq("/chisel3/AnalogBlackBox.v"), + TesterDriver.verilatorOnly + ) } it should "NOT support conditional connection of analog types" in { - a [ChiselException] should be thrownBy { - assertTesterPasses(new AnalogTester { - val mod = Module(new AnalogReaderBlackBox) - when (cycle > 3.U) { - mod.io.bus <> writer.io.bus - } - check(mod) - }, Seq("/chisel3/AnalogBlackBox.v")) + a[ChiselException] should be thrownBy { + assertTesterPasses( + new AnalogTester { + val mod = Module(new AnalogReaderBlackBox) + when(cycle > 3.U) { + mod.io.bus <> writer.io.bus + } + check(mod) + }, + Seq("/chisel3/AnalogBlackBox.v") + ) } } it should "work with Vecs of Analog" in { - assertTesterPasses(new AnalogTester { - val mod = Module(new VecAnalogReaderWrapper) - mod.bus <> writer.io.bus - check(mod) - }, Seq("/chisel3/AnalogBlackBox.v"), TesterDriver.verilatorOnly) + assertTesterPasses( + new AnalogTester { + val mod = Module(new VecAnalogReaderWrapper) + mod.bus <> writer.io.bus + check(mod) + }, + Seq("/chisel3/AnalogBlackBox.v"), + TesterDriver.verilatorOnly + ) } it should "work with Vecs of Bundles of Analog" in { - assertTesterPasses(new AnalogTester { - val mod = Module(new VecBundleAnalogReaderWrapper) - mod.bus <> writer.io.bus - check(mod) - }, Seq("/chisel3/AnalogBlackBox.v"), TesterDriver.verilatorOnly) + assertTesterPasses( + new AnalogTester { + val mod = Module(new VecBundleAnalogReaderWrapper) + mod.bus <> writer.io.bus + check(mod) + }, + Seq("/chisel3/AnalogBlackBox.v"), + TesterDriver.verilatorOnly + ) } } diff --git a/src/test/scala/chiselTests/AnnotatingDiamondSpec.scala b/src/test/scala/chiselTests/AnnotatingDiamondSpec.scala index cfa07e26..af73d5d4 100644 --- a/src/test/scala/chiselTests/AnnotatingDiamondSpec.scala +++ b/src/test/scala/chiselTests/AnnotatingDiamondSpec.scala @@ -3,17 +3,12 @@ package chiselTests import chisel3._ -import chisel3.experimental.{ChiselAnnotation, RunFirrtlTransform, annotate} +import chisel3.experimental.{annotate, ChiselAnnotation, RunFirrtlTransform} import chisel3.internal.InstanceId import chisel3.stage.{ChiselGeneratorAnnotation, ChiselStage} import chisel3.testers.BasicTester import firrtl.{CircuitForm, CircuitState, DependencyAPIMigration, LowForm, Transform} -import firrtl.annotations.{ - CircuitName, - CircuitTarget, - SingleTargetAnnotation, - Target -} +import firrtl.annotations.{CircuitName, CircuitTarget, SingleTargetAnnotation, Target} import firrtl.stage.Forms import org.scalatest._ import org.scalatest.freespec.AnyFreeSpec @@ -25,10 +20,12 @@ import org.scalatest.matchers.should.Matchers case class IdentityAnnotation(target: Target, value: String) extends SingleTargetAnnotation[Target] { def duplicate(n: Target): IdentityAnnotation = this.copy(target = n) } + /** ChiselAnnotation that corresponds to the above FIRRTL annotation */ case class IdentityChiselAnnotation(target: InstanceId, value: String) - extends ChiselAnnotation with RunFirrtlTransform { - def toFirrtl: IdentityAnnotation = IdentityAnnotation(target.toNamed, value) + extends ChiselAnnotation + with RunFirrtlTransform { + def toFirrtl: IdentityAnnotation = IdentityAnnotation(target.toNamed, value) def transformClass: Class[IdentityTransform] = classOf[IdentityTransform] } object identify { @@ -47,7 +44,7 @@ class IdentityTransform extends Transform with DependencyAPIMigration { def execute(state: CircuitState): CircuitState = { val annosx = state.annotations.map { case IdentityAnnotation(t, value) => IdentityAnnotation(t, value + ":seen") - case other => other + case other => other } state.copy(annotations = annosx) } @@ -109,8 +106,8 @@ class ModB(widthB: Int) extends Module { class TopOfDiamond extends Module { val io = IO(new Bundle { - val in = Input(UInt(32.W)) - val out = Output(UInt(32.W)) + val in = Input(UInt(32.W)) + val out = Output(UInt(32.W)) }) val x = Reg(UInt(32.W)) val y = Reg(UInt(32.W)) @@ -146,21 +143,24 @@ class AnnotatingDiamondSpec extends AnyFreeSpec with Matchers { |that happens only after emit has been called on circuit""".stripMargin in { val annos = (new ChiselStage) - .execute(Array("--target-dir", "test_run_dir", "--no-run-firrtl"), - Seq(ChiselGeneratorAnnotation(() => new TopOfDiamond))) + .execute( + Array("--target-dir", "test_run_dir", "--no-run-firrtl"), + Seq(ChiselGeneratorAnnotation(() => new TopOfDiamond)) + ) .filter { case _: IdentityAnnotation => true - case _ => false - }.toSeq + case _ => false + } + .toSeq info("Found ten (10) 'IdentityAnnotation's") - annos should have length (10) + (annos should have).length(10) info("Found IdentityAnnotation targeting '~*|ModC' with value 'ModC(16)'") - annos should contain (IdentityAnnotation(CircuitTarget("TopOfDiamond").module("ModC"), "ModC(16)")) + annos should contain(IdentityAnnotation(CircuitTarget("TopOfDiamond").module("ModC"), "ModC(16)")) info("Found IdentityAnnotation targeting '~*|ModC_1:seen' with value 'ModC(32)'") - annos should contain (IdentityAnnotation(CircuitTarget("TopOfDiamond").module("ModC_1"), "ModC(32)")) + annos should contain(IdentityAnnotation(CircuitTarget("TopOfDiamond").module("ModC_1"), "ModC(32)")) } } } diff --git a/src/test/scala/chiselTests/AnnotationNoDedup.scala b/src/test/scala/chiselTests/AnnotationNoDedup.scala index d99a0021..2150f925 100644 --- a/src/test/scala/chiselTests/AnnotationNoDedup.scala +++ b/src/test/scala/chiselTests/AnnotationNoDedup.scala @@ -9,7 +9,6 @@ import firrtl.stage.FirrtlCircuitAnnotation import org.scalatest.freespec.AnyFreeSpec import org.scalatest.matchers.should.Matchers - class MuchUsedModule extends Module { val io = IO(new Bundle { val in = Input(UInt(16.W)) @@ -35,7 +34,7 @@ class UsesMuchUsedModule(addAnnos: Boolean) extends Module { mod3.io.in := mod2.io.out io.out := mod3.io.out - if(addAnnos) { + if (addAnnos) { doNotDedup(mod1) doNotDedup(mod3) } @@ -46,29 +45,35 @@ class AnnotationNoDedup extends AnyFreeSpec with Matchers { "Firrtl provides transform that reduces identical modules to a single instance" - { "Annotations can be added which will prevent this deduplication for specific modules instances" in { val lowFirrtl = stage - .execute(Array("-X", "low", "--target-dir", "test_run_dir"), - Seq(ChiselGeneratorAnnotation(() => new UsesMuchUsedModule(addAnnos = true)))) + .execute( + Array("-X", "low", "--target-dir", "test_run_dir"), + Seq(ChiselGeneratorAnnotation(() => new UsesMuchUsedModule(addAnnos = true))) + ) .collectFirst { case FirrtlCircuitAnnotation(circuit) => circuit.serialize - }.getOrElse(fail) - lowFirrtl should include ("module MuchUsedModule :") - lowFirrtl should include ("module MuchUsedModule_1 :") - lowFirrtl should include ("module MuchUsedModule_3 :") - lowFirrtl should not include "module MuchUsedModule_2 :" - lowFirrtl should not include "module MuchUsedModule_4 :" + } + .getOrElse(fail) + lowFirrtl should include("module MuchUsedModule :") + lowFirrtl should include("module MuchUsedModule_1 :") + lowFirrtl should include("module MuchUsedModule_3 :") + (lowFirrtl should not).include("module MuchUsedModule_2 :") + (lowFirrtl should not).include("module MuchUsedModule_4 :") } "Turning off these annotations dedups all the occurrences" in { val lowFirrtl = stage - .execute(Array("-X", "low", "--target-dir", "test_run_dir"), - Seq(ChiselGeneratorAnnotation(() => new UsesMuchUsedModule(addAnnos = false)))) + .execute( + Array("-X", "low", "--target-dir", "test_run_dir"), + Seq(ChiselGeneratorAnnotation(() => new UsesMuchUsedModule(addAnnos = false))) + ) .collectFirst { case FirrtlCircuitAnnotation(circuit) => circuit.serialize - }.getOrElse(fail) - lowFirrtl should include ("module MuchUsedModule :") - lowFirrtl should not include "module MuchUsedModule_1 :" - lowFirrtl should not include "module MuchUsedModule_3 :" - lowFirrtl should not include "module MuchUsedModule_2 :" - lowFirrtl should not include "module MuchUsedModule_4 :" + } + .getOrElse(fail) + lowFirrtl should include("module MuchUsedModule :") + (lowFirrtl should not).include("module MuchUsedModule_1 :") + (lowFirrtl should not).include("module MuchUsedModule_3 :") + (lowFirrtl should not).include("module MuchUsedModule_2 :") + (lowFirrtl should not).include("module MuchUsedModule_4 :") } } } diff --git a/src/test/scala/chiselTests/AsTypeOfTester.scala b/src/test/scala/chiselTests/AsTypeOfTester.scala index c0365177..2141cac2 100644 --- a/src/test/scala/chiselTests/AsTypeOfTester.scala +++ b/src/test/scala/chiselTests/AsTypeOfTester.scala @@ -3,13 +3,13 @@ package chiselTests import chisel3._ -import chisel3.experimental.{DataMirror, FixedPoint, ChiselEnum} +import chisel3.experimental.{ChiselEnum, DataMirror, FixedPoint} import chisel3.testers.BasicTester class AsTypeOfBundleTester extends BasicTester { class MultiTypeBundle extends Bundle { - val u = UInt(4.W) - val s = SInt(4.W) + val u = UInt(4.W) + val s = SInt(4.W) val fp = FixedPoint(4.W, 3.BP) } @@ -55,12 +55,12 @@ class AsTypeOfVecTester extends BasicTester { class AsTypeOfTruncationTester extends BasicTester { val truncate = (64 + 3).U.asTypeOf(UInt(3.W)) - val expand = 1.U.asTypeOf(UInt(3.W)) + val expand = 1.U.asTypeOf(UInt(3.W)) - assert( DataMirror.widthOf(truncate).get == 3 ) - assert( truncate === 3.U ) - assert( DataMirror.widthOf(expand).get == 3 ) - assert( expand === 1.U ) + assert(DataMirror.widthOf(truncate).get == 3) + assert(truncate === 3.U) + assert(DataMirror.widthOf(expand).get == 3) + assert(expand === 1.U) stop() } @@ -123,26 +123,26 @@ class AsChiselEnumTester extends BasicTester { } class AsTypeOfSpec extends ChiselFlatSpec { - behavior of "asTypeOf" + behavior.of("asTypeOf") it should "work with Bundles containing Bits Types" in { - assertTesterPasses{ new AsTypeOfBundleTester } + assertTesterPasses { new AsTypeOfBundleTester } } it should "work with Bundles that have fields of zero width" in { - assertTesterPasses{ new AsTypeOfBundleZeroWidthTester } + assertTesterPasses { new AsTypeOfBundleZeroWidthTester } } it should "work with Vecs containing Bits Types" in { - assertTesterPasses{ new AsTypeOfVecTester } + assertTesterPasses { new AsTypeOfVecTester } } it should "expand and truncate UInts of different width" in { - assertTesterPasses{ new AsTypeOfTruncationTester } + assertTesterPasses { new AsTypeOfTruncationTester } } it should "work for casting implicit Reset to Bool" in { - assertTesterPasses{ new ResetAsTypeOfBoolTester } + assertTesterPasses { new ResetAsTypeOfBoolTester } } it should "work for casting to and from ChiselEnums" in { diff --git a/src/test/scala/chiselTests/Assert.scala b/src/test/scala/chiselTests/Assert.scala index 0cb554f5..1849ddf8 100644 --- a/src/test/scala/chiselTests/Assert.scala +++ b/src/test/scala/chiselTests/Assert.scala @@ -11,7 +11,7 @@ class FailingAssertTester() extends BasicTester { assert(false.B) // Wait to come out of reset val (_, done) = Counter(!reset.asBool, 4) - when (done) { + when(done) { stop() } } @@ -20,13 +20,13 @@ class SucceedingAssertTester() extends BasicTester { assert(true.B) // Wait to come out of reset val (_, done) = Counter(!reset.asBool, 4) - when (done) { + when(done) { stop() } } class PipelinedResetModule extends Module { - val io = IO(new Bundle { }) + val io = IO(new Bundle {}) val a = RegInit(0xbeef.U) val b = RegInit(0xbeef.U) assert(a === b) @@ -39,7 +39,7 @@ class PipelinedResetTester extends BasicTester { module.reset := RegNext(RegNext(RegNext(reset))) val (_, done) = Counter(!reset.asBool, 4) - when (done) { + when(done) { stop() } } @@ -63,22 +63,22 @@ class BadUnescapedPercentAssertTester extends BasicTester { class AssertSpec extends ChiselFlatSpec with Utils { "A failing assertion" should "fail the testbench" in { - assert(!runTester{ new FailingAssertTester }) + assert(!runTester { new FailingAssertTester }) } "A succeeding assertion" should "not fail the testbench" in { - assertTesterPasses{ new SucceedingAssertTester } + assertTesterPasses { new SucceedingAssertTester } } "An assertion" should "not assert until we come out of reset" in { - assertTesterPasses{ new PipelinedResetTester } + assertTesterPasses { new PipelinedResetTester } } "Assertions" should "allow the modulo operator % in the message" in { - assertTesterPasses{ new ModuloAssertTester } + assertTesterPasses { new ModuloAssertTester } } they should "allow printf-style format strings with arguments" in { - assertTesterPasses{ new FormattedAssertTester } + assertTesterPasses { new FormattedAssertTester } } they should "not allow unescaped % in the message" in { - a [java.util.UnknownFormatConversionException] should be thrownBy { + a[java.util.UnknownFormatConversionException] should be thrownBy { extractCause[java.util.UnknownFormatConversionException] { ChiselStage.elaborate { new BadUnescapedPercentAssertTester } } diff --git a/src/test/scala/chiselTests/AsyncResetSpec.scala b/src/test/scala/chiselTests/AsyncResetSpec.scala index d49f390c..ac7ae0d1 100644 --- a/src/test/scala/chiselTests/AsyncResetSpec.scala +++ b/src/test/scala/chiselTests/AsyncResetSpec.scala @@ -24,16 +24,16 @@ class AsyncResetTester extends BasicTester { } reg := 5.U // Normal connection - when (count === 3.U) { + when(count === 3.U) { assert(reg === 5.U) } - when (count >= 5.U && count < 7.U) { + when(count >= 5.U && count < 7.U) { assert(reg === 123.U) - } .elsewhen (count >= 7.U) { + }.elsewhen(count >= 7.U) { assert(reg === 5.U) } - when (done) { + when(done) { stop() } } @@ -66,25 +66,25 @@ class AsyncResetAggregateTester extends BasicTester { reg(1).x := 7.U reg(1).y := 8.U - when (count === 3.U) { + when(count === 3.U) { assert(reg(0).x === 5.U) assert(reg(0).y === 6.U) assert(reg(1).x === 7.U) assert(reg(1).y === 8.U) } - when (count >= 5.U && count < 7.U) { + when(count >= 5.U && count < 7.U) { assert(reg(0).x === 0.U) assert(reg(0).y === 0.U) assert(reg(1).x === 0.U) assert(reg(1).y === 0.U) - } .elsewhen (count >= 7.U) { + }.elsewhen(count >= 7.U) { assert(reg(0).x === 5.U) assert(reg(0).y === 6.U) assert(reg(1).x === 7.U) assert(reg(1).y === 8.U) } - when (done) { + when(done) { stop() } } @@ -98,7 +98,7 @@ class AsyncResetQueueTester extends BasicTester { val asyncResetNext = RegNext(false.B, false.B) val asyncReset = asyncResetNext.asAsyncReset - val queue = withClockAndReset (slowClk, asyncReset) { + val queue = withClockAndReset(slowClk, asyncReset) { Module(new Queue(UInt(8.W), 4)) } queue.io.enq.valid := true.B @@ -107,15 +107,15 @@ class AsyncResetQueueTester extends BasicTester { queue.io.deq.ready := false.B val doCheck = RegNext(false.B, false.B) - when (queue.io.count === 3.U) { + when(queue.io.count === 3.U) { asyncResetNext := true.B doCheck := true.B } - when (doCheck) { + when(doCheck) { assert(queue.io.count === 0.U) } - when (done) { + when(done) { stop() } } @@ -140,7 +140,7 @@ class AsyncResetDontCareModule extends RawModule { class AsyncResetSpec extends ChiselFlatSpec with Utils { - behavior of "AsyncReset" + behavior.of("AsyncReset") it should "be able to be connected to DontCare" in { ChiselStage.elaborate(new AsyncResetDontCareModule) @@ -153,7 +153,7 @@ class AsyncResetSpec extends ChiselFlatSpec with Utils { } it should "NOT be allowed with non-literal reset values" in { - a [NonLiteralAsyncResetValueException] should be thrownBy extractCause[NonLiteralAsyncResetValueException] { + a[NonLiteralAsyncResetValueException] should be thrownBy extractCause[NonLiteralAsyncResetValueException] { compile(new BasicTester { val x = WireInit(123.U + 456.U) withReset(reset.asAsyncReset)(RegInit(x)) @@ -162,7 +162,7 @@ class AsyncResetSpec extends ChiselFlatSpec with Utils { } it should "NOT be allowed to connect directly to a Bool" in { - a [ChiselException] should be thrownBy extractCause[ChiselException] { + a[ChiselException] should be thrownBy extractCause[ChiselException] { ChiselStage.elaborate(new BasicTester { val bool = Wire(Bool()) val areset = reset.asAsyncReset @@ -199,12 +199,12 @@ class AsyncResetSpec extends ChiselFlatSpec with Utils { val reg = withReset(reset.asAsyncReset)(RegNext(initValue, 27.S)) initValue := -43.S val (count, done) = Counter(true.B, 4) - when (count === 0.U) { + when(count === 0.U) { chisel3.assert(reg === 27.S) - } .otherwise { + }.otherwise { chisel3.assert(reg === -43.S) } - when (done) { stop() } + when(done) { stop() } }) } @@ -212,12 +212,12 @@ class AsyncResetSpec extends ChiselFlatSpec with Utils { assertTesterPasses(new BasicTester { val reg = withReset(reset.asAsyncReset)(RegNext(-6.0.F(2.BP), 3.F(2.BP))) val (count, done) = Counter(true.B, 4) - when (count === 0.U) { + when(count === 0.U) { chisel3.assert(reg === 3.F(2.BP)) - } .otherwise { + }.otherwise { chisel3.assert(reg === -6.0.F(2.BP)) } - when (done) { stop() } + when(done) { stop() } }) } @@ -230,12 +230,12 @@ class AsyncResetSpec extends ChiselFlatSpec with Utils { x } val (count, done) = Counter(true.B, 4) - when (count === 0.U) { + when(count === 0.U) { chisel3.assert(reg === 13.I) - } .otherwise { + }.otherwise { chisel3.assert(reg === 7.I) } - when (done) { stop() } + when(done) { stop() } }) } @@ -249,12 +249,12 @@ class AsyncResetSpec extends ChiselFlatSpec with Utils { RegNext(0xbad0cad0L.U.asTypeOf(new MyBundle), 0xdeadbeefL.U.asTypeOf(new MyBundle)) } val (count, done) = Counter(true.B, 4) - when (count === 0.U) { + when(count === 0.U) { chisel3.assert(reg.asUInt === 0xdeadbeefL.U) - } .otherwise { + }.otherwise { chisel3.assert(reg.asUInt === 0xbad0cad0L.U) } - when (done) { stop() } + when(done) { stop() } }) } it should "allow literals cast to Vecs as reset values" in { @@ -263,12 +263,12 @@ class AsyncResetSpec extends ChiselFlatSpec with Utils { RegNext(0xbad0cad0L.U.asTypeOf(Vec(4, UInt(8.W))), 0xdeadbeefL.U.asTypeOf(Vec(4, UInt(8.W)))) } val (count, done) = Counter(true.B, 4) - when (count === 0.U) { + when(count === 0.U) { chisel3.assert(reg.asUInt === 0xdeadbeefL.U) - } .otherwise { + }.otherwise { chisel3.assert(reg.asUInt === 0xbad0cad0L.U) } - when (done) { stop() } + when(done) { stop() } }) } } diff --git a/src/test/scala/chiselTests/AutoClonetypeSpec.scala b/src/test/scala/chiselTests/AutoClonetypeSpec.scala index ef58f1ed..2ab4c800 100644 --- a/src/test/scala/chiselTests/AutoClonetypeSpec.scala +++ b/src/test/scala/chiselTests/AutoClonetypeSpec.scala @@ -42,7 +42,7 @@ class ModuleWithInner extends Module { val out = UInt(i.W) } - val io = IO(new Bundle{}) + val io = IO(new Bundle {}) val myWire = Wire(new InnerBundle(14)) require(myWire.i == 14) @@ -75,54 +75,64 @@ class InheritingBundle extends QueueIO(UInt(8.W), 8) { class AutoClonetypeSpec extends ChiselFlatSpec with Utils { "Bundles with Scala args" should "not need clonetype" in { - elaborate { new Module { - val io = IO(new Bundle{}) + elaborate { + new Module { + val io = IO(new Bundle {}) - val myWire = Wire(new BundleWithIntArg(8)) - assert(myWire.i == 8) - } } + val myWire = Wire(new BundleWithIntArg(8)) + assert(myWire.i == 8) + } + } } "Bundles with Scala implicit args" should "not need clonetype" in { - elaborate { new Module { - val io = IO(new Bundle{}) + elaborate { + new Module { + val io = IO(new Bundle {}) - implicit val implicitInt: Int = 4 - val myWire = Wire(new BundleWithImplicit()) + implicit val implicitInt: Int = 4 + val myWire = Wire(new BundleWithImplicit()) - assert(myWire.ii == 4) - } } + assert(myWire.ii == 4) + } + } } "Bundles with Scala explicit and impicit args" should "not need clonetype" in { - elaborate { new Module { - val io = IO(new Bundle{}) + elaborate { + new Module { + val io = IO(new Bundle {}) - implicit val implicitInt: Int = 4 - val myWire = Wire(new BundleWithArgAndImplicit(8)) + implicit val implicitInt: Int = 4 + val myWire = Wire(new BundleWithArgAndImplicit(8)) - assert(myWire.i == 8) - assert(myWire.ii == 4) - } } + assert(myWire.i == 8) + assert(myWire.ii == 4) + } + } } "Subtyped Bundles" should "not need clonetype" in { - elaborate { new Module { - val io = IO(new Bundle{}) + elaborate { + new Module { + val io = IO(new Bundle {}) - val myWire = Wire(new SubBundle(8, 4)) + val myWire = Wire(new SubBundle(8, 4)) - assert(myWire.i == 8) - assert(myWire.i2 == 4) - } } - elaborate { new Module { - val io = IO(new Bundle{}) + assert(myWire.i == 8) + assert(myWire.i2 == 4) + } + } + elaborate { + new Module { + val io = IO(new Bundle {}) - val myWire = Wire(new SubBundleVal(8, 4)) + val myWire = Wire(new SubBundleVal(8, 4)) - assert(myWire.i == 8) - assert(myWire.i2 == 4) - } } + assert(myWire.i == 8) + assert(myWire.i2 == 4) + } + } } "Autoclonetype" should "work outside of a builder context" in { @@ -130,10 +140,12 @@ class AutoClonetypeSpec extends ChiselFlatSpec with Utils { } "Subtyped Bundles that don't clone well" should "be now be supported!" in { - elaborate { new Module { - val io = IO(new Bundle{}) - val myWire = Wire(new SubBundleInvalid(8, 4)) - } } + elaborate { + new Module { + val io = IO(new Bundle {}) + val myWire = Wire(new SubBundleInvalid(8, 4)) + } + } } "Inner bundles with Scala args" should "not need clonetype" in { @@ -141,76 +153,92 @@ class AutoClonetypeSpec extends ChiselFlatSpec with Utils { } "Bundles with arguments as fields" should "not need clonetype" in { - elaborate { new Module { - val io = IO(Output(new BundleWithArgumentField(UInt(8.W), UInt(8.W)))) - io.x := 1.U - io.y := 1.U - } } + elaborate { + new Module { + val io = IO(Output(new BundleWithArgumentField(UInt(8.W), UInt(8.W)))) + io.x := 1.U + io.y := 1.U + } + } } it should "also work when giving directions to the fields" in { - elaborate { new Module { - val io = IO(new BundleWithArgumentField(Input(UInt(8.W)), Output(UInt(8.W)))) - io.y := io.x - } } + elaborate { + new Module { + val io = IO(new BundleWithArgumentField(Input(UInt(8.W)), Output(UInt(8.W)))) + io.y := io.x + } + } } "Bundles inside companion objects" should "not need clonetype" in { - elaborate { new Module { - val io = IO(Output(new CompanionObjectWithBundle.Inner)) - io.data := 1.U - } } + elaborate { + new Module { + val io = IO(Output(new CompanionObjectWithBundle.Inner)) + io.data := 1.U + } + } } "Parameterized bundles inside companion objects" should "not need clonetype" in { - elaborate { new Module { - val io = IO(Output(new CompanionObjectWithBundle.ParameterizedInner(8))) - io.data := 1.U - } } + elaborate { + new Module { + val io = IO(Output(new CompanionObjectWithBundle.ParameterizedInner(8))) + io.data := 1.U + } + } } "Nested directioned anonymous Bundles" should "not need clonetype" in { - elaborate { new Module { - val io = IO(new NestedAnonymousBundle) - val a = WireDefault(io) - io.a.a := 1.U - } } + elaborate { + new Module { + val io = IO(new NestedAnonymousBundle) + val a = WireDefault(io) + io.a.a := 1.U + } + } } "3.0 null compatibility" should "not need clonetype" in { - elaborate { new Module { - class InnerClassThing { - def createBundle: Bundle = new Bundle { - val a = Output(UInt(8.W)) + elaborate { + new Module { + class InnerClassThing { + def createBundle: Bundle = new Bundle { + val a = Output(UInt(8.W)) + } } + val io = IO((new InnerClassThing).createBundle) + val a = WireDefault(io) } - val io = IO((new InnerClassThing).createBundle) - val a = WireDefault(io) - } } + } } "Aliased fields" should "be caught" in { - a [ChiselException] should be thrownBy extractCause[ChiselException] { - elaborate { new Module { - val bundleFieldType = UInt(8.W) - val io = IO(Output(new Bundle { - val a = bundleFieldType - })) - io.a := 0.U - } } + a[ChiselException] should be thrownBy extractCause[ChiselException] { + elaborate { + new Module { + val bundleFieldType = UInt(8.W) + val io = IO(Output(new Bundle { + val a = bundleFieldType + })) + io.a := 0.U + } + } } } "Aliased fields from inadequate autoclonetype" should "be caught" in { - a [ChiselException] should be thrownBy extractCause[ChiselException] { + a[ChiselException] should be thrownBy extractCause[ChiselException] { class BadBundle(val typeTuple: (Data, Int)) extends Bundle { val a = typeTuple._1 } - elaborate { new Module { - val io = IO(Output(new BadBundle(UInt(8.W), 1))) - io.a := 0.U - } } + elaborate { + new Module { + val io = IO(Output(new BadBundle(UInt(8.W), 1))) + io.a := 0.U + } + } } } @@ -250,7 +278,7 @@ class AutoClonetypeSpec extends ChiselFlatSpec with Utils { elaborate(new MyModule(3)) } - behavior of "Compiler Plugin Autoclonetype" + behavior.of("Compiler Plugin Autoclonetype") it should "NOT break code that extends chisel3.util Bundles if they use the plugin" in { class MyModule extends MultiIOModule { @@ -266,34 +294,40 @@ class AutoClonetypeSpec extends ChiselFlatSpec with Utils { class MyBundle(i: Int) extends Bundle { val foo = UInt(i.W) } - elaborate { new MultiIOModule { - val in = IO(Input(new MyBundle(8))) - val out = IO(Output(new MyBundle(8))) - out := in - }} + elaborate { + new MultiIOModule { + val in = IO(Input(new MyBundle(8))) + val out = IO(Output(new MyBundle(8))) + out := in + } + } } it should "support type-parameterized Bundles" in { class MyBundle[T <: Data](gen: T) extends Bundle { val foo = gen } - elaborate { new MultiIOModule { - val in = IO(Input(new MyBundle(UInt(8.W)))) - val out = IO(Output(new MyBundle(UInt(8.W)))) - out := in - }} + elaborate { + new MultiIOModule { + val in = IO(Input(new MyBundle(UInt(8.W)))) + val out = IO(Output(new MyBundle(UInt(8.W)))) + out := in + } + } } it should "support Bundles with non-val implicit parameters" in { class MyBundle(implicit i: Int) extends Bundle { val foo = UInt(i.W) } - elaborate { new MultiIOModule { - implicit val x = 8 - val in = IO(Input(new MyBundle)) - val out = IO(Output(new MyBundle)) - out := in - }} + elaborate { + new MultiIOModule { + implicit val x = 8 + val in = IO(Input(new MyBundle)) + val out = IO(Output(new MyBundle)) + out := in + } + } } it should "support Bundles with multiple parameter lists" in { @@ -313,11 +347,13 @@ class AutoClonetypeSpec extends ChiselFlatSpec with Utils { class MyBundle(i: Int) extends Bundle { val foo = UInt(i.W) } - elaborate { new MultiIOModule { - val in = IO(Input(new MyBundle(8))) - val out = IO(Output(new MyBundle(8))) - out := in - }} + elaborate { + new MultiIOModule { + val in = IO(Input(new MyBundle(8))) + val out = IO(Output(new MyBundle(8))) + out := in + } + } } it should "support Bundles that capture type parameters from their parent scope" in { diff --git a/src/test/scala/chiselTests/AutoNestedCloneSpec.scala b/src/test/scala/chiselTests/AutoNestedCloneSpec.scala index 258d0823..b75c0c00 100644 --- a/src/test/scala/chiselTests/AutoNestedCloneSpec.scala +++ b/src/test/scala/chiselTests/AutoNestedCloneSpec.scala @@ -14,7 +14,7 @@ class BundleWithAnonymousInner(val w: Int) extends Bundle { class AutoNestedCloneSpec extends ChiselFlatSpec with Matchers with Utils { - behavior of "autoCloneType of inner Bundle in Chisel3" + behavior.of("autoCloneType of inner Bundle in Chisel3") it should "clone a doubly-nested inner bundle successfully" in { elaborate { @@ -36,7 +36,7 @@ class AutoNestedCloneSpec extends ChiselFlatSpec with Matchers with Utils { elaborate { class TestTop(val w: Int) extends Module { val io = IO(new Bundle {}) - val myWire = Wire(new Bundle{ val a = UInt(w.W) }) + val myWire = Wire(new Bundle { val a = UInt(w.W) }) } new TestTop(2) } @@ -45,13 +45,13 @@ class AutoNestedCloneSpec extends ChiselFlatSpec with Matchers with Utils { it should "pick the correct $outer instance for an anonymous inner bundle" in { elaborate { class Inner(val w: Int) extends Module { - val io = IO(new Bundle{ + val io = IO(new Bundle { val in = Input(UInt(w.W)) val out = Output(UInt(w.W)) }) } class Outer(val w: Int) extends Module { - val io = IO(new Bundle{ + val io = IO(new Bundle { val in = Input(UInt(w.W)) val out = Output(UInt(w.W)) }) @@ -125,7 +125,7 @@ class AutoNestedCloneSpec extends ChiselFlatSpec with Matchers with Utils { val foo = new Bundle { val x = Input(Vec(n, gen)) } - val bar = Output(Option(new { def mkBundle = new Bundle { val x = Vec(n, gen) }}).get.mkBundle) + val bar = Output(Option(new { def mkBundle = new Bundle { val x = Vec(n, gen) } }).get.mkBundle) } val io = IO(new MyBundle(4, UInt(8.W))) val myWire = WireInit(io.foo) diff --git a/src/test/scala/chiselTests/BetterNamingTests.scala b/src/test/scala/chiselTests/BetterNamingTests.scala index a55d3e08..8fd1c11f 100644 --- a/src/test/scala/chiselTests/BetterNamingTests.scala +++ b/src/test/scala/chiselTests/BetterNamingTests.scala @@ -31,10 +31,14 @@ class IterableNaming extends NamedModuleTester { val seq = Seq.tabulate(3) { i => Seq.tabulate(2) { j => expectName(WireDefault((i * j).U), s"seq_${i}_${j}") } } - val optSet = Some(Set(expectName(WireDefault(0.U), "optSet_0"), - expectName(WireDefault(1.U), "optSet_1"), - expectName(WireDefault(2.U), "optSet_2"), - expectName(WireDefault(3.U), "optSet_3"))) + val optSet = Some( + Set( + expectName(WireDefault(0.U), "optSet_0"), + expectName(WireDefault(1.U), "optSet_1"), + expectName(WireDefault(2.U), "optSet_2"), + expectName(WireDefault(3.U), "optSet_3") + ) + ) val stack = { val s = mutable.Stack[Module]() @@ -62,7 +66,7 @@ class DigitFieldNamesInRecord extends NamedModuleTester { */ class BetterNamingTests extends ChiselFlatSpec { - behavior of "Better Naming" + behavior.of("Better Naming") it should "provide unique counters for each name" in { var module: PerNameIndexing = null @@ -77,7 +81,7 @@ class BetterNamingTests extends ChiselFlatSpec { } it should "allow digits to be field names in Records" in { - var module: DigitFieldNamesInRecord = null + var module: DigitFieldNamesInRecord = null ChiselStage.elaborate { module = new DigitFieldNamesInRecord; module } assert(module.getNameFailures() == Nil) } @@ -92,6 +96,6 @@ class BetterNamingTests extends ChiselFlatSpec { } val withLits = ChiselStage.emitChirrtl(new MyModule(true)) val noLits = ChiselStage.emitChirrtl(new MyModule(false)) - withLits should equal (noLits) + withLits should equal(noLits) } } diff --git a/src/test/scala/chiselTests/BitwiseOps.scala b/src/test/scala/chiselTests/BitwiseOps.scala index 9cbadbc1..2c050bfa 100644 --- a/src/test/scala/chiselTests/BitwiseOps.scala +++ b/src/test/scala/chiselTests/BitwiseOps.scala @@ -14,14 +14,15 @@ class BitwiseOpsTester(w: Int, _a: Int, _b: Int) extends BasicTester { assert((a | b) === (_a | _b).asUInt) assert((a ^ b) === (_a ^ _b).asUInt) assert((a.orR) === (_a != 0).asBool) - assert((a.andR) === (s"%${w}s".format(BigInt(_a).toString(2)).foldLeft(true)(_ && _ == '1') ).asBool) + assert((a.andR) === (s"%${w}s".format(BigInt(_a).toString(2)).foldLeft(true)(_ && _ == '1')).asBool) stop() } class BitwiseOpsSpec extends ChiselPropSpec { property("All bit-wise ops should return the correct result") { - forAll(safeUIntPair) { case(w: Int, a: Int, b: Int) => - assertTesterPasses{ new BitwiseOpsTester(w, a, b) } + forAll(safeUIntPair) { + case (w: Int, a: Int, b: Int) => + assertTesterPasses { new BitwiseOpsTester(w, a, b) } } } } diff --git a/src/test/scala/chiselTests/BlackBox.scala b/src/test/scala/chiselTests/BlackBox.scala index d3d52f96..27cdbbc4 100644 --- a/src/test/scala/chiselTests/BlackBox.scala +++ b/src/test/scala/chiselTests/BlackBox.scala @@ -5,7 +5,7 @@ package chiselTests import chisel3._ import chisel3.experimental._ import chisel3.stage.ChiselStage -import chisel3.testers.{TesterDriver, BasicTester} +import chisel3.testers.{BasicTester, TesterDriver} import chisel3.util._ class BlackBoxInverter extends BlackBox { @@ -120,8 +120,7 @@ class BlackBoxWithClockTester extends BasicTester { when(end) { stop() } } -class BlackBoxConstant(value: Int) extends BlackBox( - Map("VALUE" -> value, "WIDTH" -> log2Ceil(value + 1))) { +class BlackBoxConstant(value: Int) extends BlackBox(Map("VALUE" -> value, "WIDTH" -> log2Ceil(value + 1))) { require(value >= 0, "value must be a UInt!") val io = IO(new Bundle { val out = Output(UInt(log2Ceil(value + 1).W)) @@ -147,8 +146,8 @@ class BlackBoxTypeParam(w: Int, raw: String) extends BlackBox(Map("T" -> RawPara } class BlackBoxWithParamsTester extends BasicTester { - val blackBoxOne = Module(new BlackBoxConstant(1)) - val blackBoxFour = Module(new BlackBoxConstant(4)) + val blackBoxOne = Module(new BlackBoxConstant(1)) + val blackBoxFour = Module(new BlackBoxConstant(4)) val blackBoxStringParamOne = Module(new BlackBoxStringParam("one")) val blackBoxStringParamTwo = Module(new BlackBoxStringParam("two")) val blackBoxRealParamOne = Module(new BlackBoxRealParam(1.0)) @@ -158,7 +157,7 @@ class BlackBoxWithParamsTester extends BasicTester { val (cycles, end) = Counter(true.B, 4) - assert(blackBoxOne.io.out === 1.U) + assert(blackBoxOne.io.out === 1.U) assert(blackBoxFour.io.out === 4.U) assert(blackBoxStringParamOne.io.out === 1.U) assert(blackBoxStringParamTwo.io.out === 2.U) @@ -172,47 +171,28 @@ class BlackBoxWithParamsTester extends BasicTester { class BlackBoxSpec extends ChiselFlatSpec { "A BlackBoxed inverter" should "work" in { - assertTesterPasses( - {new BlackBoxTester}, - Seq("/chisel3/BlackBoxTest.v"), - TesterDriver.verilatorOnly) + assertTesterPasses({ new BlackBoxTester }, Seq("/chisel3/BlackBoxTest.v"), TesterDriver.verilatorOnly) } "A BlackBoxed with flipped IO" should "work" in { - assertTesterPasses( - {new BlackBoxFlipTester}, - Seq("/chisel3/BlackBoxTest.v"), - TesterDriver.verilatorOnly) + assertTesterPasses({ new BlackBoxFlipTester }, Seq("/chisel3/BlackBoxTest.v"), TesterDriver.verilatorOnly) } "Multiple BlackBoxes" should "work" in { - assertTesterPasses( - {new MultiBlackBoxTester}, - Seq("/chisel3/BlackBoxTest.v"), - TesterDriver.verilatorOnly) + assertTesterPasses({ new MultiBlackBoxTester }, Seq("/chisel3/BlackBoxTest.v"), TesterDriver.verilatorOnly) } "A BlackBoxed register" should "work" in { - assertTesterPasses( - {new BlackBoxWithClockTester}, - Seq("/chisel3/BlackBoxTest.v"), - TesterDriver.verilatorOnly) + assertTesterPasses({ new BlackBoxWithClockTester }, Seq("/chisel3/BlackBoxTest.v"), TesterDriver.verilatorOnly) } "BlackBoxes with parameters" should "work" in { - assertTesterPasses( - {new BlackBoxWithParamsTester}, - Seq("/chisel3/BlackBoxTest.v"), - TesterDriver.verilatorOnly) + assertTesterPasses({ new BlackBoxWithParamsTester }, Seq("/chisel3/BlackBoxTest.v"), TesterDriver.verilatorOnly) } "DataMirror.modulePorts" should "work with BlackBox" in { ChiselStage.elaborate(new Module { - val io = IO(new Bundle {}) - val m = Module(new BlackBoxPassthrough) - assert(DataMirror.modulePorts(m) == Seq("in" -> m.io.in, "out" -> m.io.out)) - } - ) + val io = IO(new Bundle {}) + val m = Module(new BlackBoxPassthrough) + assert(DataMirror.modulePorts(m) == Seq("in" -> m.io.in, "out" -> m.io.out)) + }) } "A BlackBoxed using suggestName(\"io\")" should "work (but don't do this)" in { - assertTesterPasses( - {new BlackBoxTesterSuggestName}, - Seq("/chisel3/BlackBoxTest.v"), - TesterDriver.verilatorOnly) + assertTesterPasses({ new BlackBoxTesterSuggestName }, Seq("/chisel3/BlackBoxTest.v"), TesterDriver.verilatorOnly) } } diff --git a/src/test/scala/chiselTests/BlackBoxImpl.scala b/src/test/scala/chiselTests/BlackBoxImpl.scala index 2fa3d8a6..4cc72dd0 100644 --- a/src/test/scala/chiselTests/BlackBoxImpl.scala +++ b/src/test/scala/chiselTests/BlackBoxImpl.scala @@ -5,7 +5,7 @@ package chiselTests import java.io.File import chisel3._ -import chisel3.util.{HasBlackBoxInline, HasBlackBoxResource, HasBlackBoxPath} +import chisel3.util.{HasBlackBoxInline, HasBlackBoxPath, HasBlackBoxResource} import chisel3.stage.{ChiselGeneratorAnnotation, ChiselStage} import firrtl.transforms.BlackBoxNotFoundException import org.scalacheck.Test.Failed @@ -13,22 +13,23 @@ import org.scalatest.Succeeded import org.scalatest.freespec.AnyFreeSpec import org.scalatest.matchers.should.Matchers - -class BlackBoxAdd(n : Int) extends HasBlackBoxInline { +class BlackBoxAdd(n: Int) extends HasBlackBoxInline { val io = IO(new Bundle { val in = Input(UInt(16.W)) val out = Output(UInt(16.W)) }) - setInline("BlackBoxAdd.v", + setInline( + "BlackBoxAdd.v", s""" - |module BlackBoxAdd( - | input [15:0] in, - | output [15:0] out - |); - | assign out = in + $n; - |endmodule - """.stripMargin) + |module BlackBoxAdd( + | input [15:0] in, + | output [15:0] out + |); + | assign out = in + $n; + |endmodule + """.stripMargin + ) } class UsesBlackBoxAddViaInline extends Module { @@ -89,7 +90,7 @@ class UsesBlackBoxMinusViaPath extends Module { } class BlackBoxResourceNotFound extends HasBlackBoxResource { - val io = IO(new Bundle{}) + val io = IO(new Bundle {}) addResource("/missing.resource") } @@ -102,29 +103,35 @@ class BlackBoxImplSpec extends AnyFreeSpec with Matchers { val stage = new ChiselStage "BlackBox can have verilator source implementation" - { "Implementations can be contained in-line" in { - stage.execute(Array("-X", "verilog", "--target-dir", targetDir), - Seq(ChiselGeneratorAnnotation(() => new UsesBlackBoxAddViaInline))) + stage.execute( + Array("-X", "verilog", "--target-dir", targetDir), + Seq(ChiselGeneratorAnnotation(() => new UsesBlackBoxAddViaInline)) + ) val verilogOutput = new File(targetDir, "BlackBoxAdd.v") - verilogOutput.exists() should be (true) + verilogOutput.exists() should be(true) verilogOutput.delete() } "Implementations can be contained in resource files" in { - stage.execute(Array("-X", "low", "--target-dir", targetDir), - Seq(ChiselGeneratorAnnotation(() => new UsesBlackBoxMinusViaResource))) + stage.execute( + Array("-X", "low", "--target-dir", targetDir), + Seq(ChiselGeneratorAnnotation(() => new UsesBlackBoxMinusViaResource)) + ) val verilogOutput = new File(targetDir, "BlackBoxTest.v") - verilogOutput.exists() should be (true) + verilogOutput.exists() should be(true) verilogOutput.delete() } "Implementations can be contained in arbitrary files" in { - stage.execute(Array("-X", "low", "--target-dir", targetDir), - Seq(ChiselGeneratorAnnotation(() => new UsesBlackBoxMinusViaPath))) + stage.execute( + Array("-X", "low", "--target-dir", targetDir), + Seq(ChiselGeneratorAnnotation(() => new UsesBlackBoxMinusViaPath)) + ) val verilogOutput = new File(targetDir, "BlackBoxTest.v") - verilogOutput.exists() should be (true) + verilogOutput.exists() should be(true) verilogOutput.delete() Succeeded } "Resource files that do not exist produce Chisel errors" in { - assertThrows[BlackBoxNotFoundException]{ + assertThrows[BlackBoxNotFoundException] { ChiselStage.emitChirrtl(new UsesMissingBlackBoxResource) } } diff --git a/src/test/scala/chiselTests/BoringUtilsSpec.scala b/src/test/scala/chiselTests/BoringUtilsSpec.scala index 39859581..9be2d75a 100644 --- a/src/test/scala/chiselTests/BoringUtilsSpec.scala +++ b/src/test/scala/chiselTests/BoringUtilsSpec.scala @@ -8,7 +8,7 @@ import chisel3.testers._ import chisel3.experimental.{BaseModule, ChiselAnnotation, RunFirrtlTransform} import chisel3.util.experimental.BoringUtils -import firrtl.{CircuitForm, CircuitState, ChirrtlForm, DependencyAPIMigration, Transform} +import firrtl.{ChirrtlForm, CircuitForm, CircuitState, DependencyAPIMigration, Transform} import firrtl.annotations.{Annotation, NoTargetAnnotation} import firrtl.options.Dependency import firrtl.transforms.{DontTouchAnnotation, NoDedupAnnotation} @@ -18,7 +18,7 @@ import firrtl.stage.Forms abstract class ShouldntAssertTester(cyclesToWait: BigInt = 4) extends BasicTester { val dut: BaseModule val (_, done) = Counter(true.B, 2) - when (done) { stop() } + when(done) { stop() } } class StripNoDedupAnnotation extends Transform with DependencyAPIMigration { @@ -27,14 +27,14 @@ class StripNoDedupAnnotation extends Transform with DependencyAPIMigration { override def optionalPrerequisiteOf = Dependency[WiringTransform] +: Forms.ChirrtlEmitters override def invalidates(a: Transform) = false def execute(state: CircuitState): CircuitState = { - state.copy(annotations = state.annotations.filter{ case _: NoDedupAnnotation => false; case _ => true }) + state.copy(annotations = state.annotations.filter { case _: NoDedupAnnotation => false; case _ => true }) } } class BoringUtilsSpec extends ChiselFlatSpec with ChiselRunners { class BoringInverter extends Module { - val io = IO(new Bundle{}) + val io = IO(new Bundle {}) val a = Wire(UInt(1.W)) val notA = Wire(UInt(1.W)) val b = Wire(UInt(1.W)) @@ -46,11 +46,13 @@ class BoringUtilsSpec extends ChiselFlatSpec with ChiselRunners { BoringUtils.addSink(b, "x") } - behavior of "BoringUtils.{addSink, addSource}" + behavior.of("BoringUtils.{addSink, addSource}") it should "connect two wires within a module" in { - runTester(new ShouldntAssertTester { val dut = Module(new BoringInverter) }, - annotations = TesterDriver.verilatorOnly) should be (true) + runTester( + new ShouldntAssertTester { val dut = Module(new BoringInverter) }, + annotations = TesterDriver.verilatorOnly + ) should be(true) } trait WireX { this: BaseModule => @@ -77,10 +79,10 @@ class BoringUtilsSpec extends ChiselFlatSpec with ChiselRunners { val sinks = Seq.fill(6)(Module(new Sink)) /* Sources are differentiated by their input connections only. */ - sources.zip(Seq(0, 1, 2)).map{ case (a, b) => a.in := b.U } + sources.zip(Seq(0, 1, 2)).map { case (a, b) => a.in := b.U } /* Sinks are differentiated by their post-boring outputs. */ - sinks.zip(Seq(0, 1, 1, 2, 2, 2)).map{ case (a, b) => chisel3.assert(a.out === b.U) } + sinks.zip(Seq(0, 1, 1, 2, 2, 2)).map { case (a, b) => chisel3.assert(a.out === b.U) } } /** This is testing a complicated wiring pattern and exercising @@ -95,22 +97,22 @@ class BoringUtilsSpec extends ChiselFlatSpec with ChiselRunners { trait FailViaDedup { this: TopTester => case object FooAnnotation extends NoTargetAnnotation - chisel3.experimental.annotate( - new ChiselAnnotation with RunFirrtlTransform { - def toFirrtl: Annotation = FooAnnotation - def transformClass: Class[_ <: Transform] = classOf[StripNoDedupAnnotation] } ) + chisel3.experimental.annotate(new ChiselAnnotation with RunFirrtlTransform { + def toFirrtl: Annotation = FooAnnotation + def transformClass: Class[_ <: Transform] = classOf[StripNoDedupAnnotation] + }) } - behavior of "BoringUtils.bore" + behavior.of("BoringUtils.bore") it should "connect across modules using BoringUtils.bore" in { - runTester(new TopTester, annotations = TesterDriver.verilatorOnly) should be (true) + runTester(new TopTester, annotations = TesterDriver.verilatorOnly) should be(true) } it should "throw an exception if NoDedupAnnotations are removed" in { - intercept[WiringException] { runTester(new TopTester with FailViaDedup, - annotations = Seq(TesterDriver.VerilatorBackend)) } - .getMessage should startWith ("Unable to determine source mapping for sink") + intercept[WiringException] { + runTester(new TopTester with FailViaDedup, annotations = Seq(TesterDriver.VerilatorBackend)) + }.getMessage should startWith("Unable to determine source mapping for sink") } class InternalBore extends RawModule { @@ -127,7 +129,7 @@ class BoringUtilsSpec extends ChiselFlatSpec with ChiselRunners { } it should "work for an internal (same module) BoringUtils.bore" in { - runTester(new InternalBoreTester, annotations = TesterDriver.verilatorOnly) should be (true) + runTester(new InternalBoreTester, annotations = TesterDriver.verilatorOnly) should be(true) } } diff --git a/src/test/scala/chiselTests/BundleLiteralSpec.scala b/src/test/scala/chiselTests/BundleLiteralSpec.scala index b4adde4a..bc6522bb 100644 --- a/src/test/scala/chiselTests/BundleLiteralSpec.scala +++ b/src/test/scala/chiselTests/BundleLiteralSpec.scala @@ -29,50 +29,57 @@ class BundleLiteralSpec extends ChiselFlatSpec with Utils { } "bundle literals" should "pack" in { - assertTesterPasses{ new BasicTester { - val bundleLit = (new MyBundle).Lit(_.a -> 42.U, _.b -> false.B, _.c -> MyEnum.sB) - bundleLit.litOption should equal (Some(169)) // packed as 42 (8-bit), false=0 (1-bit), sB=1 (1-bit) - chisel3.assert(bundleLit.asUInt() === bundleLit.litOption.get.U) // sanity-check consistency with runtime - - val longBundleLit = (new LongBundle).Lit( - _.a -> 0xDEADDEADBEEFL.U, _.b -> (-0x0BEEF00DL).S(32.W), _.c -> 4.5.F(16.W, 4.BP)) - longBundleLit.litOption should equal (Some( - (BigInt(0xDEADDEADBEEFL) << 48) - + (BigInt(0xFFFFFFFFL - 0xBEEF00DL + 1) << 16) - + BigInt(72))) - chisel3.assert(longBundleLit.asUInt() === longBundleLit.litOption.get.U) - - stop() - } } + assertTesterPasses { + new BasicTester { + val bundleLit = (new MyBundle).Lit(_.a -> 42.U, _.b -> false.B, _.c -> MyEnum.sB) + bundleLit.litOption should equal(Some(169)) // packed as 42 (8-bit), false=0 (1-bit), sB=1 (1-bit) + chisel3.assert(bundleLit.asUInt() === bundleLit.litOption.get.U) // sanity-check consistency with runtime + + val longBundleLit = + (new LongBundle).Lit(_.a -> 0xdeaddeadbeefL.U, _.b -> (-0x0beef00dL).S(32.W), _.c -> 4.5.F(16.W, 4.BP)) + longBundleLit.litOption should equal( + Some( + (BigInt(0xdeaddeadbeefL) << 48) + + (BigInt(0xffffffffL - 0xbeef00dL + 1) << 16) + + BigInt(72) + ) + ) + chisel3.assert(longBundleLit.asUInt() === longBundleLit.litOption.get.U) + + stop() + } + } } "bundle literals" should "work in RTL" in { val outsideBundleLit = (new MyBundle).Lit(_.a -> 42.U, _.b -> true.B, _.c -> MyEnum.sB) - assertTesterPasses{ new BasicTester{ - // TODO: add direct bundle compare operations, when that feature is added - chisel3.assert(outsideBundleLit.a === 42.U) - chisel3.assert(outsideBundleLit.b === true.B) - chisel3.assert(outsideBundleLit.c === MyEnum.sB) - chisel3.assert(outsideBundleLit.isLit()) - chisel3.assert(outsideBundleLit.litValue().U === outsideBundleLit.asUInt()) - val bundleLit = (new MyBundle).Lit(_.a -> 42.U, _.b -> true.B, _.c -> MyEnum.sB) - chisel3.assert(bundleLit.a === 42.U) - chisel3.assert(bundleLit.b === true.B) - chisel3.assert(bundleLit.c === MyEnum.sB) - - chisel3.assert(bundleLit.a === outsideBundleLit.a) - chisel3.assert(bundleLit.b === outsideBundleLit.b) - chisel3.assert(bundleLit.c === outsideBundleLit.c) - - val bundleWire = Wire(new MyBundle) - bundleWire := outsideBundleLit - - chisel3.assert(bundleWire.a === 42.U) - chisel3.assert(bundleWire.b === true.B) - chisel3.assert(bundleWire.c === MyEnum.sB) - - stop() - } } + assertTesterPasses { + new BasicTester { + // TODO: add direct bundle compare operations, when that feature is added + chisel3.assert(outsideBundleLit.a === 42.U) + chisel3.assert(outsideBundleLit.b === true.B) + chisel3.assert(outsideBundleLit.c === MyEnum.sB) + chisel3.assert(outsideBundleLit.isLit()) + chisel3.assert(outsideBundleLit.litValue().U === outsideBundleLit.asUInt()) + val bundleLit = (new MyBundle).Lit(_.a -> 42.U, _.b -> true.B, _.c -> MyEnum.sB) + chisel3.assert(bundleLit.a === 42.U) + chisel3.assert(bundleLit.b === true.B) + chisel3.assert(bundleLit.c === MyEnum.sB) + + chisel3.assert(bundleLit.a === outsideBundleLit.a) + chisel3.assert(bundleLit.b === outsideBundleLit.b) + chisel3.assert(bundleLit.c === outsideBundleLit.c) + + val bundleWire = Wire(new MyBundle) + bundleWire := outsideBundleLit + + chisel3.assert(bundleWire.a === 42.U) + chisel3.assert(bundleWire.b === true.B) + chisel3.assert(bundleWire.c === MyEnum.sB) + + stop() + } + } } "bundle literals of vec literals" should "work" in { @@ -82,11 +89,11 @@ class BundleLiteralSpec extends ChiselFlatSpec with Utils { val a = Vec(2, UInt(4.W)) val b = Vec(2, Interval(range)) }.Lit( - _.a -> Vec(2, UInt(4.W)).Lit(0 -> 0xA.U, 1 -> 0xB.U), + _.a -> Vec(2, UInt(4.W)).Lit(0 -> 0xa.U, 1 -> 0xb.U), _.b -> Vec(2, Interval(range)).Lit(0 -> (1.5).I(range), 1 -> (0.25).I(range)) ) - chisel3.assert(bundleWithVecs.a(0) === 0xA.U) - chisel3.assert(bundleWithVecs.a(1) === 0xB.U) + chisel3.assert(bundleWithVecs.a(0) === 0xa.U) + chisel3.assert(bundleWithVecs.a(1) === 0xb.U) chisel3.assert(bundleWithVecs.b(0) === (1.5).I(range)) chisel3.assert(bundleWithVecs.b(1) === (0.25).I(range)) stop() @@ -94,17 +101,19 @@ class BundleLiteralSpec extends ChiselFlatSpec with Utils { } "partial bundle literals" should "work in RTL" in { - assertTesterPasses{ new BasicTester{ - val bundleLit = (new MyBundle).Lit(_.a -> 42.U) - chisel3.assert(bundleLit.a === 42.U) + assertTesterPasses { + new BasicTester { + val bundleLit = (new MyBundle).Lit(_.a -> 42.U) + chisel3.assert(bundleLit.a === 42.U) - val bundleWire = Wire(new MyBundle) - bundleWire := bundleLit + val bundleWire = Wire(new MyBundle) + bundleWire := bundleLit - chisel3.assert(bundleWire.a === 42.U) + chisel3.assert(bundleWire.a === 42.U) - stop() - } } + stop() + } + } } class MyOuterBundle extends Bundle { @@ -118,120 +127,138 @@ class BundleLiteralSpec extends ChiselFlatSpec with Utils { } "contained bundles" should "work" in { - assertTesterPasses{ new BasicTester{ - // Specify the inner Bundle value as a Bundle literal - val explicitBundleLit = (new MyOuterBundle).Lit( - _.a -> (new MyBundle).Lit(_.a -> 42.U, _.b -> true.B, _.c -> MyEnum.sB) - ) - chisel3.assert(explicitBundleLit.a.a === 42.U) - chisel3.assert(explicitBundleLit.a.b === true.B) - chisel3.assert(explicitBundleLit.a.c === MyEnum.sB) - chisel3.assert(explicitBundleLit.a.isLit()) - chisel3.assert(explicitBundleLit.a.litValue().U === explicitBundleLit.a.asUInt()) - - // Specify the inner Bundle fields directly - val expandedBundleLit = (new MyOuterBundle).Lit( - _.a.a -> 42.U, _.a.b -> true.B, - _.b.c -> false.B, _.b.d -> 255.U, _.b.e -> MyEnum.sB, - _.f -> MyEnum.sB - ) - chisel3.assert(expandedBundleLit.a.a === 42.U) - chisel3.assert(expandedBundleLit.a.b === true.B) - chisel3.assert(expandedBundleLit.f === MyEnum.sB) - chisel3.assert(expandedBundleLit.b.c === false.B) - chisel3.assert(expandedBundleLit.b.d === 255.U) - chisel3.assert(expandedBundleLit.b.e === MyEnum.sB) - chisel3.assert(! expandedBundleLit.a.isLit()) // element e is missing - chisel3.assert(expandedBundleLit.b.isLit()) - chisel3.assert(! expandedBundleLit.isLit()) // element a.e is missing - chisel3.assert(expandedBundleLit.b.litValue().U === expandedBundleLit.b.asUInt()) - - // Anonymously contruct the inner Bundle literal - // A bit of weird syntax that depends on implementation details of the Bundle literal constructor - val childBundleLit = (new MyOuterBundle).Lit( - b => b.b -> b.b.Lit(_.c -> false.B, _.d -> 255.U, _.e -> MyEnum.sB) - ) - chisel3.assert(childBundleLit.b.c === false.B) - chisel3.assert(childBundleLit.b.d === 255.U) - chisel3.assert(childBundleLit.b.e === MyEnum.sB) - chisel3.assert(childBundleLit.b.isLit()) - chisel3.assert(! childBundleLit.isLit()) // elements a and f are missing - chisel3.assert(childBundleLit.b.litValue().U === childBundleLit.b.asUInt()) - - stop() - } } + assertTesterPasses { + new BasicTester { + // Specify the inner Bundle value as a Bundle literal + val explicitBundleLit = (new MyOuterBundle).Lit( + _.a -> (new MyBundle).Lit(_.a -> 42.U, _.b -> true.B, _.c -> MyEnum.sB) + ) + chisel3.assert(explicitBundleLit.a.a === 42.U) + chisel3.assert(explicitBundleLit.a.b === true.B) + chisel3.assert(explicitBundleLit.a.c === MyEnum.sB) + chisel3.assert(explicitBundleLit.a.isLit()) + chisel3.assert(explicitBundleLit.a.litValue().U === explicitBundleLit.a.asUInt()) + + // Specify the inner Bundle fields directly + val expandedBundleLit = (new MyOuterBundle).Lit( + _.a.a -> 42.U, + _.a.b -> true.B, + _.b.c -> false.B, + _.b.d -> 255.U, + _.b.e -> MyEnum.sB, + _.f -> MyEnum.sB + ) + chisel3.assert(expandedBundleLit.a.a === 42.U) + chisel3.assert(expandedBundleLit.a.b === true.B) + chisel3.assert(expandedBundleLit.f === MyEnum.sB) + chisel3.assert(expandedBundleLit.b.c === false.B) + chisel3.assert(expandedBundleLit.b.d === 255.U) + chisel3.assert(expandedBundleLit.b.e === MyEnum.sB) + chisel3.assert(!expandedBundleLit.a.isLit()) // element e is missing + chisel3.assert(expandedBundleLit.b.isLit()) + chisel3.assert(!expandedBundleLit.isLit()) // element a.e is missing + chisel3.assert(expandedBundleLit.b.litValue().U === expandedBundleLit.b.asUInt()) + + // Anonymously contruct the inner Bundle literal + // A bit of weird syntax that depends on implementation details of the Bundle literal constructor + val childBundleLit = + (new MyOuterBundle).Lit(b => b.b -> b.b.Lit(_.c -> false.B, _.d -> 255.U, _.e -> MyEnum.sB)) + chisel3.assert(childBundleLit.b.c === false.B) + chisel3.assert(childBundleLit.b.d === 255.U) + chisel3.assert(childBundleLit.b.e === MyEnum.sB) + chisel3.assert(childBundleLit.b.isLit()) + chisel3.assert(!childBundleLit.isLit()) // elements a and f are missing + chisel3.assert(childBundleLit.b.litValue().U === childBundleLit.b.asUInt()) + + stop() + } + } } "Bundle literals" should "assign" in { - assertTesterPasses{ new BasicTester{ - val bundleWire = Wire(Output(new MyBundle)) - val bundleLit = (new MyBundle).Lit(_.a -> 42.U, _.b -> true.B, _.c -> MyEnum.sB) - bundleWire := bundleLit - - chisel3.assert(bundleWire.a === 42.U) - chisel3.assert(bundleWire.b === true.B) - chisel3.assert(bundleWire.c === MyEnum.sB) - stop() - } } + assertTesterPasses { + new BasicTester { + val bundleWire = Wire(Output(new MyBundle)) + val bundleLit = (new MyBundle).Lit(_.a -> 42.U, _.b -> true.B, _.c -> MyEnum.sB) + bundleWire := bundleLit + + chisel3.assert(bundleWire.a === 42.U) + chisel3.assert(bundleWire.b === true.B) + chisel3.assert(bundleWire.c === MyEnum.sB) + stop() + } + } } "partially initialized Bundle literals" should "assign" in { - assertTesterPasses{ new BasicTester{ - val bundleWire = Wire(Output(new MyBundle)) - val bundleLit = (new MyBundle).Lit(_.a -> 42.U) - bundleWire := bundleLit - - chisel3.assert(bundleWire.a === 42.U) - stop() - } } + assertTesterPasses { + new BasicTester { + val bundleWire = Wire(Output(new MyBundle)) + val bundleLit = (new MyBundle).Lit(_.a -> 42.U) + bundleWire := bundleLit + + chisel3.assert(bundleWire.a === 42.U) + stop() + } + } } "Bundle literals" should "work as register reset values" in { - assertTesterPasses{ new BasicTester{ - val r = RegInit((new MyBundle).Lit(_.a -> 42.U, _.b -> true.B, _.c -> MyEnum.sB)) - r := (r.asUInt + 1.U).asTypeOf(new MyBundle) // prevent constprop - - // check reset values on first cycle out of reset - chisel3.assert(r.a === 42.U) - chisel3.assert(r.b === true.B) - chisel3.assert(r.c === MyEnum.sB) - stop() - } } + assertTesterPasses { + new BasicTester { + val r = RegInit((new MyBundle).Lit(_.a -> 42.U, _.b -> true.B, _.c -> MyEnum.sB)) + r := (r.asUInt + 1.U).asTypeOf(new MyBundle) // prevent constprop + + // check reset values on first cycle out of reset + chisel3.assert(r.a === 42.U) + chisel3.assert(r.b === true.B) + chisel3.assert(r.c === MyEnum.sB) + stop() + } + } } "partially initialized Bundle literals" should "work as register reset values" in { - assertTesterPasses{ new BasicTester{ - val r = RegInit((new MyBundle).Lit(_.a -> 42.U)) - r.a := r.a + 1.U // prevent const prop - chisel3.assert(r.a === 42.U) // coming out of reset - stop() - } } + assertTesterPasses { + new BasicTester { + val r = RegInit((new MyBundle).Lit(_.a -> 42.U)) + r.a := r.a + 1.U // prevent const prop + chisel3.assert(r.a === 42.U) // coming out of reset + stop() + } + } } "Fields extracted from BundleLiterals" should "work as register reset values" in { - assertTesterPasses{ new BasicTester{ - val r = RegInit((new MyBundle).Lit(_.a -> 42.U).a) - r := r + 1.U // prevent const prop - chisel3.assert(r === 42.U) // coming out of reset - stop() - } } + assertTesterPasses { + new BasicTester { + val r = RegInit((new MyBundle).Lit(_.a -> 42.U).a) + r := r + 1.U // prevent const prop + chisel3.assert(r === 42.U) // coming out of reset + stop() + } + } } "DontCare fields extracted from BundleLiterals" should "work as register reset values" in { - assertTesterPasses{ new BasicTester{ - val r = RegInit((new MyBundle).Lit(_.a -> 42.U).b) - r := reset.asBool - printf(p"r = $r\n") // Can't assert because reset value is DontCare - stop() - } } + assertTesterPasses { + new BasicTester { + val r = RegInit((new MyBundle).Lit(_.a -> 42.U).b) + r := reset.asBool + printf(p"r = $r\n") // Can't assert because reset value is DontCare + stop() + } + } } "DontCare fields extracted from BundleLiterals" should "work in other Expressions" in { - assertTesterPasses{ new BasicTester{ - val x = (new MyBundle).Lit(_.a -> 42.U).b || true.B - chisel3.assert(x === true.B) - stop() - } } + assertTesterPasses { + new BasicTester { + val x = (new MyBundle).Lit(_.a -> 42.U).b || true.B + chisel3.assert(x === true.B) + stop() + } + } } "bundle literals with bad field specifiers" should "fail" in { @@ -240,12 +267,12 @@ class BundleLiteralSpec extends ChiselFlatSpec with Utils { ChiselStage.elaborate { new RawModule { val bundle = new MyBundle - bundle.Lit(x => bundle.a -> 0.U) // DONT DO THIS, this gets past a syntax error to exercise the failure + bundle.Lit(x => bundle.a -> 0.U) // DONT DO THIS, this gets past a syntax error to exercise the failure } } } } - exc.getMessage should include ("not a field") + exc.getMessage should include("not a field") } "bundle literals with duplicate fields" should "fail" in { @@ -258,21 +285,22 @@ class BundleLiteralSpec extends ChiselFlatSpec with Utils { } } } - exc.getMessage should include ("duplicate") - exc.getMessage should include (".a") + exc.getMessage should include("duplicate") + exc.getMessage should include(".a") } "bundle literals with non-literal values" should "fail" in { val exc = intercept[BundleLiteralException] { extractCause[BundleLiteralException] { - ChiselStage.elaborate { new RawModule { - (new MyBundle).Lit(_.a -> UInt()) - } + ChiselStage.elaborate { + new RawModule { + (new MyBundle).Lit(_.a -> UInt()) + } } } } - exc.getMessage should include ("non-literal value") - exc.getMessage should include (".a") + exc.getMessage should include("non-literal value") + exc.getMessage should include(".a") } "bundle literals with non-type-equivalent element fields" should "fail" in { @@ -285,8 +313,8 @@ class BundleLiteralSpec extends ChiselFlatSpec with Utils { } } } - exc.getMessage should include ("non-type-equivalent value") - exc.getMessage should include (".a") + exc.getMessage should include("non-type-equivalent value") + exc.getMessage should include(".a") } "bundle literals with non-type-equivalent sub-bundles" should "fail" in { @@ -299,8 +327,8 @@ class BundleLiteralSpec extends ChiselFlatSpec with Utils { } } } - exc.getMessage should include ("non-type-equivalent value") - exc.getMessage should include (".b") + exc.getMessage should include("non-type-equivalent value") + exc.getMessage should include(".b") } "bundle literals with non-type-equivalent enum element fields" should "fail" in { @@ -313,14 +341,16 @@ class BundleLiteralSpec extends ChiselFlatSpec with Utils { } } } - exc.getMessage should include ("non-type-equivalent enum value") - exc.getMessage should include (".c") + exc.getMessage should include("non-type-equivalent enum value") + exc.getMessage should include(".c") } "partial bundle literals" should "fail to pack" in { - ChiselStage.elaborate { new RawModule { - val bundleLit = (new MyBundle).Lit(_.a -> 42.U) - bundleLit.litOption should equal (None) - } } + ChiselStage.elaborate { + new RawModule { + val bundleLit = (new MyBundle).Lit(_.a -> 42.U) + bundleLit.litOption should equal(None) + } + } } } diff --git a/src/test/scala/chiselTests/BundleSpec.scala b/src/test/scala/chiselTests/BundleSpec.scala index d9f82e6d..720f877f 100644 --- a/src/test/scala/chiselTests/BundleSpec.scala +++ b/src/test/scala/chiselTests/BundleSpec.scala @@ -61,13 +61,13 @@ class BundleSpec extends ChiselFlatSpec with BundleSpecUtils with Utils { } "Bulk connect on Bundles" should "check that the fields match" in { - (the [ChiselException] thrownBy extractCause[ChiselException] { + (the[ChiselException] thrownBy extractCause[ChiselException] { ChiselStage.elaborate { new MyModule(new BundleFooBar, new BundleFoo) } - }).getMessage should include ("Right Record missing field") + }).getMessage should include("Right Record missing field") - (the [ChiselException] thrownBy extractCause[ChiselException] { + (the[ChiselException] thrownBy extractCause[ChiselException] { ChiselStage.elaborate { new MyModule(new BundleFoo, new BundleFooBar) } - }).getMessage should include ("Left Record missing field") + }).getMessage should include("Left Record missing field") } "Bundles" should "not be able to use Seq for constructing hardware" in { @@ -120,33 +120,39 @@ class BundleSpec extends ChiselFlatSpec with BundleSpecUtils with Utils { } (the[ChiselException] thrownBy extractCause[ChiselException] { - ChiselStage.elaborate { new Module { - val io = IO(Output(new AliasedBundle)) - io.a := 0.U - io.b := 1.U - } } + ChiselStage.elaborate { + new Module { + val io = IO(Output(new AliasedBundle)) + io.a := 0.U + io.b := 1.U + } + } }).getMessage should include("contains aliased fields named (a,b),(c,d)") } "Bundles" should "not have bound hardware" in { (the[ChiselException] thrownBy extractCause[ChiselException] { - ChiselStage.elaborate { new Module { - class MyBundle(val foo: UInt) extends Bundle - val in = IO(Input(new MyBundle(123.U))) // This should error: value passed in instead of type - val out = IO(Output(new MyBundle(UInt(8.W)))) + ChiselStage.elaborate { + new Module { + class MyBundle(val foo: UInt) extends Bundle + val in = IO(Input(new MyBundle(123.U))) // This should error: value passed in instead of type + val out = IO(Output(new MyBundle(UInt(8.W)))) - out := in - } } + out := in + } + } }).getMessage should include("must be a Chisel type, not hardware") } "Bundles" should "not recursively contain aggregates with bound hardware" in { (the[ChiselException] thrownBy extractCause[ChiselException] { - ChiselStage.elaborate { new Module { - class MyBundle(val foo: UInt) extends Bundle - val out = IO(Output(Vec(2, UInt(8.W)))) - val in = IO(Input(new MyBundle(out(0)))) // This should error: Bound aggregate passed - out := in - } } + ChiselStage.elaborate { + new Module { + class MyBundle(val foo: UInt) extends Bundle + val out = IO(Output(Vec(2, UInt(8.W)))) + val in = IO(Input(new MyBundle(out(0)))) // This should error: Bound aggregate passed + out := in + } + } }).getMessage should include("must be a Chisel type, not hardware") } "Unbound bundles sharing a field" should "not error" in { diff --git a/src/test/scala/chiselTests/BundleWire.scala b/src/test/scala/chiselTests/BundleWire.scala index 830fb7e4..3b58d52a 100644 --- a/src/test/scala/chiselTests/BundleWire.scala +++ b/src/test/scala/chiselTests/BundleWire.scala @@ -11,12 +11,12 @@ class Coord extends Bundle { class BundleWire(n: Int) extends Module { val io = IO(new Bundle { - val in = Input(new Coord) + val in = Input(new Coord) val outs = Output(Vec(n, new Coord)) }) val coords = Wire(Vec(n, new Coord)) for (i <- 0 until n) { - coords(i) := io.in + coords(i) := io.in io.outs(i) := coords(i) } } @@ -57,14 +57,13 @@ class BundleWireSpec extends ChiselPropSpec { property("All vec elems should match the inputs") { forAll(vecSizes, safeUInts, safeUInts) { (n: Int, x: Int, y: Int) => - assertTesterPasses{ new BundleWireTester(n, x, y) } + assertTesterPasses { new BundleWireTester(n, x, y) } } } } class BundleToUIntSpec extends ChiselPropSpec { property("Bundles with same data but different, underlying elements should compare as UInt") { - assertTesterPasses( new BundleToUnitTester ) + assertTesterPasses(new BundleToUnitTester) } } - diff --git a/src/test/scala/chiselTests/ChiselSpec.scala b/src/test/scala/chiselTests/ChiselSpec.scala index 8647d903..6f560b94 100644 --- a/src/test/scala/chiselTests/ChiselSpec.scala +++ b/src/test/scala/chiselTests/ChiselSpec.scala @@ -4,7 +4,12 @@ package chiselTests import chisel3._ import chisel3.aop.Aspect -import chisel3.stage.{ChiselGeneratorAnnotation, ChiselStage, NoRunFirrtlCompilerAnnotation, PrintFullStackTraceAnnotation} +import chisel3.stage.{ + ChiselGeneratorAnnotation, + ChiselStage, + NoRunFirrtlCompilerAnnotation, + PrintFullStackTraceAnnotation +} import chisel3.testers._ import firrtl.annotations.Annotation import firrtl.ir.Circuit @@ -27,26 +32,29 @@ import scala.reflect.ClassTag /** Common utility functions for Chisel unit tests. */ trait ChiselRunners extends Assertions with BackendCompilationUtilities { - def runTester(t: => BasicTester, - additionalVResources: Seq[String] = Seq(), - annotations: AnnotationSeq = Seq() - ): Boolean = { + def runTester( + t: => BasicTester, + additionalVResources: Seq[String] = Seq(), + annotations: AnnotationSeq = Seq() + ): Boolean = { // Change this to enable Treadle as a backend val defaultBackend = chisel3.testers.TesterDriver.defaultBackend val hasBackend = TestUtils.containsBackend(annotations) val annos: Seq[Annotation] = if (hasBackend) annotations else defaultBackend +: annotations TesterDriver.execute(() => t, additionalVResources, annos) } - def assertTesterPasses(t: => BasicTester, - additionalVResources: Seq[String] = Seq(), - annotations: AnnotationSeq = Seq() - ): Unit = { + def assertTesterPasses( + t: => BasicTester, + additionalVResources: Seq[String] = Seq(), + annotations: AnnotationSeq = Seq() + ): Unit = { assert(runTester(t, additionalVResources, annotations)) } - def assertTesterFails(t: => BasicTester, - additionalVResources: Seq[String] = Seq(), - annotations: Seq[chisel3.aop.Aspect[_]] = Seq() - ): Unit = { + def assertTesterFails( + t: => BasicTester, + additionalVResources: Seq[String] = Seq(), + annotations: Seq[chisel3.aop.Aspect[_]] = Seq() + ): Unit = { assert(!runTester(t, additionalVResources, annotations)) } @@ -57,7 +65,7 @@ trait ChiselRunners extends Assertions with BackendCompilationUtilities { // Sanity check that firrtl doesn't change the width x := 0.U.asTypeOf(chiselTypeOf(x)) val (_, done) = chisel3.util.Counter(true.B, 2) - when (done) { + when(done) { chisel3.assert(~(x.asUInt) === -1.S(expected.W).asUInt) stop() } @@ -70,7 +78,7 @@ trait ChiselRunners extends Assertions with BackendCompilationUtilities { assert(!x.isWidthKnown, s"Asserting that width should be inferred yet width is known to Chisel!") x := 0.U.asTypeOf(chiselTypeOf(x)) val (_, done) = chisel3.util.Counter(true.B, 2) - when (done) { + when(done) { chisel3.assert(~(x.asUInt) === -1.S(expected.W).asUInt) stop() } @@ -84,11 +92,14 @@ trait ChiselRunners extends Assertions with BackendCompilationUtilities { */ def compile(t: => RawModule): String = { (new ChiselStage) - .execute(Array("--target-dir", createTestDirectory(this.getClass.getSimpleName).toString), - Seq(ChiselGeneratorAnnotation(() => t))) + .execute( + Array("--target-dir", createTestDirectory(this.getClass.getSimpleName).toString), + Seq(ChiselGeneratorAnnotation(() => t)) + ) .collectFirst { case EmittedVerilogCircuitAnnotation(a) => a.value - }.getOrElse(fail("No Verilog circuit was emitted by the FIRRTL compiler!")) + } + .getOrElse(fail("No Verilog circuit was emitted by the FIRRTL compiler!")) } def elaborateAndGetModule[A <: RawModule](t: => A): A = { @@ -147,9 +158,9 @@ abstract class ChiselPropSpec extends AnyPropSpec with ChiselRunners with ScalaC n <- Gen.choose(1, 10) } yield { if (dir) { - Range(m, (m+n)*step, step) + Range(m, (m + n) * step, step) } else { - Range((m+n)*step, m, -step) + Range((m + n) * step, m, -step) } } @@ -185,7 +196,7 @@ abstract class ChiselPropSpec extends AnyPropSpec with ChiselRunners with ScalaC w <- smallPosInts i <- Gen.containerOfN[List, Int](n, Gen.choose(0, (1 << w) - 1)) j <- Gen.containerOfN[List, Int](n, Gen.choose(0, (1 << w) - 1)) - } yield (w, i zip j) + } yield (w, i.zip(j)) // Generator which gives a width w and a pair of numbers up to w bits. val safeUIntPair = for { @@ -291,7 +302,6 @@ trait Utils { } } - /** A tester which runs generator and uses an aspect to check the returned object * @param gen function to generate a Chisel module * @param f a function to check the Chisel module @@ -300,14 +310,16 @@ trait Utils { def aspectTest[T <: RawModule](gen: () => T)(f: T => Unit)(implicit scalaMajorVersion: Int): Unit = { // Runs chisel stage def run[T <: RawModule](gen: () => T, annotations: AnnotationSeq): AnnotationSeq = { - new ChiselStage().run(Seq(ChiselGeneratorAnnotation(gen), NoRunFirrtlCompilerAnnotation, PrintFullStackTraceAnnotation) ++ annotations) + new ChiselStage().run( + Seq(ChiselGeneratorAnnotation(gen), NoRunFirrtlCompilerAnnotation, PrintFullStackTraceAnnotation) ++ annotations + ) } // Creates a wrapping aspect to contain checking function case object BuiltAspect extends Aspect[T] { - override def toAnnotation(top: T): AnnotationSeq = {f(top); Nil} + override def toAnnotation(top: T): AnnotationSeq = { f(top); Nil } } val currentMajorVersion = scala.util.Properties.versionNumberString.split('.')(1).toInt - if(currentMajorVersion >= scalaMajorVersion) { + if (currentMajorVersion >= scalaMajorVersion) { run(gen, Seq(BuiltAspect)) } } @@ -326,25 +338,27 @@ trait Utils { * @tparam A the type of the exception to extract * @return nothing */ - def extractCause[A <: Throwable : ClassTag](thunk: => Any): Unit = { + def extractCause[A <: Throwable: ClassTag](thunk: => Any): Unit = { def unrollCauses(a: Throwable): Seq[Throwable] = a match { case null => Seq.empty case _ => a +: unrollCauses(a.getCause) } - val exceptions: Seq[_ <: Throwable] = try { - thunk - Seq.empty - } catch { - case a: Throwable => unrollCauses(a) - } + val exceptions: Seq[_ <: Throwable] = + try { + thunk + Seq.empty + } catch { + case a: Throwable => unrollCauses(a) + } - exceptions.collectFirst{ case a: A => a } match { + exceptions.collectFirst { case a: A => a } match { case Some(a) => throw a - case None => exceptions match { - case Nil => () - case h :: t => throw h - } + case None => + exceptions match { + case Nil => () + case h :: t => throw h + } } } diff --git a/src/test/scala/chiselTests/ChiselTestUtilitiesSpec.scala b/src/test/scala/chiselTests/ChiselTestUtilitiesSpec.scala index 40358d11..451ba885 100644 --- a/src/test/scala/chiselTests/ChiselTestUtilitiesSpec.scala +++ b/src/test/scala/chiselTests/ChiselTestUtilitiesSpec.scala @@ -38,7 +38,7 @@ class ChiselTestUtilitiesSpec extends ChiselFlatSpec { } it should "error if the expected width is wrong" in { - a [TestFailedException] shouldBe thrownBy { + a[TestFailedException] shouldBe thrownBy { assertInferredWidth(8) { val w = Wire(UInt()) w := 2.U(2.W) diff --git a/src/test/scala/chiselTests/Clock.scala b/src/test/scala/chiselTests/Clock.scala index 3eb949fb..c28e1344 100644 --- a/src/test/scala/chiselTests/Clock.scala +++ b/src/test/scala/chiselTests/Clock.scala @@ -24,7 +24,6 @@ class WithClockAndNoReset extends RawModule { out := a } - class ClockSpec extends ChiselPropSpec { property("Bool.asClock.asUInt should pass a signal through unaltered") { assertTesterPasses { new ClockAsUIntTester } @@ -32,6 +31,6 @@ class ClockSpec extends ChiselPropSpec { property("Should be able to use withClock in a module with no reset") { val circuit = ChiselStage.emitChirrtl(new WithClockAndNoReset) - circuit.contains("reg a : UInt<1>, clock2") should be (true) + circuit.contains("reg a : UInt<1>, clock2") should be(true) } } diff --git a/src/test/scala/chiselTests/CloneModuleSpec.scala b/src/test/scala/chiselTests/CloneModuleSpec.scala index 8359bc28..4a70db85 100644 --- a/src/test/scala/chiselTests/CloneModuleSpec.scala +++ b/src/test/scala/chiselTests/CloneModuleSpec.scala @@ -4,7 +4,7 @@ package chiselTests import chisel3._ import chisel3.stage.ChiselStage -import chisel3.util.{Decoupled, Queue, EnqIO, DeqIO, QueueIO, log2Ceil} +import chisel3.util.{log2Ceil, Decoupled, DeqIO, EnqIO, Queue, QueueIO} import chisel3.experimental.{CloneModuleAsRecord, IO} import chisel3.testers.BasicTester @@ -51,7 +51,7 @@ class QueueCloneTester(x: Int, multiIO: Boolean = false) extends BasicTester { dut.io.enq.bits := x.U dut.io.enq.valid := start dut.io.deq.ready := accept - when (dut.io.deq.fire) { + when(dut.io.deq.fire) { assert(dut.io.deq.bits === x.U) stop() } @@ -80,14 +80,15 @@ class CloneModuleAsRecordAnnotate extends Module { class CloneModuleSpec extends ChiselPropSpec { val xVals = Table( - ("x"), // First tuple defines column names - (42), // Subsequent tuples define the data + ("x"), // First tuple defines column names + (42), // Subsequent tuples define the data (63), - (99)) + (99) + ) property("QueueCloneTester should return the correct result") { - forAll (xVals) { (x: Int) => - assertTesterPasses{ new QueueCloneTester(x) } + forAll(xVals) { (x: Int) => + assertTesterPasses { new QueueCloneTester(x) } } } @@ -97,13 +98,13 @@ class CloneModuleSpec extends ChiselPropSpec { } property("Clone of MultiIOModule should simulate correctly") { - forAll (xVals) { (x: Int) => - assertTesterPasses{ new QueueCloneTester(x, multiIO=true) } + forAll(xVals) { (x: Int) => + assertTesterPasses { new QueueCloneTester(x, multiIO = true) } } } property("Clones of MultiIOModules should share the same module") { - val c = ChiselStage.convert(new QueueClone(multiIO=true)) + val c = ChiselStage.convert(new QueueClone(multiIO = true)) assert(c.modules.length == 3) } @@ -116,39 +117,39 @@ class CloneModuleSpec extends ChiselPropSpec { } // ********** Checking the output of CloneModuleAsRecord ********** // Note that we overrode desiredName so that Top is named "Top" - mod.q1.io.enq.toTarget.serialize should be ("~Top|Queue>io.enq") - mod.q2_io.deq.toTarget.serialize should be ("~Top|Queue>io.deq") - mod.q1.io.enq.toAbsoluteTarget.serialize should be ("~Top|Top/q1:Queue>io.enq") - mod.q2_io.deq.toAbsoluteTarget.serialize should be ("~Top|Top/q2:Queue>io.deq") + mod.q1.io.enq.toTarget.serialize should be("~Top|Queue>io.enq") + mod.q2_io.deq.toTarget.serialize should be("~Top|Queue>io.deq") + mod.q1.io.enq.toAbsoluteTarget.serialize should be("~Top|Top/q1:Queue>io.enq") + mod.q2_io.deq.toAbsoluteTarget.serialize should be("~Top|Top/q2:Queue>io.deq") // Legacy APIs that nevertheless were tricky to get right - mod.q1.io.enq.toNamed.serialize should be ("Top.Queue.io.enq") - mod.q2_io.deq.toNamed.serialize should be ("Top.Queue.io.deq") - mod.q1.io.enq.instanceName should be ("io.enq") - mod.q2_io.deq.instanceName should be ("io.deq") - mod.q1.io.enq.pathName should be ("Top.q1.io.enq") - mod.q2_io.deq.pathName should be ("Top.q2.io.deq") - mod.q1.io.enq.parentPathName should be ("Top.q1") - mod.q2_io.deq.parentPathName should be ("Top.q2") - mod.q1.io.enq.parentModName should be ("Queue") - mod.q2_io.deq.parentModName should be ("Queue") + mod.q1.io.enq.toNamed.serialize should be("Top.Queue.io.enq") + mod.q2_io.deq.toNamed.serialize should be("Top.Queue.io.deq") + mod.q1.io.enq.instanceName should be("io.enq") + mod.q2_io.deq.instanceName should be("io.deq") + mod.q1.io.enq.pathName should be("Top.q1.io.enq") + mod.q2_io.deq.pathName should be("Top.q2.io.deq") + mod.q1.io.enq.parentPathName should be("Top.q1") + mod.q2_io.deq.parentPathName should be("Top.q2") + mod.q1.io.enq.parentModName should be("Queue") + mod.q2_io.deq.parentModName should be("Queue") // ********** Checking the wire cloned from the output of CloneModuleAsRecord ********** val wire_io = mod.q2_wire("io").asInstanceOf[QueueIO[UInt]] - mod.q2_wire.toTarget.serialize should be ("~Top|Top>q2_wire") - wire_io.enq.toTarget.serialize should be ("~Top|Top>q2_wire.io.enq") - mod.q2_wire.toAbsoluteTarget.serialize should be ("~Top|Top>q2_wire") - wire_io.enq.toAbsoluteTarget.serialize should be ("~Top|Top>q2_wire.io.enq") + mod.q2_wire.toTarget.serialize should be("~Top|Top>q2_wire") + wire_io.enq.toTarget.serialize should be("~Top|Top>q2_wire.io.enq") + mod.q2_wire.toAbsoluteTarget.serialize should be("~Top|Top>q2_wire") + wire_io.enq.toAbsoluteTarget.serialize should be("~Top|Top>q2_wire.io.enq") // Legacy APIs - mod.q2_wire.toNamed.serialize should be ("Top.Top.q2_wire") - wire_io.enq.toNamed.serialize should be ("Top.Top.q2_wire.io.enq") - mod.q2_wire.instanceName should be ("q2_wire") - wire_io.enq.instanceName should be ("q2_wire.io.enq") - mod.q2_wire.pathName should be ("Top.q2_wire") - wire_io.enq.pathName should be ("Top.q2_wire.io.enq") - mod.q2_wire.parentPathName should be ("Top") - wire_io.enq.parentPathName should be ("Top") - mod.q2_wire.parentModName should be ("Top") - wire_io.enq.parentModName should be ("Top") + mod.q2_wire.toNamed.serialize should be("Top.Top.q2_wire") + wire_io.enq.toNamed.serialize should be("Top.Top.q2_wire.io.enq") + mod.q2_wire.instanceName should be("q2_wire") + wire_io.enq.instanceName should be("q2_wire.io.enq") + mod.q2_wire.pathName should be("Top.q2_wire") + wire_io.enq.pathName should be("Top.q2_wire.io.enq") + mod.q2_wire.parentPathName should be("Top") + wire_io.enq.parentPathName should be("Top") + mod.q2_wire.parentModName should be("Top") + wire_io.enq.parentModName should be("Top") } } diff --git a/src/test/scala/chiselTests/CompatibilityInteroperabilitySpec.scala b/src/test/scala/chiselTests/CompatibilityInteroperabilitySpec.scala index 4b03dfa5..8210b120 100644 --- a/src/test/scala/chiselTests/CompatibilityInteroperabilitySpec.scala +++ b/src/test/scala/chiselTests/CompatibilityInteroperabilitySpec.scala @@ -114,7 +114,6 @@ class CompatibiltyInteroperabilitySpec extends ChiselFlatSpec { }) } - "Bundles defined in Chisel._" should "work in chisel3._ Modules" in { import chisel3._ import chisel3.testers.BasicTester @@ -153,9 +152,8 @@ class CompatibiltyInteroperabilitySpec extends ChiselFlatSpec { }) } - "Similar Bundles defined in the chisel3._ and Chisel._" should - "successfully bulk connect in chisel3._" in { + "successfully bulk connect in chisel3._" in { import chisel3._ import chisel3.testers.BasicTester import Chisel3Components._ @@ -227,12 +225,11 @@ class CompatibiltyInteroperabilitySpec extends ChiselFlatSpec { val cond = Bool(INPUT) val out = UInt(OUTPUT, width = 32) } - val children = Seq(Module(new PassthroughModule), - Module(new PassthroughMultiIOModule), - Module(new PassthroughRawModule)) + val children = + Seq(Module(new PassthroughModule), Module(new PassthroughMultiIOModule), Module(new PassthroughRawModule)) io.out := children.map(_.io.out).reduce(_ + _) children.foreach { child => - when (io.cond) { + when(io.cond) { child.io.in := io.in } } @@ -355,4 +352,3 @@ class CompatibiltyInteroperabilitySpec extends ChiselFlatSpec { compile(new Top(false)) } } - diff --git a/src/test/scala/chiselTests/CompatibilitySpec.scala b/src/test/scala/chiselTests/CompatibilitySpec.scala index 7ac67b7c..d134c380 100644 --- a/src/test/scala/chiselTests/CompatibilitySpec.scala +++ b/src/test/scala/chiselTests/CompatibilitySpec.scala @@ -23,7 +23,7 @@ object CompatibilityCustomCompileOptions { class CompatibiltySpec extends ChiselFlatSpec with ScalaCheckDrivenPropertyChecks with Utils { import Chisel._ - behavior of "Chisel compatibility layer" + behavior.of("Chisel compatibility layer") it should "accept direction arguments" in { ChiselStage.elaborate(new Module { @@ -39,10 +39,10 @@ class CompatibiltySpec extends ChiselFlatSpec with ScalaCheckDrivenPropertyCheck val b = Bool(directionArgument) val u = UInt(directionArgument, width) } - io.b shouldBe a [Bool] + io.b shouldBe a[Bool] io.b.getWidth shouldEqual 1 io.b.dir shouldEqual (expectedDirection) - io.u shouldBe a [UInt] + io.u shouldBe a[UInt] io.u.getWidth shouldEqual width io.u.dir shouldEqual (expectedDirection) }) @@ -52,7 +52,7 @@ class CompatibiltySpec extends ChiselFlatSpec with ScalaCheckDrivenPropertyCheck // Choose a random value val value: Int = Gen.choose(0, Int.MaxValue).sample.get val l = UInt(value) - l shouldBe a [UInt] + l shouldBe a[UInt] l shouldBe 'lit l.getWidth shouldEqual BigInt(value).bitLength l.litValue() shouldEqual value @@ -60,9 +60,10 @@ class CompatibiltySpec extends ChiselFlatSpec with ScalaCheckDrivenPropertyCheck it should "map utility objects into the package object" in { val value: Int = Gen.choose(2, 2048).sample.get - log2Up(value) shouldBe (1 max BigInt(value - 1).bitLength) + log2Up(value) shouldBe (1.max(BigInt(value - 1).bitLength)) log2Ceil(value) shouldBe (BigInt(value - 1).bitLength) - log2Down(value) shouldBe ((1 max BigInt(value - 1).bitLength) - (if (value > 0 && ((value & (value - 1)) == 0)) 0 else 1)) + log2Down(value) shouldBe ((1.max(BigInt(value - 1).bitLength)) - (if (value > 0 && ((value & (value - 1)) == 0)) 0 + else 1)) log2Floor(value) shouldBe (BigInt(value - 1).bitLength - (if (value > 0 && ((value & (value - 1)) == 0)) 0 else 1)) isPow2(BigInt(1) << value) shouldBe true isPow2((BigInt(1) << value) - 1) shouldBe false @@ -76,7 +77,7 @@ class CompatibiltySpec extends ChiselFlatSpec with ScalaCheckDrivenPropertyCheck bs(maskPosition) = '?' val bitPatString = bs.toString val bp = BitPat("b" + bitPatString) - bp shouldBe a [BitPat] + bp shouldBe a[BitPat] bp.getWidth shouldEqual binaryString.length } @@ -87,92 +88,92 @@ class CompatibiltySpec extends ChiselFlatSpec with ScalaCheckDrivenPropertyCheck val io = new Bundle {} val data = UInt(width = 3) val wire = Wire(data) - new ArbiterIO(data, 2) shouldBe a [ArbiterIO[UInt]] - Module(new LockingRRArbiter(data, 2, 2, None)) shouldBe a [LockingRRArbiter[UInt]] - Module(new RRArbiter(data, 2)) shouldBe a [RRArbiter[UInt]] - Module(new Arbiter(data, 2)) shouldBe a [Arbiter[UInt]] - new Counter(2) shouldBe a [Counter] - new ValidIO(data) shouldBe a [ValidIO[UInt]] - new DecoupledIO(data) shouldBe a [DecoupledIO[UInt]] - new QueueIO(data, 2) shouldBe a [QueueIO[UInt]] - Module(new Pipe(data, 2)) shouldBe a [Pipe[UInt]] - - FillInterleaved(2, wire) shouldBe a [UInt] - PopCount(wire) shouldBe a [UInt] - Fill(2, wire) shouldBe a [UInt] - Reverse(wire) shouldBe a [UInt] - Cat(wire, wire) shouldBe a [UInt] - Log2(wire) shouldBe a [UInt] + new ArbiterIO(data, 2) shouldBe a[ArbiterIO[UInt]] + Module(new LockingRRArbiter(data, 2, 2, None)) shouldBe a[LockingRRArbiter[UInt]] + Module(new RRArbiter(data, 2)) shouldBe a[RRArbiter[UInt]] + Module(new Arbiter(data, 2)) shouldBe a[Arbiter[UInt]] + new Counter(2) shouldBe a[Counter] + new ValidIO(data) shouldBe a[ValidIO[UInt]] + new DecoupledIO(data) shouldBe a[DecoupledIO[UInt]] + new QueueIO(data, 2) shouldBe a[QueueIO[UInt]] + Module(new Pipe(data, 2)) shouldBe a[Pipe[UInt]] + + FillInterleaved(2, wire) shouldBe a[UInt] + PopCount(wire) shouldBe a[UInt] + Fill(2, wire) shouldBe a[UInt] + Reverse(wire) shouldBe a[UInt] + Cat(wire, wire) shouldBe a[UInt] + Log2(wire) shouldBe a[UInt] // 'switch' and 'is' are tested below in Risc - Counter(2) shouldBe a [Counter] - DecoupledIO(wire) shouldBe a [DecoupledIO[UInt]] + Counter(2) shouldBe a[Counter] + DecoupledIO(wire) shouldBe a[DecoupledIO[UInt]] val dcd = Wire(Decoupled(data)) - dcd shouldBe a [DecoupledIO[UInt]] - Queue(dcd) shouldBe a [DecoupledIO[UInt]] - Queue(dcd, 0) shouldBe a [DecoupledIO[UInt]] - Enum(UInt(), 2) shouldBe a [List[UInt]] - ListLookup(wire, List(wire), Array((BitPat("b1"), List(wire)))) shouldBe a [List[UInt]] - Lookup(wire, wire, Seq((BitPat("b1"), wire))) shouldBe a [UInt] - Mux1H(wire, Seq(wire)) shouldBe a [UInt] - PriorityMux(Seq(Bool(false)), Seq(data)) shouldBe a [UInt] - MuxLookup(wire, wire, Seq((wire, wire))) shouldBe a [UInt] - MuxCase(wire, Seq((Bool(true), wire))) shouldBe a [UInt] - OHToUInt(wire) shouldBe a [UInt] - PriorityEncoder(wire) shouldBe a [UInt] - UIntToOH(wire) shouldBe a [UInt] - PriorityEncoderOH(wire) shouldBe a [UInt] - RegNext(wire) shouldBe a [UInt] - RegInit(wire) shouldBe a [UInt] - RegEnable(wire, Bool(true)) shouldBe a [UInt] - ShiftRegister(wire, 2) shouldBe a [UInt] - Valid(data) shouldBe a [ValidIO[UInt]] - Pipe(Wire(Valid(data)), 2) shouldBe a [ValidIO[UInt]] + dcd shouldBe a[DecoupledIO[UInt]] + Queue(dcd) shouldBe a[DecoupledIO[UInt]] + Queue(dcd, 0) shouldBe a[DecoupledIO[UInt]] + Enum(UInt(), 2) shouldBe a[List[UInt]] + ListLookup(wire, List(wire), Array((BitPat("b1"), List(wire)))) shouldBe a[List[UInt]] + Lookup(wire, wire, Seq((BitPat("b1"), wire))) shouldBe a[UInt] + Mux1H(wire, Seq(wire)) shouldBe a[UInt] + PriorityMux(Seq(Bool(false)), Seq(data)) shouldBe a[UInt] + MuxLookup(wire, wire, Seq((wire, wire))) shouldBe a[UInt] + MuxCase(wire, Seq((Bool(true), wire))) shouldBe a[UInt] + OHToUInt(wire) shouldBe a[UInt] + PriorityEncoder(wire) shouldBe a[UInt] + UIntToOH(wire) shouldBe a[UInt] + PriorityEncoderOH(wire) shouldBe a[UInt] + RegNext(wire) shouldBe a[UInt] + RegInit(wire) shouldBe a[UInt] + RegEnable(wire, Bool(true)) shouldBe a[UInt] + ShiftRegister(wire, 2) shouldBe a[UInt] + Valid(data) shouldBe a[ValidIO[UInt]] + Pipe(Wire(Valid(data)), 2) shouldBe a[ValidIO[UInt]] } ChiselStage.elaborate { new Dummy } } // Verify we can elaborate a design expressed in Chisel2 class Chisel2CompatibleRisc extends Module { val io = new Bundle { - val isWr = Bool(INPUT) + val isWr = Bool(INPUT) val wrAddr = UInt(INPUT, 8) val wrData = Bits(INPUT, 32) - val boot = Bool(INPUT) - val valid = Bool(OUTPUT) - val out = Bits(OUTPUT, 32) + val boot = Bool(INPUT) + val valid = Bool(OUTPUT) + val out = Bits(OUTPUT, 32) } val file = Mem(256, Bits(width = 32)) val code = Mem(256, Bits(width = 32)) - val pc = Reg(init=UInt(0, 8)) + val pc = Reg(init = UInt(0, 8)) val add_op :: imm_op :: Nil = Enum(2) val inst = code(pc) - val op = inst(31,24) - val rci = inst(23,16) - val rai = inst(15, 8) - val rbi = inst( 7, 0) + val op = inst(31, 24) + val rci = inst(23, 16) + val rai = inst(15, 8) + val rbi = inst(7, 0) val ra = Mux(rai === Bits(0), Bits(0), file(rai)) val rb = Mux(rbi === Bits(0), Bits(0), file(rbi)) val rc = Wire(Bits(width = 32)) io.valid := Bool(false) - io.out := Bits(0) - rc := Bits(0) + io.out := Bits(0) + rc := Bits(0) - when (io.isWr) { + when(io.isWr) { code(io.wrAddr) := io.wrData - } .elsewhen (io.boot) { + }.elsewhen(io.boot) { pc := UInt(0) - } .otherwise { + }.otherwise { switch(op) { is(add_op) { rc := ra +% rb } is(imm_op) { rc := (rai << 8) | rbi } } io.out := rc - when (rci === UInt(255)) { + when(rci === UInt(255)) { io.valid := Bool(true) - } .otherwise { + }.otherwise { file(rci) := rc } pc := pc +% UInt(1) @@ -191,7 +192,6 @@ class CompatibiltySpec extends ChiselFlatSpec with ScalaCheckDrivenPropertyCheck }) } - class SmallBundle extends Bundle { val f1 = UInt(width = 4) val f2 = UInt(width = 5) @@ -219,7 +219,7 @@ class CompatibiltySpec extends ChiselFlatSpec with ScalaCheckDrivenPropertyCheck val in = (new SmallBundle).asInput val out = (new BigBundle).asOutput } - val badReg = Reg(UInt(7, width=4)) + val badReg = Reg(UInt(7, width = 4)) } ChiselStage.elaborate { new CreateRegFromBoundTypeModule() } } @@ -302,9 +302,9 @@ class CompatibiltySpec extends ChiselFlatSpec with ScalaCheckDrivenPropertyCheck // Note: This is a regression (see https://github.com/freechipsproject/chisel3/issues/668) it should "fail for Chisel types" in { import Chisel._ - an [chisel3.ExpectedHardwareException] should be thrownBy extractCause[chisel3.ExpectedHardwareException] { + an[chisel3.ExpectedHardwareException] should be thrownBy extractCause[chisel3.ExpectedHardwareException] { ChiselStage.elaborate(new Module { - val io = new Bundle { } + val io = new Bundle {} UInt(INPUT).dir }) } @@ -342,11 +342,11 @@ class CompatibiltySpec extends ChiselFlatSpec with ScalaCheckDrivenPropertyCheck }) } - behavior of "BitPat" + behavior.of("BitPat") it should "support old operators" in { class Foo extends Module { - val io = IO(new Bundle{}) + val io = IO(new Bundle {}) info("Deprecated method DC hasn't been removed") val bp = BitPat.DC(4) @@ -355,34 +355,34 @@ class CompatibiltySpec extends ChiselFlatSpec with ScalaCheckDrivenPropertyCheck ChiselStage.elaborate(new Foo) } - behavior of "Enum" + behavior.of("Enum") it should "support apply[T <: Bits](nodeType: T, n: Int): List[T]" in { class Foo extends Module { - val io = IO(new Bundle{}) + val io = IO(new Bundle {}) info("works for a UInt") - Enum(UInt(), 4) shouldBe a [List[UInt]] + Enum(UInt(), 4) shouldBe a[List[UInt]] info("throw an exception for non-UInt types") - intercept [IllegalArgumentException] { + intercept[IllegalArgumentException] { Enum(SInt(), 4) - }.getMessage should include ("Only UInt supported for enums") + }.getMessage should include("Only UInt supported for enums") info("throw an exception if the bit width is specified") - intercept [IllegalArgumentException] { + intercept[IllegalArgumentException] { Enum(UInt(width = 8), 4) - }.getMessage should include ("Bit width may no longer be specified for enums") + }.getMessage should include("Bit width may no longer be specified for enums") } ChiselStage.elaborate(new Foo) } - behavior of "Queue" + behavior.of("Queue") it should "support deprecated constructors" in { class Foo extends Module { - val io = IO(new Bundle{}) + val io = IO(new Bundle {}) info("reset: Option[Bool] constructor works") val option = Module(new Queue(UInt(), 4, false, false, Some(Bool(true)))) @@ -394,56 +394,56 @@ class CompatibiltySpec extends ChiselFlatSpec with ScalaCheckDrivenPropertyCheck ChiselStage.elaborate(new Foo) } - behavior of "LFSR16" + behavior.of("LFSR16") it should "still exist" in { class Foo extends Module { - val io = IO(new Bundle{}) + val io = IO(new Bundle {}) info("Still exists") val lfsr = LFSR16() info("apply method returns a UInt") - lfsr shouldBe a [UInt] + lfsr shouldBe a[UInt] info("returned UInt has a width of 16") - lfsr.getWidth should be (16) + lfsr.getWidth should be(16) } ChiselStage.elaborate(new Foo) } - behavior of "Mem" + behavior.of("Mem") it should "support deprecated apply methods" in { class Foo extends Module { - val io = IO(new Bundle{}) + val io = IO(new Bundle {}) info("apply[T <: Data](t: T, size: BigInt): Mem[T] works") val memBigInt = Mem(UInt(), 8: BigInt) - memBigInt shouldBe a [Mem[UInt]] + memBigInt shouldBe a[Mem[UInt]] info("apply[T <: Data](t: T, size: Int): Mem[T] works") val memInt = Mem(SInt(), 16: Int) - memInt shouldBe a [Mem[SInt]] + memInt shouldBe a[Mem[SInt]] } ChiselStage.elaborate(new Foo) } - behavior of "SeqMem" + behavior.of("SeqMem") it should "support deprecated apply methods" in { class Foo extends Module { - val io = IO(new Bundle{}) + val io = IO(new Bundle {}) info("apply[T <: Data](t: T, size: BigInt): SeqMem[T] works") val seqMemBigInt = SeqMem(UInt(), 8: BigInt) - seqMemBigInt shouldBe a [SeqMem[UInt]] + seqMemBigInt shouldBe a[SeqMem[UInt]] info("apply[T <: Data](t: T, size: Int): SeqMem[T] works") val seqMemInt = SeqMem(UInt(), 16: Int) - seqMemInt shouldBe a [SeqMem[UInt]] + seqMemInt shouldBe a[SeqMem[UInt]] } ChiselStage.elaborate(new Foo) @@ -461,11 +461,11 @@ class CompatibiltySpec extends ChiselFlatSpec with ScalaCheckDrivenPropertyCheck ChiselStage.elaborate((new Foo)) } - behavior of "debug" + behavior.of("debug") it should "still exist" in { class Foo extends Module { - val io = IO(new Bundle{}) + val io = IO(new Bundle {}) val data = UInt(width = 2) debug(data) @@ -474,35 +474,35 @@ class CompatibiltySpec extends ChiselFlatSpec with ScalaCheckDrivenPropertyCheck ChiselStage.elaborate(new Foo) } - behavior of "Data methods" + behavior.of("Data methods") - behavior of "Wire" + behavior.of("Wire") it should "support legacy methods" in { class Foo extends Module { - val io = IO(new Bundle{}) + val io = IO(new Bundle {}) info("apply[T <: Data](dummy: Int = 0, init: T): T works") - val first = Wire(init=UInt("hdeadbeef")) - first shouldBe a [UInt] + val first = Wire(init = UInt("hdeadbeef")) + first shouldBe a[UInt] info("apply[T <: Data](t: T, init: T): T works") val second = Wire(SInt(), SInt(-100)) - second shouldBe a [SInt] + second shouldBe a[SInt] info("apply[T <: Data](t: T, init: DontCare.type): T works") val third = Wire(UInt(), chisel3.DontCare) - third shouldBe a [UInt] + third shouldBe a[UInt] } ChiselStage.elaborate(new Foo) } - behavior of "Vec" + behavior.of("Vec") it should "support legacy methods" in { class Foo extends BasicTester { - val seq = Seq(Wire(UInt(0, width=4)), Wire(UInt(1, width=4)), Wire(UInt(2, width=4))) + val seq = Seq(Wire(UInt(0, width = 4)), Wire(UInt(1, width = 4)), Wire(UInt(2, width = 4))) val vec = Vec(seq) info("read works") @@ -513,32 +513,32 @@ class CompatibiltySpec extends ChiselFlatSpec with ScalaCheckDrivenPropertyCheck chisel3.assert(vec.read(UInt(1)) === UInt(3)) val (_, done) = Counter(Bool(true), 4) - when (done) { stop } + when(done) { stop } } assertTesterPasses(new Foo) } - behavior of "Bits methods" + behavior.of("Bits methods") it should "support legacy methods" in { class Foo extends Module { - val io = new Bundle{} + val io = new Bundle {} val u = UInt(8) val s = SInt(-4) info("asBits works") - s.asBits shouldBe a [Bits] + s.asBits shouldBe a[Bits] info("toSInt works") - u.toSInt shouldBe a [SInt] + u.toSInt shouldBe a[SInt] info("toUInt works") - s.toUInt shouldBe a [UInt] + s.toUInt shouldBe a[UInt] info("toBools works") - s.toBools shouldBe a [Seq[Bool]] + s.toBools shouldBe a[Seq[Bool]] } ChiselStage.elaborate(new Foo) @@ -547,8 +547,8 @@ class CompatibiltySpec extends ChiselFlatSpec with ScalaCheckDrivenPropertyCheck it should "properly propagate custom compileOptions in Chisel.Module" in { import CompatibilityCustomCompileOptions._ var result: Foo = null - ChiselStage.elaborate({result = new Foo; result}) - result.compileOptions should be theSameInstanceAs (customCompileOptions) + ChiselStage.elaborate({ result = new Foo; result }) + (result.compileOptions should be).theSameInstanceAs(customCompileOptions) } it should "properly set the refs of Records" in { @@ -564,7 +564,7 @@ class CompatibiltySpec extends ChiselFlatSpec with ScalaCheckDrivenPropertyCheck } val verilog = ChiselStage.emitVerilog(new Foo) // Check that the names are correct (and that the FIRRTL is valid) - verilog should include ("assign io_out_0 = io_in_0;") + verilog should include("assign io_out_0 = io_in_0;") } it should "ignore .suggestName on field io" in { @@ -577,8 +577,8 @@ class CompatibiltySpec extends ChiselFlatSpec with ScalaCheckDrivenPropertyCheck io.bar := io.foo } val verilog = ChiselStage.emitVerilog(new MyModule) - verilog should include ("input [7:0] io_foo") - verilog should include ("output [7:0] io_bar") + verilog should include("input [7:0] io_foo") + verilog should include("output [7:0] io_bar") } it should "properly name field io" in { @@ -591,8 +591,8 @@ class CompatibiltySpec extends ChiselFlatSpec with ScalaCheckDrivenPropertyCheck io.bar := wire } val verilog = ChiselStage.emitVerilog(new MyModule) - verilog should include ("input [7:0] io_foo") - verilog should include ("output [7:0] io_bar") + verilog should include("input [7:0] io_foo") + verilog should include("output [7:0] io_bar") } } diff --git a/src/test/scala/chiselTests/CompileOptionsTest.scala b/src/test/scala/chiselTests/CompileOptionsTest.scala index 1ecf97f0..3ec59954 100644 --- a/src/test/scala/chiselTests/CompileOptionsTest.scala +++ b/src/test/scala/chiselTests/CompileOptionsTest.scala @@ -20,7 +20,7 @@ class CompileOptionsSpec extends ChiselFlatSpec with Utils { } "A Module with missing bundle fields when compiled with implicit Strict.CompileOption " should "throw an exception" in { - a [ChiselException] should be thrownBy extractCause[ChiselException] { + a[ChiselException] should be thrownBy extractCause[ChiselException] { import chisel3.ExplicitCompileOptions.Strict class ConnectFieldMismatchModule extends Module { @@ -48,7 +48,7 @@ class CompileOptionsSpec extends ChiselFlatSpec with Utils { } "A Module in which a Reg is created with a bound type when compiled with implicit Strict.CompileOption " should "throw an exception" in { - a [BindingException] should be thrownBy extractCause[BindingException] { + a[BindingException] should be thrownBy extractCause[BindingException] { import chisel3.ExplicitCompileOptions.Strict class CreateRegFromBoundTypeModule extends Module { @@ -89,7 +89,7 @@ class CompileOptionsSpec extends ChiselFlatSpec with Utils { } "A Module with unwrapped IO when compiled with implicit Strict.CompileOption " should "throw an exception" in { - a [BindingException] should be thrownBy extractCause[BindingException] { + a[BindingException] should be thrownBy extractCause[BindingException] { import chisel3.ExplicitCompileOptions.Strict class RequireIOWrapModule extends Module { @@ -106,7 +106,7 @@ class CompileOptionsSpec extends ChiselFlatSpec with Utils { } "A Module connecting output as source to input as sink when compiled with implicit Strict.CompileOption " should "throw an exception" in { - a [ChiselException] should be thrownBy extractCause[ChiselException] { + a[ChiselException] should be thrownBy extractCause[ChiselException] { import chisel3.ExplicitCompileOptions.Strict class SimpleModule extends Module { @@ -140,7 +140,7 @@ class CompileOptionsSpec extends ChiselFlatSpec with Utils { } "A Module with directionless connections when compiled with implicit Strict.CompileOption " should "throw an exception" in { - a [ChiselException] should be thrownBy extractCause[ChiselException] { + a[ChiselException] should be thrownBy extractCause[ChiselException] { // Verify we can suppress the inclusion of default compileOptions import Chisel.{defaultCompileOptions => _} import chisel3.ExplicitCompileOptions.Strict diff --git a/src/test/scala/chiselTests/ComplexAssign.scala b/src/test/scala/chiselTests/ComplexAssign.scala index 222b6373..99313967 100644 --- a/src/test/scala/chiselTests/ComplexAssign.scala +++ b/src/test/scala/chiselTests/ComplexAssign.scala @@ -11,16 +11,16 @@ class Complex[T <: Data](val re: T, val im: T) extends Bundle class ComplexAssign(w: Int) extends Module { val io = IO(new Bundle { - val e = Input(Bool()) - val in = Input(new Complex(UInt(w.W), UInt(w.W))) + val e = Input(Bool()) + val in = Input(new Complex(UInt(w.W), UInt(w.W))) val out = Output(new Complex(UInt(w.W), UInt(w.W))) }) - when (io.e) { + when(io.e) { val tmp = Wire(new Complex(UInt(w.W), UInt(w.W))) tmp := io.in io.out.re := tmp.re io.out.im := tmp.im - } .otherwise { + }.otherwise { io.out.re := 0.U io.out.im := 0.U } @@ -46,7 +46,7 @@ class ComplexAssignSpec extends ChiselPropSpec { implicit val noShrinkListVal = Shrink[List[Boolean]](_ => Stream.empty) implicit val noShrinkInt = Shrink[Int](_ => Stream.empty) forAll(enSequence(2), safeUInts, safeUInts) { (en: List[Boolean], re: Int, im: Int) => - assertTesterPasses{ new ComplexAssignTester(en, re, im) } + assertTesterPasses { new ComplexAssignTester(en, re, im) } } } } diff --git a/src/test/scala/chiselTests/ConnectSpec.scala b/src/test/scala/chiselTests/ConnectSpec.scala index f9ef5946..3a2b6d93 100644 --- a/src/test/scala/chiselTests/ConnectSpec.scala +++ b/src/test/scala/chiselTests/ConnectSpec.scala @@ -10,7 +10,7 @@ import chisel3.stage.ChiselStage import chisel3.testers.BasicTester abstract class CrossCheck extends Bundle { - val in: Data + val in: Data val out: Data } @@ -41,92 +41,120 @@ class CrossConnectTester(inType: Data, outType: Data) extends BasicTester { class ConnectSpec extends ChiselPropSpec with Utils { property("SInt := SInt should succeed") { - assertTesterPasses{ new CrossConnectTester(SInt(16.W), SInt(16.W)) } + assertTesterPasses { new CrossConnectTester(SInt(16.W), SInt(16.W)) } } property("SInt := UInt should fail") { - intercept[ChiselException]{ + intercept[ChiselException] { extractCause[ChiselException] { - ChiselStage.elaborate { new CrossConnectTester(UInt(16.W), SInt(16.W)) } } } + ChiselStage.elaborate { new CrossConnectTester(UInt(16.W), SInt(16.W)) } + } + } } property("SInt := FixedPoint should fail") { - intercept[ChiselException]{ + intercept[ChiselException] { extractCause[ChiselException] { - ChiselStage.elaborate { new CrossConnectTester(FixedPoint(16.W, 8.BP), UInt(16.W)) } } } + ChiselStage.elaborate { new CrossConnectTester(FixedPoint(16.W, 8.BP), UInt(16.W)) } + } + } } property("UInt := UInt should succeed") { - assertTesterPasses{ new CrossConnectTester(UInt(16.W), UInt(16.W)) } + assertTesterPasses { new CrossConnectTester(UInt(16.W), UInt(16.W)) } } property("UInt := SInt should fail") { - intercept[ChiselException]{ + intercept[ChiselException] { extractCause[ChiselException] { - ChiselStage.elaborate { new CrossConnectTester(SInt(16.W), UInt(16.W)) } } } + ChiselStage.elaborate { new CrossConnectTester(SInt(16.W), UInt(16.W)) } + } + } } property("UInt := FixedPoint should fail") { - intercept[ChiselException]{ + intercept[ChiselException] { extractCause[ChiselException] { - ChiselStage.elaborate { new CrossConnectTester(FixedPoint(16.W, 8.BP), UInt(16.W)) } } } + ChiselStage.elaborate { new CrossConnectTester(FixedPoint(16.W, 8.BP), UInt(16.W)) } + } + } } property("Clock := Clock should succeed") { - assertTesterPasses{ new CrossConnectTester(Clock(), Clock()) } + assertTesterPasses { new CrossConnectTester(Clock(), Clock()) } } property("Clock := UInt should fail") { - intercept[ChiselException]{ + intercept[ChiselException] { extractCause[ChiselException] { - ChiselStage.elaborate { new CrossConnectTester(Clock(), UInt(16.W)) } } } + ChiselStage.elaborate { new CrossConnectTester(Clock(), UInt(16.W)) } + } + } } property("FixedPoint := FixedPoint should succeed") { - assertTesterPasses{ new CrossConnectTester(FixedPoint(16.W, 8.BP), FixedPoint(16.W, 8.BP)) } + assertTesterPasses { new CrossConnectTester(FixedPoint(16.W, 8.BP), FixedPoint(16.W, 8.BP)) } } property("FixedPoint := SInt should fail") { - intercept[ChiselException]{ + intercept[ChiselException] { extractCause[ChiselException] { - ChiselStage.elaborate { new CrossConnectTester(SInt(16.W), FixedPoint(16.W, 8.BP)) } } } + ChiselStage.elaborate { new CrossConnectTester(SInt(16.W), FixedPoint(16.W, 8.BP)) } + } + } } property("FixedPoint := UInt should fail") { - intercept[ChiselException]{ + intercept[ChiselException] { extractCause[ChiselException] { - ChiselStage.elaborate { new CrossConnectTester(UInt(16.W), FixedPoint(16.W, 8.BP)) } } } + ChiselStage.elaborate { new CrossConnectTester(UInt(16.W), FixedPoint(16.W, 8.BP)) } + } + } } property("Analog := Analog should fail") { - intercept[ChiselException]{ + intercept[ChiselException] { extractCause[ChiselException] { - ChiselStage.elaborate { new CrossConnectTester(Analog(16.W), Analog(16.W)) } } } + ChiselStage.elaborate { new CrossConnectTester(Analog(16.W), Analog(16.W)) } + } + } } property("Analog := FixedPoint should fail") { - intercept[ChiselException]{ + intercept[ChiselException] { extractCause[ChiselException] { - ChiselStage.elaborate { new CrossConnectTester(Analog(16.W), FixedPoint(16.W, 8.BP)) } } } + ChiselStage.elaborate { new CrossConnectTester(Analog(16.W), FixedPoint(16.W, 8.BP)) } + } + } } property("FixedPoint := Analog should fail") { - intercept[ChiselException]{ + intercept[ChiselException] { extractCause[ChiselException] { - ChiselStage.elaborate { new CrossConnectTester(FixedPoint(16.W, 8.BP), Analog(16.W)) } } } + ChiselStage.elaborate { new CrossConnectTester(FixedPoint(16.W, 8.BP), Analog(16.W)) } + } + } } property("Analog := UInt should fail") { - intercept[ChiselException]{ + intercept[ChiselException] { extractCause[ChiselException] { - ChiselStage.elaborate { new CrossConnectTester(Analog(16.W), UInt(16.W)) } } } + ChiselStage.elaborate { new CrossConnectTester(Analog(16.W), UInt(16.W)) } + } + } } property("Analog := SInt should fail") { - intercept[ChiselException]{ + intercept[ChiselException] { extractCause[ChiselException] { - ChiselStage.elaborate { new CrossConnectTester(Analog(16.W), SInt(16.W)) } } } + ChiselStage.elaborate { new CrossConnectTester(Analog(16.W), SInt(16.W)) } + } + } } property("UInt := Analog should fail") { - intercept[ChiselException]{ + intercept[ChiselException] { extractCause[ChiselException] { - ChiselStage.elaborate { new CrossConnectTester(UInt(16.W), Analog(16.W)) } } } + ChiselStage.elaborate { new CrossConnectTester(UInt(16.W), Analog(16.W)) } + } + } } property("SInt := Analog should fail") { - intercept[ChiselException]{ + intercept[ChiselException] { extractCause[ChiselException] { - ChiselStage.elaborate { new CrossConnectTester(SInt(16.W), Analog(16.W)) } } } + ChiselStage.elaborate { new CrossConnectTester(SInt(16.W), Analog(16.W)) } + } + } } property("Pipe internal connections should succeed") { - ChiselStage.elaborate( new PipeInternalWires) + ChiselStage.elaborate(new PipeInternalWires) } property("Connect error messages should have meaningful information") { @@ -139,9 +167,9 @@ class ConnectSpec extends ChiselPropSpec with Utils { inner.myReg := false.B // ERROR } - val assignError = the [ChiselException] thrownBy {ChiselStage.elaborate { new OuterAssignExample}} + val assignError = the[ChiselException] thrownBy { ChiselStage.elaborate { new OuterAssignExample } } val expectedAssignError = """.*@: myReg in InnerExample cannot be written from module OuterAssignExample.""" - assignError.getMessage should fullyMatch regex expectedAssignError + (assignError.getMessage should fullyMatch).regex(expectedAssignError) class OuterReadExample extends Module { val myReg = RegInit(0.U(8.W)) @@ -149,16 +177,20 @@ class ConnectSpec extends ChiselPropSpec with Utils { myReg := inner.myReg // ERROR } - val readError = the [ChiselException] thrownBy {ChiselStage.elaborate { new OuterReadExample }} + val readError = the[ChiselException] thrownBy { ChiselStage.elaborate { new OuterReadExample } } val expectedReadError = """.*@: myReg in InnerExample cannot be read from module OuterReadExample.""" - readError.getMessage should fullyMatch regex expectedReadError - - val typeMismatchError = the [ChiselException] thrownBy {ChiselStage.elaborate { new RawModule { - val myUInt = Wire(UInt(4.W)) - val mySInt = Wire(SInt(4.W)) - myUInt := mySInt - }}} + (readError.getMessage should fullyMatch).regex(expectedReadError) + + val typeMismatchError = the[ChiselException] thrownBy { + ChiselStage.elaborate { + new RawModule { + val myUInt = Wire(UInt(4.W)) + val mySInt = Wire(SInt(4.W)) + myUInt := mySInt + } + } + } val expectedTypeMismatchError = """.*@: Sink \(UInt<4>\) and Source \(SInt<4>\) have different types.""" - typeMismatchError.getMessage should fullyMatch regex expectedTypeMismatchError + (typeMismatchError.getMessage should fullyMatch).regex(expectedTypeMismatchError) } } diff --git a/src/test/scala/chiselTests/Counter.scala b/src/test/scala/chiselTests/Counter.scala index 121d481a..0e2a339a 100644 --- a/src/test/scala/chiselTests/Counter.scala +++ b/src/test/scala/chiselTests/Counter.scala @@ -34,7 +34,7 @@ class ResetTester(n: Int) extends BasicTester { val wasReset = RegNext(triggerReset) val (value, _) = Counter(0 until 8, reset = triggerReset) - triggerReset := value === (n-1).U + triggerReset := value === (n - 1).U when(wasReset) { assert(value === 0.U) @@ -71,20 +71,20 @@ class CounterSpec extends ChiselPropSpec { } property("Counter can be en/disabled") { - forAll(safeUInts) { (seed: Int) => whenever(seed >= 0) { assertTesterPasses{ new EnableTester(seed) } } } + forAll(safeUInts) { (seed: Int) => whenever(seed >= 0) { assertTesterPasses { new EnableTester(seed) } } } } property("Counter can be reset") { - forAll(smallPosInts) { (seed: Int) => assertTesterPasses{ new ResetTester(seed) } } + forAll(smallPosInts) { (seed: Int) => assertTesterPasses { new ResetTester(seed) } } } property("Counter should wrap") { - forAll(smallPosInts) { (max: Int) => assertTesterPasses{ new WrapTester(max) } } + forAll(smallPosInts) { (max: Int) => assertTesterPasses { new WrapTester(max) } } } property("Counter should handle a range") { forAll(posRange) { (r: Range) => - assertTesterPasses{ new RangeTester(r) } + assertTesterPasses { new RangeTester(r) } } } } diff --git a/src/test/scala/chiselTests/CustomBundle.scala b/src/test/scala/chiselTests/CustomBundle.scala index b04dcc59..ee964d2d 100644 --- a/src/test/scala/chiselTests/CustomBundle.scala +++ b/src/test/scala/chiselTests/CustomBundle.scala @@ -3,7 +3,7 @@ package chiselTests import chisel3._ -import chisel3.experimental.{DataMirror, requireIsChiselType} +import chisel3.experimental.{requireIsChiselType, DataMirror} import scala.collection.immutable.ListMap // An example of how Record might be extended @@ -11,9 +11,10 @@ import scala.collection.immutable.ListMap // it is a possible implementation of a programmatic "Bundle" // (and can by connected to MyBundle below) final class CustomBundle(elts: (String, Data)*) extends Record { - val elements = ListMap(elts map { case (field, elt) => - requireIsChiselType(elt) - field -> elt + val elements = ListMap(elts.map { + case (field, elt) => + requireIsChiselType(elt) + field -> elt }: _*) def apply(elt: String): Data = elements(elt) override def cloneType: this.type = { @@ -21,4 +22,3 @@ final class CustomBundle(elts: (String, Data)*) extends Record { (new CustomBundle(cloned: _*)).asInstanceOf[this.type] } } - diff --git a/src/test/scala/chiselTests/DataPrint.scala b/src/test/scala/chiselTests/DataPrint.scala index 7fb790a8..091722b8 100644 --- a/src/test/scala/chiselTests/DataPrint.scala +++ b/src/test/scala/chiselTests/DataPrint.scala @@ -29,30 +29,32 @@ class DataPrintSpec extends ChiselFlatSpec with Matchers { } "Data types" should "have a meaningful string representation" in { - ChiselStage.elaborate { new RawModule { - UInt().toString should be ("UInt") - UInt(8.W).toString should be ("UInt<8>") - SInt(15.W).toString should be ("SInt<15>") - Bool().toString should be ("Bool") - Clock().toString should be ("Clock") - FixedPoint(5.W, 3.BP).toString should be ("FixedPoint<5><<3>>") - Vec(3, UInt(2.W)).toString should be ("UInt<2>[3]") - EnumTest.Type().toString should be ("EnumTest") - (new BundleTest).toString should be ("BundleTest") - new Bundle { val a = UInt(8.W) }.toString should be ("AnonymousBundle") - new Bundle { val a = UInt(8.W) }.a.toString should be ("UInt<8>") - }} + ChiselStage.elaborate { + new RawModule { + UInt().toString should be("UInt") + UInt(8.W).toString should be("UInt<8>") + SInt(15.W).toString should be("SInt<15>") + Bool().toString should be("Bool") + Clock().toString should be("Clock") + FixedPoint(5.W, 3.BP).toString should be("FixedPoint<5><<3>>") + Vec(3, UInt(2.W)).toString should be("UInt<2>[3]") + EnumTest.Type().toString should be("EnumTest") + (new BundleTest).toString should be("BundleTest") + new Bundle { val a = UInt(8.W) }.toString should be("AnonymousBundle") + new Bundle { val a = UInt(8.W) }.a.toString should be("UInt<8>") + } + } } - class BoundDataModule extends Module { // not in the test to avoid anon naming suffixes + class BoundDataModule extends Module { // not in the test to avoid anon naming suffixes Wire(UInt()).toString should be("BoundDataModule.?: Wire[UInt]") Reg(SInt()).toString should be("BoundDataModule.?: Reg[SInt]") - val io = IO(Output(Bool())) // needs a name so elaboration doesn't fail + val io = IO(Output(Bool())) // needs a name so elaboration doesn't fail io.toString should be("BoundDataModule.io: IO[Bool]") val m = Mem(4, UInt(2.W)) m(2).toString should be("BoundDataModule.?: MemPort[UInt<2>]") (2.U + 2.U).toString should be("BoundDataModule.?: OpResult[UInt<2>]") - Wire(Vec(3, UInt(2.W))).toString should be ("BoundDataModule.?: Wire[UInt<2>[3]]") + Wire(Vec(3, UInt(2.W))).toString should be("BoundDataModule.?: Wire[UInt<2>[3]]") class InnerModule extends Module { val io = IO(Output(new Bundle { @@ -60,8 +62,8 @@ class DataPrintSpec extends ChiselFlatSpec with Matchers { })) } val inner = Module(new InnerModule) - inner.clock.toString should be ("InnerModule.clock: IO[Clock]") - inner.io.a.toString should be ("InnerModule.io.a: IO[UInt<4>]") + inner.clock.toString should be("InnerModule.clock: IO[Clock]") + inner.io.a.toString should be("InnerModule.io.a: IO[UInt<4>]") class FooTypeTest extends Bundle { val foo = Vec(2, UInt(8.W)) @@ -69,7 +71,7 @@ class DataPrintSpec extends ChiselFlatSpec with Matchers { } val tpe = new FooTypeTest val fooio: FooTypeTest = IO(Input(tpe)) - fooio.foo(0).toString should be ("BoundDataModule.fooio.foo[0]: IO[UInt<8>]") + fooio.foo(0).toString should be("BoundDataModule.fooio.foo[0]: IO[UInt<8>]") class NestedBundle extends Bundle { val nestedFoo = UInt(8.W) @@ -81,10 +83,8 @@ class DataPrintSpec extends ChiselFlatSpec with Matchers { val nestedTpe = new NestedType val nestedio = IO(Input(nestedTpe)) - (nestedio.foo.nestedFoo.toString should be - ("BoundDataModule.nestedio.foo.nestedFoo: IO[UInt<8>]")) - (nestedio.foo.nestedFooVec(0).toString should be - ("BoundDataModule.nestedio.foo.nestedFooVec[0]: IO[UInt<8>]")) + (nestedio.foo.nestedFoo.toString should be("BoundDataModule.nestedio.foo.nestedFoo: IO[UInt<8>]")) + (nestedio.foo.nestedFooVec(0).toString should be("BoundDataModule.nestedio.foo.nestedFooVec[0]: IO[UInt<8>]")) } "Bound data types" should "have a meaningful string representation" in { @@ -92,21 +92,25 @@ class DataPrintSpec extends ChiselFlatSpec with Matchers { } "Literals" should "have a meaningful string representation" in { - ChiselStage.elaborate { new RawModule { - 3.U.toString should be ("UInt<2>(3)") - 3.U(5.W).toString should be ("UInt<5>(3)") - -1.S.toString should be ("SInt<1>(-1)") - false.B.toString should be ("Bool(false)") - true.B.toString should be ("Bool(true)") - 2.25.F(6.W, 2.BP).toString should be ("FixedPoint<6><<2>>(2.25)") - -2.25.F(6.W, 2.BP).toString should be ("FixedPoint<6><<2>>(-2.25)") - Vec(3, UInt(4.W)).toString should be ("UInt<4>[3]") - EnumTest.sNone.toString should be ("EnumTest(0=sNone)") - EnumTest.sTwo.toString should be ("EnumTest(2=sTwo)") - EnumTest(1.U).toString should be ("EnumTest(1=sOne)") - (new BundleTest).Lit(_.a -> 2.U, _.b -> false.B).toString should be ("BundleTest(a=UInt<8>(2), b=Bool(false))") - (new PartialBundleTest).Lit().toString should be ("PartialBundleTest(a=UInt<8>(DontCare), b=Bool(DontCare), c=SInt<8>(DontCare), e=FixedPoint<5><<3>>(DontCare), f=EnumTest(DontCare))") - DontCare.toString should be ("DontCare()") - } } + ChiselStage.elaborate { + new RawModule { + 3.U.toString should be("UInt<2>(3)") + 3.U(5.W).toString should be("UInt<5>(3)") + -1.S.toString should be("SInt<1>(-1)") + false.B.toString should be("Bool(false)") + true.B.toString should be("Bool(true)") + 2.25.F(6.W, 2.BP).toString should be("FixedPoint<6><<2>>(2.25)") + -2.25.F(6.W, 2.BP).toString should be("FixedPoint<6><<2>>(-2.25)") + Vec(3, UInt(4.W)).toString should be("UInt<4>[3]") + EnumTest.sNone.toString should be("EnumTest(0=sNone)") + EnumTest.sTwo.toString should be("EnumTest(2=sTwo)") + EnumTest(1.U).toString should be("EnumTest(1=sOne)") + (new BundleTest).Lit(_.a -> 2.U, _.b -> false.B).toString should be("BundleTest(a=UInt<8>(2), b=Bool(false))") + (new PartialBundleTest).Lit().toString should be( + "PartialBundleTest(a=UInt<8>(DontCare), b=Bool(DontCare), c=SInt<8>(DontCare), e=FixedPoint<5><<3>>(DontCare), f=EnumTest(DontCare))" + ) + DontCare.toString should be("DontCare()") + } + } } } diff --git a/src/test/scala/chiselTests/Decoder.scala b/src/test/scala/chiselTests/Decoder.scala index d802c6ce..0c644b49 100644 --- a/src/test/scala/chiselTests/Decoder.scala +++ b/src/test/scala/chiselTests/Decoder.scala @@ -10,10 +10,10 @@ import chisel3.util._ class Decoder(bitpats: List[String]) extends Module { val io = IO(new Bundle { - val inst = Input(UInt(32.W)) + val inst = Input(UInt(32.W)) val matched = Output(Bool()) }) - io.matched := VecInit(bitpats.map(BitPat(_) === io.inst)).reduce(_||_) + io.matched := VecInit(bitpats.map(BitPat(_) === io.inst)).reduce(_ || _) } class DecoderTester(pairs: List[(String, String)]) extends BasicTester { @@ -33,10 +33,10 @@ class DecoderTester(pairs: List[(String, String)]) extends BasicTester { class DecoderSpec extends ChiselPropSpec { // Use a single Int to make both a specific instruction and a BitPat that will match it - val bitpatPair = for(seed <- Arbitrary.arbitrary[Int]) yield { + val bitpatPair = for (seed <- Arbitrary.arbitrary[Int]) yield { val rnd = new scala.util.Random(seed) val bs = seed.toBinaryString - val bp = bs.map(if(rnd.nextBoolean) _ else "?") + val bp = bs.map(if (rnd.nextBoolean) _ else "?") // The following randomly throws in white space and underscores which are legal and ignored. val bpp = bp.map { a => @@ -49,11 +49,11 @@ class DecoderSpec extends ChiselPropSpec { ("b" + bs, "b" + bpp) } - private def nPairs(n: Int) = Gen.containerOfN[List, (String,String)](n,bitpatPair) + private def nPairs(n: Int) = Gen.containerOfN[List, (String, String)](n, bitpatPair) property("BitPat wildcards should be usable in decoding") { - forAll(nPairs(4)){ (pairs: List[(String, String)]) => - assertTesterPasses{ new DecoderTester(pairs) } + forAll(nPairs(4)) { (pairs: List[(String, String)]) => + assertTesterPasses { new DecoderTester(pairs) } } } } diff --git a/src/test/scala/chiselTests/DedupSpec.scala b/src/test/scala/chiselTests/DedupSpec.scala index 61f2995a..f2f2ed45 100644 --- a/src/test/scala/chiselTests/DedupSpec.scala +++ b/src/test/scala/chiselTests/DedupSpec.scala @@ -65,11 +65,10 @@ class SharedConstantValDedupTop extends Module { io.out := inst0.io.out + inst1.io.out } - class DedupSpec extends ChiselFlatSpec { private val ModuleRegex = """\s*module\s+(\w+)\b.*""".r def countModules(verilog: String): Int = - (verilog split "\n" collect { case ModuleRegex(name) => name }).size + (verilog.split("\n").collect { case ModuleRegex(name) => name }).size "Deduplication" should "occur" in { assert(countModules(compile { new DedupQueues(4) }) === 2) @@ -80,7 +79,6 @@ class DedupSpec extends ChiselFlatSpec { } it should "dedup modules that share a literal" in { - assert(countModules(compile { new SharedConstantValDedupTop }) === 2) + assert(countModules(compile { new SharedConstantValDedupTop }) === 2) } } - diff --git a/src/test/scala/chiselTests/Direction.scala b/src/test/scala/chiselTests/Direction.scala index 39ff1f0e..0c657273 100644 --- a/src/test/scala/chiselTests/Direction.scala +++ b/src/test/scala/chiselTests/Direction.scala @@ -16,8 +16,8 @@ class DirectionHaver extends Module { val io = IO(new Bundle { val in = Input(UInt(32.W)) val out = Output(UInt(32.W)) - val inBundle = Input(new DirectionedBundle) // should override elements - val outBundle = Output(new DirectionedBundle) // should override elements + val inBundle = Input(new DirectionedBundle) // should override elements + val outBundle = Output(new DirectionedBundle) // should override elements }) } @@ -51,10 +51,10 @@ class DirectionSpec extends ChiselPropSpec with Matchers with Utils { property("Inputs should not be assignable") { a[Exception] should be thrownBy extractCause[Exception] { - ChiselStage.elaborate(new BadDirection) + ChiselStage.elaborate(new BadDirection) } a[Exception] should be thrownBy extractCause[Exception] { - ChiselStage.elaborate(new BadSubDirection) + ChiselStage.elaborate(new BadSubDirection) } } @@ -84,7 +84,7 @@ class DirectionSpec extends ChiselPropSpec with Matchers with Utils { } property("Empty Vecs with no direction on the sample_element *should* cause direction errors") { - an [Exception] should be thrownBy extractCause[Exception] { + an[Exception] should be thrownBy extractCause[Exception] { ChiselStage.elaborate(new Module { val io = IO(new Bundle { val foo = Input(UInt(8.W)) @@ -118,7 +118,7 @@ class DirectionSpec extends ChiselPropSpec with Matchers with Utils { } property("Explicitly directioned but empty Bundles should cause direction errors") { - an [Exception] should be thrownBy extractCause[Exception] { + an[Exception] should be thrownBy extractCause[Exception] { ChiselStage.elaborate(new Module { val io = IO(new Bundle { val foo = UInt(8.W) @@ -241,18 +241,20 @@ class DirectionSpec extends ChiselPropSpec with Matchers with Utils { } val emitted: String = ChiselStage.emitChirrtl(new MyModule) - val firrtl: String = ChiselStage.convert(new MyModule).serialize + val firrtl: String = ChiselStage.convert(new MyModule).serialize // Check that emitted directions are correct. - Seq(emitted, firrtl).foreach { o => { - // Chisel Emitter formats spacing a little differently than the - // FIRRTL Emitter :-( - val s = o.replace("{flip a", "{ flip a") - assert(s.contains("output regularVec : { flip a : UInt<1>, b : UInt<1>}[2]")) - assert(s.contains("input vecFlipped : { flip a : UInt<1>, b : UInt<1>}[2]")) - assert(s.contains("input flippedVec : { flip a : UInt<1>, b : UInt<1>}[2]")) - assert(s.contains("output flippedVecFlipped : { flip a : UInt<1>, b : UInt<1>}[2]")) - } } + Seq(emitted, firrtl).foreach { o => + { + // Chisel Emitter formats spacing a little differently than the + // FIRRTL Emitter :-( + val s = o.replace("{flip a", "{ flip a") + assert(s.contains("output regularVec : { flip a : UInt<1>, b : UInt<1>}[2]")) + assert(s.contains("input vecFlipped : { flip a : UInt<1>, b : UInt<1>}[2]")) + assert(s.contains("input flippedVec : { flip a : UInt<1>, b : UInt<1>}[2]")) + assert(s.contains("output flippedVecFlipped : { flip a : UInt<1>, b : UInt<1>}[2]")) + } + } } property("Vec with Input/Output should calculate directions properly") { @@ -308,19 +310,21 @@ class DirectionSpec extends ChiselPropSpec with Matchers with Utils { } val emitted: String = ChiselStage.emitChirrtl(new MyModule) - val firrtl: String = ChiselStage.convert(new MyModule).serialize + val firrtl: String = ChiselStage.convert(new MyModule).serialize // Check that emitted directions are correct. - Seq(emitted, firrtl).foreach { o => { - // Chisel Emitter formats spacing a little differently than the - // FIRRTL Emitter :-( - val s = o.replace("{a", "{ a") - assert(s.contains("input inputVec : { a : UInt<1>, b : UInt<1>}[2]")) - assert(s.contains("input vecInput : { a : UInt<1>, b : UInt<1>}[2]")) - assert(s.contains("input vecInputFlipped : { a : UInt<1>, b : UInt<1>}[2]")) - assert(s.contains("output outputVec : { a : UInt<1>, b : UInt<1>}[2]")) - assert(s.contains("output vecOutput : { a : UInt<1>, b : UInt<1>}[2]")) - assert(s.contains("output vecOutputFlipped : { a : UInt<1>, b : UInt<1>}[2]")) - } } + Seq(emitted, firrtl).foreach { o => + { + // Chisel Emitter formats spacing a little differently than the + // FIRRTL Emitter :-( + val s = o.replace("{a", "{ a") + assert(s.contains("input inputVec : { a : UInt<1>, b : UInt<1>}[2]")) + assert(s.contains("input vecInput : { a : UInt<1>, b : UInt<1>}[2]")) + assert(s.contains("input vecInputFlipped : { a : UInt<1>, b : UInt<1>}[2]")) + assert(s.contains("output outputVec : { a : UInt<1>, b : UInt<1>}[2]")) + assert(s.contains("output vecOutput : { a : UInt<1>, b : UInt<1>}[2]")) + assert(s.contains("output vecOutputFlipped : { a : UInt<1>, b : UInt<1>}[2]")) + } + } } } diff --git a/src/test/scala/chiselTests/DontTouchSpec.scala b/src/test/scala/chiselTests/DontTouchSpec.scala index a6e4210c..4b21840e 100644 --- a/src/test/scala/chiselTests/DontTouchSpec.scala +++ b/src/test/scala/chiselTests/DontTouchSpec.scala @@ -32,7 +32,7 @@ class HasDeadCode(withDontTouch: Boolean) extends Module { } } -class DontTouchSpec extends ChiselFlatSpec with Utils{ +class DontTouchSpec extends ChiselFlatSpec with Utils { val deadSignals = List( "io_c_0", "io_c_1", @@ -41,20 +41,20 @@ class DontTouchSpec extends ChiselFlatSpec with Utils{ "Dead code" should "be removed by default" in { val verilog = compile(new HasDeadCode(false)) for (signal <- deadSignals) { - verilog should not include (signal) + (verilog should not).include(signal) } } it should "NOT be removed if marked dontTouch" in { val verilog = compile(new HasDeadCode(true)) for (signal <- deadSignals) { - verilog should include (signal) + verilog should include(signal) } } "Dont touch" should "only work on bound hardware" in { - a [chisel3.BindingException] should be thrownBy extractCause[BindingException] { + a[chisel3.BindingException] should be thrownBy extractCause[BindingException] { ChiselStage.elaborate(new Module { - val io = IO(new Bundle { }) - dontTouch(new Bundle { val a = UInt(32.W) } ) + val io = IO(new Bundle {}) + dontTouch(new Bundle { val a = UInt(32.W) }) }) } } diff --git a/src/test/scala/chiselTests/EnableShiftRegister.scala b/src/test/scala/chiselTests/EnableShiftRegister.scala index 34dcecb0..4d407169 100644 --- a/src/test/scala/chiselTests/EnableShiftRegister.scala +++ b/src/test/scala/chiselTests/EnableShiftRegister.scala @@ -6,9 +6,9 @@ import chisel3.stage.ChiselStage class EnableShiftRegister extends Module { val io = IO(new Bundle { - val in = Input(UInt(4.W)) + val in = Input(UInt(4.W)) val shift = Input(Bool()) - val out = Output(UInt(4.W)) + val out = Output(UInt(4.W)) }) val r0 = RegInit(0.U(4.W)) val r1 = RegInit(0.U(4.W)) @@ -41,7 +41,7 @@ class EnableShiftRegisterTester(c: EnableShiftRegister) extends Tester(c) { expect(c.io.out, reg(3)) } } -*/ + */ class EnableShiftRegisterSpec extends ChiselPropSpec { @@ -49,5 +49,5 @@ class EnableShiftRegisterSpec extends ChiselPropSpec { ChiselStage.elaborate { new EnableShiftRegister } } - ignore("EnableShiftRegisterTester should return the correct result") { } + ignore("EnableShiftRegisterTester should return the correct result") {} } diff --git a/src/test/scala/chiselTests/ExtModule.scala b/src/test/scala/chiselTests/ExtModule.scala index 161b6f5f..1dbd7447 100644 --- a/src/test/scala/chiselTests/ExtModule.scala +++ b/src/test/scala/chiselTests/ExtModule.scala @@ -61,19 +61,16 @@ class MultiExtModuleTester extends BasicTester { class ExtModuleSpec extends ChiselFlatSpec { "A ExtModule inverter" should "work" in { - assertTesterPasses({ new ExtModuleTester }, - Seq("/chisel3/BlackBoxTest.v"), TesterDriver.verilatorOnly) + assertTesterPasses({ new ExtModuleTester }, Seq("/chisel3/BlackBoxTest.v"), TesterDriver.verilatorOnly) } "Multiple ExtModules" should "work" in { - assertTesterPasses({ new MultiExtModuleTester }, - Seq("/chisel3/BlackBoxTest.v"), TesterDriver.verilatorOnly) + assertTesterPasses({ new MultiExtModuleTester }, Seq("/chisel3/BlackBoxTest.v"), TesterDriver.verilatorOnly) } "DataMirror.modulePorts" should "work with ExtModule" in { ChiselStage.elaborate(new Module { - val io = IO(new Bundle { }) + val io = IO(new Bundle {}) val m = Module(new extmoduletests.BlackBoxPassthrough) - assert(DataMirror.modulePorts(m) == Seq( - "in" -> m.in, "out" -> m.out)) + assert(DataMirror.modulePorts(m) == Seq("in" -> m.in, "out" -> m.out)) }) } } diff --git a/src/test/scala/chiselTests/ExtModuleImpl.scala b/src/test/scala/chiselTests/ExtModuleImpl.scala index c6cd4a9f..bb5c07bf 100644 --- a/src/test/scala/chiselTests/ExtModuleImpl.scala +++ b/src/test/scala/chiselTests/ExtModuleImpl.scala @@ -23,14 +23,17 @@ class ExtModuleAdd(n: Int) extends ExtModule with HasExtModuleInline { }) //scalastyle:off regex - setInline("ExtModuleAdd.v", s""" - |module ExtModuleAdd( - | input [15:0] in, - | output [15:0] out - |); - | assign out = in + $n; - |endmodule - """.stripMargin) + setInline( + "ExtModuleAdd.v", + s""" + |module ExtModuleAdd( + | input [15:0] in, + | output [15:0] out + |); + | assign out = in + $n; + |endmodule + """.stripMargin + ) } class UsesExtModuleAddViaInline extends Module { @@ -93,7 +96,7 @@ class UsesExtModuleMinusViaPath extends Module { } class ExtModuleResourceNotFound extends HasExtModuleResource { - val io = IO(new Bundle{}) + val io = IO(new Bundle {}) addResource("/missing.resource") } @@ -113,7 +116,7 @@ class ExtModuleImplSpec extends AnyFreeSpec with Matchers { ) val newAnnotations = (new ChiselStage).transform(annotations) - newAnnotations.exists(_.isInstanceOf[FirrtlCircuitAnnotation]) should be (true) + newAnnotations.exists(_.isInstanceOf[FirrtlCircuitAnnotation]) should be(true) val verilogOutput = new File(targetDir, "ExtModuleAdd.v") verilogOutput.exists() should be(true) verilogOutput.delete() @@ -127,7 +130,7 @@ class ExtModuleImplSpec extends AnyFreeSpec with Matchers { ) val newAnnotations = (new ChiselStage).transform(annotations) - newAnnotations.exists(_.isInstanceOf[FirrtlCircuitAnnotation]) should be (true) + newAnnotations.exists(_.isInstanceOf[FirrtlCircuitAnnotation]) should be(true) val verilogOutput = new File(targetDir, "BlackBoxTest.v") verilogOutput.exists() should be(true) verilogOutput.delete() @@ -141,14 +144,14 @@ class ExtModuleImplSpec extends AnyFreeSpec with Matchers { ) val newAnnotations = (new ChiselStage).transform(annotations) - newAnnotations.exists(_.isInstanceOf[FirrtlCircuitAnnotation]) should be (true) + newAnnotations.exists(_.isInstanceOf[FirrtlCircuitAnnotation]) should be(true) val verilogOutput = new File(targetDir, "BlackBoxTest.v") verilogOutput.exists() should be(true) verilogOutput.delete() } "Resource files that do not exist produce Chisel errors" in { - assertThrows[BlackBoxNotFoundException]{ + assertThrows[BlackBoxNotFoundException] { ChiselStage.emitChirrtl(new UsesMissingExtModuleResource) } } diff --git a/src/test/scala/chiselTests/FixedPointSpec.scala b/src/test/scala/chiselTests/FixedPointSpec.scala index 2530bb13..aedd195e 100644 --- a/src/test/scala/chiselTests/FixedPointSpec.scala +++ b/src/test/scala/chiselTests/FixedPointSpec.scala @@ -12,7 +12,7 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class FixedPointLiteralSpec extends AnyFlatSpec with Matchers { - behavior of "fixed point utilities" + behavior.of("fixed point utilities") they should "allow conversion between doubles and the bigints needed to represent them" in { val initialDouble = 0.125 @@ -25,11 +25,11 @@ class FixedPointLiteralSpec extends AnyFlatSpec with Matchers { they should "have their literals support to double and to BigDecimal" in { val d = -7.125 val lit1 = d.F(3.BP) - lit1.litToDouble should be (d) + lit1.litToDouble should be(d) val d2 = BigDecimal("1232123213131123.125") val lit2 = d2.F(3.BP) - lit2.litToBigDecimal should be (d2) + lit2.litToBigDecimal should be(d2) // Numbers that are too big will throw exception intercept[ChiselException] { @@ -43,33 +43,33 @@ class FixedPointFromBitsTester extends BasicTester { val uint = 3.U(4.W) val sint = (-3).S - val fp = FixedPoint.fromDouble(3.0, 4.W, 0.BP) + val fp = FixedPoint.fromDouble(3.0, 4.W, 0.BP) val fp_tpe = FixedPoint(4.W, 1.BP) val uint_result = FixedPoint.fromDouble(1.5, 4.W, 1.BP) val sint_result = FixedPoint.fromDouble(-1.5, 4.W, 1.BP) - val fp_result = FixedPoint.fromDouble(1.5, 4.W, 1.BP) + val fp_result = FixedPoint.fromDouble(1.5, 4.W, 1.BP) val uint2fp = uint.asTypeOf(fp_tpe) val sint2fp = sint.asTypeOf(fp_tpe) - val fp2fp = fp.asTypeOf(fp_tpe) + val fp2fp = fp.asTypeOf(fp_tpe) val uintToFp = uint.asFixedPoint(1.BP) val sintToFp = sint.asFixedPoint(1.BP) - val fpToFp = fp.asFixedPoint(1.BP) + val fpToFp = fp.asFixedPoint(1.BP) val negativefp = (-3.5).F(4.BP) val positivefp = 3.5.F(4.BP) - assert(- positivefp === negativefp) + assert(-positivefp === negativefp) assert(positivefp === -negativefp) assert(uint2fp === uint_result) assert(sint2fp === sint_result) - assert(fp2fp === fp_result) + assert(fp2fp === fp_result) assert(uintToFp === uint_result) assert(sintToFp === sint_result) - assert(fpToFp === fp_result) + assert(fpToFp === fp_result) assert(positivefp.abs() === positivefp) assert(negativefp.abs() === positivefp) @@ -94,7 +94,6 @@ class FixedPointFromBitsTester extends BasicTester { assert(f6bp0shiftright2 === 1.0.F(0.BP)) assert(f6bp2shiftright2 === 1.5.F(2.BP)) - stop() } @@ -115,7 +114,7 @@ class FixedPointMuxTester extends BasicTester { class SBP extends Module { val io = IO(new Bundle { - val in = Input(FixedPoint(6.W, 2.BP)) + val in = Input(FixedPoint(6.W, 2.BP)) val out = Output(FixedPoint(4.W, 0.BP)) }) io.out := io.in.setBinaryPoint(0) @@ -162,7 +161,7 @@ class FixedPointSpec extends ChiselPropSpec with Utils { assertTesterPasses { new FixedPointMuxTester } } property("Negative shift amounts are invalid") { - a [ChiselException] should be thrownBy extractCause[ChiselException] { + a[ChiselException] should be thrownBy extractCause[ChiselException] { ChiselStage.elaborate(new NegativeShift(FixedPoint(1.W, 0.BP))) } } diff --git a/src/test/scala/chiselTests/GCD.scala b/src/test/scala/chiselTests/GCD.scala index 1e40c6f4..f03d4e61 100644 --- a/src/test/scala/chiselTests/GCD.scala +++ b/src/test/scala/chiselTests/GCD.scala @@ -8,17 +8,16 @@ import chisel3.testers.BasicTester class GCD extends Module { val io = IO(new Bundle { - val a = Input(UInt(32.W)) - val b = Input(UInt(32.W)) - val e = Input(Bool()) - val z = Output(UInt(32.W)) - val v = Output(Bool()) + val a = Input(UInt(32.W)) + val b = Input(UInt(32.W)) + val e = Input(Bool()) + val z = Output(UInt(32.W)) + val v = Output(Bool()) }) val x = Reg(UInt(32.W)) val y = Reg(UInt(32.W)) - when (x > y) { x := x -% y } - .otherwise { y := y -% x } - when (io.e) { x := io.a; y := io.b } + when(x > y) { x := x -% y }.otherwise { y := y -% x } + when(io.e) { x := io.a; y := io.b } io.z := x io.v := y === 0.U } @@ -39,21 +38,22 @@ class GCDTester(a: Int, b: Int, z: Int) extends BasicTester { class GCDSpec extends ChiselPropSpec { //TODO: use generators and this function to make z's - def gcd(a: Int, b: Int): Int = if(b == 0) a else gcd(b, a%b) + def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b) val gcds = Table( - ("a", "b", "z"), // First tuple defines column names - ( 64, 48, 16), // Subsequent tuples define the data - ( 12, 9, 3), - ( 48, 64, 16)) + ("a", "b", "z"), // First tuple defines column names + (64, 48, 16), // Subsequent tuples define the data + (12, 9, 3), + (48, 64, 16) + ) property("GCD should elaborate") { ChiselStage.elaborate { new GCD } } property("GCDTester should return the correct result") { - forAll (gcds) { (a: Int, b: Int, z: Int) => - assertTesterPasses{ new GCDTester(a, b, z) } + forAll(gcds) { (a: Int, b: Int, z: Int) => + assertTesterPasses { new GCDTester(a, b, z) } } } } diff --git a/src/test/scala/chiselTests/Harness.scala b/src/test/scala/chiselTests/Harness.scala index 51576566..d4330cd6 100644 --- a/src/test/scala/chiselTests/Harness.scala +++ b/src/test/scala/chiselTests/Harness.scala @@ -15,7 +15,8 @@ module ${prefix}; endmodule """, ".v") _ - def makeFailingVerilog: (File => File) = makeHarness((prefix: String) => s""" + def makeFailingVerilog: (File => File) = makeHarness( + (prefix: String) => s""" module $prefix; initial begin assert (1 == 0) else $$error("My specific, expected error message!"); @@ -23,9 +24,12 @@ module $prefix; $$finish; end endmodule -""", ".v") _ +""", + ".v" + ) _ - def makeCppHarness: (File => File) = makeHarness((prefix: String) => s""" + def makeCppHarness: (File => File) = makeHarness( + (prefix: String) => s""" #include "V$prefix.h" #include "verilated.h" @@ -44,7 +48,9 @@ void vl_finish(const char* filename, int linenum, const char* hier) { Verilated::flushCall(); exit(0); } -""", ".cpp") _ +""", + ".cpp" + ) _ /** Compiles a C++ emulator from Verilog and returns the path to the * executable and the executable filename as a tuple. @@ -77,4 +83,3 @@ void vl_finish(const char* filename, int linenum, const char* hier) { assert(!executeExpectingFailure(target, path, "A string that doesn't match any test output")) } } - diff --git a/src/test/scala/chiselTests/IOCompatibility.scala b/src/test/scala/chiselTests/IOCompatibility.scala index 61789ffa..3e01a7a5 100644 --- a/src/test/scala/chiselTests/IOCompatibility.scala +++ b/src/test/scala/chiselTests/IOCompatibility.scala @@ -8,7 +8,7 @@ import org.scalatest._ import org.scalatest.matchers.should.Matchers class IOCSimpleIO extends Bundle { - val in = Input(UInt(32.W)) + val in = Input(UInt(32.W)) val out = Output(UInt(32.W)) } @@ -19,13 +19,13 @@ class IOCPlusOne extends Module { class IOCModuleVec(val n: Int) extends Module { val io = IO(new Bundle { - val ins = Vec(n, Input(UInt(32.W))) + val ins = Vec(n, Input(UInt(32.W))) val outs = Vec(n, Output(UInt(32.W))) }) - val pluses = VecInit(Seq.fill(n){ Module(new IOCPlusOne).io }) + val pluses = VecInit(Seq.fill(n) { Module(new IOCPlusOne).io }) for (i <- 0 until n) { pluses(i).in := io.ins(i) - io.outs(i) := pluses(i).out + io.outs(i) := pluses(i).out } } @@ -46,14 +46,13 @@ class IOCompatibilitySpec extends ChiselPropSpec with Matchers with Utils { ChiselStage.elaborate { new IOCModuleWire } } - class IOUnwrapped extends Module { val io = new IOCSimpleIO io.out := io.in } property("Unwrapped IO should generate an exception") { - a [BindingException] should be thrownBy extractCause[BindingException] { + a[BindingException] should be thrownBy extractCause[BindingException] { ChiselStage.elaborate(new IOUnwrapped) } } diff --git a/src/test/scala/chiselTests/IllegalRefSpec.scala b/src/test/scala/chiselTests/IllegalRefSpec.scala index 1bafc780..219df5af 100644 --- a/src/test/scala/chiselTests/IllegalRefSpec.scala +++ b/src/test/scala/chiselTests/IllegalRefSpec.scala @@ -39,7 +39,7 @@ object IllegalRefSpec { val o = Output(Bool()) }) private var tmp: Option[Bool] = None - when (io.i) { + when(io.i) { val x = io.i & io.i tmp = Some(x) } @@ -60,13 +60,13 @@ class IllegalRefSpec extends ChiselFlatSpec with Utils { variants.foreach { case (k, v) => s"Illegal cross-module references in ${k}" should "fail" in { - a [ChiselException] should be thrownBy extractCause[ChiselException] { + a[ChiselException] should be thrownBy extractCause[ChiselException] { ChiselStage.elaborate { new IllegalRefOuter(v) } } } s"Using a signal that has escaped its enclosing when scope in ${k}" should "fail" in { - a [ChiselException] should be thrownBy extractCause[ChiselException] { + a[ChiselException] should be thrownBy extractCause[ChiselException] { ChiselStage.elaborate { new CrossWhenConnect(v) } } } diff --git a/src/test/scala/chiselTests/ImplicitConversionsSpec.scala b/src/test/scala/chiselTests/ImplicitConversionsSpec.scala index f73b23b4..4bccf636 100644 --- a/src/test/scala/chiselTests/ImplicitConversionsSpec.scala +++ b/src/test/scala/chiselTests/ImplicitConversionsSpec.scala @@ -41,7 +41,7 @@ class ImplicitConversionsSpec extends ChiselFlatSpec { } "X.B for X not in [0,1]" should "throw an exception, even outside hardware context" in { - a [ChiselException] should be thrownBy { + a[ChiselException] should be thrownBy { 65.B } } diff --git a/src/test/scala/chiselTests/InlineSpec.scala b/src/test/scala/chiselTests/InlineSpec.scala index 59a1e984..09a92e45 100644 --- a/src/test/scala/chiselTests/InlineSpec.scala +++ b/src/test/scala/chiselTests/InlineSpec.scala @@ -4,7 +4,7 @@ package chiselTests import chisel3._ import chisel3.stage.{ChiselGeneratorAnnotation, ChiselStage} -import chisel3.util.experimental.{InlineInstance, FlattenInstance} +import chisel3.util.experimental.{FlattenInstance, InlineInstance} import firrtl.passes.InlineAnnotation import firrtl.stage.{FirrtlCircuitAnnotation, FirrtlStage} import firrtl.transforms.FlattenAnnotation @@ -16,7 +16,7 @@ import org.scalatest.matchers.should.Matchers class InlineSpec extends AnyFreeSpec with ChiselRunners with Matchers { trait Internals { this: Module => - val io = IO(new Bundle{ val a = Input(Bool()) }) + val io = IO(new Bundle { val a = Input(Bool()) }) } class Sub extends Module with Internals trait HasSub { this: Module with Internals => @@ -29,9 +29,9 @@ class InlineSpec extends AnyFreeSpec with ChiselRunners with Matchers { class Baz extends Module with Internals with HasSub class Qux extends Module with Internals with HasSub - def collectInstances(c: fir.Circuit, top: Option[String] = None): Seq[String] = new InstanceGraph(c) - .fullHierarchy.values.flatten.toSeq - .map( v => (top.getOrElse(v.head.name) +: v.tail.map(_.name)).mkString(".") ) + def collectInstances(c: fir.Circuit, top: Option[String] = None): Seq[String] = + new InstanceGraph(c).fullHierarchy.values.flatten.toSeq + .map(v => (top.getOrElse(v.head.name) +: v.tail.map(_.name)).mkString(".")) val chiselStage = new ChiselStage val firrtlStage = new FirrtlStage @@ -46,17 +46,20 @@ class InlineSpec extends AnyFreeSpec with ChiselRunners with Matchers { "should compile to low FIRRTL" - { val chiselAnnotations = chiselStage - .execute(Array("--no-run-firrtl", "--target-dir", "test_run_dir"), - Seq(ChiselGeneratorAnnotation(() => new Top))) + .execute( + Array("--no-run-firrtl", "--target-dir", "test_run_dir"), + Seq(ChiselGeneratorAnnotation(() => new Top)) + ) - chiselAnnotations.collect{ case a: InlineAnnotation => a } should have length (2) + (chiselAnnotations.collect { case a: InlineAnnotation => a } should have).length(2) val instanceNames = firrtlStage .execute(Array("-X", "low"), chiselAnnotations) .collectFirst { case FirrtlCircuitAnnotation(circuit) => circuit - }.map(collectInstances(_, Some("Top"))) + } + .map(collectInstances(_, Some("Top"))) .getOrElse(fail) instanceNames should contain theSameElementsAs Set("Top", "Top.x_sub", "Top.y_sub", "Top.z", "Top.z.sub") @@ -71,17 +74,20 @@ class InlineSpec extends AnyFreeSpec with ChiselRunners with Matchers { "should compile to low FIRRTL" - { val chiselAnnotations = chiselStage - .execute(Array("--no-run-firrtl", "--target-dir", "test_run_dir"), - Seq(ChiselGeneratorAnnotation(() => new Top))) + .execute( + Array("--no-run-firrtl", "--target-dir", "test_run_dir"), + Seq(ChiselGeneratorAnnotation(() => new Top)) + ) - chiselAnnotations.collect{ case a: FlattenAnnotation => a} should have length(1) + (chiselAnnotations.collect { case a: FlattenAnnotation => a } should have).length(1) val instanceNames = firrtlStage .execute(Array("-X", "low"), chiselAnnotations) .collectFirst { case FirrtlCircuitAnnotation(circuit) => circuit - }.map(collectInstances(_, Some("Top"))) + } + .map(collectInstances(_, Some("Top"))) .getOrElse(fail) instanceNames should contain theSameElementsAs Set("Top", "Top.x") diff --git a/src/test/scala/chiselTests/InstanceNameSpec.scala b/src/test/scala/chiselTests/InstanceNameSpec.scala index 7e3186f7..7eaf3106 100644 --- a/src/test/scala/chiselTests/InstanceNameSpec.scala +++ b/src/test/scala/chiselTests/InstanceNameSpec.scala @@ -23,7 +23,7 @@ class InstanceNameModule extends Module { } class InstanceNameSpec extends ChiselFlatSpec { - behavior of "instanceName" + behavior.of("instanceName") val moduleName = "InstanceNameModule" var m: InstanceNameModule = _ ChiselStage.elaborate { m = new InstanceNameModule; m } diff --git a/src/test/scala/chiselTests/IntegerMathSpec.scala b/src/test/scala/chiselTests/IntegerMathSpec.scala index 03b2b208..166e47bd 100644 --- a/src/test/scala/chiselTests/IntegerMathSpec.scala +++ b/src/test/scala/chiselTests/IntegerMathSpec.scala @@ -27,6 +27,6 @@ class IntegerMathTester extends BasicTester { class IntegerMathSpec extends ChiselPropSpec { property("All integer ops should return the correct result") { - assertTesterPasses{ new IntegerMathTester } + assertTesterPasses { new IntegerMathTester } } } diff --git a/src/test/scala/chiselTests/IntervalRangeSpec.scala b/src/test/scala/chiselTests/IntervalRangeSpec.scala index f17f1624..777e08d6 100644 --- a/src/test/scala/chiselTests/IntervalRangeSpec.scala +++ b/src/test/scala/chiselTests/IntervalRangeSpec.scala @@ -186,7 +186,6 @@ class IntervalRangeSpec extends AnyFreeSpec with Matchers { checkRange(range"[-8,7].2", C(-8), C(7), 2.BP) checkRange(range"[-8,7].2" >> 3, C(-1), C(0.75), 2.BP) - checkRange(range"(0,7).0", O(0), O(7), 0.BP) checkRange(range"(0,7).0" >> 1, O(0), O(3), 0.BP) @@ -219,19 +218,19 @@ class IntervalRangeSpec extends AnyFreeSpec with Matchers { "get possible values should return all values from high to low" in { var range = range"[0,4]" - range.getLowestPossibleValue should be (Some(0)) - range.getHighestPossibleValue should be (Some(4)) - range.getPossibleValues should be (Seq(0, 1, 2, 3, 4)) + range.getLowestPossibleValue should be(Some(0)) + range.getHighestPossibleValue should be(Some(4)) + range.getPossibleValues should be(Seq(0, 1, 2, 3, 4)) range = range"(0,4)" - range.getLowestPossibleValue should be (Some(1)) - range.getHighestPossibleValue should be (Some(3)) - range.getPossibleValues should be (Seq(1, 2, 3)) + range.getLowestPossibleValue should be(Some(1)) + range.getHighestPossibleValue should be(Some(3)) + range.getPossibleValues should be(Seq(1, 2, 3)) range = range"(-1,4).1" - range.getLowestPossibleValue should be (Some(-0.5)) - range.getHighestPossibleValue should be (Some(3.5)) - range.getPossibleValues should be (Seq(-0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5)) + range.getLowestPossibleValue should be(Some(-0.5)) + range.getHighestPossibleValue should be(Some(3.5)) + range.getPossibleValues should be(Seq(-0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5)) } } diff --git a/src/test/scala/chiselTests/IntervalSpec.scala b/src/test/scala/chiselTests/IntervalSpec.scala index c223260d..c0338f6d 100644 --- a/src/test/scala/chiselTests/IntervalSpec.scala +++ b/src/test/scala/chiselTests/IntervalSpec.scala @@ -15,7 +15,15 @@ import firrtl.passes.CheckTypes.InvalidConnect import firrtl.passes.CheckWidths.{DisjointSqueeze, InvalidRange} import firrtl.passes.{PassExceptions, WrapWithRemainder} import firrtl.stage.{CompilerAnnotation, FirrtlCircuitAnnotation} -import firrtl.{HighFirrtlCompiler, LowFirrtlCompiler, MiddleFirrtlCompiler, MinimumVerilogCompiler, NoneCompiler, SystemVerilogCompiler, VerilogCompiler} +import firrtl.{ + HighFirrtlCompiler, + LowFirrtlCompiler, + MiddleFirrtlCompiler, + MinimumVerilogCompiler, + NoneCompiler, + SystemVerilogCompiler, + VerilogCompiler +} import org.scalatest.freespec.AnyFreeSpec import org.scalatest.matchers.should.Matchers @@ -31,16 +39,17 @@ object IntervalTestHelper { */ def makeFirrtl[T <: RawModule](compilerName: String)(gen: () => T): String = { (new ChiselStage) - .execute(Array("--compiler", compilerName, - "--target-dir", "test_run_dir/IntervalSpec"), - Seq(ChiselGeneratorAnnotation(gen))) + .execute( + Array("--compiler", compilerName, "--target-dir", "test_run_dir/IntervalSpec"), + Seq(ChiselGeneratorAnnotation(gen)) + ) .collectFirst { case FirrtlCircuitAnnotation(source) => source } match { - case Some(circuit) => circuit.serialize - case _ => - throw new Exception( - s"makeFirrtl($compilerName) failed to generate firrtl circuit" - ) - } + case Some(circuit) => circuit.serialize + case _ => + throw new Exception( + s"makeFirrtl($compilerName) failed to generate firrtl circuit" + ) + } } } @@ -174,11 +183,12 @@ class MoreIntervalShiftTester extends BasicTester { * @param endNum end here * @param incNum increment by this */ -class ClipSqueezeWrapDemo(range: IntervalRange, - targetRange: IntervalRange, - startNum: Double, - endNum: Double, - incNum: Double) +class ClipSqueezeWrapDemo( + range: IntervalRange, + targetRange: IntervalRange, + startNum: Double, + endNum: Double, + incNum: Double) extends BasicTester { val binaryPointAsInt = range.binaryPoint.asInstanceOf[KnownBinaryPoint].value @@ -214,10 +224,7 @@ class ClipSqueezeWrapDemo(range: IntervalRange, ) } -class SqueezeFunctionalityTester(range: IntervalRange, - startNum: BigDecimal, - endNum: BigDecimal, - increment: BigDecimal) +class SqueezeFunctionalityTester(range: IntervalRange, startNum: BigDecimal, endNum: BigDecimal, increment: BigDecimal) extends BasicTester { val counter = RegInit(0.U(10.W)) @@ -436,20 +443,18 @@ class IntervalSpec extends AnyFreeSpec with Matchers with ChiselRunners { "Interval literals that don't fit in explicit ranges are caught by chisel" - { "case 1: does not fit in specified width" in { intercept[ChiselException] { - ChiselGeneratorAnnotation( - () => - new BasicTester { - val x = 5.I(3.W, 0.BP) + ChiselGeneratorAnnotation(() => + new BasicTester { + val x = 5.I(3.W, 0.BP) } ).elaborate } } "case 2: doesn't fit in specified range" in { intercept[ChiselException] { - ChiselGeneratorAnnotation( - () => - new BasicTester { - val x = 5.I(range"[0,4]") + ChiselGeneratorAnnotation(() => + new BasicTester { + val x = 5.I(range"[0,4]") } ).elaborate } @@ -459,11 +464,11 @@ class IntervalSpec extends AnyFreeSpec with Matchers with ChiselRunners { "Interval literals support to double and to BigDecimal" in { val d = -7.125 val lit1 = d.I(3.BP) - lit1.litToDouble should be (d) + lit1.litToDouble should be(d) val d2 = BigDecimal("1232123213131123.125") val lit2 = d2.I(3.BP) - lit2.litToBigDecimal should be (d2) + lit2.litToBigDecimal should be(d2) // Numbers that are too big will throw exception intercept[ChiselException] { @@ -476,8 +481,8 @@ class IntervalSpec extends AnyFreeSpec with Matchers with ChiselRunners { val inputRange = range"[-6, 6].2" val in1 = (-6.0).I(inputRange) val in2 = 6.0.I(inputRange) - BigDecimal(in1.litValue()) / (1 << inputRange.binaryPoint.get) should be (-6) - BigDecimal(in2.litValue()) / (1 << inputRange.binaryPoint.get) should be (6) + BigDecimal(in1.litValue()) / (1 << inputRange.binaryPoint.get) should be(-6) + BigDecimal(in2.litValue()) / (1 << inputRange.binaryPoint.get) should be(6) intercept[ChiselException] { (-6.25).I(inputRange) } @@ -489,8 +494,8 @@ class IntervalSpec extends AnyFreeSpec with Matchers with ChiselRunners { val inputRange = range"(-6, 6).2" val in1 = (-5.75).I(inputRange) val in2 = 5.75.I(inputRange) - BigDecimal(in1.litValue()) / (1 << inputRange.binaryPoint.get) should be (-5.75) - BigDecimal(in2.litValue()) / (1 << inputRange.binaryPoint.get) should be (5.75) + BigDecimal(in1.litValue()) / (1 << inputRange.binaryPoint.get) should be(-5.75) + BigDecimal(in2.litValue()) / (1 << inputRange.binaryPoint.get) should be(5.75) intercept[ChiselException] { (-6.0).I(inputRange) } @@ -502,8 +507,8 @@ class IntervalSpec extends AnyFreeSpec with Matchers with ChiselRunners { val inputRange = range"(-6, 6).2" val in1 = (-5.95).I(inputRange) val in2 = 5.95.I(inputRange) - BigDecimal(in1.litValue()) / (1 << inputRange.binaryPoint.get) should be (-5.75) - BigDecimal(in2.litValue()) / (1 << inputRange.binaryPoint.get) should be (5.75) + BigDecimal(in1.litValue()) / (1 << inputRange.binaryPoint.get) should be(-5.75) + BigDecimal(in2.litValue()) / (1 << inputRange.binaryPoint.get) should be(5.75) intercept[ChiselException] { (-6.1).I(inputRange) } @@ -614,28 +619,26 @@ class IntervalSpec extends AnyFreeSpec with Matchers with ChiselRunners { } } - def makeCircuit(operation: String, - sourceRange: IntervalRange, - targetRange: IntervalRange): () => RawModule = { () => - new Module { - val io = IO(new Bundle { val out = Output(Interval()) }) - val base = Wire(Interval(sourceRange)) - base := 6.I + def makeCircuit(operation: String, sourceRange: IntervalRange, targetRange: IntervalRange): () => RawModule = { + () => + new Module { + val io = IO(new Bundle { val out = Output(Interval()) }) + val base = Wire(Interval(sourceRange)) + base := 6.I - val disjointLeft = WireInit(Interval(targetRange), 8.I) - val w5 = operation match { - case "clip" => base.clip(disjointLeft) - case "wrap" => base.wrap(disjointLeft) - case "squeeze" => base.squeeze(disjointLeft) + val disjointLeft = WireInit(Interval(targetRange), 8.I) + val w5 = operation match { + case "clip" => base.clip(disjointLeft) + case "wrap" => base.wrap(disjointLeft) + case "squeeze" => base.squeeze(disjointLeft) + } + io.out := w5 } - io.out := w5 - } } "disjoint ranges should error when used with clip, wrap and squeeze" - { - def mustGetException(disjointLeft: Boolean, - operation: String): Boolean = { + def mustGetException(disjointLeft: Boolean, operation: String): Boolean = { val (rangeA, rangeB) = if (disjointLeft) { (range"[-4, 6]", range"[7,10]") } else { @@ -675,57 +678,37 @@ class IntervalSpec extends AnyFreeSpec with Matchers with ChiselRunners { "Errors are sometimes inconsistent or incorrectly labelled as Firrtl Internal Error" - { "squeeze disjoint is not internal error when defined in BasicTester" in { intercept[DisjointSqueeze] { - makeFirrtl("low")( - () => - new BasicTester { - val base = Wire(Interval(range"[-4, 6]")) - val base2 = Wire(Interval(range"[-4, 6]")) - base := 6.I - base2 := 5.I - val disjointLeft = WireInit(Interval(range"[7,10]"), 8.I) - val w5 = base.squeeze(disjointLeft) - stop() + makeFirrtl("low")(() => + new BasicTester { + val base = Wire(Interval(range"[-4, 6]")) + val base2 = Wire(Interval(range"[-4, 6]")) + base := 6.I + base2 := 5.I + val disjointLeft = WireInit(Interval(range"[7,10]"), 8.I) + val w5 = base.squeeze(disjointLeft) + stop() } ) } } "wrap disjoint is not internal error when defined in BasicTester" in { intercept[DisjointSqueeze] { - makeFirrtl("low")( - () => - new BasicTester { - val base = Wire(Interval(range"[-4, 6]")) - val base2 = Wire(Interval(range"[-4, 6]")) - base := 6.I - base2 := 5.I - val disjointLeft = WireInit(Interval(range"[7,10]"), 8.I) - val w5 = base.squeeze(disjointLeft) - stop() + makeFirrtl("low")(() => + new BasicTester { + val base = Wire(Interval(range"[-4, 6]")) + val base2 = Wire(Interval(range"[-4, 6]")) + base := 6.I + base2 := 5.I + val disjointLeft = WireInit(Interval(range"[7,10]"), 8.I) + val w5 = base.squeeze(disjointLeft) + stop() } ) } } "squeeze disjoint from Module gives exception" in { intercept[DisjointSqueeze] { - makeFirrtl("low")( - () => - new Module { - val io = IO(new Bundle { - val out = Output(Interval()) - }) - val base = Wire(Interval(range"[-4, 6]")) - base := 6.I - - val disjointLeft = WireInit(Interval(range"[7,10]"), 8.I) - val w5 = base.squeeze(disjointLeft) - io.out := w5 - } - ) - } - } - "clip disjoint from Module gives no error" in { - makeFirrtl("low")( - () => + makeFirrtl("low")(() => new Module { val io = IO(new Bundle { val out = Output(Interval()) @@ -734,25 +717,40 @@ class IntervalSpec extends AnyFreeSpec with Matchers with ChiselRunners { base := 6.I val disjointLeft = WireInit(Interval(range"[7,10]"), 8.I) - val w5 = base.clip(disjointLeft) + val w5 = base.squeeze(disjointLeft) io.out := w5 + } + ) + } + } + "clip disjoint from Module gives no error" in { + makeFirrtl("low")(() => + new Module { + val io = IO(new Bundle { + val out = Output(Interval()) + }) + val base = Wire(Interval(range"[-4, 6]")) + base := 6.I + + val disjointLeft = WireInit(Interval(range"[7,10]"), 8.I) + val w5 = base.clip(disjointLeft) + io.out := w5 } ) } "wrap disjoint from Module wrap with remainder" in { intercept[WrapWithRemainder] { - makeFirrtl("low")( - () => - new Module { - val io = IO(new Bundle { - val out = Output(Interval()) - }) - val base = Wire(Interval(range"[-4, 6]")) - base := 6.I - - val disjointLeft = WireInit(Interval(range"[7,10]"), 8.I) - val w5 = base.wrap(disjointLeft) - io.out := w5 + makeFirrtl("low")(() => + new Module { + val io = IO(new Bundle { + val out = Output(Interval()) + }) + val base = Wire(Interval(range"[-4, 6]")) + base := 6.I + + val disjointLeft = WireInit(Interval(range"[7,10]"), 8.I) + val w5 = base.wrap(disjointLeft) + io.out := w5 } ) } @@ -772,26 +770,24 @@ class IntervalSpec extends AnyFreeSpec with Matchers with ChiselRunners { "Intervals should catch assignment of literals outside of range" - { "when literal is too small" in { intercept[InvalidConnect] { - makeFirrtl("low")( - () => - new Module { - val io = IO(new Bundle { val out = Output(Interval()) }) - val base = Wire(Interval(range"[-4, 6]")) - base := (-7).I - io.out := base + makeFirrtl("low")(() => + new Module { + val io = IO(new Bundle { val out = Output(Interval()) }) + val base = Wire(Interval(range"[-4, 6]")) + base := (-7).I + io.out := base } ) } } "when literal is too big" in { intercept[InvalidConnect] { - makeFirrtl("low")( - () => - new Module { - val io = IO(new Bundle { val out = Output(Interval()) }) - val base = Wire(Interval(range"[-4, 6]")) - base := 9.I - io.out := base + makeFirrtl("low")(() => + new Module { + val io = IO(new Bundle { val out = Output(Interval()) }) + val base = Wire(Interval(range"[-4, 6]")) + base := 9.I + io.out := base } ) } @@ -834,18 +830,17 @@ class IntervalSpec extends AnyFreeSpec with Matchers with ChiselRunners { assertTesterPasses { new IntervalChainedAddTester } } "Intervals should produce canonically smaller ranges via inference" in { - val loFirrtl = makeFirrtl("low")( - () => - new Module { - val io = IO(new Bundle { - val in = Input(Interval(range"[0,1]")) - val out = Output(Interval()) - }) + val loFirrtl = makeFirrtl("low")(() => + new Module { + val io = IO(new Bundle { + val in = Input(Interval(range"[0,1]")) + val out = Output(Interval()) + }) - val intervalResult = Wire(Interval()) + val intervalResult = Wire(Interval()) - intervalResult := 1.I + 1.I + 1.I + 1.I + 1.I + 1.I + 1.I - io.out := intervalResult + intervalResult := 1.I + 1.I + 1.I + 1.I + 1.I + 1.I + 1.I + io.out := intervalResult } ) loFirrtl.contains("output io_out : SInt<4>") should be(true) diff --git a/src/test/scala/chiselTests/InvalidateAPISpec.scala b/src/test/scala/chiselTests/InvalidateAPISpec.scala index 52ad02b4..2c51e5d2 100644 --- a/src/test/scala/chiselTests/InvalidateAPISpec.scala +++ b/src/test/scala/chiselTests/InvalidateAPISpec.scala @@ -16,11 +16,13 @@ class InvalidateAPISpec extends ChiselPropSpec with Matchers with BackendCompila def compileFirrtl(t: => Module): Unit = { val testDir = createTestDirectory(this.getClass.getSimpleName) - (new ChiselStage).execute(Array[String]("-td", testDir.getAbsolutePath, "--compiler", "verilog"), - Seq(ChiselGeneratorAnnotation(() => t))) + (new ChiselStage).execute( + Array[String]("-td", testDir.getAbsolutePath, "--compiler", "verilog"), + Seq(ChiselGeneratorAnnotation(() => t)) + ) } class TrivialInterface extends Bundle { - val in = Input(Bool()) + val in = Input(Bool()) val out = Output(Bool()) } @@ -42,7 +44,7 @@ class InvalidateAPISpec extends ChiselPropSpec with Matchers with BackendCompila io.out := io.in } val firrtlOutput = myGenerateFirrtl(new ModuleWithoutDontCare) - firrtlOutput should not include("is invalid") + (firrtlOutput should not).include("is invalid") } property("an output without a DontCare should emit a Firrtl \"is invalid\" with NotStrict CompileOptions") { @@ -77,7 +79,7 @@ class InvalidateAPISpec extends ChiselPropSpec with Matchers with BackendCompila } val firrtlOutput = myGenerateFirrtl(new ModuleWithoutDontCare) for (i <- 0 until nElements) - firrtlOutput should include(s"io.outs[$i] is invalid") + firrtlOutput should include(s"io.outs[$i] is invalid") } property("a Vec with a DontCare should emit a Firrtl \"is invalid\" with Strict CompileOptions and mono connect") { @@ -129,7 +131,7 @@ class InvalidateAPISpec extends ChiselPropSpec with Matchers with BackendCompila val out = Output(Bool()) }) val counter = Counter(8) - when (counter.inc()) { + when(counter.inc()) { io.out := true.B } } @@ -137,9 +139,11 @@ class InvalidateAPISpec extends ChiselPropSpec with Matchers with BackendCompila compileFirrtl(new ModuleWithIncompleteAssignment) } exception.getMessage should include("is not fully initialized") - } + } - property("FIRRTL should not complain about partial initialization with Strict CompileOptions and conditional connect after unconditional connect") { + property( + "FIRRTL should not complain about partial initialization with Strict CompileOptions and conditional connect after unconditional connect" + ) { import chisel3.ExplicitCompileOptions.Strict class ModuleWithUnconditionalAssignment extends Module { val io = IO(new Bundle { @@ -147,23 +151,25 @@ class InvalidateAPISpec extends ChiselPropSpec with Matchers with BackendCompila }) val counter = Counter(8) io.out := false.B - when (counter.inc()) { + when(counter.inc()) { io.out := true.B } } compileFirrtl(new ModuleWithUnconditionalAssignment) } - property("FIRRTL should not complain about partial initialization with Strict CompileOptions and conditional connect with otherwise clause") { + property( + "FIRRTL should not complain about partial initialization with Strict CompileOptions and conditional connect with otherwise clause" + ) { import chisel3.ExplicitCompileOptions.Strict class ModuleWithConditionalAndOtherwiseAssignment extends Module { val io = IO(new Bundle { val out = Output(Bool()) }) val counter = Counter(8) - when (counter.inc()) { + when(counter.inc()) { io.out := true.B - } otherwise { + }.otherwise { io.out := false.B } } @@ -171,7 +177,9 @@ class InvalidateAPISpec extends ChiselPropSpec with Matchers with BackendCompila compileFirrtl(new ModuleWithConditionalAndOtherwiseAssignment) } - property("an output without a DontCare should NOT emit a Firrtl \"is invalid\" with overriden NotStrict CompileOptions") { + property( + "an output without a DontCare should NOT emit a Firrtl \"is invalid\" with overriden NotStrict CompileOptions" + ) { import chisel3.ExplicitCompileOptions.NotStrict class ModuleWithoutDontCare extends Module { override val compileOptions = chisel3.ExplicitCompileOptions.NotStrict.copy(explicitInvalidate = true) @@ -179,18 +187,21 @@ class InvalidateAPISpec extends ChiselPropSpec with Matchers with BackendCompila io.out := io.in } val firrtlOutput = myGenerateFirrtl(new ModuleWithoutDontCare) - firrtlOutput should not include("is invalid") + (firrtlOutput should not).include("is invalid") } - property("an output without a DontCare should NOT emit a Firrtl \"is invalid\" with overriden NotStrict CompileOptions module definition") { + property( + "an output without a DontCare should NOT emit a Firrtl \"is invalid\" with overriden NotStrict CompileOptions module definition" + ) { import chisel3.ExplicitCompileOptions.NotStrict - abstract class ExplicitInvalidateModule extends Module()(chisel3.ExplicitCompileOptions.NotStrict.copy(explicitInvalidate = true)) + abstract class ExplicitInvalidateModule + extends Module()(chisel3.ExplicitCompileOptions.NotStrict.copy(explicitInvalidate = true)) class ModuleWithoutDontCare extends ExplicitInvalidateModule { val io = IO(new TrivialInterface) io.out := io.in } val firrtlOutput = myGenerateFirrtl(new ModuleWithoutDontCare) - firrtlOutput should not include("is invalid") + (firrtlOutput should not).include("is invalid") } property("an output without a DontCare should emit a Firrtl \"is invalid\" with overriden Strict CompileOptions") { @@ -204,9 +215,12 @@ class InvalidateAPISpec extends ChiselPropSpec with Matchers with BackendCompila firrtlOutput should include("is invalid") } - property("an output without a DontCare should emit a Firrtl \"is invalid\" with overriden Strict CompileOptions module definition") { + property( + "an output without a DontCare should emit a Firrtl \"is invalid\" with overriden Strict CompileOptions module definition" + ) { import chisel3.ExplicitCompileOptions.Strict - abstract class ImplicitInvalidateModule extends Module()(chisel3.ExplicitCompileOptions.NotStrict.copy(explicitInvalidate = false)) + abstract class ImplicitInvalidateModule + extends Module()(chisel3.ExplicitCompileOptions.NotStrict.copy(explicitInvalidate = false)) class ModuleWithoutDontCare extends ImplicitInvalidateModule { val io = IO(new TrivialInterface) io.out := io.in diff --git a/src/test/scala/chiselTests/LiteralExtractorSpec.scala b/src/test/scala/chiselTests/LiteralExtractorSpec.scala index bc0c67b8..3906057f 100644 --- a/src/test/scala/chiselTests/LiteralExtractorSpec.scala +++ b/src/test/scala/chiselTests/LiteralExtractorSpec.scala @@ -51,19 +51,21 @@ class LiteralExtractorSpec extends ChiselFlatSpec { } "litOption" should "return None for non-literal hardware" in { - ChiselStage.elaborate { new RawModule { - val a = Wire(UInt()) - assert(a.litOption == None) - }} + ChiselStage.elaborate { + new RawModule { + val a = Wire(UInt()) + assert(a.litOption == None) + } + } } "doubles and big decimals" should "round trip properly" in { intercept[ChiselException] { - Num.toBigDecimal(BigInt("1" * 109, 2), 0.BP) // this only works if number takes less than 109 bits + Num.toBigDecimal(BigInt("1" * 109, 2), 0.BP) // this only works if number takes less than 109 bits } intercept[ChiselException] { - Num.toDouble(BigInt("1" * 54, 2), 0.BP) // this only works if number takes less than 54 bits + Num.toDouble(BigInt("1" * 54, 2), 0.BP) // this only works if number takes less than 54 bits } val bigInt108 = BigInt("1" * 108, 2) @@ -71,22 +73,22 @@ class LiteralExtractorSpec extends ChiselFlatSpec { val bigIntFromBigDecimal = Num.toBigInt(bigDecimal, 2) - bigIntFromBigDecimal should be (bigInt108) + bigIntFromBigDecimal should be(bigInt108) val bigInt53 = BigInt("1" * 53, 2) - val double = Num.toDouble(bigInt53, 2) + val double = Num.toDouble(bigInt53, 2) val bigIntFromDouble = Num.toBigInt(double, 2) - bigIntFromDouble should be (bigInt53) + bigIntFromDouble should be(bigInt53) } "encoding and decoding of Intervals" should "round trip" in { val rangeMin = BigDecimal(-31.5) val rangeMax = BigDecimal(32.5) val range = range"($rangeMin, $rangeMax).2" - for(value <- (rangeMin - 4) to (rangeMax + 4) by 2.25) { + for (value <- (rangeMin - 4) to (rangeMax + 4) by 2.25) { if (value < rangeMin || value > rangeMax) { intercept[ChiselException] { val literal = value.I(range) @@ -125,11 +127,10 @@ class LiteralExtractorSpec extends ChiselFlatSpec { } val outsideLiteral = (new InsideBundle).Lit(_.x -> 7.S, _.y -> 6.125.F(4.BP)) - assertTesterPasses{ new LitInsideOutsideTester(outsideLiteral) } + assertTesterPasses { new LitInsideOutsideTester(outsideLiteral) } } - "bundle literals" should "do the right thing" in { class MyBundle extends Bundle { val a = UInt(8.W) @@ -142,7 +143,7 @@ class LiteralExtractorSpec extends ChiselFlatSpec { } "record literals" should "do the right thing" in { - class MyRecord extends Record{ + class MyRecord extends Record { override val elements = ListMap( "a" -> UInt(8.W), "b" -> Bool() diff --git a/src/test/scala/chiselTests/LiteralToTargetSpec.scala b/src/test/scala/chiselTests/LiteralToTargetSpec.scala index 3c404f2d..b1caecfa 100644 --- a/src/test/scala/chiselTests/LiteralToTargetSpec.scala +++ b/src/test/scala/chiselTests/LiteralToTargetSpec.scala @@ -9,12 +9,11 @@ import org.scalatest._ import org.scalatest.freespec.AnyFreeSpec import org.scalatest.matchers.should.Matchers - class LiteralToTargetSpec extends AnyFreeSpec with Matchers { "Literal Data should fail to be converted to ReferenceTarget" in { - the [chisel3.internal.ChiselException] thrownBy { + (the[chisel3.internal.ChiselException] thrownBy { class Bar extends RawModule { val a = 1.U @@ -26,6 +25,6 @@ class LiteralToTargetSpec extends AnyFreeSpec with Matchers { } ChiselStage.elaborate(new Foo) - } should have message "Illegal component name: UInt<1>(\"h01\") (note: literals are illegal)" + } should have).message("Illegal component name: UInt<1>(\"h01\") (note: literals are illegal)") } } diff --git a/src/test/scala/chiselTests/LoadMemoryFromFileSpec.scala b/src/test/scala/chiselTests/LoadMemoryFromFileSpec.scala index 74e587bc..8e5e48b4 100644 --- a/src/test/scala/chiselTests/LoadMemoryFromFileSpec.scala +++ b/src/test/scala/chiselTests/LoadMemoryFromFileSpec.scala @@ -6,7 +6,7 @@ import java.io.File import chisel3._ import chisel3.stage.{ChiselGeneratorAnnotation, ChiselStage} -import chisel3.util.experimental.{loadMemoryFromFile,loadMemoryFromFileInline} +import chisel3.util.experimental.{loadMemoryFromFile, loadMemoryFromFileInline} import chisel3.util.log2Ceil import firrtl.annotations.MemoryLoadFileType import org.scalatest.freespec.AnyFreeSpec @@ -15,9 +15,9 @@ import org.scalatest.matchers.should.Matchers class UsesThreeMems(memoryDepth: Int, memoryType: Data) extends Module { val io = IO(new Bundle { val address = Input(UInt(memoryType.getWidth.W)) - val value1 = Output(memoryType) - val value2 = Output(memoryType) - val value3 = Output(memoryType) + val value1 = Output(memoryType) + val value2 = Output(memoryType) + val value3 = Output(memoryType) }) val memory1 = Mem(memoryDepth, memoryType) @@ -32,12 +32,17 @@ class UsesThreeMems(memoryDepth: Int, memoryType: Data) extends Module { io.value3 := memory3(io.address) } -class UsesThreeMemsInline(memoryDepth: Int, memoryType: Data, memoryFile: String, hexOrBinary: MemoryLoadFileType.FileType) extends Module { +class UsesThreeMemsInline( + memoryDepth: Int, + memoryType: Data, + memoryFile: String, + hexOrBinary: MemoryLoadFileType.FileType) + extends Module { val io = IO(new Bundle { val address = Input(UInt(memoryType.getWidth.W)) - val value1 = Output(memoryType) - val value2 = Output(memoryType) - val value3 = Output(memoryType) + val value1 = Output(memoryType) + val value2 = Output(memoryType) + val value3 = Output(memoryType) }) val memory1 = Mem(memoryDepth, memoryType) @@ -55,9 +60,9 @@ class UsesThreeMemsInline(memoryDepth: Int, memoryType: Data, memoryFile: String class UsesMem(memoryDepth: Int, memoryType: Data) extends Module { val io = IO(new Bundle { val address = Input(UInt(memoryType.getWidth.W)) - val value = Output(memoryType) - val value1 = Output(memoryType) - val value2 = Output(memoryType) + val value = Output(memoryType) + val value1 = Output(memoryType) + val value2 = Output(memoryType) }) val memory = Mem(memoryDepth, memoryType) @@ -77,7 +82,7 @@ class UsesMem(memoryDepth: Int, memoryType: Data) extends Module { class UsesMemLow(memoryDepth: Int, memoryType: Data) extends Module { val io = IO(new Bundle { val address = Input(UInt(memoryType.getWidth.W)) - val value = Output(memoryType) + val value = Output(memoryType) }) val memory = Mem(memoryDepth, memoryType) @@ -90,8 +95,8 @@ class UsesMemLow(memoryDepth: Int, memoryType: Data) extends Module { class FileHasSuffix(memoryDepth: Int, memoryType: Data) extends Module { val io = IO(new Bundle { val address = Input(UInt(memoryType.getWidth.W)) - val value = Output(memoryType) - val value2 = Output(memoryType) + val value = Output(memoryType) + val value2 = Output(memoryType) }) val memory = Mem(memoryDepth, memoryType) @@ -115,7 +120,7 @@ class MemoryShape extends Bundle { class HasComplexMemory(memoryDepth: Int) extends Module { val io = IO(new Bundle { val address = Input(UInt(log2Ceil(memoryDepth).W)) - val value = Output(new MemoryShape) + val value = Output(new MemoryShape) }) val memory = Mem(memoryDepth, new MemoryShape) @@ -128,7 +133,7 @@ class HasComplexMemory(memoryDepth: Int) extends Module { class HasBinarySupport(memoryDepth: Int, memoryType: Data) extends Module { val io = IO(new Bundle { val address = Input(UInt(memoryType.getWidth.W)) - val value = Output(memoryType) + val value = Output(memoryType) }) val memory = Mem(memoryDepth, memoryType) @@ -138,7 +143,6 @@ class HasBinarySupport(memoryDepth: Int, memoryType: Data) extends Module { io.value := memory(io.address) } - /** * The following tests are a bit incomplete and check that the output verilog is properly constructed * For more complete working examples @@ -147,12 +151,12 @@ class HasBinarySupport(memoryDepth: Int, memoryType: Data) extends Module { class LoadMemoryFromFileSpec extends AnyFreeSpec with Matchers { def fileExistsWithMem(file: File, mem: Option[String] = None): Unit = { info(s"$file exists") - file.exists() should be (true) - mem.foreach( m => { + file.exists() should be(true) + mem.foreach(m => { info(s"Memory $m is referenced in $file") val found = io.Source.fromFile(file).getLines.exists { _.contains(s"""readmemh("$m"""") } - found should be (true) - } ) + found should be(true) + }) file.delete() } @@ -180,10 +184,10 @@ class LoadMemoryFromFileSpec extends AnyFreeSpec with Matchers { ) val dir = new File(testDirName) - fileExistsWithMem( new File(dir, "UsesThreeMems.UsesThreeMems.memory1.v"), Some("./mem1")) - fileExistsWithMem( new File(dir, "UsesThreeMems.UsesThreeMems.memory2.v"), Some("./mem1")) - fileExistsWithMem( new File(dir, "UsesThreeMems.UsesThreeMems.memory3.v"), Some("./mem1")) - fileExistsWithMem( new File(dir, "firrtl_black_box_resource_files.f")) + fileExistsWithMem(new File(dir, "UsesThreeMems.UsesThreeMems.memory1.v"), Some("./mem1")) + fileExistsWithMem(new File(dir, "UsesThreeMems.UsesThreeMems.memory2.v"), Some("./mem1")) + fileExistsWithMem(new File(dir, "UsesThreeMems.UsesThreeMems.memory3.v"), Some("./mem1")) + fileExistsWithMem(new File(dir, "firrtl_black_box_resource_files.f")) } @@ -200,9 +204,9 @@ class LoadMemoryFromFileSpec extends AnyFreeSpec with Matchers { memoryElements.foreach { element => val file = new File(dir, s"HasComplexMemory.HasComplexMemory.memory_$element.v") - file.exists() should be (true) + file.exists() should be(true) val fileText = io.Source.fromFile(file).getLines().mkString("\n") - fileText should include (s"""$$readmemh("./mem_$element", HasComplexMemory.memory_$element);""") + fileText should include(s"""$$readmemh("./mem_$element", HasComplexMemory.memory_$element);""") file.delete() } @@ -218,9 +222,9 @@ class LoadMemoryFromFileSpec extends AnyFreeSpec with Matchers { val dir = new File(testDirName) val file = new File(dir, s"HasBinarySupport.HasBinarySupport.memory.v") - file.exists() should be (true) + file.exists() should be(true) val fileText = io.Source.fromFile(file).getLines().mkString("\n") - fileText should include (s"""$$readmemb("./mem", HasBinarySupport.memory);""") + fileText should include(s"""$$readmemb("./mem", HasBinarySupport.memory);""") file.delete() } @@ -229,15 +233,19 @@ class LoadMemoryFromFileSpec extends AnyFreeSpec with Matchers { val result = (new ChiselStage).execute( args = Array("-X", "verilog", "--target-dir", testDirName), - annotations = Seq(ChiselGeneratorAnnotation(() => new UsesThreeMemsInline(memoryDepth = 8, memoryType = UInt(16.W), "./testmem.h", MemoryLoadFileType.Hex))) + annotations = Seq( + ChiselGeneratorAnnotation(() => + new UsesThreeMemsInline(memoryDepth = 8, memoryType = UInt(16.W), "./testmem.h", MemoryLoadFileType.Hex) + ) + ) ) val dir = new File(testDirName) val file = new File(dir, s"UsesThreeMemsInline.v") - file.exists() should be (true) + file.exists() should be(true) val fileText = io.Source.fromFile(file).getLines().mkString("\n") - fileText should include (s"""$$readmemh("./testmem.h", memory1);""") - fileText should include (s"""$$readmemh("./testmem.h", memory2);""") - fileText should include (s"""$$readmemh("./testmem.h", memory3);""") + fileText should include(s"""$$readmemh("./testmem.h", memory1);""") + fileText should include(s"""$$readmemh("./testmem.h", memory2);""") + fileText should include(s"""$$readmemh("./testmem.h", memory3);""") } "Module with more than one bin memory inline should work" in { @@ -245,14 +253,18 @@ class LoadMemoryFromFileSpec extends AnyFreeSpec with Matchers { val result = (new ChiselStage).execute( args = Array("-X", "verilog", "--target-dir", testDirName), - annotations = Seq(ChiselGeneratorAnnotation(() => new UsesThreeMemsInline(memoryDepth = 8, memoryType = UInt(16.W), "testmem.bin", MemoryLoadFileType.Binary))) + annotations = Seq( + ChiselGeneratorAnnotation(() => + new UsesThreeMemsInline(memoryDepth = 8, memoryType = UInt(16.W), "testmem.bin", MemoryLoadFileType.Binary) + ) + ) ) val dir = new File(testDirName) val file = new File(dir, s"UsesThreeMemsInline.v") - file.exists() should be (true) + file.exists() should be(true) val fileText = io.Source.fromFile(file).getLines().mkString("\n") - fileText should include (s"""$$readmemb("testmem.bin", memory1);""") - fileText should include (s"""$$readmemb("testmem.bin", memory2);""") - fileText should include (s"""$$readmemb("testmem.bin", memory3);""") + fileText should include(s"""$$readmemb("testmem.bin", memory1);""") + fileText should include(s"""$$readmemb("testmem.bin", memory2);""") + fileText should include(s"""$$readmemb("testmem.bin", memory3);""") } } diff --git a/src/test/scala/chiselTests/Math.scala b/src/test/scala/chiselTests/Math.scala index 9091b0b4..42eff6ad 100644 --- a/src/test/scala/chiselTests/Math.scala +++ b/src/test/scala/chiselTests/Math.scala @@ -10,41 +10,43 @@ class Math extends ChiselPropSpec { implicit val noShrinkListVal = Shrink[List[Int]](_ => Stream.empty) implicit val noShrinkInt = Shrink[Int](_ => Stream.empty) - property ("unsignedBitLength is computed correctly") { - forAll(safeUIntWidth) { case (width: Int) => - for ( offset <- List(-1, 0, 1)) { - val n = (1 << width) + offset - if (n >= 0) { - val d = unsignedBitLength(n) - val t = if (n == 0) 0 else if (offset < 0) width else width + 1 - d shouldEqual (t) + property("unsignedBitLength is computed correctly") { + forAll(safeUIntWidth) { + case (width: Int) => + for (offset <- List(-1, 0, 1)) { + val n = (1 << width) + offset + if (n >= 0) { + val d = unsignedBitLength(n) + val t = if (n == 0) 0 else if (offset < 0) width else width + 1 + d shouldEqual (t) + } } - } } } - property ("signedBitLength is computed correctly") { - forAll(safeUIntWidth) { case (width: Int) => - for ( offset <- List(-1, 0, 1)) { - for ( mult <- List(-1, +1)) { - val n = ((1 << (width - 1)) + offset) * mult - val d = signedBitLength(n) - val t = n match { - case -2 => 2 - case -1 => 1 - case 0 => 0 - case 1 => 2 - case 2 => 3 - case _ => - if (n > 0) { - if (offset < 0) width else width + 1 - } else { - if (offset > 0) width + 1 else width - } + property("signedBitLength is computed correctly") { + forAll(safeUIntWidth) { + case (width: Int) => + for (offset <- List(-1, 0, 1)) { + for (mult <- List(-1, +1)) { + val n = ((1 << (width - 1)) + offset) * mult + val d = signedBitLength(n) + val t = n match { + case -2 => 2 + case -1 => 1 + case 0 => 0 + case 1 => 2 + case 2 => 3 + case _ => + if (n > 0) { + if (offset < 0) width else width + 1 + } else { + if (offset > 0) width + 1 else width + } + } + d shouldEqual (t) } - d shouldEqual (t) } - } } } } diff --git a/src/test/scala/chiselTests/Mem.scala b/src/test/scala/chiselTests/Mem.scala index 8bcd3aac..4dcb1ad4 100644 --- a/src/test/scala/chiselTests/Mem.scala +++ b/src/test/scala/chiselTests/Mem.scala @@ -13,7 +13,7 @@ class MemVecTester extends BasicTester { val (cnt, wrap) = Counter(true.B, 2) mem(0)(0) := 1.U - when (cnt === 1.U) { + when(cnt === 1.U) { assert(mem.read(0.U)(0) === 1.U) stop() } @@ -24,12 +24,12 @@ class SyncReadMemTester extends BasicTester { val mem = SyncReadMem(2, UInt(2.W)) val rdata = mem.read(cnt - 1.U, cnt =/= 0.U) - switch (cnt) { - is (0.U) { mem.write(cnt, 3.U) } - is (1.U) { mem.write(cnt, 2.U) } - is (2.U) { assert(rdata === 3.U) } - is (3.U) { assert(rdata === 2.U) } - is (4.U) { stop() } + switch(cnt) { + is(0.U) { mem.write(cnt, 3.U) } + is(1.U) { mem.write(cnt, 2.U) } + is(2.U) { assert(rdata === 3.U) } + is(3.U) { assert(rdata === 2.U) } + is(4.U) { stop() } } } @@ -47,24 +47,24 @@ class SyncReadMemWriteCollisionTester extends BasicTester { m1.write(cnt, cnt) // Read data from address 0 - when (cnt === 3.U) { + when(cnt === 3.U) { assert(rd0 === 2.U) assert(rd1 === 0.U) } - when (cnt === 4.U) { + when(cnt === 4.U) { stop() } } class SyncReadMemWithZeroWidthTester extends BasicTester { val (cnt, _) = Counter(true.B, 3) - val mem = SyncReadMem(2, UInt(0.W)) - val rdata = mem.read(0.U, true.B) + val mem = SyncReadMem(2, UInt(0.W)) + val rdata = mem.read(0.U, true.B) - switch (cnt) { - is (1.U) { assert(rdata === 0.U) } - is (2.U) { stop() } + switch(cnt) { + is(1.U) { assert(rdata === 0.U) } + is(2.U) { stop() } } } @@ -74,12 +74,12 @@ class HugeSMemTester(size: BigInt) extends BasicTester { val mem = SyncReadMem(size, UInt(8.W)) val rdata = mem.read(cnt - 1.U, cnt =/= 0.U) - switch (cnt) { - is (0.U) { mem.write(cnt, 3.U) } - is (1.U) { mem.write(cnt, 2.U) } - is (2.U) { assert(rdata === 3.U) } - is (3.U) { assert(rdata === 2.U) } - is (4.U) { stop() } + switch(cnt) { + is(0.U) { mem.write(cnt, 3.U) } + is(1.U) { mem.write(cnt, 2.U) } + is(2.U) { assert(rdata === 3.U) } + is(3.U) { assert(rdata === 2.U) } + is(4.U) { stop() } } } class HugeCMemTester(size: BigInt) extends BasicTester { @@ -87,12 +87,12 @@ class HugeCMemTester(size: BigInt) extends BasicTester { val mem = Mem(size, UInt(8.W)) val rdata = mem.read(cnt) - switch (cnt) { - is (0.U) { mem.write(cnt, 3.U) } - is (1.U) { mem.write(cnt, 2.U) } - is (2.U) { assert(rdata === 3.U) } - is (3.U) { assert(rdata === 2.U) } - is (4.U) { stop() } + switch(cnt) { + is(0.U) { mem.write(cnt, 3.U) } + is(1.U) { mem.write(cnt, 2.U) } + is(2.U) { assert(rdata === 3.U) } + is(3.U) { assert(rdata === 2.U) } + is(4.U) { stop() } } } @@ -104,20 +104,20 @@ class SyncReadMemBundleTester extends BasicTester { val mem = SyncReadMem(2, tpe) val rdata = mem.read(cnt - 1.U, cnt =/= 0.U) - switch (cnt) { - is (0.U) { + switch(cnt) { + is(0.U) { val w = Wire(tpe) w.foo := 3.U mem.write(cnt, w) } - is (1.U) { + is(1.U) { val w = Wire(tpe) w.foo := 2.U mem.write(cnt, w) } - is (2.U) { assert(rdata.foo === 3.U) } - is (3.U) { assert(rdata.foo === 2.U) } - is (4.U) { stop() } + is(2.U) { assert(rdata.foo === 3.U) } + is(3.U) { assert(rdata.foo === 2.U) } + is(4.U) { stop() } } } @@ -135,7 +135,7 @@ class MemBundleTester extends BasicTester { w } - when (cnt === 1.U) { + when(cnt === 1.U) { assert(mem.read(0.U).foo === 1.U) stop() } @@ -170,20 +170,20 @@ class MemorySpec extends ChiselPropSpec { val addrWidth = 65 val size = BigInt(1) << addrWidth val smem = compile(new HugeSMemTester(size)) - smem should include (s"reg /* sparse */ [7:0] mem [0:$addrWidth'd${size-1}];") + smem should include(s"reg /* sparse */ [7:0] mem [0:$addrWidth'd${size - 1}];") val cmem = compile(new HugeCMemTester(size)) - cmem should include (s"reg /* sparse */ [7:0] mem [0:$addrWidth'd${size-1}];") + cmem should include(s"reg /* sparse */ [7:0] mem [0:$addrWidth'd${size - 1}];") } property("Implicit conversions with Mem indices should work") { """ - |import chisel3._ - |import chisel3.util.ImplicitConversions._ - |class MyModule extends Module { - | val io = IO(new Bundle {}) - | val mem = Mem(32, UInt(8.W)) - | mem(0) := 0.U - |} - |""".stripMargin should compile + |import chisel3._ + |import chisel3.util.ImplicitConversions._ + |class MyModule extends Module { + | val io = IO(new Bundle {}) + | val mem = Mem(32, UInt(8.W)) + | mem(0) := 0.U + |} + |""".stripMargin should compile } } diff --git a/src/test/scala/chiselTests/MemorySearch.scala b/src/test/scala/chiselTests/MemorySearch.scala index ebfdace1..df1c6b32 100644 --- a/src/test/scala/chiselTests/MemorySearch.scala +++ b/src/test/scala/chiselTests/MemorySearch.scala @@ -7,23 +7,23 @@ import chisel3.stage.ChiselStage class MemorySearch extends Module { val io = IO(new Bundle { - val target = Input(UInt(4.W)) - val en = Input(Bool()) - val done = Output(Bool()) + val target = Input(UInt(4.W)) + val en = Input(Bool()) + val done = Output(Bool()) val address = Output(UInt(3.W)) }) - val vals = Array(0, 4, 15, 14, 2, 5, 13) + val vals = Array(0, 4, 15, 14, 2, 5, 13) val index = RegInit(0.U(3.W)) - val elts = VecInit(vals.map(_.asUInt(4.W))) + val elts = VecInit(vals.map(_.asUInt(4.W))) // val elts = Mem(UInt(32.W), 8) TODO ???? - val elt = elts(index) - val end = !io.en && ((elt === io.target) || (index === 7.U)) - when (io.en) { + val elt = elts(index) + val end = !io.en && ((elt === io.target) || (index === 7.U)) + when(io.en) { index := 0.U - } .elsewhen (!end) { + }.elsewhen(!end) { index := index +% 1.U } - io.done := end + io.done := end io.address := index } @@ -46,7 +46,7 @@ class MemorySearchTester(c: MemorySearch) extends Tester(c) { "LOOKING FOR " + target + " FOUND " + addr) } } -*/ + */ class MemorySearchSpec extends ChiselPropSpec { @@ -54,5 +54,5 @@ class MemorySearchSpec extends ChiselPropSpec { ChiselStage.elaborate { new EnableShiftRegister } } - ignore("MemorySearch should return the correct result") { } + ignore("MemorySearch should return the correct result") {} } diff --git a/src/test/scala/chiselTests/MixedVecSpec.scala b/src/test/scala/chiselTests/MixedVecSpec.scala index 369ed68a..16efafd4 100644 --- a/src/test/scala/chiselTests/MixedVecSpec.scala +++ b/src/test/scala/chiselTests/MixedVecSpec.scala @@ -87,7 +87,7 @@ class MixedVecUIntDynamicIndexTester extends BasicTester { val (cycle, done) = Counter(true.B, n) assert(vecWire(cycle) === cycle) - when (done) { stop() } + when(done) { stop() } } class MixedVecTestBundle extends Bundle { @@ -143,10 +143,10 @@ class MixedVecOneBitTester extends BasicTester { val flag = RegInit(false.B) val oneBit = Reg(MixedVec(Seq(UInt(1.W)))) - when (!flag) { + when(!flag) { oneBit(0) := 1.U(1.W) flag := true.B - } .otherwise { + }.otherwise { assert(oneBit(0) === 1.U) assert(oneBit.asUInt === 1.U) stop() @@ -179,26 +179,29 @@ class MixedVecSpec extends ChiselPropSpec with Utils { } property("MixedVecs should be assignable") { - forAll(safeUIntN(8)) { case (w: Int, v: List[Int]) => - assertTesterPasses { - new MixedVecAssignTester(w, v) - } + forAll(safeUIntN(8)) { + case (w: Int, v: List[Int]) => + assertTesterPasses { + new MixedVecAssignTester(w, v) + } } } property("MixedVecs should be usable as the type for Reg()") { - forAll(safeUIntN(8)) { case (w: Int, v: List[Int]) => - assertTesterPasses { - new MixedVecRegTester(w, v) - } + forAll(safeUIntN(8)) { + case (w: Int, v: List[Int]) => + assertTesterPasses { + new MixedVecRegTester(w, v) + } } } property("MixedVecs should be passed through IO") { - forAll(safeUIntN(8)) { case (w: Int, v: List[Int]) => - assertTesterPasses { - new MixedVecIOTester(v.map(i => i.U(w.W))) - } + forAll(safeUIntN(8)) { + case (w: Int, v: List[Int]) => + assertTesterPasses { + new MixedVecIOTester(v.map(i => i.U(w.W))) + } } } @@ -209,21 +212,21 @@ class MixedVecSpec extends ChiselPropSpec with Utils { } property("MixedVecs should not be able to take hardware types") { - a [ExpectedChiselTypeException] should be thrownBy extractCause[ExpectedChiselTypeException] { + a[ExpectedChiselTypeException] should be thrownBy extractCause[ExpectedChiselTypeException] { ChiselStage.elaborate(new Module { val io = IO(new Bundle {}) val hw = Wire(MixedVec(Seq(UInt(8.W), Bool()))) val illegal = MixedVec(hw) }) } - a [ExpectedChiselTypeException] should be thrownBy extractCause[ExpectedChiselTypeException] { + a[ExpectedChiselTypeException] should be thrownBy extractCause[ExpectedChiselTypeException] { ChiselStage.elaborate(new Module { val io = IO(new Bundle {}) val hw = Reg(MixedVec(Seq(UInt(8.W), Bool()))) val illegal = MixedVec(hw) }) } - a [ExpectedChiselTypeException] should be thrownBy extractCause[ExpectedChiselTypeException] { + a[ExpectedChiselTypeException] should be thrownBy extractCause[ExpectedChiselTypeException] { ChiselStage.elaborate(new Module { val io = IO(new Bundle { val v = Input(MixedVec(Seq(UInt(8.W), Bool()))) @@ -238,19 +241,19 @@ class MixedVecSpec extends ChiselPropSpec with Utils { } property("MixedVecs of UInts should be dynamically indexable (via VecInit)") { - assertTesterPasses{ new MixedVecUIntDynamicIndexTester } + assertTesterPasses { new MixedVecUIntDynamicIndexTester } } property("MixedVecs should be creatable from Vecs") { - assertTesterPasses{ new MixedVecFromVecTester } + assertTesterPasses { new MixedVecFromVecTester } } property("It should be possible to bulk connect a MixedVec and a Vec") { - assertTesterPasses{ new MixedVecConnectWithVecTester } + assertTesterPasses { new MixedVecConnectWithVecTester } } property("It should be possible to bulk connect a MixedVec and a Seq") { - assertTesterPasses{ new MixedVecConnectWithSeqTester } + assertTesterPasses { new MixedVecConnectWithSeqTester } } property("MixedVecs of a single 1 bit element should compile and work") { @@ -258,7 +261,7 @@ class MixedVecSpec extends ChiselPropSpec with Utils { } property("Connecting a MixedVec and something of different size should report a ChiselException") { - an [IllegalArgumentException] should be thrownBy extractCause[IllegalArgumentException] { + an[IllegalArgumentException] should be thrownBy extractCause[IllegalArgumentException] { ChiselStage.elaborate(new Module { val io = IO(new Bundle { val out = Output(MixedVec(Seq(UInt(8.W), Bool()))) @@ -267,7 +270,7 @@ class MixedVecSpec extends ChiselPropSpec with Utils { io.out := seq }) } - an [IllegalArgumentException] should be thrownBy extractCause[IllegalArgumentException] { + an[IllegalArgumentException] should be thrownBy extractCause[IllegalArgumentException] { ChiselStage.elaborate(new Module { val io = IO(new Bundle { val out = Output(MixedVec(Seq(UInt(8.W), Bool()))) diff --git a/src/test/scala/chiselTests/Module.scala b/src/test/scala/chiselTests/Module.scala index f0d6dbe7..13dbe1e9 100644 --- a/src/test/scala/chiselTests/Module.scala +++ b/src/test/scala/chiselTests/Module.scala @@ -12,7 +12,7 @@ import scala.io.Source import scala.annotation.nowarn class SimpleIO extends Bundle { - val in = Input(UInt(32.W)) + val in = Input(UInt(32.W)) val out = Output(UInt(32.W)) } @@ -23,13 +23,13 @@ class PlusOne extends Module { class ModuleVec(val n: Int) extends Module { val io = IO(new Bundle { - val ins = Input(Vec(n, UInt(32.W))) + val ins = Input(Vec(n, UInt(32.W))) val outs = Output(Vec(n, UInt(32.W))) }) - val pluses = VecInit(Seq.fill(n){ Module(new PlusOne).io }) + val pluses = VecInit(Seq.fill(n) { Module(new PlusOne).io }) for (i <- 0 until n) { pluses(i).in := io.ins(i) - io.outs(i) := pluses(i).out + io.outs(i) := pluses(i).out } } @@ -49,7 +49,7 @@ class ModuleWhen extends Module { val inc = Module(new PlusOne).io inc.in := io.s.in io.s.out := inc.out - } otherwise { io.s.out := io.s.in } + }.otherwise { io.s.out := io.s.in } } class ModuleForgetWrapper extends Module { @@ -69,13 +69,13 @@ class ModuleRewrap extends Module { } class ModuleWrapper(gen: => Module) extends Module { - val io = IO(new Bundle{}) + val io = IO(new Bundle {}) val child = Module(gen) override val desiredName = s"${child.desiredName}Wrapper" } class NullModuleWrapper extends Module { - val io = IO(new Bundle{}) + val io = IO(new Bundle {}) override lazy val desiredName = s"${child.desiredName}Wrapper" println(s"My name is ${name}") val child = Module(new ModuleWire) @@ -87,34 +87,34 @@ class ModuleSpec extends ChiselPropSpec with Utils { ChiselStage.elaborate { new ModuleVec(2) } } - ignore("ModuleVecTester should return the correct result") { } + ignore("ModuleVecTester should return the correct result") {} property("ModuleWire should elaborate") { ChiselStage.elaborate { new ModuleWire } } - ignore("ModuleWireTester should return the correct result") { } + ignore("ModuleWireTester should return the correct result") {} property("ModuleWhen should elaborate") { ChiselStage.elaborate { new ModuleWhen } } - ignore("ModuleWhenTester should return the correct result") { } + ignore("ModuleWhenTester should return the correct result") {} property("Forgetting a Module() wrapper should result in an error") { - (the [ChiselException] thrownBy extractCause[ChiselException] { + (the[ChiselException] thrownBy extractCause[ChiselException] { ChiselStage.elaborate { new ModuleForgetWrapper } }).getMessage should include("attempted to instantiate a Module without wrapping it") } property("Double wrapping a Module should result in an error") { - (the [ChiselException] thrownBy extractCause[ChiselException] { + (the[ChiselException] thrownBy extractCause[ChiselException] { ChiselStage.elaborate { new ModuleDoubleWrap } }).getMessage should include("Called Module() twice without instantiating a Module") } property("Rewrapping an already instantiated Module should result in an error") { - (the [ChiselException] thrownBy extractCause[ChiselException] { + (the[ChiselException] thrownBy extractCause[ChiselException] { ChiselStage.elaborate { new ModuleRewrap } }).getMessage should include("This is probably due to rewrapping a Module instance") } @@ -140,7 +140,7 @@ class ModuleSpec extends ChiselPropSpec with Utils { property("object Module.currentModule should return an Option reference to the current Module") { def checkModule(mod: Module): Boolean = Module.currentModule.map(_ eq mod).getOrElse(false) ChiselStage.elaborate(new Module { - val io = IO(new Bundle { }) + val io = IO(new Bundle {}) assert(Module.currentModule.get eq this) assert(checkModule(this)) }) @@ -148,24 +148,27 @@ class ModuleSpec extends ChiselPropSpec with Utils { property("object chisel3.util.experimental.getAnnotations should return current annotations.") { case class DummyAnnotation() extends NoTargetAnnotation with Unserializable - (new ChiselStage).transform(Seq( - ChiselGeneratorAnnotation(() => new RawModule { - assert(chisel3.util.experimental.getAnnotations().contains(DummyAnnotation())) - }), - DummyAnnotation(), - NoRunFirrtlCompilerAnnotation)) + (new ChiselStage).transform( + Seq( + ChiselGeneratorAnnotation(() => + new RawModule { + assert(chisel3.util.experimental.getAnnotations().contains(DummyAnnotation())) + } + ), + DummyAnnotation(), + NoRunFirrtlCompilerAnnotation + ) + ) } property("DataMirror.modulePorts should work") { ChiselStage.elaborate(new Module { - val io = IO(new Bundle { }) + val io = IO(new Bundle {}) val m = Module(new chisel3.Module { val a = IO(UInt(8.W)) val b = IO(Bool()) }) - assert(DataMirror.modulePorts(m) == Seq( - "clock" -> m.clock, "reset" -> m.reset, - "a" -> m.a, "b" -> m.b)) + assert(DataMirror.modulePorts(m) == Seq("clock" -> m.clock, "reset" -> m.reset, "a" -> m.a, "b" -> m.b)) }) } @@ -186,21 +189,25 @@ class ModuleSpec extends ChiselPropSpec with Utils { mod } // Note that this is just top-level ports, Aggregates are not flattened - DataMirror.modulePorts(mod) should contain theSameElementsInOrderAs Seq( - "clock" -> mod.clock, - "reset" -> mod.reset, - "io" -> mod.io, - "extra" -> mod.extra + (DataMirror.modulePorts(mod) should contain).theSameElementsInOrderAs( + Seq( + "clock" -> mod.clock, + "reset" -> mod.reset, + "io" -> mod.io, + "extra" -> mod.extra + ) ) // Delete this when the deprecated API is deleted // Note this also uses deprecated Port import chisel3.internal.firrtl.Port import SpecifiedDirection.{Input => IN, Unspecified} - mod.getPorts should contain theSameElementsInOrderAs Seq( - Port(mod.clock, IN), - Port(mod.reset, IN), - Port(mod.io, Unspecified), - Port(mod.extra, IN) + (mod.getPorts should contain).theSameElementsInOrderAs( + Seq( + Port(mod.clock, IN), + Port(mod.reset, IN), + Port(mod.io, Unspecified), + Port(mod.extra, IN) + ) ): @nowarn // delete when Port and getPorts become private } @@ -230,15 +237,16 @@ class ModuleSpec extends ChiselPropSpec with Utils { "io_in" -> mod.io.in, "extra" -> mod.extra ) - DataMirror.fullModulePorts(mod) should contain theSameElementsInOrderAs expected + (DataMirror.fullModulePorts(mod) should contain).theSameElementsInOrderAs(expected) } property("A desiredName parameterized by a submodule should work") { - ChiselStage.elaborate(new ModuleWrapper(new ModuleWire)).name should be ("ModuleWireWrapper") + ChiselStage.elaborate(new ModuleWrapper(new ModuleWire)).name should be("ModuleWireWrapper") } property("A name generating a null pointer exception should provide a good error message") { - (the [ChiselException] thrownBy extractCause[ChiselException] (ChiselStage.elaborate(new NullModuleWrapper))) - .getMessage should include ("desiredName of chiselTests.NullModuleWrapper is null") + (the[ChiselException] thrownBy extractCause[ChiselException]( + ChiselStage.elaborate(new NullModuleWrapper) + )).getMessage should include("desiredName of chiselTests.NullModuleWrapper is null") } property("The name of a module in a function should be sane") { def foo = { @@ -262,7 +270,7 @@ class ModuleSpec extends ChiselPropSpec with Utils { } property("emitVerilog((new PlusOne()..) shall produce a valid Verilog file in a subfolder") { - emitVerilog(new PlusOne(), Array("--target-dir", "generated")) + emitVerilog(new PlusOne(), Array("--target-dir", "generated")) val s = Source.fromFile("generated/PlusOne.v").mkString("") assert(s.contains("assign io_out = io_in + 32'h1")) } diff --git a/src/test/scala/chiselTests/ModuleExplicitResetSpec.scala b/src/test/scala/chiselTests/ModuleExplicitResetSpec.scala index c55276ce..1a55fb3f 100644 --- a/src/test/scala/chiselTests/ModuleExplicitResetSpec.scala +++ b/src/test/scala/chiselTests/ModuleExplicitResetSpec.scala @@ -4,7 +4,7 @@ package chiselTests import chisel3.stage.ChiselStage -class ModuleExplicitResetSpec extends ChiselFlatSpec { +class ModuleExplicitResetSpec extends ChiselFlatSpec { "A Module with an explicit reset in compatibility mode" should "elaborate" in { import Chisel._ diff --git a/src/test/scala/chiselTests/MulLookup.scala b/src/test/scala/chiselTests/MulLookup.scala index dd539b2a..0f67ea34 100644 --- a/src/test/scala/chiselTests/MulLookup.scala +++ b/src/test/scala/chiselTests/MulLookup.scala @@ -7,9 +7,9 @@ import chisel3.testers.BasicTester class MulLookup(val w: Int) extends Module { val io = IO(new Bundle { - val x = Input(UInt(w.W)) - val y = Input(UInt(w.W)) - val z = Output(UInt((2 * w).W)) + val x = Input(UInt(w.W)) + val y = Input(UInt(w.W)) + val z = Output(UInt((2 * w).W)) }) val tbl = VecInit( for { @@ -32,7 +32,7 @@ class MulLookupSpec extends ChiselPropSpec { property("Mul lookup table should return the correct result") { forAll(smallPosInts, smallPosInts) { (x: Int, y: Int) => - assertTesterPasses{ new MulLookupTester(3, x, y) } + assertTesterPasses { new MulLookupTester(3, x, y) } } } } diff --git a/src/test/scala/chiselTests/MultiAssign.scala b/src/test/scala/chiselTests/MultiAssign.scala index fb5d6986..4cb51feb 100644 --- a/src/test/scala/chiselTests/MultiAssign.scala +++ b/src/test/scala/chiselTests/MultiAssign.scala @@ -9,16 +9,16 @@ import chisel3.util._ class LastAssignTester() extends BasicTester { val countOnClockCycles = true.B - val (cnt, wrap) = Counter(countOnClockCycles,2) + val (cnt, wrap) = Counter(countOnClockCycles, 2) val test = Wire(UInt(4.W)) - assert(test === 7.U) // allow read references before assign references + assert(test === 7.U) // allow read references before assign references test := 13.U - assert(test === 7.U) // output value should be position-independent + assert(test === 7.U) // output value should be position-independent test := 7.U - assert(test === 7.U) // this obviously should work + assert(test === 7.U) // this obviously should work when(cnt === 1.U) { stop() @@ -27,7 +27,7 @@ class LastAssignTester() extends BasicTester { class MultiAssignSpec extends ChiselFlatSpec { "The last assignment" should "be used when multiple assignments happen" in { - assertTesterPasses{ new LastAssignTester } + assertTesterPasses { new LastAssignTester } } } @@ -35,7 +35,7 @@ class IllegalAssignSpec extends ChiselFlatSpec with Utils { "Reassignments to literals" should "be disallowed" in { intercept[chisel3.internal.ChiselException] { extractCause[ChiselException] { - ChiselStage.elaborate{ + ChiselStage.elaborate { new BasicTester { 15.U := 7.U } @@ -47,7 +47,7 @@ class IllegalAssignSpec extends ChiselFlatSpec with Utils { "Reassignments to ops" should "be disallowed" in { intercept[chisel3.internal.ChiselException] { extractCause[ChiselException] { - ChiselStage.elaborate{ + ChiselStage.elaborate { new BasicTester { (15.U + 1.U) := 7.U } @@ -59,7 +59,7 @@ class IllegalAssignSpec extends ChiselFlatSpec with Utils { "Reassignments to bit slices" should "be disallowed" in { intercept[chisel3.internal.ChiselException] { extractCause[ChiselException] { - ChiselStage.elaborate{ + ChiselStage.elaborate { new BasicTester { (15.U)(1, 0) := 7.U } @@ -71,7 +71,7 @@ class IllegalAssignSpec extends ChiselFlatSpec with Utils { "Bulk-connecting two read-only nodes" should "be disallowed" in { intercept[chisel3.internal.ChiselException] { extractCause[ChiselException] { - ChiselStage.elaborate{ + ChiselStage.elaborate { new BasicTester { (15.U + 1.U) <> 7.U } diff --git a/src/test/scala/chiselTests/MultiClockSpec.scala b/src/test/scala/chiselTests/MultiClockSpec.scala index 3b52e5b9..2553f3b3 100644 --- a/src/test/scala/chiselTests/MultiClockSpec.scala +++ b/src/test/scala/chiselTests/MultiClockSpec.scala @@ -18,11 +18,11 @@ class ClockDividerTest extends BasicTester { val reg2 = withClock(clock2) { RegInit(0.U(8.W)) } reg2 := reg2 + 1.U - when (reg1 < 10.U) { + when(reg1 < 10.U) { assert(reg2 === reg1 / 2.U) // 1:2 clock relationship } - when (reg1 === 10.U) { + when(reg1 === 10.U) { stop() } } @@ -45,7 +45,7 @@ class MultiClockSubModuleTest extends BasicTester { val inst = withClockAndReset(otherClock, otherReset) { Module(new SubModule) } - when (done) { + when(done) { // The counter in inst should come out of reset later and increment at half speed assert(inst.io.out === 3.U) stop() @@ -59,14 +59,14 @@ class WithResetTest extends BasicTester { reg := reg + 1.U val (cycle, done) = Counter(true.B, 10) - when (cycle < 7.U) { + when(cycle < 7.U) { assert(reg === cycle) - } .elsewhen (cycle === 7.U) { + }.elsewhen(cycle === 7.U) { reset2 := true.B - } .elsewhen (cycle === 8.U) { + }.elsewhen(cycle === 8.U) { assert(reg === 0.U) } - when (done) { stop() } + when(done) { stop() } } /** Test Mem ports with different clocks */ @@ -82,7 +82,7 @@ class MultiClockMemTest extends BasicTester { // Write port 1 walks through writing 123 val waddr = RegInit(0.U(3.W)) waddr := waddr + 1.U - when (cycle < 8.U) { + when(cycle < 8.U) { mem(waddr) := 123.U } @@ -90,27 +90,27 @@ class MultiClockMemTest extends BasicTester { val rdata = mem(raddr) // Check each write from write port 1 - when (cycle > 0.U && cycle < 9.U) { + when(cycle > 0.U && cycle < 9.U) { assert(rdata === 123.U) } // Write port 2 walks through writing 456 on 2nd time through withClock(clock2) { - when (cycle >= 8.U && cycle < 16.U) { + when(cycle >= 8.U && cycle < 16.U) { mem(waddr) := 456.U // write 456 to different address } } // Check that every even address gets 456 - when (cycle > 8.U && cycle < 17.U) { - when (raddr % 2.U === 0.U) { + when(cycle > 8.U && cycle < 17.U) { + when(raddr % 2.U === 0.U) { assert(rdata === 456.U) - } .otherwise { + }.otherwise { assert(rdata === 123.U) } } - when (done) { stop() } + when(done) { stop() } } class MultiClockSpec extends ChiselFlatSpec { @@ -151,7 +151,7 @@ class MultiClockSpec extends ChiselFlatSpec { // The reg is always in reset so will never decrement chisel3.assert(reg === 6.U) val (_, done) = Counter(true.B, 4) - when (done) { stop() } + when(done) { stop() } }) } @@ -168,7 +168,7 @@ class MultiClockSpec extends ChiselFlatSpec { chisel3.assert(0.U === 1.U) } val (_, done) = Counter(true.B, 2) - when (done) { stop() } + when(done) { stop() } }) // Check that reset will block assertTesterPasses(new BasicTester { @@ -176,7 +176,7 @@ class MultiClockSpec extends ChiselFlatSpec { chisel3.assert(0.U === 1.U) } val (_, done) = Counter(true.B, 2) - when (done) { stop() } + when(done) { stop() } }) // Check that no rising edge will block assertTesterPasses(new BasicTester { @@ -184,7 +184,7 @@ class MultiClockSpec extends ChiselFlatSpec { chisel3.assert(0.U === 1.U) } val (_, done) = Counter(true.B, 2) - when (done) { stop() } + when(done) { stop() } }) } } diff --git a/src/test/scala/chiselTests/MultiIOModule.scala b/src/test/scala/chiselTests/MultiIOModule.scala index 9abf324b..c65d8fc4 100644 --- a/src/test/scala/chiselTests/MultiIOModule.scala +++ b/src/test/scala/chiselTests/MultiIOModule.scala @@ -6,7 +6,7 @@ import chisel3._ import chisel3.testers.BasicTester class MultiIOPlusOne extends Module { - val in = IO(Input(UInt(32.W))) + val in = IO(Input(UInt(32.W))) val out = IO(Output(UInt(32.W))) out := in + 1.asUInt @@ -33,8 +33,7 @@ trait MultiIOTrait extends Module { // Composition of the two above traits, example of IO composition directly using multiple top-level // IOs rather than indirectly by constraining the type of the single .io field. -class ComposedMultiIOModule extends Module - with LiteralOutputTrait with MultiIOTrait { +class ComposedMultiIOModule extends Module with LiteralOutputTrait with MultiIOTrait { val topModuleIO = IO(Input(UInt(32.W))) myTraitIO := topModuleIO } diff --git a/src/test/scala/chiselTests/MuxSpec.scala b/src/test/scala/chiselTests/MuxSpec.scala index 33024f0b..03505f2d 100644 --- a/src/test/scala/chiselTests/MuxSpec.scala +++ b/src/test/scala/chiselTests/MuxSpec.scala @@ -4,21 +4,21 @@ package chiselTests import chisel3._ import chisel3.stage.ChiselStage -import chisel3.util.{MuxLookup, log2Ceil} +import chisel3.util.{log2Ceil, MuxLookup} import chisel3.testers.BasicTester class MuxTester extends BasicTester { assert(Mux(0.B, 1.U, 2.U) === 2.U) assert(Mux(1.B, 1.U, 2.U) === 1.U) val dontCareMux1 = Wire(UInt()) - dontCareMux1 := Mux(0.B, DontCare, 4.U) // note: Mux output of type Element + dontCareMux1 := Mux(0.B, DontCare, 4.U) // note: Mux output of type Element assert(dontCareMux1 === 4.U) val dontCareMux2 = Wire(UInt()) - dontCareMux2 := Mux(1.B, 3.U, DontCare) // note: Mux output of type Element + dontCareMux2 := Mux(1.B, 3.U, DontCare) // note: Mux output of type Element assert(dontCareMux2 === 3.U) - Mux(0.B, 3.U, DontCare) // just to make sure nothing crashes, any result is valid + Mux(0.B, 3.U, DontCare) // just to make sure nothing crashes, any result is valid stop() } @@ -45,27 +45,28 @@ class MuxLookupExhaustiveSpec extends ChiselPropSpec { val incomplete = () => Seq(0.U -> 1.U, 1.U -> 2.U, 2.U -> 3.U) property("The default value should not be optimized away for an incomplete MuxLookup") { - ChiselStage.emitChirrtl(new MuxLookupWrapper(keyWidth, default, incomplete)) should include (firrtlLit) + ChiselStage.emitChirrtl(new MuxLookupWrapper(keyWidth, default, incomplete)) should include(firrtlLit) } val exhaustive = () => (3.U -> 0.U) +: incomplete() property("The default value should be optimized away for an exhaustive MuxLookup") { - ChiselStage.emitChirrtl(new MuxLookupWrapper(keyWidth, default, exhaustive)) should not include (firrtlLit) + (ChiselStage.emitChirrtl(new MuxLookupWrapper(keyWidth, default, exhaustive)) should not).include(firrtlLit) } val overlap = () => (4096.U -> 0.U) +: incomplete() property("The default value should not be optimized away for a MuxLookup with 2^{keyWidth} non-distinct mappings") { - ChiselStage.emitChirrtl(new MuxLookupWrapper(keyWidth, default, overlap)) should include (firrtlLit) + ChiselStage.emitChirrtl(new MuxLookupWrapper(keyWidth, default, overlap)) should include(firrtlLit) } val nonLiteral = () => { val foo = Wire(UInt()); (foo -> 1.U) +: incomplete() } property("The default value should not be optimized away for a MuxLookup with a non-literal") { - ChiselStage.emitChirrtl(new MuxLookupWrapper(keyWidth, default, nonLiteral)) should include (firrtlLit) + ChiselStage.emitChirrtl(new MuxLookupWrapper(keyWidth, default, nonLiteral)) should include(firrtlLit) } val nonLiteralStillFull = () => { val foo = Wire(UInt()); (foo -> 1.U) +: exhaustive() } property("The default value should be optimized away for a MuxLookup with a non-literal that is still full") { - ChiselStage.emitChirrtl(new MuxLookupWrapper(keyWidth, default, nonLiteralStillFull)) should not include (firrtlLit) + (ChiselStage.emitChirrtl(new MuxLookupWrapper(keyWidth, default, nonLiteralStillFull)) should not) + .include(firrtlLit) } } diff --git a/src/test/scala/chiselTests/NamingAnnotationTest.scala b/src/test/scala/chiselTests/NamingAnnotationTest.scala index 2226a48a..ded321cd 100644 --- a/src/test/scala/chiselTests/NamingAnnotationTest.scala +++ b/src/test/scala/chiselTests/NamingAnnotationTest.scala @@ -70,7 +70,7 @@ class NamedModule extends NamedModuleTester { def FunctionMockupInner(): UInt = { val my2A = 1.U val my2B = expectName(my2A +& 2.U, "test_myNested_my2B") - val my2C = my2B +& 3.U // should get named at enclosing scope + val my2C = my2B +& 3.U // should get named at enclosing scope my2C } @@ -85,14 +85,14 @@ class NamedModule extends NamedModuleTester { for ((d, i) <- myD.zipWithIndex) expectName(d, s"test_myD_$i") - myC +& 4.U // named at enclosing scope + myC +& 4.U // named at enclosing scope } // chiselName "implicitly" applied def ImplicitlyNamed(): UInt = { val implicitA = expectName(1.U + 2.U, "test3_implicitA") val implicitB = expectName(implicitA + 3.U, "test3_implicitB") - implicitB + 2.U // named at enclosing scope + implicitB + 2.U // named at enclosing scope } // Ensure this applies a partial name if there is no return value @@ -115,8 +115,9 @@ class NamedModule extends NamedModuleTester { } // Test that contents of anonymous functions are named - Seq((0, "anonInner"), (1, "anonInner_1"), (2, "anonInner_2")).foreach { case (in, name) => - val anonInner = expectName(test3 + in.U, name) + Seq((0, "anonInner"), (1, "anonInner_1"), (2, "anonInner_2")).foreach { + case (in, name) => + val anonInner = expectName(test3 + in.U, name) } NoReturnFunction() @@ -126,8 +127,8 @@ class NamedModule extends NamedModuleTester { class NameCollisionModule extends NamedModuleTester { @chiselName def repeatedCalls(id: Int): UInt = { - val test = expectName(1.U + 3.U, s"test_$id") // should disambiguate by invocation order - test + 2.U + val test = expectName(1.U + 3.U, s"test_$id") // should disambiguate by invocation order + test + 2.U } // chiselName applied by default to this @@ -167,7 +168,7 @@ object NonNamedHelper { myVal } - def NonNamedFunction() : UInt = { + def NonNamedFunction(): UInt = { val myVal = NamedFunction() myVal } @@ -230,7 +231,6 @@ class NoChiselNamePrefixTester extends NamedModuleTester { expectName(fizz.c, "fizz_c") } - /** A simple test that checks the recursive function val naming annotation both compiles and * generates the expected names. */ @@ -265,7 +265,7 @@ class NamingAnnotationSpec extends ChiselPropSpec { } property("NonBuilderFunction should run outside a Builder context") { - NonNamedHelper.NonBuilderFunction() should be (2) + NonNamedHelper.NonBuilderFunction() should be(2) } property("NoChiselNamePrefix should prevent prefixing when using @chiselName") { diff --git a/src/test/scala/chiselTests/OneHotMuxSpec.scala b/src/test/scala/chiselTests/OneHotMuxSpec.scala index 7608a3e7..b069b219 100644 --- a/src/test/scala/chiselTests/OneHotMuxSpec.scala +++ b/src/test/scala/chiselTests/OneHotMuxSpec.scala @@ -11,7 +11,6 @@ import org.scalatest._ import org.scalatest.freespec.AnyFreeSpec import org.scalatest.matchers.should.Matchers - class OneHotMuxSpec extends AnyFreeSpec with Matchers with ChiselRunners { "simple one hot mux with uint should work" in { assertTesterPasses(new SimpleOneHotTester) @@ -32,7 +31,7 @@ class OneHotMuxSpec extends AnyFreeSpec with Matchers with ChiselRunners { assertTesterPasses(new ParameterizedAggregateOneHotTester) } "simple one hot mux with all aggregates containing inferred width fixed values should NOT work" in { - intercept [ChiselException] { + intercept[ChiselException] { assertTesterPasses(new InferredWidthAggregateOneHotTester) } } @@ -56,12 +55,14 @@ class OneHotMuxSpec extends AnyFreeSpec with Matchers with ChiselRunners { class SimpleOneHotTester extends BasicTester { val out = Wire(UInt()) - out := Mux1H(Seq( - false.B -> 2.U, - false.B -> 4.U, - true.B -> 8.U, - false.B -> 11.U - )) + out := Mux1H( + Seq( + false.B -> 2.U, + false.B -> 4.U, + true.B -> 8.U, + false.B -> 11.U + ) + ) assert(out === 8.U) @@ -70,12 +71,14 @@ class SimpleOneHotTester extends BasicTester { class SIntOneHotTester extends BasicTester { val out = Wire(SInt()) - out := Mux1H(Seq( - false.B -> (-3).S, - true.B -> (-5).S, - false.B -> (-7).S, - false.B -> (-11).S - )) + out := Mux1H( + Seq( + false.B -> (-3).S, + true.B -> (-5).S, + false.B -> (-7).S, + false.B -> (-11).S + ) + ) assert(out === (-5).S) @@ -85,12 +88,14 @@ class SIntOneHotTester extends BasicTester { class FixedPointOneHotTester extends BasicTester { val out = Wire(FixedPoint(8.W, 4.BP)) - out := Mux1H(Seq( - false.B -> (-1.5).F(1.BP), - true.B -> (-2.25).F(2.BP), - false.B -> (-4.125).F(3.BP), - false.B -> (-11.625).F(3.BP) - )) + out := Mux1H( + Seq( + false.B -> (-1.5).F(1.BP), + true.B -> (-2.25).F(2.BP), + false.B -> (-4.125).F(3.BP), + false.B -> (-11.625).F(3.BP) + ) + ) assert(out === (-2.25).F(4.BP)) @@ -100,12 +105,14 @@ class FixedPointOneHotTester extends BasicTester { class AllSameFixedPointOneHotTester extends BasicTester { val out = Wire(FixedPoint(12.W, 3.BP)) - out := Mux1H(Seq( - false.B -> (-1.5).F(12.W, 3.BP), - true.B -> (-2.25).F(12.W, 3.BP), - false.B -> (-4.125).F(12.W, 3.BP), - false.B -> (-11.625).F(12.W, 3.BP) - )) + out := Mux1H( + Seq( + false.B -> (-1.5).F(12.W, 3.BP), + true.B -> (-2.25).F(12.W, 3.BP), + false.B -> (-4.125).F(12.W, 3.BP), + false.B -> (-11.625).F(12.W, 3.BP) + ) + ) assert(out === (-2.25).F(14.W, 4.BP)) @@ -199,7 +206,6 @@ class ParameterizedAggregateOneHot[T <: Data](valGen: HasMakeLit[T], outGen: T) val out = Output(outGen) }) - val values = (0 until 4).map { n => valGen.makeLit(n) } val terms = io.selectors.zip(values) io.out := Mux1H(terms) @@ -229,22 +235,26 @@ class InferredWidthAggregateOneHotTester extends BasicTester { b3.a := -0.0078125.F(7.BP) b3.b.c := -0.00390625.F(8.BP) - val o1 = Mux1H(Seq( - false.B -> b0, - false.B -> b1, - true.B -> b2, - false.B -> b3 - )) + val o1 = Mux1H( + Seq( + false.B -> b0, + false.B -> b1, + true.B -> b2, + false.B -> b3 + ) + ) assert(o1.a === -0.015625.F(5.BP)) assert(o1.b.c === -0.0078125.F(6.BP)) - val o2 = Mux1H(Seq( - false.B -> b0, - true.B -> b1, - false.B -> b2, - false.B -> b3 - )) + val o2 = Mux1H( + Seq( + false.B -> b0, + true.B -> b1, + false.B -> b2, + false.B -> b3 + ) + ) assert(o2.a === -0.0625.F(3.BP)) assert(o2.b.c === -0.03125.F(4.BP)) @@ -283,12 +293,14 @@ class DifferentBundleOneHotTester extends BasicTester { b3.a := -0.0078125.F(7.BP) b3.b.c := -0.00390625.F(8.BP) - val o1 = Mux1H(Seq( - false.B -> b0, - false.B -> b1, - true.B -> b2, - false.B -> b3 - )) + val o1 = Mux1H( + Seq( + false.B -> b0, + false.B -> b1, + true.B -> b2, + false.B -> b3 + ) + ) stop() } diff --git a/src/test/scala/chiselTests/OptionBundle.scala b/src/test/scala/chiselTests/OptionBundle.scala index 0f3502a4..628e117d 100644 --- a/src/test/scala/chiselTests/OptionBundle.scala +++ b/src/test/scala/chiselTests/OptionBundle.scala @@ -55,7 +55,7 @@ class OptionBundleSpec extends ChiselFlatSpec with Utils { } "A Bundle with an Option field" should "assert out accessing a None Option field" in { - a [Exception] should be thrownBy extractCause[Exception] { + a[Exception] should be thrownBy extractCause[Exception] { ChiselStage.elaborate { new InvalidOptionBundleTester() } } } diff --git a/src/test/scala/chiselTests/Padding.scala b/src/test/scala/chiselTests/Padding.scala index cb1da0b0..7950c203 100644 --- a/src/test/scala/chiselTests/Padding.scala +++ b/src/test/scala/chiselTests/Padding.scala @@ -7,7 +7,7 @@ import chisel3.stage.ChiselStage class Padder extends Module { val io = IO(new Bundle { - val a = Input(UInt(4.W)) + val a = Input(UInt(4.W)) val asp = Output(SInt(8.W)) val aup = Output(UInt(8.W)) }) @@ -31,7 +31,7 @@ class PadsTester(c: Pads) extends Tester(c) { expect(c.io.aup, test_a) } } -*/ + */ class PadderSpec extends ChiselPropSpec { @@ -39,5 +39,5 @@ class PadderSpec extends ChiselPropSpec { ChiselStage.elaborate { new Padder } } - ignore("PadderTester should return the correct result") { } + ignore("PadderTester should return the correct result") {} } diff --git a/src/test/scala/chiselTests/ParameterizedModule.scala b/src/test/scala/chiselTests/ParameterizedModule.scala index 3016728d..3ad054f8 100644 --- a/src/test/scala/chiselTests/ParameterizedModule.scala +++ b/src/test/scala/chiselTests/ParameterizedModule.scala @@ -7,7 +7,7 @@ import chisel3.testers.BasicTester class ParameterizedModule(invert: Boolean) extends Module { val io = IO(new Bundle { - val in = Input(Bool()) + val in = Input(Bool()) val out = Output(Bool()) }) if (invert) { diff --git a/src/test/scala/chiselTests/PopCount.scala b/src/test/scala/chiselTests/PopCount.scala index 42609dff..eaea7a2c 100644 --- a/src/test/scala/chiselTests/PopCount.scala +++ b/src/test/scala/chiselTests/PopCount.scala @@ -9,7 +9,7 @@ import chisel3.testers.BasicTester class PopCountTester(n: Int) extends BasicTester { val x = RegInit(0.U(n.W)) x := x + 1.U - when (RegNext(x === ~0.U(n.W))) { stop() } + when(RegNext(x === ~0.U(n.W))) { stop() } val result = PopCount(x.asBools) val expected = x.asBools.foldLeft(0.U)(_ +& _) @@ -20,6 +20,6 @@ class PopCountTester(n: Int) extends BasicTester { class PopCountSpec extends ChiselPropSpec { property("Mul lookup table should return the correct result") { - forAll(smallPosInts) { (n: Int) => assertTesterPasses { new PopCountTester(n) } } + forAll(smallPosInts) { (n: Int) => assertTesterPasses { new PopCountTester(n) } } } } diff --git a/src/test/scala/chiselTests/PrintableSpec.scala b/src/test/scala/chiselTests/PrintableSpec.scala index c7e819ec..7d584cea 100644 --- a/src/test/scala/chiselTests/PrintableSpec.scala +++ b/src/test/scala/chiselTests/PrintableSpec.scala @@ -20,6 +20,7 @@ case class PrintfAnnotation(target: ReferenceTarget) extends SingleTargetAnnotat } object PrintfAnnotation { + /** Create annotation for a given [[printf]]. * @param c component to be annotated */ @@ -38,7 +39,7 @@ class PrintableSpec extends AnyFlatSpec with Matchers { private case class Printf(str: String, args: Seq[String]) private def getPrintfs(firrtl: String): Seq[Printf] = { def processArgs(str: String): Seq[String] = - str split "," map (_.trim) filter (_.nonEmpty) + str.split(",").map(_.trim).filter(_.nonEmpty) def processBody(str: String): (String, Seq[String]) = { str match { case StringRegex(_, fmt, args) => @@ -47,14 +48,14 @@ class PrintableSpec extends AnyFlatSpec with Matchers { } } - firrtl split "\n" collect { + firrtl.split("\n").collect { case PrintfRegex(matched) => val (str, args) = processBody(matched) Printf(str, args) } } - behavior of "Printable & Custom Interpolator" + behavior.of("Printable & Custom Interpolator") it should "pass exact strings through" in { class MyModule extends BasicTester { @@ -63,7 +64,7 @@ class PrintableSpec extends AnyFlatSpec with Matchers { val firrtl = ChiselStage.emitChirrtl(new MyModule) getPrintfs(firrtl) match { case Seq(Printf("An exact string", Seq())) => - case e => fail() + case e => fail() } } it should "handle Printable and String concatination" in { @@ -73,7 +74,7 @@ class PrintableSpec extends AnyFlatSpec with Matchers { val firrtl = ChiselStage.emitChirrtl(new MyModule) getPrintfs(firrtl) match { case Seq(Printf("First Second Third", Seq())) => - case e => fail() + case e => fail() } } it should "call toString on non-Printable objects" in { @@ -84,7 +85,7 @@ class PrintableSpec extends AnyFlatSpec with Matchers { val firrtl = ChiselStage.emitChirrtl(new MyModule) getPrintfs(firrtl) match { case Seq(Printf("myInt = 1234", Seq())) => - case e => fail() + case e => fail() } } it should "generate proper printf for simple Decimal printing" in { @@ -95,7 +96,7 @@ class PrintableSpec extends AnyFlatSpec with Matchers { val firrtl = ChiselStage.emitChirrtl(new MyModule) getPrintfs(firrtl) match { case Seq(Printf("myWire = %d", Seq("myWire"))) => - case e => fail() + case e => fail() } } it should "handle printing literals" in { @@ -116,7 +117,7 @@ class PrintableSpec extends AnyFlatSpec with Matchers { val firrtl = ChiselStage.emitChirrtl(new MyModule) getPrintfs(firrtl) match { case Seq(Printf("%%", Seq())) => - case e => fail() + case e => fail() } } it should "correctly emit tab" in { @@ -126,7 +127,7 @@ class PrintableSpec extends AnyFlatSpec with Matchers { val firrtl = ChiselStage.emitChirrtl(new MyModule) getPrintfs(firrtl) match { case Seq(Printf("\\t", Seq())) => - case e => fail() + case e => fail() } } it should "support names of circuit elements including submodule IO" in { @@ -150,10 +151,8 @@ class PrintableSpec extends AnyFlatSpec with Matchers { } val firrtl = ChiselStage.emitChirrtl(new MyModule) getPrintfs(firrtl) match { - case Seq(Printf("foo", Seq()), - Printf("myWire.foo", Seq()), - Printf("myInst.io.fizz", Seq())) => - case e => fail() + case Seq(Printf("foo", Seq()), Printf("myWire.foo", Seq()), Printf("myInst.io.fizz", Seq())) => + case e => fail() } } it should "handle printing ports of submodules" in { @@ -169,7 +168,7 @@ class PrintableSpec extends AnyFlatSpec with Matchers { val firrtl = ChiselStage.emitChirrtl(new MyModule) getPrintfs(firrtl) match { case Seq(Printf("%d", Seq("myInst.io.fizz"))) => - case e => fail() + case e => fail() } } it should "print UInts and SInts as Decimal by default" in { @@ -181,20 +180,19 @@ class PrintableSpec extends AnyFlatSpec with Matchers { val firrtl = ChiselStage.emitChirrtl(new MyModule) getPrintfs(firrtl) match { case Seq(Printf("%d & %d", Seq("myUInt", "mySInt"))) => - case e => fail() + case e => fail() } } it should "print Vecs like Scala Seqs by default" in { class MyModule extends BasicTester { val myVec = Wire(Vec(4, UInt(32.W))) - myVec foreach (_ := 0.U) + myVec.foreach(_ := 0.U) printf(p"$myVec") } val firrtl = ChiselStage.emitChirrtl(new MyModule) getPrintfs(firrtl) match { - case Seq(Printf("Vec(%d, %d, %d, %d)", - Seq("myVec[0]", "myVec[1]", "myVec[2]", "myVec[3]"))) => - case e => fail() + case Seq(Printf("Vec(%d, %d, %d, %d)", Seq("myVec[0]", "myVec[1]", "myVec[2]", "myVec[3]"))) => + case e => fail() } } it should "print Bundles like Scala Maps by default" in { @@ -209,9 +207,8 @@ class PrintableSpec extends AnyFlatSpec with Matchers { } val firrtl = ChiselStage.emitChirrtl(new MyModule) getPrintfs(firrtl) match { - case Seq(Printf("AnonymousBundle(foo -> %d, bar -> %d)", - Seq("myBun.foo", "myBun.bar"))) => - case e => fail() + case Seq(Printf("AnonymousBundle(foo -> %d, bar -> %d)", Seq("myBun.foo", "myBun.bar"))) => + case e => fail() } } it should "get emitted with a name and annotated" in { @@ -243,10 +240,10 @@ class PrintableSpec extends AnyFlatSpec with Matchers { val annoLines = scala.io.Source.fromFile(annoFile).getLines.toList // check for expected annotations - exactly(3, annoLines) should include ("chiselTests.PrintfAnnotation") - exactly(1, annoLines) should include ("~PrintfAnnotationTest|PrintfAnnotationTest>farewell") - exactly(1, annoLines) should include ("~PrintfAnnotationTest|PrintfAnnotationTest>printf") - exactly(1, annoLines) should include ("~PrintfAnnotationTest|PrintfAnnotationTest>howdy") + exactly(3, annoLines) should include("chiselTests.PrintfAnnotation") + exactly(1, annoLines) should include("~PrintfAnnotationTest|PrintfAnnotationTest>farewell") + exactly(1, annoLines) should include("~PrintfAnnotationTest|PrintfAnnotationTest>printf") + exactly(1, annoLines) should include("~PrintfAnnotationTest|PrintfAnnotationTest>howdy") // read in FIRRTL file val firFile = new File(testDir, "PrintfAnnotationTest.fir") @@ -254,8 +251,14 @@ class PrintableSpec extends AnyFlatSpec with Matchers { val firLines = scala.io.Source.fromFile(firFile).getLines.toList // check that verification components have expected names - exactly(1, firLines) should include ("""printf(clock, UInt<1>("h1"), "hello AnonymousBundle(foo -> %d, bar -> %d)", myBun.foo, myBun.bar) : howdy""") - exactly(1, firLines) should include ("""printf(clock, UInt<1>("h1"), "goodbye AnonymousBundle(foo -> %d, bar -> %d)", myBun.foo, myBun.bar) : printf""") - exactly(1, firLines) should include ("""printf(clock, UInt<1>("h1"), "adieu AnonymousBundle(foo -> %d, bar -> %d)", myBun.foo, myBun.bar) : farewell""") + exactly(1, firLines) should include( + """printf(clock, UInt<1>("h1"), "hello AnonymousBundle(foo -> %d, bar -> %d)", myBun.foo, myBun.bar) : howdy""" + ) + exactly(1, firLines) should include( + """printf(clock, UInt<1>("h1"), "goodbye AnonymousBundle(foo -> %d, bar -> %d)", myBun.foo, myBun.bar) : printf""" + ) + exactly(1, firLines) should include( + """printf(clock, UInt<1>("h1"), "adieu AnonymousBundle(foo -> %d, bar -> %d)", myBun.foo, myBun.bar) : farewell""" + ) } } diff --git a/src/test/scala/chiselTests/Printf.scala b/src/test/scala/chiselTests/Printf.scala index 24b5e090..4171f97f 100644 --- a/src/test/scala/chiselTests/Printf.scala +++ b/src/test/scala/chiselTests/Printf.scala @@ -24,7 +24,7 @@ class MultiPrintfTester() extends BasicTester { } class ASCIIPrintableTester extends BasicTester { - printf(PString((0x20 to 0x7e) map (_.toChar) mkString "")) + printf(PString((0x20 to 0x7e).map(_.toChar).mkString(""))) stop() } diff --git a/src/test/scala/chiselTests/QueueFlushSpec.scala b/src/test/scala/chiselTests/QueueFlushSpec.scala index 9e0c6bb4..d70f9605 100644 --- a/src/test/scala/chiselTests/QueueFlushSpec.scala +++ b/src/test/scala/chiselTests/QueueFlushSpec.scala @@ -9,24 +9,36 @@ import chisel3.util.random.LFSR import treadle.WriteVcdAnnotation /** Test elements can be enqueued and dequeued when flush is tied to false - * + * * @param elements The sequence of elements used in the queue * @param queueDepth The max number of entries in the queue * @param bitWidth Integer size of the data type used in the queue * @param tap Integer tap('seed') for the LFSR * @param useSyncReadMem True uses SyncReadMem instead of Mem as an internal memory element */ -class ThingsPassThroughFlushQueueTester(elements: Seq[Int], queueDepth: Int, bitWidth: Int, tap: Int, useSyncReadMem: Boolean) extends ThingsPassThroughTester(elements, queueDepth, bitWidth, tap, useSyncReadMem, hasFlush = true) +class ThingsPassThroughFlushQueueTester( + elements: Seq[Int], + queueDepth: Int, + bitWidth: Int, + tap: Int, + useSyncReadMem: Boolean) + extends ThingsPassThroughTester(elements, queueDepth, bitWidth, tap, useSyncReadMem, hasFlush = true) /** Generic flush queue tester base class - * + * * @param elements The sequence of elements used in the queue * @param queueDepth The max number of entries in the queue * @param bitWidth Integer size of the data type used in the queue * @param tap Integer tap('seed') for the LFSR * @param useSyncReadMem True uses SyncReadMem instead of Mem as an internal memory element */ -abstract class FlushQueueTesterBase(elements: Seq[Int], queueDepth: Int, bitWidth: Int, tap: Int, useSyncReadMem: Boolean) extends BasicTester { +abstract class FlushQueueTesterBase( + elements: Seq[Int], + queueDepth: Int, + bitWidth: Int, + tap: Int, + useSyncReadMem: Boolean) + extends BasicTester { val q = Module(new Queue(UInt(bitWidth.W), queueDepth, hasFlush = true)) val elems = VecInit(elements.map(_.U)) val inCnt = Counter(elements.length + 1) @@ -51,31 +63,35 @@ abstract class FlushQueueTesterBase(elements: Seq[Int], queueDepth: Int, bitWidt //check that queue gets flushed when queue is full assert(q.io.count === 0.U) assert(!q.io.deq.valid, "Expected to not be able to dequeue when flush is asserted the previous cycle") - assert(q.io.enq.ready, "Expected enqueue to be ready when flush was asserted the previous cycle because queue should be empty") - } + assert( + q.io.enq.ready, + "Expected enqueue to be ready when flush was asserted the previous cycle because queue should be empty" + ) + } when(inCnt.value === elements.length.U) { //stop when all entries are enqueued stop() } } /** Test queue can flush at random times - * + * * @param elements The sequence of elements used in the queue * @param queueDepth The max number of entries in the queue * @param bitWidth Integer size of the data type used in the queue * @param tap Integer tap('seed') for the LFSR * @param useSyncReadMem True uses SyncReadMem instead of Mem as an internal memory element */ -class QueueGetsFlushedTester(elements: Seq[Int], queueDepth: Int, bitWidth: Int, tap: Int, useSyncReadMem: Boolean) extends FlushQueueTesterBase(elements, queueDepth, bitWidth, tap, useSyncReadMem) { - flush := LFSR(16)((tap + 3) % 16) //testing a flush when flush is called randomly - val halfCnt = (queueDepth + 1)/2 +class QueueGetsFlushedTester(elements: Seq[Int], queueDepth: Int, bitWidth: Int, tap: Int, useSyncReadMem: Boolean) + extends FlushQueueTesterBase(elements, queueDepth, bitWidth, tap, useSyncReadMem) { + flush := LFSR(16)((tap + 3) % 16) //testing a flush when flush is called randomly + val halfCnt = (queueDepth + 1) / 2 when(q.io.deq.fire) { //ensure that what comes out is what comes in assert(currQCnt <= queueDepth.U) assert(elems(outCnt) === q.io.deq.bits) outCnt := outCnt + 1.U - when (currQCnt > 0.U) { + when(currQCnt > 0.U) { currQCnt := Mux(q.io.enq.fire, currQCnt, (currQCnt - 1.U)) } } @@ -87,19 +103,20 @@ class QueueGetsFlushedTester(elements: Seq[Int], queueDepth: Int, bitWidth: Int, } /** Test queue can flush when empty - * + * * @param elements The sequence of elements used in the queue * @param queueDepth The max number of entries in the queue * @param bitWidth Integer size of the data type used in the queue * @param tap Integer tap('seed') for the LFSR * @param useSyncReadMem True uses SyncReadMem instead of Mem as an internal memory element */ -class EmptyFlushEdgecaseTester (elements: Seq[Int], queueDepth: Int, bitWidth: Int, tap: Int, useSyncReadMem: Boolean) extends FlushQueueTesterBase(elements, queueDepth, bitWidth, tap, useSyncReadMem) { +class EmptyFlushEdgecaseTester(elements: Seq[Int], queueDepth: Int, bitWidth: Int, tap: Int, useSyncReadMem: Boolean) + extends FlushQueueTesterBase(elements, queueDepth, bitWidth, tap, useSyncReadMem) { val cycleCounter = Counter(elements.length + 1) cycleCounter.inc() //counts every cycle //testing a flush when queue is empty - flush := (cycleCounter.value === 0.U && inCnt.value === 0.U) //flushed only before anything is enqueued + flush := (cycleCounter.value === 0.U && inCnt.value === 0.U) //flushed only before anything is enqueued q.io.enq.valid := (inCnt.value < elements.length.U) && !flush when(q.io.deq.fire) { @@ -109,23 +126,29 @@ class EmptyFlushEdgecaseTester (elements: Seq[Int], queueDepth: Int, bitWidth: I } /** Test queue can enqueue during a flush - * + * * @param elements The sequence of elements used in the queue * @param queueDepth The max number of entries in the queue * @param bitWidth Integer size of the data type used in the queue * @param tap Integer tap('seed') for the LFSR * @param useSyncReadMem True uses SyncReadMem instead of Mem as an internal memory element */ -class EnqueueEmptyFlushEdgecaseTester (elements: Seq[Int], queueDepth: Int, bitWidth: Int, tap: Int, useSyncReadMem: Boolean) extends FlushQueueTesterBase(elements, queueDepth, bitWidth, tap, useSyncReadMem) { +class EnqueueEmptyFlushEdgecaseTester( + elements: Seq[Int], + queueDepth: Int, + bitWidth: Int, + tap: Int, + useSyncReadMem: Boolean) + extends FlushQueueTesterBase(elements, queueDepth, bitWidth, tap, useSyncReadMem) { val cycleCounter = Counter(elements.length + 1) val outCounter = Counter(elements.length + 1) //testing an enqueue during a flush - flush := (cycleCounter.value === 0.U && inCnt.value === 0.U) //flushed only before anything is enqueued + flush := (cycleCounter.value === 0.U && inCnt.value === 0.U) //flushed only before anything is enqueued cycleCounter.inc() //counts every cycle when(q.io.deq.fire) { - //flush and enqueue were both active on the first cycle, + //flush and enqueue were both active on the first cycle, //so that element is flushed immediately which makes outCnt off by one assert(elems(outCounter.value + 1.U) === q.io.deq.bits) //ensure that what comes out is what comes in outCounter.inc() @@ -133,14 +156,20 @@ class EnqueueEmptyFlushEdgecaseTester (elements: Seq[Int], queueDepth: Int, bitW } /** Test queue can flush when full - * + * * @param elements The sequence of elements used in the queue * @param queueDepth The max number of entries in the queue * @param bitWidth Integer size of the data type used in the queue * @param tap Integer tap('seed') for the LFSR * @param useSyncReadMem True uses SyncReadMem instead of Mem as an internal memory element */ -class FullQueueFlushEdgecaseTester (elements: Seq[Int], queueDepth: Int, bitWidth: Int, tap: Int, useSyncReadMem: Boolean) extends FlushQueueTesterBase(elements, queueDepth, bitWidth, tap, useSyncReadMem) { +class FullQueueFlushEdgecaseTester( + elements: Seq[Int], + queueDepth: Int, + bitWidth: Int, + tap: Int, + useSyncReadMem: Boolean) + extends FlushQueueTesterBase(elements, queueDepth, bitWidth, tap, useSyncReadMem) { //testing a flush when queue is full flush := (currQCnt === queueDepth.U) @@ -150,7 +179,7 @@ class FullQueueFlushEdgecaseTester (elements: Seq[Int], queueDepth: Int, bitWidt assert(currQCnt <= queueDepth.U) assert(elems(outCnt) === q.io.deq.bits) outCnt := outCnt + 1.U - when (currQCnt > 0.U) { + when(currQCnt > 0.U) { currQCnt := currQCnt - 1.U } } @@ -162,18 +191,24 @@ class FullQueueFlushEdgecaseTester (elements: Seq[Int], queueDepth: Int, bitWidt } /** Test queue can dequeue on the same cycle as a flush - * + * * @param elements The sequence of elements used in the queue * @param queueDepth The max number of entries in the queue * @param bitWidth Integer size of the data type used in the queue * @param tap Integer tap('seed') for the LFSR * @param useSyncReadMem True uses SyncReadMem instead of Mem as an internal memory element */ -class DequeueFullQueueEdgecaseTester (elements: Seq[Int], queueDepth: Int, bitWidth: Int, tap: Int, useSyncReadMem: Boolean) extends FlushQueueTesterBase(elements, queueDepth, bitWidth, tap, useSyncReadMem) { +class DequeueFullQueueEdgecaseTester( + elements: Seq[Int], + queueDepth: Int, + bitWidth: Int, + tap: Int, + useSyncReadMem: Boolean) + extends FlushQueueTesterBase(elements, queueDepth, bitWidth, tap, useSyncReadMem) { //Queue should be able to dequeue when queue is not empty and flush is high //testing a flush when dequeue is called - flush := currQCnt === (queueDepth/2).U + flush := currQCnt === (queueDepth / 2).U q.io.enq.valid := !flushRegister q.io.deq.ready := flush @@ -185,14 +220,14 @@ class DequeueFullQueueEdgecaseTester (elements: Seq[Int], queueDepth: Int, bitWi } when(flush) { //The outcount register is one count behind because the dequeue happens at the same time as the flush - outCnt := outCnt + currQCnt + 1.U + outCnt := outCnt + currQCnt + 1.U currQCnt := 0.U //resets the number of items currently inside queue assert(currQCnt === 0.U || q.io.deq.valid) } when(flushRegister) { //check that queue gets flushed when queue is full assert(q.io.deq.fire === false.B) - } + } } @@ -200,7 +235,7 @@ class QueueFlushSpec extends ChiselPropSpec { // Disable shrinking on error. implicit val noShrinkListVal = Shrink[List[Int]](_ => Stream.empty) implicit val noShrinkInt = Shrink[Int](_ => Stream.empty) - + property("Queue should have things pass through") { forAll(vecSizes, safeUIntN(20), Gen.choose(0, 15), Gen.oneOf(true, false)) { (depth, se, tap, isSync) => whenever(se._1 >= 1 && depth >= 1 && se._2.nonEmpty) { @@ -249,7 +284,7 @@ class QueueFlushSpec extends ChiselPropSpec { property("Queue should be able to dequeue when flush is high") { forAll(Gen.choose(3, 5), safeUIntN(20), Gen.choose(0, 15), Gen.oneOf(true, false)) { (depth, se, tap, isSync) => whenever(se._1 >= 1 && depth >= 1 && se._2.nonEmpty) { - assertTesterPasses ( + assertTesterPasses( new DequeueFullQueueEdgecaseTester(se._2, depth, se._1, tap, isSync), annotations = Seq(WriteVcdAnnotation) ) diff --git a/src/test/scala/chiselTests/QueueSpec.scala b/src/test/scala/chiselTests/QueueSpec.scala index 9eb6c20c..eaeb7f01 100644 --- a/src/test/scala/chiselTests/QueueSpec.scala +++ b/src/test/scala/chiselTests/QueueSpec.scala @@ -9,7 +9,14 @@ import chisel3.testers.BasicTester import chisel3.util._ import chisel3.util.random.LFSR -class ThingsPassThroughTester(elements: Seq[Int], queueDepth: Int, bitWidth: Int, tap: Int, useSyncReadMem: Boolean, hasFlush: Boolean) extends BasicTester { +class ThingsPassThroughTester( + elements: Seq[Int], + queueDepth: Int, + bitWidth: Int, + tap: Int, + useSyncReadMem: Boolean, + hasFlush: Boolean) + extends BasicTester { val q = Module(new Queue(UInt(bitWidth.W), queueDepth, useSyncReadMem = useSyncReadMem, hasFlush = hasFlush)) val elems = VecInit(elements.map { _.asUInt() @@ -34,7 +41,8 @@ class ThingsPassThroughTester(elements: Seq[Int], queueDepth: Int, bitWidth: Int } } -class QueueReasonableReadyValid(elements: Seq[Int], queueDepth: Int, bitWidth: Int, tap: Int, useSyncReadMem: Boolean) extends BasicTester { +class QueueReasonableReadyValid(elements: Seq[Int], queueDepth: Int, bitWidth: Int, tap: Int, useSyncReadMem: Boolean) + extends BasicTester { val q = Module(new Queue(UInt(bitWidth.W), queueDepth, useSyncReadMem = useSyncReadMem)) val elems = VecInit(elements.map { _.asUInt() @@ -62,7 +70,8 @@ class QueueReasonableReadyValid(elements: Seq[Int], queueDepth: Int, bitWidth: I } } -class CountIsCorrectTester(elements: Seq[Int], queueDepth: Int, bitWidth: Int, tap: Int, useSyncReadMem: Boolean) extends BasicTester { +class CountIsCorrectTester(elements: Seq[Int], queueDepth: Int, bitWidth: Int, tap: Int, useSyncReadMem: Boolean) + extends BasicTester { val q = Module(new Queue(UInt(bitWidth.W), queueDepth, useSyncReadMem = useSyncReadMem)) val elems = VecInit(elements.map { _.asUInt(bitWidth.W) @@ -115,7 +124,8 @@ class QueueSinglePipeTester(elements: Seq[Int], bitWidth: Int, tap: Int, useSync } } -class QueuePipeTester(elements: Seq[Int], queueDepth: Int, bitWidth: Int, tap: Int, useSyncReadMem: Boolean) extends BasicTester { +class QueuePipeTester(elements: Seq[Int], queueDepth: Int, bitWidth: Int, tap: Int, useSyncReadMem: Boolean) + extends BasicTester { val q = Module(new Queue(UInt(bitWidth.W), queueDepth, pipe = true, useSyncReadMem = useSyncReadMem)) val elems = VecInit(elements.map { _.asUInt(bitWidth.W) @@ -141,8 +151,9 @@ class QueuePipeTester(elements: Seq[Int], queueDepth: Int, bitWidth: Int, tap: I } } -class QueueFlowTester(elements: Seq[Int], queueDepth: Int, bitWidth: Int, tap: Int, useSyncReadMem: Boolean) extends BasicTester { - val q = Module(new Queue(UInt(bitWidth.W), queueDepth, flow = true, useSyncReadMem = useSyncReadMem)) +class QueueFlowTester(elements: Seq[Int], queueDepth: Int, bitWidth: Int, tap: Int, useSyncReadMem: Boolean) + extends BasicTester { + val q = Module(new Queue(UInt(bitWidth.W), queueDepth, flow = true, useSyncReadMem = useSyncReadMem)) val elems = VecInit(elements.map { _.asUInt() }) @@ -169,7 +180,8 @@ class QueueFlowTester(elements: Seq[Int], queueDepth: Int, bitWidth: Int, tap: I } } -class QueueFactoryTester(elements: Seq[Int], queueDepth: Int, bitWidth: Int, tap: Int, useSyncReadMem: Boolean) extends BasicTester { +class QueueFactoryTester(elements: Seq[Int], queueDepth: Int, bitWidth: Int, tap: Int, useSyncReadMem: Boolean) + extends BasicTester { val enq = Wire(Decoupled(UInt(bitWidth.W))) val deq = Queue(enq, queueDepth, useSyncReadMem = useSyncReadMem) @@ -276,6 +288,7 @@ class QueueSpec extends ChiselPropSpec { val in = Wire(Decoupled(Bool())) val iQueue = Queue.irrevocable(in, 1) } - (new chisel3.stage.phases.Elaborate).transform(Seq(chisel3.stage.ChiselGeneratorAnnotation(() => new IrrevocableQueue))) + (new chisel3.stage.phases.Elaborate) + .transform(Seq(chisel3.stage.ChiselGeneratorAnnotation(() => new IrrevocableQueue))) } } diff --git a/src/test/scala/chiselTests/RangeSpec.scala b/src/test/scala/chiselTests/RangeSpec.scala index 0b888ab6..bc723bf6 100644 --- a/src/test/scala/chiselTests/RangeSpec.scala +++ b/src/test/scala/chiselTests/RangeSpec.scala @@ -9,5 +9,4 @@ import firrtl.ir.{Closed, Open} import org.scalatest.freespec.AnyFreeSpec import org.scalatest.matchers.should.Matchers -class RangeSpec extends AnyFreeSpec with Matchers { -} +class RangeSpec extends AnyFreeSpec with Matchers {} diff --git a/src/test/scala/chiselTests/RawModuleSpec.scala b/src/test/scala/chiselTests/RawModuleSpec.scala index 3d678d1f..95687e82 100644 --- a/src/test/scala/chiselTests/RawModuleSpec.scala +++ b/src/test/scala/chiselTests/RawModuleSpec.scala @@ -7,7 +7,7 @@ import chisel3.stage.ChiselStage import chisel3.testers.BasicTester class UnclockedPlusOne extends RawModule { - val in = IO(Input(UInt(32.W))) + val in = IO(Input(UInt(32.W))) val out = IO(Output(UInt(32.W))) out := in + 1.asUInt @@ -22,14 +22,14 @@ class RawModuleTester extends BasicTester { class PlusOneModule extends Module { val io = IO(new Bundle { - val in = Input(UInt(32.W)) + val in = Input(UInt(32.W)) val out = Output(UInt(32.W)) }) io.out := io.in + 1.asUInt } class RawModuleWithImplicitModule extends RawModule { - val in = IO(Input(UInt(32.W))) + val in = IO(Input(UInt(32.W))) val out = IO(Output(UInt(32.W))) val clk = IO(Input(Clock())) val rst = IO(Input(Bool())) @@ -72,7 +72,6 @@ class RawModuleSpec extends ChiselFlatSpec with Utils { assertTesterPasses({ new ImplicitModuleInRawModuleTester }) } - "ImplicitModule directly in a RawModule" should "fail" in { intercept[chisel3.internal.ChiselException] { extractCause[ChiselException] { diff --git a/src/test/scala/chiselTests/RebindingSpec.scala b/src/test/scala/chiselTests/RebindingSpec.scala index 808b1137..5dc0589e 100644 --- a/src/test/scala/chiselTests/RebindingSpec.scala +++ b/src/test/scala/chiselTests/RebindingSpec.scala @@ -7,22 +7,26 @@ import chisel3.stage.ChiselStage class RebindingSpec extends ChiselFlatSpec with Utils { "Rebinding a literal" should "fail" in { - a [BindingException] should be thrownBy extractCause[BindingException] { - ChiselStage.elaborate { new Module { - val io = IO(new Bundle { - val a = 4.U - }) - } } + a[BindingException] should be thrownBy extractCause[BindingException] { + ChiselStage.elaborate { + new Module { + val io = IO(new Bundle { + val a = 4.U + }) + } + } } } "Rebinding a hardware type" should "fail" in { - a [BindingException] should be thrownBy extractCause[BindingException] { - ChiselStage.elaborate { new Module { - val io = IO(new Bundle { - val a = Reg(UInt(32.W)) - }) - } } + a[BindingException] should be thrownBy extractCause[BindingException] { + ChiselStage.elaborate { + new Module { + val io = IO(new Bundle { + val a = Reg(UInt(32.W)) + }) + } + } } } } diff --git a/src/test/scala/chiselTests/RecordSpec.scala b/src/test/scala/chiselTests/RecordSpec.scala index e6986efb..da3840dd 100644 --- a/src/test/scala/chiselTests/RecordSpec.scala +++ b/src/test/scala/chiselTests/RecordSpec.scala @@ -50,18 +50,18 @@ trait RecordSpecUtils { queue.io.enq.valid := false.B val (cycle, done) = Counter(true.B, 4) - when (cycle === 0.U) { + when(cycle === 0.U) { queue.io.enq.bits("foo") := 1234.U queue.io.enq.bits("bar") := 5678.U queue.io.enq.valid := true.B } - when (cycle === 1.U) { + when(cycle === 1.U) { queue.io.deq.ready := true.B assert(queue.io.deq.valid === true.B) assert(queue.io.deq.bits("foo").asUInt === 1234.U) assert(queue.io.deq.bits("bar").asUInt === 5678.U) } - when (done) { + when(done) { stop() } } @@ -91,16 +91,16 @@ trait RecordSpecUtils { } class RecordTypeTester extends BasicTester { - val wire0 = Wire(new CustomBundle("0"-> UInt(32.W))) - val wire1 = Reg(new CustomBundle("0"-> UInt(32.W))) - val wire2 = Wire(new CustomBundle("1"-> UInt(32.W))) + val wire0 = Wire(new CustomBundle("0" -> UInt(32.W))) + val wire1 = Reg(new CustomBundle("0" -> UInt(32.W))) + val wire2 = Wire(new CustomBundle("1" -> UInt(32.W))) require(DataMirror.checkTypeEquivalence(wire0, wire1)) require(!DataMirror.checkTypeEquivalence(wire1, wire2)) } } class RecordSpec extends ChiselFlatSpec with RecordSpecUtils with Utils { - behavior of "Records" + behavior.of("Records") they should "bulk connect similarly to Bundles" in { ChiselStage.elaborate { new MyModule(fooBarType, fooBarType) } @@ -124,7 +124,7 @@ class RecordSpec extends ChiselFlatSpec with RecordSpecUtils with Utils { } } } - e.getMessage should include ("contains aliased fields named (bar,foo)") + e.getMessage should include("contains aliased fields named (bar,foo)") } they should "follow UInt serialization/deserialization API" in { @@ -144,13 +144,13 @@ class RecordSpec extends ChiselFlatSpec with RecordSpecUtils with Utils { } "Bulk connect on Record" should "check that the fields match" in { - (the [ChiselException] thrownBy extractCause[ChiselException] { + (the[ChiselException] thrownBy extractCause[ChiselException] { ChiselStage.elaborate { new MyModule(fooBarType, new CustomBundle("bar" -> UInt(32.W))) } - }).getMessage should include ("Right Record missing field") + }).getMessage should include("Right Record missing field") - (the [ChiselException] thrownBy extractCause[ChiselException] { + (the[ChiselException] thrownBy extractCause[ChiselException] { ChiselStage.elaborate { new MyModule(new CustomBundle("bar" -> UInt(32.W)), fooBarType) } - }).getMessage should include ("Left Record missing field") + }).getMessage should include("Left Record missing field") } "CustomBundle" should "work like built-in aggregates" in { diff --git a/src/test/scala/chiselTests/Reg.scala b/src/test/scala/chiselTests/Reg.scala index a02e6fa5..c814a030 100644 --- a/src/test/scala/chiselTests/Reg.scala +++ b/src/test/scala/chiselTests/Reg.scala @@ -13,19 +13,19 @@ class RegSpec extends ChiselFlatSpec { "Reg" should "be of the same type and width as t" in { class RegOutTypeWidthTester extends BasicTester { val reg = Reg(UInt(2.W)) - DataMirror.widthOf(reg) should be (2.W) + DataMirror.widthOf(reg) should be(2.W) } - ChiselStage.elaborate{ new RegOutTypeWidthTester } + ChiselStage.elaborate { new RegOutTypeWidthTester } } "RegNext" should "be of unknown width" in { class RegUnknownWidthTester extends BasicTester { val reg1 = RegNext(2.U(3.W)) - DataMirror.widthOf(reg1).known should be (false) + DataMirror.widthOf(reg1).known should be(false) val reg2 = RegNext(2.U(3.W), 4.U) - DataMirror.widthOf(reg2).known should be (false) + DataMirror.widthOf(reg2).known should be(false) val reg3 = RegNext(2.U(3.W), 4.U(5.W)) - DataMirror.widthOf(reg3).known should be (false) + DataMirror.widthOf(reg3).known should be(false) } ChiselStage.elaborate { new RegUnknownWidthTester } } @@ -33,11 +33,11 @@ class RegSpec extends ChiselFlatSpec { "RegInit" should "have width only if specified in the literal" in { class RegForcedWidthTester extends BasicTester { val reg1 = RegInit(20.U) - DataMirror.widthOf(reg1).known should be (false) + DataMirror.widthOf(reg1).known should be(false) val reg2 = RegInit(20.U(7.W)) - DataMirror.widthOf(reg2) should be (7.W) + DataMirror.widthOf(reg2) should be(7.W) } - ChiselStage.elaborate{ new RegForcedWidthTester } + ChiselStage.elaborate { new RegForcedWidthTester } } } @@ -52,22 +52,22 @@ class ShiftTester(n: Int) extends BasicTester { } class ShiftResetTester(n: Int) extends BasicTester { - val (cntVal, done) = Counter(true.B, n-1) + val (cntVal, done) = Counter(true.B, n - 1) val start = 23.U val sr = ShiftRegister(cntVal + 23.U, n, 1.U, true.B) when(done) { - assert(sr === (if(n == 0) cntVal + 23.U else 1.U)) + assert(sr === (if (n == 0) cntVal + 23.U else 1.U)) stop() } } class ShiftRegisterSpec extends ChiselPropSpec { property("ShiftRegister should shift") { - forAll(Gen.choose(0, 4)) { (shift: Int) => assertTesterPasses{ new ShiftTester(shift) } } + forAll(Gen.choose(0, 4)) { (shift: Int) => assertTesterPasses { new ShiftTester(shift) } } } property("ShiftRegister should reset all values inside") { - forAll(Gen.choose(0, 4)) { (shift: Int) => assertTesterPasses{ new ShiftResetTester(shift) } } + forAll(Gen.choose(0, 4)) { (shift: Int) => assertTesterPasses { new ShiftResetTester(shift) } } } } @@ -76,8 +76,9 @@ class ShiftsTester(n: Int) extends BasicTester { val start = 23.U val srs = ShiftRegisters(cntVal + start, n) when(RegNext(done)) { - srs.zipWithIndex.foreach{ case (data, index) => - assert(data === (23 + n - 1 - index).U) + srs.zipWithIndex.foreach { + case (data, index) => + assert(data === (23 + n - 1 - index).U) } stop() } @@ -85,6 +86,6 @@ class ShiftsTester(n: Int) extends BasicTester { class ShiftRegistersSpec extends ChiselPropSpec { property("ShiftRegisters should shift") { - forAll(Gen.choose(0, 4)) { (shift: Int) => assertTesterPasses{ new ShiftsTester(shift) } } + forAll(Gen.choose(0, 4)) { (shift: Int) => assertTesterPasses { new ShiftsTester(shift) } } } } diff --git a/src/test/scala/chiselTests/ResetSpec.scala b/src/test/scala/chiselTests/ResetSpec.scala index 7a5d444d..fe0273b3 100644 --- a/src/test/scala/chiselTests/ResetSpec.scala +++ b/src/test/scala/chiselTests/ResetSpec.scala @@ -35,10 +35,9 @@ class AbstractResetDontCareModule extends RawModule { bulkAggPort <> DontCare } - class ResetSpec extends ChiselFlatSpec with Utils { - behavior of "Reset" + behavior.of("Reset") it should "be able to be connected to DontCare" in { ChiselStage.elaborate(new AbstractResetDontCareModule) @@ -75,7 +74,7 @@ class ResetSpec extends ChiselFlatSpec with Utils { assert(inst.rst.isInstanceOf[chisel3.ResetType]) io.out := inst.out }) - sync should include ("always @(posedge clk)") + sync should include("always @(posedge clk)") val async = compile(new Module { val io = IO(new Bundle { @@ -87,27 +86,27 @@ class ResetSpec extends ChiselFlatSpec with Utils { assert(inst.rst.isInstanceOf[chisel3.ResetType]) io.out := inst.out }) - async should include ("always @(posedge clk or posedge rst)") + async should include("always @(posedge clk or posedge rst)") } - behavior of "Users" + behavior.of("Users") they should "be able to force implicit reset to be synchronous" in { val fir = ChiselStage.emitChirrtl(new Module with RequireSyncReset { - reset shouldBe a [Bool] + reset shouldBe a[Bool] }) - fir should include ("input reset : UInt<1>") + fir should include("input reset : UInt<1>") } they should "be able to force implicit reset to be asynchronous" in { val fir = ChiselStage.emitChirrtl(new Module with RequireAsyncReset { - reset shouldBe an [AsyncReset] + reset shouldBe an[AsyncReset] }) - fir should include ("input reset : AsyncReset") + fir should include("input reset : AsyncReset") } "Chisel" should "error if sync and async modules are nested" in { - a [ChiselException] should be thrownBy extractCause[ChiselException] { + a[ChiselException] should be thrownBy extractCause[ChiselException] { ChiselStage.elaborate(new Module with RequireAsyncReset { val mod = Module(new Module with RequireSyncReset) }) diff --git a/src/test/scala/chiselTests/Risc.scala b/src/test/scala/chiselTests/Risc.scala index 74c55a12..e0eacb90 100644 --- a/src/test/scala/chiselTests/Risc.scala +++ b/src/test/scala/chiselTests/Risc.scala @@ -8,47 +8,47 @@ import chisel3.util._ class Risc extends Module { val io = IO(new Bundle { - val isWr = Input(Bool()) + val isWr = Input(Bool()) val wrAddr = Input(UInt(8.W)) val wrData = Input(Bits(32.W)) - val boot = Input(Bool()) - val valid = Output(Bool()) - val out = Output(Bits(32.W)) + val boot = Input(Bool()) + val valid = Output(Bool()) + val out = Output(Bits(32.W)) }) val memSize = 256 val file = Mem(memSize, Bits(32.W)) val code = Mem(memSize, Bits(32.W)) - val pc = RegInit(0.U(8.W)) + val pc = RegInit(0.U(8.W)) val add_op :: imm_op :: Nil = Enum(2) val inst = code(pc) - val op = inst(31,24) - val rci = inst(23,16) - val rai = inst(15, 8) - val rbi = inst( 7, 0) + val op = inst(31, 24) + val rci = inst(23, 16) + val rai = inst(15, 8) + val rbi = inst(7, 0) val ra = Mux(rai === 0.U, 0.U, file(rai)) val rb = Mux(rbi === 0.U, 0.U, file(rbi)) val rc = Wire(Bits(32.W)) io.valid := false.B - io.out := 0.U - rc := 0.U + io.out := 0.U + rc := 0.U - when (io.isWr) { + when(io.isWr) { code(io.wrAddr) := io.wrData - } .elsewhen (io.boot) { + }.elsewhen(io.boot) { pc := 0.U - } .otherwise { + }.otherwise { switch(op) { is(add_op) { rc := ra +% rb } is(imm_op) { rc := (rai << 8) | rbi } } io.out := rc - when (rci === 255.U) { + when(rci === 255.U) { io.valid := true.B - } .otherwise { + }.otherwise { file(rci) := rc } pc := pc +% 1.U @@ -111,7 +111,7 @@ class RiscTester(c: Risc) extends Tester(c) { expect(k <= 10, "TIME LIMIT") expect(c.io.out, 4) } -*/ + */ class RiscSpec extends ChiselPropSpec { @@ -119,5 +119,5 @@ class RiscSpec extends ChiselPropSpec { ChiselStage.elaborate { new Risc } } - ignore("RiscTester should return the correct result") { } + ignore("RiscTester should return the correct result") {} } diff --git a/src/test/scala/chiselTests/SIntOps.scala b/src/test/scala/chiselTests/SIntOps.scala index 222d0ba7..55b4c915 100644 --- a/src/test/scala/chiselTests/SIntOps.scala +++ b/src/test/scala/chiselTests/SIntOps.scala @@ -82,7 +82,7 @@ class SIntOpsTester(c: SIntOps) extends Tester(c) { expect(c.io.greateqout, int(test_a >= test_b)) } } -*/ + */ class SIntLitExtractTester extends BasicTester { assert(-5.S(1) === true.B) @@ -105,12 +105,12 @@ class SIntOpsSpec extends ChiselPropSpec with Utils { } property("Negative shift amounts are invalid") { - a [ChiselException] should be thrownBy extractCause[ChiselException] { + a[ChiselException] should be thrownBy extractCause[ChiselException] { ChiselStage.elaborate(new NegativeShift(SInt())) } } - ignore("SIntOpsTester should return the correct result") { } + ignore("SIntOpsTester should return the correct result") {} property("Bit extraction on literals should work for all non-negative indices") { assertTesterPasses(new SIntLitExtractTester) diff --git a/src/test/scala/chiselTests/ScalaIntervalSimulatorTest.scala b/src/test/scala/chiselTests/ScalaIntervalSimulatorTest.scala index 540cc456..94f5ccc7 100644 --- a/src/test/scala/chiselTests/ScalaIntervalSimulatorTest.scala +++ b/src/test/scala/chiselTests/ScalaIntervalSimulatorTest.scala @@ -11,87 +11,87 @@ class ScalaIntervalSimulatorSpec extends AnyFreeSpec with Matchers { "clip tests" - { "Should work for closed ranges" in { val sim = ScalaIntervalSimulator(range"[2,4]") - sim.clip(BigDecimal(1.0)) should be (2.0) - sim.clip(BigDecimal(2.0)) should be (2.0) - sim.clip(BigDecimal(3.0)) should be (3.0) - sim.clip(BigDecimal(4.0)) should be (4.0) - sim.clip(BigDecimal(5.0)) should be (4.0) + sim.clip(BigDecimal(1.0)) should be(2.0) + sim.clip(BigDecimal(2.0)) should be(2.0) + sim.clip(BigDecimal(3.0)) should be(3.0) + sim.clip(BigDecimal(4.0)) should be(4.0) + sim.clip(BigDecimal(5.0)) should be(4.0) } "Should work for closed ranges with binary point" in { val sim = ScalaIntervalSimulator(range"[2,6].2") - sim.clip(BigDecimal(1.75)) should be (2.0) - sim.clip(BigDecimal(2.0)) should be (2.0) - sim.clip(BigDecimal(2.25)) should be (2.25) - sim.clip(BigDecimal(2.5)) should be (2.5) - sim.clip(BigDecimal(5.75)) should be (5.75) - sim.clip(BigDecimal(6.0)) should be (6.0) - sim.clip(BigDecimal(6.25)) should be (6.0) - sim.clip(BigDecimal(6.5)) should be (6.0) - sim.clip(BigDecimal(8.5)) should be (6.0) + sim.clip(BigDecimal(1.75)) should be(2.0) + sim.clip(BigDecimal(2.0)) should be(2.0) + sim.clip(BigDecimal(2.25)) should be(2.25) + sim.clip(BigDecimal(2.5)) should be(2.5) + sim.clip(BigDecimal(5.75)) should be(5.75) + sim.clip(BigDecimal(6.0)) should be(6.0) + sim.clip(BigDecimal(6.25)) should be(6.0) + sim.clip(BigDecimal(6.5)) should be(6.0) + sim.clip(BigDecimal(8.5)) should be(6.0) } "Should work for open ranges" in { val sim = ScalaIntervalSimulator(range"(2,4)") - sim.clip(BigDecimal(1.0)) should be (3.0) - sim.clip(BigDecimal(2.0)) should be (3.0) - sim.clip(BigDecimal(3.0)) should be (3.0) - sim.clip(BigDecimal(4.0)) should be (3.0) - sim.clip(BigDecimal(5.0)) should be (3.0) + sim.clip(BigDecimal(1.0)) should be(3.0) + sim.clip(BigDecimal(2.0)) should be(3.0) + sim.clip(BigDecimal(3.0)) should be(3.0) + sim.clip(BigDecimal(4.0)) should be(3.0) + sim.clip(BigDecimal(5.0)) should be(3.0) } "Should work for open ranges with binary point" in { val sim = ScalaIntervalSimulator(range"(2,6).2") - sim.clip(BigDecimal(1.75)) should be (2.25) - sim.clip(BigDecimal(2.0)) should be (2.25) - sim.clip(BigDecimal(2.25)) should be (2.25) - sim.clip(BigDecimal(2.5)) should be (2.5) - sim.clip(BigDecimal(5.75)) should be (5.75) - sim.clip(BigDecimal(6.0)) should be (5.75) - sim.clip(BigDecimal(6.25)) should be (5.75) - sim.clip(BigDecimal(6.5)) should be (5.75) - sim.clip(BigDecimal(8.5)) should be (5.75) + sim.clip(BigDecimal(1.75)) should be(2.25) + sim.clip(BigDecimal(2.0)) should be(2.25) + sim.clip(BigDecimal(2.25)) should be(2.25) + sim.clip(BigDecimal(2.5)) should be(2.5) + sim.clip(BigDecimal(5.75)) should be(5.75) + sim.clip(BigDecimal(6.0)) should be(5.75) + sim.clip(BigDecimal(6.25)) should be(5.75) + sim.clip(BigDecimal(6.5)) should be(5.75) + sim.clip(BigDecimal(8.5)) should be(5.75) } } "wrap tests" - { "Should work for closed ranges" in { val sim = ScalaIntervalSimulator(range"[2,6]") - sim.wrap(BigDecimal(1.0)) should be (6.0) - sim.wrap(BigDecimal(2.0)) should be (2.0) - sim.wrap(BigDecimal(3.0)) should be (3.0) - sim.wrap(BigDecimal(4.0)) should be (4.0) - sim.wrap(BigDecimal(5.0)) should be (5.0) - sim.wrap(BigDecimal(6.0)) should be (6.0) - sim.wrap(BigDecimal(7.0)) should be (2.0) + sim.wrap(BigDecimal(1.0)) should be(6.0) + sim.wrap(BigDecimal(2.0)) should be(2.0) + sim.wrap(BigDecimal(3.0)) should be(3.0) + sim.wrap(BigDecimal(4.0)) should be(4.0) + sim.wrap(BigDecimal(5.0)) should be(5.0) + sim.wrap(BigDecimal(6.0)) should be(6.0) + sim.wrap(BigDecimal(7.0)) should be(2.0) } "Should work for closed ranges with binary point" in { val sim = ScalaIntervalSimulator(range"[2,6].2") - sim.wrap(BigDecimal(1.75)) should be (6.0) - sim.wrap(BigDecimal(2.0)) should be (2.0) - sim.wrap(BigDecimal(2.25)) should be (2.25) - sim.wrap(BigDecimal(2.5)) should be (2.5) - sim.wrap(BigDecimal(5.75)) should be (5.75) - sim.wrap(BigDecimal(6.0)) should be (6.0) - sim.wrap(BigDecimal(6.25)) should be (2.0) - sim.wrap(BigDecimal(6.5)) should be (2.25) + sim.wrap(BigDecimal(1.75)) should be(6.0) + sim.wrap(BigDecimal(2.0)) should be(2.0) + sim.wrap(BigDecimal(2.25)) should be(2.25) + sim.wrap(BigDecimal(2.5)) should be(2.5) + sim.wrap(BigDecimal(5.75)) should be(5.75) + sim.wrap(BigDecimal(6.0)) should be(6.0) + sim.wrap(BigDecimal(6.25)) should be(2.0) + sim.wrap(BigDecimal(6.5)) should be(2.25) } "Should work for open ranges" in { val sim = ScalaIntervalSimulator(range"(2,6)") - sim.wrap(BigDecimal(1.0)) should be (4.0) - sim.wrap(BigDecimal(2.0)) should be (5.0) - sim.wrap(BigDecimal(3.0)) should be (3.0) - sim.wrap(BigDecimal(4.0)) should be (4.0) - sim.wrap(BigDecimal(5.0)) should be (5.0) - sim.wrap(BigDecimal(6.0)) should be (3.0) - sim.wrap(BigDecimal(7.0)) should be (4.0) + sim.wrap(BigDecimal(1.0)) should be(4.0) + sim.wrap(BigDecimal(2.0)) should be(5.0) + sim.wrap(BigDecimal(3.0)) should be(3.0) + sim.wrap(BigDecimal(4.0)) should be(4.0) + sim.wrap(BigDecimal(5.0)) should be(5.0) + sim.wrap(BigDecimal(6.0)) should be(3.0) + sim.wrap(BigDecimal(7.0)) should be(4.0) } "Should work for open ranges with binary point" in { val sim = ScalaIntervalSimulator(range"(2,6).2") - sim.wrap(BigDecimal(1.75)) should be (5.5) - sim.wrap(BigDecimal(2.0)) should be (5.75) - sim.wrap(BigDecimal(2.25)) should be (2.25) - sim.wrap(BigDecimal(2.5)) should be (2.5) - sim.wrap(BigDecimal(5.75)) should be (5.75) - sim.wrap(BigDecimal(6.0)) should be (2.25) - sim.wrap(BigDecimal(6.25)) should be (2.5) - sim.wrap(BigDecimal(7.0)) should be (3.25) + sim.wrap(BigDecimal(1.75)) should be(5.5) + sim.wrap(BigDecimal(2.0)) should be(5.75) + sim.wrap(BigDecimal(2.25)) should be(2.25) + sim.wrap(BigDecimal(2.5)) should be(2.5) + sim.wrap(BigDecimal(5.75)) should be(5.75) + sim.wrap(BigDecimal(6.0)) should be(2.25) + sim.wrap(BigDecimal(6.25)) should be(2.5) + sim.wrap(BigDecimal(7.0)) should be(3.25) } } } diff --git a/src/test/scala/chiselTests/Stack.scala b/src/test/scala/chiselTests/Stack.scala index cb21e2c0..085f4e34 100644 --- a/src/test/scala/chiselTests/Stack.scala +++ b/src/test/scala/chiselTests/Stack.scala @@ -8,25 +8,25 @@ import chisel3.util._ class ChiselStack(val depth: Int) extends Module { val io = IO(new Bundle { - val push = Input(Bool()) - val pop = Input(Bool()) - val en = Input(Bool()) - val dataIn = Input(UInt(32.W)) + val push = Input(Bool()) + val pop = Input(Bool()) + val en = Input(Bool()) + val dataIn = Input(UInt(32.W)) val dataOut = Output(UInt(32.W)) }) val stack_mem = Mem(depth, UInt(32.W)) - val sp = RegInit(0.U(log2Ceil(depth + 1).W)) - val out = RegInit(0.U(32.W)) + val sp = RegInit(0.U(log2Ceil(depth + 1).W)) + val out = RegInit(0.U(32.W)) - when (io.en) { + when(io.en) { when(io.push && (sp < depth.asUInt)) { stack_mem(sp) := io.dataIn sp := sp +% 1.U - } .elsewhen(io.pop && (sp > 0.U)) { + }.elsewhen(io.pop && (sp > 0.U)) { sp := sp -% 1.U } - when (sp > 0.U) { + when(sp > 0.U) { out := stack_mem(sp -% 1.U) } } @@ -65,7 +65,7 @@ class StackTester(c: Stack) extends Tester(c) { expect(c.io.dataOut, dataOut) } } -*/ + */ class StackSpec extends ChiselPropSpec { @@ -73,5 +73,5 @@ class StackSpec extends ChiselPropSpec { ChiselStage.elaborate { new ChiselStack(2) } } - ignore("StackTester should return the correct result") { } + ignore("StackTester should return the correct result") {} } diff --git a/src/test/scala/chiselTests/Stop.scala b/src/test/scala/chiselTests/Stop.scala index 1634f776..25aae2d9 100644 --- a/src/test/scala/chiselTests/Stop.scala +++ b/src/test/scala/chiselTests/Stop.scala @@ -12,7 +12,7 @@ class StopTester() extends BasicTester { class StopImmediatelyTester extends BasicTester { val cycle = RegInit(0.asUInt(4.W)) cycle := cycle + 1.U - when (cycle === 4.U) { + when(cycle === 4.U) { stop() } assert(cycle =/= 5.U, "Simulation did not exit upon executing stop()") diff --git a/src/test/scala/chiselTests/StrongEnum.scala b/src/test/scala/chiselTests/StrongEnum.scala index 404c3f66..c43d832a 100644 --- a/src/test/scala/chiselTests/StrongEnum.scala +++ b/src/test/scala/chiselTests/StrongEnum.scala @@ -142,21 +142,21 @@ class StrongEnumFSM extends Module { io.out := (state === sTwo1s) io.state := state - switch (state) { - is (sNone) { - when (io.in) { + switch(state) { + is(sNone) { + when(io.in) { state := sOne1 } } - is (sOne1) { - when (io.in) { + is(sOne1) { + when(io.in) { state := sTwo1s - } .otherwise { + }.otherwise { state := sNone } } - is (sTwo1s) { - when (!io.in) { + is(sTwo1s) { + when(!io.in) { state := sNone } } @@ -164,7 +164,7 @@ class StrongEnumFSM extends Module { } class CastToUIntTester extends BasicTester { - for ((enum,lit) <- EnumExample.all zip EnumExample.litValues) { + for ((enum, lit) <- EnumExample.all.zip(EnumExample.litValues)) { val mod = Module(new CastToUInt) mod.io.in := enum assert(mod.io.out === lit) @@ -173,7 +173,7 @@ class CastToUIntTester extends BasicTester { } class CastFromLitTester extends BasicTester { - for ((enum,lit) <- EnumExample.all zip EnumExample.litValues) { + for ((enum, lit) <- EnumExample.all.zip(EnumExample.litValues)) { val mod = Module(new CastFromLit(lit)) assert(mod.io.out === enum) assert(mod.io.valid === true.B) @@ -182,16 +182,15 @@ class CastFromLitTester extends BasicTester { } class CastFromNonLitTester extends BasicTester { - for ((enum,lit) <- EnumExample.all zip EnumExample.litValues) { + for ((enum, lit) <- EnumExample.all.zip(EnumExample.litValues)) { val mod = Module(new CastFromNonLit) mod.io.in := lit assert(mod.io.out === enum) assert(mod.io.valid === true.B) } - val invalid_values = (1 until (1 << EnumExample.getWidth)). - filter(!EnumExample.litValues.map(_.litValue).contains(_)). - map(_.U) + val invalid_values = + (1 until (1 << EnumExample.getWidth)).filter(!EnumExample.litValues.map(_.litValue).contains(_)).map(_.U) for (invalid_val <- invalid_values) { val mod = Module(new CastFromNonLit) @@ -204,16 +203,15 @@ class CastFromNonLitTester extends BasicTester { } class SafeCastFromNonLitTester extends BasicTester { - for ((enum,lit) <- EnumExample.all zip EnumExample.litValues) { + for ((enum, lit) <- EnumExample.all.zip(EnumExample.litValues)) { val mod = Module(new SafeCastFromNonLit) mod.io.in := lit assert(mod.io.out === enum) assert(mod.io.valid === true.B) } - val invalid_values = (1 until (1 << EnumExample.getWidth)). - filter(!EnumExample.litValues.map(_.litValue).contains(_)). - map(_.U) + val invalid_values = + (1 until (1 << EnumExample.getWidth)).filter(!EnumExample.litValues.map(_.litValue).contains(_)).map(_.U) for (invalid_val <- invalid_values) { val mod = Module(new SafeCastFromNonLit) @@ -231,8 +229,10 @@ class CastToInvalidEnumTester extends BasicTester { } class EnumOpsTester extends BasicTester { - for (x <- EnumExample.all; - y <- EnumExample.all) { + for { + x <- EnumExample.all + y <- EnumExample.all + } { val mod = Module(new EnumOps(EnumExample, EnumExample)) mod.io.x := x mod.io.y := y @@ -264,7 +264,7 @@ class IsLitTester extends BasicTester { } class NextTester extends BasicTester { - for ((e,n) <- EnumExample.all.zip(EnumExample.litValues.tail :+ EnumExample.litValues.head)) { + for ((e, n) <- EnumExample.all.zip(EnumExample.litValues.tail :+ EnumExample.litValues.head)) { assert(e.next.litValue == n.litValue) val w = WireDefault(e) assert(w.next === EnumExample(n)) @@ -275,7 +275,7 @@ class NextTester extends BasicTester { class WidthTester extends BasicTester { assert(EnumExample.getWidth == EnumExample.litValues.last.getWidth) assert(EnumExample.all.forall(_.getWidth == EnumExample.litValues.last.getWidth)) - assert(EnumExample.all.forall{e => + assert(EnumExample.all.forall { e => val w = WireDefault(e) w.getWidth == EnumExample.litValues.last.getWidth }) @@ -289,7 +289,8 @@ class StrongEnumFSMTester extends BasicTester { // Inputs and expected results val inputs: Vec[Bool] = VecInit(false.B, true.B, false.B, true.B, true.B, true.B, false.B, true.B, true.B, false.B) - val expected: Vec[Bool] = VecInit(false.B, false.B, false.B, false.B, false.B, true.B, true.B, false.B, false.B, true.B) + val expected: Vec[Bool] = + VecInit(false.B, false.B, false.B, false.B, false.B, true.B, true.B, false.B, false.B, true.B) val expected_state = VecInit(sNone, sNone, sOne1, sNone, sOne1, sTwo1s, sTwo1s, sNone, sOne1, sTwo1s) val cntr = Counter(inputs.length) @@ -342,16 +343,16 @@ class IsOneOfTester extends BasicTester { class StrongEnumSpec extends ChiselFlatSpec with Utils { import chisel3.internal.ChiselException - behavior of "Strong enum tester" + behavior.of("Strong enum tester") it should "fail to instantiate non-literal enums with the Value function" in { - an [ExceptionInInitializerError] should be thrownBy extractCause[ExceptionInInitializerError] { + an[ExceptionInInitializerError] should be thrownBy extractCause[ExceptionInInitializerError] { ChiselStage.elaborate(new SimpleConnector(NonLiteralEnumType(), NonLiteralEnumType())) } } it should "fail to instantiate non-increasing enums with the Value function" in { - an [ExceptionInInitializerError] should be thrownBy extractCause[ExceptionInInitializerError] { + an[ExceptionInInitializerError] should be thrownBy extractCause[ExceptionInInitializerError] { ChiselStage.elaborate(new SimpleConnector(NonIncreasingEnum(), NonIncreasingEnum())) } } @@ -362,17 +363,17 @@ class StrongEnumSpec extends ChiselFlatSpec with Utils { } it should "fail to connect a strong enum to a UInt" in { - a [ChiselException] should be thrownBy extractCause[ChiselException] { + a[ChiselException] should be thrownBy extractCause[ChiselException] { ChiselStage.elaborate(new SimpleConnector(EnumExample(), UInt())) } } it should "fail to connect enums of different types" in { - a [ChiselException] should be thrownBy extractCause[ChiselException] { + a[ChiselException] should be thrownBy extractCause[ChiselException] { ChiselStage.elaborate(new SimpleConnector(EnumExample(), OtherEnum())) } - a [ChiselException] should be thrownBy extractCause[ChiselException] { + a[ChiselException] should be thrownBy extractCause[ChiselException] { ChiselStage.elaborate(new SimpleConnector(EnumExample.Type(), OtherEnum.Type())) } } @@ -394,7 +395,7 @@ class StrongEnumSpec extends ChiselFlatSpec with Utils { } it should "prevent illegal literal casts to enums" in { - a [ChiselException] should be thrownBy extractCause[ChiselException] { + a[ChiselException] should be thrownBy extractCause[ChiselException] { ChiselStage.elaborate(new CastToInvalidEnumTester) } } @@ -403,12 +404,12 @@ class StrongEnumSpec extends ChiselFlatSpec with Utils { for (w <- 0 to EnumExample.getWidth) ChiselStage.elaborate(new CastFromNonLitWidth(Some(w))) - a [ChiselException] should be thrownBy extractCause[ChiselException] { + a[ChiselException] should be thrownBy extractCause[ChiselException] { ChiselStage.elaborate(new CastFromNonLitWidth) } for (w <- (EnumExample.getWidth + 1) to (EnumExample.getWidth + 100)) { - a [ChiselException] should be thrownBy extractCause[ChiselException] { + a[ChiselException] should be thrownBy extractCause[ChiselException] { ChiselStage.elaborate(new CastFromNonLitWidth(Some(w))) } } @@ -419,7 +420,7 @@ class StrongEnumSpec extends ChiselFlatSpec with Utils { } it should "fail to compare enums of different types" in { - a [ChiselException] should be thrownBy extractCause[ChiselException] { + a[ChiselException] should be thrownBy extractCause[ChiselException] { ChiselStage.elaborate(new InvalidEnumOpsTester) } } @@ -462,8 +463,8 @@ class StrongEnumSpec extends ChiselFlatSpec with Utils { out := MyEnum(in) } val (log, _) = grabLog(ChiselStage.elaborate(new MyModule)) - log should include ("warn") - log should include ("Casting non-literal UInt") + log should include("warn") + log should include("Casting non-literal UInt") } it should "NOT warn if the Enum is total" in { @@ -477,7 +478,7 @@ class StrongEnumSpec extends ChiselFlatSpec with Utils { out := TotalEnum(in) } val (log, _) = grabLog(ChiselStage.elaborate(new MyModule)) - log should not include ("warn") + (log should not).include("warn") } "Casting a UInt to an Enum with .safe" should "NOT warn" in { @@ -491,7 +492,7 @@ class StrongEnumSpec extends ChiselFlatSpec with Utils { out := MyEnum.safe(in)._1 } val (log, _) = grabLog(ChiselStage.elaborate(new MyModule)) - log should not include ("warn") + (log should not).include("warn") } it should "NOT generate any validity logic if the Enum is total" in { @@ -507,7 +508,7 @@ class StrongEnumSpec extends ChiselFlatSpec with Utils { out := res } val (log, _) = grabLog(ChiselStage.elaborate(new MyModule)) - log should not include ("warn") + (log should not).include("warn") } it should "correctly check if the enumeration is one of the values in a given sequence" in { @@ -524,7 +525,7 @@ class StrongEnumAnnotator extends Module { val le100 = Value(100.U) } - val io = IO(new Bundle{ + val io = IO(new Bundle { val in = Input(EnumExample()) val out = Output(EnumExample()) val other = Output(OtherEnum()) @@ -584,7 +585,7 @@ class StrongEnumAnnotatorWithChiselName extends Module { val le100 = Value(100.U) } - val io = IO(new Bundle{ + val io = IO(new Bundle { val in = Input(EnumExample()) val out = Output(EnumExample()) val other = Output(OtherEnum()) @@ -636,7 +637,7 @@ class StrongEnumAnnotatorWithChiselName extends Module { class StrongEnumAnnotationSpec extends AnyFreeSpec with Matchers { import chisel3.experimental.EnumAnnotations._ - import firrtl.annotations.{ComponentName, Annotation} + import firrtl.annotations.{Annotation, ComponentName} val enumExampleName = "EnumExample" val otherEnumName = "OtherEnum" @@ -667,7 +668,11 @@ class StrongEnumAnnotationSpec extends AnyFreeSpec with Matchers { val correctVecAnnos = Seq( CorrectVecAnno("vec", enumExampleName, Set()), CorrectVecAnno("vec_of_vecs", enumExampleName, Set()), - CorrectVecAnno("vec_of_bundles", enumExampleName, Set(Seq("field"), Seq("vec"), Seq("inner_bundle1", "e"), Seq("inner_bundle1", "v"))), + CorrectVecAnno( + "vec_of_bundles", + enumExampleName, + Set(Seq("field"), Seq("vec"), Seq("inner_bundle1", "e"), Seq("inner_bundle1", "v")) + ), CorrectVecAnno("vec_of_bundles", otherEnumName, Set(Seq("other"))), CorrectVecAnno("vec_of_bundles", localEnumName, Set(Seq("local"))), CorrectVecAnno("bund.vec", enumExampleName, Set()), @@ -678,49 +683,49 @@ class StrongEnumAnnotationSpec extends AnyFreeSpec with Matchers { println("Enum definitions:") annos.foreach { case EnumDefAnnotation(enumTypeName, definition) => println(s"\t$enumTypeName: $definition") - case _ => + case _ => } println("Enum components:") - annos.foreach{ + annos.foreach { case EnumComponentAnnotation(target, enumTypeName) => println(s"\t$target => $enumTypeName") - case _ => + case _ => } println("Enum vecs:") - annos.foreach{ + annos.foreach { case EnumVecAnnotation(target, enumTypeName, fields) => println(s"\t$target[$fields] => $enumTypeName") - case _ => + case _ => } } def isCorrect(anno: EnumDefAnnotation, correct: CorrectDefAnno): Boolean = { (anno.typeName == correct.typeName || - anno.typeName.endsWith("." + correct.typeName) || - anno.typeName.endsWith("$" + correct.typeName)) && - anno.definition == correct.definition + anno.typeName.endsWith("." + correct.typeName) || + anno.typeName.endsWith("$" + correct.typeName)) && + anno.definition == correct.definition } def isCorrect(anno: EnumComponentAnnotation, correct: CorrectCompAnno): Boolean = { (anno.target match { case ComponentName(name, _) => name == correct.targetName - case _ => throw new Exception("Unknown target type in EnumComponentAnnotation") + case _ => throw new Exception("Unknown target type in EnumComponentAnnotation") }) && - (anno.enumTypeName == correct.typeName || anno.enumTypeName.endsWith("." + correct.typeName) || - anno.enumTypeName.endsWith("$" + correct.typeName)) + (anno.enumTypeName == correct.typeName || anno.enumTypeName.endsWith("." + correct.typeName) || + anno.enumTypeName.endsWith("$" + correct.typeName)) } def isCorrect(anno: EnumVecAnnotation, correct: CorrectVecAnno): Boolean = { (anno.target match { case ComponentName(name, _) => name == correct.targetName - case _ => throw new Exception("Unknown target type in EnumVecAnnotation") + case _ => throw new Exception("Unknown target type in EnumVecAnnotation") }) && - (anno.typeName == correct.typeName || anno.typeName.endsWith("." + correct.typeName) || - anno.typeName.endsWith("$" + correct.typeName)) && - anno.fields.map(_.toSeq).toSet == correct.fields + (anno.typeName == correct.typeName || anno.typeName.endsWith("." + correct.typeName) || + anno.typeName.endsWith("$" + correct.typeName)) && + anno.fields.map(_.toSeq).toSet == correct.fields } def allCorrectDefs(annos: Seq[EnumDefAnnotation], corrects: Seq[CorrectDefAnno]): Boolean = { corrects.forall(c => annos.exists(isCorrect(_, c))) && - correctDefAnnos.length == annos.length + correctDefAnnos.length == annos.length } // Because temporary variables might be formed and annotated, we do not check that every component or vector @@ -732,8 +737,10 @@ class StrongEnumAnnotationSpec extends AnyFreeSpec with Matchers { corrects.forall(c => annos.exists(isCorrect(_, c))) def test(strongEnumAnnotatorGen: () => Module) { - val annos = (new ChiselStage).execute(Array("--target-dir", "test_run_dir", "--no-run-firrtl"), - Seq(ChiselGeneratorAnnotation(strongEnumAnnotatorGen))) + val annos = (new ChiselStage).execute( + Array("--target-dir", "test_run_dir", "--no-run-firrtl"), + Seq(ChiselGeneratorAnnotation(strongEnumAnnotatorGen)) + ) val enumDefAnnos = annos.collect { case a: EnumDefAnnotation => a } val enumCompAnnos = annos.collect { case a: EnumComponentAnnotation => a } diff --git a/src/test/scala/chiselTests/SwitchSpec.scala b/src/test/scala/chiselTests/SwitchSpec.scala index 12bbb9e7..52f50a53 100644 --- a/src/test/scala/chiselTests/SwitchSpec.scala +++ b/src/test/scala/chiselTests/SwitchSpec.scala @@ -4,30 +4,30 @@ package chiselTests import chisel3._ import chisel3.stage.ChiselStage -import chisel3.util.{switch, is} +import chisel3.util.{is, switch} class SwitchSpec extends ChiselFlatSpec with Utils { "switch" should "require literal conditions" in { - a [java.lang.IllegalArgumentException] should be thrownBy extractCause[IllegalArgumentException] { + a[java.lang.IllegalArgumentException] should be thrownBy extractCause[IllegalArgumentException] { ChiselStage.elaborate(new Module { val io = IO(new Bundle {}) val state = RegInit(0.U) val wire = WireDefault(0.U) - switch (state) { - is (wire) { state := 1.U } + switch(state) { + is(wire) { state := 1.U } } }) } } it should "require mutually exclusive conditions" in { - a [java.lang.IllegalArgumentException] should be thrownBy extractCause[IllegalArgumentException] { + a[java.lang.IllegalArgumentException] should be thrownBy extractCause[IllegalArgumentException] { ChiselStage.elaborate(new Module { val io = IO(new Bundle {}) val state = RegInit(0.U) - switch (state) { - is (0.U) { state := 1.U } - is (1.U) { state := 2.U } - is (0.U) { state := 3.U } + switch(state) { + is(0.U) { state := 1.U } + is(1.U) { state := 2.U } + is(0.U) { state := 3.U } } }) } @@ -40,14 +40,14 @@ class SwitchSpec extends ChiselFlatSpec with Utils { }) io.out := 0.U - switch (io.in) { - is (0.U) { io.out := 3.U } - is (1.U) { io.out := 0.U } - is (2.U) { io.out := 1.U } - is (3.U) { io.out := 3.U } + switch(io.in) { + is(0.U) { io.out := 3.U } + is(1.U) { io.out := 0.U } + is(2.U) { io.out := 1.U } + is(3.U) { io.out := 3.U } } }) - chirrtl should not include "Conditional.scala" + (chirrtl should not).include("Conditional.scala") } } diff --git a/src/test/scala/chiselTests/Tbl.scala b/src/test/scala/chiselTests/Tbl.scala index c7b45a16..5e127770 100644 --- a/src/test/scala/chiselTests/Tbl.scala +++ b/src/test/scala/chiselTests/Tbl.scala @@ -8,15 +8,15 @@ import chisel3.util._ class Tbl(w: Int, n: Int) extends Module { val io = IO(new Bundle { - val wi = Input(UInt(log2Ceil(n).W)) - val ri = Input(UInt(log2Ceil(n).W)) - val we = Input(Bool()) - val d = Input(UInt(w.W)) - val o = Output(UInt(w.W)) + val wi = Input(UInt(log2Ceil(n).W)) + val ri = Input(UInt(log2Ceil(n).W)) + val we = Input(Bool()) + val d = Input(UInt(w.W)) + val o = Output(UInt(w.W)) }) val m = Mem(n, UInt(w.W)) io.o := m(io.ri) - when (io.we) { + when(io.we) { m(io.wi) := io.d when(io.ri === io.wi) { io.o := io.d @@ -35,10 +35,10 @@ class TblTester(w: Int, n: Int, idxs: List[Int], values: List[Int]) extends Basi dut.io.ri := prev_idx dut.io.we := true.B //TODO enSequence dut.io.d := vvalues(cnt) - when (cnt > 0.U) { - when (prev_idx === vidxs(cnt)) { + when(cnt > 0.U) { + when(prev_idx === vidxs(cnt)) { assert(dut.io.o === vvalues(cnt)) - } .otherwise { + }.otherwise { assert(dut.io.o === prev_value) } } @@ -49,13 +49,14 @@ class TblTester(w: Int, n: Int, idxs: List[Int], values: List[Int]) extends Basi class TblSpec extends ChiselPropSpec { property("All table reads should return the previous write") { - forAll(safeUIntPairN(8)) { case(w: Int, pairs: List[(Int, Int)]) => - // Provide an appropriate whenever clause. - // ScalaTest will try and shrink the values on error to determine the smallest values that cause the error. - whenever(w > 0 && pairs.length > 0) { - val (idxs, values) = pairs.unzip - assertTesterPasses{ new TblTester(w, 1 << w, idxs, values) } - } + forAll(safeUIntPairN(8)) { + case (w: Int, pairs: List[(Int, Int)]) => + // Provide an appropriate whenever clause. + // ScalaTest will try and shrink the values on error to determine the smallest values that cause the error. + whenever(w > 0 && pairs.length > 0) { + val (idxs, values) = pairs.unzip + assertTesterPasses { new TblTester(w, 1 << w, idxs, values) } + } } } } diff --git a/src/test/scala/chiselTests/TesterDriverSpec.scala b/src/test/scala/chiselTests/TesterDriverSpec.scala index 5c0e277e..c3cc232f 100644 --- a/src/test/scala/chiselTests/TesterDriverSpec.scala +++ b/src/test/scala/chiselTests/TesterDriverSpec.scala @@ -42,4 +42,3 @@ class TesterDriverSpec extends ChiselFlatSpec { } } } - diff --git a/src/test/scala/chiselTests/TransitNameSpec.scala b/src/test/scala/chiselTests/TransitNameSpec.scala index 656c6731..ae08336d 100644 --- a/src/test/scala/chiselTests/TransitNameSpec.scala +++ b/src/test/scala/chiselTests/TransitNameSpec.scala @@ -1,7 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 package chiselTests - import chisel3._ import chisel3.stage.{ChiselGeneratorAnnotation, ChiselStage} import chisel3.util.TransitName @@ -12,7 +11,7 @@ import org.scalatest.matchers.should.Matchers class TransitNameSpec extends AnyFlatSpec with Matchers { class MyModule extends RawModule { - val io = IO(new Bundle{}) + val io = IO(new Bundle {}) override val desiredName: String = "MyModule" } @@ -42,13 +41,13 @@ class TransitNameSpec extends AnyFlatSpec with Matchers { .emitFirrtl(new Top, Array("--target-dir", "test_run_dir/TransitNameSpec")) info("""output FIRRTL includes "inst MyModule"""") - firrtl should include ("inst MyModule of MyModule") + firrtl should include("inst MyModule of MyModule") info("""output FIRRTL includes "inst bar"""") - firrtl should include ("inst bar of MyModule") + firrtl should include("inst bar of MyModule") info("""output FIRRTL includes "inst baz_generated"""") - firrtl should include ("inst baz_generated of MyModule") + firrtl should include("inst baz_generated of MyModule") } } diff --git a/src/test/scala/chiselTests/UIntOps.scala b/src/test/scala/chiselTests/UIntOps.scala index bc6454b8..5fb86001 100644 --- a/src/test/scala/chiselTests/UIntOps.scala +++ b/src/test/scala/chiselTests/UIntOps.scala @@ -70,8 +70,8 @@ class UIntOpsTester(a: Long, b: Long) extends BasicTester { assert(dut.io.addampout === (a + b).U(33.W)) assert(dut.io.subampout === (a - b).S(33.W).asUInt) assert(dut.io.timesout === (a * b).U(32.W)) - assert(dut.io.divout === (a / (b max 1)).U(32.W)) - assert(dut.io.modout === (a % (b max 1)).U(32.W)) + assert(dut.io.divout === (a / (b.max(1))).U(32.W)) + assert(dut.io.modout === (a % (b.max(1))).U(32.W)) assert(dut.io.lshiftout === (a << (b % 16)).U(32.W)) assert(dut.io.rshiftout === (a >> b).U(32.W)) assert( @@ -117,7 +117,6 @@ class BasicRotate extends BasicTester { val shiftAmount = random.LFSR(4) val ctr = RegInit(0.U(4.W)) - val rotL = 1.U(3.W).rotateLeft(shiftAmount) val rotR = 1.U(3.W).rotateRight(shiftAmount) @@ -140,7 +139,7 @@ class BasicRotate extends BasicTester { ctr := ctr + 1.U - when (ctr === 15.U){ + when(ctr === 15.U) { stop() } } @@ -197,7 +196,7 @@ class UIntOpsSpec extends ChiselPropSpec with Matchers with Utils { } property("Bools cannot be created from >1 bit UInts") { - a [Exception] should be thrownBy extractCause[Exception] { ChiselStage.elaborate(new BadBoolConversion) } + a[Exception] should be thrownBy extractCause[Exception] { ChiselStage.elaborate(new BadBoolConversion) } } property("UIntOps should elaborate") { @@ -209,7 +208,7 @@ class UIntOpsSpec extends ChiselPropSpec with Matchers with Utils { } property("Negative shift amounts are invalid") { - a [ChiselException] should be thrownBy extractCause[ChiselException] { + a[ChiselException] should be thrownBy extractCause[ChiselException] { ChiselStage.elaborate(new NegativeShift(UInt())) } } diff --git a/src/test/scala/chiselTests/Util.scala b/src/test/scala/chiselTests/Util.scala index e8354b8d..d2f8bd9b 100644 --- a/src/test/scala/chiselTests/Util.scala +++ b/src/test/scala/chiselTests/Util.scala @@ -25,14 +25,14 @@ class PassthroughRawModule extends RawModule with AbstractPassthroughModule case class ScalaIntervalSimulator(intervalRange: IntervalRange) { val binaryPoint: Int = intervalRange.binaryPoint.asInstanceOf[KnownBinaryPoint].value - val epsilon: Double = 1.0 / math.pow(2.0, binaryPoint.toDouble) + val epsilon: Double = 1.0 / math.pow(2.0, binaryPoint.toDouble) val (lower, upper) = (intervalRange.lowerBound, intervalRange.upperBound) match { case (firrtlir.Closed(lower1), firrtlir.Closed(upper1)) => (lower1, upper1) case (firrtlir.Closed(lower1), firrtlir.Open(upper1)) => (lower1, upper1 - epsilon) - case (firrtlir.Open(lower1), firrtlir.Closed(upper1)) => (lower1 + epsilon, upper1) - case (firrtlir.Open(lower1), firrtlir.Open(upper1)) => (lower1 + epsilon, upper1 - epsilon) + case (firrtlir.Open(lower1), firrtlir.Closed(upper1)) => (lower1 + epsilon, upper1) + case (firrtlir.Open(lower1), firrtlir.Open(upper1)) => (lower1 + epsilon, upper1 - epsilon) case _ => throw new Exception(s"lower and upper bounds must be defined, range here is $intervalRange") } @@ -41,11 +41,9 @@ case class ScalaIntervalSimulator(intervalRange: IntervalRange) { if (value < lower) { lower - } - else if (value > upper) { + } else if (value > upper) { upper - } - else { + } else { value } } @@ -54,11 +52,9 @@ case class ScalaIntervalSimulator(intervalRange: IntervalRange) { if (value < lower) { upper + (value - lower) + epsilon - } - else if (value > upper) { + } else if (value > upper) { ((value - upper) - epsilon) + lower - } - else { + } else { value } } @@ -71,5 +67,3 @@ case class ScalaIntervalSimulator(intervalRange: IntervalRange) { Interval.fromDouble(value.toDouble, width = Width(), binaryPoint = binaryPoint.BP) } } - - diff --git a/src/test/scala/chiselTests/Vec.scala b/src/test/scala/chiselTests/Vec.scala index 24ba0bf8..2eb6ae5f 100644 --- a/src/test/scala/chiselTests/Vec.scala +++ b/src/test/scala/chiselTests/Vec.scala @@ -15,7 +15,7 @@ class LitTesterMod(vecSize: Int) extends Module { val io = IO(new Bundle { val out = Output(Vec(vecSize, UInt())) }) - io.out := VecInit(Seq.fill(vecSize){0.U}) + io.out := VecInit(Seq.fill(vecSize) { 0.U }) } class RegTesterMod(vecSize: Int) extends Module { @@ -23,7 +23,7 @@ class RegTesterMod(vecSize: Int) extends Module { val in = Input(Vec(vecSize, UInt())) val out = Output(Vec(vecSize, UInt())) }) - val vecReg = RegNext(io.in, VecInit(Seq.fill(vecSize){0.U})) + val vecReg = RegNext(io.in, VecInit(Seq.fill(vecSize) { 0.U })) io.out := vecReg } @@ -56,11 +56,11 @@ class RegTester(w: Int, values: List[Int]) extends BasicTester { val dut = Module(new RegTesterMod(values.length)) val doneReg = RegInit(false.B) dut.io.in := v - when (doneReg) { - for ((a,b) <- dut.io.out.zip(values)) + when(doneReg) { + for ((a, b) <- dut.io.out.zip(values)) assert(a === b.U) stop() - } .otherwise { + }.otherwise { doneReg := true.B for (a <- dut.io.out) assert(a === 0.U) @@ -71,7 +71,7 @@ class IOTester(w: Int, values: List[Int]) extends BasicTester { val v = VecInit(values.map(_.U(w.W))) // Does this need a Wire? No. It's a Vec of Lits and hence synthesizeable. val dut = Module(new IOTesterMod(values.length)) dut.io.in := v - for ((a,b) <- dut.io.out.zip(values)) { + for ((a, b) <- dut.io.out.zip(values)) { assert(a === b.U) } stop() @@ -81,24 +81,24 @@ class IOTesterModFill(vecSize: Int) extends Module { // This should generate a BindingException when we attempt to wire up the Vec.fill elements // since they're pure types and hence unsynthesizeable. val io = IO(new Bundle { - val in = Input(VecInit(Seq.fill(vecSize) {UInt()})) - val out = Output(VecInit(Seq.fill(vecSize) {UInt()})) + val in = Input(VecInit(Seq.fill(vecSize) { UInt() })) + val out = Output(VecInit(Seq.fill(vecSize) { UInt() })) }) io.out := io.in } class ValueTester(w: Int, values: List[Int]) extends BasicTester { val v = VecInit(values.map(_.asUInt(w.W))) - for ((a,b) <- v.zip(values)) { + for ((a, b) <- v.zip(values)) { assert(a === b.asUInt) } stop() } class TabulateTester(n: Int) extends BasicTester { - val v = VecInit(Range(0, n).map(i => (i*2).asUInt)) - val x = VecInit(Array.tabulate(n){ i => (i*2).asUInt }) - val u = VecInit.tabulate(n)(i => (i*2).asUInt) + val v = VecInit(Range(0, n).map(i => (i * 2).asUInt)) + val x = VecInit(Array.tabulate(n) { i => (i * 2).asUInt }) + val u = VecInit.tabulate(n)(i => (i * 2).asUInt) assert(v.asUInt() === x.asUInt()) assert(v.asUInt() === u.asUInt()) @@ -115,54 +115,54 @@ class FillTester(n: Int, value: Int) extends BasicTester { stop() } -object VecMultiDimTester { - +object VecMultiDimTester { + @tailrec private def assert2DIsCorrect(n: Int, arr: Vec[Vec[UInt]], compArr: Seq[Seq[Int]]): Unit = { - val compareRow = arr(n) zip compArr(n) - compareRow.foreach (x => assert(x._1 === x._2.U)) - if (n != 0) assert2DIsCorrect(n-1, arr, compArr) + val compareRow = arr(n).zip(compArr(n)) + compareRow.foreach(x => assert(x._1 === x._2.U)) + if (n != 0) assert2DIsCorrect(n - 1, arr, compArr) } @tailrec private def assert3DIsCorrect(n: Int, m: Int, arr: Vec[Vec[Vec[UInt]]], compArr: Seq[Seq[Seq[Int]]]): Unit = { - assert2DIsCorrect(m-1, arr(n), compArr(n)) - if (n != 0) assert3DIsCorrect(n-1, m, arr, compArr) + assert2DIsCorrect(m - 1, arr(n), compArr(n)) + if (n != 0) assert3DIsCorrect(n - 1, m, arr, compArr) } class TabulateTester2D(n: Int, m: Int) extends BasicTester { - def gen(x: Int, y: Int): UInt = (x+y).asUInt - def genCompVec(x: Int, y:Int): Int = x+y - val vec = VecInit.tabulate(n, m){ gen } - val compArr = Seq.tabulate(n,m){ genCompVec } - - assert2DIsCorrect(n-1, vec, compArr) + def gen(x: Int, y: Int): UInt = (x + y).asUInt + def genCompVec(x: Int, y: Int): Int = x + y + val vec = VecInit.tabulate(n, m) { gen } + val compArr = Seq.tabulate(n, m) { genCompVec } + + assert2DIsCorrect(n - 1, vec, compArr) stop() } class TabulateTester3D(n: Int, m: Int, p: Int) extends BasicTester { - def gen(x: Int, y: Int, z: Int): UInt = (x+y+z).asUInt - def genCompVec(x: Int, y:Int, z: Int): Int = x+y+z - val vec = VecInit.tabulate(n, m, p){ gen } - val compArr = Seq.tabulate(n, m, p){ genCompVec } + def gen(x: Int, y: Int, z: Int): UInt = (x + y + z).asUInt + def genCompVec(x: Int, y: Int, z: Int): Int = x + y + z + val vec = VecInit.tabulate(n, m, p) { gen } + val compArr = Seq.tabulate(n, m, p) { genCompVec } - assert3DIsCorrect(n-1, m, vec, compArr) + assert3DIsCorrect(n - 1, m, vec, compArr) stop() } class Fill2DTester(n: Int, m: Int, value: Int) extends BasicTester { - val u = VecInit.fill(n,m)(value.U) - val compareArr = Seq.fill(n,m)(value) - - assert2DIsCorrect(n-1, u, compareArr) + val u = VecInit.fill(n, m)(value.U) + val compareArr = Seq.fill(n, m)(value) + + assert2DIsCorrect(n - 1, u, compareArr) stop() } class Fill3DTester(n: Int, m: Int, p: Int, value: Int) extends BasicTester { - val u = VecInit.fill(n,m,p)(value.U) - val compareArr = Seq.fill(n,m,p)(value) + val u = VecInit.fill(n, m, p)(value.U) + val compareArr = Seq.fill(n, m, p)(value) - assert3DIsCorrect(n-1, m, u, compareArr) + assert3DIsCorrect(n - 1, m, u, compareArr) stop() } @@ -181,7 +181,7 @@ object VecMultiDimTester { class BidirectionalTester3DFill(n: Int, m: Int, p: Int) extends BasicTester { val mod = Module(new PassthroughModule) val vec3D = VecInit.fill(n, m, p)(mod.io) - + for { vec2D <- vec3D vec1D <- vec2D @@ -191,7 +191,7 @@ object VecMultiDimTester { } stop() } - + class TabulateModuleTester(value: Int) extends Module { val io = IO(Flipped(new PassthroughModuleIO)) // This drives the input of a PassthroughModule @@ -199,11 +199,11 @@ object VecMultiDimTester { } class BidirectionalTester2DTabulate(n: Int, m: Int) extends BasicTester { - val vec2D = VecInit.tabulate(n, m) { (x, y) => Module(new TabulateModuleTester(x + y + 1)).io} + val vec2D = VecInit.tabulate(n, m) { (x, y) => Module(new TabulateModuleTester(x + y + 1)).io } for { x <- 0 until n - y <- 0 until m + y <- 0 until m } yield { val value = x + y + 1 val receiveMod = Module(new PassthroughModule).io @@ -233,20 +233,23 @@ object VecMultiDimTester { class IterateTester(start: Int, len: Int)(f: UInt => UInt) extends BasicTester { val controlVec = VecInit(Seq.iterate(start.U, len)(f)) val testVec = VecInit.iterate(start.U, len)(f) - assert(controlVec.asUInt() === testVec.asUInt(), s"Expected Vec to be filled like $controlVec, instead creaeted $testVec\n") + assert( + controlVec.asUInt() === testVec.asUInt(), + s"Expected Vec to be filled like $controlVec, instead creaeted $testVec\n" + ) stop() } class ShiftRegisterTester(n: Int) extends BasicTester { - val (cnt, wrap) = Counter(true.B, n*2) - val shifter = Reg(Vec(n, UInt((log2Ceil(n) max 1).W))) - (shifter, shifter drop 1).zipped.foreach(_ := _) - shifter(n-1) := cnt - when (cnt >= n.asUInt) { + val (cnt, wrap) = Counter(true.B, n * 2) + val shifter = Reg(Vec(n, UInt((log2Ceil(n).max(1)).W))) + (shifter, shifter.drop(1)).zipped.foreach(_ := _) + shifter(n - 1) := cnt + when(cnt >= n.asUInt) { val expected = cnt - n.asUInt assert(shifter(0) === expected) } - when (wrap) { + when(wrap) { stop() } } @@ -299,10 +302,10 @@ class ModuleIODynamicIndexTester(n: Int) extends BasicTester { val (cycle, done) = Counter(true.B, n) for ((m, i) <- duts.zipWithIndex) { - when (cycle =/= i.U) { - m.in := 0.U // default + when(cycle =/= i.U) { + m.in := 0.U // default assert(m.out === 0.U) - } .otherwise { + }.otherwise { m.in := DontCare } } @@ -310,7 +313,7 @@ class ModuleIODynamicIndexTester(n: Int) extends BasicTester { duts(cycle) <> tester.io assert(duts(cycle).out === 123.U) - when (done) { stop() } + when(done) { stop() } } class ReduceTreeTester() extends BasicTester { @@ -349,84 +352,107 @@ class VecSpec extends ChiselPropSpec with Utils { implicit val noShrinkInt = Shrink[Int](_ => Stream.empty) property("Vecs should be assignable") { - forAll(safeUIntN(8)) { case(w: Int, v: List[Int]) => - assertTesterPasses{ new ValueTester(w, v) } + forAll(safeUIntN(8)) { + case (w: Int, v: List[Int]) => + assertTesterPasses { new ValueTester(w, v) } } } property("Vecs should be passed through vec IO") { - forAll(safeUIntN(8)) { case(w: Int, v: List[Int]) => - assertTesterPasses{ new IOTester(w, v) } + forAll(safeUIntN(8)) { + case (w: Int, v: List[Int]) => + assertTesterPasses { new IOTester(w, v) } } } property("Vec.fill with a pure type should generate an exception") { // We don't really need a sequence of random widths here, since any should throw an exception. - forAll(safeUIntWidth) { case(w: Int) => - an[BindingException] should be thrownBy extractCause[BindingException] { - ChiselStage.elaborate(new IOTesterModFill(w)) - } + forAll(safeUIntWidth) { + case (w: Int) => + an[BindingException] should be thrownBy extractCause[BindingException] { + ChiselStage.elaborate(new IOTesterModFill(w)) + } } } property("A Reg of a Vec should operate correctly") { - forAll(safeUIntN(8)) { case(w: Int, v: List[Int]) => - assertTesterPasses{ new RegTester(w, v) } + forAll(safeUIntN(8)) { + case (w: Int, v: List[Int]) => + assertTesterPasses { new RegTester(w, v) } } } property("A Vec of lit should operate correctly") { - forAll(safeUIntN(8)) { case(w: Int, v: List[Int]) => - assertTesterPasses{ new LitTester(w, v) } + forAll(safeUIntN(8)) { + case (w: Int, v: List[Int]) => + assertTesterPasses { new LitTester(w, v) } } } property("VecInit should tabulate correctly") { - forAll(smallPosInts) { (n: Int) => assertTesterPasses{ new TabulateTester(n) } } + forAll(smallPosInts) { (n: Int) => assertTesterPasses { new TabulateTester(n) } } } property("VecInit should tabulate 2D vec correctly") { - forAll(smallPosInts, smallPosInts) { (n: Int, m: Int) => assertTesterPasses { new VecMultiDimTester.TabulateTester2D(n, m) } } + forAll(smallPosInts, smallPosInts) { (n: Int, m: Int) => + assertTesterPasses { new VecMultiDimTester.TabulateTester2D(n, m) } + } } property("VecInit should tabulate 3D vec correctly") { - forAll(smallPosInts, smallPosInts, smallPosInts) { (n: Int, m: Int, p: Int) => assertTesterPasses{ new VecMultiDimTester.TabulateTester3D(n, m, p) } } + forAll(smallPosInts, smallPosInts, smallPosInts) { (n: Int, m: Int, p: Int) => + assertTesterPasses { new VecMultiDimTester.TabulateTester3D(n, m, p) } + } } property("VecInit should fill correctly") { - forAll(smallPosInts, Gen.choose(0, 50)) { (n: Int, value: Int) => assertTesterPasses{ new FillTester(n, value) } } + forAll(smallPosInts, Gen.choose(0, 50)) { (n: Int, value: Int) => assertTesterPasses { new FillTester(n, value) } } } property("VecInit should fill 2D vec correctly") { - forAll(smallPosInts, smallPosInts, Gen.choose(0, 50)) { (n: Int, m: Int, value: Int) => assertTesterPasses{ new VecMultiDimTester.Fill2DTester(n, m, value) } } + forAll(smallPosInts, smallPosInts, Gen.choose(0, 50)) { (n: Int, m: Int, value: Int) => + assertTesterPasses { new VecMultiDimTester.Fill2DTester(n, m, value) } + } } - + property("VecInit should fill 3D vec correctly") { - forAll(smallPosInts, smallPosInts, smallPosInts, Gen.choose(0, 50)) { (n: Int, m: Int, p: Int, value: Int) => assertTesterPasses{ new VecMultiDimTester.Fill3DTester(n, m, p, value) } } + forAll(smallPosInts, smallPosInts, smallPosInts, Gen.choose(0, 50)) { (n: Int, m: Int, p: Int, value: Int) => + assertTesterPasses { new VecMultiDimTester.Fill3DTester(n, m, p, value) } + } } property("VecInit should support 2D fill bidirectional wire connection") { - forAll(smallPosInts, smallPosInts) { (n: Int, m: Int) => assertTesterPasses{ new VecMultiDimTester.BidirectionalTester2DFill(n, m) }} + forAll(smallPosInts, smallPosInts) { (n: Int, m: Int) => + assertTesterPasses { new VecMultiDimTester.BidirectionalTester2DFill(n, m) } + } } - + property("VecInit should support 3D fill bidirectional wire connection") { - forAll(smallPosInts, smallPosInts, smallPosInts) { (n: Int, m: Int, p: Int) => assertTesterPasses{ new VecMultiDimTester.BidirectionalTester3DFill(n, m, p) }} + forAll(smallPosInts, smallPosInts, smallPosInts) { (n: Int, m: Int, p: Int) => + assertTesterPasses { new VecMultiDimTester.BidirectionalTester3DFill(n, m, p) } + } } property("VecInit should support 2D tabulate bidirectional wire connection") { - forAll(smallPosInts, smallPosInts) { (n: Int, m: Int) => assertTesterPasses{ new VecMultiDimTester.BidirectionalTester2DTabulate(n, m) }} + forAll(smallPosInts, smallPosInts) { (n: Int, m: Int) => + assertTesterPasses { new VecMultiDimTester.BidirectionalTester2DTabulate(n, m) } + } } - + property("VecInit should support 3D tabulate bidirectional wire connection") { - forAll(smallPosInts, smallPosInts, smallPosInts) { (n: Int, m: Int, p: Int) => assertTesterPasses{ new VecMultiDimTester.BidirectionalTester3DTabulate(n, m, p) }} + forAll(smallPosInts, smallPosInts, smallPosInts) { (n: Int, m: Int, p: Int) => + assertTesterPasses { new VecMultiDimTester.BidirectionalTester3DTabulate(n, m, p) } + } } - + property("VecInit should iterate correctly") { - forAll(Gen.choose(1, 10), smallPosInts) { (start: Int, len: Int) => assertTesterPasses{ new IterateTester(start, len)(x => x + 50.U)}} + forAll(Gen.choose(1, 10), smallPosInts) { (start: Int, len: Int) => + assertTesterPasses { new IterateTester(start, len)(x => x + 50.U) } + } } property("Regs of vecs should be usable as shift registers") { - forAll(smallPosInts) { (n: Int) => assertTesterPasses{ new ShiftRegisterTester(n) } } + forAll(smallPosInts) { (n: Int) => assertTesterPasses { new ShiftRegisterTester(n) } } } property("Infering widths on huge Vecs should not cause a stack overflow") { @@ -434,15 +460,15 @@ class VecSpec extends ChiselPropSpec with Utils { } property("A Reg of a Vec of a single 1 bit element should compile and work") { - assertTesterPasses{ new OneBitUnitRegVecTester } + assertTesterPasses { new OneBitUnitRegVecTester } } property("A Vec with zero entries should compile and have zero width") { - assertTesterPasses{ new ZeroEntryVecTester } + assertTesterPasses { new ZeroEntryVecTester } } property("Dynamic indexing of a Vec of Module IOs should work") { - assertTesterPasses{ new ModuleIODynamicIndexTester(4) } + assertTesterPasses { new ModuleIODynamicIndexTester(4) } } property("It should be possible to bulk connect a Vec and a Seq") { @@ -456,7 +482,7 @@ class VecSpec extends ChiselPropSpec with Utils { } property("Bulk connecting a Vec and Seq of different sizes should report a ChiselException") { - a [ChiselException] should be thrownBy extractCause[ChiselException] { + a[ChiselException] should be thrownBy extractCause[ChiselException] { ChiselStage.elaborate(new Module { val io = IO(new Bundle { val out = Output(Vec(4, UInt(8.W))) @@ -477,17 +503,18 @@ class VecSpec extends ChiselPropSpec with Utils { } property("Indexing a Chisel type Vec by a hardware type should give a sane error message") { - a [ExpectedHardwareException] should be thrownBy extractCause[ChiselException] { - ChiselStage.elaborate{ + a[ExpectedHardwareException] should be thrownBy extractCause[ChiselException] { + ChiselStage.elaborate { new Module { - val io = IO(new Bundle{}) + val io = IO(new Bundle {}) val foo = Vec(2, Bool()) foo(0.U) := false.B - }} + } + } } } property("reduceTree should preserve input/output type") { - assertTesterPasses { new ReduceTreeTester() } + assertTesterPasses { new ReduceTreeTester() } } } diff --git a/src/test/scala/chiselTests/VecLiteralSpec.scala b/src/test/scala/chiselTests/VecLiteralSpec.scala index 74d8c005..228f409b 100644 --- a/src/test/scala/chiselTests/VecLiteralSpec.scala +++ b/src/test/scala/chiselTests/VecLiteralSpec.scala @@ -20,10 +20,10 @@ class VecLiteralSpec extends ChiselFreeSpec with Utils { } "Vec literals should work with chisel Enums" in { - val enumVec = Vec(3, MyEnum()).Lit(0 -> MyEnum.sA, 1 -> MyEnum.sB, 2-> MyEnum.sC) - enumVec(0).toString should include (MyEnum.sA.toString) - enumVec(1).toString should include (MyEnum.sB.toString) - enumVec(2).toString should include (MyEnum.sC.toString) + val enumVec = Vec(3, MyEnum()).Lit(0 -> MyEnum.sA, 1 -> MyEnum.sB, 2 -> MyEnum.sC) + enumVec(0).toString should include(MyEnum.sA.toString) + enumVec(1).toString should include(MyEnum.sB.toString) + enumVec(2).toString should include(MyEnum.sC.toString) } "improperly constructed vec literals should be detected" - { @@ -31,7 +31,7 @@ class VecLiteralSpec extends ChiselFreeSpec with Utils { val e = intercept[VecLiteralException] { Vec(2, UInt(4.W)).Lit(0 -> 1.U, 1 -> 2.U, 2 -> 3.U, 3 -> 4.U, -2 -> 7.U) } - e.getMessage should include ( + e.getMessage should include( "VecLiteral: The following indices (2,3,-2) are less than zero or greater or equal to than Vec length" ) } @@ -56,7 +56,7 @@ class VecLiteralSpec extends ChiselFreeSpec with Utils { val v = Vec(2, SInt(4.W)).Lit(0 -> 1.S, 1 -> -2.S) v(0).toString should include(1.S(4.W).toString) v(1).toString should include((-2).S(4.W).toString) - v.toString should include ("SInt<4>[2](0=SLit(1,<4>), 1=SLit(-2,<4>)") + v.toString should include("SInt<4>[2](0=SLit(1,<4>), 1=SLit(-2,<4>)") } "all lits must be the same type but width cannot be greater than Vec's element width" in { @@ -71,7 +71,7 @@ class VecLiteralSpec extends ChiselFreeSpec with Utils { //NOTE: I had problems where this would not work if this class declaration was inside test scope class HasVecInit extends Module { - val initValue = Vec(4, UInt(8.W)).Lit(0 -> 0xAB.U(8.W), 1 -> 0xCD.U(8.W), 2 -> 0xEF.U(8.W), 3 -> 0xFF.U(8.W)) + val initValue = Vec(4, UInt(8.W)).Lit(0 -> 0xab.U(8.W), 1 -> 0xcd.U(8.W), 2 -> 0xef.U(8.W), 3 -> 0xff.U(8.W)) val y = RegInit(initValue) } @@ -86,7 +86,7 @@ class VecLiteralSpec extends ChiselFreeSpec with Utils { //NOTE: I had problems where this would not work if this class declaration was inside test scope class HasPartialVecInit extends Module { - val initValue = Vec(4, UInt(8.W)).Lit(0 -> 0xAB.U(8.W), 2 -> 0xEF.U(8.W), 3 -> 0xFF.U(8.W)) + val initValue = Vec(4, UInt(8.W)).Lit(0 -> 0xab.U(8.W), 2 -> 0xef.U(8.W), 3 -> 0xff.U(8.W)) val y = RegInit(initValue) } @@ -102,7 +102,7 @@ class VecLiteralSpec extends ChiselFreeSpec with Utils { class ResetRegWithPartialVecLiteral extends Module { val in = IO(Input(Vec(4, UInt(8.W)))) val out = IO(Output(Vec(4, UInt(8.W)))) - val initValue = Vec(4, UInt(8.W)).Lit(0 -> 0xAB.U(8.W), 2 -> 0xEF.U(8.W), 3 -> 0xFF.U(8.W)) + val initValue = Vec(4, UInt(8.W)).Lit(0 -> 0xab.U(8.W), 2 -> 0xef.U(8.W), 3 -> 0xff.U(8.W)) val y = RegInit(initValue) when(in(1) > 0.U) { y(1) := in(1) @@ -132,7 +132,7 @@ class VecLiteralSpec extends ChiselFreeSpec with Utils { }.elsewhen(counter > 2.U) { // m.out(1) should not be reset, m.out(2) should be reset chisel3.assert(m.out(1) === 0xff.U) - chisel3.assert(m.out(2) === 0xEF.U) + chisel3.assert(m.out(2) === 0xef.U) } when(wrapped) { stop() @@ -141,12 +141,12 @@ class VecLiteralSpec extends ChiselFreeSpec with Utils { } "lowest of vec literal contains least significant bits and " in { - val y = Vec(4, UInt(8.W)).Lit(0 -> 0xAB.U(8.W), 1 -> 0xCD.U(8.W), 2 -> 0xEF.U(8.W), 3 -> 0xFF.U(8.W)) + val y = Vec(4, UInt(8.W)).Lit(0 -> 0xab.U(8.W), 1 -> 0xcd.U(8.W), 2 -> 0xef.U(8.W), 3 -> 0xff.U(8.W)) y.litValue should be(BigInt("FFEFCDAB", 16)) } "the order lits are specified does not matter" in { - val y = Vec(4, UInt(8.W)).Lit(3 -> 0xFF.U(8.W), 2 -> 0xEF.U(8.W), 1 -> 0xCD.U(8.W), 0 -> 0xAB.U(8.W)) + val y = Vec(4, UInt(8.W)).Lit(3 -> 0xff.U(8.W), 2 -> 0xef.U(8.W), 1 -> 0xcd.U(8.W), 0 -> 0xab.U(8.W)) y.litValue should be(BigInt("FFEFCDAB", 16)) } @@ -164,7 +164,7 @@ class VecLiteralSpec extends ChiselFreeSpec with Utils { "registers can be initialized with a Vec literal" in { assertTesterPasses(new BasicTester { - val y = RegInit(Vec(4, UInt(8.W)).Lit(0 -> 0xAB.U(8.W), 1 -> 0xCD.U(8.W), 2 -> 0xEF.U(8.W), 3 -> 0xFF.U(8.W))) + val y = RegInit(Vec(4, UInt(8.W)).Lit(0 -> 0xab.U(8.W), 1 -> 0xcd.U(8.W), 2 -> 0xef.U(8.W), 3 -> 0xff.U(8.W))) chisel3.assert(y.asUInt === BigInt("FFEFCDAB", 16).U) stop() }) @@ -172,9 +172,9 @@ class VecLiteralSpec extends ChiselFreeSpec with Utils { "how does asUInt work" in { assertTesterPasses(new BasicTester { - val vec1 = Vec(4, UInt(16.W)).Lit(0 -> 0xDD.U, 1 -> 0xCC.U, 2 -> 0xBB.U, 3 -> 0xAA.U) + val vec1 = Vec(4, UInt(16.W)).Lit(0 -> 0xdd.U, 1 -> 0xcc.U, 2 -> 0xbb.U, 3 -> 0xaa.U) - val vec2 = VecInit(Seq(0xDD.U, 0xCC.U, 0xBB.U, 0xAA.U)) + val vec2 = VecInit(Seq(0xdd.U, 0xcc.U, 0xbb.U, 0xaa.U)) printf("vec1 %x\n", vec1.asUInt()) printf("vec2 %x\n", vec2.asUInt()) stop() @@ -186,10 +186,10 @@ class VecLiteralSpec extends ChiselFreeSpec with Utils { val out1 = IO(Output(UInt(64.W))) val out2 = IO(Output(UInt(64.W))) - val v1 = Vec(4, UInt(16.W)).Lit(0 -> 0xDD.U, 1 -> 0xCC.U, 2 -> 0xBB.U, 3 -> 0xAA.U) + val v1 = Vec(4, UInt(16.W)).Lit(0 -> 0xdd.U, 1 -> 0xcc.U, 2 -> 0xbb.U, 3 -> 0xaa.U) out1 := v1.asUInt - val v2 = VecInit(0xDD.U(16.W), 0xCC.U, 0xBB.U, 0xAA.U) + val v2 = VecInit(0xdd.U(16.W), 0xcc.U, 0xbb.U, 0xaa.U) out2 := v2.asUInt } @@ -201,33 +201,33 @@ class VecLiteralSpec extends ChiselFreeSpec with Utils { } "VecLits should work properly with .asUInt" in { - val outsideVecLit = Vec(4, UInt(16.W)).Lit(0 -> 0xDD.U, 1 -> 0xCC.U, 2 -> 0xBB.U, 3 -> 0xAA.U) + val outsideVecLit = Vec(4, UInt(16.W)).Lit(0 -> 0xdd.U, 1 -> 0xcc.U, 2 -> 0xbb.U, 3 -> 0xaa.U) assertTesterPasses { new BasicTester { - chisel3.assert(outsideVecLit(0) === 0xDD.U, s"v(0)") + chisel3.assert(outsideVecLit(0) === 0xdd.U, s"v(0)") stop() } } } "bundle literals should work in RTL" in { - val outsideVecLit = Vec(4, UInt(16.W)).Lit(0 -> 0xDD.U, 1 -> 0xCC.U, 2 -> 0xBB.U, 3 -> 0xAA.U) + val outsideVecLit = Vec(4, UInt(16.W)).Lit(0 -> 0xdd.U, 1 -> 0xcc.U, 2 -> 0xbb.U, 3 -> 0xaa.U) assertTesterPasses { new BasicTester { - chisel3.assert(outsideVecLit(0) === 0xDD.U, s"v(0)") - chisel3.assert(outsideVecLit(1) === 0xCC.U) - chisel3.assert(outsideVecLit(2) === 0xBB.U) - chisel3.assert(outsideVecLit(3) === 0xAA.U) + chisel3.assert(outsideVecLit(0) === 0xdd.U, s"v(0)") + chisel3.assert(outsideVecLit(1) === 0xcc.U) + chisel3.assert(outsideVecLit(2) === 0xbb.U) + chisel3.assert(outsideVecLit(3) === 0xaa.U) chisel3.assert(outsideVecLit.litValue.U === outsideVecLit.asUInt()) - val insideVecLit = Vec(4, UInt(16.W)).Lit(0 -> 0xDD.U, 1 -> 0xCC.U, 2 -> 0xBB.U, 3 -> 0xAA.U) - chisel3.assert(insideVecLit(0) === 0xDD.U) - chisel3.assert(insideVecLit(1) === 0xCC.U) - chisel3.assert(insideVecLit(2) === 0xBB.U) - chisel3.assert(insideVecLit(3) === 0xAA.U) + val insideVecLit = Vec(4, UInt(16.W)).Lit(0 -> 0xdd.U, 1 -> 0xcc.U, 2 -> 0xbb.U, 3 -> 0xaa.U) + chisel3.assert(insideVecLit(0) === 0xdd.U) + chisel3.assert(insideVecLit(1) === 0xcc.U) + chisel3.assert(insideVecLit(2) === 0xbb.U) + chisel3.assert(insideVecLit(3) === 0xaa.U) chisel3.assert(insideVecLit(0) === outsideVecLit(0)) chisel3.assert(insideVecLit(1) === outsideVecLit(1)) @@ -237,18 +237,18 @@ class VecLiteralSpec extends ChiselFreeSpec with Utils { val vecWire1 = Wire(Vec(4, UInt(16.W))) vecWire1 := outsideVecLit - chisel3.assert(vecWire1(0) === 0xDD.U) - chisel3.assert(vecWire1(1) === 0xCC.U) - chisel3.assert(vecWire1(2) === 0xBB.U) - chisel3.assert(vecWire1(3) === 0xAA.U) + chisel3.assert(vecWire1(0) === 0xdd.U) + chisel3.assert(vecWire1(1) === 0xcc.U) + chisel3.assert(vecWire1(2) === 0xbb.U) + chisel3.assert(vecWire1(3) === 0xaa.U) val vecWire2 = Wire(Vec(4, UInt(16.W))) vecWire2 := insideVecLit - chisel3.assert(vecWire2(0) === 0xDD.U) - chisel3.assert(vecWire2(1) === 0xCC.U) - chisel3.assert(vecWire2(2) === 0xBB.U) - chisel3.assert(vecWire2(3) === 0xAA.U) + chisel3.assert(vecWire2(0) === 0xdd.U) + chisel3.assert(vecWire2(1) === 0xcc.U) + chisel3.assert(vecWire2(2) === 0xbb.U) + chisel3.assert(vecWire2(3) === 0xaa.U) stop() } @@ -256,19 +256,21 @@ class VecLiteralSpec extends ChiselFreeSpec with Utils { } "partial vec literals should work in RTL" in { - assertTesterPasses{ new BasicTester{ - val vecLit = Vec(4, UInt(8.W)).Lit(0 -> 42.U, 2 -> 5.U) - chisel3.assert(vecLit(0) === 42.U) - chisel3.assert(vecLit(2) === 5.U) + assertTesterPasses { + new BasicTester { + val vecLit = Vec(4, UInt(8.W)).Lit(0 -> 42.U, 2 -> 5.U) + chisel3.assert(vecLit(0) === 42.U) + chisel3.assert(vecLit(2) === 5.U) - val vecWire = Wire(Vec(4, UInt(8.W))) - vecWire := vecLit + val vecWire = Wire(Vec(4, UInt(8.W))) + vecWire := vecLit - chisel3.assert(vecWire(0) === 42.U) - chisel3.assert(vecWire(2) === 5.U) + chisel3.assert(vecWire(0) === 42.U) + chisel3.assert(vecWire(2) === 5.U) - stop() - }} + stop() + } + } } "nested vec literals should be constructable" in { @@ -277,42 +279,44 @@ class VecLiteralSpec extends ChiselFreeSpec with Utils { 1 -> Vec(3, UInt(4.W)).Lit(0 -> 4.U, 1 -> 5.U, 2 -> 6.U) ) - outerVec.litValue should be (BigInt("654321", 16)) - outerVec(0).litValue should be (BigInt("321", 16)) - outerVec(1).litValue should be (BigInt("654", 16)) - outerVec(0)(0).litValue should be (BigInt(1)) - outerVec(0)(1).litValue should be (BigInt(2)) - outerVec(0)(2).litValue should be (BigInt(3)) - outerVec(1)(0).litValue should be (BigInt(4)) - outerVec(1)(1).litValue should be (BigInt(5)) - outerVec(1)(2).litValue should be (BigInt(6)) + outerVec.litValue should be(BigInt("654321", 16)) + outerVec(0).litValue should be(BigInt("321", 16)) + outerVec(1).litValue should be(BigInt("654", 16)) + outerVec(0)(0).litValue should be(BigInt(1)) + outerVec(0)(1).litValue should be(BigInt(2)) + outerVec(0)(2).litValue should be(BigInt(3)) + outerVec(1)(0).litValue should be(BigInt(4)) + outerVec(1)(1).litValue should be(BigInt(5)) + outerVec(1)(2).litValue should be(BigInt(6)) } "contained vecs should work" in { - assertTesterPasses{ new BasicTester { - val outerVec = Vec(2, Vec(3, UInt(4.W))).Lit( - 0 -> Vec(3, UInt(4.W)).Lit(0 -> 1.U, 1 -> 2.U, 2 -> 3.U), - 1 -> Vec(3, UInt(4.W)).Lit(0 -> 4.U, 1 -> 5.U, 2 -> 6.U) - ) - - chisel3.assert(outerVec(0)(0) === 1.U) - chisel3.assert(outerVec(0)(1) === 2.U) - chisel3.assert(outerVec(0)(2) === 3.U) - chisel3.assert(outerVec(1)(0) === 4.U) - chisel3.assert(outerVec(1)(1) === 5.U) - chisel3.assert(outerVec(1)(2) === 6.U) - - val v0 = outerVec(0) - val v1 = outerVec(1) - chisel3.assert(v0(0) === 1.U) - chisel3.assert(v0(1) === 2.U) - chisel3.assert(v0(2) === 3.U) - chisel3.assert(v1(0) === 4.U) - chisel3.assert(v1(1) === 5.U) - chisel3.assert(v1(2) === 6.U) + assertTesterPasses { + new BasicTester { + val outerVec = Vec(2, Vec(3, UInt(4.W))).Lit( + 0 -> Vec(3, UInt(4.W)).Lit(0 -> 1.U, 1 -> 2.U, 2 -> 3.U), + 1 -> Vec(3, UInt(4.W)).Lit(0 -> 4.U, 1 -> 5.U, 2 -> 6.U) + ) + + chisel3.assert(outerVec(0)(0) === 1.U) + chisel3.assert(outerVec(0)(1) === 2.U) + chisel3.assert(outerVec(0)(2) === 3.U) + chisel3.assert(outerVec(1)(0) === 4.U) + chisel3.assert(outerVec(1)(1) === 5.U) + chisel3.assert(outerVec(1)(2) === 6.U) + + val v0 = outerVec(0) + val v1 = outerVec(1) + chisel3.assert(v0(0) === 1.U) + chisel3.assert(v0(1) === 2.U) + chisel3.assert(v0(2) === 3.U) + chisel3.assert(v1(0) === 4.U) + chisel3.assert(v1(1) === 5.U) + chisel3.assert(v1(2) === 6.U) - stop() - }} + stop() + } + } } //TODO: decide what behavior here should be @@ -360,13 +364,13 @@ class VecLiteralSpec extends ChiselFreeSpec with Utils { "Vec literals should work as register reset values" in { assertTesterPasses { new BasicTester { - val r = RegInit(Vec(3, UInt(11.W)).Lit(0 -> 0xA.U, 1 -> 0xB.U, 2 -> 0xC.U)) + val r = RegInit(Vec(3, UInt(11.W)).Lit(0 -> 0xa.U, 1 -> 0xb.U, 2 -> 0xc.U)) r := (r.asUInt + 1.U).asTypeOf(Vec(3, UInt(11.W))) // prevent constprop // check reset values on first cycle out of reset - chisel3.assert(r(0) === 0xA.U) - chisel3.assert(r(1) === 0xB.U) - chisel3.assert(r(2) === 0xC.U) + chisel3.assert(r(0) === 0xa.U) + chisel3.assert(r(1) === 0xb.U) + chisel3.assert(r(2) === 0xc.U) stop() } } @@ -375,11 +379,11 @@ class VecLiteralSpec extends ChiselFreeSpec with Utils { "partially initialized Vec literals should work as register reset values" in { assertTesterPasses { new BasicTester { - val r = RegInit(Vec(3, UInt(11.W)).Lit(0 -> 0xA.U, 2 -> 0xC.U)) + val r = RegInit(Vec(3, UInt(11.W)).Lit(0 -> 0xa.U, 2 -> 0xc.U)) r := (r.asUInt + 1.U).asTypeOf(Vec(3, UInt(11.W))) // prevent constprop // check reset values on first cycle out of reset - chisel3.assert(r(0) === 0xA.U) - chisel3.assert(r(2) === 0xC.U) + chisel3.assert(r(0) === 0xa.U) + chisel3.assert(r(2) === 0xc.U) stop() } } @@ -388,9 +392,9 @@ class VecLiteralSpec extends ChiselFreeSpec with Utils { "Fields extracted from Vec Literals should work as register reset values" in { assertTesterPasses { new BasicTester { - val r = RegInit(Vec(3, UInt(11.W)).Lit(0 -> 0xA.U, 2 -> 0xC.U).apply(0)) + val r = RegInit(Vec(3, UInt(11.W)).Lit(0 -> 0xa.U, 2 -> 0xc.U).apply(0)) r := r + 1.U // prevent const prop - chisel3.assert(r === 0xA.U) // coming out of reset + chisel3.assert(r === 0xa.U) // coming out of reset stop() } } diff --git a/src/test/scala/chiselTests/VectorPacketIO.scala b/src/test/scala/chiselTests/VectorPacketIO.scala index c4b0f1f7..1474177f 100644 --- a/src/test/scala/chiselTests/VectorPacketIO.scala +++ b/src/test/scala/chiselTests/VectorPacketIO.scala @@ -28,7 +28,7 @@ class Packet extends Bundle { * The problem does not occur if the Vec is taken out */ class VectorPacketIO(val n: Int) extends Bundle { - val ins = Vec(n, chisel3.util.DeqIO(new Packet())) + val ins = Vec(n, chisel3.util.DeqIO(new Packet())) val outs = Vec(n, chisel3.util.EnqIO(new Packet())) } @@ -37,7 +37,7 @@ class VectorPacketIO(val n: Int) extends Bundle { * the value of n does not affect the error */ class BrokenVectorPacketModule extends Module { - val n = 4 + val n = 4 val io = IO(new VectorPacketIO(n)) // Avoid a "Reference io is not fully initialized" error from firrtl. diff --git a/src/test/scala/chiselTests/VerificationSpec.scala b/src/test/scala/chiselTests/VerificationSpec.scala index 2d7144df..95b0ffe6 100644 --- a/src/test/scala/chiselTests/VerificationSpec.scala +++ b/src/test/scala/chiselTests/VerificationSpec.scala @@ -11,13 +11,13 @@ import org.scalatest.matchers.should.Matchers import java.io.File class SimpleTest extends Module { - val io = IO(new Bundle{ + val io = IO(new Bundle { val in = Input(UInt(8.W)) val out = Output(UInt(8.W)) }) io.out := io.in cover(io.in === 3.U) - when (io.in === 3.U) { + when(io.in === 3.U) { assume(io.in =/= 2.U) assert(io.out === io.in) } @@ -31,6 +31,7 @@ case class VerifAnnotation(target: ReferenceTarget) extends SingleTargetAnnotati } object VerifAnnotation { + /** Create annotation for a given verification component. * @param c component to be annotated */ @@ -64,9 +65,10 @@ class VerificationSpec extends ChiselPropSpec with Matchers { } property("annotation of verification constructs should work") { + /** Circuit that contains and annotates verification nodes. */ class AnnotationTest extends Module { - val io = IO(new Bundle{ + val io = IO(new Bundle { val in = Input(UInt(8.W)) val out = Output(UInt(8.W)) }) @@ -92,10 +94,10 @@ class VerificationSpec extends ChiselPropSpec with Matchers { val annoLines = scala.io.Source.fromFile(annoFile).getLines.toList // check for expected verification annotations - exactly(3, annoLines) should include ("chiselTests.VerifAnnotation") - exactly(1, annoLines) should include ("~AnnotationTest|AnnotationTest>asst") - exactly(1, annoLines) should include ("~AnnotationTest|AnnotationTest>assm") - exactly(1, annoLines) should include ("~AnnotationTest|AnnotationTest>cov") + exactly(3, annoLines) should include("chiselTests.VerifAnnotation") + exactly(1, annoLines) should include("~AnnotationTest|AnnotationTest>asst") + exactly(1, annoLines) should include("~AnnotationTest|AnnotationTest>assm") + exactly(1, annoLines) should include("~AnnotationTest|AnnotationTest>cov") // read in FIRRTL file val firFile = new File(testDir, "AnnotationTest.fir") @@ -103,15 +105,16 @@ class VerificationSpec extends ChiselPropSpec with Matchers { val firLines = scala.io.Source.fromFile(firFile).getLines.toList // check that verification components have expected names - exactly(1, firLines) should include ("cover(clock, _T, UInt<1>(\"h1\"), \"\") : cov") - exactly(1, firLines) should include ("assume(clock, _T_3, UInt<1>(\"h1\"), \"\") : assm") - exactly(1, firLines) should include ("assert(clock, _T_7, UInt<1>(\"h1\"), \"\") : asst") + exactly(1, firLines) should include("cover(clock, _T, UInt<1>(\"h1\"), \"\") : cov") + exactly(1, firLines) should include("assume(clock, _T_3, UInt<1>(\"h1\"), \"\") : assm") + exactly(1, firLines) should include("assert(clock, _T_7, UInt<1>(\"h1\"), \"\") : asst") } property("annotation of verification constructs with suggested name should work") { + /** Circuit that annotates a renamed verification nodes. */ class AnnotationRenameTest extends Module { - val io = IO(new Bundle{ + val io = IO(new Bundle { val in = Input(UInt(8.W)) val out = Output(UInt(8.W)) }) @@ -137,9 +140,9 @@ class VerificationSpec extends ChiselPropSpec with Matchers { val annoLines = scala.io.Source.fromFile(annoFile).getLines.toList // check for expected verification annotations - exactly(2, annoLines) should include ("chiselTests.VerifAnnotation") - exactly(1, annoLines) should include ("~AnnotationRenameTest|AnnotationRenameTest>hello") - exactly(1, annoLines) should include ("~AnnotationRenameTest|AnnotationRenameTest>howdy") + exactly(2, annoLines) should include("chiselTests.VerifAnnotation") + exactly(1, annoLines) should include("~AnnotationRenameTest|AnnotationRenameTest>hello") + exactly(1, annoLines) should include("~AnnotationRenameTest|AnnotationRenameTest>howdy") // read in FIRRTL file val firFile = new File(testDir, "AnnotationRenameTest.fir") @@ -147,7 +150,7 @@ class VerificationSpec extends ChiselPropSpec with Matchers { val firLines = scala.io.Source.fromFile(firFile).getLines.toList // check that verification components have expected names - exactly(1, firLines) should include ("assert(clock, _T, UInt<1>(\"h1\"), \"\") : hello") - exactly(1, firLines) should include ("assume(clock, _T_4, UInt<1>(\"h1\"), \"\") : howdy") + exactly(1, firLines) should include("assert(clock, _T, UInt<1>(\"h1\"), \"\") : hello") + exactly(1, firLines) should include("assume(clock, _T_4, UInt<1>(\"h1\"), \"\") : howdy") } } diff --git a/src/test/scala/chiselTests/When.scala b/src/test/scala/chiselTests/When.scala index 3b5ec62e..032a8eac 100644 --- a/src/test/scala/chiselTests/When.scala +++ b/src/test/scala/chiselTests/When.scala @@ -14,11 +14,11 @@ class WhenTester() extends BasicTester { val out = Wire(UInt(3.W)) when(cnt.value === 0.U) { out := 1.U - } .elsewhen (cnt.value === 1.U) { + }.elsewhen(cnt.value === 1.U) { out := 2.U - } .elsewhen (cnt.value === 2.U) { + }.elsewhen(cnt.value === 2.U) { out := 3.U - } .otherwise { + }.otherwise { out := 0.U } @@ -36,11 +36,11 @@ class OverlappedWhenTester() extends BasicTester { val out = Wire(UInt(3.W)) when(cnt.value <= 0.U) { out := 1.U - } .elsewhen (cnt.value <= 1.U) { + }.elsewhen(cnt.value <= 1.U) { out := 2.U - } .elsewhen (cnt.value <= 2.U) { + }.elsewhen(cnt.value <= 2.U) { out := 3.U - } .otherwise { + }.otherwise { out := 0.U } @@ -58,13 +58,13 @@ class NoOtherwiseOverlappedWhenTester() extends BasicTester { val out = Wire(UInt(3.W)) when(cnt.value <= 0.U) { out := 1.U - } .elsewhen (cnt.value <= 1.U) { + }.elsewhen(cnt.value <= 1.U) { out := 2.U - } .elsewhen (cnt.value <= 2.U) { + }.elsewhen(cnt.value <= 2.U) { out := 3.U - } .elsewhen (cnt.value <= 3.U) { + }.elsewhen(cnt.value <= 3.U) { out := 0.U - } .otherwise { + }.otherwise { out := DontCare } @@ -77,15 +77,14 @@ class NoOtherwiseOverlappedWhenTester() extends BasicTester { class SubmoduleWhenTester extends BasicTester { val (cycle, done) = Counter(true.B, 3) - when (done) { stop() } - val children = Seq(Module(new PassthroughModule), - Module(new PassthroughMultiIOModule), - Module(new PassthroughRawModule)) + when(done) { stop() } + val children = + Seq(Module(new PassthroughModule), Module(new PassthroughMultiIOModule), Module(new PassthroughRawModule)) children.foreach { child => - when (cycle === 1.U) { + when(cycle === 1.U) { child.io.in := "hdeadbeef".U assert(child.io.out === "hdeadbeef".U) - } .otherwise { + }.otherwise { child.io.in := "h0badcad0".U assert(child.io.out === "h0badcad0".U) } @@ -97,17 +96,17 @@ class WhenCondTester extends BasicTester { val (cycle, done) = Counter(true.B, 1 << pred.size) // Cycle through every predicate pred := cycle.asBools - val Seq(a, b, c, d) = pred // Just for nicer accessors + val Seq(a, b, c, d) = pred // Just for nicer accessors // When want the when predicates on connection to optimize away, // it's not necessary but it makes the Verilog prettier val w1, w2, w3, w4, w5, w6, w7 = WireInit(Bool(), DontCare) - when (a) { + when(a) { w1 := when.cond - when (b) { + when(b) { w2 := when.cond - }.elsewhen (c) { + }.elsewhen(c) { w3 := when.cond - }.elsewhen (d) { + }.elsewhen(d) { w4 := when.cond }.otherwise { w5 := when.cond @@ -125,18 +124,18 @@ class WhenCondTester extends BasicTester { assert(w6 === !a) assert(w7) - when (done) { stop() } + when(done) { stop() } } class WhenSpec extends ChiselFlatSpec with Utils { "When, elsewhen, and otherwise with orthogonal conditions" should "work" in { - assertTesterPasses{ new WhenTester } + assertTesterPasses { new WhenTester } } "When, elsewhen, and otherwise with overlapped conditions" should "work" in { - assertTesterPasses{ new OverlappedWhenTester } + assertTesterPasses { new OverlappedWhenTester } } "When and elsewhen without otherwise with overlapped conditions" should "work" in { - assertTesterPasses{ new NoOtherwiseOverlappedWhenTester } + assertTesterPasses { new NoOtherwiseOverlappedWhenTester } } "Conditional connections to submodule ports" should "be handled properly" in { assertTesterPasses(new SubmoduleWhenTester) @@ -146,7 +145,7 @@ class WhenSpec extends ChiselFlatSpec with Utils { } "Returning in a when scope" should "give a reasonable error message" in { - val e = the [ChiselException] thrownBy extractCause[ChiselException] { + val e = the[ChiselException] thrownBy extractCause[ChiselException] { ChiselStage.elaborate(new Module { val io = IO(new Bundle { val foo = Input(UInt(8.W)) @@ -164,6 +163,6 @@ class WhenSpec extends ChiselFlatSpec with Utils { io.out := func() }) } - e.getMessage should include ("Cannot exit from a when() block with a \"return\"") + e.getMessage should include("Cannot exit from a when() block with a \"return\"") } } diff --git a/src/test/scala/chiselTests/WidthSpec.scala b/src/test/scala/chiselTests/WidthSpec.scala index 34159214..77a09e1c 100644 --- a/src/test/scala/chiselTests/WidthSpec.scala +++ b/src/test/scala/chiselTests/WidthSpec.scala @@ -19,13 +19,13 @@ object SimpleBundle { class WidthSpec extends ChiselFlatSpec { "Literals without specified widths" should "get the minimum legal width" in { - "hdeadbeef".U.getWidth should be (32) - "h_dead_beef".U.getWidth should be (32) - "h0a".U.getWidth should be (4) - "h1a".U.getWidth should be (5) - "h0".U.getWidth should be (1) - 1.U.getWidth should be (1) - 1.S.getWidth should be (2) + "hdeadbeef".U.getWidth should be(32) + "h_dead_beef".U.getWidth should be(32) + "h0a".U.getWidth should be(4) + "h1a".U.getWidth should be(5) + "h0".U.getWidth should be(1) + 1.U.getWidth should be(1) + 1.S.getWidth should be(2) } } @@ -33,7 +33,7 @@ abstract class WireRegWidthSpecImpl extends ChiselFlatSpec { def name: String def builder[T <: Data](x: T): T - behavior of name + behavior.of(name) it should "set the width if the template type has a set width" in { assertKnownWidth(4) { @@ -83,7 +83,7 @@ abstract class WireDefaultRegInitSpecImpl extends ChiselFlatSpec { def builder1[T <: Data](x: T): T def builder2[T <: Data](x: T, y: T): T - behavior of s"$name (Single Argument)" + behavior.of(s"$name (Single Argument)") it should "set width if passed a literal with forced width" in { assertKnownWidth(4) { @@ -129,7 +129,7 @@ abstract class WireDefaultRegInitSpecImpl extends ChiselFlatSpec { } } - behavior of s"$name (Double Argument)" + behavior.of(s"$name (Double Argument)") it should "set the width if the template type has a set width" in { assertKnownWidth(4) { @@ -152,7 +152,10 @@ abstract class WireDefaultRegInitSpecImpl extends ChiselFlatSpec { it should "infer the width if the template type has no width" in { val templates = Seq( - () => 0.U, () => 0.U(2.W), () => WireDefault(0.U), () => WireDefault(0.U(2.W)) + () => 0.U, + () => 0.U(2.W), + () => WireDefault(0.U), + () => WireDefault(0.U(2.W)) ) for (gen <- templates) { assertInferredWidth(4) { diff --git a/src/test/scala/chiselTests/aop/InjectionSpec.scala b/src/test/scala/chiselTests/aop/InjectionSpec.scala index a28501a5..9b29b0ba 100644 --- a/src/test/scala/chiselTests/aop/InjectionSpec.scala +++ b/src/test/scala/chiselTests/aop/InjectionSpec.scala @@ -38,12 +38,15 @@ object InjectionHierarchy { val in = Input(Bool()) }) //scalastyle:off regex - setInline("SubmoduleC.v", s""" - |module SubmoduleC( - | input io_in - |); - |endmodule - """.stripMargin) + setInline( + "SubmoduleC.v", + s""" + |module SubmoduleC( + | input io_in + |); + |endmodule + """.stripMargin + ) } class AspectTester(results: Seq[Int]) extends BasicTester { @@ -63,26 +66,26 @@ object InjectionHierarchy { class InjectionSpec extends ChiselFlatSpec with Utils { import InjectionHierarchy._ val correctValueAspect = InjectingAspect( - {dut: AspectTester => Seq(dut)}, - {dut: AspectTester => - for(i <- 0 until dut.values.length) { + { dut: AspectTester => Seq(dut) }, + { dut: AspectTester => + for (i <- 0 until dut.values.length) { dut.values(i) := i.U } } ) val wrongValueAspect = InjectingAspect( - {dut: AspectTester => Seq(dut)}, - {dut: AspectTester => - for(i <- 0 until dut.values.length) { + { dut: AspectTester => Seq(dut) }, + { dut: AspectTester => + for (i <- 0 until dut.values.length) { dut.values(i) := (i + 1).U } } ) val manipulateSubmoduleAspect = InjectingAspect( - {dut: SubmoduleManipulationTester => Seq(dut)}, - {dut: SubmoduleManipulationTester => + { dut: SubmoduleManipulationTester => Seq(dut) }, + { dut: SubmoduleManipulationTester => val moduleSubmoduleB = Module(new SubmoduleB) moduleSubmoduleB.io.in := dut.moduleSubmoduleA.io.out //if we're here then we've elaborated correctly @@ -91,8 +94,8 @@ class InjectionSpec extends ChiselFlatSpec with Utils { ) val duplicateSubmoduleAspect = InjectingAspect( - {dut: SubmoduleManipulationTester => Seq(dut)}, - {_: SubmoduleManipulationTester => + { dut: SubmoduleManipulationTester => Seq(dut) }, + { _: SubmoduleManipulationTester => // By creating a second SubmoduleA, the module names would conflict unless they were uniquified val moduleSubmoduleA2 = Module(new SubmoduleA) //if we're here then we've elaborated correctly @@ -101,8 +104,8 @@ class InjectionSpec extends ChiselFlatSpec with Utils { ) val addingExternalModules = InjectingAspect( - {dut: SubmoduleManipulationTester => Seq(dut)}, - {_: SubmoduleManipulationTester => + { dut: SubmoduleManipulationTester => Seq(dut) }, + { _: SubmoduleManipulationTester => // By creating a second SubmoduleA, the module names would conflict unless they were uniquified val moduleSubmoduleC = Module(new SubmoduleC) //if we're here then we've elaborated correctly @@ -123,30 +126,36 @@ class InjectionSpec extends ChiselFlatSpec with Utils { ) "Test" should "pass if inserted the correct values" in { - assertTesterPasses{ new AspectTester(Seq(0, 1, 2)) } + assertTesterPasses { new AspectTester(Seq(0, 1, 2)) } } "Test" should "fail if inserted the wrong values" in { - assertTesterFails{ new AspectTester(Seq(9, 9, 9)) } + assertTesterFails { new AspectTester(Seq(9, 9, 9)) } } "Test" should "pass if pass wrong values, but correct with aspect" in { - assertTesterPasses({ new AspectTester(Seq(9, 9, 9))} , Nil, Seq(correctValueAspect) ++ TesterDriver.verilatorOnly) + assertTesterPasses({ new AspectTester(Seq(9, 9, 9)) }, Nil, Seq(correctValueAspect) ++ TesterDriver.verilatorOnly) } "Test" should "pass if pass wrong values, then wrong aspect, then correct aspect" in { assertTesterPasses( - new AspectTester(Seq(9, 9, 9)), Nil, Seq(wrongValueAspect, correctValueAspect) ++ TesterDriver.verilatorOnly + new AspectTester(Seq(9, 9, 9)), + Nil, + Seq(wrongValueAspect, correctValueAspect) ++ TesterDriver.verilatorOnly ) } "Test" should "fail if pass wrong values, then correct aspect, then wrong aspect" in { - assertTesterFails({ new AspectTester(Seq(9, 9, 9))} , Nil, Seq(correctValueAspect, wrongValueAspect)) + assertTesterFails({ new AspectTester(Seq(9, 9, 9)) }, Nil, Seq(correctValueAspect, wrongValueAspect)) } "Test" should "pass if the submodules in SubmoduleManipulationTester can be manipulated by manipulateSubmoduleAspect" in { - assertTesterPasses({ new SubmoduleManipulationTester} , Nil, Seq(manipulateSubmoduleAspect) ++ TesterDriver.verilatorOnly) + assertTesterPasses( + { new SubmoduleManipulationTester }, + Nil, + Seq(manipulateSubmoduleAspect) ++ TesterDriver.verilatorOnly + ) } "Module name collisions when adding a new module" should "be resolved" in { assertTesterPasses( - { new SubmoduleManipulationTester}, + { new SubmoduleManipulationTester }, Nil, Seq(duplicateSubmoduleAspect) ++ TesterDriver.verilatorOnly ) @@ -154,7 +163,7 @@ class InjectionSpec extends ChiselFlatSpec with Utils { "Adding external modules" should "work" in { assertTesterPasses( - { new SubmoduleManipulationTester}, + { new SubmoduleManipulationTester }, Nil, Seq(addingExternalModules) ++ TesterDriver.verilatorOnly ) @@ -162,7 +171,7 @@ class InjectionSpec extends ChiselFlatSpec with Utils { "Injection into multiple submodules of the same class" should "work" in { assertTesterPasses( - {new MultiModuleInjectionTester}, + { new MultiModuleInjectionTester }, Nil, Seq(multiModuleInjectionAspect) ++ TesterDriver.verilatorOnly ) diff --git a/src/test/scala/chiselTests/aop/SelectSpec.scala b/src/test/scala/chiselTests/aop/SelectSpec.scala index 2b47c6b8..72802c80 100644 --- a/src/test/scala/chiselTests/aop/SelectSpec.scala +++ b/src/test/scala/chiselTests/aop/SelectSpec.scala @@ -39,22 +39,35 @@ case class SelectAspect[T <: RawModule, X](selector: T => Seq[X], desired: T => override def toAnnotation(top: T): AnnotationSeq = { val results = selector(top) val desiredSeq = desired(top) - assert(results.length == desiredSeq.length, s"Failure! Results $results have different length than desired $desiredSeq!") + assert( + results.length == desiredSeq.length, + s"Failure! Results $results have different length than desired $desiredSeq!" + ) val mismatches = results.zip(desiredSeq).flatMap { case (res, des) if res != des => Seq((res, des)) - case other => Nil + case other => Nil } - assert(mismatches.isEmpty,s"Failure! The following selected items do not match their desired item:\n" + mismatches.map{ - case (res: Select.Serializeable, des: Select.Serializeable) => s" ${res.serialize} does not match:\n ${des.serialize}" - case (res, des) => s" $res does not match:\n $des" - }.mkString("\n")) + assert( + mismatches.isEmpty, + s"Failure! The following selected items do not match their desired item:\n" + mismatches.map { + case (res: Select.Serializeable, des: Select.Serializeable) => + s" ${res.serialize} does not match:\n ${des.serialize}" + case (res, des) => s" $res does not match:\n $des" + }.mkString("\n") + ) Nil } } class SelectSpec extends ChiselFlatSpec { - def execute[T <: RawModule, X](dut: () => T, selector: T => Seq[X], desired: T => Seq[X])(implicit tTag: TypeTag[T]): Unit = { + def execute[T <: RawModule, X]( + dut: () => T, + selector: T => Seq[X], + desired: T => Seq[X] + )( + implicit tTag: TypeTag[T] + ): Unit = { val ret = new chisel3.stage.ChiselStage().run( Seq( new chisel3.stage.ChiselGeneratorAnnotation(dut), @@ -85,16 +98,20 @@ class SelectSpec extends ChiselFlatSpec { () => new SelectTester(Seq(0, 1, 2)), { dut: SelectTester => Seq(Select.printfs(dut).last.toString) }, { dut: SelectTester => - Seq(Select.Printf( - dut.p, - Seq( - When(Select.ops("eq")(dut).last.asInstanceOf[Bool]), - When(dut.nreset), - WhenNot(dut.overflow) - ), - dut.p.pable, - dut.clock - ).toString) + Seq( + Select + .Printf( + dut.p, + Seq( + When(Select.ops("eq")(dut).last.asInstanceOf[Bool]), + When(dut.nreset), + WhenNot(dut.overflow) + ), + dut.p.pable, + dut.clock + ) + .toString + ) } ) } @@ -104,8 +121,10 @@ class SelectSpec extends ChiselFlatSpec { () => new SelectTester(Seq(0, 1, 2)), { dut: SelectTester => Select.connectionsTo(dut)(dut.counter) }, { dut: SelectTester => - Seq(PredicatedConnect(Nil, dut.counter, dut.added, false), - PredicatedConnect(Seq(When(dut.overflow)), dut.counter, dut.zero, false)) + Seq( + PredicatedConnect(Nil, dut.counter, dut.added, false), + PredicatedConnect(Seq(When(dut.overflow)), dut.counter, dut.zero, false) + ) } ) } @@ -121,7 +140,7 @@ class SelectSpec extends ChiselFlatSpec { "Test" should "pass if selecting ops" in { execute( () => new SelectTester(Seq(0, 1, 2)), - { dut: SelectTester => Select.ops(dut).collect { case ("tail", d) => d} }, + { dut: SelectTester => Select.ops(dut).collect { case ("tail", d) => d } }, { dut: SelectTester => Seq(dut.added, dut.zero) } ) } @@ -131,20 +150,22 @@ class SelectSpec extends ChiselFlatSpec { () => new SelectTester(Seq(0, 1, 2)), { dut: SelectTester => Seq(Select.stops(dut).last) }, { dut: SelectTester => - Seq(Select.Stop( - Seq( - When(Select.ops("eq")(dut)(1).asInstanceOf[Bool]), - When(dut.overflow) - ), - 0, - dut.clock - )) + Seq( + Select.Stop( + Seq( + When(Select.ops("eq")(dut)(1).asInstanceOf[Bool]), + When(dut.overflow) + ), + 0, + dut.clock + ) + ) } ) } "Blackboxes" should "be supported in Select.instances" in { - class BB extends ExtModule { } + class BB extends ExtModule {} class Top extends RawModule { val bb = Module(new BB) } @@ -173,12 +194,10 @@ class SelectSpec extends ChiselFlatSpec { } val top = ChiselGeneratorAnnotation(() => { new Top() - }).elaborate - .collectFirst { case DesignAnnotation(design: Top) => design } - .get - Select.collectDeep(top) { case x => x } should equal (Seq(top, top.inst0)) - Select.getDeep(top)(x => Seq(x)) should equal (Seq(top, top.inst0)) - Select.instances(top) should equal (Seq(top.inst0)) + }).elaborate.collectFirst { case DesignAnnotation(design: Top) => design }.get + Select.collectDeep(top) { case x => x } should equal(Seq(top, top.inst0)) + Select.getDeep(top)(x => Seq(x)) should equal(Seq(top, top.inst0)) + Select.instances(top) should equal(Seq(top.inst0)) } "Using Definition/Instance with Injecting Aspects" should "throw an error" in { @@ -202,13 +221,10 @@ class SelectSpec extends ChiselFlatSpec { } val top = ChiselGeneratorAnnotation(() => { new Top() - }).elaborate - .collectFirst { case DesignAnnotation(design: Top) => design } - .get + }).elaborate.collectFirst { case DesignAnnotation(design: Top) => design }.get intercept[Exception] { Select.collectDeep(top) { case x => x } } intercept[Exception] { Select.getDeep(top)(x => Seq(x)) } intercept[Exception] { Select.instances(top) } } } - diff --git a/src/test/scala/chiselTests/experimental/DataView.scala b/src/test/scala/chiselTests/experimental/DataView.scala index 7c5d170b..5ef062fa 100644 --- a/src/test/scala/chiselTests/experimental/DataView.scala +++ b/src/test/scala/chiselTests/experimental/DataView.scala @@ -54,7 +54,7 @@ object FlatDecoupledDataView { class DataViewSpec extends ChiselFlatSpec { - behavior of "DataView" + behavior.of("DataView") it should "support simple Bundle viewing" in { import SimpleBundleDataView._ @@ -240,8 +240,8 @@ class DataViewSpec extends ChiselFlatSpec { fooOut := cat } val chirrtl = ChiselStage.emitChirrtl(new MyModule) - chirrtl should include ("node cat = cat(barIn.foo, barIn.bar)") - chirrtl should include ("fooOut <= cat") + chirrtl should include("node cat = cat(barIn.foo, barIn.bar)") + chirrtl should include("fooOut <= cat") } it should "be composable" in { @@ -262,8 +262,8 @@ class DataViewSpec extends ChiselFlatSpec { z := b.viewAs[Bar].viewAs[Fizz] } val chirrtl = ChiselStage.emitChirrtl(new MyModule) - chirrtl should include ("y.fizz <= a.foo") - chirrtl should include ("z.fizz <= b.foo") + chirrtl should include("y.fizz <= a.foo") + chirrtl should include("z.fizz <= b.foo") } it should "enable using Seq like Data" in { @@ -277,8 +277,8 @@ class DataViewSpec extends ChiselFlatSpec { } // Verilog instead of CHIRRTL because the optimizations make it much prettier val verilog = ChiselStage.emitVerilog(new MyModule) - verilog should include ("assign y = sel ? a : c;") - verilog should include ("assign z = sel ? b : d;") + verilog should include("assign y = sel ? a : c;") + verilog should include("assign z = sel ? b : d;") } // This example should be turned into a built-in feature @@ -291,9 +291,9 @@ class DataViewSpec extends ChiselFlatSpec { } // Verilog instead of CHIRRTL because the optimizations make it much prettier val verilog = ChiselStage.emitVerilog(new MyModule) - verilog should include ("assign x = a;") - verilog should include ("assign y = b;") - verilog should include ("assign z = c;") + verilog should include("assign x = a;") + verilog should include("assign y = b;") + verilog should include("assign z = c;") } it should "support recursive composition of views" in { @@ -307,10 +307,10 @@ class DataViewSpec extends ChiselFlatSpec { Seq((w, x), (y, z)) := VecInit[HWTuple2[UInt, UInt]]((a, b), (c, d)) } val verilog = ChiselStage.emitVerilog(new MyModule) - verilog should include ("assign w = a;") - verilog should include ("assign x = b;") - verilog should include ("assign y = c;") - verilog should include ("assign z = d;") + verilog should include("assign w = a;") + verilog should include("assign x = b;") + verilog should include("assign y = c;") + verilog should include("assign z = d;") } it should "support dynamic indexing for Vec identity views" in { @@ -328,8 +328,8 @@ class DataViewSpec extends ChiselFlatSpec { dataOut := selected } val chirrtl = ChiselStage.emitChirrtl(new MyModule) - chirrtl should include ("vec[addr] <= dataIn") - chirrtl should include ("dataOut <= vec[addr]") + chirrtl should include("vec[addr] <= dataIn") + chirrtl should include("dataOut <= vec[addr]") } it should "error if you try to dynamically index a Vec view that does not correspond to a Vec target" in { @@ -346,9 +346,9 @@ class DataViewSpec extends ChiselFlatSpec { selected := (inA, inB) (outA, outB) := selected } - (the [InvalidViewException] thrownBy { + (the[InvalidViewException] thrownBy { ChiselStage.emitChirrtl(new MyModule) - }).getMessage should include ("Dynamic indexing of Views is not yet supported") + }).getMessage should include("Dynamic indexing of Views is not yet supported") } it should "error if the mapping is non-total in the view" in { @@ -360,8 +360,8 @@ class DataViewSpec extends ChiselFlatSpec { val out = IO(Output(tpe)) out := in.viewAs[MyBundle] } - val err = the [InvalidViewException] thrownBy (ChiselStage.emitVerilog(new MyModule)) - err.toString should include ("View field '_.foo' is missing") + val err = the[InvalidViewException] thrownBy (ChiselStage.emitVerilog(new MyModule)) + err.toString should include("View field '_.foo' is missing") } it should "error if the mapping is non-total in the target" in { @@ -371,8 +371,8 @@ class DataViewSpec extends ChiselFlatSpec { val out = IO(Output(UInt(8.W))) out := (a, b).viewAs[UInt] } - val err = the [InvalidViewException] thrownBy (ChiselStage.emitVerilog(new MyModule)) - err.toString should include ("Target field '_._2' is missing") + val err = the[InvalidViewException] thrownBy (ChiselStage.emitVerilog(new MyModule)) + err.toString should include("Target field '_._2' is missing") } it should "error if the mapping contains Data that are not part of the Target" in { @@ -389,8 +389,8 @@ class DataViewSpec extends ChiselFlatSpec { val out = IO(Output(new BundleB)) out := in.viewAs[BundleB] } - val err = the [InvalidViewException] thrownBy (ChiselStage.emitVerilog(new MyModule)) - err.toString should include ("View mapping must only contain Elements within the Target") + val err = the[InvalidViewException] thrownBy (ChiselStage.emitVerilog(new MyModule)) + err.toString should include("View mapping must only contain Elements within the Target") } it should "error if the mapping contains Data that are not part of the View" in { @@ -408,8 +408,8 @@ class DataViewSpec extends ChiselFlatSpec { val out = IO(Output(new BundleB)) out.viewAs[BundleA] := in } - val err = the [InvalidViewException] thrownBy (ChiselStage.emitVerilog(new MyModule)) - err.toString should include ("View mapping must only contain Elements within the View") + val err = the[InvalidViewException] thrownBy (ChiselStage.emitVerilog(new MyModule)) + err.toString should include("View mapping must only contain Elements within the View") } it should "error if a view has a width that does not match the target" in { @@ -425,9 +425,9 @@ class DataViewSpec extends ChiselFlatSpec { val out = IO(Output(new BundleB)) out := in.viewAs[BundleB] } - val err = the [InvalidViewException] thrownBy ChiselStage.emitChirrtl(new MyModule) + val err = the[InvalidViewException] thrownBy ChiselStage.emitChirrtl(new MyModule) val expected = """View field _\.bar UInt<4> has width <4> that is incompatible with target value .+'s width <8>""".r - err.getMessage should fullyMatch regex expected + (err.getMessage should fullyMatch).regex(expected) } it should "error if a view has a known width when the target width is unknown" in { @@ -443,12 +443,13 @@ class DataViewSpec extends ChiselFlatSpec { val out = IO(Output(new BundleB)) out := in.viewAs[BundleB] } - val err = the [InvalidViewException] thrownBy ChiselStage.emitChirrtl(new MyModule) - val expected = """View field _\.bar UInt<4> has width <4> that is incompatible with target value .+'s width <unknown>""".r - err.getMessage should fullyMatch regex expected + val err = the[InvalidViewException] thrownBy ChiselStage.emitChirrtl(new MyModule) + val expected = + """View field _\.bar UInt<4> has width <4> that is incompatible with target value .+'s width <unknown>""".r + (err.getMessage should fullyMatch).regex(expected) } - behavior of "PartialDataView" + behavior.of("PartialDataView") it should "still error if the mapping is non-total in the view" in { class MyBundle(val foo: UInt, val bar: UInt) extends Bundle @@ -458,8 +459,8 @@ class DataViewSpec extends ChiselFlatSpec { val out = IO(Output(new MyBundle(UInt(8.W), UInt(8.W)))) out := in.viewAs[MyBundle] } - val err = the [InvalidViewException] thrownBy (ChiselStage.emitVerilog(new MyModule)) - err.toString should include ("View field '_.foo' is missing") + val err = the[InvalidViewException] thrownBy (ChiselStage.emitVerilog(new MyModule)) + err.toString should include("View field '_.foo' is missing") } it should "NOT error if the mapping is non-total in the target" in { @@ -470,6 +471,6 @@ class DataViewSpec extends ChiselFlatSpec { out := (a, b).viewAs[UInt] } val verilog = ChiselStage.emitVerilog(new MyModule) - verilog should include ("assign out = b;") + verilog should include("assign out = b;") } } diff --git a/src/test/scala/chiselTests/experimental/DataViewIntegrationSpec.scala b/src/test/scala/chiselTests/experimental/DataViewIntegrationSpec.scala index 3f149f75..4704a942 100644 --- a/src/test/scala/chiselTests/experimental/DataViewIntegrationSpec.scala +++ b/src/test/scala/chiselTests/experimental/DataViewIntegrationSpec.scala @@ -5,7 +5,7 @@ package chiselTests.experimental import chisel3._ import chisel3.experimental.{BaseModule, ExtModule} import chisel3.experimental.dataview._ -import chisel3.util.{Decoupled, DecoupledIO, Queue, QueueIO, log2Ceil} +import chisel3.util.{log2Ceil, Decoupled, DecoupledIO, Queue, QueueIO} import chiselTests.ChiselFlatSpec import firrtl.transforms.DontTouchAnnotation @@ -52,6 +52,6 @@ class DataViewIntegrationSpec extends ChiselFlatSpec { "Users" should "be able to view and annotate Modules" in { val (_, annos) = getFirrtlAndAnnos(new MyModule) val ts = annos.collect { case DontTouchAnnotation(t) => t.serialize } - ts should equal (Seq("~MyModule|Queue>enq_ptr_value")) + ts should equal(Seq("~MyModule|Queue>enq_ptr_value")) } } diff --git a/src/test/scala/chiselTests/experimental/DataViewTargetSpec.scala b/src/test/scala/chiselTests/experimental/DataViewTargetSpec.scala index a17b0f40..da27c9c8 100644 --- a/src/test/scala/chiselTests/experimental/DataViewTargetSpec.scala +++ b/src/test/scala/chiselTests/experimental/DataViewTargetSpec.scala @@ -5,7 +5,7 @@ package chiselTests.experimental import chisel3._ import chisel3.experimental.dataview._ import chisel3.experimental.conversions._ -import chisel3.experimental.{ChiselAnnotation, annotate} +import chisel3.experimental.{annotate, ChiselAnnotation} import chiselTests.ChiselFlatSpec object DataViewTargetSpec { @@ -29,22 +29,22 @@ class DataViewTargetSpec extends ChiselFlatSpec { _.instanceName, _.pathName, _.parentPathName, - _.parentModName, + _.parentModName ) // Check helpers private def checkAll(impl: Data, refs: String*): Unit = { - refs.size should be (checks.size) + refs.size should be(checks.size) for ((check, value) <- checks.zip(refs)) { - check(impl) should be (value) + check(impl) should be(value) } } private def checkSameAs(impl: Data, refs: Data*): Unit = for (ref <- refs) { - checkAll(impl, checks.map(_(ref)):_*) + checkAll(impl, checks.map(_(ref)): _*) } - behavior of "DataView Naming" + behavior.of("DataView Naming") it should "support views of Elements" in { class MyChild extends Module { @@ -67,7 +67,8 @@ class DataViewTargetSpec extends ChiselFlatSpec { val foo = UInt(8.W) val bars = Vec(2, UInt(8.W)) } - implicit val dv = DataView[MyBundle, Vec[UInt]](_ => Vec(3, UInt(8.W)), _.foo -> _(0), _.bars(0) -> _(1), _.bars(1) -> _(2)) + implicit val dv = + DataView[MyBundle, Vec[UInt]](_ => Vec(3, UInt(8.W)), _.foo -> _(0), _.bars(0) -> _(1), _.bars(1) -> _(2)) class MyChild extends Module { val out = IO(Output(new MyBundle)) val outView = out.viewAs[Vec[UInt]] // Note different type @@ -82,7 +83,7 @@ class DataViewTargetSpec extends ChiselFlatSpec { out := inst.out } val m = elaborateAndGetModule(new MyParent) - val outView = m.inst.out.viewAs[Vec[UInt]]// Note different type + val outView = m.inst.out.viewAs[Vec[UInt]] // Note different type val outFooView = m.inst.out.foo.viewAs[UInt] val outBarsView = m.inst.out.bars.viewAs[Vec[UInt]] val outBars0View = m.inst.out.bars(0).viewAs[UInt] @@ -90,8 +91,15 @@ class DataViewTargetSpec extends ChiselFlatSpec { checkSameAs(m.inst.out, m.inst.outView, outView) checkSameAs(m.inst.out.foo, m.inst.outFooView, m.inst.outView(0), outFooView, outView(0)) checkSameAs(m.inst.out.bars, m.inst.outBarsView, outBarsView) - checkSameAs(m.inst.out.bars(0), m.inst.outBars0View, outBars0View, m.inst.outView(1), outView(1), - m.inst.outBarsView(0), outBarsView(0)) + checkSameAs( + m.inst.out.bars(0), + m.inst.outBars0View, + outBars0View, + m.inst.outView(1), + outView(1), + m.inst.outBarsView(0), + outBarsView(0) + ) } // Ideally this would work 1:1 but that requires changing the binding @@ -123,7 +131,7 @@ class DataViewTargetSpec extends ChiselFlatSpec { 2 -> "~MyParent|MyParent/inst:MyChild>out.foo", 3 -> "~MyParent|MyParent/inst:MyChild>out" ) - pairs should equal (expected) + pairs should equal(expected) } it should "support annotating views that cannot be mapped to a single ReferenceTarget" in { @@ -161,9 +169,9 @@ class DataViewTargetSpec extends ChiselFlatSpec { 3 -> "~MyParent|MyParent/inst:MyChild>io.c", 3 -> "~MyParent|MyParent/inst:MyChild>io.d", 4 -> "~MyParent|MyChild>io.b", - 4 -> "~MyParent|MyChild>io.d", + 4 -> "~MyParent|MyChild>io.d" ) - pairs should equal (expected) + pairs should equal(expected) } // TODO check these properties when using @instance API (especially preservation of totality) diff --git a/src/test/scala/chiselTests/experimental/ForceNames.scala b/src/test/scala/chiselTests/experimental/ForceNames.scala index 06f911e6..233b4a5f 100644 --- a/src/test/scala/chiselTests/experimental/ForceNames.scala +++ b/src/test/scala/chiselTests/experimental/ForceNames.scala @@ -6,7 +6,7 @@ import firrtl._ import chisel3._ import chisel3.experimental.annotate import chisel3.stage.{ChiselGeneratorAnnotation, ChiselStage} -import chisel3.util.experimental.{ForceNameAnnotation, ForceNamesTransform, InlineInstance, forceName} +import chisel3.util.experimental.{forceName, ForceNameAnnotation, ForceNamesTransform, InlineInstance} import firrtl.annotations.{Annotation, ReferenceTarget} import firrtl.options.{Dependency, TargetDirAnnotation} import firrtl.stage.RunFirrtlTransformAnnotation @@ -61,7 +61,12 @@ object ForceNamesHierarchy { class ForceNamesSpec extends ChiselFlatSpec { - def run[T <: RawModule](dut: => T, testName: String, inputAnnos: Seq[Annotation] = Nil, info: LogLevel.Value = LogLevel.None): Iterable[String] = { + def run[T <: RawModule]( + dut: => T, + testName: String, + inputAnnos: Seq[Annotation] = Nil, + info: LogLevel.Value = LogLevel.None + ): Iterable[String] = { def stage = new ChiselStage { override val targets = Seq( Dependency[chisel3.stage.phases.Elaborate], @@ -85,11 +90,11 @@ class ForceNamesSpec extends ChiselFlatSpec { } "Force Names on a wrapping instance" should "work" in { val verilog = run(new ForceNamesHierarchy.WrapperExample, "wrapper") - exactly(1, verilog) should include ("MyLeaf inst") + exactly(1, verilog) should include("MyLeaf inst") } "Force Names on an instance port" should "work" in { val verilog = run(new ForceNamesHierarchy.RenamePortsExample, "instports") - atLeast(1, verilog) should include ("input [2:0] inn") + atLeast(1, verilog) should include("input [2:0] inn") } "Force Names with a conflicting name" should "error" in { intercept[CustomTransformException] { diff --git a/src/test/scala/chiselTests/experimental/GroupSpec.scala b/src/test/scala/chiselTests/experimental/GroupSpec.scala index 52435ad8..5e0c34bb 100644 --- a/src/test/scala/chiselTests/experimental/GroupSpec.scala +++ b/src/test/scala/chiselTests/experimental/GroupSpec.scala @@ -16,9 +16,9 @@ import scala.collection.mutable class GroupSpec extends ChiselFlatSpec { - def collectInstances(c: fir.Circuit, top: Option[String] = None): Seq[String] = new InstanceGraph(c) - .fullHierarchy.values.flatten.toSeq - .map( v => (top.getOrElse(v.head.name) +: v.tail.map(_.name)).mkString(".") ) + def collectInstances(c: fir.Circuit, top: Option[String] = None): Seq[String] = + new InstanceGraph(c).fullHierarchy.values.flatten.toSeq + .map(v => (top.getOrElse(v.head.name) +: v.tail.map(_.name)).mkString(".")) def collectDeclarations(m: fir.DefModule): Set[String] = { val decs = mutable.HashSet[String]() @@ -32,17 +32,16 @@ class GroupSpec extends ChiselFlatSpec { def lower[T <: RawModule](gen: () => T): fir.Circuit = { (new ChiselStage) - .execute(Array("--compiler", "low", - "--target-dir", "test_run_dir"), - Seq(ChiselGeneratorAnnotation(gen))) + .execute(Array("--compiler", "low", "--target-dir", "test_run_dir"), Seq(ChiselGeneratorAnnotation(gen))) .collectFirst { case firrtl.stage.FirrtlCircuitAnnotation(circuit) => circuit - }.get + } + .get } "Module Grouping" should "compile to low FIRRTL" in { class MyModule extends Module { - val io = IO(new Bundle{ + val io = IO(new Bundle { val a = Input(Bool()) val b = Output(Bool()) }) @@ -56,17 +55,17 @@ class GroupSpec extends ChiselFlatSpec { val firrtlCircuit = lower(() => new MyModule) firrtlCircuit.modules.collect { case m: fir.Module if m.name == "MyModule" => - Set("doubleReg") should be (collectDeclarations(m)) + Set("doubleReg") should be(collectDeclarations(m)) case m: fir.Module if m.name == "DosRegisters" => - Set("reg1", "reg2") should be (collectDeclarations(m)) + Set("reg1", "reg2") should be(collectDeclarations(m)) } val instances = collectInstances(firrtlCircuit, Some("MyModule")).toSet - Set("MyModule", "MyModule.doubleReg") should be (instances) + Set("MyModule", "MyModule.doubleReg") should be(instances) } "Module Grouping" should "not include intermediate registers" in { class MyModule extends Module { - val io = IO(new Bundle{ + val io = IO(new Bundle { val a = Input(Bool()) val b = Output(Bool()) }) @@ -81,17 +80,17 @@ class GroupSpec extends ChiselFlatSpec { val firrtlCircuit = lower(() => new MyModule) firrtlCircuit.modules.collect { case m: fir.Module if m.name == "MyModule" => - Set("reg2", "doubleReg") should be (collectDeclarations(m)) + Set("reg2", "doubleReg") should be(collectDeclarations(m)) case m: fir.Module if m.name == "DosRegisters" => - Set("reg1", "reg3") should be (collectDeclarations(m)) + Set("reg1", "reg3") should be(collectDeclarations(m)) } val instances = collectInstances(firrtlCircuit, Some("MyModule")).toSet - Set("MyModule", "MyModule.doubleReg") should be (instances) + Set("MyModule", "MyModule.doubleReg") should be(instances) } "Module Grouping" should "include intermediate wires" in { class MyModule extends Module { - val io = IO(new Bundle{ + val io = IO(new Bundle { val a = Input(Bool()) val b = Output(Bool()) }) @@ -106,11 +105,11 @@ class GroupSpec extends ChiselFlatSpec { val firrtlCircuit = lower(() => new MyModule) firrtlCircuit.modules.collect { case m: fir.Module if m.name == "MyModule" => - Set("doubleReg") should be (collectDeclarations(m)) + Set("doubleReg") should be(collectDeclarations(m)) case m: fir.Module if m.name == "DosRegisters" => - Set("reg1", "reg3", "wire") should be (collectDeclarations(m)) + Set("reg1", "reg3", "wire") should be(collectDeclarations(m)) } val instances = collectInstances(firrtlCircuit, Some("MyModule")).toSet - Set("MyModule", "MyModule.doubleReg") should be (instances) + Set("MyModule", "MyModule.doubleReg") should be(instances) } } diff --git a/src/test/scala/chiselTests/experimental/ModuleDataProductSpec.scala b/src/test/scala/chiselTests/experimental/ModuleDataProductSpec.scala index 78986517..713f9d04 100644 --- a/src/test/scala/chiselTests/experimental/ModuleDataProductSpec.scala +++ b/src/test/scala/chiselTests/experimental/ModuleDataProductSpec.scala @@ -39,7 +39,7 @@ object ModuleDataProductSpec { class ModuleDataProductSpec extends ChiselFlatSpec { import ModuleDataProductSpec._ - behavior of "DataProduct" + behavior.of("DataProduct") it should "work for UserModules (recursively)" in { val m = elaborateAndGetModule(new MyUserModule) @@ -62,7 +62,7 @@ class ModuleDataProductSpec extends ChiselFlatSpec { val impl = implicitly[DataProduct[MyUserModule]] val set = impl.dataSet(m) for ((d, _) <- expected) { - set(d) should be (true) + set(d) should be(true) } val it = impl.dataIterator(m, "m") it.toList should contain theSameElementsAs (expected) @@ -82,7 +82,7 @@ class ModuleDataProductSpec extends ChiselFlatSpec { val impl = implicitly[DataProduct[MyExtModule]] val set = impl.dataSet(m) for ((d, _) <- expected) { - set(d) should be (true) + set(d) should be(true) } val it = impl.dataIterator(m, "m") it.toList should contain theSameElementsAs (expected) diff --git a/src/test/scala/chiselTests/experimental/ProgrammaticPortsSpec.scala b/src/test/scala/chiselTests/experimental/ProgrammaticPortsSpec.scala index ffe3a37f..64aabb4b 100644 --- a/src/test/scala/chiselTests/experimental/ProgrammaticPortsSpec.scala +++ b/src/test/scala/chiselTests/experimental/ProgrammaticPortsSpec.scala @@ -63,7 +63,7 @@ class ProgrammaticPortsSpec extends ChiselFlatSpec with Utils { } "SuggestName collisions on ports" should "be illegal" in { - a [ChiselException] should be thrownBy extractCause[ChiselException] { + a[ChiselException] should be thrownBy extractCause[ChiselException] { ChiselStage.elaborate(new Module { val foo = IO(UInt(8.W)).suggestName("apple") val bar = IO(UInt(8.W)).suggestName("apple") diff --git a/src/test/scala/chiselTests/experimental/TraceSpec.scala b/src/test/scala/chiselTests/experimental/TraceSpec.scala index 59548921..31ccdf9b 100644 --- a/src/test/scala/chiselTests/experimental/TraceSpec.scala +++ b/src/test/scala/chiselTests/experimental/TraceSpec.scala @@ -88,13 +88,17 @@ class TraceSpec extends ChiselFlatSpec with Matchers { .flatMap(finalTarget(annos)) .toSet .map { target: CompleteTarget => - s"""public_flat_rd -module "${target.tokens.collectFirst { case OfModule(m) => m }.get}" -var "${target.tokens.collectFirst { case Ref(r) => r }.get}"""" + s"""public_flat_rd -module "${target.tokens.collectFirst { + case OfModule(m) => m + }.get}" -var "${target.tokens.collectFirst { case Ref(r) => r }.get}"""" } .mkString("\n") + "\n" def verilatorTemplate(data: Seq[Data], annos: AnnotationSeq): String = { val vpiNames = data.flatMap(finalTarget(annos)).map { ct => - s"""TOP.${ct.circuit}.${ct.path.map { case (Instance(i), _) => i }.mkString(".")}.${ct.tokens.collectFirst { case Ref(r) => r }.get}""" + s"""TOP.${ct.circuit}.${ct.path.map { case (Instance(i), _) => i }.mkString(".")}.${ct.tokens.collectFirst { + case Ref(r) => r + }.get}""" } s""" |#include "V${topName}.h" @@ -155,20 +159,34 @@ class TraceSpec extends ChiselFlatSpec with Matchers { val verilog = testDir / s"$topName.v" val cpp = os.temp(dir = testDir, suffix = ".cpp", contents = verilatorTemplate(Seq(dut.m0.o.a.b), annos)) val exe = testDir / "obj_dir" / s"V$topName" - os.proc("verilator", "-Wall", "--cc", "--exe", "--build", "--vpi", s"$cpp", s"$verilog", s"$config").call(stdout = os.Inherit, stderr = os.Inherit, cwd = testDir) - assert(os.proc(s"$exe").call(stdout = os.Inherit, stderr = os.Inherit).exitCode == 0, "verilator should exit peacefully") + os.proc("verilator", "-Wall", "--cc", "--exe", "--build", "--vpi", s"$cpp", s"$verilog", s"$config") + .call(stdout = os.Inherit, stderr = os.Inherit, cwd = testDir) + assert( + os.proc(s"$exe").call(stdout = os.Inherit, stderr = os.Inherit).exitCode == 0, + "verilator should exit peacefully" + ) } "TraceFromCollideBundle" should "work" in { class CollideModule extends Module { - val a = IO(Input(Vec(2, new Bundle { - val b = Flipped(Bool()) - val c = Vec(2, new Bundle { - val d = UInt(2.W) - val e = Flipped(UInt(3.W)) - }) - val c_1_e = UInt(4.W) - }))) + val a = IO( + Input( + Vec( + 2, + new Bundle { + val b = Flipped(Bool()) + val c = Vec( + 2, + new Bundle { + val d = UInt(2.W) + val e = Flipped(UInt(3.W)) + } + ) + val c_1_e = UInt(4.W) + } + ) + ) + ) val a_0_c = IO(Output(UInt(5.W))) val a__0 = IO(Output(UInt(5.W))) a_0_c := DontCare @@ -298,12 +316,14 @@ class TraceSpec extends ChiselFlatSpec with Matchers { val (_, annos) = compile("NestedModule", () => new M) val dut = annos.collectFirst { case DesignAnnotation(dut) => dut }.get.asInstanceOf[M] val allTargets = finalTargetMap(annos) - allTargets(dut.a.toAbsoluteTarget) should be (Seq(refTarget("M", "a"))) - allTargets(dut.b.toAbsoluteTarget) should be (Seq( - refTarget("M", "b_0"), - refTarget("M", "b_1"), - )) - allTargets(dut.b(0).toAbsoluteTarget) should be (Seq(refTarget("M", "b_0"))) - allTargets(dut.b(1).toAbsoluteTarget) should be (Seq(refTarget("M", "b_1"))) + allTargets(dut.a.toAbsoluteTarget) should be(Seq(refTarget("M", "a"))) + allTargets(dut.b.toAbsoluteTarget) should be( + Seq( + refTarget("M", "b_0"), + refTarget("M", "b_1") + ) + ) + allTargets(dut.b(0).toAbsoluteTarget) should be(Seq(refTarget("M", "b_0"))) + allTargets(dut.b(1).toAbsoluteTarget) should be(Seq(refTarget("M", "b_1"))) } } diff --git a/src/test/scala/chiselTests/experimental/Tuple.scala b/src/test/scala/chiselTests/experimental/Tuple.scala index 5f897fbc..b57766e7 100644 --- a/src/test/scala/chiselTests/experimental/Tuple.scala +++ b/src/test/scala/chiselTests/experimental/Tuple.scala @@ -9,7 +9,7 @@ import chisel3.stage.ChiselStage class TupleSpec extends ChiselFlatSpec { - behavior of "Tuple" + behavior.of("Tuple") it should "enable using Tuple2 like Data" in { class MyModule extends Module { @@ -20,8 +20,8 @@ class TupleSpec extends ChiselFlatSpec { } // Verilog instead of CHIRRTL because the optimizations make it much prettier val verilog = ChiselStage.emitVerilog(new MyModule) - verilog should include ("assign y = sel ? a : c;") - verilog should include ("assign z = sel ? b : d;") + verilog should include("assign y = sel ? a : c;") + verilog should include("assign z = sel ? b : d;") } it should "support nesting of tuples" in { @@ -31,10 +31,10 @@ class TupleSpec extends ChiselFlatSpec { ((w, x), (y, z)) := ((a, b), (c, d)) } val chirrtl = ChiselStage.emitChirrtl(new MyModule) - chirrtl should include ("w <= a") - chirrtl should include ("x <= b") - chirrtl should include ("y <= c") - chirrtl should include ("z <= d") + chirrtl should include("w <= a") + chirrtl should include("x <= b") + chirrtl should include("y <= c") + chirrtl should include("z <= d") } it should "enable using Tuple3 like Data" in { @@ -47,9 +47,9 @@ class TupleSpec extends ChiselFlatSpec { } // Verilog instead of CHIRRTL because the optimizations make it much prettier val verilog = ChiselStage.emitVerilog(new MyModule) - verilog should include ("assign v = sel ? a : f;") - verilog should include ("assign w = sel ? b : g;") - verilog should include ("assign x = sel ? c : h;") + verilog should include("assign v = sel ? a : f;") + verilog should include("assign w = sel ? b : g;") + verilog should include("assign x = sel ? c : h;") } it should "enable using Tuple4 like Data" in { @@ -62,10 +62,10 @@ class TupleSpec extends ChiselFlatSpec { } // Verilog instead of CHIRRTL because the optimizations make it much prettier val verilog = ChiselStage.emitVerilog(new MyModule) - verilog should include ("assign v = sel ? a : f;") - verilog should include ("assign w = sel ? b : g;") - verilog should include ("assign x = sel ? c : h;") - verilog should include ("assign y = sel ? d : i;") + verilog should include("assign v = sel ? a : f;") + verilog should include("assign w = sel ? b : g;") + verilog should include("assign x = sel ? c : h;") + verilog should include("assign y = sel ? d : i;") } it should "enable using Tuple5 like Data" in { diff --git a/src/test/scala/chiselTests/experimental/hierarchy/Annotations.scala b/src/test/scala/chiselTests/experimental/hierarchy/Annotations.scala index eba412f1..2c1d2e9e 100644 --- a/src/test/scala/chiselTests/experimental/hierarchy/Annotations.scala +++ b/src/test/scala/chiselTests/experimental/hierarchy/Annotations.scala @@ -5,20 +5,22 @@ package chiselTests.experimental.hierarchy import _root_.firrtl.annotations._ import chisel3.experimental.{annotate, BaseModule} import chisel3.Data -import chisel3.experimental.hierarchy.{Instance, Definition, Hierarchy} +import chisel3.experimental.hierarchy.{Definition, Hierarchy, Instance} object Annotations { case class MarkAnnotation(target: IsMember, tag: String) extends SingleTargetAnnotation[IsMember] { def duplicate(n: IsMember): Annotation = this.copy(target = n) } - case class MarkChiselHierarchyAnnotation[B <: BaseModule](d: Hierarchy[B], tag: String, isAbsolute: Boolean) extends chisel3.experimental.ChiselAnnotation { + case class MarkChiselHierarchyAnnotation[B <: BaseModule](d: Hierarchy[B], tag: String, isAbsolute: Boolean) + extends chisel3.experimental.ChiselAnnotation { def toFirrtl = MarkAnnotation(d.toTarget, tag) } - case class MarkChiselAnnotation(d: Data, tag: String, isAbsolute: Boolean) extends chisel3.experimental.ChiselAnnotation { - def toFirrtl = if(isAbsolute) MarkAnnotation(d.toAbsoluteTarget, tag) else MarkAnnotation(d.toTarget, tag) + case class MarkChiselAnnotation(d: Data, tag: String, isAbsolute: Boolean) + extends chisel3.experimental.ChiselAnnotation { + def toFirrtl = if (isAbsolute) MarkAnnotation(d.toAbsoluteTarget, tag) else MarkAnnotation(d.toTarget, tag) } - def mark(d: Data, tag: String): Unit = annotate(MarkChiselAnnotation(d, tag, false)) - def mark[B <: BaseModule](d: Hierarchy[B], tag: String): Unit = annotate(MarkChiselHierarchyAnnotation(d, tag, true)) - def amark(d: Data, tag: String): Unit = annotate(MarkChiselAnnotation(d, tag, true)) + def mark(d: Data, tag: String): Unit = annotate(MarkChiselAnnotation(d, tag, false)) + def mark[B <: BaseModule](d: Hierarchy[B], tag: String): Unit = annotate(MarkChiselHierarchyAnnotation(d, tag, true)) + def amark(d: Data, tag: String): Unit = annotate(MarkChiselAnnotation(d, tag, true)) def amark[B <: BaseModule](d: Hierarchy[B], tag: String): Unit = annotate(MarkChiselHierarchyAnnotation(d, tag, true)) } diff --git a/src/test/scala/chiselTests/experimental/hierarchy/DefinitionSpec.scala b/src/test/scala/chiselTests/experimental/hierarchy/DefinitionSpec.scala index f33f7869..63beb394 100644 --- a/src/test/scala/chiselTests/experimental/hierarchy/DefinitionSpec.scala +++ b/src/test/scala/chiselTests/experimental/hierarchy/DefinitionSpec.scala @@ -5,7 +5,7 @@ package experimental.hierarchy import chisel3._ import chisel3.experimental.BaseModule -import chisel3.experimental.hierarchy.{Definition, Instance, instantiable, public} +import chisel3.experimental.hierarchy.{instantiable, public, Definition, Instance} // TODO/Notes // - In backport, clock/reset are not automatically assigned. I think this is fixed in 3.5 @@ -19,7 +19,7 @@ class DefinitionSpec extends ChiselFunSpec with Utils { val definition = Definition(new AddOne) } val (chirrtl, _) = getFirrtlAndAnnos(new Top) - chirrtl.serialize should include ("module AddOne :") + chirrtl.serialize should include("module AddOne :") } it("0.2: accessing internal fields through non-generated means is hard to do") { class Top extends Module { @@ -29,7 +29,7 @@ class DefinitionSpec extends ChiselFunSpec with Utils { definition.in } val (chirrtl, _) = getFirrtlAndAnnos(new Top) - chirrtl.serialize should include ("module AddOne :") + chirrtl.serialize should include("module AddOne :") } it("0.2: reset inference is not defaulted to Bool for definitions") { class Top extends Module with RequireAsyncReset { @@ -38,21 +38,27 @@ class DefinitionSpec extends ChiselFunSpec with Utils { i0.in := 0.U } val (chirrtl, _) = getFirrtlAndAnnos(new Top) - chirrtl.serialize should include ("inst i0 of HasUninferredReset") + chirrtl.serialize should include("inst i0 of HasUninferredReset") } it("0.3: module names of repeated definition should be sequential") { class Top extends Module { - val k = Module(new AddTwoParameterized(4, (x: Int) => Seq.tabulate(x){j => - val addOneDef = Definition(new AddOneParameterized(x+j)) - val addOne = Instance(addOneDef) - addOne - })) + val k = Module( + new AddTwoParameterized( + 4, + (x: Int) => + Seq.tabulate(x) { j => + val addOneDef = Definition(new AddOneParameterized(x + j)) + val addOne = Instance(addOneDef) + addOne + } + ) + ) } val (chirrtl, _) = getFirrtlAndAnnos(new Top) - chirrtl.serialize should include ("module AddOneParameterized :") - chirrtl.serialize should include ("module AddOneParameterized_1 :") - chirrtl.serialize should include ("module AddOneParameterized_2 :") - chirrtl.serialize should include ("module AddOneParameterized_3 :") + chirrtl.serialize should include("module AddOneParameterized :") + chirrtl.serialize should include("module AddOneParameterized_1 :") + chirrtl.serialize should include("module AddOneParameterized_2 :") + chirrtl.serialize should include("module AddOneParameterized_3 :") } it("0.4: multiple instantiations should have sequential names") { class Top extends Module { @@ -61,22 +67,28 @@ class DefinitionSpec extends ChiselFunSpec with Utils { val otherAddOne = Module(new AddOneParameterized(4)) } val (chirrtl, _) = getFirrtlAndAnnos(new Top) - chirrtl.serialize should include ("module AddOneParameterized :") - chirrtl.serialize should include ("module AddOneParameterized_1 :") + chirrtl.serialize should include("module AddOneParameterized :") + chirrtl.serialize should include("module AddOneParameterized_1 :") } it("0.5: nested definitions should have sequential names") { class Top extends Module { - val k = Module(new AddTwoWithNested(4, (x: Int) => Seq.tabulate(x){j => - val addOneDef = Definition(new AddOneWithNested(x+j)) - val addOne = Instance(addOneDef) - addOne - })) + val k = Module( + new AddTwoWithNested( + 4, + (x: Int) => + Seq.tabulate(x) { j => + val addOneDef = Definition(new AddOneWithNested(x + j)) + val addOne = Instance(addOneDef) + addOne + } + ) + ) } val (chirrtl, _) = getFirrtlAndAnnos(new Top) - chirrtl.serialize should include ("module AddOneWithNested :") - chirrtl.serialize should include ("module AddOneWithNested_1 :") - chirrtl.serialize should include ("module AddOneWithNested_2 :") - chirrtl.serialize should include ("module AddOneWithNested_3 :") + chirrtl.serialize should include("module AddOneWithNested :") + chirrtl.serialize should include("module AddOneWithNested_1 :") + chirrtl.serialize should include("module AddOneWithNested_2 :") + chirrtl.serialize should include("module AddOneWithNested_3 :") } } describe("1: Annotations on definitions in same chisel compilation") { @@ -179,7 +191,7 @@ class DefinitionSpec extends ChiselFunSpec with Utils { val (_, annos) = getFirrtlAndAnnos(new Top) annos should contain(MarkAnnotation("~Top|AddOneWithInstantiableInstantiable/i0:AddOne".it, "i0.i0")) } - it("1.10: should work for targets on definition to have correct circuit name"){ + it("1.10: should work for targets on definition to have correct circuit name") { class Top extends Module { val definition = Definition(new AddOneWithAnnotation) } @@ -307,6 +319,16 @@ class DefinitionSpec extends ChiselFunSpec with Utils { val (_, annos) = getFirrtlAndAnnos(new Top) annos should contain(MarkAnnotation("~Top|ConcreteHasBlah".mt, "10")) } + it("3.11: should work on eithers") { + class Top() extends Module { + val i = Definition(new HasEither()) + i.x.map(x => mark(x, "xright")).left.map(x => mark(x, "xleft")) + i.y.map(x => mark(x, "yright")).left.map(x => mark(x, "yleft")) + } + val (_, annos) = getFirrtlAndAnnos(new Top) + annos should contain(MarkAnnotation("~Top|HasEither>x".rt, "xright")) + annos should contain(MarkAnnotation("~Top|HasEither>y".rt, "yleft")) + } } describe("4: toDefinition") { it("4.0: should work on modules") { @@ -401,10 +423,12 @@ class DefinitionSpec extends ChiselFunSpec with Utils { ) val (chirrtl, annos) = getFirrtlAndAnnos(new Top) for (e <- expected.map(MarkAnnotation.tupled)) { - annos should contain (e) + annos should contain(e) } } - it("6.1 An @instantiable Module that implements an @instantiable trait should be able to use extension methods from both") { + it( + "6.1 An @instantiable Module that implements an @instantiable trait should be able to use extension methods from both" + ) { class Top extends Module { val i: Definition[ModuleWithCommonIntf] = Definition(new ModuleWithCommonIntf) mark(i.io.in, "gotcha") @@ -418,7 +442,7 @@ class DefinitionSpec extends ChiselFunSpec with Utils { ) val (chirrtl, annos) = getFirrtlAndAnnos(new Top) for (e <- expected.map(MarkAnnotation.tupled)) { - annos should contain (e) + annos should contain(e) } } it("6.2 A BlackBox that implements an @instantiable trait should be instantiable as that trait") { @@ -434,7 +458,7 @@ class DefinitionSpec extends ChiselFunSpec with Utils { ) val (chirrtl, annos) = getFirrtlAndAnnos(new Top) for (e <- expected.map(MarkAnnotation.tupled)) { - annos should contain (e) + annos should contain(e) } } it("6.3 It should be possible to have Vectors of @instantiable traits mixing concrete subclasses") { @@ -456,7 +480,7 @@ class DefinitionSpec extends ChiselFunSpec with Utils { ) val (chirrtl, annos) = getFirrtlAndAnnos(new Top) for (e <- expected.map(MarkAnnotation.tupled)) { - annos should contain (e) + annos should contain(e) } } } @@ -495,10 +519,10 @@ class DefinitionSpec extends ChiselFunSpec with Utils { val (chirrtl, annos) = getFirrtlAndAnnos(new Top) val text = chirrtl.serialize for (line <- expectedLines) { - text should include (line) + text should include(line) } for (e <- expectedAnnos.map(MarkAnnotation.tupled)) { - annos should contain (e) + annos should contain(e) } } ignore("7.1: should work on Aggregate Views that are mapped 1:1") { @@ -523,7 +547,7 @@ class DefinitionSpec extends ChiselFunSpec with Utils { } val expectedAnnos = List( "~Top|MyModule>a".rt -> "in", - "~Top|MyModule>a.foo".rt -> "in_bar", + "~Top|MyModule>a.foo".rt -> "in_bar" ) val expectedLines = List( "i.a <= foo", @@ -532,10 +556,10 @@ class DefinitionSpec extends ChiselFunSpec with Utils { val (chirrtl, annos) = getFirrtlAndAnnos(new Top) val text = chirrtl.serialize for (line <- expectedLines) { - text should include (line) + text should include(line) } for (e <- expectedAnnos.map(MarkAnnotation.tupled)) { - annos should contain (e) + annos should contain(e) } } } diff --git a/src/test/scala/chiselTests/experimental/hierarchy/Examples.scala b/src/test/scala/chiselTests/experimental/hierarchy/Examples.scala index c0f504ff..5b78b7cc 100644 --- a/src/test/scala/chiselTests/experimental/hierarchy/Examples.scala +++ b/src/test/scala/chiselTests/experimental/hierarchy/Examples.scala @@ -11,7 +11,7 @@ object Examples { import Annotations._ @instantiable class AddOne extends Module { - @public val in = IO(Input(UInt(32.W))) + @public val in = IO(Input(UInt(32.W))) @public val out = IO(Output(UInt(32.W))) @public val innerWire = Wire(UInt(32.W)) innerWire := in + 1.U @@ -19,7 +19,7 @@ object Examples { } @instantiable class AddOneWithAnnotation extends Module { - @public val in = IO(Input(UInt(32.W))) + @public val in = IO(Input(UInt(32.W))) @public val out = IO(Output(UInt(32.W))) @public val innerWire = Wire(UInt(32.W)) mark(innerWire, "innerWire") @@ -28,7 +28,7 @@ object Examples { } @instantiable class AddOneWithAbsoluteAnnotation extends Module { - @public val in = IO(Input(UInt(32.W))) + @public val in = IO(Input(UInt(32.W))) @public val out = IO(Output(UInt(32.W))) @public val innerWire = Wire(UInt(32.W)) amark(innerWire, "innerWire") @@ -37,12 +37,12 @@ object Examples { } @instantiable class AddOneParameterized(width: Int) extends Module { - @public val in = IO(Input(UInt(width.W))) + @public val in = IO(Input(UInt(width.W))) @public val out = IO(Output(UInt(width.W))) out := in + 1.U } class AddOneWithNested(width: Int) extends Module { - @public val in = IO(Input(UInt(width.W))) + @public val in = IO(Input(UInt(width.W))) @public val out = IO(Output(UInt(width.W))) val addOneDef = Seq.fill(3)(Definition(new AddOne)) out := in + 1.U @@ -50,7 +50,7 @@ object Examples { @instantiable class AddTwo extends Module { - @public val in = IO(Input(UInt(32.W))) + @public val in = IO(Input(UInt(32.W))) @public val out = IO(Output(UInt(32.W))) @public val definition = Definition(new AddOne) @public val i0: Instance[AddOne] = Instance(definition) @@ -61,7 +61,7 @@ object Examples { } @instantiable class AddTwoMixedModules extends Module { - @public val in = IO(Input(UInt(32.W))) + @public val in = IO(Input(UInt(32.W))) @public val out = IO(Output(UInt(32.W))) val definition = Definition(new AddOne) @public val i0: Instance[AddOne] = Instance(definition) @@ -71,24 +71,25 @@ object Examples { out := i1.out } @instantiable - class AddTwoParameterized(width: Int, makeParameterizedOnes: Int => Seq[Instance[AddOneParameterized]]) extends Module { - val in = IO(Input(UInt(width.W))) + class AddTwoParameterized(width: Int, makeParameterizedOnes: Int => Seq[Instance[AddOneParameterized]]) + extends Module { + val in = IO(Input(UInt(width.W))) val out = IO(Output(UInt(width.W))) val addOnes = makeParameterizedOnes(width) addOnes.head.in := in out := addOnes.last.out - addOnes.zip(addOnes.tail).foreach{ case (head, tail) => tail.in := head.out} + addOnes.zip(addOnes.tail).foreach { case (head, tail) => tail.in := head.out } } @instantiable class AddTwoWithNested(width: Int, makeParameterizedOnes: Int => Seq[Instance[AddOneWithNested]]) extends Module { - val in = IO(Input(UInt(width.W))) + val in = IO(Input(UInt(width.W))) val out = IO(Output(UInt(width.W))) val addOnes = makeParameterizedOnes(width) } @instantiable class AddFour extends Module { - @public val in = IO(Input(UInt(32.W))) + @public val in = IO(Input(UInt(32.W))) @public val out = IO(Output(UInt(32.W))) @public val definition = Definition(new AddTwoMixedModules) @public val i0 = Instance(definition) @@ -111,7 +112,7 @@ object Examples { } @instantiable class AddOneWithInstantiableWire extends Module { - @public val in = IO(Input(UInt(32.W))) + @public val in = IO(Input(UInt(32.W))) @public val out = IO(Output(UInt(32.W))) @public val wireContainer = new WireContainer() wireContainer.innerWire := in + 1.U @@ -123,7 +124,7 @@ object Examples { } @instantiable class AddOneWithInstantiableModule extends Module { - @public val in = IO(Input(UInt(32.W))) + @public val in = IO(Input(UInt(32.W))) @public val out = IO(Output(UInt(32.W))) @public val moduleContainer = new AddOneContainer() moduleContainer.i0.in := in @@ -136,7 +137,7 @@ object Examples { } @instantiable class AddOneWithInstantiableInstance extends Module { - @public val in = IO(Input(UInt(32.W))) + @public val in = IO(Input(UInt(32.W))) @public val out = IO(Output(UInt(32.W))) @public val instanceContainer = new AddOneInstanceContainer() instanceContainer.i0.in := in @@ -148,7 +149,7 @@ object Examples { } @instantiable class AddOneWithInstantiableInstantiable extends Module { - @public val in = IO(Input(UInt(32.W))) + @public val in = IO(Input(UInt(32.W))) @public val out = IO(Output(UInt(32.W))) @public val containerContainer = new AddOneContainerContainer() containerContainer.container.i0.in := in @@ -157,12 +158,12 @@ object Examples { @instantiable class Viewer(val y: AddTwo, markPlease: Boolean) { @public val x = y - if(markPlease) mark(x.i0.innerWire, "first") + if (markPlease) mark(x.i0.innerWire, "first") } @instantiable class ViewerParent(val x: AddTwo, markHere: Boolean, markThere: Boolean) extends Module { @public val viewer = new Viewer(x, markThere) - if(markHere) mark(viewer.x.i0.innerWire, "second") + if (markHere) mark(viewer.x.i0.innerWire, "second") } @instantiable class MultiVal() extends Module { @@ -194,6 +195,11 @@ object Examples { @public val x: Option[UInt] = Some(Wire(UInt(3.W))) } @instantiable + class HasEither() extends Module { + @public val x: Either[Bool, UInt] = Right(Wire(UInt(3.W)).suggestName("x")) + @public val y: Either[Bool, UInt] = Left(Wire(Bool()).suggestName("y")) + } + @instantiable class HasVec() extends Module { @public val x = VecInit(1.U, 2.U, 3.U) } @@ -236,4 +242,14 @@ object Examples { class HasTypeParams[D <: Data](d: D) extends Module { @public val blah = Wire(d) } + + @instantiable + class HasMultipleTypeParamsInside extends Module { + val tpDef0 = Definition(new HasTypeParams(Bool())) + val tpDef1 = Definition(new HasTypeParams(UInt(4.W))) + val i00 = Instance(tpDef0) + val i01 = Instance(tpDef0) + val i10 = Instance(tpDef1) + val i11 = Instance(tpDef1) + } } diff --git a/src/test/scala/chiselTests/experimental/hierarchy/InstanceSpec.scala b/src/test/scala/chiselTests/experimental/hierarchy/InstanceSpec.scala index 9ceb9b40..f62d1e49 100644 --- a/src/test/scala/chiselTests/experimental/hierarchy/InstanceSpec.scala +++ b/src/test/scala/chiselTests/experimental/hierarchy/InstanceSpec.scala @@ -5,10 +5,9 @@ package experimental.hierarchy import chisel3._ import chisel3.experimental.BaseModule -import chisel3.experimental.hierarchy.{Definition, Instance, instantiable, public} +import chisel3.experimental.hierarchy.{instantiable, public, Definition, Instance} import chisel3.util.{DecoupledIO, Valid} - // TODO/Notes // - In backport, clock/reset are not automatically assigned. I think this is fixed in 3.5 // - CircuitTarget for annotations on the definition are wrong - needs to be fixed. @@ -22,7 +21,7 @@ class InstanceSpec extends ChiselFunSpec with Utils { val i0 = Instance(definition) } val (chirrtl, _) = getFirrtlAndAnnos(new Top) - chirrtl.serialize should include ("inst i0 of AddOne") + chirrtl.serialize should include("inst i0 of AddOne") } it("0.1: name of an instanceclone should not error") { class Top extends Module { @@ -31,7 +30,7 @@ class InstanceSpec extends ChiselFunSpec with Utils { val i = i0.i0 // This should not error } val (chirrtl, _) = getFirrtlAndAnnos(new Top) - chirrtl.serialize should include ("inst i0 of AddTwo") + chirrtl.serialize should include("inst i0 of AddTwo") } it("0.2: accessing internal fields through non-generated means is hard to do") { class Top extends Module { @@ -42,63 +41,63 @@ class InstanceSpec extends ChiselFunSpec with Utils { i0.in } val (chirrtl, _) = getFirrtlAndAnnos(new Top) - chirrtl.serialize should include ("inst i0 of AddOne") + chirrtl.serialize should include("inst i0 of AddOne") } } describe("1: Annotations on instances in same chisel compilation") { it("1.0: should work on a single instance, annotating the instance") { class Top extends Module { val definition: Definition[AddOne] = Definition(new AddOne) - val i0: Instance[AddOne] = Instance(definition) + val i0: Instance[AddOne] = Instance(definition) mark(i0, "i0") } val (_, annos) = getFirrtlAndAnnos(new Top) - annos should contain (MarkAnnotation("~Top|Top/i0:AddOne".it, "i0")) + annos should contain(MarkAnnotation("~Top|Top/i0:AddOne".it, "i0")) } it("1.1: should work on a single instance, annotating an inner wire") { class Top extends Module { val definition: Definition[AddOne] = Definition(new AddOne) - val i0: Instance[AddOne] = Instance(definition) + val i0: Instance[AddOne] = Instance(definition) mark(i0.innerWire, "i0.innerWire") } val (_, annos) = getFirrtlAndAnnos(new Top) - annos should contain (MarkAnnotation("~Top|Top/i0:AddOne>innerWire".rt, "i0.innerWire")) + annos should contain(MarkAnnotation("~Top|Top/i0:AddOne>innerWire".rt, "i0.innerWire")) } it("1.2: should work on a two nested instances, annotating the instance") { class Top extends Module { val definition: Definition[AddTwo] = Definition(new AddTwo) - val i0: Instance[AddTwo] = Instance(definition) + val i0: Instance[AddTwo] = Instance(definition) mark(i0.i0, "i0.i0") } val (_, annos) = getFirrtlAndAnnos(new Top) - annos should contain (MarkAnnotation("~Top|Top/i0:AddTwo/i0:AddOne".it, "i0.i0")) + annos should contain(MarkAnnotation("~Top|Top/i0:AddTwo/i0:AddOne".it, "i0.i0")) } it("1.3: should work on a two nested instances, annotating the inner wire") { class Top extends Module { val definition: Definition[AddTwo] = Definition(new AddTwo) - val i0: Instance[AddTwo] = Instance(definition) + val i0: Instance[AddTwo] = Instance(definition) mark(i0.i0.innerWire, "i0.i0.innerWire") } val (_, annos) = getFirrtlAndAnnos(new Top) - annos should contain (MarkAnnotation("~Top|Top/i0:AddTwo/i0:AddOne>innerWire".rt, "i0.i0.innerWire")) + annos should contain(MarkAnnotation("~Top|Top/i0:AddTwo/i0:AddOne>innerWire".rt, "i0.i0.innerWire")) } it("1.4: should work on a nested module in an instance, annotating the module") { class Top extends Module { val definition: Definition[AddTwoMixedModules] = Definition(new AddTwoMixedModules) - val i0: Instance[AddTwoMixedModules] = Instance(definition) + val i0: Instance[AddTwoMixedModules] = Instance(definition) mark(i0.i1, "i0.i1") } val (_, annos) = getFirrtlAndAnnos(new Top) - annos should contain (MarkAnnotation("~Top|Top/i0:AddTwoMixedModules/i1:AddOne_1".it, "i0.i1")) + annos should contain(MarkAnnotation("~Top|Top/i0:AddTwoMixedModules/i1:AddOne_1".it, "i0.i1")) } it("1.5: should work on an instantiable container, annotating a wire") { class Top extends Module { val definition: Definition[AddOneWithInstantiableWire] = Definition(new AddOneWithInstantiableWire) - val i0: Instance[AddOneWithInstantiableWire] = Instance(definition) + val i0: Instance[AddOneWithInstantiableWire] = Instance(definition) mark(i0.wireContainer.innerWire, "i0.innerWire") } val (_, annos) = getFirrtlAndAnnos(new Top) - annos should contain (MarkAnnotation("~Top|Top/i0:AddOneWithInstantiableWire>innerWire".rt, "i0.innerWire")) + annos should contain(MarkAnnotation("~Top|Top/i0:AddOneWithInstantiableWire>innerWire".rt, "i0.innerWire")) } it("1.6: should work on an instantiable container, annotating a module") { class Top extends Module { @@ -107,7 +106,7 @@ class InstanceSpec extends ChiselFunSpec with Utils { mark(i0.moduleContainer.i0, "i0.i0") } val (_, annos) = getFirrtlAndAnnos(new Top) - annos should contain (MarkAnnotation("~Top|Top/i0:AddOneWithInstantiableModule/i0:AddOne".it, "i0.i0")) + annos should contain(MarkAnnotation("~Top|Top/i0:AddOneWithInstantiableModule/i0:AddOne".it, "i0.i0")) } it("1.7: should work on an instantiable container, annotating an instance") { class Top extends Module { @@ -116,7 +115,7 @@ class InstanceSpec extends ChiselFunSpec with Utils { mark(i0.instanceContainer.i0, "i0.i0") } val (_, annos) = getFirrtlAndAnnos(new Top) - annos should contain (MarkAnnotation("~Top|Top/i0:AddOneWithInstantiableInstance/i0:AddOne".it, "i0.i0")) + annos should contain(MarkAnnotation("~Top|Top/i0:AddOneWithInstantiableInstance/i0:AddOne".it, "i0.i0")) } it("1.8: should work on an instantiable container, annotating an instantiable container's module") { class Top extends Module { @@ -125,7 +124,7 @@ class InstanceSpec extends ChiselFunSpec with Utils { mark(i0.containerContainer.container.i0, "i0.i0") } val (_, annos) = getFirrtlAndAnnos(new Top) - annos should contain (MarkAnnotation("~Top|Top/i0:AddOneWithInstantiableInstantiable/i0:AddOne".it, "i0.i0")) + annos should contain(MarkAnnotation("~Top|Top/i0:AddOneWithInstantiableInstantiable/i0:AddOne".it, "i0.i0")) } it("1.9: should work on public member which references public member of another instance") { class Top extends Module { @@ -134,24 +133,24 @@ class InstanceSpec extends ChiselFunSpec with Utils { mark(i0.containerContainer.container.i0, "i0.i0") } val (_, annos) = getFirrtlAndAnnos(new Top) - annos should contain (MarkAnnotation("~Top|Top/i0:AddOneWithInstantiableInstantiable/i0:AddOne".it, "i0.i0")) + annos should contain(MarkAnnotation("~Top|Top/i0:AddOneWithInstantiableInstantiable/i0:AddOne".it, "i0.i0")) } - it("1.10: should work for targets on definition to have correct circuit name"){ + it("1.10: should work for targets on definition to have correct circuit name") { class Top extends Module { val definition = Definition(new AddOneWithAnnotation) val i0 = Instance(definition) } val (_, annos) = getFirrtlAndAnnos(new Top) - annos should contain (MarkAnnotation("~Top|AddOneWithAnnotation>innerWire".rt, "innerWire")) + annos should contain(MarkAnnotation("~Top|AddOneWithAnnotation>innerWire".rt, "innerWire")) } - it("1.11: should work on things with type parameters"){ + it("1.11: should work on things with type parameters") { class Top extends Module { val definition = Definition(new HasTypeParams[UInt](UInt(3.W))) val i0 = Instance(definition) mark(i0.blah, "blah") } val (_, annos) = getFirrtlAndAnnos(new Top) - annos should contain (MarkAnnotation("~Top|Top/i0:HasTypeParams>blah".rt, "blah")) + annos should contain(MarkAnnotation("~Top|Top/i0:HasTypeParams>blah".rt, "blah")) } } describe("2: Annotations on designs not in the same chisel compilation") { @@ -161,7 +160,7 @@ class InstanceSpec extends ChiselFunSpec with Utils { val parent = Instance(Definition(new ViewerParent(x, false, true))) } val (_, annos) = getFirrtlAndAnnos(new Top(first)) - annos should contain (MarkAnnotation("~AddTwo|AddTwo/i0:AddOne>innerWire".rt, "first")) + annos should contain(MarkAnnotation("~AddTwo|AddTwo/i0:AddOne>innerWire".rt, "first")) } it("2.1: should work on an innerWire, marked in a different compilation, in instanced instantiable") { val first = elaborateAndGetModule(new AddTwo) @@ -169,7 +168,7 @@ class InstanceSpec extends ChiselFunSpec with Utils { val parent = Instance(Definition(new ViewerParent(x, true, false))) } val (_, annos) = getFirrtlAndAnnos(new Top(first)) - annos should contain (MarkAnnotation("~AddTwo|AddTwo/i0:AddOne>innerWire".rt, "second")) + annos should contain(MarkAnnotation("~AddTwo|AddTwo/i0:AddOne>innerWire".rt, "second")) } it("2.2: should work on an innerWire, marked in a different compilation, in instanced module") { val first = elaborateAndGetModule(new AddTwo) @@ -178,7 +177,7 @@ class InstanceSpec extends ChiselFunSpec with Utils { mark(parent.viewer.x.i0.innerWire, "third") } val (_, annos) = getFirrtlAndAnnos(new Top(first)) - annos should contain (MarkAnnotation("~AddTwo|AddTwo/i0:AddOne>innerWire".rt, "third")) + annos should contain(MarkAnnotation("~AddTwo|AddTwo/i0:AddOne>innerWire".rt, "third")) } } describe("3: @public") { @@ -188,7 +187,7 @@ class InstanceSpec extends ChiselFunSpec with Utils { mark(mv.x, "mv.x") } val (_, annos) = getFirrtlAndAnnos(new Top) - annos should contain (MarkAnnotation("~Top|Top/mv:MultiVal>x".rt, "mv.x")) + annos should contain(MarkAnnotation("~Top|Top/mv:MultiVal>x".rt, "mv.x")) } it("3.1: should work on lazy vals") { class Top() extends Module { @@ -196,7 +195,7 @@ class InstanceSpec extends ChiselFunSpec with Utils { mark(lv.x, lv.y) } val (_, annos) = getFirrtlAndAnnos(new Top) - annos should contain (MarkAnnotation("~Top|Top/lv:LazyVal>x".rt, "Hi")) + annos should contain(MarkAnnotation("~Top|Top/lv:LazyVal>x".rt, "Hi")) } it("3.2: should work on islookupables") { class Top() extends Module { @@ -275,10 +274,10 @@ class InstanceSpec extends ChiselFunSpec with Utils { val (chirrtl, annos) = getFirrtlAndAnnos(new Top) val text = chirrtl.serialize for (line <- lines) { - text should include (line) + text should include(line) } for (e <- expected.map(MarkAnnotation.tupled)) { - annos should contain (e) + annos should contain(e) } } ignore("3.10: should work on vals in constructor arguments") { @@ -289,6 +288,16 @@ class InstanceSpec extends ChiselFunSpec with Utils { val (_, annos) = getFirrtlAndAnnos(new Top) annos should contain(MarkAnnotation("~Top|Top/i:HasPublicConstructorArgs>x".rt, "10")) } + it("3.11: should work on eithers") { + class Top() extends Module { + val i = Instance(Definition(new HasEither())) + i.x.map(x => mark(x, "xright")).left.map(x => mark(x, "xleft")) + i.y.map(x => mark(x, "yright")).left.map(x => mark(x, "yleft")) + } + val (_, annos) = getFirrtlAndAnnos(new Top) + annos should contain(MarkAnnotation("~Top|Top/i:HasEither>x".rt, "xright")) + annos should contain(MarkAnnotation("~Top|Top/i:HasEither>y".rt, "yleft")) + } } describe("4: toInstance") { it("4.0: should work on modules") { @@ -398,7 +407,7 @@ class InstanceSpec extends ChiselFunSpec with Utils { val (_, annos) = getFirrtlAndAnnos(new Top) annos should contain(MarkAnnotation("~Top|Top/i:AddTwo/i1:AddOne".it, "blah")) } - it("5.6: should work for absolute targets on definition to have correct circuit name"){ + it("5.6: should work for absolute targets on definition to have correct circuit name") { class Top extends Module { val definition = Definition(new AddOneWithAbsoluteAnnotation) val i0 = Instance(definition) @@ -437,10 +446,12 @@ class InstanceSpec extends ChiselFunSpec with Utils { ) val (chirrtl, annos) = getFirrtlAndAnnos(new Top) for (e <- expected.map(MarkAnnotation.tupled)) { - annos should contain (e) + annos should contain(e) } } - it("6.1 An @instantiable Module that implements an @instantiable trait should be able to use extension methods from both") { + it( + "6.1 An @instantiable Module that implements an @instantiable trait should be able to use extension methods from both" + ) { class Top extends Module { val i: Instance[ModuleWithCommonIntf] = Instance(Definition(new ModuleWithCommonIntf)) mark(i.io.in, "gotcha") @@ -454,7 +465,7 @@ class InstanceSpec extends ChiselFunSpec with Utils { ) val (chirrtl, annos) = getFirrtlAndAnnos(new Top) for (e <- expected.map(MarkAnnotation.tupled)) { - annos should contain (e) + annos should contain(e) } } it("6.2 A BlackBox that implements an @instantiable trait should be instantiable as that trait") { @@ -469,7 +480,7 @@ class InstanceSpec extends ChiselFunSpec with Utils { ) val (chirrtl, annos) = getFirrtlAndAnnos(new Top) for (e <- expected.map(MarkAnnotation.tupled)) { - annos should contain (e) + annos should contain(e) } } it("6.3 It should be possible to have Vectors of @instantiable traits mixing concrete subclasses") { @@ -491,7 +502,7 @@ class InstanceSpec extends ChiselFunSpec with Utils { ) val (chirrtl, annos) = getFirrtlAndAnnos(new Top) for (e <- expected.map(MarkAnnotation.tupled)) { - annos should contain (e) + annos should contain(e) } } } @@ -530,10 +541,10 @@ class InstanceSpec extends ChiselFunSpec with Utils { val (chirrtl, annos) = getFirrtlAndAnnos(new Top) val text = chirrtl.serialize for (line <- expectedLines) { - text should include (line) + text should include(line) } for (e <- expectedAnnos.map(MarkAnnotation.tupled)) { - annos should contain (e) + annos should contain(e) } } @@ -578,15 +589,15 @@ class InstanceSpec extends ChiselFunSpec with Utils { "bar.valid <= i.b.valid", "i.b.ready <= bar.ready", "bar.bits.fizz <= i.b.fizz", - "bar.bits.buzz <= i.b.buzz", + "bar.bits.buzz <= i.b.buzz" ) val (chirrtl, annos) = getFirrtlAndAnnos(new Top) val text = chirrtl.serialize for (line <- expectedLines) { - text should include (line) + text should include(line) } for (e <- expectedAnnos.map(MarkAnnotation.tupled)) { - annos should contain (e) + annos should contain(e) } } @@ -612,7 +623,7 @@ class InstanceSpec extends ChiselFunSpec with Utils { } val expected = List( "~Top|Top/i:MyModule>a".rt -> "in", - "~Top|Top/i:MyModule>b.foo".rt -> "out_bar", + "~Top|Top/i:MyModule>b.foo".rt -> "out_bar" ) val lines = List( "i.a <= foo", @@ -621,10 +632,10 @@ class InstanceSpec extends ChiselFunSpec with Utils { val (chirrtl, annos) = getFirrtlAndAnnos(new Top) val text = chirrtl.serialize for (line <- lines) { - text should include (line) + text should include(line) } for (e <- expected.map(MarkAnnotation.tupled)) { - annos should contain (e) + annos should contain(e) } } @@ -647,7 +658,7 @@ class InstanceSpec extends ChiselFunSpec with Utils { val expected = List( // Not 1:1 so will get split out "~Top|Top/i:MyModule>a".rt -> "i.ports", - "~Top|Top/i:MyModule>b".rt -> "i.ports", + "~Top|Top/i:MyModule>b".rt -> "i.ports" ) val lines = List( "i.a <= foo", @@ -656,10 +667,10 @@ class InstanceSpec extends ChiselFunSpec with Utils { val (chirrtl, annos) = getFirrtlAndAnnos(new Top) val text = chirrtl.serialize for (line <- lines) { - text should include (line) + text should include(line) } for (e <- expected.map(MarkAnnotation.tupled)) { - annos should contain (e) + annos should contain(e) } } } @@ -682,11 +693,10 @@ class InstanceSpec extends ChiselFunSpec with Utils { val expected = List( "~Top|HasCMAR/c:AggregatePortModule>io".rt -> "c.io", "~Top|HasCMAR/c:AggregatePortModule>io.out".rt -> "c.io.out" - ) val (_, annos) = getFirrtlAndAnnos(new Top) for (e <- expected.map(MarkAnnotation.tupled)) { - annos should contain (e) + annos should contain(e) } } it("8.1: it should support @public on a CMAR Record in Instances") { @@ -706,11 +716,10 @@ class InstanceSpec extends ChiselFunSpec with Utils { val expected = List( "~Top|Top/i:HasCMAR/c:AggregatePortModule>io".rt -> "i.c.io", "~Top|Top/i:HasCMAR/c:AggregatePortModule>io.out".rt -> "i.c.io.out" - ) val (_, annos) = getFirrtlAndAnnos(new Top) for (e <- expected.map(MarkAnnotation.tupled)) { - annos should contain (e) + annos should contain(e) } } } @@ -754,15 +763,27 @@ class InstanceSpec extends ChiselFunSpec with Utils { } getFirrtlAndAnnos(new Top) } + it("9.3 it should ignore type parameters (even though it would be nice if it didn't)") { + class Top extends Module { + val d0: Definition[Module] = Definition(new HasTypeParams(Bool())) + require(d0.isA[HasTypeParams[Bool]]) + require(d0.isA[HasTypeParams[_]]) + require(d0.isA[HasTypeParams[UInt]]) + require(!d0.isA[HasBlah]) + } + getFirrtlAndAnnos(new Top) + } } describe("10: Select APIs") { it("10.0: instancesOf") { val aspect = aop.inspecting.InspectingAspect({ m: AddTwoMixedModules => val targets = aop.Select.instancesOf[AddOne](m.toDefinition).map { i: Instance[AddOne] => i.toTarget } - targets should be (Seq( - "~AddTwoMixedModules|AddTwoMixedModules/i0:AddOne".it, - "~AddTwoMixedModules|AddTwoMixedModules/i1:AddOne_1".it, - )) + targets should be( + Seq( + "~AddTwoMixedModules|AddTwoMixedModules/i0:AddOne".it, + "~AddTwoMixedModules|AddTwoMixedModules/i1:AddOne_1".it + ) + ) }) getFirrtlAndAnnos(new AddTwoMixedModules, Seq(aspect)) } @@ -771,14 +792,18 @@ class InstanceSpec extends ChiselFunSpec with Utils { val insts = aop.Select.instancesIn(m.toDefinition) val abs = insts.map { i: Instance[BaseModule] => i.toAbsoluteTarget } val rel = insts.map { i: Instance[BaseModule] => i.toTarget } - abs should be (Seq( - "~AddTwoMixedModules|AddTwoMixedModules/i0:AddOne".it, - "~AddTwoMixedModules|AddTwoMixedModules/i1:AddOne_1".it, - )) - rel should be (Seq( - "~AddTwoMixedModules|AddTwoMixedModules/i0:AddOne".it, - "~AddTwoMixedModules|AddTwoMixedModules/i1:AddOne_1".it, - )) + abs should be( + Seq( + "~AddTwoMixedModules|AddTwoMixedModules/i0:AddOne".it, + "~AddTwoMixedModules|AddTwoMixedModules/i1:AddOne_1".it + ) + ) + rel should be( + Seq( + "~AddTwoMixedModules|AddTwoMixedModules/i0:AddOne".it, + "~AddTwoMixedModules|AddTwoMixedModules/i1:AddOne_1".it + ) + ) }) getFirrtlAndAnnos(new AddTwoMixedModules, Seq(aspect)) } @@ -787,48 +812,58 @@ class InstanceSpec extends ChiselFunSpec with Utils { val insts = aop.Select.allInstancesOf[AddOne](m.toDefinition) val abs = insts.map { i: Instance[AddOne] => i.in.toAbsoluteTarget } val rel = insts.map { i: Instance[AddOne] => i.in.toTarget } - rel should be (Seq( - "~AddFour|AddFour/i0:AddTwoMixedModules/i0:AddOne>in".rt, - "~AddFour|AddFour/i0:AddTwoMixedModules/i1:AddOne_1>in".rt, - "~AddFour|AddFour/i1:AddTwoMixedModules/i0:AddOne>in".rt, - "~AddFour|AddFour/i1:AddTwoMixedModules/i1:AddOne_1>in".rt, - )) - abs should be (Seq( - "~AddFour|AddFour/i0:AddTwoMixedModules/i0:AddOne>in".rt, - "~AddFour|AddFour/i0:AddTwoMixedModules/i1:AddOne_1>in".rt, - "~AddFour|AddFour/i1:AddTwoMixedModules/i0:AddOne>in".rt, - "~AddFour|AddFour/i1:AddTwoMixedModules/i1:AddOne_1>in".rt, - )) + rel should be( + Seq( + "~AddFour|AddFour/i0:AddTwoMixedModules/i0:AddOne>in".rt, + "~AddFour|AddFour/i0:AddTwoMixedModules/i1:AddOne_1>in".rt, + "~AddFour|AddFour/i1:AddTwoMixedModules/i0:AddOne>in".rt, + "~AddFour|AddFour/i1:AddTwoMixedModules/i1:AddOne_1>in".rt + ) + ) + abs should be( + Seq( + "~AddFour|AddFour/i0:AddTwoMixedModules/i0:AddOne>in".rt, + "~AddFour|AddFour/i0:AddTwoMixedModules/i1:AddOne_1>in".rt, + "~AddFour|AddFour/i1:AddTwoMixedModules/i0:AddOne>in".rt, + "~AddFour|AddFour/i1:AddTwoMixedModules/i1:AddOne_1>in".rt + ) + ) }) getFirrtlAndAnnos(new AddFour, Seq(aspect)) } it("10.3: definitionsOf") { val aspect = aop.inspecting.InspectingAspect({ m: AddTwoMixedModules => val targets = aop.Select.definitionsOf[AddOne](m.toDefinition).map { i: Definition[AddOne] => i.in.toTarget } - targets should be (Seq( - "~AddTwoMixedModules|AddOne>in".rt, - "~AddTwoMixedModules|AddOne_1>in".rt, - )) + targets should be( + Seq( + "~AddTwoMixedModules|AddOne>in".rt, + "~AddTwoMixedModules|AddOne_1>in".rt + ) + ) }) getFirrtlAndAnnos(new AddTwoMixedModules, Seq(aspect)) } it("10.4: definitionsIn") { val aspect = aop.inspecting.InspectingAspect({ m: AddTwoMixedModules => val targets = aop.Select.definitionsIn(m.toDefinition).map { i: Definition[BaseModule] => i.toTarget } - targets should be (Seq( - "~AddTwoMixedModules|AddOne".mt, - "~AddTwoMixedModules|AddOne_1".mt, - )) + targets should be( + Seq( + "~AddTwoMixedModules|AddOne".mt, + "~AddTwoMixedModules|AddOne_1".mt + ) + ) }) getFirrtlAndAnnos(new AddTwoMixedModules, Seq(aspect)) } it("10.5: allDefinitionsOf") { val aspect = aop.inspecting.InspectingAspect({ m: AddFour => val targets = aop.Select.allDefinitionsOf[AddOne](m.toDefinition).map { i: Definition[AddOne] => i.in.toTarget } - targets should be (Seq( - "~AddFour|AddOne>in".rt, - "~AddFour|AddOne_1>in".rt, - )) + targets should be( + Seq( + "~AddFour|AddOne>in".rt, + "~AddFour|AddOne_1>in".rt + ) + ) }) getFirrtlAndAnnos(new AddFour, Seq(aspect)) } @@ -850,6 +885,141 @@ class InstanceSpec extends ChiselFunSpec with Utils { }) intercept[Exception] { getFirrtlAndAnnos(new AddFour, Seq(aspect)) } } + it("10.9: allInstancesOf.ios") { + val aspect = aop.inspecting.InspectingAspect({ m: AddFour => + val abs = aop.Select.allInstancesOf[AddOne](m.toDefinition).flatMap { i: Instance[AddOne] => + aop.Select.ios(i).map(_.toAbsoluteTarget) + } + val rel = aop.Select.allInstancesOf[AddOne](m.toDefinition).flatMap { i: Instance[AddOne] => + aop.Select.ios(i).map(_.toTarget) + } + abs should be( + Seq( + "~AddFour|AddFour/i0:AddTwoMixedModules/i0:AddOne>clock".rt, + "~AddFour|AddFour/i0:AddTwoMixedModules/i0:AddOne>reset".rt, + "~AddFour|AddFour/i0:AddTwoMixedModules/i0:AddOne>in".rt, + "~AddFour|AddFour/i0:AddTwoMixedModules/i0:AddOne>out".rt, + "~AddFour|AddFour/i0:AddTwoMixedModules/i1:AddOne_1>clock".rt, + "~AddFour|AddFour/i0:AddTwoMixedModules/i1:AddOne_1>reset".rt, + "~AddFour|AddFour/i0:AddTwoMixedModules/i1:AddOne_1>in".rt, + "~AddFour|AddFour/i0:AddTwoMixedModules/i1:AddOne_1>out".rt, + "~AddFour|AddFour/i1:AddTwoMixedModules/i0:AddOne>clock".rt, + "~AddFour|AddFour/i1:AddTwoMixedModules/i0:AddOne>reset".rt, + "~AddFour|AddFour/i1:AddTwoMixedModules/i0:AddOne>in".rt, + "~AddFour|AddFour/i1:AddTwoMixedModules/i0:AddOne>out".rt, + "~AddFour|AddFour/i1:AddTwoMixedModules/i1:AddOne_1>clock".rt, + "~AddFour|AddFour/i1:AddTwoMixedModules/i1:AddOne_1>reset".rt, + "~AddFour|AddFour/i1:AddTwoMixedModules/i1:AddOne_1>in".rt, + "~AddFour|AddFour/i1:AddTwoMixedModules/i1:AddOne_1>out".rt + ) + ) + + rel should be( + Seq( + "~AddFour|AddFour/i0:AddTwoMixedModules/i0:AddOne>clock".rt, + "~AddFour|AddFour/i0:AddTwoMixedModules/i0:AddOne>reset".rt, + "~AddFour|AddFour/i0:AddTwoMixedModules/i0:AddOne>in".rt, + "~AddFour|AddFour/i0:AddTwoMixedModules/i0:AddOne>out".rt, + "~AddFour|AddFour/i0:AddTwoMixedModules/i1:AddOne_1>clock".rt, + "~AddFour|AddFour/i0:AddTwoMixedModules/i1:AddOne_1>reset".rt, + "~AddFour|AddFour/i0:AddTwoMixedModules/i1:AddOne_1>in".rt, + "~AddFour|AddFour/i0:AddTwoMixedModules/i1:AddOne_1>out".rt, + "~AddFour|AddFour/i1:AddTwoMixedModules/i0:AddOne>clock".rt, + "~AddFour|AddFour/i1:AddTwoMixedModules/i0:AddOne>reset".rt, + "~AddFour|AddFour/i1:AddTwoMixedModules/i0:AddOne>in".rt, + "~AddFour|AddFour/i1:AddTwoMixedModules/i0:AddOne>out".rt, + "~AddFour|AddFour/i1:AddTwoMixedModules/i1:AddOne_1>clock".rt, + "~AddFour|AddFour/i1:AddTwoMixedModules/i1:AddOne_1>reset".rt, + "~AddFour|AddFour/i1:AddTwoMixedModules/i1:AddOne_1>in".rt, + "~AddFour|AddFour/i1:AddTwoMixedModules/i1:AddOne_1>out".rt + ) + ) + }) + getFirrtlAndAnnos(new AddFour, Seq(aspect)) + } + it("10.10: allDefinitionsOf.ios") { + val aspect = aop.inspecting.InspectingAspect({ m: AddFour => + val abs = aop.Select.allDefinitionsOf[AddOne](m.toDefinition).flatMap { i: Definition[AddOne] => + aop.Select.ios(i).map(_.toAbsoluteTarget) + } + val rel = aop.Select.allDefinitionsOf[AddOne](m.toDefinition).flatMap { i: Definition[AddOne] => + aop.Select.ios(i).map(_.toTarget) + } + abs should be( + Seq( + "~AddFour|AddOne>clock".rt, + "~AddFour|AddOne>reset".rt, + "~AddFour|AddOne>in".rt, + "~AddFour|AddOne>out".rt, + "~AddFour|AddOne_1>clock".rt, + "~AddFour|AddOne_1>reset".rt, + "~AddFour|AddOne_1>in".rt, + "~AddFour|AddOne_1>out".rt + ) + ) + + rel should be( + Seq( + "~AddFour|AddOne>clock".rt, + "~AddFour|AddOne>reset".rt, + "~AddFour|AddOne>in".rt, + "~AddFour|AddOne>out".rt, + "~AddFour|AddOne_1>clock".rt, + "~AddFour|AddOne_1>reset".rt, + "~AddFour|AddOne_1>in".rt, + "~AddFour|AddOne_1>out".rt + ) + ) + + }) + getFirrtlAndAnnos(new AddFour, Seq(aspect)) + } + it("10.11 Select.instancesIn for typed BaseModules") { + val aspect = aop.inspecting.InspectingAspect({ m: HasMultipleTypeParamsInside => + val targets = aop.Select.instancesIn(m.toDefinition).map { i: Instance[BaseModule] => i.toTarget } + targets should be( + Seq( + "~HasMultipleTypeParamsInside|HasMultipleTypeParamsInside/i00:HasTypeParams".it, + "~HasMultipleTypeParamsInside|HasMultipleTypeParamsInside/i01:HasTypeParams".it, + "~HasMultipleTypeParamsInside|HasMultipleTypeParamsInside/i10:HasTypeParams_1".it, + "~HasMultipleTypeParamsInside|HasMultipleTypeParamsInside/i11:HasTypeParams_1".it + ) + ) + }) + getFirrtlAndAnnos(new HasMultipleTypeParamsInside, Seq(aspect)) + } + it("10.12 Select.instancesOf for typed BaseModules if type is ignored") { + val aspect = aop.inspecting.InspectingAspect({ m: HasMultipleTypeParamsInside => + val targets = + aop.Select.instancesOf[HasTypeParams[_]](m.toDefinition).map { i: Instance[HasTypeParams[_]] => i.toTarget } + targets should be( + Seq( + "~HasMultipleTypeParamsInside|HasMultipleTypeParamsInside/i00:HasTypeParams".it, + "~HasMultipleTypeParamsInside|HasMultipleTypeParamsInside/i01:HasTypeParams".it, + "~HasMultipleTypeParamsInside|HasMultipleTypeParamsInside/i10:HasTypeParams_1".it, + "~HasMultipleTypeParamsInside|HasMultipleTypeParamsInside/i11:HasTypeParams_1".it + ) + ) + }) + getFirrtlAndAnnos(new HasMultipleTypeParamsInside, Seq(aspect)) + } + it( + "10.13 Select.instancesOf for typed BaseModules even type is specified wrongly (should be ignored, even though we wish it weren't)" + ) { + val aspect = aop.inspecting.InspectingAspect({ m: HasMultipleTypeParamsInside => + val targets = aop.Select.instancesOf[HasTypeParams[SInt]](m.toDefinition).map { i: Instance[HasTypeParams[_]] => + i.toTarget + } + targets should be( + Seq( + "~HasMultipleTypeParamsInside|HasMultipleTypeParamsInside/i00:HasTypeParams".it, + "~HasMultipleTypeParamsInside|HasMultipleTypeParamsInside/i01:HasTypeParams".it, + "~HasMultipleTypeParamsInside|HasMultipleTypeParamsInside/i10:HasTypeParams_1".it, + "~HasMultipleTypeParamsInside|HasMultipleTypeParamsInside/i11:HasTypeParams_1".it + ) + ) + }) + getFirrtlAndAnnos(new HasMultipleTypeParamsInside, Seq(aspect)) + } } } - diff --git a/src/test/scala/chiselTests/naming/NamePluginSpec.scala b/src/test/scala/chiselTests/naming/NamePluginSpec.scala index 3a539bd4..18359fd2 100644 --- a/src/test/scala/chiselTests/naming/NamePluginSpec.scala +++ b/src/test/scala/chiselTests/naming/NamePluginSpec.scala @@ -12,20 +12,20 @@ class NamePluginSpec extends ChiselFlatSpec with Utils { "Scala plugin" should "name internally scoped components" in { class Test extends Module { - { val mywire = Wire(UInt(3.W))} + { val mywire = Wire(UInt(3.W)) } } - aspectTest(() => new Test) { - top: Test => Select.wires(top).head.toTarget.ref should be("mywire") + aspectTest(() => new Test) { top: Test => + Select.wires(top).head.toTarget.ref should be("mywire") } } "Scala plugin" should "name internally scoped instances" in { - class Inner extends Module { } + class Inner extends Module {} class Test extends Module { { val myinstance = Module(new Inner) } } - aspectTest(() => new Test) { - top: Test => Select.instances(top).head.instanceName should be("myinstance") + aspectTest(() => new Test) { top: Test => + Select.instances(top).head.instanceName should be("myinstance") } } @@ -41,8 +41,8 @@ class NamePluginSpec extends ChiselFlatSpec with Utils { builder() } } - aspectTest(() => new Test) { - top: Test => Select.wires(top).map(_.instanceName) should be (List("first_wire", "second_wire")) + aspectTest(() => new Test) { top: Test => + Select.wires(top).map(_.instanceName) should be(List("first_wire", "second_wire")) } } @@ -64,8 +64,8 @@ class NamePluginSpec extends ChiselFlatSpec with Utils { } } } - aspectTest(() => new Test) { - top: Test => Select.wires(top).map(_.instanceName) should be (List("x1_first_wire1", "x1", "x2_second_wire1", "x2")) + aspectTest(() => new Test) { top: Test => + Select.wires(top).map(_.instanceName) should be(List("x1_first_wire1", "x1", "x2_second_wire1", "x2")) } } @@ -79,13 +79,11 @@ class NamePluginSpec extends ChiselFlatSpec with Utils { { val blah = builder() } } - aspectTest(() => new Test) { - top: Test => - Select.wires(top).map(_.instanceName) should be (List("blah")) + aspectTest(() => new Test) { top: Test => + Select.wires(top).map(_.instanceName) should be(List("blah")) } } - "Naming on iterables" should "work" in { class Test extends Module { @@ -100,9 +98,8 @@ class NamePluginSpec extends ChiselFlatSpec with Utils { } } } - aspectTest(() => new Test) { - top: Test => - Select.wires(top).map(_.instanceName) should be (List("blah_0", "blah_1")) + aspectTest(() => new Test) { top: Test => + Select.wires(top).map(_.instanceName) should be(List("blah_0", "blah_1")) } } @@ -122,15 +119,15 @@ class NamePluginSpec extends ChiselFlatSpec with Utils { } } } - aspectTest(() => new Test) { - top: Test => - Select.wires(top).map(_.instanceName) should be ( - List( - "blah_0_0", - "blah_0_1", - "blah_1_0", - "blah_1_1" - )) + aspectTest(() => new Test) { top: Test => + Select.wires(top).map(_.instanceName) should be( + List( + "blah_0_0", + "blah_0_1", + "blah_1_0", + "blah_1_1" + ) + ) } } @@ -146,9 +143,8 @@ class NamePluginSpec extends ChiselFlatSpec with Utils { { val blah = builder() } } - aspectTest(() => new Test) { - top: Test => - Select.wires(top).map(_.instanceName) should be (List("a", "b")) + aspectTest(() => new Test) { top: Test => + Select.wires(top).map(_.instanceName) should be(List("a", "b")) } } @@ -160,9 +156,8 @@ class NamePluginSpec extends ChiselFlatSpec with Utils { } } - aspectTest(() => new Test) { - top: Test => - Select.ios(top).map(_.instanceName) should be (List("a")) + aspectTest(() => new Test) { top: Test => + Select.ios(top).map(_.instanceName) should be(List("a")) } } @@ -174,9 +169,8 @@ class NamePluginSpec extends ChiselFlatSpec with Utils { } } - aspectTest(() => new Test) { - top: Test => - Select.wires(top).map(_.instanceName) should be (List("a")) + aspectTest(() => new Test) { top: Test => + Select.wires(top).map(_.instanceName) should be(List("a")) } } @@ -193,9 +187,8 @@ class NamePluginSpec extends ChiselFlatSpec with Utils { } } - aspectTest(() => new Test) { - top: Test => - Select.ios(top).map(_.instanceName) should be (List("out")) + aspectTest(() => new Test) { top: Test => + Select.ios(top).map(_.instanceName) should be(List("out")) } } @@ -212,9 +205,8 @@ class NamePluginSpec extends ChiselFlatSpec with Utils { } } - aspectTest(() => new Test) { - top: Test => - Select.wires(top).map(_.instanceName) should be (List("fizz")) + aspectTest(() => new Test) { top: Test => + Select.wires(top).map(_.instanceName) should be(List("fizz")) } } @@ -226,13 +218,11 @@ class NamePluginSpec extends ChiselFlatSpec with Utils { } } - aspectTest(() => new Test) { - top: Test => - Select.ios(top).map(_.instanceName) should be (List("a")) + aspectTest(() => new Test) { top: Test => + Select.ios(top).map(_.instanceName) should be(List("a")) } } - "autoSeed" should "override automatic naming for non-IO" in { class Test extends Module { { @@ -241,9 +231,8 @@ class NamePluginSpec extends ChiselFlatSpec with Utils { } } - aspectTest(() => new Test) { - top: Test => - Select.wires(top).map(_.instanceName) should be (List("b")) + aspectTest(() => new Test) { top: Test => + Select.wires(top).map(_.instanceName) should be(List("b")) } } @@ -254,9 +243,8 @@ class NamePluginSpec extends ChiselFlatSpec with Utils { } } - aspectTest(() => new Test) { - top: Test => - Select.wires(top).map(_.instanceName) should be (List("a", "b")) + aspectTest(() => new Test) { top: Test => + Select.wires(top).map(_.instanceName) should be(List("a", "b")) } } @@ -268,9 +256,8 @@ class NamePluginSpec extends ChiselFlatSpec with Utils { } } - aspectTest(() => new Test) { - top: Test => - Select.wires(top).map(_.instanceName) should be (List("x", "b")) + aspectTest(() => new Test) { top: Test => + Select.wires(top).map(_.instanceName) should be(List("x", "b")) } } @@ -283,9 +270,8 @@ class NamePluginSpec extends ChiselFlatSpec with Utils { } } - aspectTest(() => new Test) { - top: Test => - Select.wires(top).map(_.instanceName) should be (List("a", "b")) + aspectTest(() => new Test) { top: Test => + Select.wires(top).map(_.instanceName) should be(List("a", "b")) } } @@ -302,9 +288,8 @@ class NamePluginSpec extends ChiselFlatSpec with Utils { } } - aspectTest(() => new Test) { - top: Test => - Select.wires(top).map(_.instanceName) should be (List("w", "a", "_WIRE")) + aspectTest(() => new Test) { top: Test => + Select.wires(top).map(_.instanceName) should be(List("w", "a", "_WIRE")) } } @@ -332,9 +317,8 @@ class NamePluginSpec extends ChiselFlatSpec with Utils { } } - aspectTest(() => new Test) { - top: Test => Select.wires(top).map(_.instanceName) should be (List("a_b_c", "a_b", "a")) + aspectTest(() => new Test) { top: Test => + Select.wires(top).map(_.instanceName) should be(List("a_b_c", "a_b", "a")) } } } - diff --git a/src/test/scala/chiselTests/naming/PrefixSpec.scala b/src/test/scala/chiselTests/naming/PrefixSpec.scala index 0712692d..f9a78f0e 100644 --- a/src/test/scala/chiselTests/naming/PrefixSpec.scala +++ b/src/test/scala/chiselTests/naming/PrefixSpec.scala @@ -28,8 +28,8 @@ class PrefixSpec extends ChiselPropSpec with Utils { } } } - aspectTest(() => new Test) { - top: Test => Select.wires(top).map(_.instanceName) should be (List("x1_first_wire1", "x1", "x2_second_wire1", "x2")) + aspectTest(() => new Test) { top: Test => + Select.wires(top).map(_.instanceName) should be(List("x1_first_wire1", "x1", "x2_second_wire1", "x2")) } } @@ -50,20 +50,19 @@ class PrefixSpec extends ChiselPropSpec with Utils { { val x1 = builder() } { val x2 = builder() } } - aspectTest(() => new Test) { - top: Test => - Select.wires(top).map(_.instanceName) should be ( - List( - "x1_wire1", - "x1_wire2", - "x1_foo_wire1", - "x1", - "x2_wire1", - "x2_wire2", - "x2_foo_wire1", - "x2" - ) + aspectTest(() => new Test) { top: Test => + Select.wires(top).map(_.instanceName) should be( + List( + "x1_wire1", + "x1_wire2", + "x1_foo_wire1", + "x1", + "x2_wire1", + "x2_wire2", + "x2_foo_wire1", + "x2" ) + ) } } @@ -85,9 +84,8 @@ class PrefixSpec extends ChiselPropSpec with Utils { } } } - aspectTest(() => new Test) { - top: Test => - Select.wires(top).map(_.instanceName) should be (List("x1", "x1_wire", "x2", "x2_wire")) + aspectTest(() => new Test) { top: Test => + Select.wires(top).map(_.instanceName) should be(List("x1", "x1_wire", "x2", "x2_wire")) } } @@ -105,9 +103,8 @@ class PrefixSpec extends ChiselPropSpec with Utils { val JACOB = builder() } } - aspectTest(() => new Test) { - top: Test => - Select.wires(top).map(_.instanceName) should be (List("ADAM_a", "ADAM", "JACOB_a", "JACOB")) + aspectTest(() => new Test) { top: Test => + Select.wires(top).map(_.instanceName) should be(List("ADAM_a", "ADAM", "JACOB_a", "JACOB")) } } @@ -122,9 +119,8 @@ class PrefixSpec extends ChiselPropSpec with Utils { { val noprefix = builder() } } - aspectTest(() => new Test) { - top: Test => - Select.wires(top).map(_.instanceName) should be (List("a", "noprefix")) + aspectTest(() => new Test) { top: Test => + Select.wires(top).map(_.instanceName) should be(List("a", "noprefix")) } } @@ -139,12 +135,13 @@ class PrefixSpec extends ChiselPropSpec with Utils { { val blah = builder() } } - aspectTest(() => new Test) { - top: Test => - Select.ops(top).map(x => (x._1, x._2.instanceName)) should be (List( + aspectTest(() => new Test) { top: Test => + Select.ops(top).map(x => (x._1, x._2.instanceName)) should be( + List( ("mul", "_blah_T"), ("add", "blah") - )) + ) + ) } } @@ -162,9 +159,8 @@ class PrefixSpec extends ChiselPropSpec with Utils { } } } - aspectTest(() => new Test) { - top: Test => - Select.wires(Select.instances(top).head).map(_.instanceName) should be (List("wire")) + aspectTest(() => new Test) { top: Test => + Select.wires(Select.instances(top).head).map(_.instanceName) should be(List("wire")) } } @@ -182,9 +178,8 @@ class PrefixSpec extends ChiselPropSpec with Utils { val child = Module(module) } } - aspectTest(() => new Test) { - top: Test => - Select.wires(Select.instances(top).head).map(_.instanceName) should be (List("wire")) + aspectTest(() => new Test) { top: Test => + Select.wires(Select.instances(top).head).map(_.instanceName) should be(List("wire")) } } @@ -204,13 +199,11 @@ class PrefixSpec extends ChiselPropSpec with Utils { val child = Module(module) } } - aspectTest(() => new Test) { - top: Test => - Select.ios(Select.instances(top).head).map(_.instanceName) should be (List("clock", "reset", "io")) + aspectTest(() => new Test) { top: Test => + Select.ios(Select.instances(top).head).map(_.instanceName) should be(List("clock", "reset", "io")) } } - property("Prefixing should not be caused by nested Iterable[Iterable[Any]]") { class Test extends Module { { @@ -220,9 +213,8 @@ class PrefixSpec extends ChiselPropSpec with Utils { } } } - aspectTest(() => new Test) { - top: Test => - Select.wires(top).map(_.instanceName) should be (List("wire")) + aspectTest(() => new Test) { top: Test => + Select.wires(top).map(_.instanceName) should be(List("wire")) } } @@ -235,9 +227,8 @@ class PrefixSpec extends ChiselPropSpec with Utils { } } } - aspectTest(() => new Test) { - top: Test => - Select.wires(top).map(_.instanceName) should be (List("iia_wire")) + aspectTest(() => new Test) { top: Test => + Select.wires(top).map(_.instanceName) should be(List("iia_wire")) } } @@ -250,10 +241,9 @@ class PrefixSpec extends ChiselPropSpec with Utils { } } } - aspectTest(() => new Test) { - top: Test => - Select.wires(top).map(_.instanceName) should be (List("mywire")) - Select.wires(top).map(_.instanceName) shouldNot be (List("wire_mywire")) + aspectTest(() => new Test) { top: Test => + Select.wires(top).map(_.instanceName) should be(List("mywire")) + Select.wires(top).map(_.instanceName) shouldNot be(List("wire_mywire")) } } @@ -268,8 +258,8 @@ class PrefixSpec extends ChiselPropSpec with Utils { } } } - aspectTest(() => new Test) { - top: Test => Select.wires(top).map(_.instanceName) should be (List("wire_mywire", "mywire2")) + aspectTest(() => new Test) { top: Test => + Select.wires(top).map(_.instanceName) should be(List("wire_mywire", "mywire2")) } } @@ -288,15 +278,16 @@ class PrefixSpec extends ChiselPropSpec with Utils { wire.vec(1.U) := RegNext(3.U) } } - aspectTest(() => new Test) { - top: Test => - Select.registers(top).map(_.instanceName) should be (List( + aspectTest(() => new Test) { top: Test => + Select.registers(top).map(_.instanceName) should be( + List( "wire_x_REG", "wire_y_REG", "wire_vec_0_REG", "wire_vec_REG", "wire_vec_1_REG" - )) + ) + ) } } @@ -312,14 +303,17 @@ class PrefixSpec extends ChiselPropSpec with Utils { child.in := RegNext(3.U) } } - aspectTest(() => new Test) { - top: Test => - Select.registers(top).map(_.instanceName) should be (List( + aspectTest(() => new Test) { top: Test => + Select.registers(top).map(_.instanceName) should be( + List( "child_in_REG" - )) - Select.registers(Select.instances(top).head).map(_.instanceName) should be (List( + ) + ) + Select.registers(Select.instances(top).head).map(_.instanceName) should be( + List( "out_REG" - )) + ) + ) } } @@ -335,14 +329,17 @@ class PrefixSpec extends ChiselPropSpec with Utils { child.in <> RegNext(3.U) } } - aspectTest(() => new Test) { - top: Test => - Select.registers(top).map(_.instanceName) should be (List( + aspectTest(() => new Test) { top: Test => + Select.registers(top).map(_.instanceName) should be( + List( "child_in_REG" - )) - Select.registers(Select.instances(top).head).map(_.instanceName) should be (List( + ) + ) + Select.registers(Select.instances(top).head).map(_.instanceName) should be( + List( "out_REG" - )) + ) + ) } } @@ -357,9 +354,8 @@ class PrefixSpec extends ChiselPropSpec with Utils { } } } - aspectTest(() => new Test) { - top: Test => - Select.wires(top).map(_.instanceName) should be (List("foo_x", "foo_x_w")) + aspectTest(() => new Test) { top: Test => + Select.wires(top).map(_.instanceName) should be(List("foo_x", "foo_x_w")) } } @@ -374,13 +370,11 @@ class PrefixSpec extends ChiselPropSpec with Utils { } } } - aspectTest(() => new Test) { - top: Test => - Select.wires(top).map(_.instanceName) should be (List("foo_x", "foo_x_bar_w")) + aspectTest(() => new Test) { top: Test => + Select.wires(top).map(_.instanceName) should be(List("foo_x", "foo_x_bar_w")) } } - property("Prefixing with wires in recursive functions should grow linearly") { class Test extends Module { def func(bools: Seq[Bool]): Bool = { @@ -394,9 +388,8 @@ class PrefixSpec extends ChiselPropSpec with Utils { val in = IO(Input(Vec(4, Bool()))) val x = func(in) } - aspectTest(() => new Test) { - top: Test => - Select.wires(top).map(_.instanceName) should be (List("x", "x_w_w", "x_w_w_w", "x_w_w_w_w")) + aspectTest(() => new Test) { top: Test => + Select.wires(top).map(_.instanceName) should be(List("x", "x_w_w", "x_w_w_w", "x_w_w_w_w")) } } diff --git a/src/test/scala/chiselTests/stage/ChiselAnnotationsSpec.scala b/src/test/scala/chiselTests/stage/ChiselAnnotationsSpec.scala index 2d804562..9dac820c 100644 --- a/src/test/scala/chiselTests/stage/ChiselAnnotationsSpec.scala +++ b/src/test/scala/chiselTests/stage/ChiselAnnotationsSpec.scala @@ -27,41 +27,41 @@ class ChiselAnnotation class ChiselAnnotationsSpec extends AnyFlatSpec with Matchers { - behavior of "ChiselGeneratorAnnotation elaboration" + behavior.of("ChiselGeneratorAnnotation elaboration") it should "elaborate to a ChiselCircuitAnnotation" in { val annotation = ChiselGeneratorAnnotation(() => new ChiselAnnotationsSpecFoo) val res = annotation.elaborate - res(0) shouldBe a [ChiselCircuitAnnotation] - res(1) shouldBe a [DesignAnnotation[ChiselAnnotationsSpecFoo]] + res(0) shouldBe a[ChiselCircuitAnnotation] + res(1) shouldBe a[DesignAnnotation[ChiselAnnotationsSpecFoo]] } it should "throw an exception if elaboration fails" in { val annotation = ChiselGeneratorAnnotation(() => new ChiselAnnotationsSpecQux) - intercept [ChiselException] { annotation.elaborate } + intercept[ChiselException] { annotation.elaborate } } - behavior of "ChiselGeneratorAnnotation when stringly constructing from Module names" + behavior.of("ChiselGeneratorAnnotation when stringly constructing from Module names") it should "elaborate from a String" in { val annotation = ChiselGeneratorAnnotation("chiselTests.stage.ChiselAnnotationsSpecFoo") val res = annotation.elaborate - res(0) shouldBe a [ChiselCircuitAnnotation] - res(1) shouldBe a [DesignAnnotation[ChiselAnnotationsSpecFoo]] + res(0) shouldBe a[ChiselCircuitAnnotation] + res(1) shouldBe a[DesignAnnotation[ChiselAnnotationsSpecFoo]] } it should "throw an exception if elaboration from a String refers to nonexistant class" in { val bar = "chiselTests.stage.ChiselAnnotationsSpecBar" val annotation = ChiselGeneratorAnnotation(bar) - intercept [OptionsException] { annotation.elaborate } - .getMessage should startWith (s"Unable to locate module '$bar'") + intercept[OptionsException] { annotation.elaborate }.getMessage should startWith(s"Unable to locate module '$bar'") } it should "throw an exception if elaboration from a String refers to an anonymous class" in { val baz = "chiselTests.stage.ChiselAnnotationsSpecBaz" val annotation = ChiselGeneratorAnnotation(baz) - intercept [OptionsException] { annotation.elaborate } - .getMessage should startWith (s"Unable to create instance of module '$baz'") + intercept[OptionsException] { annotation.elaborate }.getMessage should startWith( + s"Unable to create instance of module '$baz'" + ) } } diff --git a/src/test/scala/chiselTests/stage/ChiselMainSpec.scala b/src/test/scala/chiselTests/stage/ChiselMainSpec.scala index 1634e765..e8773111 100644 --- a/src/test/scala/chiselTests/stage/ChiselMainSpec.scala +++ b/src/test/scala/chiselTests/stage/ChiselMainSpec.scala @@ -44,13 +44,15 @@ object ChiselMainSpec { } } -case class TestClassAspect() extends InspectorAspect[RawModule] ({ - _: RawModule => println("Ran inspectingAspect") -}) +case class TestClassAspect() + extends InspectorAspect[RawModule]({ _: RawModule => + println("Ran inspectingAspect") + }) -case object TestObjectAspect extends InspectorAspect[RawModule] ({ - _: RawModule => println("Ran inspectingAspect") -}) +case object TestObjectAspect + extends InspectorAspect[RawModule]({ _: RawModule => + println("Ran inspectingAspect") + }) class ChiselMainSpec extends AnyFeatureSpec with GivenWhenThen with Matchers with chiselTests.Utils { @@ -68,14 +70,14 @@ class ChiselMainSpec extends AnyFeatureSpec with GivenWhenThen with Matchers wit } case class ChiselMainTest( - args: Array[String], - generator: Option[Class[_ <: RawModule]] = None, - files: Seq[String] = Seq.empty, - stdout: Seq[Either[String, String]] = Seq.empty, - stderr: Seq[Either[String, String]] = Seq.empty, - result: Int = 0, + args: Array[String], + generator: Option[Class[_ <: RawModule]] = None, + files: Seq[String] = Seq.empty, + stdout: Seq[Either[String, String]] = Seq.empty, + stderr: Seq[Either[String, String]] = Seq.empty, + result: Int = 0, fileChecks: Map[String, File => Unit] = Map.empty) { - def testName: String = "args" + args.mkString("_") + def testName: String = "args" + args.mkString("_") def argsString: String = args.mkString(" ") } @@ -89,14 +91,13 @@ class ChiselMainSpec extends AnyFeatureSpec with GivenWhenThen with Matchers wit * @tparam the type of exception that should occur */ case class ChiselMainExceptionTest[A <: Throwable]( - args: Array[String], - generator: Option[Class[_ <: RawModule]] = None, - message: Seq[Either[String, String]] = Seq.empty, - stdout: Seq[Either[String, String]] = Seq.empty, - stderr: Seq[Either[String, String]] = Seq.empty, - stackTrace: Seq[Either[String, String]] = Seq.empty - ) { - def testName: String = "args" + args.mkString("_") + args: Array[String], + generator: Option[Class[_ <: RawModule]] = None, + message: Seq[Either[String, String]] = Seq.empty, + stdout: Seq[Either[String, String]] = Seq.empty, + stderr: Seq[Either[String, String]] = Seq.empty, + stackTrace: Seq[Either[String, String]] = Seq.empty) { + def testName: String = "args" + args.mkString("_") def argsString: String = args.mkString(" ") } @@ -105,12 +106,12 @@ class ChiselMainSpec extends AnyFeatureSpec with GivenWhenThen with Matchers wit val f = new ChiselMainFixture val td = new TargetDirectoryFixture(p.testName) - p.files.foreach( f => new File(td.buildDir + s"/$f").delete() ) + p.files.foreach(f => new File(td.buildDir + s"/$f").delete()) When(s"""the user tries to compile with '${p.argsString}'""") val module: Array[String] = (if (p.generator.nonEmpty) { Array("--module", p.generator.get.getName) } - else { Array.empty[String] }) + else { Array.empty[String] }) f.stage.main(Array("-td", td.buildDir.toString) ++ module ++ p.args) val (stdout, stderr, result) = grabStdOutErr { @@ -122,25 +123,25 @@ class ChiselMainSpec extends AnyFeatureSpec with GivenWhenThen with Matchers wit p.stdout.foreach { case Right(a) => Then(s"""STDOUT should include "$a"""") - stdout should include (a) + stdout should include(a) case Left(a) => Then(s"""STDOUT should not include "$a"""") - stdout should not include (a) + (stdout should not).include(a) } p.stderr.foreach { case Right(a) => Then(s"""STDERR should include "$a"""") - stderr should include (a) + stderr should include(a) case Left(a) => Then(s"""STDERR should not include "$a"""") - stderr should not include (a) + (stderr should not).include(a) } p.result match { case 0 => And(s"the exit code should be 0") - result shouldBe a [Right[_,_]] + result shouldBe a[Right[_, _]] case a => And(s"the exit code should be $a") result shouldBe (Left(a)) @@ -167,7 +168,7 @@ class ChiselMainSpec extends AnyFeatureSpec with GivenWhenThen with Matchers wit When(s"""the user tries to compile with '${p.argsString}'""") val module: Array[String] = (if (p.generator.nonEmpty) { Array("--module", p.generator.get.getName) } - else { Array.empty[String] }) + else { Array.empty[String] }) val (stdout, stderr, result) = grabStdOutErr { catchStatus { @@ -178,7 +179,7 @@ class ChiselMainSpec extends AnyFeatureSpec with GivenWhenThen with Matchers wit } Then("the expected exception was thrown") - result should be a ('right) + (result should be).a('right) val exception = result.right.get info(s""" - Exception was a "${exception.getClass.getName}"""") @@ -186,38 +187,38 @@ class ChiselMainSpec extends AnyFeatureSpec with GivenWhenThen with Matchers wit p.message.foreach { case Right(a) => Then(s"""STDOUT should include "$a"""") - message should include (a) + message should include(a) case Left(a) => Then(s"""STDOUT should not include "$a"""") - message should not include (a) + (message should not).include(a) } p.stdout.foreach { case Right(a) => Then(s"""STDOUT should include "$a"""") - stdout should include (a) + stdout should include(a) case Left(a) => Then(s"""STDOUT should not include "$a"""") - stdout should not include (a) + (stdout should not).include(a) } p.stderr.foreach { case Right(a) => Then(s"""STDERR should include "$a"""") - stderr should include (a) + stderr should include(a) case Left(a) => Then(s"""STDERR should not include "$a"""") - stderr should not include (a) + (stderr should not).include(a) } val stackTraceString = exception.getStackTrace.mkString("\n") p.stackTrace.foreach { case Left(a) => And(s"""the stack does not include "$a"""") - stackTraceString should not include (a) + (stackTraceString should not).include(a) case Right(a) => And(s"""the stack trace includes "$a"""") - stackTraceString should include (a) + stackTraceString should include(a) } } @@ -227,9 +228,7 @@ class ChiselMainSpec extends AnyFeatureSpec with GivenWhenThen with Matchers wit info("I compile a design") Feature("show elaborating message") { runStageExpectFiles( - ChiselMainTest(args = Array("-X", "high"), - generator = Some(classOf[SameTypesModule]) - ) + ChiselMainTest(args = Array("-X", "high"), generator = Some(classOf[SameTypesModule])) ) } @@ -268,46 +267,58 @@ class ChiselMainSpec extends AnyFeatureSpec with GivenWhenThen with Matchers wit args = Array("-X", "low"), generator = Some(classOf[BuilderErrorModule]), message = Seq(Right("Fatal errors during hardware elaboration")), - stdout = Seq(Right("ChiselMainSpec.scala:43: Invalid bit range (3,-1) in class chiselTests.stage.ChiselMainSpec$BuilderErrorModule")) + stdout = Seq( + Right( + "ChiselMainSpec.scala:43: Invalid bit range (3,-1) in class chiselTests.stage.ChiselMainSpec$BuilderErrorModule" + ) + ) ) ).foreach(runStageExpectException) } Feature("Specifying a custom output file") { - runStageExpectFiles(ChiselMainTest( - args = Array("--chisel-output-file", "Foo", "--no-run-firrtl"), - generator = Some(classOf[SameTypesModule]), - files = Seq("Foo.fir"), - fileChecks = Map( - "Foo.fir" -> { file => - And("It should be valid FIRRTL") - Parser.parse(Source.fromFile(file).mkString) - } + runStageExpectFiles( + ChiselMainTest( + args = Array("--chisel-output-file", "Foo", "--no-run-firrtl"), + generator = Some(classOf[SameTypesModule]), + files = Seq("Foo.fir"), + fileChecks = Map( + "Foo.fir" -> { file => + And("It should be valid FIRRTL") + Parser.parse(Source.fromFile(file).mkString) + } + ) ) - )) - runStageExpectFiles(ChiselMainTest( - args = Array("--chisel-output-file", "Foo.pb", "--no-run-firrtl"), - generator = Some(classOf[SameTypesModule]), - files = Seq("Foo.pb"), - fileChecks = Map( - "Foo.pb" -> { file => - And("It should be valid ProtoBuf") - firrtl.proto.FromProto.fromFile(file.toString) - } + ) + runStageExpectFiles( + ChiselMainTest( + args = Array("--chisel-output-file", "Foo.pb", "--no-run-firrtl"), + generator = Some(classOf[SameTypesModule]), + files = Seq("Foo.pb"), + fileChecks = Map( + "Foo.pb" -> { file => + And("It should be valid ProtoBuf") + firrtl.proto.FromProto.fromFile(file.toString) + } + ) ) - )) + ) } info("As an aspect writer") info("I write an aspect") Feature("Running aspects via the command line") { Seq( - ChiselMainTest(args = Array( "-X", "high", "--with-aspect", "chiselTests.stage.TestClassAspect" ), + ChiselMainTest( + args = Array("-X", "high", "--with-aspect", "chiselTests.stage.TestClassAspect"), generator = Some(classOf[SameTypesModule]), - stdout = Seq(Right("Ran inspectingAspect"))), - ChiselMainTest(args = Array( "-X", "high", "--with-aspect", "chiselTests.stage.TestObjectAspect" ), + stdout = Seq(Right("Ran inspectingAspect")) + ), + ChiselMainTest( + args = Array("-X", "high", "--with-aspect", "chiselTests.stage.TestObjectAspect"), generator = Some(classOf[SameTypesModule]), - stdout = Seq(Right("Ran inspectingAspect"))) + stdout = Seq(Right("Ran inspectingAspect")) + ) ).foreach(runStageExpectFiles) } diff --git a/src/test/scala/chiselTests/stage/ChiselOptionsViewSpec.scala b/src/test/scala/chiselTests/stage/ChiselOptionsViewSpec.scala index 99c0f7c0..b164ff20 100644 --- a/src/test/scala/chiselTests/stage/ChiselOptionsViewSpec.scala +++ b/src/test/scala/chiselTests/stage/ChiselOptionsViewSpec.scala @@ -2,7 +2,6 @@ package chiselTests.stage - import firrtl.options.Viewer.view import firrtl.RenameMap @@ -13,7 +12,7 @@ import org.scalatest.matchers.should.Matchers class ChiselOptionsViewSpec extends AnyFlatSpec with Matchers { - behavior of ChiselOptionsView.getClass.getName + behavior.of(ChiselOptionsView.getClass.getName) it should "construct a view from an AnnotationSeq" in { val bar = Circuit("bar", Seq.empty, Seq.empty, RenameMap()) @@ -26,16 +25,16 @@ class ChiselOptionsViewSpec extends AnyFlatSpec with Matchers { val out = view[ChiselOptions](annotations) info("runFirrtlCompiler was set to false") - out.runFirrtlCompiler should be (false) + out.runFirrtlCompiler should be(false) info("printFullStackTrace was set to true") - out.printFullStackTrace should be (true) + out.printFullStackTrace should be(true) info("outputFile was set to 'foo'") - out.outputFile should be (Some("foo")) + out.outputFile should be(Some("foo")) info("chiselCircuit was set to circuit 'bar'") - out.chiselCircuit should be (Some(bar)) + out.chiselCircuit should be(Some(bar)) } diff --git a/src/test/scala/chiselTests/stage/ChiselStageSpec.scala b/src/test/scala/chiselTests/stage/ChiselStageSpec.scala index 7b6a2d39..e88a2385 100644 --- a/src/test/scala/chiselTests/stage/ChiselStageSpec.scala +++ b/src/test/scala/chiselTests/stage/ChiselStageSpec.scala @@ -44,44 +44,44 @@ class ChiselStageSpec extends AnyFlatSpec with Matchers with Utils { val stage = new ChiselStage } - behavior of "ChiselStage$.emitChirrtl" + behavior.of("ChiselStage$.emitChirrtl") it should "return a CHIRRTL string" in { - ChiselStage.emitChirrtl(new Foo) should include ("infer mport") + ChiselStage.emitChirrtl(new Foo) should include("infer mport") } - behavior of "ChiselStage$.emitFirrtl" + behavior.of("ChiselStage$.emitFirrtl") it should "return a High FIRRTL string" in { - ChiselStage.emitFirrtl(new Foo) should include ("mem memory") + ChiselStage.emitFirrtl(new Foo) should include("mem memory") } it should "return a flattened FIRRTL string with '-e high'" in { val args = Array("-e", "high", "-td", createTestDirectory(this.getClass.getSimpleName).toString) (new ChiselStage) - .emitFirrtl(new Foo, args) should include ("module Bar") + .emitFirrtl(new Foo, args) should include("module Bar") } - behavior of "ChiselStage$.emitVerilog" + behavior.of("ChiselStage$.emitVerilog") it should "return a Verilog string" in { - ChiselStage.emitVerilog(new Foo) should include ("endmodule") + ChiselStage.emitVerilog(new Foo) should include("endmodule") } it should "return a flattened Verilog string with '-e verilog'" in { val args = Array("-e", "verilog", "-td", createTestDirectory(this.getClass.getSimpleName).toString) (new ChiselStage) - .emitVerilog(new Foo, args) should include ("module Bar") + .emitVerilog(new Foo, args) should include("module Bar") } - behavior of "ChiselStage$.elaborate" + behavior.of("ChiselStage$.elaborate") ignore should "generate a Chisel circuit from a Chisel module" in { info("no files were written") catchWrites { ChiselStage.elaborate(new Foo) } shouldBe a[Right[_, _]] } - behavior of "ChiselStage$.convert" + behavior.of("ChiselStage$.convert") ignore should "generate a CHIRRTL circuit from a Chisel module" in { info("no files were written") @@ -95,7 +95,7 @@ class ChiselStageSpec extends AnyFlatSpec with Matchers with Utils { } shouldBe a[Right[_, _]] } - behavior of "ChiselStage$.emitChirrtl" + behavior.of("ChiselStage$.emitChirrtl") ignore should "generate a CHIRRTL string from a Chisel module" in { val wrapped = catchWrites { ChiselStage.emitChirrtl(new Foo) } @@ -104,10 +104,10 @@ class ChiselStageSpec extends AnyFlatSpec with Matchers with Utils { wrapped shouldBe a[Right[_, _]] info("returned string looks like FIRRTL") - wrapped.right.get should include ("circuit") + wrapped.right.get should include("circuit") } - behavior of "ChiselStage$.emitFirrtl" + behavior.of("ChiselStage$.emitFirrtl") ignore should "generate a FIRRTL string from a Chisel module" in { val wrapped = catchWrites { ChiselStage.emitFirrtl(new Foo) } @@ -116,10 +116,10 @@ class ChiselStageSpec extends AnyFlatSpec with Matchers with Utils { wrapped shouldBe a[Right[_, _]] info("returned string looks like FIRRTL") - wrapped.right.get should include ("circuit") + wrapped.right.get should include("circuit") } - behavior of "ChiselStage$.emitVerilog" + behavior.of("ChiselStage$.emitVerilog") ignore should "generate a Verilog string from a Chisel module" in { val wrapped = catchWrites { ChiselStage.emitVerilog(new Foo) } @@ -128,10 +128,10 @@ class ChiselStageSpec extends AnyFlatSpec with Matchers with Utils { wrapped shouldBe a[Right[_, _]] info("returned string looks like Verilog") - wrapped.right.get should include ("endmodule") + wrapped.right.get should include("endmodule") } - behavior of "ChiselStage$.emitSystemVerilog" + behavior.of("ChiselStage$.emitSystemVerilog") ignore should "generate a SystemvVerilog string from a Chisel module" in { val wrapped = catchWrites { ChiselStage.emitSystemVerilog(new Foo) } @@ -139,10 +139,10 @@ class ChiselStageSpec extends AnyFlatSpec with Matchers with Utils { wrapped shouldBe a[Right[_, _]] info("returned string looks like Verilog") - wrapped.right.get should include ("endmodule") + wrapped.right.get should include("endmodule") } - behavior of "ChiselStage phase ordering" + behavior.of("ChiselStage phase ordering") it should "only run elaboration once" in new ChiselStageFixture { info("Phase order is:\n" + stage.phaseManager.prettyPrint(" ")) @@ -150,10 +150,10 @@ class ChiselStageSpec extends AnyFlatSpec with Matchers with Utils { val order = stage.phaseManager.flattenedTransformOrder.map(Dependency.fromTransform) info("Elaborate only runs once") - exactly (1, order) should be (Dependency[chisel3.stage.phases.Elaborate]) + exactly(1, order) should be(Dependency[chisel3.stage.phases.Elaborate]) } - behavior of "ChiselStage$ exception handling" + behavior.of("ChiselStage$ exception handling") it should "truncate a user exception" in { info("The user's java.lang.AssertionError was thrown") @@ -163,13 +163,13 @@ class ChiselStageSpec extends AnyFlatSpec with Matchers with Utils { val message = exception.getMessage info("The exception includes the user's message") - message should include ("User threw an exception") + message should include("User threw an exception") info("The stack trace is trimmed") - exception.getStackTrace.mkString("\n") should not include ("java") + (exception.getStackTrace.mkString("\n") should not).include("java") } - behavior of "ChiselStage exception handling" + behavior.of("ChiselStage exception handling") it should "truncate a user exception" in { info("The user's java.lang.AssertionError was thrown") @@ -181,14 +181,14 @@ class ChiselStageSpec extends AnyFlatSpec with Matchers with Utils { val message = exception.getMessage info("The exception includes the user's message") - message should include ("User threw an exception") + message should include("User threw an exception") val stackTrace = exception.getStackTrace.mkString("\n") info("The stack trace is trimmed") - stackTrace should not include ("java") + (stackTrace should not).include("java") info("The stack trace include information about running --full-stacktrace") - stackTrace should include ("--full-stacktrace") + stackTrace should include("--full-stacktrace") } it should """not truncate a user exception with "--full-stacktrace"""" in { @@ -201,10 +201,10 @@ class ChiselStageSpec extends AnyFlatSpec with Matchers with Utils { val message = exception.getMessage info("The exception includes the user's message") - message should include ("User threw an exception") + message should include("User threw an exception") info("The stack trace is not trimmed") - exception.getStackTrace.mkString("\n") should include ("java") + exception.getStackTrace.mkString("\n") should include("java") } } diff --git a/src/test/scala/chiselTests/stage/phases/AddImplicitOutputAnnotationFileSpec.scala b/src/test/scala/chiselTests/stage/phases/AddImplicitOutputAnnotationFileSpec.scala index 63ac7bbe..faf411ed 100644 --- a/src/test/scala/chiselTests/stage/phases/AddImplicitOutputAnnotationFileSpec.scala +++ b/src/test/scala/chiselTests/stage/phases/AddImplicitOutputAnnotationFileSpec.scala @@ -2,7 +2,6 @@ package chiselTests.stage.phases - import chisel3.RawModule import chisel3.stage.ChiselGeneratorAnnotation import chisel3.stage.phases.{AddImplicitOutputAnnotationFile, Elaborate} @@ -18,26 +17,25 @@ class AddImplicitOutputAnnotationFileSpec extends AnyFlatSpec with Matchers { class Fixture { val phase: Phase = new AddImplicitOutputAnnotationFile } - behavior of classOf[AddImplicitOutputAnnotationFile].toString + behavior.of(classOf[AddImplicitOutputAnnotationFile].toString) it should "not override an existing OutputAnnotationFileAnnotation" in new Fixture { - val annotations: AnnotationSeq = Seq( - ChiselGeneratorAnnotation(() => new Foo), - OutputAnnotationFileAnnotation("Bar") ) + val annotations: AnnotationSeq = + Seq(ChiselGeneratorAnnotation(() => new Foo), OutputAnnotationFileAnnotation("Bar")) - Seq( new Elaborate, phase ) + Seq(new Elaborate, phase) .foldLeft(annotations)((a, p) => p.transform(a)) - .collect{ case a: OutputAnnotationFileAnnotation => a.file } - .toSeq should be (Seq("Bar")) + .collect { case a: OutputAnnotationFileAnnotation => a.file } + .toSeq should be(Seq("Bar")) } it should "generate an OutputAnnotationFileAnnotation from a ChiselCircuitAnnotation" in new Fixture { - val annotations: AnnotationSeq = Seq( ChiselGeneratorAnnotation(() => new Foo) ) + val annotations: AnnotationSeq = Seq(ChiselGeneratorAnnotation(() => new Foo)) - Seq( new Elaborate, phase ) + Seq(new Elaborate, phase) .foldLeft(annotations)((a, p) => p.transform(a)) - .collect{ case a: OutputAnnotationFileAnnotation => a.file } - .toSeq should be (Seq("Foo")) + .collect { case a: OutputAnnotationFileAnnotation => a.file } + .toSeq should be(Seq("Foo")) } } diff --git a/src/test/scala/chiselTests/stage/phases/AddImplicitOutputFileSpec.scala b/src/test/scala/chiselTests/stage/phases/AddImplicitOutputFileSpec.scala index e8ba390e..20274e7a 100644 --- a/src/test/scala/chiselTests/stage/phases/AddImplicitOutputFileSpec.scala +++ b/src/test/scala/chiselTests/stage/phases/AddImplicitOutputFileSpec.scala @@ -2,7 +2,6 @@ package chiselTests.stage.phases - import chisel3.RawModule import chisel3.stage.{ChiselGeneratorAnnotation, ChiselOutputFileAnnotation} import chisel3.stage.phases.{AddImplicitOutputFile, Elaborate} @@ -19,32 +18,28 @@ class AddImplicitOutputFileSpec extends AnyFlatSpec with Matchers { class Fixture { val phase: Phase = new AddImplicitOutputFile } - behavior of classOf[AddImplicitOutputFile].toString + behavior.of(classOf[AddImplicitOutputFile].toString) it should "not override an existing ChiselOutputFileAnnotation" in new Fixture { - val annotations: AnnotationSeq = Seq( - ChiselGeneratorAnnotation(() => new Foo), - ChiselOutputFileAnnotation("Bar") ) + val annotations: AnnotationSeq = Seq(ChiselGeneratorAnnotation(() => new Foo), ChiselOutputFileAnnotation("Bar")) - Seq( new Elaborate, phase ) + Seq(new Elaborate, phase) .foldLeft(annotations)((a, p) => p.transform(a)) - .collect{ case a: ChiselOutputFileAnnotation => a.file } - .toSeq should be (Seq("Bar")) + .collect { case a: ChiselOutputFileAnnotation => a.file } + .toSeq should be(Seq("Bar")) } it should "generate a ChiselOutputFileAnnotation from a ChiselCircuitAnnotation" in new Fixture { - val annotations: AnnotationSeq = Seq( - ChiselGeneratorAnnotation(() => new Foo), - TargetDirAnnotation("test_run_dir") ) + val annotations: AnnotationSeq = Seq(ChiselGeneratorAnnotation(() => new Foo), TargetDirAnnotation("test_run_dir")) - Seq( new Elaborate, phase ) + Seq(new Elaborate, phase) .foldLeft(annotations)((a, p) => p.transform(a)) - .collect{ case a: ChiselOutputFileAnnotation => a.file } - .toSeq should be (Seq("Foo")) + .collect { case a: ChiselOutputFileAnnotation => a.file } + .toSeq should be(Seq("Foo")) } it should "do nothing to an empty annotation sequence" in new Fixture { - phase.transform(AnnotationSeq(Seq.empty)).toSeq should be (empty) + phase.transform(AnnotationSeq(Seq.empty)).toSeq should be(empty) } } diff --git a/src/test/scala/chiselTests/stage/phases/AddSerializationAnnotationsSpec.scala b/src/test/scala/chiselTests/stage/phases/AddSerializationAnnotationsSpec.scala index 8bca9ccd..57633eac 100644 --- a/src/test/scala/chiselTests/stage/phases/AddSerializationAnnotationsSpec.scala +++ b/src/test/scala/chiselTests/stage/phases/AddSerializationAnnotationsSpec.scala @@ -2,14 +2,13 @@ package chiselTests.stage.phases - import chisel3.RawModule import chisel3.stage.{ChiselGeneratorAnnotation, ChiselOutputFileAnnotation, CircuitSerializationAnnotation} import chisel3.stage.CircuitSerializationAnnotation._ -import chisel3.stage.phases.{AddSerializationAnnotations, AddImplicitOutputFile, Elaborate} +import chisel3.stage.phases.{AddImplicitOutputFile, AddSerializationAnnotations, Elaborate} import firrtl.AnnotationSeq -import firrtl.options.{Phase, PhaseManager, Dependency, TargetDirAnnotation} +import firrtl.options.{Dependency, Phase, PhaseManager, TargetDirAnnotation} import firrtl.options.Viewer.view import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers @@ -23,39 +22,34 @@ class AddSerializationAnnotationsSpec extends AnyFlatSpec with Matchers { val manager = new PhaseManager(Dependency[AddSerializationAnnotations] :: Nil) } - behavior of classOf[AddSerializationAnnotations].toString + behavior.of(classOf[AddSerializationAnnotations].toString) it should "default to FirrtlFileFormat" in new Fixture { - val annotations: AnnotationSeq = Seq( - ChiselGeneratorAnnotation(() => new Foo), - ChiselOutputFileAnnotation("Bar") ) + val annotations: AnnotationSeq = Seq(ChiselGeneratorAnnotation(() => new Foo), ChiselOutputFileAnnotation("Bar")) manager .transform(annotations) .collect { case CircuitSerializationAnnotation(_, filename, format) => (filename, format) } - .toSeq should be (Seq(("Bar", FirrtlFileFormat))) + .toSeq should be(Seq(("Bar", FirrtlFileFormat))) } it should "support ProtoBufFileFormat" in new Fixture { - val annotations: AnnotationSeq = Seq( - ChiselGeneratorAnnotation(() => new Foo), - ChiselOutputFileAnnotation("Bar.pb") ) + val annotations: AnnotationSeq = Seq(ChiselGeneratorAnnotation(() => new Foo), ChiselOutputFileAnnotation("Bar.pb")) manager .transform(annotations) .collect { case CircuitSerializationAnnotation(_, filename, format) => (filename, format) } - .toSeq should be (Seq(("Bar", ProtoBufFileFormat))) + .toSeq should be(Seq(("Bar", ProtoBufFileFormat))) } it should "support explicitly asking for FirrtlFileFormat" in new Fixture { - val annotations: AnnotationSeq = Seq( - ChiselGeneratorAnnotation(() => new Foo), - ChiselOutputFileAnnotation("Bar.pb.fir") ) + val annotations: AnnotationSeq = + Seq(ChiselGeneratorAnnotation(() => new Foo), ChiselOutputFileAnnotation("Bar.pb.fir")) manager .transform(annotations) .collect { case CircuitSerializationAnnotation(_, filename, format) => (filename, format) } - .toSeq should be (Seq(("Bar.pb", FirrtlFileFormat))) + .toSeq should be(Seq(("Bar.pb", FirrtlFileFormat))) } } diff --git a/src/test/scala/chiselTests/stage/phases/ChecksSpec.scala b/src/test/scala/chiselTests/stage/phases/ChecksSpec.scala index ba9e9254..3d42efdd 100644 --- a/src/test/scala/chiselTests/stage/phases/ChecksSpec.scala +++ b/src/test/scala/chiselTests/stage/phases/ChecksSpec.scala @@ -2,7 +2,6 @@ package chiselTests.stage.phases - import chisel3.stage.{ChiselOutputFileAnnotation, NoRunFirrtlCompilerAnnotation, PrintFullStackTraceAnnotation} import chisel3.stage.phases.Checks @@ -15,15 +14,15 @@ import org.scalatest.matchers.should.Matchers class ChecksSpec extends AnyFlatSpec with Matchers { def checkExceptionMessage(phase: Phase, annotations: AnnotationSeq, messageStart: String): Unit = - intercept[OptionsException]{ phase.transform(annotations) }.getMessage should startWith(messageStart) + intercept[OptionsException] { phase.transform(annotations) }.getMessage should startWith(messageStart) class Fixture { val phase: Phase = new Checks } - behavior of classOf[Checks].toString + behavior.of(classOf[Checks].toString) it should "do nothing on sane annotation sequences" in new Fixture { val a = Seq(NoRunFirrtlCompilerAnnotation, PrintFullStackTraceAnnotation) - phase.transform(a).toSeq should be (a) + phase.transform(a).toSeq should be(a) } it should "throw an OptionsException if more than one NoRunFirrtlCompilerAnnotation is specified" in new Fixture { diff --git a/src/test/scala/chiselTests/stage/phases/ConvertSpec.scala b/src/test/scala/chiselTests/stage/phases/ConvertSpec.scala index 8718f64b..46a2994b 100644 --- a/src/test/scala/chiselTests/stage/phases/ConvertSpec.scala +++ b/src/test/scala/chiselTests/stage/phases/ConvertSpec.scala @@ -2,7 +2,6 @@ package chiselTests.stage.phases - import chisel3._ import chisel3.experimental.{ChiselAnnotation, RunFirrtlTransform} import chisel3.stage.ChiselGeneratorAnnotation @@ -20,13 +19,13 @@ class ConvertSpecFirrtlTransform extends Transform with DependencyAPIMigration { override def optionalPrerequisites = Seq.empty override def optionalPrerequisiteOf = Seq.empty override def invalidates(a: Transform) = false - def execute(state: CircuitState): CircuitState = state + def execute(state: CircuitState): CircuitState = state } case class ConvertSpecFirrtlAnnotation(name: String) extends NoTargetAnnotation case class ConvertSpecChiselAnnotation(name: String) extends ChiselAnnotation with RunFirrtlTransform { - def toFirrtl: Annotation = ConvertSpecFirrtlAnnotation(name) + def toFirrtl: Annotation = ConvertSpecFirrtlAnnotation(name) def transformClass: Class[_ <: Transform] = classOf[ConvertSpecFirrtlTransform] } @@ -43,23 +42,24 @@ class ConvertSpec extends AnyFlatSpec with Matchers { class Fixture { val phase: Phase = new Convert } - behavior of classOf[Convert].toString + behavior.of(classOf[Convert].toString) it should "convert a Chisel Circuit to a FIRRTL Circuit" in new Fixture { val annos: AnnotationSeq = Seq(ChiselGeneratorAnnotation(() => new ConvertSpecFoo)) val annosx = Seq(new Elaborate, phase) - .foldLeft(annos)( (a, p) => p.transform(a) ) + .foldLeft(annos)((a, p) => p.transform(a)) info("FIRRTL circuit generated") - annosx.collect{ case a: FirrtlCircuitAnnotation => a.circuit.main }.toSeq should be (Seq("foo")) + annosx.collect { case a: FirrtlCircuitAnnotation => a.circuit.main }.toSeq should be(Seq("foo")) info("FIRRTL annotations generated") - annosx.collect{ case a: ConvertSpecFirrtlAnnotation => a.name }.toSeq should be (Seq("bar")) + annosx.collect { case a: ConvertSpecFirrtlAnnotation => a.name }.toSeq should be(Seq("bar")) info("FIRRTL transform annotations generated") - annosx.collect{ case a: RunFirrtlTransformAnnotation => a.transform.getClass} - .toSeq should be (Seq(classOf[ConvertSpecFirrtlTransform])) + annosx.collect { case a: RunFirrtlTransformAnnotation => a.transform.getClass }.toSeq should be( + Seq(classOf[ConvertSpecFirrtlTransform]) + ) } } diff --git a/src/test/scala/chiselTests/stage/phases/ElaborateSpec.scala b/src/test/scala/chiselTests/stage/phases/ElaborateSpec.scala index fce040d4..90bb229b 100644 --- a/src/test/scala/chiselTests/stage/phases/ElaborateSpec.scala +++ b/src/test/scala/chiselTests/stage/phases/ElaborateSpec.scala @@ -2,7 +2,6 @@ package chiselTests.stage.phases - import chisel3._ import chisel3.stage.{ChiselCircuitAnnotation, ChiselGeneratorAnnotation} import chisel3.stage.phases.Elaborate @@ -15,11 +14,10 @@ class ElaborateSpec extends AnyFlatSpec with Matchers { class Foo extends Module { override def desiredName: String = "Foo" - val io = IO( - new Bundle { - val in = Input(Bool()) - val out = Output(Bool()) - }) + val io = IO(new Bundle { + val in = Input(Bool()) + val out = Output(Bool()) + }) io.out := ~io.in } @@ -30,18 +28,17 @@ class ElaborateSpec extends AnyFlatSpec with Matchers { class Fixture { val phase: Phase = new Elaborate } - behavior of classOf[Elaborate].toString + behavior.of(classOf[Elaborate].toString) it should "expand ChiselGeneratorAnnotations into ChiselCircuitAnnotations and delete originals" in new Fixture { - val annotations = Seq( ChiselGeneratorAnnotation(() => new Foo), - ChiselGeneratorAnnotation(() => new Bar) ) + val annotations = Seq(ChiselGeneratorAnnotation(() => new Foo), ChiselGeneratorAnnotation(() => new Bar)) val out = phase.transform(annotations) info("original annotations removed") - out.collect{ case a: ChiselGeneratorAnnotation => a } should be (empty) + out.collect { case a: ChiselGeneratorAnnotation => a } should be(empty) info("circuits created with the expected names") - out.collect{ case a: ChiselCircuitAnnotation => a.circuit.name } should be (Seq("Foo", "Bar")) + out.collect { case a: ChiselCircuitAnnotation => a.circuit.name } should be(Seq("Foo", "Bar")) } } diff --git a/src/test/scala/chiselTests/stage/phases/EmitterSpec.scala b/src/test/scala/chiselTests/stage/phases/EmitterSpec.scala index 201f8eaf..9b7d4f42 100644 --- a/src/test/scala/chiselTests/stage/phases/EmitterSpec.scala +++ b/src/test/scala/chiselTests/stage/phases/EmitterSpec.scala @@ -2,7 +2,6 @@ package chiselTests.stage.phases - import chisel3.RawModule import chisel3.stage.{ChiselCircuitAnnotation, ChiselGeneratorAnnotation, ChiselOutputFileAnnotation} import chisel3.stage.phases.{Convert, Elaborate, Emitter} @@ -22,32 +21,31 @@ class EmitterSpec extends AnyFlatSpec with Matchers { class Fixture { val phase: Phase = new Emitter } - behavior of classOf[Emitter].toString + behavior.of(classOf[Emitter].toString) it should "do nothing if no ChiselOutputFileAnnotations are present" in new Fixture { val dir = new File("test_run_dir/EmitterSpec") - val annotations = (new Elaborate).transform(Seq( TargetDirAnnotation(dir.toString), - ChiselGeneratorAnnotation(() => new FooModule) )) + val annotations = + (new Elaborate).transform(Seq(TargetDirAnnotation(dir.toString), ChiselGeneratorAnnotation(() => new FooModule))) val annotationsx = phase.transform(annotations) val Seq(fooFile, barFile) = Seq("Foo.fir", "Bar.fir").map(f => new File(dir + "/" + f)) info(s"$fooFile does not exist") - fooFile should not (exist) + fooFile should not(exist) info("annotations are unmodified") - annotationsx.toSeq should be (annotations.toSeq) + annotationsx.toSeq should be(annotations.toSeq) } it should "emit a ChiselCircuitAnnotation to a specific file" in new Fixture { val dir = new File("test_run_dir/EmitterSpec") val circuit = (new Elaborate) .transform(Seq(ChiselGeneratorAnnotation(() => new BarModule))) - .collectFirst{ case a: ChiselCircuitAnnotation => a} + .collectFirst { case a: ChiselCircuitAnnotation => a } .get - val annotations = phase.transform(Seq( TargetDirAnnotation(dir.toString), - circuit, - ChiselOutputFileAnnotation("Baz") )) + val annotations = + phase.transform(Seq(TargetDirAnnotation(dir.toString), circuit, ChiselOutputFileAnnotation("Baz"))) val bazFile = new File(dir + "/Baz.fir") @@ -55,7 +53,7 @@ class EmitterSpec extends AnyFlatSpec with Matchers { bazFile should (exist) info("a deleted EmittedFirrtlCircuitAnnotation should be generated") - annotations.collect{ case a @ DeletedAnnotation(_, _: EmittedFirrtlCircuitAnnotation) => a }.size should be (1) + annotations.collect { case a @ DeletedAnnotation(_, _: EmittedFirrtlCircuitAnnotation) => a }.size should be(1) } } diff --git a/src/test/scala/chiselTests/util/BitPatSpec.scala b/src/test/scala/chiselTests/util/BitPatSpec.scala index 549e8bca..38ffc3ba 100644 --- a/src/test/scala/chiselTests/util/BitPatSpec.scala +++ b/src/test/scala/chiselTests/util/BitPatSpec.scala @@ -6,13 +6,12 @@ import chisel3.util.BitPat import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers - class BitPatSpec extends AnyFlatSpec with Matchers { - behavior of classOf[BitPat].toString + behavior.of(classOf[BitPat].toString) it should "convert a BitPat to readable form" in { val testPattern = "0" * 32 + "1" * 32 + "?" * 32 + "?01" * 32 - BitPat("b" + testPattern).toString should be (s"BitPat($testPattern)") + BitPat("b" + testPattern).toString should be(s"BitPat($testPattern)") } it should "convert a BitPat to raw form" in { @@ -21,15 +20,15 @@ class BitPatSpec extends AnyFlatSpec with Matchers { } it should "not fail if BitPat width is 0" in { - intercept[IllegalArgumentException]{BitPat("b")} + intercept[IllegalArgumentException] { BitPat("b") } } it should "concat BitPat via ##" in { - (BitPat.Y(4) ## BitPat.dontCare(3) ## BitPat.N(2)).toString should be (s"BitPat(1111???00)") + (BitPat.Y(4) ## BitPat.dontCare(3) ## BitPat.N(2)).toString should be(s"BitPat(1111???00)") } it should "throw when BitPat apply to a Hardware" in { - intercept[java.lang.IllegalArgumentException]{ + intercept[java.lang.IllegalArgumentException] { chisel3.stage.ChiselStage.emitChirrtl(new chisel3.Module { BitPat(chisel3.Reg(chisel3.Bool())) }) diff --git a/src/test/scala/chiselTests/util/BitSetSpec.scala b/src/test/scala/chiselTests/util/BitSetSpec.scala index 8120cc97..dd66ba40 100644 --- a/src/test/scala/chiselTests/util/BitSetSpec.scala +++ b/src/test/scala/chiselTests/util/BitSetSpec.scala @@ -6,14 +6,13 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class BitSetSpec extends AnyFlatSpec with Matchers { - behavior of classOf[BitSet].toString + behavior.of(classOf[BitSet].toString) it should "reject unequal width when constructing a BitSet" in { intercept[IllegalArgumentException] { - BitSet.fromString( - """b0010 - |b00010 - |""".stripMargin) + BitSet.fromString("""b0010 + |b00010 + |""".stripMargin) } } @@ -21,7 +20,7 @@ class BitSetSpec extends AnyFlatSpec with Matchers { val aBitPat = BitPat("b10?") val bBitPat = BitPat("b1??") - aBitPat.subtract(bBitPat).isEmpty should be (true) + aBitPat.subtract(bBitPat).isEmpty should be(true) } it should "return nonempty subtraction result correctly" in { @@ -31,20 +30,19 @@ class BitSetSpec extends AnyFlatSpec with Matchers { val dBitPat = BitPat("b100") val diffBitPat = bBitPat.subtract(aBitPat) - bBitPat.cover(diffBitPat) should be (true) - diffBitPat.equals(cBitPat) should be (true) + bBitPat.cover(diffBitPat) should be(true) + diffBitPat.equals(cBitPat) should be(true) val largerdiffBitPat = bBitPat.subtract(dBitPat) - aBitPat.cover(dBitPat) should be (true) - largerdiffBitPat.cover(diffBitPat) should be (true) + aBitPat.cover(dBitPat) should be(true) + largerdiffBitPat.cover(diffBitPat) should be(true) } it should "be able to handle complex subtract between BitSet" in { - val aBitSet = BitSet.fromString( - """b?01?0 - |b11111 - |b00000 - |""".stripMargin) + val aBitSet = BitSet.fromString("""b?01?0 + |b11111 + |b00000 + |""".stripMargin) val bBitSet = BitSet.fromString( """b?1111 |b?0000 @@ -52,44 +50,41 @@ class BitSetSpec extends AnyFlatSpec with Matchers { ) val expected = BitPat("b?01?0") - expected.equals(aBitSet.subtract(bBitSet)) should be (true) + expected.equals(aBitSet.subtract(bBitSet)) should be(true) } it should "be generated from BitPat union" in { - val aBitSet = BitSet.fromString( - """b001?0 - |b000??""".stripMargin) + val aBitSet = BitSet.fromString("""b001?0 + |b000??""".stripMargin) val aBitPat = BitPat("b000??") val bBitPat = BitPat("b001?0") val cBitPat = BitPat("b00000") - aBitPat.cover(cBitPat) should be (true) - aBitSet.cover(bBitPat) should be (true) + aBitPat.cover(cBitPat) should be(true) + aBitSet.cover(bBitPat) should be(true) - aBitSet.equals(aBitPat.union(bBitPat)) should be (true) + aBitSet.equals(aBitPat.union(bBitPat)) should be(true) } it should "be generated from BitPat subtraction" in { - val aBitSet = BitSet.fromString( - """b001?0 - |b000??""".stripMargin) + val aBitSet = BitSet.fromString("""b001?0 + |b000??""".stripMargin) val aBitPat = BitPat("b00???") val bBitPat = BitPat("b001?1") - aBitSet.equals(aBitPat.subtract(bBitPat)) should be (true) + aBitSet.equals(aBitPat.subtract(bBitPat)) should be(true) } it should "union two BitSet together" in { - val aBitSet = BitSet.fromString( - """b001?0 - |b001?1 - |""".stripMargin) + val aBitSet = BitSet.fromString("""b001?0 + |b001?1 + |""".stripMargin) val bBitSet = BitSet.fromString( """b000?? |b01??? |""".stripMargin ) val cBitPat = BitPat("b0????") - cBitPat.equals(aBitSet.union(bBitSet)) should be (true) + cBitPat.equals(aBitSet.union(bBitSet)) should be(true) } it should "be decoded" in { @@ -100,19 +95,23 @@ class BitSetSpec extends AnyFlatSpec with Matchers { chisel3.stage.ChiselStage.emitSystemVerilog(new Module { val in = IO(Input(UInt(8.W))) val out = IO(Output(UInt(4.W))) - out := decoder.bitset(in, Seq( - BitSet.fromString( - "b000?????" + out := decoder.bitset( + in, + Seq( + BitSet.fromString( + "b000?????" + ), + BitSet.fromString( + """b0010???? + |b01?????? + |""".stripMargin + ), + BitSet.fromString( + "b11??????" + ) ), - BitSet.fromString( - """b0010???? - |b01?????? - |""".stripMargin - ), - BitSet.fromString( - "b11??????" - ) - ), true) + true + ) }) } diff --git a/src/test/scala/chiselTests/util/CatSpec.scala b/src/test/scala/chiselTests/util/CatSpec.scala index 79d2c027..a75c4ec0 100644 --- a/src/test/scala/chiselTests/util/CatSpec.scala +++ b/src/test/scala/chiselTests/util/CatSpec.scala @@ -12,7 +12,7 @@ import chiselTests.ChiselFlatSpec object CatSpec { class JackIsATypeSystemGod extends Module { - val in = IO(Input (Vec(0, UInt(8.W)))) + val in = IO(Input(Vec(0, UInt(8.W)))) val out = IO(Output(UInt(8.W))) out := Cat(in) @@ -24,7 +24,7 @@ class CatSpec extends ChiselFlatSpec { import CatSpec._ - behavior of "util.Cat" + behavior.of("util.Cat") it should "not fail to elaborate a zero-element Vec" in { @@ -41,7 +41,7 @@ class CatSpec extends ChiselFlatSpec { } val chirrtl = ChiselStage.emitChirrtl(new MyModule) for (name <- Seq("a", "b", "c", "d")) { - chirrtl should include (s"input $name : UInt<8>") + chirrtl should include(s"input $name : UInt<8>") } } @@ -54,11 +54,10 @@ class CatSpec extends ChiselFlatSpec { out := noPrefix(Cat(in)) } val chirrtl = ChiselStage.emitChirrtl(new MyModule) - chirrtl should include ("node lo_lo = cat(in[6], in[7])") - chirrtl should include ("node lo_hi = cat(in[4], in[5])") - chirrtl should include ("node hi_lo = cat(in[2], in[3])") - chirrtl should include ("node hi_hi = cat(in[0], in[1])") + chirrtl should include("node lo_lo = cat(in[6], in[7])") + chirrtl should include("node lo_hi = cat(in[4], in[5])") + chirrtl should include("node hi_lo = cat(in[2], in[3])") + chirrtl should include("node hi_hi = cat(in[0], in[1])") } - } diff --git a/src/test/scala/chiselTests/util/experimental/PlaSpec.scala b/src/test/scala/chiselTests/util/experimental/PlaSpec.scala index 8af5c936..156249a2 100644 --- a/src/test/scala/chiselTests/util/experimental/PlaSpec.scala +++ b/src/test/scala/chiselTests/util/experimental/PlaSpec.scala @@ -3,7 +3,7 @@ package chiselTests.util.experimental import chisel3._ import chisel3.stage.PrintFullStackTraceAnnotation import chisel3.testers.BasicTester -import chisel3.util.{BitPat, pla} +import chisel3.util.{pla, BitPat} import chiselTests.ChiselFlatSpec class PlaSpec extends ChiselFlatSpec { @@ -17,12 +17,17 @@ class PlaSpec extends ChiselFlatSpec { (BitPat("b100"), BitPat("b00010000")), (BitPat("b101"), BitPat("b00100000")), (BitPat("b110"), BitPat("b01000000")), - (BitPat("b111"), BitPat("b10000000")), + (BitPat("b111"), BitPat("b10000000")) ) - table.foreach { case (i, o) => - val (plaIn, plaOut) = pla(table) - plaIn := WireDefault(i.value.U(3.W)) - chisel3.assert(plaOut === o.value.U(8.W), "Input " + i.toString + " produced incorrect output BitPat(%b)", plaOut) + table.foreach { + case (i, o) => + val (plaIn, plaOut) = pla(table) + plaIn := WireDefault(i.value.U(3.W)) + chisel3.assert( + plaOut === o.value.U(8.W), + "Input " + i.toString + " produced incorrect output BitPat(%b)", + plaOut + ) } stop() }) @@ -38,12 +43,17 @@ class PlaSpec extends ChiselFlatSpec { (BitPat("b100"), BitPat("b00010000")), (BitPat("b101"), BitPat("b00100000")), (BitPat("b110"), BitPat("b01000000")), - (BitPat("b111"), BitPat("b10000000")), + (BitPat("b111"), BitPat("b10000000")) ) - table.foreach { case (i, o) => - val (plaIn, plaOut) = pla(table, BitPat("b11111111")) - plaIn := WireDefault(i.value.U(3.W)) - chisel3.assert(plaOut === ~o.value.U(8.W), "Input " + i.toString + " produced incorrect output BitPat(%b)", plaOut) + table.foreach { + case (i, o) => + val (plaIn, plaOut) = pla(table, BitPat("b11111111")) + plaIn := WireDefault(i.value.U(3.W)) + chisel3.assert( + plaOut === ~o.value.U(8.W), + "Input " + i.toString + " produced incorrect output BitPat(%b)", + plaOut + ) } stop() }) @@ -53,12 +63,13 @@ class PlaSpec extends ChiselFlatSpec { assertTesterPasses(new BasicTester { val table = Seq( (BitPat("b000"), BitPat("b?01")), - (BitPat("b111"), BitPat("b?01")), + (BitPat("b111"), BitPat("b?01")) ) - table.foreach { case (i, o) => - val (plaIn, plaOut) = pla(table) - plaIn := WireDefault(i.value.U(3.W)) - chisel3.assert(o === plaOut, "Input " + i.toString + " produced incorrect output BitPat(%b)", plaOut) + table.foreach { + case (i, o) => + val (plaIn, plaOut) = pla(table) + plaIn := WireDefault(i.value.U(3.W)) + chisel3.assert(o === plaOut, "Input " + i.toString + " produced incorrect output BitPat(%b)", plaOut) } stop() }) @@ -82,12 +93,17 @@ class PlaSpec extends ChiselFlatSpec { (BitPat("b1100"), BitPat("b0")), (BitPat("b1101"), BitPat("b1")), (BitPat("b1110"), BitPat("b1")), - (BitPat("b1111"), BitPat("b1")), + (BitPat("b1111"), BitPat("b1")) ) - table.foreach { case (i, o) => - val (plaIn, plaOut) = pla(table) - plaIn := WireDefault(i.value.U(4.W)) - chisel3.assert(plaOut === o.value.U(1.W), "Input " + i.toString + " produced incorrect output BitPat(%b)", plaOut) + table.foreach { + case (i, o) => + val (plaIn, plaOut) = pla(table) + plaIn := WireDefault(i.value.U(4.W)) + chisel3.assert( + plaOut === o.value.U(1.W), + "Input " + i.toString + " produced incorrect output BitPat(%b)", + plaOut + ) } stop() }) diff --git a/src/test/scala/chiselTests/util/experimental/TruthTableSpec.scala b/src/test/scala/chiselTests/util/experimental/TruthTableSpec.scala index 255effaf..2ef316bb 100644 --- a/src/test/scala/chiselTests/util/experimental/TruthTableSpec.scala +++ b/src/test/scala/chiselTests/util/experimental/TruthTableSpec.scala @@ -4,7 +4,7 @@ package chiselTests.util.experimental import chisel3._ import chisel3.util.BitPat -import chisel3.util.experimental.decode.{TruthTable, decoder} +import chisel3.util.experimental.decode.{decoder, TruthTable} import org.scalatest.flatspec.AnyFlatSpec class TruthTableSpec extends AnyFlatSpec { @@ -64,15 +64,14 @@ class TruthTableSpec extends AnyFlatSpec { "TruthTable" should "be reproducible" in { class Foo extends Module { - val io = IO(new Bundle{ + val io = IO(new Bundle { val in = Input(UInt(4.W)) val out = Output(UInt(16.W)) }) - val table = TruthTable( - (0 until 16).map{ - i => BitPat(i.U(4.W)) -> BitPat((1<<i).U(16.W)) + (0 until 16).map { i => + BitPat(i.U(4.W)) -> BitPat((1 << i).U(16.W)) }, BitPat.dontCare(16) ) diff --git a/src/test/scala/chiselTests/util/random/LFSRSpec.scala b/src/test/scala/chiselTests/util/random/LFSRSpec.scala index 975a3c93..d47c2d7d 100644 --- a/src/test/scala/chiselTests/util/random/LFSRSpec.scala +++ b/src/test/scala/chiselTests/util/random/LFSRSpec.scala @@ -23,7 +23,7 @@ class LFSRMaxPeriod(gen: => UInt) extends BasicTester { val (_, wrap) = Counter(started, math.pow(2.0, rv.getWidth).toInt - 1) - when (rv === seed && started) { + when(rv === seed && started) { chisel3.assert(wrap) stop() } @@ -49,7 +49,7 @@ class LFSRDistribution(gen: => UInt, cycles: Int = 10000) extends BasicTester { val (trial, done) = Counter(true.B, cycles) - val rollValue = die0 +& die1 // Note +& is critical because sum will need an extra bit. + val rollValue = die0 +& die1 // Note +& is critical because sum will need an extra bit. bins(rollValue) := bins(rollValue) + 1.U @@ -88,17 +88,17 @@ class LFSRResetTester(gen: => LFSR, lockUpValue: BigInt) extends BasicTester { lfsr.io.seed.bits := lockUpValue.U(lfsr.width.W).asBools lfsr.io.increment := true.B - when (count === 2.U) { + when(count === 2.U) { assert(lfsr.io.out.asUInt === lockUpValue.U, "LFSR is NOT locked up, but should be!") } lfsr.reset := count === 3.U - when (count === 4.U) { + when(count === 4.U) { assert(lfsr.io.out.asUInt =/= lockUpValue.U, "LFSR is locked up, but should not be after reset!") } - when (done) { + when(done) { stop() } @@ -110,29 +110,34 @@ class LFSRSpec extends ChiselFlatSpec with Utils { val testName = s"have a maximal period over a range of widths (${range.head} to ${range.last})" + s" using ${reduction.getClass}" it should testName in { - range - .foreach{ width => - LFSR.tapsMaxPeriod(width).foreach{ taps => - info(s"""width $width okay using taps: ${taps.mkString(", ")}""") - assertTesterPasses(new LFSRMaxPeriod(PRNG(gen(width, taps, reduction))), - annotations = TesterDriver.verilatorOnly) - } + range.foreach { width => + LFSR.tapsMaxPeriod(width).foreach { taps => + info(s"""width $width okay using taps: ${taps.mkString(", ")}""") + assertTesterPasses( + new LFSRMaxPeriod(PRNG(gen(width, taps, reduction))), + annotations = TesterDriver.verilatorOnly + ) } + } } } - behavior of "LFSR" + behavior.of("LFSR") it should "throw an exception if initialized to a seed of zero for XOR configuration" in { - { the [IllegalArgumentException] thrownBy extractCause[IllegalArgumentException] { - ChiselStage.elaborate(new FooLFSR(XOR, Some(0))) } - }.getMessage should include ("Seed cannot be zero") + { + the[IllegalArgumentException] thrownBy extractCause[IllegalArgumentException] { + ChiselStage.elaborate(new FooLFSR(XOR, Some(0))) + } + }.getMessage should include("Seed cannot be zero") } it should "throw an exception if initialized to a seed of all ones for XNOR configuration" in { - { the [IllegalArgumentException] thrownBy extractCause[IllegalArgumentException] { - ChiselStage.elaborate(new FooLFSR(XNOR, Some(15))) } - }.getMessage should include ("Seed cannot be all ones") + { + the[IllegalArgumentException] thrownBy extractCause[IllegalArgumentException] { + ChiselStage.elaborate(new FooLFSR(XNOR, Some(15))) + } + }.getMessage should include("Seed cannot be all ones") } it should "reset correctly without a seed for XOR configuration" in { @@ -143,34 +148,35 @@ class LFSRSpec extends ChiselFlatSpec with Utils { assertTesterPasses(new LFSRResetTester(new FooLFSR(XNOR, None), 15)) } - behavior of "MaximalPeriodGaloisLFSR" + behavior.of("MaximalPeriodGaloisLFSR") it should "throw an exception if no LFSR taps are known" in { - { the [IllegalArgumentException] thrownBy extractCause[IllegalArgumentException] { - ChiselStage.elaborate(new MaxPeriodGaloisLFSR(787)) } - }.getMessage should include ("No max period LFSR taps stored for requested width") + { + the[IllegalArgumentException] thrownBy extractCause[IllegalArgumentException] { + ChiselStage.elaborate(new MaxPeriodGaloisLFSR(787)) + } + }.getMessage should include("No max period LFSR taps stored for requested width") } - periodCheck((w: Int, t: Set[Int], r: LFSRReduce) => new GaloisLFSR(w, t, reduction=r), XOR, 2 to 16) - periodCheck((w: Int, t: Set[Int], r: LFSRReduce) => new GaloisLFSR(w, t, reduction=r), XNOR, 2 to 16) + periodCheck((w: Int, t: Set[Int], r: LFSRReduce) => new GaloisLFSR(w, t, reduction = r), XOR, 2 to 16) + periodCheck((w: Int, t: Set[Int], r: LFSRReduce) => new GaloisLFSR(w, t, reduction = r), XNOR, 2 to 16) ignore should "have a sane distribution for larger widths" in { - ((17 to 32) ++ Seq(64, 128, 256, 512, 1024, 2048, 4096)) - .foreach{ width => - info(s"width $width okay!") - assertTesterPasses(new LFSRDistribution(LFSR(width), math.pow(2, 22).toInt)) - } + ((17 to 32) ++ Seq(64, 128, 256, 512, 1024, 2048, 4096)).foreach { width => + info(s"width $width okay!") + assertTesterPasses(new LFSRDistribution(LFSR(width), math.pow(2, 22).toInt)) + } } - behavior of "MaximalPeriodFibonacciLFSR" + behavior.of("MaximalPeriodFibonacciLFSR") - periodCheck((w: Int, t: Set[Int], r: LFSRReduce) => new FibonacciLFSR(w, t, reduction=r), XOR, 2 to 16) - periodCheck((w: Int, t: Set[Int], r: LFSRReduce) => new FibonacciLFSR(w, t, reduction=r), XNOR, 2 to 16) + periodCheck((w: Int, t: Set[Int], r: LFSRReduce) => new FibonacciLFSR(w, t, reduction = r), XOR, 2 to 16) + periodCheck((w: Int, t: Set[Int], r: LFSRReduce) => new FibonacciLFSR(w, t, reduction = r), XNOR, 2 to 16) - behavior of "LFSR maximal period taps" + behavior.of("LFSR maximal period taps") it should "contain all the expected widths" in { - ((2 to 786) ++ Seq(1024, 2048, 4096)).foreach(LFSR.tapsMaxPeriod.keys should contain (_)) + ((2 to 786) ++ Seq(1024, 2048, 4096)).foreach(LFSR.tapsMaxPeriod.keys should contain(_)) } } diff --git a/src/test/scala/chiselTests/util/random/PRNGSpec.scala b/src/test/scala/chiselTests/util/random/PRNGSpec.scala index 71a8635c..36fdf9cb 100644 --- a/src/test/scala/chiselTests/util/random/PRNGSpec.scala +++ b/src/test/scala/chiselTests/util/random/PRNGSpec.scala @@ -28,15 +28,15 @@ class PRNGStepTest extends BasicTester { val (_, done) = Counter(true.B, 16) - when (count2 === 0.U) { + when(count2 === 0.U) { assert(a === b, "1-step and 2-step PRNGs did not agree! (0b%b != 0b%b)", a, b) } - when (count4 === 0.U) { + when(count4 === 0.U) { assert(a === c, "1-step and 4-step PRNGs did not agree!") } - when (done) { + when(done) { stop() } @@ -52,11 +52,11 @@ class PRNGUpdateSeedTest(updateSeed: Boolean, seed: BigInt, expected: BigInt) ex a.io.seed.valid := count === 2.U a.io.seed.bits := seed.U(a.width.W).asBools - when (count === 3.U) { + when(count === 3.U) { assert(a.io.out.asUInt === expected.U, "Output didn't match!") } - when (done) { + when(done) { stop() } @@ -64,18 +64,22 @@ class PRNGUpdateSeedTest(updateSeed: Boolean, seed: BigInt, expected: BigInt) ex class PRNGSpec extends ChiselFlatSpec with Utils { - behavior of "PRNG" + behavior.of("PRNG") it should "throw an exception if the step size is < 1" in { - { the [IllegalArgumentException] thrownBy extractCause[IllegalArgumentException] { - ChiselStage.elaborate(new CyclePRNG(0, Some(1), 1, true)) } - }.getMessage should include ("Width must be greater than zero!") + { + the[IllegalArgumentException] thrownBy extractCause[IllegalArgumentException] { + ChiselStage.elaborate(new CyclePRNG(0, Some(1), 1, true)) + } + }.getMessage should include("Width must be greater than zero!") } it should "throw an exception if the step size is <= 0" in { - { the [IllegalArgumentException] thrownBy extractCause[IllegalArgumentException] { - ChiselStage.elaborate(new CyclePRNG(1, Some(1), 0, true)) } - }.getMessage should include ("Step size must be greater than one!") + { + the[IllegalArgumentException] thrownBy extractCause[IllegalArgumentException] { + ChiselStage.elaborate(new CyclePRNG(1, Some(1), 0, true)) + } + }.getMessage should include("Step size must be greater than one!") } it should "handle non-unary steps" in { diff --git a/src/test/scala/cookbook/Bundle2UInt.scala b/src/test/scala/cookbook/Bundle2UInt.scala index 5bc1063a..21d06df7 100644 --- a/src/test/scala/cookbook/Bundle2UInt.scala +++ b/src/test/scala/cookbook/Bundle2UInt.scala @@ -24,7 +24,7 @@ class Bundle2UInt extends CookbookTester(1) { assert(uint === 0xc3.U) } -class Bundle2UIntSpec extends CookbookSpec { +class Bundle2UIntSpec extends CookbookSpec { "Bundle2UInt" should "work" in { assertTesterPasses { new Bundle2UInt } } diff --git a/src/test/scala/cookbook/CookbookSpec.scala b/src/test/scala/cookbook/CookbookSpec.scala index c1acc0de..7d6c9726 100644 --- a/src/test/scala/cookbook/CookbookSpec.scala +++ b/src/test/scala/cookbook/CookbookSpec.scala @@ -16,7 +16,7 @@ abstract class CookbookTester(length: Int) extends BasicTester { require(length >= 0, "Simulation length must be non-negative!") val (cycle, done) = Counter(true.B, length + 1) // + 1 cycle because done is actually wrap - when (done) { stop() } + when(done) { stop() } } abstract class CookbookSpec extends ChiselFlatSpec diff --git a/src/test/scala/cookbook/FSM.scala b/src/test/scala/cookbook/FSM.scala index 0c1173ec..66f3063f 100644 --- a/src/test/scala/cookbook/FSM.scala +++ b/src/test/scala/cookbook/FSM.scala @@ -26,21 +26,21 @@ class DetectTwoOnes extends Module { io.out := (state === State.sTwo1s) - switch (state) { - is (State.sNone) { - when (io.in) { + switch(state) { + is(State.sNone) { + when(io.in) { state := State.sOne1 } } - is (State.sOne1) { - when (io.in) { + is(State.sOne1) { + when(io.in) { state := State.sTwo1s - } .otherwise { + }.otherwise { state := State.sNone } } - is (State.sTwo1s) { - when (!io.in) { + is(State.sTwo1s) { + when(!io.in) { state := State.sNone } } @@ -53,7 +53,8 @@ class DetectTwoOnesTester extends CookbookTester(10) { // Inputs and expected results val inputs: Vec[Bool] = VecInit(false.B, true.B, false.B, true.B, true.B, true.B, false.B, true.B, true.B, false.B) - val expected: Vec[Bool] = VecInit(false.B, false.B, false.B, false.B, false.B, true.B, true.B, false.B, false.B, true.B) + val expected: Vec[Bool] = + VecInit(false.B, false.B, false.B, false.B, false.B, true.B, true.B, false.B, false.B, true.B) dut.io.in := inputs(cycle) assert(dut.io.out === expected(cycle)) diff --git a/src/test/scala/cookbook/RegOfVec.scala b/src/test/scala/cookbook/RegOfVec.scala index ba1ab359..ddb615c7 100644 --- a/src/test/scala/cookbook/RegOfVec.scala +++ b/src/test/scala/cookbook/RegOfVec.scala @@ -22,11 +22,11 @@ class RegOfVec extends CookbookTester(2) { val initRegOfVec = RegInit(VecInit(Seq.fill(4)(0.U(32.W)))) // Simple test (cycle comes from superclass) - when (cycle === 2.U) { assert(regOfVec(2) === 123.U) } + when(cycle === 2.U) { assert(regOfVec(2) === 123.U) } for (elt <- initRegOfVec) { assert(elt === 0.U) } } -class RegOfVecSpec extends CookbookSpec { +class RegOfVecSpec extends CookbookSpec { "RegOfVec" should "work" in { assertTesterPasses { new RegOfVec } } diff --git a/src/test/scala/cookbook/VecOfBool2UInt.scala b/src/test/scala/cookbook/VecOfBool2UInt.scala index 024eca89..ca1413dc 100644 --- a/src/test/scala/cookbook/VecOfBool2UInt.scala +++ b/src/test/scala/cookbook/VecOfBool2UInt.scala @@ -21,7 +21,7 @@ class VecOfBool2UInt extends CookbookTester(1) { assert(0xd.U === uint) } -class VecOfBool2UIntSpec extends CookbookSpec { +class VecOfBool2UIntSpec extends CookbookSpec { "VecOfBool2UInt" should "work" in { assertTesterPasses { new VecOfBool2UInt } } diff --git a/src/test/scala/examples/ImplicitStateVendingMachine.scala b/src/test/scala/examples/ImplicitStateVendingMachine.scala index 817240d5..36ac82ab 100644 --- a/src/test/scala/examples/ImplicitStateVendingMachine.scala +++ b/src/test/scala/examples/ImplicitStateVendingMachine.scala @@ -12,14 +12,14 @@ class ImplicitStateVendingMachine extends SimpleVendingMachine { val incValue = WireDefault(0.asUInt(3.W)) val doDispense = value >= 4.U // 4 * nickel as 1 == $0.20 - when (doDispense) { + when(doDispense) { value := 0.U // No change given - } .otherwise { + }.otherwise { value := value + incValue } - when (io.nickel) { incValue := 1.U } - when (io.dime) { incValue := 2.U } + when(io.nickel) { incValue := 1.U } + when(io.dime) { incValue := 2.U } io.dispense := doDispense } diff --git a/src/test/scala/examples/SimpleVendingMachine.scala b/src/test/scala/examples/SimpleVendingMachine.scala index dff60a4d..819669a3 100644 --- a/src/test/scala/examples/SimpleVendingMachine.scala +++ b/src/test/scala/examples/SimpleVendingMachine.scala @@ -9,8 +9,8 @@ import chisel3.util._ class SimpleVendingMachineIO extends Bundle { val nickel = Input(Bool()) - val dime = Input(Bool()) - val dispense = Output(Bool()) + val dime = Input(Bool()) + val dispense = Output(Bool()) } // Superclass for vending machines with very simple IO @@ -24,24 +24,24 @@ class FSMVendingMachine extends SimpleVendingMachine { val sIdle :: s5 :: s10 :: s15 :: sOk :: Nil = Enum(5) val state = RegInit(sIdle) - switch (state) { - is (sIdle) { - when (io.nickel) { state := s5 } - when (io.dime) { state := s10 } + switch(state) { + is(sIdle) { + when(io.nickel) { state := s5 } + when(io.dime) { state := s10 } } - is (s5) { - when (io.nickel) { state := s10 } - when (io.dime) { state := s15 } + is(s5) { + when(io.nickel) { state := s10 } + when(io.dime) { state := s15 } } - is (s10) { - when (io.nickel) { state := s15 } - when (io.dime) { state := sOk } + is(s10) { + when(io.nickel) { state := s15 } + when(io.dime) { state := sOk } } - is (s15) { - when (io.nickel) { state := sOk } - when (io.dime) { state := sOk } + is(s15) { + when(io.nickel) { state := sOk } + when(io.dime) { state := sOk } } - is (sOk) { + is(sOk) { state := sIdle } } @@ -73,11 +73,11 @@ class SimpleVendingMachineTester(mod: => SimpleVendingMachine) extends BasicTest val dut = Module(mod) val (cycle, done) = Counter(true.B, 10) - when (done) { stop(); stop() } // Stop twice because of Verilator + when(done) { stop(); stop() } // Stop twice because of Verilator val nickelInputs = VecInit(true.B, true.B, true.B, true.B, true.B, false.B, false.B, false.B, true.B, false.B) - val dimeInputs = VecInit(false.B, false.B, false.B, false.B, false.B, true.B, true.B, false.B, false.B, true.B) - val expected = VecInit(false.B, false.B, false.B, false.B, true.B , false.B, false.B, true.B, false.B, false.B) + val dimeInputs = VecInit(false.B, false.B, false.B, false.B, false.B, true.B, true.B, false.B, false.B, true.B) + val expected = VecInit(false.B, false.B, false.B, false.B, true.B, false.B, false.B, true.B, false.B, false.B) dut.io.nickel := nickelInputs(cycle) dut.io.dime := dimeInputs(cycle) @@ -89,7 +89,10 @@ class SimpleVendingMachineSpec extends ChiselFlatSpec { assertTesterPasses { new SimpleVendingMachineTester(new FSMVendingMachine) } } "An Verilog implementation of a vending machine" should "work" in { - assertTesterPasses(new SimpleVendingMachineTester(new VerilogVendingMachineWrapper), - List("/chisel3/VerilogVendingMachine.v"), annotations = TesterDriver.verilatorOnly) + assertTesterPasses( + new SimpleVendingMachineTester(new VerilogVendingMachineWrapper), + List("/chisel3/VerilogVendingMachine.v"), + annotations = TesterDriver.verilatorOnly + ) } } diff --git a/src/test/scala/examples/VendingMachineGenerator.scala b/src/test/scala/examples/VendingMachineGenerator.scala index 72bfdf53..4adae987 100644 --- a/src/test/scala/examples/VendingMachineGenerator.scala +++ b/src/test/scala/examples/VendingMachineGenerator.scala @@ -12,12 +12,14 @@ import VendingMachineUtils._ class VendingMachineIO(val legalCoins: Seq[Coin]) extends Bundle { require(legalCoins.size >= 1, "The vending machine must accept at least 1 coin!") // Order of coins by value - val coins: Seq[Coin] = legalCoins sortBy (_.value) + val coins: Seq[Coin] = legalCoins.sortBy(_.value) // Map of coin names to their relative position in value (ie. index in inputs) val indexMap: Map[String, Int] = coins.map(_.name).zipWithIndex.toMap - require(coins map (_.value % coins.head.value == 0) reduce (_ && _), - "All coins must be a multiple of the lowest value coin!") + require( + coins.map(_.value % coins.head.value == 0).reduce(_ && _), + "All coins must be a multiple of the lowest value coin!" + ) val inputs = Input(Vec(legalCoins.size, Bool())) val dispense = Output(Bool()) @@ -34,17 +36,17 @@ abstract class ParameterizedVendingMachine(legalCoins: Seq[Coin], val sodaCost: // Enforce one hot if (io.inputs.size > 1) { for (input <- io.inputs) { - when (input) { - assert(io.inputs.filterNot(_ == input).map(!_).reduce(_ && _), - "Only 1 coin can be input in a given cycle!") + when(input) { + assert(io.inputs.filterNot(_ == input).map(!_).reduce(_ && _), "Only 1 coin can be input in a given cycle!") } } } } class VendingMachineGenerator( - legalCoins: Seq[Coin], - sodaCost: Int) extends ParameterizedVendingMachine(legalCoins, sodaCost) { + legalCoins: Seq[Coin], + sodaCost: Int) + extends ParameterizedVendingMachine(legalCoins, sodaCost) { require(sodaCost > 0, "Sodas must actually cost something!") // All coin values are normalized to a multiple of the minimum coin value @@ -57,21 +59,22 @@ class VendingMachineGenerator( val incValue = WireDefault(0.asUInt(width)) val doDispense = value >= (sodaCost / minCoin).U - when (doDispense) { + when(doDispense) { value := 0.U // No change given - } .otherwise { + }.otherwise { value := value + incValue } for ((coin, index) <- io.coins.zipWithIndex) { - when (io.inputs(index)) { incValue := (coin.value / minCoin).U } + when(io.inputs(index)) { incValue := (coin.value / minCoin).U } } io.dispense := doDispense } class ParameterizedVendingMachineTester( - mod: => ParameterizedVendingMachine, - testLength: Int) extends BasicTester { + mod: => ParameterizedVendingMachine, + testLength: Int) + extends BasicTester { require(testLength > 0, "Test length must be positive!") // Construct the module @@ -81,24 +84,24 @@ class ParameterizedVendingMachineTester( // Inputs and expected results // Do random testing private val _rand = scala.util.Random - val inputs: Seq[Option[Coin]] = Seq.fill(testLength)(coins.lift(_rand.nextInt(coins.size + 1))) + val inputs: Seq[Option[Coin]] = Seq.fill(testLength)(coins.lift(_rand.nextInt(coins.size + 1))) val expected: Seq[Boolean] = getExpectedResults(inputs, dut.sodaCost) - val inputVec: Vec[UInt] = VecInit(inputs map { + val inputVec: Vec[UInt] = VecInit(inputs.map { case Some(coin) => (1 << dut.io.indexMap(coin.name)).asUInt(coins.size.W) - case None => 0.asUInt(coins.size.W) + case None => 0.asUInt(coins.size.W) }) - val expectedVec: Vec[Bool] = VecInit(expected map (_.B)) + val expectedVec: Vec[Bool] = VecInit(expected.map(_.B)) val (idx, done) = Counter(true.B, testLength + 1) - when (done) { stop(); stop() } // Two stops for Verilator + when(done) { stop(); stop() } // Two stops for Verilator dut.io.inputs := inputVec(idx).asBools assert(dut.io.dispense === expectedVec(idx)) } class VendingMachineGeneratorSpec extends ChiselFlatSpec { - behavior of "The vending machine generator" + behavior.of("The vending machine generator") it should "generate a vending machine that accepts only nickels and dimes and costs $0.20" in { val coins = Seq(Nickel, Dime) diff --git a/src/test/scala/examples/VendingMachineUtils.scala b/src/test/scala/examples/VendingMachineUtils.scala index 6847768a..8d5aea57 100644 --- a/src/test/scala/examples/VendingMachineUtils.scala +++ b/src/test/scala/examples/VendingMachineUtils.scala @@ -24,7 +24,7 @@ object VendingMachineUtils { for (input <- inputs) { val incValue = input match { case Some(coin) => coin.value - case None => 0 + case None => 0 } if (value >= sodaCost) { outputs.append(true) |
