internal class BooleanRewritingWalker : BabelParserBaseListener() { var isBooleanExpression = false private set override fun exitScalarExpr(ctx: BabelParser.ScalarExprContext) { val operation = ctx.children?.firstOrNull { it.isOperation} when(operation){ is BabelParser.LteqContext -> { swapInequalityWithSubtraction(ctx, "~<=") isBooleanExpression = true } is BabelParser.GteqContext -> { swapLiteralChildren(ctx) swapInequalityWithSubtraction(ctx, "~>=") isBooleanExpression = true } is BabelParser.LtContext -> { swapInequalityWithSubtraction(ctx, "~<") addEpsilonAdditionASTLayer(ctx) isBooleanExpression = true } is BabelParser.GtContext ->{ swapLiteralChildren(ctx) swapInequalityWithSubtraction(ctx, "~>") addEpsilonAdditionASTLayer(ctx) isBooleanExpression = true } else ->{ isBooleanExpression = false } } } private fun addEpsilonAdditionASTLayer(ctx: BabelParser.ScalarExprContext) { val parent = ctx.getParent() val superExpression = BabelParser.ScalarExprContext(parent, 20) parent.children.add(parent.children.indexOf(ctx), superExpression) parent.children.remove(ctx) superExpression.addChild(ctx) ctx.parent = superExpression val plusContext = BabelParser.PlusContext(superExpression, 20) val terminalNode = TerminalNodeImpl( CommonToken(20, "ADDFOREPSILON")) plusContext.addChild(terminalNode) superExpression.addChild(plusContext) addValue(superExpression, Epsilon) } private fun addValue(superExpression: BabelParser.ScalarExprContext, value: Double) { val valueExpr = BabelParser.ScalarExprContext(superExpression, 1) val valueContext = BabelParser.LiteralContext(valueExpr, 1) val valueTerminalNode = TerminalNodeImpl(CommonToken(BabelLexer.FLOAT, value.toString())) superExpression.addChild(valueExpr) valueExpr.addChild(valueContext) valueContext.addChild(valueTerminalNode) } private fun swapInequalityWithSubtraction(ctx: BabelParser.ScalarExprContext, literalNodeMessage: String) { ctx.children.removeAt(1) val minusContext = BabelParser.MinusContext(ctx, 21) val terminalNode = TerminalNodeImpl(CommonToken(BabelLexer.FLOAT, literalNodeMessage)) minusContext.addChild(terminalNode) ctx.children.add(1, minusContext) } private fun swapLiteralChildren(ctx: BabelParser.ScalarExprContext) { val firstChild = ctx.children.removeAt(0) val lastChild = ctx.children.removeAt(1) ctx.children.add(0, lastChild) ctx.children.add(firstChild) } private val ParseTree.isOperation get() = this.childCount == 1 && this.getChild(0) is TerminalNode companion object { @JvmField val Epsilon: Double = java.lang.Double.MIN_NORMAL } }