aboutsummaryrefslogtreecommitdiff
path: root/src/main/scala/firrtl/passes/memlib/YamlUtils.scala
blob: 75a62245c6a3dfbed8b45d913883730f16581a82 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// See LICENSE for license details.

package firrtl.passes
package memlib
import net.jcazevedo.moultingyaml._
import java.io.{File, CharArrayWriter, PrintWriter}

object CustomYAMLProtocol extends DefaultYamlProtocol {
  // bottom depends on top
  implicit val _pin = yamlFormat1(Pin)
  implicit val _source = yamlFormat2(Source)
  implicit val _top = yamlFormat1(Top)
  implicit val _configs = yamlFormat3(Config)
}

case class Pin(name: String)
case class Source(name: String, module: String)
case class Top(name: String)
case class Config(pin: Pin, source: Source, top: Top)


class YamlFileReader(file: String) {
  import CustomYAMLProtocol._
  def parse[A](implicit reader: YamlReader[A]) : Seq[A] = {
    if (new File(file).exists) {
      val yamlString = scala.io.Source.fromFile(file).getLines.mkString("\n")
      yamlString.parseYamls flatMap (x =>
        try Some(reader read x)
        catch { case e: Exception => None }
      )
    }
    else error("Yaml file doesn't exist!")
  }
}

class YamlFileWriter(file: String) {
  import CustomYAMLProtocol._
  val outputBuffer = new CharArrayWriter
  val separator = "--- \n"
  def append(in: YamlValue) {
    outputBuffer append s"$separator${in.prettyPrint}"
  }
  def dump() {
    val outputFile = new PrintWriter(file)
    outputFile write outputBuffer.toString
    outputFile.close()
  }
}