Skip to content

Instantly share code, notes, and snippets.

@fmarchand
Created January 16, 2019 12:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fmarchand/3c2300611872ec1b0b22673a083a7354 to your computer and use it in GitHub Desktop.
Save fmarchand/3c2300611872ec1b0b22673a083a7354 to your computer and use it in GitHub Desktop.
import com.agaetis.antlr4.mysql.MySqlParserBaseListener
import com.agaetis.antlr4.mysql.MySqlLexer
import com.agaetis.antlr4.mysql.MySqlParser
import org.antlr.v4.runtime.ParserRuleContext
import org.antlr.v4.runtime.CharStream
import org.antlr.v4.runtime.CharStreams
import org.antlr.v4.runtime.CommonTokenStream
import org.antlr.v4.runtime.tree.ParseTree
import org.antlr.v4.runtime.tree.ParseTreeWalker
import scala.collection.mutable.Map
class MyListener extends MySqlParserBaseListener {
val nodeCountPerLevel = LinkedHashMap[Int, Int]();
override def enterEveryRule(ctx:ParserRuleContext) {
nodeCountPerLevel(ctx.depth()) = nodeCountPerLevel.getOrElse(ctx.depth(),0) + 1
}
}
class MyErrorListener extends BaseErrorListener {
@throws(classOf[ParseCancellationException])
override def syntaxError( recognizer: Recognizer[_, _],
offendingSymbol:Object, line:Int ,
charPositionInLine:Int ,
msg:String ,
e:RecognitionException) = {
println(s"ERROR $msg")
throw new ParseCancellationException(msg);
}
}
def evalComplexity(input:String, exprType:String) : Double = {
if(input == null || input.isEmpty)
0
else {
try {
val inputCharStream = CharStreams.fromString(input)
val sqlLexer:MySqlLexer = new MySqlLexer(inputCharStream)
val tokenStream = new CommonTokenStream(sqlLexer)
val parser = new MySqlParser(tokenStream)
parser.removeErrorListeners();
parser.addErrorListener(new MyErrorListener());
val tree:ParseTree = exprType match {
case "SELECT" => parser.selectStatement()
case "EXPR" => parser.expression()
case _ => parser.root()
}
val walker = new ParseTreeWalker()
val listener = new MyListener()
walker.walk(listener, tree)
val nodeCountPerLevel = listener.nodeCountPerLevel
println(nodeCountPerLevel.size)
val score = nodeCountPerLevel.map { case (k,v) => {
Math.log(k * v) + 1.0
}
}.reduce( (a,b) => a * b )
Math.log(score)
} catch {
case e:ParseCancellationException => -1.0
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment