Created
January 16, 2019 12:38
-
-
Save fmarchand/3c2300611872ec1b0b22673a083a7354 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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