Defining constraints in Z3 using Boolean operators

血红的双手。 提交于 2019-12-02 05:24:40

问题


Let's say, I want to restrict each character of the string to the charset: [a-zA-Z0-9_] using Z3 constraints, can I use a boolean operator to specify that?

As an example:

input = [BitVec("input%s" % i, 8) for i in range(10)]

for i in range(10):
  s.add(input[i] >= 0x30 and input[i] <= 0x39)
  s.add(input[i] >= 0x41 and input[i] <= 0x5A)
  s.add(input[i] >= 0x61 and input[i] <= 0x7A)

Is this correct? Any other efficient way to define constraints?

Usually in Python, I could do something like:

import string

charset = string.uppercase + string.lowercase + string.digits + "_"

for i in charset:
    ...

Can something similar be done to define constraints in Z3?

Thanks.


回答1:


The best way to go about this would be to simply use z3's regular-expression matching facilities:

from z3 import *
import string

lower  = Union([Re(c) for c in string.lowercase])
upper  = Union([Re(c) for c in string.uppercase])
digs   = Union([Re(c) for c in string.digits])
uscore = Re('_')

charset = Union(lower, upper, digs, uscore)
lang    = Plus(charset)


s = Solver()
test = String("test")
s.add(Length(test) == 10)
s.add(InRe(test, lang))

print s.check()
print s.model()

This prints:

sat
[test = "9L25ZPC1B8"]

Or you can use it to test whether particular strings belong to the regular-expression you've defined:

>>> print (simplify(InRe("hEllO_123", lang)))
True
>>> print (simplify(InRe("%$", lang)))
False


来源:https://stackoverflow.com/questions/53808101/defining-constraints-in-z3-using-boolean-operators

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