aboutsummaryrefslogtreecommitdiff
path: root/src/main/scala/firrtl/Visitor.scala
blob: a1963265636c7804e043a834dc6f7ae8365e5fac (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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
/*
 * TODO
 *  - Implement UBits and SBits
 *  - Support all integer types (not just "h...")
*/

package firrtl

import org.antlr.v4.runtime.tree.AbstractParseTreeVisitor;
import org.antlr.v4.runtime.ParserRuleContext
import org.antlr.v4.runtime.tree.ErrorNode
import org.antlr.v4.runtime.tree.TerminalNode
import scala.collection.JavaConversions._
import antlr._
import PrimOps._

class Visitor(val fullFilename: String) extends FIRRTLBaseVisitor[AST] 
{
  // Strip file path
  private val filename = fullFilename.drop(fullFilename.lastIndexOf("/")+1)

  // For some reason visitCircuit does not visit the right function 
  // FIXME for some reason this cannot be private, probably because it extends
  //   FIRRTLBaseVisitor which is in a subpackage?
  def visit[AST](ctx: FIRRTLParser.CircuitContext): Circuit = visitCircuit(ctx)

  //  These regex have to change if grammar changes
  private def string2BigInt(s: String): BigInt = {
    // private define legal patterns
    val HexPattern = """\"*h([a-zA-Z0-9]+)\"*""".r
    val DecPattern = """(\+|-)?([1-9]\d*)""".r
    val ZeroPattern = "0".r
    s match {
      case ZeroPattern(_*) => BigInt(0)
      case HexPattern(hexdigits) => BigInt(hexdigits, 16)
      case DecPattern(sign, num) => BigInt(num)
      case  _  => throw new Exception("Invalid String for conversion to BigInt " + s)
    }
  }
  private def string2Int(s: String): Int = string2BigInt(s).toInt
  private def getInfo(ctx: ParserRuleContext): Info = 
    FileInfo(filename, ctx.getStart().getLine(), ctx.getStart().getCharPositionInLine())

	private def visitCircuit[AST](ctx: FIRRTLParser.CircuitContext): Circuit = 
    Circuit(getInfo(ctx), ctx.id.getText, ctx.module.map(visitModule)) 
    
  private def visitModule[AST](ctx: FIRRTLParser.ModuleContext): Module = 
    Module(getInfo(ctx), ctx.id.getText, ctx.port.map(visitPort), visitBlock(ctx.block))

	private def visitPort[AST](ctx: FIRRTLParser.PortContext): Port = 
    Port(getInfo(ctx), ctx.id.getText, visitDir(ctx.dir), visitType(ctx.`type`))

	private def visitDir[AST](ctx: FIRRTLParser.DirContext): Direction =
    ctx.getText match {
      case "input" => Input
      case "output" => Output
    }

  // Match on a type instead of on strings?
	private def visitType[AST](ctx: FIRRTLParser.TypeContext): Type = {
    ctx.getChild(0).getText match {
      case "UInt" => if (ctx.getChildCount > 1) UIntType(IntWidth(string2BigInt(ctx.IntLit.getText))) 
                     else UIntType( UnknownWidth )
      case "SInt" => if (ctx.getChildCount > 1) SIntType(IntWidth(string2BigInt(ctx.IntLit.getText))) 
                     else SIntType( UnknownWidth )
      case "Clock" => ClockType
      case "{" => BundleType(ctx.field.map(visitField))
      case _ => new VectorType( visitType(ctx.`type`), string2BigInt(ctx.IntLit.getText) )
    }
  }
      
	private def visitField[AST](ctx: FIRRTLParser.FieldContext): Field = {
    val flip = if(ctx.getChild(0).getText == "flip") Reverse else Default
    Field(ctx.id.getText, flip, visitType(ctx.`type`))
  }
     

  // visitBlock
	private def visitBlock[AST](ctx: FIRRTLParser.BlockContext): Stmt = 
    Begin(ctx.stmt.map(visitStmt)) 

	private def visitStmt[AST](ctx: FIRRTLParser.StmtContext): Stmt = {
    val info = getInfo(ctx)

    ctx.getChild(0).getText match {
      case "wire" => DefWire(info, ctx.id(0).getText, visitType(ctx.`type`))
      case "reg"  => {
        val name = ctx.id(0).getText
        val tpe = visitType(ctx.`type`)
        val (reset, init) = if (ctx.getChildCount > 5) (visitExp(ctx.exp(1)), visitExp(ctx.exp(2))) 
                            else (UIntValue(0, IntWidth(1)), Ref(name, tpe))
        DefRegister(info, name, tpe, visitExp(ctx.exp(0)), reset, init)
      }
      case "mem" => DefMemory(info, ctx.id(0).getText, visitType(ctx.`type`), string2Int(ctx.IntLit(0).getText),
                              string2Int(ctx.IntLit(2).getText), string2Int(ctx.IntLit(1).getText),
                              Seq(), Seq(), Seq()) // TODO implement readers and writers
      case "inst"  => DefInstance(info, ctx.id(0).getText, ctx.id(1).getText)
      case "node" =>  DefNode(info, ctx.id(0).getText, visitExp(ctx.exp(0)))
      case "when" => { 
        val alt = if (ctx.block.length > 1) visitBlock(ctx.block(1)) else Empty
        Conditionally(info, visitExp(ctx.exp(0)), visitBlock(ctx.block(0)), alt)
      }
      // TODO implement stop
      // TODO implement printf
      case "skip" => Empty
      // If we don't match on the first child, try the next one
      case _ => {
        ctx.getChild(1).getText match {
          case "<=" => Connect(info, visitExp(ctx.exp(0)), visitExp(ctx.exp(1)) )
          case "<-" => BulkConnect(info, visitExp(ctx.exp(0)), visitExp(ctx.exp(1)) )
          case "is" => IsInvalid(info, visitExp(ctx.exp(0)))
        }
      }
    }
  }
     
  // add visitRuw ?
	//T visitRuw(FIRRTLParser.RuwContext ctx);
  //private def visitRuw[AST](ctx: FIRRTLParser.RuwContext): 

  // TODO 
  // - Add mux
  // - Add validif
	private def visitExp[AST](ctx: FIRRTLParser.ExpContext): Expression = 
    if( ctx.getChildCount == 1 ) 
      Ref(ctx.getText, UnknownType)
    else
      ctx.getChild(0).getText match {
        case "UInt" => { // This could be better
          val (width, value) = 
            if (ctx.getChildCount > 4) 
              (IntWidth(string2BigInt(ctx.IntLit(0).getText)), string2BigInt(ctx.IntLit(1).getText))
            else (UnknownWidth, string2BigInt(ctx.IntLit(0).getText))
          UIntValue(value, width)
        }
        case "SInt" => {
          val (width, value) = 
            if (ctx.getChildCount > 4) 
              (IntWidth(string2BigInt(ctx.IntLit(0).getText)), string2BigInt(ctx.IntLit(1).getText))
            else (UnknownWidth, string2BigInt(ctx.IntLit(0).getText))
          SIntValue(value, width)
        }
        case _ => 
          ctx.getChild(1).getText match {
            case "." => new SubField(visitExp(ctx.exp(0)), ctx.id.getText, UnknownType)
            case "[" => if (ctx.IntLit != null) 
                          new SubIndex(visitExp(ctx.exp(0)), string2BigInt(ctx.IntLit(0).getText), UnknownType)
                        else new SubAccess(visitExp(ctx.exp(0)), visitExp(ctx.exp(1)), UnknownType)
            // Assume primop
            case _ => DoPrim(visitPrimop(ctx.primop), ctx.exp.map(visitExp),
                             ctx.IntLit.map(x => string2BigInt(x.getText)), UnknownType)
          }
      }
  
  // stripSuffix("(") is included because in ANTLR concrete syntax we have to include open parentheses, 
  //  see grammar file for more details
	private def visitPrimop[AST](ctx: FIRRTLParser.PrimopContext): PrimOp = fromString(ctx.getText.stripSuffix("("))

  // visit Id and Keyword?
}