package io.gitlab.jfronny.muscript.ast.bool; import io.gitlab.jfronny.muscript.ast.compare.Equal; import io.gitlab.jfronny.muscript.ast.compare.Greater; import io.gitlab.jfronny.muscript.ast.literal.NumberLiteral; import io.gitlab.jfronny.muscript.compiler.ExprWriter; import io.gitlab.jfronny.muscript.compiler.Order; import io.gitlab.jfronny.muscript.data.Scope; import io.gitlab.jfronny.muscript.ast.BoolExpr; import io.gitlab.jfronny.muscript.ast.Expr; import io.gitlab.jfronny.muscript.ast.literal.BoolLiteral; import java.io.IOException; public class Not extends BoolExpr { private final BoolExpr inner; public Not(int chStart, int chEnd, BoolExpr inner) { super(Order.Unary, chStart, chEnd); this.inner = inner; } @Override public Boolean get(Scope dataRoot) { return !inner.get(dataRoot); } @Override public BoolExpr optimize() { BoolExpr inner = this.inner.optimize(); if (inner instanceof Not not) return not.inner; if (inner instanceof BoolLiteral literal) return Expr.literal(chStart, chEnd, !literal.value); return new Not(chStart, chEnd, inner); } @Override public void decompile(ExprWriter writer) throws IOException { if (inner instanceof Equal eq) { parenthesize(eq.left, writer, false); writer.append(" != "); parenthesize(eq.right, writer, true); } else if (inner instanceof Greater gt) { if (gt.left instanceof NumberLiteral && !(gt.right instanceof NumberLiteral)) { parenthesize(gt.right, writer, false); writer.append(" >= "); parenthesize(gt.left, writer, true); } else { parenthesize(gt.left, writer, false); writer.append(" <= "); parenthesize(gt.right, writer, true); } } else { writer.append("!"); parenthesize(inner, writer, false); } } @Override public boolean equals(Object obj) { return obj instanceof Not not && inner.equals(not.inner); } }