aboutsummaryrefslogtreecommitdiff
path: root/src/test/scala/firrtlTests/execution/ParserHelpers.scala
blob: c5561059ee50d93fb84ace8a658e678bd2d59645 (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
49
50
51
52
53
54
// SPDX-License-Identifier: Apache-2.0

package firrtlTests.execution

import firrtl._
import firrtl.ir._

class ParserHelperException(val pe: ParserException, input: String)
    extends FirrtlUserException(s"Got error ${pe.toString} while parsing input:\n${input}")

/**
  * A utility class that parses a FIRRTL string representing a statement to a sub-AST
  */
object ParseStatement {
  private def wrapStmtStr(stmtStr: String): String = {
    val indent = "    "
    val indented = stmtStr.split("\n").mkString(indent, s"\n${indent}", "")
    s"""circuit ${DUTRules.dutName} :
       |  module ${DUTRules.dutName} :
       |    input clock : Clock
       |    input reset : UInt<1>
       |${indented}""".stripMargin
  }

  private def parse(stmtStr: String): Circuit = {
    try {
      Parser.parseString(wrapStmtStr(stmtStr), Parser.IgnoreInfo)
    } catch {
      case e: ParserException => throw new ParserHelperException(e, stmtStr)
    }
  }

  def apply(stmtStr: String): Statement = {
    val c = parse(stmtStr)
    val stmt = c.modules.collectFirst { case Module(_, _, _, b: Block) => b.stmts.head }
    stmt.get
  }

  private[execution] def makeDUT(body: String): Circuit = parse(body)
}

/**
  * A utility class that parses a FIRRTL string representing an expression to a sub-AST
  */
object ParseExpression {
  def apply(expStr: String): Expression = {
    try {
      val s = ParseStatement(s"${expStr} is invalid")
      s.asInstanceOf[IsInvalid].expr
    } catch {
      case e: ParserHelperException => throw new ParserHelperException(e.pe, expStr)
    }
  }
}