Is there a way of querying or accessing the struct

2019-07-20 23:23发布

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.

标签: z3
1条回答
做自己的国王
2楼-- · 2019-07-20 23:37

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 *)
查看更多
登录 后发表回答