diff options
| author | chick | 2020-08-14 19:47:53 -0700 |
|---|---|---|
| committer | Jack Koenig | 2020-08-14 19:47:53 -0700 |
| commit | 6fc742bfaf5ee508a34189400a1a7dbffe3f1cac (patch) | |
| tree | 2ed103ee80b0fba613c88a66af854ae9952610ce /src/main/scala/firrtl/annotations | |
| parent | b516293f703c4de86397862fee1897aded2ae140 (diff) | |
All of src/ formatted with scalafmt
Diffstat (limited to 'src/main/scala/firrtl/annotations')
11 files changed, 535 insertions, 430 deletions
diff --git a/src/main/scala/firrtl/annotations/Annotation.scala b/src/main/scala/firrtl/annotations/Annotation.scala index a382f685..16f85e67 100644 --- a/src/main/scala/firrtl/annotations/Annotation.scala +++ b/src/main/scala/firrtl/annotations/Annotation.scala @@ -5,7 +5,6 @@ package annotations import firrtl.options.StageUtils - case class AnnotationException(message: String) extends Exception(message) /** Base type of auxiliary information */ @@ -26,8 +25,8 @@ trait Annotation extends Product { */ private def extractComponents(ls: scala.collection.Traversable[_]): Seq[Target] = { ls.collect { - case c: Target => Seq(c) - case o: Product => extractComponents(o.productIterator.toIterable) + case c: Target => Seq(c) + case o: Product => extractComponents(o.productIterator.toIterable) case x: scala.collection.Traversable[_] => extractComponents(x) }.foldRight(Seq.empty[Target])((seq, c) => c ++ seq) } @@ -62,52 +61,54 @@ trait SingleTargetAnnotation[T <: Named] extends Annotation { x.map(newTargets => newTargets.map(t => duplicate(t.asInstanceOf[T]))).getOrElse(List(this)) case from: Named => val ret = renames.get(Target.convertNamed2Target(target)) - ret.map(_.map { newT => - val result = newT match { - case c: InstanceTarget => ModuleName(c.ofModule, CircuitName(c.circuit)) - case c: IsMember => - val local = Target.referringModule(c) - c.setPathTarget(local) - case c: CircuitTarget => c.toNamed - case other => throw Target.NamedException(s"Cannot convert $other to [[Named]]") - } - Target.convertTarget2Named(result) match { - case newTarget: T @unchecked => - try { - duplicate(newTarget) - } - catch { - case _: java.lang.ClassCastException => - val msg = s"${this.getClass.getName} target ${target.getClass.getName} " + - s"cannot be renamed to ${newTarget.getClass}" - throw AnnotationException(msg) - } - } - }).getOrElse(List(this)) + ret + .map(_.map { newT => + val result = newT match { + case c: InstanceTarget => ModuleName(c.ofModule, CircuitName(c.circuit)) + case c: IsMember => + val local = Target.referringModule(c) + c.setPathTarget(local) + case c: CircuitTarget => c.toNamed + case other => throw Target.NamedException(s"Cannot convert $other to [[Named]]") + } + Target.convertTarget2Named(result) match { + case newTarget: T @unchecked => + try { + duplicate(newTarget) + } catch { + case _: java.lang.ClassCastException => + val msg = s"${this.getClass.getName} target ${target.getClass.getName} " + + s"cannot be renamed to ${newTarget.getClass}" + throw AnnotationException(msg) + } + } + }) + .getOrElse(List(this)) } } } /** [[MultiTargetAnnotation]] keeps the renamed targets grouped within a single annotation. */ trait MultiTargetAnnotation extends Annotation { + /** Contains a sequence of [[firrtl.annotations.Target Target]]. * When created, [[targets]] should be assigned by `Seq(Seq(TargetA), Seq(TargetB), Seq(TargetC))` */ val targets: Seq[Seq[Target]] - /** Create another instance of this Annotation*/ + /** Create another instance of this Annotation */ def duplicate(n: Seq[Seq[Target]]): Annotation /** Assume [[RenameMap]] is `Map(TargetA -> Seq(TargetA1, TargetA2, TargetA3), TargetB -> Seq(TargetB1, TargetB2))` * in the update, this Annotation is still one annotation, but the contents are renamed in the below form * Seq(Seq(TargetA1, TargetA2, TargetA3), Seq(TargetB1, TargetB2), Seq(TargetC)) - **/ + */ def update(renames: RenameMap): Seq[Annotation] = Seq(duplicate(targets.map(ts => ts.flatMap(renames(_))))) private def crossJoin[T](list: Seq[Seq[T]]): Seq[Seq[T]] = list match { - case Nil => Nil - case x :: Nil => x map (Seq(_)) + case Nil => Nil + case x :: Nil => x.map(Seq(_)) case x :: xs => val xsJoin = crossJoin(xs) for { @@ -123,7 +124,7 @@ trait MultiTargetAnnotation extends Annotation { * Seq(Seq(TargetA1), Seq(TargetB1), Seq(TargetC)); Seq(Seq(TargetA1), Seq(TargetB2), Seq(TargetC)) * Seq(Seq(TargetA2), Seq(TargetB1), Seq(TargetC)); Seq(Seq(TargetA2), Seq(TargetB2), Seq(TargetC)) * Seq(Seq(TargetA3), Seq(TargetB1), Seq(TargetC)); Seq(Seq(TargetA3), Seq(TargetB2), Seq(TargetC)) - * */ + */ def flat(): AnnotationSeq = crossJoin(targets).map(r => duplicate(r.map(Seq(_)))) } diff --git a/src/main/scala/firrtl/annotations/AnnotationUtils.scala b/src/main/scala/firrtl/annotations/AnnotationUtils.scala index 58cc0097..a1276e0e 100644 --- a/src/main/scala/firrtl/annotations/AnnotationUtils.scala +++ b/src/main/scala/firrtl/annotations/AnnotationUtils.scala @@ -8,14 +8,16 @@ import java.io.File import firrtl.ir._ case class InvalidAnnotationFileException(file: File, cause: FirrtlUserException = null) - extends FirrtlUserException(s"$file", cause) + extends FirrtlUserException(s"$file", cause) case class InvalidAnnotationJSONException(msg: String) extends FirrtlUserException(msg) -case class AnnotationFileNotFoundException(file: File) extends FirrtlUserException( - s"Annotation file $file not found!" -) -case class AnnotationClassNotFoundException(className: String) extends FirrtlUserException( - s"Annotation class $className not found! Please check spelling and classpath" -) +case class AnnotationFileNotFoundException(file: File) + extends FirrtlUserException( + s"Annotation file $file not found!" + ) +case class AnnotationClassNotFoundException(className: String) + extends FirrtlUserException( + s"Annotation class $className not found! Please check spelling and classpath" + ) object AnnotationUtils { @@ -23,33 +25,33 @@ object AnnotationUtils { val SerializedModuleName = """([a-zA-Z_][a-zA-Z_0-9~!@#$%^*\-+=?/]*)""".r def validModuleName(s: String): Boolean = s match { case SerializedModuleName(name) => true - case _ => false + case _ => false } /** Returns true if a valid component/subcomponent name */ val SerializedComponentName = """([a-zA-Z_][a-zA-Z_0-9\[\]\.~!@#$%^*\-+=?/]*)""".r def validComponentName(s: String): Boolean = s match { case SerializedComponentName(name) => true - case _ => false + case _ => false } /** Tokenizes a string with '[', ']', '.' as tokens, e.g.: - * "foo.bar[boo.far]" becomes Seq("foo" "." "bar" "[" "boo" "." "far" "]") - */ + * "foo.bar[boo.far]" becomes Seq("foo" "." "bar" "[" "boo" "." "far" "]") + */ def tokenize(s: String): Seq[String] = s.find(c => "[].".contains(c)) match { case Some(_) => val i = s.indexWhere(c => "[].".contains(c)) s.slice(0, i) match { case "" => s(i).toString +: tokenize(s.drop(i + 1)) - case x => x +: s(i).toString +: tokenize(s.drop(i + 1)) + case x => x +: s(i).toString +: tokenize(s.drop(i + 1)) } case None if s == "" => Nil - case None => Seq(s) + case None => Seq(s) } def toNamed(s: String): Named = s.split("\\.", 3) match { - case Array(n) => CircuitName(n) - case Array(c, m) => ModuleName(m, CircuitName(c)) + case Array(n) => CircuitName(n) + case Array(c, m) => ModuleName(m, CircuitName(c)) case Array(c, m, x) => ComponentName(x, ModuleName(m, CircuitName(c))) } @@ -60,38 +62,39 @@ object AnnotationUtils { def toSubComponents(s: String): Seq[TargetToken] = { import TargetToken._ def exp2subcomp(e: ir.Expression): Seq[TargetToken] = e match { - case ir.Reference(name, _, _, _) => Seq(Ref(name)) + case ir.Reference(name, _, _, _) => Seq(Ref(name)) case ir.SubField(expr, name, _, _) => exp2subcomp(expr) :+ Field(name) case ir.SubIndex(expr, idx, _, _) => exp2subcomp(expr) :+ Index(idx) - case ir.SubAccess(expr, idx, _, _) => Utils.throwInternalError(s"For string $s, cannot convert a subaccess $e into a Target") + case ir.SubAccess(expr, idx, _, _) => + Utils.throwInternalError(s"For string $s, cannot convert a subaccess $e into a Target") } exp2subcomp(toExp(s)) } - /** Given a serialized component/subcomponent reference, subindex, subaccess, - * or subfield, return the corresponding IR expression. - * E.g. "foo.bar" becomes SubField(Reference("foo", UnknownType), "bar", UnknownType) - */ + * or subfield, return the corresponding IR expression. + * E.g. "foo.bar" becomes SubField(Reference("foo", UnknownType), "bar", UnknownType) + */ def toExp(s: String): Expression = { def parse(tokens: Seq[String]): Expression = { val DecPattern = """(\d+)""".r def findClose(tokens: Seq[String], index: Int, nOpen: Int): Seq[String] = { - if(index >= tokens.size) { + if (index >= tokens.size) { Utils.error("Cannot find closing bracket ]") - } else tokens(index) match { - case "[" => findClose(tokens, index + 1, nOpen + 1) - case "]" if nOpen == 1 => tokens.slice(1, index) - case "]" => findClose(tokens, index + 1, nOpen - 1) - case _ => findClose(tokens, index + 1, nOpen) - } + } else + tokens(index) match { + case "[" => findClose(tokens, index + 1, nOpen + 1) + case "]" if nOpen == 1 => tokens.slice(1, index) + case "]" => findClose(tokens, index + 1, nOpen - 1) + case _ => findClose(tokens, index + 1, nOpen) + } } def buildup(e: Expression, tokens: Seq[String]): Expression = tokens match { case "[" :: tail => val indexOrAccess = findClose(tokens, 0, 0) val exp = indexOrAccess.head match { case DecPattern(d) => SubIndex(e, d.toInt, UnknownType) - case _ => SubAccess(e, parse(indexOrAccess), UnknownType) + case _ => SubAccess(e, parse(indexOrAccess), UnknownType) } buildup(exp, tokens.drop(2 + indexOrAccess.size)) case "." :: tail => @@ -101,7 +104,7 @@ object AnnotationUtils { val root = Reference(tokens.head, UnknownType) buildup(root, tokens.tail) } - if(validComponentName(s)) { + if (validComponentName(s)) { parse(tokenize(s)) } else { Utils.error(s"Cannot convert $s into an expression.") diff --git a/src/main/scala/firrtl/annotations/JsonProtocol.scala b/src/main/scala/firrtl/annotations/JsonProtocol.scala index 941bf003..0ef8b020 100644 --- a/src/main/scala/firrtl/annotations/JsonProtocol.scala +++ b/src/main/scala/firrtl/annotations/JsonProtocol.scala @@ -5,7 +5,7 @@ package annotations import firrtl.ir._ -import scala.util.{Try, Failure} +import scala.util.{Failure, Try} import org.json4s._ import org.json4s.native.JsonMethods._ @@ -20,112 +20,189 @@ trait HasSerializationHints { } object JsonProtocol { - class TransformClassSerializer extends CustomSerializer[Class[_ <: Transform]](format => ( - { case JString(s) => Class.forName(s).asInstanceOf[Class[_ <: Transform]] }, - { case x: Class[_] => JString(x.getName) } - )) + class TransformClassSerializer + extends CustomSerializer[Class[_ <: Transform]](format => + ( + { case JString(s) => Class.forName(s).asInstanceOf[Class[_ <: Transform]] }, + { case x: Class[_] => JString(x.getName) } + ) + ) // TODO Reduce boilerplate? - class NamedSerializer extends CustomSerializer[Named](format => ( - { case JString(s) => AnnotationUtils.toNamed(s) }, - { case named: Named => JString(named.serialize) } - )) - class CircuitNameSerializer extends CustomSerializer[CircuitName](format => ( - { case JString(s) => AnnotationUtils.toNamed(s).asInstanceOf[CircuitName] }, - { case named: CircuitName => JString(named.serialize) } - )) - class ModuleNameSerializer extends CustomSerializer[ModuleName](format => ( - { case JString(s) => AnnotationUtils.toNamed(s).asInstanceOf[ModuleName] }, - { case named: ModuleName => JString(named.serialize) } - )) - class ComponentNameSerializer extends CustomSerializer[ComponentName](format => ( - { case JString(s) => AnnotationUtils.toNamed(s).asInstanceOf[ComponentName] }, - { case named: ComponentName => JString(named.serialize) } - )) - class TransformSerializer extends CustomSerializer[Transform](format => ( - { case JString(s) => - try { - Class.forName(s).asInstanceOf[Class[_ <: Transform]].newInstance() - } catch { - case e: java.lang.InstantiationException => throw new FirrtlInternalException( - "NoSuchMethodException during construction of serialized Transform. Is your Transform an inner class?", e) - case t: Throwable => throw t - }}, - { case x: Transform => JString(x.getClass.getName) } - )) - class LoadMemoryFileTypeSerializer extends CustomSerializer[MemoryLoadFileType](format => ( - { case JString(s) => MemoryLoadFileType.deserialize(s) }, - { case named: MemoryLoadFileType => JString(named.serialize) } - )) + class NamedSerializer + extends CustomSerializer[Named](format => + ( + { case JString(s) => AnnotationUtils.toNamed(s) }, + { case named: Named => JString(named.serialize) } + ) + ) + class CircuitNameSerializer + extends CustomSerializer[CircuitName](format => + ( + { case JString(s) => AnnotationUtils.toNamed(s).asInstanceOf[CircuitName] }, + { case named: CircuitName => JString(named.serialize) } + ) + ) + class ModuleNameSerializer + extends CustomSerializer[ModuleName](format => + ( + { case JString(s) => AnnotationUtils.toNamed(s).asInstanceOf[ModuleName] }, + { case named: ModuleName => JString(named.serialize) } + ) + ) + class ComponentNameSerializer + extends CustomSerializer[ComponentName](format => + ( + { case JString(s) => AnnotationUtils.toNamed(s).asInstanceOf[ComponentName] }, + { case named: ComponentName => JString(named.serialize) } + ) + ) + class TransformSerializer + extends CustomSerializer[Transform](format => + ( + { + case JString(s) => + try { + Class.forName(s).asInstanceOf[Class[_ <: Transform]].newInstance() + } catch { + case e: java.lang.InstantiationException => + throw new FirrtlInternalException( + "NoSuchMethodException during construction of serialized Transform. Is your Transform an inner class?", + e + ) + case t: Throwable => throw t + } + }, + { case x: Transform => JString(x.getClass.getName) } + ) + ) + class LoadMemoryFileTypeSerializer + extends CustomSerializer[MemoryLoadFileType](format => + ( + { case JString(s) => MemoryLoadFileType.deserialize(s) }, + { case named: MemoryLoadFileType => JString(named.serialize) } + ) + ) - class TargetSerializer extends CustomSerializer[Target](format => ( - { case JString(s) => Target.deserialize(s) }, - { case named: Target => JString(named.serialize) } - )) - class GenericTargetSerializer extends CustomSerializer[GenericTarget](format => ( - { case JString(s) => Target.deserialize(s).asInstanceOf[GenericTarget] }, - { case named: GenericTarget => JString(named.serialize) } - )) - class CircuitTargetSerializer extends CustomSerializer[CircuitTarget](format => ( - { case JString(s) => Target.deserialize(s).asInstanceOf[CircuitTarget] }, - { case named: CircuitTarget => JString(named.serialize) } - )) - class ModuleTargetSerializer extends CustomSerializer[ModuleTarget](format => ( - { case JString(s) => Target.deserialize(s).asInstanceOf[ModuleTarget] }, - { case named: ModuleTarget => JString(named.serialize) } - )) - class InstanceTargetSerializer extends CustomSerializer[InstanceTarget](format => ( - { case JString(s) => Target.deserialize(s).asInstanceOf[InstanceTarget] }, - { case named: InstanceTarget => JString(named.serialize) } - )) - class ReferenceTargetSerializer extends CustomSerializer[ReferenceTarget](format => ( - { case JString(s) => Target.deserialize(s).asInstanceOf[ReferenceTarget] }, - { case named: ReferenceTarget => JString(named.serialize) } - )) - class IsModuleSerializer extends CustomSerializer[IsModule](format => ( - { case JString(s) => Target.deserialize(s).asInstanceOf[IsModule] }, - { case named: IsModule => JString(named.serialize) } - )) - class IsMemberSerializer extends CustomSerializer[IsMember](format => ( - { case JString(s) => Target.deserialize(s).asInstanceOf[IsMember] }, - { case named: IsMember => JString(named.serialize) } - )) - class CompleteTargetSerializer extends CustomSerializer[CompleteTarget](format => ( - { case JString(s) => Target.deserialize(s).asInstanceOf[CompleteTarget] }, - { case named: CompleteTarget => JString(named.serialize) } - )) + class TargetSerializer + extends CustomSerializer[Target](format => + ( + { case JString(s) => Target.deserialize(s) }, + { case named: Target => JString(named.serialize) } + ) + ) + class GenericTargetSerializer + extends CustomSerializer[GenericTarget](format => + ( + { case JString(s) => Target.deserialize(s).asInstanceOf[GenericTarget] }, + { case named: GenericTarget => JString(named.serialize) } + ) + ) + class CircuitTargetSerializer + extends CustomSerializer[CircuitTarget](format => + ( + { case JString(s) => Target.deserialize(s).asInstanceOf[CircuitTarget] }, + { case named: CircuitTarget => JString(named.serialize) } + ) + ) + class ModuleTargetSerializer + extends CustomSerializer[ModuleTarget](format => + ( + { case JString(s) => Target.deserialize(s).asInstanceOf[ModuleTarget] }, + { case named: ModuleTarget => JString(named.serialize) } + ) + ) + class InstanceTargetSerializer + extends CustomSerializer[InstanceTarget](format => + ( + { case JString(s) => Target.deserialize(s).asInstanceOf[InstanceTarget] }, + { case named: InstanceTarget => JString(named.serialize) } + ) + ) + class ReferenceTargetSerializer + extends CustomSerializer[ReferenceTarget](format => + ( + { case JString(s) => Target.deserialize(s).asInstanceOf[ReferenceTarget] }, + { case named: ReferenceTarget => JString(named.serialize) } + ) + ) + class IsModuleSerializer + extends CustomSerializer[IsModule](format => + ( + { case JString(s) => Target.deserialize(s).asInstanceOf[IsModule] }, + { case named: IsModule => JString(named.serialize) } + ) + ) + class IsMemberSerializer + extends CustomSerializer[IsMember](format => + ( + { case JString(s) => Target.deserialize(s).asInstanceOf[IsMember] }, + { case named: IsMember => JString(named.serialize) } + ) + ) + class CompleteTargetSerializer + extends CustomSerializer[CompleteTarget](format => + ( + { case JString(s) => Target.deserialize(s).asInstanceOf[CompleteTarget] }, + { case named: CompleteTarget => JString(named.serialize) } + ) + ) // FIRRTL Serializers - class TypeSerializer extends CustomSerializer[Type](format => ( - { case JString(s) => Parser.parseType(s) }, - { case tpe: Type => JString(tpe.serialize) } - )) - class ExpressionSerializer extends CustomSerializer[Expression](format => ( - { case JString(s) => Parser.parseExpression(s) }, - { case expr: Expression => JString(expr.serialize) } - )) - class StatementSerializer extends CustomSerializer[Statement](format => ( - { case JString(s) => Parser.parseStatement(s) }, - { case statement: Statement => JString(statement.serialize) } - )) - class PortSerializer extends CustomSerializer[Port](format => ( - { case JString(s) => Parser.parsePort(s) }, - { case port: Port => JString(port.serialize) } - )) - class DefModuleSerializer extends CustomSerializer[DefModule](format => ( - { case JString(s) => Parser.parseDefModule(s) }, - { case mod: DefModule => JString(mod.serialize) } - )) - class CircuitSerializer extends CustomSerializer[Circuit](format => ( - { case JString(s) => Parser.parse(s) }, - { case cir: Circuit => JString(cir.serialize) } - )) - class InfoSerializer extends CustomSerializer[Info](format => ( - { case JString(s) => Parser.parseInfo(s) }, - { case info: Info => JString(info.serialize) } - )) - class GroundTypeSerializer extends CustomSerializer[GroundType](format => ( - { case JString(s) => Parser.parseType(s).asInstanceOf[GroundType] }, - { case tpe: GroundType => JString(tpe.serialize) } - )) + class TypeSerializer + extends CustomSerializer[Type](format => + ( + { case JString(s) => Parser.parseType(s) }, + { case tpe: Type => JString(tpe.serialize) } + ) + ) + class ExpressionSerializer + extends CustomSerializer[Expression](format => + ( + { case JString(s) => Parser.parseExpression(s) }, + { case expr: Expression => JString(expr.serialize) } + ) + ) + class StatementSerializer + extends CustomSerializer[Statement](format => + ( + { case JString(s) => Parser.parseStatement(s) }, + { case statement: Statement => JString(statement.serialize) } + ) + ) + class PortSerializer + extends CustomSerializer[Port](format => + ( + { case JString(s) => Parser.parsePort(s) }, + { case port: Port => JString(port.serialize) } + ) + ) + class DefModuleSerializer + extends CustomSerializer[DefModule](format => + ( + { case JString(s) => Parser.parseDefModule(s) }, + { case mod: DefModule => JString(mod.serialize) } + ) + ) + class CircuitSerializer + extends CustomSerializer[Circuit](format => + ( + { case JString(s) => Parser.parse(s) }, + { case cir: Circuit => JString(cir.serialize) } + ) + ) + class InfoSerializer + extends CustomSerializer[Info](format => + ( + { case JString(s) => Parser.parseInfo(s) }, + { case info: Info => JString(info.serialize) } + ) + ) + class GroundTypeSerializer + extends CustomSerializer[GroundType](format => + ( + { case JString(s) => Parser.parseType(s).asInstanceOf[GroundType] }, + { case tpe: GroundType => JString(tpe.serialize) } + ) + ) /** Construct Json formatter for annotations */ def jsonFormat(tags: Seq[Class[_]]) = { @@ -133,7 +210,7 @@ object JsonProtocol { new TransformClassSerializer + new NamedSerializer + new CircuitNameSerializer + new ModuleNameSerializer + new ComponentNameSerializer + new TargetSerializer + new GenericTargetSerializer + new CircuitTargetSerializer + new ModuleTargetSerializer + - new InstanceTargetSerializer + new ReferenceTargetSerializer + new TransformSerializer + + new InstanceTargetSerializer + new ReferenceTargetSerializer + new TransformSerializer + new LoadMemoryFileTypeSerializer + new IsModuleSerializer + new IsMemberSerializer + new CompleteTargetSerializer + new TypeSerializer + new ExpressionSerializer + new StatementSerializer + new PortSerializer + new DefModuleSerializer + @@ -144,10 +221,12 @@ object JsonProtocol { def serialize(annos: Seq[Annotation]): String = serializeTry(annos).get def serializeTry(annos: Seq[Annotation]): Try[String] = { - val tags = annos.flatMap({ - case anno: HasSerializationHints => anno.getClass +: anno.typeHints - case anno => Seq(anno.getClass) - }).distinct + val tags = annos + .flatMap({ + case anno: HasSerializationHints => anno.getClass +: anno.typeHints + case anno => Seq(anno.getClass) + }) + .distinct implicit val formats = jsonFormat(tags) Try(writePretty(annos)) @@ -159,20 +238,25 @@ object JsonProtocol { val parsed = parse(in) val annos = parsed match { case JArray(objs) => objs - case x => throw new InvalidAnnotationJSONException( - s"Annotations must be serialized as a JArray, got ${x.getClass.getName} instead!") + case x => + throw new InvalidAnnotationJSONException( + s"Annotations must be serialized as a JArray, got ${x.getClass.getName} instead!" + ) } // Recursively gather typeHints by pulling the "class" field from JObjects // Json4s should emit this as the first field in all serialized classes // Setting requireClassField mandates that all JObjects must provide a typeHint, // this used on the first invocation to check all annotations do so - def findTypeHints(classInst: Seq[JValue], requireClassField: Boolean = false): Seq[String] = classInst.flatMap({ - case JObject(("class", JString(name)) :: fields) => name +: findTypeHints(fields.map(_._2)) - case obj: JObject if requireClassField => throw new InvalidAnnotationJSONException(s"Expected field 'class' not found! $obj") - case JObject(fields) => findTypeHints(fields.map(_._2)) - case JArray(arr) => findTypeHints(arr) - case oJValue => Seq() - }).distinct + def findTypeHints(classInst: Seq[JValue], requireClassField: Boolean = false): Seq[String] = classInst + .flatMap({ + case JObject(("class", JString(name)) :: fields) => name +: findTypeHints(fields.map(_._2)) + case obj: JObject if requireClassField => + throw new InvalidAnnotationJSONException(s"Expected field 'class' not found! $obj") + case JObject(fields) => findTypeHints(fields.map(_._2)) + case JArray(arr) => findTypeHints(arr) + case oJValue => Seq() + }) + .distinct val classes = findTypeHints(annos, true) val loaded = classes.map(Class.forName(_)) @@ -186,10 +270,11 @@ object JsonProtocol { case e @ (_: org.json4s.ParserUtil.ParseException | _: org.json4s.MappingException) => Failure(new InvalidAnnotationJSONException(e.getMessage)) }.recoverWith { // If the input is a file, wrap in InvalidAnnotationFileException - case e: FirrtlUserException => in match { - case FileInput(file) => - Failure(new InvalidAnnotationFileException(file, e)) - case _ => Failure(e) - } + case e: FirrtlUserException => + in match { + case FileInput(file) => + Failure(new InvalidAnnotationFileException(file, e)) + case _ => Failure(e) + } } } diff --git a/src/main/scala/firrtl/annotations/LoadMemoryAnnotation.scala b/src/main/scala/firrtl/annotations/LoadMemoryAnnotation.scala index 64c30bdb..043c1b3b 100644 --- a/src/main/scala/firrtl/annotations/LoadMemoryAnnotation.scala +++ b/src/main/scala/firrtl/annotations/LoadMemoryAnnotation.scala @@ -21,7 +21,7 @@ object MemoryLoadFileType { def deserialize(s: String): MemoryLoadFileType = s match { case "h" => MemoryLoadFileType.Hex case "b" => MemoryLoadFileType.Binary - case _ => throw new FirrtlUserException(s"Unrecognized MemoryLoadFileType: $s") + case _ => throw new FirrtlUserException(s"Unrecognized MemoryLoadFileType: $s") } } @@ -31,11 +31,11 @@ object MemoryLoadFileType { * @param hexOrBinary use `\$readmemh` or `\$readmemb` */ case class LoadMemoryAnnotation( - target: ComponentName, - fileName: String, - hexOrBinary: MemoryLoadFileType = MemoryLoadFileType.Hex, - originalMemoryNameOpt: Option[String] = None -) extends SingleTargetAnnotation[Named] { + target: ComponentName, + fileName: String, + hexOrBinary: MemoryLoadFileType = MemoryLoadFileType.Hex, + originalMemoryNameOpt: Option[String] = None) + extends SingleTargetAnnotation[Named] { val (prefix, suffix) = { fileName.split("""\.""").toList match { @@ -57,7 +57,7 @@ case class LoadMemoryAnnotation( def getPrefix: String = prefix + originalMemoryNameOpt.map(n => target.name.drop(n.length)).getOrElse("") - def getSuffix: String = suffix + def getSuffix: String = suffix def getFileName: String = getPrefix + getSuffix def duplicate(newNamed: Named): LoadMemoryAnnotation = { diff --git a/src/main/scala/firrtl/annotations/MemoryInitAnnotation.scala b/src/main/scala/firrtl/annotations/MemoryInitAnnotation.scala index 44a8e3b5..7cefdef8 100644 --- a/src/main/scala/firrtl/annotations/MemoryInitAnnotation.scala +++ b/src/main/scala/firrtl/annotations/MemoryInitAnnotation.scala @@ -5,10 +5,10 @@ package firrtl.annotations import firrtl.{MemoryArrayInit, MemoryEmissionOption, MemoryInitValue, MemoryRandomInit, MemoryScalarInit} /** - * Represents the initial value of the annotated memory. - * While not supported on normal ASIC flows, it can be useful for simulation and FPGA flows. - * This annotation is consumed by the verilog emitter. - */ + * Represents the initial value of the annotated memory. + * While not supported on normal ASIC flows, it can be useful for simulation and FPGA flows. + * This annotation is consumed by the verilog emitter. + */ sealed trait MemoryInitAnnotation extends SingleTargetAnnotation[ReferenceTarget] with MemoryEmissionOption { def isRandomInit: Boolean } @@ -16,20 +16,20 @@ sealed trait MemoryInitAnnotation extends SingleTargetAnnotation[ReferenceTarget /** Randomly initialize the `target` memory. This is the same as the default behavior. */ case class MemoryRandomInitAnnotation(target: ReferenceTarget) extends MemoryInitAnnotation { override def duplicate(n: ReferenceTarget): Annotation = copy(n) - override def initValue: MemoryInitValue = MemoryRandomInit + override def initValue: MemoryInitValue = MemoryRandomInit override def isRandomInit: Boolean = true } /** Initialize all entries of the `target` memory with the scalar `value`. */ case class MemoryScalarInitAnnotation(target: ReferenceTarget, value: BigInt) extends MemoryInitAnnotation { override def duplicate(n: ReferenceTarget): Annotation = copy(n) - override def initValue: MemoryInitValue = MemoryScalarInit(value) - override def isRandomInit: Boolean = false + override def initValue: MemoryInitValue = MemoryScalarInit(value) + override def isRandomInit: Boolean = false } /** Initialize the `target` memory with the array of `values` which must be the same size as the memory depth. */ case class MemoryArrayInitAnnotation(target: ReferenceTarget, values: Seq[BigInt]) extends MemoryInitAnnotation { override def duplicate(n: ReferenceTarget): Annotation = copy(n) - override def initValue: MemoryInitValue = MemoryArrayInit(values) - override def isRandomInit: Boolean = false -}
\ No newline at end of file + override def initValue: MemoryInitValue = MemoryArrayInit(values) + override def isRandomInit: Boolean = false +} diff --git a/src/main/scala/firrtl/annotations/PresetAnnotations.scala b/src/main/scala/firrtl/annotations/PresetAnnotations.scala index 727417c1..d6066aa7 100644 --- a/src/main/scala/firrtl/annotations/PresetAnnotations.scala +++ b/src/main/scala/firrtl/annotations/PresetAnnotations.scala @@ -10,11 +10,11 @@ package annotations * @param target ReferenceTarget to an AsyncReset */ case class PresetAnnotation(target: ReferenceTarget) - extends SingleTargetAnnotation[ReferenceTarget] with firrtl.transforms.DontTouchAllTargets { + extends SingleTargetAnnotation[ReferenceTarget] + with firrtl.transforms.DontTouchAllTargets { override def duplicate(n: ReferenceTarget) = this.copy(target = n) } - /** * Transform the targeted asynchronously-reset Reg into a bitstream preset Reg * Used internally to annotate all registers associated to an AsyncReset tree @@ -22,12 +22,10 @@ case class PresetAnnotation(target: ReferenceTarget) * @param target ReferenceTarget to a Reg */ private[firrtl] case class PresetRegAnnotation( - target: ReferenceTarget -) extends SingleTargetAnnotation[ReferenceTarget] with RegisterEmissionOption { + target: ReferenceTarget) + extends SingleTargetAnnotation[ReferenceTarget] + with RegisterEmissionOption { def duplicate(n: ReferenceTarget) = this.copy(target = n) override def useInitAsPreset = true override def disableRandomization = true } - - - diff --git a/src/main/scala/firrtl/annotations/Target.scala b/src/main/scala/firrtl/annotations/Target.scala index 4d1cdc2f..afde84dc 100644 --- a/src/main/scala/firrtl/annotations/Target.scala +++ b/src/main/scala/firrtl/annotations/Target.scala @@ -4,7 +4,7 @@ package firrtl package annotations import firrtl.ir.{Field => _, _} -import firrtl.Utils.{sub_type, field_type} +import firrtl.Utils.{field_type, sub_type} import AnnotationUtils.{toExp, validComponentName, validModuleName} import TargetToken._ @@ -29,27 +29,29 @@ sealed trait Target extends Named { def tokens: Seq[TargetToken] /** @return Returns a new [[GenericTarget]] with new values */ - def modify(circuitOpt: Option[String] = circuitOpt, - moduleOpt: Option[String] = moduleOpt, - tokens: Seq[TargetToken] = tokens): GenericTarget = GenericTarget(circuitOpt, moduleOpt, tokens.toVector) + def modify( + circuitOpt: Option[String] = circuitOpt, + moduleOpt: Option[String] = moduleOpt, + tokens: Seq[TargetToken] = tokens + ): GenericTarget = GenericTarget(circuitOpt, moduleOpt, tokens.toVector) /** @return Human-readable serialization */ def serialize: String = { val circuitString = "~" + circuitOpt.getOrElse("???") val moduleString = "|" + moduleOpt.getOrElse("???") val tokensString = tokens.map { - case Ref(r) => s">$r" - case Instance(i) => s"/$i" - case OfModule(o) => s":$o" + case Ref(r) => s">$r" + case Instance(i) => s"/$i" + case OfModule(o) => s":$o" case TargetToken.Field(f) => s".$f" - case Index(v) => s"[$v]" - case Clock => s"@clock" - case Reset => s"@reset" - case Init => s"@init" + case Index(v) => s"[$v]" + case Clock => s"@clock" + case Reset => s"@reset" + case Init => s"@init" }.mkString("") - if(moduleOpt.isEmpty && tokens.isEmpty) { + if (moduleOpt.isEmpty && tokens.isEmpty) { circuitString - } else if(tokens.isEmpty) { + } else if (tokens.isEmpty) { circuitString + moduleString } else { circuitString + moduleString + tokensString @@ -64,24 +66,23 @@ sealed trait Target extends Named { val moduleString = s"""\n$tab└── module ${moduleOpt.getOrElse("???")}:""" var depth = 4 val tokenString = tokens.map { - case Ref(r) => val rx = s"""\n$tab${" "*depth}└── $r"""; depth += 4; rx - case Instance(i) => val ix = s"""\n$tab${" "*depth}└── inst $i """; ix + case Ref(r) => val rx = s"""\n$tab${" " * depth}└── $r"""; depth += 4; rx + case Instance(i) => val ix = s"""\n$tab${" " * depth}└── inst $i """; ix case OfModule(o) => val ox = s"of $o:"; depth += 4; ox - case Field(f) => s".$f" - case Index(v) => s"[$v]" - case Clock => s"@clock" - case Reset => s"@reset" - case Init => s"@init" + case Field(f) => s".$f" + case Index(v) => s"[$v]" + case Clock => s"@clock" + case Reset => s"@reset" + case Init => s"@init" }.mkString("") (moduleOpt.isEmpty, tokens.isEmpty) match { case (true, true) => circuitString - case (_, true) => circuitString + moduleString - case (_, _) => circuitString + moduleString + tokenString + case (_, true) => circuitString + moduleString + case (_, _) => circuitString + moduleString + tokenString } } - /** @return Converts this [[Target]] into a [[GenericTarget]] */ def toGenericTarget: GenericTarget = GenericTarget(circuitOpt, moduleOpt, tokens.toVector) @@ -113,13 +114,13 @@ sealed trait Target extends Named { object Target { def asTarget(m: ModuleTarget)(e: Expression): ReferenceTarget = e match { case r: ir.Reference => m.ref(r.name) - case s: ir.SubIndex => asTarget(m)(s.expr).index(s.value) - case s: ir.SubField => asTarget(m)(s.expr).field(s.name) + case s: ir.SubIndex => asTarget(m)(s.expr).index(s.value) + case s: ir.SubField => asTarget(m)(s.expr).field(s.name) case s: ir.SubAccess => asTarget(m)(s.expr).field("@" + s.index.serialize) - case d: DoPrim => m.ref("@" + d.serialize) - case d: Mux => m.ref("@" + d.serialize) - case d: ValidIf => m.ref("@" + d.serialize) - case d: Literal => m.ref("@" + d.serialize) + case d: DoPrim => m.ref("@" + d.serialize) + case d: Mux => m.ref("@" + d.serialize) + case d: ValidIf => m.ref("@" + d.serialize) + case d: Literal => m.ref("@" + d.serialize) case other => sys.error(s"Unsupported: $other") } @@ -131,14 +132,14 @@ object Target { case class NamedException(message: String) extends Exception(message) - implicit def convertCircuitTarget2CircuitName(c: CircuitTarget): CircuitName = c.toNamed - implicit def convertModuleTarget2ModuleName(c: ModuleTarget): ModuleName = c.toNamed - implicit def convertIsComponent2ComponentName(c: IsComponent): ComponentName = c.toNamed - implicit def convertTarget2Named(c: Target): Named = c.toNamed - implicit def convertCircuitName2CircuitTarget(c: CircuitName): CircuitTarget = c.toTarget - implicit def convertModuleName2ModuleTarget(c: ModuleName): ModuleTarget = c.toTarget + implicit def convertCircuitTarget2CircuitName(c: CircuitTarget): CircuitName = c.toNamed + implicit def convertModuleTarget2ModuleName(c: ModuleTarget): ModuleName = c.toNamed + implicit def convertIsComponent2ComponentName(c: IsComponent): ComponentName = c.toNamed + implicit def convertTarget2Named(c: Target): Named = c.toNamed + implicit def convertCircuitName2CircuitTarget(c: CircuitName): CircuitTarget = c.toTarget + implicit def convertModuleName2ModuleTarget(c: ModuleName): ModuleTarget = c.toTarget implicit def convertComponentName2ReferenceTarget(c: ComponentName): ReferenceTarget = c.toTarget - implicit def convertNamed2Target(n: Named): CompleteTarget = n.toTarget + implicit def convertNamed2Target(n: Named): CompleteTarget = n.toTarget /** Converts [[ComponentName]]'s name into TargetTokens * @param name @@ -148,7 +149,7 @@ object Target { val tokens = AnnotationUtils.tokenize(name) val subComps = mutable.ArrayBuffer[TargetToken]() subComps += Ref(tokens.head) - if(tokens.tail.nonEmpty) { + if (tokens.tail.nonEmpty) { tokens.tail.zip(tokens.tail.tail).foreach { case (".", value: String) => subComps += Field(value) case ("[", value: String) => subComps += Index(value.toInt) @@ -163,31 +164,33 @@ object Target { * @param keywords * @return */ - def isOnly(seq: Seq[TargetToken], keywords:String*): Boolean = { - seq.map(_.is(keywords:_*)).foldLeft(false)(_ || _) && keywords.nonEmpty + def isOnly(seq: Seq[TargetToken], keywords: String*): Boolean = { + seq.map(_.is(keywords: _*)).foldLeft(false)(_ || _) && keywords.nonEmpty } /** @return [[Target]] from human-readable serialization */ def deserialize(s: String): Target = { val regex = """(?=[~|>/:.\[@])""" - s.split(regex).foldLeft(GenericTarget(None, None, Vector.empty)) { (t, tokenString) => - val value = tokenString.tail - tokenString(0) match { - case '~' if t.circuitOpt.isEmpty && t.moduleOpt.isEmpty && t.tokens.isEmpty => - if(value == "???") t else t.copy(circuitOpt = Some(value)) - case '|' if t.moduleOpt.isEmpty && t.tokens.isEmpty => - if(value == "???") t else t.copy(moduleOpt = Some(value)) - case '/' => t.add(Instance(value)) - case ':' => t.add(OfModule(value)) - case '>' => t.add(Ref(value)) - case '.' => t.add(Field(value)) - case '[' if value.dropRight(1).toInt >= 0 => t.add(Index(value.dropRight(1).toInt)) - case '@' if value == "clock" => t.add(Clock) - case '@' if value == "init" => t.add(Init) - case '@' if value == "reset" => t.add(Reset) - case other => throw NamedException(s"Cannot deserialize Target: $s") + s.split(regex) + .foldLeft(GenericTarget(None, None, Vector.empty)) { (t, tokenString) => + val value = tokenString.tail + tokenString(0) match { + case '~' if t.circuitOpt.isEmpty && t.moduleOpt.isEmpty && t.tokens.isEmpty => + if (value == "???") t else t.copy(circuitOpt = Some(value)) + case '|' if t.moduleOpt.isEmpty && t.tokens.isEmpty => + if (value == "???") t else t.copy(moduleOpt = Some(value)) + case '/' => t.add(Instance(value)) + case ':' => t.add(OfModule(value)) + case '>' => t.add(Ref(value)) + case '.' => t.add(Field(value)) + case '[' if value.dropRight(1).toInt >= 0 => t.add(Index(value.dropRight(1).toInt)) + case '@' if value == "clock" => t.add(Clock) + case '@' if value == "init" => t.add(Init) + case '@' if value == "reset" => t.add(Reset) + case other => throw NamedException(s"Cannot deserialize Target: $s") + } } - }.tryToComplete + .tryToComplete } /** Returns the module that a [[Target]] "refers" to. @@ -217,14 +220,16 @@ object Target { def getReferenceTarget(t: Target): Target = { (t.toGenericTarget match { case t: GenericTarget if t.isLegal => - val newTokens = t.tokens.reverse.dropWhile({ - case x: Field => true - case x: Index => true - case Clock => true - case Init => true - case Reset => true - case other => false - }).reverse + val newTokens = t.tokens.reverse + .dropWhile({ + case x: Field => true + case x: Index => true + case Clock => true + case Init => true + case Reset => true + case other => false + }) + .reverse GenericTarget(t.circuitOpt, t.moduleOpt, newTokens) case other => sys.error(s"Can't make $other pathless!") }).tryToComplete @@ -236,9 +241,8 @@ object Target { * @param moduleOpt Optional module name * @param tokens [[TargetToken]]s to represent the target in a circuit and module */ -case class GenericTarget(circuitOpt: Option[String], - moduleOpt: Option[String], - tokens: Vector[TargetToken]) extends Target { +case class GenericTarget(circuitOpt: Option[String], moduleOpt: Option[String], tokens: Vector[TargetToken]) + extends Target { override def toGenericTarget: GenericTarget = this @@ -252,11 +256,12 @@ case class GenericTarget(circuitOpt: Option[String], override def toTarget: CompleteTarget = getComplete.get override def getComplete: Option[CompleteTarget] = { - if(!isComplete) None else { + if (!isComplete) None + else { val target = this match { - case GenericTarget(Some(c), None, Vector()) => CircuitTarget(c) - case GenericTarget(Some(c), Some(m), Vector()) => ModuleTarget(c, m) - case GenericTarget(Some(c), Some(m), Ref(r) +: component) => ReferenceTarget(c, m, Nil, r, component) + case GenericTarget(Some(c), None, Vector()) => CircuitTarget(c) + case GenericTarget(Some(c), Some(m), Vector()) => ModuleTarget(c, m) + case GenericTarget(Some(c), Some(m), Ref(r) +: component) => ReferenceTarget(c, m, Nil, r, component) case GenericTarget(Some(c), Some(m), Instance(i) +: OfModule(o) +: Vector()) => InstanceTarget(c, m, Nil, i, o) case GenericTarget(Some(c), Some(m), component) => val path = getPath.getOrElse(Nil) @@ -271,7 +276,7 @@ case class GenericTarget(circuitOpt: Option[String], override def isLocal: Boolean = !(getPath.nonEmpty && getPath.get.nonEmpty) - def path: Vector[(Instance, OfModule)] = if(isComplete){ + def path: Vector[(Instance, OfModule)] = if (isComplete) { tokens.zip(tokens.tail).collect { case (i: Instance, o: OfModule) => (i, o) } @@ -280,9 +285,9 @@ case class GenericTarget(circuitOpt: Option[String], /** If complete, return this [[GenericTarget]]'s path * @return */ - def getPath: Option[Seq[(Instance, OfModule)]] = if(isComplete) { - val allInstOfs = tokens.grouped(2).collect { case Seq(i: Instance, o:OfModule) => (i, o)}.toSeq - if(tokens.nonEmpty && tokens.last.isInstanceOf[OfModule]) Some(allInstOfs.dropRight(1)) else Some(allInstOfs) + def getPath: Option[Seq[(Instance, OfModule)]] = if (isComplete) { + val allInstOfs = tokens.grouped(2).collect { case Seq(i: Instance, o: OfModule) => (i, o) }.toSeq + if (tokens.nonEmpty && tokens.last.isInstanceOf[OfModule]) Some(allInstOfs.dropRight(1)) else Some(allInstOfs) } else { None } @@ -290,7 +295,7 @@ case class GenericTarget(circuitOpt: Option[String], /** If complete and a reference, return the reference and subcomponents * @return */ - def getRef: Option[(String, Seq[TargetToken])] = if(isComplete) { + 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 ((r: Some[String], comps), c) => (r, comps :+ c) @@ -304,7 +309,7 @@ case class GenericTarget(circuitOpt: Option[String], /** If complete and an instance target, return the instance and ofmodule * @return */ - def getInstanceOf: Option[(String, String)] = if(isComplete) { + 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 @@ -328,14 +333,14 @@ case class GenericTarget(circuitOpt: Option[String], */ def add(token: TargetToken): GenericTarget = { token match { - case _: Instance => requireLast(true, "inst", "of") - case _: OfModule => requireLast(false, "inst") - case _: Ref => requireLast(true, "inst", "of") - case _: Field => requireLast(true, "ref", "[]", ".", "init", "clock", "reset") - case _: Index => requireLast(true, "ref", "[]", ".", "init", "clock", "reset") - case Init => requireLast(true, "ref", "[]", ".", "init", "clock", "reset") - case Clock => requireLast(true, "ref", "[]", ".", "init", "clock", "reset") - case Reset => requireLast(true, "ref", "[]", ".", "init", "clock", "reset") + case _: Instance => requireLast(true, "inst", "of") + case _: OfModule => requireLast(false, "inst") + case _: Ref => requireLast(true, "inst", "of") + case _: Field => requireLast(true, "ref", "[]", ".", "init", "clock", "reset") + case _: Index => requireLast(true, "ref", "[]", ".", "init", "clock", "reset") + case Init => requireLast(true, "ref", "[]", ".", "init", "clock", "reset") + case Clock => requireLast(true, "ref", "[]", ".", "init", "clock", "reset") + case Reset => requireLast(true, "ref", "[]", ".", "init", "clock", "reset") } this.copy(tokens = tokens :+ token) } @@ -345,7 +350,7 @@ case class GenericTarget(circuitOpt: Option[String], /** Optionally tries to append token to tokens, fails return is not a legal Target */ def optAdd(token: TargetToken): Option[Target] = { - try{ + try { Some(add(token)) } catch { case _: IllegalArgumentException => None @@ -358,7 +363,7 @@ case class GenericTarget(circuitOpt: Option[String], def isLegal: Boolean = { try { var comp: GenericTarget = this.copy(tokens = Vector.empty) - for(token <- tokens) { + for (token <- tokens) { comp = comp.add(token) } true @@ -374,19 +379,18 @@ case class GenericTarget(circuitOpt: Option[String], def isComplete: Boolean = { isLegal && (isCircuitTarget || isModuleTarget || (isComponentTarget && tokens.tails.forall { case Instance(_) +: OfModule(_) +: tail => true - case Instance(_) +: x +: tail => false - case x +: OfModule(_) +: tail => false - case _ => true - } )) + case Instance(_) +: x +: tail => false + case x +: OfModule(_) +: tail => false + case _ => true + })) } - - def isCircuitTarget: Boolean = circuitOpt.nonEmpty && moduleOpt.isEmpty && tokens.isEmpty - def isModuleTarget: Boolean = circuitOpt.nonEmpty && moduleOpt.nonEmpty && tokens.isEmpty + def isCircuitTarget: Boolean = circuitOpt.nonEmpty && moduleOpt.isEmpty && tokens.isEmpty + def isModuleTarget: Boolean = circuitOpt.nonEmpty && moduleOpt.nonEmpty && tokens.isEmpty def isComponentTarget: Boolean = circuitOpt.nonEmpty && moduleOpt.nonEmpty && tokens.nonEmpty lazy val (parentModule: Option[String], astModule: Option[String]) = path match { - case Seq() => (None, moduleOpt) + case Seq() => (None, moduleOpt) case Seq((i, OfModule(o))) => (moduleOpt, Some(o)) case seq if seq.size > 1 => val reversed = seq.reverse @@ -421,7 +425,6 @@ trait CompleteTarget extends Target { override def toString: String = serialize } - /** A member of a FIRRTL Circuit (e.g. cannot point to a CircuitTarget) * Concrete Subclasses are: [[ModuleTarget]], [[InstanceTarget]], and [[ReferenceTarget]] */ @@ -456,10 +459,12 @@ 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)) - }._2 + path + .foldLeft((module, Vector.empty[InstanceTarget])) { + case ((m, vec), (Instance(i), OfModule(o))) => + (o, vec :+ InstanceTarget(circuit, m, Nil, i, o)) + } + ._2 } /** Resets this target to have a new path @@ -469,7 +474,7 @@ trait IsMember extends CompleteTarget { def setPathTarget(newPath: IsModule): CompleteTarget /** @return The [[ModuleTarget]] of the module that directly contains this component */ - def encapsulatingModule: String = if(path.isEmpty) module else path.last._2.value + def encapsulatingModule: String = if (path.isEmpty) module else path.last._2.value def encapsulatingModuleTarget: ModuleTarget = ModuleTarget(circuit, encapsulatingModule) @@ -492,6 +497,7 @@ trait IsModule extends IsMember { /** A component of a FIRRTL Module (e.g. cannot point to a CircuitTarget or ModuleTarget) */ trait IsComponent extends IsMember { + /** Removes n levels of instance hierarchy * * Example: n=1, transforms (Top, A)/b:B/c:C -> (Top, B)/c:C @@ -501,13 +507,13 @@ trait IsComponent extends IsMember { def stripHierarchy(n: Int): IsMember override def toNamed: ComponentName = { - if(isLocal){ + if (isLocal) { val mn = ModuleName(module, CircuitName(circuit)) - Seq(tokens:_*) match { + Seq(tokens: _*) match { case Seq(Ref(name)) => ComponentName(name, mn) case Ref(_) :: tail if Target.isOnly(tail, ".", "[]") => - val name = tokens.foldLeft(""){ - case ("", Ref(name)) => name + val name = tokens.foldLeft("") { + case ("", Ref(name)) => name case (string, Field(value)) => s"$string.$value" case (string, Index(value)) => s"$string[$value]" } @@ -524,7 +530,8 @@ trait IsComponent extends IsMember { } override def pathTarget: IsModule = { - if(path.isEmpty) moduleTarget else { + if (path.isEmpty) moduleTarget + else { val (i, o) = path.last InstanceTarget(circuit, module, path.dropRight(1), i.value, o.value) } @@ -535,7 +542,6 @@ trait IsComponent extends IsMember { override def isLocal = path.isEmpty } - /** Target pointing to a FIRRTL [[firrtl.ir.Circuit]] * @param circuit Name of a FIRRTL circuit */ @@ -577,7 +583,8 @@ case class ModuleTarget(circuit: String, module: String) extends IsModule { override def targetParent: CircuitTarget = CircuitTarget(circuit) - override def addHierarchy(root: String, instance: String): InstanceTarget = InstanceTarget(circuit, root, Nil, instance, module) + override def addHierarchy(root: String, instance: String): InstanceTarget = + InstanceTarget(circuit, root, Nil, instance, module) override def ref(value: String): ReferenceTarget = ReferenceTarget(circuit, module, Nil, value, Nil) @@ -613,11 +620,13 @@ case class ModuleTarget(circuit: String, module: String) extends IsModule { * @param ref Name of component * @param component Subcomponent of this reference, e.g. field or index */ -case class ReferenceTarget(circuit: String, - module: String, - override val path: Seq[(Instance, OfModule)], - ref: String, - component: Seq[TargetToken]) extends IsComponent { +case class ReferenceTarget( + circuit: String, + module: String, + override val path: Seq[(Instance, OfModule)], + ref: String, + component: Seq[TargetToken]) + extends IsComponent { /** @param value Index value of this target * @return A new [[ReferenceTarget]] to the specified index of this [[ReferenceTarget]] @@ -648,7 +657,7 @@ case class ReferenceTarget(circuit: String, baseType } else { val headType = tokens.head match { - case Index(idx) => sub_type(baseType) + case Index(idx) => sub_type(baseType) case Field(field) => field_type(baseType, field) case _: Ref => baseType } @@ -662,7 +671,8 @@ case class ReferenceTarget(circuit: String, override def targetParent: CompleteTarget = component match { case Nil => - if(path.isEmpty) moduleTarget else { + if (path.isEmpty) moduleTarget + else { val (i, o) = path.last InstanceTarget(circuit, module, path.dropRight(1), i.value, o.value) } @@ -676,7 +686,8 @@ case class ReferenceTarget(circuit: String, override def stripHierarchy(n: Int): ReferenceTarget = { require(path.size >= n, s"Cannot strip $n levels of hierarchy from $this") - if(n == 0) this else { + if (n == 0) this + else { val newModule = path(n - 1)._2.value ReferenceTarget(circuit, newModule, path.drop(n), ref, component) } @@ -700,15 +711,15 @@ case class ReferenceTarget(circuit: String, def leafSubTargets(tpe: firrtl.ir.Type): Seq[ReferenceTarget] = tpe match { case _: firrtl.ir.GroundType => Vector(this) case firrtl.ir.VectorType(t, size) => (0 until size).flatMap { i => index(i).leafSubTargets(t) } - case firrtl.ir.BundleType(fields) => fields.flatMap { f => field(f.name).leafSubTargets(f.tpe)} - case other => sys.error(s"Error! Unexpected type $other") + case firrtl.ir.BundleType(fields) => fields.flatMap { f => field(f.name).leafSubTargets(f.tpe) } + case other => sys.error(s"Error! Unexpected type $other") } def allSubTargets(tpe: firrtl.ir.Type): Seq[ReferenceTarget] = tpe match { case _: firrtl.ir.GroundType => Vector(this) case firrtl.ir.VectorType(t, size) => this +: (0 until size).flatMap { i => index(i).allSubTargets(t) } - case firrtl.ir.BundleType(fields) => this +: fields.flatMap { f => field(f.name).allSubTargets(f.tpe)} - case other => sys.error(s"Error! Unexpected type $other") + case firrtl.ir.BundleType(fields) => this +: fields.flatMap { f => field(f.name).allSubTargets(f.tpe) } + case other => sys.error(s"Error! Unexpected type $other") } override def leafModule: String = encapsulatingModule @@ -721,11 +732,14 @@ case class ReferenceTarget(circuit: String, * @param instance Name of the instance * @param ofModule Name of the instance's module */ -case class InstanceTarget(circuit: String, - module: String, - override val path: Seq[(Instance, OfModule)], - instance: String, - ofModule: String) extends IsModule with IsComponent { +case class InstanceTarget( + circuit: String, + module: String, + override val path: Seq[(Instance, OfModule)], + instance: String, + ofModule: String) + extends IsModule + with IsComponent { /** @return a [[ReferenceTarget]] referring to this declaration of this instance */ def asReference: ReferenceTarget = ReferenceTarget(circuit, module, path, instance, Nil) @@ -744,7 +758,8 @@ case class InstanceTarget(circuit: String, override def moduleOpt: Option[String] = Some(module) override def targetParent: IsModule = { - if(isLocal) ModuleTarget(circuit, module) else { + if (isLocal) ModuleTarget(circuit, module) + else { val (newInstance, newOfModule) = path.last InstanceTarget(circuit, module, path.dropRight(1), newInstance.value, newOfModule.value) } @@ -759,8 +774,9 @@ case class InstanceTarget(circuit: String, override def stripHierarchy(n: Int): IsModule = { require(path.size + 1 >= n, s"Cannot strip $n levels of hierarchy from $this") - if(n == 0) this else { - if(path.size < n){ + if (n == 0) this + else { + if (path.size < n) { ModuleTarget(circuit, ofModule) } else { val newModule = path(n - 1)._2.value @@ -769,7 +785,7 @@ case class InstanceTarget(circuit: String, } } - override def asPath: Seq[(Instance, OfModule)] = path :+( (Instance(instance), OfModule(ofModule)) ) + override def asPath: Seq[(Instance, OfModule)] = path :+ ((Instance(instance), OfModule(ofModule))) override def pathlessTarget: InstanceTarget = InstanceTarget(circuit, encapsulatingModule, Nil, instance, ofModule) @@ -781,33 +797,32 @@ case class InstanceTarget(circuit: String, override def leafModule: String = ofModule } - /** Named classes associate an annotation with a component in a Firrtl circuit */ sealed trait Named { def serialize: String - def toTarget: CompleteTarget + def toTarget: CompleteTarget } final case class CircuitName(name: String) extends Named { - if(!validModuleName(name)) throw AnnotationException(s"Illegal circuit name: $name") + if (!validModuleName(name)) throw AnnotationException(s"Illegal circuit name: $name") def serialize: String = name - def toTarget: CircuitTarget = CircuitTarget(name) + def toTarget: CircuitTarget = CircuitTarget(name) } final case class ModuleName(name: String, circuit: CircuitName) extends Named { - if(!validModuleName(name)) throw AnnotationException(s"Illegal module name: $name") + if (!validModuleName(name)) throw AnnotationException(s"Illegal module name: $name") def serialize: String = circuit.serialize + "." + name - def toTarget: ModuleTarget = ModuleTarget(circuit.name, name) + def toTarget: ModuleTarget = ModuleTarget(circuit.name, name) } final case class ComponentName(name: String, module: ModuleName) extends Named { - if(!validComponentName(name)) throw AnnotationException(s"Illegal component name: $name") - def expr: Expression = toExp(name) + if (!validComponentName(name)) throw AnnotationException(s"Illegal component name: $name") + def expr: Expression = toExp(name) def serialize: String = module.serialize + "." + name def toTarget: ReferenceTarget = { Target.toTargetTokens(name).toList match { case Ref(r) :: components => ReferenceTarget(module.circuit.name, module.name, Nil, r, components) - case other => throw Target.NamedException(s"Cannot convert $this into [[ReferenceTarget]]: $other") + case other => throw Target.NamedException(s"Cannot convert $this into [[ReferenceTarget]]: $other") } } } diff --git a/src/main/scala/firrtl/annotations/TargetToken.scala b/src/main/scala/firrtl/annotations/TargetToken.scala index 765102a6..a4a98eed 100644 --- a/src/main/scala/firrtl/annotations/TargetToken.scala +++ b/src/main/scala/firrtl/annotations/TargetToken.scala @@ -3,12 +3,12 @@ package firrtl.annotations import firrtl._ -import ir.{DefModule, DefInstance} +import ir.{DefInstance, DefModule} /** Building block to represent a [[Target]] of a FIRRTL component */ sealed trait TargetToken { def keyword: String - def value: Any + def value: Any /** Returns whether this token is one of the type of tokens whose keyword is passed as an argument * @param keywords @@ -16,8 +16,10 @@ sealed trait TargetToken { */ def is(keywords: String*): Boolean = { keywords.map { kw => - require(TargetToken.keyword2targettoken.keySet.contains(kw), - s"Keyword $kw must be in set ${TargetToken.keyword2targettoken.keys}") + require( + TargetToken.keyword2targettoken.keySet.contains(kw), + s"Keyword $kw must be in set ${TargetToken.keyword2targettoken.keys}" + ) val lastClass = this.getClass lastClass == TargetToken.keyword2targettoken(kw)("0").getClass }.reduce(_ || _) @@ -26,20 +28,20 @@ sealed trait TargetToken { /** Object containing all [[TargetToken]] subclasses */ case object TargetToken { - case class Instance(value: String) extends TargetToken { override def keyword: String = "inst" } - case class OfModule(value: String) extends TargetToken { override def keyword: String = "of" } - case class Ref(value: String) extends TargetToken { override def keyword: String = "ref" } - case class Index(value: Int) extends TargetToken { override def keyword: String = "[]" } - case class Field(value: String) extends TargetToken { override def keyword: String = "." } - case object Clock extends TargetToken { override def keyword: String = "clock"; val value = "" } - case object Init extends TargetToken { override def keyword: String = "init"; val value = "" } - case object Reset extends TargetToken { override def keyword: String = "reset"; val value = "" } + case class Instance(value: String) extends TargetToken { override def keyword: String = "inst" } + case class OfModule(value: String) extends TargetToken { override def keyword: String = "of" } + case class Ref(value: String) extends TargetToken { override def keyword: String = "ref" } + case class Index(value: Int) extends TargetToken { override def keyword: String = "[]" } + case class Field(value: String) extends TargetToken { override def keyword: String = "." } + case object Clock extends TargetToken { override def keyword: String = "clock"; val value = "" } + case object Init extends TargetToken { override def keyword: String = "init"; val value = "" } + case object Reset extends TargetToken { override def keyword: String = "reset"; val value = "" } implicit class fromStringToTargetToken(s: String) { def Instance: Instance = new TargetToken.Instance(s) def OfModule: OfModule = new TargetToken.OfModule(s) - def Ref: Ref = new TargetToken.Ref(s) - def Field: Field = new TargetToken.Field(s) + def Ref: Ref = new TargetToken.Ref(s) + def Field: Field = new TargetToken.Field(s) } implicit class fromIntToTargetToken(i: Int) { @@ -67,4 +69,3 @@ case object TargetToken { "reset" -> ((value: String) => Reset) ) } - diff --git a/src/main/scala/firrtl/annotations/analysis/DuplicationHelper.scala b/src/main/scala/firrtl/annotations/analysis/DuplicationHelper.scala index 8f925ee7..31d13139 100644 --- a/src/main/scala/firrtl/annotations/analysis/DuplicationHelper.scala +++ b/src/main/scala/firrtl/annotations/analysis/DuplicationHelper.scala @@ -88,10 +88,12 @@ case class DuplicationHelper(existingModules: Set[String]) { * @param originalOfModule original module being instantiated in originalModule * @return */ - def getNewOfModule(originalModule: String, - newModule: String, - instance: Instance, - originalOfModule: OfModule): OfModule = { + def getNewOfModule( + originalModule: String, + newModule: String, + instance: Instance, + originalOfModule: OfModule + ): OfModule = { dupMap.get(originalModule) match { case None => // No duplication, can return originalOfModule originalOfModule @@ -129,18 +131,18 @@ case class DuplicationHelper(existingModules: Set[String]) { val newTops = getDuplicates(top) newTops.map { newTop => val newPath = mutable.ArrayBuffer[TargetToken]() - path.foldLeft((top, newTop)) { case ((originalModule, newModule), (instance, ofModule)) => - val newOfModule = getNewOfModule(originalModule, newModule, instance, ofModule) - newPath ++= Seq(instance, newOfModule) - (ofModule.value, newOfModule.value) + path.foldLeft((top, newTop)) { + case ((originalModule, newModule), (instance, ofModule)) => + val newOfModule = getNewOfModule(originalModule, newModule, instance, ofModule) + newPath ++= Seq(instance, newOfModule) + (ofModule.value, newOfModule.value) } - val module = if(newPath.nonEmpty) newPath.last.value.toString else newTop + val module = if (newPath.nonEmpty) newPath.last.value.toString else newTop t.notPath match { - case Seq() => ModuleTarget(t.circuit, module) + case Seq() => ModuleTarget(t.circuit, module) case Instance(i) +: OfModule(m) +: Seq() => ModuleTarget(t.circuit, module) - case Ref(r) +: components => ReferenceTarget(t.circuit, module, Nil, r, components) + case Ref(r) +: components => ReferenceTarget(t.circuit, module, Nil, r, components) } }.toSeq } } - diff --git a/src/main/scala/firrtl/annotations/transforms/CleanupNamedTargets.scala b/src/main/scala/firrtl/annotations/transforms/CleanupNamedTargets.scala index a4219a03..20304378 100644 --- a/src/main/scala/firrtl/annotations/transforms/CleanupNamedTargets.scala +++ b/src/main/scala/firrtl/annotations/transforms/CleanupNamedTargets.scala @@ -27,19 +27,25 @@ class CleanupNamedTargets extends Transform with DependencyAPIMigration { override def invalidates(a: Transform) = false - private def onStatement(statement: ir.Statement) - (implicit references: ISet[ReferenceTarget], - renameMap: RenameMap, - module: ModuleTarget): Unit = statement match { + private def onStatement( + statement: ir.Statement + )( + implicit references: ISet[ReferenceTarget], + renameMap: RenameMap, + module: ModuleTarget + ): Unit = statement match { case ir.DefInstance(_, a, b, _) if references(module.instOf(a, b).asReference) => renameMap.record(module.instOf(a, b).asReference, module.instOf(a, b)) case a => statement.foreach(onStatement) } - private def onModule(module: ir.DefModule) - (implicit references: ISet[ReferenceTarget], - renameMap: RenameMap, - circuit: CircuitTarget): Unit = { + private def onModule( + module: ir.DefModule + )( + implicit references: ISet[ReferenceTarget], + renameMap: RenameMap, + circuit: CircuitTarget + ): Unit = { implicit val mTarget = circuit.module(module.name) module.foreach(onStatement) } @@ -49,7 +55,7 @@ class CleanupNamedTargets extends Transform with DependencyAPIMigration { implicit val rTargets: ISet[ReferenceTarget] = state.annotations.flatMap { case a: SingleTargetAnnotation[_] => Some(a.target) case a: MultiTargetAnnotation => a.targets.flatten - case _ => None + case _ => None }.collect { case a: ReferenceTarget => a }.toSet diff --git a/src/main/scala/firrtl/annotations/transforms/EliminateTargetPaths.scala b/src/main/scala/firrtl/annotations/transforms/EliminateTargetPaths.scala index d92d3b5e..596a344f 100644 --- a/src/main/scala/firrtl/annotations/transforms/EliminateTargetPaths.scala +++ b/src/main/scala/firrtl/annotations/transforms/EliminateTargetPaths.scala @@ -5,7 +5,7 @@ package firrtl.annotations.transforms import firrtl.Mappers._ import firrtl.analyses.InstanceKeyGraph import firrtl.annotations.ModuleTarget -import firrtl.annotations.TargetToken.{Instance, OfModule, fromDefModuleToTargetToken} +import firrtl.annotations.TargetToken.{fromDefModuleToTargetToken, Instance, OfModule} import firrtl.annotations.analysis.DuplicationHelper import firrtl.annotations._ import firrtl.ir._ @@ -15,7 +15,6 @@ import firrtl.transforms.DedupedResult import scala.collection.mutable - /** Group of targets that should become local targets * @param targets */ @@ -36,7 +35,7 @@ case class DupedResult(newModules: Set[IsModule], originalModule: ModuleTarget) override def duplicate(n: Seq[Seq[Target]]): Annotation = { n.toList match { case Seq(newMods) => DupedResult(newMods.collect { case x: IsModule => x }.toSet, originalModule) - case _ => DupedResult(Set.empty, originalModule) + case _ => DupedResult(Set.empty, originalModule) } } } @@ -47,35 +46,35 @@ object EliminateTargetPaths { def renameModules(c: Circuit, toRename: Map[String, String], renameMap: RenameMap): Circuit = { val ct = CircuitTarget(c.main) - val cx = if(toRename.contains(c.main)) { + val cx = if (toRename.contains(c.main)) { renameMap.record(ct, CircuitTarget(toRename(c.main))) c.copy(main = toRename(c.main)) } else { c } def onMod(m: DefModule): DefModule = { - m map onStmt match { + m.map(onStmt) match { case e: ExtModule if toRename.contains(e.name) => renameMap.record(ct.module(e.name), ct.module(toRename(e.name))) e.copy(name = toRename(e.name)) - case e: Module if toRename.contains(e.name) => + case e: Module if toRename.contains(e.name) => renameMap.record(ct.module(e.name), ct.module(toRename(e.name))) e.copy(name = toRename(e.name)) case o => o } } - def onStmt(s: Statement): Statement = s map onStmt match { - case w@DefInstance(info, name, module, _) if toRename.contains(module) => w.copy(module = toRename(module)) - case other => other + def onStmt(s: Statement): Statement = s.map(onStmt) match { + case w @ DefInstance(info, name, module, _) if toRename.contains(module) => w.copy(module = toRename(module)) + case other => other } - cx map onMod + cx.map(onMod) } def reorderModules(c: Circuit, toReorder: Map[String, Double]): Circuit = { val newOrderMap = c.modules.zipWithIndex.map { case (m, _) if toReorder.contains(m.name) => m.name -> toReorder(m.name) - case (m, i) if c.modules.size > 1 => m.name -> i.toDouble / (c.modules.size - 1) - case (m, _) => m.name -> 1.0 + case (m, i) if c.modules.size > 1 => m.name -> i.toDouble / (c.modules.size - 1) + case (m, _) => m.name -> 1.0 }.toMap val newOrder = c.modules.sortBy { m => newOrderMap(m.name) } @@ -83,7 +82,6 @@ object EliminateTargetPaths { c.copy(modules = newOrder) } - } /** For a set of non-local targets, modify the instance/module hierarchy of the circuit such that @@ -116,24 +114,20 @@ class EliminateTargetPaths extends Transform with DependencyAPIMigration { * @param s * @return */ - private def onStmt(dupMap: DuplicationHelper) - (originalModule: String, newModule: String) - (s: Statement): Statement = s match { - case d@DefInstance(_, name, module, _) => - val ofModule = dupMap.getNewOfModule(originalModule, newModule, Instance(name), OfModule(module)).value - d.copy(module = ofModule) - case other => other map onStmt(dupMap)(originalModule, newModule) - } + private def onStmt(dupMap: DuplicationHelper)(originalModule: String, newModule: String)(s: Statement): Statement = + s match { + case d @ DefInstance(_, name, module, _) => + val ofModule = dupMap.getNewOfModule(originalModule, newModule, Instance(name), OfModule(module)).value + d.copy(module = ofModule) + case other => other.map(onStmt(dupMap)(originalModule, newModule)) + } /** Returns a modified circuit and [[RenameMap]] containing the associated target remapping * @param cir * @param targets * @return */ - def run(cir: Circuit, - targets: Seq[IsMember], - iGraph: InstanceKeyGraph - ): (Circuit, RenameMap, AnnotationSeq) = { + def run(cir: Circuit, targets: Seq[IsMember], iGraph: InstanceKeyGraph): (Circuit, RenameMap, AnnotationSeq) = { val dupMap = DuplicationHelper(cir.modules.map(_.name).toSet) @@ -161,7 +155,7 @@ class EliminateTargetPaths extends Transform with DependencyAPIMigration { } val finalModuleList = duplicatedModuleList - lazy val finalModuleSet = finalModuleList.map{ case a: DefModule => a.name }.toSet + lazy val finalModuleSet = finalModuleList.map { case a: DefModule => a.name }.toSet // Records how targets have been renamed val renameMap = RenameMap() @@ -203,8 +197,9 @@ class EliminateTargetPaths extends Transform with DependencyAPIMigration { duplicatedParents.foreach { parent => val paths = iGraph.findInstancesInHierarchy(parent.value) val newTargets = paths.map { path => - path.tail.foldLeft(topMod: IsModule) { case (mod, wDefInst) => - mod.instOf(wDefInst.name, wDefInst.module) + path.tail.foldLeft(topMod: IsModule) { + case (mod, wDefInst) => + mod.instOf(wDefInst.name, wDefInst.module) } } newTargets.foreach(addSelfRecord(_)) @@ -219,13 +214,11 @@ class EliminateTargetPaths extends Transform with DependencyAPIMigration { val (remainingAnnotations, targetsToEliminate, previouslyDeduped) = state.annotations.foldLeft( - ( Vector.empty[Annotation], - Seq.empty[CompleteTarget], - Map.empty[IsModule, (ModuleTarget, Double)] - ) - ) { case ((remainingAnnos, targets, dedupedResult), anno) => + (Vector.empty[Annotation], Seq.empty[CompleteTarget], Map.empty[IsModule, (ModuleTarget, Double)]) + ) { + case ((remainingAnnos, targets, dedupedResult), anno) => anno match { - case ResolvePaths(ts) => + case ResolvePaths(ts) => (remainingAnnos, ts ++ targets, dedupedResult) case DedupedResult(orig, dups, idx) if dups.nonEmpty => (remainingAnnos, targets, dedupedResult ++ dups.map(_ -> (orig, idx)).toMap) @@ -234,29 +227,29 @@ class EliminateTargetPaths extends Transform with DependencyAPIMigration { } } - // Collect targets that are not local val targets = targetsToEliminate.collect { case x: IsMember => x } // Check validity of paths in targets val iGraph = InstanceKeyGraph(state.circuit) - val instanceOfModules = iGraph.getChildInstances.map { case(k,v) => k -> v.map(_.toTokens) }.toMap + val instanceOfModules = iGraph.getChildInstances.map { case (k, v) => k -> v.map(_.toTokens) }.toMap val targetsWithInvalidPaths = mutable.ArrayBuffer[IsMember]() targets.foreach { t => val path = t match { - case _: ModuleTarget => Nil - case i: InstanceTarget => i.asPath + case _: ModuleTarget => Nil + case i: InstanceTarget => i.asPath case r: ReferenceTarget => r.path } - path.foldLeft(t.module) { case (module, (inst: Instance, of: OfModule)) => - val childrenOpt = instanceOfModules.get(module) - if(childrenOpt.isEmpty || !childrenOpt.get.contains((inst, of))) { - targetsWithInvalidPaths += t - } - of.value + path.foldLeft(t.module) { + case (module, (inst: Instance, of: OfModule)) => + val childrenOpt = instanceOfModules.get(module) + if (childrenOpt.isEmpty || !childrenOpt.get.contains((inst, of))) { + targetsWithInvalidPaths += t + } + of.value } } - if(targetsWithInvalidPaths.nonEmpty) { + if (targetsWithInvalidPaths.nonEmpty) { val string = targetsWithInvalidPaths.mkString(",") throw NoSuchTargetException(s"""Some targets have illegal paths that cannot be resolved/eliminated: $string""") } @@ -292,7 +285,7 @@ class EliminateTargetPaths extends Transform with DependencyAPIMigration { } val newTarget = t match { case r: ReferenceTarget => r.setPathTarget(newIsModule) - case i: InstanceTarget => newIsModule + case i: InstanceTarget => newIsModule } firstRenameMap.record(t, Seq(newTarget)) newTarget +: acc @@ -312,10 +305,10 @@ class EliminateTargetPaths extends Transform with DependencyAPIMigration { } val iGraphx = InstanceKeyGraph(newCircuit) - val newlyUnreachableModules = iGraphx.unreachableModules.toSet diff iGraph.unreachableModules.toSet + val newlyUnreachableModules = iGraphx.unreachableModules.toSet.diff(iGraph.unreachableModules.toSet) val newCircuitGC = { - val modulesx = newCircuit.modules.flatMap{ + val modulesx = newCircuit.modules.flatMap { case dead if newlyUnreachableModules(dead.OfModule) => None case live => val m = CircuitTarget(newCircuit.main).module(live.name) @@ -338,7 +331,8 @@ class EliminateTargetPaths extends Transform with DependencyAPIMigration { val renamedCircuit = renameModules(newCircuitGC, newModuleNameMapping, renamedModuleMap) - val reorderedCircuit = reorderModules(renamedCircuit, + val reorderedCircuit = reorderModules( + renamedCircuit, previouslyDeduped.map { case (current: IsModule, (orig: ModuleTarget, idx)) => orig.name -> idx |
