Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Create z3_pass #36

Merged
merged 3 commits into from
Jul 19, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 84 additions & 0 deletions solver/passes/z3_pass
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
from typing import override
sanjanamandadi marked this conversation as resolved.
Show resolved Hide resolved
from parser.ast import Expr
from parser.ast import AndExpr, OrExpr, Expr, NotExpr, ParenExpr, Var, VarExpr
from parser.visitor import Visitor, RetVisitor
import z3

from parser.lex import Lexer
from parser.parse import Parser


def run_pass(ast: Expr) -> Expr:
v: Z3MappingVisitor = Z3MappingVisitor()
ast.accept(v)

t: TranslateToZ3 = TranslateToZ3(v.symbols)
p: z3.ExprRef = ast.acceptRet(t)
simplifiedExpr: z3.ExprRef = z3.simplify(p)
simplifiedStr: str = str(simplifiedExpr)

l: Lexer = Lexer()
l.lex(simplifiedStr)

pa: Parser = Parser()
ast: Expr = pa.parse(l.tokens)

return ast


class Z3MappingVisitor(Visitor):
def __init__(self) -> None:
self.symbols: dict[str, z3.Bool] = {}

@override
def visitVar(self, va: Var):
self.symbols[va.name] = z3.Bool(va.name)


class TranslateToZ3(RetVisitor[z3.ExprRef]):

def __init__(self, symbols: dict[str, z3.Bool]) -> None:
self.symbols = symbols
sanjanamandadi marked this conversation as resolved.
Show resolved Hide resolved

@override
def visitVarExpr(self, vex: VarExpr) -> z3.ExprRef:
first: z3.ExprRef = vex.first.acceptRet(self)
if vex.second:
second: z3.ExprRef = vex.second.first.acceptRet(self)
if isinstance(vex.second, AndExpr):
return z3.And(first, second)
elif isinstance(vex.second, OrExpr):
return z3.Or(first, second)
return first

@override
def visitNotExpr(self, nex: NotExpr) -> z3.ExprRef:
return z3.Not(nex.first.acceptRet(self))

@override
def visitParenExpr(self, pex: ParenExpr) -> z3.ExprRef:
return pex.first.acceptRet(self)

@override
def visitAndExpr(self) -> None:
pass

@override
def visitOrExpr(self) -> None:
pass

@override
def visitVar(self, va: Var) -> z3.ExprRef:
return self.symbols[va.name]


if __name__ == "__main__":

prog: str = "A | B & C"
l: Lexer = Lexer()
l.lex(prog)

p: Parser = Parser()
ast: Expr = p.parse(l.tokens)

run_pass(ast)
Loading