Is there a way of querying or accessing the structure of a Z3 expression via the API

≡放荡痞女 提交于 2019-12-10 22:34:27

问题


I am accessing the managed API from F#. I can construct Z3 expressions using ctx.MkFalse, MkImplies, MkMul etc. but how do i traverse a Z3 expression to discover its structure? Is there something like e.Op or e.IsFalse, e.IsImplies etc.


回答1:


You should take a look at documentation of Expr.cs.

Here is a simple F# example that traverses through an expression:

let traverse (expr: Expr) =
    printfn "num args: %O" expr.NumArgs
    printfn "children: %A" expr.Args
    printfn "1st child: %O" expr.Args.[0]
    printfn "2nd child: %O" expr.Args.[1]
    printfn "operator: %O" expr.FuncDecl
    printfn "op name: %O" expr.FuncDecl.Name

Expr class also exposes all Term Kind Tests including IsTrue, IsAnd, isImplies, etc which are necessary to discover the structure of an expression. In F# you should define a set of active patterns:

let (|True|_|) (expr: Expr) = if expr.IsTrue then Some() else None
let (|False|_|) (expr: Expr) = if expr.IsFalse then Some() else None

let (|And|_|) (expr: Expr) = if expr.IsAnd then Some expr.Args else None
let (|Or|_|) (expr: Expr) = if expr.IsOr then Some expr.Args else None
let (|Not|_|) (expr: Expr) = if expr.IsNot && expr.NumArgs = 1u 
                             then Some(expr.Args.[0]) else None

let (|Iff|_|) (expr: Expr) = if expr.IsIff && expr.NumArgs = 2u 
                             then Some(expr.Args.[0], expr.Args.[1]) else None
let (|Implies|_|) (expr: Expr) = if expr.IsImplies && expr.NumArgs = 2u 
                                 then Some(expr.Args.[0], expr.Args.[1]) else None

So that you can easily query an expression's structure by pattern matching, even in a recursive way:

match e with
| True -> (* boolean literal *)
| False -> (* boolean literal *)
| And es -> (* query es; possibly by pattern matching *)
| Or es -> (* query es; possibly by pattern matching *)
| Not e' -> (* query e; possibly by pattern matching *)
| Iff(e1, e2) -> (* query e1, e2; possibly by pattern matching *)
| Implies(e1, e2) -> (* query e1, e2; possibly by pattern matching *)
| _ -> (* Not a boolean expression; do something else *)


来源:https://stackoverflow.com/questions/14084659/is-there-a-way-of-querying-or-accessing-the-structure-of-a-z3-expression-via-the

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!