summaryrefslogtreecommitdiff
path: root/src/main/scala/Chisel/Error.scala
blob: 1ad5414d8bfebab6a296296e62bc75653497b332 (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
161
162
163
164
165
166
167
/*
 Copyright (c) 2011, 2012, 2013, 2014 The Regents of the University of
 California (Regents). All Rights Reserved.  Redistribution and use in
 source and binary forms, with or without modification, are permitted
 provided that the following conditions are met:

    * Redistributions of source code must retain the above
      copyright notice, this list of conditions and the following
      two paragraphs of disclaimer.
    * Redistributions in binary form must reproduce the above
      copyright notice, this list of conditions and the following
      two paragraphs of disclaimer in the documentation and/or other materials
      provided with the distribution.
    * Neither the name of the Regents nor the names of its contributors
      may be used to endorse or promote products derived from this
      software without specific prior written permission.

 IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
 SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
 ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
 REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF
 ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION
 TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
 MODIFICATIONS.
*/

package Chisel
import scala.collection.mutable.ArrayBuffer

/** This Singleton implements a log4j compatible interface.
  It is used through out the Chisel package to report errors and warnings
  detected at runtime.
  */
object ChiselError {
  var hasErrors: Boolean = false;
  val ChiselErrors = new ArrayBuffer[ChiselError];

  def clear() {
    ChiselErrors.clear()
    hasErrors = false
  }

  /** emit an error message */
  def error(mf: => String, line: StackTraceElement) {
    hasErrors = true
    ChiselErrors += new ChiselError(() => mf, line)
  }

  def error(m: String) {
    val stack = Thread.currentThread().getStackTrace
    error(m, findFirstUserLine(stack) getOrElse stack(0))
  }

  /** Emit an informational message
    (useful to track long running passes) */
  def info(m: String): Unit =
    println(tag("info", Console.MAGENTA) + " [%2.3f] ".format(Driver.elapsedTime/1e3) + m)

  /** emit a warning message */
  def warning(m: => String) {
    val stack = Thread.currentThread().getStackTrace
    ChiselErrors += new ChiselError(() => m,
      findFirstUserLine(stack) getOrElse stack(0), 1)
  }

  def findFirstUserLine(stack: Array[StackTraceElement]): Option[StackTraceElement] = {
    findFirstUserInd(stack) map { stack(_) }
  }

  def findFirstUserInd(stack: Array[StackTraceElement]): Option[Int] = {
    def isUserCode(ste: StackTraceElement): Boolean = {
      val className = ste.getClassName()
      try {
        val cls = Class.forName(className)
        if( cls.getSuperclass() == classOf[Module] ) {
          true
        } else {
        /* XXX Do it the old way until we figure if it is safe
               to remove from Node.scala
           var line: StackTraceElement = findFirstUserLine(Thread.currentThread().getStackTrace)
         */
          val dotPos = className.lastIndexOf('.')
          if( dotPos > 0 ) {
            (className.subSequence(0, dotPos) != "Chisel") && !className.contains("scala") &&
            !className.contains("java") && !className.contains("$$")
          } else {
            false
          }
        }
      } catch {
        case e: java.lang.ClassNotFoundException => false
      }
    }
    val idx = stack.indexWhere(isUserCode)
    if(idx < 0) {
      println("COULDN'T FIND LINE NUMBER (" + stack(1) + ")")
      None
    } else {
      Some(idx)
    }
  }

  // Print stack frames up to and including the "user" stack frame.
  def printChiselStackTrace() {
    val stack = Thread.currentThread().getStackTrace
    val idx = ChiselError.findFirstUserInd(stack)
    idx match {
      case None => {}
      case Some(x) => for (i <- 0 to x) println(stack(i))
    }
  }

  /** Prints error messages generated by Chisel at runtime. */
  def report() {
    if (!ChiselErrors.isEmpty) {
      for(err <- ChiselErrors)  err.print;
    }
  }

  /** Throws an exception if there has been any error recorded
    before this point. */
  def checkpoint() {
    if(hasErrors) {
      throw new IllegalStateException(
        Console.UNDERLINED + "CODE HAS " +
        Console.UNDERLINED + Console.BOLD + ChiselErrors.filter(_.isError).length + Console.RESET +
        Console.UNDERLINED + " " +
        Console.UNDERLINED + Console.RED + "ERRORS" + Console.RESET +
        Console.UNDERLINED + " and " +
        Console.UNDERLINED + Console.BOLD + ChiselErrors.filter(_.isWarning).length + Console.RESET +
        Console.UNDERLINED + " " +
        Console.UNDERLINED + Console.YELLOW + "WARNINGS" + Console.RESET)
    }
  }

  def tag(name: String, color: String): String =
    s"[${color}${name}${Console.RESET}]"
}

class ChiselError(val errmsgFun: () => String, val errline: StackTraceElement,
val errlevel: Int = 0) {

  val level = errlevel
  val line = errline
  val msgFun = errmsgFun

  def isError = (level == 0)
  def isWarning = (level == 1)

  def print() {
    /* Following conventions for error formatting */
    val levelstr =
      if (isError) ChiselError.tag("error", Console.RED)
      else ChiselError.tag("warn", Console.YELLOW)
    if( line != null ) {
      println(levelstr + " " + line.getFileName + ":" +
        line.getLineNumber + ": " + msgFun() +
        " in class " + line.getClassName)
    } else {
      println(levelstr + ": " + msgFun())
    }
  }
}