diff --git a/core/src/main/scala-2/chisel3/Aggregate.scala b/core/src/main/scala-2/chisel3/Aggregate.scala index 1fbae658ff9..21f6912c69f 100644 --- a/core/src/main/scala-2/chisel3/Aggregate.scala +++ b/core/src/main/scala-2/chisel3/Aggregate.scala @@ -117,9 +117,8 @@ object VecInit extends VecInitImpl with SourceInfoDoc { /** @group SourceInfoTransformMacro */ def do_tabulate[T <: Data]( - n: Int - )(gen: (Int) => T - )( + n: Int + )(gen: (Int) => T)( implicit sourceInfo: SourceInfo ): Vec[T] = _tabulateImpl(n)(gen) @@ -136,10 +135,9 @@ object VecInit extends VecInitImpl with SourceInfoDoc { /** @group SourceInfoTransformMacro */ def do_tabulate[T <: Data]( - n: Int, - m: Int - )(gen: (Int, Int) => T - )( + n: Int, + m: Int + )(gen: (Int, Int) => T)( implicit sourceInfo: SourceInfo ): Vec[Vec[T]] = _tabulateImpl(n, m)(gen) @@ -157,11 +155,10 @@ object VecInit extends VecInitImpl with SourceInfoDoc { /** @group SourceInfoTransformMacro */ def do_tabulate[T <: Data]( - n: Int, - m: Int, - p: Int - )(gen: (Int, Int, Int) => T - )( + n: Int, + m: Int, + p: Int + )(gen: (Int, Int, Int) => T)( implicit sourceInfo: SourceInfo ): Vec[Vec[Vec[T]]] = _tabulateImpl(n, m, p)(gen) @@ -189,10 +186,9 @@ object VecInit extends VecInitImpl with SourceInfoDoc { /** @group SourceInfoTransformMacro */ def do_fill[T <: Data]( - n: Int, - m: Int - )(gen: => T - )( + n: Int, + m: Int + )(gen: => T)( implicit sourceInfo: SourceInfo ): Vec[Vec[T]] = _fillImpl(n, m)(gen) @@ -209,11 +205,10 @@ object VecInit extends VecInitImpl with SourceInfoDoc { /** @group SourceInfoTransformMacro */ def do_fill[T <: Data]( - n: Int, - m: Int, - p: Int - )(gen: => T - )( + n: Int, + m: Int, + p: Int + )(gen: => T)( implicit sourceInfo: SourceInfo ): Vec[Vec[Vec[T]]] = _fillImpl(n, m, p)(gen) @@ -231,8 +226,7 @@ object VecInit extends VecInitImpl with SourceInfoDoc { def do_iterate[T <: Data]( start: T, len: Int - )(f: (T) => T - )( + )(f: (T) => T)( implicit sourceInfo: SourceInfo ): Vec[T] = _iterateImpl(start, len)(f) } diff --git a/core/src/main/scala-2/chisel3/ChiselEnum.scala b/core/src/main/scala-2/chisel3/ChiselEnum.scala index bd47b47e7d7..730a2726592 100644 --- a/core/src/main/scala-2/chisel3/ChiselEnum.scala +++ b/core/src/main/scala-2/chisel3/ChiselEnum.scala @@ -26,7 +26,7 @@ abstract class EnumType(factory: ChiselEnum, selfAnnotating: Boolean = true) } abstract class ChiselEnum extends ChiselEnumImpl { - protected def Value: Type = macro EnumMacros.ValImpl + protected def Value: Type = macro EnumMacros.ValImpl protected def Value(id: UInt): Type = macro EnumMacros.ValCustomImpl } diff --git a/core/src/main/scala-2/chisel3/Mem.scala b/core/src/main/scala-2/chisel3/Mem.scala index 1f01c9c9370..71c59c32739 100644 --- a/core/src/main/scala-2/chisel3/Mem.scala +++ b/core/src/main/scala-2/chisel3/Mem.scala @@ -185,7 +185,7 @@ object SyncReadMem extends ObjectSyncReadMemImpl { * @param size number of elements in the memory * @param t data type of memory element */ - def apply[T <: Data](size: BigInt, t: T): SyncReadMem[T] = macro MemTransform.apply[T] + def apply[T <: Data](size: BigInt, t: T): SyncReadMem[T] = macro MemTransform.apply[T] def apply[T <: Data](size: BigInt, t: T, ruw: ReadUnderWrite): SyncReadMem[T] = macro MemTransform.apply_ruw[T] /** Creates a sequential/synchronous-read, sequential/synchronous-write [[SyncReadMem]]. @@ -193,7 +193,7 @@ object SyncReadMem extends ObjectSyncReadMemImpl { * @param size number of elements in the memory * @param t data type of memory element */ - def apply[T <: Data](size: Int, t: T): SyncReadMem[T] = macro MemTransform.apply[T] + def apply[T <: Data](size: Int, t: T): SyncReadMem[T] = macro MemTransform.apply[T] def apply[T <: Data](size: Int, t: T, ruw: ReadUnderWrite): SyncReadMem[T] = macro MemTransform.apply_ruw[T] /** @group SourceInfoTransformMacro */ @@ -239,8 +239,8 @@ sealed class SyncReadMem[T <: Data] private[chisel3] ( t: T, n: BigInt, val readUnderWrite: SyncReadMem.ReadUnderWrite, - sourceInfo: SourceInfo) - extends MemBase[T](t, n, sourceInfo) + sourceInfo: SourceInfo +) extends MemBase[T](t, n, sourceInfo) with SyncReadMemImpl[T] { override def read(x: UInt): T = macro SourceInfoTransform.xArg diff --git a/core/src/main/scala-2/chisel3/Num.scala b/core/src/main/scala-2/chisel3/Num.scala index 6a015b1197c..6951525f674 100644 --- a/core/src/main/scala-2/chisel3/Num.scala +++ b/core/src/main/scala-2/chisel3/Num.scala @@ -29,7 +29,7 @@ import chisel3.experimental.SourceInfo trait Num[T <: Data] extends NumImpl[T] { // def << (b: T): T // def >> (b: T): T - //def unary_-: T + // def unary_-: T // REVIEW TODO: double check ops conventions against FIRRTL diff --git a/core/src/main/scala-2/chisel3/PrintfMacros.scala b/core/src/main/scala-2/chisel3/PrintfMacros.scala index 308a49494d9..3bcb23fb9ad 100644 --- a/core/src/main/scala-2/chisel3/PrintfMacros.scala +++ b/core/src/main/scala-2/chisel3/PrintfMacros.scala @@ -11,11 +11,8 @@ import scala.reflect.macros.blackbox object PrintfMacrosCompat { def _applyMacroWithInterpolatorCheck( - c: blackbox.Context - )(fmt: c.Tree, - data: c.Tree* - )(sourceInfo: c.Tree - ): c.Tree = { + c: blackbox.Context + )(fmt: c.Tree, data: c.Tree*)(sourceInfo: c.Tree): c.Tree = { import c.universe._ _checkFormatString(c)(fmt) val apply_impl_do = symbolOf[this.type].asClass.module.info.member(TermName("printfWithReset")) diff --git a/core/src/main/scala-2/chisel3/VerificationStatementMacros.scala b/core/src/main/scala-2/chisel3/VerificationStatementMacros.scala index d32764c0085..267dc380fec 100644 --- a/core/src/main/scala-2/chisel3/VerificationStatementMacros.scala +++ b/core/src/main/scala-2/chisel3/VerificationStatementMacros.scala @@ -46,12 +46,8 @@ object VerifStmtMacrosCompat { /** @group VerifPrintMacros */ def _applyMacroWithInterpolatorCheck( - c: blackbox.Context - )(cond: c.Tree, - message: c.Tree, - data: c.Tree* - )(sourceInfo: c.Tree - ): c.Tree = { + c: blackbox.Context + )(cond: c.Tree, message: c.Tree, data: c.Tree*)(sourceInfo: c.Tree): c.Tree = { import c.universe._ _checkFormatString(c)(message) val apply_impl_do = symbolOf[this.type].asClass.module.info.member(TermName("_applyWithSourceLinePrintable")) @@ -60,12 +56,8 @@ object VerifStmtMacrosCompat { /** @group VerifPrintMacros */ def _applyMacroWithStringMessage( - c: blackbox.Context - )(cond: c.Tree, - message: c.Tree, - data: c.Tree - )(sourceInfo: c.Tree - ): c.Tree = { + c: blackbox.Context + )(cond: c.Tree, message: c.Tree, data: c.Tree)(sourceInfo: c.Tree): c.Tree = { import c.universe._ val apply_impl_do = symbolOf[this.type].asClass.module.info.member(TermName("_applyWithSourceLinePrintable")) q"$apply_impl_do($cond, ${getLine(c)},_root_.scala.Some(_root_.chisel3.Printable.pack($message,..$data)))($sourceInfo)" @@ -73,11 +65,8 @@ object VerifStmtMacrosCompat { /** @group VerifPrintMacros */ def _applyMacroWithPrintableMessage( - c: blackbox.Context - )(cond: c.Tree, - message: c.Tree - )(sourceInfo: c.Tree - ): c.Tree = { + c: blackbox.Context + )(cond: c.Tree, message: c.Tree)(sourceInfo: c.Tree): c.Tree = { import c.universe._ val apply_impl_do = symbolOf[this.type].asClass.module.info.member(TermName("_applyWithSourceLinePrintable")) q"$apply_impl_do($cond, ${getLine(c)}, _root_.scala.Some($message))($sourceInfo)" @@ -85,10 +74,8 @@ object VerifStmtMacrosCompat { /** @group VerifPrintMacros */ def _applyMacroWithNoMessage( - c: blackbox.Context - )(cond: c.Tree - )(sourceInfo: c.Tree - ): c.Tree = { + c: blackbox.Context + )(cond: c.Tree)(sourceInfo: c.Tree): c.Tree = { import c.universe._ val apply_impl_do = symbolOf[this.type].asClass.module.info.member(TermName("_applyWithSourceLinePrintable")) q"$apply_impl_do($cond, ${getLine(c)}, _root_.scala.None)($sourceInfo)" @@ -127,12 +114,8 @@ object VerifStmtMacrosCompat { /** @group VerifPrintMacros */ def _applyMacroWithInterpolatorCheck( - c: blackbox.Context - )(cond: c.Tree, - message: c.Tree, - data: c.Tree* - )(sourceInfo: c.Tree - ): c.Tree = { + c: blackbox.Context + )(cond: c.Tree, message: c.Tree, data: c.Tree*)(sourceInfo: c.Tree): c.Tree = { import c.universe._ _checkFormatString(c)(message) val apply_impl_do = symbolOf[this.type].asClass.module.info.member(TermName("_applyWithSourceLinePrintable")) @@ -141,12 +124,8 @@ object VerifStmtMacrosCompat { /** @group VerifPrintMacros */ def _applyMacroWithStringMessage( - c: blackbox.Context - )(cond: c.Tree, - message: c.Tree, - data: c.Tree - )(sourceInfo: c.Tree - ): c.Tree = { + c: blackbox.Context + )(cond: c.Tree, message: c.Tree, data: c.Tree)(sourceInfo: c.Tree): c.Tree = { import c.universe._ val apply_impl_do = symbolOf[this.type].asClass.module.info.member(TermName("_applyWithSourceLinePrintable")) q"$apply_impl_do($cond, ${getLine(c)}, _root_.scala.Some(_root_.chisel3.Printable.pack($message, ..$data)))($sourceInfo)" @@ -154,11 +133,8 @@ object VerifStmtMacrosCompat { /** @group VerifPrintMacros */ def _applyMacroWithPrintableMessage( - c: blackbox.Context - )(cond: c.Tree, - message: c.Tree - )(sourceInfo: c.Tree - ): c.Tree = { + c: blackbox.Context + )(cond: c.Tree, message: c.Tree)(sourceInfo: c.Tree): c.Tree = { import c.universe._ val apply_impl_do = symbolOf[this.type].asClass.module.info.member(TermName("_applyWithSourceLinePrintable")) q"$apply_impl_do($cond, ${getLine(c)}, _root_.scala.Some($message))($sourceInfo)" @@ -166,10 +142,8 @@ object VerifStmtMacrosCompat { /** @group VerifPrintMacros */ def _applyMacroWithNoMessage( - c: blackbox.Context - )(cond: c.Tree - )(sourceInfo: c.Tree - ): c.Tree = { + c: blackbox.Context + )(cond: c.Tree)(sourceInfo: c.Tree): c.Tree = { import c.universe._ val apply_impl_do = symbolOf[this.type].asClass.module.info.member(TermName("_applyWithSourceLinePrintable")) q"$apply_impl_do($cond, ${getLine(c)}, _root_.scala.None)($sourceInfo)" @@ -199,10 +173,8 @@ object VerifStmtMacrosCompat { /** @group VerifPrintMacros */ def _applyMacroWithNoMessage( - c: blackbox.Context - )(cond: c.Tree - )(sourceInfo: c.Tree - ): c.Tree = { + c: blackbox.Context + )(cond: c.Tree)(sourceInfo: c.Tree): c.Tree = { import c.universe._ val apply_impl_do = symbolOf[this.type].asClass.module.info.member(TermName("_applyWithSourceLine")) q"$apply_impl_do($cond, ${getLine(c)}, _root_.scala.None)($sourceInfo)" @@ -210,11 +182,8 @@ object VerifStmtMacrosCompat { /** @group VerifPrintMacros */ def _applyMacroWithMessage( - c: blackbox.Context - )(cond: c.Tree, - message: c.Tree - )(sourceInfo: c.Tree - ): c.Tree = { + c: blackbox.Context + )(cond: c.Tree, message: c.Tree)(sourceInfo: c.Tree): c.Tree = { import c.universe._ val apply_impl_do = symbolOf[this.type].asClass.module.info.member(TermName("_applyWithSourceLine")) q"$apply_impl_do($cond, ${getLine(c)}, _root_.scala.Some($message))($sourceInfo)" diff --git a/core/src/main/scala-2/chisel3/experimental/SourceInfo.scala b/core/src/main/scala-2/chisel3/experimental/SourceInfo.scala index 8e0063485b5..c4e8b94893e 100644 --- a/core/src/main/scala-2/chisel3/experimental/SourceInfo.scala +++ b/core/src/main/scala-2/chisel3/experimental/SourceInfo.scala @@ -34,7 +34,7 @@ sealed trait SourceInfo { sealed trait NoSourceInfo extends SourceInfo { def makeMessage(f: String => String = x => x): String = "" - def filenameOption: Option[String] = None + def filenameOption: Option[String] = None } /** For when source info can't be generated because of a technical limitation, like for Reg because diff --git a/core/src/main/scala-2/chisel3/experimental/dataview/InvertibleDataView.scala b/core/src/main/scala-2/chisel3/experimental/dataview/InvertibleDataView.scala index da6b6fc4132..c36fe660342 100644 --- a/core/src/main/scala-2/chisel3/experimental/dataview/InvertibleDataView.scala +++ b/core/src/main/scala-2/chisel3/experimental/dataview/InvertibleDataView.scala @@ -6,8 +6,8 @@ import chisel3._ import scala.reflect.runtime.universe.WeakTypeTag private[chisel3] trait InvertibleDataView { - def swapArgs[A, B, C, D](f: (A, B) => Iterable[(C, D)]): (B, A) => Iterable[(D, C)] = { - case (b, a) => f(a, b).map(_.swap) + def swapArgs[A, B, C, D](f: (A, B) => Iterable[(C, D)]): (B, A) => Iterable[(D, C)] = { case (b, a) => + f(a, b).map(_.swap) } /** Provides `invert` for invertible [[DataView]]s diff --git a/core/src/main/scala/chisel3/AggregateImpl.scala b/core/src/main/scala/chisel3/AggregateImpl.scala index e878c8c089f..5eec5a28f40 100644 --- a/core/src/main/scala/chisel3/AggregateImpl.scala +++ b/core/src/main/scala/chisel3/AggregateImpl.scala @@ -119,13 +119,12 @@ private[chisel3] trait AggregateImpl extends Data { thiz: Aggregate => val clone: Aggregate = this.cloneTypeFull val mapping = clone.flatten.view .zip(elems) - .map { - case (thisElt, litElt) => - val litArg = litElt.topBindingOpt match { - case Some(ElementLitBinding(value)) => value - case _ => throwException(s"Internal Error! For field $thisElt, given non-literal $litElt!") - } - thisElt -> litArg + .map { case (thisElt, litElt) => + val litArg = litElt.topBindingOpt match { + case Some(ElementLitBinding(value)) => value + case _ => throwException(s"Internal Error! For field $thisElt, given non-literal $litElt!") + } + thisElt -> litArg } val binding = clone match { case r: Record => BundleLitBinding(mapping.to(Map)) @@ -139,14 +138,13 @@ private[chisel3] trait AggregateImpl extends Data { thiz: Aggregate => val _asUInt = _resizeToWidth(that, this.widthOption, true)(identity) // If that is a literal and all constituent Elements can be represented as literals, return a literal val ((_, allLit), rvalues) = { - this.flatten.toList.mapAccumulate[(Int, Boolean), Element]((0, _asUInt.isLit)) { - case ((lo, literal), elt) => - val hi = lo + elt.getWidth - // Chisel only supports zero width extraction if hi = -1 and lo = 0, so do it manually - val _extracted = if (elt.getWidth == 0) 0.U(0.W) else _asUInt(hi - 1, lo) - // _fromUInt returns Data but we know that it is an Element - val rhs = elt._fromUInt(_extracted).asInstanceOf[Element] - ((hi, literal && rhs.isLit), rhs) + this.flatten.toList.mapAccumulate[(Int, Boolean), Element]((0, _asUInt.isLit)) { case ((lo, literal), elt) => + val hi = lo + elt.getWidth + // Chisel only supports zero width extraction if hi = -1 and lo = 0, so do it manually + val _extracted = if (elt.getWidth == 0) 0.U(0.W) else _asUInt(hi - 1, lo) + // _fromUInt returns Data but we know that it is an Element + val rhs = elt._fromUInt(_extracted).asInstanceOf[Element] + ((hi, literal && rhs.isLit), rhs) } } if (allLit) { @@ -220,9 +218,8 @@ private[chisel3] abstract class VecImpl[T <: Data] private[chisel3] (gen: => T, override def toString: String = { topBindingOpt match { case Some(VecLitBinding(vecLitBinding)) => - val contents = vecLitBinding.zipWithIndex.map { - case ((data, lit), index) => - s"$index=$lit" + val contents = vecLitBinding.zipWithIndex.map { case ((data, lit), index) => + s"$index=$lit" }.mkString(", ") s"${sample_element.cloneType}[$length]($contents)" case _ => stringAccessor(s"${sample_element.cloneType}[$length]") @@ -462,8 +459,8 @@ private[chisel3] abstract class VecImpl[T <: Data] private[chisel3] (gen: => T, val r = s .drop(p) .grouped(2) - .map { - case Seq(a, b) => op(a, b) + .map { case Seq(a, b) => + op(a, b) } .toVector recReduce(l ++ r, op, lop) @@ -494,13 +491,12 @@ private[chisel3] abstract class VecImpl[T <: Data] private[chisel3] (gen: => T, ): this.type = { def checkLiteralConstruction(): Unit = { - val dupKeys = elementInitializers.map { x => x._1 }.groupBy(x => x).flatMap { - case (k, v) => - if (v.length > 1) { - Some(k, v.length) - } else { - None - } + val dupKeys = elementInitializers.map { x => x._1 }.groupBy(x => x).flatMap { case (k, v) => + if (v.length > 1) { + Some(k, v.length) + } else { + None + } } if (dupKeys.nonEmpty) { throw new VecLiteralException( @@ -548,93 +544,90 @@ private[chisel3] abstract class VecImpl[T <: Data] private[chisel3] (gen: => T, // Create the Vec literal binding from litArgs of arguments val vecLitLinkedMap = new mutable.LinkedHashMap[Data, LitArg]() - elementInitializers.sortBy { case (a, _) => a }.foreach { - case (fieldIndex, value) => - val field = clone.apply(fieldIndex) - val fieldName = cloneFields.getOrElse( - field, - throw new VecLiteralException( - s"field $field (with value $value) is not a field," + - s" ensure the field is specified as a function returning a field on an object of class ${this.getClass}," + - s" eg '_.a' to select hypothetical bundle field 'a'" - ) + elementInitializers.sortBy { case (a, _) => a }.foreach { case (fieldIndex, value) => + val field = clone.apply(fieldIndex) + val fieldName = cloneFields.getOrElse( + field, + throw new VecLiteralException( + s"field $field (with value $value) is not a field," + + s" ensure the field is specified as a function returning a field on an object of class ${this.getClass}," + + s" eg '_.a' to select hypothetical bundle field 'a'" ) + ) - val valueBinding = value.topBindingOpt match { - case Some(litBinding: LitBinding) => litBinding - case _ => throw new VecLiteralException(s"field $fieldIndex specified with non-literal value $value") - } + val valueBinding = value.topBindingOpt match { + case Some(litBinding: LitBinding) => litBinding + case _ => throw new VecLiteralException(s"field $fieldIndex specified with non-literal value $value") + } - field match { // Get the litArg(s) for this field - case bitField: Bits => - if (!field.typeEquivalent(bitField)) { - throw new VecLiteralException( - s"VecLit: Literal specified at index $fieldIndex ($value) does not match Vec type $sample_element" - ) - } - if (bitField.getWidth > field.getWidth) { - throw new VecLiteralException( - s"VecLit: Literal specified at index $fieldIndex ($value) is too wide for Vec type $sample_element" + field match { // Get the litArg(s) for this field + case bitField: Bits => + if (!field.typeEquivalent(bitField)) { + throw new VecLiteralException( + s"VecLit: Literal specified at index $fieldIndex ($value) does not match Vec type $sample_element" + ) + } + if (bitField.getWidth > field.getWidth) { + throw new VecLiteralException( + s"VecLit: Literal specified at index $fieldIndex ($value) is too wide for Vec type $sample_element" + ) + } + val litArg = valueBinding match { + case ElementLitBinding(litArg) => litArg + case BundleLitBinding(litMap) => + litMap.getOrElse( + value, + throw new BundleLiteralException(s"Field $fieldName specified with unspecified value") ) - } - val litArg = valueBinding match { - case ElementLitBinding(litArg) => litArg - case BundleLitBinding(litMap) => - litMap.getOrElse( - value, - throw new BundleLiteralException(s"Field $fieldName specified with unspecified value") - ) - case VecLitBinding(litMap) => - litMap.getOrElse( - value, - throw new VecLiteralException(s"Field $fieldIndex specified with unspecified value") - ) - } - val adjustedLitArg = litArg.cloneWithWidth(sample_element.width) - vecLitLinkedMap(bitField) = adjustedLitArg - - case recordField: Record => - if (!(recordField.typeEquivalent(value))) { - throw new VecLiteralException( - s"field $fieldIndex $recordField specified with non-type-equivalent value $value" + case VecLitBinding(litMap) => + litMap.getOrElse( + value, + throw new VecLiteralException(s"Field $fieldIndex specified with unspecified value") ) - } - // Copy the source BundleLitBinding with fields (keys) remapped to the clone - val remap = getMatchedFields(value, recordField).toMap - valueBinding.asInstanceOf[BundleLitBinding].litMap.map { - case (valueField, valueValue) => - vecLitLinkedMap(remap(valueField)) = valueValue - } + } + val adjustedLitArg = litArg.cloneWithWidth(sample_element.width) + vecLitLinkedMap(bitField) = adjustedLitArg - case vecField: Vec[_] => - if (!(vecField.typeEquivalent(value))) { - throw new VecLiteralException( - s"field $fieldIndex $vecField specified with non-type-equivalent value $value" - ) - } - // Copy the source VecLitBinding with vecFields (keys) remapped to the clone - val remap = getMatchedFields(value, vecField).toMap - value.topBinding.asInstanceOf[VecLitBinding].litMap.map { - case (valueField, valueValue) => - vecLitLinkedMap(remap(valueField)) = valueValue - } + case recordField: Record => + if (!(recordField.typeEquivalent(value))) { + throw new VecLiteralException( + s"field $fieldIndex $recordField specified with non-type-equivalent value $value" + ) + } + // Copy the source BundleLitBinding with fields (keys) remapped to the clone + val remap = getMatchedFields(value, recordField).toMap + valueBinding.asInstanceOf[BundleLitBinding].litMap.map { case (valueField, valueValue) => + vecLitLinkedMap(remap(valueField)) = valueValue + } - case enumField: EnumType => { - if (!(enumField.typeEquivalent(value))) { - throw new VecLiteralException( - s"field $fieldIndex $enumField specified with non-type-equivalent enum value $value" - ) - } - val litArg = valueBinding match { - case ElementLitBinding(litArg) => litArg - case _ => - throw new VecLiteralException(s"field $fieldIndex $enumField could not bematched with $valueBinding") - } - vecLitLinkedMap(field) = litArg + case vecField: Vec[_] => + if (!(vecField.typeEquivalent(value))) { + throw new VecLiteralException( + s"field $fieldIndex $vecField specified with non-type-equivalent value $value" + ) + } + // Copy the source VecLitBinding with vecFields (keys) remapped to the clone + val remap = getMatchedFields(value, vecField).toMap + value.topBinding.asInstanceOf[VecLitBinding].litMap.map { case (valueField, valueValue) => + vecLitLinkedMap(remap(valueField)) = valueValue } - case _ => throw new VecLiteralException(s"unsupported field $fieldIndex of type $field") + case enumField: EnumType => { + if (!(enumField.typeEquivalent(value))) { + throw new VecLiteralException( + s"field $fieldIndex $enumField specified with non-type-equivalent enum value $value" + ) + } + val litArg = valueBinding match { + case ElementLitBinding(litArg) => litArg + case _ => + throw new VecLiteralException(s"field $fieldIndex $enumField could not bematched with $valueBinding") + } + vecLitLinkedMap(field) = litArg } + + case _ => throw new VecLiteralException(s"unsupported field $fieldIndex of type $field") + } } clone.bind(VecLitBinding(VectorMap(vecLitLinkedMap.toSeq: _*))) @@ -668,18 +661,16 @@ private[chisel3] trait VecInitImpl { _applyImpl(elt0 +: elts.toSeq) protected def _tabulateImpl[T <: Data]( - n: Int - )(gen: (Int) => T - )( + n: Int + )(gen: (Int) => T)( implicit sourceInfo: SourceInfo ): Vec[T] = _applyImpl((0 until n).map(i => gen(i))) protected def _tabulateImpl[T <: Data]( - n: Int, - m: Int - )(gen: (Int, Int) => T - )( + n: Int, + m: Int + )(gen: (Int, Int) => T)( implicit sourceInfo: SourceInfo ): Vec[Vec[T]] = { // TODO make this lazy (requires LazyList and cross compilation, beyond the scope of this PR) @@ -701,11 +692,10 @@ private[chisel3] trait VecInitImpl { } protected def _tabulateImpl[T <: Data]( - n: Int, - m: Int, - p: Int - )(gen: (Int, Int, Int) => T - )( + n: Int, + m: Int, + p: Int + )(gen: (Int, Int, Int) => T)( implicit sourceInfo: SourceInfo ): Vec[Vec[Vec[T]]] = { // TODO make this lazy (requires LazyList and cross compilation, beyond the scope of this PR) @@ -734,21 +724,19 @@ private[chisel3] trait VecInitImpl { else { _applyImpl(Seq.fill(n)(gen)) } protected def _fillImpl[T <: Data]( - n: Int, - m: Int - )(gen: => T - )( + n: Int, + m: Int + )(gen: => T)( implicit sourceInfo: SourceInfo ): Vec[Vec[T]] = { _tabulateImpl(n, m)((_, _) => gen) } protected def _fillImpl[T <: Data]( - n: Int, - m: Int, - p: Int - )(gen: => T - )( + n: Int, + m: Int, + p: Int + )(gen: => T)( implicit sourceInfo: SourceInfo ): Vec[Vec[Vec[T]]] = { _tabulateImpl(n, m, p)((_, _, _) => gen) @@ -757,8 +745,7 @@ private[chisel3] trait VecInitImpl { protected def _iterateImpl[T <: Data]( start: T, len: Int - )(f: (T) => T - )( + )(f: (T) => T)( implicit sourceInfo: SourceInfo ): Vec[T] = _applyImpl(Seq.iterate(start, len)(f)) @@ -767,7 +754,7 @@ private[chisel3] trait VecInitImpl { private[chisel3] trait VecLikeImpl[T <: Data] extends IndexedSeq[T] with HasId { // IndexedSeq has its own hashCode/equals that we must not use - override def hashCode: Int = super[HasId].hashCode + override def hashCode: Int = super[HasId].hashCode override def equals(that: Any): Boolean = super[HasId].equals(that) protected def _forallImpl(p: T => Bool)(implicit sourceInfo: SourceInfo): Bool = @@ -960,85 +947,82 @@ private[chisel3] trait RecordImpl extends AggregateImpl { thiz: Record => val cloneFields = getRecursiveFields(clone, "_").toMap // Create the Bundle literal binding from litargs of arguments - val bundleLitMapping = elems.map { fn => fn(clone) }.flatMap { - case (field, value) => - val fieldName = cloneFields.getOrElse( - field, - throw new BundleLiteralException( - s"field $field (with value $value) is not a field," + - s" ensure the field is specified as a function returning a field on an object of class ${this.getClass}," + - s" eg '_.a' to select hypothetical bundle field 'a'" - ) + val bundleLitMapping = elems.map { fn => fn(clone) }.flatMap { case (field, value) => + val fieldName = cloneFields.getOrElse( + field, + throw new BundleLiteralException( + s"field $field (with value $value) is not a field," + + s" ensure the field is specified as a function returning a field on an object of class ${this.getClass}," + + s" eg '_.a' to select hypothetical bundle field 'a'" ) - val valueBinding = value.topBindingOpt match { - case Some(litBinding: LitBinding) => litBinding - case _ => throw new BundleLiteralException(s"field $fieldName specified with non-literal value $value") - } + ) + val valueBinding = value.topBindingOpt match { + case Some(litBinding: LitBinding) => litBinding + case _ => throw new BundleLiteralException(s"field $fieldName specified with non-literal value $value") + } - field match { // Get the litArg(s) for this field - case field: Bits => - if (field.getClass != value.getClass) { // TODO typeEquivalent is too strict because it checks width - throw new BundleLiteralException( - s"Field $fieldName $field specified with non-type-equivalent value $value" + field match { // Get the litArg(s) for this field + case field: Bits => + if (field.getClass != value.getClass) { // TODO typeEquivalent is too strict because it checks width + throw new BundleLiteralException( + s"Field $fieldName $field specified with non-type-equivalent value $value" + ) + } + val litArg = valueBinding match { + case ElementLitBinding(litArg) => litArg + case BundleLitBinding(litMap) => + litMap.getOrElse( + value, + throw new BundleLiteralException(s"Field $fieldName specified with unspecified value") + ) + case VecLitBinding(litMap) => + litMap.getOrElse( + value, + throw new VecLiteralException(s"Vec literal $fieldName specified with out literal values") ) - } - val litArg = valueBinding match { - case ElementLitBinding(litArg) => litArg - case BundleLitBinding(litMap) => - litMap.getOrElse( - value, - throw new BundleLiteralException(s"Field $fieldName specified with unspecified value") - ) - case VecLitBinding(litMap) => - litMap.getOrElse( - value, - throw new VecLiteralException(s"Vec literal $fieldName specified with out literal values") - ) - } - Seq(field -> litArg) + } + Seq(field -> litArg) - case field: Record => - if (!(field.typeEquivalent(value))) { - throw new BundleLiteralException( - s"field $fieldName $field specified with non-type-equivalent value $value" - ) - } - // Copy the source BundleLitBinding with fields (keys) remapped to the clone - val remap = getMatchedFields(value, field).toMap - value.topBinding.asInstanceOf[BundleLitBinding].litMap.map { - case (valueField, valueValue) => - remap(valueField) -> valueValue - } + case field: Record => + if (!(field.typeEquivalent(value))) { + throw new BundleLiteralException( + s"field $fieldName $field specified with non-type-equivalent value $value" + ) + } + // Copy the source BundleLitBinding with fields (keys) remapped to the clone + val remap = getMatchedFields(value, field).toMap + value.topBinding.asInstanceOf[BundleLitBinding].litMap.map { case (valueField, valueValue) => + remap(valueField) -> valueValue + } - case vecField: Vec[_] => - if (!(vecField.typeEquivalent(value))) { - throw new BundleLiteralException( - s"field $fieldName $vecField specified with non-type-equivalent value $value" - ) - } - // Copy the source BundleLitBinding with fields (keys) remapped to the clone - val remap = getMatchedFields(value, vecField).toMap - value.topBinding.asInstanceOf[VecLitBinding].litMap.map { - case (valueField, valueValue) => - remap(valueField) -> valueValue - } + case vecField: Vec[_] => + if (!(vecField.typeEquivalent(value))) { + throw new BundleLiteralException( + s"field $fieldName $vecField specified with non-type-equivalent value $value" + ) + } + // Copy the source BundleLitBinding with fields (keys) remapped to the clone + val remap = getMatchedFields(value, vecField).toMap + value.topBinding.asInstanceOf[VecLitBinding].litMap.map { case (valueField, valueValue) => + remap(valueField) -> valueValue + } - case field: EnumType => { - if (!(field.typeEquivalent(value))) { - throw new BundleLiteralException( - s"field $fieldName $field specified with non-type-equivalent enum value $value" - ) - } - val litArg = valueBinding match { - case ElementLitBinding(litArg) => litArg - case _ => - throw new BundleLiteralException(s"field $fieldName $field could not be matched with $valueBinding") - } - Seq(field -> litArg) + case field: EnumType => { + if (!(field.typeEquivalent(value))) { + throw new BundleLiteralException( + s"field $fieldName $field specified with non-type-equivalent enum value $value" + ) + } + val litArg = valueBinding match { + case ElementLitBinding(litArg) => litArg + case _ => + throw new BundleLiteralException(s"field $fieldName $field could not be matched with $valueBinding") } - case _ => throw new BundleLiteralException(s"unsupported field $fieldName of type $field") + Seq(field -> litArg) } + case _ => throw new BundleLiteralException(s"unsupported field $fieldName of type $field") + } } // don't convert to a Map yet to preserve duplicate keys @@ -1048,28 +1032,27 @@ private[chisel3] trait RecordImpl extends AggregateImpl { thiz: Record => throw new BundleLiteralException(s"duplicate fields $duplicateNames in Bundle literal constructor") } // Check widths and sign extend as appropriate. - val bundleLitMap = bundleLitMapping.view.map { - case (field, value) => - field.width match { - // If width is unknown, then it is set by the literal value. - case UnknownWidth => field -> value - case width @ KnownWidth(widthValue) => - val valuex = if (widthValue < value.width.get) { - // For legacy reasons, 0.U is 1-bit, don't warn when it comes up as a literal value for 0-bit Bundle lit field. - val dontWarnOnZeroDotU = widthValue == 0 && value.num == 0 && value.width.get == 1 - if (!dontWarnOnZeroDotU) { - val msg = s"Literal value $value is too wide for field ${cloneFields(field)} with width $widthValue" - Builder.warning(Warning(WarningID.BundleLiteralValueTooWide, msg)) - } - // Mask the value to the width of the field. - val mask = (BigInt(1) << widthValue) - 1 - value.cloneWithValue(value.num & mask).cloneWithWidth(width) - } else if (widthValue > value.width.get) value.cloneWithWidth(width) - // Otherwise, ensure width is same as that of the field. - else value - - field -> valuex - } + val bundleLitMap = bundleLitMapping.view.map { case (field, value) => + field.width match { + // If width is unknown, then it is set by the literal value. + case UnknownWidth => field -> value + case width @ KnownWidth(widthValue) => + val valuex = if (widthValue < value.width.get) { + // For legacy reasons, 0.U is 1-bit, don't warn when it comes up as a literal value for 0-bit Bundle lit field. + val dontWarnOnZeroDotU = widthValue == 0 && value.num == 0 && value.width.get == 1 + if (!dontWarnOnZeroDotU) { + val msg = s"Literal value $value is too wide for field ${cloneFields(field)} with width $widthValue" + Builder.warning(Warning(WarningID.BundleLiteralValueTooWide, msg)) + } + // Mask the value to the width of the field. + val mask = (BigInt(1) << widthValue) - 1 + value.cloneWithValue(value.num & mask).cloneWithWidth(width) + } else if (widthValue > value.width.get) value.cloneWithWidth(width) + // Otherwise, ensure width is same as that of the field. + else value + + field -> valuex + } }.toMap clone.bind(BundleLitBinding(bundleLitMap)) clone @@ -1093,9 +1076,8 @@ private[chisel3] trait RecordImpl extends AggregateImpl { thiz: Record => override def toString: String = { topBindingOpt match { case Some(BundleLitBinding(_)) => - val contents = _elements.toList.reverse.map { - case (name, data) => - s"$name=$data" + val contents = _elements.toList.reverse.map { case (name, data) => + s"$name=$data" }.mkString(", ") s"$className($contents)" case _ => stringAccessor(s"$className") @@ -1127,19 +1109,18 @@ private[chisel3] trait RecordImpl extends AggregateImpl { thiz: Record => // This is true if elements is not a VectorMap or if any names need sanitization var needNewMap = !originalElements.isInstanceOf[VectorMap[_, _]] val newNames = - elements.view.map { - case (name, field) => - if (field.binding.isDefined) { - throw RebindingException( - s"Cannot create Record ${this.className}; element ${field} of Record must be a Chisel type, not hardware." - ) - } - // namespace.name also sanitizes for firrtl, leave name alone for OpaqueTypes - val sanitizedName = namespace.map(_.name(name, leadingDigitOk = true)).getOrElse(name) - if (sanitizedName != name) { - needNewMap = true - } - sanitizedName + elements.view.map { case (name, field) => + if (field.binding.isDefined) { + throw RebindingException( + s"Cannot create Record ${this.className}; element ${field} of Record must be a Chisel type, not hardware." + ) + } + // namespace.name also sanitizes for firrtl, leave name alone for OpaqueTypes + val sanitizedName = namespace.map(_.name(name, leadingDigitOk = true)).getOrElse(name) + if (sanitizedName != name) { + needNewMap = true + } + sanitizedName }.toArray // It's very important we eagerly evaluate this sequence. if (needNewMap) { newNames.view @@ -1170,9 +1151,8 @@ private[chisel3] trait RecordImpl extends AggregateImpl { thiz: Record => val xs = if (elts.isEmpty) List.empty[Printable] // special case because of dropRight below else - elts.flatMap { - case (name, data) => - List(PString(s"$name -> "), data.toPrintable, PString(", ")) + elts.flatMap { case (name, data) => + List(PString(s"$name -> "), data.toPrintable, PString(", ")) }.dropRight(1) // Remove trailing ", " PString(s"$className(") + Printables(xs) + PString(")") } diff --git a/core/src/main/scala/chisel3/BitsImpl.scala b/core/src/main/scala/chisel3/BitsImpl.scala index a6f44a938cd..cda6eb13d29 100644 --- a/core/src/main/scala/chisel3/BitsImpl.scala +++ b/core/src/main/scala/chisel3/BitsImpl.scala @@ -348,8 +348,8 @@ private[chisel3] trait UIntImpl extends BitsImpl with Num[UInt] { self: UInt => )( implicit sourceInfo: SourceInfo ): UInt = - n.asBools.zipWithIndex.foldLeft(this) { - case (in, (en, sh)) => Mux(en, staticShift(in, 1 << sh), in) + n.asBools.zipWithIndex.foldLeft(this) { case (in, (en, sh)) => + Mux(en, staticShift(in, 1 << sh), in) } protected def _rotateRightImpl(n: UInt)(implicit sourceInfo: SourceInfo): UInt = diff --git a/core/src/main/scala/chisel3/BlackBox.scala b/core/src/main/scala/chisel3/BlackBox.scala index 4fa9eea0b03..4213dd2658b 100644 --- a/core/src/main/scala/chisel3/BlackBox.scala +++ b/core/src/main/scala/chisel3/BlackBox.scala @@ -78,8 +78,8 @@ package experimental { // Ports are named in the same way as regular Modules namePorts() - val firrtlPorts = getModulePorts.map { - case port => Port(port, port.specifiedDirection, UnlocatableSourceInfo) + val firrtlPorts = getModulePorts.map { case port => + Port(port, port.specifiedDirection, UnlocatableSourceInfo) } val component = DefBlackBox(this, name, firrtlPorts, SpecifiedDirection.Unspecified, params) _component = Some(component) @@ -127,9 +127,7 @@ package experimental { * }}} * @note The parameters API is experimental and may change */ -abstract class BlackBox( - val params: Map[String, Param] = Map.empty[String, Param]) - extends BaseBlackBox { +abstract class BlackBox(val params: Map[String, Param] = Map.empty[String, Param]) extends BaseBlackBox { // Find a Record port named "io" for purposes of stripping the prefix private[chisel3] lazy val _io: Option[Record] = diff --git a/core/src/main/scala/chisel3/ChiselEnumImpl.scala b/core/src/main/scala/chisel3/ChiselEnumImpl.scala index f0cfd7534dc..a3782dbf945 100644 --- a/core/src/main/scala/chisel3/ChiselEnumImpl.scala +++ b/core/src/main/scala/chisel3/ChiselEnumImpl.scala @@ -162,9 +162,9 @@ private[chisel3] abstract class EnumTypeImpl(private[chisel3] val factory: Chise } case b: Record => b.elements.collect { - case (name, e: EnumType) if this.typeEquivalent(e) => Seq(Seq(name)) + case (name, e: EnumType) if this.typeEquivalent(e) => Seq(Seq(name)) case (name, v: Vec[_]) if this.typeEquivalent(v.sample_element) => Seq(Seq(name)) - case (name, b2: Bundle) => enumFields(b2).map(name +: _) + case (name, b2: Bundle) => enumFields(b2).map(name +: _) }.flatten.toSeq } diff --git a/core/src/main/scala/chisel3/ClockImpl.scala b/core/src/main/scala/chisel3/ClockImpl.scala index cf4e26b8d0e..afd8341b965 100644 --- a/core/src/main/scala/chisel3/ClockImpl.scala +++ b/core/src/main/scala/chisel3/ClockImpl.scala @@ -18,7 +18,7 @@ private[chisel3] trait ClockImpl extends Element { override def connect(that: Data)(implicit sourceInfo: SourceInfo): Unit = that match { case _: Clock | DontCare => super.connect(that)(sourceInfo) - case _ => super.badConnect(that)(sourceInfo) + case _ => super.badConnect(that)(sourceInfo) } override def litOption: Option[BigInt] = None diff --git a/core/src/main/scala/chisel3/DataImpl.scala b/core/src/main/scala/chisel3/DataImpl.scala index e262dbd7bdc..84cf7c13407 100644 --- a/core/src/main/scala/chisel3/DataImpl.scala +++ b/core/src/main/scala/chisel3/DataImpl.scala @@ -67,8 +67,7 @@ object SpecifiedDirection { private[chisel3] def specifiedDirection[T <: Data]( source: => T - )(dir: T => SpecifiedDirection - ): T = { + )(dir: T => SpecifiedDirection): T = { val prevId = Builder.idGen.value val data = source // evaluate source once (passed by name) requireIsChiselType(data) @@ -118,7 +117,7 @@ object ActualDirection { case class Bidirectional private[chisel3] (dir: BidirectionalDirection, _value: Byte) extends ActualDirection(_value) { @deprecated("Use companion object factory apply method", "Chisel 6.5") - def this(dir: BidirectionalDirection) = this(dir, dir.value) + def this(dir: BidirectionalDirection) = this(dir, dir.value) private[chisel3] def copy(dir: BidirectionalDirection = this.dir, _value: Byte = this._value) = new Bidirectional(dir, _value) } @@ -250,7 +249,7 @@ private[chisel3] object getRecursiveFields { def noPath(data: Data): Seq[Data] = lazilyNoPath(data).toVector def lazilyNoPath(data: Data): Iterable[Data] = DataMirror.collectMembers(data) { case x => x } - def apply(data: Data, path: String): Seq[(Data, String)] = lazily(data, path).toVector + def apply(data: Data, path: String): Seq[(Data, String)] = lazily(data, path).toVector def lazily(data: Data, path: String): Iterable[(Data, String)] = DataMirror.collectMembersAndPaths(data, path) { case x => x } @@ -270,13 +269,12 @@ private[chisel3] object getMatchedFields { case (x: Record, y: Record) => (x._elements .zip(y._elements)) - .map { - case ((xName, xElt), (yName, yElt)) => - require( - xName == yName, - s"$xName != $yName, ${x._elements}, ${y._elements}, $x, $y" - ) // assume fields returned in same, deterministic order - getMatchedFields(xElt, yElt) + .map { case ((xName, xElt), (yName, yElt)) => + require( + xName == yName, + s"$xName != $yName, ${x._elements}, ${y._elements}, $x, $y" + ) // assume fields returned in same, deterministic order + getMatchedFields(xElt, yElt) } .fold(Seq(x -> y)) { _ ++ _ @@ -284,9 +282,8 @@ private[chisel3] object getMatchedFields { case (x: Vec[_], y: Vec[_]) => (x.elementsIterator .zip(y.elementsIterator)) - .map { - case (xElt, yElt) => - getMatchedFields(xElt, yElt) + .map { case (xElt, yElt) => + getMatchedFields(xElt, yElt) } .fold(Seq(x -> y)) { _ ++ _ @@ -413,7 +410,7 @@ private[chisel3] trait DataImpl extends HasId with NamedComponent { self: Data = */ private[chisel3] def _assignCompatibilityExplicitDirection: Unit = { (this, specifiedDirection) match { - case (_: Analog, _) => // nothing to do + case (_: Analog, _) => // nothing to do case (_, SpecifiedDirection.Unspecified) => specifiedDirection = SpecifiedDirection.Output case (_, SpecifiedDirection.Flip) => specifiedDirection = SpecifiedDirection.Input case (_, SpecifiedDirection.Input | SpecifiedDirection.Output) => // nothing to do @@ -447,7 +444,7 @@ private[chisel3] trait DataImpl extends HasId with NamedComponent { self: Data = private[chisel3] def topBindingOpt: Option[TopBinding] = _binding.flatMap { case ChildBinding(parent) => parent.topBindingOpt case bindingVal: TopBinding => Some(bindingVal) - case SampleElementBinding(parent) => parent.topBindingOpt + case SampleElementBinding(parent) => parent.topBindingOpt case (_: MemTypeBinding[_] | _: FirrtlMemTypeBinding) => None } @@ -570,7 +567,7 @@ private[chisel3] trait DataImpl extends HasId with NamedComponent { self: Data = case (_: ReadOnlyBinding, _: ReadOnlyBinding) => throwException(s"Both $this and $that are read-only") // DontCare cannot be a sink (LHS) case (_: DontCareBinding, _) => throw BiConnect.DontCareCantBeSink - case _ => // fine + case _ => // fine } try { BiConnect.connect(sourceInfo, this, that, Builder.referenceUserModule) @@ -640,13 +637,12 @@ private[chisel3] trait DataImpl extends HasId with NamedComponent { self: Data = case (r1: Record, r2: Record) if !strictTypes || r1.getClass == r2.getClass => val (larger, smaller, msg) = if (r1._elements.size >= r2._elements.size) (r1, r2, "Left") else (r2, r1, "Right") - larger._elements.flatMap { - case (name, data) => - val recurse = smaller._elements.get(name) match { - case None => Some(s": Dangling field on $msg") - case Some(data2) => rec(data, data2) - } - recurse.map("." + name + _) + larger._elements.flatMap { case (name, data) => + val recurse = smaller._elements.get(name) match { + case None => Some(s": Dangling field on $msg") + case Some(data2) => rec(data, data2) + } + recurse.map("." + name + _) }.headOption case (v1: Vec[_], v2: Vec[_]) => if (v1.size != v2.size) { @@ -691,9 +687,9 @@ private[chisel3] trait DataImpl extends HasId with NamedComponent { self: Data = true case Some(ViewBinding(target, _)) => target.isVisibleFromModule case Some(AggregateViewBinding(mapping, _)) => mapping.values.forall(_.isVisibleFromModule) - case Some(pb: SecretPortBinding) => true // Ignore secret to not require visibility - case Some(_: UnconstrainedBinding) => true - case _ => false + case Some(pb: SecretPortBinding) => true // Ignore secret to not require visibility + case Some(_: UnconstrainedBinding) => true + case _ => false } } private[chisel3] def visibleFromBlock: Option[SourceInfo] = MonoConnect.checkBlockVisibility(this) @@ -722,7 +718,7 @@ private[chisel3] trait DataImpl extends HasId with NamedComponent { self: Data = val writability = wr1.combine(wr2) writability.reportIfReadOnly(target2.lref)(Wire(chiselTypeOf(target2)).lref) case Some(binding: TopBinding) => Node(this) - case opt => throwException(s"internal error: unknown binding $opt in generating LHS ref") + case opt => throwException(s"internal error: unknown binding $opt in generating LHS ref") } } @@ -778,7 +774,7 @@ private[chisel3] trait DataImpl extends HasId with NamedComponent { self: Data = private[chisel3] def setAllParents(parent: Option[BaseModule]): Unit = DataMirror.collectAllMembers(this).foreach { x => x._parent = parent } - private[chisel3] def width: Width + private[chisel3] def width: Width private[chisel3] def firrtlConnect(that: Data)(implicit sourceInfo: SourceInfo): Unit /** Internal API; Chisel users should look at chisel3.chiselTypeOf(...). @@ -916,9 +912,8 @@ private[chisel3] trait ObjectDataImpl { private[chisel3] def makeConnectableDefault[T <: Data](d: T): Connectable[T] = { val base = Connectable.apply(d) DataMirror - .collectMembers(d) { - case hasCustom: HasCustomConnectable => - hasCustom + .collectMembers(d) { case hasCustom: HasCustomConnectable => + hasCustom } .foldLeft(base)((connectable, hasCustom) => hasCustom.customConnectable(connectable)) } @@ -942,9 +937,9 @@ private[chisel3] trait ObjectDataImpl { implicit class RecordOptGet(rOpt: Option[Record]) { // Like .get, but its already defined on Option def grab(k: String): Option[Data] = rOpt.flatMap { _._elements.get(k) } - def keys: Iterable[String] = rOpt.map { r => r._elements.map(_._1) }.getOrElse(Seq.empty[String]) + def keys: Iterable[String] = rOpt.map { r => r._elements.map(_._1) }.getOrElse(Seq.empty[String]) } - //TODO(azidar): Rewrite this to be more clear, probably not the cleanest way to express this + // TODO(azidar): Rewrite this to be more clear, probably not the cleanest way to express this private def isDifferent(l: Option[Data], r: Option[Data]): Boolean = l.nonEmpty && r.nonEmpty && !isRecord(l, r) && !isVec(l, r) && !isElement(l, r) && !isProbe(l, r) private def isRecord(l: Option[Data], r: Option[Data]): Boolean = @@ -1004,12 +999,12 @@ private[chisel3] trait ObjectDataImpl { */ def ===(rhs: T): Bool = { (lhs, rhs) match { - case (thiz: UInt, that: UInt) => thiz === that - case (thiz: SInt, that: SInt) => thiz === that + case (thiz: UInt, that: UInt) => thiz === that + case (thiz: SInt, that: SInt) => thiz === that case (thiz: AsyncReset, that: AsyncReset) => thiz.asBool === that.asBool - case (thiz: Reset, that: Reset) => thiz.asBool === that.asBool - case (thiz: EnumType, that: EnumType) => thiz === that - case (thiz: Clock, that: Clock) => thiz.asUInt === that.asUInt + case (thiz: Reset, that: Reset) => thiz.asBool === that.asBool + case (thiz: EnumType, that: EnumType) => thiz === that + case (thiz: Clock, that: Clock) => thiz.asUInt === that.asUInt case (thiz: Vec[_], that: Vec[_]) => if (thiz.length != that.length) { throwException(s"Cannot compare Vecs $thiz and $that: Vec sizes differ") @@ -1024,23 +1019,22 @@ private[chisel3] trait ObjectDataImpl { if (thiz._elements.size != that._elements.size) { throwException(s"Cannot compare Bundles $thiz and $that: Bundle types differ") } else { - thiz._elements.map { - case (thisName, thisData) => - if (!that._elements.contains(thisName)) + thiz._elements.map { case (thisName, thisData) => + if (!that._elements.contains(thisName)) + throwException( + s"Cannot compare Bundles $thiz and $that: field $thisName (from $thiz) was not found in $that" + ) + + val thatData = that._elements(thisName) + + try { + thisData === thatData + } catch { + case e: chisel3.ChiselException => throwException( - s"Cannot compare Bundles $thiz and $that: field $thisName (from $thiz) was not found in $that" + s"Cannot compare field $thisName in Bundles $thiz and $that: ${e.getMessage.split(": ").last}" ) - - val thatData = that._elements(thisName) - - try { - thisData === thatData - } catch { - case e: chisel3.ChiselException => - throwException( - s"Cannot compare field $thisName in Bundles $thiz and $that: ${e.getMessage.split(": ").last}" - ) - } + } } .reduceOption(_ && _) // forall but that isn't defined for Bool on Seq .getOrElse(true.B) diff --git a/core/src/main/scala/chisel3/IO.scala b/core/src/main/scala/chisel3/IO.scala index 1814d6aa97a..9a997684132 100644 --- a/core/src/main/scala/chisel3/IO.scala +++ b/core/src/main/scala/chisel3/IO.scala @@ -26,8 +26,8 @@ object IO { if (!module.isIOCreationAllowed) Builder.error( s"This module cannot have IOs instantiated after disallowing IOs: ${module._whereIOCreationIsDisallowed - .map(_.makeMessage { (s: String) => s }) - .mkString(",")}" + .map(_.makeMessage { (s: String) => s }) + .mkString(",")}" ) require(!module.isClosed, "Can't add more ports after module close") val prevId = Builder.idGen.value @@ -97,14 +97,13 @@ object FlatIO { gen match { case d if hasProbeTypeModifier(d) => IO(d) case _: Element => IO(gen) - case _: Vec[_] => IO(gen) + case _: Vec[_] => IO(gen) case record: R => val ports: Seq[Data] = - record._elements.toSeq.reverse.map { - case (name, data) => - val p = IO(coerceDirection(data).asInstanceOf[Data]) - p.suggestName(name) - p + record._elements.toSeq.reverse.map { case (name, data) => + val p = IO(coerceDirection(data).asInstanceOf[Data]) + p.suggestName(name) + p } diff --git a/core/src/main/scala/chisel3/Intrinsic.scala b/core/src/main/scala/chisel3/Intrinsic.scala index 6f1d0d5e091..4095d775b9d 100644 --- a/core/src/main/scala/chisel3/Intrinsic.scala +++ b/core/src/main/scala/chisel3/Intrinsic.scala @@ -45,8 +45,7 @@ object IntrinsicExpr { intrinsic: String, ret: => T, params: (String, Param)* - )(data: Data* - )( + )(data: Data*)( implicit sourceInfo: SourceInfo ): T = { val prevId = Builder.idGen.value diff --git a/core/src/main/scala/chisel3/Layer.scala b/core/src/main/scala/chisel3/Layer.scala index fe4d4ebb940..df297fdeed4 100644 --- a/core/src/main/scala/chisel3/Layer.scala +++ b/core/src/main/scala/chisel3/Layer.scala @@ -87,9 +87,7 @@ object layer { */ abstract class Layer( val config: LayerConfig - )( - implicit _parent: Layer, - _sourceInfo: SourceInfo) { + )(implicit _parent: Layer, _sourceInfo: SourceInfo) { self: Singleton => @deprecated("`Convention` is being removed in favor of `LayerConfig`", "Chisel 7.0.0") @@ -221,8 +219,7 @@ object layer { layer: Layer, skipIfAlreadyInBlock: Boolean = false, skipIfLayersEnabled: Boolean = false - )(thunk: => A - )( + )(thunk: => A)( implicit sourceInfo: SourceInfo ): Unit = { // Do nothing if we are already in a layer block and are not supposed to diff --git a/core/src/main/scala/chisel3/Printable.scala b/core/src/main/scala/chisel3/Printable.scala index d7646ae5bfd..2b187dbdd7f 100644 --- a/core/src/main/scala/chisel3/Printable.scala +++ b/core/src/main/scala/chisel3/Printable.scala @@ -219,17 +219,17 @@ case class Character(bits: Bits) extends FirrtlFormat('c') /** Put innermost name (eg. field of bundle) */ case class Name(data: Data) extends Printable { final def unpack(ctx: Component): (String, Iterable[String]) = (data.ref.name, List.empty) - final def unpackArgs: Seq[Bits] = List.empty + final def unpackArgs: Seq[Bits] = List.empty } /** Put full name within parent namespace (eg. bundleName.field) */ case class FullName(data: Data) extends Printable { final def unpack(ctx: Component): (String, Iterable[String]) = (data.ref.fullName(ctx), List.empty) - final def unpackArgs: Seq[Bits] = List.empty + final def unpackArgs: Seq[Bits] = List.empty } /** Represents escaped percents */ case object Percent extends Printable { final def unpack(ctx: Component): (String, Iterable[String]) = ("%%", List.empty) - final def unpackArgs: Seq[Bits] = List.empty + final def unpackArgs: Seq[Bits] = List.empty } diff --git a/core/src/main/scala/chisel3/RawModule.scala b/core/src/main/scala/chisel3/RawModule.scala index de74374d6f3..f2234623a40 100644 --- a/core/src/main/scala/chisel3/RawModule.scala +++ b/core/src/main/scala/chisel3/RawModule.scala @@ -177,7 +177,7 @@ abstract class RawModule extends BaseModule { case id: assert.Assert => id.forceName(default = "assert", _namespace) case id: assume.Assume => id.forceName(default = "assume", _namespace) case id: cover.Cover => id.forceName(default = "cover", _namespace) - case id: printf.Printf => id.forceName(default = "printf", _namespace) + case id: printf.Printf => id.forceName(default = "printf", _namespace) case id: DynamicObject => { // Force name of the DynamicObject, and set its Property[ClassType] type's ref to the DynamicObject. // The type's ref can't be set upon instantiation, because the DynamicObject hasn't been named yet. @@ -237,9 +237,8 @@ abstract class RawModule extends BaseModule { nameId(id) } - val firrtlPorts = getModulePortsAndLocators.map { - case (port, sourceInfo) => - Port(port, port.specifiedDirection, sourceInfo) + val firrtlPorts = getModulePortsAndLocators.map { case (port, sourceInfo) => + Port(port, port.specifiedDirection, sourceInfo) } _firrtlPorts = Some(firrtlPorts) diff --git a/core/src/main/scala/chisel3/SeqUtils.scala b/core/src/main/scala/chisel3/SeqUtils.scala index 212087861c8..de9284939e7 100644 --- a/core/src/main/scala/chisel3/SeqUtils.scala +++ b/core/src/main/scala/chisel3/SeqUtils.scala @@ -54,8 +54,8 @@ private[chisel3] object SeqUtils { in.head._2 } else { val r = in.view.reverse - r.tail.foldLeft(r.head._2) { - case (alt, (sel, elt)) => Mux(sel, elt, alt) + r.tail.foldLeft(r.head._2) { case (alt, (sel, elt)) => + Mux(sel, elt, alt) } } } @@ -85,9 +85,8 @@ private[chisel3] object SeqUtils { case _: SInt => // SInt's have to be managed carefully so sign extension works - val sInts: Iterable[(Bool, SInt)] = in.collect { - case (s: Bool, f: SInt) => - (s, f.asTypeOf(output).asInstanceOf[SInt]) + val sInts: Iterable[(Bool, SInt)] = in.collect { case (s: Bool, f: SInt) => + (s, f.asTypeOf(output).asInstanceOf[SInt]) } val masked = for ((s, i) <- sInts) yield Mux(s, i, 0.S) @@ -100,9 +99,8 @@ private[chisel3] object SeqUtils { val (sel, inData) = in.unzip val inElts = inData.map(_.asInstanceOf[Aggregate].getElements) // We want to iterate on the columns of inElts, so we transpose - out.getElements.zip(inElts.transpose).foreach { - case (outElt, elts) => - outElt := oneHotMux(sel.zip(elts)) + out.getElements.zip(inElts.transpose).foreach { case (outElt, elts) => + outElt := oneHotMux(sel.zip(elts)) } out.asInstanceOf[T] } else { diff --git a/core/src/main/scala/chisel3/When.scala b/core/src/main/scala/chisel3/When.scala index ce6d37b59c1..93676d94d3c 100644 --- a/core/src/main/scala/chisel3/When.scala +++ b/core/src/main/scala/chisel3/When.scala @@ -28,9 +28,8 @@ object when { */ def apply( - cond: => Bool - )(block: => Any - )( + cond: => Bool + )(block: => Any)( implicit sourceInfo: SourceInfo ): WhenContext = { new WhenContext(sourceInfo, () => cond, block, Nil) @@ -53,8 +52,8 @@ object when { def cond: Bool = { implicit val sourceInfo = UnlocatableSourceInfo val whens = Builder.whenStack - whens.foldRight(true.B) { - case (ctx, acc) => acc && ctx.localCond + whens.foldRight(true.B) { case (ctx, acc) => + acc && ctx.localCond } } } @@ -88,7 +87,8 @@ final class WhenContext private[chisel3] ( cond: () => Bool, block: => Any, // For capturing conditions from prior whens or elsewhens - altConds: List[() => Bool]) { + altConds: List[() => Bool] +) { /** Indicate if the `WhenContext` is "closed" (`None`) or if this is writing to * the "if" or "else" region. @@ -100,8 +100,8 @@ final class WhenContext private[chisel3] ( /** Returns the local condition, inverted for an otherwise */ private[chisel3] def localCond: Bool = { implicit val sourceInfo = UnlocatableSourceInfo - val alt = altConds.foldRight(true.B) { - case (c, acc) => acc & !c() + val alt = altConds.foldRight(true.B) { case (c, acc) => + acc & !c() } scope match { case Some(Scope.If) => alt && cond() @@ -118,8 +118,7 @@ final class WhenContext private[chisel3] ( */ def elsewhen( elseCond: => Bool - )(block: => Any - )( + )(block: => Any)( implicit sourceInfo: SourceInfo ): WhenContext = { Builder.forcedUserModule.withRegion(whenCommand.elseRegion) { diff --git a/core/src/main/scala/chisel3/Width.scala b/core/src/main/scala/chisel3/Width.scala index d207f3d0650..8e52a4a1e91 100644 --- a/core/src/main/scala/chisel3/Width.scala +++ b/core/src/main/scala/chisel3/Width.scala @@ -4,7 +4,7 @@ package chisel3 object Width { def apply(x: Int): Width = KnownWidth(x) - def apply(): Width = UnknownWidth + def apply(): Width = UnknownWidth } sealed abstract class Width { @@ -20,19 +20,19 @@ sealed abstract class Width { def shiftRight(that: Int): Width = this.op(this, (a, b) => 0.max(a - that)) def unsignedShiftRight(that: Int): Width = this.op(this, (a, b) => 0.max(a - that)) def signedShiftRight(that: Int): Width = this.op(this, (a, b) => 1.max(a - that)) - def dynamicShiftLeft(that: Width): Width = + def dynamicShiftLeft(that: Width): Width = this.op(that, (a, b) => a + (1 << b) - 1) - def known: Boolean - def get: W + def known: Boolean + def get: W protected def op(that: Width, f: (W, W) => W): Width } case object UnknownWidth extends Width { - def known: Boolean = false - def get: Int = None.get + def known: Boolean = false + def get: Int = None.get def op(that: Width, f: (W, W) => W): Width = this - override def toString: String = "" + override def toString: String = "" @deprecated("UnknownWidth is now a case object, remove the parentheses", "Chisel 7.0") def apply(): UnknownWidth.type = this diff --git a/core/src/main/scala/chisel3/connectable/Alignment.scala b/core/src/main/scala/chisel3/connectable/Alignment.scala index 35b63366b6f..022780bdce5 100644 --- a/core/src/main/scala/chisel3/connectable/Alignment.scala +++ b/core/src/main/scala/chisel3/connectable/Alignment.scala @@ -47,33 +47,27 @@ private[chisel3] case class EmptyAlignment(isConsumer: Boolean) extends Alignmen def member: Data = DontCare def invert: EmptyAlignment = this def coerced = false - def coerce: EmptyAlignment = this + def coerce: EmptyAlignment = this def swap(d: Data): Alignment = this - def alignment: String = "none" + def alignment: String = "none" } private[chisel3] sealed trait NonEmptyAlignment extends Alignment -private[chisel3] case class AlignedWithRoot( - member: Data, - coerced: Boolean, - isConsumer: Boolean) +private[chisel3] case class AlignedWithRoot(member: Data, coerced: Boolean, isConsumer: Boolean) extends NonEmptyAlignment { def invert = if (coerced) this else FlippedWithRoot(member, coerced, isConsumer) - def coerce: AlignedWithRoot = this.copy(member, true) + def coerce: AlignedWithRoot = this.copy(member, true) def swap(d: Data): Alignment = this.copy(member = d) - def alignment: String = "aligned" + def alignment: String = "aligned" } -private[chisel3] case class FlippedWithRoot( - member: Data, - coerced: Boolean, - isConsumer: Boolean) +private[chisel3] case class FlippedWithRoot(member: Data, coerced: Boolean, isConsumer: Boolean) extends NonEmptyAlignment { def invert = if (coerced) this else AlignedWithRoot(member, coerced, isConsumer) - def coerce: FlippedWithRoot = this.copy(member, true) + def coerce: FlippedWithRoot = this.copy(member, true) def swap(d: Data): Alignment = this.copy(member = d) - def alignment: String = "flipped" + def alignment: String = "flipped" } object Alignment { @@ -89,9 +83,9 @@ object Alignment { def recUp(x: Data): Boolean = x.binding match { case _ if isLocallyCoercing(x) => true case None => false - case Some(t: TopBinding) => false - case Some(ChildBinding(p)) => recUp(p) - case other => throw new Exception(s"Unexpected $other! $x, $member") + case Some(t: TopBinding) => false + case Some(ChildBinding(p)) => recUp(p) + case other => throw new Exception(s"Unexpected $other! $x, $member") } def isLocallyCoercing(d: Data): Boolean = { val s = DataMirror.specifiedDirectionOf(d) @@ -115,8 +109,8 @@ object Alignment { left: Option[Alignment], right: Option[Alignment] ): Seq[(Option[Alignment], Option[Alignment])] = { - Data.dataMatchingZipOfChildren.matchingZipOfChildren(left.map(_.member), right.map(_.member)).map { - case (l, r) => l.map(deriveChildAlignment(_, left.get)) -> r.map(deriveChildAlignment(_, right.get)) + Data.dataMatchingZipOfChildren.matchingZipOfChildren(left.map(_.member), right.map(_.member)).map { case (l, r) => + l.map(deriveChildAlignment(_, left.get)) -> r.map(deriveChildAlignment(_, right.get)) } } } @@ -130,12 +124,12 @@ private[chisel3] case class ConnectableAlignment(base: Connectable[Data], align: // Returns loc and roc final def computeLandR(c: Data, p: Data, op: Connection): Option[(Data, Data)] = { (c, p, this.align, op.connectToConsumer, op.connectToProducer, op.alwaysConnectToConsumer) match { - case (x: Analog, y: Analog, _, _, _, _) => Some((x, y)) - case (x: Analog, DontCare, _, _, _, _) => Some((x, DontCare)) + case (x: Analog, y: Analog, _, _, _, _) => Some((x, y)) + case (x: Analog, DontCare, _, _, _, _) => Some((x, DontCare)) case (x, y, _: AlignedWithRoot, true, _, _) => Some((c, p)) case (x, y, _: FlippedWithRoot, _, true, _) => Some((p, c)) - case (x, y, _, _, _, true) => Some((c, p)) - case other => None + case (x, y, _, _, _, true) => Some((c, p)) + case other => None } } diff --git a/core/src/main/scala/chisel3/connectable/Connectable.scala b/core/src/main/scala/chisel3/connectable/Connectable.scala index 36fadedab0a..a35de50653a 100644 --- a/core/src/main/scala/chisel3/connectable/Connectable.scala +++ b/core/src/main/scala/chisel3/connectable/Connectable.scala @@ -18,7 +18,8 @@ final class Connectable[+T <: Data] private ( val base: T, private[chisel3] val waived: Set[Data], private[chisel3] val squeezed: Set[Data], - private[chisel3] val excluded: Set[Data]) { + private[chisel3] val excluded: Set[Data] +) { requireIsHardware(base, s"Can only created Connectable of components, not unbound Chisel types") private[chisel3] def copy( diff --git a/core/src/main/scala/chisel3/connectable/Connection.scala b/core/src/main/scala/chisel3/connectable/Connection.scala index ede985f929b..11bbf7cd654 100644 --- a/core/src/main/scala/chisel3/connectable/Connection.scala +++ b/core/src/main/scala/chisel3/connectable/Connection.scala @@ -120,8 +120,8 @@ private[chisel3] object Connection { try { (l, r) match { case (x: Analog, y: Analog) => connectAnalog(x, y) - case (x: Analog, DontCare) => connectAnalog(x, DontCare) - case (_, _) => l := r + case (x: Analog, DontCare) => connectAnalog(x, DontCare) + case (_, _) => l := r } } catch { case e: Exception => Builder.error(e.getMessage) @@ -186,25 +186,22 @@ private[chisel3] object Connection { (conAlign.member, proAlign.member) match { case (consumer: Aggregate, producer: Aggregate) if !hasProbeTypeModifier(consumer) && !hasProbeTypeModifier(producer) => - matchingZipOfChildren(Some(conAlign), Some(proAlign)).foreach { - case (ceo, peo) => - doConnection(ceo.getOrElse(conAlign.empty), peo.getOrElse(proAlign.empty)) + matchingZipOfChildren(Some(conAlign), Some(proAlign)).foreach { case (ceo, peo) => + doConnection(ceo.getOrElse(conAlign.empty), peo.getOrElse(proAlign.empty)) } case (consumer: Aggregate, DontCare) if !hasProbeTypeModifier(consumer) => - consumer.getElements.foreach { - case f => - doConnection( - deriveChildAlignment(f, conAlign), - deriveChildAlignment(f, conAlign).swap(DontCare) - ) + consumer.getElements.foreach { case f => + doConnection( + deriveChildAlignment(f, conAlign), + deriveChildAlignment(f, conAlign).swap(DontCare) + ) } case (DontCare, producer: Aggregate) if !hasProbeTypeModifier(producer) => - producer.getElements.foreach { - case f => - doConnection( - deriveChildAlignment(f, proAlign).swap(DontCare), - deriveChildAlignment(f, proAlign) - ) + producer.getElements.foreach { case f => + doConnection( + deriveChildAlignment(f, proAlign).swap(DontCare), + deriveChildAlignment(f, proAlign) + ) } // Check that neither consumer nor producer contains probes case (consumer: Data, producer: Data) diff --git a/core/src/main/scala/chisel3/dontTouch.scala b/core/src/main/scala/chisel3/dontTouch.scala index 283b59d600d..3266b811543 100644 --- a/core/src/main/scala/chisel3/dontTouch.scala +++ b/core/src/main/scala/chisel3/dontTouch.scala @@ -38,7 +38,7 @@ object dontTouch { data match { case d if DataMirror.hasProbeTypeModifier(d) => () case _: Property[_] => () - case agg: Aggregate => agg.getElements.foreach(dontTouch.apply) + case agg: Aggregate => agg.getElements.foreach(dontTouch.apply) case _: Element => annotate(new ChiselAnnotation { def toFirrtl: DontTouchAnnotation = DontTouchAnnotation(data.toNamed) }) case _ => throw new ChiselException("Non-hardware dontTouch") diff --git a/core/src/main/scala/chisel3/experimental/Analog.scala b/core/src/main/scala/chisel3/experimental/Analog.scala index c0136abe0ca..79ba0bbba93 100644 --- a/core/src/main/scala/chisel3/experimental/Analog.scala +++ b/core/src/main/scala/chisel3/experimental/Analog.scala @@ -47,7 +47,7 @@ final class Analog private (private[chisel3] val width: Width) extends Element { this.maybeAddToParentIds(target) SpecifiedDirection.fromParent(parentDirection, specifiedDirection) match { case SpecifiedDirection.Unspecified | SpecifiedDirection.Flip => - case x => throwException(s"Analog may not have explicit direction, got '$x'") + case x => throwException(s"Analog may not have explicit direction, got '$x'") } val targetTopBinding = target match { case target: TopBinding => target diff --git a/core/src/main/scala/chisel3/experimental/HasAutoTypename.scala b/core/src/main/scala/chisel3/experimental/HasAutoTypename.scala index 7adfc6afc53..c4cd0c029e3 100644 --- a/core/src/main/scala/chisel3/experimental/HasAutoTypename.scala +++ b/core/src/main/scala/chisel3/experimental/HasAutoTypename.scala @@ -41,8 +41,8 @@ trait HasAutoTypename { override def typeName: String = autoTypeName(simpleClassName(this.getClass), _typeNameConParams) private def autoTypeName(bundleName: String, typeNameParams: Iterable[Any]): String = { - _typeNameConParams.foldLeft(sanitize(bundleName)) { - case (prev, accessor) => prev + s"_${accessorString(accessor)}" + _typeNameConParams.foldLeft(sanitize(bundleName)) { case (prev, accessor) => + prev + s"_${accessorString(accessor)}" } } diff --git a/core/src/main/scala/chisel3/experimental/HasTypeAlias.scala b/core/src/main/scala/chisel3/experimental/HasTypeAlias.scala index 4d3e9e79a04..5cb47dba6d1 100644 --- a/core/src/main/scala/chisel3/experimental/HasTypeAlias.scala +++ b/core/src/main/scala/chisel3/experimental/HasTypeAlias.scala @@ -19,7 +19,7 @@ case class RecordAlias private[chisel3] (info: SourceInfo, id: String, strippedS } object RecordAlias { - def apply(id: String)(implicit info: SourceInfo): RecordAlias = new RecordAlias(info, id) + def apply(id: String)(implicit info: SourceInfo): RecordAlias = new RecordAlias(info, id) def apply(id: String, strippedSuffix: String)(implicit info: SourceInfo): RecordAlias = RecordAlias(info, id, strippedSuffix) def apply(info: SourceInfo, id: String, strippedSuffix: String): RecordAlias = diff --git a/core/src/main/scala/chisel3/experimental/IntrinsicModule.scala b/core/src/main/scala/chisel3/experimental/IntrinsicModule.scala index f1f2efd52f9..5d9a7303bee 100644 --- a/core/src/main/scala/chisel3/experimental/IntrinsicModule.scala +++ b/core/src/main/scala/chisel3/experimental/IntrinsicModule.scala @@ -21,8 +21,8 @@ abstract class IntrinsicModule(intrinsicName: String, val params: Map[String, Pa // Ports are named in the same way as regular Modules namePorts() - val firrtlPorts = getModulePorts.map { - case port => Port(port, port.specifiedDirection, UnlocatableSourceInfo) + val firrtlPorts = getModulePorts.map { case port => + Port(port, port.specifiedDirection, UnlocatableSourceInfo) } val component = DefIntrinsicModule(this, name, firrtlPorts, SpecifiedDirection.Unspecified, params) _component = Some(component) diff --git a/core/src/main/scala/chisel3/experimental/SerializableModuleGenerator.scala b/core/src/main/scala/chisel3/experimental/SerializableModuleGenerator.scala index a48c2448e02..31707e81b7d 100644 --- a/core/src/main/scala/chisel3/experimental/SerializableModuleGenerator.scala +++ b/core/src/main/scala/chisel3/experimental/SerializableModuleGenerator.scala @@ -49,8 +49,8 @@ object SerializableModuleGenerator { /** cache instance of a generator. */ private case class CacheKey[P <: SerializableModuleParameter, M <: SerializableModule[P]]( parameter: P, - mTypeTag: universe.TypeTag[M]) - extends BuilderContextCache.Key[Definition[M with BaseModule]] + mTypeTag: universe.TypeTag[M] + ) extends BuilderContextCache.Key[Definition[M with BaseModule]] } @@ -61,9 +61,7 @@ object SerializableModuleGenerator { case class SerializableModuleGenerator[M <: SerializableModule[P], P <: SerializableModuleParameter]( generator: Class[M], parameter: P -)( - implicit val pTag: universe.TypeTag[P], - implicit val mTag: universe.TypeTag[M]) { +)(implicit val pTag: universe.TypeTag[P], implicit val mTag: universe.TypeTag[M]) { private[chisel3] def construct: M with BaseModule = { require( generator.getConstructors.length == 1, diff --git a/core/src/main/scala/chisel3/experimental/dataview/DataProduct.scala b/core/src/main/scala/chisel3/experimental/dataview/DataProduct.scala index b07bdbf706d..ba6ace684dd 100644 --- a/core/src/main/scala/chisel3/experimental/dataview/DataProduct.scala +++ b/core/src/main/scala/chisel3/experimental/dataview/DataProduct.scala @@ -105,9 +105,8 @@ object DataProduct extends LowPriorityDataProduct { def seqDataProduct[A: DataProduct]: DataProduct[Seq[A]] = new DataProduct[Seq[A]] { def dataIterator(a: Seq[A], path: String): Iterator[(Data, String)] = { val dpa = implicitly[DataProduct[A]] - a.iterator.zipWithIndex.flatMap { - case (elt, idx) => - dpa.dataIterator(elt, s"$path[$idx]") + a.iterator.zipWithIndex.flatMap { case (elt, idx) => + dpa.dataIterator(elt, s"$path[$idx]") } } } @@ -116,9 +115,8 @@ object DataProduct extends LowPriorityDataProduct { implicit def iterableDataProduct[A: DataProduct, F[A] <: IterableOnce[A]]: DataProduct[F[A]] = new DataProduct[F[A]] { def dataIterator(a: F[A], path: String): Iterator[(Data, String)] = { val dpa = implicitly[DataProduct[A]] - a.iterator.zipWithIndex.flatMap { - case (elt, idx) => - dpa.dataIterator(elt, s"$path[$idx]") + a.iterator.zipWithIndex.flatMap { case (elt, idx) => + dpa.dataIterator(elt, s"$path[$idx]") } } } diff --git a/core/src/main/scala/chisel3/experimental/dataview/DataView.scala b/core/src/main/scala/chisel3/experimental/dataview/DataView.scala index a9e22e8ca50..529544980c5 100644 --- a/core/src/main/scala/chisel3/experimental/dataview/DataView.scala +++ b/core/src/main/scala/chisel3/experimental/dataview/DataView.scala @@ -50,8 +50,7 @@ sealed class DataView[T: DataProduct, V <: Data] private[chisel3] ( private[chisel3] val mapping: (T, V) => Iterable[(Data, Data)], // Aliasing this with a def below to make the ScalaDoc show up for the field _total: Boolean -)( - implicit private[chisel3] val sourceInfo: SourceInfo) { +)(implicit private[chisel3] val sourceInfo: SourceInfo) { /** Indicates if the mapping contains every field of the target */ def total: Boolean = _total @@ -144,9 +143,8 @@ object DataView extends InvertibleDataView { ): DataView[(T1, T2), HWTuple2[V1, V2]] = DataView.mapping( { case (a, b) => new HWTuple2(a.viewAs[V1].cloneType, b.viewAs[V2].cloneType) }, - { - case ((a, b), hwt) => - Seq(a.viewAs[V1] -> hwt._1, b.viewAs[V2] -> hwt._2) + { case ((a, b), hwt) => + Seq(a.viewAs[V1] -> hwt._1, b.viewAs[V2] -> hwt._2) } ) @@ -159,9 +157,8 @@ object DataView extends InvertibleDataView { ): DataView[(T1, T2, T3), HWTuple3[V1, V2, V3]] = DataView.mapping( { case (a, b, c) => new HWTuple3(a.viewAs[V1].cloneType, b.viewAs[V2].cloneType, c.viewAs[V3].cloneType) }, - { - case ((a, b, c), hwt) => - Seq(a.viewAs[V1] -> hwt._1, b.viewAs[V2] -> hwt._2, c.viewAs[V3] -> hwt._3) + { case ((a, b, c), hwt) => + Seq(a.viewAs[V1] -> hwt._1, b.viewAs[V2] -> hwt._2, c.viewAs[V3] -> hwt._3) } ) @@ -183,13 +180,11 @@ object DataView extends InvertibleDataView { sourceInfo: SourceInfo ): DataView[(T1, T2, T3, T4), HWTuple4[V1, V2, V3, V4]] = DataView.mapping( - { - case (a, b, c, d) => - new HWTuple4(a.viewAs[V1].cloneType, b.viewAs[V2].cloneType, c.viewAs[V3].cloneType, d.viewAs[V4].cloneType) + { case (a, b, c, d) => + new HWTuple4(a.viewAs[V1].cloneType, b.viewAs[V2].cloneType, c.viewAs[V3].cloneType, d.viewAs[V4].cloneType) }, - { - case ((a, b, c, d), hwt) => - Seq(a.viewAs[V1] -> hwt._1, b.viewAs[V2] -> hwt._2, c.viewAs[V3] -> hwt._3, d.viewAs[V4] -> hwt._4) + { case ((a, b, c, d), hwt) => + Seq(a.viewAs[V1] -> hwt._1, b.viewAs[V2] -> hwt._2, c.viewAs[V3] -> hwt._3, d.viewAs[V4] -> hwt._4) } ) @@ -214,26 +209,24 @@ object DataView extends InvertibleDataView { sourceInfo: SourceInfo ): DataView[(T1, T2, T3, T4, T5), HWTuple5[V1, V2, V3, V4, V5]] = { DataView.mapping( - { - case tup: Tuple5[T1, T2, T3, T4, T5] => - val (a, b, c, d, e) = tup - new HWTuple5( - a.viewAs[V1].cloneType, - b.viewAs[V2].cloneType, - c.viewAs[V3].cloneType, - d.viewAs[V4].cloneType, - e.viewAs[V5].cloneType - ) + { case tup: Tuple5[T1, T2, T3, T4, T5] => + val (a, b, c, d, e) = tup + new HWTuple5( + a.viewAs[V1].cloneType, + b.viewAs[V2].cloneType, + c.viewAs[V3].cloneType, + d.viewAs[V4].cloneType, + e.viewAs[V5].cloneType + ) }, - { - case ((a, b, c, d, e), hwt) => - Seq( - a.viewAs[V1] -> hwt._1, - b.viewAs[V2] -> hwt._2, - c.viewAs[V3] -> hwt._3, - d.viewAs[V4] -> hwt._4, - e.viewAs[V5] -> hwt._5 - ) + { case ((a, b, c, d, e), hwt) => + Seq( + a.viewAs[V1] -> hwt._1, + b.viewAs[V2] -> hwt._2, + c.viewAs[V3] -> hwt._3, + d.viewAs[V4] -> hwt._4, + e.viewAs[V5] -> hwt._5 + ) } ) } @@ -262,27 +255,25 @@ object DataView extends InvertibleDataView { sourceInfo: SourceInfo ): DataView[(T1, T2, T3, T4, T5, T6), HWTuple6[V1, V2, V3, V4, V5, V6]] = DataView.mapping( - { - case (a, b, c, d, e, f) => - new HWTuple6( - a.viewAs[V1].cloneType, - b.viewAs[V2].cloneType, - c.viewAs[V3].cloneType, - d.viewAs[V4].cloneType, - e.viewAs[V5].cloneType, - f.viewAs[V6].cloneType - ) + { case (a, b, c, d, e, f) => + new HWTuple6( + a.viewAs[V1].cloneType, + b.viewAs[V2].cloneType, + c.viewAs[V3].cloneType, + d.viewAs[V4].cloneType, + e.viewAs[V5].cloneType, + f.viewAs[V6].cloneType + ) }, - { - case ((a, b, c, d, e, f), hwt) => - Seq( - a.viewAs[V1] -> hwt._1, - b.viewAs[V2] -> hwt._2, - c.viewAs[V3] -> hwt._3, - d.viewAs[V4] -> hwt._4, - e.viewAs[V5] -> hwt._5, - f.viewAs[V6] -> hwt._6 - ) + { case ((a, b, c, d, e, f), hwt) => + Seq( + a.viewAs[V1] -> hwt._1, + b.viewAs[V2] -> hwt._2, + c.viewAs[V3] -> hwt._3, + d.viewAs[V4] -> hwt._4, + e.viewAs[V5] -> hwt._5, + f.viewAs[V6] -> hwt._6 + ) } ) @@ -313,29 +304,27 @@ object DataView extends InvertibleDataView { sourceInfo: SourceInfo ): DataView[(T1, T2, T3, T4, T5, T6, T7), HWTuple7[V1, V2, V3, V4, V5, V6, V7]] = DataView.mapping( - { - case (a, b, c, d, e, f, g) => - new HWTuple7( - a.viewAs[V1].cloneType, - b.viewAs[V2].cloneType, - c.viewAs[V3].cloneType, - d.viewAs[V4].cloneType, - e.viewAs[V5].cloneType, - f.viewAs[V6].cloneType, - g.viewAs[V7].cloneType - ) + { case (a, b, c, d, e, f, g) => + new HWTuple7( + a.viewAs[V1].cloneType, + b.viewAs[V2].cloneType, + c.viewAs[V3].cloneType, + d.viewAs[V4].cloneType, + e.viewAs[V5].cloneType, + f.viewAs[V6].cloneType, + g.viewAs[V7].cloneType + ) }, - { - case ((a, b, c, d, e, f, g), hwt) => - Seq( - a.viewAs[V1] -> hwt._1, - b.viewAs[V2] -> hwt._2, - c.viewAs[V3] -> hwt._3, - d.viewAs[V4] -> hwt._4, - e.viewAs[V5] -> hwt._5, - f.viewAs[V6] -> hwt._6, - g.viewAs[V7] -> hwt._7 - ) + { case ((a, b, c, d, e, f, g), hwt) => + Seq( + a.viewAs[V1] -> hwt._1, + b.viewAs[V2] -> hwt._2, + c.viewAs[V3] -> hwt._3, + d.viewAs[V4] -> hwt._4, + e.viewAs[V5] -> hwt._5, + f.viewAs[V6] -> hwt._6, + g.viewAs[V7] -> hwt._7 + ) } ) @@ -369,31 +358,29 @@ object DataView extends InvertibleDataView { sourceInfo: SourceInfo ): DataView[(T1, T2, T3, T4, T5, T6, T7, T8), HWTuple8[V1, V2, V3, V4, V5, V6, V7, V8]] = DataView.mapping( - { - case (a, b, c, d, e, f, g, h) => - new HWTuple8( - a.viewAs[V1].cloneType, - b.viewAs[V2].cloneType, - c.viewAs[V3].cloneType, - d.viewAs[V4].cloneType, - e.viewAs[V5].cloneType, - f.viewAs[V6].cloneType, - g.viewAs[V7].cloneType, - h.viewAs[V8].cloneType - ) + { case (a, b, c, d, e, f, g, h) => + new HWTuple8( + a.viewAs[V1].cloneType, + b.viewAs[V2].cloneType, + c.viewAs[V3].cloneType, + d.viewAs[V4].cloneType, + e.viewAs[V5].cloneType, + f.viewAs[V6].cloneType, + g.viewAs[V7].cloneType, + h.viewAs[V8].cloneType + ) }, - { - case ((a, b, c, d, e, f, g, h), hwt) => - Seq( - a.viewAs[V1] -> hwt._1, - b.viewAs[V2] -> hwt._2, - c.viewAs[V3] -> hwt._3, - d.viewAs[V4] -> hwt._4, - e.viewAs[V5] -> hwt._5, - f.viewAs[V6] -> hwt._6, - g.viewAs[V7] -> hwt._7, - h.viewAs[V8] -> hwt._8 - ) + { case ((a, b, c, d, e, f, g, h), hwt) => + Seq( + a.viewAs[V1] -> hwt._1, + b.viewAs[V2] -> hwt._2, + c.viewAs[V3] -> hwt._3, + d.viewAs[V4] -> hwt._4, + e.viewAs[V5] -> hwt._5, + f.viewAs[V6] -> hwt._6, + g.viewAs[V7] -> hwt._7, + h.viewAs[V8] -> hwt._8 + ) } ) @@ -430,33 +417,31 @@ object DataView extends InvertibleDataView { sourceInfo: SourceInfo ): DataView[(T1, T2, T3, T4, T5, T6, T7, T8, T9), HWTuple9[V1, V2, V3, V4, V5, V6, V7, V8, V9]] = DataView.mapping( - { - case (a, b, c, d, e, f, g, h, i) => - new HWTuple9( - a.viewAs[V1].cloneType, - b.viewAs[V2].cloneType, - c.viewAs[V3].cloneType, - d.viewAs[V4].cloneType, - e.viewAs[V5].cloneType, - f.viewAs[V6].cloneType, - g.viewAs[V7].cloneType, - h.viewAs[V8].cloneType, - i.viewAs[V9].cloneType - ) + { case (a, b, c, d, e, f, g, h, i) => + new HWTuple9( + a.viewAs[V1].cloneType, + b.viewAs[V2].cloneType, + c.viewAs[V3].cloneType, + d.viewAs[V4].cloneType, + e.viewAs[V5].cloneType, + f.viewAs[V6].cloneType, + g.viewAs[V7].cloneType, + h.viewAs[V8].cloneType, + i.viewAs[V9].cloneType + ) }, - { - case ((a, b, c, d, e, f, g, h, i), hwt) => - Seq( - a.viewAs[V1] -> hwt._1, - b.viewAs[V2] -> hwt._2, - c.viewAs[V3] -> hwt._3, - d.viewAs[V4] -> hwt._4, - e.viewAs[V5] -> hwt._5, - f.viewAs[V6] -> hwt._6, - g.viewAs[V7] -> hwt._7, - h.viewAs[V8] -> hwt._8, - i.viewAs[V9] -> hwt._9 - ) + { case ((a, b, c, d, e, f, g, h, i), hwt) => + Seq( + a.viewAs[V1] -> hwt._1, + b.viewAs[V2] -> hwt._2, + c.viewAs[V3] -> hwt._3, + d.viewAs[V4] -> hwt._4, + e.viewAs[V5] -> hwt._5, + f.viewAs[V6] -> hwt._6, + g.viewAs[V7] -> hwt._7, + h.viewAs[V8] -> hwt._8, + i.viewAs[V9] -> hwt._9 + ) } ) @@ -496,35 +481,33 @@ object DataView extends InvertibleDataView { sourceInfo: SourceInfo ): DataView[(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10), HWTuple10[V1, V2, V3, V4, V5, V6, V7, V8, V9, V10]] = DataView.mapping( - { - case (a, b, c, d, e, f, g, h, i, j) => - new HWTuple10( - a.viewAs[V1].cloneType, - b.viewAs[V2].cloneType, - c.viewAs[V3].cloneType, - d.viewAs[V4].cloneType, - e.viewAs[V5].cloneType, - f.viewAs[V6].cloneType, - g.viewAs[V7].cloneType, - h.viewAs[V8].cloneType, - i.viewAs[V9].cloneType, - j.viewAs[V10].cloneType - ) + { case (a, b, c, d, e, f, g, h, i, j) => + new HWTuple10( + a.viewAs[V1].cloneType, + b.viewAs[V2].cloneType, + c.viewAs[V3].cloneType, + d.viewAs[V4].cloneType, + e.viewAs[V5].cloneType, + f.viewAs[V6].cloneType, + g.viewAs[V7].cloneType, + h.viewAs[V8].cloneType, + i.viewAs[V9].cloneType, + j.viewAs[V10].cloneType + ) }, - { - case ((a, b, c, d, e, f, g, h, i, j), hwt) => - Seq( - a.viewAs[V1] -> hwt._1, - b.viewAs[V2] -> hwt._2, - c.viewAs[V3] -> hwt._3, - d.viewAs[V4] -> hwt._4, - e.viewAs[V5] -> hwt._5, - f.viewAs[V6] -> hwt._6, - g.viewAs[V7] -> hwt._7, - h.viewAs[V8] -> hwt._8, - i.viewAs[V9] -> hwt._9, - j.viewAs[V10] -> hwt._10 - ) + { case ((a, b, c, d, e, f, g, h, i, j), hwt) => + Seq( + a.viewAs[V1] -> hwt._1, + b.viewAs[V2] -> hwt._2, + c.viewAs[V3] -> hwt._3, + d.viewAs[V4] -> hwt._4, + e.viewAs[V5] -> hwt._5, + f.viewAs[V6] -> hwt._6, + g.viewAs[V7] -> hwt._7, + h.viewAs[V8] -> hwt._8, + i.viewAs[V9] -> hwt._9, + j.viewAs[V10] -> hwt._10 + ) } ) } @@ -572,13 +555,12 @@ object PartialDataView { ): DataView[T, V] = mapping[T, V]( mkView, - { - case (a, b) => - val aElts = a._elements - val bElts = b._elements - val bKeys = bElts.keySet - val keys = aElts.keysIterator.filter(bKeys.contains) - keys.map(k => aElts(k) -> bElts(k)).toSeq + { case (a, b) => + val aElts = a._elements + val bElts = b._elements + val bKeys = bElts.keySet + val keys = aElts.keysIterator.filter(bKeys.contains) + keys.map(k => aElts(k) -> bElts(k)).toSeq } ) } diff --git a/core/src/main/scala/chisel3/experimental/dataview/package.scala b/core/src/main/scala/chisel3/experimental/dataview/package.scala index 6e8b0320094..b5c911fd5cb 100644 --- a/core/src/main/scala/chisel3/experimental/dataview/package.scala +++ b/core/src/main/scala/chisel3/experimental/dataview/package.scala @@ -196,7 +196,7 @@ package object dataview { } getMatchedFields(aa, ba).foreach { case (aelt: Element, belt: Element) => onElt(aelt, belt) - case (t, v) => aggregateMappings += (v -> t) + case (t, v) => aggregateMappings += (v -> t) } } @@ -206,19 +206,18 @@ package object dataview { val targetSeen: Option[mutable.Set[Data]] = if (total) Some(mutable.Set.empty[Data]) else None - val elementResult = elementBindings.map { - case (data, targets) => - val targetsx = targets match { - case collection.Seq(target: Element) => target - case collection.Seq() => - viewNonTotalErrors = data :: viewNonTotalErrors - data.asInstanceOf[Element] // Return the Data itself, will error after this map, cast is safe - case x => - throw InvalidViewException(s"Got $x, expected Seq(_: Direct)") - } - // TODO record and report aliasing errors - targetSeen.foreach(_ += targetsx) - data -> targetsx + val elementResult = elementBindings.map { case (data, targets) => + val targetsx = targets match { + case collection.Seq(target: Element) => target + case collection.Seq() => + viewNonTotalErrors = data :: viewNonTotalErrors + data.asInstanceOf[Element] // Return the Data itself, will error after this map, cast is safe + case x => + throw InvalidViewException(s"Got $x, expected Seq(_: Direct)") + } + // TODO record and report aliasing errors + targetSeen.foreach(_ += targetsx) + data -> targetsx }.toMap // Check for totality of Target @@ -319,13 +318,12 @@ package object dataview { case Some(vb @ AggregateViewBinding(lookup, _)) => lookup.get(data).map(_ -> vb.lookupWritability(data)) case Some(_) => Some(data -> ViewWriteability.Default) } - candidate.flatMap { - case (d, wr) => - val wrx = wrAcc.combine(wr) - // This cast is safe by construction, we only put Data in the view mapping if it is an identity mapping. - val cast = d.asInstanceOf[T] - // Candidate may itself be a view, keep tracing in those cases. - if (isView(d)) reifyIdentityView(cast, wrx) else Some(cast -> wrx) + candidate.flatMap { case (d, wr) => + val wrx = wrAcc.combine(wr) + // This cast is safe by construction, we only put Data in the view mapping if it is an identity mapping. + val cast = d.asInstanceOf[T] + // Candidate may itself be a view, keep tracing in those cases. + if (isView(d)) reifyIdentityView(cast, wrx) else Some(cast -> wrx) } } diff --git a/core/src/main/scala/chisel3/experimental/hierarchy/InstantiableClone.scala b/core/src/main/scala/chisel3/experimental/hierarchy/InstantiableClone.scala index d6aeef7ddcc..ac870059410 100644 --- a/core/src/main/scala/chisel3/experimental/hierarchy/InstantiableClone.scala +++ b/core/src/main/scala/chisel3/experimental/hierarchy/InstantiableClone.scala @@ -7,6 +7,6 @@ import chisel3.experimental.BaseModule /** @note If we are cloning a non-module, we need another object which has the proper _parent set! */ trait InstantiableClone[T <: IsInstantiable] extends core.IsClone[T] { - private[chisel3] def _innerContext: Hierarchy[_] + private[chisel3] def _innerContext: Hierarchy[_] private[chisel3] def getInnerContext: Option[BaseModule] = _innerContext.getInnerDataContext } diff --git a/core/src/main/scala/chisel3/experimental/hierarchy/core/Definition.scala b/core/src/main/scala/chisel3/experimental/hierarchy/core/Definition.scala index 7f584963877..efd921c85b4 100644 --- a/core/src/main/scala/chisel3/experimental/hierarchy/core/Definition.scala +++ b/core/src/main/scala/chisel3/experimental/hierarchy/core/Definition.scala @@ -138,5 +138,5 @@ object Definition extends SourceInfoDoc { */ case class ImportDefinitionAnnotation[T <: BaseModule with IsInstantiable]( definition: Definition[T], - overrideDefName: Option[String] = None) - extends NoTargetAnnotation + overrideDefName: Option[String] = None +) extends NoTargetAnnotation diff --git a/core/src/main/scala/chisel3/experimental/hierarchy/core/Hierarchy.scala b/core/src/main/scala/chisel3/experimental/hierarchy/core/Hierarchy.scala index a3d212f0543..843e81a2e5f 100644 --- a/core/src/main/scala/chisel3/experimental/hierarchy/core/Hierarchy.scala +++ b/core/src/main/scala/chisel3/experimental/hierarchy/core/Hierarchy.scala @@ -18,7 +18,7 @@ import scala.annotation.implicitNotFound sealed trait Hierarchy[+A] { private[chisel3] def underlying: Underlying[A] private[chisel3] def proto: A = underlying match { - case Proto(value) => value + case Proto(value) => value case Clone(i: IsClone[A]) => i.getProto } diff --git a/core/src/main/scala/chisel3/experimental/hierarchy/core/Instance.scala b/core/src/main/scala/chisel3/experimental/hierarchy/core/Instance.scala index ebacfee5a95..934fa8a8197 100644 --- a/core/src/main/scala/chisel3/experimental/hierarchy/core/Instance.scala +++ b/core/src/main/scala/chisel3/experimental/hierarchy/core/Instance.scala @@ -23,24 +23,24 @@ final case class Instance[+A] private[chisel3] (private[chisel3] val underlying: extends SealedHierarchy[A] { underlying match { case Proto(p: IsClone[_]) => chisel3.internal.throwException("Cannot have a Proto with a clone!") - case other => //Ok + case other => // Ok } /** @return the context of any Data's return from inside the instance */ private[chisel3] def getInnerDataContext: Option[BaseModule] = underlying match { - case Proto(value: BaseModule) => Some(value) - case Proto(value: IsInstantiable) => None - case Clone(i: BaseModule) => Some(i) + case Proto(value: BaseModule) => Some(value) + case Proto(value: IsInstantiable) => None + case Clone(i: BaseModule) => Some(i) case Clone(i: InstantiableClone[_]) => i.getInnerContext - case _ => throw new InternalErrorException(s"Match error: underlying=$underlying") + case _ => throw new InternalErrorException(s"Match error: underlying=$underlying") } /** @return the context this instance. Note that for non-module clones, getInnerDataContext will be the same as getClonedParent */ private[chisel3] def getClonedParent: Option[BaseModule] = underlying match { - case Proto(value: BaseModule) => value._parent - case Clone(i: BaseModule) => i._parent + case Proto(value: BaseModule) => value._parent + case Clone(i: BaseModule) => i._parent case Clone(i: InstantiableClone[_]) => i.getInnerContext - case _ => throw new InternalErrorException(s"Match error: underlying=$underlying") + case _ => throw new InternalErrorException(s"Match error: underlying=$underlying") } /** Used by Chisel's internal macros. DO NOT USE in your normal Chisel code!!! @@ -81,7 +81,7 @@ object Instance extends SourceInfoDoc { * @return target of this instance */ def toTarget: IsModule = i.underlying match { - case Proto(x: BaseModule) => x.getTarget + case Proto(x: BaseModule) => x.getTarget case Clone(x: IsClone[_] with BaseModule) => x.getTarget case _ => throw new InternalErrorException(s"Match error: i.underlying=${i.underlying}") } @@ -90,7 +90,7 @@ object Instance extends SourceInfoDoc { * @return absoluteTarget of this instance */ def toAbsoluteTarget: IsModule = i.underlying match { - case Proto(x) => x.toAbsoluteTarget + case Proto(x) => x.toAbsoluteTarget case Clone(x: IsClone[_] with BaseModule) => x.toAbsoluteTarget case _ => throw new InternalErrorException(s"Match error: i.underlying=${i.underlying}") } @@ -106,21 +106,21 @@ object Instance extends SourceInfoDoc { * @note This doesn't have special handling for Views. */ def toRelativeTarget(root: Option[BaseModule]): IsModule = i.underlying match { - case Proto(x) => x.toRelativeTarget(root) + case Proto(x) => x.toRelativeTarget(root) case Clone(x: IsClone[_] with BaseModule) => x.toRelativeTarget(root) case _ => throw new InternalErrorException(s"Match error: i.underlying=${i.underlying}") } def toRelativeTargetToHierarchy(root: Option[Hierarchy[BaseModule]]): IsModule = i.underlying match { - case Proto(x) => x.toRelativeTargetToHierarchy(root) + case Proto(x) => x.toRelativeTargetToHierarchy(root) case Clone(x: IsClone[_] with BaseModule) => x.toRelativeTargetToHierarchy(root) case _ => throw new InternalErrorException(s"Match error: i.underlying=${i.underlying}") } def suggestName(name: String): Unit = i.underlying match { case Clone(m: BaseModule) => m.suggestName(name) - case Proto(m) => m.suggestName(name) - case x => Builder.exception(s"Cannot call .suggestName on $x")(UnlocatableSourceInfo) + case Proto(m) => m.suggestName(name) + case x => Builder.exception(s"Cannot call .suggestName on $x")(UnlocatableSourceInfo) } } @@ -158,9 +158,8 @@ object Instance extends SourceInfoDoc { override def generateComponent(): Option[Component] = { require(!_closed, s"Can't generate $desiredName module more than once") _closed = true - val firrtlPorts = definition.proto.getModulePortsAndLocators.map { - case (port, sourceInfo) => - Port(port, port.specifiedDirection, sourceInfo): @nowarn // Deprecated code allowed for internal use + val firrtlPorts = definition.proto.getModulePortsAndLocators.map { case (port, sourceInfo) => + Port(port, port.specifiedDirection, sourceInfo): @nowarn // Deprecated code allowed for internal use } val component = DefBlackBox(this, definition.proto.name, firrtlPorts, SpecifiedDirection.Unspecified, params) Some(component) diff --git a/core/src/main/scala/chisel3/experimental/hierarchy/core/Lookupable.scala b/core/src/main/scala/chisel3/experimental/hierarchy/core/Lookupable.scala index d5a25367788..d0792364662 100644 --- a/core/src/main/scala/chisel3/experimental/hierarchy/core/Lookupable.scala +++ b/core/src/main/scala/chisel3/experimental/hierarchy/core/Lookupable.scala @@ -56,8 +56,8 @@ trait Lookupable[-B] { * @return */ def definitionLookup[A](that: A => B, definition: Definition[A]): C - protected def getProto[A](h: Hierarchy[A]): A = h.proto - protected def getUnderlying[A](h: Hierarchy[A]): Underlying[A] = h.underlying + protected def getProto[A](h: Hierarchy[A]): A = h.proto + protected def getUnderlying[A](h: Hierarchy[A]): Underlying[A] = h.underlying // Single method that may eventually replace instanceLookup and definitionLookup. private[chisel3] def hierarchyLookup[A](that: A => B, hierarchy: Hierarchy[A]): C = { @@ -231,7 +231,7 @@ object Lookupable { } data.binding match { case Some(_: ChildBinding) => mapRootAndExtractSubField(data, impl) - case _ => impl(data) + case _ => impl(data) } } @@ -255,7 +255,7 @@ object Lookupable { * Invariants that elt is a Child of something of the type of data is dynamically checked as we traverse */ private def mapRootAndExtractSubField[A <: Data](arg: A, f: Data => Data): A = { - def err(msg: String) = throwException(s"Internal Error! $msg") + def err(msg: String) = throwException(s"Internal Error! $msg") def unrollCoordinates(res: List[Arg], d: Data): (List[Arg], Data) = d.binding.get match { case ChildBinding(parent) => d.getRef match { @@ -269,11 +269,11 @@ object Lookupable { if (coor.isEmpty) d else { val next = (coor.head, d) match { - case (Slot(_, name), rec: Record) => rec._elements(name) - case (LitIndex(_, n), vec: Vec[_]) => vec.apply(n) + case (Slot(_, name), rec: Record) => rec._elements(name) + case (LitIndex(_, n), vec: Vec[_]) => vec.apply(n) case (Index(_, ILit(n)), vec: Vec[_]) => vec.apply(n.toInt) case (ModuleIO(_, name), rec: Record) => rec._elements(name) - case (arg, _) => err(s"Unexpected Arg '$arg' applied to '$d'! Root was '$start'.") + case (arg, _) => err(s"Unexpected Arg '$arg' applied to '$d'! Root was '$start'.") } applyCoordinates(coor.tail, next) } @@ -321,8 +321,8 @@ object Lookupable { // faster to just use it but then call reifyIdentityView in case the target is itself a view def reifyOpt(data: Data): Option[(Data, ViewWriteability)] = map.get(data).flatMap(reifyIdentityView(_)) // Just remap each Data present in the map - val mapping = coiterate(result, data).flatMap { - case (res, from) => reifyOpt(from).map { case (t, w) => (res, lookupData(t), w) } + val mapping = coiterate(result, data).flatMap { case (res, from) => + reifyOpt(from).map { case (t, w) => (res, lookupData(t), w) } } val newMap = mapping.map { case (from, to, _) => from -> to }.toMap val wrMap = mapping.flatMap { case (from, _, wr) => Option.when(wr.isReadOnly)(from -> wr) }.toMap @@ -377,9 +377,9 @@ object Lookupable { Clone(newChild) } (m, context) match { - case (c, ctx) if ctx == c => Proto(c) + case (c, ctx) if ctx == c => Proto(c) case (c, ctx: IsClone[_]) if ctx.hasSameProto(c) => Clone(ctx.asInstanceOf[IsClone[A]]) - case (c, ctx) if c._parent.isEmpty => Proto(c) + case (c, ctx) if c._parent.isEmpty => Proto(c) case (_, _) => cloneModuleToContext(Proto(m._parent.get), context) match { case Proto(p) => Proto(m) @@ -478,9 +478,9 @@ object Lookupable { def getIoMap(hierarchy: Hierarchy[_]): Option[Map[Data, Data]] = { hierarchy.underlying match { case Clone(x: ModuleClone[_]) => Some(x.ioMap) - case Proto(x: BaseModule) => Some(x.getChiselPorts.map { case (_, data: Data) => data -> data }.toMap) + case Proto(x: BaseModule) => Some(x.getChiselPorts.map { case (_, data: Data) => data -> data }.toMap) case Clone(x: InstantiableClone[_]) => getIoMap(x._innerContext) - case Clone(x: InstanceClone[_]) => None + case Clone(x: InstanceClone[_]) => None case other => { Builder.exception(s"Internal Error! Unexpected case where we can't get IO Map: $other") } diff --git a/core/src/main/scala/chisel3/experimental/package.scala b/core/src/main/scala/chisel3/experimental/package.scala index b8e47563ba2..2b8a24aa36e 100644 --- a/core/src/main/scala/chisel3/experimental/package.scala +++ b/core/src/main/scala/chisel3/experimental/package.scala @@ -189,10 +189,7 @@ package object experimental { * Users may not instantiate this class directly. Instead they should use the implicit conversion from `Tuple3` in * `chisel3.experimental.conversions` */ - final class HWTuple3[+A <: Data, +B <: Data, +C <: Data] private[chisel3] ( - val _1: A, - val _2: B, - val _3: C) + final class HWTuple3[+A <: Data, +B <: Data, +C <: Data] private[chisel3] (val _1: A, val _2: B, val _3: C) extends Bundle() { // Because this implementation exists in chisel3.core, it cannot compile with the plugin, so we implement the behavior manually override protected def _usingPlugin: Boolean = true @@ -217,8 +214,8 @@ package object experimental { val _1: A, val _2: B, val _3: C, - val _4: D) - extends Bundle() { + val _4: D + ) extends Bundle() { // Because this implementation exists in chisel3.core, it cannot compile with the plugin, so we implement the behavior manually override protected def _usingPlugin: Boolean = true override protected def _cloneTypeImpl: Bundle = new HWTuple4( @@ -245,8 +242,8 @@ package object experimental { val _2: B, val _3: C, val _4: D, - val _5: E) - extends Bundle() { + val _5: E + ) extends Bundle() { // Because this implementation exists in chisel3.core, it cannot compile with the plugin, so we implement the behavior manually override protected def _usingPlugin: Boolean = true override protected def _cloneTypeImpl: Bundle = new HWTuple5( @@ -276,8 +273,8 @@ package object experimental { val _3: C, val _4: D, val _5: E, - val _6: F) - extends Bundle() { + val _6: F + ) extends Bundle() { // Because this implementation exists in chisel3.core, it cannot compile with the plugin, so we implement the behavior manually override protected def _usingPlugin: Boolean = true override protected def _cloneTypeImpl: Bundle = new HWTuple6( @@ -311,14 +308,7 @@ package object experimental { +E <: Data, +F <: Data, +G <: Data - ] private[chisel3] ( - val _1: A, - val _2: B, - val _3: C, - val _4: D, - val _5: E, - val _6: F, - val _7: G) + ] private[chisel3] (val _1: A, val _2: B, val _3: C, val _4: D, val _5: E, val _6: F, val _7: G) extends Bundle() { // Because this implementation exists in chisel3.core, it cannot compile with the plugin, so we implement the behavior manually override protected def _usingPlugin: Boolean = true @@ -356,15 +346,7 @@ package object experimental { +F <: Data, +G <: Data, +H <: Data - ] private[chisel3] ( - val _1: A, - val _2: B, - val _3: C, - val _4: D, - val _5: E, - val _6: F, - val _7: G, - val _8: H) + ] private[chisel3] (val _1: A, val _2: B, val _3: C, val _4: D, val _5: E, val _6: F, val _7: G, val _8: H) extends Bundle() { // Because this implementation exists in chisel3.core, it cannot compile with the plugin, so we implement the behavior manually override protected def _usingPlugin: Boolean = true @@ -405,16 +387,7 @@ package object experimental { +G <: Data, +H <: Data, +I <: Data - ] private[chisel3] ( - val _1: A, - val _2: B, - val _3: C, - val _4: D, - val _5: E, - val _6: F, - val _7: G, - val _8: H, - val _9: I) + ] private[chisel3] (val _1: A, val _2: B, val _3: C, val _4: D, val _5: E, val _6: F, val _7: G, val _8: H, val _9: I) extends Bundle() { // Because this implementation exists in chisel3.core, it cannot compile with the plugin, so we implement the behavior manually override protected def _usingPlugin: Boolean = true @@ -468,8 +441,8 @@ package object experimental { val _7: G, val _8: H, val _9: I, - val _10: J) - extends Bundle() { + val _10: J + ) extends Bundle() { // Because this implementation exists in chisel3.core, it cannot compile with the plugin, so we implement the behavior manually override protected def _usingPlugin: Boolean = true override protected def _cloneTypeImpl: Bundle = new HWTuple10( diff --git a/core/src/main/scala/chisel3/internal/BiConnect.scala b/core/src/main/scala/chisel3/internal/BiConnect.scala index 9e54b29caf9..914a0c40125 100644 --- a/core/src/main/scala/chisel3/internal/BiConnect.scala +++ b/core/src/main/scala/chisel3/internal/BiConnect.scala @@ -310,7 +310,7 @@ private[chisel3] object BiConnect { // do not bulk connect the 'io' pseudo-bundle of a BlackBox since it will be decomposed in FIRRTL def blackBoxCheck = Seq(source, sink).map(_._parent).forall { case Some(_: BlackBox) => false - case _ => true + case _ => true } typeCheck && contextCheck && bindingCheck && flowSinkCheck && flowSourceCheck && sourceAndSinkNotLiteralOrViewCheck && blackBoxCheck diff --git a/core/src/main/scala/chisel3/internal/Binding.scala b/core/src/main/scala/chisel3/internal/Binding.scala index efbda453759..55b4ff9c3c1 100644 --- a/core/src/main/scala/chisel3/internal/Binding.scala +++ b/core/src/main/scala/chisel3/internal/Binding.scala @@ -58,7 +58,7 @@ private[chisel3] object binding { // Location will track where this Module is, and the bound object can be referenced in FIRRTL sealed trait ConstrainedBinding extends TopBinding { def enclosure: BaseModule - def location: Option[BaseModule] = Some(enclosure) + def location: Option[BaseModule] = Some(enclosure) } // A binding representing a data that cannot be (re)assigned to. @@ -180,9 +180,7 @@ private[chisel3] object binding { * @note The types of key and value need not match for the top Data in a total view of type * Aggregate */ - case class AggregateViewBinding( - childMap: Map[Data, Data], - writabilityMap: Option[Map[Data, ViewWriteability]]) + case class AggregateViewBinding(childMap: Map[Data, Data], writabilityMap: Option[Map[Data, ViewWriteability]]) extends Binding with BlockBinding { // Helper lookup function since types of Elements always match @@ -198,7 +196,7 @@ private[chisel3] object binding { key, { key.binding match { case Some(ChildBinding(parent)) => rec(map, parent) - case _ => throwException(s"Internal error! $key not found in AggregateViewBinding writabilityMap!") + case _ => throwException(s"Internal error! $key not found in AggregateViewBinding writabilityMap!") } } ) diff --git a/core/src/main/scala/chisel3/internal/Builder.scala b/core/src/main/scala/chisel3/internal/Builder.scala index 3f93f9b6334..f5ff2bd25f3 100644 --- a/core/src/main/scala/chisel3/internal/Builder.scala +++ b/core/src/main/scala/chisel3/internal/Builder.scala @@ -102,7 +102,7 @@ private[chisel3] object Namespace { /** Constructs an empty Namespace */ def empty(separator: Char): Namespace = new Namespace(Set.empty[String], separator) - def empty: Namespace = new Namespace(Set.empty[String]) + def empty: Namespace = new Namespace(Set.empty[String]) } private[chisel3] class IdGen { @@ -125,7 +125,7 @@ private[chisel3] trait HasId extends chisel3.InstanceId { private[chisel3] val _id: Long = Builder.idGen.next // TODO: remove this, but its removal seems to cause a nasty Scala compiler crash. - override def hashCode: Int = super.hashCode() + override def hashCode: Int = super.hashCode() override def equals(that: Any): Boolean = super.equals(that) // Did the user suggest a name? This overrides names suggested by the compiler plugin. @@ -252,8 +252,8 @@ private[chisel3] trait HasId extends chisel3.InstanceId { naming_prefix = Nil } - private var _refVar: Arg = null // using nullable var for better memory usage - private def _ref: Option[Arg] = Option(_refVar) + private var _refVar: Arg = null // using nullable var for better memory usage + private def _ref: Option[Arg] = Option(_refVar) private[chisel3] def setRef(imm: Arg): Unit = setRef(imm, false) private[chisel3] def setRef(imm: Arg, force: Boolean): Unit = { if (_ref.isEmpty || force) { @@ -314,9 +314,9 @@ private[chisel3] trait HasId extends chisel3.InstanceId { case Some(ViewParent) => reifyTarget.map(_.instanceName).getOrElse(this.refName(ViewParent.fakeComponent)) case Some(p) => (p._component, this) match { - case (Some(c), _) => refName(c) + case (Some(c), _) => refName(c) case (None, d: Data) if d.topBindingOpt == Some(CrossModuleBinding) => _ref.get.localName - case (None, _: MemBase[_]) => _ref.get.localName + case (None, _: MemBase[_]) => _ref.get.localName case (None, _) if _ref.isDefined => { // Support instance names for HasIds that don't have a _parent set yet, but do have a _ref set. // This allows HasIds to be named in atModuleBodyEnd, for example. @@ -447,7 +447,7 @@ private[chisel3] trait NamedComponent extends HasId { val isVecSubaccess = getOptionRef.map { case Index(_, _: ULit) => true // Vec literal indexing case Index(_, _: Node) => true // Vec dynamic indexing - case _ => false + case _ => false }.getOrElse(false) if (isVecSubaccess) { @@ -489,7 +489,8 @@ private[chisel3] class DynamicContext( val loggerOptions: LoggerOptions, val definitions: ArrayBuffer[Definition[_]], val contextCache: BuilderContextCache, - val layerMap: Map[layer.Layer, layer.Layer]) { + val layerMap: Map[layer.Layer, layer.Layer] +) { val importedDefinitionAnnos = annotationSeq.collect { case a: ImportDefinitionAnnotation[_] => a } // Map from proto module name to ext-module name @@ -660,8 +661,8 @@ private[chisel3] object Builder extends LazyLogging { case Index(_, ILit(n)) => Some(n.toString) // Vec static indexing case LitIndex(_, n) => Some(n.toString) // Vec static indexing case Index(_, ULit(n, _)) => Some(n.toString) // Vec lit indexing - case Index(_, _: Node) => None // Vec dynamic indexing - case ModuleIO(_, n) => Some(n) // BlackBox port + case Index(_, _: Node) => None // Vec dynamic indexing + case ModuleIO(_, n) => Some(n) // BlackBox port case f => throw new InternalErrorException(s"Match Error: field=$f") } @@ -678,8 +679,8 @@ private[chisel3] object Builder extends LazyLogging { case SampleElementBinding(parent) => recData(parent) case PortBinding(mod) if Builder.currentModule.contains(mod) => data.seedOpt case PortBinding(mod) => map2(mod.seedOpt, data.seedOpt)(_ + "_" + _) - case (_: LitBinding | _: DontCareBinding) => None - case _ => Some("view_") // TODO implement + case (_: LitBinding | _: DontCareBinding) => None + case _ => Some("view_") // TODO implement } id match { case d: Data => recData(d) @@ -754,7 +755,7 @@ private[chisel3] object Builder extends LazyLogging { def referenceUserContainer: BaseModule = { currentModule match { case Some(module: RawModule) => module - case Some(cls: Class) => cls + case Some(cls: Class) => cls case _ => throwException( "Error: Not in a RawModule or Class. Likely cause: Missed Module() or Definition() wrap, bare chisel API call, or attempting to construct hardware inside a BlackBox." @@ -917,7 +918,7 @@ private[chisel3] object Builder extends LazyLogging { case (id: Instance[_]) => id.underlying match { case Clone(m: experimental.hierarchy.ModuleClone[_]) => namer(m.getPorts, prefix) - case _ => + case _ => } case (d: Data) => // Views are often returned in lieu of the target, so name the target (as appropriate). @@ -932,11 +933,10 @@ private[chisel3] object Builder extends LazyLogging { nameRecursively(s"${prefix}_${i}", elt, namer) } case product: Product => - product.productIterator.zip(product.productElementNames).foreach { - case (elt, fullName) => - val name = fullName.stripPrefix("_") - val prefixedName = if (name.nonEmpty) s"${prefix}_${name}" else prefix - nameRecursively(prefixedName, elt, namer) + product.productIterator.zip(product.productElementNames).foreach { case (elt, fullName) => + val name = fullName.stripPrefix("_") + val prefixedName = if (name.nonEmpty) s"${prefix}_${name}" else prefix + nameRecursively(prefixedName, elt, namer) } case disable: Disable => nameRecursively(prefix, disable.value, namer) case _ => // Do nothing @@ -1047,7 +1047,7 @@ private[chisel3] object Builder extends LazyLogging { // Conflict found: error( s"Attempted to redeclare an existing type alias '$alias' with a new Record structure:\n'$tpe'.\n\nThe alias was previously defined as:\n'${recordValue._1}${recordValue._2 - .makeMessage(" " + _)}" + .makeMessage(" " + _)}" )(sourceInfo) None @@ -1106,7 +1106,7 @@ private[chisel3] object Builder extends LazyLogging { val typeAliases = aliasMap.flatMap { case (name, (underlying: fir.Type, info: SourceInfo)) => Some(DefTypeAlias(info, underlying, name)) - case _ => None + case _ => None }.toSeq /** Stores an adjacency list representation of layers. Connections indicating children. */ @@ -1133,13 +1133,12 @@ private[chisel3] object Builder extends LazyLogging { Layer(l.sourceInfo, l.name, config, children.map(foldLayers).toSeq, l) } - val optionDefs = groupByIntoSeq(options)(opt => opt.group).map { - case (optGroup, cases) => - DefOption( - optGroup.sourceInfo, - optGroup.name, - cases.map(optCase => DefOptionCase(optCase.sourceInfo, optCase.name)) - ) + val optionDefs = groupByIntoSeq(options)(opt => opt.group).map { case (optGroup, cases) => + DefOption( + optGroup.sourceInfo, + optGroup.name, + cases.map(optCase => DefOptionCase(optCase.sourceInfo, optCase.name)) + ) } // Make the main module (the last component) public if this is not a @@ -1189,10 +1188,9 @@ private[chisel3] object Builder extends LazyLogging { val ctx = chiselContext.get() val modulePrefixStack = ctx.modulePrefixStack val sep = ctx.modulePrefixSeperator - modulePrefixStack.foldLeft("") { - case (acc, (elt, useSep)) => - val s = if (useSep) sep else "" - elt + s + acc + modulePrefixStack.foldLeft("") { case (acc, (elt, useSep)) => + val s = if (useSep) sep else "" + elt + s + acc } } diff --git a/core/src/main/scala/chisel3/internal/CIRCTPassManager.scala b/core/src/main/scala/chisel3/internal/CIRCTPassManager.scala index c534ca47157..4520c9e36c2 100644 --- a/core/src/main/scala/chisel3/internal/CIRCTPassManager.scala +++ b/core/src/main/scala/chisel3/internal/CIRCTPassManager.scala @@ -4,13 +4,13 @@ package chisel3.internal @deprecated("There no CIRCTPassManager anymore, use circtpanamaconverter directly", "Chisel 6.0") abstract class CIRCTPassManager { - def populatePreprocessTransforms(): Boolean - def populateCHIRRTLToLowFIRRTL(): Boolean - def populateLowFIRRTLToHW(): Boolean - def populateLowHWToSV(): Boolean + def populatePreprocessTransforms(): Boolean + def populateCHIRRTLToLowFIRRTL(): Boolean + def populateLowFIRRTLToHW(): Boolean + def populateLowHWToSV(): Boolean def populateExportVerilog(callback: String => Unit): Boolean def populateExportSplitVerilog(directory: String): Boolean - def populateFinalizeIR(): Boolean + def populateFinalizeIR(): Boolean def run(): Boolean; } diff --git a/core/src/main/scala/chisel3/internal/Error.scala b/core/src/main/scala/chisel3/internal/Error.scala index f9708ad8652..13c6f35008a 100644 --- a/core/src/main/scala/chisel3/internal/Error.scala +++ b/core/src/main/scala/chisel3/internal/Error.scala @@ -119,7 +119,8 @@ object ExceptionHelpers { private[chisel3] case class WarningFilter( src: Option[PathMatcher], id: Option[WarningID.WarningID], - action: WarningFilter.Action) { + action: WarningFilter.Action +) { /** Does this filter apply to the warning? */ def applies(warning: Warning): Boolean = { @@ -149,7 +150,7 @@ private[chisel3] object WarningFilter { private def categoryOneOf = "must be one of 'any', 'src', or 'id'." // TODO find a better way to deal with line and column - private def srcGlobDefault(base: String): String = base //s"**/$base" + private def srcGlobDefault(base: String): String = base // s"**/$base" /** Parse a String into a [[WarningFilter]] * @@ -273,7 +274,8 @@ private[chisel3] object ErrorLog { private[chisel3] class ErrorLog( warningFilters: Seq[WarningFilter], sourceRoots: Seq[File], - throwOnFirstError: Boolean) { + throwOnFirstError: Boolean +) { import ErrorLog.withColor /** Returns an appropriate location string for the provided source info. @@ -282,9 +284,9 @@ private[chisel3] class ErrorLog( */ private def errorLocationString(si: Option[SourceInfo]): String = { si match { - case Some(sl: SourceLine) => sl.serialize + case Some(sl: SourceLine) => sl.serialize case Some(_: NoSourceInfo) => "(unknown)" - case None => "" + case None => "" } } @@ -344,9 +346,8 @@ private[chisel3] class ErrorLog( case _ => } - deprecations.foreach { - case ((message, sourceLoc), count) => - logger.warn(s"${ErrorLog.depTag} $sourceLoc ($count calls): $message") + deprecations.foreach { case ((message, sourceLoc), count) => + logger.warn(s"${ErrorLog.depTag} $sourceLoc ($count calls): $message") } errors.foreach(e => logger.error(e.serialize(includeTag = true))) diff --git a/core/src/main/scala/chisel3/internal/firrtl/Converter.scala b/core/src/main/scala/chisel3/internal/firrtl/Converter.scala index 0ebe910c649..81db0111c61 100644 --- a/core/src/main/scala/chisel3/internal/firrtl/Converter.scala +++ b/core/src/main/scala/chisel3/internal/firrtl/Converter.scala @@ -353,7 +353,7 @@ private[chisel3] object Converter { case t: EnumType => fir.UIntType(convert(t.width)) case t: UInt => fir.UIntType(convert(t.width)) case t: SInt => fir.SIntType(convert(t.width)) - case t: Analog => fir.AnalogType(convert(t.width)) + case t: Analog => fir.AnalogType(convert(t.width)) case t: Vec[_] => val childClearDir = clearDir || t.specifiedDirection == SpecifiedDirection.Input || t.specifiedDirection == SpecifiedDirection.Output diff --git a/core/src/main/scala/chisel3/internal/firrtl/IR.scala b/core/src/main/scala/chisel3/internal/firrtl/IR.scala index dd2ae4816f9..0078fccc581 100644 --- a/core/src/main/scala/chisel3/internal/firrtl/IR.scala +++ b/core/src/main/scala/chisel3/internal/firrtl/IR.scala @@ -7,7 +7,7 @@ import chisel3._ import chisel3.internal._ import chisel3.internal.binding._ import chisel3.experimental._ -import chisel3.properties.{Property, PropertyType => PropertyTypeclass, Class, DynamicObject} +import chisel3.properties.{Class, DynamicObject, Property, PropertyType => PropertyTypeclass} import _root_.firrtl.{ir => firrtlir} import _root_.firrtl.{PrimOps, RenameMap} import _root_.firrtl.annotations.Annotation @@ -70,10 +70,10 @@ private[chisel3] object ir { } sealed abstract class Arg { - def localName: String = name + def localName: String = name def contextualName(ctx: Component): String = name def fullName(ctx: Component): String = contextualName(ctx) - def name: String + def name: String } case class Node(id: HasId) extends Arg { @@ -117,7 +117,7 @@ private[chisel3] object ir { abstract class LitArg(val num: BigInt, widthArg: Width) extends Arg { def forcedWidth = widthArg.known - def width: Width = if (forcedWidth) widthArg else Width(minWidth) + def width: Width = if (forcedWidth) widthArg else Width(minWidth) override def contextualName(ctx: Component): String = name // Ensure the node representing this LitArg has a ref to it and a literal binding. def bindLitArg[T <: Element](elem: T): T = { @@ -184,12 +184,10 @@ private[chisel3] object ir { * * These are not LitArgs, because not all property literals are integers. */ - case class PropertyLit[T, U]( - propertyType: PropertyTypeclass[_] { type Underlying = U; type Type = T }, - lit: U) + case class PropertyLit[T, U](propertyType: PropertyTypeclass[_] { type Underlying = U; type Type = T }, lit: U) extends Arg { - def name: String = s"PropertyLit($lit)" - def minWidth: Int = 0 + def name: String = s"PropertyLit($lit)" + def minWidth: Int = 0 def cloneWithWidth(newWidth: Width): this.type = PropertyLit(propertyType, lit).asInstanceOf[this.type] /** Expose a bindLitArg API for PropertyLit, similar to LitArg. @@ -247,20 +245,20 @@ private[chisel3] object ir { case class OpaqueSlot(imm: Node) extends Arg { override def contextualName(ctx: Component): String = imm.contextualName(ctx) - override def name: String = imm.name + override def name: String = imm.name } case class Index(imm: Arg, value: Arg) extends Arg { - def name: String = s"[$value]" + def name: String = s"[$value]" override def contextualName(ctx: Component): String = s"${imm.contextualName(ctx)}[${value.contextualName(ctx)}]" - override def localName: String = s"${imm.localName}[${value.localName}]" + override def localName: String = s"${imm.localName}[${value.localName}]" } // Like index above, except the index is a literal, used for elements of Vecs case class LitIndex(imm: Arg, value: Int) extends Arg { - def name: String = s"[$value]" + def name: String = s"[$value]" override def contextualName(ctx: Component): String = s"${imm.contextualName(ctx)}[$value]" - override def localName: String = s"${imm.localName}[$value]" + override def localName: String = s"${imm.localName}[$value]" } sealed trait ProbeDetails { this: Arg => @@ -286,7 +284,7 @@ private[chisel3] object ir { } abstract class Definition extends Command { - def id: HasId + def id: HasId def name: String = id.getRef.name } @@ -307,8 +305,8 @@ private[chisel3] object ir { id: HasId, t: Data, size: BigInt, - readUnderWrite: fir.ReadUnderWrite.Value) - extends Definition + readUnderWrite: fir.ReadUnderWrite.Value + ) extends Definition case class FirrtlMemory( sourceInfo: SourceInfo, @@ -317,8 +315,8 @@ private[chisel3] object ir { size: BigInt, readPortNames: Seq[String], writePortNames: Seq[String], - readwritePortNames: Seq[String]) - extends Definition + readwritePortNames: Seq[String] + ) extends Definition case class DefMemPort[T <: Data]( sourceInfo: SourceInfo, @@ -326,8 +324,8 @@ private[chisel3] object ir { source: Node, dir: MemPortDirection, index: Arg, - clock: Arg) - extends Definition + clock: Arg + ) extends Definition case class DefInstance(sourceInfo: SourceInfo, id: BaseModule, ports: Seq[Port]) extends Definition case class DefInstanceChoice( @@ -335,8 +333,8 @@ private[chisel3] object ir { id: HasId, default: BaseModule, option: String, - choices: Seq[(String, BaseModule)]) - extends Definition + choices: Seq[(String, BaseModule)] + ) extends Definition case class DefObject(sourceInfo: SourceInfo, id: HasId, className: String) extends Definition class Block(val sourceInfo: SourceInfo) { @@ -429,7 +427,8 @@ private[chisel3] object ir { name: String, config: LayerConfig, children: Seq[Layer], - chiselLayer: layer.Layer) + chiselLayer: layer.Layer + ) class LayerBlock(val sourceInfo: SourceInfo, val layer: chisel3.layer.Layer) extends Command { val region = new Block(sourceInfo) @@ -441,10 +440,7 @@ private[chisel3] object ir { } } - case class DefOption( - sourceInfo: SourceInfo, - name: String, - cases: Seq[DefOptionCase]) + case class DefOption(sourceInfo: SourceInfo, name: String, cases: Seq[DefOptionCase]) case class DefOptionCase(sourceInfo: SourceInfo, name: String) case class Port(id: Data, dir: SpecifiedDirection, sourceInfo: SourceInfo) @@ -469,13 +465,13 @@ private[chisel3] object ir { sourceInfo: SourceInfo, clock: Arg, predicate: Arg, - pable: Printable) - extends Definition + pable: Printable + ) extends Definition abstract class Component extends Arg { - def id: BaseModule - def name: String - def ports: Seq[Port] + def id: BaseModule + def name: String + def ports: Seq[Port] val secretPorts: mutable.ArrayBuffer[Port] = id.secretPorts } @@ -487,32 +483,32 @@ private[chisel3] object ir { isPublic: Boolean, layers: Seq[chisel3.layer.Layer], ports: Seq[Port], - block: Block) - extends Component + block: Block + ) extends Component case class DefBlackBox( id: BaseBlackBox, name: String, ports: Seq[Port], topDir: SpecifiedDirection, - params: Map[String, Param]) - extends Component + params: Map[String, Param] + ) extends Component case class DefIntrinsicModule( id: BaseIntrinsicModule, name: String, ports: Seq[Port], topDir: SpecifiedDirection, - params: Map[String, Param]) - extends Component + params: Map[String, Param] + ) extends Component case class DefIntrinsicExpr[T <: Data]( sourceInfo: SourceInfo, intrinsic: String, id: T, args: Seq[Arg], - params: Seq[(String, Param)]) - extends Definition + params: Seq[(String, Param)] + ) extends Definition case class DefIntrinsic(sourceInfo: SourceInfo, intrinsic: String, args: Seq[Arg], params: Seq[(String, Param)]) extends Command @@ -527,7 +523,8 @@ private[chisel3] object ir { newAnnotations: Seq[ChiselMultiAnnotation], typeAliases: Seq[DefTypeAlias], layers: Seq[Layer], - options: Seq[DefOption]) { + options: Seq[DefOption] + ) { def this( name: String, diff --git a/core/src/main/scala/chisel3/internal/package.scala b/core/src/main/scala/chisel3/internal/package.scala index b022a38866b..b3c96c2398e 100644 --- a/core/src/main/scala/chisel3/internal/package.scala +++ b/core/src/main/scala/chisel3/internal/package.scala @@ -88,8 +88,7 @@ package object internal { that: A, targetWidthOpt: Option[Int], isUInt: Boolean - )(fromUInt: UInt => A - )( + )(fromUInt: UInt => A)( implicit sourceInfo: SourceInfo ): A = { (targetWidthOpt, that.widthOption) match { @@ -206,10 +205,9 @@ package object internal { // TODO this exists in cats.Traverse, should we just use that? private[chisel3] implicit class ListSyntax[A](xs: List[A]) { def mapAccumulate[B, C](z: B)(f: (B, A) => (B, C)): (B, List[C]) = { - val (zz, result) = xs.foldLeft((z, List.empty[C])) { - case ((acc, res), a) => - val (accx, c) = f(acc, a) - (accx, c :: res) + val (zz, result) = xs.foldLeft((z, List.empty[C])) { case ((acc, res), a) => + val (accx, c) = f(acc, a) + (accx, c :: res) } (zz, result.reverse) } diff --git a/core/src/main/scala/chisel3/naming/Identifier.scala b/core/src/main/scala/chisel3/naming/Identifier.scala index 12c1dd3ad36..af71b98df5f 100644 --- a/core/src/main/scala/chisel3/naming/Identifier.scala +++ b/core/src/main/scala/chisel3/naming/Identifier.scala @@ -43,9 +43,9 @@ object IdentifierProposer { // Summons correct IdentifierProposer to generate a proposal def getProposal[T](obj: T): String = { obj match { - case i: HasCustomIdentifier => i.customDefinitionIdentifier // First give precedence to custom identifiers + case i: HasCustomIdentifier => i.customDefinitionIdentifier // First give precedence to custom identifiers case b: chisel3.experimental.BaseModule => b.definitionIdentifier // Then to the one generated by the plugin - case l: Iterable[_] => makeProposal(l.toList.map(getProposal): _*) // Handle iterables automatically + case l: Iterable[_] => makeProposal(l.toList.map(getProposal): _*) // Handle iterables automatically case _ => filterProposal(obj.toString) } } diff --git a/core/src/main/scala/chisel3/package.scala b/core/src/main/scala/chisel3/package.scala index 4f349d76151..9bdf9109808 100644 --- a/core/src/main/scala/chisel3/package.scala +++ b/core/src/main/scala/chisel3/package.scala @@ -266,7 +266,7 @@ package object chisel3 { } - //TODO: Update this to current API when 2.12 is EOL + // TODO: Update this to current API when 2.12 is EOL sc.checkLengths(args) // Enforce sc.parts.size == pargs.size + 1 val parts = sc.parts.map(StringContext.processEscapes) // The 1st part is assumed never to contain a format specifier. @@ -417,8 +417,8 @@ package object chisel3 { // This is only currently used for SRAM to hide the underlying Memory but still let users annotate it. // Rather than generalizing this, it's more likely that we'll just delete it (and the use in SRAM) in favor of Path Properties. sealed trait HasTarget { - def toTarget: ReferenceTarget - def toAbsoluteTarget: ReferenceTarget + def toTarget: ReferenceTarget + def toAbsoluteTarget: ReferenceTarget def toRelativeTarget(root: Option[BaseModule]): ReferenceTarget def toRelativeTargetToHierarchy(root: Option[Hierarchy[BaseModule]]): ReferenceTarget diff --git a/core/src/main/scala/chisel3/probe/PackageImpl.scala b/core/src/main/scala/chisel3/probe/PackageImpl.scala index 6420385e9ff..1424233e932 100644 --- a/core/src/main/scala/chisel3/probe/PackageImpl.scala +++ b/core/src/main/scala/chisel3/probe/PackageImpl.scala @@ -53,8 +53,8 @@ private[chisel3] trait ObjectProbeImpl { requireCompatibleDestinationProbeColor( realSink, s"""Cannot define '$realSink' from colors ${(Builder.layerStack.headOption) - .map(a => s"'${a.fullName}'") - .mkString("{", ", ", "}")} since at least one of these is NOT enabled when '$realSink' is enabled""" + .map(a => s"'${a.fullName}'") + .mkString("{", ", ", "}")} since at least one of these is NOT enabled when '$realSink' is enabled""" ) if (realSink.probeInfo.get.writable) { requireHasWritableProbeTypeModifier( diff --git a/core/src/main/scala/chisel3/properties/Class.scala b/core/src/main/scala/chisel3/properties/Class.scala index 61284e9a978..e0de3487abe 100644 --- a/core/src/main/scala/chisel3/properties/Class.scala +++ b/core/src/main/scala/chisel3/properties/Class.scala @@ -61,9 +61,8 @@ class Class extends BaseModule { } // Create IR Ports and set the firrtlPorts variable. - val ports = getModulePortsAndLocators.map { - case (port, sourceInfo) => - Port(port, port.specifiedDirection, sourceInfo) + val ports = getModulePortsAndLocators.map { case (port, sourceInfo) => + Port(port, port.specifiedDirection, sourceInfo) } // No more commands. diff --git a/core/src/main/scala/chisel3/properties/Property.scala b/core/src/main/scala/chisel3/properties/Property.scala index 1287e9ec685..af4f27042bf 100644 --- a/core/src/main/scala/chisel3/properties/Property.scala +++ b/core/src/main/scala/chisel3/properties/Property.scala @@ -62,9 +62,9 @@ private[chisel3] object RecursivePropertyType { private[chisel3] trait SimplePropertyType[T] extends RecursivePropertyType[T] { final type Type = T final type Underlying = T - def convert(value: T): fir.Expression + def convert(value: T): fir.Expression def convert(value: T, ctx: ir.Component, info: SourceInfo): fir.Expression = convert(value) - def convertUnderlying(value: T): T = value + def convertUnderlying(value: T): T = value } private[chisel3] class SeqPropertyType[A, F[A] <: Seq[A], PT <: PropertyType[A]](val tpe: PT) diff --git a/core/src/main/scala/chisel3/reflect/DataMirror.scala b/core/src/main/scala/chisel3/reflect/DataMirror.scala index 78a889c56dc..d54e351bdd7 100644 --- a/core/src/main/scala/chisel3/reflect/DataMirror.scala +++ b/core/src/main/scala/chisel3/reflect/DataMirror.scala @@ -33,7 +33,7 @@ object DataMirror { // Cannot use isDefined because of the ClassTag target.topBindingOpt match { case Some(b: B) => true - case _ => false + case _ => false } } @@ -74,8 +74,8 @@ object DataMirror { * @param x the `Data` to examine * @return a `Some[Layer]` if the data has a layer color, `None` otherwise */ - def getLayerColor(x: Data): Option[layer.Layer] = x.probeInfo.collect { - case Data.ProbeInfo(_, Some(color)) => color + def getLayerColor(x: Data): Option[layer.Layer] = x.probeInfo.collect { case Data.ProbeInfo(_, Some(color)) => + color } /** Get an early guess for the name of this [[Data]] @@ -139,9 +139,9 @@ object DataMirror { * @return true if the two Chisel types have alignment type equivalence. */ def checkAlignmentTypeEquivalence(x: Data, y: Data): Boolean = { - //TODO(azidar): Perhaps there is a better pattern of `iterateOverMatches` that we can support - collectMembersOverMatches(connectable.Alignment(x, true), connectable.Alignment(y, true)) { - case (a, b) => a.alignment == b.alignment + // TODO(azidar): Perhaps there is a better pattern of `iterateOverMatches` that we can support + collectMembersOverMatches(connectable.Alignment(x, true), connectable.Alignment(y, true)) { case (a, b) => + a.alignment == b.alignment }(AlignmentMatchingZipOfChildren).forall(r => r) } @@ -213,16 +213,14 @@ object DataMirror { def getPortNames(name: String, data: Data): Seq[(String, Data)] = Seq(name -> data) ++ (data match { case _: Element => Seq() case r: Record => - r._elements.toSeq.flatMap { - case (eltName, elt) => - if (r._isOpaqueType) { getPortNames(s"${name}", elt) } - else { getPortNames(s"${name}_${eltName}", elt) } + r._elements.toSeq.flatMap { case (eltName, elt) => + if (r._isOpaqueType) { getPortNames(s"${name}", elt) } + else { getPortNames(s"${name}_${eltName}", elt) } } case v: Vec[_] => v.zipWithIndex.flatMap { case (elt, index) => getPortNames(s"${name}_${index}", elt) } }) - modulePorts(target).flatMap { - case (name, data) => - getPortNames(name, data).toList + modulePorts(target).flatMap { case (name, data) => + getPortNames(name, data).toList } } @@ -332,22 +330,19 @@ object DataMirror { * @tparam T Type of the component that will be collected */ private[chisel3] def collectMembersAndPaths[T]( - d: Data, - path: String = "" - )(collector: PartialFunction[Data, T] - ): Iterable[(T, String)] = new Iterable[(T, String)] { + d: Data, + path: String = "" + )(collector: PartialFunction[Data, T]): Iterable[(T, String)] = new Iterable[(T, String)] { def iterator = { val myItems = collector.lift(d).map { x => (x -> path) } val deepChildrenItems = d match { case a: Record if (!hasProbeTypeModifier(a)) => - a._elements.iterator.flatMap { - case (fieldName, fieldData) => - collectMembersAndPaths(fieldData, s"$path.$fieldName")(collector) + a._elements.iterator.flatMap { case (fieldName, fieldData) => + collectMembersAndPaths(fieldData, s"$path.$fieldName")(collector) } case a: Vec[_] if (!hasProbeTypeModifier(a)) => - a.elementsIterator.zipWithIndex.flatMap { - case (fieldData, fieldIndex) => - collectMembersAndPaths(fieldData, s"$path($fieldIndex)")(collector) + a.elementsIterator.zipWithIndex.flatMap { case (fieldData, fieldIndex) => + collectMembersAndPaths(fieldData, s"$path($fieldIndex)")(collector) } case other => Nil } @@ -404,8 +399,8 @@ object DataMirror { * @tparam T Type of the component that will be collected */ def collectAlignedDeep[T](base: Data)(pf: PartialFunction[Data, T]): Seq[T] = { - collectMembersOverAllForAny(Some(Alignment(base, true)), None) { - case (Some(x: AlignedWithRoot), _) => (pf.lift(x.member), None) + collectMembersOverAllForAny(Some(Alignment(base, true)), None) { case (Some(x: AlignedWithRoot), _) => + (pf.lift(x.member), None) }.map(_._1).flatten } @@ -417,8 +412,8 @@ object DataMirror { * @tparam T Type of the component that will be collected */ def collectFlippedDeep[T](base: Data)(pf: PartialFunction[Data, T]): Seq[T] = { - collectMembersOverAllForAny(Some(Alignment(base, true)), None) { - case (Some(x: FlippedWithRoot), _) => (pf.lift(x.member), None) + collectMembersOverAllForAny(Some(Alignment(base, true)), None) { case (Some(x: FlippedWithRoot), _) => + (pf.lift(x.member), None) }.map(_._1).flatten } @@ -445,10 +440,9 @@ object DataMirror { * @tparam T Type of the thing being collected */ def collectMembersOverMatches[D: HasMatchingZipOfChildren, T]( - left: D, - right: D - )(collector: PartialFunction[(D, D), T] - ): Seq[T] = { + left: D, + right: D + )(collector: PartialFunction[(D, D), T]): Seq[T] = { def newCollector(lOpt: Option[D], rOpt: Option[D]): Option[(Option[T], Option[Unit])] = { (lOpt, rOpt) match { case (Some(l), Some(r)) => @@ -480,18 +474,16 @@ object DataMirror { * @tparam T Type of the thing being collected */ def collectMembersOverAll[D: HasMatchingZipOfChildren, T]( - left: D, - right: D - )(collector: PartialFunction[(Option[D], Option[D]), T] - ): Seq[T] = { - collectMembersOverAllForAnyFunction(Some(left), Some(right)) { - case (lOpt: Option[D], rOpt: Option[D]) => - collector.lift((lOpt, rOpt)) match { - case Some(x) => Some((Some(x), None)) - case None => None - } - }.collect { - case (Some(x), None) => x + left: D, + right: D + )(collector: PartialFunction[(Option[D], Option[D]), T]): Seq[T] = { + collectMembersOverAllForAnyFunction(Some(left), Some(right)) { case (lOpt: Option[D], rOpt: Option[D]) => + collector.lift((lOpt, rOpt)) match { + case Some(x) => Some((Some(x), None)) + case None => None + } + }.collect { case (Some(x), None) => + x } } @@ -506,10 +498,9 @@ object DataMirror { * @tparam R Type of the thing being collected from the right */ def collectMembersOverAllForAny[D: HasMatchingZipOfChildren, L, R]( - left: Option[D], - right: Option[D] - )(pcollector: PartialFunction[(Option[D], Option[D]), (Option[L], Option[R])] - ): Seq[(Option[L], Option[R])] = { + left: Option[D], + right: Option[D] + )(pcollector: PartialFunction[(Option[D], Option[D]), (Option[L], Option[R])]): Seq[(Option[L], Option[R])] = { collectMembersOverAllForAnyFunction(left, right)(pcollector.lift) } @@ -524,18 +515,17 @@ object DataMirror { * @tparam R Type of the thing being collected from the right */ def collectMembersOverAllForAnyFunction[D: HasMatchingZipOfChildren, L, R]( - left: Option[D], - right: Option[D] - )(collector: ((Option[D], Option[D])) => Option[(Option[L], Option[R])] - ): Seq[(Option[L], Option[R])] = { + left: Option[D], + right: Option[D] + )(collector: ((Option[D], Option[D])) => Option[(Option[L], Option[R])]): Seq[(Option[L], Option[R])] = { val myItems = collector((left, right)) match { case None => Nil case Some((None, None)) => Nil case Some(other) => Seq(other) } val matcher = implicitly[HasMatchingZipOfChildren[D]] - val childItems = matcher.matchingZipOfChildren(left, right).flatMap { - case (l, r) => collectMembersOverAllForAnyFunction(l, r)(collector) + val childItems = matcher.matchingZipOfChildren(left, right).flatMap { case (l, r) => + collectMembersOverAllForAnyFunction(l, r)(collector) } myItems ++ childItems } diff --git a/firrtl/src/main/scala/firrtl/RenameMap.scala b/firrtl/src/main/scala/firrtl/RenameMap.scala index 70fafb35053..4b04fea6ed2 100644 --- a/firrtl/src/main/scala/firrtl/RenameMap.scala +++ b/firrtl/src/main/scala/firrtl/RenameMap.scala @@ -55,10 +55,10 @@ sealed trait RenameMap { protected def _recordAll(map: collection.Map[CompleteTarget, Seq[CompleteTarget]]): Unit = map.foreach { - case (from: IsComponent, tos: Seq[_]) => completeRename(from, tos) - case (from: IsModule, tos: Seq[_]) => completeRename(from, tos) + case (from: IsComponent, tos: Seq[_]) => completeRename(from, tos) + case (from: IsModule, tos: Seq[_]) => completeRename(from, tos) case (from: CircuitTarget, tos: Seq[_]) => completeRename(from, tos) - case other => Utils.throwInternalError(s"Illegal rename: ${other._1} -> ${other._2}") + case other => Utils.throwInternalError(s"Illegal rename: ${other._1} -> ${other._2}") } /** Renames a [[firrtl.annotations.CompleteTarget CompleteTarget]] @@ -109,9 +109,8 @@ sealed trait RenameMap { /** Visualize the [[RenameMap]] */ - def serialize: String = _underlying.map { - case (k, v) => - k.serialize + "=>" + v.map(_.serialize).mkString(", ") + def serialize: String = _underlying.map { case (k, v) => + k.serialize + "=>" + v.map(_.serialize).mkString(", ") }.mkString("\n") /** Records which local InstanceTargets will require modification. @@ -209,7 +208,7 @@ sealed trait RenameMap { val parent = t.copy(component = t.component.dropRight(1)) traverseTokens(parent).map(_.flatMap { x => (x, last) match { - case (t2: InstanceTarget, Field(f)) => Some(t2.ref(f)) + case (t2: InstanceTarget, Field(f)) => Some(t2.ref(f)) case (t2: ReferenceTarget, Field(f)) => Some(t2.field(f)) case (t2: ReferenceTarget, Index(i)) => Some(t2.index(i)) case other => @@ -400,8 +399,8 @@ sealed trait RenameMap { } rename match { case Seq(absolute: IsModule) if absolute.module == absolute.circuit => - val withChildren = children.foldLeft(absolute) { - case (target, (inst, ofMod)) => target.instOf(inst.value, ofMod.value) + val withChildren = children.foldLeft(absolute) { case (target, (inst, ofMod)) => + target.instOf(inst.value, ofMod.value) } AbsoluteOfModule(withChildren) case Seq(isMod: ModuleTarget) => @@ -453,7 +452,7 @@ sealed trait RenameMap { } else { key match { case t: CircuitTarget => None - case t: ModuleTarget => moduleGet(errors)(t) + case t: ModuleTarget => moduleGet(errors)(t) case t: IsComponent => ofModuleGet(errors)(t) match { case AbsoluteOfModule(absolute) => @@ -513,16 +512,15 @@ sealed trait RenameMap { key match { case t: CircuitTarget => circuitGet(errors)(t) case t: ModuleTarget => - circuitGet(errors)(CircuitTarget(t.circuit)).map { - case CircuitTarget(c) => t.copy(circuit = c) + circuitGet(errors)(CircuitTarget(t.circuit)).map { case CircuitTarget(c) => + t.copy(circuit = c) } case t: IsComponent => - circuitGet(errors)(CircuitTarget(t.circuit)).map { - case CircuitTarget(c) => - t match { - case ref: ReferenceTarget => ref.copy(circuit = c) - case inst: InstanceTarget => inst.copy(circuit = c) - } + circuitGet(errors)(CircuitTarget(t.circuit)).map { case CircuitTarget(c) => + t match { + case ref: ReferenceTarget => ref.copy(circuit = c) + case inst: InstanceTarget => inst.copy(circuit = c) + } } } } @@ -595,8 +593,8 @@ package object renamemap { protected val _underlying: mutable.HashMap[CompleteTarget, Seq[CompleteTarget]] = mutable.HashMap[CompleteTarget, Seq[CompleteTarget]](), protected val _chained: Option[RenameMap] = None, - protected val doDistinct: Boolean = true) - extends RenameMap { + protected val doDistinct: Boolean = true + ) extends RenameMap { /** Record that the from [[firrtl.annotations.CircuitTarget CircuitTarget]] is renamed to another * [[firrtl.annotations.CircuitTarget CircuitTarget]] @@ -665,8 +663,8 @@ package object renamemap { def delete(name: ComponentName): Unit = _underlying(name) = Seq.empty def addMap(map: collection.Map[Named, Seq[Named]]): Unit = - recordAll(map.map { - case (key, values) => (Target.convertNamed2Target(key), values.map(Target.convertNamed2Target)) + recordAll(map.map { case (key, values) => + (Target.convertNamed2Target(key), values.map(Target.convertNamed2Target)) }) } } diff --git a/firrtl/src/main/scala/firrtl/WIR.scala b/firrtl/src/main/scala/firrtl/WIR.scala index 31dca3e33e3..d7829dc0384 100644 --- a/firrtl/src/main/scala/firrtl/WIR.scala +++ b/firrtl/src/main/scala/firrtl/WIR.scala @@ -24,8 +24,8 @@ case class CDefMemory( tpe: Type, size: BigInt, seq: Boolean, - readUnderWrite: ReadUnderWrite.Value = ReadUnderWrite.Undefined) - extends Statement + readUnderWrite: ReadUnderWrite.Value = ReadUnderWrite.Undefined +) extends Statement with HasInfo with UseSerializer { def mapExpr(f: Expression => Expression): Statement = this diff --git a/firrtl/src/main/scala/firrtl/annotations/JsonProtocol.scala b/firrtl/src/main/scala/firrtl/annotations/JsonProtocol.scala index 11b9c723586..87162b0b25a 100644 --- a/firrtl/src/main/scala/firrtl/annotations/JsonProtocol.scala +++ b/firrtl/src/main/scala/firrtl/annotations/JsonProtocol.scala @@ -180,10 +180,9 @@ object JsonProtocol extends LazyLogging { val tags = getTags(annos.toSeq) implicit val formats = jsonFormat(tags) - Try(writePretty(annos, out)).recoverWith { - case e: org.json4s.MappingException => - val badAnnos = findUnserializeableAnnos(annos.toSeq) - Failure(if (badAnnos.isEmpty) e else UnserializableAnnotationException(badAnnos)) + Try(writePretty(annos, out)).recoverWith { case e: org.json4s.MappingException => + val badAnnos = findUnserializeableAnnos(annos.toSeq) + Failure(if (badAnnos.isEmpty) e else UnserializableAnnotationException(badAnnos)) } } diff --git a/firrtl/src/main/scala/firrtl/annotations/LoadMemoryAnnotation.scala b/firrtl/src/main/scala/firrtl/annotations/LoadMemoryAnnotation.scala index f3300f7c632..8605662f702 100644 --- a/firrtl/src/main/scala/firrtl/annotations/LoadMemoryAnnotation.scala +++ b/firrtl/src/main/scala/firrtl/annotations/LoadMemoryAnnotation.scala @@ -34,8 +34,8 @@ case class LoadMemoryAnnotation( target: ComponentName, fileName: String, hexOrBinary: MemoryLoadFileType = MemoryLoadFileType.Hex, - originalMemoryNameOpt: Option[String] = None) - extends SingleTargetAnnotation[Named] { + originalMemoryNameOpt: Option[String] = None +) extends SingleTargetAnnotation[Named] { val (prefix, suffix) = { fileName.split("""\.""").toList match { diff --git a/firrtl/src/main/scala/firrtl/annotations/MemoryInitAnnotation.scala b/firrtl/src/main/scala/firrtl/annotations/MemoryInitAnnotation.scala index e38abe7b335..17746aecc76 100644 --- a/firrtl/src/main/scala/firrtl/annotations/MemoryInitAnnotation.scala +++ b/firrtl/src/main/scala/firrtl/annotations/MemoryInitAnnotation.scala @@ -15,9 +15,9 @@ sealed trait MemoryInitAnnotation extends SingleTargetAnnotation[ReferenceTarget case class MemoryFileInlineAnnotation( target: ReferenceTarget, filename: String, - hexOrBinary: MemoryLoadFileType.FileType = MemoryLoadFileType.Hex) - extends MemoryInitAnnotation { + hexOrBinary: MemoryLoadFileType.FileType = MemoryLoadFileType.Hex +) extends MemoryInitAnnotation { require(filename.trim.nonEmpty, "empty filename not allowed in MemoryFileInlineAnnotation") override def duplicate(n: ReferenceTarget): Annotation = copy(n) - override def isRandomInit: Boolean = false + override def isRandomInit: Boolean = false } diff --git a/firrtl/src/main/scala/firrtl/annotations/Target.scala b/firrtl/src/main/scala/firrtl/annotations/Target.scala index 98f7421c897..87681be5ea6 100644 --- a/firrtl/src/main/scala/firrtl/annotations/Target.scala +++ b/firrtl/src/main/scala/firrtl/annotations/Target.scala @@ -153,7 +153,7 @@ object Target { tokens.tail.zip(tokens.tail.tail).foreach { case (".", value: String) => subComps += Field(value) case ("[", value: String) => subComps += Index(value.toInt) - case other => + case other => } } subComps.toSeq @@ -209,7 +209,7 @@ object Target { def getPathlessTarget(t: Target): Target = { t.tryToComplete match { case c: CircuitTarget => c - case m: IsMember => m.pathlessTarget + case m: IsMember => m.pathlessTarget case t: GenericTarget if t.isLegal => val newTokens = t.tokens.dropWhile(x => x.isInstanceOf[Instance] || x.isInstanceOf[OfModule]) GenericTarget(t.circuitOpt, t.moduleOpt, newTokens) @@ -248,9 +248,9 @@ case class GenericTarget(circuitOpt: Option[String], moduleOpt: Option[String], override def toNamed: Named = getComplete match { case Some(c: IsComponent) if c.isLocal => c.toNamed - case Some(c: ModuleTarget) => c.toNamed - case Some(c: CircuitTarget) => c.toNamed - case other => throw Target.NamedException(s"Cannot convert $this to [[Named]]") + case Some(c: ModuleTarget) => c.toNamed + case Some(c: CircuitTarget) => c.toNamed + case other => throw Target.NamedException(s"Cannot convert $this to [[Named]]") } override def toTarget: CompleteTarget = getComplete.get @@ -273,8 +273,8 @@ case class GenericTarget(circuitOpt: Option[String], moduleOpt: Option[String], override def isLocal: Boolean = !(getPath.nonEmpty && getPath.get.nonEmpty) def path: Vector[(Instance, OfModule)] = if (isComplete) { - tokens.zip(tokens.tail).collect { - case (i: Instance, o: OfModule) => (i, o) + tokens.zip(tokens.tail).collect { case (i: Instance, o: OfModule) => + (i, o) } } else Vector.empty[(Instance, OfModule)] @@ -293,9 +293,9 @@ case class GenericTarget(circuitOpt: Option[String], moduleOpt: Option[String], */ def getRef: Option[(String, Seq[TargetToken])] = if (isComplete) { val (optRef, comps) = tokens.foldLeft((None: Option[String], Vector.empty[TargetToken])) { - case ((None, v), Ref(r)) => (Some(r), v) + case ((None, v), Ref(r)) => (Some(r), v) case ((r: Some[String], comps), c) => (r, comps :+ c) - case ((r, v), other) => (None, v) + case ((r, v), other) => (None, v) } optRef.map(x => (x, comps)) } else { @@ -308,7 +308,7 @@ case class GenericTarget(circuitOpt: Option[String], moduleOpt: Option[String], def getInstanceOf: Option[(String, String)] = if (isComplete) { tokens.grouped(2).foldLeft(None: Option[(String, String)]) { case (instOf, Seq(i: Instance, o: OfModule)) => Some((i.value, o.value)) - case (instOf, _) => None + case (instOf, _) => None } } else { None @@ -456,9 +456,8 @@ trait IsMember extends CompleteTarget { /** @return List of local Instance Targets refering to each instance/ofModule in this member's path */ def pathAsTargets: Seq[InstanceTarget] = { path - .foldLeft((module, Vector.empty[InstanceTarget])) { - case ((m, vec), (Instance(i), OfModule(o))) => - (o, vec :+ InstanceTarget(circuit, m, Nil, i, o)) + .foldLeft((module, Vector.empty[InstanceTarget])) { case ((m, vec), (Instance(i), OfModule(o))) => + (o, vec :+ InstanceTarget(circuit, m, Nil, i, o)) } ._2 } @@ -522,8 +521,8 @@ trait IsComponent extends IsMember { } } - override def justPath: Seq[TargetToken] = path.foldLeft(Vector.empty[TargetToken]) { - case (vec, (i, o)) => vec ++ Seq(i, o) + override def justPath: Seq[TargetToken] = path.foldLeft(Vector.empty[TargetToken]) { case (vec, (i, o)) => + vec ++ Seq(i, o) } override def pathTarget: IsModule = { @@ -623,8 +622,8 @@ case class ReferenceTarget( module: String, override val path: Seq[(Instance, OfModule)], ref: String, - component: Seq[TargetToken]) - extends IsComponent { + component: Seq[TargetToken] +) extends IsComponent { /** @param value Index value of this target * @return A new [[ReferenceTarget]] to the specified index of this [[ReferenceTarget]] @@ -745,8 +744,8 @@ case class InstanceTarget( module: String, override val path: Seq[(Instance, OfModule)], instance: String, - ofModule: String) - extends IsModule + ofModule: String +) extends IsModule with IsComponent { /** @return a [[ReferenceTarget]] referring to this declaration of this instance */ diff --git a/firrtl/src/main/scala/firrtl/graph/DiGraph.scala b/firrtl/src/main/scala/firrtl/graph/DiGraph.scala index 3348c55ad99..5d786ee9e53 100644 --- a/firrtl/src/main/scala/firrtl/graph/DiGraph.scala +++ b/firrtl/src/main/scala/firrtl/graph/DiGraph.scala @@ -331,15 +331,14 @@ class DiGraph[T](private[graph] val edges: LinkedHashMap[T, LinkedHashSet[T]]) { def reverse: DiGraph[T] = { val mdg = new MutableDiGraph[T] edges.foreach({ case (u, edges) => mdg.addVertex(u) }) - edges.foreach({ - case (u, edges) => - edges.foreach(v => mdg.addEdge(v, u)) + edges.foreach({ case (u, edges) => + edges.foreach(v => mdg.addEdge(v, u)) }) DiGraph(mdg) } private def filterEdges(vprime: Set[T]): LinkedHashMap[T, LinkedHashSet[T]] = { - def filterNodeSet(s: LinkedHashSet[T]): LinkedHashSet[T] = s.filter({ case (k) => vprime.contains(k) }) + def filterNodeSet(s: LinkedHashSet[T]): LinkedHashSet[T] = s.filter({ case (k) => vprime.contains(k) }) def filterAdjacencyLists(m: LinkedHashMap[T, LinkedHashSet[T]]): LinkedHashMap[T, LinkedHashSet[T]] = m.map({ case (k, v) => (k, filterNodeSet(v)) }) @@ -417,17 +416,16 @@ class DiGraph[T](private[graph] val edges: LinkedHashMap[T, LinkedHashSet[T]]) { val last = children.size - 1 children.toList // Convert LinkedHashSet to List to avoid determinism issues .zipWithIndex // Find last - .foldLeft(here :: prev) { - case (acc, (nodex, idx)) => - val nextTab = if (idx == last) tab + ctab else tab + c + " " - val nextMark = if (idx == last) tab + l else tab + n - rec(nextTab, nodex, nextMark + " ", acc) + .foldLeft(here :: prev) { case (acc, (nodex, idx)) => + val nextTab = if (idx == last) tab + ctab else tab + c + " " + val nextMark = if (idx == last) tab + l else tab + n + rec(nextTab, nodex, nextMark + " ", acc) } } this.findSources.toList // Convert LinkedHashSet to List to avoid determinism issues .sortBy(_.toString) // Make order deterministic - .foldLeft(Nil: List[String]) { - case (acc, root) => rec("", root, "", acc) + .foldLeft(Nil: List[String]) { case (acc, root) => + rec("", root, "", acc) } .reverse .mkString("\n") diff --git a/firrtl/src/main/scala/firrtl/ir/IR.scala b/firrtl/src/main/scala/firrtl/ir/IR.scala index b512814efb5..b58f61f29ea 100644 --- a/firrtl/src/main/scala/firrtl/ir/IR.scala +++ b/firrtl/src/main/scala/firrtl/ir/IR.scala @@ -167,8 +167,8 @@ abstract class PrimOp extends FirrtlNode { case x: Int => "int" case other => "other" } - val exprs = groups.getOrElse("exp", Nil).collect { - case e: Expression => e + val exprs = groups.getOrElse("exp", Nil).collect { case e: Expression => + e } val consts = groups.getOrElse("int", Nil).map { _ match { @@ -287,11 +287,7 @@ case class DoPrim(op: PrimOp, args: Seq[Expression], consts: Seq[BigInt], tpe: T abstract class Statement extends FirrtlNode case class DefWire(info: Info, name: String, tpe: Type) extends Statement with IsDeclaration with UseSerializer -case class DefRegister( - info: Info, - name: String, - tpe: Type, - clock: Expression) +case class DefRegister(info: Info, name: String, tpe: Type, clock: Expression) extends Statement with IsDeclaration with UseSerializer @@ -301,8 +297,8 @@ case class DefRegisterWithReset( tpe: Type, clock: Expression, reset: Expression, - init: Expression) - extends Statement + init: Expression +) extends Statement with IsDeclaration with UseSerializer @@ -315,12 +311,7 @@ case class DefInstance(info: Info, name: String, module: String, tpe: Type = Unk with IsDeclaration with UseSerializer -case class DefInstanceChoice( - info: Info, - name: String, - default: String, - option: String, - choices: Seq[(String, String)]) +case class DefInstanceChoice(info: Info, name: String, default: String, option: String, choices: Seq[(String, String)]) extends Statement with IsDeclaration with UseSerializer @@ -344,8 +335,8 @@ case class DefMemory( writers: Seq[String], readwriters: Seq[String], // TODO: handle read-under-write - readUnderWrite: ReadUnderWrite.Value = ReadUnderWrite.Undefined) - extends Statement + readUnderWrite: ReadUnderWrite.Value = ReadUnderWrite.Undefined +) extends Statement with IsDeclaration with UseSerializer case class DefNode(info: Info, name: String, value: Expression) extends Statement with IsDeclaration with UseSerializer @@ -353,11 +344,7 @@ case class DefNode(info: Info, name: String, value: Expression) extends Statemen /** Record/bundle type definition that names a FIRRTL type with an alias name */ case class DefTypeAlias(info: Info, name: String, tpe: Type) extends Statement with UseSerializer -case class Conditionally( - info: Info, - pred: Expression, - conseq: Statement, - alt: Statement) +case class Conditionally(info: Info, pred: Expression, conseq: Statement, alt: Statement) extends Statement with HasInfo with UseSerializer @@ -372,12 +359,7 @@ case class PropAssign(info: Info, loc: Expression, expr: Expression) extends Sta case class IsInvalid(info: Info, expr: Expression) extends Statement with HasInfo with UseSerializer case class Attach(info: Info, exprs: Seq[Expression]) extends Statement with HasInfo with UseSerializer -case class Stop( - val info: Info, - val ret: Int, - val clk: Expression, - val en: Expression, - val name: String = "") +case class Stop(val info: Info, val ret: Int, val clk: Expression, val en: Expression, val name: String = "") extends Statement with HasInfo with IsDeclaration @@ -389,8 +371,8 @@ case class Print( val args: Seq[Expression], val clk: Expression, val en: Expression, - val name: String = "") - extends Statement + val name: String = "" +) extends Statement with HasInfo with IsDeclaration with UseSerializer @@ -416,11 +398,7 @@ object LayerConfig { final case object Inline extends LayerConfig } -final case class Layer( - info: Info, - name: String, - config: LayerConfig, - body: Seq[Layer]) +final case class Layer(info: Info, name: String, config: LayerConfig, body: Seq[Layer]) extends FirrtlNode with IsDeclaration with UseSerializer { @@ -436,11 +414,7 @@ case class LayerBlock(info: Info, layer: String, body: Statement) extends Statem case class DefOption(info: Info, name: String, cases: Seq[DefOptionCase]) case class DefOptionCase(info: Info, name: String) -case class IntrinsicExpr( - intrinsic: String, - args: Seq[Expression], - params: Seq[Param], - tpe: Type) +case class IntrinsicExpr(intrinsic: String, args: Seq[Expression], params: Seq[Param], tpe: Type) extends Expression with UseSerializer @@ -449,8 +423,8 @@ case class IntrinsicStmt( intrinsic: String, args: Seq[Expression], params: Seq[Param], - tpe: Option[Type] = None) - extends Statement + tpe: Option[Type] = None +) extends Statement with UseSerializer // formal @@ -468,8 +442,8 @@ case class Verification( en: Expression, msg: StringLit, args: Seq[Expression], - name: String = "") - extends Statement + name: String = "" +) extends Statement with HasInfo with IsDeclaration with UseSerializer { @@ -482,19 +456,19 @@ case object EmptyStmt extends Statement with UseSerializer abstract class Width extends FirrtlNode { def +(x: Width): Width = (this, x) match { case (a: IntWidth, b: IntWidth) => IntWidth(a.width + b.width) - case _ => UnknownWidth + case _ => UnknownWidth } def -(x: Width): Width = (this, x) match { case (a: IntWidth, b: IntWidth) => IntWidth(a.width - b.width) - case _ => UnknownWidth + case _ => UnknownWidth } def max(x: Width): Width = (this, x) match { case (a: IntWidth, b: IntWidth) => IntWidth(a.width.max(b.width)) - case _ => UnknownWidth + case _ => UnknownWidth } def min(x: Width): Width = (this, x) match { case (a: IntWidth, b: IntWidth) => IntWidth(a.width.min(b.width)) - case _ => UnknownWidth + case _ => UnknownWidth } } @@ -611,11 +585,7 @@ case object Output extends Direction { } /** [[DefModule]] Port */ -case class Port( - info: Info, - name: String, - direction: Direction, - tpe: Type) +case class Port(info: Info, name: String, direction: Direction, tpe: Type) extends FirrtlNode with IsDeclaration with UseSerializer @@ -660,12 +630,7 @@ case class Module(info: Info, name: String, public: Boolean, layers: Seq[String] * Generally used for Verilog black boxes * @param defname Defined name of the external module (ie. the name Firrtl will emit) */ -case class ExtModule( - info: Info, - name: String, - ports: Seq[Port], - defname: String, - params: Seq[Param]) +case class ExtModule(info: Info, name: String, ports: Seq[Port], defname: String, params: Seq[Param]) extends DefModule with UseSerializer @@ -674,12 +639,7 @@ case class ExtModule( * Used for compiler intrinsics. * @param intrinsic Defined intrinsic of the module */ -case class IntModule( - info: Info, - name: String, - ports: Seq[Port], - intrinsic: String, - params: Seq[Param]) +case class IntModule(info: Info, name: String, ports: Seq[Port], intrinsic: String, params: Seq[Param]) extends DefModule with UseSerializer @@ -693,8 +653,8 @@ case class Circuit( main: String, typeAliases: Seq[DefTypeAlias] = Seq.empty, layers: Seq[Layer] = Seq.empty, - options: Seq[DefOption] = Seq.empty) - extends FirrtlNode + options: Seq[DefOption] = Seq.empty +) extends FirrtlNode with HasInfo with UseSerializer diff --git a/firrtl/src/main/scala/firrtl/ir/Serializer.scala b/firrtl/src/main/scala/firrtl/ir/Serializer.scala index a1da49da0fe..89c0c2715e0 100644 --- a/firrtl/src/main/scala/firrtl/ir/Serializer.scala +++ b/firrtl/src/main/scala/firrtl/ir/Serializer.scala @@ -121,10 +121,9 @@ object Serializer { case SequencePropertyValue(tpe, values) => b ++= "List<"; s(tpe); b ++= ">("; val lastIdx = values.size - 1 - values.zipWithIndex.foreach { - case (value, idx) => - s(value) - if (idx != lastIdx) b ++= ", " + values.zipWithIndex.foreach { case (value, idx) => + s(value) + if (idx != lastIdx) b ++= ", " } b += ')' case ProbeExpr(expr, _) => b ++= "probe("; s(expr); b += ')' @@ -146,7 +145,7 @@ object Serializer { def mapStmt(f: Statement => Statement): Statement = ??? def mapString(f: String => String): Statement = ??? def mapType(f: Type => Type): Statement = ??? - def serialize: String = ??? + def serialize: String = ??? } // To treat Statments as Iterable, we need to flatten out when scoping @@ -296,10 +295,9 @@ object Serializer { case DefInstanceChoice(info, name, default, option, choices) => b ++= "instchoice "; b ++= legalize(name); b ++= " of "; b ++= legalize(default); b ++= ", "; b ++= legalize(option); b ++= " : "; s(info) - choices.foreach { - case (choice, module) => - newLineAndIndent(1) - b ++= legalize(choice); b ++= " => "; b ++= legalize(module) + choices.foreach { case (choice, module) => + newLineAndIndent(1) + b ++= legalize(choice); b ++= " => "; b ++= legalize(module) } case DefObject(info, name, cls) => b ++= "object "; b ++= legalize(name); b ++= " of "; b ++= legalize(cls); s(info) @@ -326,7 +324,7 @@ object Serializer { b ++= "read-under-write => "; b ++= readUnderWrite.toString case DefTypeAlias(info, name, tpe) => b ++= "type "; b ++= name; b ++= " = "; - s(tpe) //; s(info) TODO: Uncomment once firtool accepts infos for type aliases + s(tpe) // ; s(info) TODO: Uncomment once firtool accepts infos for type aliases case Attach(info, exprs) => // exprs should never be empty since the attach statement takes *at least* two signals according to the spec b ++= "attach ("; s(exprs, ", "); b += ')'; s(info) @@ -378,10 +376,9 @@ object Serializer { if (params.nonEmpty) { b += '<'; val lastIdx = params.size - 1 - params.zipWithIndex.foreach { - case (param, idx) => - s(param) - if (idx != lastIdx) b ++= ", " + params.zipWithIndex.foreach { case (param, idx) => + s(param) + if (idx != lastIdx) b ++= ", " } b += '>' } @@ -440,8 +437,8 @@ object Serializer { } s(underlying, true)(b, indent) } - case UIntType(width: Width) => b ++= "UInt"; s(width) - case SIntType(width: Width) => b ++= "SInt"; s(width) + case UIntType(width: Width) => b ++= "UInt"; s(width) + case SIntType(width: Width) => b ++= "SInt"; s(width) case BundleType(fields) => b ++= "{ "; sField(fields, ", "); b += '}' case VectorType(tpe, size) => s(tpe, lastEmittedConst); b += '['; b ++= size.toString; b += ']' case ClockType => b ++= "Clock" @@ -598,10 +595,9 @@ object Serializer { options ++ typeAliases ++ layers ++ - circuit.modules.iterator.zipWithIndex.flatMap { - case (m, i) => - val newline = Iterator(if (i == 0) s"$NewLine" else s"${NewLine}${NewLine}") - newline ++ sIt(m)(indent + 1) + circuit.modules.iterator.zipWithIndex.flatMap { case (m, i) => + val newline = Iterator(if (i == 0) s"$NewLine" else s"${NewLine}${NewLine}") + newline ++ sIt(m)(indent + 1) } ++ Iterator(s"$NewLine") } diff --git a/firrtl/src/main/scala/firrtl/options/DependencyManager.scala b/firrtl/src/main/scala/firrtl/options/DependencyManager.scala index 45055086dfb..71da96c4e1b 100644 --- a/firrtl/src/main/scala/firrtl/options/DependencyManager.scala +++ b/firrtl/src/main/scala/firrtl/options/DependencyManager.scala @@ -150,10 +150,9 @@ trait DependencyManager[A, B <: TransformLike[A] with DependencyAPI[B]] extends .map { a => a -> prerequisiteGraph.getVertices.filter(a._optionalPrerequisiteOf(_)) } x.values .reduce(_ ++ _) - .foldLeft(x) { - case (xx, y) => - if (xx.contains(y)) { xx } - else { xx ++ Map(y -> Set.empty[B]) } + .foldLeft(x) { case (xx, y) => + if (xx.contains(y)) { xx } + else { xx ++ Map(y -> Set.empty[B]) } } } DiGraph(edges).reverse @@ -211,8 +210,8 @@ trait DependencyManager[A, B <: TransformLike[A] with DependencyAPI[B]] extends /* A comparison function that will sort vertices based on the topological sort of the invalidation graph */ val cmp = (l: B, r: B) => - v.foldLeft((Map.empty[B, Dependency[B] => Boolean], ISet.empty[Dependency[B]])) { - case ((m, s), r) => (m + (r -> ((a: Dependency[B]) => !s(a))), s + r) + v.foldLeft((Map.empty[B, Dependency[B] => Boolean], ISet.empty[Dependency[B]])) { case ((m, s), r) => + (m + (r -> ((a: Dependency[B]) => !s(a))), s + r) }._1(l)(r) new LinkedHashMap() ++ v.map(vv => vv -> (new LinkedHashSet() ++ (dependencyGraph.getEdges(vv).toSeq.sortWith(cmp)))) @@ -225,17 +224,16 @@ trait DependencyManager[A, B <: TransformLike[A] with DependencyAPI[B]] extends } /* [todo] Seq is inefficient here, but Array has ClassTag problems. Use something else? */ - val (s, l) = sorted.foldLeft((_currentState, Seq[B]())) { - case ((state, out), in) => - val prereqs = in._prerequisites ++ - dependencyGraph.getEdges(in).toSeq.map(oToD) ++ - otherPrerequisites.getEdges(in).toSeq.map(oToD) - val preprocessing: Option[B] = { - if ((prereqs.diff(state)).nonEmpty) { Some(this.copy(prereqs.toSeq, state.toSeq)) } - else { None } - } - /* "in" is added *after* invalidation because a transform my not invalidate itself! */ - ((state ++ prereqs).map(dToO).filterNot(in.invalidates).map(oToD) += in, out ++ preprocessing :+ in) + val (s, l) = sorted.foldLeft((_currentState, Seq[B]())) { case ((state, out), in) => + val prereqs = in._prerequisites ++ + dependencyGraph.getEdges(in).toSeq.map(oToD) ++ + otherPrerequisites.getEdges(in).toSeq.map(oToD) + val preprocessing: Option[B] = { + if ((prereqs.diff(state)).nonEmpty) { Some(this.copy(prereqs.toSeq, state.toSeq)) } + else { None } + } + /* "in" is added *after* invalidation because a transform my not invalidate itself! */ + ((state ++ prereqs).map(dToO).filterNot(in.invalidates).map(oToD) += in, out ++ preprocessing :+ in) } val postprocessing: Option[B] = { if ((_targets.diff(s)).nonEmpty) { Some(this.copy(_targets.toSeq, s.toSeq)) } @@ -266,23 +264,22 @@ trait DependencyManager[A, B <: TransformLike[A] with DependencyAPI[B]] extends val w = wrappers.foldLeft(t) { case (tx, wrapper) => wrapper(tx) } wrapperToClass += (w -> t) w - }.foldLeft((annotations, _currentState)) { - case ((a, state), t) => - if (!t.prerequisites.toSet.subsetOf(state)) { - throw new DependencyManagerException( - s"""|Tried to execute '$t' for which run-time prerequisites were not satisfied: - | state: ${state.mkString("\n -", "\n -", "")} - | prerequisites: ${prerequisites.mkString("\n -", "\n -", "")}""".stripMargin - ) - } - val logger = t.getLogger - logger.info(s"======== Starting ${t.name} ========") - val (timeMillis, annosx) = firrtl.Utils.time { t.transform(a) } - logger.info(s"""----------------------------${"-" * t.name.size}---------\n""") - logger.info(f"Time: $timeMillis%.1f ms") - logger.info(s"======== Finished ${t.name} ========") - val statex = (state += wrapperToClass(t)).map(dToO).filterNot(t.invalidates).map(oToD) - (annosx, statex) + }.foldLeft((annotations, _currentState)) { case ((a, state), t) => + if (!t.prerequisites.toSet.subsetOf(state)) { + throw new DependencyManagerException( + s"""|Tried to execute '$t' for which run-time prerequisites were not satisfied: + | state: ${state.mkString("\n -", "\n -", "")} + | prerequisites: ${prerequisites.mkString("\n -", "\n -", "")}""".stripMargin + ) + } + val logger = t.getLogger + logger.info(s"======== Starting ${t.name} ========") + val (timeMillis, annosx) = firrtl.Utils.time { t.transform(a) } + logger.info(s"""----------------------------${"-" * t.name.size}---------\n""") + logger.info(f"Time: $timeMillis%.1f ms") + logger.info(s"======== Finished ${t.name} ========") + val statex = (state += wrapperToClass(t)).map(dToO).filterNot(t.invalidates).map(oToD) + (annosx, statex) }._1 } @@ -300,9 +297,8 @@ trait DependencyManager[A, B <: TransformLike[A] with DependencyAPI[B]] extends def toGraphviz(digraph: DiGraph[B], attributes: String = "", tab: String = " "): Option[String] = { val edges = - digraph.getEdgeMap.collect { case (v, edges) if edges.nonEmpty => (v -> edges) }.map { - case (v, edges) => - s"""${transformName(v)} -> ${edges.map(e => transformName(e)).mkString("{ ", " ", " }")}""" + digraph.getEdgeMap.collect { case (v, edges) if edges.nonEmpty => (v -> edges) }.map { case (v, edges) => + s"""${transformName(v)} -> ${edges.map(e => transformName(e)).mkString("{ ", " ", " }")}""" } if (edges.isEmpty) { None } @@ -406,8 +402,8 @@ trait DependencyManager[A, B <: TransformLike[A] with DependencyAPI[B]] extends case (a: DependencyManager[_, _], `last`) => Seq(s"$tab$l ${a.name}") ++ a.prettyPrintRec(s"""$tab${" " * c.size} """, charSet) case (a: DependencyManager[_, _], _) => Seq(s"$tab$n ${a.name}") ++ a.prettyPrintRec(s"$tab$c ", charSet) - case (a, `last`) => Seq(s"$tab$l ${a.name}") - case (a, _) => Seq(s"$tab$n ${a.name}") + case (a, `last`) => Seq(s"$tab$l ${a.name}") + case (a, _) => Seq(s"$tab$n ${a.name}") } val handling = customPrintHandling(tab, charSet, transformOrder.size) match { @@ -443,8 +439,8 @@ trait DependencyManager[A, B <: TransformLike[A] with DependencyAPI[B]] extends class PhaseManager( val targets: Seq[PhaseManager.PhaseDependency], val currentState: Seq[PhaseManager.PhaseDependency] = Seq.empty, - val knownObjects: Set[Phase] = Set.empty) - extends DependencyManager[AnnotationSeq, Phase] + val knownObjects: Set[Phase] = Set.empty +) extends DependencyManager[AnnotationSeq, Phase] with Phase { import PhaseManager.PhaseDependency diff --git a/firrtl/src/main/scala/firrtl/options/Registration.scala b/firrtl/src/main/scala/firrtl/options/Registration.scala index ff3e29654f4..c5d82af7c05 100644 --- a/firrtl/src/main/scala/firrtl/options/Registration.scala +++ b/firrtl/src/main/scala/firrtl/options/Registration.scala @@ -19,7 +19,8 @@ final class ShellOption[A: Read]( val toAnnotationSeq: A => AnnotationSeq, val helpText: String, val shortOption: Option[String] = None, - val helpValueName: Option[String] = None) { + val helpValueName: Option[String] = None +) { /** Add this specific shell (command line) option to an option parser * @param p an option parser diff --git a/firrtl/src/main/scala/firrtl/options/StageOptions.scala b/firrtl/src/main/scala/firrtl/options/StageOptions.scala index 74b84891059..fa65ac6a412 100644 --- a/firrtl/src/main/scala/firrtl/options/StageOptions.scala +++ b/firrtl/src/main/scala/firrtl/options/StageOptions.scala @@ -14,7 +14,8 @@ class StageOptions private[firrtl] ( val targetDir: String = TargetDirAnnotation().directory, val annotationFilesIn: Seq[String] = Seq.empty, val annotationFileOut: Option[String] = None, - val programArgs: Seq[String] = Seq.empty) { + val programArgs: Seq[String] = Seq.empty +) { private[options] def copy( targetDir: String = targetDir, diff --git a/firrtl/src/main/scala/firrtl/passes/CheckTypes.scala b/firrtl/src/main/scala/firrtl/passes/CheckTypes.scala index be6269a49e2..95ca0cec6b7 100644 --- a/firrtl/src/main/scala/firrtl/passes/CheckTypes.scala +++ b/firrtl/src/main/scala/firrtl/passes/CheckTypes.scala @@ -20,8 +20,8 @@ object CheckTypes { // it cannot drive Bool nor AsyncResetType private def compare(sink: Type, source: Type): Boolean = (sink, source) match { - case (_: UIntType, _: UIntType) => true - case (_: SIntType, _: SIntType) => true + case (_: UIntType, _: UIntType) => true + case (_: SIntType, _: SIntType) => true case (ClockType, ClockType) => true case (AsyncResetType, AsyncResetType) => true case (ResetType, tpe) => legalResetType(tpe) @@ -34,19 +34,18 @@ object CheckTypes { sink.size == source.size && compare(sink.tpe, source.tpe) case (sink: BundleType, source: BundleType) => (sink.fields.size == source.fields.size) && - sink.fields.zip(source.fields).forall { - case (f1, f2) => - (f1.flip == f2.flip) && (f1.name == f2.name) && (f1.flip match { - case Default => compare(f1.tpe, f2.tpe) - // We allow UInt<1> and AsyncReset to drive Reset but not the other way around - case Flip => compare(f2.tpe, f1.tpe) - }) - } + sink.fields.zip(source.fields).forall { case (f1, f2) => + (f1.flip == f2.flip) && (f1.name == f2.name) && (f1.flip match { + case Default => compare(f1.tpe, f2.tpe) + // We allow UInt<1> and AsyncReset to drive Reset but not the other way around + case Flip => compare(f2.tpe, f1.tpe) + }) + } // Const connection validity is checked later on in the Firrtl compiler. case (sink: ConstType, source: ConstType) => compare(sink.underlying, source.underlying) - case (sink, source: ConstType) => compare(sink, source.underlying) - case (sink: ConstType, source) => compare(sink.underlying, source) - case _ => false + case (sink, source: ConstType) => compare(sink, source.underlying) + case (sink: ConstType, source) => compare(sink.underlying, source) + case _ => false } def validConnect(locTpe: Type, expTpe: Type): Boolean = { diff --git a/firrtl/src/main/scala/firrtl/stage/FirrtlOptions.scala b/firrtl/src/main/scala/firrtl/stage/FirrtlOptions.scala index 64fa569c24e..954d74d8df6 100644 --- a/firrtl/src/main/scala/firrtl/stage/FirrtlOptions.scala +++ b/firrtl/src/main/scala/firrtl/stage/FirrtlOptions.scala @@ -12,7 +12,8 @@ import firrtl.ir.Circuit class FirrtlOptions private[stage] ( val outputFileName: Option[String] = None, val infoModeName: String = InfoModeAnnotation().modeName, - val firrtlCircuit: Option[Circuit] = None) { + val firrtlCircuit: Option[Circuit] = None +) { private[stage] def copy( outputFileName: Option[String] = outputFileName, diff --git a/firrtl/src/main/scala/firrtl/transforms/MustDedup.scala b/firrtl/src/main/scala/firrtl/transforms/MustDedup.scala index d6533a40c2a..294fa558835 100644 --- a/firrtl/src/main/scala/firrtl/transforms/MustDedup.scala +++ b/firrtl/src/main/scala/firrtl/transforms/MustDedup.scala @@ -11,8 +11,8 @@ case class MustDeduplicateAnnotation(modules: Seq[IsModule]) extends Annotation def update(renames: RenameMap): Seq[MustDeduplicateAnnotation] = { val newModules: Seq[IsModule] = modules.flatMap { m => renames.get(m) match { - case None => Seq(m) - case Some(Seq()) => Seq() + case None => Seq(m) + case Some(Seq()) => Seq() case Some(Seq(one: IsModule)) => Seq(one) case Some(many) => val msg = "Something went wrong! This anno's targets should only rename to IsModules! " + diff --git a/firrtl/src/main/scala/firrtl/util/BackendCompilationUtilities.scala b/firrtl/src/main/scala/firrtl/util/BackendCompilationUtilities.scala index 24aca6b3c88..5d5d5c445b1 100644 --- a/firrtl/src/main/scala/firrtl/util/BackendCompilationUtilities.scala +++ b/firrtl/src/main/scala/firrtl/util/BackendCompilationUtilities.scala @@ -139,9 +139,9 @@ object BackendCompilationUtilities extends LazyLogging { blackBoxVerilogList ++ vSourcesFiltered.flatMap(file => Seq("-v", file.getCanonicalPath)) ++ Seq("--assert", "-Wno-fatal", "-Wno-WIDTH", "-Wno-STMTDLY") ++ { - if (suppressVcd) { Seq.empty } - else { Seq("--trace") } - } ++ + if (suppressVcd) { Seq.empty } + else { Seq("--trace") } + } ++ Seq( "-O1", "--top-module", diff --git a/firrtl/src/main/scala/logger/LoggerOptions.scala b/firrtl/src/main/scala/logger/LoggerOptions.scala index dc58108510c..873deaf2259 100644 --- a/firrtl/src/main/scala/logger/LoggerOptions.scala +++ b/firrtl/src/main/scala/logger/LoggerOptions.scala @@ -13,7 +13,8 @@ class LoggerOptions private[logger] ( val globalLogLevel: LogLevel.Value = LogLevelAnnotation().globalLogLevel, val classLogLevels: Map[String, LogLevel.Value] = Map.empty, val logClassNames: Boolean = false, - val logFileName: Option[String] = None) { + val logFileName: Option[String] = None +) { private[logger] def copy( globalLogLevel: LogLevel.Value = globalLogLevel, diff --git a/firrtl/src/test/scala/firrtlTests/annotationTests/JsonProtocolSpec.scala b/firrtl/src/test/scala/firrtlTests/annotationTests/JsonProtocolSpec.scala index 489de5c4f34..065ed5941e5 100644 --- a/firrtl/src/test/scala/firrtlTests/annotationTests/JsonProtocolSpec.scala +++ b/firrtl/src/test/scala/firrtlTests/annotationTests/JsonProtocolSpec.scala @@ -21,17 +21,16 @@ case class AnAnnotation( statement: Statement, expr: Expression, tpe: Type, - groundType: GroundType) - extends NoTargetAnnotation + groundType: GroundType +) extends NoTargetAnnotation class JsonProtocolSpec extends AnyFlatSpec with Matchers { "Trying to serialize annotations that cannot be serialized" should "tell you why" in { case class MyAnno(x: Int) extends NoTargetAnnotation - inside(JsonProtocol.serializeTry(MyAnno(3) :: Nil)) { - case Failure(e: UnserializableAnnotationException) => - e.getMessage should include("MyAnno") - // From json4s Exception - e.getMessage should include("Classes defined in method bodies are not supported") + inside(JsonProtocol.serializeTry(MyAnno(3) :: Nil)) { case Failure(e: UnserializableAnnotationException) => + e.getMessage should include("MyAnno") + // From json4s Exception + e.getMessage should include("Classes defined in method bodies are not supported") } } "JsonProtocol.serializeRecover" should "emit even annotations that cannot be serialized" in { diff --git a/firrtl/src/test/scala/firrtlTests/annotationTests/TargetSpec.scala b/firrtl/src/test/scala/firrtlTests/annotationTests/TargetSpec.scala index 47555f43651..553d093d3dd 100644 --- a/firrtl/src/test/scala/firrtlTests/annotationTests/TargetSpec.scala +++ b/firrtl/src/test/scala/firrtlTests/annotationTests/TargetSpec.scala @@ -24,9 +24,8 @@ class TargetSpec extends FirrtlPropSpec { (top.ref("r").index(1).field("hi").clock, "~Circuit|Top>r[1].hi@clock"), (GenericTarget(None, None, Vector(Ref("r"))), "~???|???>r") ) - targets.foreach { - case (t, str) => - assert(t.serialize == str, s"$t does not properly serialize") + targets.foreach { case (t, str) => + assert(t.serialize == str, s"$t does not properly serialize") } } property("Should convert to/from Named") { @@ -65,20 +64,35 @@ class TargetSpec extends FirrtlPropSpec { val top = circuit.module("B") val targets = Seq( (circuit, "circuit A:"), - (top, """|circuit A: - |└── module B:""".stripMargin), - (top.instOf("c", "C"), """|circuit A: - |└── module B: - | └── inst c of C:""".stripMargin), - (top.ref("r"), """|circuit A: - |└── module B: - | └── r""".stripMargin), - (top.ref("r").index(1).field("hi").clock, """|circuit A: - |└── module B: - | └── r[1].hi@clock""".stripMargin), - (GenericTarget(None, None, Vector(Ref("r"))), """|circuit ???: - |└── module ???: - | └── r""".stripMargin) + ( + top, + """|circuit A: + |└── module B:""".stripMargin + ), + ( + top.instOf("c", "C"), + """|circuit A: + |└── module B: + | └── inst c of C:""".stripMargin + ), + ( + top.ref("r"), + """|circuit A: + |└── module B: + | └── r""".stripMargin + ), + ( + top.ref("r").index(1).field("hi").clock, + """|circuit A: + |└── module B: + | └── r[1].hi@clock""".stripMargin + ), + ( + GenericTarget(None, None, Vector(Ref("r"))), + """|circuit ???: + |└── module ???: + | └── r""".stripMargin + ) ) targets.foreach { case (t, str) => assert(t.prettyPrint() == str, s"$t didn't properly prettyPrint") } } diff --git a/firrtl/src/test/scala/firrtlTests/annotationTests/UnrecognizedAnnotationSpec.scala b/firrtl/src/test/scala/firrtlTests/annotationTests/UnrecognizedAnnotationSpec.scala index 2765eeb39b9..0f276db2b56 100644 --- a/firrtl/src/test/scala/firrtlTests/annotationTests/UnrecognizedAnnotationSpec.scala +++ b/firrtl/src/test/scala/firrtlTests/annotationTests/UnrecognizedAnnotationSpec.scala @@ -69,7 +69,8 @@ class UnrecognizedAnnotationSpec extends FirrtlFlatSpec { outputAnnotations: String, outputAnnotationsFull: String, firrtlSource: String, - firrtlOutput: String) + firrtlOutput: String + ) def setupFiles(addAllowUnrecognizedFlag: Boolean, addAllowUnrecognizedAnno: Boolean): TestFileNames = { val dirName = (addAllowUnrecognizedFlag, addAllowUnrecognizedAnno) match { diff --git a/firrtl/src/test/scala/firrtlTests/options/PhaseManagerSpec.scala b/firrtl/src/test/scala/firrtlTests/options/PhaseManagerSpec.scala index 248979dbbac..656e1285695 100644 --- a/firrtl/src/test/scala/firrtlTests/options/PhaseManagerSpec.scala +++ b/firrtl/src/test/scala/firrtlTests/options/PhaseManagerSpec.scala @@ -112,7 +112,7 @@ object ComplicatedFixture { override def prerequisites = Seq(Dependency[B]) override def invalidates(phase: Phase): Boolean = phase match { case _: C | _: E => true - case _ => false + case _ => false } } class E extends IdentityPhase { @@ -162,14 +162,14 @@ object InvertedAnalysisFixture { override def prerequisites = Seq(Dependency[Analysis]) override def invalidates(phase: Phase): Boolean = phase match { case _: Analysis | _: A => true - case _ => false + case _ => false } } class C extends IdentityPhase { override def prerequisites = Seq(Dependency[Analysis]) override def invalidates(phase: Phase): Boolean = phase match { case _: Analysis | _: B => true - case _ => false + case _ => false } } diff --git a/firrtl/src/test/scala/firrtlTests/options/phases/GetIncludesSpec.scala b/firrtl/src/test/scala/firrtlTests/options/phases/GetIncludesSpec.scala index 9474040892a..7fc0d723a43 100644 --- a/firrtl/src/test/scala/firrtlTests/options/phases/GetIncludesSpec.scala +++ b/firrtl/src/test/scala/firrtlTests/options/phases/GetIncludesSpec.scala @@ -41,11 +41,10 @@ class GetIncludesSpec extends AnyFlatSpec with Matchers with firrtl.testutils.Ut new File(dir, "e.anno.json") -> Seq(E) ) - files.foreach { - case (file, annotations) => - val pw = new PrintWriter(file) - pw.write(JsonProtocol.serialize(annotations)) - pw.close() + files.foreach { case (file, annotations) => + val pw = new PrintWriter(file) + pw.write(JsonProtocol.serialize(annotations)) + pw.close() } class Fixture { val phase: Phase = new GetIncludes } diff --git a/firrtl/src/test/scala/firrtlTests/options/phases/WriteOutputAnnotationsSpec.scala b/firrtl/src/test/scala/firrtlTests/options/phases/WriteOutputAnnotationsSpec.scala index 89a330b56cd..b5a80bbd0ab 100644 --- a/firrtl/src/test/scala/firrtlTests/options/phases/WriteOutputAnnotationsSpec.scala +++ b/firrtl/src/test/scala/firrtlTests/options/phases/WriteOutputAnnotationsSpec.scala @@ -45,10 +45,9 @@ class WriteOutputAnnotationsSpec extends AnyFlatSpec with Matchers with firrtl.t read .zip(a) - .foreach { - case (read, expected) => - info(s"$read matches") - read should be(expected) + .foreach { case (read, expected) => + info(s"$read matches") + read should be(expected) } f.delete() diff --git a/integration-tests/src/test/scala/chiselTest/LFSRSpec.scala b/integration-tests/src/test/scala/chiselTest/LFSRSpec.scala index 5d6db231006..36ec1cf3902 100644 --- a/integration-tests/src/test/scala/chiselTest/LFSRSpec.scala +++ b/integration-tests/src/test/scala/chiselTest/LFSRSpec.scala @@ -107,7 +107,7 @@ class LFSRSpec extends ChiselFlatSpec with Utils { def periodCheck(gen: (Int, Set[Int], LFSRReduce) => PRNG, reduction: LFSRReduce, range: Range): Unit = { val testName = s"have a maximal period over a range of widths (${range.head} to ${range.last})" + s" using ${reduction.getClass}" - //TODO: SFC->MFC, these tests fail due to a bootstrap problem under MFC in LFSRMaxPeriod + // TODO: SFC->MFC, these tests fail due to a bootstrap problem under MFC in LFSRMaxPeriod it should testName ignore { range.foreach { width => LFSR.tapsMaxPeriod(width).foreach { taps => diff --git a/integration-tests/src/test/scala/chiselTest/MixedVecIntegrationSpec.scala b/integration-tests/src/test/scala/chiselTest/MixedVecIntegrationSpec.scala index 4f6385c0a85..050dfd2c31f 100644 --- a/integration-tests/src/test/scala/chiselTest/MixedVecIntegrationSpec.scala +++ b/integration-tests/src/test/scala/chiselTest/MixedVecIntegrationSpec.scala @@ -175,29 +175,26 @@ class MixedVecIntegrationSpec 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))) + } } } diff --git a/integration-tests/src/test/scala/chiselTest/QueueFlushSpec.scala b/integration-tests/src/test/scala/chiselTest/QueueFlushSpec.scala index 0120b0b982c..15f324b29a2 100644 --- a/integration-tests/src/test/scala/chiselTest/QueueFlushSpec.scala +++ b/integration-tests/src/test/scala/chiselTest/QueueFlushSpec.scala @@ -20,8 +20,8 @@ class ThingsPassThroughFlushQueueTester( queueDepth: Int, bitWidth: Int, tap: Int, - useSyncReadMem: Boolean) - extends ThingsPassThroughTester(elements, queueDepth, bitWidth, tap, useSyncReadMem, hasFlush = true) + useSyncReadMem: Boolean +) extends ThingsPassThroughTester(elements, queueDepth, bitWidth, tap, useSyncReadMem, hasFlush = true) /** Generic flush queue tester base class * @@ -36,8 +36,8 @@ abstract class FlushQueueTesterBase( queueDepth: Int, bitWidth: Int, tap: Int, - useSyncReadMem: Boolean) - extends BasicTester { + 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) @@ -53,13 +53,13 @@ abstract class FlushQueueTesterBase( q.io.enq.bits := elems(inCnt.value) when(q.io.enq.fire) { inCnt.inc() - currQCnt := currQCnt + 1.U //counts how many items have been enqueued + currQCnt := currQCnt + 1.U // counts how many items have been enqueued } when(q.io.deq.fire) { - assert(flushRegister === false.B) //check queue isn't flushed (can't dequeue an empty queue) + assert(flushRegister === false.B) // check queue isn't flushed (can't dequeue an empty queue) } - when(flushRegister) { //Internal signal maybe_full is a register so some signals update on the next cycle - //check that queue gets flushed when queue is full + when(flushRegister) { // Internal signal maybe_full is a register so some signals update on the next cycle + // 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( @@ -67,7 +67,7 @@ abstract class FlushQueueTesterBase( "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 + when(inCnt.value === elements.length.U) { // stop when all entries are enqueued stop() } } @@ -82,11 +82,11 @@ abstract class FlushQueueTesterBase( */ 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 + 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 + // ensure that what comes out is what comes in assert(currQCnt <= queueDepth.U) assert(elems(outCnt) === q.io.deq.bits) outCnt := outCnt + 1.U @@ -97,7 +97,7 @@ class QueueGetsFlushedTester(elements: Seq[Int], queueDepth: Int, bitWidth: Int, when(flush) { assert(currQCnt === 0.U || q.io.deq.valid) outCnt := outCnt + Mux(q.io.enq.fire, (currQCnt + 1.U), currQCnt) - currQCnt := 0.U //resets the number of items currently inside queue + currQCnt := 0.U // resets the number of items currently inside queue } } @@ -112,10 +112,10 @@ class QueueGetsFlushedTester(elements: Seq[Int], queueDepth: Int, bitWidth: Int, 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 + 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 + // testing a flush when queue is empty + 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) { @@ -137,19 +137,19 @@ class EnqueueEmptyFlushEdgecaseTester( queueDepth: Int, bitWidth: Int, tap: Int, - useSyncReadMem: Boolean) - extends FlushQueueTesterBase(elements, queueDepth, bitWidth, tap, useSyncReadMem) { + 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 - cycleCounter.inc() //counts every cycle + // testing an enqueue during a flush + 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, - //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 + // 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() } } @@ -167,14 +167,14 @@ class FullQueueFlushEdgecaseTester( queueDepth: Int, bitWidth: Int, tap: Int, - useSyncReadMem: Boolean) - extends FlushQueueTesterBase(elements, queueDepth, bitWidth, tap, useSyncReadMem) { + useSyncReadMem: Boolean +) extends FlushQueueTesterBase(elements, queueDepth, bitWidth, tap, useSyncReadMem) { - //testing a flush when queue is full + // testing a flush when queue is full flush := (currQCnt === queueDepth.U) when(q.io.deq.fire) { - //ensure that what comes out is what comes in + // ensure that what comes out is what comes in assert(currQCnt <= queueDepth.U) assert(elems(outCnt) === q.io.deq.bits) outCnt := outCnt + 1.U @@ -184,7 +184,7 @@ class FullQueueFlushEdgecaseTester( } when(flush) { outCnt := outCnt + currQCnt - currQCnt := 0.U //resets the number of items currently inside queue + currQCnt := 0.U // resets the number of items currently inside queue assert(currQCnt === 0.U || q.io.deq.valid) } } @@ -202,29 +202,29 @@ class DequeueFullQueueEdgecaseTester( 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 + 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 + // testing a flush when dequeue is called flush := currQCnt === (queueDepth / 2).U q.io.enq.valid := !flushRegister q.io.deq.ready := flush when(q.io.deq.fire) { - //ensure that what comes out is what comes in + // ensure that what comes out is what comes in assert(currQCnt <= queueDepth.U) assert(elems(outCnt) === q.io.deq.bits) assert(currQCnt > 0.U) } when(flush) { - //The outcount register is one count behind because the dequeue happens at the same time as the flush + // The outcount register is one count behind because the dequeue happens at the same time as the flush outCnt := outCnt + currQCnt + 1.U - currQCnt := 0.U //resets the number of items currently inside queue + 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 + // check that queue gets flushed when queue is full assert(q.io.deq.fire === false.B) } diff --git a/integration-tests/src/test/scala/chiselTest/QueueSpec.scala b/integration-tests/src/test/scala/chiselTest/QueueSpec.scala index 439c4753a52..8a5faa77f2c 100644 --- a/integration-tests/src/test/scala/chiselTest/QueueSpec.scala +++ b/integration-tests/src/test/scala/chiselTest/QueueSpec.scala @@ -15,8 +15,8 @@ class ThingsPassThroughTester( bitWidth: Int, tap: Int, useSyncReadMem: Boolean, - hasFlush: Boolean) - extends BasicTester { + hasFlush: Boolean +) extends BasicTester { val q = Module(new Queue(UInt(bitWidth.W), queueDepth, useSyncReadMem = useSyncReadMem, hasFlush = hasFlush)) val elems = VecInit(elements.map { _.asUInt @@ -26,13 +26,13 @@ class ThingsPassThroughTester( q.io.enq.valid := (inCnt.value < elements.length.U) q.io.deq.ready := LFSR(16)(tap) - q.io.flush.foreach { _ := false.B } //Flush behavior is tested in QueueFlushSpec + q.io.flush.foreach { _ := false.B } // Flush behavior is tested in QueueFlushSpec q.io.enq.bits := elems(inCnt.value) when(q.io.enq.fire) { inCnt.inc() } when(q.io.deq.fire) { - //ensure that what comes out is what comes in + // ensure that what comes out is what comes in assert(elems(outCnt.value) === q.io.deq.bits) outCnt.inc() } @@ -51,11 +51,11 @@ class QueueReasonableReadyValid(elements: Seq[Int], queueDepth: Int, bitWidth: I val outCnt = Counter(elements.length + 1) q.io.enq.valid := (inCnt.value < elements.length.U) - //Queue should be full or ready + // Queue should be full or ready assert(q.io.enq.ready || q.io.count === queueDepth.U) q.io.deq.ready := LFSR(16)(tap) - //Queue should be empty or valid + // Queue should be empty or valid assert(q.io.deq.valid || q.io.count === 0.U) q.io.enq.bits := elems(inCnt.value) @@ -91,7 +91,7 @@ class CountIsCorrectTester(elements: Seq[Int], queueDepth: Int, bitWidth: Int, t outCnt.inc() assert(q.io.count === (inCnt.value - outCnt.value)) } - //assert(q.io.count === (inCnt.value - outCnt.value)) + // assert(q.io.count === (inCnt.value - outCnt.value)) when(outCnt.value === elements.length.U) { stop() @@ -161,11 +161,11 @@ class QueueFlowTester(elements: Seq[Int], queueDepth: Int, bitWidth: Int, tap: I val outCnt = Counter(elements.length + 1) q.io.enq.valid := (inCnt.value < elements.length.U) - //Queue should be full or ready + // Queue should be full or ready assert(q.io.enq.ready || q.io.count === queueDepth.U) q.io.deq.ready := LFSR(16)(tap) - //Queue should be empty or valid + // Queue should be empty or valid assert(q.io.deq.valid || (q.io.count === 0.U && !q.io.enq.fire)) q.io.enq.bits := elems(inCnt.value) @@ -199,7 +199,7 @@ class QueueFactoryTester(elements: Seq[Int], queueDepth: Int, bitWidth: Int, tap inCnt.inc() } when(deq.fire) { - //ensure that what comes out is what comes in + // ensure that what comes out is what comes in assert(elems(outCnt.value) === deq.bits) outCnt.inc() } diff --git a/integration-tests/src/test/scala/chiselTest/VecIntegrationSpec.scala b/integration-tests/src/test/scala/chiselTest/VecIntegrationSpec.scala index f6b57e2f099..650bbdf6808 100644 --- a/integration-tests/src/test/scala/chiselTest/VecIntegrationSpec.scala +++ b/integration-tests/src/test/scala/chiselTest/VecIntegrationSpec.scala @@ -44,9 +44,8 @@ class VecIntegrationSpec extends ChiselPropSpec { } } - 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) } } } diff --git a/integration-tests/src/test/scala/chiselTest/util/SparseVecSpec.scala b/integration-tests/src/test/scala/chiselTest/util/SparseVecSpec.scala index 7f0c74a3b51..a4977edf94b 100644 --- a/integration-tests/src/test/scala/chiselTest/util/SparseVecSpec.scala +++ b/integration-tests/src/test/scala/chiselTest/util/SparseVecSpec.scala @@ -20,11 +20,7 @@ import java.util.ResourceBundle * @param tpe the type of the vecs * @param mapping a mapping of index to value */ -class SparseVecDynamicIndexEquivalenceTest( - size: Int, - tpe: UInt, - mapping: Seq[(Int, UInt)], - debug: Boolean = false) +class SparseVecDynamicIndexEquivalenceTest(size: Int, tpe: UInt, mapping: Seq[(Int, UInt)], debug: Boolean = false) extends BasicTester { // The number of indices that needs to be checked. This is larger than `size` @@ -38,9 +34,8 @@ class SparseVecDynamicIndexEquivalenceTest( private val denseVec = { val w = Wire(Vec(size, tpe)) w.foreach(_ := DontCare) - mapping.foreach { - case (index, data) => - w(index) := data + mapping.foreach { case (index, data) => + w(index) := data } w } @@ -98,8 +93,8 @@ class SparseVecTest( outOfBoundsBehavior: OutOfBoundsBehavior.Type, mapping: Seq[(Int, UInt)], expected: Seq[(Int, Data)], - debug: Boolean = false) - extends BasicTester { + debug: Boolean = false +) extends BasicTester { // Create a wire SparseVec and initialize it to the values in the mapping. private val sparseVec = Wire(new SparseVec(size, tpe, mapping.map(_._1), defaultValueBehavior, outOfBoundsBehavior)) sparseVec.elements.values.zip(mapping.map(_._2)).foreach { case (a, b) => a :<>= b } @@ -115,10 +110,9 @@ class SparseVecTest( new TestBundle ) ) - expected.zipWithIndex.foreach { - case ((index, value), testNumber) => - tests(testNumber).index := index.U - tests(testNumber).value := value + expected.zipWithIndex.foreach { case ((index, value), testNumber) => + tests(testNumber).index := index.U + tests(testNumber).value := value } // Access the dense vector and the sparse vector, using all of the access diff --git a/integration-tests/src/test/scala/chiselTest/util/experimental/PlaSpec.scala b/integration-tests/src/test/scala/chiselTest/util/experimental/PlaSpec.scala index 156249a2b41..bd6c7bd76b3 100644 --- a/integration-tests/src/test/scala/chiselTest/util/experimental/PlaSpec.scala +++ b/integration-tests/src/test/scala/chiselTest/util/experimental/PlaSpec.scala @@ -19,15 +19,14 @@ class PlaSpec extends ChiselFlatSpec { (BitPat("b110"), BitPat("b01000000")), (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() }) @@ -45,15 +44,14 @@ class PlaSpec extends ChiselFlatSpec { (BitPat("b110"), BitPat("b01000000")), (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() }) @@ -65,11 +63,10 @@ class PlaSpec extends ChiselFlatSpec { (BitPat("b000"), 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() }) @@ -95,15 +92,14 @@ class PlaSpec extends ChiselFlatSpec { (BitPat("b1110"), 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/lit/utility/src/package.scala b/lit/utility/src/package.scala index 242d184011b..5c9e98d2019 100644 --- a/lit/utility/src/package.scala +++ b/lit/utility/src/package.scala @@ -15,9 +15,8 @@ package object lit { ).foldLeft( firrtl.AnnotationSeq(Seq(chisel3.stage.ChiselGeneratorAnnotation(() => module))) ) { case (annos, phase) => phase.transform(annos) } - .collectFirst { - case chisel3.panamaconverter.stage.PanamaCIRCTConverterAnnotation(converter) => - converter + .collectFirst { case chisel3.panamaconverter.stage.PanamaCIRCTConverterAnnotation(converter) => + converter } .get diff --git a/macros/src/main/scala/chisel3/internal/naming/Identifier.scala b/macros/src/main/scala/chisel3/internal/naming/Identifier.scala index 7a07471c8ed..a1828bed157 100644 --- a/macros/src/main/scala/chisel3/internal/naming/Identifier.scala +++ b/macros/src/main/scala/chisel3/internal/naming/Identifier.scala @@ -33,7 +33,7 @@ private[chisel3] object identifyMacro { val newMethod = q"override protected def _traitModuleDefinitionIdentifierProposal = Some(${tpname.toString})" val newStats = newMethod +: stats ( - q"$mods trait $tpname[..$tparams] extends { ..$earlydefns } with ..$parents { $self => ..$newStats }", + q"$mods trait $tpname[..$tparams] extends { ..$earlydefns } with ..$parents { $self => ..$newStats }" ) case _ => c.error(c.enclosingPosition, "Can only use @identify on traits, not classes, objects, vals, or defs") diff --git a/macros/src/main/scala/chisel3/internal/sourceinfo/SourceInfoTransform.scala b/macros/src/main/scala/chisel3/internal/sourceinfo/SourceInfoTransform.scala index 76d07a0d908..47220ed9bbd 100644 --- a/macros/src/main/scala/chisel3/internal/sourceinfo/SourceInfoTransform.scala +++ b/macros/src/main/scala/chisel3/internal/sourceinfo/SourceInfoTransform.scala @@ -260,8 +260,7 @@ class SourceInfoTransform(val c: Context) extends AutoSourceTransform { mask: c.Tree, en: c.Tree, isWrite: c.Tree - )(evidence: c.Tree - ): c.Tree = { + )(evidence: c.Tree): c.Tree = { q"$thisObj.$doFuncTerm($idx, $writeData, $mask, $en, $isWrite)($evidence, $implicitSourceInfo)" } @@ -272,8 +271,7 @@ class SourceInfoTransform(val c: Context) extends AutoSourceTransform { en: c.Tree, isWrite: c.Tree, clock: c.Tree - )(evidence: c.Tree - ): c.Tree = { + )(evidence: c.Tree): c.Tree = { q"$thisObj.$doFuncTerm($idx, $writeData, $mask, $en, $isWrite, $clock)($evidence, $implicitSourceInfo)" } diff --git a/panamaconverter/src/Convert.scala b/panamaconverter/src/Convert.scala index 10b14396a58..fdb34c91d33 100644 --- a/panamaconverter/src/Convert.scala +++ b/panamaconverter/src/Convert.scala @@ -28,8 +28,8 @@ object Convert extends Phase { PanamaCIRCTConverterAnnotation( PanamaCIRCTConverter.convert( circuit, - annotations.collectFirst { - case FirtoolOptionsAnnotation(firtoolOptions) => firtoolOptions + annotations.collectFirst { case FirtoolOptionsAnnotation(firtoolOptions) => + firtoolOptions }, firrtl.annotations.JsonProtocol.serialize(circuit.firrtlAnnotations.filter { anno => Seq( diff --git a/panamaconverter/src/PanamaCIRCTConverter.scala b/panamaconverter/src/PanamaCIRCTConverter.scala index 5da12f316c4..6c8951d89fe 100644 --- a/panamaconverter/src/PanamaCIRCTConverter.scala +++ b/panamaconverter/src/PanamaCIRCTConverter.scala @@ -25,7 +25,7 @@ import chisel3.stop.{Stop => VerifStop} import chisel3.util._ case class Region(region: MlirRegion, blocks: Seq[MlirBlock]) { - def get(): MlirRegion = region + def get(): MlirRegion = region def block(i: Int): MlirBlock = blocks(i) } @@ -44,7 +44,8 @@ case class Ports( typeAttrs: Seq[MlirAttribute], annotationAttrs: Seq[MlirAttribute], symAttrs: Seq[MlirAttribute], - locAttrs: Seq[MlirAttribute]) + locAttrs: Seq[MlirAttribute] +) final case class FirTypeLazy(private var tpeOrData: Either[fir.Type, ChiselData]) { def get: fir.Type = { @@ -122,9 +123,8 @@ class InnerSymCache { slots += ((id._id, InnerSymSlot.Op(op))) def setPortSlots(op: MlirOperation, ports: Seq[Port]): Unit = { portSyms = ports.map(_ => None) - ports.zipWithIndex.foreach { - case (port, i) => - slots += ((port.id._id, InnerSymSlot.Port(op, i))) + ports.zipWithIndex.foreach { case (port, i) => + slots += ((port.id._id, InnerSymSlot.Port(op, i))) } } @@ -156,16 +156,16 @@ class FirContext { } def enterWhen(whenOp: Op): Unit = whenStack.push(WhenContext(whenOp, currentBlock, false)) - def enterAlt(): Unit = whenStack.top.inAlt = true - def leaveWhen(): Unit = whenStack.pop + def enterAlt(): Unit = whenStack.top.inAlt = true + def leaveWhen(): Unit = whenStack.pop - def circuitBlock: MlirBlock = opCircuit.region(0).block(0) + def circuitBlock: MlirBlock = opCircuit.region(0).block(0) def findModuleBlock(name: String): MlirBlock = opModules.find(_._1 == name).get._2.region(0).block(0) - def currentModuleName: String = opModules.last._1 - def currentModuleBlock: MlirBlock = opModules.last._2.region(0).block(0) - def currentBlock: MlirBlock = if (whenStack.nonEmpty) whenStack.top.block else currentModuleBlock - def currentWhen: Option[WhenContext] = Option.when(whenStack.nonEmpty)(whenStack.top) - def rootWhen: Option[WhenContext] = Option.when(whenStack.nonEmpty)(whenStack.last) + def currentModuleName: String = opModules.last._1 + def currentModuleBlock: MlirBlock = opModules.last._2.region(0).block(0) + def currentBlock: MlirBlock = if (whenStack.nonEmpty) whenStack.top.block else currentModuleBlock + def currentWhen: Option[WhenContext] = Option.when(whenStack.nonEmpty)(whenStack.top) + def rootWhen: Option[WhenContext] = Option.when(whenStack.nonEmpty)(whenStack.last) } class PanamaCIRCTConverter(val circt: PanamaCIRCT, fos: Option[FirtoolOptions], annotationsJSON: String) { @@ -190,8 +190,8 @@ class PanamaCIRCTConverter(val circt: PanamaCIRCT, fos: Option[FirtoolOptions], case fir.AnalogType(width) => getWidthOrSentinel(width) case fir.ProbeType(underlying, _) => getWidthOrSentinel(underlying) case fir.RWProbeType(underlying, _) => getWidthOrSentinel(underlying) - case _: fir.BundleType | _: fir.VectorType => -2 - case unhandled => throw new Exception(s"unhandled: $unhandled") + case _: fir.BundleType | _: fir.VectorType => -2 + case unhandled => throw new Exception(s"unhandled: $unhandled") } } @@ -289,7 +289,7 @@ class PanamaCIRCTConverter(val circt: PanamaCIRCT, fos: Option[FirtoolOptions], def widthShl(lhs: fir.Width, rhs: fir.Width): fir.Width = (lhs, rhs) match { case (l: fir.IntWidth, r: fir.IntWidth) => fir.IntWidth(l.width << r.width.toInt) - case _ => fir.UnknownWidth + case _ => fir.UnknownWidth } case class OpBuilder(opName: String, parent: MlirBlock, loc: MlirLocation) { @@ -321,12 +321,12 @@ class PanamaCIRCTConverter(val circt: PanamaCIRCT, fos: Option[FirtoolOptions], this } - def withOperand(o: MlirValue): OpBuilder = { operands = operands :+ o; this } + def withOperand(o: MlirValue): OpBuilder = { operands = operands :+ o; this } def withOperands(os: Seq[MlirValue]): OpBuilder = { operands = operands ++ os; this } - def withResult(r: MlirType): OpBuilder = { results = results :+ r; this } - def withResults(rs: Seq[MlirType]): OpBuilder = { results = results ++ rs; this } - def withResultInference(expectedCount: Int): OpBuilder = { resultInference = Some(expectedCount); this } + def withResult(r: MlirType): OpBuilder = { results = results :+ r; this } + def withResults(rs: Seq[MlirType]): OpBuilder = { results = results ++ rs; this } + def withResultInference(expectedCount: Int): OpBuilder = { resultInference = Some(expectedCount); this } private[OpBuilder] def buildImpl(inserter: MlirOperation => Unit): Op = { val state = circt.mlirOperationStateGet(opName, loc) @@ -368,7 +368,7 @@ class PanamaCIRCTConverter(val circt: PanamaCIRCT, fos: Option[FirtoolOptions], Op(state, op, builtRegions, resultVals) } - def build(): Op = buildImpl(circt.mlirBlockAppendOwnedOperation(parent, _)) + def build(): Op = buildImpl(circt.mlirBlockAppendOwnedOperation(parent, _)) def buildAfter(ref: Op): Op = buildImpl(circt.mlirBlockInsertOwnedOperationAfter(parent, ref.op, _)) def buildBefore(ref: Op): Op = buildImpl(circt.mlirBlockInsertOwnedOperationBefore(parent, ref.op, _)) } @@ -812,13 +812,12 @@ class PanamaCIRCTConverter(val circt: PanamaCIRCT, fos: Option[FirtoolOptions], RecursiveTypeProperties(true, false) case _: fir.AnalogType => RecursiveTypeProperties(true, true) case bundle: fir.BundleType => - bundle.fields.foldLeft(RecursiveTypeProperties(true, false)) { - case (properties, field) => - val fieldProperties = recursiveTypeProperties(field.tpe) - RecursiveTypeProperties( - properties.isPassive && fieldProperties.isPassive && field.flip == fir.Flip, - properties.containsAnalog || fieldProperties.containsAnalog - ) + bundle.fields.foldLeft(RecursiveTypeProperties(true, false)) { case (properties, field) => + val fieldProperties = recursiveTypeProperties(field.tpe) + RecursiveTypeProperties( + properties.isPassive && fieldProperties.isPassive && field.flip == fir.Flip, + properties.containsAnalog || fieldProperties.containsAnalog + ) } case _: fir.PropertyType => RecursiveTypeProperties(true, false) case vector: fir.VectorType => recursiveTypeProperties(vector.tpe) @@ -881,19 +880,18 @@ class PanamaCIRCTConverter(val circt: PanamaCIRCT, fos: Option[FirtoolOptions], val indexType = circt.mlirIntegerTypeGet(32) value.tpe match { case bundle: fir.BundleType => - bundle.fields.zipWithIndex.foreach { - case (field, index) => - val fieldAccess = Reference.Value( - util - .OpBuilder("firrtl.subfield", firCtx.currentBlock, loc) - .withNamedAttr("fieldIndex", circt.mlirIntegerAttrGet(indexType, index)) - .withOperand(value.value) - .withResult(util.convert(field.tpe)) - .build() - .results(0), - field.tpe - ) - emitInvalidate(fieldAccess, loc, if (field.flip == fir.Flip) swapFlow(flow) else flow) + bundle.fields.zipWithIndex.foreach { case (field, index) => + val fieldAccess = Reference.Value( + util + .OpBuilder("firrtl.subfield", firCtx.currentBlock, loc) + .withNamedAttr("fieldIndex", circt.mlirIntegerAttrGet(indexType, index)) + .withOperand(value.value) + .withResult(util.convert(field.tpe)) + .build() + .results(0), + field.tpe + ) + emitInvalidate(fieldAccess, loc, if (field.flip == fir.Flip) swapFlow(flow) else flow) } case vector: fir.VectorType => for (index <- 0 until vector.size) { @@ -1874,8 +1872,8 @@ object PanamaCIRCTConverter { private def visitCommand(parent: Component, cmd: Command)(implicit cvt: PanamaCIRCTConverter): Unit = { cmd match { - case attach: Attach => visitAttach(attach) - case connect: Connect => visitConnect(connect) + case attach: Attach => visitAttach(attach) + case connect: Connect => visitConnect(connect) case defInvalid: DefInvalid => visitDefInvalid(defInvalid) case when: When => visitWhen( diff --git a/panamaconverter/src/PanamaCIRCTPassManager.scala b/panamaconverter/src/PanamaCIRCTPassManager.scala index 70528c77254..15855a88b4d 100644 --- a/panamaconverter/src/PanamaCIRCTPassManager.scala +++ b/panamaconverter/src/PanamaCIRCTPassManager.scala @@ -9,7 +9,8 @@ import chisel3.panamalib.option.PanamaFirtoolOption.FirtoolOptionsToPanama private[panamaconverter] class PanamaCIRCTPassManager( circt: PanamaCIRCT, mlirModule: MlirModule, - fos: Option[FirtoolOptions]) { + fos: Option[FirtoolOptions] +) { val pm = circt.mlirPassManagerCreate() val options = fos.map(_.toPanama(circt)).getOrElse(circt.circtFirtoolOptionsCreateDefault()) diff --git a/panamalib/src/PanamaCIRCT.scala b/panamalib/src/PanamaCIRCT.scala index c78591f9dfb..3d4d4e96d9a 100644 --- a/panamalib/src/PanamaCIRCT.scala +++ b/panamalib/src/PanamaCIRCT.scala @@ -72,12 +72,11 @@ class PanamaCIRCT { val sizeOfT = xs(0).sizeof val buffer = arena.allocate(sizeOfT * xs.length) - xs.zipWithIndex.foreach { - case (x, i) => - x.get match { - case value: MemorySegment => buffer.asSlice(sizeOfT * i, sizeOfT).copyFrom(value) - case value: Int => buffer.setAtIndex(CAPI.C_INT, i, value) - } + xs.zipWithIndex.foreach { case (x, i) => + x.get match { + case value: MemorySegment => buffer.asSlice(sizeOfT * i, sizeOfT).copyFrom(value) + case value: Int => buffer.setAtIndex(CAPI.C_INT, i, value) + } } (buffer, xs.length) } else { @@ -290,7 +289,7 @@ class PanamaCIRCT { ) def circtFirtoolOptionsCreateDefault() = CirctFirtoolFirtoolOptions(CAPI.circtFirtoolOptionsCreateDefault(arena)) - def circtFirtoolOptionsDestroy(options: CirctFirtoolFirtoolOptions) = CAPI.circtFirtoolOptionsDestroy(options.get) + def circtFirtoolOptionsDestroy(options: CirctFirtoolFirtoolOptions) = CAPI.circtFirtoolOptionsDestroy(options.get) def circtFirtoolOptionsSetOutputFilename(options: CirctFirtoolFirtoolOptions, value: String) = CAPI.circtFirtoolOptionsSetOutputFilename(options.get, newString(value).get) def circtFirtoolOptionsSetDisableUnknownAnnotations(options: CirctFirtoolFirtoolOptions, value: Boolean) = @@ -438,12 +437,11 @@ class PanamaCIRCT { def firrtlTypeGetBundle(fields: Seq[FIRRTLBundleField]): MlirType = { val buffer = circt.FIRRTLBundleField.allocateArray(fields.length, arena) - fields.zipWithIndex.foreach { - case (field, i) => - val fieldBuffer = buffer.asSlice(circt.FIRRTLBundleField.sizeof() * i, circt.FIRRTLBundleField.sizeof()) - circt.FIRRTLBundleField.name$slice(fieldBuffer).copyFrom(mlirIdentifierGet(field.name).get) - circt.FIRRTLBundleField.isFlip$set(fieldBuffer, field.isFlip) - circt.FIRRTLBundleField.type$slice(fieldBuffer).copyFrom(field.tpe.get) + fields.zipWithIndex.foreach { case (field, i) => + val fieldBuffer = buffer.asSlice(circt.FIRRTLBundleField.sizeof() * i, circt.FIRRTLBundleField.sizeof()) + circt.FIRRTLBundleField.name$slice(fieldBuffer).copyFrom(mlirIdentifierGet(field.name).get) + circt.FIRRTLBundleField.isFlip$set(fieldBuffer, field.isFlip) + circt.FIRRTLBundleField.type$slice(fieldBuffer).copyFrom(field.tpe.get) } MlirType(CAPI.firrtlTypeGetBundle(arena, mlirCtx, fields.length, buffer)) } @@ -473,12 +471,11 @@ class PanamaCIRCT { def firrtlTypeGetClass(name: MlirAttribute /* FlatSymbolRefAttr */, elements: Seq[FIRRTLClassElement]): MlirType = { val buffer = circt.FIRRTLClassElement.allocateArray(elements.length, arena) - elements.zipWithIndex.foreach { - case (element, i) => - val elementBuffer = buffer.asSlice(circt.FIRRTLClassElement.sizeof() * i, circt.FIRRTLClassElement.sizeof()) - circt.FIRRTLClassElement.name$slice(elementBuffer).copyFrom(mlirIdentifierGet(element.name).get) - circt.FIRRTLClassElement.type$slice(elementBuffer).copyFrom(element.tpe.get) - circt.FIRRTLClassElement.direction$set(elementBuffer, element.direction.get) + elements.zipWithIndex.foreach { case (element, i) => + val elementBuffer = buffer.asSlice(circt.FIRRTLClassElement.sizeof() * i, circt.FIRRTLClassElement.sizeof()) + circt.FIRRTLClassElement.name$slice(elementBuffer).copyFrom(mlirIdentifierGet(element.name).get) + circt.FIRRTLClassElement.type$slice(elementBuffer).copyFrom(element.tpe.get) + circt.FIRRTLClassElement.direction$set(elementBuffer, element.direction.get) } MlirType(CAPI.firrtlTypeGetClass(arena, mlirCtx, name.get, elements.length, buffer)) } @@ -582,13 +579,13 @@ class PanamaCIRCT { ) } def omEvaluatorGetModule(evaluator: OMEvaluator) = MlirModule(CAPI.omEvaluatorGetModule(arena, evaluator.get)) - def omEvaluatorObjectIsNull(obj: OMEvaluatorValue): Boolean = CAPI.omEvaluatorObjectIsNull(obj.get) + def omEvaluatorObjectIsNull(obj: OMEvaluatorValue): Boolean = CAPI.omEvaluatorObjectIsNull(obj.get) def omEvaluatorObjectGetType(obj: OMEvaluatorValue) = MlirType(CAPI.omEvaluatorObjectGetType(arena, obj.get)) - def omEvaluatorObjectGetField(obj: OMEvaluatorValue, name: String) = OMEvaluatorValue( + def omEvaluatorObjectGetField(obj: OMEvaluatorValue, name: String) = OMEvaluatorValue( CAPI.omEvaluatorObjectGetField(arena, obj.get, mlirStringAttrGet(name).get) ) def omEvaluatorObjectGetHash(obj: OMEvaluatorValue): Int = CAPI.omEvaluatorObjectGetHash(obj.get) - def omEvaluatorObjectIsEq(obj: OMEvaluatorValue, other: OMEvaluatorValue): Boolean = + def omEvaluatorObjectIsEq(obj: OMEvaluatorValue, other: OMEvaluatorValue): Boolean = CAPI.omEvaluatorObjectIsEq(obj.get, other.get) def omEvaluatorObjectGetFieldNames(obj: OMEvaluatorValue) = MlirAttribute( CAPI.omEvaluatorObjectGetFieldNames(arena, obj.get) @@ -625,7 +622,7 @@ class PanamaCIRCT { def omEvaluatorMapGetElement(evaluatorValue: OMEvaluatorValue, attr: MlirAttribute) = OMEvaluatorValue( CAPI.omEvaluatorMapGetElement(arena, evaluatorValue.get, attr.get) ) - def omEvaluatorMapGetKeys(obj: OMEvaluatorValue) = MlirAttribute(CAPI.omEvaluatorMapGetKeys(arena, obj.get)) + def omEvaluatorMapGetKeys(obj: OMEvaluatorValue) = MlirAttribute(CAPI.omEvaluatorMapGetKeys(arena, obj.get)) def omEvaluatorValueIsAMap(evaluatorValue: OMEvaluatorValue): Boolean = CAPI.omEvaluatorValueIsAMap(evaluatorValue.get) def omEvaluatorMapGetType(evaluatorValue: OMEvaluatorValue): MlirType = MlirType( @@ -650,12 +647,12 @@ class PanamaCIRCT { def omIntegerAttrGet(attr: MlirAttribute) = MlirAttribute(CAPI.omIntegerAttrGet(arena, attr.get)) def omAttrIsAListAttr(attr: MlirAttribute): Boolean = CAPI.omAttrIsAListAttr(attr.get) def omListAttrGetNumElements(attr: MlirAttribute): Long = CAPI.omListAttrGetNumElements(attr.get) - def omListAttrGetElement(attr: MlirAttribute, pos: Long) = MlirAttribute( + def omListAttrGetElement(attr: MlirAttribute, pos: Long) = MlirAttribute( CAPI.omListAttrGetElement(arena, attr.get, pos) ) def omAttrIsAMapAttr(attr: MlirAttribute): Boolean = CAPI.omAttrIsAMapAttr(attr.get) def omMapAttrGetNumElements(attr: MlirAttribute): Long = CAPI.omMapAttrGetNumElements(attr.get) - def omMapAttrGetElementKey(attr: MlirAttribute, pos: Long) = MlirIdentifier( + def omMapAttrGetElementKey(attr: MlirAttribute, pos: Long) = MlirIdentifier( CAPI.omMapAttrGetElementKey(arena, attr.get, pos) ) def omMapAttrGetElementValue(attr: MlirAttribute, pos: Long) = MlirAttribute( diff --git a/panamaom/src/PanamaCIRCTOM.scala b/panamaom/src/PanamaCIRCTOM.scala index 02ae166e2a4..bd65732950d 100644 --- a/panamaom/src/PanamaCIRCTOM.scala +++ b/panamaom/src/PanamaCIRCTOM.scala @@ -91,8 +91,8 @@ abstract class PanamaCIRCTOMEvaluatorValue { // Incomplete. currently for debugging purposes only override def toString: String = { this match { - case v: PanamaCIRCTOMEvaluatorValuePath => s"path{${v.toString}}" - case v: PanamaCIRCTOMEvaluatorValueList => s"[ ${v.elements.map(_.toString).mkString(", ")} ]" + case v: PanamaCIRCTOMEvaluatorValuePath => s"path{${v.toString}}" + case v: PanamaCIRCTOMEvaluatorValueList => s"[ ${v.elements.map(_.toString).mkString(", ")} ]" case v: PanamaCIRCTOMEvaluatorValuePrimitive => s"prim{${v.toString}}" case v: PanamaCIRCTOMEvaluatorValueObject => val subfields = v.fieldNames @@ -187,8 +187,8 @@ abstract class PanamaCIRCTOMEvaluatorValuePrimitive extends PanamaCIRCTOMEvaluat class PanamaCIRCTOMEvaluatorValuePrimitiveInteger private[chisel3] ( val circt: PanamaCIRCT, val value: OMEvaluatorValue, - val primitive: MlirAttribute) - extends PanamaCIRCTOMEvaluatorValuePrimitive { + val primitive: MlirAttribute +) extends PanamaCIRCTOMEvaluatorValuePrimitive { val integer: Long = circt.mlirIntegerAttrGetValueSInt(primitive) override def toString: String = integer.toString } @@ -196,8 +196,8 @@ class PanamaCIRCTOMEvaluatorValuePrimitiveInteger private[chisel3] ( class PanamaCIRCTOMEvaluatorValuePrimitiveString private[chisel3] ( val circt: PanamaCIRCT, val value: OMEvaluatorValue, - val primitive: MlirAttribute) - extends PanamaCIRCTOMEvaluatorValuePrimitive { + val primitive: MlirAttribute +) extends PanamaCIRCTOMEvaluatorValuePrimitive { override def toString: String = circt.mlirStringAttrGetValue(primitive) } diff --git a/plugin/src/main/scala/chisel3/internal/plugin/BundleComponent.scala b/plugin/src/main/scala/chisel3/internal/plugin/BundleComponent.scala index 73ec1a82e51..a3289c1de0a 100644 --- a/plugin/src/main/scala/chisel3/internal/plugin/BundleComponent.scala +++ b/plugin/src/main/scala/chisel3/internal/plugin/BundleComponent.scala @@ -27,8 +27,8 @@ private[plugin] class BundleComponent(val global: Global, arguments: ChiselPlugi with ChiselOuterUtils { import global._ - val phaseName: String = "chiselbundlephase" - val runsAfter: List[String] = "typer" :: Nil + val phaseName: String = "chiselbundlephase" + val runsAfter: List[String] = "typer" :: Nil def newPhase(prev: Phase): Phase = new BundlePhase(prev) private class BundlePhase(prev: Phase) extends StdPhase(prev) { diff --git a/plugin/src/main/scala/chisel3/internal/plugin/ChiselComponent.scala b/plugin/src/main/scala/chisel3/internal/plugin/ChiselComponent.scala index 2dab83b8c93..55ee919d7d9 100644 --- a/plugin/src/main/scala/chisel3/internal/plugin/ChiselComponent.scala +++ b/plugin/src/main/scala/chisel3/internal/plugin/ChiselComponent.scala @@ -18,8 +18,8 @@ class ChiselComponent(val global: Global, arguments: ChiselPluginArguments) with TypingTransformers with ChiselOuterUtils { import global._ - val runsAfter: List[String] = List[String]("typer") - val phaseName: String = "chiselcomponent" + val runsAfter: List[String] = List[String]("typer") + val phaseName: String = "chiselcomponent" def newPhase(_prev: Phase): ChiselComponentPhase = new ChiselComponentPhase(_prev) class ChiselComponentPhase(prev: Phase) extends StdPhase(prev) { override def name: String = phaseName diff --git a/plugin/src/main/scala/chisel3/internal/plugin/ChiselPlugin.scala b/plugin/src/main/scala/chisel3/internal/plugin/ChiselPlugin.scala index dcd6dd41bdf..77af68f0748 100644 --- a/plugin/src/main/scala/chisel3/internal/plugin/ChiselPlugin.scala +++ b/plugin/src/main/scala/chisel3/internal/plugin/ChiselPlugin.scala @@ -8,8 +8,7 @@ import nsc.plugins.{Plugin, PluginComponent} import scala.reflect.internal.util.NoPosition import scala.collection.mutable -private[plugin] case class ChiselPluginArguments( - val skipFiles: mutable.HashSet[String] = mutable.HashSet.empty) { +private[plugin] case class ChiselPluginArguments(val skipFiles: mutable.HashSet[String] = mutable.HashSet.empty) { var deprecateSFC: Boolean = true def useBundlePluginOpt = "useBundlePlugin" def useBundlePluginFullOpt = s"-P:${ChiselPlugin.name}:$useBundlePluginOpt" @@ -27,8 +26,7 @@ object ChiselPlugin { private[plugin] def runComponent( global: Global, arguments: ChiselPluginArguments - )(unit: global.CompilationUnit - ): Boolean = { + )(unit: global.CompilationUnit): Boolean = { // This plugin doesn't work on Scala 2.11 nor Scala 3. Rather than complicate the sbt build flow, // instead we just check the version and if its an early Scala version, the plugin does nothing val scalaVersion = scala.util.Properties.versionNumberString.split('.') diff --git a/plugin/src/main/scala/chisel3/internal/plugin/ChiselUtils.scala b/plugin/src/main/scala/chisel3/internal/plugin/ChiselUtils.scala index 9f0deceea4c..7285f746ed7 100644 --- a/plugin/src/main/scala/chisel3/internal/plugin/ChiselUtils.scala +++ b/plugin/src/main/scala/chisel3/internal/plugin/ChiselUtils.scala @@ -27,11 +27,11 @@ private[plugin] trait ChiselOuterUtils { outerSelf: TypingTransformers => def stringFromTypeName(name: TypeName): String = name.toString.trim() // Remove trailing space (Scalac implementation detail) - def isAModule(sym: Symbol): Boolean = { sym.tpe <:< baseModuleTpe } - def isExactBaseModule(sym: Symbol): Boolean = { sym.tpe =:= baseModuleTpe } - def isABundle(sym: Symbol): Boolean = { sym.tpe <:< bundleTpe } - def isAutoTypenamed(sym: Symbol): Boolean = { sym.tpe <:< autoTypenameTpe } - def isARecord(sym: Symbol): Boolean = { sym.tpe <:< recordTpe } + def isAModule(sym: Symbol): Boolean = { sym.tpe <:< baseModuleTpe } + def isExactBaseModule(sym: Symbol): Boolean = { sym.tpe =:= baseModuleTpe } + def isABundle(sym: Symbol): Boolean = { sym.tpe <:< bundleTpe } + def isAutoTypenamed(sym: Symbol): Boolean = { sym.tpe <:< autoTypenameTpe } + def isARecord(sym: Symbol): Boolean = { sym.tpe <:< recordTpe } def isIgnoreSeqInBundle(sym: Symbol): Boolean = { sym.tpe <:< ignoreSeqTpe } def isSeqOfData(sym: Symbol): Boolean = { val tpe = sym.tpe diff --git a/plugin/src/main/scala/chisel3/internal/plugin/DeprecateSFCComponent.scala b/plugin/src/main/scala/chisel3/internal/plugin/DeprecateSFCComponent.scala index 2488accdea6..175d8817bc1 100644 --- a/plugin/src/main/scala/chisel3/internal/plugin/DeprecateSFCComponent.scala +++ b/plugin/src/main/scala/chisel3/internal/plugin/DeprecateSFCComponent.scala @@ -15,8 +15,8 @@ class DeprecateSFCComponent(val global: Global, arguments: ChiselPluginArguments extends PluginComponent with TypingTransformers { import global._ - val runsAfter: List[String] = List[String]("typer") - val phaseName: String = "deprecatesfccomponent" + val runsAfter: List[String] = List[String]("typer") + val phaseName: String = "deprecatesfccomponent" def newPhase(_prev: Phase): DeprecateSFCComponent = new DeprecateSFCComponent(_prev) class DeprecateSFCComponent(prev: Phase) extends StdPhase(prev) { override def name: String = phaseName @@ -47,8 +47,7 @@ class DeprecateSFCComponent(val global: Global, arguments: ChiselPluginArguments Reporting.WarningCategory } } - implicit final class GlobalCompat( - self: DeprecateSFCComponent.this.global.type) { + implicit final class GlobalCompat(self: DeprecateSFCComponent.this.global.type) { // Added in Scala 2.13.2 for configurable warnings object runReporting { diff --git a/plugin/src/main/scala/chisel3/internal/plugin/IdentifierComponent.scala b/plugin/src/main/scala/chisel3/internal/plugin/IdentifierComponent.scala index dacc2702474..58543b29500 100644 --- a/plugin/src/main/scala/chisel3/internal/plugin/IdentifierComponent.scala +++ b/plugin/src/main/scala/chisel3/internal/plugin/IdentifierComponent.scala @@ -16,8 +16,8 @@ class IdentifierComponent(val global: Global, arguments: ChiselPluginArguments) with TypingTransformers with ChiselOuterUtils { import global._ - val runsAfter: List[String] = "typer" :: Nil - val phaseName: String = "identifiercomponent" + val runsAfter: List[String] = "typer" :: Nil + val phaseName: String = "identifiercomponent" def newPhase(_prev: Phase): ChiselComponentPhase = new ChiselComponentPhase(_prev) class ChiselComponentPhase(prev: Phase) extends StdPhase(prev) { override def name: String = phaseName diff --git a/src/main/scala-2/chisel3/aop/Select.scala b/src/main/scala-2/chisel3/aop/Select.scala index 35ee817609a..25858d3dc79 100644 --- a/src/main/scala-2/chisel3/aop/Select.scala +++ b/src/main/scala-2/chisel3/aop/Select.scala @@ -58,14 +58,13 @@ object Select { implicit val mg = new chisel3.internal.MacroGenerated {} parent.proto._component.get match { case d: DefModule => - collect(d.block.getCommands()) { - case d: DefInstance => - d.id match { - case p: IsClone[_] => - parent._lookup { x => new Instance(Clone(p)).asInstanceOf[Instance[BaseModule]] } - case other: BaseModule => - parent._lookup { x => other } - } + collect(d.block.getCommands()) { case d: DefInstance => + d.id match { + case p: IsClone[_] => + parent._lookup { x => new Instance(Clone(p)).asInstanceOf[Instance[BaseModule]] } + case other: BaseModule => + parent._lookup { x => other } + } } case other => Nil } @@ -122,14 +121,13 @@ object Select { check(parent) val defs = parent.proto._component.get match { case d: DefModule => - collect(d.block.getCommands()) { - case i: DefInstance => - i.id match { - case p: IsClone[_] => - parent._lookup { x => new Definition(Proto(p.getProto)).asInstanceOf[Definition[BaseModule]] } - case other: BaseModule => - parent._lookup { x => other.toDefinition } - } + collect(d.block.getCommands()) { case i: DefInstance => + i.id match { + case p: IsClone[_] => + parent._lookup { x => new Definition(Proto(p.getProto)).asInstanceOf[Definition[BaseModule]] } + case other: BaseModule => + parent._lookup { x => other.toDefinition } + } } case other => Nil } @@ -303,8 +301,8 @@ object Select { */ def syncReadMems(module: BaseModule): Seq[SyncReadMem[_]] = { check(module) - collect(module._component.get.asInstanceOf[DefModule].block.getCommands()) { - case r: DefSeqMemory => r.id.asInstanceOf[SyncReadMem[_]] + collect(module._component.get.asInstanceOf[DefModule].block.getCommands()) { case r: DefSeqMemory => + r.id.asInstanceOf[SyncReadMem[_]] } } @@ -313,8 +311,8 @@ object Select { */ def mems(module: BaseModule): Seq[Mem[_]] = { check(module) - collect(module._component.get.asInstanceOf[DefModule].block.getCommands()) { - case r: DefMemory => r.id.asInstanceOf[Mem[_]] + collect(module._component.get.asInstanceOf[DefModule].block.getCommands()) { case r: DefMemory => + r.id.asInstanceOf[Mem[_]] } } @@ -323,8 +321,8 @@ object Select { */ def ops(module: BaseModule): Seq[(String, Data)] = { check(module) - collect(module._component.get.asInstanceOf[DefModule].block.getCommands()) { - case d: DefPrim[_] => (d.op.name, d.id) + collect(module._component.get.asInstanceOf[DefModule].block.getCommands()) { case d: DefPrim[_] => + (d.op.name, d.id) } } @@ -345,8 +343,8 @@ object Select { */ def wires(module: BaseModule): Seq[Data] = { check(module) - collect(module._component.get.asInstanceOf[DefModule].block.getCommands()) { - case r: DefWire => r.id + collect(module._component.get.asInstanceOf[DefModule].block.getCommands()) { case r: DefWire => + r.id } } @@ -355,8 +353,8 @@ object Select { */ def memPorts(module: BaseModule): Seq[(Data, MemPortDirection, MemBase[_])] = { check(module) - collect(module._component.get.asInstanceOf[DefModule].block.getCommands()) { - case r: DefMemPort[_] => (r.id, r.dir, r.source.id.asInstanceOf[MemBase[_ <: Data]]) + collect(module._component.get.asInstanceOf[DefModule].block.getCommands()) { case r: DefMemPort[_] => + (r.id, r.dir, r.source.id.asInstanceOf[MemBase[_ <: Data]]) } } @@ -376,8 +374,8 @@ object Select { */ def invalids(module: BaseModule): Seq[Data] = { check(module) - collect(module._component.get.asInstanceOf[DefModule].block.getCommands()) { - case DefInvalid(_, arg) => getData(arg) + collect(module._component.get.asInstanceOf[DefModule].block.getCommands()) { case DefInvalid(_, arg) => + getData(arg) } } @@ -489,11 +487,11 @@ object Select { // Given a loc, return all subcomponents of id that could be assigned to in connect private def getEffected(a: Arg): Seq[Data] = a match { - case Node(id: Data) => DataMirror.collectAllMembers(id) + case Node(id: Data) => DataMirror.collectAllMembers(id) case Slot(imm: Node, name) => Seq(imm.id.asInstanceOf[Record].elements(name)) - case Index(imm, _) => getEffected(imm) - case LitIndex(imm, _) => getEffected(imm) - case _ => throw new InternalErrorException(s"Match error: a=$a") + case Index(imm, _) => getEffected(imm) + case LitIndex(imm, _) => getEffected(imm) + case _ => throw new InternalErrorException(s"Match error: a=$a") } // Given an arg, return the corresponding id. Don't use on a loc of a connect. diff --git a/src/main/scala-2/chisel3/choice/ModuleChoice.scala b/src/main/scala-2/chisel3/choice/ModuleChoice.scala index 99ec07c2de4..9394464bb34 100644 --- a/src/main/scala-2/chisel3/choice/ModuleChoice.scala +++ b/src/main/scala-2/chisel3/choice/ModuleChoice.scala @@ -31,8 +31,7 @@ object ModuleChoice extends ModuleChoiceImpl with SourceInfoDoc { */ def apply[T <: Data]( default: => FixedIOBaseModule[T] - )(choices: => Seq[(Case, () => FixedIOBaseModule[T])] - ): T = + )(choices: => Seq[(Case, () => FixedIOBaseModule[T])]): T = macro InstChoiceTransform.apply[T] /** @group SourceInfoTransformMacro */ diff --git a/src/main/scala-2/chisel3/experimental/util/SerializableModuleElaborator.scala b/src/main/scala-2/chisel3/experimental/util/SerializableModuleElaborator.scala index 11d6fa57f84..dd3c20c5b45 100644 --- a/src/main/scala-2/chisel3/experimental/util/SerializableModuleElaborator.scala +++ b/src/main/scala-2/chisel3/experimental/util/SerializableModuleElaborator.scala @@ -45,8 +45,7 @@ trait SerializableModuleElaborator { def designImpl[M <: SerializableModule[P]: universe.TypeTag, P <: SerializableModuleParameter: universe.TypeTag]( parameter: Readable )( - implicit - rwP: upickle.default.Reader[P] + implicit rwP: upickle.default.Reader[P] ): (Readable, Readable) = { var fir: firrtl.ir.Circuit = null val annos = Seq( diff --git a/src/main/scala-2/chisel3/interface/Interface.scala b/src/main/scala-2/chisel3/interface/Interface.scala index e5d5edf67c8..89fd4e4755d 100644 --- a/src/main/scala-2/chisel3/interface/Interface.scala +++ b/src/main/scala-2/chisel3/interface/Interface.scala @@ -105,8 +105,7 @@ trait Interface extends InterfaceCommon { self: Singleton => /** The module that wraps any module which conforms to this Interface. */ final class Module[B <: BaseModule]( - )( - implicit conformance: Conformance[B]) + )(implicit conformance: Conformance[B]) extends RawModule with Entity { final val io = FlatIO(ports) @@ -146,8 +145,8 @@ trait Interface extends InterfaceCommon { self: Singleton => } .flatten } - probes(io).zip(probes(portsView)).foreach { - case (ioProbe, internalProbe) => define(ioProbe, internalProbe) + probes(io).zip(probes(portsView)).foreach { case (ioProbe, internalProbe) => + define(ioProbe, internalProbe) } } catch { case e: InvalidViewException => diff --git a/src/main/scala-2/chisel3/ltl/LTL.scala b/src/main/scala-2/chisel3/ltl/LTL.scala index d2546d57c44..65259f82941 100644 --- a/src/main/scala-2/chisel3/ltl/LTL.scala +++ b/src/main/scala-2/chisel3/ltl/LTL.scala @@ -40,9 +40,9 @@ private case class DelayAtom(val min: Int, val max: Option[Int]) extends Sequenc * in `Sequence(...)`. See `SequenceAtom` for details. */ object Delay { - def apply(): SequenceAtom = DelayAtom(1, Some(1)) - def apply(delay: Int): SequenceAtom = DelayAtom(delay, Some(delay)) - def apply(min: Int, max: Int): SequenceAtom = DelayAtom(min, Some(max)) + def apply(): SequenceAtom = DelayAtom(1, Some(1)) + def apply(delay: Int): SequenceAtom = DelayAtom(delay, Some(delay)) + def apply(min: Int, max: Int): SequenceAtom = DelayAtom(min, Some(max)) def apply(min: Int, max: Option[Int]): SequenceAtom = DelayAtom(min, max) } diff --git a/src/main/scala-2/chisel3/simulator/EphemeralSimulator.scala b/src/main/scala-2/chisel3/simulator/EphemeralSimulator.scala index 739600c7fbe..ed05b4ecaab 100644 --- a/src/main/scala-2/chisel3/simulator/EphemeralSimulator.scala +++ b/src/main/scala-2/chisel3/simulator/EphemeralSimulator.scala @@ -21,8 +21,7 @@ object EphemeralSimulator extends PeekPokeAPI { def simulate[T <: RawModule]( module: => T, layerControl: LayerControl.Type = LayerControl.EnableAll - )(body: (T) => Unit - ): Unit = { + )(body: (T) => Unit): Unit = { makeSimulator().simulate(module, layerControl)({ module => body(module.wrapped) }).result } diff --git a/src/main/scala-2/chisel3/simulator/LayerControl.scala b/src/main/scala-2/chisel3/simulator/LayerControl.scala index be6e3f01f34..0a1f4dbc673 100644 --- a/src/main/scala-2/chisel3/simulator/LayerControl.scala +++ b/src/main/scala-2/chisel3/simulator/LayerControl.scala @@ -31,13 +31,12 @@ object LayerControl { final def preprocessorDefines( module: RawModule, allLayers: Seq[Layer] - ): Seq[VerilogPreprocessorDefine] = getLayerSubset(allLayers).flatMap { - case layer => - layer.config.abi match { - case abi: chisel3.layer.ABI.PreprocessorDefine.type => - Some(VerilogPreprocessorDefine(abi.toMacroIdentifier(layer, module.circuitName))) - case _ => None - } + ): Seq[VerilogPreprocessorDefine] = getLayerSubset(allLayers).flatMap { case layer => + layer.config.abi match { + case abi: chisel3.layer.ABI.PreprocessorDefine.type => + Some(VerilogPreprocessorDefine(abi.toMacroIdentifier(layer, module.circuitName))) + case _ => None + } } /** Return the preprocessor defines that should be set to enable the layers of @@ -65,13 +64,12 @@ object LayerControl { module: RawModule, allLayers: Seq[Layer] ): PartialFunction[File, Boolean] = { - val layerFilenames: Seq[String] = getLayerSubset(allLayers).flatMap { - case layer => - layer.config.abi match { - case abi: chisel3.layer.ABI.FileInclude.type => - Some(abi.toFilename(layer, module.circuitName)) - case _ => None - } + val layerFilenames: Seq[String] = getLayerSubset(allLayers).flatMap { case layer => + layer.config.abi match { + case abi: chisel3.layer.ABI.FileInclude.type => + Some(abi.toFilename(layer, module.circuitName)) + case _ => None + } } { @@ -122,8 +120,8 @@ object LayerControl { require( layerSet.contains(layer), s"""cannot enable layer '${layer.fullName}' as it is not one of the defined layers: ${allLayers.map( - _.fullName - )}""" + _.fullName + )}""" ) } layers diff --git a/src/main/scala-2/chisel3/simulator/Simulator.scala b/src/main/scala-2/chisel3/simulator/Simulator.scala index d0e2c3d406b..b319c7a8b9a 100644 --- a/src/main/scala-2/chisel3/simulator/Simulator.scala +++ b/src/main/scala-2/chisel3/simulator/Simulator.scala @@ -7,8 +7,9 @@ import svsim._ final object Simulator { trait BackendProcessor { def process[T <: Backend]( - backend: T - )(tag: String, + backend: T + )( + tag: String, commonCompilationSettings: CommonCompilationSettings, backendSpecificCompilationSettings: backend.CompilationSettings ): Unit @@ -17,7 +18,8 @@ final object Simulator { final case class BackendInvocationDigest[T]( compilationStartTime: Long, compilationEndTime: Long, - outcome: BackendInvocationOutcome[T]) { + outcome: BackendInvocationOutcome[T] + ) { def result = outcome match { case SimulationDigest(_, _, outcome) => outcome.get case CompilationFailed(error) => throw error @@ -26,10 +28,7 @@ final object Simulator { sealed trait BackendInvocationOutcome[T] final case class CompilationFailed[T](error: Throwable) extends BackendInvocationOutcome[T] - final case class SimulationDigest[T]( - simulationStartTime: Long, - simulationEndTime: Long, - outcome: Try[T]) + final case class SimulationDigest[T](simulationStartTime: Long, simulationEndTime: Long, outcome: Try[T]) extends BackendInvocationOutcome[T] private[simulator] final class WorkspaceCompiler[T, U]( @@ -37,13 +36,14 @@ final object Simulator { workspace: Workspace, customSimulationWorkingDirectory: Option[String], verbose: Boolean, - body: (SimulatedModule[T]) => U) - extends BackendProcessor { + body: (SimulatedModule[T]) => U + ) extends BackendProcessor { val results = scala.collection.mutable.Stack[BackendInvocationDigest[U]]() def process[T <: Backend]( - backend: T - )(tag: String, + backend: T + )( + tag: String, commonCompilationSettings: CommonCompilationSettings, backendSpecificCompilationSettings: backend.CompilationSettings ): Unit = { @@ -99,7 +99,7 @@ trait Simulator { def customSimulationWorkingDirectory: Option[String] = None def verbose: Boolean = false def firtoolArgs: Seq[String] = Seq() - def commonCompilationSettings: CommonCompilationSettings + def commonCompilationSettings: CommonCompilationSettings private[simulator] def processBackends( processor: Simulator.BackendProcessor, @@ -108,8 +108,7 @@ trait Simulator { private[simulator] def _simulate[T <: RawModule, U]( module: => T, layerControl: LayerControl.Type - )(body: (SimulatedModule[T]) => U - ): Seq[Simulator.BackendInvocationDigest[U]] = { + )(body: (SimulatedModule[T]) => U): Seq[Simulator.BackendInvocationDigest[U]] = { val workspace = new Workspace(path = workspacePath, workingDirectoryPrefix = workingDirectoryPrefix) workspace.reset() val elaboratedModule = workspace.elaborateGeneratedModule({ () => module }, firtoolArgs) @@ -146,8 +145,7 @@ trait MultiBackendSimulator extends Simulator { def simulate[T <: RawModule, U]( module: => T, layerControl: LayerControl.Type = LayerControl.EnableAll - )(body: (SimulatedModule[T]) => U - ): Seq[Simulator.BackendInvocationDigest[U]] = { + )(body: (SimulatedModule[T]) => U): Seq[Simulator.BackendInvocationDigest[U]] = { _simulate(module, layerControl)(body) } } @@ -168,8 +166,7 @@ trait SingleBackendSimulator[T <: Backend] extends Simulator { def simulate[T <: RawModule, U]( module: => T, layerControl: LayerControl.Type = LayerControl.EnableAll - )(body: (SimulatedModule[T]) => U - ): Simulator.BackendInvocationDigest[U] = { + )(body: (SimulatedModule[T]) => U): Simulator.BackendInvocationDigest[U] = { _simulate(module, layerControl)(body).head } diff --git a/src/main/scala-2/chisel3/simulator/package.scala b/src/main/scala-2/chisel3/simulator/package.scala index 27f2e7fafc8..9026960a963 100644 --- a/src/main/scala-2/chisel3/simulator/package.scala +++ b/src/main/scala-2/chisel3/simulator/package.scala @@ -16,25 +16,27 @@ package object simulator { final class ElaboratedModule[T] private[simulator] ( private[simulator] val wrapped: T, private[simulator] val ports: Seq[(Data, ModuleInfo.Port)], - private[simulator] val layers: Seq[chisel3.layer.Layer]) + private[simulator] val layers: Seq[chisel3.layer.Layer] + ) /** * A class that enables using a Chisel module to control an `svsim.Simulation`. */ final class SimulatedModule[T] private[simulator] ( private[simulator] val elaboratedModule: ElaboratedModule[T], - controller: Simulation.Controller) - extends AnySimulatedModule(elaboratedModule.ports, controller) { + controller: Simulation.Controller + ) extends AnySimulatedModule(elaboratedModule.ports, controller) { def wrapped: T = elaboratedModule.wrapped } sealed class AnySimulatedModule protected ( ports: Seq[(Data, ModuleInfo.Port)], - val controller: Simulation.Controller) { + val controller: Simulation.Controller + ) { // -- Port Mapping - private val simulationPorts = ports.map { - case (data, port) => data -> controller.port(port.name) + private val simulationPorts = ports.map { case (data, port) => + data -> controller.port(port.name) }.toMap def port(data: Data): Simulation.Port = { // TODO, we can support non identity views, but it will require changing this API to return a Seq[Port] @@ -94,8 +96,7 @@ package object simulator { verbose: Boolean = false, traceEnabled: Boolean = false, executionScriptLimit: Option[Int] = None - )(body: SimulatedModule[T] => U - ): U = { + )(body: SimulatedModule[T] => U): U = { simulation.run(conservativeCommandResolution, verbose, traceEnabled, executionScriptLimit) { controller => val module = new SimulatedModule(elaboratedModule, controller) AnySimulatedModule.withValue(module) { @@ -187,15 +188,13 @@ package object simulator { def leafPorts(node: Data, name: String): Seq[(Data, ModuleInfo.Port)] = { node match { case record: Record => { - record.elements.toSeq.flatMap { - case (fieldName, field) => - leafPorts(field, s"${name}_${fieldName}") + record.elements.toSeq.flatMap { case (fieldName, field) => + leafPorts(field, s"${name}_${fieldName}") } } case vec: Vec[_] => { - vec.zipWithIndex.flatMap { - case (element, index) => - leafPorts(element, s"${name}_${index}") + vec.zipWithIndex.flatMap { case (element, index) => + leafPorts(element, s"${name}_${index}") } } case element: Element => @@ -215,7 +214,7 @@ package object simulator { // Chisel ports can be Data or Property, but there is no ABI for Property ports, so we only return Data. DataMirror.modulePorts(dut).flatMap { case (name, data: Data) => leafPorts(data, name) - case _ => Nil + case _ => Nil } } workspace.elaborate( diff --git a/src/main/scala-2/chisel3/util/BitPat.scala b/src/main/scala-2/chisel3/util/BitPat.scala index a844e3041c1..92baebf6ef1 100644 --- a/src/main/scala-2/chisel3/util/BitPat.scala +++ b/src/main/scala-2/chisel3/util/BitPat.scala @@ -29,11 +29,11 @@ sealed class BitPat(val value: BigInt, val mask: BigInt, val width: Int) extends import chisel3.util.experimental.BitSet def terms = Set(this) - def apply(x: Int): BitPat = macro SourceInfoTransform.xArg + def apply(x: Int): BitPat = macro SourceInfoTransform.xArg def apply(x: Int, y: Int): BitPat = macro SourceInfoTransform.xyArg - def ===(that: UInt): Bool = macro SourceInfoTransform.thatArg - def =/=(that: UInt): Bool = macro SourceInfoTransform.thatArg - def ##(that: BitPat): BitPat = macro SourceInfoTransform.thatArg + def ===(that: UInt): Bool = macro SourceInfoTransform.thatArg + def =/=(that: UInt): Bool = macro SourceInfoTransform.thatArg + def ##(that: BitPat): BitPat = macro SourceInfoTransform.thatArg /** @group SourceInfoTransformMacro */ def do_apply(x: Int)(implicit sourceInfo: SourceInfo): BitPat = _applyImpl(x) diff --git a/src/main/scala-2/chisel3/util/SRAM.scala b/src/main/scala-2/chisel3/util/SRAM.scala index 22089cbcca1..2751f500950 100644 --- a/src/main/scala-2/chisel3/util/SRAM.scala +++ b/src/main/scala-2/chisel3/util/SRAM.scala @@ -145,8 +145,8 @@ class SRAMInterface[T <: Data]( val numWritePorts: Int, val numReadwritePorts: Int, val masked: Boolean = false, - val hasDescription: Boolean = false) - extends Bundle { + val hasDescription: Boolean = false +) extends Bundle { /** Public accessor for data type of this interface. */ def dataType: T = tpe @@ -159,7 +159,7 @@ class SRAMInterface[T <: Data]( } override def typeName: String = s"SRAMInterface_${SRAM.portedness(numReadPorts, numWritePorts, numReadwritePorts)}${if (masked) "_masked" - else ""}}_${tpe.typeName}" + else ""}}_${tpe.typeName}" val addrWidth = log2Up(memSize) @@ -677,23 +677,21 @@ object SRAM { new SRAMInterface(size, tpe, numReadPorts, numWritePorts, numReadwritePorts, enableMask, includeMetadata) ) - out.readPorts.zip(sramReadPorts).zip(readPortClocks).map { - case ((intfReadPort, sramReadPort), readClock) => - sramReadPort.address := intfReadPort.address - sramReadPort.clock := readClock - intfReadPort.data := sramReadPort.data.asTypeOf(tpe) - sramReadPort.enable := intfReadPort.enable + out.readPorts.zip(sramReadPorts).zip(readPortClocks).map { case ((intfReadPort, sramReadPort), readClock) => + sramReadPort.address := intfReadPort.address + sramReadPort.clock := readClock + intfReadPort.data := sramReadPort.data.asTypeOf(tpe) + sramReadPort.enable := intfReadPort.enable } - out.writePorts.zip(sramWritePorts).zip(writePortClocks).map { - case ((intfWritePort, sramWritePort), writeClock) => - sramWritePort.address := intfWritePort.address - sramWritePort.clock := writeClock - sramWritePort.data := intfWritePort.data.asUInt - sramWritePort.enable := intfWritePort.enable - sramWritePort.mask match { - case Some(mask) => mask := intfWritePort.mask.get.asUInt - case None => assert(intfWritePort.mask.isEmpty) - } + out.writePorts.zip(sramWritePorts).zip(writePortClocks).map { case ((intfWritePort, sramWritePort), writeClock) => + sramWritePort.address := intfWritePort.address + sramWritePort.clock := writeClock + sramWritePort.data := intfWritePort.data.asUInt + sramWritePort.enable := intfWritePort.enable + sramWritePort.mask match { + case Some(mask) => mask := intfWritePort.mask.get.asUInt + case None => assert(intfWritePort.mask.isEmpty) + } } out.readwritePorts.zip(sramReadwritePorts).zip(readwritePortClocks).map { case ((intfReadwritePort, sramReadwritePort), readwriteClock) => @@ -782,11 +780,10 @@ object SRAM { // set references to firrtl memory ports def nameAndSetRef(ports: Seq[Data], namePrefix: String): Seq[String] = { - ports.zipWithIndex.map { - case (p, idx) => - val name = namePrefix + idx - p.setRef(Slot(Node(mem), name)) - name + ports.zipWithIndex.map { case (p, idx) => + val name = namePrefix + idx + p.setRef(Slot(Node(mem), name)) + name } } diff --git a/src/main/scala-2/chisel3/util/Switch.scala b/src/main/scala-2/chisel3/util/Switch.scala index 6b5e92c03ab..05e3454f78a 100644 --- a/src/main/scala-2/chisel3/util/Switch.scala +++ b/src/main/scala-2/chisel3/util/Switch.scala @@ -28,14 +28,13 @@ object switch { def impl(c: Context)(cond: c.Tree)(x: c.Tree): c.Tree = { import c.universe._ val q"..$body" = x - val res = body.foldLeft(q"""new chisel3.util.SwitchContext($cond, None, Set.empty)""") { - case (acc, tree) => - tree match { - // TODO: remove when Chisel compatibility package is removed - case q"Chisel.`package`.is.apply( ..$params )( ..$body )" => q"$acc.is( ..$params )( ..$body )" - case q"chisel3.util.is.apply( ..$params )( ..$body )" => q"$acc.is( ..$params )( ..$body )" - case b => throw new Exception(s"Cannot include blocks that do not begin with is() in switch.") - } + val res = body.foldLeft(q"""new chisel3.util.SwitchContext($cond, None, Set.empty)""") { case (acc, tree) => + tree match { + // TODO: remove when Chisel compatibility package is removed + case q"Chisel.`package`.is.apply( ..$params )( ..$body )" => q"$acc.is( ..$params )( ..$body )" + case q"chisel3.util.is.apply( ..$params )( ..$body )" => q"$acc.is( ..$params )( ..$body )" + case b => throw new Exception(s"Cannot include blocks that do not begin with is() in switch.") + } } q"""{ $res }""" } diff --git a/src/main/scala-2/chisel3/util/circt/LTLIntrinsics.scala b/src/main/scala-2/chisel3/util/circt/LTLIntrinsics.scala index 929f3226f07..651a0fbfda8 100644 --- a/src/main/scala-2/chisel3/util/circt/LTLIntrinsics.scala +++ b/src/main/scala-2/chisel3/util/circt/LTLIntrinsics.scala @@ -20,8 +20,7 @@ private[chisel3] object BaseIntrinsic { intrinsicName: String, ret: => T, maybeParams: Seq[(String, Param)] = Seq() - )(data: Data* - )( + )(data: Data*)( implicit sourceInfo: SourceInfo ): T = { IntrinsicExpr(f"circt_$intrinsicName", ret, maybeParams: _*)(data: _*) @@ -33,8 +32,7 @@ private[chisel3] object UnaryLTLIntrinsic { def apply[T <: Data]( intrinsicName: String, params: Seq[(String, Param)] = Seq() - )(_in: T - )( + )(_in: T)( implicit sourceInfo: SourceInfo ): Bool = BaseIntrinsic(f"ltl_$intrinsicName", Bool(), params)(_in).suggestName(f"ltl_$intrinsicName") @@ -45,9 +43,7 @@ private[chisel3] object BinaryLTLIntrinsic { def apply[T <: Data, U <: Data]( intrinsicName: String, params: Seq[(String, Param)] = Seq() - )(lhs: T, - rhs: U - )( + )(lhs: T, rhs: U)( implicit sourceInfo: SourceInfo ): Bool = BaseIntrinsic(f"ltl_$intrinsicName", Bool(), params)(lhs, rhs).suggestName(f"ltl_$intrinsicName") @@ -148,9 +144,7 @@ private[chisel3] object VerifAssertLikeIntrinsic { def apply( intrinsicName: String, label: Option[String] - )(prop: Bool, - enable: Option[Bool] - )( + )(prop: Bool, enable: Option[Bool])( implicit sourceInfo: SourceInfo ): Unit = { val name = f"circt_verif_$intrinsicName" diff --git a/src/main/scala/chisel3/Driver.scala b/src/main/scala/chisel3/Driver.scala index 75a94f238a2..db67ddf453d 100644 --- a/src/main/scala/chisel3/Driver.scala +++ b/src/main/scala/chisel3/Driver.scala @@ -19,7 +19,7 @@ private[chisel3] trait BackendCompilationUtilities extends LazyLogging { def copyResourceToFile(name: String, file: File): Unit = FirrtlBackendCompilationUtilities.copyResourceToFile(name, file) def createTestDirectory(testName: String): File = FirrtlBackendCompilationUtilities.createTestDirectory(testName) - def makeHarness(template: String => String, post: String)(f: File): File = + def makeHarness(template: String => String, post: String)(f: File): File = FirrtlBackendCompilationUtilities.makeHarness(template, post)(f) def firrtlToVerilog(prefix: String, dir: File): ProcessBuilder = FirrtlBackendCompilationUtilities.firrtlToVerilog(prefix, dir) diff --git a/src/main/scala/chisel3/choice/ModuleChoiceImpl.scala b/src/main/scala/chisel3/choice/ModuleChoiceImpl.scala index 8eb606b0426..0ee9bc15d8c 100644 --- a/src/main/scala/chisel3/choice/ModuleChoiceImpl.scala +++ b/src/main/scala/chisel3/choice/ModuleChoiceImpl.scala @@ -21,21 +21,19 @@ private[chisel3] trait ModuleChoiceImpl { ): T = { val instDefaultModule = Module.evaluate(default) - val choiceModules = choices.map { - case (choice, module) => - val instModule = Module.evaluate(module()) - if (!instModule.io.typeEquivalent(instDefaultModule.io)) { - Builder.error("Error: choice module IO bundles are not type equivalent") - } - Builder.options += choice - (choice, instModule) + val choiceModules = choices.map { case (choice, module) => + val instModule = Module.evaluate(module()) + if (!instModule.io.typeEquivalent(instDefaultModule.io)) { + Builder.error("Error: choice module IO bundles are not type equivalent") + } + Builder.options += choice + (choice, instModule) } - groupByIntoSeq(choiceModules.map(_._1))(opt => opt).foreach { - case (_, group) => - if (group.size != 1) { - throw new IllegalArgumentException(s"Error: duplicate case '${group.head.name}'") - } + groupByIntoSeq(choiceModules.map(_._1))(opt => opt).foreach { case (_, group) => + if (group.size != 1) { + throw new IllegalArgumentException(s"Error: duplicate case '${group.head.name}'") + } } val groupedChoices = choices.map(_._1.group).distinct @@ -57,9 +55,8 @@ private[chisel3] trait ModuleChoiceImpl { binding, instDefaultModule, group, - choiceModules.map { - case (choice, instModule) => - (choice.name, instModule) + choiceModules.map { case (choice, instModule) => + (choice.name, instModule) } ) ) diff --git a/src/main/scala/chisel3/experimental/conversions/package.scala b/src/main/scala/chisel3/experimental/conversions/package.scala index 7374f223252..580729ec919 100644 --- a/src/main/scala/chisel3/experimental/conversions/package.scala +++ b/src/main/scala/chisel3/experimental/conversions/package.scala @@ -45,8 +45,7 @@ package object conversions { V2 <: Data, V3 <: Data, V4 <: Data - ](tup: (T1, T2, T3, T4) - )( + ](tup: (T1, T2, T3, T4))( implicit v1: DataView[T1, V1], v2: DataView[T2, V2], v3: DataView[T3, V3], @@ -67,8 +66,7 @@ package object conversions { V3 <: Data, V4 <: Data, V5 <: Data - ](tup: (T1, T2, T3, T4, T5) - )( + ](tup: (T1, T2, T3, T4, T5))( implicit v1: DataView[T1, V1], v2: DataView[T2, V2], v3: DataView[T3, V3], @@ -92,8 +90,7 @@ package object conversions { V4 <: Data, V5 <: Data, V6 <: Data - ](tup: (T1, T2, T3, T4, T5, T6) - )( + ](tup: (T1, T2, T3, T4, T5, T6))( implicit v1: DataView[T1, V1], v2: DataView[T2, V2], v3: DataView[T3, V3], @@ -120,8 +117,7 @@ package object conversions { V5 <: Data, V6 <: Data, V7 <: Data - ](tup: (T1, T2, T3, T4, T5, T6, T7) - )( + ](tup: (T1, T2, T3, T4, T5, T6, T7))( implicit v1: DataView[T1, V1], v2: DataView[T2, V2], v3: DataView[T3, V3], @@ -151,8 +147,7 @@ package object conversions { V6 <: Data, V7 <: Data, V8 <: Data - ](tup: (T1, T2, T3, T4, T5, T6, T7, T8) - )( + ](tup: (T1, T2, T3, T4, T5, T6, T7, T8))( implicit v1: DataView[T1, V1], v2: DataView[T2, V2], v3: DataView[T3, V3], @@ -185,8 +180,7 @@ package object conversions { V7 <: Data, V8 <: Data, V9 <: Data - ](tup: (T1, T2, T3, T4, T5, T6, T7, T8, T9) - )( + ](tup: (T1, T2, T3, T4, T5, T6, T7, T8, T9))( implicit v1: DataView[T1, V1], v2: DataView[T2, V2], v3: DataView[T3, V3], @@ -222,8 +216,7 @@ package object conversions { V8 <: Data, V9 <: Data, V10 <: Data - ](tup: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10) - )( + ](tup: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10))( implicit v1: DataView[T1, V1], v2: DataView[T2, V2], v3: DataView[T3, V3], diff --git a/src/main/scala/chisel3/stage/ChiselAnnotations.scala b/src/main/scala/chisel3/stage/ChiselAnnotations.scala index b59974d3bf7..9bd2c085014 100644 --- a/src/main/scala/chisel3/stage/ChiselAnnotations.scala +++ b/src/main/scala/chisel3/stage/ChiselAnnotations.scala @@ -99,15 +99,14 @@ case class WarningConfigurationAnnotation(value: String) // Add accumulating index to each filter for error reporting .mapAccumulate(0) { case (idx, s) => (idx + 1 + s.length, (idx, s)) } // + 1 for removed ',' ._2 // Discard accumulator - .map { - case (idx, s) => - WarningFilter.parse(s) match { - case Right(wf) => wf - case Left((jdx, msg)) => - val carat = (" " * (idx + jdx)) + "^" - // Note tab before value and carat - throw new Exception(s"Failed to parse configuration: $msg\n $value\n $carat") - } + .map { case (idx, s) => + WarningFilter.parse(s) match { + case Right(wf) => wf + case Left((jdx, msg)) => + val carat = (" " * (idx + jdx)) + "^" + // Note tab before value and carat + throw new Exception(s"Failed to parse configuration: $msg\n $value\n $carat") + } } } } @@ -154,21 +153,20 @@ case class WarningConfigurationFileAnnotation(value: File) require(value.exists, s"Warning configuration file '$value' must exist!") require(value.isFile && value.canRead, s"Warning configuration file '$value' must be a readable file!") val lines = scala.io.Source.fromFile(value).getLines() - lines.zipWithIndex.flatMap { - case (contents, lineNo) => - val (str, jdx) = trimAndRemoveComments(contents) - Option.when(str.nonEmpty) { - WarningFilter.parse(str) match { - case Right(wf) => wf - case Left((idx, msg)) => - val carat = (" " * (idx + jdx)) + "^" - val info = s"$value:${lineNo + 1}:$idx" // +1 to lineNo because we start at 0 but files start with 1 - // Note tab before value and carat - throw new Exception( - s"Failed to parse configuration at $info: $msg\n $contents\n $carat" - ) - } + lines.zipWithIndex.flatMap { case (contents, lineNo) => + val (str, jdx) = trimAndRemoveComments(contents) + Option.when(str.nonEmpty) { + WarningFilter.parse(str) match { + case Right(wf) => wf + case Left((idx, msg)) => + val carat = (" " * (idx + jdx)) + "^" + val info = s"$value:${lineNo + 1}:$idx" // +1 to lineNo because we start at 0 but files start with 1 + // Note tab before value and carat + throw new Exception( + s"Failed to parse configuration at $info: $msg\n $contents\n $carat" + ) } + } }.toVector } } @@ -479,7 +477,7 @@ object RemapLayer extends HasShellOptions { toAnnotationSeq = (raw: String) => raw match { case layerMapRegex(oldLayerName, newLayerName) => Seq(RemapLayer(oldLayerName, newLayerName)) - case _ => throw new OptionsException(s"Invalid layer remap format: '$raw'") + case _ => throw new OptionsException(s"Invalid layer remap format: '$raw'") }, helpText = "Globally remap a layer to another layer", helpValueName = Some(",") diff --git a/src/main/scala/chisel3/stage/ChiselOptions.scala b/src/main/scala/chisel3/stage/ChiselOptions.scala index ebd78656fe5..81e8328b562 100644 --- a/src/main/scala/chisel3/stage/ChiselOptions.scala +++ b/src/main/scala/chisel3/stage/ChiselOptions.scala @@ -17,7 +17,8 @@ class ChiselOptions private[stage] ( val useLegacyWidth: Boolean = false, val layerMap: Map[Layer, Layer] = Map.empty, val includeUtilMetadata: Boolean = false, - val useSRAMBlackbox: Boolean = false) { + val useSRAMBlackbox: Boolean = false +) { private[stage] def copy( printFullStackTrace: Boolean = printFullStackTrace, diff --git a/src/main/scala/chisel3/stage/phases/AddImplicitOutputAnnotationFile.scala b/src/main/scala/chisel3/stage/phases/AddImplicitOutputAnnotationFile.scala index d4ea48fb752..b944ef11057 100644 --- a/src/main/scala/chisel3/stage/phases/AddImplicitOutputAnnotationFile.scala +++ b/src/main/scala/chisel3/stage/phases/AddImplicitOutputAnnotationFile.scala @@ -20,9 +20,8 @@ class AddImplicitOutputAnnotationFile extends Phase { case _: OutputAnnotationFileAnnotation => annotations }.getOrElse { - val x: Option[AnnotationSeq] = annotations.collectFirst { - case a: ChiselCircuitAnnotation => - OutputAnnotationFileAnnotation(a.circuit.name) +: annotations + val x: Option[AnnotationSeq] = annotations.collectFirst { case a: ChiselCircuitAnnotation => + OutputAnnotationFileAnnotation(a.circuit.name) +: annotations } x.getOrElse(annotations) diff --git a/src/main/scala/chisel3/stage/phases/AddImplicitOutputFile.scala b/src/main/scala/chisel3/stage/phases/AddImplicitOutputFile.scala index 396f2a8b86d..53cbc6ac8fa 100644 --- a/src/main/scala/chisel3/stage/phases/AddImplicitOutputFile.scala +++ b/src/main/scala/chisel3/stage/phases/AddImplicitOutputFile.scala @@ -20,9 +20,8 @@ class AddImplicitOutputFile extends Phase { def transform(annotations: AnnotationSeq): AnnotationSeq = annotations.collectFirst { case _: ChiselOutputFileAnnotation => annotations }.getOrElse { - val x: Option[AnnotationSeq] = annotations.collectFirst { - case a: ChiselCircuitAnnotation => - ChiselOutputFileAnnotation(a.circuit.name) +: annotations + val x: Option[AnnotationSeq] = annotations.collectFirst { case a: ChiselCircuitAnnotation => + ChiselOutputFileAnnotation(a.circuit.name) +: annotations } x.getOrElse(annotations) diff --git a/src/main/scala/chisel3/stage/phases/Convert.scala b/src/main/scala/chisel3/stage/phases/Convert.scala index 0025f74265e..b83472f8772 100644 --- a/src/main/scala/chisel3/stage/phases/Convert.scala +++ b/src/main/scala/chisel3/stage/phases/Convert.scala @@ -29,7 +29,7 @@ class Convert extends Phase { /* Convert this Chisel Circuit to a FIRRTL Circuit */ Some(FirrtlCircuitAnnotation(Converter.convert(a.circuit))) ++ /* Convert all Chisel Annotations to FIRRTL Annotations */ - //TODO: clean up this code when firrtl is merged + // TODO: clean up this code when firrtl is merged a.circuit.firrtlAnnotations case a => Some(a) } diff --git a/src/main/scala/chisel3/testers/TesterDriver.scala b/src/main/scala/chisel3/testers/TesterDriver.scala index af850dbbe16..3eba5d7e609 100644 --- a/src/main/scala/chisel3/testers/TesterDriver.scala +++ b/src/main/scala/chisel3/testers/TesterDriver.scala @@ -17,7 +17,7 @@ import scala.sys.process.ProcessLogger @nowarn("msg=trait BackendCompilationUtilities in package chisel3 is deprecated") object TesterDriver extends BackendCompilationUtilities { - //TODO: need to remove BackendCompilationUtilities here but it will break external API + // TODO: need to remove BackendCompilationUtilities here but it will break external API // unless all methods of it are implemented private[chisel3] trait Backend extends NoTargetAnnotation with Unserializable { diff --git a/src/main/scala/chisel3/util/BitwiseImpl.scala b/src/main/scala/chisel3/util/BitwiseImpl.scala index 3d9edea5411..01dafe7dd37 100644 --- a/src/main/scala/chisel3/util/BitwiseImpl.scala +++ b/src/main/scala/chisel3/util/BitwiseImpl.scala @@ -49,8 +49,8 @@ private[chisel3] trait ReverseImpl { private def doit(in: UInt, length: Int)(implicit sourceInfo: SourceInfo): UInt = length match { - case _ if length < 0 => throw new IllegalArgumentException(s"length (=$length) must be nonnegative integer.") - case _ if length <= 1 => in + case _ if length < 0 => throw new IllegalArgumentException(s"length (=$length) must be nonnegative integer.") + case _ if length <= 1 => in case _ if isPow2(length) && length >= 8 && length <= 64 => // This esoterica improves simulation performance var res = in diff --git a/src/main/scala/chisel3/util/Conditional.scala b/src/main/scala/chisel3/util/Conditional.scala index 955d7aff163..7f6bbfaff75 100644 --- a/src/main/scala/chisel3/util/Conditional.scala +++ b/src/main/scala/chisel3/util/Conditional.scala @@ -14,9 +14,8 @@ import chisel3.experimental.SourceInfo */ class SwitchContext[T <: Element](cond: T, whenContext: Option[WhenContext], lits: Set[BigInt]) { def is( - v: Iterable[T] - )(block: => Any - )( + v: Iterable[T] + )(block: => Any)( implicit sourceInfo: SourceInfo ): SwitchContext[T] = { if (!v.isEmpty) { @@ -39,10 +38,9 @@ class SwitchContext[T <: Element](cond: T, whenContext: Option[WhenContext], lit def is(v: T)(block: => Any)(implicit sourceInfo: SourceInfo): SwitchContext[T] = is(Seq(v))(block) def is( - v: T, - vr: T* - )(block: => Any - )( + v: T, + vr: T* + )(block: => Any)( implicit sourceInfo: SourceInfo ): SwitchContext[T] = is(v :: vr.toList)(block) } diff --git a/src/main/scala/chisel3/util/Decoupled.scala b/src/main/scala/chisel3/util/Decoupled.scala index cc29aab6149..c8601e89e8f 100644 --- a/src/main/scala/chisel3/util/Decoupled.scala +++ b/src/main/scala/chisel3/util/Decoupled.scala @@ -193,11 +193,7 @@ object DeqIO { * @param hasFlush A boolean for whether the generated Queue is flushable * @groupdesc Signals The hardware fields of the Bundle */ -class QueueIO[T <: Data]( - private val gen: T, - val entries: Int, - val hasFlush: Boolean = false) - extends Bundle { // See github.com/freechipsproject/chisel3/issues/765 for why gen is a private val and proposed replacement APIs. +class QueueIO[T <: Data](private val gen: T, val entries: Int, val hasFlush: Boolean = false) extends Bundle { // See github.com/freechipsproject/chisel3/issues/765 for why gen is a private val and proposed replacement APIs. /* These may look inverted, because the names (enq/deq) are from the perspective of the client, * but internally, the queue implementation itself sits on the other side @@ -246,8 +242,8 @@ class Queue[T <: Data]( val pipe: Boolean = false, val flow: Boolean = false, val useSyncReadMem: Boolean = false, - val hasFlush: Boolean = false) - extends Module() { + val hasFlush: Boolean = false +) extends Module() { require(entries > -1, "Queue must have non-negative number of entries") require(entries != 0, "Use companion object Queue.apply for zero entries") requireIsChiselType(gen) diff --git a/src/main/scala/chisel3/util/Lookup.scala b/src/main/scala/chisel3/util/Lookup.scala index f538c4d1e66..673c027f887 100644 --- a/src/main/scala/chisel3/util/Lookup.scala +++ b/src/main/scala/chisel3/util/Lookup.scala @@ -29,9 +29,8 @@ import chisel3._ object ListLookup { def apply[T <: Data](addr: UInt, default: List[T], mapping: Array[(BitPat, List[T])]): List[T] = { val map = mapping.map(m => (m._1 === addr, m._2)) - default.zipWithIndex.map { - case (d, i) => - map.foldRight(d)((m, n) => Mux(m._1, m._2(i), n)) + default.zipWithIndex.map { case (d, i) => + map.foldRight(d)((m, n) => Mux(m._1, m._2(i), n)) } } } diff --git a/src/main/scala/chisel3/util/Math.scala b/src/main/scala/chisel3/util/Math.scala index e160c83f12e..aa27d89f761 100644 --- a/src/main/scala/chisel3/util/Math.scala +++ b/src/main/scala/chisel3/util/Math.scala @@ -25,8 +25,8 @@ import chisel3.internal object log2Up { // Do not deprecate until zero-width wires fully work: // https://github.com/freechipsproject/chisel3/issues/847 - //@chiselRuntimeDeprecated - //@deprecated("Use log2Ceil instead", "chisel3") + // @chiselRuntimeDeprecated + // @deprecated("Use log2Ceil instead", "chisel3") def apply(in: BigInt): Int = { require(in >= 0, s"log2Up is only defined on integers >= 0, got $in") 1.max((in - 1).bitLength) @@ -68,8 +68,8 @@ object log2Ceil { object log2Down { // Do not deprecate until zero-width wires fully work: // https://github.com/freechipsproject/chisel3/issues/847 - //@chiselRuntimeDeprecated - //@deprecated("Use log2Floor instead", "chisel3") + // @chiselRuntimeDeprecated + // @deprecated("Use log2Floor instead", "chisel3") def apply(in: BigInt): Int = log2Up(in) - (if (isPow2(in)) 0 else 1) def apply(in: Int): Int = apply(BigInt(in)) } diff --git a/src/main/scala/chisel3/util/MuxImpl.scala b/src/main/scala/chisel3/util/MuxImpl.scala index a9c5f4668bf..23a3b1ffa97 100644 --- a/src/main/scala/chisel3/util/MuxImpl.scala +++ b/src/main/scala/chisel3/util/MuxImpl.scala @@ -25,7 +25,7 @@ import chisel3.experimental.SourceInfo object Mux1H { def apply[T <: Data](sel: Seq[Bool], in: Seq[T]): T = apply(sel.zip(in)) - def apply[T <: Data](in: Iterable[(Bool, T)]): T = SeqUtils.oneHotMux(in) + def apply[T <: Data](in: Iterable[(Bool, T)]): T = SeqUtils.oneHotMux(in) def apply[T <: Data](sel: UInt, in: Seq[T]): T = apply((0 until in.size).map(sel(_)), in) def apply(sel: UInt, in: UInt): Bool = (sel & in).orR @@ -45,9 +45,9 @@ object Mux1H { * Returns the output of the Mux tree. */ object PriorityMux { - def apply[T <: Data](in: Seq[(Bool, T)]): T = SeqUtils.priorityMux(in) + def apply[T <: Data](in: Seq[(Bool, T)]): T = SeqUtils.priorityMux(in) def apply[T <: Data](sel: Seq[Bool], in: Seq[T]): T = apply(sel.zip(in)) - def apply[T <: Data](sel: Bits, in: Seq[T]): T = apply((0 until in.size).map(sel(_)), in) + def apply[T <: Data](sel: Bits, in: Seq[T]): T = apply((0 until in.size).map(sel(_)), in) } private[chisel3] trait MuxLookupImpl { diff --git a/src/main/scala/chisel3/util/SparseVec.scala b/src/main/scala/chisel3/util/SparseVec.scala index 2c31c47f2c7..67fd0e9f98e 100644 --- a/src/main/scala/chisel3/util/SparseVec.scala +++ b/src/main/scala/chisel3/util/SparseVec.scala @@ -72,8 +72,8 @@ class SparseVec[A <: Data]( gen: => A, indices: Seq[Int], defaultValue: DefaultValueBehavior.Type = DefaultValueBehavior.Indeterminate, - outOfBoundsValue: OutOfBoundsBehavior.Type = OutOfBoundsBehavior.Indeterminate) - extends Record { + outOfBoundsValue: OutOfBoundsBehavior.Type = OutOfBoundsBehavior.Indeterminate +) extends Record { require(indices.size <= size, s"the SparseVec indices size (${indices.size}) must be <= the SparseVec size ($size)") @@ -83,11 +83,10 @@ class SparseVec[A <: Data]( override final val elements = { var nonUniqueIndices: List[Int] = Nil // List is cheap in common case, no allocation val duplicates: HashSet[Int] = HashSet.empty[Int] - val result = indices.view.map { - case index => - if (!duplicates.add(index)) - nonUniqueIndices ::= index - index.toString -> DataMirror.internal.chiselTypeClone(gen) + val result = indices.view.map { case index => + if (!duplicates.add(index)) + nonUniqueIndices ::= index + index.toString -> DataMirror.internal.chiselTypeClone(gen) }.to(VectorMap) // Throw a runtime exception if there is a non-unique indices. // TODO: Improve this error message. @@ -193,16 +192,14 @@ class SparseVec[A <: Data]( // in the denseVec. If out-of-bounds values are possible and the user // instructed us to return the first-element on out-of-bounds acesses, // then fill out the array with BitPats to do this. - val bitPats = indices.zipWithIndex.map { - case (index, i) => - BitPat(index.U(addrWidth.W)) -> BitPat(d.encoding(i + baseEncodedAddress, encodedSize)) + val bitPats = indices.zipWithIndex.map { case (index, i) => + BitPat(index.U(addrWidth.W)) -> BitPat(d.encoding(i + baseEncodedAddress, encodedSize)) } ++ { (outOfBoundsValue, zeroValue) match { case (OutOfBoundsBehavior.Indeterminate, _) | (_, None) => Seq.empty case (OutOfBoundsBehavior.First, Some(_)) => - (size until BigInt(addrWidth).pow(2).toInt).map { - case i => - BitPat(i.U(addrWidth.W)) -> BitPat(d.encoding(baseEncodedAddress, encodedSize)) + (size until BigInt(addrWidth).pow(2).toInt).map { case i => + BitPat(i.U(addrWidth.W)) -> BitPat(d.encoding(baseEncodedAddress, encodedSize)) } } } @@ -237,11 +234,10 @@ class SparseVec[A <: Data]( result := defaultValue.getValue(lookupType) // Generate one when statement for each value. - indices.zip(elements.values).foreach { - case (index, data) => - when(addr === index.U) { - result := data - } + indices.zip(elements.values).foreach { case (index, data) => + when(addr === index.U) { + result := data + } } // If the elements have a value at index zero and if the user indicated diff --git a/src/main/scala/chisel3/util/circt/DPI.scala b/src/main/scala/chisel3/util/circt/DPI.scala index 4dc2674066e..1e6cd2fe79f 100644 --- a/src/main/scala/chisel3/util/circt/DPI.scala +++ b/src/main/scala/chisel3/util/circt/DPI.scala @@ -44,10 +44,7 @@ object RawClockedNonVoidFunctionCall { ret: => T, inputNames: Option[Seq[String]] = None, outputName: Option[String] = None - )(clock: Clock, - enable: Bool, - data: Data* - ): T = { + )(clock: Clock, enable: Bool, data: Data*): T = { IntrinsicExpr( "circt_dpi_call", ret, @@ -77,9 +74,7 @@ object RawUnclockedNonVoidFunctionCall { ret: => T, inputNames: Option[Seq[String]] = None, outputName: Option[String] = None - )(enable: Bool, - data: Data* - ): T = { + )(enable: Bool, data: Data*): T = { IntrinsicExpr( "circt_dpi_call", ret, @@ -102,10 +97,7 @@ object RawClockedVoidFunctionCall { def apply( functionName: String, inputNames: Option[Seq[String]] = None - )(clock: Clock, - enable: Bool, - data: Data* - ): Unit = { + )(clock: Clock, enable: Bool, data: Data*): Unit = { Intrinsic("circt_dpi_call", GetDPIParams(functionName, true, inputNames): _*)( (Seq(clock, enable) ++ data): _* ) @@ -115,13 +107,13 @@ object RawClockedVoidFunctionCall { // A common trait for DPI functions. trait DPIFunctionImport { def functionName: String - def inputNames: Option[Seq[String]] = None + def inputNames: Option[Seq[String]] = None } // Base trait for a non-void function that returns `T`. trait DPINonVoidFunctionImport[T <: Data] extends DPIFunctionImport { - def ret: T - def clocked: Boolean + def ret: T + def clocked: Boolean def outputName: Option[String] = None final def callWithEnable(enable: Bool, data: Data*): T = if (clocked) { diff --git a/src/main/scala/chisel3/util/experimental/AutoBlackBox.scala b/src/main/scala/chisel3/util/experimental/AutoBlackBox.scala index 62d67b3bc3f..c6abc8c5b87 100644 --- a/src/main/scala/chisel3/util/experimental/AutoBlackBox.scala +++ b/src/main/scala/chisel3/util/experimental/AutoBlackBox.scala @@ -10,8 +10,7 @@ import chisel3.experimental.SourceInfo class AutoBlackBox( val verilog: String, val signalFilter: String => Boolean = _ => true -)( - implicit val __sourceInfo: SourceInfo) +)(implicit val __sourceInfo: SourceInfo) extends FixedIOExtModule( ioGenerator = new AutoBundleFromVerilog( SeqMap.from(SlangUtils.verilogModuleIO(SlangUtils.getVerilogAst(verilog))) @@ -22,12 +21,11 @@ class AutoBlackBox( } class AutoBundleFromVerilog( - allElements: SeqMap[String, Data] + allElements: SeqMap[String, Data] )(signalFilter: String => Boolean) extends Record { - val elements: SeqMap[String, Data] = allElements.filter(n => signalFilter(n._1)).map { - case (k, v) => - k -> chisel3.reflect.DataMirror.internal.chiselTypeClone(v) + val elements: SeqMap[String, Data] = allElements.filter(n => signalFilter(n._1)).map { case (k, v) => + k -> chisel3.reflect.DataMirror.internal.chiselTypeClone(v) } def apply(data: String) = elements.getOrElse( data, diff --git a/src/main/scala/chisel3/util/experimental/BoringUtils.scala b/src/main/scala/chisel3/util/experimental/BoringUtils.scala index 83e59fb9916..f6eb88d82a5 100644 --- a/src/main/scala/chisel3/util/experimental/BoringUtils.scala +++ b/src/main/scala/chisel3/util/experimental/BoringUtils.scala @@ -251,8 +251,8 @@ object BoringUtils { def boringError(module: BaseModule): Unit = { (module.fullyClosedErrorMessages ++ Seq( (si, s"Can only bore into modules that are not fully closed: ${module.name} was fully closed") - )).foreach { - case (sourceInfo, msg) => Builder.error(msg)(sourceInfo) + )).foreach { case (sourceInfo, msg) => + Builder.error(msg)(sourceInfo) } } def drill(source: A, path: Seq[BaseModule], connectionLocation: Seq[BaseModule], up: Boolean): A = { diff --git a/src/main/scala/chisel3/util/experimental/CIRCTSRAMInterface.scala b/src/main/scala/chisel3/util/experimental/CIRCTSRAMInterface.scala index 9cc236368bf..93ba2a6d6b3 100644 --- a/src/main/scala/chisel3/util/experimental/CIRCTSRAMInterface.scala +++ b/src/main/scala/chisel3/util/experimental/CIRCTSRAMInterface.scala @@ -21,7 +21,8 @@ case class CIRCTSRAMParameter( readwrite: Int, depth: Int, width: Int, - maskGranularity: Int) { + maskGranularity: Int +) { def masked: Boolean = maskGranularity != 0 } diff --git a/src/main/scala/chisel3/util/experimental/LoadMemoryTransform.scala b/src/main/scala/chisel3/util/experimental/LoadMemoryTransform.scala index cad3bb966f1..47c95a641ab 100644 --- a/src/main/scala/chisel3/util/experimental/LoadMemoryTransform.scala +++ b/src/main/scala/chisel3/util/experimental/LoadMemoryTransform.scala @@ -17,8 +17,8 @@ import scala.collection.mutable private case class ChiselLoadMemoryAnnotation[T <: Data]( target: MemBase[T], fileName: String, - hexOrBinary: MemoryLoadFileType.FileType = MemoryLoadFileType.Hex) - extends ChiselAnnotation { + hexOrBinary: MemoryLoadFileType.FileType = MemoryLoadFileType.Hex +) extends ChiselAnnotation { if (fileName.isEmpty) { throw new Exception( diff --git a/src/main/scala/chisel3/util/experimental/decode/DecodeTableAnnotation.scala b/src/main/scala/chisel3/util/experimental/decode/DecodeTableAnnotation.scala index 2b50ef9016f..00c23083d7f 100644 --- a/src/main/scala/chisel3/util/experimental/decode/DecodeTableAnnotation.scala +++ b/src/main/scala/chisel3/util/experimental/decode/DecodeTableAnnotation.scala @@ -13,10 +13,7 @@ import firrtl.annotations.{Annotation, ReferenceTarget, SingleTargetAnnotation} * @param truthTable input [[TruthTable]] encoded in a serialized [[TruthTable]]. * @param minimizedTable minimized [[truthTable]] encoded in a serialized [[TruthTable]]. */ -case class DecodeTableAnnotation( - target: ReferenceTarget, - truthTable: String, - minimizedTable: String) +case class DecodeTableAnnotation(target: ReferenceTarget, truthTable: String, minimizedTable: String) extends SingleTargetAnnotation[ReferenceTarget] { override def duplicate(n: ReferenceTarget): Annotation = this.copy(target = n) } diff --git a/src/main/scala/chisel3/util/experimental/decode/QMCMinimizer.scala b/src/main/scala/chisel3/util/experimental/decode/QMCMinimizer.scala index b9456ea5b94..b845b3e45a9 100644 --- a/src/main/scala/chisel3/util/experimental/decode/QMCMinimizer.scala +++ b/src/main/scala/chisel3/util/experimental/decode/QMCMinimizer.scala @@ -232,7 +232,7 @@ object QMCMinimizer extends Minimizer { ) // make sure no two inputs specified in the truth table intersect - for (t <- inputs.tails; if t.nonEmpty) + for (t <- inputs.tails if t.nonEmpty) for (u <- t.tail) require(!t.head.intersects(u), "truth table entries " + t.head + " and " + u + " overlap") @@ -317,26 +317,24 @@ object QMCMinimizer extends Minimizer { ) ) else - minimized.tail.foldLeft(table.copy(table = Seq(minimized.head))) { - case (tb, t) => - if (tb.table.exists(x => x._1 == t._1)) { - tb.copy(table = tb.table.map { - case (k, v) => - if (k == t._1) { - def ones(bitPat: BitPat) = bitPat.rawString.zipWithIndex.collect { case ('1', x) => x } - ( - k, - BitPat( - "b" + (0 until v.getWidth) - .map(i => if ((ones(v) ++ ones(t._2)).contains(i)) "1" else "?") - .mkString - ) - ) - } else (k, v) - }) - } else { - tb.copy(table = tb.table :+ t) - } + minimized.tail.foldLeft(table.copy(table = Seq(minimized.head))) { case (tb, t) => + if (tb.table.exists(x => x._1 == t._1)) { + tb.copy(table = tb.table.map { case (k, v) => + if (k == t._1) { + def ones(bitPat: BitPat) = bitPat.rawString.zipWithIndex.collect { case ('1', x) => x } + ( + k, + BitPat( + "b" + (0 until v.getWidth) + .map(i => if ((ones(v) ++ ones(t._2)).contains(i)) "1" else "?") + .mkString + ) + ) + } else (k, v) + }) + } else { + tb.copy(table = tb.table :+ t) + } } } } diff --git a/src/main/scala/chisel3/util/experimental/decode/TruthTable.scala b/src/main/scala/chisel3/util/experimental/decode/TruthTable.scala index 8d637ed169c..1a741cd0455 100644 --- a/src/main/scala/chisel3/util/experimental/decode/TruthTable.scala +++ b/src/main/scala/chisel3/util/experimental/decode/TruthTable.scala @@ -57,9 +57,8 @@ object TruthTable { * for the input */ private def mergeTableOnInputs(table: Iterable[(BitPat, BitPat)]): Seq[(BitPat, Seq[BitPat])] = { - groupByIntoSeq(table)(_._1).map { - case (input, mappings) => - input -> mappings.map(_._2) + groupByIntoSeq(table)(_._1).map { case (input, mappings) => + input -> mappings.map(_._2) } } @@ -105,14 +104,13 @@ object TruthTable { val mergedTable = mergeTableOnInputs(paddedTable) - val finalTable: Seq[(BitPat, BitPat)] = mergedTable.map { - case (input, outputs) => - val (result, noCollisions) = outputs.tail.foldLeft((outputs.head, checkCollisions)) { - case ((acc, ok), o) => (merge(acc, o), ok && acc.overlap(o)) - } - // Throw an error if checkCollisions is true but there are bits with a non-zero overlap. - require(!checkCollisions || noCollisions, s"TruthTable conflict on merged row:\n $input -> $outputs") - (input, result) + val finalTable: Seq[(BitPat, BitPat)] = mergedTable.map { case (input, outputs) => + val (result, noCollisions) = outputs.tail.foldLeft((outputs.head, checkCollisions)) { case ((acc, ok), o) => + (merge(acc, o), ok && acc.overlap(o)) + } + // Throw an error if checkCollisions is true but there are bits with a non-zero overlap. + require(!checkCollisions || noCollisions, s"TruthTable conflict on merged row:\n $input -> $outputs") + (input, result) } import BitPat.bitPatOrder @@ -188,9 +186,9 @@ object TruthTable { .rawString .zip(indexes) def bitPat(indexedChar: Seq[(Char, Int)]) = BitPat(s"b${indexedChar - .sortBy(_._2) - .map(_._1) - .mkString}") + .sortBy(_._2) + .map(_._1) + .mkString}") val needToMerge = tables.size > 1 if (needToMerge) { TruthTable( diff --git a/src/main/scala/chisel3/util/experimental/decode/decoder.scala b/src/main/scala/chisel3/util/experimental/decode/decoder.scala index e6424883a15..b25685dd365 100644 --- a/src/main/scala/chisel3/util/experimental/decode/decoder.scala +++ b/src/main/scala/chisel3/util/experimental/decode/decoder.scala @@ -20,8 +20,8 @@ object decoder extends LazyLogging { * @return decode table output. */ def apply(minimizer: Minimizer, input: UInt, truthTable: TruthTable): UInt = { - val minimizedTable = getAnnotations().collect { - case DecodeTableAnnotation(_, in, out) => TruthTable.fromString(in) -> TruthTable.fromString(out) + val minimizedTable = getAnnotations().collect { case DecodeTableAnnotation(_, in, out) => + TruthTable.fromString(in) -> TruthTable.fromString(out) }.toMap.getOrElse(truthTable, minimizer.minimize(truthTable)) if (minimizedTable.table.isEmpty) { val outputs = Wire(UInt(minimizedTable.default.getWidth.W)) @@ -105,11 +105,10 @@ object decoder extends LazyLogging { input, chisel3.util.experimental.decode.TruthTable.fromString( { - bitSets.zipWithIndex.flatMap { - case (bs, i) => - bs.terms.map(bp => - s"${bp.rawString}->${if (errorBit) "0" else ""}${"0" * (bitSets.size - i - 1)}1${"0" * i}" - ) + bitSets.zipWithIndex.flatMap { case (bs, i) => + bs.terms.map(bp => + s"${bp.rawString}->${if (errorBit) "0" else ""}${"0" * (bitSets.size - i - 1)}1${"0" * i}" + ) } ++ Seq(s"${if (errorBit) "1" ++ "0" * bitSets.size else "?" * bitSets.size}") }.mkString("\n") ) diff --git a/src/main/scala/chisel3/util/pla.scala b/src/main/scala/chisel3/util/pla.scala index b43812d0c04..be2ec3a52fb 100644 --- a/src/main/scala/chisel3/util/pla.scala +++ b/src/main/scala/chisel3/util/pla.scala @@ -104,11 +104,10 @@ object pla { .tabulate(numberOfOutputs) { i => val andMatrixLines = table // OR matrix composed by input terms which makes this output bit a `1` - .filter { - case (_, or) => or.mask.testBit(i) && or.value.testBit(i) - }.map { - case (inputTerm, _) => - andMatrixOutputs(inputTerm.toString) + .filter { case (_, or) => + or.mask.testBit(i) && or.value.testBit(i) + }.map { case (inputTerm, _) => + andMatrixOutputs(inputTerm.toString) } if (andMatrixLines.isEmpty) false.B else Cat(andMatrixLines).orR diff --git a/src/main/scala/chisel3/util/random/FibonacciLFSR.scala b/src/main/scala/chisel3/util/random/FibonacciLFSR.scala index 4da51a4e900..1c52f4598e8 100644 --- a/src/main/scala/chisel3/util/random/FibonacciLFSR.scala +++ b/src/main/scala/chisel3/util/random/FibonacciLFSR.scala @@ -45,8 +45,8 @@ class FibonacciLFSR( seed: Option[BigInt] = Some(1), val reduction: LFSRReduce = XOR, step: Int = 1, - updateSeed: Boolean = false) - extends PRNG(width, seed, step, updateSeed) + updateSeed: Boolean = false +) extends PRNG(width, seed, step, updateSeed) with LFSR { def delta(s: Seq[Bool]): Seq[Bool] = taps.map { case i => s(i - 1) }.reduce(reduction) +: s.dropRight(1) diff --git a/src/main/scala/chisel3/util/random/GaloisLFSR.scala b/src/main/scala/chisel3/util/random/GaloisLFSR.scala index f452cf750b5..be3d8b98b0b 100644 --- a/src/main/scala/chisel3/util/random/GaloisLFSR.scala +++ b/src/main/scala/chisel3/util/random/GaloisLFSR.scala @@ -43,8 +43,8 @@ class GaloisLFSR( seed: Option[BigInt] = Some(1), val reduction: LFSRReduce = XOR, step: Int = 1, - updateSeed: Boolean = false) - extends PRNG(width, seed, step, updateSeed) + updateSeed: Boolean = false +) extends PRNG(width, seed, step, updateSeed) with LFSR { def delta(s: Seq[Bool]): Seq[Bool] = { diff --git a/src/main/scala/chisel3/verilog.scala b/src/main/scala/chisel3/verilog.scala index 570cf659ac6..7c49f09f5f7 100644 --- a/src/main/scala/chisel3/verilog.scala +++ b/src/main/scala/chisel3/verilog.scala @@ -46,8 +46,8 @@ object getVerilogString { ) ++ (new circt.stage.ChiselStage).shell.parse(args) ++ annotations phase .transform(annos) - .collectFirst { - case EmittedVerilogCircuitAnnotation(a) => a + .collectFirst { case EmittedVerilogCircuitAnnotation(a) => + a } .get .value @@ -61,8 +61,8 @@ object emitVerilog { Array("--target", "systemverilog") ++ args, ChiselGeneratorAnnotation(() => gen) +: annotations ) - .collectFirst { - case EmittedVerilogCircuitAnnotation(a) => a + .collectFirst { case EmittedVerilogCircuitAnnotation(a) => + a } .get .value diff --git a/src/main/scala/circt/stage/Annotations.scala b/src/main/scala/circt/stage/Annotations.scala index b8e81bf11cb..9cd9285741c 100644 --- a/src/main/scala/circt/stage/Annotations.scala +++ b/src/main/scala/circt/stage/Annotations.scala @@ -91,10 +91,7 @@ object CIRCTTargetAnnotation extends HasShellOptions { * @param value a string of MLIR * @param suffix an optional suffix added to the filename when this is written to disk */ -case class EmittedMLIR( - filename: String, - value: String, - suffix: Option[String]) +case class EmittedMLIR(filename: String, value: String, suffix: Option[String]) extends NoTargetAnnotation with CustomFileEmission { diff --git a/src/main/scala/circt/stage/CIRCTOptions.scala b/src/main/scala/circt/stage/CIRCTOptions.scala index 91c3cb3030e..234e76bbb97 100644 --- a/src/main/scala/circt/stage/CIRCTOptions.scala +++ b/src/main/scala/circt/stage/CIRCTOptions.scala @@ -19,7 +19,8 @@ class CIRCTOptions private[stage] ( val firtoolOptions: Seq[String] = Seq.empty, val splitVerilog: Boolean = false, val firtoolBinaryPath: Option[String] = None, - val dumpFir: Boolean = false) { + val dumpFir: Boolean = false +) { private[stage] def copy( outputFile: Option[File] = outputFile, diff --git a/src/main/scala/circt/stage/ChiselStage.scala b/src/main/scala/circt/stage/ChiselStage.scala index d4dfee09c16..93cdf601ea7 100644 --- a/src/main/scala/circt/stage/ChiselStage.scala +++ b/src/main/scala/circt/stage/ChiselStage.scala @@ -118,8 +118,8 @@ object ChiselStage { phase .transform(annos) - .collectFirst { - case FirrtlCircuitAnnotation(a) => a + .collectFirst { case FirrtlCircuitAnnotation(a) => + a } .get } @@ -137,8 +137,8 @@ object ChiselStage { phase .transform(annos) - .collectFirst { - case EmittedMLIR(_, a, _) => a + .collectFirst { case EmittedMLIR(_, a, _) => + a } .get } @@ -156,8 +156,8 @@ object ChiselStage { phase .transform(annos) - .collectFirst { - case EmittedMLIR(_, a, _) => a + .collectFirst { case EmittedMLIR(_, a, _) => + a } .get } @@ -180,8 +180,8 @@ object ChiselStage { ) ++ (new Shell("circt")).parse(args) ++ firtoolOpts.map(FirtoolOption(_)) phase .transform(annos) - .collectFirst { - case EmittedVerilogCircuitAnnotation(a) => a + .collectFirst { case EmittedVerilogCircuitAnnotation(a) => + a } .get .value @@ -222,8 +222,8 @@ object ChiselStage { ) ++ (new Shell("circt")).parse(args) ++ firtoolOpts.map(FirtoolOption(_)) phase .transform(annos) - .collectFirst { - case EmittedBtor2CircuitAnnotation(a) => a + .collectFirst { case EmittedBtor2CircuitAnnotation(a) => + a } .get .value diff --git a/src/test/scala/chisel3/experimental/dataview/ReifySpec.scala b/src/test/scala/chisel3/experimental/dataview/ReifySpec.scala index 4e7b1b321af..9d2467371b4 100644 --- a/src/test/scala/chisel3/experimental/dataview/ReifySpec.scala +++ b/src/test/scala/chisel3/experimental/dataview/ReifySpec.scala @@ -66,9 +66,8 @@ object ReifySpec { implicit val myView: DataView[(UInt, TargetBundle), ViewBundle] = DataView.mapping[(UInt, TargetBundle), ViewBundle]( _ => new ViewBundle, - { - case ((u, t), v) => - Seq(u -> v.foo, t.fizz.child.value -> v.bar.a(0), t.buzz.value -> v.bar.a(1), t.vec -> v.bar.b) + { case ((u, t), v) => + Seq(u -> v.foo, t.fizz.child.value -> v.bar.a(0), t.buzz.value -> v.bar.a(1), t.vec -> v.bar.b) } ) } @@ -84,11 +83,10 @@ class ReifySpec extends AnyFunSpec { val wires = (new AllElementsBundle).getElements.map(Wire(_)) // .getElements returns Data so we have to match that these are Elements. - wires.foreach { - case elt: Element => - _reify(elt) should be(elt) - _reifyIdentityView(elt) should be(Some(elt)) - reifySingleTarget(elt) should be(Some(elt)) + wires.foreach { case elt: Element => + _reify(elt) should be(elt) + _reifyIdentityView(elt) should be(Some(elt)) + reifySingleTarget(elt) should be(Some(elt)) } }) } @@ -98,11 +96,10 @@ class ReifySpec extends AnyFunSpec { val bundle = IO(new AllElementsBundle) // .getElements returns Data so we have to match that these are Elements. - bundle.getElements.foreach { - case elt: Element => - _reify(elt) should be(elt) - _reifyIdentityView(elt) should be(Some(elt)) - reifySingleTarget(elt) should be(Some(elt)) + bundle.getElements.foreach { case elt: Element => + _reify(elt) should be(elt) + _reifyIdentityView(elt) should be(Some(elt)) + reifySingleTarget(elt) should be(Some(elt)) } }) } @@ -116,11 +113,10 @@ class ReifySpec extends AnyFunSpec { reifySingleTarget(view) should be(Some(bundle)) // .getElements returns Data so we have to match that these are Elements. - view.getElements.zip(bundle.getElements).foreach { - case (v: Element, t: Element) => - _reify(v) should be(t) - _reifyIdentityView(v) should be(Some(t)) - reifySingleTarget(v) should be(Some(t)) + view.getElements.zip(bundle.getElements).foreach { case (v: Element, t: Element) => + _reify(v) should be(t) + _reifyIdentityView(v) should be(Some(t)) + reifySingleTarget(v) should be(Some(t)) } }) } @@ -134,11 +130,10 @@ class ReifySpec extends AnyFunSpec { reifySingleTarget(view) should be(None) // .getElements returns Data so we have to match that these are Elements. - view.getElements.zip(wires).foreach { - case (v: Element, t: Element) => - _reify(v) should be(t) - _reifyIdentityView(v) should be(Some(t)) - reifySingleTarget(v) should be(Some(t)) + view.getElements.zip(wires).foreach { case (v: Element, t: Element) => + _reify(v) should be(t) + _reifyIdentityView(v) should be(Some(t)) + reifySingleTarget(v) should be(Some(t)) } }) } @@ -196,11 +191,10 @@ class ReifySpec extends AnyFunSpec { val child = Instantiate(new MyModule) // .getElements returns Data so we have to match that these are Elements. - child.ios.foreach { - case elt: Element => - _reify(elt) should be(elt) - _reifyIdentityView(elt) should be(Some(elt)) - reifySingleTarget(elt) should be(Some(elt)) + child.ios.foreach { case elt: Element => + _reify(elt) should be(elt) + _reifyIdentityView(elt) should be(Some(elt)) + reifySingleTarget(elt) should be(Some(elt)) } }) } @@ -214,11 +208,10 @@ class ReifySpec extends AnyFunSpec { val child = Instantiate(new MyModule) // .getElements returns Data so we have to match that these are Elements. - child.bundle.getElements.foreach { - case elt: Element => - _reify(elt) should be(elt) - _reifyIdentityView(elt) should be(Some(elt)) - reifySingleTarget(elt) should be(Some(elt)) + child.bundle.getElements.foreach { case elt: Element => + _reify(elt) should be(elt) + _reifyIdentityView(elt) should be(Some(elt)) + reifySingleTarget(elt) should be(Some(elt)) } }) } @@ -236,11 +229,10 @@ class ReifySpec extends AnyFunSpec { reifySingleTarget(child.view) should be(Some(child.bundle)) // .getElements returns Data so we have to match that these are Elements. - child.view.getElements.zip(child.bundle.getElements).foreach { - case (v: Element, t: Element) => - _reify(v) should be(t) - _reifyIdentityView(v) should be(Some(t)) - reifySingleTarget(v) should be(Some(t)) + child.view.getElements.zip(child.bundle.getElements).foreach { case (v: Element, t: Element) => + _reify(v) should be(t) + _reifyIdentityView(v) should be(Some(t)) + reifySingleTarget(v) should be(Some(t)) } }) } @@ -258,11 +250,10 @@ class ReifySpec extends AnyFunSpec { reifySingleTarget(child.view) should be(None) // .getElements returns Data so we have to match that these are Elements. - child.view.getElements.zip(child.wires).foreach { - case (v: Element, t: Element) => - _reify(v) should be(t) - _reifyIdentityView(v) should be(Some(t)) - reifySingleTarget(v) should be(Some(t)) + child.view.getElements.zip(child.wires).foreach { case (v: Element, t: Element) => + _reify(v) should be(t) + _reifyIdentityView(v) should be(Some(t)) + reifySingleTarget(v) should be(Some(t)) } }) } diff --git a/src/test/scala/chisel3/testers/TestUtils.scala b/src/test/scala/chisel3/testers/TestUtils.scala index 7051fabb34c..174c98ec791 100644 --- a/src/test/scala/chisel3/testers/TestUtils.scala +++ b/src/test/scala/chisel3/testers/TestUtils.scala @@ -31,8 +31,8 @@ object TestUtils { ChiselGeneratorAnnotation(() => gen) +: annos ) - val circuit = processedAnnos.collectFirst { - case FirrtlCircuitAnnotation(a) => a + val circuit = processedAnnos.collectFirst { case FirrtlCircuitAnnotation(a) => + a }.get (circuit, processedAnnos) } diff --git a/src/test/scala/chiselTests/AnnotatingDiamondSpec.scala b/src/test/scala/chiselTests/AnnotatingDiamondSpec.scala index 7216645221c..b466bea5dba 100644 --- a/src/test/scala/chiselTests/AnnotatingDiamondSpec.scala +++ b/src/test/scala/chiselTests/AnnotatingDiamondSpec.scala @@ -4,7 +4,7 @@ package chiselTests import chisel3._ import chisel3.experimental.{annotate, ChiselAnnotation} -import chisel3.stage.{ChiselGeneratorAnnotation} +import chisel3.stage.ChiselGeneratorAnnotation import chisel3.testers.BasicTester import circt.stage.ChiselStage import firrtl.annotations.{CircuitTarget, SingleTargetAnnotation, Target} diff --git a/src/test/scala/chiselTests/BitwiseOps.scala b/src/test/scala/chiselTests/BitwiseOps.scala index 2c050bfa7f0..ffb5cdfe983 100644 --- a/src/test/scala/chiselTests/BitwiseOps.scala +++ b/src/test/scala/chiselTests/BitwiseOps.scala @@ -20,9 +20,8 @@ class BitwiseOpsTester(w: Int, _a: Int, _b: Int) extends BasicTester { 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 b7bc4931f24..61d80cdc576 100644 --- a/src/test/scala/chiselTests/BlackBox.scala +++ b/src/test/scala/chiselTests/BlackBox.scala @@ -206,14 +206,14 @@ class BlackBoxSpec extends ChiselFlatSpec { "A BlackBoxed register" should "work" in { assertTesterPasses({ new BlackBoxWithClockTester }, Seq("/chisel3/BlackBoxTest.v")) } - //TODO: SFC->MFC, this test is ignored because the parameters have undesired quotes around values in verilog in MFC + // TODO: SFC->MFC, this test is ignored because the parameters have undesired quotes around values in verilog in MFC "BlackBoxes with simpler parameters" should "work" ignore { assertTesterPasses( { new SimplerBlackBoxWithParamsTester }, Seq("/chisel3/BlackBoxTest.v") ) } - //TODO: SFC->MFC, this test is ignored because the parameters have undesired quotes around values in verilog in MFC + // TODO: SFC->MFC, this test is ignored because the parameters have undesired quotes around values in verilog in MFC "BlackBoxes with parameters" should "work" ignore { assertTesterPasses({ new BlackBoxWithParamsTester }, Seq("/chisel3/BlackBoxTest.v")) } diff --git a/src/test/scala/chiselTests/BoringUtilsSpec.scala b/src/test/scala/chiselTests/BoringUtilsSpec.scala index dea6d02f465..059795585b1 100644 --- a/src/test/scala/chiselTests/BoringUtilsSpec.scala +++ b/src/test/scala/chiselTests/BoringUtilsSpec.scala @@ -279,7 +279,7 @@ class BoringUtilsSpec extends ChiselFlatSpec with ChiselRunners with Utils with class Foo extends RawModule { val a = IO(Output(UInt())) val bar = Module(new Bar) - //val preBore = DataMirror.modulePorts(bar) + // val preBore = DataMirror.modulePorts(bar) a := BoringUtils.bore(bar.a_wire) val postBore = DataMirror.modulePorts(bar) postBore.size should be(1) diff --git a/src/test/scala/chiselTests/BundleElementsSpec.scala b/src/test/scala/chiselTests/BundleElementsSpec.scala index 5a68acab182..8c33b088ef2 100644 --- a/src/test/scala/chiselTests/BundleElementsSpec.scala +++ b/src/test/scala/chiselTests/BundleElementsSpec.scala @@ -404,7 +404,7 @@ class BundleElementsSpec extends AnyFreeSpec with Matchers { class UsesBundleWithOptionFields extends Module { val outTrue = IO(Output(new OptionBundle(hasIn = true))) val outFalse = IO(Output(new OptionBundle(hasIn = false))) - //NOTE: The _.in.get _.in is an optional field + // NOTE: The _.in.get _.in is an optional field assertElementsMatchExpected(outTrue)("out" -> _.out, "in" -> _.in.get) assertElementsMatchExpected(outFalse)("out" -> _.out) } @@ -429,7 +429,7 @@ class BundleElementsSpec extends AnyFreeSpec with Matchers { } "plugin will NOT see fields that are Data but declared in some way as Any" in { - //This is not incompatible with chisel not using the plugin, but this code is considered bad practice + // This is not incompatible with chisel not using the plugin, but this code is considered bad practice ChiselStage.emitCHIRRTL(new Module { val out = IO(Output(new Bundle { @@ -497,10 +497,7 @@ class BundleElementsSpec extends AnyFreeSpec with Matchers { } "plugin should handle fields using the boolean to option construct" in { - case class ALUConfig( - xLen: Int, - mul: Boolean, - b: Boolean) + case class ALUConfig(xLen: Int, mul: Boolean, b: Boolean) class OptionalBundle extends Bundle { val optionBundleA = Input(UInt(3.W)) @@ -592,23 +589,22 @@ object assertElementsMatchExpected { val missingMsg = "missing field in #elements" val extraMsg = "extra field in #elements" val paired = elements.toSeq.zipAll(expected, missingMsg -> UInt(1.W), extraMsg -> UInt(1.W)) - val errorsStrings = paired.flatMap { - case (element, expected) => - val (elementName, elementData) = element - val (expectedName, expectedData) = expected - if (elementName == missingMsg) { - Some(s"#elements is missing the '$expectedName' field") - } else if (expectedName == extraMsg) { - Some(s"expected fields did not include '$elementName' field found in #elements") - } else if (elementName != expectedName) { - Some(s"field: '$elementName' did not match expected '$expectedName'") - } else if (elementData != expectedData) { - Some( - s"field '$elementName' data field ${elementData}(${elementData.hashCode}) did not match expected $expectedData(${expectedData.hashCode})" - ) - } else { - None - } + val errorsStrings = paired.flatMap { case (element, expected) => + val (elementName, elementData) = element + val (expectedName, expectedData) = expected + if (elementName == missingMsg) { + Some(s"#elements is missing the '$expectedName' field") + } else if (expectedName == extraMsg) { + Some(s"expected fields did not include '$elementName' field found in #elements") + } else if (elementName != expectedName) { + Some(s"field: '$elementName' did not match expected '$expectedName'") + } else if (elementData != expectedData) { + Some( + s"field '$elementName' data field ${elementData}(${elementData.hashCode}) did not match expected $expectedData(${expectedData.hashCode})" + ) + } else { + None + } } assert(errorsStrings.isEmpty, s"Bundle: ${bun.getClass.getName}: " + errorsStrings.mkString(", ")) } diff --git a/src/test/scala/chiselTests/ChiselEnum.scala b/src/test/scala/chiselTests/ChiselEnum.scala index 5a7d2c1dc32..861aa1211ab 100644 --- a/src/test/scala/chiselTests/ChiselEnum.scala +++ b/src/test/scala/chiselTests/ChiselEnum.scala @@ -813,8 +813,8 @@ class ChiselEnumAnnotationSpec extends AnyFreeSpec with Matchers { def isCorrect(anno: EnumDefAnnotation, correct: CorrectDefAnno): Boolean = { (anno.typeName == correct.typeName || - anno.typeName.endsWith("." + correct.typeName) || - anno.typeName.endsWith("$" + correct.typeName)) && + anno.typeName.endsWith("." + correct.typeName) || + anno.typeName.endsWith("$" + correct.typeName)) && anno.definition == correct.definition } @@ -824,7 +824,7 @@ class ChiselEnumAnnotationSpec extends AnyFreeSpec with Matchers { 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.endsWith("$" + correct.typeName)) } def isCorrect(anno: EnumVecAnnotation, correct: CorrectVecAnno): Boolean = { @@ -833,7 +833,7 @@ class ChiselEnumAnnotationSpec extends AnyFreeSpec with Matchers { case _ => throw new Exception("Unknown target type in EnumVecAnnotation") }) && (anno.typeName == correct.typeName || anno.typeName.endsWith("." + correct.typeName) || - anno.typeName.endsWith("$" + correct.typeName)) && + anno.typeName.endsWith("$" + correct.typeName)) && anno.fields.map(_.toSeq).toSet == correct.fields } diff --git a/src/test/scala/chiselTests/ChiselSpec.scala b/src/test/scala/chiselTests/ChiselSpec.scala index e68a1da6816..04710e88361 100644 --- a/src/test/scala/chiselTests/ChiselSpec.scala +++ b/src/test/scala/chiselTests/ChiselSpec.scala @@ -186,8 +186,8 @@ trait ChiselRunners extends Assertions { Array("--target-dir", BackendCompilationUtilities.createTestDirectory(this.getClass.getSimpleName).toString), Seq(ChiselGeneratorAnnotation(() => t), CIRCTTargetAnnotation(CIRCTTarget.SystemVerilog)) ) - .collectFirst { - case EmittedVerilogCircuitAnnotation(a) => a.value + .collectFirst { case EmittedVerilogCircuitAnnotation(a) => + a.value } .getOrElse(fail("No Verilog circuit was emitted by the FIRRTL compiler!")) } @@ -411,7 +411,7 @@ trait Utils { /** Contains helpful function to assert both statements to match, and statements to omit */ trait MatchesAndOmits extends Assertions { private def matches(lines: List[String], matchh: String): Option[String] = lines.filter(_.contains(matchh)).lastOption - private def omits(line: String, omit: String): Option[(String, String)] = + private def omits(line: String, omit: String): Option[(String, String)] = if (line.contains(omit)) Some((omit, line)) else None private def omits(lines: List[String], omit: String): Seq[(String, String)] = lines.flatMap { omits(_, omit) } def matchesAndOmits(output: String)(matchList: String*)(omitList: String*): Unit = { @@ -419,8 +419,8 @@ trait MatchesAndOmits extends Assertions { val unmatched = matchList.flatMap { m => if (matches(lines, m).nonEmpty) None else Some(m) }.map(x => s" > '$x' was unmatched") - val unomitted = omitList.flatMap { o => omits(lines, o) }.map { - case (o, l) => s" > '$o' was not omitted in ($l)" + val unomitted = omitList.flatMap { o => omits(lines, o) }.map { case (o, l) => + s" > '$o' was not omitted in ($l)" } val results = unmatched ++ unomitted assert(results.isEmpty, results.mkString("\n") + s"\nFull Input:\n'$output'\n") diff --git a/src/test/scala/chiselTests/ConnectableSpec.scala b/src/test/scala/chiselTests/ConnectableSpec.scala index 3cb8e2e371e..de40464f244 100644 --- a/src/test/scala/chiselTests/ConnectableSpec.scala +++ b/src/test/scala/chiselTests/ConnectableSpec.scala @@ -21,8 +21,8 @@ object ConnectableSpec { inDrivesOut: Boolean, op: (Data, Data) => Unit, monitorOp: Option[(Data, Data) => Unit], - nTmps: Int) - extends Module { + nTmps: Int + ) extends Module { val io = IO(new Bundle { val in = Flipped(inType) val out = Flipped(Flipped(outType)) // no clonetype, no Aligned (yet) @@ -36,12 +36,12 @@ object ConnectableSpec { val wiresIn = Seq.fill(nTmps)(Wire(inType)) val wiresOut = Seq.fill(nTmps)(Wire(outType)) - (Seq(io.out) ++ wiresOut ++ wiresIn).zip(wiresOut ++ wiresIn :+ io.in).foreach { - case (l, r) => if (inDrivesOut) op(l, r) else op(r, l) + (Seq(io.out) ++ wiresOut ++ wiresIn).zip(wiresOut ++ wiresIn :+ io.in).foreach { case (l, r) => + if (inDrivesOut) op(l, r) else op(r, l) } } - def vec[T <: Data](tpe: T, n: Int = 3) = Vec(n, tpe) + def vec[T <: Data](tpe: T, n: Int = 3) = Vec(n, tpe) def alignedBundle[T <: Data](fieldType: T) = new Bundle { val foo = Flipped(Flipped(fieldType)) val bar = Flipped(Flipped(fieldType)) @@ -96,8 +96,8 @@ object ConnectableSpec { elements ++ allAggs ++ allNestedAgg } def getInfo(t: Data): Seq[Any] = DataMirror - .collectMembers(t) { - case x => (x, DataMirror.specifiedDirectionOf(x)) + .collectMembers(t) { case x => + (x, DataMirror.specifiedDirectionOf(x)) } .toSeq @@ -174,7 +174,7 @@ class ConnectableSpec extends ChiselFunSpec with Utils { // (D)irectional Bulk Connect tests describe("(0): :<>=") { - implicit val op: (Data, Data) => Unit = { _ :<>= _ } + implicit val op: (Data, Data) => Unit = { _ :<>= _ } implicit val monitorOp: Option[(Data, Data) => Unit] = None implicit val inDrivesOut = true implicit val nTmps = 0 @@ -322,7 +322,7 @@ class ConnectableSpec extends ChiselFunSpec with Utils { // TODO Write test that demonstrates multiple evaluation of producer: => T } describe("(1): :<= ") { - implicit val op: (Data, Data) => Unit = { _ :<= _ } + implicit val op: (Data, Data) => Unit = { _ :<= _ } implicit val monitorOp: Option[(Data, Data) => Unit] = None implicit val inDrivesOut = true implicit val nTmps = 0 @@ -542,7 +542,7 @@ class ConnectableSpec extends ChiselFunSpec with Utils { } } describe("(2): :>= ") { - implicit val op: (Data, Data) => Unit = { _ :>= _ } + implicit val op: (Data, Data) => Unit = { _ :>= _ } implicit val monitorOp: Option[(Data, Data) => Unit] = None implicit val inDrivesOut = true implicit val nTmps = 0 @@ -718,7 +718,7 @@ class ConnectableSpec extends ChiselFunSpec with Utils { } } describe("(3): :#= ") { - implicit val op: (Data, Data) => Unit = { _ :<>= _ } + implicit val op: (Data, Data) => Unit = { _ :<>= _ } implicit val monitorOp: Option[(Data, Data) => Unit] = Some({ _ :#= _ }) implicit val inDrivesOut = true implicit val nTmps = 0 @@ -860,7 +860,7 @@ class ConnectableSpec extends ChiselFunSpec with Utils { testException(SInt(1.W), Clock(), "have different types") } it("(3.g): Emit 'attach' between Analog types or Aggregates with Analog types") { - implicit val op: (Data, Data) => Unit = { _ :#= _ } + implicit val op: (Data, Data) => Unit = { _ :#= _ } implicit val monitorOp: Option[(Data, Data) => Unit] = None test(Analog(3.W), Seq("attach (io.out, io.in)")) test(mixedBundle(Analog(3.W)), Seq("attach (io.out.foo, io.in.foo)", "attach (io.out.bar, io.in.bar")) @@ -868,7 +868,7 @@ class ConnectableSpec extends ChiselFunSpec with Utils { } it("(3.h): Error on unconnected or dangling subfield/subindex from either side") { // Missing flip bar - implicit val op: (Data, Data) => Unit = { _ :#= _ } + implicit val op: (Data, Data) => Unit = { _ :#= _ } implicit val monitorOp: Option[(Data, Data) => Unit] = None testException(mixedBundle(Bool()), alignedFooBundle(Bool()), "unmatched consumer field") testException(alignedFooBundle(Bool()), mixedBundle(Bool()), "unmatched producer field") @@ -898,7 +898,7 @@ class ConnectableSpec extends ChiselFunSpec with Utils { ) } it("(3.i): Always connect to consumer regardless of orientation") { - implicit val op: (Data, Data) => Unit = { _ :#= _ } + implicit val op: (Data, Data) => Unit = { _ :#= _ } implicit val monitorOp: Option[(Data, Data) => Unit] = None testException(mixedBundle(Bool()), alignedBundle(Bool()), "cannot be written from module") testDistinctTypes( @@ -913,7 +913,7 @@ class ConnectableSpec extends ChiselFunSpec with Utils { it( "(3.k): When connecting FROM DontCare, emit for aligned aggregate fields and emit for flipped aggregate fields" ) { - implicit val op: (Data, Data) => Unit = { (x, y) => x :#= DontCare } + implicit val op: (Data, Data) => Unit = { (x, y) => x :#= DontCare } implicit val monitorOp: Option[(Data, Data) => Unit] = None test(UInt(3.W), Seq("invalidate io.out")) test(SInt(3.W), Seq("invalidate io.out")) @@ -1021,7 +1021,7 @@ class ConnectableSpec extends ChiselFunSpec with Utils { ) val in = IO(Flipped(new DecoupledGen(() => ab))) val out = IO(new DecoupledGen(() => bc)) - //Programmatic + // Programmatic BundleMap.waive(out) :<>= BundleMap.waive(in) } testCheck( @@ -1051,7 +1051,7 @@ class ConnectableSpec extends ChiselFunSpec with Utils { val in = IO(Flipped(new DecoupledGen(() => ab))) val out = IO(new DecoupledGen(() => bc)) out :<= (chiselTypeOf(out).Lit(_.data.elements("b") -> 1.U, _.data.elements("c") -> 1.U)) - //Programmatic + // Programmatic BundleMap.waive(out) :<>= BundleMap.waive(in) } testCheck( @@ -1172,7 +1172,7 @@ class ConnectableSpec extends ChiselFunSpec with Utils { ) val in = IO(Flipped(new DecoupledGen(() => ab))) val out = IO(new DecoupledGen(() => bc)) - //Programmatic + // Programmatic BundleMap.waive(out) :<>= BundleMap.waive(in).squeezeAll } testCheck( @@ -1353,7 +1353,7 @@ class ConnectableSpec extends ChiselFunSpec with Utils { ) val in = IO(Flipped(new DecoupledGen(() => ab))) val out = IO(new DecoupledGen(() => bc)) - //Programmatic + // Programmatic val (cout, cin) = BundleMap.onlyIncludeUnion(out, in) cout :<>= cin } diff --git a/src/test/scala/chiselTests/CustomBundle.scala b/src/test/scala/chiselTests/CustomBundle.scala index 01b9617c89a..dee99e01a35 100644 --- a/src/test/scala/chiselTests/CustomBundle.scala +++ b/src/test/scala/chiselTests/CustomBundle.scala @@ -12,10 +12,9 @@ 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 -> DataMirror.internal.chiselTypeClone(elt) + val elements = ListMap(elts.map { case (field, elt) => + requireIsChiselType(elt) + field -> DataMirror.internal.chiselTypeClone(elt) }: _*) def apply(elt: String): Data = elements(elt) } diff --git a/src/test/scala/chiselTests/DedupSpec.scala b/src/test/scala/chiselTests/DedupSpec.scala index 465ad21eba0..266c6b83bc2 100644 --- a/src/test/scala/chiselTests/DedupSpec.scala +++ b/src/test/scala/chiselTests/DedupSpec.scala @@ -143,16 +143,16 @@ class DedupSpec extends ChiselFlatSpec { it should "not add DedupGroupAnnotation to intrinsics" in { val (_, annos) = getFirrtlAndAnnos(new ModuleWithIntrinsic) - val dedupGroupAnnos = annos.collect { - case DedupGroupAnnotation(target, _) => target.module + val dedupGroupAnnos = annos.collect { case DedupGroupAnnotation(target, _) => + target.module } dedupGroupAnnos should contain theSameElementsAs Seq("ModuleWithIntrinsic") } it should "not add DedupGroupAnnotation to classes" in { val (_, annos) = getFirrtlAndAnnos(new ModuleWithClass) - val dedupGroupAnnos = annos.collect { - case DedupGroupAnnotation(target, _) => target.module + val dedupGroupAnnos = annos.collect { case DedupGroupAnnotation(target, _) => + target.module } dedupGroupAnnos should contain theSameElementsAs Seq("ModuleWithClass") } diff --git a/src/test/scala/chiselTests/Direction.scala b/src/test/scala/chiselTests/Direction.scala index a4093bf35fa..28aadd49881 100644 --- a/src/test/scala/chiselTests/Direction.scala +++ b/src/test/scala/chiselTests/Direction.scala @@ -46,7 +46,7 @@ class TopDirectionOutput extends Module { class DirectionSpec extends ChiselPropSpec with Matchers with Utils { - //TODO: In Chisel3 these are actually FIRRTL errors. Remove from tests? + // TODO: In Chisel3 these are actually FIRRTL errors. Remove from tests? property("Outputs should be assignable") { ChiselStage.emitCHIRRTL(new GoodDirection) diff --git a/src/test/scala/chiselTests/ExtModuleImpl.scala b/src/test/scala/chiselTests/ExtModuleImpl.scala index eec1000da8a..d7da39a2edc 100644 --- a/src/test/scala/chiselTests/ExtModuleImpl.scala +++ b/src/test/scala/chiselTests/ExtModuleImpl.scala @@ -23,7 +23,7 @@ class ExtModuleAdd(n: Int) extends ExtModule with HasExtModuleInline { val out = Output(UInt(16.W)) }) - //scalastyle:off regex + // scalastyle:off regex setInline( "ExtModuleAdd.v", s""" diff --git a/src/test/scala/chiselTests/GCD.scala b/src/test/scala/chiselTests/GCD.scala index 704f4c69890..06ff57749e2 100644 --- a/src/test/scala/chiselTests/GCD.scala +++ b/src/test/scala/chiselTests/GCD.scala @@ -37,7 +37,7 @@ class GCDTester(a: Int, b: Int, z: Int) extends BasicTester { class GCDSpec extends ChiselPropSpec { - //TODO: use generators and this function to make z's + // 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) val gcds = Table( diff --git a/src/test/scala/chiselTests/Harness.scala b/src/test/scala/chiselTests/Harness.scala index c7ef7cc60be..ed43504d22a 100644 --- a/src/test/scala/chiselTests/Harness.scala +++ b/src/test/scala/chiselTests/Harness.scala @@ -6,14 +6,17 @@ import java.io.File import firrtl.util.BackendCompilationUtilities._ class HarnessSpec extends ChiselPropSpec { - def makeTrivialVerilog: (File => File) = makeHarness((prefix: String) => s""" + def makeTrivialVerilog: (File => File) = makeHarness( + (prefix: String) => s""" module ${prefix}; initial begin $$display("$prefix!"); $$finish; end endmodule -""", ".v") _ +""", + ".v" + ) _ def makeFailingVerilog: (File => File) = makeHarness( (prefix: String) => s""" diff --git a/src/test/scala/chiselTests/IllegalRefSpec.scala b/src/test/scala/chiselTests/IllegalRefSpec.scala index eac4419f59a..035bd3adec5 100644 --- a/src/test/scala/chiselTests/IllegalRefSpec.scala +++ b/src/test/scala/chiselTests/IllegalRefSpec.scala @@ -57,18 +57,17 @@ class IllegalRefSpec extends ChiselFlatSpec with Utils { val variants = Map("a connect" -> true, "an op" -> false) - variants.foreach { - case (k, v) => - s"Illegal cross-module references in ${k}" should "fail" in { - a[ChiselException] should be thrownBy extractCause[ChiselException] { - ChiselStage.emitCHIRRTL { new IllegalRefOuter(v) } - } + variants.foreach { case (k, v) => + s"Illegal cross-module references in ${k}" should "fail" in { + a[ChiselException] should be thrownBy extractCause[ChiselException] { + ChiselStage.emitCHIRRTL { 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] { - ChiselStage.emitCHIRRTL { new CrossWhenConnect(v) } - } + s"Using a signal that has escaped its enclosing when scope in ${k}" should "fail" in { + a[ChiselException] should be thrownBy extractCause[ChiselException] { + ChiselStage.emitCHIRRTL { new CrossWhenConnect(v) } } + } } } diff --git a/src/test/scala/chiselTests/IntegerMathSpec.scala b/src/test/scala/chiselTests/IntegerMathSpec.scala index 4bc1525320b..e89476bd6e2 100644 --- a/src/test/scala/chiselTests/IntegerMathSpec.scala +++ b/src/test/scala/chiselTests/IntegerMathSpec.scala @@ -7,7 +7,7 @@ import chisel3.testers.BasicTester class IntegerMathTester extends BasicTester { - //TODO: Add more operators + // TODO: Add more operators /* absolute values tests */ diff --git a/src/test/scala/chiselTests/LoadMemoryFromFileSpec.scala b/src/test/scala/chiselTests/LoadMemoryFromFileSpec.scala index 1819dfdbd41..6d0d2c065f3 100644 --- a/src/test/scala/chiselTests/LoadMemoryFromFileSpec.scala +++ b/src/test/scala/chiselTests/LoadMemoryFromFileSpec.scala @@ -43,8 +43,8 @@ class UsesThreeMemsInline( memoryDepth: Int, memoryType: Data, memoryFile: String, - hexOrBinary: MemoryLoadFileType.FileType) - extends Module { + hexOrBinary: MemoryLoadFileType.FileType +) extends Module { val io = Seq.fill(3)(IO(new Read(memoryDepth, memoryType))) val memory1 = Mem(memoryDepth, memoryType) diff --git a/src/test/scala/chiselTests/Math.scala b/src/test/scala/chiselTests/Math.scala index b83b60f60e0..57c2a8590bd 100644 --- a/src/test/scala/chiselTests/Math.scala +++ b/src/test/scala/chiselTests/Math.scala @@ -6,42 +6,40 @@ class Math extends ChiselPropSpec { import chisel3.util._ 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) - } + 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 - } - } - d shouldEqual (t) + 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) } + } } } } diff --git a/src/test/scala/chiselTests/Mem.scala b/src/test/scala/chiselTests/Mem.scala index d4164861fad..859d9e47680 100644 --- a/src/test/scala/chiselTests/Mem.scala +++ b/src/test/scala/chiselTests/Mem.scala @@ -355,7 +355,7 @@ class MemorySpec extends ChiselPropSpec { assertTesterPasses { new MemBundleTester } } - //TODO: SFC->MFC, this test is ignored because the read-under-write specifiers are not emitted to work with MFC + // TODO: SFC->MFC, this test is ignored because the read-under-write specifiers are not emitted to work with MFC ignore("SyncReadMem write collision behaviors should work") { assertTesterPasses { new SyncReadMemWriteCollisionTester } } @@ -460,58 +460,57 @@ class SRAMSpec extends ChiselFunSpec { if (numWR + numRW) > 0 } yield (numRD, numWR, numRW) - portCombos.foreach { - case (numRD, numWR, numRW) => - val portedness: String = { - val rdPorts: String = if (numRD > 0) s"${numRD}R" else "" - val wrPorts: String = if (numWR > 0) s"${numWR}W" else "" - val rwPorts: String = if (numRW > 0) s"${numRW}RW" else "" + portCombos.foreach { case (numRD, numWR, numRW) => + val portedness: String = { + val rdPorts: String = if (numRD > 0) s"${numRD}R" else "" + val wrPorts: String = if (numWR > 0) s"${numWR}W" else "" + val rwPorts: String = if (numRW > 0) s"${numRW}RW" else "" - s"$rdPorts$wrPorts$rwPorts" - } - it(s"should generate a $portedness memory") { - class TestModule(val rd: Int, val wr: Int, val rw: Int) extends Module { - val mem = SRAM(32, UInt(8.W), rd, wr, rw) - - dontTouch(mem) - - for (i <- 0 until rd) { - mem.readPorts(i) := DontCare - } - for (i <- 0 until wr) { - mem.writePorts(i) := DontCare - } - for (i <- 0 until rw) { - mem.readwritePorts(i) := DontCare - } + s"$rdPorts$wrPorts$rwPorts" + } + it(s"should generate a $portedness memory") { + class TestModule(val rd: Int, val wr: Int, val rw: Int) extends Module { + val mem = SRAM(32, UInt(8.W), rd, wr, rw) + + dontTouch(mem) + + for (i <- 0 until rd) { + mem.readPorts(i) := DontCare } - val chirrtl = ChiselStage.emitCHIRRTL(new TestModule(numRD, numWR, numRW), args = Array("--full-stacktrace")) - - // Check that the chirrtl ports actually exist and the signals - // are properly connected - for (rd <- 0 until numRD) { - chirrtl should include(s"connect mem_sram.R$rd.addr, mem.readPorts[$rd].address") - chirrtl should include(s"connect mem.readPorts[$rd].data, mem_sram.R$rd.data") - chirrtl should include(s"connect mem_sram.R$rd.en, mem.readPorts[$rd].enable") + for (i <- 0 until wr) { + mem.writePorts(i) := DontCare } - - for (wr <- 0 until numWR) { - chirrtl should include(s"connect mem_sram.W$wr.addr, mem.writePorts[$wr].address") - chirrtl should include(s"connect mem_sram.W$wr.data, mem.writePorts[$wr].data") - chirrtl should include(s"connect mem_sram.W$wr.en, mem.writePorts[$wr].enable") - chirrtl should include(s"connect mem_sram.W$wr.mask, UInt<1>(0h1)") + for (i <- 0 until rw) { + mem.readwritePorts(i) := DontCare } + } + val chirrtl = ChiselStage.emitCHIRRTL(new TestModule(numRD, numWR, numRW), args = Array("--full-stacktrace")) + + // Check that the chirrtl ports actually exist and the signals + // are properly connected + for (rd <- 0 until numRD) { + chirrtl should include(s"connect mem_sram.R$rd.addr, mem.readPorts[$rd].address") + chirrtl should include(s"connect mem.readPorts[$rd].data, mem_sram.R$rd.data") + chirrtl should include(s"connect mem_sram.R$rd.en, mem.readPorts[$rd].enable") + } - for (rw <- 0 until numRW) { - chirrtl should include(s"connect mem_sram.RW$rw.addr, mem.readwritePorts[$rw].address") - chirrtl should include(s"connect mem_sram.RW$rw.en, mem.readwritePorts[$rw].enable") - chirrtl should include(s"connect mem.readwritePorts[$rw].readData, mem_sram.RW$rw.rdata") - chirrtl should include(s"connect mem_sram.RW$rw.wdata, mem.readwritePorts[$rw].writeData") - chirrtl should include(s"connect mem_sram.RW$rw.wmode, mem.readwritePorts[$rw].isWrite") - chirrtl should include(s"connect mem_sram.RW$rw.wmask, UInt<1>(0h1)") + for (wr <- 0 until numWR) { + chirrtl should include(s"connect mem_sram.W$wr.addr, mem.writePorts[$wr].address") + chirrtl should include(s"connect mem_sram.W$wr.data, mem.writePorts[$wr].data") + chirrtl should include(s"connect mem_sram.W$wr.en, mem.writePorts[$wr].enable") + chirrtl should include(s"connect mem_sram.W$wr.mask, UInt<1>(0h1)") + } + + for (rw <- 0 until numRW) { + chirrtl should include(s"connect mem_sram.RW$rw.addr, mem.readwritePorts[$rw].address") + chirrtl should include(s"connect mem_sram.RW$rw.en, mem.readwritePorts[$rw].enable") + chirrtl should include(s"connect mem.readwritePorts[$rw].readData, mem_sram.RW$rw.rdata") + chirrtl should include(s"connect mem_sram.RW$rw.wdata, mem.readwritePorts[$rw].writeData") + chirrtl should include(s"connect mem_sram.RW$rw.wmode, mem.readwritePorts[$rw].isWrite") + chirrtl should include(s"connect mem_sram.RW$rw.wmask, UInt<1>(0h1)") - } } + } } it(s"should support masking with Vec-valued data") { diff --git a/src/test/scala/chiselTests/ModulePrefixSpec.scala b/src/test/scala/chiselTests/ModulePrefixSpec.scala index e4a61374bf0..75df6e9fc2e 100644 --- a/src/test/scala/chiselTests/ModulePrefixSpec.scala +++ b/src/test/scala/chiselTests/ModulePrefixSpec.scala @@ -441,8 +441,8 @@ class ModulePrefixSpec extends ChiselFlatSpec with ChiselRunners with Utils with val bar = Module(new Bar) } val (_, annos) = getFirrtlAndAnnos(new Top) - val dedupGroups = annos.collect { - case DedupGroupAnnotation(target, group) => target.module -> group + val dedupGroups = annos.collect { case DedupGroupAnnotation(target, group) => + target.module -> group } dedupGroups should be(Seq("Outer_Inner_Foo" -> "Outer_Inner_Foo", "Outer_Bar" -> "Outer_Bar", "Top" -> "Top")) } diff --git a/src/test/scala/chiselTests/MuxSpec.scala b/src/test/scala/chiselTests/MuxSpec.scala index af93c133864..97f6286e1d7 100644 --- a/src/test/scala/chiselTests/MuxSpec.scala +++ b/src/test/scala/chiselTests/MuxSpec.scala @@ -55,9 +55,8 @@ class MuxLookupEnumTester extends BasicTester { val b = Value(7.U) val c = Value } - val mapping = TestEnum.all.zipWithIndex.map { - case (e, i) => - e -> i.U + val mapping = TestEnum.all.zipWithIndex.map { case (e, i) => + e -> i.U } assert(MuxLookup(TestEnum.a, 3.U)(mapping) === 0.U) assert(MuxLookup(TestEnum.b, 3.U)(mapping) === 1.U) diff --git a/src/test/scala/chiselTests/PrintableSpec.scala b/src/test/scala/chiselTests/PrintableSpec.scala index 505d4287489..8a507f30b30 100644 --- a/src/test/scala/chiselTests/PrintableSpec.scala +++ b/src/test/scala/chiselTests/PrintableSpec.scala @@ -25,10 +25,9 @@ class PrintableSpec extends AnyFlatSpec with Matchers with Utils { case _ => fail(s"Regex to process Printf should work on $str!") } } - firrtl.split("\n").toIndexedSeq.collect { - case PrintfRegex(matched) => - val (str, args) = processBody(matched) - Printf(str, args) + firrtl.split("\n").toIndexedSeq.collect { case PrintfRegex(matched) => + val (str, args) = processBody(matched) + Printf(str, args) } } @@ -50,16 +49,14 @@ class PrintableSpec extends AnyFlatSpec with Matchers with Utils { class MyModule extends BasicTester { printf(p"An exact string") } - generateAndCheck(new MyModule) { - case Seq(Printf("An exact string", Seq())) => + generateAndCheck(new MyModule) { case Seq(Printf("An exact string", Seq())) => } } it should "handle Printable and String concatenation" in { class MyModule extends BasicTester { printf(p"First " + PString("Second ") + "Third") } - generateAndCheck(new MyModule) { - case Seq(Printf("First Second Third", Seq())) => + generateAndCheck(new MyModule) { case Seq(Printf("First Second Third", Seq())) => } } it should "call toString on non-Printable objects" in { @@ -67,8 +64,7 @@ class PrintableSpec extends AnyFlatSpec with Matchers with Utils { val myInt = 1234 printf(p"myInt = $myInt") } - generateAndCheck(new MyModule) { - case Seq(Printf("myInt = 1234", Seq())) => + generateAndCheck(new MyModule) { case Seq(Printf("myInt = 1234", Seq())) => } } it should "generate proper printf for simple Decimal printing" in { @@ -76,33 +72,29 @@ class PrintableSpec extends AnyFlatSpec with Matchers with Utils { val myWire = WireDefault(1234.U) printf(p"myWire = ${Decimal(myWire)}") } - generateAndCheck(new MyModule) { - case Seq(Printf("myWire = %d", Seq("myWire"))) => + generateAndCheck(new MyModule) { case Seq(Printf("myWire = %d", Seq("myWire"))) => } } it should "handle printing literals" in { class MyModule extends BasicTester { printf(Decimal(10.U(32.W))) } - generateAndCheck(new MyModule) { - case Seq(Printf("%d", Seq(lit))) => - assert(lit contains "UInt<32>") + generateAndCheck(new MyModule) { case Seq(Printf("%d", Seq(lit))) => + assert(lit contains "UInt<32>") } } it should "correctly escape percent" in { class MyModule extends BasicTester { printf(p"%") } - generateAndCheck(new MyModule) { - case Seq(Printf("%%", Seq())) => + generateAndCheck(new MyModule) { case Seq(Printf("%%", Seq())) => } } it should "correctly emit tab" in { class MyModule extends BasicTester { printf(p"\t") } - generateAndCheck(new MyModule) { - case Seq(Printf("\\t", Seq())) => + generateAndCheck(new MyModule) { case Seq(Printf("\\t", Seq())) => } } it should "support names of circuit elements including submodule IO" in { @@ -138,8 +130,7 @@ class PrintableSpec extends AnyFlatSpec with Matchers with Utils { val myInst = Module(new MySubModule) printf(p"${myInst.io.fizz}") } - generateAndCheck(new MyModule) { - case Seq(Printf("%d", Seq("myInst.io.fizz"))) => + generateAndCheck(new MyModule) { case Seq(Printf("%d", Seq("myInst.io.fizz"))) => } } it should "print UInts and SInts as Decimal by default" in { @@ -148,8 +139,7 @@ class PrintableSpec extends AnyFlatSpec with Matchers with Utils { val mySInt = WireDefault(-1.S) printf(p"$myUInt & $mySInt") } - generateAndCheck(new MyModule) { - case Seq(Printf("%d & %d", Seq("myUInt", "mySInt"))) => + generateAndCheck(new MyModule) { case Seq(Printf("%d & %d", Seq("myUInt", "mySInt"))) => } } it should "print Vecs like Scala Seqs by default" in { @@ -186,8 +176,7 @@ class PrintableSpec extends AnyFlatSpec with Matchers with Utils { myBun.`a-x` := 0.U printf(p"$myBun") } - generateAndCheck(new MyModule) { - case Seq(Printf("UnsanitaryBundle(aminusx -> %d)", Seq("myBun.aminusx"))) => + generateAndCheck(new MyModule) { case Seq(Printf("UnsanitaryBundle(aminusx -> %d)", Seq("myBun.aminusx"))) => } } @@ -226,8 +215,7 @@ class PrintableSpec extends AnyFlatSpec with Matchers with Utils { w1.bar := 10.U printf(cf"w1 = $w1") } - generateAndCheck(new MyModule) { - case Seq(Printf("w1 = Bundle : Foo : %x Bar : %x", Seq("w1.foo", "w1.bar"))) => + generateAndCheck(new MyModule) { case Seq(Printf("w1 = Bundle : Foo : %x Bar : %x", Seq("w1.foo", "w1.bar"))) => } } @@ -272,9 +260,8 @@ class PrintableSpec extends AnyFlatSpec with Matchers with Utils { printf(cf"%% $b1%x%%$b2%b = ${b1 % b2}%d %%%% Tail String") } - generateAndCheck(new MyModule) { - case Seq(Printf("%% %x%%%b = %d %%%% Tail String", Seq(lita, litb, _))) => - assert(lita.contains("UInt<4>") && litb.contains("UInt<5>")) + generateAndCheck(new MyModule) { case Seq(Printf("%% %x%%%b = %d %%%% Tail String", Seq(lita, litb, _))) => + assert(lita.contains("UInt<4>") && litb.contains("UInt<5>")) } } @@ -327,8 +314,7 @@ class PrintableSpec extends AnyFlatSpec with Matchers with Utils { class MyModule extends BasicTester { printf(Printable.pack("\\ \\]")) } - generateAndCheck(new MyModule) { - case Seq(Printf("\\\\ \\\\]", Seq())) => + generateAndCheck(new MyModule) { case Seq(Printf("\\\\ \\\\]", Seq())) => } } } diff --git a/src/test/scala/chiselTests/RecordSpec.scala b/src/test/scala/chiselTests/RecordSpec.scala index 8a9c00e8ce1..da92ef79807 100644 --- a/src/test/scala/chiselTests/RecordSpec.scala +++ b/src/test/scala/chiselTests/RecordSpec.scala @@ -211,9 +211,8 @@ class RecordSpec extends ChiselFlatSpec with Utils { "Bundle types which couldn't be cloned by the plugin" should "throw an error" in { class CustomBundleBroken(elts: (String, Data)*) extends Record { - val elements = ListMap(elts.map { - case (field, elt) => - field -> elt + val elements = ListMap(elts.map { case (field, elt) => + field -> elt }: _*) def apply(elt: String): Data = elements(elt) } diff --git a/src/test/scala/chiselTests/Reg.scala b/src/test/scala/chiselTests/Reg.scala index 69f34ff43ea..731de86e8a3 100644 --- a/src/test/scala/chiselTests/Reg.scala +++ b/src/test/scala/chiselTests/Reg.scala @@ -76,9 +76,8 @@ 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() } diff --git a/src/test/scala/chiselTests/SIntOps.scala b/src/test/scala/chiselTests/SIntOps.scala index 0263e0fc296..fa9615a6713 100644 --- a/src/test/scala/chiselTests/SIntOps.scala +++ b/src/test/scala/chiselTests/SIntOps.scala @@ -32,11 +32,11 @@ class SIntOps extends Module { io.addout := a +% b io.subout := a -% b // TODO: - //io.timesout := (a * b)(15, 0) - //io.divout := a / Mux(b === 0.S, 1.S, b) - //io.divout := (a / b)(15, 0) - //io.modout := 0.S - //io.lshiftout := (a << 12)(15, 0) // (a << ub(3, 0))(15, 0).toSInt + // io.timesout := (a * b)(15, 0) + // io.divout := a / Mux(b === 0.S, 1.S, b) + // io.divout := (a / b)(15, 0) + // io.modout := 0.S + // io.lshiftout := (a << 12)(15, 0) // (a << ub(3, 0))(15, 0).toSInt io.rshiftout := (a >> 8) // (a >> ub).toSInt io.lessout := a < b io.greatout := a > b diff --git a/src/test/scala/chiselTests/Tbl.scala b/src/test/scala/chiselTests/Tbl.scala index 5e127770dd5..e132c9d66e1 100644 --- a/src/test/scala/chiselTests/Tbl.scala +++ b/src/test/scala/chiselTests/Tbl.scala @@ -33,7 +33,7 @@ class TblTester(w: Int, n: Int, idxs: List[Int], values: List[Int]) extends Basi val prev_value = vvalues(cnt - 1.U) dut.io.wi := vidxs(cnt) dut.io.ri := prev_idx - dut.io.we := true.B //TODO enSequence + dut.io.we := true.B // TODO enSequence dut.io.d := vvalues(cnt) when(cnt > 0.U) { when(prev_idx === vidxs(cnt)) { @@ -49,14 +49,13 @@ 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 c3cc232fb0e..f2560fbca5b 100644 --- a/src/test/scala/chiselTests/TesterDriverSpec.scala +++ b/src/test/scala/chiselTests/TesterDriverSpec.scala @@ -37,8 +37,8 @@ class FinishTester extends BasicTester { class TesterDriverSpec extends ChiselFlatSpec { "TesterDriver calls BasicTester's finish method which" should "allow modifications of test circuit after the tester's constructor is done" in { - assertTesterPasses { - new FinishTester + assertTesterPasses { + new FinishTester + } } - } } diff --git a/src/test/scala/chiselTests/UIntOps.scala b/src/test/scala/chiselTests/UIntOps.scala index db7ff30de78..392b358dc13 100644 --- a/src/test/scala/chiselTests/UIntOps.scala +++ b/src/test/scala/chiselTests/UIntOps.scala @@ -214,16 +214,13 @@ class UIntLitZeroWidthTester extends BasicTester { trait ShiftRightWidthBehavior { self: ChiselRunners => // The UInt and SInt objects don't share a type, so make one up that they can conform to structurally type BitsFactory[T <: Bits] = { - def apply(): T + def apply(): T def apply(w: Width): T } def testShiftRightWidthBehavior[T <: Bits]( - factory: BitsFactory[T] - )(chiselMinWidth: Int, - firrtlMinWidth: Int, - args: Iterable[String] = Nil - ): Unit = { + factory: BitsFactory[T] + )(chiselMinWidth: Int, firrtlMinWidth: Int, args: Iterable[String] = Nil): Unit = { assertKnownWidth(4, args) { val in = IO(Input(factory(8.W))) in >> 4 @@ -498,9 +495,8 @@ class UIntOpsSpec extends ChiselPropSpec with Matchers with Utils with ShiftRigh Seq( grabLog(ChiselStage.emitCHIRRTL(new TooWide)), grabLog(ChiselStage.emitCHIRRTL(new TooNarrow)) - ).foreach { - case (log, _) => - log should include("warn") + ).foreach { case (log, _) => + log should include("warn") } a[ChiselException] should be thrownBy extractCause[ChiselException] { @@ -531,9 +527,8 @@ class UIntOpsSpec extends ChiselPropSpec with Matchers with Utils with ShiftRigh Seq( grabLog(ChiselStage.emitCHIRRTL(new Ok)) - ).foreach { - case (log, _) => - log should be("") + ).foreach { case (log, _) => + log should be("") } } diff --git a/src/test/scala/chiselTests/VecLiteralSpec.scala b/src/test/scala/chiselTests/VecLiteralSpec.scala index a125bbee842..9707a21aeea 100644 --- a/src/test/scala/chiselTests/VecLiteralSpec.scala +++ b/src/test/scala/chiselTests/VecLiteralSpec.scala @@ -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 + // 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 y = RegInit(initValue) @@ -86,7 +86,7 @@ class VecLiteralSpec extends ChiselFreeSpec with Utils { firrtl should include("""regreset y : UInt<8>[4], clock, reset, _y_WIRE""".stripMargin) } - //NOTE: I had problems where this would not work if this class declaration was inside test scope + // 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 y = RegInit(initValue) diff --git a/src/test/scala/chiselTests/VectorPacketIO.scala b/src/test/scala/chiselTests/VectorPacketIO.scala index 1474177f66c..f116ebee162 100644 --- a/src/test/scala/chiselTests/VectorPacketIO.scala +++ b/src/test/scala/chiselTests/VectorPacketIO.scala @@ -64,8 +64,8 @@ class VectorPacketIOUnitTester extends BasicTester { class VectorPacketIOUnitTesterSpec extends ChiselFlatSpec { "a circuit using an io containing a vector of EnqIO wrapped packets" should "compile and run" in { - assertTesterPasses { - new VectorPacketIOUnitTester + assertTesterPasses { + new VectorPacketIOUnitTester + } } - } } diff --git a/src/test/scala/chiselTests/WidthSpec.scala b/src/test/scala/chiselTests/WidthSpec.scala index ffdaa3e6570..cd945876401 100644 --- a/src/test/scala/chiselTests/WidthSpec.scala +++ b/src/test/scala/chiselTests/WidthSpec.scala @@ -45,7 +45,7 @@ class WidthSpec extends ChiselFlatSpec { } abstract class WireRegWidthSpecImpl extends ChiselFlatSpec { - def name: String + def name: String def builder[T <: Data](x: T): T behavior.of(name) @@ -118,17 +118,17 @@ abstract class WireRegWidthSpecImpl extends ChiselFlatSpec { } class WireWidthSpec extends WireRegWidthSpecImpl { - def name: String = "Wire" + def name: String = "Wire" def builder[T <: Data](x: T): T = Wire(x) } class RegWidthSpec extends WireRegWidthSpecImpl { - def name: String = "Reg" + def name: String = "Reg" def builder[T <: Data](x: T): T = Reg(x) } abstract class WireDefaultRegInitSpecImpl extends ChiselFlatSpec { - def name: String - def builder1[T <: Data](x: T): T + def name: String + def builder1[T <: Data](x: T): T def builder2[T <: Data](x: T, y: T): T behavior.of(s"$name (Single Argument)") @@ -235,13 +235,13 @@ abstract class WireDefaultRegInitSpecImpl extends ChiselFlatSpec { } class WireDefaultWidthSpec extends WireDefaultRegInitSpecImpl { - def name: String = "WireDefault" - def builder1[T <: Data](x: T): T = WireDefault(x) + def name: String = "WireDefault" + def builder1[T <: Data](x: T): T = WireDefault(x) def builder2[T <: Data](x: T, y: T): T = WireDefault(x, y) } class RegInitWidthSpec extends WireDefaultRegInitSpecImpl { - def name: String = "RegInit" - def builder1[T <: Data](x: T): T = RegInit(x) + def name: String = "RegInit" + def builder1[T <: Data](x: T): T = RegInit(x) def builder2[T <: Data](x: T, y: T): T = RegInit(x, y) } diff --git a/src/test/scala/chiselTests/experimental/CIRCTSRAMInterfaceSpec.scala b/src/test/scala/chiselTests/experimental/CIRCTSRAMInterfaceSpec.scala index e4a0049d357..d55b631ca40 100644 --- a/src/test/scala/chiselTests/experimental/CIRCTSRAMInterfaceSpec.scala +++ b/src/test/scala/chiselTests/experimental/CIRCTSRAMInterfaceSpec.scala @@ -17,14 +17,14 @@ class CIRCTSRAMInterfaceSpec extends ChiselFlatSpec { class GenerateSRAMModule extends Module { val sram = SRAM.masked(depth, Vec(width / maskGranularity, UInt(maskGranularity.W)), rd, wr, rw) - val ioR = IO(chiselTypeOf(sram.readPorts)).tap(_.zip(sram.readPorts).foreach { - case (io, mem) => io <> mem + val ioR = IO(chiselTypeOf(sram.readPorts)).tap(_.zip(sram.readPorts).foreach { case (io, mem) => + io <> mem }) - val ioRW = IO(chiselTypeOf(sram.readwritePorts)).tap(_.zip(sram.readwritePorts).foreach { - case (io, mem) => io <> mem + val ioRW = IO(chiselTypeOf(sram.readwritePorts)).tap(_.zip(sram.readwritePorts).foreach { case (io, mem) => + io <> mem }) - val ioW = IO(chiselTypeOf(sram.writePorts)).tap(_.zip(sram.writePorts).foreach { - case (io, mem) => io <> mem + val ioW = IO(chiselTypeOf(sram.writePorts)).tap(_.zip(sram.writePorts).foreach { case (io, mem) => + io <> mem }) } diff --git a/src/test/scala/chiselTests/experimental/ForceNames.scala b/src/test/scala/chiselTests/experimental/ForceNames.scala index bba469fc21b..9854a187ad3 100644 --- a/src/test/scala/chiselTests/experimental/ForceNames.scala +++ b/src/test/scala/chiselTests/experimental/ForceNames.scala @@ -52,8 +52,8 @@ class ForceNamesSpec extends ChiselFlatSpec { ) ++ inputAnnos val ret = stage.execute(Array("--target", "systemverilog"), annos) - val verilog = ret.collectFirst { - case e: EmittedVerilogCircuitAnnotation => e.value.value + val verilog = ret.collectFirst { case e: EmittedVerilogCircuitAnnotation => + e.value.value }.get verilog.split("\\\n") diff --git a/src/test/scala/chiselTests/experimental/TraceSpec.scala b/src/test/scala/chiselTests/experimental/TraceSpec.scala index 619720a2bb9..79d986356d2 100644 --- a/src/test/scala/chiselTests/experimental/TraceSpec.scala +++ b/src/test/scala/chiselTests/experimental/TraceSpec.scala @@ -93,17 +93,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}""" + case Ref(r) => r + }.get}""" } s""" |#include "V${topName}.h" diff --git a/src/test/scala/chiselTests/experimental/hierarchy/Annotations.scala b/src/test/scala/chiselTests/experimental/hierarchy/Annotations.scala index c6daf6a9692..4e4e3b83ab7 100644 --- a/src/test/scala/chiselTests/experimental/hierarchy/Annotations.scala +++ b/src/test/scala/chiselTests/experimental/hierarchy/Annotations.scala @@ -28,10 +28,10 @@ private[hierarchy] object Annotations { 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[T <: Data](d: MemBase[T], tag: String): Unit = annotate(MarkChiselMemAnnotation(d, tag, false)) - def mark(d: HasTarget, tag: String): Unit = annotate(MarkChiselHasTargetAnnotation(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[T <: Data](d: MemBase[T], tag: String): Unit = annotate(MarkChiselMemAnnotation(d, tag, false)) + def mark(d: HasTarget, tag: String): Unit = annotate(MarkChiselHasTargetAnnotation(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 9881edaa82e..39418eab602 100644 --- a/src/test/scala/chiselTests/experimental/hierarchy/DefinitionSpec.scala +++ b/src/test/scala/chiselTests/experimental/hierarchy/DefinitionSpec.scala @@ -24,8 +24,8 @@ class DefinitionSpec extends ChiselFunSpec with Utils { it("(0.b): accessing internal fields through non-generated means is hard to do") { class Top extends Module { val definition = Definition(new AddOne) - //definition.lookup(_.in) // Uncommenting this line will give the following error: - //"You are trying to access a macro-only API. Please use the @public annotation instead." + // definition.lookup(_.in) // Uncommenting this line will give the following error: + // "You are trying to access a macro-only API. Please use the @public annotation instead." definition.in } val (chirrtl, _) = getFirrtlAndAnnos(new Top) @@ -347,7 +347,7 @@ class DefinitionSpec extends ChiselFunSpec with Utils { ignore("(3.j): should work on vals in constructor arguments") { class Top() extends Module { val i = Definition(new HasPublicConstructorArgs(10)) - //mark(i.x, i.int.toString) + // mark(i.x, i.int.toString) } val (_, annos) = getFirrtlAndAnnos(new Top) annos should contain(MarkAnnotation("~Top|HasPublicConstructorArgs>x".rt, "10")) diff --git a/src/test/scala/chiselTests/experimental/hierarchy/InstanceSpec.scala b/src/test/scala/chiselTests/experimental/hierarchy/InstanceSpec.scala index 0f6ebf00b3b..da9c82f68a6 100644 --- a/src/test/scala/chiselTests/experimental/hierarchy/InstanceSpec.scala +++ b/src/test/scala/chiselTests/experimental/hierarchy/InstanceSpec.scala @@ -39,8 +39,8 @@ class InstanceSpec extends ChiselFunSpec with Utils { class Top extends Module { val definition = Definition(new AddOne) val i0 = Instance(definition) - //i0.lookup(_.in) // Uncommenting this line will give the following error: - //"You are trying to access a macro-only API. Please use the @public annotation instead." + // i0.lookup(_.in) // Uncommenting this line will give the following error: + // "You are trying to access a macro-only API. Please use the @public annotation instead." i0.in } val chirrtl = circt.stage.ChiselStage.emitCHIRRTL(new Top) @@ -407,7 +407,7 @@ class InstanceSpec extends ChiselFunSpec with Utils { ignore("(3.k): should work on vals in constructor arguments") { class Top() extends Module { val i = Instance(Definition(new HasPublicConstructorArgs(10))) - //mark(i.x, i.int.toString) + // mark(i.x, i.int.toString) } val (_, annos) = getFirrtlAndAnnos(new Top) annos.collect { case c: MarkAnnotation => c } should contain( @@ -448,9 +448,9 @@ class InstanceSpec extends ChiselFunSpec with Utils { } @instantiable class SubClass() extends SupClass with SupTrait { // This errors - //@public private val privateVal = 10 + // @public private val privateVal = 10 // This errors - //@public protected val protectedVal = 10 + // @public protected val protectedVal = 10 @public override val overriddenVal = 12 @public final val finalVal = 12 @public lazy val lazyValue = 12 @@ -528,7 +528,7 @@ class InstanceSpec extends ChiselFunSpec with Utils { } def f(i: Instance[AddOne]): Unit = mark(i.innerWire, "blah") val (_, annos) = getFirrtlAndAnnos(new Top) - //TODO: Should this be ~Top|Top/i:AddOne>innerWire ??? + // TODO: Should this be ~Top|Top/i:AddOne>innerWire ??? annos.collect { case c: MarkAnnotation => c } should contain(MarkAnnotation("~Top|AddOne>innerWire".rt, "blah")) } it("(4.b): should work on IsInstantiable") { @@ -550,7 +550,7 @@ class InstanceSpec extends ChiselFunSpec with Utils { } def f(i: Seq[Instance[AddTwo]]): Data = i.head.i0.innerWire val (c, annos) = getFirrtlAndAnnos(new Top) - //TODO: Should this be ~Top|Top... ?? + // TODO: Should this be ~Top|Top... ?? annos.collect { case c: MarkAnnotation => c } should contain( MarkAnnotation("~Top|AddTwo/i0:AddOne>innerWire".rt, "blah") ) diff --git a/src/test/scala/chiselTests/experimental/hierarchy/SeparateElaborationSpec.scala b/src/test/scala/chiselTests/experimental/hierarchy/SeparateElaborationSpec.scala index 455c2999980..4e8e26cc8d0 100644 --- a/src/test/scala/chiselTests/experimental/hierarchy/SeparateElaborationSpec.scala +++ b/src/test/scala/chiselTests/experimental/hierarchy/SeparateElaborationSpec.scala @@ -24,7 +24,7 @@ class SeparateElaborationSpec extends ChiselFunSpec with Utils { private def getDesignAnnotation[T <: RawModule](annos: AnnotationSeq): DesignAnnotation[T] = { val designAnnos = annos.flatMap { a => a match { - case a: DesignAnnotation[T] => Some(a) //TODO: cleanup, T is necessary to make type of designAnnos right + case a: DesignAnnotation[T] => Some(a) // TODO: cleanup, T is necessary to make type of designAnnos right case _ => None } } diff --git a/src/test/scala/chiselTests/interface/Drivers.scala b/src/test/scala/chiselTests/interface/Drivers.scala index beaccaf79a6..138b8aca04b 100644 --- a/src/test/scala/chiselTests/interface/Drivers.scala +++ b/src/test/scala/chiselTests/interface/Drivers.scala @@ -16,7 +16,8 @@ object Drivers { case class CompilationUnit( generator: () => RawModule, args: Array[String] = Array.empty, - annotations: AnnotationSeq = Seq.empty) + annotations: AnnotationSeq = Seq.empty + ) /** Compile one or more Chisel Modules into an output directory. The first * compile will be put into the output directory. All subsequent compiles @@ -28,25 +29,24 @@ object Drivers { main: CompilationUnit, other: CompilationUnit* ) = { - (main +: other).zipWithIndex.foreach { - case (CompilationUnit(generator, args, annotations), i) => - stage.execute( - Array( - "--target", - "systemverilog", - "--target-dir", - dir.getPath() + "/firrtl" - ) ++ args, - Seq( - ChiselGeneratorAnnotation(generator), - FirtoolOption("-split-verilog"), - FirtoolOption("-o"), - FirtoolOption(dir.getPath() + s"/compile-$i"), - FirtoolOption("-disable-annotation-unknown"), - FirtoolOption("-disable-all-randomization"), - FirtoolOption("-strip-debug-info") - ) ++ annotations - ) + (main +: other).zipWithIndex.foreach { case (CompilationUnit(generator, args, annotations), i) => + stage.execute( + Array( + "--target", + "systemverilog", + "--target-dir", + dir.getPath() + "/firrtl" + ) ++ args, + Seq( + ChiselGeneratorAnnotation(generator), + FirtoolOption("-split-verilog"), + FirtoolOption("-o"), + FirtoolOption(dir.getPath() + s"/compile-$i"), + FirtoolOption("-disable-annotation-unknown"), + FirtoolOption("-disable-all-randomization"), + FirtoolOption("-strip-debug-info") + ) ++ annotations + ) } } @@ -65,11 +65,10 @@ object Drivers { .map(dir => s"-I${dir.getPath()}") /** Find any reference definition files, which need to be parsed by Verilator first */ - val refDefinitionFiles = includeDirs.flatMap { - case f => - f.listFiles().collect { - case f if f.getName().startsWith("ref_") => f.getPath() - } + val refDefinitionFiles = includeDirs.flatMap { case f => + f.listFiles().collect { + case f if f.getName().startsWith("ref_") => f.getPath() + } } val cmd: Seq[String] = Seq( diff --git a/src/test/scala/chiselTests/simulator/LayerControlSpec.scala b/src/test/scala/chiselTests/simulator/LayerControlSpec.scala index 616e49db373..981bfd341c1 100644 --- a/src/test/scala/chiselTests/simulator/LayerControlSpec.scala +++ b/src/test/scala/chiselTests/simulator/LayerControlSpec.scala @@ -31,10 +31,9 @@ class LayerControlSpec extends AnyFunSpec with Matchers { info("non-layer files are ignored") layerControl.shouldIncludeFile(elaboratedModule).isDefinedAt(new File("Foo.sv")) should be(false) - Seq("layers-Foo-A.sv", "layers-Foo-B.sv", "layers-Foo-B-C.sv").map(new File(_)).foreach { - case filename => - info(s"$filename is included") - layerControl.shouldIncludeFile(elaboratedModule)(filename) should be(true) + Seq("layers-Foo-A.sv", "layers-Foo-B.sv", "layers-Foo-B-C.sv").map(new File(_)).foreach { case filename => + info(s"$filename is included") + layerControl.shouldIncludeFile(elaboratedModule)(filename) should be(true) } } } @@ -45,10 +44,9 @@ class LayerControlSpec extends AnyFunSpec with Matchers { info("non-layer files are ignored") layerControl.shouldIncludeFile(elaboratedModule).isDefinedAt(new File("Foo.sv")) should be(false) - Seq("layers-Foo-A.sv", "layers-Foo-B.sv", "layers-Foo-B-C.sv").map(new File(_)).foreach { - case filename => - info(s"$filename is excluded") - layerControl.shouldIncludeFile(elaboratedModule)(filename) should be(false) + Seq("layers-Foo-A.sv", "layers-Foo-B.sv", "layers-Foo-B-C.sv").map(new File(_)).foreach { case filename => + info(s"$filename is excluded") + layerControl.shouldIncludeFile(elaboratedModule)(filename) should be(false) } } } @@ -59,10 +57,9 @@ class LayerControlSpec extends AnyFunSpec with Matchers { info("non-layer files are ignored") layerControl.shouldIncludeFile(elaboratedModule).isDefinedAt(new File("Foo.sv")) should be(false) - Seq("layers-Foo-A.sv", "layers-Foo-B.sv", "layers-Foo-B-C.sv").map(new File(_)).foreach { - case filename => - info(s"$filename is excluded") - layerControl.shouldIncludeFile(elaboratedModule)(filename) should be(false) + Seq("layers-Foo-A.sv", "layers-Foo-B.sv", "layers-Foo-B-C.sv").map(new File(_)).foreach { case filename => + info(s"$filename is excluded") + layerControl.shouldIncludeFile(elaboratedModule)(filename) should be(false) } } } @@ -73,10 +70,9 @@ class LayerControlSpec extends AnyFunSpec with Matchers { info("non-layer files are ignored") layerControl.shouldIncludeFile(elaboratedModule).isDefinedAt(new File("foo")) should be(false) - Seq("layers-Foo-A.sv", "layers-Foo-B-C.sv").map(new File(_)).foreach { - case filename => - info(s"$filename is included") - layerControl.shouldIncludeFile(elaboratedModule)(filename) should be(true) + Seq("layers-Foo-A.sv", "layers-Foo-B-C.sv").map(new File(_)).foreach { case filename => + info(s"$filename is included") + layerControl.shouldIncludeFile(elaboratedModule)(filename) should be(true) } info("layers-Foo-A-B.sv is excluded") diff --git a/src/test/scala/chiselTests/util/SRAMSpec.scala b/src/test/scala/chiselTests/util/SRAMSpec.scala index 59e845a696d..2b63c0f9d06 100644 --- a/src/test/scala/chiselTests/util/SRAMSpec.scala +++ b/src/test/scala/chiselTests/util/SRAMSpec.scala @@ -258,14 +258,14 @@ class SRAMSpec extends ChiselFlatSpec { class Top extends Module { val sram = SRAM.masked(depth, Vec(width / maskGranularity, UInt(maskGranularity.W)), rd, wr, rw) - val ioR = IO(chiselTypeOf(sram.readPorts)).tap(_.zip(sram.readPorts).foreach { - case (io, mem) => io <> mem + val ioR = IO(chiselTypeOf(sram.readPorts)).tap(_.zip(sram.readPorts).foreach { case (io, mem) => + io <> mem }) - val ioRW = IO(chiselTypeOf(sram.readwritePorts)).tap(_.zip(sram.readwritePorts).foreach { - case (io, mem) => io <> mem + val ioRW = IO(chiselTypeOf(sram.readwritePorts)).tap(_.zip(sram.readwritePorts).foreach { case (io, mem) => + io <> mem }) - val ioW = IO(chiselTypeOf(sram.writePorts)).tap(_.zip(sram.writePorts).foreach { - case (io, mem) => io <> mem + val ioW = IO(chiselTypeOf(sram.writePorts)).tap(_.zip(sram.writePorts).foreach { case (io, mem) => + io <> mem }) } diff --git a/src/test/scala/circtTests/stage/ChiselStageSpec.scala b/src/test/scala/circtTests/stage/ChiselStageSpec.scala index c557a97aff5..f57d81dc210 100644 --- a/src/test/scala/circtTests/stage/ChiselStageSpec.scala +++ b/src/test/scala/circtTests/stage/ChiselStageSpec.scala @@ -286,8 +286,8 @@ class ChiselStageSpec extends AnyFunSpec with Matchers with chiselTests.Utils { FirtoolOption("--lowering-options=disallowPackedArrays") ) ) - .collectFirst { - case EmittedVerilogCircuitAnnotation(a) => a + .collectFirst { case EmittedVerilogCircuitAnnotation(a) => + a } .get .value should include("case") @@ -309,8 +309,8 @@ class ChiselStageSpec extends AnyFunSpec with Matchers with chiselTests.Utils { args, Seq(ChiselGeneratorAnnotation(() => new ChiselStageSpec.Baz), PreserveAggregate(PreserveAggregate.All)) ) - .collectFirst { - case EmittedVerilogCircuitAnnotation(a) => a + .collectFirst { case EmittedVerilogCircuitAnnotation(a) => + a } .get .value should include("struct") @@ -435,8 +435,8 @@ class ChiselStageSpec extends AnyFunSpec with Matchers with chiselTests.Utils { args, Seq(ChiselGeneratorAnnotation(() => new ChiselStageSpec.Bar)) ) - .collectFirst { - case EmittedVerilogCircuitAnnotation(a) => a + .collectFirst { case EmittedVerilogCircuitAnnotation(a) => + a } .get .value should not).include("ChiselStageSpec.scala") @@ -743,8 +743,8 @@ class ChiselStageSpec extends AnyFunSpec with Matchers with chiselTests.Utils { ((new ChiselStage) .execute(args, Seq(ChiselGeneratorAnnotation(() => new Foo))) - .collectFirst { - case EmittedVerilogCircuitAnnotation(a) => a + .collectFirst { case EmittedVerilogCircuitAnnotation(a) => + a } .get .value should not).include("module Bar") @@ -787,8 +787,8 @@ class ChiselStageSpec extends AnyFunSpec with Matchers with chiselTests.Utils { val verilog = (new ChiselStage) .execute(args, Seq(ChiselGeneratorAnnotation(() => new Foo))) - .collectFirst { - case EmittedVerilogCircuitAnnotation(a) => a + .collectFirst { case EmittedVerilogCircuitAnnotation(a) => + a } .get .value @@ -895,8 +895,8 @@ class ChiselStageSpec extends AnyFunSpec with Matchers with chiselTests.Utils { val verilog = (new ChiselStage) .execute(args, Seq(ChiselGeneratorAnnotation(() => new Foo))) - .collectFirst { - case EmittedVerilogCircuitAnnotation(a) => a + .collectFirst { case EmittedVerilogCircuitAnnotation(a) => + a } .get .value @@ -949,8 +949,8 @@ class ChiselStageSpec extends AnyFunSpec with Matchers with chiselTests.Utils { val verilog: String = (new ChiselStage) .execute(args, Seq(ChiselGeneratorAnnotation(() => new Foo))) - .collectFirst { - case EmittedVerilogCircuitAnnotation(a) => a + .collectFirst { case EmittedVerilogCircuitAnnotation(a) => + a } .get .value @@ -1011,8 +1011,8 @@ class ChiselStageSpec extends AnyFunSpec with Matchers with chiselTests.Utils { val verilog: String = (new ChiselStage) .execute(args, Seq(ChiselGeneratorAnnotation(() => new Foo))) - .collectFirst { - case EmittedVerilogCircuitAnnotation(a) => a + .collectFirst { case EmittedVerilogCircuitAnnotation(a) => + a } .get .value @@ -1064,8 +1064,8 @@ class ChiselStageSpec extends AnyFunSpec with Matchers with chiselTests.Utils { val verilog: String = (new ChiselStage) .execute(args, Seq(ChiselGeneratorAnnotation(() => new Foo))) - .collectFirst { - case EmittedVerilogCircuitAnnotation(a) => a + .collectFirst { case EmittedVerilogCircuitAnnotation(a) => + a } .get .value @@ -1111,8 +1111,8 @@ class ChiselStageSpec extends AnyFunSpec with Matchers with chiselTests.Utils { new ChiselStageSpec.Bar, args ) - .collectFirst { - case CircuitSerializationAnnotation(_, filename, _) => filename + .collectFirst { case CircuitSerializationAnnotation(_, filename, _) => + filename } .get should be("Bar") @@ -1174,8 +1174,8 @@ class ChiselStageSpec extends AnyFunSpec with Matchers with chiselTests.Utils { args, Array("--lowering-options=disallowPackedArrays") ) - .collectFirst { - case EmittedVerilogCircuitAnnotation(a) => a + .collectFirst { case EmittedVerilogCircuitAnnotation(a) => + a } .get .value should include("case") diff --git a/src/test/scala/examples/VendingMachineGenerator.scala b/src/test/scala/examples/VendingMachineGenerator.scala index 4adae987630..b8a016babea 100644 --- a/src/test/scala/examples/VendingMachineGenerator.scala +++ b/src/test/scala/examples/VendingMachineGenerator.scala @@ -43,9 +43,7 @@ abstract class ParameterizedVendingMachine(legalCoins: Seq[Coin], val sodaCost: } } -class VendingMachineGenerator( - legalCoins: Seq[Coin], - sodaCost: Int) +class VendingMachineGenerator(legalCoins: Seq[Coin], sodaCost: Int) extends ParameterizedVendingMachine(legalCoins, sodaCost) { require(sodaCost > 0, "Sodas must actually cost something!") @@ -71,10 +69,7 @@ class VendingMachineGenerator( io.dispense := doDispense } -class ParameterizedVendingMachineTester( - mod: => ParameterizedVendingMachine, - testLength: Int) - extends BasicTester { +class ParameterizedVendingMachineTester(mod: => ParameterizedVendingMachine, testLength: Int) extends BasicTester { require(testLength > 0, "Test length must be positive!") // Construct the module diff --git a/stdlib/src/main/scala/chisel3/std/BarrelShifter.scala b/stdlib/src/main/scala/chisel3/std/BarrelShifter.scala index c60256530bc..35b4d95ece5 100644 --- a/stdlib/src/main/scala/chisel3/std/BarrelShifter.scala +++ b/stdlib/src/main/scala/chisel3/std/BarrelShifter.scala @@ -47,35 +47,34 @@ object BarrelShifter { .grouped(shiftGranularity) .map(VecInit(_).asUInt) .zipWithIndex - .foldLeft(inputs) { - case (prev, (shiftBits, layer)) => - Mux1H( - UIntToOH(shiftBits), - Seq.tabulate(1 << shiftBits.getWidth)(i => { - // For each layer of barrel shifter, it needs to - // Mux between shift 0 and i * 2^(depthOfLayer*granularity) - // - // e.g, when depth = 2 and granu = 1, the first layer Mux between 0 and 1 - // while the second layer Mux between 0 and 2, thus Vec.shift(UInt(2.W)) - // - // e.g, when depth = 2 and granu = 2, the first layer Mux between 0, 1, 2 and 3 - // while the second layer Mux between 0, 4, 8, and 12, thus achieving Vec.shift(UInt(4.W)) - // - // Also, shift no more than inputs length since prev.drop will not warn about overflow - // this is for Vec with length not the exponential of 2, e.g. 13 - val layerShift: Int = (i * (1 << (layer * shiftGranularity))).min(prev.length) - VecInit(shiftType match { - case LeftRotate => - prev.drop(layerShift) ++ prev.take(layerShift) - case LeftShift => - prev.drop(layerShift) ++ Seq.fill(layerShift)(0.U.asTypeOf(elementType)) - case RightRotate => - prev.takeRight(layerShift) ++ prev.dropRight(layerShift) - case RightShift => - Seq.fill(layerShift)(0.U.asTypeOf(elementType)) ++ prev.dropRight(layerShift) - }) + .foldLeft(inputs) { case (prev, (shiftBits, layer)) => + Mux1H( + UIntToOH(shiftBits), + Seq.tabulate(1 << shiftBits.getWidth)(i => { + // For each layer of barrel shifter, it needs to + // Mux between shift 0 and i * 2^(depthOfLayer*granularity) + // + // e.g, when depth = 2 and granu = 1, the first layer Mux between 0 and 1 + // while the second layer Mux between 0 and 2, thus Vec.shift(UInt(2.W)) + // + // e.g, when depth = 2 and granu = 2, the first layer Mux between 0, 1, 2 and 3 + // while the second layer Mux between 0, 4, 8, and 12, thus achieving Vec.shift(UInt(4.W)) + // + // Also, shift no more than inputs length since prev.drop will not warn about overflow + // this is for Vec with length not the exponential of 2, e.g. 13 + val layerShift: Int = (i * (1 << (layer * shiftGranularity))).min(prev.length) + VecInit(shiftType match { + case LeftRotate => + prev.drop(layerShift) ++ prev.take(layerShift) + case LeftShift => + prev.drop(layerShift) ++ Seq.fill(layerShift)(0.U.asTypeOf(elementType)) + case RightRotate => + prev.takeRight(layerShift) ++ prev.dropRight(layerShift) + case RightShift => + Seq.fill(layerShift)(0.U.asTypeOf(elementType)) ++ prev.dropRight(layerShift) }) - ) + }) + ) } } diff --git a/svsim/src/main/scala/Backend.scala b/svsim/src/main/scala/Backend.scala index 32096635bd3..5a63217dd65 100644 --- a/svsim/src/main/scala/Backend.scala +++ b/svsim/src/main/scala/Backend.scala @@ -8,14 +8,15 @@ import java.io.File */ case class CommonCompilationSettings( verilogPreprocessorDefines: Seq[CommonCompilationSettings.VerilogPreprocessorDefine] = Seq(), - optimizationStyle: CommonCompilationSettings.OptimizationStyle = CommonCompilationSettings.OptimizationStyle.Default, + optimizationStyle: CommonCompilationSettings.OptimizationStyle = CommonCompilationSettings.OptimizationStyle.Default, availableParallelism: CommonCompilationSettings.AvailableParallelism = CommonCompilationSettings.AvailableParallelism.Default, defaultTimescale: Option[CommonCompilationSettings.Timescale] = None, libraryExtensions: Option[Seq[String]] = None, libraryPaths: Option[Seq[String]] = None, includeDirs: Option[Seq[String]] = None, - fileFilter: PartialFunction[File, Boolean] = PartialFunction.empty) + fileFilter: PartialFunction[File, Boolean] = PartialFunction.empty +) object CommonCompilationSettings { object VerilogPreprocessorDefine { def apply(name: String, value: String) = new VerilogPreprocessorDefine(name, Some(value)) @@ -88,7 +89,8 @@ final object Backend { final case class Parameters( private[svsim] val compilerPath: String, private[svsim] val compilerInvocation: Parameters.Invocation, - private[svsim] val simulationInvocation: Parameters.Invocation) + private[svsim] val simulationInvocation: Parameters.Invocation + ) final object Parameters { @@ -97,7 +99,8 @@ final object Backend { */ final case class Invocation( private[svsim] val arguments: Seq[String], - private[svsim] val environment: Seq[(String, String)]) + private[svsim] val environment: Seq[(String, String)] + ) } /** diff --git a/svsim/src/main/scala/Simulation.scala b/svsim/src/main/scala/Simulation.scala index 7286bd998e6..aa5e793d892 100644 --- a/svsim/src/main/scala/Simulation.scala +++ b/svsim/src/main/scala/Simulation.scala @@ -10,7 +10,8 @@ final class Simulation private[svsim] ( executableName: String, settings: Simulation.Settings, val workingDirectoryPath: String, - moduleInfo: ModuleInfo) { + moduleInfo: ModuleInfo +) { private val executionScriptPath = s"$workingDirectoryPath/execution-script.txt" def run[T](body: Simulation.Controller => T): T = run()(body) @@ -19,8 +20,7 @@ final class Simulation private[svsim] ( verbose: Boolean = false, traceEnabled: Boolean = false, executionScriptLimit: Option[Int] = None - )(body: Simulation.Controller => T - ): T = { + )(body: Simulation.Controller => T): T = { val cwd = settings.customWorkingDirectory match { case None => workingDirectoryPath case Some(value) => @@ -94,7 +94,8 @@ object Simulation { private[svsim] final case class Settings( customWorkingDirectory: Option[String] = None, arguments: Seq[String] = Seq(), - environment: Map[String, String] = Map()) + environment: Map[String, String] = Map() + ) /** @note Methods in this class and `Simulation.Port` are somewhat lazy in their execution. Specifically, methods returning `Unit` neither flush the command buffer, nor do they actively read from the message buffer. Only commands which return a value will wait to return until the simulation has progressed to the point where the value is available. This can improve performance by essentially enabling batching of both commands and messages. If you want to ensure that all commands have been sent to the simulation executable, you can call `completeInFlightCommands()`. */ @@ -103,7 +104,8 @@ object Simulation { messageReader: BufferedReader, moduleInfo: ModuleInfo, conservativeCommandResolution: Boolean = false, - logMessagesAndCommands: Boolean = false) { + logMessagesAndCommands: Boolean = false + ) { private def readStringOfLength(length: Int): String = { val array = new Array[Char](length) @@ -306,9 +308,8 @@ object Simulation { def readLog(): String = { sendCommand(Simulation.Command.Log) - processNextMessage { - case Simulation.Message.Log(message) => - message + processNextMessage { case Simulation.Message.Log(message) => + message } } @@ -322,9 +323,8 @@ object Simulation { expectNextMessage { case Simulation.Message.Ack => } } - private val portInfos = moduleInfo.ports.zipWithIndex.map { - case (port, index) => - port.name -> (index.toHexString, port) + private val portInfos = moduleInfo.ports.zipWithIndex.map { case (port, index) => + port.name -> (index.toHexString, port) }.toMap def port(name: String): Simulation.Port = { @@ -360,8 +360,8 @@ object Simulation { outOfPhaseValue: BigInt, timestepsPerPhase: Int, maxCycles: Int, - sentinel: Option[(Port, BigInt)]) - extends Command + sentinel: Option[(Port, BigInt)] + ) extends Command case class Trace(enable: Boolean) extends Command } @@ -371,16 +371,14 @@ object Simulation { def set(value: BigInt) = { controller.sendCommand(Simulation.Command.SetBits(id, value)) - controller.expectNextMessage { - case Simulation.Message.Ack => + controller.expectNextMessage { case Simulation.Message.Ack => } } def get(isSigned: Boolean = false): Value = { controller.sendCommand(Simulation.Command.GetBits(id, isSigned)) - controller.processNextMessage { - case Simulation.Message.Bits(bitCount, value) => - Value(bitCount, value) + controller.processNextMessage { case Simulation.Message.Bits(bitCount, value) => + Value(bitCount, value) } } @@ -388,8 +386,7 @@ object Simulation { controller.sendCommand( Simulation.Command.Tick(id, inPhaseValue, outOfPhaseValue, timestepsPerPhase, cycles, None) ) - controller.expectNextMessage { - case Simulation.Message.Bits(_, _) => + controller.expectNextMessage { case Simulation.Message.Bits(_, _) => } } @@ -403,9 +400,8 @@ object Simulation { controller.sendCommand( Simulation.Command.Tick(id, inPhaseValue, outOfPhaseValue, timestepsPerPhase, maxCycles, sentinel) ) - controller.processNextMessage { - case Simulation.Message.Bits(_, cyclesElapsed) => - cyclesElapsed + controller.processNextMessage { case Simulation.Message.Bits(_, cyclesElapsed) => + cyclesElapsed } } @@ -420,18 +416,16 @@ object Simulation { controller.sendCommand( Simulation.Command.Tick(id, inPhaseValue, outOfPhaseValue, timestepsPerPhase, maxCycles, sentinel) ) - controller.expectNextMessage { - case Simulation.Message.Bits(_, cyclesElapsed) => - checkElapsedCycleCount(cyclesElapsed) + controller.expectNextMessage { case Simulation.Message.Bits(_, cyclesElapsed) => + checkElapsedCycleCount(cyclesElapsed) } } def check(f: Value => Unit): Unit = check()(f) def check(isSigned: Boolean = false)(f: Value => Unit): Unit = { controller.sendCommand(Simulation.Command.GetBits(id, isSigned)) - controller.expectNextMessage { - case Simulation.Message.Bits(bitCount, value) => - f(Value(bitCount, value)) + controller.expectNextMessage { case Simulation.Message.Bits(bitCount, value) => + f(Value(bitCount, value)) } } } diff --git a/svsim/src/main/scala/Workspace.scala b/svsim/src/main/scala/Workspace.scala index 427910520aa..0b76fd84ded 100644 --- a/svsim/src/main/scala/Workspace.scala +++ b/svsim/src/main/scala/Workspace.scala @@ -6,16 +6,11 @@ import java.lang.ProcessBuilder.Redirect import scala.annotation.meta.param import scala.jdk.CollectionConverters._ -case class ModuleInfo( - name: String, - ports: Seq[ModuleInfo.Port]) { +case class ModuleInfo(name: String, ports: Seq[ModuleInfo.Port]) { private[svsim] val instanceName = "dut" } object ModuleInfo { - case class Port( - name: String, - isSettable: Boolean = false, - isGettable: Boolean = false) { + case class Port(name: String, isSettable: Boolean = false, isGettable: Boolean = false) { assert(name.matches("^[a-zA-Z0-9\\-_]*$")) } } @@ -27,7 +22,8 @@ final class Workspace( path: String, /** The prefix for the working directory used when invoking `compile` */ - val workingDirectoryPrefix: String = "workdir") { + val workingDirectoryPrefix: String = "workdir" +) { val absolutePath = if (path.startsWith("/")) @@ -295,8 +291,9 @@ final class Workspace( * @param outputTag A string which will be used to tag the output directory. This enables compiling and simulating the same workspace with multiple backends. */ def compile[T <: Backend]( - backend: T - )(workingDirectoryTag: String, + backend: T + )( + workingDirectoryTag: String, commonSettings: CommonCompilationSettings, backendSpecificSettings: backend.CompilationSettings, customSimulationWorkingDirectory: Option[String], diff --git a/svsim/src/main/scala/vcs/Backend.scala b/svsim/src/main/scala/vcs/Backend.scala index f1538e60771..f0b2aa3024c 100644 --- a/svsim/src/main/scala/vcs/Backend.scala +++ b/svsim/src/main/scala/vcs/Backend.scala @@ -18,7 +18,8 @@ object Backend { final case class TraceSettings( enableVcd: Boolean = false, enableVpd: Boolean = false, - fsdbSettings: Option[TraceSettings.FsdbSettings] = None) { + fsdbSettings: Option[TraceSettings.FsdbSettings] = None + ) { private def fsdbEnabled = fsdbSettings match { case Some(_) => true case None => false @@ -40,9 +41,8 @@ object Backend { (enableVcd, svsim.Backend.HarnessCompilationFlags.enableVcdTracingSupport), (enableVpd, svsim.Backend.HarnessCompilationFlags.enableVpdTracingSupport), (fsdbEnabled, svsim.Backend.HarnessCompilationFlags.enableFsdbTracingSupport) - ).collect { - case (true, value) => - svsim.CommonCompilationSettings.VerilogPreprocessorDefine(value) + ).collect { case (true, value) => + svsim.CommonCompilationSettings.VerilogPreprocessorDefine(value) } private[vcs] def environment = fsdbSettings match { case None => Seq() @@ -56,7 +56,8 @@ object Backend { final case class SimulationSettings( customWorkingDirectory: Option[String] = None, - assertionSettings: Option[AssertionSettings] = None) + assertionSettings: Option[AssertionSettings] = None + ) case class CompilationSettings( xProp: Option[CompilationSettings.XProp] = None, @@ -65,7 +66,8 @@ object Backend { simulationSettings: SimulationSettings = SimulationSettings(), licenceExpireWarningTimeout: Option[Int] = None, archOverride: Option[String] = None, - waitForLicenseIfUnavailable: Boolean = false) + waitForLicenseIfUnavailable: Boolean = false + ) def initializeFromProcessEnvironment() = { (sys.env.get("VCS_HOME"), sys.env.get("LM_LICENSE_FILE")) match { @@ -86,8 +88,8 @@ final class Backend( vcsHome: String, lmLicenseFile: String, defaultArchOverride: Option[String] = None, - defaultLicenseExpireWarningTimeout: Option[String] = None) - extends svsim.Backend { + defaultLicenseExpireWarningTimeout: Option[String] = None +) extends svsim.Backend { type CompilationSettings = Backend.CompilationSettings def generateParameters( diff --git a/svsim/src/main/scala/verilator/Backend.scala b/svsim/src/main/scala/verilator/Backend.scala index ab54de4ec1f..cb1851b4414 100644 --- a/svsim/src/main/scala/verilator/Backend.scala +++ b/svsim/src/main/scala/verilator/Backend.scala @@ -20,7 +20,8 @@ object Backend { outputSplitCFuncs: Option[Int] = None, disabledWarnings: Seq[String] = Seq(), disableFatalExitOnWarnings: Boolean = false, - enableAllAssertions: Boolean = false) + enableAllAssertions: Boolean = false + ) def initializeFromProcessEnvironment() = { val output = mutable.ArrayBuffer.empty[String] @@ -32,9 +33,7 @@ object Backend { new Backend(executablePath = executablePath) } } -final class Backend( - executablePath: String) - extends svsim.Backend { +final class Backend(executablePath: String) extends svsim.Backend { type CompilationSettings = Backend.CompilationSettings def generateParameters( diff --git a/svsim/src/test/scala/BackendSpec.scala b/svsim/src/test/scala/BackendSpec.scala index ccfa12ff5eb..1df97a039b0 100644 --- a/svsim/src/test/scala/BackendSpec.scala +++ b/svsim/src/test/scala/BackendSpec.scala @@ -58,10 +58,9 @@ class VerilatorSpec extends BackendSpec { trait BackendSpec extends AnyFunSpec with Matchers { def test[Backend <: svsim.Backend]( - name: String, - backend: Backend - )(compilationSettings: backend.CompilationSettings - ) = { + name: String, + backend: Backend + )(compilationSettings: backend.CompilationSettings) = { describe(s"Svsim backend '$name'") { val workspace = new svsim.Workspace(path = s"test_run_dir/${getClass().getSimpleName()}") var simulation: Simulation = null