Jon Aquino's Mental Garden

Engineering beautiful software jon aquino labs | personal blog

Friday, October 08, 2004

Groovy script for finding empty catch blocks


import java.io.*
import java.util.*

class Block {
catchType
lineNumber
lines = new ArrayList()
Block(catchType, lineNumber) {
this.catchType = catchType
this.lineNumber = lineNumber
}
add(line) {
if (line.trim().length() == 0) { return }
lines.add(line)
}
isEmpty() {
lines.empty
}
}

completedBlocks = []
lineNumber = 0
blocks = [new Block(false, 0)]
catchType = false
new File(args[0]).eachLine() { line |
lineNumber++
tokenizer = new StringTokenizer(line, "{}", true)
while (tokenizer.hasMoreTokens()) {
token = tokenizer.nextToken().trim()
if (token == "{") {
blocks.add(new Block(catchType, lineNumber))
catchType = false
}
else if (token == "}") {
completedBlocks.add(blocks.pop())
}
else {
if (token =~ "\\s*//.*") { return }
if (token =~ ".*catch\\s*\\(.*") { catchType = true }
blocks[-1].add(token)
}
}
}
lineNumbers = []
completedBlocks.each { block |
if (block.catchType && block.isEmpty()) { lineNumbers.add(block.lineNumber) }
}
if (lineNumbers.size() > 0) {
print args[0] + " " + lineNumbers + "\n"
}

0 Comments:

Post a Comment

<< Home