aboutsummaryrefslogtreecommitdiff
path: root/src/main/scala/firrtl/options
diff options
context:
space:
mode:
authorchick2020-08-14 19:47:53 -0700
committerJack Koenig2020-08-14 19:47:53 -0700
commit6fc742bfaf5ee508a34189400a1a7dbffe3f1cac (patch)
tree2ed103ee80b0fba613c88a66af854ae9952610ce /src/main/scala/firrtl/options
parentb516293f703c4de86397862fee1897aded2ae140 (diff)
All of src/ formatted with scalafmt
Diffstat (limited to 'src/main/scala/firrtl/options')
-rw-r--r--src/main/scala/firrtl/options/DependencyManager.scala181
-rw-r--r--src/main/scala/firrtl/options/ExitCodes.scala2
-rw-r--r--src/main/scala/firrtl/options/OptionParser.scala15
-rw-r--r--src/main/scala/firrtl/options/Phase.scala30
-rw-r--r--src/main/scala/firrtl/options/Registration.scala28
-rw-r--r--src/main/scala/firrtl/options/Shell.scala19
-rw-r--r--src/main/scala/firrtl/options/Stage.scala11
-rw-r--r--src/main/scala/firrtl/options/StageAnnotations.scala21
-rw-r--r--src/main/scala/firrtl/options/StageOptions.scala28
-rw-r--r--src/main/scala/firrtl/options/StageUtils.scala10
-rw-r--r--src/main/scala/firrtl/options/package.scala7
-rw-r--r--src/main/scala/firrtl/options/phases/AddDefaults.scala2
-rw-r--r--src/main/scala/firrtl/options/phases/Checks.scala15
-rw-r--r--src/main/scala/firrtl/options/phases/GetIncludes.scala5
-rw-r--r--src/main/scala/firrtl/options/phases/WriteOutputAnnotations.scala12
15 files changed, 212 insertions, 174 deletions
diff --git a/src/main/scala/firrtl/options/DependencyManager.scala b/src/main/scala/firrtl/options/DependencyManager.scala
index ee6a7404..561e32ab 100644
--- a/src/main/scala/firrtl/options/DependencyManager.scala
+++ b/src/main/scala/firrtl/options/DependencyManager.scala
@@ -3,7 +3,7 @@
package firrtl.options
import firrtl.AnnotationSeq
-import firrtl.graph.{DiGraph, CyclicException}
+import firrtl.graph.{CyclicException, DiGraph}
import scala.collection.Set
import scala.collection.immutable.{Set => ISet}
@@ -22,7 +22,6 @@ trait DependencyManager[A, B <: TransformLike[A] with DependencyAPI[B]] extends
override def prerequisites = currentState
-
override def optionalPrerequisites = Seq.empty
override def optionalPrerequisiteOf = Seq.empty
@@ -34,13 +33,13 @@ trait DependencyManager[A, B <: TransformLike[A] with DependencyAPI[B]] extends
*/
def targets: Seq[Dependency[B]]
private lazy val _targets: LinkedHashSet[Dependency[B]] = targets
- .foldLeft(new LinkedHashSet[Dependency[B]]()){ case (a, b) => a += b }
+ .foldLeft(new LinkedHashSet[Dependency[B]]()) { case (a, b) => a += b }
/** A sequence of [[firrtl.Transform]]s that have been run. Internally, this will be converted to an ordered set.
*/
def currentState: Seq[Dependency[B]]
private lazy val _currentState: LinkedHashSet[Dependency[B]] = currentState
- .foldLeft(new LinkedHashSet[Dependency[B]]()){ case (a, b) => a += b }
+ .foldLeft(new LinkedHashSet[Dependency[B]]()) { case (a, b) => a += b }
/** Existing transform objects that have already been constructed */
def knownObjects: Set[B]
@@ -64,9 +63,10 @@ trait DependencyManager[A, B <: TransformLike[A] with DependencyAPI[B]] extends
* requirements. This is used to solve sub-problems arising from invalidations.
*/
protected def copy(
- targets: Seq[Dependency[B]],
+ targets: Seq[Dependency[B]],
currentState: Seq[Dependency[B]],
- knownObjects: ISet[B] = dependencyToObject.values.toSet): B
+ knownObjects: ISet[B] = dependencyToObject.values.toSet
+ ): B
/** Implicit conversion from Dependency to B */
private implicit def dToO(d: Dependency[B]): B = dependencyToObject.getOrElseUpdate(d, d.getObject())
@@ -77,14 +77,16 @@ trait DependencyManager[A, B <: TransformLike[A] with DependencyAPI[B]] extends
/** Modified breadth-first search that supports multiple starting nodes and a custom extractor that can be used to
* generate/filter the edges to explore. Additionally, this will include edges to previously discovered nodes.
*/
- private def bfs( start: LinkedHashSet[Dependency[B]],
- blacklist: LinkedHashSet[Dependency[B]],
- extractor: B => Set[Dependency[B]] ): LinkedHashMap[B, LinkedHashSet[B]] = {
+ private def bfs(
+ start: LinkedHashSet[Dependency[B]],
+ blacklist: LinkedHashSet[Dependency[B]],
+ extractor: B => Set[Dependency[B]]
+ ): LinkedHashMap[B, LinkedHashSet[B]] = {
val (queue, edges) = {
- val a: Queue[Dependency[B]] = Queue(start.toSeq:_*)
- val b: LinkedHashMap[B, LinkedHashSet[B]] = LinkedHashMap[B, LinkedHashSet[B]](
- start.map((dToO(_) -> LinkedHashSet[B]())).toSeq:_*)
+ val a: Queue[Dependency[B]] = Queue(start.toSeq: _*)
+ val b: LinkedHashMap[B, LinkedHashSet[B]] =
+ LinkedHashMap[B, LinkedHashSet[B]](start.map((dToO(_) -> LinkedHashSet[B]())).toSeq: _*)
(a, b)
}
@@ -117,7 +119,8 @@ trait DependencyManager[A, B <: TransformLike[A] with DependencyAPI[B]] extends
val edges = bfs(
start = _targets &~ _currentState,
blacklist = _currentState,
- extractor = (p: B) => p._prerequisites &~ _currentState)
+ extractor = (p: B) => p._prerequisites &~ _currentState
+ )
DiGraph(edges)
}
@@ -144,11 +147,14 @@ trait DependencyManager[A, B <: TransformLike[A] with DependencyAPI[B]] extends
val edges = {
val x = new LinkedHashMap ++ _targets
.map(dependencyToObject)
- .map{ a => a -> prerequisiteGraph.getVertices.filter(a._optionalPrerequisiteOf(_)) }
- x
- .values
+ .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
}
@@ -165,23 +171,26 @@ trait DependencyManager[A, B <: TransformLike[A] with DependencyAPI[B]] extends
bfs(
start = v.map(oToD(_)),
blacklist = _currentState,
-
/* Explore all invalidated transforms **EXCEPT** the current transform! */
extractor = (p: B) => {
val filtered = new LinkedHashSet[Dependency[B]]
filtered ++= v.filter(p.invalidates).map(oToD(_))
filtered -= oToD(p)
filtered
- })
+ }
+ )
).reverse
}
/** Wrap a possible [[CyclicException]] thrown by a thunk in a [[DependencyManagerException]] */
- private def cyclePossible[A](a: String, diGraph: DiGraph[_])(thunk: => A): A = try { thunk } catch {
+ private def cyclePossible[A](a: String, diGraph: DiGraph[_])(thunk: => A): A = try { thunk }
+ catch {
case e: CyclicException =>
throw new DependencyManagerException(
s"""|No transform ordering possible due to cyclic dependency in $a with cycles:
- |${diGraph.findSCCs.filter(_.size > 1).mkString(" - ", "\n - ", "")}""".stripMargin, e)
+ |${diGraph.findSCCs.filter(_.size > 1).mkString(" - ", "\n - ", "")}""".stripMargin,
+ e
+ )
}
/** An ordering of [[firrtl.options.TransformLike TransformLike]]s that causes the requested [[DependencyManager.targets
@@ -198,38 +207,39 @@ trait DependencyManager[A, B <: TransformLike[A] with DependencyAPI[B]] extends
*/
val sorted = {
val edges = {
- val v = cyclePossible("invalidates", invalidateGraph){ invalidateGraph.linearize }.reverse
+ val v = cyclePossible("invalidates", invalidateGraph) { invalidateGraph.linearize }.reverse
/* 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], Set.empty[Dependency[B]])){
- case ((m, s), r) => (m + (r -> ((a: Dependency[B]) => !s(a))), s + r) }._1(l)(r)
+ (l: B, r: B) =>
+ v.foldLeft((Map.empty[B, Dependency[B] => Boolean], Set.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))))
}
cyclePossible("prerequisites", dependencyGraph) {
- DiGraph(edges)
- .linearize
- .reverse
+ DiGraph(edges).linearize.reverse
.dropWhile(b => _currentState.contains(b))
}
}
/* [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 -- 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 -- 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 -- s).nonEmpty) { Some(this.copy(_targets.toSeq, s.toSeq)) }
- else { None }
+ else { None }
}
l ++ postprocessing
}
@@ -252,20 +262,21 @@ trait DependencyManager[A, B <: TransformLike[A] with DependencyAPI[B]] extends
* applied while tracking the state of the underlying A. If the state ever disagrees with a prerequisite, then this
* throws an exception.
*/
- flattenedTransformOrder
- .map{ t =>
- 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)
- }
- (t.transform(a), ((state + wrapperToClass(t)).map(dToO).filterNot(t.invalidates).map(oToD)))
- }._1
+ flattenedTransformOrder.map { t =>
+ 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
+ )
+ }
+ (t.transform(a), ((state + wrapperToClass(t)).map(dToO).filterNot(t.invalidates).map(oToD)))
+ }._1
}
/** This colormap uses Colorbrewer's 4-class OrRd color scheme */
@@ -282,13 +293,13 @@ 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 } else {
+ if (edges.isEmpty) { None }
+ else {
Some(
s"""| { $attributes
|${edges.mkString(tab, "\n" + tab, "")}
@@ -298,16 +309,16 @@ trait DependencyManager[A, B <: TransformLike[A] with DependencyAPI[B]] extends
}
val connections =
- Seq( (prerequisiteGraph, "edge []"),
- (optionalPrerequisiteOfGraph, """edge [style=bold color="#4292c6"]"""),
- (invalidateGraph, """edge [minlen=2 style=dashed constraint=false color="#fb6a4a"]"""),
- (optionalPrerequisitesGraph, """edge [style=dotted color="#a1d99b"]""") )
- .flatMap{ case (a, b) => toGraphviz(a, b) }
+ Seq(
+ (prerequisiteGraph, "edge []"),
+ (optionalPrerequisiteOfGraph, """edge [style=bold color="#4292c6"]"""),
+ (invalidateGraph, """edge [minlen=2 style=dashed constraint=false color="#fb6a4a"]"""),
+ (optionalPrerequisitesGraph, """edge [style=dotted color="#a1d99b"]""")
+ ).flatMap { case (a, b) => toGraphviz(a, b) }
.mkString("\n")
val nodes =
- (prerequisiteGraph + optionalPrerequisiteOfGraph + invalidateGraph + otherPrerequisites)
- .getVertices
+ (prerequisiteGraph + optionalPrerequisiteOfGraph + invalidateGraph + otherPrerequisites).getVertices
.map(v => s"""${transformName(v)} [label="${v.name}"]""")
s"""|digraph DependencyManager {
@@ -322,9 +333,9 @@ trait DependencyManager[A, B <: TransformLike[A] with DependencyAPI[B]] extends
def transformOrderToGraphviz(colormap: Seq[String] = colormap): String = {
def rotate[A](a: Seq[A]): Seq[A] = a match {
- case Nil => Nil
+ case Nil => Nil
case car :: cdr => cdr :+ car
- case car => car
+ case car => car
}
val sorted = ArrayBuffer.empty[String]
@@ -340,7 +351,7 @@ trait DependencyManager[A, B <: TransformLike[A] with DependencyAPI[B]] extends
|$tab labeljust=l
|$tab node [fillcolor="${cm.head}"]""".stripMargin
- val body = pm.transformOrder.map{
+ val body = pm.transformOrder.map {
case a: DependencyManager[A, B] =>
val (str, d) = rec(a, rotate(cm), tab + " ", offset + 1)
offset = d
@@ -369,9 +380,10 @@ trait DependencyManager[A, B <: TransformLike[A] with DependencyAPI[B]] extends
* @param size the number of nodes at the current level of the tree
*/
def customPrintHandling(
- tab: String,
+ tab: String,
charSet: CharSet,
- size: Int): Option[PartialFunction[(B, Int), Seq[String]]] = None
+ size: Int
+ ): Option[PartialFunction[(B, Int), Seq[String]]] = None
/** Helper utility when recursing during pretty printing
* @param tab an indentation string to use for every line of output
@@ -386,9 +398,9 @@ trait DependencyManager[A, B <: TransformLike[A] with DependencyAPI[B]] extends
val defaultHandling: PartialFunction[(B, Int), Seq[String]] = {
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: 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}")
}
val handling = customPrintHandling(tab, charSet, transformOrder.size) match {
@@ -396,8 +408,7 @@ trait DependencyManager[A, B <: TransformLike[A] with DependencyAPI[B]] extends
case None => defaultHandling
}
- transformOrder
- .zipWithIndex
+ transformOrder.zipWithIndex
.flatMap(handling)
}
@@ -406,8 +417,9 @@ trait DependencyManager[A, B <: TransformLike[A] with DependencyAPI[B]] extends
* @param charSet a collection of characters to use when printing
*/
def prettyPrint(
- tab: String = "",
- charSet: DependencyManagerUtils.CharSet = DependencyManagerUtils.PrettyCharSet): String = {
+ tab: String = "",
+ charSet: DependencyManagerUtils.CharSet = DependencyManagerUtils.PrettyCharSet
+ ): String = {
(Seq(s"$tab$name") ++ prettyPrintRec(tab, charSet)).mkString("\n")
@@ -422,9 +434,11 @@ trait DependencyManager[A, B <: TransformLike[A] with DependencyAPI[B]] extends
* @param targets the [[Phase]]s you want to run
*/
class PhaseManager(
- val targets: Seq[PhaseManager.PhaseDependency],
+ val targets: Seq[PhaseManager.PhaseDependency],
val currentState: Seq[PhaseManager.PhaseDependency] = Seq.empty,
- val knownObjects: Set[Phase] = Set.empty) extends DependencyManager[AnnotationSeq, Phase] with Phase {
+ val knownObjects: Set[Phase] = Set.empty)
+ extends DependencyManager[AnnotationSeq, Phase]
+ with Phase {
import PhaseManager.PhaseDependency
protected def copy(a: Seq[PhaseDependency], b: Seq[PhaseDependency], c: ISet[Phase]) = new PhaseManager(a, b, c)
@@ -444,6 +458,7 @@ object DependencyManagerUtils {
* @see [[ASCIICharSet]]
*/
trait CharSet {
+
/** Used when printing the last node */
val lastNode: String
@@ -456,15 +471,15 @@ object DependencyManagerUtils {
/** Uses prettier characters, but possibly not supported by all fonts */
object PrettyCharSet extends CharSet {
- val lastNode = "└──"
- val notLastNode = "├──"
+ val lastNode = "└──"
+ val notLastNode = "├──"
val continuation = "│ "
}
/** Basic ASCII output */
object ASCIICharSet extends CharSet {
- val lastNode = "\\--"
- val notLastNode = "|--"
+ val lastNode = "\\--"
+ val notLastNode = "|--"
val continuation = "| "
}
diff --git a/src/main/scala/firrtl/options/ExitCodes.scala b/src/main/scala/firrtl/options/ExitCodes.scala
index 0e91fdec..94e525de 100644
--- a/src/main/scala/firrtl/options/ExitCodes.scala
+++ b/src/main/scala/firrtl/options/ExitCodes.scala
@@ -6,7 +6,7 @@ package firrtl.options
sealed trait ExitCode { val number: Int }
/** [[ExitCode]] indicating success */
-object ExitSuccess extends ExitCode{ val number = 0 }
+object ExitSuccess extends ExitCode { val number = 0 }
/** An [[ExitCode]] indicative of failure. This must be non-zero and should not conflict with a reserved exit code. */
sealed trait ExitFailure extends ExitCode
diff --git a/src/main/scala/firrtl/options/OptionParser.scala b/src/main/scala/firrtl/options/OptionParser.scala
index 9360a961..e7ea68bf 100644
--- a/src/main/scala/firrtl/options/OptionParser.scala
+++ b/src/main/scala/firrtl/options/OptionParser.scala
@@ -9,7 +9,8 @@ import scopt.OptionParser
case object OptionsHelpException extends Exception("Usage help invoked")
/** OptionParser mixin that causes the OptionParser to not call exit (call `sys.exit`) if the `--help` option is
- * passed */
+ * passed
+ */
trait DoNotTerminateOnExit { this: OptionParser[_] =>
override def terminate(exitState: Either[String, Unit]): Unit = ()
}
@@ -33,16 +34,18 @@ trait DuplicateHandling extends OptionParser[AnnotationSeq] {
/** Message for found duplicate options */
def msg(x: String, y: String) = s"""Duplicate $x "$y" (did your custom Transform or OptionsManager add this?)"""
- val longDups = options.map(_.name).groupBy(identity).collect{ case (k, v) if v.size > 1 && k != "" => k }
- val shortDups = options.map(_.shortOpt).flatten.groupBy(identity).collect{ case (k, v) if v.size > 1 => k }
-
+ val longDups = options.map(_.name).groupBy(identity).collect { case (k, v) if v.size > 1 && k != "" => k }
+ val shortDups = options.map(_.shortOpt).flatten.groupBy(identity).collect { case (k, v) if v.size > 1 => k }
- if (longDups.nonEmpty) {
+ if (longDups.nonEmpty) {
throw new OptionsException(msg("long option", longDups.map("--" + _).mkString(",")), new IllegalArgumentException)
}
if (shortDups.nonEmpty) {
- throw new OptionsException(msg("short option", shortDups.map("-" + _).mkString(",")), new IllegalArgumentException)
+ throw new OptionsException(
+ msg("short option", shortDups.map("-" + _).mkString(",")),
+ new IllegalArgumentException
+ )
}
super.parse(args, init)
diff --git a/src/main/scala/firrtl/options/Phase.scala b/src/main/scala/firrtl/options/Phase.scala
index 2a68251d..6a3f4a8c 100644
--- a/src/main/scala/firrtl/options/Phase.scala
+++ b/src/main/scala/firrtl/options/Phase.scala
@@ -12,7 +12,7 @@ import scala.reflect
import scala.reflect.ClassTag
object Dependency {
- def apply[A <: DependencyAPI[_] : ClassTag]: Dependency[A] = {
+ def apply[A <: DependencyAPI[_]: ClassTag]: Dependency[A] = {
val clazz = reflect.classTag[A].runtimeClass
Dependency(Left(clazz.asInstanceOf[Class[A]]))
}
@@ -40,26 +40,30 @@ object Dependency {
case class Dependency[+A <: DependencyAPI[_]](id: Either[Class[_ <: A], A with Singleton]) {
def getObject(): A = id match {
- case Left(c) => safeConstruct(c)
+ case Left(c) => safeConstruct(c)
case Right(o) => o
}
def getSimpleName: String = id match {
- case Left(c) => c.getSimpleName
+ case Left(c) => c.getSimpleName
case Right(o) => o.getClass.getSimpleName
}
def getName: String = id match {
- case Left(c) => c.getName
+ case Left(c) => c.getName
case Right(o) => o.getClass.getName
}
/** Wrap an [[IllegalAccessException]] due to attempted object construction in a [[DependencyManagerException]] */
- private def safeConstruct[A](a: Class[_ <: A]): A = try { a.newInstance } catch {
- case e: IllegalAccessException => throw new DependencyManagerException(
- s"Failed to construct '$a'! (Did you try to construct an object?)", e)
- case e: InstantiationException => throw new DependencyManagerException(
- s"Failed to construct '$a'! (Did you try to construct an inner class or a class with parameters?)", e)
+ private def safeConstruct[A](a: Class[_ <: A]): A = try { a.newInstance }
+ catch {
+ case e: IllegalAccessException =>
+ throw new DependencyManagerException(s"Failed to construct '$a'! (Did you try to construct an object?)", e)
+ case e: InstantiationException =>
+ throw new DependencyManagerException(
+ s"Failed to construct '$a'! (Did you try to construct an inner class or a class with parameters?)",
+ e
+ )
}
}
@@ -124,7 +128,7 @@ trait DependencyAPI[A <: DependencyAPI[A]] { this: TransformLike[_] =>
/** All transform that must run before this transform
* $seqNote
*/
- def prerequisites: Seq[Dependency[A]] = Seq.empty
+ def prerequisites: Seq[Dependency[A]] = Seq.empty
private[options] lazy val _prerequisites: LinkedHashSet[Dependency[A]] = new LinkedHashSet() ++ prerequisites
/** All transforms that, if a prerequisite of *another* transform, will run before this transform.
@@ -184,8 +188,10 @@ trait DependencyAPI[A <: DependencyAPI[A]] { this: TransformLike[_] =>
/** A trait indicating that no invalidations occur, i.e., all previous transforms are preserved
* @tparam A some [[TransformLike]]
*/
-@deprecated("Use an explicit `override def invalidates` returning false. This will be removed in FIRRTL 1.5.",
- "FIRRTL 1.4")
+@deprecated(
+ "Use an explicit `override def invalidates` returning false. This will be removed in FIRRTL 1.5.",
+ "FIRRTL 1.4"
+)
trait PreservesAll[A <: DependencyAPI[A]] { this: DependencyAPI[A] =>
override final def invalidates(a: A): Boolean = false
diff --git a/src/main/scala/firrtl/options/Registration.scala b/src/main/scala/firrtl/options/Registration.scala
index c832ec7c..55772c79 100644
--- a/src/main/scala/firrtl/options/Registration.scala
+++ b/src/main/scala/firrtl/options/Registration.scala
@@ -14,26 +14,26 @@ import scopt.{OptionDef, OptionParser, Read}
* @param shortOption an optional single-dash option
* @param helpValueName a string to show as a placeholder argument in help text
*/
-final class ShellOption[A: Read] (
- val longOption: String,
+final class ShellOption[A: Read](
+ val longOption: String,
val toAnnotationSeq: A => AnnotationSeq,
- val helpText: String,
- val shortOption: Option[String] = None,
- val helpValueName: Option[String] = None
-) {
+ val helpText: String,
+ val shortOption: Option[String] = None,
+ val helpValueName: Option[String] = None) {
/** Add this specific shell (command line) option to an option parser
* @param p an option parser
*/
final def addOption(p: OptionParser[AnnotationSeq]): Unit = {
val f = Seq(
- (p: OptionDef[A, AnnotationSeq]) => p.action( (x, c) => toAnnotationSeq(x).reverse ++ c ),
+ (p: OptionDef[A, AnnotationSeq]) => p.action((x, c) => toAnnotationSeq(x).reverse ++ c),
(p: OptionDef[A, AnnotationSeq]) => p.text(helpText),
- (p: OptionDef[A, AnnotationSeq]) => p.unbounded()) ++
- shortOption.map( a => (p: OptionDef[A, AnnotationSeq]) => p.abbr(a) ) ++
- helpValueName.map( a => (p: OptionDef[A, AnnotationSeq]) => p.valueName(a) )
+ (p: OptionDef[A, AnnotationSeq]) => p.unbounded()
+ ) ++
+ shortOption.map(a => (p: OptionDef[A, AnnotationSeq]) => p.abbr(a)) ++
+ helpValueName.map(a => (p: OptionDef[A, AnnotationSeq]) => p.valueName(a))
- f.foldLeft(p.opt[A](longOption))( (a, b) => b(a) )
+ f.foldLeft(p.opt[A](longOption))((a, b) => b(a))
}
}
@@ -55,13 +55,15 @@ trait HasShellOptions {
/** A [[Transform]] that includes an option that should be exposed at the top level.
*
* @note To complete registration, include an entry in
- * src/main/resources/META-INF/services/firrtl.options.RegisteredTransform */
+ * src/main/resources/META-INF/services/firrtl.options.RegisteredTransform
+ */
trait RegisteredTransform extends HasShellOptions { this: Transform => }
/** A class that includes options that should be exposed as a group at the top level.
*
* @note To complete registration, include an entry in
- * src/main/resources/META-INF/services/firrtl.options.RegisteredLibrary */
+ * src/main/resources/META-INF/services/firrtl.options.RegisteredLibrary
+ */
trait RegisteredLibrary extends HasShellOptions {
/** The name of this library.
diff --git a/src/main/scala/firrtl/options/Shell.scala b/src/main/scala/firrtl/options/Shell.scala
index 88301d30..b0ead81f 100644
--- a/src/main/scala/firrtl/options/Shell.scala
+++ b/src/main/scala/firrtl/options/Shell.scala
@@ -4,7 +4,7 @@ package firrtl.options
import firrtl.AnnotationSeq
-import logger.{LogLevelAnnotation, ClassLogLevelAnnotation, LogFileAnnotation, LogClassNamesAnnotation}
+import logger.{ClassLogLevelAnnotation, LogClassNamesAnnotation, LogFileAnnotation, LogLevelAnnotation}
import scopt.OptionParser
@@ -62,28 +62,25 @@ class Shell(val applicationName: String) {
parser.note("Shell Options")
ProgramArgsAnnotation.addOptions(parser)
- Seq( TargetDirAnnotation,
- InputAnnotationFileAnnotation,
- OutputAnnotationFileAnnotation )
+ Seq(TargetDirAnnotation, InputAnnotationFileAnnotation, OutputAnnotationFileAnnotation)
.foreach(_.addOptions(parser))
- parser.opt[Unit]("show-registrations")
- .action{ (_, c) =>
+ parser
+ .opt[Unit]("show-registrations")
+ .action { (_, c) =>
val rtString = registeredTransforms.map(r => s"\n - ${r.getClass.getName}").mkString
val rlString = registeredLibraries.map(l => s"\n - ${l.getClass.getName}").mkString
println(s"""|The following FIRRTL transforms registered command line options:$rtString
|The following libraries registered command line options:$rlString""".stripMargin)
- c }
+ c
+ }
.unbounded()
.text("print discovered registered libraries and transforms")
parser.help("help").text("prints this usage text")
parser.note("Logging Options")
- Seq( LogLevelAnnotation,
- ClassLogLevelAnnotation,
- LogFileAnnotation,
- LogClassNamesAnnotation )
+ Seq(LogLevelAnnotation, ClassLogLevelAnnotation, LogFileAnnotation, LogClassNamesAnnotation)
.foreach(_.addOptions(parser))
}
diff --git a/src/main/scala/firrtl/options/Stage.scala b/src/main/scala/firrtl/options/Stage.scala
index aa4809dd..77c8133b 100644
--- a/src/main/scala/firrtl/options/Stage.scala
+++ b/src/main/scala/firrtl/options/Stage.scala
@@ -37,10 +37,12 @@ abstract class Stage extends Phase {
.foldLeft(annotations)((a, p) => p.transform(a))
Logger.makeScope(annotationsx) {
- Seq( new phases.AddDefaults,
- new phases.Checks,
- new Phase { def transform(a: AnnotationSeq) = run(a) },
- new phases.WriteOutputAnnotations )
+ Seq(
+ new phases.AddDefaults,
+ new phases.Checks,
+ new Phase { def transform(a: AnnotationSeq) = run(a) },
+ new phases.WriteOutputAnnotations
+ )
.map(phases.DeletedWrapper(_))
.foldLeft(annotationsx)((a, p) => p.transform(a))
}
@@ -61,6 +63,7 @@ abstract class Stage extends Phase {
* @param stage the stage to run
*/
class StageMain(val stage: Stage) {
+
/** The main function that serves as this stage's command line interface.
* @param args command line arguments
*/
diff --git a/src/main/scala/firrtl/options/StageAnnotations.scala b/src/main/scala/firrtl/options/StageAnnotations.scala
index 32f8ff59..84168975 100644
--- a/src/main/scala/firrtl/options/StageAnnotations.scala
+++ b/src/main/scala/firrtl/options/StageAnnotations.scala
@@ -89,7 +89,9 @@ object TargetDirAnnotation extends HasShellOptions {
toAnnotationSeq = (a: String) => Seq(TargetDirAnnotation(a)),
helpText = "Work directory (default: '.')",
shortOption = Some("td"),
- helpValueName = Some("<directory>") ) )
+ helpValueName = Some("<directory>")
+ )
+ )
}
@@ -101,10 +103,11 @@ case class ProgramArgsAnnotation(arg: String) extends NoTargetAnnotation with St
object ProgramArgsAnnotation {
- def addOptions(p: OptionParser[AnnotationSeq]): Unit = p.arg[String]("<arg>...")
+ def addOptions(p: OptionParser[AnnotationSeq]): Unit = p
+ .arg[String]("<arg>...")
.unbounded()
.optional()
- .action( (x, c) => ProgramArgsAnnotation(x) +: c )
+ .action((x, c) => ProgramArgsAnnotation(x) +: c)
.text("optional unbounded args")
}
@@ -123,7 +126,9 @@ object InputAnnotationFileAnnotation extends HasShellOptions {
toAnnotationSeq = (a: String) => Seq(InputAnnotationFileAnnotation(a)),
helpText = "An input annotation file",
shortOption = Some("faf"),
- helpValueName = Some("<file>") ) )
+ helpValueName = Some("<file>")
+ )
+ )
}
@@ -141,7 +146,9 @@ object OutputAnnotationFileAnnotation extends HasShellOptions {
toAnnotationSeq = (a: String) => Seq(OutputAnnotationFileAnnotation(a)),
helpText = "An output annotation file",
shortOption = Some("foaf"),
- helpValueName = Some("<file>") ) )
+ helpValueName = Some("<file>")
+ )
+ )
}
@@ -156,6 +163,8 @@ case object WriteDeletedAnnotation extends NoTargetAnnotation with StageOption w
new ShellOption[Unit](
longOption = "write-deleted",
toAnnotationSeq = (_: Unit) => Seq(WriteDeletedAnnotation),
- helpText = "Include deleted annotations in the output annotation file" ) )
+ helpText = "Include deleted annotations in the output annotation file"
+ )
+ )
}
diff --git a/src/main/scala/firrtl/options/StageOptions.scala b/src/main/scala/firrtl/options/StageOptions.scala
index f60a991c..6b9190a7 100644
--- a/src/main/scala/firrtl/options/StageOptions.scala
+++ b/src/main/scala/firrtl/options/StageOptions.scala
@@ -10,26 +10,28 @@ import java.io.File
* @param programArgs explicit program arguments
* @param outputAnnotationFileName an output annotation filename
*/
-class StageOptions private [firrtl] (
- val targetDir: String = TargetDirAnnotation().directory,
- val annotationFilesIn: Seq[String] = Seq.empty,
+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 writeDeleted: Boolean = false ) {
+ val programArgs: Seq[String] = Seq.empty,
+ val writeDeleted: Boolean = false) {
- private [options] def copy(
- targetDir: String = targetDir,
- annotationFilesIn: Seq[String] = annotationFilesIn,
+ private[options] def copy(
+ targetDir: String = targetDir,
+ annotationFilesIn: Seq[String] = annotationFilesIn,
annotationFileOut: Option[String] = annotationFileOut,
- programArgs: Seq[String] = programArgs,
- writeDeleted: Boolean = writeDeleted ): StageOptions = {
+ programArgs: Seq[String] = programArgs,
+ writeDeleted: Boolean = writeDeleted
+ ): StageOptions = {
new StageOptions(
targetDir = targetDir,
annotationFilesIn = annotationFilesIn,
annotationFileOut = annotationFileOut,
programArgs = programArgs,
- writeDeleted = writeDeleted )
+ writeDeleted = writeDeleted
+ )
}
@@ -62,9 +64,9 @@ class StageOptions private [firrtl] (
}.toPath.normalize.toFile
file.getParentFile match {
- case null =>
+ case null =>
case parent if (!parent.exists) => parent.mkdirs()
- case _ =>
+ case _ =>
}
file.toString
diff --git a/src/main/scala/firrtl/options/StageUtils.scala b/src/main/scala/firrtl/options/StageUtils.scala
index 3983f653..2411da6e 100644
--- a/src/main/scala/firrtl/options/StageUtils.scala
+++ b/src/main/scala/firrtl/options/StageUtils.scala
@@ -2,16 +2,16 @@
package firrtl.options
-
/** Utilities related to working with a [[Stage]] */
object StageUtils {
+
/** Print a warning message (in yellow)
* @param message error message
*/
def dramaticWarning(message: String): Unit = {
- println(Console.YELLOW + "-"*78)
+ println(Console.YELLOW + "-" * 78)
println(s"Warning: $message")
- println("-"*78 + Console.RESET)
+ println("-" * 78 + Console.RESET)
}
/** Print an error message (in red)
@@ -19,9 +19,9 @@ object StageUtils {
* @note This does not stop the Driver.
*/
def dramaticError(message: String): Unit = {
- println(Console.RED + "-"*78)
+ println(Console.RED + "-" * 78)
println(s"Error: $message")
- println("-"*78 + Console.RESET)
+ println("-" * 78 + Console.RESET)
}
/** Generate a message suggesting that the user look at the usage text.
diff --git a/src/main/scala/firrtl/options/package.scala b/src/main/scala/firrtl/options/package.scala
index 8cf2875b..f87fb8a8 100644
--- a/src/main/scala/firrtl/options/package.scala
+++ b/src/main/scala/firrtl/options/package.scala
@@ -5,17 +5,16 @@ package firrtl
package object options {
implicit object StageOptionsView extends OptionsView[StageOptions] {
- def view(options: AnnotationSeq): StageOptions = options
- .collect { case a: StageOption => a }
+ def view(options: AnnotationSeq): StageOptions = options.collect { case a: StageOption => a }
.foldLeft(new StageOptions())((c, x) =>
x match {
case TargetDirAnnotation(a) => c.copy(targetDir = a)
/* Insert input files at the head of the Seq for speed and because order shouldn't matter */
- case InputAnnotationFileAnnotation(a) => c.copy(annotationFilesIn = a +: c.annotationFilesIn)
+ case InputAnnotationFileAnnotation(a) => c.copy(annotationFilesIn = a +: c.annotationFilesIn)
case OutputAnnotationFileAnnotation(a) => c.copy(annotationFileOut = Some(a))
/* Do NOT reorder program args. The order may matter. */
case ProgramArgsAnnotation(a) => c.copy(programArgs = c.programArgs :+ a)
- case WriteDeletedAnnotation => c.copy(writeDeleted = true)
+ case WriteDeletedAnnotation => c.copy(writeDeleted = true)
}
)
}
diff --git a/src/main/scala/firrtl/options/phases/AddDefaults.scala b/src/main/scala/firrtl/options/phases/AddDefaults.scala
index ab342b1e..0ef1832a 100644
--- a/src/main/scala/firrtl/options/phases/AddDefaults.scala
+++ b/src/main/scala/firrtl/options/phases/AddDefaults.scala
@@ -19,7 +19,7 @@ class AddDefaults extends Phase {
override def invalidates(a: Phase) = false
def transform(annotations: AnnotationSeq): AnnotationSeq = {
- val td = annotations.collectFirst{ case a: TargetDirAnnotation => a}.isEmpty
+ val td = annotations.collectFirst { case a: TargetDirAnnotation => a }.isEmpty
(if (td) Seq(TargetDirAnnotation()) else Seq()) ++
annotations
diff --git a/src/main/scala/firrtl/options/phases/Checks.scala b/src/main/scala/firrtl/options/phases/Checks.scala
index 9e671aa5..024c13a9 100644
--- a/src/main/scala/firrtl/options/phases/Checks.scala
+++ b/src/main/scala/firrtl/options/phases/Checks.scala
@@ -25,24 +25,27 @@ class Checks extends Phase {
val td, outA = collection.mutable.ListBuffer[Annotation]()
annotations.foreach {
- case a: TargetDirAnnotation => td += a
+ case a: TargetDirAnnotation => td += a
case a: OutputAnnotationFileAnnotation => outA += a
case _ =>
}
if (td.size != 1) {
- val d = td.map{ case TargetDirAnnotation(x) => x }
+ val d = td.map { case TargetDirAnnotation(x) => x }
throw new OptionsException(
s"""|Exactly one target directory must be specified, but found `${d.mkString(", ")}` specified via:
| - explicit target directory: -td, --target-dir, TargetDirAnnotation
- | - fallback default value""".stripMargin )}
+ | - fallback default value""".stripMargin
+ )
+ }
if (outA.size > 1) {
- val x = outA.map{ case OutputAnnotationFileAnnotation(x) => x }
+ val x = outA.map { case OutputAnnotationFileAnnotation(x) => x }
throw new OptionsException(
s"""|At most one output annotation file can be specified, but found '${x.mkString(", ")}' specified via:
- | - an option or annotation: -foaf, --output-annotation-file, OutputAnnotationFileAnnotation"""
- .stripMargin )}
+ | - an option or annotation: -foaf, --output-annotation-file, OutputAnnotationFileAnnotation""".stripMargin
+ )
+ }
annotations
}
diff --git a/src/main/scala/firrtl/options/phases/GetIncludes.scala b/src/main/scala/firrtl/options/phases/GetIncludes.scala
index b9320585..dd08e09b 100644
--- a/src/main/scala/firrtl/options/phases/GetIncludes.scala
+++ b/src/main/scala/firrtl/options/phases/GetIncludes.scala
@@ -10,7 +10,7 @@ import firrtl.FileUtils
import java.io.File
import scala.collection.mutable
-import scala.util.{Try, Failure}
+import scala.util.{Failure, Try}
/** Recursively expand all [[InputAnnotationFileAnnotation]]s in an [[AnnotationSeq]] */
class GetIncludes extends Phase {
@@ -37,8 +37,7 @@ class GetIncludes extends Phase {
* @param annos a sequence of annotations
* @return the original annotation sequence with any discovered annotations added
*/
- private def getIncludes(includeGuard: mutable.Set[String] = mutable.Set())
- (annos: AnnotationSeq): AnnotationSeq = {
+ private def getIncludes(includeGuard: mutable.Set[String] = mutable.Set())(annos: AnnotationSeq): AnnotationSeq = {
annos.flatMap {
case a @ InputAnnotationFileAnnotation(value) =>
if (includeGuard.contains(value)) {
diff --git a/src/main/scala/firrtl/options/phases/WriteOutputAnnotations.scala b/src/main/scala/firrtl/options/phases/WriteOutputAnnotations.scala
index 7ee385b1..53306c8a 100644
--- a/src/main/scala/firrtl/options/phases/WriteOutputAnnotations.scala
+++ b/src/main/scala/firrtl/options/phases/WriteOutputAnnotations.scala
@@ -16,9 +16,7 @@ import scala.collection.mutable
class WriteOutputAnnotations extends Phase {
override def prerequisites =
- Seq( Dependency[GetIncludes],
- Dependency[AddDefaults],
- Dependency[Checks] )
+ Seq(Dependency[GetIncludes], Dependency[AddDefaults], Dependency[Checks])
override def optionalPrerequisiteOf = Seq.empty
@@ -29,8 +27,10 @@ class WriteOutputAnnotations extends Phase {
val sopts = Viewer[StageOptions].view(annotations)
val filesWritten = mutable.HashMap.empty[String, Annotation]
val serializable: AnnotationSeq = annotations.toSeq.flatMap {
- case _: Unserializable => None
- case a: DeletedAnnotation => if (sopts.writeDeleted) { Some(a) } else { None }
+ case _: Unserializable => None
+ case a: DeletedAnnotation =>
+ if (sopts.writeDeleted) { Some(a) }
+ else { None }
case a: CustomFileEmission =>
val filename = a.filename(annotations)
val canonical = filename.getCanonicalPath()
@@ -38,7 +38,7 @@ class WriteOutputAnnotations extends Phase {
filesWritten.get(canonical) match {
case None =>
val w = new BufferedWriter(new FileWriter(filename))
- a.getBytes.foreach( w.write(_) )
+ a.getBytes.foreach(w.write(_))
w.close()
filesWritten(canonical) = a
case Some(first) =>